@zukhruf/schema-drift 0.0.0-stage → 0.8.283
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/LICENSE +21 -0
- package/README.md +725 -2
- package/dist/drift.d.ts +18 -0
- package/dist/drift.d.ts.map +1 -0
- package/dist/drift.js +2 -0
- package/dist/drift.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/postgres/postgres-declaration.d.ts +41 -0
- package/dist/postgres/postgres-declaration.d.ts.map +1 -0
- package/dist/postgres/postgres-declaration.js +504 -0
- package/dist/postgres/postgres-declaration.js.map +1 -0
- package/dist/postgres/postgres-statement.d.ts +19 -0
- package/dist/postgres/postgres-statement.d.ts.map +1 -0
- package/dist/postgres/postgres-statement.js +253 -0
- package/dist/postgres/postgres-statement.js.map +1 -0
- package/dist/postgres.d.ts +2 -0
- package/dist/postgres.d.ts.map +1 -0
- package/dist/postgres.js +2 -0
- package/dist/postgres.js.map +1 -0
- package/dist/schema-drift-error.d.ts +11 -0
- package/dist/schema-drift-error.d.ts.map +1 -0
- package/dist/schema-drift-error.js +17 -0
- package/dist/schema-drift-error.js.map +1 -0
- package/dist/sqlite/sqlite-declaration.d.ts +14 -0
- package/dist/sqlite/sqlite-declaration.d.ts.map +1 -0
- package/dist/sqlite/sqlite-declaration.js +407 -0
- package/dist/sqlite/sqlite-declaration.js.map +1 -0
- package/dist/sqlite.d.ts +2 -0
- package/dist/sqlite.d.ts.map +1 -0
- package/dist/sqlite.js +2 -0
- package/dist/sqlite.js.map +1 -0
- package/package.json +64 -4
package/README.md
CHANGED
|
@@ -1,3 +1,726 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zukhruf/schema-drift
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> **Design accepted 2026-12-01.** The root entry point, `./sqlite` and `./postgres` are built. `./sqlserver` is the API on paper, which the maintainer approved, and is not built yet (backlog #2625).
|
|
4
|
+
|
|
5
|
+
A package keeps tables, indexes, views and other objects in a database. A later version of the package can declare them otherwise, for example with one more column. The database still stores the objects as the earlier version made them, and the new code fails on them, for example with `column "reloading" does not exist` (elt #2625). This package compares the objects of a database with their **declaration**, and makes the database store them as declared. No person keeps a version number. The industry calls this declarative schema management, and the difference that it finds schema drift (Atlas, Liquibase).
|
|
6
|
+
|
|
7
|
+
The package that keeps the tables exports their declaration. The host applies it when it chooses: at deploy, at start, or from its own tool. The package itself only checks, when it opens, and throws `SchemaDriftError` when an object is missing or stale ([ADR 0007](./docs/adr/0007-the-package-declares-its-objects-the-host-applies-them-and-the-package-only-checks-when-it-opens.md)).
|
|
8
|
+
|
|
9
|
+
The package has four entry points. `@zukhruf/schema-drift` has the error and the shared types. `@zukhruf/schema-drift/sqlite`, `@zukhruf/schema-drift/postgres` and `@zukhruf/schema-drift/sqlserver` each have the declaration of one engine ([ADR 0006](./docs/adr/0006-the-package-is-zukhruf-schema-drift-with-one-import-path-for-each-engine-and-sqlite-drift-moves-into-it.md)). `@zukhruf/sqlite-drift` moves into `./sqlite` with no change of behaviour, and goes away with no alias.
|
|
10
|
+
|
|
11
|
+
The words in these documents have one meaning each. See the glossary in [CONTEXT.md](./CONTEXT.md).
|
|
12
|
+
|
|
13
|
+
## Use it
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
npm install @zukhruf/schema-drift
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The package that keeps the tables exports their declaration:
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { PostgresDeclaration } from '@zukhruf/schema-drift/postgres';
|
|
23
|
+
|
|
24
|
+
export const warehouse = new PostgresDeclaration(
|
|
25
|
+
[
|
|
26
|
+
'CREATE SCHEMA _warehouse',
|
|
27
|
+
`CREATE TABLE _warehouse.extraction_coverage (
|
|
28
|
+
stream text PRIMARY KEY,
|
|
29
|
+
target_schema text NOT NULL,
|
|
30
|
+
reloading boolean NOT NULL DEFAULT false
|
|
31
|
+
)`,
|
|
32
|
+
'CREATE INDEX extraction_coverage_target ON _warehouse.extraction_coverage (target_schema)',
|
|
33
|
+
],
|
|
34
|
+
{ ledgerSchema: '_warehouse' },
|
|
35
|
+
);
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The host applies it, once, when it chooses:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { warehouse } from 'elt-postgresql';
|
|
42
|
+
|
|
43
|
+
await warehouse.apply(session, { rows: 'keep' }); // the host chooses keep or replace
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The package checks it when it opens, and runs no DDL:
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
await warehouse.check(session); // throws SchemaDriftError when an object is missing or stale
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`session` is a `PostgresSession` that the host writes over its own driver, as for [`@zukhruf/checkpoint`](../checkpoint/README.md#keep-checkpoints-in-postgres-or-sql-server) ([ADR 0015](./docs/adr/0015-the-postgres-and-sql-server-paths-take-a-driver-free-session-a-fourth-copy-of-the-session-ports.md)).
|
|
53
|
+
|
|
54
|
+
A warehouse that an older elt made with `CREATE TABLE IF NOT EXISTS` has the tables but no ledger rows. `check` names each of its tables as stale. `apply` with `rows: 'keep'` rebuilds each one, keeps the rows of the columns that both shapes have, and writes the ledger rows. After `apply`, `check` passes.
|
|
55
|
+
|
|
56
|
+
## Declare the objects of a package
|
|
57
|
+
|
|
58
|
+
- `new <Engine>Declaration(statements, options)` takes one CREATE statement for each declared object, in the order to make them. List a schema before its objects, and a table before the tables and views that refer to it.
|
|
59
|
+
- `rows` is `'replace'` or `'keep'`, an option of `apply`. It tells `apply` what to do with the rows of a stale table. The host gives it, because the host knows whether its rows can be made again; `drift` and `check` do not use it. It has no default, so no caller loses rows because it forgot an option.
|
|
60
|
+
- On Postgres and SQL Server, the constructor reads the kind and the qualified name of each statement from its head, and refuses a statement that it cannot read ([ADR 0011](./docs/adr/0011-the-constructor-reads-the-kind-and-the-qualified-name-of-each-statement-from-its-head-and-refuses-one-it-cannot-read.md)). Each name carries its schema: `_warehouse.extraction_coverage`, not `extraction_coverage`. An index takes the schema of its table.
|
|
61
|
+
- The constructor refuses `IF NOT EXISTS`, as [sqlite-drift ADR 0004](./docs/adr/0004-a-statement-owns-the-objects-its-create-makes.md) does: it hides a stale object behind its name.
|
|
62
|
+
- The constructor refuses a `CREATE SCHEMA` with `AUTHORIZATION` or with objects in it. The owner and the grants of a schema belong to the host.
|
|
63
|
+
- On Postgres and SQL Server, the constructor refuses two functions or two procedures of one qualified name. The package does not declare overloads.
|
|
64
|
+
- The SQLite constructor keeps the `devDatabase` option of sqlite-drift: it opens the empty database in memory where the statements run once. `rows` moved from the constructor of sqlite-drift to `apply(database, { rows })` ([ADR 0007](./docs/adr/0007-the-package-declares-its-objects-the-host-applies-them-and-the-package-only-checks-when-it-opens.md), [ADR 0008](./docs/adr/0008-the-sqlite-path-keeps-the-design-of-sqlite-drift-and-adds-check-and-a-report-of-each-object.md)).
|
|
65
|
+
|
|
66
|
+
## Find the drift
|
|
67
|
+
|
|
68
|
+
`drift(database)` on SQLite and `await drift(session)` on Postgres and SQL Server give a report: the drift of the whole declaration, and each object that does not fit.
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
const report = await warehouse.drift(session);
|
|
72
|
+
// { drift: 'stale',
|
|
73
|
+
// objects: [
|
|
74
|
+
// { name: '_warehouse.extraction_coverage', kind: 'table', drift: 'stale' },
|
|
75
|
+
// { name: '_warehouse.extraction_coverage_target', kind: 'index', drift: 'missing' } ] }
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
- `drift` is `missing` when the database stores none of the objects, `fits` when it stores each one as declared, and `stale` for all other cases.
|
|
79
|
+
- `objects` lists each declared object that is missing or stale, in the order of the declaration. It is empty when the drift is `fits`.
|
|
80
|
+
- `drift` only reads. It takes no lock and needs no write permission.
|
|
81
|
+
|
|
82
|
+
**SQLite** compares the text that SQLite stores in `sqlite_schema` with the text of the declaration, made once in the dev database ([sqlite-drift ADR 0001](./docs/adr/0001-compare-the-text-that-sqlite-stores.md)). A hand edit of an object is drift.
|
|
83
|
+
|
|
84
|
+
**Postgres and SQL Server** compare a checksum of each declared statement with the ledger row of its object, in one query ([ADR 0009](./docs/adr/0009-postgres-and-sql-server-compare-a-checksum-of-each-declared-statement-with-a-ledger-row-and-need-no-dev-database.md)):
|
|
85
|
+
|
|
86
|
+
| Ledger row | Object in the catalog | Drift |
|
|
87
|
+
| --------------------- | --------------------- | --------- |
|
|
88
|
+
| Has the same checksum | Exists | `fits` |
|
|
89
|
+
| Has another checksum | Exists | `stale` |
|
|
90
|
+
| None | Exists | `stale` |
|
|
91
|
+
| Any, or none | Does not exist | `missing` |
|
|
92
|
+
|
|
93
|
+
- The checksum is the SHA-256 of the tokens of the statement. A comment, and a change of the spaces and line breaks between two tokens, is not drift. A change of a string, of a quoted name, of a dollar-quoted body (Postgres), of a `[bracketed]` name or of an `N'…'` string (SQL Server) is drift. A change of case of a word is drift too ([ADR 0010](./docs/adr/0010-a-checksum-covers-the-tokens-of-a-statement-and-comments-and-the-spaces-between-tokens-are-not-drift.md)).
|
|
94
|
+
- A declared schema fits when it exists, with or without a ledger row: its statement holds only its name.
|
|
95
|
+
- An object with no ledger row is stale, also when its shape is the declared one. The package cannot know who made it, or from which text. Thus `apply` repairs a database that older code made with `IF NOT EXISTS`.
|
|
96
|
+
- A change that a person makes by hand after `apply` is not seen. The ledger row still has the checksum of the declared statement. Liquibase (`MD5SUM`) and Flyway (`validate`) have the same limit. A dropped object is seen: it is missing.
|
|
97
|
+
|
|
98
|
+
## Check a database when the package opens
|
|
99
|
+
|
|
100
|
+
`check(database)` on SQLite and `await check(session)` on Postgres and SQL Server run `drift`. When the drift is not `fits`, they throw `SchemaDriftError`, which names each missing or stale object. The next step is to apply the declaration.
|
|
101
|
+
|
|
102
|
+
```
|
|
103
|
+
SchemaDriftError: The database does not store the declaration as declared:
|
|
104
|
+
_warehouse.extraction_coverage (table) is stale.
|
|
105
|
+
_warehouse.extraction_coverage_target (index) is missing.
|
|
106
|
+
Apply the declaration.
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
A package calls `check` in its constructor or its `open`. It does not call `apply` ([ADR 0007](./docs/adr/0007-the-package-declares-its-objects-the-host-applies-them-and-the-package-only-checks-when-it-opens.md)).
|
|
110
|
+
|
|
111
|
+
## Apply a declaration
|
|
112
|
+
|
|
113
|
+
`apply` makes the database store each object of the declaration as declared. It does nothing when the drift is `fits`. It does not drop an object that the declaration does not name.
|
|
114
|
+
|
|
115
|
+
**SQLite** keeps the `apply` of sqlite-drift: with `rows: 'replace'`, one stale object replaces the whole declaration; with `rows: 'keep'`, each stale table is rebuilt from its declared text ([sqlite-drift ADR 0002](./docs/adr/0002-a-stale-object-replaces-the-whole-declaration.md), [ADR 0003](./docs/adr/0003-keep-rows-rebuilds-a-table-and-keeps-its-references.md)).
|
|
116
|
+
|
|
117
|
+
**Postgres and SQL Server** work only on the stale and the missing objects, in the order of the declaration ([ADR 0012](./docs/adr/0012-keep-rows-rebuilds-a-stale-table-and-replace-drops-and-makes-each-stale-object.md)):
|
|
118
|
+
|
|
119
|
+
1. `apply` opens one transaction on the session. On SQL Server it runs `SET XACT_ABORT ON` and `BEGIN TRANSACTION`.
|
|
120
|
+
2. It takes the lock of the package, which the transaction owns, and reads the ledger again inside the lock ([ADR 0014](./docs/adr/0014-apply-takes-a-lock-that-its-transaction-owns-and-reads-the-ledger-again-inside-it.md)).
|
|
121
|
+
3. It makes the ledger table when it is missing, after the declared schemas.
|
|
122
|
+
4. It makes each missing object from its statement.
|
|
123
|
+
5. It replaces each stale view, function, procedure and index: it drops the object and makes it from its statement. These objects keep no rows.
|
|
124
|
+
6. It replaces or rebuilds each stale table, as `rows` says (see below), and each stale sequence.
|
|
125
|
+
7. It writes the ledger row of each object that it made, with the checksum of its statement. The rows commit with the objects, or neither does.
|
|
126
|
+
|
|
127
|
+
A stale schema does not occur: a declared schema has only its name, so it is missing or it fits. `apply` never drops a schema, because a drop takes each object in it.
|
|
128
|
+
|
|
129
|
+
### Replace the rows
|
|
130
|
+
|
|
131
|
+
With `rows: 'replace'`, `apply` drops a stale table and makes it from its statement. Its rows are gone.
|
|
132
|
+
|
|
133
|
+
- A declared table that refers to the replaced table is replaced too, so no kept row refers to a row that is gone.
|
|
134
|
+
- A view that depends on the table is dropped first, and made again after it: a declared view from its statement, any other view from its definition that `apply` read before the drop.
|
|
135
|
+
- A declared index on the table is made from its statement. An index and a trigger that the declaration does not name are made again from their catalog definitions, as with `rows: 'keep'`.
|
|
136
|
+
- A foreign key of a table that the declaration does not name is made again after the table. When that table has a row that refers to a row that is gone, `apply` fails with the error of the database, and the transaction rolls back.
|
|
137
|
+
- A stale sequence is dropped and made from its statement. It starts again.
|
|
138
|
+
|
|
139
|
+
### Keep the rows
|
|
140
|
+
|
|
141
|
+
With `rows: 'keep'`, `apply` rebuilds each stale table and keeps its rows. This is the table rebuild of DacFx ([its publish script](https://learn.microsoft.com/en-us/sql/tools/sqlpackage/sqlpackage-publish)), with the old table renamed away first, as SQLite rebuilds a table ([sqlite-drift ADR 0003](./docs/adr/0003-keep-rows-rebuilds-a-table-and-keeps-its-references.md)):
|
|
142
|
+
|
|
143
|
+
1. It reads, from the catalog of the target, the views that depend on the table, the foreign keys that refer to it, and the indexes and triggers on it that the declaration does not name.
|
|
144
|
+
2. It drops those views and foreign keys.
|
|
145
|
+
3. It renames the stored table to a temporary name, and renames its constraints, its indexes and its owned sequences away too. The declared names are then free.
|
|
146
|
+
4. It makes the table from its statement, under its declared name. Each name that the database gives (`<table>_pkey`, `<table>_<column>_seq`) is the name that a new database gives.
|
|
147
|
+
5. It copies the columns that both tables have, read from the catalog of the target, by name, in the order of the primary key. It writes the stored values of an identity column: `OVERRIDING SYSTEM VALUE` on Postgres, `SET IDENTITY_INSERT … ON` on SQL Server. It does not copy a column that the database computes (generated, computed, `rowversion`).
|
|
148
|
+
6. On Postgres, it sets the sequence of each identity or `serial` column to the largest copied value (`setval`). SQL Server moves the identity on its own when it inserts a larger value.
|
|
149
|
+
7. It drops the old table, and makes again the indexes and triggers of step 1 from their catalog definitions.
|
|
150
|
+
8. It makes again the foreign keys and the views of step 1: a declared view from its statement, any other view from its definition. On SQL Server, it runs `sp_refreshview` on each view that is not schema-bound and that refers to the table.
|
|
151
|
+
|
|
152
|
+
A stale sequence keeps its last value: `apply` reads it, makes the sequence from its statement, and sets the value again.
|
|
153
|
+
|
|
154
|
+
- A column that only the declaration has gets its default.
|
|
155
|
+
- A column that only the stored table has is gone, with its values. The declaration states this intent ([ADR 0013](./docs/adr/0013-a-column-that-the-declaration-drops-loses-its-data-as-the-declaration-states.md)).
|
|
156
|
+
- `apply` does not find a renamed column. A new name reads as one column dropped and one column added. To keep the values, copy them with your own SQL before `apply`.
|
|
157
|
+
- When a stored row does not fit the declared table (`NOT NULL`, `CHECK`, a foreign key, a type), `apply` fails with the error of the database, and the transaction rolls back.
|
|
158
|
+
- The grants, the comments and the row-level security policies of a rebuilt table or a made-again view are gone. The host grants them again after `apply`.
|
|
159
|
+
|
|
160
|
+
## Work on Postgres
|
|
161
|
+
|
|
162
|
+
`@zukhruf/schema-drift/postgres` imports no driver. The host gives a `PostgresSession` over its own driver. The example writes one over node-postgres, makes the table as an older elt did, and repairs it.
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
import pg from 'pg';
|
|
166
|
+
|
|
167
|
+
import {
|
|
168
|
+
PostgresDeclaration,
|
|
169
|
+
type PostgresSession,
|
|
170
|
+
} from '@zukhruf/schema-drift/postgres';
|
|
171
|
+
|
|
172
|
+
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
|
|
173
|
+
// The session over node-postgres: queries on the pool, and a transaction on
|
|
174
|
+
// one client of it.
|
|
175
|
+
const session: PostgresSession = {
|
|
176
|
+
query: async (sql, parameters) =>
|
|
177
|
+
(await pool.query(sql, [...parameters])).rows,
|
|
178
|
+
transaction: async (work) => {
|
|
179
|
+
const client = await pool.connect();
|
|
180
|
+
try {
|
|
181
|
+
await client.query('BEGIN');
|
|
182
|
+
const inner: PostgresSession = {
|
|
183
|
+
query: async (sql, parameters) =>
|
|
184
|
+
(await client.query(sql, [...parameters])).rows,
|
|
185
|
+
transaction: async (nested) => nested(inner),
|
|
186
|
+
};
|
|
187
|
+
await work(inner);
|
|
188
|
+
await client.query('COMMIT');
|
|
189
|
+
} catch (error) {
|
|
190
|
+
await client.query('ROLLBACK');
|
|
191
|
+
throw error;
|
|
192
|
+
} finally {
|
|
193
|
+
client.release();
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
// An older elt made the table with IF NOT EXISTS, without reloading.
|
|
198
|
+
await pool.query(`CREATE SCHEMA _warehouse;
|
|
199
|
+
CREATE TABLE IF NOT EXISTS _warehouse.extraction_coverage (stream text PRIMARY KEY, target_schema text NOT NULL);
|
|
200
|
+
INSERT INTO _warehouse.extraction_coverage VALUES ('orders', 'raw')`);
|
|
201
|
+
|
|
202
|
+
const warehouse = new PostgresDeclaration(
|
|
203
|
+
[
|
|
204
|
+
'CREATE SCHEMA _warehouse',
|
|
205
|
+
`CREATE TABLE _warehouse.extraction_coverage (
|
|
206
|
+
stream text PRIMARY KEY,
|
|
207
|
+
target_schema text NOT NULL,
|
|
208
|
+
reloading boolean NOT NULL DEFAULT false
|
|
209
|
+
)`,
|
|
210
|
+
'CREATE INDEX extraction_coverage_target ON _warehouse.extraction_coverage (target_schema)',
|
|
211
|
+
],
|
|
212
|
+
{ ledgerSchema: '_warehouse' },
|
|
213
|
+
);
|
|
214
|
+
console.log(await warehouse.drift(session));
|
|
215
|
+
try {
|
|
216
|
+
await warehouse.check(session);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
console.log(String(error));
|
|
219
|
+
}
|
|
220
|
+
await warehouse.apply(session, { rows: 'keep' });
|
|
221
|
+
console.log(await warehouse.drift(session));
|
|
222
|
+
console.log(
|
|
223
|
+
(await pool.query('SELECT * FROM _warehouse.extraction_coverage')).rows,
|
|
224
|
+
);
|
|
225
|
+
await pool.end();
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
Output:
|
|
229
|
+
|
|
230
|
+
```
|
|
231
|
+
{
|
|
232
|
+
drift: 'stale',
|
|
233
|
+
objects: [
|
|
234
|
+
{
|
|
235
|
+
name: '_warehouse.extraction_coverage',
|
|
236
|
+
kind: 'table',
|
|
237
|
+
drift: 'stale'
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
name: '_warehouse.extraction_coverage_target',
|
|
241
|
+
kind: 'index',
|
|
242
|
+
drift: 'missing'
|
|
243
|
+
}
|
|
244
|
+
]
|
|
245
|
+
}
|
|
246
|
+
SchemaDriftError: The database does not store the declaration as declared:
|
|
247
|
+
_warehouse.extraction_coverage (table) is stale.
|
|
248
|
+
_warehouse.extraction_coverage_target (index) is missing.
|
|
249
|
+
Apply the declaration.
|
|
250
|
+
{ drift: 'fits', objects: [] }
|
|
251
|
+
[ { stream: 'orders', target_schema: 'raw', reloading: false } ]
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
## Work on SQLite
|
|
255
|
+
|
|
256
|
+
`@zukhruf/schema-drift/sqlite` is `@zukhruf/sqlite-drift`, moved in with its behaviour. It uses only `node:sqlite`.
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
import { mkdtempDisposable } from 'node:fs/promises';
|
|
260
|
+
import { tmpdir } from 'node:os';
|
|
261
|
+
import { join } from 'node:path';
|
|
262
|
+
|
|
263
|
+
import { SqliteDeclaration } from '@zukhruf/schema-drift/sqlite';
|
|
264
|
+
import { open } from '@zukhruf/sqlite-open';
|
|
265
|
+
|
|
266
|
+
await using scratch = await mkdtempDisposable(join(tmpdir(), 'drift-'));
|
|
267
|
+
using database = open(join(scratch.path, 'app.sqlite'));
|
|
268
|
+
// An earlier version made the table without failed_at.
|
|
269
|
+
database.exec(`CREATE TABLE failures (directory TEXT PRIMARY KEY, error TEXT NOT NULL);
|
|
270
|
+
INSERT INTO failures VALUES ('/data/notes', 'denied')`);
|
|
271
|
+
|
|
272
|
+
const failures = new SqliteDeclaration([
|
|
273
|
+
'CREATE TABLE failures (directory TEXT PRIMARY KEY, error TEXT NOT NULL, failed_at TEXT NOT NULL)',
|
|
274
|
+
'CREATE INDEX failures_at ON failures (failed_at)',
|
|
275
|
+
]);
|
|
276
|
+
console.log(failures.drift(database));
|
|
277
|
+
try {
|
|
278
|
+
failures.check(database);
|
|
279
|
+
} catch (error) {
|
|
280
|
+
console.log(String(error));
|
|
281
|
+
}
|
|
282
|
+
failures.apply(database, { rows: 'replace' });
|
|
283
|
+
console.log(failures.drift(database));
|
|
284
|
+
console.log(database.prepare('SELECT count(*) AS rows FROM failures').get());
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
Output:
|
|
288
|
+
|
|
289
|
+
```
|
|
290
|
+
{
|
|
291
|
+
drift: 'stale',
|
|
292
|
+
objects: [
|
|
293
|
+
{ name: 'failures', kind: 'table', drift: 'stale' },
|
|
294
|
+
{ name: 'failures_at', kind: 'index', drift: 'missing' }
|
|
295
|
+
]
|
|
296
|
+
}
|
|
297
|
+
SchemaDriftError: The database does not store the declaration as declared:
|
|
298
|
+
failures (table) is stale.
|
|
299
|
+
failures_at (index) is missing.
|
|
300
|
+
Apply the declaration.
|
|
301
|
+
{ drift: 'fits', objects: [] }
|
|
302
|
+
[Object: null prototype] { rows: 0 }
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
### A SQLite declaration compares the text that SQLite stores
|
|
306
|
+
|
|
307
|
+
- `new SqliteDeclaration(statements, { devDatabase })` makes the objects once in the dev database, and keeps the text that SQLite stores for each one. [ADR 0001](./docs/adr/0001-compare-the-text-that-sqlite-stores.md) tells why.
|
|
308
|
+
- The dev database is an empty database in memory. `devDatabase` is an optional function that opens it. When there is no `devDatabase`, the package opens `open(':memory:')` of `@zukhruf/sqlite-open`. See [Extensions and functions](#extensions-and-functions).
|
|
309
|
+
- A statement can also add owned objects to `sqlite_schema`: the shadow tables of a virtual table, `sqlite_sequence` for `AUTOINCREMENT`, and the index of a `UNIQUE` column. SQLite makes and drops an owned object with its declared object. `drift`, `check` and `apply` examine only the declared objects. [ADR 0004](./docs/adr/0004-a-statement-owns-the-objects-its-create-makes.md) tells why.
|
|
310
|
+
- The kind of an object is the `type` of `sqlite_schema` (`table`, `index`, `view`, `trigger`), and `virtual table` for a `CREATE VIRTUAL TABLE`.
|
|
311
|
+
- `drift` and `check` only read, so they also work on a database opened read-only.
|
|
312
|
+
- Each change to a token after the name of the object is drift: a column, a type, a CHECK, STRICT, the query of a view, a string, and a quoted name, also a space in it. SQLite stores that text as the statement has it, and `drift` compares its tokens, by the rules of the tokenizer of SQLite. A comment, and a change of the spaces and line breaks between two tokens, is not drift. Thus a comment that changes, or that wraps to more lines, does not rebuild a table. SQLite writes the text before the name again: it stores `create table a (x INT)` as `CREATE TABLE a (x INT)`. Thus a change of case before the name is not drift. A change of quotes is drift: `a`, `"a"` and `[a]` are different tokens. [ADR 0001](./docs/adr/0001-compare-the-text-that-sqlite-stores.md) tells why.
|
|
313
|
+
- A change of meaning with no change of text is not drift. When the meaning of a column changes, change its name too.
|
|
314
|
+
- SQLite takes names that are different only in ASCII case as one name.
|
|
315
|
+
|
|
316
|
+
### Apply on SQLite
|
|
317
|
+
|
|
318
|
+
- `apply(database, { rows })` does nothing when the drift is `fits`.
|
|
319
|
+
- When no stored object is stale, `apply` makes each missing object, and the other objects keep their rows.
|
|
320
|
+
- With `rows: 'replace'`, when one stored object is stale, `apply` replaces every object of the declaration, and their rows are gone. [ADR 0002](./docs/adr/0002-a-stale-object-replaces-the-whole-declaration.md) tells why.
|
|
321
|
+
- With `rows: 'keep'`, `apply` rebuilds each stale table and keeps its rows. See [Keep the rows on SQLite](#keep-the-rows-on-sqlite).
|
|
322
|
+
- `apply` does not drop an object that the declaration does not name.
|
|
323
|
+
- A trigger can read a table that is not its own table. SQLite does not examine the body of a trigger at `CREATE`, so a change to one table can break a trigger on another table. Before the change, `apply` records which tables with triggers compile a `DELETE`, an `INSERT` and an `UPDATE`. It finds these tables in `sqlite_schema`, also the tables that the declaration does not name. After the change, it compiles these statements again, and runs no row. When a table compiled them before and does not compile them now, `apply` fails with the error of SQLite. This check is the same with `rows: 'replace'` and `rows: 'keep'`. A trigger that did not compile before does not make `apply` fail.
|
|
324
|
+
- In a transaction of the caller, `apply` works in a savepoint, and a rollback of the caller removes its changes. With no transaction, `apply` writes in its own `BEGIN IMMEDIATE` transaction. [`@zukhruf/sqlite-transaction`](../sqlite/transaction) does this work, so when SQLite ends the transaction itself, `apply` throws the original error.
|
|
325
|
+
|
|
326
|
+
### Keep the rows on SQLite
|
|
327
|
+
|
|
328
|
+
With `rows: 'keep'`, `apply` keeps the rows of each stale table. It replaces a stale index, trigger or view, because these have no rows. It rebuilds each stale table, in the order of the declaration:
|
|
329
|
+
|
|
330
|
+
1. It renames the stored table to a temporary name, with `PRAGMA legacy_alter_table` on. Thus the references of other tables, views and triggers stay on the name of the table.
|
|
331
|
+
2. It makes the table from its declared text, so SQLite stores the declared text.
|
|
332
|
+
3. It copies the columns that both tables have, by name. SQLite takes names that are different only in ASCII case as one name. When both tables have a rowid, it also copies the rowid of each row. A copied `INTEGER PRIMARY KEY` column keeps its own values. When the declared table has `AUTOINCREMENT`, it keeps the largest id that the old table gave, so the id of a deleted row is not given again.
|
|
333
|
+
4. It drops the old table, and makes again the indexes and triggers on the table that the declaration does not name.
|
|
334
|
+
5. It runs `PRAGMA foreign_key_check`. When a kept row breaks a foreign key, `apply` fails.
|
|
335
|
+
6. After it makes the missing objects, it compiles a `DELETE`, an `INSERT` and an `UPDATE` of each rebuilt table, and runs no row. SQLite does not examine the body of a trigger at `CREATE`. It examines the body when it compiles a statement that fires the trigger. When a trigger on the table names a dropped column, `apply` fails with the error of SQLite. The check of the triggers on other tables comes after this step. See [Apply on SQLite](#apply-on-sqlite).
|
|
336
|
+
7. It compiles each view. Before the rebuilds, it records which views compile. When a view compiled before and does not compile now, `apply` fails. A view that did not compile before does not make `apply` fail.
|
|
337
|
+
|
|
338
|
+
[ADR 0003](./docs/adr/0003-keep-rows-rebuilds-a-table-and-keeps-its-references.md) tells why.
|
|
339
|
+
|
|
340
|
+
```ts
|
|
341
|
+
import { mkdtempDisposable } from 'node:fs/promises';
|
|
342
|
+
import { tmpdir } from 'node:os';
|
|
343
|
+
import { join } from 'node:path';
|
|
344
|
+
|
|
345
|
+
import { SqliteDeclaration } from '@zukhruf/schema-drift/sqlite';
|
|
346
|
+
import { open } from '@zukhruf/sqlite-open';
|
|
347
|
+
|
|
348
|
+
await using scratch = await mkdtempDisposable(join(tmpdir(), 'drift-'));
|
|
349
|
+
using database = open(join(scratch.path, 'app.sqlite'));
|
|
350
|
+
// An earlier version made runs without status. Cases refer to runs.
|
|
351
|
+
database.exec(`CREATE TABLE runs (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
|
|
352
|
+
CREATE TABLE cases (run INTEGER NOT NULL REFERENCES runs (id) ON DELETE CASCADE);
|
|
353
|
+
INSERT INTO runs VALUES (1, 'nightly');
|
|
354
|
+
INSERT INTO cases VALUES (1)`);
|
|
355
|
+
|
|
356
|
+
const runs = new SqliteDeclaration([
|
|
357
|
+
"CREATE TABLE runs (id INTEGER PRIMARY KEY, name TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'done')",
|
|
358
|
+
]);
|
|
359
|
+
console.log(runs.drift(database).drift);
|
|
360
|
+
runs.apply(database, { rows: 'keep' });
|
|
361
|
+
console.log(runs.drift(database).drift);
|
|
362
|
+
console.log(database.prepare('SELECT * FROM runs').all());
|
|
363
|
+
console.log(database.prepare('SELECT count(*) AS cases FROM cases').get());
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
Output:
|
|
367
|
+
|
|
368
|
+
```
|
|
369
|
+
stale
|
|
370
|
+
fits
|
|
371
|
+
[ [Object: null prototype] { id: 1, name: 'nightly', status: 'done' } ]
|
|
372
|
+
[Object: null prototype] { cases: 1 }
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
- A column that only the declaration has gets its default.
|
|
376
|
+
- A column that only the stored table has is discarded, with its values.
|
|
377
|
+
- `apply` does not find a renamed column. A new name reads as one column dropped and one column added, so the values of the old column are discarded. To keep them, copy them yourself before `apply`.
|
|
378
|
+
- `apply` does not fill values and does not remove rows. When a stored row does not fit the declaration (NOT NULL, CHECK, a foreign key, STRICT), `apply` fails with the error of SQLite, and the table and its rows stay as they were. To keep such rows, change them with your own SQL before `apply`.
|
|
379
|
+
- When foreign keys are on and a table refers to a stale table (also the stale table to itself), `apply` must turn foreign keys off. SQLite ignores `PRAGMA foreign_keys` in a transaction. Thus `apply` turns foreign keys off before its own transaction, and on again after it. In a transaction of the caller, `apply` fails before it changes the database. Call `apply` outside a transaction, or turn foreign keys off before it.
|
|
380
|
+
- When no table refers to the stale table, `apply` also works in a transaction of the caller, with foreign keys on.
|
|
381
|
+
- After a rebuild, `PRAGMA legacy_alter_table` has its old value again, also when `apply` fails.
|
|
382
|
+
- `apply` does not rebuild a virtual table. A module keeps the data of a virtual table in its own way, and a copy of the rows can break it. For example, an external-content FTS5 index can then find the wrong rows. When a virtual table is stale, `apply` fails before it changes the database. Give the virtual table its own declaration, apply that one with `rows: 'replace'`, and fill it again after `apply`.
|
|
383
|
+
|
|
384
|
+
### Extensions and functions
|
|
385
|
+
|
|
386
|
+
SQLite keeps virtual-table modules, functions of the application and collations on the connection, not in the database file. Thus a statement that uses one runs only in a connection that has it. The default dev database has only what SQLite has by default. A statement that uses more fails in `new SqliteDeclaration`, for example with `no such module: vec0`. Give `devDatabase`, and open the dev database as you open the target database: load the same extensions, and register the same functions. The example loads the `vec0` module of the sqlite-vec extension. [ADR 0005](./docs/adr/0005-the-caller-can-give-the-dev-database.md) tells why.
|
|
387
|
+
|
|
388
|
+
```ts
|
|
389
|
+
import { mkdtempDisposable } from 'node:fs/promises';
|
|
390
|
+
import { tmpdir } from 'node:os';
|
|
391
|
+
import { join } from 'node:path';
|
|
392
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
393
|
+
|
|
394
|
+
import * as sqliteVec from 'sqlite-vec';
|
|
395
|
+
|
|
396
|
+
import { SqliteDeclaration } from '@zukhruf/schema-drift/sqlite';
|
|
397
|
+
import { open } from '@zukhruf/sqlite-open';
|
|
398
|
+
|
|
399
|
+
function openWithVectors(path: string): DatabaseSync {
|
|
400
|
+
const database = open(path, { allowExtension: true });
|
|
401
|
+
database.loadExtension(sqliteVec.getLoadablePath());
|
|
402
|
+
return database;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
await using scratch = await mkdtempDisposable(join(tmpdir(), 'drift-'));
|
|
406
|
+
using database = openWithVectors(join(scratch.path, 'app.sqlite'));
|
|
407
|
+
|
|
408
|
+
const vectors = new SqliteDeclaration(
|
|
409
|
+
['CREATE VIRTUAL TABLE vectors USING vec0(embedding float[4])'],
|
|
410
|
+
{ devDatabase: () => openWithVectors(':memory:') },
|
|
411
|
+
);
|
|
412
|
+
console.log(vectors.drift(database).drift);
|
|
413
|
+
vectors.apply(database, { rows: 'replace' });
|
|
414
|
+
console.log(vectors.drift(database).drift);
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
Output:
|
|
418
|
+
|
|
419
|
+
```
|
|
420
|
+
missing
|
|
421
|
+
fits
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
- The dev database must be empty when the declaration starts. When it has an object, `new SqliteDeclaration` fails.
|
|
425
|
+
- `new SqliteDeclaration` closes the dev database, also when it fails. Do not use the connection after you give it.
|
|
426
|
+
- The target database must load the same modules. When it does not, `apply` fails with the error of SQLite, for example `no such module: vec0`. `drift` and `check` read only `sqlite_schema`, so they still give the drift.
|
|
427
|
+
|
|
428
|
+
### Write a SQLite declaration
|
|
429
|
+
|
|
430
|
+
- A declaration must stand alone in the dev database. Do not declare a trigger or an index on a table that the declaration does not name. When a statement uses a function, a module or a collation, the dev database must have it too.
|
|
431
|
+
- With `rows: 'replace'`, give each table its own declaration when it must keep its rows while another table changes.
|
|
432
|
+
|
|
433
|
+
## What each call does in the database
|
|
434
|
+
|
|
435
|
+
| Call | What happens underneath |
|
|
436
|
+
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
437
|
+
| `new SqliteDeclaration` | Runs each statement once in the dev database, and keeps the text that SQLite stores for each declared object. |
|
|
438
|
+
| `new PostgresDeclaration`, `new SqlServerDeclaration` | Reads the kind and the qualified name of each statement from its head, and computes its checksum. Opens no connection. |
|
|
439
|
+
| SQLite `drift`, `check` | Reads `sqlite_schema` of the target. |
|
|
440
|
+
| Postgres `drift`, `check` | One `SELECT` that joins the declared names and checksums (as parameters) to the catalog (`pg_class`, `pg_proc`, `pg_namespace`) and to the ledger. When the ledger table does not exist (`42P01`), one `SELECT` of the catalog. |
|
|
441
|
+
| SQL Server `drift`, `check` | One `SELECT` that joins the declared names and checksums to `sys.objects`, `sys.indexes`, `sys.schemas`, `sys.sequences` and the ledger. When the ledger table does not exist (error 208), one `SELECT` of the catalog. |
|
|
442
|
+
| SQLite `apply` | A savepoint in the caller's transaction, or its own `BEGIN IMMEDIATE`. The steps of sqlite-drift. |
|
|
443
|
+
| Postgres `apply` | `session.transaction`: `pg_advisory_xact_lock(<constant of the package>)`, the ledger read again, then `CREATE`, `DROP`, `ALTER … RENAME`, `INSERT … OVERRIDING SYSTEM VALUE SELECT`, `setval` and the ledger `INSERT … ON CONFLICT`. |
|
|
444
|
+
| SQL Server `apply` | `session.transaction` with `SET XACT_ABORT ON`: `sp_getapplock N'@zukhruf/schema-drift', 'Exclusive', @LockOwner = 'Transaction'`, the ledger read again, then `CREATE`, `DROP`, `sp_rename`, `SET IDENTITY_INSERT`, `sp_refreshview` and the ledger `MERGE`. |
|
|
445
|
+
|
|
446
|
+
## The ledger
|
|
447
|
+
|
|
448
|
+
On Postgres and SQL Server, `apply` keeps one row for each declared object that it made, in the table `zukhruf_schema_drift` ([ADR 0009](./docs/adr/0009-postgres-and-sql-server-compare-a-checksum-of-each-declared-statement-with-a-ledger-row-and-need-no-dev-database.md)).
|
|
449
|
+
|
|
450
|
+
| Column | Postgres | SQL Server | Holds |
|
|
451
|
+
| ------------ | ------------- | --------------- | ---------------------------------------------- |
|
|
452
|
+
| `name` | `text` | `nvarchar(400)` | The qualified name of the object. |
|
|
453
|
+
| `kind` | `text` | `nvarchar(20)` | `table`, `index`, `view`, and the other kinds. |
|
|
454
|
+
| `checksum` | `text` | `char(64)` | The SHA-256 of the tokens, in hex. |
|
|
455
|
+
| `applied_at` | `timestamptz` | `datetime2` | When `apply` wrote the row. |
|
|
456
|
+
|
|
457
|
+
The key is `(kind, name)`. The table lives in the schema that `ledgerSchema` names: `public` on Postgres and `dbo` on SQL Server when there is no `ledgerSchema`. The package that exports the declaration names the schema, usually the schema of its own objects, so the host needs no grant on `public`. Two declarations can share one ledger table, because each row has the qualified name of its object.
|
|
458
|
+
|
|
459
|
+
## Errors
|
|
460
|
+
|
|
461
|
+
| Error | When |
|
|
462
|
+
| ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
463
|
+
| `SchemaDriftError` | `check` found an object that is missing or stale. `objects` lists each one with its name, kind and drift. Apply the declaration ([ADR 0016](./docs/adr/0016-the-package-owns-one-error-class-schemadrifterror-and-every-other-error-is-the-error-of-the-database.md)). |
|
|
464
|
+
| `A statement of a declaration must start with CREATE …` | The Postgres or SQL Server constructor cannot read the kind and the name from the head of a statement. |
|
|
465
|
+
| `A declared object needs a schema in its name: …` | The Postgres or SQL Server constructor found a name with no schema. |
|
|
466
|
+
| `A declaration does not use IF NOT EXISTS: …` | A constructor found `IF NOT EXISTS`. On SQLite, the message of sqlite-drift: `An element of a declaration makes one object. …`. |
|
|
467
|
+
| `A declared schema has only its name: …` | A `CREATE SCHEMA` has `AUTHORIZATION` or objects in it. |
|
|
468
|
+
| `A statement of a declaration must close each …` | The Postgres constructor found a string, a quoted name, a dollar-quoted body or a comment that does not close. |
|
|
469
|
+
| `A declaration names each object once: …` | Two statements make objects of one kind and one qualified name, also two overloads of one function. |
|
|
470
|
+
| `apply needs rows: 'replace' or 'keep'. …` (`TypeError`) | A JavaScript caller gave `apply` no `rows`. TypeScript refuses the call. Nothing changes. |
|
|
471
|
+
| The error of SQLite | `new SqliteDeclaration` fails when a statement does not run in the dev database. |
|
|
472
|
+
| `The dev database must be empty. …` | `new SqliteDeclaration` fails when the dev database has an object. |
|
|
473
|
+
| `no such module: …`, `no such function: …` | `new SqliteDeclaration`, or SQLite `apply` on the target database, when that connection does not have a module or a function that a statement uses. |
|
|
474
|
+
| `An element of a declaration holds one statement. …` | `new SqliteDeclaration` fails when one string holds two statements. The Postgres constructor ends the message with `:` and the element. |
|
|
475
|
+
| `An element of a declaration makes one object. …` | `new SqliteDeclaration` fails when a statement makes no object, for example `CREATE TABLE IF NOT EXISTS` of a declared table, a `TEMP` table, or an `INSERT`. |
|
|
476
|
+
| `The virtual table … cannot keep its rows: …` | SQLite `apply` with `rows: 'keep'`, and a virtual table is stale. Nothing changes. |
|
|
477
|
+
| `database is locked` | SQLite `apply` with no transaction waits for the busy timeout of the connection, then fails. |
|
|
478
|
+
| `Keeping the rows of a table that other tables reference needs foreign keys off, …` | SQLite `apply` with `rows: 'keep'`, in a transaction of the caller, with foreign keys on, and another table refers to a stale table. Nothing changes. |
|
|
479
|
+
| `The kept rows break a foreign key: …` | SQLite `apply` with `rows: 'keep'`, and `PRAGMA foreign_key_check` finds a kept row that refers to no row. The database stays as it was. |
|
|
480
|
+
| `The rebuild breaks the view …` | SQLite `apply` with `rows: 'keep'`, and a view compiled before the rebuild and does not compile after it. The `cause` has the error of SQLite. The database stays as it was. |
|
|
481
|
+
| The error of the database | `apply` fails on a statement, a copy, a foreign key or a lock. The transaction rolls back, and the database stays as it was. The package does not wrap it. |
|
|
482
|
+
|
|
483
|
+
## What the package does not do
|
|
484
|
+
|
|
485
|
+
- **It keeps no migration files and no history of versions.** The declaration is the one source of the shape. The ledger has one row for each object, not one for each change.
|
|
486
|
+
- **It does not find a rename.** A renamed table or column is one object or column dropped and one made. Copy the values yourself before `apply`.
|
|
487
|
+
- **It does not change data.** It runs no data migration and writes no seed rows. A host writes them after `apply`.
|
|
488
|
+
- **It does not change an object in place.** It does no `ALTER` for each difference, as Atlas, pg-schema-diff, EF Core and Prisma do. A diff needs a dev database or a reader of the catalog that knows every clause of every engine ([ADR 0009](./docs/adr/0009-postgres-and-sql-server-compare-a-checksum-of-each-declared-statement-with-a-ledger-row-and-need-no-dev-database.md)).
|
|
489
|
+
- **It does not change objects online.** It runs in one transaction, so it does no `CREATE INDEX CONCURRENTLY` and no online rebuild. A rebuild locks the table until the commit.
|
|
490
|
+
- **It does not see a hand edit on Postgres or SQL Server.** It sees only the checksum of the statement that it applied.
|
|
491
|
+
- **It does not drop an object that the declaration does not name.** A removed statement leaves its object and its ledger row. Drop them with your own SQL.
|
|
492
|
+
- **It does not keep grants, comments or policies.** The host grants again after `apply`.
|
|
493
|
+
- **It does not support MySQL or MariaDB yet.**
|
|
494
|
+
|
|
495
|
+
What is in the package now, what comes later, and what never comes:
|
|
496
|
+
|
|
497
|
+
| Now | Later | Never |
|
|
498
|
+
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
|
|
499
|
+
| Tables, indexes, views, sequences, functions, procedures and schemas on SQLite, Postgres and SQL Server (SQLite: also virtual tables and triggers). `drift`, `check`, `apply`. `rows: 'replace'` and `'keep'`. | Triggers, materialized views, types and enums, policies and grants on Postgres and SQL Server. MySQL and MariaDB. | Migration files. Renames. `ALTER` for each difference. A dev database in production. |
|
|
500
|
+
|
|
501
|
+
## Who uses it
|
|
502
|
+
|
|
503
|
+
zukhruf's own SQLite packages use `./sqlite`. Each one still applies its declaration when it opens, with the `rows` it had in sqlite-drift; they move to check only in #6874. The other moves follow the release, each with its backlog item.
|
|
504
|
+
|
|
505
|
+
| Consumer | How | Record |
|
|
506
|
+
| --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
|
|
507
|
+
| `@zukhruf/checkpoint`, `@zukhruf/sqlite-queue`, `@zukhruf/sqlite-notify` | `apply(database, { rows: 'keep' })` when the store or the file opens, so a newer release keeps the checkpoints, the jobs and the notifications. | ADR 0006, #6874 |
|
|
508
|
+
| `@zukhruf/embeddings`, `@zukhruf/event-detection` | `apply(database, { rows: 'replace' })` when the collection or the detector opens. Each row comes again from the caller's documents or reports. | ADR 0006, #6874 |
|
|
509
|
+
| The other importers of `@zukhruf/sqlite-drift` | 24 files move to `@zukhruf/schema-drift/sqlite`: elt 10, context-compiler 6, deepagents 8. `Declaration` becomes `SqliteDeclaration`, `rows` moves from the constructor to `apply`, and `drift(...)` gives a report in place of a string. | ADR 0006 |
|
|
510
|
+
| `@zukhruf/checkpoint` | Each of its three stores exports its declaration. `SqliteCheckpointStore` and the `open` of the Postgres and SQL Server stores only check. This supersedes checkpoint ADR 0011's "Async open() creates them". | checkpoint ADR 0011, backlog #2625 |
|
|
511
|
+
| elt-postgresql | Exports the `warehouse` declaration of its fixed tables, views, functions, sequences and schemas. The hosts apply it at start. | #2625 |
|
|
512
|
+
| zukhruf SQLite packages (embeddings, event-detection, sqlite-notify, sqlite-queue, embedding-cache) | Export their declarations and only check when they open. | #6874 |
|
|
513
|
+
| `@zukhruf/mutex` database lock stores | A named error when the host has not made the objects of the store. | #6875 |
|
|
514
|
+
| elt-sqlite, elt-sqlserver, the vectorizer keyword indexes | Declare and export their fixed tables. The hosts apply. | #6877 |
|
|
515
|
+
| deepagents stores | Export their declarations and only check when they open. | #6878 |
|
|
516
|
+
| context-compiler hosts | Apply the declarations of the stores that they use. | #6879 |
|
|
517
|
+
|
|
518
|
+
## The same concepts in other systems
|
|
519
|
+
|
|
520
|
+
| Concept | Other systems |
|
|
521
|
+
| ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
522
|
+
| Schema drift, declarative schema management | [Atlas](https://atlasgo.io/concepts/declarative-vs-versioned) (`schema apply`), Liquibase (drift reports), Prisma `db push`, Drizzle Kit `push`, DacFx and SqlPackage `Publish`. |
|
|
523
|
+
| A checksum of each applied unit | Liquibase `DATABASECHANGELOG.MD5SUM` for each changeset (`CheckSum.java:85-90`, `StandardChangeLogHistoryService.java:553`). Flyway's `checksum` column and `validate` ("Migration checksum mismatch", `ValidateVerbExtension.java:269`). |
|
|
524
|
+
| The host applies, the package checks | Spring Batch `spring.batch.jdbc.initialize-schema=never`, Django `migrate`, Hangfire `PrepareSchemaIfNecessary = false`, pg-boss `migrate: false`, Temporal's check of the schema version at start. `@zukhruf/mutex`'s lock stores already run no DDL. |
|
|
525
|
+
| A lock around apply only | Flyway `pg_try_advisory_xact_lock` (`PostgreSQLAdvisoryLockTemplate.java:101`) and `sp_getapplock` (`SQLServerApplicationLockTemplate.java:66`), EF Core 9 `sp_getapplock '__EFMigrationsLock'` (`SqlServerHistoryRepository.cs:169`), golang-migrate `pg_advisory_lock` (`database/postgres/postgres.go:241`). |
|
|
526
|
+
| Rebuild a table and keep its rows | DacFx: `CREATE TABLE tmp_ms_xx_<t>`, `SET IDENTITY_INSERT ON`, `INSERT … SELECT … ORDER BY` the key, `DROP TABLE`, `sp_rename`, in one transaction with `SET XACT_ABORT ON`. SQLite's 12 steps of "Making Other Kinds Of Table Schema Changes". |
|
|
527
|
+
| Block a change that loses data | DacFx `BlockOnPossibleDataLoss`, Atlas lint (destructive changes), Prisma `db push --accept-data-loss`. This package does not block ([ADR 0013](./docs/adr/0013-a-column-that-the-declaration-drops-loses-its-data-as-the-declaration-states.md)). |
|
|
528
|
+
| Compare the stored text with a copy in the dev database | Röthlisberger's SQLite migrator: it makes the declaration in memory and compares `sqlite_schema`. |
|
|
529
|
+
| Rebuild with a map of renamed columns | sqlite-utils `table.transform()`: it rebuilds a table with the 12 steps, keeps the rows, and takes a map of renamed columns. SQLite `rows: 'keep'` has no such map ([ADR 0003](./docs/adr/0003-keep-rows-rebuilds-a-table-and-keeps-its-references.md)). |
|
|
530
|
+
| Find a declaration that changed | Android Room (`RoomConnectionManager.kt`): Room keeps a version number, and a hash of the declaration finds a number that a person forgot to raise ([ADR 0001](./docs/adr/0001-compare-the-text-that-sqlite-stores.md)). |
|
|
531
|
+
| Dev database | Atlas's dev database, Prisma's shadow database. Only the SQLite path has one, in memory. |
|
|
532
|
+
|
|
533
|
+
No package on npm does this work. Each candidate of the search on 2026-12-01 fails one requirement:
|
|
534
|
+
|
|
535
|
+
| Package | Why it does not fit |
|
|
536
|
+
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
537
|
+
| `@supabase/pg-delta` 1.0.0-alpha.61 | No stable release. It diffs against a shadow database. |
|
|
538
|
+
| `@pgkit/migra` 0.6.1 | Last release 2025-08. It does not pin `search_path`, so its output depends on the session. It diffs against a second database. |
|
|
539
|
+
| `extract-pg-schema` 5.9.0 | It opens its own `pg` connection, and it reads a model for code generation. It does not compare. |
|
|
540
|
+
| pg-schema-diff | Go. It diffs against a temporary database. |
|
|
541
|
+
| DacFx and SqlPackage | .NET. |
|
|
542
|
+
| Atlas | Go. SQL Server needs Atlas Pro. |
|
|
543
|
+
|
|
544
|
+
## API
|
|
545
|
+
|
|
546
|
+
```ts
|
|
547
|
+
// @zukhruf/schema-drift
|
|
548
|
+
|
|
549
|
+
/** How a database stores the objects of a declaration: none of them, each one as declared, or anything else. */
|
|
550
|
+
export type Drift = 'missing' | 'stale' | 'fits';
|
|
551
|
+
|
|
552
|
+
/** What apply does with the rows of a stale table. It has no default. */
|
|
553
|
+
export type Rows = 'replace' | 'keep';
|
|
554
|
+
|
|
555
|
+
export type ObjectKind =
|
|
556
|
+
| 'table'
|
|
557
|
+
| 'virtual table' // SQLite only
|
|
558
|
+
| 'trigger' // SQLite only, for now
|
|
559
|
+
| 'index'
|
|
560
|
+
| 'view'
|
|
561
|
+
| 'sequence'
|
|
562
|
+
| 'function'
|
|
563
|
+
| 'procedure'
|
|
564
|
+
| 'schema';
|
|
565
|
+
|
|
566
|
+
/** One declared object that does not fit. */
|
|
567
|
+
export type DriftedObject = {
|
|
568
|
+
/** Qualified on Postgres and SQL Server: '_warehouse.extraction_coverage'. An index on SQL Server: 'dbo.runs.runs_by_name'. */
|
|
569
|
+
readonly name: string;
|
|
570
|
+
readonly kind: ObjectKind;
|
|
571
|
+
readonly drift: 'missing' | 'stale';
|
|
572
|
+
};
|
|
573
|
+
|
|
574
|
+
export type DriftReport = {
|
|
575
|
+
readonly drift: Drift;
|
|
576
|
+
/** Each missing or stale object, in the order of the declaration. Empty when drift is 'fits'. */
|
|
577
|
+
readonly objects: readonly DriftedObject[];
|
|
578
|
+
};
|
|
579
|
+
|
|
580
|
+
/** check found an object that is missing or stale. The next step: apply the declaration. */
|
|
581
|
+
export class SchemaDriftError extends Error {
|
|
582
|
+
readonly objects: readonly DriftedObject[];
|
|
583
|
+
}
|
|
584
|
+
```
|
|
585
|
+
|
|
586
|
+
```ts
|
|
587
|
+
// @zukhruf/schema-drift/sqlite
|
|
588
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
589
|
+
|
|
590
|
+
export class SqliteDeclaration {
|
|
591
|
+
/** devDatabase opens the empty database in memory. The declaration closes it. */
|
|
592
|
+
constructor(
|
|
593
|
+
statements: readonly string[],
|
|
594
|
+
options?: { readonly devDatabase?: () => DatabaseSync },
|
|
595
|
+
);
|
|
596
|
+
drift(database: DatabaseSync): DriftReport;
|
|
597
|
+
/** Throws SchemaDriftError when the drift is not 'fits'. */
|
|
598
|
+
check(database: DatabaseSync): void;
|
|
599
|
+
/** The host chooses rows when it applies. It has no default. */
|
|
600
|
+
apply(database: DatabaseSync, options: { readonly rows: Rows }): void;
|
|
601
|
+
}
|
|
602
|
+
```
|
|
603
|
+
|
|
604
|
+
```ts
|
|
605
|
+
// @zukhruf/schema-drift/postgres
|
|
606
|
+
|
|
607
|
+
export type SignalOption = { readonly signal?: AbortSignal };
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* The port through which the declaration sends its SQL: the host writes it
|
|
611
|
+
* over its own driver. The parameters are positional, `$1` for the first.
|
|
612
|
+
* `transaction(work)` runs the work on one connection in one transaction.
|
|
613
|
+
* A copy of the PostgresSession of @zukhruf/checkpoint (docs/copied-session-ports.md).
|
|
614
|
+
*/
|
|
615
|
+
export type PostgresSession = {
|
|
616
|
+
query(
|
|
617
|
+
sql: string,
|
|
618
|
+
parameters: readonly unknown[],
|
|
619
|
+
options?: SignalOption,
|
|
620
|
+
): Promise<readonly Record<string, unknown>[]>;
|
|
621
|
+
transaction(work: (session: PostgresSession) => Promise<void>): Promise<void>;
|
|
622
|
+
};
|
|
623
|
+
|
|
624
|
+
export class PostgresDeclaration {
|
|
625
|
+
/** ledgerSchema is the schema of the ledger table. Default: 'public'. */
|
|
626
|
+
constructor(
|
|
627
|
+
statements: readonly string[],
|
|
628
|
+
options?: { readonly ledgerSchema?: string },
|
|
629
|
+
);
|
|
630
|
+
drift(session: PostgresSession): Promise<DriftReport>;
|
|
631
|
+
/** Throws SchemaDriftError when the drift is not 'fits'. */
|
|
632
|
+
check(session: PostgresSession): Promise<void>;
|
|
633
|
+
/** The host chooses rows when it applies. It has no default. */
|
|
634
|
+
apply(
|
|
635
|
+
session: PostgresSession,
|
|
636
|
+
options: { readonly rows: Rows },
|
|
637
|
+
): Promise<void>;
|
|
638
|
+
}
|
|
639
|
+
```
|
|
640
|
+
|
|
641
|
+
```ts
|
|
642
|
+
// @zukhruf/schema-drift/sqlserver
|
|
643
|
+
|
|
644
|
+
export type SignalOption = { readonly signal?: AbortSignal };
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* The port through which the declaration sends its SQL: the host writes it
|
|
648
|
+
* over its own driver. The parameters are named, `@p0` for the key `p0`.
|
|
649
|
+
* `transaction(work)` runs the work on one connection in one transaction.
|
|
650
|
+
* A copy of the SqlServerSession of @zukhruf/checkpoint (docs/copied-session-ports.md).
|
|
651
|
+
*/
|
|
652
|
+
export type SqlServerSession = {
|
|
653
|
+
query(
|
|
654
|
+
sql: string,
|
|
655
|
+
parameters: Readonly<Record<string, unknown>>,
|
|
656
|
+
options?: SignalOption,
|
|
657
|
+
): Promise<readonly Record<string, unknown>[]>;
|
|
658
|
+
transaction(
|
|
659
|
+
work: (session: SqlServerSession) => Promise<void>,
|
|
660
|
+
): Promise<void>;
|
|
661
|
+
};
|
|
662
|
+
|
|
663
|
+
export class SqlServerDeclaration {
|
|
664
|
+
/** ledgerSchema is the schema of the ledger table. Default: 'dbo'. */
|
|
665
|
+
constructor(
|
|
666
|
+
statements: readonly string[],
|
|
667
|
+
options?: { readonly ledgerSchema?: string },
|
|
668
|
+
);
|
|
669
|
+
drift(session: SqlServerSession): Promise<DriftReport>;
|
|
670
|
+
/** Throws SchemaDriftError when the drift is not 'fits'. */
|
|
671
|
+
check(session: SqlServerSession): Promise<void>;
|
|
672
|
+
/** The host chooses rows when it applies. It has no default. */
|
|
673
|
+
apply(
|
|
674
|
+
session: SqlServerSession,
|
|
675
|
+
options: { readonly rows: Rows },
|
|
676
|
+
): Promise<void>;
|
|
677
|
+
}
|
|
678
|
+
```
|
|
679
|
+
|
|
680
|
+
## Documentation
|
|
681
|
+
|
|
682
|
+
**Decisions**
|
|
683
|
+
|
|
684
|
+
ADRs 0001 to 0005 are the decisions of `@zukhruf/sqlite-drift`, which moved into this package with their numbers.
|
|
685
|
+
|
|
686
|
+
- [ADR 0001](./docs/adr/0001-compare-the-text-that-sqlite-stores.md): compare the text that SQLite stores.
|
|
687
|
+
- [ADR 0002](./docs/adr/0002-a-stale-object-replaces-the-whole-declaration.md): a stale object replaces the whole declaration.
|
|
688
|
+
- [ADR 0003](./docs/adr/0003-keep-rows-rebuilds-a-table-and-keeps-its-references.md): keep rows rebuilds a table and keeps its references.
|
|
689
|
+
- [ADR 0004](./docs/adr/0004-a-statement-owns-the-objects-its-create-makes.md): a statement owns the objects its CREATE makes.
|
|
690
|
+
- [ADR 0005](./docs/adr/0005-the-caller-can-give-the-dev-database.md): the caller can give the dev database.
|
|
691
|
+
- [ADR 0006](./docs/adr/0006-the-package-is-zukhruf-schema-drift-with-one-import-path-for-each-engine-and-sqlite-drift-moves-into-it.md): the package is `@zukhruf/schema-drift`, with one import path for each engine, and sqlite-drift moves into it.
|
|
692
|
+
- [ADR 0007](./docs/adr/0007-the-package-declares-its-objects-the-host-applies-them-and-the-package-only-checks-when-it-opens.md): the package declares its objects, the host applies them, and the package only checks when it opens.
|
|
693
|
+
- [ADR 0008](./docs/adr/0008-the-sqlite-path-keeps-the-design-of-sqlite-drift-and-adds-check-and-a-report-of-each-object.md): the SQLite path keeps the design of sqlite-drift, and adds check and a report of each object.
|
|
694
|
+
- [ADR 0009](./docs/adr/0009-postgres-and-sql-server-compare-a-checksum-of-each-declared-statement-with-a-ledger-row-and-need-no-dev-database.md): Postgres and SQL Server compare a checksum of each declared statement with a ledger row, and need no dev database.
|
|
695
|
+
- [ADR 0010](./docs/adr/0010-a-checksum-covers-the-tokens-of-a-statement-and-comments-and-the-spaces-between-tokens-are-not-drift.md): a checksum covers the tokens of a statement, and comments and the spaces between tokens are not drift.
|
|
696
|
+
- [ADR 0011](./docs/adr/0011-the-constructor-reads-the-kind-and-the-qualified-name-of-each-statement-from-its-head-and-refuses-one-it-cannot-read.md): the constructor reads the kind and the qualified name of each statement from its head, and refuses one it cannot read.
|
|
697
|
+
- [ADR 0012](./docs/adr/0012-keep-rows-rebuilds-a-stale-table-and-replace-drops-and-makes-each-stale-object.md): keep rows rebuilds a stale table, and replace drops and makes each stale object.
|
|
698
|
+
- [ADR 0013](./docs/adr/0013-a-column-that-the-declaration-drops-loses-its-data-as-the-declaration-states.md): a column that the declaration drops loses its data, as the declaration states.
|
|
699
|
+
- [ADR 0014](./docs/adr/0014-apply-takes-a-lock-that-its-transaction-owns-and-reads-the-ledger-again-inside-it.md): apply takes a lock that its transaction owns, and reads the ledger again inside it.
|
|
700
|
+
- [ADR 0015](./docs/adr/0015-the-postgres-and-sql-server-paths-take-a-driver-free-session-a-fourth-copy-of-the-session-ports.md): the Postgres and SQL Server paths take a driver-free session, a fourth copy of the session ports.
|
|
701
|
+
- [ADR 0016](./docs/adr/0016-the-package-owns-one-error-class-schemadrifterror-and-every-other-error-is-the-error-of-the-database.md): the package owns one error class, `SchemaDriftError`, and every other error is the error of the database.
|
|
702
|
+
|
|
703
|
+
## Development
|
|
704
|
+
|
|
705
|
+
This package is part of the [zukhruf](../../README.md) workspace. Run the commands from the workspace root.
|
|
706
|
+
|
|
707
|
+
```sh
|
|
708
|
+
npm install
|
|
709
|
+
npx nx run schema-drift:test # builds, then runs the tests in src/
|
|
710
|
+
npx nx run schema-drift:typecheck # formats, lints, then type checks
|
|
711
|
+
npx nx run schema-drift:build # compiles src/ to dist/
|
|
712
|
+
```
|
|
713
|
+
|
|
714
|
+
```
|
|
715
|
+
src/
|
|
716
|
+
index.ts the root entry point: the shared types and SchemaDriftError
|
|
717
|
+
drift.ts Drift, Rows, ObjectKind, DriftedObject, DriftReport
|
|
718
|
+
schema-drift-error.ts SchemaDriftError
|
|
719
|
+
sqlite.ts the ./sqlite entry point
|
|
720
|
+
sqlite/sqlite-declaration.ts SqliteDeclaration
|
|
721
|
+
sqlite/sqlite-declaration.test.ts the tests, on real SQLite files
|
|
722
|
+
postgres.ts the ./postgres entry point
|
|
723
|
+
postgres/postgres-statement.ts the tokens, the checksum and the head of a statement
|
|
724
|
+
postgres/postgres-declaration.ts PostgresDeclaration, PostgresSession
|
|
725
|
+
postgres/postgres-declaration.test.ts the tests, on a real Postgres of @zukhruf/testing/postgres
|
|
726
|
+
```
|