@zukhruf/schema-drift
v0.8.375
Published
Declarative schema management for SQLite, Postgres and SQL Server: a package exports the CREATE statements of its objects, the host applies them, and the package checks and throws SchemaDriftError for each missing or stale object.
Maintainers
Readme
@zukhruf/schema-drift
Design accepted 2026-12-01. The root entry point,
./sqlite,./postgresand./sqlserverare built (backlog #2625).
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).
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).
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). @zukhruf/sqlite-drift moves into ./sqlite with no change of behaviour, and goes away with no alias.
The words in these documents have one meaning each. See the glossary in CONTEXT.md.
Use it
npm install @zukhruf/schema-driftThe package that keeps the tables exports their declaration:
import { PostgresDeclaration } from '@zukhruf/schema-drift/postgres';
export const warehouse = new PostgresDeclaration(
[
'CREATE SCHEMA _warehouse',
`CREATE TABLE _warehouse.extraction_coverage (
stream text PRIMARY KEY,
target_schema text NOT NULL,
reloading boolean NOT NULL DEFAULT false
)`,
'CREATE INDEX extraction_coverage_target ON _warehouse.extraction_coverage (target_schema)',
],
{ name: 'elt-postgresql/warehouse', ledgerSchema: '_warehouse' },
);The host applies it, once, when it chooses:
import { warehouse } from 'elt-postgresql';
await warehouse.apply(session, { rows: 'keep' }); // the host chooses keep or replaceThe package checks it when it opens, and runs no DDL:
await warehouse.check(session); // throws SchemaDriftError when an object is missing or stalesession is a PostgresSession that the host writes over its own driver, as for @zukhruf/checkpoint (ADR 0015).
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.
Declare the objects of a package
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.nameis required on every engine:'<npm package>/<declaration>', such as'@zukhruf/checkpoint/postgres'. The package gives it, never the host, so it is the same on every host and every deploy. It owns each object of the declaration in the ledger; see Own the objects. A factory whose declarations can share one ledger folds its parameter in:`@zukhruf/embedding-cache/sqlserver:${table}`. A JavaScript caller that gives no name, an empty one or one longer than 400 characters getsTypeError.rowsis'replace'or'keep', an option ofapply. It tellsapplywhat to do with the rows of a stale table. The host gives it, because the host knows whether its rows can be made again;driftandcheckdo not use it. It has no default, so no caller loses rows because it forgot an option.- 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). Each name carries its schema:
_warehouse.extraction_coverage, notextraction_coverage. An index takes the schema of its table. - The constructor refuses
IF NOT EXISTS, as sqlite-drift ADR 0004 does: it hides a stale object behind its name. - The constructor refuses a
CREATE SCHEMAwithAUTHORIZATIONor with objects in it. The owner and the grants of a schema belong to the host. - On Postgres and SQL Server, the constructor refuses two functions or two procedures of one qualified name. The package does not declare overloads.
- On Postgres and SQL Server, an element can declare a DML trigger on a table or a view that an earlier statement makes. See Declare a trigger.
- On Postgres, an element can also be
COMMENT ON <kind> <name> IS '<text>', which describes an object that an earlier statement makes. See Describe the objects (ADR 0017). - The SQLite constructor keeps the
devDatabaseoption of sqlite-drift, besidename: it opens the empty database in memory where the statements run once.rowsmoved from the constructor of sqlite-drift toapply(database, { rows })(ADR 0007, ADR 0008).
Declare a trigger
A declaration of Postgres or SQL Server declares a DML trigger with its CREATE TRIGGER statement (ADR 0011):
| | Postgres | SQL Server |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| Statement | CREATE [OR REPLACE] [CONSTRAINT] TRIGGER <name> … ON <schema>.<table or view> …, FOR EACH ROW or FOR EACH STATEMENT, with REFERENCING, WHEN and UPDATE OF as Postgres has them | CREATE [OR ALTER] TRIGGER <schema>.<name> ON <schema>.<table or view> … AS <body>; the body may hold statements of its own |
| Name in the report and the ledger | <schema>.<table>.<trigger>: the trigger takes the schema of its table, and its name is unique only in that table | <schema>.<trigger>: the name is unique in its schema |
| Refused | A schema in the trigger name; CONSTRAINT with OR REPLACE; COMMENT ON TRIGGER | A name with no schema; a schema other than the table's (error 2108 at apply otherwise); ON DATABASE and ON ALL SERVER |
- A trigger comes after the statement that makes its table or view. On Postgres it comes after the declared function that it executes too, when its head names that function with its schema. The constructor refuses another order, so
applymakes the table and the function first. driftreadspg_trigger(an internal trigger is never a declared one) orsys.triggerson the declared table. A trigger is missing when the catalog does not list it, and stale when its statement changed or when it is disabled: its statement makes it enabled, as sqlpackage counts the state as a difference (IgnoreDmlTriggerState=False).applydrops a stale trigger and makes it from its statement.- The checksum covers each token of the statement: the timing, the events,
REFERENCING,FOR EACH,WHEN, the function and its arguments, the body. It does not cover the body of the function, which is its own declared object, or the firing order (sp_settriggerorder). applydrops each trigger on a declared table or view that the declaration does not declare, as sqlpackage'sDropDmlTriggersNotInSourcedoes. A trigger on a table or a view that the declaration does not name stays. See Apply a declaration.
Find the drift
drift(database) on SQLite and await drift(session) on Postgres and SQL Server give a report: the drift of the whole declaration, each object that does not fit, and each leftover.
const report = await warehouse.drift(session);
// { drift: 'stale',
// objects: [
// { name: '_warehouse.extraction_coverage', kind: 'table', drift: 'stale' },
// { name: '_warehouse.extraction_coverage_target', kind: 'index', drift: 'missing' } ],
// leftovers: [] }driftismissingwhen the database stores none of the objects,fitswhen it stores each one as declared, andstalefor all other cases.objectslists each declared object that is missing or stale, in the order of the declaration. It is empty when the drift isfits.leftoverslists each object that the ledger says thenameowns, that the declaration no longer names, and that the database still stores:{ name, kind }, by kind, then name (#7155). The nextapplydrops each one, or refuses a table with rows underrows: 'keep'(Own the objects).terraform planlists "to destroy" apart from "to change" the same way.- A leftover does not change
drift, which is about the declared objects only.checkdoes not throw for a leftover, andSchemaDriftErrornever carries one: a leftover breaks no query of the package, andcheckruns in processes that never apply (ADR 0007). - An index or a trigger on a declared table that no ledger row of the
nameowns is not a leftover, thoughapplydrops it (Apply a declaration). An object whose ledger row stays but that the database no longer stores is not a leftover either:applyonly deletes its row. A schema and a Postgres object comment are never leftovers. - On Postgres and SQL Server,
driftreads the leftovers in its one query. A ledger that a version before theownercolumn wrote gives no leftovers. driftonly reads. It takes no lock and needs no write permission.
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). A hand edit of an object is drift.
Postgres and SQL Server compare a checksum of each declared statement with the ledger row of its object, in one query (ADR 0009):
| Ledger row | Object in the catalog | Drift |
| --------------------- | --------------------- | --------- |
| Has the same checksum | Exists | fits |
| Has another checksum | Exists | stale |
| None | Exists | stale |
| Any, or none | Does not exist | missing |
- 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 anN'…'string (SQL Server) is drift. A change of case of a word is drift too (ADR 0010). - A declared schema fits when it exists, with or without a ledger row: its statement holds only its name.
- 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
applyrepairs a database that older code made withIF NOT EXISTS. - A change that a person makes by hand after
applyis 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.
Check a database when the package opens
check(database) on SQLite and await check(session) on Postgres and SQL Server run drift. On Postgres and SQL Server, drift and check need only the query of the session; apply also needs its transaction. When the drift is not fits, they throw SchemaDriftError, which names each missing or stale object. The next step is to apply the declaration. A leftover does not make them throw.
SchemaDriftError: The database does not store the declaration as declared:
_warehouse.extraction_coverage (table) is stale.
_warehouse.extraction_coverage_target (index) is missing.
Apply the declaration.A package calls check in its constructor or its open, and gives it the signal of its open: await check(session, { signal }). It does not call apply (ADR 0007).
Apply a declaration
apply makes the database store each object of the declaration as declared. It drops each index on a declared table that the declaration does not name, with each rows option, as sqlpackage (DropIndexesNotInSource), Atlas and Prisma drop them. It drops each trigger that the declaration does not declare on a declared table, and on Postgres and SQL Server on a declared view too, as sqlpackage's DropDmlTriggersNotInSource does. A Postgres internal trigger (of a foreign key or a deferrable constraint) and the copy of a trigger on a partition stay, and so do a SQL Server trigger that SQL Server ships (is_ms_shipped) and a database or server DDL trigger. An index that the CREATE TABLE makes (a primary key, a unique constraint, an INDEX that a SQL Server CREATE TABLE names) is the table's own and stays. To keep an index or a trigger of its own on a declared table, a host declares it in a declaration that composes the package's (ADR 0002); on Postgres and SQL Server, an index whose ledger row another declaration owns stays too. apply also drops each object that its declaration's name owns and no longer names (Own the objects). An object that no ledger row of the declaration owns stays: on a table that the declaration does not name, and a view or a table that the declaration does not name. apply does nothing more when the drift is fits and nothing is left to drop. drift lists the objects that the name owns and that apply would drop as leftovers, but not an index or a trigger that no ledger row of the name owns.
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, ADR 0003). It also keeps a ledger of the owners. See Apply on SQLite.
Postgres and SQL Server work only on the stale and the missing objects, in the order of the declaration (ADR 0012):
applyopens one transaction on the session. On SQL Server it runsSET XACT_ABORT ONandBEGIN TRANSACTION.- It takes the lock of the package, which the transaction owns, and reads the ledger again inside the lock (ADR 0014).
- It adds the
ownercolumn to a ledger that a version before it wrote, and refuses, before any change, a declared object other than a schema whose ledger row anothernameowns. - In one statement, it deletes the ledger rows that its
nameowns and the declaration no longer names, and sets itsnameon each row of a declared object that has no owner. Withrows: 'keep', a removed table with rows makes it refuse first. It drops each removed trigger, view and index, and on Postgres each removed comment. A removed table whose name a declared object takes drops here too. - It drops each index on a declared table and each trigger on a declared table or view that the declaration does not name and that no other
nameowns. - It makes the ledger table when it is missing, after the declared schemas.
- It makes each missing object from its statement.
- It replaces each stale view, function, procedure, index and trigger: it drops the object and makes it from its statement. These objects keep no rows. The views that read a stale view or call a stale function are dropped first and made again after (ADR 0018). A declared trigger that
applydrops with its table, its view or the function that it executes is made again from its statement at its own place in the declaration, after what it needs. - It replaces or rebuilds each stale table, as
rowssays (see below), and each stale sequence. - On Postgres, it runs the
COMMENTstatement of each missing or stale object comment, and of each comment whose object it made. - It drops each other removed table, then the removed functions, procedures and sequences, also when nothing drifted. A declared table that no longer refers to a removed table was rebuilt or replaced first, so its old foreign key does not block the drop (#7156). On SQL Server, step 12 comes before this step.
- It writes the ledger row of each object and each object comment that it made, with the checksum of its statement and its
nameas the owner. The rows commit with the objects, or neither does.
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.
Replace the rows
With rows: 'replace', apply drops a stale table and makes it from its statement. Its rows are gone.
- A declared table that refers to the replaced table is replaced too, so no kept row refers to a row that is gone.
- 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
applyread before the drop. - A declared index on the table is made from its statement. An index that the declaration does not name was dropped before, and is not made again. A declared trigger on the table is made from its statement at its own place in the declaration. A trigger that the declaration does not declare was dropped before, and is not made again.
- 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,
applyfails with the error of the database, and the transaction rolls back. - A stale sequence is dropped and made from its statement. It starts again.
- A stale function is dropped after the views that call it, and the views that read those. On SQL Server, only the schema-bound ones are dropped. After the function, they are made again: a declared view from its statement, any other view from its definition; on SQL Server, the others get
sp_refreshview. On Postgres, the triggers that execute the function are dropped before it, and made again after it: a declared trigger from its statement at its own place in the declaration, any other frompg_get_triggerdef. A SQL Server DML trigger cannot be schema-bound, so it does not stop the drop. A default, aCHECK, a computed column or an index expression that calls the function still makesapplyfail with the error of the database (ADR 0018).
Keep the rows
With rows: 'keep', apply rebuilds each stale table and keeps its rows. This is the table rebuild of DacFx (its publish script), with the old table renamed away first, as SQLite rebuilds a table (sqlite-drift ADR 0003):
- It reads, from the catalog of the target, the views that depend on the table and the foreign keys that refer to it.
- It drops those views and foreign keys.
- 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.
- 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. - 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 VALUEon Postgres,SET IDENTITY_INSERT … ONon SQL Server. It does not copy a column that the database computes (generated, computed,rowversion). - On Postgres, it sets the sequence of each identity or
serialcolumn to the largest copied value (setval). SQL Server moves the identity on its own when it inserts a larger value. - It drops the old table, and makes each declared index on the table from its statement. An index or a trigger that the declaration does not name was dropped before the rebuild, and is not made again. Each declared trigger on the table is made from its statement at its own place in the declaration, after the copy, so it does not fire for the copied rows.
- 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_refreshviewon each view that is not schema-bound and that refers to the table.
A stale sequence keeps its last value: apply reads it, makes the sequence from its statement, and sets the value again.
- A column that only the declaration has gets its default.
- A column that only the stored table has is gone, with its values. The declaration states this intent (ADR 0013).
applydoes 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 beforeapply.- When a stored row does not fit the declared table (
NOT NULL,CHECK, a foreign key, a type),applyfails with the error of the database, and the transaction rolls back. - The grants and the row-level security policies of a rebuilt table or a made-again view are gone. The host grants them again after
apply. On Postgres, the declared object comments come back; the comments of an undeclared view thatapplymakes again from its definition are gone.
Own the objects
On every engine, the name of a declaration owns each of its objects in the ledger, as a Helm release owns the objects of its chart and a kubectl ApplySet its members (ADR 0002):
applyrefuses, before any change, a declaration that names an object whose ledger row anothernameowns:An object of the declaration belongs to another declaration: public.runs (table) belongs to '@zukhruf/runs/postgres'.Helm refuses an object of another release the same way.- On Postgres and SQL Server, a schema holds the objects of several declarations, as a namespace holds several Helm releases, so
applytakes a schema whose row anothernameowns. The row keeps thenamewhoseapplymade the schema. SQLite has no schema statement: the database file holds the ledger. applydrops each object whose ledger row itsnameowns and that the declaration no longer names, in the same transaction and lock, and deletes the row.driftlists each such object that the database still stores as a leftover (Find the drift).- On Postgres and SQL Server, the triggers, the views and the indexes go before the declared objects change. On Postgres, a comment whose object stays gets
COMMENT … IS NULL. The tables go after the declared tables are rebuilt or made, then the functions and procedures, and the sequences (#7156). A removed table whose name a declared object takes goes first. A schema stays:applydeletes its row only, because a drop takes each object in it. For the order on SQLite, see Apply on SQLite. - A declared table that drops its foreign key to a removed table does not block the drop: the rebuild or the replace takes the old foreign key away first, as a schema compare drops a foreign key before the table it references (Redgate SQL Compare). Before #7156, Postgres failed with
2BP01and SQL Server with3726, and the transaction rolled back. - With
rows: 'keep',applycounts each table that it would drop, before any change; on Postgres and SQL Server, it locks the table first. An empty one drops. One with rows makesapplythrowSchemaDriftErrorbefore any change:objectsholds{ name, kind: 'table', drift: 'removed', rows }for each, and the message ends withMove the rows, or apply with rows: 'replace'.Withrows: 'replace', the table drops with its rows. - On Postgres and SQL Server, a declared view that reads a dropped object goes first, and
applymakes it from its statement: on Postgres any view, on SQL Server a schema-bound one. On SQL Server, a view that is not schema-bound getssp_refreshviewat the end. Any other object that depends on a dropped one (a view of the host, a foreign key of a declared table) makesapplyfail with the error of the database, and the transaction rolls back. - On SQLite, a table that stays and still refers to a removed table makes
applythrow<table> references <removed>, which the declaration no longer names.SQLite would otherwise delete the rows that refer to it, underON DELETE CASCADE, or fail. SQLite drops a table that a view or a trigger reads, so a view that compiled before the drop and does not compile after it makesapplythrowThe removal of <tables> breaks the view <view>., and a table whose trigger writes compiled before and do not compile after makes it throw the error of SQLite. Nothing changes. - An object that no ledger row of the
nameowns is never dropped this way. - On Postgres and SQL Server, a ledger row that a version before the owner wrote has none. The first
applyof a declaration that names its object claims it, also when nothing drifted. A row that no declaration names stays without an owner, and its object stays. - On SQLite, the first
applymakes the ledger and writes a row for each declared object, also when nothing drifted. Thus it claims the objects that a version before the ledger made. An object of such a version that no declaration names gets no row, soapplynever drops it. Drop it with your own SQL. - A renamed
nameis a new owner:applyrefuses the objects of the old one.
Describe the objects
On Postgres, a declaration describes its objects with COMMENT ON statements, one element each, after the statement of the object (ADR 0017). Atlas keeps the same fact as the comment attribute of a table, a column and an index.
export const warehouse = new PostgresDeclaration(
[
'CREATE SCHEMA _warehouse',
"COMMENT ON SCHEMA _warehouse IS 'The tables that elt keeps.'",
`CREATE TABLE _warehouse.extraction_coverage (
stream text PRIMARY KEY,
target_schema text NOT NULL
)`,
"COMMENT ON TABLE _warehouse.extraction_coverage IS 'One row for each stream that elt extracts.'",
"COMMENT ON COLUMN _warehouse.extraction_coverage.target_schema IS 'The schema that the stream lands in.'",
],
{ name: 'elt-postgresql/warehouse', ledgerSchema: '_warehouse' },
);- The kinds are
TABLE,VIEW,COLUMN,INDEX,SEQUENCE,FUNCTION,PROCEDUREandSCHEMA. Each name carries its schema; a column is<schema>.<table>.<column>, and an index takes the schema of its table. A function or a procedure may give its arguments:COMMENT ON FUNCTION app.twice(int) IS '…'. - The text is a string or a dollar-quoted string. The constructor refuses
IS NULL: to remove a description, remove its element and runCOMMENT … IS NULLyourself, as you drop a removed object. - The constructor refuses a comment whose object no earlier statement makes, of the same kind and name, or a table or a view for a column. It refuses two comments on one target. A column that the table does not have fails at
apply, with the error of Postgres. - Each comment has a ledger row of its own, of kind
comment. The report names it by the kind and the name of its target:{ name: 'column _warehouse.extraction_coverage.target_schema', kind: 'comment', drift: 'stale' }. - A comment is missing when its object has no description, and stale when its text changed.
applyruns itsCOMMENTstatement again and does not touch the object, so a new description never rebuilds a table, also withrows: 'keep'. - Each time
applymakes an object from its statement (new, replaced, rebuilt, or a declared index or view made again), it runs the comments of the object and its columns again, because Postgres drops a description with its object. - SQL Server and SQLite declarations do not describe their objects. SQL Server keeps descriptions as
MS_Descriptionextended properties; their support waits for backlog #6949. SQLite has no comments of objects.
Compose another package's declaration
A package can keep its tables beside the tables of a package that it uses, in one schema with one ledger. Its declaration then takes the other declaration's statements: the statements as that package gave them, in order. elt's warehouse holds the tables of its checkpoint store:
import { PostgresCheckpointStore } from '@zukhruf/checkpoint/postgres';
import { PostgresDeclaration } from '@zukhruf/schema-drift/postgres';
export const warehouse = new PostgresDeclaration(
[
'CREATE SCHEMA _warehouse',
`CREATE TABLE _warehouse.extraction_coverage (
stream text PRIMARY KEY,
target_schema text NOT NULL
)`,
...PostgresCheckpointStore.declaration('_warehouse').statements,
],
{ name: 'elt-postgresql/warehouse', ledgerSchema: '_warehouse' },
);- The host applies
warehouseonce. The checkpoint store's owncheckthen passes, because each of its statements has its ledger row in the same ledger schema. - The composed objects belong to
warehouse'sname, as the objects of a subchart belong to the Helm release of its parent chart. Anapplyof the checkpoint store's own declaration then refuses them, and awarehousethat stops composing them drops them. - Two declarations of one package that replace each other in one ledger (a variant with triggers, say) share one
name, so anapplyof either drops what the other added. statementsis a frozen copy. A change to the array that the package gave does not change the declaration.- The constructor refuses two statements of one object, as for any declaration:
A declaration names each object once: …. On SQLite, the error of SQLite:table … already exists.
Work on Postgres
@zukhruf/schema-drift/postgres imports no driver. The host gives a PostgresSession over its own driver. The work that apply gives to transaction(work) never goes on after a failed query: it asks the catalog whether the ledger exists, and does not try it. Thus a session may end the transaction on any failed query, as the fromPglite adapter of pg-boss and sql.begin of postgres.js do. The example writes one over node-postgres, makes the table as an older elt did, and repairs it.
import pg from 'pg';
import {
PostgresDeclaration,
type PostgresSession,
} from '@zukhruf/schema-drift/postgres';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
// The session over node-postgres: queries on the pool, and a transaction on
// one client of it.
const session: PostgresSession = {
query: async (sql, parameters) =>
(await pool.query(sql, [...parameters])).rows,
transaction: async (work) => {
const client = await pool.connect();
try {
await client.query('BEGIN');
const inner: PostgresSession = {
query: async (sql, parameters) =>
(await client.query(sql, [...parameters])).rows,
transaction: async (nested) => nested(inner),
};
await work(inner);
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
},
};
// An older elt made the table with IF NOT EXISTS, without reloading.
await pool.query(`CREATE SCHEMA _warehouse;
CREATE TABLE IF NOT EXISTS _warehouse.extraction_coverage (stream text PRIMARY KEY, target_schema text NOT NULL);
INSERT INTO _warehouse.extraction_coverage VALUES ('orders', 'raw')`);
const warehouse = new PostgresDeclaration(
[
'CREATE SCHEMA _warehouse',
`CREATE TABLE _warehouse.extraction_coverage (
stream text PRIMARY KEY,
target_schema text NOT NULL,
reloading boolean NOT NULL DEFAULT false
)`,
'CREATE INDEX extraction_coverage_target ON _warehouse.extraction_coverage (target_schema)',
],
{ name: 'elt-postgresql/warehouse', ledgerSchema: '_warehouse' },
);
console.log(await warehouse.drift(session));
try {
await warehouse.check(session);
} catch (error) {
console.log(String(error));
}
await warehouse.apply(session, { rows: 'keep' });
console.log(await warehouse.drift(session));
console.log(
(await pool.query('SELECT * FROM _warehouse.extraction_coverage')).rows,
);
await pool.end();Output:
{
drift: 'stale',
objects: [
{
name: '_warehouse.extraction_coverage',
kind: 'table',
drift: 'stale'
},
{
name: '_warehouse.extraction_coverage_target',
kind: 'index',
drift: 'missing'
}
],
leftovers: []
}
SchemaDriftError: The database does not store the declaration as declared:
_warehouse.extraction_coverage (table) is stale.
_warehouse.extraction_coverage_target (index) is missing.
Apply the declaration.
{ drift: 'fits', objects: [], leftovers: [] }
[ { stream: 'orders', target_schema: 'raw', reloading: false } ]Work on SQL Server
@zukhruf/schema-drift/sqlserver imports no driver. The host gives a SqlServerSession over its own driver. The example writes one over mssql, makes the table as an older elt did, and repairs it.
import mssql from 'mssql';
import {
SqlServerDeclaration,
type SqlServerSession,
} from '@zukhruf/schema-drift/sqlserver';
const pool = await new mssql.ConnectionPool(
process.env.DATABASE_URL ?? '',
).connect();
const bind = (
request: mssql.Request,
parameters: Readonly<Record<string, unknown>>,
) => {
for (const [name, value] of Object.entries(parameters))
request.input(name, value);
return request;
};
// The session over mssql: queries on the pool, and a transaction of the pool.
// apply runs with XACT_ABORT on, so an error rolls the transaction back in
// the server, and mssql then refuses a second rollback.
const session: SqlServerSession = {
query: async (sql, parameters) =>
(await bind(pool.request(), parameters).query(sql)).recordset ?? [],
transaction: async (work) => {
const transaction = new mssql.Transaction(pool);
let aborted = false;
transaction.on('rollback', (byServer: boolean) => {
aborted = byServer;
});
await transaction.begin();
try {
const inner: SqlServerSession = {
query: async (sql, parameters) =>
(await bind(transaction.request(), parameters).query(sql))
.recordset ?? [],
transaction: async (nested) => nested(inner),
};
await work(inner);
await transaction.commit();
} catch (error) {
if (!aborted) await transaction.rollback();
throw error;
}
},
};
// An older elt made the table behind a guard, without reloading.
await pool.query('CREATE SCHEMA _warehouse');
await pool.query(`IF OBJECT_ID(N'_warehouse.extraction_coverage', N'U') IS NULL
CREATE TABLE _warehouse.extraction_coverage (stream nvarchar(200) PRIMARY KEY, target_schema nvarchar(200) NOT NULL);
INSERT INTO _warehouse.extraction_coverage VALUES (N'orders', N'raw')`);
const warehouse = new SqlServerDeclaration(
[
'CREATE SCHEMA _warehouse',
`CREATE TABLE _warehouse.extraction_coverage (
stream nvarchar(200) PRIMARY KEY,
target_schema nvarchar(200) NOT NULL,
reloading bit NOT NULL DEFAULT 0
)`,
'CREATE INDEX extraction_coverage_target ON _warehouse.extraction_coverage (target_schema)',
],
{ name: 'elt-sqlserver/warehouse', ledgerSchema: '_warehouse' },
);
console.log(await warehouse.drift(session));
try {
await warehouse.check(session);
} catch (error) {
console.log(String(error));
}
await warehouse.apply(session, { rows: 'keep' });
console.log(await warehouse.drift(session));
console.log(
(await pool.query('SELECT * FROM _warehouse.extraction_coverage')).recordset,
);
await pool.close();Output:
{
drift: 'stale',
objects: [
{
name: '_warehouse.extraction_coverage',
kind: 'table',
drift: 'stale'
},
{
name: '_warehouse.extraction_coverage.extraction_coverage_target',
kind: 'index',
drift: 'missing'
}
],
leftovers: []
}
SchemaDriftError: The database does not store the declaration as declared:
_warehouse.extraction_coverage (table) is stale.
_warehouse.extraction_coverage.extraction_coverage_target (index) is missing.
Apply the declaration.
{ drift: 'fits', objects: [], leftovers: [] }
[ { stream: 'orders', target_schema: 'raw', reloading: false } ]- The qualified name of an index has its table:
_warehouse.extraction_coverage.extraction_coverage_target. SQL Server keeps an index name unique only in its table. - The catalog compares names by the collation of the database, as SQL Server does.
applyruns each declared statement throughsp_executesql, soCREATE VIEW,CREATE FUNCTION,CREATE PROCEDURE,CREATE TRIGGERandCREATE SCHEMAeach run as the only statement of their batch. The body of a function, a procedure or a trigger can hold statements of its own, with;between them. Each other kind is one statement.- The constructor refuses a
GOon its own line, as two statements, and a statement that starts withIF, such asIF OBJECT_ID(…) IS NULL CREATE TABLE …, asIF NOT EXISTS: the guard hides a stale object behind its name. applystarts each batch of its transaction withSET XACT_ABORT ON. ASETinsidesp_executesqlends with it, and drivers such as mssql send each query with parameters throughsp_executesql. Thus an error rolls the whole transaction back in the server. A session must then not roll back again: mssql refuses a second rollback withEABORTand hides the error of the database. The example listens for therollbackevent of the transaction.- Inside the lock,
applyreads the ledger withXACT_ABORToff: under it, error 208 of a missing ledger would end the transaction and its lock.
Keep the rows on SQL Server
applyrenames the old table away withsp_rename, and renames away each of its constraints (primary key, unique, default, check, foreign key), also those that SQL Server named. A constraint name is unique in its schema; an index name is unique only in its table, so the indexes of the old table keep their names.- SQL Server refuses to rename or drop a table that a schema-bound view reads (errors 15336, 3729).
applydrops the schema-bound views that read the table, and makes them again after it: a declared view from its statement, any other view fromsys.sql_modules, with theANSI_NULLSandQUOTED_IDENTIFIERthat it was made under. A view that is not schema-bound stays, andapplyrunssp_refreshviewon it, so aSELECT *view sees the declared columns. - It makes again the foreign keys of other tables
WITH CHECK, with theirON DELETEandON UPDATE. Such a foreign key that was disabled is disabled again. A declared trigger is made from its statement, enabled, afterDROP TABLEof the old table, which holds the trigger's name in the schema until then. - It copies with
SET IDENTITY_INSERT … ONwhen the declared table has an identity column that both tables have. It does not copy a computed column, arowversioncolumn or a column of a temporal period. - A stale sequence with
rows: 'keep'restarts at itslast_used_valueplus the increment of the declared sequence. A sequence that never gave a value starts at theSTART WITHof its statement.
Work on SQLite
@zukhruf/schema-drift/sqlite is @zukhruf/sqlite-drift, moved in with its behaviour. It uses only node:sqlite.
import { mkdtempDisposable } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { SqliteDeclaration } from '@zukhruf/schema-drift/sqlite';
import { open } from '@zukhruf/sqlite-open';
await using scratch = await mkdtempDisposable(join(tmpdir(), 'drift-'));
using database = open(join(scratch.path, 'app.sqlite'));
// An earlier version made the table without failed_at.
database.exec(`CREATE TABLE failures (directory TEXT PRIMARY KEY, error TEXT NOT NULL);
INSERT INTO failures VALUES ('/data/notes', 'denied')`);
const failures = new SqliteDeclaration(
[
'CREATE TABLE failures (directory TEXT PRIMARY KEY, error TEXT NOT NULL, failed_at TEXT NOT NULL)',
'CREATE INDEX failures_at ON failures (failed_at)',
],
{ name: '@acme/scanner/failures' },
);
console.log(failures.drift(database));
try {
failures.check(database);
} catch (error) {
console.log(String(error));
}
failures.apply(database, { rows: 'replace' });
console.log(failures.drift(database));
console.log(database.prepare('SELECT count(*) AS rows FROM failures').get());Output:
{
drift: 'stale',
objects: [
{ name: 'failures', kind: 'table', drift: 'stale' },
{ name: 'failures_at', kind: 'index', drift: 'missing' }
],
leftovers: []
}
SchemaDriftError: The database does not store the declaration as declared:
failures (table) is stale.
failures_at (index) is missing.
Apply the declaration.
{ drift: 'fits', objects: [], leftovers: [] }
[Object: null prototype] { rows: 0 }A SQLite declaration compares the text that SQLite stores
new SqliteDeclaration(statements, { name, devDatabase })makes the objects once in the dev database, and keeps the text that SQLite stores for each one. ADR 0001 tells why.- The dev database is an empty database in memory.
devDatabaseis an optional function that opens it. When there is nodevDatabase, the package opensopen(':memory:')of@zukhruf/sqlite-open. See Extensions and functions. - A statement can also add owned objects to
sqlite_schema: the shadow tables of a virtual table,sqlite_sequenceforAUTOINCREMENT, and the index of aUNIQUEcolumn. SQLite makes and drops an owned object with its declared object.drift,checkandapplyexamine only the declared objects. ADR 0004 tells why. - The kind of an object is the
typeofsqlite_schema(table,index,view,trigger), andvirtual tablefor aCREATE VIRTUAL TABLE. driftandcheckonly read, so they also work on a database opened read-only.- 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
driftcompares 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 storescreate table a (x INT)asCREATE 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 tells why. - A change of meaning with no change of text is not drift. When the meaning of a column changes, change its name too.
- SQLite takes names that are different only in ASCII case as one name.
Apply on SQLite
apply(database, { rows })drops each index and trigger on a declared table that the declaration does not name, with eachrowsoption. An index of aPRIMARY KEYor aUNIQUE(sqlite_autoindex_*, originpkoruinpragma_index_list) is the table's own and stays.applydoes nothing when the drift isfits, no such index or trigger is left, and the ledger holds a row of thenamefor each declared object and none for an object that the declaration no longer names. Then it writes nothing.- When no stored object is stale,
applymakes each missing object, and the other objects keep their rows. - With
rows: 'replace', when one stored object is stale,applyreplaces every object of the declaration, and their rows are gone. ADR 0002 tells why. - With
rows: 'keep',applyrebuilds each stale table and keeps its rows. See Keep the rows on SQLite. applydoes not drop a table or a view that the declaration does not name, nor an index or a trigger on such a table, unless a ledger row of itsnameowns it.- 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,applyrecords which tables with triggers compile aDELETE, anINSERTand anUPDATE. It finds these tables insqlite_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,applyfails with the error of SQLite. This check is the same withrows: 'replace'androws: 'keep'. A trigger that did not compile before does not makeapplyfail. - In its transaction,
applyworks in this order:- It refuses, before any change, a declared object whose ledger row another
nameowns. - With
rows: 'keep', it counts the rows of each removed table, also a virtual table. A table with rows makes it throwSchemaDriftErrorwith the driftremoved, before any change. - It drops each removed trigger, view and index. One on a removed table goes with its table.
- It drops each index and trigger on a declared table that the declaration does not name.
- It makes, replaces or rebuilds the declared objects, as
rowssays. - It drops each removed table, the tables that refer to another removed table first. A table that stays and still refers to one makes it throw. A view that compiled before and does not compile now makes it throw.
- It compiles the writes of each table with triggers, as above.
- It makes the ledger when it is missing, deletes the rows of the removed objects and of each object whose kind changed, and writes a row of its
namefor each declared object (INSERT … ON CONFLICT).
- It refuses, before any change, a declared object whose ledger row another
- A trigger has a namespace of its own. Tables, indexes and views share one. Thus a table that becomes a view or a virtual table under its name is stale, not removed, and its ledger row takes the new kind.
- In a transaction of the caller,
applyworks in a savepoint, and a rollback of the caller removes its changes. With no transaction,applywrites in its ownBEGIN IMMEDIATEtransaction.@zukhruf/sqlite-transactiondoes this work, so when SQLite ends the transaction itself,applythrows the original error.
Keep the rows on SQLite
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:
- It renames the stored table to a temporary name, with
PRAGMA legacy_alter_tableon. Thus the references of other tables, views and triggers stay on the name of the table. - It makes the table from its declared text, so SQLite stores the declared text.
- 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 KEYcolumn keeps its own values. When the declared table hasAUTOINCREMENT, it keeps the largest id that the old table gave, so the id of a deleted row is not given again. - It drops the old table. The declared indexes and triggers on the table are made when
applymakes the missing objects; the others were dropped before the rebuild. - It runs
PRAGMA foreign_key_check. When a kept row breaks a foreign key,applyfails. - After it makes the missing objects, it compiles a
DELETE, anINSERTand anUPDATEof each rebuilt table, and runs no row. SQLite does not examine the body of a trigger atCREATE. It examines the body when it compiles a statement that fires the trigger. When a trigger on the table names a dropped column,applyfails with the error of SQLite. The check of the triggers on other tables comes after this step. See Apply on SQLite. - It compiles each view. Before the rebuilds, it records which views compile. When a view compiled before and does not compile now,
applyfails. A view that did not compile before does not makeapplyfail.
ADR 0003 tells why.
import { mkdtempDisposable } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { SqliteDeclaration } from '@zukhruf/schema-drift/sqlite';
import { open } from '@zukhruf/sqlite-open';
await using scratch = await mkdtempDisposable(join(tmpdir(), 'drift-'));
using database = open(join(scratch.path, 'app.sqlite'));
// An earlier version made runs without status. Cases refer to runs.
database.exec(`CREATE TABLE runs (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE cases (run INTEGER NOT NULL REFERENCES runs (id) ON DELETE CASCADE);
INSERT INTO runs VALUES (1, 'nightly');
INSERT INTO cases VALUES (1)`);
const runs = new SqliteDeclaration(
[
"CREATE TABLE runs (id INTEGER PRIMARY KEY, name TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'done')",
],
{ name: '@acme/evals/runs' },
);
console.log(runs.drift(database).drift);
runs.apply(database, { rows: 'keep' });
console.log(runs.drift(database).drift);
console.log(database.prepare('SELECT * FROM runs').all());
console.log(database.prepare('SELECT count(*) AS cases FROM cases').get());Output:
stale
fits
[ [Object: null prototype] { id: 1, name: 'nightly', status: 'done' } ]
[Object: null prototype] { cases: 1 }- A column that only the declaration has gets its default.
- A column that only the stored table has is discarded, with its values.
applydoes 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 beforeapply.applydoes not fill values and does not remove rows. When a stored row does not fit the declaration (NOT NULL, CHECK, a foreign key, STRICT),applyfails 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 beforeapply.- When foreign keys are on and a table refers to a stale table (also the stale table to itself),
applymust turn foreign keys off. SQLite ignoresPRAGMA foreign_keysin a transaction. Thusapplyturns foreign keys off before its own transaction, and on again after it. In a transaction of the caller,applyfails before it changes the database. Callapplyoutside a transaction, or turn foreign keys off before it. - When no table refers to the stale table,
applyalso works in a transaction of the caller, with foreign keys on. - After a rebuild,
PRAGMA legacy_alter_tablehas its old value again, also whenapplyfails. applydoes 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,applyfails before it changes the database. Give the virtual table its own declaration, apply that one withrows: 'replace', and fill it again afterapply.
Extensions and functions
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 tells why.
import { mkdtempDisposable } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { DatabaseSync } from 'node:sqlite';
import * as sqliteVec from 'sqlite-vec';
import { SqliteDeclaration } from '@zukhruf/schema-drift/sqlite';
import { open } from '@zukhruf/sqlite-open';
function openWithVectors(path: string): DatabaseSync {
const database = open(path, { allowExtension: true });
database.loadExtension(sqliteVec.getLoadablePath());
return database;
}
await using scratch = await mkdtempDisposable(join(tmpdir(), 'drift-'));
using database = openWithVectors(join(scratch.path, 'app.sqlite'));
const vectors = new SqliteDeclaration(
['CREATE VIRTUAL TABLE vectors USING vec0(embedding float[4])'],
{
name: '@acme/search/vectors',
devDatabase: () => openWithVectors(':memory:'),
},
);
console.log(vectors.drift(database).drift);
vectors.apply(database, { rows: 'replace' });
console.log(vectors.drift(database).drift);Output:
missing
fits- The dev database must be empty when the declaration starts. When it has an object,
new SqliteDeclarationfails. new SqliteDeclarationcloses the dev database, also when it fails. Do not use the connection after you give it.- The target database must load the same modules. When it does not,
applyfails with the error of SQLite, for exampleno such module: vec0.driftandcheckread onlysqlite_schema, so they still give the drift.
Write a SQLite declaration
- 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.
- With
rows: 'replace', give each table its own declaration when it must keep its rows while another table changes.
What each call does in the database
| Call | What happens underneath |
| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| new SqliteDeclaration | Runs each statement once in the dev database, and keeps the text that SQLite stores for each declared object. |
| new PostgresDeclaration, new SqlServerDeclaration | Reads the kind and the qualified name of each statement from its head, and computes its checksum. Opens no connection. |
| SQLite drift, check | Reads sqlite_schema of the target. When the ledger exists, also reads the ledger rows of the name. |
| Postgres drift, check | One SELECT that joins the declared names and checksums (as parameters) to the catalog (pg_class, pg_proc, pg_namespace, pg_attribute, pg_description, pg_trigger) and to the ledger, whatever the number of declared objects. The same SELECT lists the leftovers. When the ledger table does not exist (42P01), one SELECT of the catalog more. When the ledger has no owner column (42703), one SELECT with the ledger more, and no leftovers. |
| SQL Server drift, check | One SELECT that joins the declared names and checksums to sys.objects, sys.indexes, sys.triggers, sys.schemas, sys.sequences and the ledger, whatever the number of declared objects. The same SELECT lists the leftovers. When the ledger table does not exist (error 208), one SELECT of the catalog more. When the ledger has no owner column (error 207), one SELECT with the ledger more, and no leftovers. |
| SQLite apply | The reads of drift, and of the indexes and triggers to drop, outside a transaction; nothing more when they show nothing to do. Else a savepoint in the caller's transaction, or its own BEGIN IMMEDIATE: the ledger rows of the declared objects, count(*) of each removed table with rows: 'keep', the steps of sqlite-drift, the DROP of each removed object, CREATE TABLE zukhruf_schema_drift when it is missing, and the ledger DELETE and INSERT … ON CONFLICT. |
| Postgres apply
