npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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.

Readme

@zukhruf/schema-drift

Design accepted 2026-12-01. The root entry point, ./sqlite, ./postgres and ./sqlserver are 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-drift

The 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 replace

The package checks it when it opens, and runs no DDL:

await warehouse.check(session); // throws SchemaDriftError when an object is missing or stale

session 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.
  • name is 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 gets TypeError.
  • 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.
  • 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, not extraction_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 SCHEMA with AUTHORIZATION or 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 devDatabase option of sqlite-drift, beside name: 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, 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 apply makes the table and the function first.
  • drift reads pg_trigger (an internal trigger is never a declared one) or sys.triggers on 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). apply drops 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).
  • apply drops each trigger on a declared table or view that the declaration does not declare, as sqlpackage's DropDmlTriggersNotInSource does. 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: [] }
  • 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.
  • objects lists each declared object that is missing or stale, in the order of the declaration. It is empty when the drift is fits.
  • leftovers lists each object that the ledger says the name owns, that the declaration no longer names, and that the database still stores: { name, kind }, by kind, then name (#7155). The next apply drops each one, or refuses a table with rows under rows: 'keep' (Own the objects). terraform plan lists "to destroy" apart from "to change" the same way.
  • A leftover does not change drift, which is about the declared objects only. check does not throw for a leftover, and SchemaDriftError never carries one: a leftover breaks no query of the package, and check runs in processes that never apply (ADR 0007).
  • An index or a trigger on a declared table that no ledger row of the name owns is not a leftover, though apply drops it (Apply a declaration). An object whose ledger row stays but that the database no longer stores is not a leftover either: apply only deletes its row. A schema and a Postgres object comment are never leftovers.
  • On Postgres and SQL Server, drift reads the leftovers in its one query. A ledger that a version before the owner column wrote gives no leftovers.
  • drift only 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 an N'…' 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 apply repairs a database that older code made with IF NOT EXISTS.
  • 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.

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):

  1. apply opens one transaction on the session. On SQL Server it runs SET XACT_ABORT ON and BEGIN TRANSACTION.
  2. It takes the lock of the package, which the transaction owns, and reads the ledger again inside the lock (ADR 0014).
  3. It adds the owner column to a ledger that a version before it wrote, and refuses, before any change, a declared object other than a schema whose ledger row another name owns.
  4. In one statement, it deletes the ledger rows that its name owns and the declaration no longer names, and sets its name on each row of a declared object that has no owner. With rows: '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.
  5. 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 name owns.
  6. It makes the ledger table when it is missing, after the declared schemas.
  7. It makes each missing object from its statement.
  8. 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 apply drops 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.
  9. It replaces or rebuilds each stale table, as rows says (see below), and each stale sequence.
  10. On Postgres, it runs the COMMENT statement of each missing or stale object comment, and of each comment whose object it made.
  11. 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.
  12. It writes the ledger row of each object and each object comment that it made, with the checksum of its statement and its name as 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 apply read 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, apply fails 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 from pg_get_triggerdef. A SQL Server DML trigger cannot be schema-bound, so it does not stop the drop. A default, a CHECK, a computed column or an index expression that calls the function still makes apply fail 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):

  1. It reads, from the catalog of the target, the views that depend on the table and the foreign keys that refer to it.
  2. It drops those views and foreign keys.
  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.
  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.
  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).
  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.
  7. 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.
  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.

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).
  • 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.
  • 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.
  • 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 that apply makes 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):

  • apply refuses, before any change, a declaration that names an object whose ledger row another name owns: 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 apply takes a schema whose row another name owns. The row keeps the name whose apply made the schema. SQLite has no schema statement: the database file holds the ledger.
  • apply drops each object whose ledger row its name owns and that the declaration no longer names, in the same transaction and lock, and deletes the row. drift lists 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: apply deletes 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 2BP01 and SQL Server with 3726, and the transaction rolled back.
  • With rows: 'keep', apply counts 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 makes apply throw SchemaDriftError before any change: objects holds { name, kind: 'table', drift: 'removed', rows } for each, and the message ends with Move the rows, or apply with rows: 'replace'. With rows: 'replace', the table drops with its rows.
  • On Postgres and SQL Server, a declared view that reads a dropped object goes first, and apply makes 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 gets sp_refreshview at the end. Any other object that depends on a dropped one (a view of the host, a foreign key of a declared table) makes apply fail 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 apply throw <table> references <removed>, which the declaration no longer names. SQLite would otherwise delete the rows that refer to it, under ON 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 makes apply throw The 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 name owns is never dropped this way.
  • On Postgres and SQL Server, a ledger row that a version before the owner wrote has none. The first apply of 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 apply makes 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, so apply never drops it. Drop it with your own SQL.
  • A renamed name is a new owner: apply refuses 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, PROCEDURE and SCHEMA. 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 run COMMENT … IS NULL yourself, 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. apply runs its COMMENT statement again and does not touch the object, so a new description never rebuilds a table, also with rows: 'keep'.
  • Each time apply makes 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_Description extended 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 warehouse once. The checkpoint store's own check then passes, because each of its statements has its ledger row in the same ledger schema.
  • The composed objects belong to warehouse's name, as the objects of a subchart belong to the Helm release of its parent chart. An apply of the checkpoint store's own declaration then refuses them, and a warehouse that 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 an apply of either drops what the other added.
  • statements is 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.
  • apply runs each declared statement through sp_executesql, so CREATE VIEW, CREATE FUNCTION, CREATE PROCEDURE, CREATE TRIGGER and CREATE SCHEMA each 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 GO on its own line, as two statements, and a statement that starts with IF, such as IF OBJECT_ID(…) IS NULL CREATE TABLE …, as IF NOT EXISTS: the guard hides a stale object behind its name.
  • apply starts each batch of its transaction with SET XACT_ABORT ON. A SET inside sp_executesql ends with it, and drivers such as mssql send each query with parameters through sp_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 with EABORT and hides the error of the database. The example listens for the rollback event of the transaction.
  • Inside the lock, apply reads the ledger with XACT_ABORT off: under it, error 208 of a missing ledger would end the transaction and its lock.

