@expressive/sql 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,302 @@
1
+ # @expressive/sql
2
+
3
+ ## 0.12.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#78](https://github.com/gabeklein/expressive-orm/pull/78) [`3a60a89`](https://github.com/gabeklein/expressive-orm/commit/3a60a895b1e2418fec9d4b41dfbd18b74a9dfb7b) SQLite stores a `timestamp` as INTEGER epoch milliseconds again, and the connection chooses: `SQLiteConnection.new(types, source, { timestamps })` takes `"ms"` (default), `"seconds"` or `"iso"` (ISO 8601 UTC text). `sql.now` in a `Query` or comparison, and a `fallback: sql.now` column default, render in the connection's storage, so `lessThan(sql.now)` and `date.created()` are right on an integer column. `sync`, `plan` and `expressive sql check` refuse a timestamp column declared the other way - INTEGER under `"iso"`, TEXT under `"ms"` - naming the option that keeps it, where before they reported plain type drift and `sync --force` would cast epoch numbers to unreadable text. `date` and `time` types stay text. Published packages now include `CHANGELOG.md`.
8
+
9
+ **Breaking:** a SQLite or D1 database created by 0.6 through 0.11 keeps timestamps as ISO text; `sync` now refuses it until you pass `{ timestamps: "iso" }` or migrate the columns.
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [[`3a60a89`](https://github.com/gabeklein/expressive-orm/commit/3a60a895b1e2418fec9d4b41dfbd18b74a9dfb7b)]:
14
+ - @expressive/orm@0.21.1
15
+
16
+ ## 0.11.0
17
+
18
+ ### Minor Changes
19
+
20
+ - [#73](https://github.com/gabeklein/expressive-orm/pull/73) [`4c19f4b`](https://github.com/gabeklein/expressive-orm/commit/4c19f4b25a643b3e5526bd7552ffcd3545ff0809) `Remote` requests carry a format version, `v: 1`, and `Remote.handle` refuses with a `Remote.Error` whose `code` says why: `version`, `malformed`, `unknown`, `invalid` or `failed`. Failures past validation still read `Request failed.`, with the original as `cause`; errors thrown by `check` pass through.
21
+
22
+ **Breaking:** a server on this version refuses requests without `v` - those from a 0.20 `Remote` client - with code `version`. Update client and server together.
23
+
24
+ ### Patch Changes
25
+
26
+ - Updated dependencies [[`4c19f4b`](https://github.com/gabeklein/expressive-orm/commit/4c19f4b25a643b3e5526bd7552ffcd3545ff0809)]:
27
+ - @expressive/orm@0.21.0
28
+
29
+ ## 0.10.0
30
+
31
+ ### Minor Changes
32
+
33
+ - [#69](https://github.com/gabeklein/expressive-orm/pull/69) [`b9a1b16`](https://github.com/gabeklein/expressive-orm/commit/b9a1b164559577122bb9f1b134f9b4792dcecadd) A class bound as an object - `Connection.new({ User, Post })` - takes its default table name from its key, in snake case. Keys survive minification where class names don't, so a bundled app keeps its tables without `static table`. An explicit `static table` still wins, and an array binds as before. A class listed twice now throws.
34
+
35
+ **Breaking:** an object whose key differs from the class name - `{ users: User }` - now reads and writes table `users` where it used `user`. `sync` would create the new table empty. Set `static table = "user"` to keep the old one.
36
+
37
+ - [#70](https://github.com/gabeklein/expressive-orm/pull/70) [`7adc7a0`](https://github.com/gabeklein/expressive-orm/commit/7adc7a034d0fc4d6e5d7a9eee8f54ff63df69495) `Remote` - a connection forwarding every read and write through a function you give it, to `Remote.handle(connection, options)` on a server. Requests name classes by the key they are bound under and fields by property, never table or column, so the server alone decides storage. The server validates each request and runs it as the class's own statics would, and masks failures past validation as `Request failed.`; `expose` names the classes and properties served and `check` authorizes each request with a context you pass. Reads, inserts, writes by id, relations and instance writes travel; `count`, writes by filter, `Query`, transactions and live rows don't.
38
+
39
+ SQL generation now refuses an unknown operator, sort order, or a limit or offset that isn't a whole number. A failed SQLite statement over 4KB is reported unformatted. Ordering by, or matching null on, a required relation no longer throws.
40
+
41
+ ### Patch Changes
42
+
43
+ - Updated dependencies [[`b9a1b16`](https://github.com/gabeklein/expressive-orm/commit/b9a1b164559577122bb9f1b134f9b4792dcecadd), [`7adc7a0`](https://github.com/gabeklein/expressive-orm/commit/7adc7a034d0fc4d6e5d7a9eee8f54ff63df69495)]:
44
+ - @expressive/orm@0.20.0
45
+
46
+ ## 0.9.1
47
+
48
+ ### Patch Changes
49
+
50
+ - [#64](https://github.com/gabeklein/expressive-orm/pull/64) [`e38054e`](https://github.com/gabeklein/expressive-orm/commit/e38054e27400a618b31b5f0f7845f2be3cc54cac) Agent skills checked against the source: test setup on `Memory` and how classes join the last connection, persisted `Memory`, React Native, forcing a sync, the CLI entry, Postgres `sync(false)` and `static schema`, and corrections to `timezone`, `one(id)` and `static schema`. `Connection`'s JSDoc is attached to the class again.
51
+ - Updated dependencies [[`2ddee0c`](https://github.com/gabeklein/expressive-orm/commit/2ddee0c5d766eb48e4d992cfdfc22fc34f3ec550), [`d8a845d`](https://github.com/gabeklein/expressive-orm/commit/d8a845d97914029de95998b4731d34c57720b440), [`e38054e`](https://github.com/gabeklein/expressive-orm/commit/e38054e27400a618b31b5f0f7845f2be3cc54cac)]:
52
+ - @expressive/orm@0.19.0
53
+
54
+ ## 0.9.0
55
+
56
+ ### Minor Changes
57
+
58
+ - [#54](https://github.com/gabeklein/expressive-orm/pull/54) [`3ff4f2b`](https://github.com/gabeklein/expressive-orm/commit/3ff4f2b7cc5086e0740780398db410e88a8dcad0) Breaking: `Type.one(where?, expect?)` resolves the live entity, loaded as `load(where, 1)` - a loaded entity settles the fetched row and is returned as is. It takes a filter only; `get(id)` covers ids, and an id throws. `Type.find` is now `Type.query(where?, limit?, offset?)`, still resolving frozen rows through the driver's `select` alone; `query(callback)` stays the `Query` builder, and `query()` without arguments now reads rows rather than building a `Query`. `rows()` handles follow: `find` is `query`, and `one` resolves an entity.
59
+
60
+ `date.created()` marks the class's recency. Without a filter - `{}` and all-`undefined` filters included - `query`, `load` and `one` take the newest first by it then by `id`, else by an incrementing `id`, else unordered - and `one()` without a filter then throws asking for one. A second `created()` on one class throws.
61
+
62
+ - [#56](https://github.com/gabeklein/expressive-orm/pull/56) [`d946b59`](https://github.com/gabeklein/expressive-orm/commit/d946b597a91d1f4219aee47301d6b9adea29c563) Breaking: `Type.all(pageSize, where?)` is gone - use `query(where, pageSize)`, arguments swapped. `query(where, limit, offset?)` with a numeric `limit` now returns `Type.Results` rather than a plain `Promise<Columns[]>`: it resolves its first `limit` rows when awaited and, iterated with `for await`, yields every match `limit` rows per select. A `limit` typed `number | undefined` resolves rows. A limit of `0` reads every match in one batch. `rows()` handles follow.
63
+
64
+ A read with a limit is always totally ordered: the filter's `asc()` / `desc()`, else the class's newest first, then by id. Every limited select now carries an `ORDER BY` - `one`, `load(where, limit)` and the by-id load behind `get` included. `one({ ... })` now resolves the newest match rather than any.
65
+
66
+ ### Patch Changes
67
+
68
+ - Updated dependencies [[`3ff4f2b`](https://github.com/gabeklein/expressive-orm/commit/3ff4f2b7cc5086e0740780398db410e88a8dcad0), [`d946b59`](https://github.com/gabeklein/expressive-orm/commit/d946b597a91d1f4219aee47301d6b9adea29c563)]:
69
+ - @expressive/orm@0.18.0
70
+
71
+ ## 0.8.3
72
+
73
+ ### Patch Changes
74
+
75
+ - Updated dependencies [[`5e6ac69`](https://github.com/gabeklein/expressive-orm/commit/5e6ac69fd0980879590d6d0bf7dddd00fed76615), [`9f0596d`](https://github.com/gabeklein/expressive-orm/commit/9f0596dfa3f9c3921f1f440aa49e88ffa37d48ec)]:
76
+ - @expressive/orm@0.17.0
77
+
78
+ ## 0.8.2
79
+
80
+ ### Patch Changes
81
+
82
+ - Updated dependencies [[`da081bd`](https://github.com/gabeklein/expressive-orm/commit/da081bd0ed401965f6ec097099034022adb6e215)]:
83
+ - @expressive/orm@0.16.0
84
+
85
+ ## 0.8.1
86
+
87
+ ### Patch Changes
88
+
89
+ - [#49](https://github.com/gabeklein/expressive-orm/pull/49) [`8d351b8`](https://github.com/gabeklein/expressive-orm/commit/8d351b81030922a9135f779f94af6baae37d475f) **`@expressive/sql` bundles under Metro for iOS and Android.** The SQLite driver loader sits in its own module, which a `react-native` package field swaps for one that loads nothing, so Metro no longer rejects its dynamic `import()`. On React Native, pass an `Engine` in place of a filename; a filename or libSQL address rejects, asking for one. Expo web and Expo Router server bundles still do not bundle `@expressive/sql`.
90
+ - Updated dependencies [[`8d351b8`](https://github.com/gabeklein/expressive-orm/commit/8d351b81030922a9135f779f94af6baae37d475f)]:
91
+ - @expressive/orm@0.15.1
92
+
93
+ ## 0.8.0
94
+
95
+ ### Minor Changes
96
+
97
+ - [#51](https://github.com/gabeklein/expressive-orm/pull/51) [`8905fb4`](https://github.com/gabeklein/expressive-orm/commit/8905fb4a3553437e2ac3d7c3e33e564c7a46cd55) Fields declare portable datatypes and connections own storage. A field checks plain values the same on every side - integer ranges, decimal precision and scale, string length - and a connection takes and returns them, Dates and JSON values included, storing them through codecs chosen by the field's base helper (`Connection.Codec`, a protected `codecs` getter). One schema module importing only `@expressive/orm` binds to SQLite, D1, Postgres, `memory()` or a connection forwarding to a server, and the SQL floor checks forwarded values again before storing them. `Connection.new` throws for a field the connection can't store.
98
+
99
+ Breaking: orm declares the portable types - `str` text, varchar, char, uuid; `num` integer (now the default everywhere), smallint, bigint, real, double, decimal, numeric; `date` timestamp, date, time, with `timezone`; `bool` boolean. Storage-only types are dropped - `date` ms, seconds, integer and text, `num` float, `bool` with `either`, `one` integer and bigint (a relation takes its key's type), Postgres `serial` and `interval` - with their `sql.*` tokens. The column classes and `X.Type` hooks are gone (`StringColumn`, `NumericColumn`, `BooleanColumn`, `TimeColumn`, `ForeignColumn`); `@expressive/sql` exports `codecs` instead. `Field.datatype` is gone. `memory()` stores values as given.
100
+
101
+ Every helper gains `.and(...presets)`, returning the same helper with those options first; `date.created` and `date.updated` are presets of `date`.
102
+
103
+ A `date({ type: "date" })` column is a calendar day, not an instant: a Date gives its local day, a `"YYYY-MM-DD"` string is that day, and it reads as local midnight. It crosses every connection and is stored as `YYYY-MM-DD`, so a client and server in different time zones agree.
104
+
105
+ - [#50](https://github.com/gabeklein/expressive-orm/pull/50) [`f5cafff`](https://github.com/gabeklein/expressive-orm/commit/f5cafff8d048e390a48dd6c67315ccdc2496e464) `Type.load(where?, limit?, offset?)` resolves live entities for a filter in one select, reusing and settling loaded ones; `rows()` handles gain `load`. `connection.before(Type, { delete(row) })` gates a delete by id - a throw cancels it - and `connection.after(Type, { delete(row) })` runs best-effort effects once it is done: awaited, errors logged rather than thrown, after commit inside a transaction. Each returns a remover.
106
+
107
+ ### Patch Changes
108
+
109
+ - Updated dependencies [[`8905fb4`](https://github.com/gabeklein/expressive-orm/commit/8905fb4a3553437e2ac3d7c3e33e564c7a46cd55), [`f5cafff`](https://github.com/gabeklein/expressive-orm/commit/f5cafff8d048e390a48dd6c67315ccdc2496e464)]:
110
+ - @expressive/orm@0.15.0
111
+
112
+ ## 0.7.0
113
+
114
+ ### Minor Changes
115
+
116
+ - [#36](https://github.com/gabeklein/expressive-orm/pull/36) [`7024b85`](https://github.com/gabeklein/expressive-orm/commit/7024b85d4386b1aad9f238543926d1b1dd5980d9) **`SQLiteConnection` runs on Cloudflare D1 and libSQL (Turso).** In place of a filename it takes a D1 binding, a libSQL client, or a `libsql:`, `https:`, `http:`, `ws:` or `wss:` address, which opens `@libsql/client` and reads a token from `?authToken=`. D1 applies `sync` as one batch, refuses `transaction`, and refuses a rebuild since it keeps foreign keys on. Every libSQL client, the built-in loader's included, runs each `transaction` on a libSQL write transaction, applies `sync` as one batch and rebuilds a table through `migrate`; schema checks inside a transaction run on it. The `@libsql/client` peer is now `>=0.18.0` - older clients lose an in-memory database on its first transaction. A table created by `sync` now plans its indexes as statements of their own, so a batch that runs one statement per entry creates them.
117
+
118
+ ## 0.6.0
119
+
120
+ ### Minor Changes
121
+
122
+ - [#40](https://github.com/gabeklein/expressive-orm/pull/40) [`1d1dbb5`](https://github.com/gabeklein/expressive-orm/commit/1d1dbb55f3b0cccb2049d41035aa31f7772ed65e) **`Generator` exposes protected hooks for dialects.** `literal(value)` renders every literal in values, `SET` and `WHERE`; `insertWith(cte, into, select)` places a data CTE in an insert; `table(table)` renders a table with its alias for `FROM`, joins, `UPDATE` and `DELETE`. A schema-qualified table's alias is now quoted everywhere, fixing Postgres queries and updates that aliased one.
123
+
124
+ - [#47](https://github.com/gabeklein/expressive-orm/pull/47) [`9cf9cde`](https://github.com/gabeklein/expressive-orm/commit/9cf9cde5a0b5e74c8f514e44ee68a88d7cb63f03) Driver seams move to `@expressive/orm/driver`: `Builder`, `Where`, `Computed`, `DataField`, `DataTable`, `Parameter` and `QueryTemplate`. The root entry - and `@expressive/sql`'s, which re-exports it - keeps the app API. `Where` stays on the root as a type. A driver imports these, and `evaluate`, from `@expressive/orm/driver`.
125
+
126
+ - [#41](https://github.com/gabeklein/expressive-orm/pull/41) [`4f3e23c`](https://github.com/gabeklein/expressive-orm/commit/4f3e23c9e75cd4f9dc65e7ebda02577829e4d0d1) **`memory()` runs transactions, and every driver gets them from `@expressive/orm`.** `transaction(fn)`, the connection lock (`lock()`, `idle()`) and the journal that restores instances move from `@expressive/sql`'s `Connection` to `@expressive/orm`'s, over a protected `transact(fn)` hook, so a driver without SQL implements `transact` and nothing else. On `memory()` a rollback restores every table and the next id, subscribers hear of changes once a transaction commits, and statements from outside an open transaction wait for it. Like the SQL drivers, it needs `AsyncLocalStorage` and throws without it.
127
+
128
+ - [#39](https://github.com/gabeklein/expressive-orm/pull/39) [`0c5d036`](https://github.com/gabeklein/expressive-orm/commit/0c5d03630311ccbcbfa29515537577ad509ecaac) **SQLite engines can bring their own transactions and batches.** An `Engine` may implement `transaction()`, returning a session whose statements, `commit` and `rollback` back `transaction(fn)`, and `batch(sql)`, through which `sync` applies atomically. A batched rebuild turns foreign keys off around it and is refused where the engine keeps them on. A failed rollback no longer hides the error that caused it.
129
+
130
+ - [#34](https://github.com/gabeklein/expressive-orm/pull/34) [`7603ed0`](https://github.com/gabeklein/expressive-orm/commit/7603ed0b12d4305c34adc1cca5b0126dcdde01ee) **`SQLiteConnection` takes an engine.** `new SQLiteConnection(types, engine)` runs on any object implementing the exported `Engine` type (`all`, `get`, `run`, `exec`, `close`), for a SQLite the built-in loader can't open. A filename still selects the built-in engine. A given engine is used as is and left open by `close()`.
131
+
132
+ ### Patch Changes
133
+
134
+ - [#46](https://github.com/gabeklein/expressive-orm/pull/46) [`acd61f1`](https://github.com/gabeklein/expressive-orm/commit/acd61f112e38d330fe7c990e974bf6595a59699a) Document the public API in JSDoc, so hovers and completions carry each symbol's contract, and correct the agent skills against the source: `json()` takes one option, relation writes insert an object without `id`, `where(Other)` needs a join condition on SQL, `num()` is a 32-bit integer on SQL, default ordering of `find()` and `one()`, and an error table.
135
+
136
+ - [#44](https://github.com/gabeklein/expressive-orm/pull/44) [`567a398`](https://github.com/gabeklein/expressive-orm/commit/567a3982aeea543aeadec8d9529b836187671330) Ship each package's agent skill in the package, at `skills/expressive-<pkg>/SKILL.md`, so the docs an agent reads match the installed version. Agents read them from `node_modules/@expressive/<pkg>/skills/` - point one there with a line in `AGENTS.md`, or `npx skills add gabeklein/expressive`.
137
+ - Updated dependencies [[`7603ed0`](https://github.com/gabeklein/expressive-orm/commit/7603ed0b12d4305c34adc1cca5b0126dcdde01ee), [`acd61f1`](https://github.com/gabeklein/expressive-orm/commit/acd61f112e38d330fe7c990e974bf6595a59699a), [`9cf9cde`](https://github.com/gabeklein/expressive-orm/commit/9cf9cde5a0b5e74c8f514e44ee68a88d7cb63f03), [`4f3e23c`](https://github.com/gabeklein/expressive-orm/commit/4f3e23c9e75cd4f9dc65e7ebda02577829e4d0d1), [`567a398`](https://github.com/gabeklein/expressive-orm/commit/567a3982aeea543aeadec8d9529b836187671330), [`acd61f1`](https://github.com/gabeklein/expressive-orm/commit/acd61f112e38d330fe7c990e974bf6595a59699a)]:
138
+ - @expressive/orm@0.14.0
139
+
140
+ ## 0.5.0
141
+
142
+ ### Minor Changes
143
+
144
+ - [#22](https://github.com/gabeklein/expressive-orm/pull/22) [`23f442c`](https://github.com/gabeklein/expressive-orm/commit/23f442c449927b10c9fb9b240eaa5161e6a01672) **Datatypes as modifiers.** `sql.*` names a column's datatype, with factories for sized ones: `num(sql.bigint, null)`, `str(sql.varchar(120), unique)`, `num(sql.decimal(10, 2))`. A datatype of another helper, like `num(sql.text)`, is a type error. `@expressive/postgres` adds `sql.serial`, `sql.timestamptz`, `sql.timetz` and `sql.interval`. `unique` and `index` join `optional` as modifiers; `null` replaces `orNull`, which is deprecated.
145
+
146
+ **Indexes.** `index`, or `{ index: "name" }`, makes `sync` create a missing index, named `<table>_<column>` by default. On SQLite an existing single-column index on the column counts.
147
+
148
+ **`key()` declares any id.** `key()` is an incrementing integer, typed `number`; `key(sql.text, { column: "name" })` a string required on insert; `key(sql.uuid)` a string generated on insert as a UUIDv7 when absent. A non-integer numeric key does not increment. `uuid()` is deprecated for `key(sql.uuid)` or `str(sql.uuid)`.
149
+
150
+ **Epoch dates.** `date(sql.ms)` stores a `Date` as epoch milliseconds - INTEGER on SQLite, BIGINT on Postgres; `date(sql.seconds)` names the existing epoch-seconds `integer` storage.
151
+
152
+ **`Query` is a `Promise`.** It has `catch` and `finally`, so returning one from an async function typechecks.
153
+
154
+ - [#22](https://github.com/gabeklein/expressive-orm/pull/22) [`0149fbe`](https://github.com/gabeklein/expressive-orm/commit/0149fbefd67b74f87ac9599b6f9b9bde4935e434) **A relation's column is named after its property.** `author = one(User)` stores `author_id`, not `user_id`; relations named after their class keep their column. Two fields on one column throw when the class is first used. On a table still holding the old column, sync reports the relation instead of adding an empty one: add `{ column: "user_id" }` to keep it.
155
+
156
+ - [#16](https://github.com/gabeklein/expressive-orm/pull/16) [`d4ee4e4`](https://github.com/gabeklein/expressive-orm/commit/d4ee4e443867520f8422b4c9b5bb240157ae3449) `@expressive/sql` is Expressive ORM on SQL: it depends on and re-exports `@expressive/orm`, holds the SQL datatype vocabulary and the SQL connection base, and absorbs `@expressive/sqlite`. Installed alone it is a working embedded store on Bun or Node 24. Import `Type`, `Query`, the field helpers and a connection from here.
157
+
158
+ **Moved and removed**
159
+
160
+ - `Table`, `Field`, `Query`, `Builder`, `Parameter`, `DataTable`, `Primary` and the `Str`, `Num`, `Bool`, `Time` and `One` columns are removed. Entities are `Type` subclasses with orm's `str`, `num`, `bool`, `date`, `uuid`, `json` and `one` helpers; `Query` comes from orm, re-exported here.
161
+ - `SQLiteConnection` moves in from `@expressive/sqlite`. Construct connections with `SQLiteConnection.new(types, filename?)`.
162
+ - `Connection.None` is removed; a query without a connection prints orm's intent dump.
163
+ - `@expressive/orm` is a dependency; `@expressive/mvc` is a peer.
164
+
165
+ **SQLite**
166
+
167
+ - The driver is picked at runtime: `bun:sqlite`, `node:sqlite` (Node 24), then `better-sqlite3`, `sqlite3` or `@libsql/client`, the last three optional peers.
168
+ - `sync` validates existing tables, creates missing ones and adds missing columns with `ALTER TABLE ... ADD COLUMN`, so a database file reopens after a field is added. A column it cannot add - primary, `unique`, `NOT NULL` without a `fallback`, or defaulting to `"NOW"` - is reported with the reason and nothing changes. Type drift is reported, never altered; columns not on the class are ignored. `sync(false)` throws for a missing table or column. Awaiting the connection runs it.
169
+ - Schema renders `PRIMARY KEY` for any primary column, `DEFAULT` for every `fallback` with `"NOW"` as `CURRENT_TIMESTAMP`, and `one()`'s `onDelete` / `onUpdate`. Each type renders as its affinity - `TEXT`, `INTEGER`, `REAL` or `NUMERIC` (`numeric` and `decimal` were `REAL`) - while a field's `datatype` stays the declared type. `json` is `TEXT`.
170
+ - `date` stores ISO strings by default; `"NOW"` is no longer a value to `set`.
171
+ - `close()` destroys the connection and unbinds its classes.
172
+ - No live rows: neither `node:sqlite` nor `bun:sqlite` exposes an update hook. `Type.update(id, data)` still settles a loaded entity.
173
+ - `insert` reads the stored row back through `RETURNING`, defaults included.
174
+
175
+ **Datatypes.** One vocabulary augments orm's helpers and validates on every dialect - `varchar`/`char` length, integer ranges, numeric precision and scale:
176
+
177
+ - `str`: `text` (default), `varchar`, `char`, `uuid`
178
+ - `num`: `integer` (default), `smallint`, `bigint`, `real`, `float`, `double`, `numeric`, `decimal`
179
+ - `bool`: `boolean` (default, a JS boolean, bound as 1/0 on SQLite), `integer` (1/0), `text` and `varchar` with `either`
180
+ - `date`: `timestamp` (default), `date`, `time`, `integer` (unix seconds), `text`
181
+ - `one`: `integer` (default), `bigint`
182
+
183
+ `num` and `date` no longer take `serial` or `datetime`. The column classes export as `StringColumn`, `NumericColumn`, `BooleanColumn`, `TimeColumn` and `ForeignColumn`; importing only a connection narrows `type` options.
184
+
185
+ **Connection base.** `Connection` extends orm's: it implements the floor - `select`, `insert`, `update`, `remove` - as builder statements against the class registered for the table (passed to `new` or bound by `Type.connection = db`), values bound as parameters and the class's primary column matched, so a renamed key round-trips. A dialect supplies `prepare` through a `Generator` subclass, and `sync`. `Generator` renders orm's `Builder`: `null` comparisons as `IS NULL` / `IS NOT NULL`, an insert with a selection with `RETURNING`, `offset` as `OFFSET`, an empty `isIn` as false and `notIn` as true.
186
+
187
+ **Fixes**
188
+
189
+ - Inline string literals quote by doubling `'`, with no backslash escapes. A value containing `\'` broke out of its string on SQLite and Postgres - an injection - and `'` was a syntax error.
190
+ - `static schema` throws on SQLite and Postgres `sync`; only `memory()` honours it.
191
+ - A failed SQLite statement reports the engine error when its SQL cannot be formatted.
192
+
193
+ **Packaging.** ESM only, built with tsdown.
194
+
195
+ Requires `@expressive/mvc` `^0.94.0`.
196
+
197
+ - [#22](https://github.com/gabeklein/expressive-orm/pull/22) [`b9d339f`](https://github.com/gabeklein/expressive-orm/commit/b9d339f65bfdaf9fc68d06e2d4d9b509c86600b8) **`expressive sql check | sync [--force] <entry>`.** A bin, shared by `@expressive/*` packages, that imports the module creating your connections with `sync` held back, then reports or applies what each connection's schema needs. `check` exits 1 when anything would change and marks drift `--force` can rebuild.
198
+
199
+ **`plan(force?)`.** SQL connections return what `sync` would do - `{ steps, problems }`, each step with `action`, `reason` and `sql` - without doing it. `sync` applies the plan in one transaction, and verify-only `sync(false)` now also reports missing indexes. A table referencing one the same sync creates no longer fails as a missing referenced table.
200
+
201
+ **`sync(true, true)` rebuilds drift.** A column whose type or nullability differs from its class is altered on Postgres and rebuilt with its table on SQLite, keeping columns the class doesn't declare, indexes and triggers, and casting values. It refuses while a row would not fit - a NULL under `NOT NULL`, or text that is not a number for a numeric column - or while any row references a missing one. `plan()` is abstract on `Connection`; a custom subclass implements it.
202
+
203
+ - [#22](https://github.com/gabeklein/expressive-orm/pull/22) [`3c9c7a2`](https://github.com/gabeklein/expressive-orm/commit/3c9c7a2737be328077bf4c8c34060b60fbf338ef) **Transactions.** `connection.transaction(fn)` runs `fn` in one database transaction, committing when it resolves and rolling back when it throws. Statements inside join it without a handle, through `AsyncLocalStorage` loaded on first use; a nested call joins the open transaction, so a caught nested failure commits with it. On SQLite and PGlite, other statements wait until it ends and transactions queue; `pg` runs each on its own pooled client, discarding a client whose `BEGIN`, `COMMIT` or `ROLLBACK` failed. A rollback restores instances changed inside, destroys entities created inside and keeps entities deleted inside; a commit destroys those. SQLite and Postgres support it. Where `AsyncLocalStorage` is missing it throws, and `memory()` has none.
204
+
205
+ **Driver contract.** orm's `Connection` declares an optional `transaction(fn)`. `@expressive/sql`'s `Connection` implements it over a protected `transact(fn)`, which a driver provides, plus `lock()` and an `idle()` its statements await - a pooled driver overrides both.
206
+
207
+ - [#22](https://github.com/gabeklein/expressive-orm/pull/22) [`cdf383b`](https://github.com/gabeklein/expressive-orm/commit/cdf383be6f92e34b2b75b3764696855ba83c872f) **Upsert.** `Type.insert(data, { conflict })` writes `ON CONFLICT`. `"update"` overwrites the existing row with every column given, minus the target and `keep`, returns it and settles a loaded instance; `"ignore"` leaves it and resolves `undefined`. `on` names the target - a key or keys, the primary key by default. The memory driver matches.
208
+
209
+ **Composite keys.** `id = key(() => [this.account, this.role])` keys an entity by the fields it lists, with no column of its own. `id` is a string - the parts as JSON - typed as a key of their tuple (`Type.Id<T>` takes either), so it compares by value. `get`, `one`, `update` and `delete` take the key or the tuple, the identity map holds it, a part change through `set` or `update` rekeys a loaded instance, and `sync` declares `PRIMARY KEY (...)` - existing tables included. Live rows report a composite id on Postgres and memory. `one()` cannot relate to a composite-keyed class.
210
+
211
+ **Driver contract.** `insert(table, data, returns?, conflict?)` takes `Connection.Conflict` (`{ on, update? }` by column). `update` and `remove` take `Connection.Key`, which is a tuple for a composite key; `Change.id` likewise. `Field.parts` lists a composite key's fields.
212
+
213
+ - [#22](https://github.com/gabeklein/expressive-orm/pull/22) [`a5fe1d2`](https://github.com/gabeklein/expressive-orm/commit/a5fe1d2b7c60a8a5a4485924d6ac50e99719caee) **`sql.now`.** The current time, wherever a date goes: a column `fallback`, an insert or update value, a comparison. In `Query` it renders as the database's clock in the column's own storage - ISO text with milliseconds, epoch ms or seconds, `date`, `time`, `timestamptz`; statics resolve it from the app's clock so settled instances hold the exact value. `fallback: "NOW"` is a deprecated alias, and a new SQLite `timestamp` default is ISO text with milliseconds rather than `CURRENT_TIMESTAMP`'s `YYYY-MM-DD HH:MM:SS`, which reads as UTC.
214
+
215
+ **`date.created()` and `date.updated()`.** Date columns defaulting to now; `created` is never overwritten after insert, `updated` is set to now on every update and upsert that doesn't give it. They are `date()` with `{ fixed: true }` and `{ update: sql.now }`, which any column takes. A fixed column is left out of update types and throws if given to `update()` or `set()`; `update` also takes a function, called once per write.
216
+
217
+ **`conflict: "replace"`.** An upsert setting every column from the new row - an omitted one to its default or NULL - except the primary key, `date.created` columns and `keep`. An upsert's `update` values apply only on conflict; a new row gets its `fallback`.
218
+
219
+ **Writes by query.** `update(where, data)` and `delete(where)` take a query object in place of an id and resolve the rows affected, settling into or destroying loaded instances; an empty query throws. `count(where?)` counts rows. `null` in a query object matches a missing value. In `Query`, `where(table).match({ ... })` adds an `equal` per key.
220
+
221
+ **`json()`** reads unparseable text as `undefined` instead of throwing, and `isLike` matches a `json()` column's stored text.
222
+
223
+ **`Key<P>`** is exported, and a composite `id` is typed `Key<[number, string]>` rather than `Optional<KeyOf<...>>`.
224
+
225
+ **Fallbacks fill on insert.** An omitted column with a `fallback` is written with it by the orm, not left to a database `DEFAULT` - a table created before the fallback existed gets it too. A nullable column defaulting to now can now be added to an existing SQLite table.
226
+
227
+ **SQLite enforces foreign keys** on every driver; `bun:sqlite` left them off.
228
+
229
+ ### Patch Changes
230
+
231
+ - [#22](https://github.com/gabeklein/expressive-orm/pull/22) [`338865e`](https://github.com/gabeklein/expressive-orm/commit/338865e3a62f411801517b02fc04b0c13832fc89) Fixes found adopting an existing SQLite database:
232
+
233
+ - SQLite `sync` accepts a primary key column not declared `NOT NULL`, as tables created outside the library usually are.
234
+ - A count `Query` (no selection) resolves the matching row count on SQLite and Postgres; it resolved 0 on SQLite and the affected rows on Postgres.
235
+ - A table joined twice in one `Query`, such as two relations to the same class, is aliased instead of failing with an ambiguous column.
236
+ - `insert({})` writes `DEFAULT VALUES`. An insert per joined row with no values throws a clear error.
237
+ - Updated dependencies [[`23f442c`](https://github.com/gabeklein/expressive-orm/commit/23f442c449927b10c9fb9b240eaa5161e6a01672), [`d4ee4e4`](https://github.com/gabeklein/expressive-orm/commit/d4ee4e443867520f8422b4c9b5bb240157ae3449), [`0149fbe`](https://github.com/gabeklein/expressive-orm/commit/0149fbefd67b74f87ac9599b6f9b9bde4935e434), [`338865e`](https://github.com/gabeklein/expressive-orm/commit/338865e3a62f411801517b02fc04b0c13832fc89), [`b9d339f`](https://github.com/gabeklein/expressive-orm/commit/b9d339f65bfdaf9fc68d06e2d4d9b509c86600b8), [`3c9c7a2`](https://github.com/gabeklein/expressive-orm/commit/3c9c7a2737be328077bf4c8c34060b60fbf338ef), [`cdf383b`](https://github.com/gabeklein/expressive-orm/commit/cdf383be6f92e34b2b75b3764696855ba83c872f), [`a5fe1d2`](https://github.com/gabeklein/expressive-orm/commit/a5fe1d2b7c60a8a5a4485924d6ac50e99719caee)]:
238
+ - @expressive/orm@0.13.0
239
+
240
+ ## 0.4.4
241
+
242
+ ### Patch Changes
243
+
244
+ - allow uuid type for Primary
245
+
246
+ ## 0.4.3
247
+
248
+ ### Patch Changes
249
+
250
+ - fix: failed to build previous change
251
+
252
+ ## 0.4.2
253
+
254
+ ### Patch Changes
255
+
256
+ - 2acdeb2: primary and fields with defaults are now Optional
257
+
258
+ ## 0.4.1
259
+
260
+ ### Patch Changes
261
+
262
+ - b8b2195: fix: rebuild libraries
263
+
264
+ ## 0.4.0
265
+
266
+ ### Minor Changes
267
+
268
+ - 6f4c66b: Major upgrade: generic Fields
269
+
270
+ ## 0.3.1
271
+
272
+ ### Patch Changes
273
+
274
+ - 857a18c: Improved types for One
275
+
276
+ ## 0.3.0
277
+
278
+ ### Minor Changes
279
+
280
+ - aa94a15: Generic fields
281
+
282
+ ## 0.2.1
283
+
284
+ ### Patch Changes
285
+
286
+ - f5c7c31: Allow any number as Str length
287
+
288
+ ## 0.2.0
289
+
290
+ ### Minor Changes
291
+
292
+ - 9720a38: Multiple Updates
293
+
294
+ ### Patch Changes
295
+
296
+ - 004ebe8: replaced bad test scripts
297
+
298
+ ## 0.1.1
299
+
300
+ ### Patch Changes
301
+
302
+ - cef396d: limit published files to "dist" in package.json
package/README.md CHANGED
@@ -42,7 +42,7 @@ await gabe.set({ name: "Gabriel" });
42
42
  await db.close();
43
43
  ```
44
44
 
45
- `SQLiteConnection.new(types, filename?)` binds the classes; awaiting it creates missing tables, adds missing columns and checks existing ones. SQLite cannot add a `unique` column or one defaulting to `"NOW"`; `sync` reports those. Omit `filename` for an in-memory database. In its place, pass a Cloudflare D1 binding, a libSQL client or a `libsql://` address - see [SQLite hosts](https://github.com/gabeklein/expressive-orm#sqlite-hosts).
45
+ `SQLiteConnection.new(types, filename?, { timestamps? })` binds the classes; awaiting it creates missing tables, adds missing columns and checks existing ones. SQLite cannot add a `unique` column or one defaulting to `"NOW"`; `sync` reports those. Omit `filename` for an in-memory database. `timestamps` is `"ms"` (default), `"seconds"` or `"iso"` - see [Datatypes](https://github.com/gabeklein/expressive-orm#datatypes). In its place, pass a Cloudflare D1 binding, a libSQL client or a `libsql://` address - see [SQLite hosts](https://github.com/gabeklein/expressive-orm#sqlite-hosts).
46
46
 
47
47
  ## Also here
48
48
 
@@ -1,9 +1,22 @@
1
1
  import { Connection as Connection$1 } from "../connection/Connection.js";
2
2
  import { D1Database, Engine, LibSQLClient } from "./engine.js";
3
+ import { Timestamps } from "./SQLiteGenerator.js";
3
4
  import { Field, Query } from "@expressive/orm";
4
5
  import { Builder } from "@expressive/orm/driver";
5
6
 
6
7
  //#region src/sqlite/SQLiteConnection.d.ts
8
+ declare namespace SQLiteConnection {
9
+ /** How a SQLite connection stores what the database can't type itself. */
10
+ interface Options {
11
+ /**
12
+ * Storage of a `timestamp` - `"ms"` INTEGER epoch milliseconds, `"seconds"` INTEGER epoch seconds, `"iso"` ISO 8601 UTC text.
13
+ *
14
+ * Defaults to `"ms"`. `"seconds"` drops the milliseconds. `sql.now` and `fallback: now` render in the same storage.
15
+ * A `date` or `time` type stays text. `sync` refuses a column holding the other storage.
16
+ */
17
+ timestamps?: Timestamps;
18
+ }
19
+ }
7
20
  type TableInfo = {
8
21
  name: string;
9
22
  type: string;
@@ -22,6 +35,7 @@ type TableInfo = {
22
35
  declare class SQLiteConnection extends Connection$1 {
23
36
  #private;
24
37
  protected get codecs(): ReadonlyMap<Function, Connection$1.Codec>;
38
+ protected timestamps: Timestamps;
25
39
  protected filename: string;
26
40
  protected engine?: Promise<Engine>;
27
41
  protected owned: boolean;
@@ -33,7 +47,7 @@ declare class SQLiteConnection extends Connection$1 {
33
47
  * A D1 binding, a libSQL client or an `Engine` is used as given - foreign keys are not switched on, and `close()` leaves it open.
34
48
  * D1 refuses `transaction`. libSQL runs each `transaction` on a libSQL write transaction, one at a time.
35
49
  */
36
- constructor(using: Connection$1.Types, source?: string | Engine | D1Database | LibSQLClient);
50
+ constructor(using: Connection$1.Types, source?: string | Engine | D1Database | LibSQLClient, options?: SQLiteConnection.Options);
37
51
  protected db(): Promise<Engine>;
38
52
  /** `CREATE TABLE` and `CREATE INDEX` statements for the bound classes, formatted. */
39
53
  get schema(): string;
@@ -2,7 +2,7 @@ import { codecs } from "../codecs.js";
2
2
  import { Connection as Connection$1 } from "../connection/Connection.js";
3
3
  import { createEngine, host, migrations } from "./engine.js";
4
4
  import { SQLiteGenerator, now as now$1 } from "./SQLiteGenerator.js";
5
- import { now } from "@expressive/orm";
5
+ import { date, now } from "@expressive/orm";
6
6
  import { format } from "sql-formatter";
7
7
 
8
8
  //#region src/sqlite/SQLiteConnection.ts
@@ -17,7 +17,7 @@ import { format } from "sql-formatter";
17
17
  */
18
18
  var SQLiteConnection = class extends Connection$1 {
19
19
  get codecs() {
20
- return affinities;
20
+ return STORAGE[this.timestamps || "ms"];
21
21
  }
22
22
  /**
23
23
  * Bind `using` to a SQLite database. Construct with `SQLiteConnection.new`.
@@ -27,9 +27,10 @@ var SQLiteConnection = class extends Connection$1 {
27
27
  * A D1 binding, a libSQL client or an `Engine` is used as given - foreign keys are not switched on, and `close()` leaves it open.
28
28
  * D1 refuses `transaction`. libSQL runs each `transaction` on a libSQL write transaction, one at a time.
29
29
  */
30
- constructor(using, source) {
30
+ constructor(using, source, options = {}) {
31
31
  super(using);
32
32
  this.owned = true;
33
+ this.timestamps = options.timestamps || "ms";
33
34
  if (typeof source == "object") {
34
35
  (this.engine = Promise.resolve(source).then(host)).catch(() => {});
35
36
  this.owned = false;
@@ -53,7 +54,7 @@ var SQLiteConnection = class extends Connection$1 {
53
54
  * A failure when run rethrows as `Error running SQL: <message>` with the statement.
54
55
  */
55
56
  prepare(builder) {
56
- const sql = String(new SQLiteGenerator(builder));
57
+ const sql = String(new SQLiteGenerator(builder, this.timestamps));
57
58
  const string = (x) => x ? x.map((x) => x !== null && typeof x === "object" ? JSON.stringify(x) : typeof x === "boolean" ? Number(x) : x) : [];
58
59
  const run = async (op) => {
59
60
  try {
@@ -224,8 +225,10 @@ var SQLiteConnection = class extends Connection$1 {
224
225
  absent.push(field);
225
226
  continue;
226
227
  }
227
- const message = drifted(field, info);
228
- if (message) drift.push({
228
+ const stored = restored(field, info);
229
+ const message = !stored && drifted(field, info);
230
+ if (stored) issues.push(stored);
231
+ else if (message) drift.push({
229
232
  field,
230
233
  message
231
234
  });
@@ -324,6 +327,20 @@ function indexName(field) {
324
327
  function index(field) {
325
328
  return `CREATE INDEX IF NOT EXISTS \`${indexName(field)}\` ON ${field.parent.table} (\`${field.column}\`);`;
326
329
  }
330
+ function restored(field, info) {
331
+ const target = field.reference || field;
332
+ const found = info.type.toUpperCase();
333
+ const expected = affinity(field);
334
+ if (target.type !== "timestamp" || found === expected || !["INTEGER", "TEXT"].includes(found)) return;
335
+ const mode = connection(field)["timestamps"];
336
+ const keep = found == "TEXT" ? `{ timestamps: "iso" }` : `{ timestamps: "ms" } or { timestamps: "seconds" }`;
337
+ return `Column ${field.column} in table ${field.parent.table} holds timestamps as ${found}, but this connection stores them as ${STORED[mode]}. Pass ${keep} to SQLiteConnection.new to keep them, or migrate the column.`;
338
+ }
339
+ const STORED = {
340
+ ms: "INTEGER epoch milliseconds",
341
+ seconds: "INTEGER epoch seconds",
342
+ iso: "ISO 8601 TEXT"
343
+ };
327
344
  function drifted(field, info) {
328
345
  const { column, nullable, primary } = field;
329
346
  const parent = field.parent;
@@ -385,10 +402,27 @@ const AFFINITY = {
385
402
  time: "TEXT",
386
403
  json: "TEXT"
387
404
  };
388
- const affinities = new Map(Array.from(codecs, ([helper, codec]) => [helper, {
389
- ...codec,
390
- datatype: (field) => AFFINITY[field.type]
391
- }]));
405
+ function storage(timestamps) {
406
+ const scale = timestamps == "seconds" ? 1e3 : 1;
407
+ return new Map(Array.from(codecs, ([helper, codec]) => {
408
+ const datatype = (field) => AFFINITY[field.type];
409
+ if (helper !== date || timestamps == "iso") return [helper, {
410
+ ...codec,
411
+ datatype
412
+ }];
413
+ return [helper, {
414
+ ...codec,
415
+ datatype: (field) => field.type == "timestamp" ? "INTEGER" : datatype(field),
416
+ encode: (field, value) => field.type == "timestamp" ? Math.floor(value.getTime() / scale) : codec.encode(field, value),
417
+ decode: (field, value) => field.type == "timestamp" && typeof value == "number" ? new Date(value * scale) : codec.decode(field, value)
418
+ }];
419
+ }));
420
+ }
421
+ const STORAGE = {
422
+ ms: storage("ms"),
423
+ seconds: storage("seconds"),
424
+ iso: storage("iso")
425
+ };
392
426
  function connection(field) {
393
427
  return field.parent.connection;
394
428
  }
@@ -396,7 +430,7 @@ function affinity(field) {
396
430
  return connection(field)._datatype(field);
397
431
  }
398
432
  function literal(field, value) {
399
- if (value === "NOW" || value === now) return `(${now$1(field)})`;
433
+ if (value === "NOW" || value === now) return `(${now$1(field, connection(field)["timestamps"])})`;
400
434
  if (value === null) return "NULL";
401
435
  const encoded = connection(field)._encode(field, field.set(value));
402
436
  return typeof encoded == "string" ? `'${encoded.replace(/'/g, "''")}'` : String(encoded);
@@ -1 +1 @@
1
- {"version":3,"file":"SQLiteConnection.js","names":["Connection","#statements","current"],"sources":["../../src/sqlite/SQLiteConnection.ts"],"sourcesContent":["import { Field, now, Query, Type } from '@expressive/orm';\nimport { Builder } from '@expressive/orm/driver';\nimport { codecs } from '../codecs';\nimport { Connection } from '../connection/Connection';\nimport { format } from 'sql-formatter';\n\nimport { createEngine, type D1Database, Engine, host, type LibSQLClient, migrations } from './engine';\nimport { now as current, SQLiteGenerator } from './SQLiteGenerator';\n\ntype TableInfo = {\n name: string;\n type: string;\n notnull: number;\n dflt_value: any\n};\n\n/**\n * A connection to SQLite - a file, in memory, a libSQL address, a D1 binding, a libSQL client or a given `Engine`.\n *\n * The built-in loader takes the first of `bun:sqlite`, `node:sqlite`, `better-sqlite3`, `sqlite3`, `@libsql/client`, with foreign keys on.\n * Awaiting it runs `sync`. No live rows.\n *\n * @example\n * const db = await SQLiteConnection.new([User, Post], \"app.db\");\n */\nexport class SQLiteConnection extends Connection {\n protected get codecs(){\n return affinities;\n }\n\n protected filename: string;\n protected engine?: Promise<Engine>;\n protected owned = true;\n\n /**\n * Bind `using` to a SQLite database. Construct with `SQLiteConnection.new`.\n *\n * Without `source`, the database is in memory. A filename opens through the built-in loader.\n * A `libsql:`, `https:`, `http:`, `ws:` or `wss:` address opens a `@libsql/client` 0.18 or later - pass a token as `?authToken=`.\n * A D1 binding, a libSQL client or an `Engine` is used as given - foreign keys are not switched on, and `close()` leaves it open.\n * D1 refuses `transaction`. libSQL runs each `transaction` on a libSQL write transaction, one at a time.\n */\n constructor(using: Connection.Types, source?: string | Engine | D1Database | LibSQLClient) {\n super(using);\n\n if (typeof source == \"object\") {\n (this.engine = Promise.resolve(source).then(host)).catch(() => {});\n this.owned = false;\n }\n\n this.filename = typeof source == \"string\" && source || ':memory:';\n }\n\n protected db(){\n return this.engine ??= createEngine(this.filename);\n }\n\n async #statements(): Promise<Engine.Statements> {\n await this.idle();\n\n return this._journal()?.session as Engine.Session || this.db();\n }\n\n /** `CREATE TABLE` and `CREATE INDEX` statements for the bound classes, formatted. */\n get schema() {\n return pretty(this.generateSchema(this.using));\n }\n\n /**\n * Compile a builder to SQLite SQL.\n *\n * A failure when run rethrows as `Error running SQL: <message>` with the statement.\n */\n prepare(builder: Builder){\n const sql = String(new SQLiteGenerator(builder));\n const string = (x?: unknown[]) => x\n ? x.map(x => (\n x !== null && typeof x === 'object' ? JSON.stringify(x) :\n typeof x === 'boolean' ? Number(x) :\n x\n ))\n : [];\n\n const run = async <R>(op: (engine: Engine.Statements) => Promise<R>) => {\n try {\n return await op(await this.#statements());\n }\n catch (err) {\n if(err instanceof Error)\n throw new Error(`Error running SQL: ${err.message}\\n${sql.length > 4096 ? sql.slice(0, 4096) + \"...\" : pretty(sql)}`);\n\n throw err;\n }\n };\n\n const counts = !builder.returns && !builder.inserts.size && !builder.updates.size && !builder.deletes.size;\n\n return {\n all: (p?: any[]) => run(e => e.all(sql, string(p))),\n run: counts\n ? (p?: any[]) => run(e => e.get(sql, string(p)).then(row => Number(Object.values(row)[0])))\n : (p?: any[]) => run(e => e.run(sql, string(p)).then(r => r.changes)),\n toString: () => pretty(sql)\n };\n }\n\n protected async transact<T>(fn: () => Promise<T>): Promise<T> {\n const db = await this.db();\n const session = this._journal()!.session = await db.transaction?.();\n\n if (!session)\n await db.exec(\"BEGIN\");\n\n try {\n const result = await fn();\n\n await (session ? session.commit() : db.exec(\"COMMIT\"));\n\n return result;\n }\n catch (error) {\n await (session ? session.rollback() : db.exec(\"ROLLBACK\")).catch(() => {});\n throw error;\n }\n }\n\n /** Close the database when this connection opened it, then release the connection. */\n async close(){\n const engine = await this.engine?.catch(() => undefined);\n\n if (engine && this.owned)\n await engine.close();\n\n await super.close();\n }\n\n /**\n * Bring the database in line with the bound classes, then mark the connection ready.\n *\n * Creates missing tables and adds missing columns and indexes, in one transaction. Throws for any problem `plan` reports, changing nothing.\n * `fix` false only verifies - anything missing throws too. `force` rebuilds a table whose column type or nullability drifted.\n * Throws when the connection is already ready.\n */\n async sync(fix = true, force = false){\n if (this.ready)\n throw new Error(\"Connection is already active.\");\n\n const { steps, problems } = await this.plan(force);\n const issues = fix ? problems : [...problems, ...steps.map(step => step.reason)];\n\n if (issues.length)\n throw new Error(issues.join(\"\\n\"));\n\n if (steps.length)\n await this.apply(steps);\n\n (this as Connection).set({ ready: true });\n\n return this;\n }\n\n /**\n * List what `sync` would do, without doing it.\n *\n * `problems` are what it cannot fix - drift without `force`, a column SQLite cannot add, a missing referenced table, `static schema`.\n */\n async plan(force = false): Promise<Connection.Plan> {\n const steps: Connection.Step[] = [];\n const problems: string[] = [];\n\n for (const type of this.using) {\n const { table } = type;\n\n if (type.schema) {\n problems.push(`static schema is not supported by ${this.constructor.name}.`);\n continue;\n }\n\n const found = await this.inspect(type, true);\n\n if (!found) {\n steps.push({ table, action: `create table ${table}`, reason: `Table ${table} does not exist.`, sql: [this.tableSchema(type), ...indexed(type).map(index)] });\n continue;\n }\n\n const { columns, absent, drift, issues } = found;\n const rebuild = force && drift.length > 0;\n\n problems.push(...issues);\n\n if (!rebuild)\n problems.push(...drift.map(({ message }) => message));\n\n for (const field of absent) {\n const reason = moved(field, columns.map(col => col.name)) || unfit(field);\n\n if (reason)\n problems.push(`Column ${field.column} in table ${table} ${reason}`);\n else if (!rebuild)\n steps.push({\n table,\n column: field.column,\n action: `add column ${field.column} to ${table}`,\n reason: `Column ${field.column} does not exist in table ${table}`,\n sql: [`ALTER TABLE ${table} ADD COLUMN ${definition(field, true)};`]\n });\n }\n\n if (rebuild) {\n const fields = drift.map(({ field }) => field);\n const misfit = await this.misfit(type, fields, columns);\n\n if (misfit.length)\n problems.push(...misfit);\n else\n steps.push({\n table,\n action: `rebuild table ${table}`,\n reason: drift.map(({ message }) => message).join(\"; \"),\n sql: await this.rebuild(type, fields, columns)\n });\n }\n\n for (const field of await this.unindexed(type))\n steps.push({\n table,\n column: field.column,\n action: `create index ${indexName(field)} on ${table}`,\n reason: `Index ${indexName(field)} does not exist on ${table}`,\n sql: [index(field)]\n });\n }\n\n return { steps, problems };\n }\n\n protected async apply(steps: Connection.Step[]){\n const db = await this.db();\n const rebuilds = steps.some(step => step.action.startsWith(\"rebuild\"));\n const sql = steps.flatMap(step => step.sql);\n const migrate = migrations.get(db);\n\n if (migrate && rebuilds) {\n await intact(db);\n return void await migrate(sql);\n }\n\n const guard = rebuilds && (await db.get(\"PRAGMA foreign_keys\"))?.foreign_keys;\n\n if (db.batch && !guard)\n return db.batch(sql);\n\n if (db.batch) {\n await db.exec(\"PRAGMA foreign_keys = OFF\").catch(() => {});\n\n try {\n if ((await db.get(\"PRAGMA foreign_keys\")).foreign_keys)\n throw new Error(\"Cannot rebuild: this engine keeps foreign keys on, so dropping the table would cascade.\");\n\n await intact(db);\n\n return await db.batch(sql);\n }\n finally {\n await db.exec(\"PRAGMA foreign_keys = ON\").catch(() => {});\n }\n }\n\n if (guard)\n await db.exec(\"PRAGMA foreign_keys = OFF\");\n\n await db.exec(\"BEGIN\");\n\n try {\n await db.exec(sql.join(\"\\n\"));\n\n if (guard)\n await intact(db);\n\n await db.exec(\"COMMIT\");\n }\n catch (error) {\n await db.exec(\"ROLLBACK\");\n throw error;\n }\n finally {\n if (guard)\n await db.exec(\"PRAGMA foreign_keys = ON\");\n }\n }\n\n async valid(type: Query.Table){\n const found = await this.inspect(type);\n\n if (!found)\n return false;\n\n const [problem] = [...found.drift.map(({ message }) => message), ...found.issues];\n\n if (problem)\n throw new Error(problem);\n\n return found.absent;\n }\n\n protected async inspect(type: Query.Table, planning = false){\n const { table } = type;\n const db = await this.#statements();\n\n const tableExists = await db.get(\n `SELECT name FROM sqlite_master WHERE type='table' AND name=?`, [table]);\n\n if (!tableExists)\n return false;\n\n const columns = await db.all(`PRAGMA table_info(${table})`) as TableInfo[];\n const absent: Field[] = [];\n const drift: { field: Field, message: string }[] = [];\n const issues: string[] = [];\n\n for (const field of type.fields.values()) {\n if (field.parts)\n continue;\n\n const info = columns.find(col => col.name === field.column);\n\n if (!info) {\n absent.push(field);\n continue;\n }\n\n const message = drifted(field, info);\n\n if (message)\n drift.push({ field, message });\n\n issues.push(...await this.references(field, planning));\n }\n\n return { columns, absent, drift, issues };\n }\n\n protected async unindexed(type: Query.Table){\n const db = await this.#statements();\n const covered = new Set<string>();\n\n for (const { name } of await db.all(`PRAGMA index_list(${type.table})`)) {\n const columns = await db.all(`PRAGMA index_info(\\`${name}\\`)`);\n\n if (columns.length == 1)\n covered.add(columns[0].name);\n }\n\n return indexed(type).filter(field => !covered.has(field.column));\n }\n\n protected async misfit(type: Query.Table, fields: Field[], columns: TableInfo[]){\n const db = await this.#statements();\n const { table } = type;\n const problems: string[] = [];\n\n for (const field of fields) {\n const info = columns.find(col => col.name === field.column)!;\n const column = `\\`${field.column}\\``;\n const expected = affinity(field);\n const fits = FITS[expected];\n const checks: [string, string][] = [];\n\n if (!field.nullable)\n checks.push([`${column} IS NULL`, \"NULL\"]);\n\n if (info.type.toUpperCase() !== expected && fits)\n checks.push([`${column} IS NOT NULL AND NOT (${fits(column)})`, `not ${expected}`]);\n\n for (const [where, what] of checks) {\n const { count } = await db.get(`SELECT COUNT(*) AS count FROM ${table} WHERE ${where}`);\n\n if (count)\n problems.push(\n `Column ${field.column} in table ${table} cannot be rebuilt: ${count} ${count == 1 ? \"row is\" : \"rows are\"} ${what}.`\n );\n }\n }\n\n return problems;\n }\n\n protected async rebuild(type: Query.Table, fields: Field[], columns: TableInfo[]){\n const db = await this.#statements();\n const { table } = type;\n const temp = `${table}__rebuild`;\n const own = Array.from(type.fields.values()).filter(field => !field.parts);\n const known = new Set(own.map(field => field.column));\n const extra = columns.filter(col => !known.has(col.name));\n const cast = new Set(fields.filter(field => (\n columns.find(col => col.name === field.column)!.type.toUpperCase() !== affinity(field)\n )));\n\n const copied = [\n ...own\n .filter(field => columns.some(col => col.name === field.column))\n .map(field => [field.column, cast.has(field) ? `CAST(\\`${field.column}\\` AS ${affinity(field)})` : `\\`${field.column}\\``]),\n ...extra.map(col => [col.name, `\\`${col.name}\\``])\n ];\n\n const indexes = await db.all(\n `SELECT sql FROM sqlite_master WHERE type IN ('index', 'trigger') AND tbl_name = ? AND sql IS NOT NULL`, [table]);\n\n return [\n this.tableSchema(type, temp, extra.map(col => (\n `\\`${col.name}\\` ${col.type}` +\n (col.notnull ? \" NOT NULL\" : \"\") +\n (col.dflt_value != null ? ` DEFAULT ${col.dflt_value}` : \"\")\n ))),\n `INSERT INTO ${temp} (${copied.map(([column]) => `\\`${column}\\``).join(\", \")}) ` +\n `SELECT ${copied.map(([, value]) => value).join(\", \")} FROM ${table};`,\n `DROP TABLE ${table};`,\n `ALTER TABLE ${temp} RENAME TO ${table};`,\n ...indexes.map(({ sql }: { sql: string }) => `${sql};`)\n ];\n }\n\n protected async references(field: Field, planning: boolean): Promise<string[]> {\n const { reference } = field;\n\n if (!reference)\n return [];\n\n const foreignKey = reference.column;\n const foreignTable = reference.parent!.table;\n\n if (reference.parent!.connection !== this)\n return [`Foreign key ${foreignTable}.${foreignKey} cannot be checked by another connection`];\n\n const db = await this.#statements();\n\n const foreignTableExists = await db.get(\n `SELECT name FROM sqlite_master WHERE type='table' AND name=?`, [foreignTable]);\n\n if (!foreignTableExists)\n return planning && this.using.has(reference.parent!) ? [] : [`Referenced table ${foreignTable} does not exist`];\n\n const foreignColumn = (await db.all(`PRAGMA table_info(${foreignTable})`))\n .find(col => col.name === foreignKey);\n\n if (!foreignColumn)\n return [`Referenced column ${foreignKey} does not exist in table ${foreignTable}`];\n\n return [];\n }\n\n protected generateSchema(types: Iterable<Query.Table>): string {\n return Array.from(types)\n .map(type => this.generateTableSchema(type))\n .join('\\n');\n }\n\n protected generateTableSchema(type: Query.Table): string {\n return [this.tableSchema(type), ...indexed(type).map(index)].join('\\n');\n }\n\n protected tableSchema(type: Query.Table, name = type.table, extra: string[] = []){\n const { parts } = type.fields.get(\"id\")!;\n const fields = [\n ...Array.from(type.fields.values()).filter(field => !field.parts).map(field => definition(field)),\n ...extra\n ];\n\n if (parts)\n fields.push(`PRIMARY KEY (${parts.map(part => `\\`${part.column}\\``).join(', ')})`);\n\n return `CREATE TABLE ${name} (${fields.join(', ')});`;\n }\n}\n\nfunction indexed(type: Query.Table){\n return Array.from(type.fields.values()).filter(field => field.index && !field.primary && !field.unique);\n}\n\nasync function intact(db: Engine.Statements){\n const broken: { table: string }[] = await db.all(\"PRAGMA foreign_key_check\");\n\n if (broken.length) {\n const tables = [...new Set(broken.map(row => row.table))].join(\", \");\n\n throw new Error(`Cannot rebuild: ${tables} has references to missing rows (${broken.length}).`);\n }\n}\n\nfunction indexName(field: Field){\n return typeof field.index == \"string\" ? field.index : `${field.parent!.table}_${field.column}`;\n}\n\nfunction index(field: Field){\n return `CREATE INDEX IF NOT EXISTS \\`${indexName(field)}\\` ON ${field.parent!.table} (\\`${field.column}\\`);`;\n}\n\nfunction drifted(field: Field, info: TableInfo){\n const { column, nullable, primary } = field;\n const parent = field.parent!;\n const keyed = primary || parent.fields.get(\"id\")!.parts?.includes(field);\n const expected = affinity(field);\n\n if (info.type.toUpperCase() !== expected)\n return `Column ${column} in table ${parent.table} has type ${info.type}, expected ${expected}`;\n\n if (!keyed && info.notnull === (nullable ? 1 : 0))\n return `Column ${column} in table ${parent.table} has incorrect nullable value`;\n}\n\nconst NUMBER = (column: string) =>\n `typeof(${column}) = 'text' AND CASE WHEN json_valid(trim(${column})) THEN json_type(trim(${column})) ELSE '' END IN ('integer', 'real')`;\n\nconst FITS: Record<string, (column: string) => string> = {\n INTEGER: column =>\n `typeof(${column}) = 'integer' OR typeof(${column}) = 'real' AND ${column} = CAST(${column} AS INTEGER) ` +\n `OR ${NUMBER(column)} AND ${column} NOT GLOB '*[eE]*' AND CAST(${column} AS REAL) = CAST(${column} AS INTEGER)`,\n REAL: column =>\n `typeof(${column}) IN ('integer', 'real') OR ${NUMBER(column)}`\n};\n\nFITS.NUMERIC = FITS.REAL;\n\nfunction definition(field: Field, adding?: boolean){\n const {\n column,\n fallback,\n reference,\n increment,\n nullable,\n primary,\n unique,\n } = field;\n\n const { onDelete, onUpdate } = field as Field & { onDelete?: string, onUpdate?: string };\n let parts = `\\`${column}\\` ${affinity(field)}`;\n\n if (!nullable) parts += ' NOT NULL';\n if (primary) parts += ' PRIMARY KEY';\n if (increment) parts += ' AUTOINCREMENT';\n if (unique) parts += ' UNIQUE';\n\n if (fallback !== undefined && !(adding && clock(fallback)))\n parts += ' DEFAULT ' + literal(field, fallback);\n\n if (reference)\n parts += ` REFERENCES ${reference.parent!.table}(${reference.column})`;\n\n if (onDelete) parts += ` ON DELETE ${onDelete}`;\n if (onUpdate) parts += ` ON UPDATE ${onUpdate}`;\n\n return parts;\n}\n\nfunction moved(field: Field, existing: string[]){\n const { entity } = field as Field & { entity?: Query.Table };\n const old = entity && `${entity.table}_id`;\n const taken = Array.from(field.parent!.fields.values()).some(other => other.column === old);\n\n if (old && !taken && existing.includes(old))\n return `is missing but ${old} exists; add { column: \"${old}\" } to ${field.parent!.name}.${field.key} to keep it.`;\n}\n\nfunction clock(fallback: unknown){\n return fallback === \"NOW\" || fallback === now;\n}\n\nfunction unfit({ primary, unique, nullable, fallback }: Field){\n if (primary)\n return \"is a primary key and cannot be added to an existing table.\";\n\n if (unique)\n return \"is UNIQUE and cannot be added by SQLite.\";\n\n if (!nullable && fallback === undefined)\n return \"is NOT NULL without a default and cannot be added to existing rows.\";\n\n if (!nullable && clock(fallback))\n return \"defaults to the current time and cannot be added by SQLite.\";\n}\n\nconst AFFINITY: Record<string, string> = {\n integer: \"INTEGER\",\n smallint: \"INTEGER\",\n bigint: \"INTEGER\",\n boolean: \"INTEGER\",\n real: \"REAL\",\n double: \"REAL\",\n numeric: \"NUMERIC\",\n decimal: \"NUMERIC\",\n text: \"TEXT\",\n varchar: \"TEXT\",\n char: \"TEXT\",\n uuid: \"TEXT\",\n timestamp: \"TEXT\",\n date: \"TEXT\",\n time: \"TEXT\",\n json: \"TEXT\"\n};\n\nconst affinities: ReadonlyMap<Function, Connection.Codec> = new Map(Array.from(codecs, ([helper, codec]) => [\n helper,\n { ...codec, datatype: (field: Field) => AFFINITY[field.type] }\n]));\n\nfunction connection(field: Field){\n return (field.parent as Type.Class).connection;\n}\n\nfunction affinity(field: Field){\n return connection(field)._datatype(field);\n}\n\nfunction literal(field: Field, value: unknown){\n if (value === \"NOW\" || value === now)\n return `(${current(field)})`;\n\n if (value === null)\n return \"NULL\";\n\n const encoded = connection(field)._encode(field, field.set(value));\n\n return typeof encoded == \"string\"\n ? `'${encoded.replace(/'/g, \"''\")}'`\n : String(encoded);\n}\n\nfunction pretty(sql: string){\n try {\n return format(sql, { language: 'sqlite', keywordCase: \"upper\" })\n .replace(/ - > > /g, \" ->> \")\n .replace(/`([a-zA-Z][a-zA-Z0-9_]*)`/g, \"$1\");\n }\n catch {\n return sql;\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;AAyBA,IAAa,mBAAb,cAAsCA,aAAW;CAC/C,IAAc,SAAQ;AACpB,SAAO;;;;;;;;;;CAeT,YAAY,OAAyB,QAAsD;AACzF,QAAM,MAAM;eAXI;AAahB,MAAI,OAAO,UAAU,UAAU;AAC7B,IAAC,KAAK,SAAS,QAAQ,QAAQ,OAAO,CAAC,KAAK,KAAK,EAAE,YAAY,GAAG;AAClE,QAAK,QAAQ;;AAGf,OAAK,WAAW,OAAO,UAAU,YAAY,UAAU;;CAGzD,AAAU,KAAI;AACZ,SAAO,KAAK,WAAW,a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C/D,CAAC,CAAC;AAEH,SAAS,WAAW,OAAa;AAC/B,QAAQ,MAAM,OAAsB;;AAGtC,SAAS,SAAS,OAAa;AAC7B,QAAO,WAAW,MAAM,CAAC,UAAU,MAAM;;AAG3C,SAAS,QAAQ,OAAc,OAAe;AAC5C,KAAI,UAAU,SAAS,UAAU,IAC/B,QAAO,IAAIC,MAAQ,MAAM,CAAC;AAE5B,KAAI,UAAU,KACZ,QAAO;CAET,MAAM,UAAU,WAAW,MAAM,CAAC,QAAQ,OAAO,MAAM,IAAI,MAAM,CAAC;AAElE,QAAO,OAAO,WAAW,WACrB,IAAI,QAAQ,QAAQ,MAAM,KAAK,CAAC,KAChC,OAAO,QAAQ;;AAGrB,SAAS,OAAO,KAAY;AAC1B,KAAI;AACF,SAAO,OAAO,KAAK;GAAE,UAAU;GAAU,aAAa;GAAS,CAAC,CAC7D,QAAQ,YAAY,QAAQ,CAC5B,QAAQ,8BAA8B,KAAK;SAE1C;AACJ,SAAO"}
1
+ {"version":3,"file":"SQLiteConnection.js","names":["Connection","#statements","current"],"sources":["../../src/sqlite/SQLiteConnection.ts"],"sourcesContent":["import { date, Field, now, Query, Type } from '@expressive/orm';\nimport { Builder } from '@expressive/orm/driver';\nimport { codecs } from '../codecs';\nimport { Connection } from '../connection/Connection';\nimport { format } from 'sql-formatter';\n\nimport { createEngine, type D1Database, Engine, host, type LibSQLClient, migrations } from './engine';\nimport { now as current, SQLiteGenerator, type Timestamps } from './SQLiteGenerator';\n\nexport declare namespace SQLiteConnection {\n /** How a SQLite connection stores what the database can't type itself. */\n interface Options {\n /**\n * Storage of a `timestamp` - `\"ms\"` INTEGER epoch milliseconds, `\"seconds\"` INTEGER epoch seconds, `\"iso\"` ISO 8601 UTC text.\n *\n * Defaults to `\"ms\"`. `\"seconds\"` drops the milliseconds. `sql.now` and `fallback: now` render in the same storage.\n * A `date` or `time` type stays text. `sync` refuses a column holding the other storage.\n */\n timestamps?: Timestamps;\n }\n}\n\ntype TableInfo = {\n name: string;\n type: string;\n notnull: number;\n dflt_value: any\n};\n\n/**\n * A connection to SQLite - a file, in memory, a libSQL address, a D1 binding, a libSQL client or a given `Engine`.\n *\n * The built-in loader takes the first of `bun:sqlite`, `node:sqlite`, `better-sqlite3`, `sqlite3`, `@libsql/client`, with foreign keys on.\n * Awaiting it runs `sync`. No live rows.\n *\n * @example\n * const db = await SQLiteConnection.new([User, Post], \"app.db\");\n */\nexport class SQLiteConnection extends Connection {\n protected get codecs(){\n return STORAGE[this.timestamps || \"ms\"];\n }\n\n protected timestamps: Timestamps;\n\n protected filename: string;\n protected engine?: Promise<Engine>;\n protected owned = true;\n\n /**\n * Bind `using` to a SQLite database. Construct with `SQLiteConnection.new`.\n *\n * Without `source`, the database is in memory. A filename opens through the built-in loader.\n * A `libsql:`, `https:`, `http:`, `ws:` or `wss:` address opens a `@libsql/client` 0.18 or later - pass a token as `?authToken=`.\n * A D1 binding, a libSQL client or an `Engine` is used as given - foreign keys are not switched on, and `close()` leaves it open.\n * D1 refuses `transaction`. libSQL runs each `transaction` on a libSQL write transaction, one at a time.\n */\n constructor(using: Connection.Types, source?: string | Engine | D1Database | LibSQLClient, options: SQLiteConnection.Options = {}) {\n super(using);\n\n this.timestamps = options.timestamps || \"ms\";\n\n if (typeof source == \"object\") {\n (this.engine = Promise.resolve(source).then(host)).catch(() => {});\n this.owned = false;\n }\n\n this.filename = typeof source == \"string\" && source || ':memory:';\n }\n\n protected db(){\n return this.engine ??= createEngine(this.filename);\n }\n\n async #statements(): Promise<Engine.Statements> {\n await this.idle();\n\n return this._journal()?.session as Engine.Session || this.db();\n }\n\n /** `CREATE TABLE` and `CREATE INDEX` statements for the bound classes, formatted. */\n get schema() {\n return pretty(this.generateSchema(this.using));\n }\n\n /**\n * Compile a builder to SQLite SQL.\n *\n * A failure when run rethrows as `Error running SQL: <message>` with the statement.\n */\n prepare(builder: Builder){\n const sql = String(new SQLiteGenerator(builder, this.timestamps));\n const string = (x?: unknown[]) => x\n ? x.map(x => (\n x !== null && typeof x === 'object' ? JSON.stringify(x) :\n typeof x === 'boolean' ? Number(x) :\n x\n ))\n : [];\n\n const run = async <R>(op: (engine: Engine.Statements) => Promise<R>) => {\n try {\n return await op(await this.#statements());\n }\n catch (err) {\n if(err instanceof Error)\n throw new Error(`Error running SQL: ${err.message}\\n${sql.length > 4096 ? sql.slice(0, 4096) + \"...\" : pretty(sql)}`);\n\n throw err;\n }\n };\n\n const counts = !builder.returns && !builder.inserts.size && !builder.updates.size && !builder.deletes.size;\n\n return {\n all: (p?: any[]) => run(e => e.all(sql, string(p))),\n run: counts\n ? (p?: any[]) => run(e => e.get(sql, string(p)).then(row => Number(Object.values(row)[0])))\n : (p?: any[]) => run(e => e.run(sql, string(p)).then(r => r.changes)),\n toString: () => pretty(sql)\n };\n }\n\n protected async transact<T>(fn: () => Promise<T>): Promise<T> {\n const db = await this.db();\n const session = this._journal()!.session = await db.transaction?.();\n\n if (!session)\n await db.exec(\"BEGIN\");\n\n try {\n const result = await fn();\n\n await (session ? session.commit() : db.exec(\"COMMIT\"));\n\n return result;\n }\n catch (error) {\n await (session ? session.rollback() : db.exec(\"ROLLBACK\")).catch(() => {});\n throw error;\n }\n }\n\n /** Close the database when this connection opened it, then release the connection. */\n async close(){\n const engine = await this.engine?.catch(() => undefined);\n\n if (engine && this.owned)\n await engine.close();\n\n await super.close();\n }\n\n /**\n * Bring the database in line with the bound classes, then mark the connection ready.\n *\n * Creates missing tables and adds missing columns and indexes, in one transaction. Throws for any problem `plan` reports, changing nothing.\n * `fix` false only verifies - anything missing throws too. `force` rebuilds a table whose column type or nullability drifted.\n * Throws when the connection is already ready.\n */\n async sync(fix = true, force = false){\n if (this.ready)\n throw new Error(\"Connection is already active.\");\n\n const { steps, problems } = await this.plan(force);\n const issues = fix ? problems : [...problems, ...steps.map(step => step.reason)];\n\n if (issues.length)\n throw new Error(issues.join(\"\\n\"));\n\n if (steps.length)\n await this.apply(steps);\n\n (this as Connection).set({ ready: true });\n\n return this;\n }\n\n /**\n * List what `sync` would do, without doing it.\n *\n * `problems` are what it cannot fix - drift without `force`, a column SQLite cannot add, a missing referenced table, `static schema`.\n */\n async plan(force = false): Promise<Connection.Plan> {\n const steps: Connection.Step[] = [];\n const problems: string[] = [];\n\n for (const type of this.using) {\n const { table } = type;\n\n if (type.schema) {\n problems.push(`static schema is not supported by ${this.constructor.name}.`);\n continue;\n }\n\n const found = await this.inspect(type, true);\n\n if (!found) {\n steps.push({ table, action: `create table ${table}`, reason: `Table ${table} does not exist.`, sql: [this.tableSchema(type), ...indexed(type).map(index)] });\n continue;\n }\n\n const { columns, absent, drift, issues } = found;\n const rebuild = force && drift.length > 0;\n\n problems.push(...issues);\n\n if (!rebuild)\n problems.push(...drift.map(({ message }) => message));\n\n for (const field of absent) {\n const reason = moved(field, columns.map(col => col.name)) || unfit(field);\n\n if (reason)\n problems.push(`Column ${field.column} in table ${table} ${reason}`);\n else if (!rebuild)\n steps.push({\n table,\n column: field.column,\n action: `add column ${field.column} to ${table}`,\n reason: `Column ${field.column} does not exist in table ${table}`,\n sql: [`ALTER TABLE ${table} ADD COLUMN ${definition(field, true)};`]\n });\n }\n\n if (rebuild) {\n const fields = drift.map(({ field }) => field);\n const misfit = await this.misfit(type, fields, columns);\n\n if (misfit.length)\n problems.push(...misfit);\n else\n steps.push({\n table,\n action: `rebuild table ${table}`,\n reason: drift.map(({ message }) => message).join(\"; \"),\n sql: await this.rebuild(type, fields, columns)\n });\n }\n\n for (const field of await this.unindexed(type))\n steps.push({\n table,\n column: field.column,\n action: `create index ${indexName(field)} on ${table}`,\n reason: `Index ${indexName(field)} does not exist on ${table}`,\n sql: [index(field)]\n });\n }\n\n return { steps, problems };\n }\n\n protected async apply(steps: Connection.Step[]){\n const db = await this.db();\n const rebuilds = steps.some(step => step.action.startsWith(\"rebuild\"));\n const sql = steps.flatMap(step => step.sql);\n const migrate = migrations.get(db);\n\n if (migrate && rebuilds) {\n await intact(db);\n return void await migrate(sql);\n }\n\n const guard = rebuilds && (await db.get(\"PRAGMA foreign_keys\"))?.foreign_keys;\n\n if (db.batch && !guard)\n return db.batch(sql);\n\n if (db.batch) {\n await db.exec(\"PRAGMA foreign_keys = OFF\").catch(() => {});\n\n try {\n if ((await db.get(\"PRAGMA foreign_keys\")).foreign_keys)\n throw new Error(\"Cannot rebuild: this engine keeps foreign keys on, so dropping the table would cascade.\");\n\n await intact(db);\n\n return await db.batch(sql);\n }\n finally {\n await db.exec(\"PRAGMA foreign_keys = ON\").catch(() => {});\n }\n }\n\n if (guard)\n await db.exec(\"PRAGMA foreign_keys = OFF\");\n\n await db.exec(\"BEGIN\");\n\n try {\n await db.exec(sql.join(\"\\n\"));\n\n if (guard)\n await intact(db);\n\n await db.exec(\"COMMIT\");\n }\n catch (error) {\n await db.exec(\"ROLLBACK\");\n throw error;\n }\n finally {\n if (guard)\n await db.exec(\"PRAGMA foreign_keys = ON\");\n }\n }\n\n async valid(type: Query.Table){\n const found = await this.inspect(type);\n\n if (!found)\n return false;\n\n const [problem] = [...found.drift.map(({ message }) => message), ...found.issues];\n\n if (problem)\n throw new Error(problem);\n\n return found.absent;\n }\n\n protected async inspect(type: Query.Table, planning = false){\n const { table } = type;\n const db = await this.#statements();\n\n const tableExists = await db.get(\n `SELECT name FROM sqlite_master WHERE type='table' AND name=?`, [table]);\n\n if (!tableExists)\n return false;\n\n const columns = await db.all(`PRAGMA table_info(${table})`) as TableInfo[];\n const absent: Field[] = [];\n const drift: { field: Field, message: string }[] = [];\n const issues: string[] = [];\n\n for (const field of type.fields.values()) {\n if (field.parts)\n continue;\n\n const info = columns.find(col => col.name === field.column);\n\n if (!info) {\n absent.push(field);\n continue;\n }\n\n const stored = restored(field, info);\n const message = !stored && drifted(field, info);\n\n if (stored)\n issues.push(stored);\n else if (message)\n drift.push({ field, message });\n\n issues.push(...await this.references(field, planning));\n }\n\n return { columns, absent, drift, issues };\n }\n\n protected async unindexed(type: Query.Table){\n const db = await this.#statements();\n const covered = new Set<string>();\n\n for (const { name } of await db.all(`PRAGMA index_list(${type.table})`)) {\n const columns = await db.all(`PRAGMA index_info(\\`${name}\\`)`);\n\n if (columns.length == 1)\n covered.add(columns[0].name);\n }\n\n return indexed(type).filter(field => !covered.has(field.column));\n }\n\n protected async misfit(type: Query.Table, fields: Field[], columns: TableInfo[]){\n const db = await this.#statements();\n const { table } = type;\n const problems: string[] = [];\n\n for (const field of fields) {\n const info = columns.find(col => col.name === field.column)!;\n const column = `\\`${field.column}\\``;\n const expected = affinity(field);\n const fits = FITS[expected];\n const checks: [string, string][] = [];\n\n if (!field.nullable)\n checks.push([`${column} IS NULL`, \"NULL\"]);\n\n if (info.type.toUpperCase() !== expected && fits)\n checks.push([`${column} IS NOT NULL AND NOT (${fits(column)})`, `not ${expected}`]);\n\n for (const [where, what] of checks) {\n const { count } = await db.get(`SELECT COUNT(*) AS count FROM ${table} WHERE ${where}`);\n\n if (count)\n problems.push(\n `Column ${field.column} in table ${table} cannot be rebuilt: ${count} ${count == 1 ? \"row is\" : \"rows are\"} ${what}.`\n );\n }\n }\n\n return problems;\n }\n\n protected async rebuild(type: Query.Table, fields: Field[], columns: TableInfo[]){\n const db = await this.#statements();\n const { table } = type;\n const temp = `${table}__rebuild`;\n const own = Array.from(type.fields.values()).filter(field => !field.parts);\n const known = new Set(own.map(field => field.column));\n const extra = columns.filter(col => !known.has(col.name));\n const cast = new Set(fields.filter(field => (\n columns.find(col => col.name === field.column)!.type.toUpperCase() !== affinity(field)\n )));\n\n const copied = [\n ...own\n .filter(field => columns.some(col => col.name === field.column))\n .map(field => [field.column, cast.has(field) ? `CAST(\\`${field.column}\\` AS ${affinity(field)})` : `\\`${field.column}\\``]),\n ...extra.map(col => [col.name, `\\`${col.name}\\``])\n ];\n\n const indexes = await db.all(\n `SELECT sql FROM sqlite_master WHERE type IN ('index', 'trigger') AND tbl_name = ? AND sql IS NOT NULL`, [table]);\n\n return [\n this.tableSchema(type, temp, extra.map(col => (\n `\\`${col.name}\\` ${col.type}` +\n (col.notnull ? \" NOT NULL\" : \"\") +\n (col.dflt_value != null ? ` DEFAULT ${col.dflt_value}` : \"\")\n ))),\n `INSERT INTO ${temp} (${copied.map(([column]) => `\\`${column}\\``).join(\", \")}) ` +\n `SELECT ${copied.map(([, value]) => value).join(\", \")} FROM ${table};`,\n `DROP TABLE ${table};`,\n `ALTER TABLE ${temp} RENAME TO ${table};`,\n ...indexes.map(({ sql }: { sql: string }) => `${sql};`)\n ];\n }\n\n protected async references(field: Field, planning: boolean): Promise<string[]> {\n const { reference } = field;\n\n if (!reference)\n return [];\n\n const foreignKey = reference.column;\n const foreignTable = reference.parent!.table;\n\n if (reference.parent!.connection !== this)\n return [`Foreign key ${foreignTable}.${foreignKey} cannot be checked by another connection`];\n\n const db = await this.#statements();\n\n const foreignTableExists = await db.get(\n `SELECT name FROM sqlite_master WHERE type='table' AND name=?`, [foreignTable]);\n\n if (!foreignTableExists)\n return planning && this.using.has(reference.parent!) ? [] : [`Referenced table ${foreignTable} does not exist`];\n\n const foreignColumn = (await db.all(`PRAGMA table_info(${foreignTable})`))\n .find(col => col.name === foreignKey);\n\n if (!foreignColumn)\n return [`Referenced column ${foreignKey} does not exist in table ${foreignTable}`];\n\n return [];\n }\n\n protected generateSchema(types: Iterable<Query.Table>): string {\n return Array.from(types)\n .map(type => this.generateTableSchema(type))\n .join('\\n');\n }\n\n protected generateTableSchema(type: Query.Table): string {\n return [this.tableSchema(type), ...indexed(type).map(index)].join('\\n');\n }\n\n protected tableSchema(type: Query.Table, name = type.table, extra: string[] = []){\n const { parts } = type.fields.get(\"id\")!;\n const fields = [\n ...Array.from(type.fields.values()).filter(field => !field.parts).map(field => definition(field)),\n ...extra\n ];\n\n if (parts)\n fields.push(`PRIMARY KEY (${parts.map(part => `\\`${part.column}\\``).join(', ')})`);\n\n return `CREATE TABLE ${name} (${fields.join(', ')});`;\n }\n}\n\nfunction indexed(type: Query.Table){\n return Array.from(type.fields.values()).filter(field => field.index && !field.primary && !field.unique);\n}\n\nasync function intact(db: Engine.Statements){\n const broken: { table: string }[] = await db.all(\"PRAGMA foreign_key_check\");\n\n if (broken.length) {\n const tables = [...new Set(broken.map(row => row.table))].join(\", \");\n\n throw new Error(`Cannot rebuild: ${tables} has references to missing rows (${broken.length}).`);\n }\n}\n\nfunction indexName(field: Field){\n return typeof field.index == \"string\" ? field.index : `${field.parent!.table}_${field.column}`;\n}\n\nfunction index(field: Field){\n return `CREATE INDEX IF NOT EXISTS \\`${indexName(field)}\\` ON ${field.parent!.table} (\\`${field.column}\\`);`;\n}\n\nfunction restored(field: Field, info: TableInfo){\n const target = field.reference || field;\n const found = info.type.toUpperCase();\n const expected = affinity(field);\n\n if (target.type !== \"timestamp\" || found === expected || ![\"INTEGER\", \"TEXT\"].includes(found))\n return;\n\n const mode = connection(field)[\"timestamps\"];\n const keep = found == \"TEXT\" ? `{ timestamps: \"iso\" }` : `{ timestamps: \"ms\" } or { timestamps: \"seconds\" }`;\n\n return `Column ${field.column} in table ${field.parent!.table} holds timestamps as ${found}, but this connection stores them as ${STORED[mode]}. ` +\n `Pass ${keep} to SQLiteConnection.new to keep them, or migrate the column.`;\n}\n\nconst STORED: Record<Timestamps, string> = {\n ms: \"INTEGER epoch milliseconds\",\n seconds: \"INTEGER epoch seconds\",\n iso: \"ISO 8601 TEXT\"\n};\n\nfunction drifted(field: Field, info: TableInfo){\n const { column, nullable, primary } = field;\n const parent = field.parent!;\n const keyed = primary || parent.fields.get(\"id\")!.parts?.includes(field);\n const expected = affinity(field);\n\n if (info.type.toUpperCase() !== expected)\n return `Column ${column} in table ${parent.table} has type ${info.type}, expected ${expected}`;\n\n if (!keyed && info.notnull === (nullable ? 1 : 0))\n return `Column ${column} in table ${parent.table} has incorrect nullable value`;\n}\n\nconst NUMBER = (column: string) =>\n `typeof(${column}) = 'text' AND CASE WHEN json_valid(trim(${column})) THEN json_type(trim(${column})) ELSE '' END IN ('integer', 'real')`;\n\nconst FITS: Record<string, (column: string) => string> = {\n INTEGER: column =>\n `typeof(${column}) = 'integer' OR typeof(${column}) = 'real' AND ${column} = CAST(${column} AS INTEGER) ` +\n `OR ${NUMBER(column)} AND ${column} NOT GLOB '*[eE]*' AND CAST(${column} AS REAL) = CAST(${column} AS INTEGER)`,\n REAL: column =>\n `typeof(${column}) IN ('integer', 'real') OR ${NUMBER(column)}`\n};\n\nFITS.NUMERIC = FITS.REAL;\n\nfunction definition(field: Field, adding?: boolean){\n const {\n column,\n fallback,\n reference,\n increment,\n nullable,\n primary,\n unique,\n } = field;\n\n const { onDelete, onUpdate } = field as Field & { onDelete?: string, onUpdate?: string };\n let parts = `\\`${column}\\` ${affinity(field)}`;\n\n if (!nullable) parts += ' NOT NULL';\n if (primary) parts += ' PRIMARY KEY';\n if (increment) parts += ' AUTOINCREMENT';\n if (unique) parts += ' UNIQUE';\n\n if (fallback !== undefined && !(adding && clock(fallback)))\n parts += ' DEFAULT ' + literal(field, fallback);\n\n if (reference)\n parts += ` REFERENCES ${reference.parent!.table}(${reference.column})`;\n\n if (onDelete) parts += ` ON DELETE ${onDelete}`;\n if (onUpdate) parts += ` ON UPDATE ${onUpdate}`;\n\n return parts;\n}\n\nfunction moved(field: Field, existing: string[]){\n const { entity } = field as Field & { entity?: Query.Table };\n const old = entity && `${entity.table}_id`;\n const taken = Array.from(field.parent!.fields.values()).some(other => other.column === old);\n\n if (old && !taken && existing.includes(old))\n return `is missing but ${old} exists; add { column: \"${old}\" } to ${field.parent!.name}.${field.key} to keep it.`;\n}\n\nfunction clock(fallback: unknown){\n return fallback === \"NOW\" || fallback === now;\n}\n\nfunction unfit({ primary, unique, nullable, fallback }: Field){\n if (primary)\n return \"is a primary key and cannot be added to an existing table.\";\n\n if (unique)\n return \"is UNIQUE and cannot be added by SQLite.\";\n\n if (!nullable && fallback === undefined)\n return \"is NOT NULL without a default and cannot be added to existing rows.\";\n\n if (!nullable && clock(fallback))\n return \"defaults to the current time and cannot be added by SQLite.\";\n}\n\nconst AFFINITY: Record<string, string> = {\n integer: \"INTEGER\",\n smallint: \"INTEGER\",\n bigint: \"INTEGER\",\n boolean: \"INTEGER\",\n real: \"REAL\",\n double: \"REAL\",\n numeric: \"NUMERIC\",\n decimal: \"NUMERIC\",\n text: \"TEXT\",\n varchar: \"TEXT\",\n char: \"TEXT\",\n uuid: \"TEXT\",\n timestamp: \"TEXT\",\n date: \"TEXT\",\n time: \"TEXT\",\n json: \"TEXT\"\n};\n\nfunction storage(timestamps: Timestamps): ReadonlyMap<Function, Connection.Codec> {\n const scale = timestamps == \"seconds\" ? 1000 : 1;\n\n return new Map(Array.from(codecs, ([helper, codec]) => {\n const datatype = (field: Field) => AFFINITY[field.type];\n\n if (helper !== date || timestamps == \"iso\")\n return [helper, { ...codec, datatype }];\n\n return [helper, {\n ...codec,\n datatype: (field: Field) => field.type == \"timestamp\" ? \"INTEGER\" : datatype(field),\n encode: (field: Field, value: unknown) => field.type == \"timestamp\"\n ? Math.floor((value as Date).getTime() / scale)\n : codec.encode(field, value),\n decode: (field: Field, value: unknown) => field.type == \"timestamp\" && typeof value == \"number\"\n ? new Date(value * scale)\n : codec.decode(field, value)\n }];\n }));\n}\n\nconst STORAGE: Record<Timestamps, ReadonlyMap<Function, Connection.Codec>> = {\n ms: storage(\"ms\"),\n seconds: storage(\"seconds\"),\n iso: storage(\"iso\")\n};\n\nfunction connection(field: Field){\n return (field.parent as Type.Class).connection as SQLiteConnection;\n}\n\nfunction affinity(field: Field){\n return connection(field)._datatype(field);\n}\n\nfunction literal(field: Field, value: unknown){\n if (value === \"NOW\" || value === now)\n return `(${current(field, connection(field)[\"timestamps\"])})`;\n\n if (value === null)\n return \"NULL\";\n\n const encoded = connection(field)._encode(field, field.set(value));\n\n return typeof encoded == \"string\"\n ? `'${encoded.replace(/'/g, \"''\")}'`\n : String(encoded);\n}\n\nfunction pretty(sql: string){\n try {\n return format(sql, { language: 'sqlite', keywordCase: \"upper\" })\n .replace(/ - > > /g, \" ->> \")\n .replace(/`([a-zA-Z][a-zA-Z0-9_]*)`/g, \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S,MAAM;GACnF,SAAS,OAAc,UAAmB,MAAM,QAAQ,cACpD,KAAK,MAAO,MAAe,SAAS,GAAG,MAAM,GAC7C,MAAM,OAAO,OAAO,MAAM;GAC9B,SAAS,OAAc,UAAmB,MAAM,QAAQ,eAAe,OAAO,SAAS,WACnF,IAAI,KAAK,QAAQ,MAAM,GACvB,MAAM,OAAO,OAAO,MAAM;GAC/B,CAAC;GACF,CAAC;;AAGL,MAAM,UAAuE;CAC3E,IAAI,QAAQ,KAAK;CACjB,SAAS,QAAQ,UAAU;CAC3B,KAAK,QAAQ,MAAM;CACpB;AAED,SAAS,WAAW,OAAa;AAC/B,QAAQ,MAAM,OAAsB;;AAGtC,SAAS,SAAS,OAAa;AAC7B,QAAO,WAAW,MAAM,CAAC,UAAU,MAAM;;AAG3C,SAAS,QAAQ,OAAc,OAAe;AAC5C,KAAI,UAAU,SAAS,UAAU,IAC/B,QAAO,IAAIC,MAAQ,OAAO,WAAW,MAAM,CAAC,cAAc,CAAC;AAE7D,KAAI,UAAU,KACZ,QAAO;CAET,MAAM,UAAU,WAAW,MAAM,CAAC,QAAQ,OAAO,MAAM,IAAI,MAAM,CAAC;AAElE,QAAO,OAAO,WAAW,WACrB,IAAI,QAAQ,QAAQ,MAAM,KAAK,CAAC,KAChC,OAAO,QAAQ;;AAGrB,SAAS,OAAO,KAAY;AAC1B,KAAI;AACF,SAAO,OAAO,KAAK;GAAE,UAAU;GAAU,aAAa;GAAS,CAAC,CAC7D,QAAQ,YAAY,QAAQ,CAC5B,QAAQ,8BAA8B,KAAK;SAE1C;AACJ,SAAO"}
@@ -1,15 +1,18 @@
1
1
  import { Generator } from "../connection/Generator.js";
2
2
  import { Field } from "@expressive/orm";
3
- import { DataTable } from "@expressive/orm/driver";
3
+ import { Builder, DataTable } from "@expressive/orm/driver";
4
4
 
5
5
  //#region src/sqlite/SQLiteGenerator.d.ts
6
- declare function now(field?: Field): "date('now')" | "time('now')" | "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
6
+ type Timestamps = "ms" | "seconds" | "iso";
7
+ declare function now(field?: Field, timestamps?: Timestamps): "date('now')" | "time('now')" | "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')" | "CAST(strftime('%s', 'now') AS INTEGER)" | "CAST(ROUND((julianday('now') - 2440587.5) * 86400000) AS INTEGER)";
7
8
  declare class SQLiteGenerator extends Generator {
8
- protected now(field?: Field): "date('now')" | "time('now')" | "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
9
+ protected timestamps?: Timestamps | undefined;
10
+ constructor(query: Builder, timestamps?: Timestamps | undefined);
11
+ protected now(field?: Field): "date('now')" | "time('now')" | "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')" | "CAST(strftime('%s', 'now') AS INTEGER)" | "CAST(ROUND((julianday('now') - 2440587.5) * 86400000) AS INTEGER)";
9
12
  protected jsonTable(table: DataTable): string;
10
13
  protected update(): string[] | undefined;
11
14
  protected limit(): (string | 0 | undefined)[];
12
15
  }
13
16
  //#endregion
14
- export { SQLiteGenerator, now };
17
+ export { SQLiteGenerator, Timestamps, now };
15
18
  //# sourceMappingURL=SQLiteGenerator.d.ts.map
@@ -1,16 +1,24 @@
1
1
  import { Generator } from "../connection/Generator.js";
2
2
 
3
3
  //#region src/sqlite/SQLiteGenerator.ts
4
- function now(field) {
4
+ function now(field, timestamps = "ms") {
5
5
  switch (field?.type) {
6
6
  case "date": return "date('now')";
7
7
  case "time": return "time('now')";
8
- default: return "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
8
+ }
9
+ switch (timestamps) {
10
+ case "iso": return "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
11
+ case "seconds": return "CAST(strftime('%s', 'now') AS INTEGER)";
12
+ default: return "CAST(ROUND((julianday('now') - 2440587.5) * 86400000) AS INTEGER)";
9
13
  }
10
14
  }
11
15
  var SQLiteGenerator = class extends Generator {
16
+ constructor(query, timestamps) {
17
+ super(query);
18
+ this.timestamps = timestamps;
19
+ }
12
20
  now(field) {
13
- return now(field);
21
+ return now(field, this.timestamps);
14
22
  }
15
23
  jsonTable(table) {
16
24
  const param = this.param(table);
@@ -1 +1 @@
1
- {"version":3,"file":"SQLiteGenerator.js","names":[],"sources":["../../src/sqlite/SQLiteGenerator.ts"],"sourcesContent":["import { Field } from '@expressive/orm';\nimport { DataTable } from '@expressive/orm/driver';\nimport { Generator } from '../connection/Generator';\n\nexport function now(field?: Field){\n switch (field?.type) {\n case \"date\":\n return \"date('now')\";\n case \"time\":\n return \"time('now')\";\n default:\n return \"strftime('%Y-%m-%dT%H:%M:%fZ', 'now')\";\n }\n}\n\nexport class SQLiteGenerator extends Generator {\n protected now(field?: Field){\n return now(field);\n }\n\n protected jsonTable(table: DataTable): string {\n const param = this.param(table);\n const fields = Array.from(table.used, (field, i) => {\n return `value ->> ${i} ${this.escape(field.column)}`;\n });\n \n return `SELECT ${fields.join(', ')} FROM json_each(${param})`;\n }\n\n protected update(){\n const { updates, tables } = this.query;\n\n const [main] = updates.keys();\n\n if (!updates.size)\n return\n\n const output = [\n 'UPDATE',\n this.escape(main),\n this.set(updates)\n ]\n\n if (tables.size > 1) {\n const using = Array.from(tables.values())\n .filter(table => table !== main)\n .map(table => {\n if (table.joins.length === 0)\n throw new Error(`Table ${table.name} has no joins.`);\n\n const conditions = table.joins\n .map(x => this.filter(x.left, x.op, x.right))\n .join(' AND ')\n\n return { conditions, table };\n });\n\n output.push(\n 'FROM', using.map(x => x.table.name).join(', '),\n 'WHERE', using.map(x => x.conditions).join(' AND ')\n )\n }\n\n return output;\n }\n\n protected limit(){\n const { limit, offset } = this.query;\n const clauses = super.limit();\n\n return offset && !limit ? [\"LIMIT -1\", ...clauses] : clauses;\n }\n}\n"],"mappings":";;;AAIA,SAAgB,IAAI,OAAc;AAChC,SAAQ,OAAO,MAAf;EACE,KAAK,OACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,QACE,QAAO;;;AAIb,IAAa,kBAAb,cAAqC,UAAU;CAC7C,AAAU,IAA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DataTable } from '@expressive/orm/driver';\nimport { Builder } from '@expressive/orm/driver';\nimport { Generator } from '../connection/Generator';\n\nexport type Timestamps = \"ms\" | \"seconds\" | \"iso\";\n\nexport function now(field?: Field, timestamps: Timestamps = \"ms\"){\n switch (field?.type) {\n case \"date\":\n return \"date('now')\";\n case \"time\":\n return \"time('now')\";\n }\n\n switch (timestamps) {\n case \"iso\":\n return \"strftime('%Y-%m-%dT%H:%M:%fZ', 'now')\";\n case \"seconds\":\n return \"CAST(strftime('%s', 'now') AS INTEGER)\";\n default:\n return \"CAST(ROUND((julianday('now') - 2440587.5) * 86400000) AS INTEGER)\";\n }\n}\n\nexport class SQLiteGenerator extends Generator {\n constructor(query: Builder, protected timestamps?: Timestamps){\n super(query);\n }\n\n protected now(field?: Field){\n return now(field, this.timestamps);\n }\n\n protected jsonTable(table: DataTable): string {\n const param = this.param(table);\n const fields = Array.from(table.used, (field, i) => {\n return `value ->> ${i} ${this.escape(field.column)}`;\n });\n \n return `SELECT ${fields.join(', ')} FROM json_each(${param})`;\n }\n\n protected update(){\n const { updates, tables } = this.query;\n\n const [main] = updates.keys();\n\n if (!updates.size)\n return\n\n const output = [\n 'UPDATE',\n this.escape(main),\n this.set(updates)\n ]\n\n if (tables.size > 1) {\n const using = Array.from(tables.values())\n .filter(table => table !== main)\n .map(table => {\n if (table.joins.length === 0)\n throw new Error(`Table ${table.name} has no joins.`);\n\n const conditions = table.joins\n .map(x => this.filter(x.left, x.op, x.right))\n .join(' AND ')\n\n return { conditions, table };\n });\n\n output.push(\n 'FROM', using.map(x => x.table.name).join(', '),\n 'WHERE', using.map(x => x.conditions).join(' AND ')\n )\n }\n\n return output;\n }\n\n protected limit(){\n const { limit, offset } = this.query;\n const clauses = super.limit();\n\n return offset && !limit ? [\"LIMIT -1\", ...clauses] : clauses;\n }\n}\n"],"mappings":";;;AAOA,SAAgB,IAAI,OAAe,aAAyB,MAAK;AAC/D,SAAQ,OAAO,MAAf;EACE,KAAK,OACH,QAAO;EAC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,OAAO,WAAW,KAAK;EAC/B,MAAM,UAAU,MAAM,OAAO;AAE7B,SAAO,UAAU,CAAC,QAAQ,CAAC,YAAY,GAAG,QAAQ,GAAG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expressive/sql",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "Expressive ORM on SQL: entities, Query and an embedded SQLite store from one import.",
5
5
  "keywords": [
6
6
  "orm",
@@ -50,7 +50,8 @@
50
50
  },
51
51
  "files": [
52
52
  "dist",
53
- "skills"
53
+ "skills",
54
+ "CHANGELOG.md"
54
55
  ],
55
56
  "scripts": {
56
57
  "build": "tsdown",
@@ -59,7 +60,7 @@
59
60
  "test": "bun run typecheck && bun run coverage"
60
61
  },
61
62
  "dependencies": {
62
- "@expressive/orm": "^0.20.0",
63
+ "@expressive/orm": "^0.21.1",
63
64
  "sql-formatter": "^10.7.2"
64
65
  },
65
66
  "devDependencies": {
@@ -95,6 +95,7 @@ Awaiting a connection runs `sync`:
95
95
  - Missing tables are created, missing columns and indexes added, existing ones checked against the classes.
96
96
  - A new column reads `undefined` or its `fallback` on old rows. One that cannot fill existing rows - primary, `UNIQUE`, `NOT NULL` without a `fallback` or defaulting to now - is reported and nothing changes. A nullable column defaulting to now is added without the default; inserts fill it.
97
97
  - Type and nullability drift is reported. `sync(true, true)` rebuilds the table, refusing while a row would not fit or a value would not convert. A rebuild keeps columns not on the class, indexes and triggers, but not UNIQUE or REFERENCES on columns the class doesn't declare, and refuses while any row references a missing one.
98
+ - A timestamp column declared INTEGER under `"iso"`, or TEXT under `"ms"` or `"seconds"`, is reported with the `timestamps` option that keeps it. `sync(true, true)` does not convert it - converting would guess the unit.
98
99
  - `static schema` is reported - SQLite has none.
99
100
  - A relation column missing while `<table>_id` exists is reported, not added - set `{ column: "<table>_id" }` to keep the old one.
100
101
  - `sync(false)` only verifies. `plan(force?)` returns `{ steps, problems }` - each step with `action`, `reason` and `sql` - without doing it. A sync applies in one transaction.
@@ -119,7 +120,7 @@ Datatypes are orm's (`expressive-orm/SKILL.md#entities`); `sql.*` is shorthand f
119
120
  | `str` | TEXT |
120
121
  | `num` | INTEGER; `real`, `double` REAL; `numeric`, `decimal` NUMERIC |
121
122
  | `bool` | INTEGER, 1 or 0 |
122
- | `date` | TEXT - ISO 8601 UTC to the ms; `date` the local day `YYYY-MM-DD`; `time` UTC `HH:MM:SS` |
123
+ | `date` | INTEGER epoch ms by default - see `timestamps` below; `date` the local day `YYYY-MM-DD`; `time` UTC `HH:MM:SS` |
123
124
  | `json` | TEXT |
124
125
  | `one` | the related key's |
125
126
 
@@ -136,6 +137,7 @@ class Product extends Type {
136
137
  ```
137
138
 
138
139
  - `num()` is a 32-bit integer - a fraction or a value outside 32-bit range throws on write. `sql.bigint` for large integers, `sql.real` or `sql.numeric(p, s)` for fractions.
140
+ - A `timestamp`'s storage is the connection's: `SQLiteConnection.new(types, "app.db", { timestamps: "seconds" })`. `"ms"` (default) and `"seconds"` are INTEGER epoch values; `"iso"` is ISO 8601 UTC text, for reading in a DB browser or D1 console. Every connection to one file must agree. A database written by 0.6-0.11 holds ISO text - open it with `{ timestamps: "iso" }`.
139
141
  - Options a factory doesn't take go in an object - `date({ type: "timestamp", precision: 3 })`.
140
142
  - `sql.now` is the database's current time in the column's storage - as a `fallback`, in a statics write or comparison (`lessThan(sql.now)`), or in a `Query`. Statics read it from the app's clock.
141
143
  - The SQL floor checks values again before storing, so rows forwarded from a client meet the same rules.