Repository navigation
NTNT v0.6.5 — Broader database migration coverage and safer PostgreSQL replay
0.6.5 lets ntnt db plan, migrate and verify more of the schemas real
applications use, on SQLite and on PostgreSQL, and changes how PostgreSQL
replay uses the scratch database. If you use ntnt db with PostgreSQL, read
"Upgrading from 0.6.4" below before you upgrade: scratch has new requirements.
In short
- More SQLite schemas work. Tables with
AUTOINCREMENT(the default
primary key in Django and Rails), SQLite's built-in functions (the JSON
functions,hex,randombloband the rest), the statisticsANALYZE
writes, andWITH RECURSIVEnow plan, migrate and verify. - More PostgreSQL schemas work. Enums, domains, composite types, trusted
extensions such as citext and pg_trgm, user-defined operators andEXCLUDE
constraints are covered. They used to leave every planunknown. - Extensions a superuser installs can be declared. List them in
[databases.<name>] extensions = [...], in any schema,publicincluded,
and plans compare them instead of stopping on them. - Checks behave as your application does. A
requires,ensuresor
adoption check is refused before it runs when PostgreSQL could pick a
different comparison operator than the application would (on acitext
column, for example), or when it reads a view that writes, such as one that
callsnextval. - Replay commits each migration on scratch. A history that adds an enum
value withALTER TYPE ... ADD VALUEand uses it in the next migration now
plans on PostgreSQL 16. Scratch is cleaned up whatever the outcome, and the
next plan cleans up after a replay that was killed, when it can prove the
leftovers are that replay's. - PostgreSQL refusals name their cause. A check that row-level security
would block, and a migration that creates an untrusted extension, are named
with what to do, instead of failing with a bare SQLSTATE 42501. - Restored databases verify. A database restored with
pg_dumpand
pg_restoreno longer reports drift (#460). - Security.
cookieis updated to 0.18.3 for RUSTSEC-2026-0594.
Upgrading from 0.6.4
-
PostgreSQL scratch has new requirements. Check them before upgrading:
- The scratch role holds no privileges on objects it does not own, other
than onpublic: no grants on other databases, tablespaces,
configuration parameters or system objects. Cleanup'sDROP OWNEDwould
revoke them. track_countsis on, as it is by default.- Before replay, the scratch role owns nothing in scratch but
public,
such as a large object or a publication.DROP OWNEDwould drop it.
plan,statusandverifyrefuse a scratch that misses one of the first
two withDB_SCRATCH_UNSAFE, and one that misses the third with
DB_SCRATCH_NOT_EMPTY, and change nothing. See
Disposable replay and its boundary. - The scratch role holds no privileges on objects it does not own, other
-
Keep each scratch database to itself. Replay now commits to scratch
while it runs, and a replay that is killed leaves its objects there, under
the marker schema_ntnt_replay, until the next plan, status or verify
cleans them up.status,plan,verifyandmigraterefuse a target
that holds that marker withDB_TARGET_IS_SCRATCH, reading and changing
nothing: some NTNT configuration names that database as its scratch. Give
that configuration a dedicated empty scratch database. -
Plan again once if your history's fingerprints changed. For a history
with values that 0.6.5 compares in their restored form (see "Restored
databases verify" below), a new plan recordscanonicalization_version: 2,
and its fingerprints andplan_digestdiffer from those 0.6.4 computed, so
the new plan needs approving. A plan that 0.6.4 saved still passes
--againstand migrates, because saved fingerprints are matched in both
forms. Every other history keepscanonicalization_version: 1, its
fingerprints and its plan digest. The ledger records no fingerprint, so
applied history is unaffected. -
Scripts that read
capabilitiesneed the new names. These keys of the
JSON reports'capabilitiesobject changed, withformat_versionstill 1:0.6.4 0.6.5 inspection.custom_types_external_dependencies_non_sql_routines:unknowninspection.enums_domains_composite_types_operators_exclusion_constraints:definition_fingerprintsandinspection.range_and_base_types_external_dependencies_non_sql_routines:unknowninspection.managed_schema_extensions:versioninspection.managed_schema_extensions:version_covers_membersoperations.transactional_script_replay:rollback_only_scratchoperations.transactional_script_replay:per_migration_commits_on_scratchcanonicalization_version: 1canonicalization_version: 2Capabilities feed no digest, so these changes alone change no plan.
-
Upgrade every user of one scratch database together. 0.6.5 takes a
lock on scratch for each replay, so plans, statuses and verifies on one
scratch database never interleave. 0.6.4 takes no replay lock, so its runs
do not wait for a 0.6.5 replay on the same scratch database. Upgrade every
machine and CI job that shares a scratch database at the same time. -
PostgreSQL plans take a little longer. Committing each migration and
cleaning up afterwards added about 0.4 to 0.8 seconds to each plan of a
41-migration history. This is indicative only: it was measured on
development builds. A history that adds one table per migration now stays
withinplan's replay deadline up to about 800 migrations, down from about
900.
ntnt db on PostgreSQL
Types, extensions, operators and constraints
- Enums, domains and composite types. A history that uses
CREATE TYPE ... AS ENUM,CREATE DOMAINor a composite type plans,
migrates and verifies. Each type is compared by its definition (an enum's
labels in order; a domain's base type,NOT NULL, default, collation and
constraints; a composite type's attributes), in the managed schema and in
schemas the history creates, and columns of these types are covered. An
out-of-bandALTER TYPE ... ADD VALUEor a changed domain constraint is
drift on the type. A domain whose constraints call a routine, or use an
operator, outside the managed scope that inspection does not compare is
uncovered. Any of these types used to leave every planunknownwith
DB_COVERAGE_INCOMPLETE(#430). - Trusted extensions in the managed schema. An extension such as pg_trgm,
citext, hstore or btree_gist installed in the managed schema is compared by
its name and version, which cover what it installs: types, functions,
aggregates, operators, operator classes and families, and casts. A
gin_trgm_opsindex or acitextcolumn plans and migrates, and citext's
implicit casts no longer stop every later migration. An out-of-band
ALTER EXTENSION ... UPDATEis drift on the extension. Any other custom
implicit or assignment cast still stops the next migration, now with
DB_CHECK_UNSUPPORTEDnaming the cast and the migration (#430). - Operators and operator classes. An operator's catalog key carries its
argument types (other:operator.===(integer,integer)) and an operator
class's its access method (other:operator_class.citext_ops USING btree), so
overloads, and citext's btree and hashcitext_ops, no longer collide. A
user-defined operator whose function is covered is covered. When two objects
still share a key,DB_CATALOG_AMBIGUOUSnames it and the migration that
made them (#430). EXCLUDEconstraints plan, migrate and verify, with built-in operator
classes or an extension's such as btree_gist (#430).- Restored databases verify. A database restored with
pg_dumpand
pg_restorebehaves like the one it was dumped from but stores some values
differently, andstatus,verifyandplanreported them asDB_DRIFT
until each was repaired by hand.BETWEEN,NOT BETWEEN,INlists of
columns and row comparisons nest anANDorORinside another, and a
restore merges one that comes first into the enclosing one: in CHECK
constraints (of tables and domains),EXCLUDEand index predicates, index
expressions, policies, column defaults and generated expressions, domain
defaults, views, triggers'WHEN, partition keys and SQL-standard routine
bodies, including bodies that name an argument by position ($1). And
partitions' PRIMARY KEY and UNIQUE constraints come back with
connoinheritset, which does nothing for them. Inspection now compares
both as a restore leaves them; a real change, such as another CHECK bound,
is still drift. Such histories get new fingerprints once (see "Upgrading
from 0.6.4"), andcapabilities.canonicalization_versionis now 2. See
Restored databases
(#460).
Catalogs that use none of these keep their fingerprints, so saved plans and
applied history stay valid.
Extensions a superuser installs
- Declared extensions.
[databases.<name>] extensions = ["postgres_fdw", "pg_stat_statements"]declares extensions that a superuser
installs in both the target and the scratch database, at one version and in
one schema, which may bepublicor any other schema but_ntntand
PostgreSQL's own. Inspection compares each by its version and schema, so a
mismatch between the two databases is drift; scratch may hold the extension
and what it owns, and one missing from scratch is refused by name;
migrations may keepCREATE EXTENSION IF NOT EXISTS, which then does
nothing. An undeclared extension outside the managed scope, such as a DBA's
pg_stat_statementsinpublic, still leaves the catalog uncovered, and
the diagnostic now says to declare it. Replay's cleanup, and its recovery
of a replay that never finished, keep the declared extensions. A privilege
a DBA grants the scratch role on what they install, such asUSAGEon
postgres_fdw's foreign-data wrapper, is refused by name with
DB_SCRATCH_UNSAFE, since cleanup'sDROP OWNEDwould revoke it; grant it
toPUBLICin the scratch database instead. The key is part of the plan
only when present, so manifests without it keep their plan digests (#430). - Foreign servers are inspected. A server a migration creates (with a
declared postgres_fdw) is covered asserver:<name>by its wrapper, owner,
privileges and options (shown only as a digest, since they hold host
names), so a superuser's out-of-bandALTER SERVER ... OPTIONS (SET host ...)orOWNER TOis drift; before,verifypassed. A server no migration
creates, and a foreign-data wrapper no extension installed, are reported
uncovered by name. Histories without servers keep their digests (#430). - User mappings.
CREATE USER MAPPING(andALTER/DROP) is refused
with its own reason,USER_MAPPING, instead of as role DDL: create
mappings outside the history as a DBA step, with the credentials in the
secrets provider. NTNT does not inspect them, so they cause no drift
(#430). - Extension drift and leftovers are named. An undeclared extension in
scratch is named inDB_SCRATCH_NOT_EMPTY(extension:hstore) with what
to do. Moving a declared extension to another schema is one drift entry
with its members under it, and a relation is listed under the extension
that owns it (#430). - Untrusted extensions. A migration that creates an untrusted extension,
such aspostgres_fdw, fails withDB_EXTENSION_PRIVILEGE, naming the
statement and the extension, explaining that roles that are not superusers
can create only trusted extensions, and saying what to do. It used to fail
with a bare SQLSTATE 42501. ForCREATE EXTENSION ... VERSION, as for
CASCADE, the diagnostic explains the failure without naming a statement
(#430).
Checks
- Checks on tables with these types.
requires,ensuresand adoption
checks may read tables with columns of these types, including types the
history created outside the managed scope (an enum inpublic), and run
while an extension's casts exist. Adopting a history that uses an enum or
citext column used to fail atmigratewithDB_CHECK_UNSUPPORTED. Checks
still run no routine the history wrote. Comparing a column with a literal
converts the literal to the column's type; for a domain that is its base
type, so a domain's own constraints never run, whatever they call. The
elements of an array and the attributes of a composite go through their
types' input, though, so a check that can reademails app.email[], where
app.email's constraint calls a function the history wrote or a volatile
one such asnextval, fails withDB_CHECK_UNSUPPORTEDbefore it runs,
naming the table, column, type, domain and function. So does a view that
converts values to such a domain, or that uses an operator whose function,
or whose negator's, the history wrote, and a view that calls
pg_input_is_validorjson_populate_recordwhile such a domain exists. A
domain whose constraint uses only builtins, such as a regular expression,
is allowed at any depth (#430). - Checks compare as the application does. Checks resolve operators with
search_path=pg_catalog, soemail = 'admin@example.com'on acitext
column compared case-sensitive text, and a check that the application's
comparison would fail could pass. A check that compares a column (or a
table's whole row) whose type, builtin or not, or a domain's base type, has
a same-named operator outsidepg_catalog, in any schema, since NTNT
cannot know the application's search path, is now refused before any check
runs, withDB_CHECK_UNSUPPORTEDnaming the check, table, column, type and
operator (app.=(app.citext,app.citext)), andplanlists it in
plan.check_warnings. Compare in a view a migration creates, which keeps
citext's operator, and check the view. Enums,citext[]arrays and citext
columns read withIS NULLorcount(*)stay allowed (#456).- A value a check computes, such as
id + 1 = 2orcount(*) = 0, is
screened like a column: each column the value is computed from, and the
types the computation can give it, are checked against operators of that
name outsidepg_catalog. Warnings show a computed value with?for
each literal (id + ?), so no literal from a check is shown. - Unquoted names in checks fold as PostgreSQL folds them, only ASCII
letters in a UTF-8 database, so a citext column namedÉmailis screened
and a schema qualifier is not mistaken for the managed schema.
- A value a check computes, such as
- Checks never write through a view. A check that reads a view, directly
or through other views, that callsnextval,setval, an advisory-lock
function or another builtin PostgreSQL marks parallel unsafe is refused
before it runs, naming the check, view and function.random(),
clock_timestamp()andgen_random_uuid()stay allowed (#456). - Checks on tables with row-level security. Checks read with
row_security=off, so that no policy can silently filter them, and
PostgreSQL refuses such a read where row-level security applies to the
migration role: a table withFORCE ROW LEVEL SECURITY, for the
unprivileged owner role the migration guide uses.plannow lists each
suchrequires,ensuresor adoption check inplan.check_warnings
(CHECK_ROW_SECURITY), naming the check and the table, andmigrate
refuses it withDB_CHECK_ROW_SECURITYbefore it runs, saying that the
migration role needsBYPASSRLS. Such a migration used to plan cleanly and
then fail with a bare SQLSTATE 42501. Only PostgreSQL's row-security
refusal of a check's read is reported this way; another SQLSTATE 42501,
such as a table the role may lock but not read, staysDB_POSTGRES. Plans
without such checks keep their digests (#430).
Replay and the scratch database
- Replay commits each migration on scratch, as
migratedoes on the
target. Replay used to run the whole history in one rollback-only
transaction. A history whose migration adds an enum value with
ALTER TYPE ... ADD VALUE(as Prisma generates) and whose next migration
uses it could never plan on PostgreSQL 16 (SQLSTATE 55P04); it now plans,
migrates and verifies on 16, 17 and 18. Each migration runs in a
READ COMMITTEDtransaction with the target's settings and commits (#430). - Enum values used too early are named. A statement that uses an enum
value thatALTER TYPE ... ADD VALUEadded in the same transaction fails
withDB_ENUM_VALUE_UNCOMMITTED, naming the migration and statements, in
replay and inmigrate, instead of an opaque SQLSTATE 55P04. Such a
migration used to plan on PostgreSQL 17 and 18 and then fail atmigrate;
it now fails atplan. PutALTER TYPE ... ADD VALUEin its own migration
and use the value in a later one (#456). - Scratch is cleaned up, fail-safe. Replay commits a marker (schema
_ntnt_replay) before the first migration and, whatever the outcome, drops
what the scratch role owns withDROP OWNED, restorespublic's owner,
privileges and comment, and checks scratch is empty again. A plan after one
that was killed between migrations cleans up its leftovers when only the
scratch role owns them, and reportsscratch.recovered; without the marker,
or with another role's objects, scratch is refused with
DB_SCRATCH_NOT_EMPTYas before and left untouched. A failed cleanup is
DB_SCRATCH_CLEANUP. Its advice to drop or recreate scratch applies only
when nothing but this configuration uses the database; otherwise it says to
point[databases.<name>.scratch]at a dedicated database (#430). - Recovery drops only what it can prove the unfinished replay committed.
The marker is bound to the database's OID and the cluster's system
identifier, and records each transaction of the replay that wrote the
catalog or rows of the scratch role's tables. A plan recovers only when
every catalog row in scratch, and every row of those tables, was last
written by one of them and scratch holds no_ntntledger; otherwise it
refuses withDB_SCRATCH_NOT_EMPTY, names why (a table another session
wrote rows into, for example), and drops nothing. A malformed marker (a
NULL in its transaction list, or settings that are not a snapshot) is not
NTNT's and is never cleaned. A database another project uses as its
target, reached through a misconfigured scratch, is therefore never wiped,
and that project's commands refuse a target holding the marker with
DB_TARGET_IS_SCRATCH(#430).- Known limitation. The scratch role cannot read
pg_largeobject, so
recovery cannot tell who wrote the data of a large object the replay
created. Data that another session writes into such an object after a
replay is killed is dropped with the leftovers.
- Known limitation. The scratch role cannot read
- Replay has its own deadline. It stops at the inspection deadline,
cancels the running statement, and cleanup still gets 30 seconds;
DB_TIMEOUTsays scratch may keep leftovers for the next plan to recover.
scratch.cleanupisnot_neededwhen nothing was committed. Cleanup drops
nothing unless it holds the replay lock, and a committed marker that is
gone isDB_SCRATCH_CLEANUP(#430). - Cleanup keeps to its limits. Each of its locks waits at most 2 seconds,
DROP OWNEDruns at most 10, and cleanup as a whole fits its 30 seconds. A
session that holds a lock on a table the replay committed (an open
transaction that read it, say) makes cleanup fail fast with
DB_SCRATCH_CLEANUPnaming that session's PID and role; the marker stays,
and the next plan, status or verify recovers once the session is gone. A
wait that autovacuum caused is tried again, up to three times (#430). - Concurrent plans on one scratch database wait for each other instead
of interleaving: a session advisory lock covers each replay, and a second
plan, status or verify waits up tomigrator_wait_secondsand then fails
withDB_SCRATCH_BUSY. A migration that releases the lock
(pg_advisory_unlock_all()), or swaps it for a transaction-level lock on
the same key, is refused before it commits, and the lock is checked again
after each commit. A killed replay's leftovers wait until no other session
of the scratch role is connected (DB_SCRATCH_BUSY). If releasing the lock
fails after cleanup finished, the failure is reported beside the finished
cleanup, and NTNT closes the scratch session, which releases the lock
(#430). - Cleanup restores the scratch database and role. Its privileges
(compared as sets), connection limit, comment and settings, and the scratch
role's settings, are recorded in the marker and restored, so histories that
runALTER DATABASE current_database() SET ...orGRANT/REVOKE CONNECT
in aDOblock, or recreatepublicforpg_database_owner, plan with the
same digests as before. Setting values are restored as escape string
literals (#430). - Changes cleanup cannot undo are refused before they commit, with
DB_REPLAY_UNSUPPORTEDnaming the migration: passwords (PostgreSQL's write
counters also count one an exception block rolled back), memberships, role
attributes and comments, other databases, objects given to another role, a
session left acting as another role, a schema another role owns left after
the migration droppedpublic, a change to the scratch database's or
public's privileges while they hold a grant another role made with a
grant option (the message names it and says to re-grant it as the owner),
andlocal_preload_librariesorsession_preload_librariesset for the
scratch database or role. So are a connection limit of 0 on scratch and a
REVOKE CONNECT, from the scratch role or fromPUBLICwhen the role
connects through it, that leaves the scratch role unable to connect; the
message names whose grant was revoked. Cleanup would restore both, but a
replay stopped before cleanup would leave no way to connect and clean
scratch up. AGRANTorREVOKE CONNECTthat keeps the role connectable,
and every history that does none of this, plans as before, with the same
digests (#430). _ntnt_replaycannot be the managed schema, like_ntnt:DB_CONFIG
says both are NTNT's own (the ledger and replay's marker in scratch), where
a plan used to fail on a duplicate schema (#430).- Deferral defaults. Same-named constraints with different
INITIALLY DEFERREDdefaults, or a name shared with a non-deferrable
constraint, no longer stop replay withDB_REPLAY_UNSUPPORTED; they plan
and migrate (#430). - Scratch's new requirements are listed under "Upgrading from 0.6.4".
ntnt db on SQLite
- Built-in functions. SQLite migrations can call SQLite's built-in
functions in defaults, CHECK constraints, index expressions, triggers, views
and backfills: the JSON functions (json_extract,json_set,->>, the
json_eachandjson_treetable-valued functions and the rest),hex,
randomblob,replace,instr,round,nullif,iif,
group_concat, the window functions and the other core scalar and
aggregate functions.DEFAULT (lower(hex(randomblob(16))))now plans,
migrates and verifies.load_extension,sqlite_log, and functions an
extension or the application registers stay refused with
DB_SQL_UNSUPPORTED, which names the function and now says what a
migration can use (#427). - AUTOINCREMENT. Tables with
INTEGER PRIMARY KEY AUTOINCREMENT, the
default primary key in Django and Rails schemas, plan, migrate and verify.
The counters insqlite_sequenceare left out of coverage and drift, like
PostgreSQL sequence counters; the table's definition, keyword included,
still counts. These tables used to fail withStatement 1 uses table `sqlite_sequence`(#427). - Planner statistics. After the application runs
ANALYZEorPRAGMA optimize,status,verifyandplanno longer reportsqlite_stat1as
uncovered, which blocked every migration, and a migration can drop a table
or index the statistics describe. A migration can runANALYZEitself
(#427). - ADD COLUMN.
ALTER TABLE ... ADD COLUMNon a STRICT table, or with a
CHECK constraint, plans like any other ADD COLUMN instead of failing with
uses SQLite function `glob`. When existing rows on the target would
break the new column,migratenames the failure, such asCHECK constraint failed, and commits nothing (#427). - Reads and CTEs.
INSERT INTO stats SELECT count(*) FROM eventsand
other reads that name no column of a table run, andWITH RECURSIVEis
allowed, including aWITHclause that leads an INSERT, UPDATE or DELETE
(#427). - Rebuilds keep AUTOINCREMENT counters. A
sqlite_rebuildof an
AUTOINCREMENT table that copies its rows into a replacement used to reset
the counter to the highest id copied, so the ids of deleted rows were
given out again. The rebuild guard now refuses that with
DB_REBUILD_GUARD, naming the table and both counter values, and its
next_actiongives theUPDATE,DELETEandINSERTto put before the
DROP (see
Explicit one-table rebuild).
They leave the replacement one counter row with the highest counter of
both tables, whether it had none, one or more. SQLite reads only the first
sqlite_sequencerow for a name, so the guard also refuses a rebuilt table
left with two, and gives the same lines. It also refuses a rebuild that
lowers or removes another table's counter (#427). - Rebuild guard says what failed.
DB_REBUILD_GUARDnames each rule a
rebuild broke and the object:the row count of table `log` changed from 0 to 1,index `index_posts_on_user_id` has another stored SQL text than before the rebuild(SQLite compares the stored text, so whitespace and
quoting must match) orview `titles` is missing, with their catalog
keys inobjectsand anext_actionfor each rule (#427). - Clearer refusals. A function SQLite does not define, such as one the
application registers, used in an INSERT or UPDATE is now
DB_SQL_UNSUPPORTED: Statement 2 uses SQLite function `app_slugify`,
as in a DEFAULT, instead ofno such function.ALTER TABLE ... ADD COLUMN c TEXT UNIQUEreports SQLite'sCannot add a UNIQUE columnand suggests
ADD COLUMN followed by CREATE UNIQUE INDEX, instead of naming an internal
autoindex (#427). - Failures that replay cannot show. On a target with rows, ADD COLUMN
with a non-constant default (CURRENT_TIMESTAMP,randomblob()) or NOT
NULL without a default, and a rebuild without the sidecar of a table that
other tables reference (immediate keys fail the DROP, deferred keys such as
Django's fail the COMMIT), now fail with anext_actionthat says what to
write instead: a constant default and an UPDATE, or thesqlite_rebuild
sidecar. The COMMIT failure also names its migration (#427). - Deferred foreign keys in replay. Replay never commits, so it now checks
deferred foreign keys at the end of each migration: when the history's rows
show it,planrefuses a drop that the target's COMMIT would fail.
ntnt db on every engine
- Blocked saved plans.
migrate --planwith a file thatplan --out
saved whenplanstopped before it could make a plan (outcomefail, no
plan_digest) says the plan is blocked instead of calling it edited. The
quick start examples check a plan's outcome before approving its digest
(#427).
Security
The lockfile updates cookie from 0.18.2 to 0.18.3 for
RUSTSEC-2026-0594
(#456).
See NTNT v0.6.4
for the previous release.
What's Changed
- fix(db): SQLite migrations accept built-in functions, AUTOINCREMENT, planner statistics and ADD COLUMN re-checks (#427) by @larimonious in #455
- fix(db): cover PostgreSQL enums, domains, composite types, trusted extensions, operators and EXCLUDE constraints (#430) by @larimonious in #456
- fix(db): name checks blocked by row-level security and CREATE EXTENSION privilege failures (#430) by @larimonious in #454
- fix(db): PostgreSQL replay commits per migration on scratch (#430) by @larimonious in #457
- feat(db): declared superuser-installed PostgreSQL extensions (#430) by @larimonious in #458
- fix(db): a database restored with pg_dump and pg_restore verifies (#460) by @larimonious in #463
- fix(db): 0.6.5 review follow-ups — checks, coverage, SQLite and docs by @larimonious in #464
- fix(db): 0.6.5 review follow-ups — replay and scratch cleanup by @larimonious in #465
- Prepare NTNT 0.6.5 for release by @larimonious in #467
Full Changelog: v0.6.4...v0.6.5