Repository navigation
v0.29.2
- Numeric polymorphism now selects Int or Float representation before literals
and arithmetic run, including local functions, recursive calls, higher-order
calls and memoised values. This fixes precision errors that result conversion
could not repair. - Partial application evaluates supplied arguments once. Functions that return
functions preserve each application stage, and closures keep captured values
when their caller proceeds through a tail-recursive loop. - Inferred bounds follow forward function references through the full helper
chain. Mutually recursive unannotated functions share their types before
generalisation, so invalid infinite recursive types are rejected. - Typed callback bodies keep their known types across generic function slots,
preserving direct field access and typed folds without extra runtime narrowing.
A patch release for v0.29.1. sky run and sky watch now start the embedded
PostgreSQL cluster and pass its address to a Std.App app and a Sky.Spa app,
as they already did for a plain app. sky db check compares a live database
with the code, Std.Codec gets exact decimal columns, and Std.Money returns
a Result wherever two currencies can differ. Every type variable in an
annotation is now checked: a body that pins one to a type, which turned a
String into an Int and crashed at run time, is a compile error. See
Breaking and Migration.
Added
Codec.writeChecksandCodec.problems.writeCheckslists the fields of a
record codec that are partial (their encoder can write a value their own
reader refuses), with the checkStd.Db.Storeruns on a write. It is
derived from the codec tree:Codec.decimal,moneyIn,moneyObject,
isoCurrency,enum,taggedUnionand aCodec.autoDecimal or Money
field, at any depth (see Fixed).problemslists what is wrong with a codec
as built (anautoWithkey that names no field or two keys naming one
column, amoneyIncode that is not a currency code, one enum name, union
tag or object key used twice);Store.fromCodecrefuses a store whose codec
has one.- Exact decimal columns:
Codec.decimalandCodec.moneyIn. A new column
kind,CDecimal: plainNUMERICon PostgreSQL,TEXTholding the canonical
decimal on SQLite.Std.Db.Storecompares, orders, sums (sumAs) and takes
minAs/maxAsof it exactly on both: on SQLite through thesky_decimal
collation and thesky_decimal_sumaggregate the runtime registers. It takes
SqlDecimalandSqlInt(a condition also takes decimal text, so
findBy "12.30"matches 12.3) and refusesSqlFloat,SqlMoney,adjust,
addExcluded,keepMin/keepMaxand text matches before any statement.
Store.defaultDecimalgives a default; a required decimal column added to a
table with rows defaults to'0'(Store.migrateandsky db migrate --genagree).Codec.moneyIn GBPstores one currency in such a column (a
Money in another currency is refused, never relabelled),Codec.moneyObject
is the{"amount","currency"}JSON in a JSON column, andCodec.isoCurrency
is the code string. ACodec.autoDecimal or Money field keeps its JSON-text
column, so no existing table changes. To move such a field to
Codec.decimalorCodec.moneyIn, convert the column first:Store.migrate
andStore.pushProjectrefuse a decimal field on a column that holds the
JSON text (any non-NUMERICcolumn on PostgreSQL; on SQLite, a row that
still holds"9.5"or{"amount":…}), namingtable.columnand the
statement that converts it, because a text column orders"10"before
"9.5"and new writes would mix two spellings (docs/skydb/overview.md,
"Decimal columns"). Std.Moneyfollows one rule. Every operation that combines two Money
values by arithmetic or by order returnsResult Error _:add,sub,
sum,compare,lt,lte,gtandgte. Two different currencies are
anErr(kindInvalidInput) naming both, never a value and never a crash.
eq/neqstay plainBool. Exchange rates are an explicit value:
Money.rates [ ( USD, EUR, r ) ], read withMoney.rate, used by
Money.convert rates to m(theMoney.Ratestype).
Money.currencyFromCode : String -> Maybe Currencyreads a code under the
strict decoders' grammar, andMoney.eqCurrencycompares two currencies by
code. See the Migration
section.sky checkwarns about an unknown Store column name. A literal column
name given to a Store builder (primaryKey,unique,index,uniqueOn,
uniqueWhere, …), toStore.findBy, or toorderAsc/orderDesc/ a
where_condition on aStore.querychain, that the store's codec does not
have, is a compile-time warning with the column list and a did-you-mean. At
run time it makes every verb on the store fail. The lint speaks only when
the source shows the codec's columns, and never for a declared external
column (docs/skydb/overview.md).Canvas.pasteExactmoves pixels exactly.Std.Image.Canvas.pasteExact x y bytes canvasputs an image's pixels in place of the canvas's, with no
blending, and keeps each colour byte for byte.pasteblends in
premultiplied 8-bit RGBA, which moves a semi-transparent colour by up to 2
from alpha 128 up (more below), so a test of such output could not compare
bytes. A step drawn over the pixel later still shows.Codec.value, a codec for a rawJson.Value. The JSON as it is, both
ways, in a JSON text column, soCodec.object(or anautoWithoverride)
carries aList Json.Value(Codec.list Codec.value) or a
Dict String Json.Value(Codec.dict Codec.string Codec.value), whatever
the blank holds. UnderCodec.autosuch a field reads when the blank's list
or dict holds one JSON value (items = [ Json.Encode.null ]); with no JSON
value in the blank it is a builder problem (see Fixed).Store.noCond, the condition every row meets (the same asand_ []),
andStore.defaultDecimalare exposed.sky db check: does the live database match the code? A read-only
check on any DSN the app uses (a local cluster,DATABASE_URL,
<PREFIX>_DB_PATH, a remote database), on PostgreSQL and SQLite. It
compares every table ofdb : Store.Project(stores andStd.Db.Schema
tables) with the database: tables, columns, types,NOT NULL, defaults,
UNIQUE(column and multi-column constraints), the primary key, the serial
key, and indexes (partial and unique ones included). An index a Store
cannot declare (an expression, a collation, INCLUDE columns, …) is a
notice.
It reports eachdb/migrationsfile as applied, pending or edited. It
prints a plain-words report and exits 1 on drift, for CI and pre-deploy
gates. The live schema is read into the modelsky db migrate --gen
diffs, through the same diff, so the two cannot disagree.--sqlprints the SQL that makes the database match the code, and runs
nothing. Safe steps are plain, rendered by the migration renderer. A type
change,NOT NULLon existing rows and every drop are commented out with
the reason. A PostgreSQLINTEGERcolumn for anIntis accepted, with
a notice and a commentedALTER … TYPE BIGINT.--sql --writesaves the safe steps as a migration file in
db/migrations(the--genformat and ops) and updates
db/schema.json. When the database is ahead ofdb/schema.json(an
adopted table), the file also carries the--gensteps a fresh database
needs, which change nothing on this one. It refuses while a migration is
pending or edited.--codelists the columns the code has no field for or reads as
another type, and prints a record type alias, aCodec.object(one
Codec.fieldper column,Codec.decimalforNUMERIC) and aStore
(with aStore.default…builder for each column default) for each table
the code has no Store for. An adopted stub passessky db check. A column the Store cannot use
(binary data, an SQL keyword, a quoted upper-case name on PostgreSQL)
gets no field and a comment that says why; when a row cannot be written
without it, the whole stub is a comment, so it never compiles into a
store that fails at its first write.- A decimal field over a
TEXTcolumn (aCodec.autoDecimal or Money
column) proposes the conversion that reads the JSON text, not
USING price::NUMERIC, which fails on"9.5". It never drops a
currency: for aCodec.moneyIn GBPfield it gives a check query that
lists the rows in another currency first, and the conversion fails on
such a row. ACodec.decimalfield converts no Money object. - It writes nothing: the helper opens a SQLite file read-only (a missing
file is refused with exit 2, not created), every PostgreSQL transaction
is read-only, and no telemetry table is written.sky db statusruns
the same way.
Std.Db.Migrate.inspectSchema, the read-only report behindsky db check
andsky db status:
the live tables, columns and indexes, and each migration's state against
the ledger, as JSON. It never creates the ledger.
Fixed
- Adoption migrations replay safely.
sky db check --writecreates tables
before adding columns, and columns before indexes. It refuses snapshot
repairs that cannot apply to both the live database and a fresh replay, and
protects folded primary-key and UNIQUE constraint indexes from drops.
An equivalent ordinary UNIQUE constraint satisfies a snapshot-only adoption
index without creating a duplicate. Explicit named index operations retain
their normal behaviour. SQLite primary keys with a collation or descending
order retain their unsupported-index notices. Codec.autonested enum tuples. Dict and native-map values retain their
declared tuple element types when encoded, so enum names read back through
JSON and Store. Codec safety checks traverse finite types beyond depth 64,
with cycle detection for recursive types.
Data: codecs, Std.Db.Store, Decimal and Money
- Every stdlib leaf read by
Codec.autogets its write check. This includes
Currencyinside containers and tuples. An invalid currency code is refused
before a write, so it cannot make later reads fail. A tuple containing a
Decimal, Money or Currency now round-trips by its declared element types. - Arithmetic writes keep Int columns readable.
Store.adjustand
Store.addExcludedrefuse an overflowing sum on SQLite, as PostgreSQL does,
and leave the original rows unchanged. - Decimal places never wrap to a smaller value. Places and computed
exponents outside -100000 to 100000 fail asNumericOverflow. This also
bounds exponent-driven output allocation.Money.allocatebelow one part
fails asDivisionByZero, and above 10000000 parts asNumericOverflow.
See Migration for these newly loud failures. - A
Codec.autofield of a custom type with data reads back exactly, or is
refused.BoxM (Just 3)read back asBoxM (Just 0),Fixed 12.5as a
broken Decimal, and a variant with aList,Dict,Moneyor enum payload
wrote rows no read took back. The reader now decodes each variant's payload
by its own type, strictly. A payload whose type the generated code does not
keep inside a variant (aDecimal,Money,Currency,Json.Value, a type
variable, or a nested anonymous record holding one of them) is a builder
problem naming the field and the variant (Codec.problems;Store.fromCodec
refuses the store), and its read is anErr(see Breaking). - A
Codec.autoCurrencyfield never read back. It was written as a
tagged object no reader rebuilt. It is now its code ("GBP"), as
Codec.isoCurrencywrites it; the old tagged form reads too. - An annotated
Codec.autowith an empty[]orDict.emptywitness
stored rows it could not read.cA : Codec RListwithcA = Codec.auto { id = "", v = [] }passed[E2009]but lowered the witness to[]any, so
every read failed with "cannot decode kind interface". The witness now takes
the annotation's types in the generated code. AList Json.ValueorDict String Json.Valuefield reads when its blank holds a JSON value ([ Json.Encode.null ]); it was anErr. With no JSON value in the blank
([],Dict.empty, aNothingblank of aMaybe Json.Value, at any
depth: a nested record, a tuple, a List of Lists), the field is a builder
problem (Codec.problems;Store.fromCodecrefuses the store). Before,
Codec.problemswas empty, the write was taken, and one row made every
read of the table fail with "cannot decode kind interface" (seventh Judge). - Two
Codec.autofields that become one key (aBanda_bare both
a_b) overwrote each other with no error. It is a builder problem and a
decodeErr, in the record and in every record it holds: a nested record,
aList,MaybeorDictof records, a tuple and a variant's payload
(the seventh Judge foundn = { aB, a_b }written as{"a_b":1,"a_b":2}
and read back as2/2). UnderCodec.autoCamelthe keys differ. - A
Justwritten as null was stored asNothing.Just Nothingof a
Codec.maybe (Codec.maybe c)or aMaybe (Maybe a)auto field, andJust Json.Encode.nullof aCodec.maybe Codec.valueor aMaybe Json.Value
auto field, stored NULL and read back asNothing. AStd.Db.Storewrite
now refuses the row, naming the column, wherever theMaybeis: aList, a
nested record, a tuple, aDictvalue, a variant's payload or aMaybeof
a variant (aDictvalue and a variant's payload were not checked; the
seventh Judge storedJust Nothingthere and read backNothing).Codec.toJsonstill writesnull,
and a stored NULL still reads asNothing, so existing data reads as before. Store.updateFields,setFieldsandupdateSetwith aSqlDecimalover
1000 characters made the table unreadable. The write check of a decimal
column now applies the bound the column's reader applies, on both engines.- The SQLite conversion of a legacy Money column rounded a JSON-number
amount.json_extractreturns a REAL, so0.12345678901234567891became
0.12345678901234568and12345678901234567890123became
1.2345678901234568e+22. The statementStore.migratenames now copies the
number's JSON text, so the amount is exact.Store.migratealso refuses a
SQLite decimal column that holds a value its reader refuses (a REAL,1e3),
naming the values, instead of accepting a column every read then fails on. Decimal.toInt,Decimal.toMinorandMoney.toMinorwrapped round past
the 64-bit Int range (Money.toMinorof 10 ETH gave
-8446744073709551616), andDecimal.toFloatof1e400gave an infinite
Float. Each now fails as the classifiedNumericOverflow(see Breaking).
The release candidate turned that into an unrecoverablefatal error: stack overflow(exit 2) that ended a server with every session: the kernel runs
throughFfi.callPure, whose recover made the panic anErr, and
rt.AsInt/rt.AsFloatthen recursed on theErrwithout end. An Ffi
boundary, andDb.withTransactionafter its rollback, now re-raise a
loud-by-design panic (DivisionByZero,NumericOverflow,
JsonEncodeFailure), and no runtime narrowing (AsInt,AsFloat,
AsBool,AsList,AsMapT, …) recurses on anError aNothing.
Std.Ai.Trainkeeps a cloud run's spend as a Decimal count of minor units,
so a run priced in ETH is stopped by its budget past 9.22 ETH instead of
failing;cloud.jsonwritesspentMinoras a decimal string and still
reads the number an older run wrote.- An
Error aNothingthat reached a value conversion was printed or
dropped. A stdlib kernel that panics with an unclassified message reaches
a bare-typed caller throughFfi.callPureas anErr.rt.AsStringthen
printed the container (Decimal.toStringshowed{1 <nil> {0 Error [2 {Ffi "Decimal_toString" panicked: …}]}}and the app went on), and the
list, dict, char and tuple conversions (AsList,AsListT,AsMapAny,
AsDict,AsRune,AsTuple2, …) gave an empty value. Each now fails as
the classifiedCoerceFailure, or as the loud class theErrcarries
(NumericOverflow, …): a 500 in a server, exit 1 in a CLI.AsTuple2and
AsTuple3now unwrap anOkor aJust; before, they read the
container's own fields as the tuple. Money.allocatelost the part of an amount below the minor unit.
Money.allocate 3 (1.005 USD)gave[0.34, 0.33, 0.33], which sums to
1.00. Such amounts come fromMoney.mul,percentOfandconvert. The
digits below the minor unit now go to the first part:[0.345, 0.33, 0.33]. Every other part is still a whole number of minor units, as even as
possible. The parts always sum exactly to the amount. The defect was in
v0.29.1 too.
Std.Aino longer converts a cost throughtoMinorwhere it does not need
an Int, and bounds the seconds a budget buys.- An
ErrfromProvider.costnamedMoney.add. It names
Provider.costand both currencies of the price book. - No codec writes a value it cannot read back, and a Store write never makes
a table unreadable. A codec could write a value its own reader refused,
and one such row made every later read of the table fail. Earlier fixes
closed one codec at a time (Codec.moneyIn); this closes the class. Each
codec now states whether it is partial (its encoder can write a value its
reader refuses), and a container (maybe,list,dict,result,map,
a record, a union) is partial exactly when a codec inside it is, so a new
partial codec is covered at every depth with no other change.
Std.Db.Storeruns each partial field's own reader on every write, in a
scalar column as well as a JSON one, and refuses the row with the column
and the reason. The partial codecs found by an audit of every codec, and
what changed for each:Codec.enumwith a value not in its pairs wrote""(or another value's
name, when""was one). It now writes{"notInEnum": "<Constructor>"},
which every reader refuses with the constructor named, and a Store write
refuses it:column "t.status" would hold a value its field's codec does not read (Codec.enum: the value Suspended is not one of the enum's values (active) …). Two values given one name are a builder problem.- A Decimal written out over 1000 characters:
Decimal.fromString "1e1500"
wasOk, and no decimal column,Codec.decimalorCodec.autofield
read it back.Decimal.fromStringnow refuses a decimal whose canonical
text is over 1000 characters (one bound,decimalStrictMaxLen, for the
parse and every reader), and a computed one (Decimal.mulof two long
ones) is refused by the write check ofCodec.decimal,Codec.moneyIn,
Codec.moneyObjectand aCodec.autoDecimal or Money field, at any
depth. Codec.moneyObjectwith a currency code a reader refuses
(CurrencyRaw "zz") andCodec.isoCurrencywith one (CurrencyRaw "a b") were written and not read. Both are refused on a write.Codec.taggedUnionis partial, since its encoder is your function (a
tag no variant reads): each write runs its reader. Two variants given one
tag are a builder problem, and so is one JSON key used by two fields of a
buildObjectrecord (its decoder already failed on every read).- A
Codec.auto(orautoWith) field whose type holds a Decimal or a
Money, in a field, aList, aMaybe, aDictor a nested record, is
checked with the auto reader of that field. A record without one does no
check, so a plainCodec.autostore costs what it did. - A NaN or infinite
Float(Math.sqrt -1) in a Float column was written:
SQLite stores NaN as NULL and keeps an Infinity, PostgreSQL keeps both,
and every later read of the table failed. The write now refuses it,
naming the column (a JSON column refused it already). - Found by the new generative test: a JSON column read its numbers as
float64, so an Int past 2^53 inside aCodec.list Codec.intread back as
another Int, and9223372036854775807made the table unreadable. The
column is now read as a decoder reads JSON text, with each number exact.
The test that keeps the class closed builds every codec constructor and
every combination up to depth 3, generates edge values for each (empty,
Nothing, Unicode, 5000-character strings, the Int extremes, unlisted
enum values, long decimals, each currency form, NaN), and checks through
JSON and a real Store on SQLite and PostgreSQL that each value reads back
equal or is refused, and that the table always reads.
- A
Std.Db.Storewrite never stores a JSON value its codec does not read
back. ACodec.list (Codec.moneyIn GBP)field holding a USD Money was
written, and then every read of the table failed on that row.insert,
insertMany,upsert,upsertWith,insertReturning,updateand
updateWherenow read each JSON column of the row with the codec first,
and refuse the write with the column and the reason. Codec.autoWithwith two keys naming one column ("price_list"and
"priceList", or one key twice) kept one override and dropped the other.
It is a builder problem naming both keys, and the codec does not decode.Codec.autoWithignored a key that named the record field.
Codec.autoWith [ ( "priceList", … ) ] blankmatched no column (the column
isprice_list), so the override was dropped with no error. A key is now
the column or the record field, and a key that names neither is an error
naming the keys it takes: the codec's decoder fails, andStore.fromCodec
refuses the store.Codec.autoWithwith aCodec.moneyInoverride made a JSON text
column (a regression in this release). An override's column type goes
through its kind (decimal|money=GBP,decimal?|money=GBP) and back, and
only a baredecimalwas read back, so the documented
Codec.autoWith [ ( "cost", Codec.moneyIn GBP ) ] blankgaveCBlob:
orderAsc "cost"ordered"10"before"9.5", a USD Money was written
into the GBP column, and aMaybeoverride made aNOT NULLcolumn. Every
kind now maps back to the sameColType, aMaybeof each included. A
conformance matrix covers each new codec (decimal,moneyIn,
moneyObject,isoCurrency,value) as an object field, anautoWith
override, aMaybeof each and aCodec.listof each, on SQLite and
PostgreSQL: shape, column type, round trip, order and the refusal of
another currency.Codec.moneyInlost its currency forUSDT,USDCand any
CurrencyRawcode (a regression in this release). The runtime read only
a three-letter[A-Z]{3}code from the column, so aCodec.moneyIn USDT
column was taken for aCodec.decimalone, andStore.migrate's refusal
told the user to use theCodec.moneyInthey already used. The runtime and
sky db checknow read the grammarMoney.currencyFromCodereads: 3 to 10
ASCII letters or digits.Codec.moneyInreads its own code the same way, so
Codec.moneyIn (CurrencyRaw "gbp")isCodec.moneyIn GBPand takes a GBP
Money. A code that is not a currency code is aStore.fromCodecbuilder
problem naming it.- The write check made
Store.insertManyslower (a regression in this
release). Each JSON column of each row was encoded to
text, parsed back, and decoded inside the codec's zero record, twice. A
codec now knows which of its fields are partial (see the first entry), and
a write checks only those, once per row, on the encoded value in memory. A
store without such a field (aCodec.autorecord of plain fields included)
does no check at all. Every refusal stays (insert, insertMany,
upsert, upsertWith, insertReturning, insertOrIgnore, update, updateWhere). Store.insertManyfailed above the engine's bound-parameter limit.
It wrote every row in oneINSERT, so 10,000 rows of 4 columns failed on
SQLite with "too many SQL variables" (its limit is 32,766) and 20,000 rows
of 5 columns on PostgreSQL (65,535). The insert is now split by the limit
into several statements in one transaction (the caller's own inside
Db.withTransaction), so it stays all-or-nothing.Store.inListfailed on a long list. One parameter per value stopped
at the engine's limit on the parameters of one statement: on SQLite a list
over 32,766 values failed with "too many SQL variables", and on a
PostgreSQL connection that uses pgx's extended protocol a list over 65,535
failed with "extended protocol limited to 65535 parameters" (the app pool's
simple protocol inlines the values and had no limit). A condition is one
statement, so it cannot be split. A list over 1,000 values now has ONE
placeholder, marked with its count (/*sky-list:N*/), and the runtime
binds its N values as one parameter just before the statement runs:
PostgreSQLcol = ANY(?)with the text of an array literal, which the
server reads as an array of the column's type; SQLite
col IN (SELECT +value FROM json_each(?))with a JSON array, where the
unary+removes json_each's NUMERIC affinity so the column's affinity
and itssky_decimalcollation apply as they do toIN (…). A Float
column on SQLite reads each value asm * pow(2, e), exact where SQLite's
own reading of a decimal number is not (below about 1e-305), and a v0.28
TEXT column of a nullable Bool or Float gets the text v0.28 wrote, as one
value does. A list up to 1,000 values keepscol IN (?, ?, …), so its SQL
and plan do not change.toSqlshows the mark and the N values, and that
SQL runs unchanged throughDb.query. The StoreQuery conformance suite
checks the long form againstIN (?, …)on every column kind on both
engines (NULLs, duplicates, text case, decimals, booleans, a float near
1e-308, an empty list), 40,000 and 70,000 values, andtoSql.- On PostgreSQL an
Intcondition on a foreignINTEGERorSMALLINT
column failed with "out of range" for a value outside the column's range
(eq,lt,inListof any length,findBy): the value is bound as text,
which the server reads as the column's type. Each Int placeholder compared
with a plain column now names it (?/*sky-int:table|col*/, and
?/*sky-list:N:int:table|col*/for a long list), and the runtime reads the
column's type from the catalogue (once per pool and table, cleared after a
schema change) and casts the value toBIGINTon anINTEGERor
SMALLINTcolumn only, so an out-of-range value matches nothing, as SQL
compares an integer with a wider one, and the column's index is still used.
Every other column keeps the value as v0.29.1 bound it. An earlier
candidate of this release cast every Int toBIGINT, which broke anInt
field on aTEXTcolumn ("operator does not exist: text = bigint", where
v0.29.1 answered); the StoreQuery conformance suite and a PostgreSQL test
now coverTEXT,NUMERIC,INTEGER,SMALLINT,BIGINTand a domain,
short and long, on both protocols, withEXPLAIN.toSqlshows the mark,
and its SQL runs unchanged throughDb.query. Store.setFieldsrefusals saidupdateFields,updateFieldsReturning
refusals saidupdateFields, andcopyIntoOrIgnorerefusals said
copyInto. Each names the verb called.- Refusals from
upsertWith,insertReturning,insertOrIgnoreand
insertOrIgnoreOnsaidStore.insert:. Each now names its own verb. - A Store column named with an SQL keyword is refused with the reason. The
Store writes names unquoted (quoting would change how PostgreSQL folds an
existing camelCase column), so a field namedorderfailed at its first
statement with "syntax error at or near order". A keyword of both engines
(order,select,group,from, …) is now a Store builder problem, which
every verb andsky verify's stores step report; a keyword of one engine
(userandsystem_useron PostgreSQL,indexandcommiton SQLite) is
refused byStore.migrateandStore.createon that engine. On SQLite a
name that fails in one position only is refused there only:ifas a
table name,raiseas a column name. The lists are measured: tests run the
Store's statements with every SQLite keyword and every PostgreSQL reserved
keyword (pg_get_keywords()) in both positions. Map the field to another
column withCodec.field "sort_order" .order Codec.int. - A Store JSON field on a binary column is refused, not misread.
Schema.blobmakesBYTEA(BLOBon SQLite) through
Schema.createSchema, and aStd.Db.Storereads and writes a JSON field
(a list, a record, a custom type, aJson.Value) as text. A Store over such
a table misread every row.Store.migrateandStore.pushProjectnow
refuse it with anErrnamingtable.columnand the fix. Both types stay:
aSchema.blobcolumn thatsky db pushmakesTEXTis named once at
WARN, andsky verify's stores step names everySchema.blobcolumn
(docs/skydb/overview.md). Schema.intis one column type on both creation paths. On PostgreSQL
Schema.createSchemamade a 4-byteINTEGERandStore.pushProject (Schema.toProject …)(andsky db push) aBIGINT, so a fresh database
differed with the path that made it. Both now makeBIGINT, the size of a
SkyInt: anINTEGERcolumn fails with "integer out of range" above
2,147,483,647. Neither path alters a column that exists, andsky db migrate --genproposes no change: a table an oldercreateSchemamade keeps
INTEGER.Store.migrateandpushProjecttreat it as a match and log a
one-time WARN naming the column, with theALTER TABLE … ALTER COLUMN … TYPE BIGINTthat widens it. Widening stays your choice.Decimal.fromFloatof a NaN or an infinite Float panicked unclassified
(shopspring's "Cannot create a Decimal from NaN"). It is now the classified
DivisionByZero, as a Float division with no answer is.- A decoded currency matches its own
casearm.Codec.autoand
Db.Decode.moneybuilt every named currency with the tag ofUSD, so a
decodedGBPmatched theUSDarm of acaseand printed as USD. Each
currency now carries its own constructor. Codec.autoDecimal and Money decode strictly. A Decimal (and a Money
amount) is read under-?[0-9]+(\.[0-9]+)?, at most 1000 characters. An
exponent used to reach the decimal library, and"1e2000000000"in a request
body made the process write out billions of digits (the test of it ran for
five minutes). A Money with nocurrencywasCurrencyRaw ""and is now an
Err;"gbp"reads as GBP; an exact JSON number amount reads.Decimal.fromStringbounds its exponent. It keeps the exponent grammar
("1.5e3"is 1500), but"1e2000000000"parsed at once and then took
minutes to print or add (a decimal with exponent e has about |e| digits).
Text over 1000 characters, or an exponent past 10000 either way, is now an
Err.Money.fromStringand a Decimal that reaches the runtime as text go
through the same bound.- The JSON Schema of a
Codec.autoDecimal or Money field is exact. It was
the open{}, soCodec.toXmlwrote the JSON text"12.34"into the
element. It is now a string with the decimal pattern, and the Money object. Db.Decode.moneyreads both Money text forms strictly. It reads
"USD 12.34"(SqlMoney) and"12.34 USD"(Money.formatWithCode), the
code in upper case, the amount under the strict grammar.Money.convertthrough the inverse rate divides by it. It multiplied
by1 / rrounded to 16 places, soMoney.rates [ ( USD, EUR, 3 ) ]made
3 EUR into 0.9999999999999999 USD. It now divides byr: exact when the
quotient ends within 16 decimal places, else rounded to 16, half away from
zero.- The legacy Money refusal says what each engine does. A Money object
with no currency was named{1 <nil>}; it is?. The SQLite conversion
leaves a Money object in another currency (or with none) as it is, and the
store refuses the column again; the text said it "makes it fail", which is
what the PostgreSQL conversion does. The text now says each, and the check
query is named as listing rows with no currency too. - Every
Std.MoneyErrnames the operation called.Money.sumover two
currencies said "Money.add: …", andMoney.fromStringsaid
"Decimal.fromString: …". They now sayMoney.sum:and
Money.fromString:. - A removed
Std.Moneyname used bare names its replacement. After
import Std.Money exposing (..), a baresetRateorsumOfgave only
"Undefined name"; it now names the replacement, asMoney.setRateand
exposing (setRate)do.
sky db check, sky db status and read-only mode
-
sky db checkdid not see a multi-column UNIQUE constraint.
UNIQUE (tenant, name)in a CREATE TABLE was skipped by the schema reader
on SQLite and PostgreSQL, so the check said "matches" for code that left
it out, reported "unique index ux_… is missing" for code that declared
Store.uniqueOn [ "tenant", "name" ], and--sql --writesaved a
second unique index. A UNIQUE constraint is now read as the index it is
and matched to a declareduniqueOnby its columns; one the code leaves
out is a difference that names the constraint (never aDROP INDEX), and
the--codestub declares it withStore.uniqueOn. -
sky db checkdid not compare the primary key. A composite key read
as its first column, soPRIMARY KEY (a, b)gave the stub
Store.primaryKey "a"and the check passed, and a code key on another
column than the database's was not reported either. On such a table a
Store.updateorStore.deletebyareaches every row with thata.
The key is now compared (a composite key, a key on another column, no
key), and the--codestub of a composite-key table is a comment that
says why it is not a Store. -
sky db checkread an index its column list does not describe as a
plain one. On PostgreSQL an expression column was dropped from the list
((lower(name), tenant)became(tenant), a stricter constraint) and an
INCLUDE column added to it (a weaker one); on SQLite an expression column
had an empty name andUNIQUE (email COLLATE NOCASE)became
Store.unique "email", which is case-sensitive. Each then "matched". The
reader now says why such an index is not a column list (an expression, a
collation or operator class of its own, DESC, INCLUDE columns, another
index method, an exclusion constraint, or PostgreSQL'sNULLS NOT DISTINCT).
The latter rejects duplicate null keys that plain uniqueness permits. It
remains an index with a notice, including a one-column UNIQUE constraint,
rather than becoming a plain unique field in an adoption stub.
Deferrable constraints and indexes that are not valid, ready and live
also retain a notice, including an unsupported primary-key index.
INCLUDE columns on a primary-key index are not reported as key columns.
A PostgreSQL index that inherits a non-default column collation also
retains its notice, including UNIQUE constraints and primary-key indexes.
A Store cannot declare it, so the
check gives a notice for it and the stub a comment; under a name the code
also declares, it is a difference. A foreign key on another table no
longer makes PostgreSQL's plain unique index read as a constraint. -
sky db check --sql --writeon an adopted table wrote a migration
chain that could not build a fresh database. The file held only the
steps the live database needed, whiledb/schema.jsonrecorded the whole
code, sosky db migrateon a fresh database failed ("no such table") and
--gennever wrote the CREATE TABLE. The file now also carries the steps
--genwrites againstdb/schema.json(CREATE TABLE and CREATE INDEX,
which areIF NOT EXISTSand change nothing on the live database), so
both databases reach the code. A column the live database has and no
migration adds is refused with the reason, and nothing is written. -
An adopted
sky db check --codestub failedsky db checkon a table
with a UNIQUE column or an index. The stub declared neither, so the check
reported each one ("the code does not declare it"). The stub now writes
Store.uniquefor a single-column UNIQUE constraint or index, and
Store.indexNamed/Store.uniqueOnNamed(new:index/uniqueOnunder
a name you give) for every other index under its live name, so the adopted
stub matches. An index the Store cannot declare (a partial index, a unique
index over a nullable column, one over a column the stub has no field for)
is a comment in the stub that says so, and the check reports it. -
A project with no tables made
sky db checkandsky db migrate --gen
exit 2 ("the schema ofdbis not readable: invalid type: null, expected
a sequence").db = Store.project []dumped"tables":null. It now dumps
[], and every listcheckand--genread takes anullas empty. This
blocked adopting an existing database before the code had a Store. -
The notice for a narrow PostgreSQL integer column said a SMALLINT holds
values up to 2147483647. It now gives each type's range: 16-bit values
(at most 32767) for a SMALLINT, 32-bit values for an INTEGER, and the error
PostgreSQL gives (smallint out of range), insky db checkand in
Store.migrate's notice. -
An Int condition on a domain over a domain over INTEGER failed "out of
range". The Int cast resolved a domain one level only. It now follows the
domain chain to its base type at any depth. -
sky db checkwrote beside a SQLite database in WAL mode.Db.connect
sets WAL mode, and a read-only open of a WAL database createdx.db-wal
andx.db-shm; in a directory it could not write,sky db checkexited 2
with "attempt to write a readonly database (1544)" and the advice ofsky db status. With no-walfile beside it (no process has the database
open, and every committed page is in the main file) the database is now
read withimmutable=1, which creates nothing; with one (a live process),
through the-waland-shmalready there, so the check sees the running
app's committed rows. A-walfile with no-shmfile (a backup that
copied the database and its-walonly) is refused with exit 2 and the
fix: SQLite reads a-walonly through the-shmindex, so a read-only
open createdx.db-shm(32 KB) beside the database, and in a read-only
directory failed with "unable to open database file (14)" and no hint. The
message namessqlite3 x.db 'PRAGMA wal_checkpoint(TRUNCATE)'(with no app
running), or copying the-shmwith it. The hint after a read-only refusal
names the command that ran (SKY_READ_ONLY_DB=checkor=status). -
Read-only mode refused a plain SQLite path with parameters
(w/x.db?_pragma=foreign_keys(1)) that the app opens: it looked for a file
named with the parameters. The path now ends at the first?, as the
driver reads it, and the parameters are kept. -
Read-only mode could write through a SQLite
file:DSN.sky db statusandsky db checkopen the database read-only, but a DSN such as
SKY_DB_PATH="file:st.db?mode=rwc"kept its ownmode:sky db status
created the file and ran writes, andsky db checkcreated an empty
database and exited 1. Read-only mode now replaces anymodewithroand
adds_pragma=query_only(1), so a write fails in SQLite twice over. A
missing file is refused with exit 2 for every spelling (a plain path, a
file:URI with or without parameters,file://). On PostgreSQL a DSN
option such asoptions=-c default_transaction_read_only=offcannot turn
the guard off (measured), and the connection now reads the setting back and
refuses a session that is not read-only. -
A read-only SQLite connection keeps
busy_timeout. With
SKY_READ_ONLY_DB=1(sky db check,sky db status) the write PRAGMAs
are skipped, andbusy_timeoutwent with them, so a check against a
database another process was writing failed at once with "database is
locked". It is now set on every read-only connection. -
sky db checkruns the data check the app'sStore.migrateruns. On
SQLite it said "up to date" (exit 0) for aTEXTcolumn ofCodec.auto
Money JSON read byCodec.moneyIn GBP, which the app refused: only the
column type was compared. It now calls the runtime's check
(Store.checkProjectData) and reports each refusal as drift, with the
runtime's text and its conversion SQL, on both engines. -
An adopted
sky db check --codestub passessky db check. The stub
and the check read column types two ways. On SQLite aTIMESTAMP,
DATETIME,DATE,UUID,JSONorNUMERICcolumn got aMaybe Float
field: the stub failed on its first row stored as text ("is a Float, and
the database holds "2026-11-02 10:00:00""), and the check reported the
stub's own fields as type drift. On PostgreSQL atimestamptz,
timestamp,uuid,jsonb,date,intervalor array column got a
Maybe Stringfield that the check reported as drift, and aDEFAULT 'x'
was left out and then reported. A date, time, UUID or JSON column is now a
Stringfield on SQLite (aNUMERICone stays aFloat), the check
accepts aStringfield on any PostgreSQL column that is not a number, a
boolean or binary data (the Store reads it as text, and the server casts
the text it writes), and the stub declares each live default with
Store.defaultText/defaultInt/defaultFloat/defaultBool/
defaultDecimal/defaultNow. A default no builder can declare (an
expression such asgen_random_uuid()) is a comment in the stub. A test
builds every stub kind against its column, and the SQLite and PostgreSQL
flow tests adopt a stub and check thatsky db checkexits 0. -
sky db statusreports an edited applied migration as EDITED. It
compared names only, so a file changed after it ran showed as "applied" and
"up to date." whilesky db checksaid EDITED. Both now read the ledger
throughMigrate.inspectSchema(the checksum checksky db migrateuses),
andstatusexits 1 on an edited file. In a project without
db/migrations(SKY_DB_OP=status),statusno longer creates the
_sky_migrationsledger. -
The
sky db statushint was wrong for an app that has noDb.migrate.
A write refused in read-only mode said "Move that write after
Db.migrate", but an app that migrates withStore.migratehas no
Db.migrate: itsCREATE TABLE, or any write after it, fails there. The
hint now gives both cases: move the write afterDb.migrate, or, with no
Db.migrate, compare the database withsky db check, which reads the
code'sStore.projectand runs no app code.
sky run, sky watch, Sky.Spa and builds
-
A U+FEFF inside a string builds as valid Go. All generated Go string
literals share one escaping rule. Controls and the byte order mark are
escaped, and ordinary Unicode text keeps its value. -
The Sky.Spa Todos headless acceptance runs the current client driver.
Its DOM shim supports URL marker queries, history replacement and scrolling.
The full round trip still checks the real wasm client against the real
SQLite backend. -
The embedded-database conflict message printed the DSN's password.
DATABASE_URL='postgres://x:secret@host/x' sky runon a project with
[database] embedded = trueshowedsecretin clear, and v0.29.2 runs the
check on everysky runpath and onsky watch, so into more terminal and
CI logs. The DSN is now shown with every password as***(the URL's
user:password@, apassword=parameter, the keyword form's
password=…, quoted or not); the user, host and database stay, so you
can still tell which DSN it is. -
The
--target web:apprefusal of amainit cannot carry did not list
every form that carries. It left out the prefix form
main = Task.andThen (\_ -> App.run app) setup(and<| setup), which
carries. The list now comes from one table that a test parses form by form,
so it names exactly the forms that carry. -
sky runpasses the embedded database address to aStd.Appapp. On a
project with[database] embedded = true,sky runon aStd.Appentry
(main = App.run app) did not start the cluster and did not set
SKY_DB_PATH(or<PREFIX>_DB_PATH). The app stopped at its first database
read with "no path given and SKY_DB_PATH / DATABASE_URL are unset". The same
was true for--target web:appand for a Sky.Spa entry (their generated
backend). Everysky runpath now starts the app with the same environment:- the configuration check before the build (an explicit DSN alongside
embedded = trueis refused on every path), - the cluster and its DSN after the build,
- the
--profilevariables and the--db-push/--db-migrate/
--db-seedsteps, which theStd.Appand Sky.Spa paths ignored. The
profile directory is an absolute path (<project>/profile, or
--profile-dirread against the directory you ranskyin): a Sky.Spa
backend runs in.split/backend, and a relative directory put its
profiles in that build folder, which the next build deleted, --openon aStd.Appentry.
sky run --embedon aStd.Appor Sky.Spa entry starts no supervised
cluster, because that binary brings up its own. - the configuration check before the build (an explicit DSN alongside
-
sky watchon aStd.Appentry runs the right backend. It compiled the
entry directly, soApp.runran its placeholder body and not the web
backend. It now builds the entry for the sky.toml[app] target(else
web), assky rundoes, and the spawned app gets the cluster's DSN on
every restart. The staged copies under.skyapp/and.split/no longer
trigger a rebuild. -
sky watchon a Sky.Spa entry (Spa.app) runs its backend. It built
the entry as a plain program, so no backend started. It now splits the
entry into.split/assky rundoes and runs the generated backend (with
the cluster's DSN), which serves the wasm frontend. -
--target web:appruns the boot setup of a fully client-local app. When
updatehad no server branch, the generated backend only served static
assets and dropped thelet _ = <task>prefix ofmainin silence, so a
schema creation or a seed there never ran. The backend now keeps that boot
setup and runs it before it listens. -
--target web:appruns a setup chained beforeApp.run. Amain
written assetup |> Task.andThen (\_ -> App.run app)(or
Task.andThen (\_ -> App.run app) setup) lostsetupin the generated
backend, in silence: only alet _ = <task>prefix was carried. The chained
setup now runs in the backend after theletprefix and before it listens.
So domain = startwith a zero-parameterstart = setup |> Task.andThen (\_ -> App.run app), a named continuationmain = setup |> Task.andThen runItwithrunIt _ = App.run app, and the two together (main = start
withstart = setup |> Task.andThen runIt): before, they failed with
"Undefined name: app … this is a defect in Sky". Any other expression aroundApp.run
(for exampleTask.mapover it, or acase), and anApp.runreached any
other way, fails the build and names the forms that carry.
The carried setup is the first task of the backend's boot sequence, so a
setup that fails stops the backend with its error and a non-zero exit, as
on--target web; it never listens. An earlier candidate of this release
forced it withlet _ =, which drops anErr: the backend logged nothing,
listened and served on a database whose schema step had failed. -
A cold build uses less memory at its peak. The compile of the runtime
package (sky-app/rt) is the largest process of every build, and Go gave
it up to four SSA back-ends at once. Everygo buildSky runs (the native
app, the Sky.Spa wasm client,sky check,sky test, the cache warm-up)
now passes-gcflags=sky-app/rt=-c=2, which lowers the cold build's peak
memory, and the compiled code is the same.
It is left out when yourGOFLAGShas a-gcflags, because Go keeps only
the last matching-gcflagspattern and would drop yours.
Compiler messages
-
The advice "write
Tinstead ofa" now names a type you can write.
An unknown part was shown as_(write List _ instead of a, which does
not parse), and a record asrecord(so the next error read "write
recordinstead ofrecord"). An unknown part is now a fresh variable
(List x1), and a record shows its fields ({ r1 | count : x1 }). -
[E1012]names the right release for a v0.29 stdlib name. A name new in
v0.29.x was called "new since Sky v0.27.8" with a link to
docs/migration/v0.28.md. The message now names the newest release that
lacked the name, which is the release users upgrade from: v0.29.1 for a
name new in v0.29.2 (Codec.value,Money.sum), v0.28.1 for one new in
v0.29.0, each with a link to docs/migration/v0.29.md. A v0.28.0 name still
points at the v0.28 guide.
Contributors
- The Nix dev shell supplies Python 3. Gate helpers no longer fall through
to the macOS SDK stub, whosexcrunlookup can recurse inside the shell.
Both Nix shell entry points verify that Python runs and that no environment
dump is written. TestDictHashKeepsTheTrieShallowfailed about one run in 50 with
nothing wrong. Measured over 10,000 seeds per key family on
linux/amd64, the Dict hash matches a uniform hash (depth 11 for 100,000
keys in 0.2 to 0.5% of seeds), so the bound of 10 was inside its normal
tail. The bound is 12, set from that distribution, and a new test counts
the key pairs that share the first 7 trie levels (about 19 for a uniform
hash; a weak mix gives thousands).- Contributors: a gate run beside
xtask harness --verify-falsifiersno
longer undoes its mutation. Everyxtask harnessrun replays the mutation
journals at start, to recover from a killed falsifier run. It could not tell
a live run's journal from a dead one's, so a second run wrote the original
file back under the live run (which then measured clean source) and stamped
it with the current time, so a Rust source looked newer thansky-out/sky
and later gates failedrequire_fresh_compiler. A live run now holds a lock
on its journal, and the replay skips a locked journal with a warning. A
replayed non-Rust file also gets its old mtime back. The lock is a separate
.lockfile per target that is never renamed: a new run on a target whose
dead run left a journal takes that lock and replays the journal first, so it
never journals the dead run's mutation as the original, and no replay can
remove a live run's journal.
Breaking
-
⚠ Breaking: a row variable in an annotation is rigid.
{ r | name : String }stands for whatever other fields a caller's record has, but its
row links were dropped:f : { r | name : String } -> { s | name : String }
withf rec = recchecked, and(f { name = "x" }).agethen crashed at
run time (CoerceFailure: expected a record with the field "Age"). So did
rec.ageon{ r | name : String }, and a closed{ name = … }returned
where{ r | name : String }was promised. Each is now[E2001]naming the
row variable and the fix ("addageto the record type", "write the same
row variable in both record types", "keep the caller's record and change
it with an update"), in every shape a record can sit in (aList,Maybe,
Dict,Result, tuple, nested record, custom-type payload or function). -
⚠ Breaking: arithmetic needs a number.
+,-and*were typeda -> a -> aon the check path, andnegateandabshad no type there, so
f : a -> awithf x = x + xchecked andf "s"crashed inrt.AsInt,
as didadd a b = a + bwithadd "s" "t". They now take anumber, as in
Elm: the first asks for thenumberbound, and the unannotated helper is
number -> number -> number, soadd 1.5 2.0checks andadd "s" "t"is
refused.Basics.absof aFloatkept only the integer part (abs -2.5
was2); it is now2.5. -
An integer literal stands for a
numbervariable. v0.29.2's rigid
variables refusedisPositive : number -> BoolwithisPositive x = x > 0
(v0.29.1 accepted it) and advised writingInt, which breaks every
Floatcaller;double : number -> numberwithdouble x = x * 2was
refused in v0.29.1 too. A literal now stands for a rigidnumber
variable, and such a body is lowered with the variable kept generic, so
double 2.5is5.0(a literal pinned the variable toIntin the
lowering, which madeisPositive 0.5Falsein v0.29.1). Everywhere else a
literal is still anInt:1 + 2.5is refused and aFloatslot needs
1.0.- An integer literal in a
numberslot reaches the program as anInt
value even when the caller choseFloat(zero : number -> number
withzero _ = 0,f xs = 1 :: xs, the[] -> 0case of a recursive
sum), and==compared the two:zero 2.5 == 0.0,List.member 1.0 (f [ 2.5 ])andpairUp 1.5 == ( 1.5, 0.0 )wereFalse.==,/=
andList.membernow compare anIntand aFloatby value, at the
top level and inside aMaybe, a tuple, a record or aList. - Unary minus on a
numberlowered asInt:neg2 x = -xtruncated its
argument (neg2 2.5was-2,diff a b = a + -bgavediff 1.5 0.25
=1), andneg : number -> numberwithneg x = -xfailedgo build
("mismatched types untyped int and any"). Unary minus, and^, now
keep the variable generic, as+does, and lower tort.Negate/
rt.Powwhen the operand is not a Gointorfloat64.
- An integer literal in a
-
An extensible-record alias with a record argument dropped the
argument's fields.type alias Named r = { r | name : String }with
type alias Model = Named { count : Int }expanded to{ r | name : String }, soinit : Modelwithinit = { name = "a", count = 2 }was
refused under v0.29.2's rigid rows ("addcountto the record type",
which it already was). v0.29.1 accepted it. The row variable is now
replaced like any other alias parameter, by a record (its fields join the
alias's), or by a variable (both : Named a -> Named b -> Stringkeeps
two rows, soboth { name = "a", age = 3 } { name = "b" }checks). One
substitution serves alias expansion, constructor payloads and the Sky.Spa
split, which each had a copy with the same flaw. -
The LSP inlay hint and hover disagreed on an unannotated function.
Hover showedadd x y = x + yasnumber -> number -> number; the hint
showeda -> a -> a. Both now show the checker's type. -
⚠ Breaking: every type variable in an annotation is rigid. The checker
made only the variables of an annotation's RESULT rigid. A variable that
appears only in argument position stayed flexible, so the body could pin
it to a type, or make two variables one type, and the annotation still
checked:show : a -> Stringwithshow v = "<" ++ v ++ ">"printed
<1>forshow (Just 1), andcoerce : a -> bwithcoerce x = xturned
aStringinto anIntthatn + 1then crashed on at run time (a panic
from well-typed code). Each variable now stands for every type a caller may
choose, as in Elm: the body may keep it polymorphic, but a body that uses
it as a type, or as another variable, is[E2001]with the fix:[show] the type annotation says `a` can be any type, but this code uses it as `String`. … Fix: write `String` instead of `a` in the type annotation, or change the code so it does not depend on the typeA bound the body needs and the name does not spell (
aordered with<)
asks forcomparable/number/appendable, as before. Alet
annotation may name the enclosing annotation's variable (scoped type
variables), and kernel and FFI signatures are unchanged. Measured over the
stdlib, every test,apps/*, 76 examples and 19 user projects, it rejects
3 definitions in 2 projects, and each was wrong:examples/13-skyshopis
fixed in this release (see Migration). -
⚠ Breaking:
==on aDecimaland on aJson.Valuecompares the value.
Decimal "1.10" == Decimal "1.1"andDecimal.mul 1.5 2 == Decimal 3are
nowTrue(they compared the representation), and so is a Money of equal
amounts in one currency. TwoJson.Values are equal when they are the same
JSON: numbers by value (5and5.0), objects in any key order. So a
Decimal, Money orJson.Valueread back from a codec or a Store is==to
the value written. Code that relied on==telling1.10from1.1should
compareDecimal.toStringinstead. -
⚠ Breaking: a currency code is read in upper case by
Std.Moneytoo.
Money.currencyCode (CurrencyRaw "gbp")is"GBP", andeqCurrency,
add,compare,ratesandconverttakeCurrencyRaw "gbp"as GBP, as
every codec already read it.Money.add (Money.Money 1 (CurrencyRaw "gbp")) (Money.fromMajor GBP 1)was anErr.==still tells the two apart (it
compares how the currency was written): compare Money withMoney.eq. -
⚠ Breaking:
Decimal.toInt,Decimal.toMinor,Money.toMinorand
Decimal.toFloatfail loudly out of range. A result outside the 64-bit Int
range (or the Float range) is the classifiedNumericOverflowpanic, never
a wrapped number: a server answers that request with a 500, a CLI exits 1
with a structured log.Money.toMinorof an ETH amount (18 minor units)
reaches it from 9.22 ETH. Store such amounts withCodec.moneyInor
Codec.moneyObject, or compare with the bound before converting. -
⚠ Breaking:
Codec.autorefuses a field it cannot read back. A field
whose custom type has a variant carrying aDecimal,Money,Currency,
Json.Valueor a type variable, a field of a stdlib custom type other than
Decimal,MoneyandCurrency, a nested anonymous record holding a
DecimalorMoney, two fields that become one key (in the record or in
a record it holds), and aJson.Valueslot whose blank holds no JSON value
(items = []for aList Json.Value,more = Nothingfor aMaybe Json.Value) are builder problems:Store.fromCodecrefuses the store. Put
one JSON value in the blank ([ Json.Encode.null ],Just Json.Encode.null), or give the fieldCodec.valuethrough
Codec.autoWith. Each of them wrote rows that
read back as another value or not at all. -
⚠ Breaking: a
Std.Db.Storewrite refuses aJustwritten as null
(Just Nothing,Just Json.Encode.null), which used to be stored as NULL
and read back asNothing. -
⚠ Breaking: the
Std.MoneyAPI is redesigned (docs/migration/v0.29.md,
"Money results").Money.addof two currencies returned the left operand in
silence, andcompare,lt,lte,gt,gteandsumOfignored the
currency. Now:add,sub : Money -> Money -> Result Error Money;
sum : Currency -> List Money -> Result Error MoneyreplacessumOf;
compare : … -> Result Error Int;lt,lte,gt,gte : … -> Result Error Bool. AnErrnames both currencies.zeroOf misMoney.zero (Money.currency m).- The global rate table (
setRate,getRate,hasRate,clearRates) is
removed:convert : Rates -> Currency -> Money -> Result Error Moneywith
Money.rates [ ( from, to, rate ) ], andMoney.rate from to rates : Maybe Decimal. parseCurrency,isKnownCodeandknownCurrencyare replaced by
currencyFromCode : String -> Maybe Currency.- Each removed name is a compile error that names its replacement.
Money.sumandDecimal.sumboth exposed with(..)make a baresum
ambiguous ([E1012]); qualify it. fromMinor,formatWithCode,amount,eqand theMoneytype are
unchanged.Std.Ai:Provider.costreturnsResult Error Moneyand
Trace.forResponsereturnsResult Error Trace(pipe it through
Task.fromResultbeforeTrace.record). A price book in two currencies,
or aSyntheticbudget in another currency than its book, is refused
before the first call (InvalidSetting); anEvalcost budget in another
currency than the suite's costs failsEval.checkwith that reason. In
v0.29.1 none of these failed:Money.addof two currencies returned the
left operand andgt/gteignored the currency, so the cost, the
budget check and the gate were silently wrong. AnErrfrom
Provider.costnamesProvider.cost, not theMoney.addinside it.
-
⚠ Breaking:
Std.Codecexposesvalue(Codec.value). A program that
importsStd.Codec exposing (..)together withJson.Decode,
Std.Html.Attributesor theJsonDeckernelexposing (..)and uses a bare
valuegets[E1012]: qualify it (Decode.value) or narrow one
exposinglist. -
A stored Money with an empty currency no longer reads.
Codec.auto
andDb.Decode.moneyread{"amount":"1.00","currency":""}(and a Money
with nocurrency) asCurrencyRaw ""; it is now a decodeErr, so a
Store.toListover such a row fails. Find the rows first, for example
SELECT id FROM orders WHERE total NOT LIKE '%"currency":"%' OR total LIKE '%"currency":""%'on the JSON text column, and set their real currency
(UPDATE … SET total = '{"amount":"1.00","currency":"GBP"}') before you
upgrade. -
sky db status(withoutdb/migrations) runs the app read-only. It
runs the app'smainwithSKY_READ_ONLY_DB=statusup toDb.migrate, so
an app that writes beforeDb.migrate(a boot log row, aCREATE TABLE IF NOT EXISTS), or that has noDb.migrateand migrates withStore.migrate,
now fails there with "attempt to write a readonly database" (SQLite) or
"cannot execute … in a read-only transaction" (PostgreSQL), where before
v0.29.2statuswrote those rows. The error names the read-only mode and
what to do (see Migration). -
Codec.ColTypehas two new constructors,CDecimalandCMoneyIn. A
caseover aColTypein your own code must add the arms (the compiler
names them).CMoneyIn codeis the columnCodec.moneyInmakes: a
decimal column whose currency iscode.
Migration
- A row variable the body pins (the rigid row check above): write the
same row variable on both sides ({ r | name : String } -> { r | name : String }), list every field the body reads ({ r | name : String, age : Int }), and change the caller's record with an update instead of building
a new one. - Arithmetic on a variable without the
numberbound: writenumber
(twice : number -> number), or the concrete type the code needs. - An annotation whose variable the body pins to a type (the rigid
type-variable check above). The pattern the measurement found is a
framework callback annotatedinit : a -> ( Model, Cmd Msg )whose body
reads its argument as a request (Dict.get "cookies" req). Write the type
the body uses, as the error says:init : Dict String String -> …. A
Std.Appinittakes(), so its argument holds no request: write
init : () -> …, and read the request withApp.withRequest
(examples/13-skyshop's oldinitread a cookie from()and so never
pre-loaded a user; that dead code is removed). LikewiseviewAddToCart : Model -> a -> …withDb.getField "id" productin the body isModel -> Dict String String -> …. A definition that is truly polymorphic needs no
change. - A
Codec.autofield the store now refuses (theStore.fromCodecerror
names the field and the variant): give that field its own codec,
Codec.autoWith [ ( "price", priceCodec ) ] blankwithpriceCodecbuilt
byCodec.taggedUnion, or use a named record alias instead of a nested
anonymous record. For two fields that become one key, rename one or use
Codec.autoCamel. - A
Just Nothingthe Store now refuses: storeNothing, or wrap the
inner value in a record or a custom type, so the two cases have their own
JSON. - Money minor units past the Int range: keep the amount as a Decimal
(Codec.moneyIn,Codec.moneyObject) instead ofMoney.toMinor. - A
Codec.autoWithkey that names no column and no record field was
ignored before, and is now an error (Store.fromCodecrefuses the store and
the codec does not decode). The error names the keys the record takes: use
one of them, or remove the override. - Upgrading from v0.29.1: most Breaking entries above are compile errors
(docs/migration/v0.29.md). The rigid type variables and row variables,
arithmetic on a variable without thenumberbound, a removedStd.Money
name (setRate,sumOf,parseCurrency, ...),Codec.valueand
Codec.ColTypeeach give an error that names the fix. A function whose
type changed (add,sub,compare,lt,lte,gt,gte,
convert,Provider.cost,Trace.forResponse) is a plain type mismatch
[E2001]at the call (MoneyvsResult Error Money,Ratesvs
Currency), which does not name the change: handle theResult(case,
Result.map,Task.fromResult) and passMoney.rates [ ... ]as
convert's first argument. The other entries show at run time, not at
compile time: a stored Money with an empty currency (its read is an
Err),sky db statuswithoutdb/migrations(it runs the app
read-only, so a write beforeDb.migratefails), aCodec.autofield or
aJustwritten as null that a Store refuses,==on aDecimalor a
Json.Value, a lower-case currency code, and a Decimal or Money past the
Int range (NumericOverflow). The steps follow. - Moving a
Codec.autoDecimal or Money field toCodec.decimal/
Codec.moneyIn: convert the column first, with the statement the
Store.migraterefusal names (in a migration file), then switch the codec.
The refusal never drops a currency (docs/skydb/overview.md, "Decimal
columns"). ForCodec.moneyIn GBPon PostgreSQL, first check that
SELECT c FROM t WHERE c::text LIKE '{%' AND upper(c::json->>'currency') IS DISTINCT FROM 'GBP'returns no rows, then runALTER TABLE t ALTER COLUMN c TYPE NUMERIC USING (CASE WHEN c::text LIKE '{%' THEN (CASE WHEN upper(c::json->>'currency') = 'GBP' THEN c::json->>'amount' ELSE 'a Money object that is not in GBP: ' || c::text END) ELSE trim(both '"' from c::text) END)::numeric; a row in another currency makes it fail. A column
of Money objects has no conversion toCodec.decimal, because the
currency would be dropped: useCodec.moneyIn(one currency) or
Codec.moneyObject. - A stored Money with an empty currency: set the real currency on those
rows before the upgrade (see Breaking). - An app whose
mainwrites beforeDb.migrate, checked withsky db status: move the write afterDb.migrate(in status modeDb.migrate
prints the report and exits, so nothing after it runs), or move to file
migrations withsky db init;sky db statusthen readsdb/migrations
and the ledger and does not runmain. An app with noDb.migrate(it
usesStore.migrate) has no migration status to report: check it with
sky db check, which runs no app code. Std.Db.Storecolumns named with an SQL keyword: map the field to
another column name (Codec.field "sort_order" .order Codec.int) and rename
the column in a migration. Such a column never worked through the Store.Schema.createSchemamakesBIGINTfor a newSchema.intcolumn on
PostgreSQL. SQL that needs a 4-byte integer (DATE '1970-01-01' + day)
casts:day::int. Existing tables do not change.