Keep the rows on SQL Server

  • apply renames the old table away with sp_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). apply drops the schema-bound views that read the table, and makes them again after it: a declared view from its statement, any other view from sys.sql_modules, with the ANSI_NULLS and QUOTED_IDENTIFIER that it was made under. A view that is not schema-bound stays, and apply runs sp_refreshview on it, so a SELECT * view sees the declared columns.
  • It makes again the foreign keys of other tables WITH CHECK, with their ON DELETE and ON UPDATE. Such a foreign key that was disabled is disabled again. A declared trigger is made from its statement, enabled, after DROP TABLE of the old table, which holds the trigger's name in the schema until then.
  • It copies with SET IDENTITY_INSERT … ON when the declared table has an identity column that both tables have. It does not copy a computed column, a rowversion column or a column of a temporal period.
  • A stale sequence with rows: 'keep' restarts at its last_used_value plus the increment of the declared sequence. A sequence that never gave a value starts at the START WITH of 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. 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.
  • 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 tells why.
  • The kind of an object is the type of sqlite_schema (table, index, view, trigger), and virtual table for a CREATE VIRTUAL TABLE.
  • drift and check only 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 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 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 each rows option. An index of a PRIMARY KEY or a UNIQUE (sqlite_autoindex_*, origin pk or u in pragma_index_list) is the table's own and stays.
  • apply does nothing when the drift is fits, no such index or trigger is left, and the ledger holds a row of the name for each declared object and none for an object that the declaration no longer names. Then it writes nothing.
  • When no stored object is stale, apply makes each missing object, and the other objects keep their rows.
  • With rows: 'replace', when one stored object is stale, apply replaces every object of the declaration, and their rows are gone. ADR 0002 tells why.
  • With rows: 'keep', apply rebuilds each stale table and keeps its rows. See Keep the rows on SQLite.
  • apply does 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 its name owns 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, 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.
  • In its transaction, apply works in this order:
    1. It refuses, before any change, a declared object whose ledger row another name owns.
    2. With rows: 'keep', it counts the rows of each removed table, also a virtual table. A table with rows makes it throw SchemaDriftError with the drift removed, before any change.
    3. It drops each removed trigger, view and index. One on a removed table goes with its table.
    4. It drops each index and trigger on a declared table that the declaration does not name.
    5. It makes, replaces or rebuilds the declared objects, as rows says.
    6. 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.
    7. It compiles the writes of each table with triggers, as above.
    8. 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 name for each declared object (INSERT … ON CONFLICT).
  • 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, 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 does this work, so when SQLite ends the transaction itself, apply throws 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:

  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.
  2. It makes the table from its declared text, so SQLite stores the declared text.
  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.
  4. It drops the old table. The declared indexes and triggers on the table are made when apply makes the missing objects; the others were dropped before the rebuild.
  5. It runs PRAGMA foreign_key_check. When a kept row breaks a foreign key, apply fails.
  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.
  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.

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.
  • 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.
  • 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.
  • 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.
  • When no table refers to the stale table, apply also works in a transaction of the caller, with foreign keys on.
  • After a rebuild, PRAGMA legacy_alter_table has its old value again, also when apply fails.
  • 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.

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 SqliteDeclaration fails.
  • new SqliteDeclaration closes 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, 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.

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