@ultimat3/db
v31.58.0
Published
Postgres access, transactions, migrations and drift detection
Maintainers
Readme
@ultimat3/db 🐘
Postgres access for Ultimate: parameterised SQL, transactions, migrations, drift detection, branch databases, and a read-only client for anything an LLM drives.
bun add @ultimat3/db · guide: Entities And Migrations
Tier 1. Imports @ultimat3/core only. No runtime dependencies; @electric-sql/pglite is an
optional peer, loaded at first query and only by the embedded driver. No ORM backs any of
this — @ultimat3/entity's hand-written postgresDriver() compiles every statement out of the
sql / identifier / join fragments below; this package declares the narrow structural types it
consumes (DbClient, SqlFragment, EntityDescriptionLike) so the SQL stays readable and the
boundary stays thin.
Public API
import { db, sql, raw, withTransaction, currentTx, setDbClient } from '@ultimat3/db';
declare const cache: { restore(id: string): void };
declare const orgId: string;
declare const id: string;
type Post = { readonly id: string; readonly orgId: string; readonly title: string };
const rows = await db().query<Post>(sql`select * from posts where org_id = ${orgId}`);
await withTransaction(async (tx) => {
await tx.execute(sql`update posts set likes = likes + 1 where id = ${id}`);
tx.onRollback(() => cache.restore(id)); // fires in reverse order on rollback
}, { isolation: 'serializable', readOnly: false });| Export | |
|---|---|
| sql / raw / identifier / literal / join | fragment builders |
| keyset({ scope, keys, after, limit }) | keyset paging for a raw join: { select, where, orderBy, limit, page(rows) }, below |
| shellInertIdentifier() | As of 2026-08-26: a quoted identifier that is also inert wherever a human PASTES it — or null. The one screen a catalog name goes through before it reaches a fix:. identifier() answers about SQL and accepts a backtick and a $, which are exactly what a shell substitutes inside double quotes, so a column called $(id) inside x db gen "add $(id)" runs id on paste |
| client.copyIn(target, rows) / canCopyIn(client) | As of 2026-11-11: COPY … FROM STDIN on postgresClient(), its pins, a DbTx on one and the replica router (to the primary) → Bulk load: copyIn |
| db() / baseClient() / setDbClient() | the ambient client; db() returns the open tx if any |
| dbClientInstalled() | As of 30.0: whether setDbClient installed a client that is still in place. Never builds the lazy default. @ultimat3/entity's testDriver() asks it on every repository call |
| ambientClient() | As of 31.30: the client db() would use now — installed, or the lazy default once built — else undefined. Never builds. A caller that displaces it with setDbClient reads it to restore or close it |
| dbExecutor(client = db) | the client as @ultimat3/core's PgExecutor (query(text, values)) — what a jobs, idempotency, notify or MCP confirmation store takes. The client is resolved per statement: the default reaches the boot's client even when declared at module scope, and joins an open withTransaction; () => pool pins one pool whatever transaction is open |
| DbTx.origin | As of 2026-08: the client the transaction was opened on — options.client or baseClient(), never the reservation it runs statements through. @ultimat3/entity compares a pinned repository's client against it, so a pinned repo joins its own shard's transaction instead of being refused |
| withTransaction() / currentTx() | transaction scope; currentTx() is the outbox seam. { retry: n } (As of 2026-08) re-runs fn from the top on a 40001/40P01 and on nothing else — default 0, so fn must be idempotent before you ask for it. Each re-run waits first, As of 2026-08-23: exponential from 10ms, capped at 500ms, full jitter (@ultimat3/core's backoffDelay). A budget of 0 waits not at all. A transaction the server aborted is reported as one, As of 2026-10-02 → Transactions that end badly |
| completeTransaction() / refuseAbandoned() | As of 2026-11-02: the mark that takes the open root's statements and COMMIT past an abandoned scope (a keyed action's), and the check for a write that goes through no DbTx (@ultimat3/entity's writing(), the enqueue facade) → Transactions that end badly |
| liveTxConnection() | the connection of the transaction still open on this async context, or undefined. currentTx() keeps answering a finished scope's handle to a promise chain the body forgot to await; this is the one that says whether a statement sent now is really inside a transaction. @ultimat3/action reads it before binding an idempotency settlement to a commit |
| sqlState() / isRetryableState() / SQLSTATE | As of 2026-08: the SQLSTATE a driver error carries, and the closed table from it to a code. Bun.SQL puts it on errno; PGlite puts it on code; one reader answers for both |
| migrate() / rollback() / readLedger() | the x_migrations ledger. rollback({ steps }) reverses the most recently applied migrations (applied_at, then id, both descending), As of 2026-11-19 — not the highest ids: a branch merged late applies an older id after a newer one, and is the first undone. rollback({ confirm }) is called once, under the migrate lock and before the first down, with the exact LedgerRows about to be reversed: throw (or return a promise that rejects — it is awaited) to refuse, and nothing is reversed. x db rollback [--steps n] is the command over it. On the embedded development database (development, no DATABASE_URL) X_MIGRATION_CONFLICT and X_MIGRATION_ROLLBACK_DESTRUCTIVE lead their fix with x stop --json && x db reset (rows lost; x db seed refills) in place of psql "$DATABASE_URL" and x deploy --image, which have nothing to dial there; restoring the file (git status, git log for an edit) stays in the line |
| ledgerAheadOfBuild() / ROLLBACK_ALLOW_DESTRUCTIVE_ENV | As of 31.30: the ledger split when it is exactly a rollback onto a newer build's schema (every unknown row newer than the newest shipped, nothing pending), else undefined and auditLedger refuses it; a destructive row ahead throws X_MIGRATION_ROLLBACK_DESTRUCTIVE unless named in the variable. migrate()'s own first step, exported so x db status judges a ledger as x db migrate will |
| statementsOf() | As of 2026-08: a SQL script → the statements a driver sends one at a time. One send is one statement, so migrate() splits with this — a ; inside a literal, an identifier, a dollar-quoted body or a comment is data |
| withReplicaReads() | As of 2026-08-24: the scope inside which a plain read may be served by a replica — until it writes, after which every read in it is the primary's. No scope open, nothing routes |
| poolerFromEnv() / POOLER_ENV / PoolerMode / POOLER_WAIT_MS / statementBound() / lostStatementBound() / StatementBound / poolerSessionRequired() | As of 2026-11-03: a connection pooler in the path (pooler.ts), and the two bounds as the session reads them. Pool sizing by role |
| replicatedClient() / ReplicaStats / REPLICA_URL_ENV | As of 2026-08-24: one DbClient over a primary and a standby. baseClient() builds one when DATABASE_REPLICA_URL is set and the single-pool client when it is not |
| INDEX_METHODS / IndexMethod / indexMethodOf() / indexMethodSql() / declaredMethod() | As of 2026-08-24: an index's access method — btree or gin, closed. Absent is btree, the live side is read open (whatever pg_am said), and the DDL literal is re-derived from the set rather than spliced from the input |
| IndexDescriptionLike.expression / .orders / .include / .operatorClass · INDEX_OPERATOR_CLASSES / requiredExtension() | As of 2026-11-12: the index parts past a plain column list — one expression key (unique (lower(email))), a direction per key, INCLUDE payload columns (btree), gin_trgm_ops (gin; requiredExtension() answers pg_trgm). Each optional, absent hashes and renders as before; drift compares each, an expression by presence only |
| tableStorage(table, { fillfactor?, unlogged?, autovacuum? }) / tableDdl() / storageAlters() / tableStorageDrift() / readTableStorageDrift() | As of 2026-11-14: a framework-owned table's storage parameters as one value; autovacuum (TableAutovacuum: vacuumThreshold, vacuumScaleFactor, analyzeThreshold, analyzeScaleFactor) states when autovacuum visits it. tableDdl(storage, columns) renders create [unlogged] table if not exists … with (fillfactor = n, autovacuum_… = v) plus the idempotent alters that bring an existing table to it at framework-schema apply; drift reads relpersistence/reloptions, each difference with its alter as fix. A bad name, fillfactor or autovacuum value is X_SQL_UNSAFE at import |
| slowStatementLog({ thresholdMs }) | one warn db.statement.slow line per slow statement shape per 10 s, with request/trace ids and no bind values; returns the unsubscribe |
| lockHeavyStatements() / migrationLockHeavy() / LOCK_HEAVY_MARKER / LOCK_HEAVY_SINCE | X_MIGRATION_LOCK_HEAVY: set not null with no prior validate, non-concurrent create index on an existing table; -- lock-heavy: true to admit; judges ids > LOCK_HEAVY_SINCE |
| isPlainRead() | As of 2026-08-24: whether a statement may leave the primary. An allow-list — everything it cannot vouch for is the primary's |
| checkDrift() / diffSchema() / assertNoSchemaDrift() | drift, with a --json report. checkDrift() is the post-migrate verification — the live database against the ledger: columns, declared indexes (access method As of 2026-08-24, columns, uniqueness, direction, and whether a predicate is there at all — never its text), declared CHECK constraints by NAME (missing-check, As of 2026-08-25 — never a predicate, which the catalog answers rewritten) and declared foreign keys, matched on where the key points and not on its constraint name, with the on delete rule compared through one normalisation As of 2026-08-19 |
| declaredSchema() / expectedSchema() | As of 2026-08: the schema the migrations write down, or undefined when the newest one carries no snapshot — never an older snapshot standing in for it |
| parseSnapshot() | As of 2026-08: a <id>.snapshot.json sidecar validated to the last nested field, or undefined. {"tables":[null]} is valid JSON and is not a schema |
| snapshotJson() | As of 2026-08: the sidecar's bytes — the JSON Biome would have printed, trailing newline included. The one writer of a <id>.snapshot.json, because JSON.stringify(…, null, 2) is not formatter-clean and an app's lint step rejected the file x db gen had just written |
| isLedgerMissing() | As of 2026-08: whether an error is Postgres' undefined_table for x_migrations — the one condition a caller may read as "nothing applied" |
| appTables() | As of 2026-08: the live schema minus the x_ namespace — no migration declares the ledger, the queue, the outbox or an auth table, so none of them is drift |
| sameTenantKeyName() | the name of a same-tenant composite key, <table>_<column>_tenant_fkey, within 63 bytes. ColumnDescriptionLike.sameTenant is what makes a key composite; @ultimat3/entity's memory driver reads this so its refusal names the constraint Postgres would |
| generateMigration() | x db gen "<name>" — reversible up/down SQL, and destructive for the marker the file must carry. As of 2026-08 a foreign key is its own alter table … add constraint, emitted after every table statement: inline, a references() had to point at a table entity registration order happened to create first, and down had to drop them in an order it did not control. As of 2026-08-19 a removed references() emits its drop constraint (it emitted nothing, and the snapshot then denied a constraint the database still held), a changed onDelete is a drop-and-add rebuild, and a declared on delete rule reaches the clause at all. As of 2026-08-25 a retype drops the partial indexes and CHECK constraints written against that column first and restores them in down: Postgres compiles both predicates against the old type and cannot recompile either, so alter column … type text using …::text was 42883 operator does not exist: text = post_status and the migration aborted mid-run. A plain btree over the column is left alone — measured, Postgres rebuilds that one itself. As of 2026-08-26 replicaIdentityFull names the tables a live query subscribes to and emits one alter table … replica identity full each, last in up, recorded on the snapshot so the next generation emits none — a parameter and never an entity field, because the live-query set is a tier-3 fact (replica-identity.ts) |
| declaredIndexes() / invariantChecks() / constraintNameFor() | As of 2026-08-25: the DDL an entity invariant becomes — a check as a named CONSTRAINT, a unique as a partial-capable unique INDEX, an assert as nothing. EntityDescriptionLike had no invariants field for three majors, so a regenerated migration silently held none of them, including the composite UNIQUE upsertAll's on conflict is inferred against |
| declaredChecks() / checkPlan() / columnChecks() | As of 2026-08-25: every CHECK a table declares — a column's own (enumerated()'s value set, tz()'s IANA whitelist, locale()'s tags, money's currency pattern and scale bound) and an invariant's — on ONE list, so createTable, diffTable and snapshotOf agree about what exists. A column's check reached create table inline and anonymous and nothing else: the snapshot recorded none and the diff had no arm, so a value added to enumerated() generated no migration and a regenerated ENUM column came back as bare text. The name is <table>_<column>_check because that is the name Postgres itself mints for the old anonymous form — measured — so the repair lands on the constraint an already-generated database is holding; checkPlan emits drop constraint if exists before the add for exactly that column, because a bare add is 42710 there and a no-op everywhere else |
| defaultExpression() / ColumnDefaultLike | As of 2026-08-25: a column's default as SQL. A DECLARED default ({ kind: 'value', value }) wins; gen_random_uuid() and now() stay as the inference for a description that carries only hasDefault |
| unrenderedOf() / unrenderedComment() / UnrenderedDeclaration | As of 2026-08-25: what the generator could not write, on GeneratedMigration.unrendered and as a -- UNRENDERED block at the top of a non-empty up. A generator that emits less than the declaration in silence is the defect the whole file exists against, and x verify's drift step reads a source hash — it never reads the SQL, so the loss was green. unrenderedOf(entities, current) takes the recorded schema, required and nullable: a rule declared as an assert reaches no SQL by design and is no loss on its own, but one whose CHECK a previous migration RECORDED is dropped by this run and reported by nothing — five in examples/dummy, and @ultimat3/cli's repairFix then offered x db gen "drop <name>" as the repair for the loss that command performs |
| isNonTransactional() / NO_TRANSACTION_MARKER / isConcurrentIndexStatement() / concurrentIndexTarget() | As of 2026-10-31: the -- transaction: false marker a migration carries to run outside a transaction, and the concurrent index statements that need it → Indexes built concurrently |
| rollingUnsafeStatements() / hasRollingUnsafeMarker() / ROLLING_UNSAFE_MARKER / retiredColumnsIn() / retireAndContractPending() / migrationRollingUnsafe() | As of 2026-11-02: the rolling-deploy rail — would the previous release trip over this up? A closed list (drop column with no earlier -- retires, rename column, rename table), read by the drift step past rollingSince, and the pair migrate() refuses pending together in production |
| recordRetired() | As of 2026-11-02: snapshotOf one step on, keeping a retired column and what hangs off it on the record. x db gen and the drift step both read through it, so they cannot disagree about one |
| a column leaving a table (column-drop.ts) | As of 2026-11-19: a plain column declared generated is drop column + add column, so it is asked what an ordinary drop is asked — X_MIGRATION_ROLLING_UNSAFE unless the column was retired first or rollingUnsafe is set, then X_MIGRATION_IRREVERSIBLE unless allowDestructive — and the result carries rollingUnsafe: true for a column never retired. The down of any column drop re-creates the indexes and foreign keys the previous snapshot recorded over the column (a key whose target table the same migration drops is a -- note); the rows are not restored. An index counts as over the column when it depends on it any way Postgres drops it for — a key, an include column, a partial predicate or an expression that reads it — so its restore is in the drop's own down, never a follow-up step's. A .snapshot.json whose dataType holds a second statement is not a snapshot (parseSnapshot answers undefined) |
| destructiveStatements() / hasDestructiveMarker() / isDestructiveMigration() / DESTRUCTIVE_MARKER | As of 2026-08: the destructive-SQL rail — does this up drop, truncate or retype, and does the file declare it with -- destructive: true? One classifier, read by x db gen when it writes the marker and by x verify when it demands one |
| stripSqlNoise() | comments, literals, dollar-quoted bodies and quoted identifiers blanked in source order, so a reader sees the operation and not the prose. Shared by readOnlyQuery() and the destructive rail |
| introspectSchema() | live schema → SchemaDescription. App tables only, As of 2026-08-24: a relation an extension owns (pg_depend, deptype = 'e') and anything that is not an ordinary or partitioned table are excluded before the fold, and an explicit exclude cannot bring them back. A partition is not app schema either (relispartition, As of 2026-11-06): its parent is judged — keys, indexes, checks, triggers — and carries partitioned: true; a key Postgres clones per partition (conparentid <> 0) is not read |
| introspectCatalog() / CatalogDescription / emptyCatalog() | @ultimat3/db/schema-dump. As of 2026-10: the WHOLE schema in the catalog's own spelling — extensions, enum and domain types, sequences, tables, indexes, foreign keys, views, functions, triggers — sorted in code-unit order, plus unrendered: what exists and the dump cannot spell. Comparable only to another reading of itself; introspectSchema() stays the entity-vocabulary reading a snapshot is diffed in |
| renderSchemaDump() / SchemaDumpFile | @ultimat3/db/schema-dump. As of 2026-10: a catalog → the schema dump's files. Pure and byte-deterministic. The schema dump |
| loadSchemaDump() | @ultimat3/db/schema-dump. As of 2026-10: build a schema from those files, in one transaction, retrying a file that names something not created yet |
| compareSchemaDump() / reloadDifferences() / schemaDumpDrift() / schemaDumpDifferenceOf() | @ultimat3/db/schema-dump. As of 2026-10: X_SCHEMA_DUMP_DRIFT — committed files against rendered ones in both directions, and load-equals-replay as a comparison |
| unexpectedObjects() | @ultimat3/db/schema-dump. As of 2026-10: the triggers, functions, views, types and sequences a live catalog holds and an expected one does not, as unexpected-object drift. Identity, never definition text. Its fix: is one psql -c command that prints the object's definition, qualified by the catalog's schema — \d+ a view, \dT+ an enum, \dD+ a domain, \d a sequence or a trigger's table, pg_get_functiondef by namespace for a function — with the repair as its comment |
| PgliteOptions.extensions / linkPgliteExtensions() | As of 2026-10: Postgres extensions to link at boot, by name — a list, or a function for a caller whose list is read from disk. linkPgliteExtensions(names) answers { linked, missing } without booting anything: missing is what the installed PGlite ships no bundle for, which is how @ultimat3/cli decides a replay needs a real Postgres. A missing name is skipped at boot and refused by create extension itself |
| PgliteOptions.snapshotDir | As of 2026-10: a directory for the post-initdb snapshot, so an in-memory boot is a restore (~0.4 s against ~2.7 s). Keyed on the PGlite version alone — initdb never sees a linked extension, so one snapshot serves every set; checksummed, never trusted, written by temp-name-then-rename. Ignored for a data directory on disk |
| createBranch() / dropBranch() / reapBranches() | copy-on-write branch databases. As of 2026-08-19 the marker comment records the base as well as the instant (ultimate:branch:<base>:<iso>, on BranchInfo.base), and reapBranches() sweeps only branches of the database it is connected to — one Postgres hosting two Ultimate apps used to mean one app's nightly reap dropped the other's branches. A pre-3.x marker records no base and is skipped, never dropped |
| pgliteClient() / branchPglite() | the embedded database — Postgres in this process |
| ensureReadOnlyRole() / READONLY_ROLE | a NOLOGIN, SELECT-only Postgres role — layer 1 of db.query's defence |
| readOnlyQuery() | one statement inside BEGIN READ ONLY with a statement timeout — layer 2 |
| dbDiagnostics() / DIAGNOSTICS_LIMIT / DIAGNOSTICS_TIMEOUT_MS (from @ultimat3/db/diagnostics) | As of 2026-11: what the database is doing now, as seven sections (blockers, activity, slowQueries, unusedIndexes, invalidIndexes, notValidConstraints, deadTuples), each { available: true, rows } or { available: false, code, reason, fix } → Diagnostics. x db diagnostics prints it |
| DbStatementEvent / StatementAttribution (types, core's) | As of 2026-11 (v31): every settled statement, both drivers, is one db.<verb> client span — always, production included — carrying db.system.name=postgresql, db.query.text (parameterised) and db.operation.name; and one db.statement event on core's bus while anything subscribes: subscribe('db.statement', (e) => …). No subscriber is one map read |
| expectedSeqScan() / expectedSeqScanReason() | As of 2026-11: the one way a hand-written statement says it reads its table whole — x exercise's plan sweep lists it exempt with the reason instead of X_QUERY_UNINDEXED. Same shape as expectedQueryLoop(): required, non-blank, innermost wins. A small table says it once on the entity: scan: '<why>' |
| expectedQueryLoop() / expectedQueryLoopReason() | As of 2026-08: the one way to declare a loop of queries deliberate — the reason rides on every statement it issues as DbStatementEvent.expected |
| withStatementAttribution() / statementAttribution() | As of 2026-08: the { entity, op } pair on DbStatementEvent.attribution, scoped exactly like expectedQueryLoop() — @ultimat3/entity's postgresRepo is the one producer |
| statementFingerprint() / statementKind() / statementVerb() | As of 2026-08: what shape a statement is — entity.op when attributed else its own collapsed text, read or write from the leading verb. One rule, so two detectors group identically |
| recordingClient() | in-memory DbClient that records SQL, for tests |
@ultimat3/db/adapter
As of v31: what a host or driver wires, never what an app calls. The . barrel is the app API;
the types below stay on it too wherever a . signature names them.
| Export | |
|---|---|
| defaultClient() | the boot's client, built from DATABASE_URL (and DATABASE_REPLICA_URL) |
| loadPgliteDriver() | the optional @electric-sql/pglite peer, imported by variable specifier |
| PostgresClientOptions / ReplicatedClientOptions | the pool options postgresClient() / replicatedClient() take |
| ReservableClient / ListeningClient | a client that pins one session; one that holds a LISTEN |
PostgresFailureStore, the x_failures store's shape, is on . only: no runtime.ts field takes
one, so it is no port.
sql is parameters-only
String interpolation is how every SQL injection ships, and an agent writing SQL cannot be trusted to remember the difference between a value and a fragment. So:
- scalars (
string,number,boolean,bigint,Date,Uint8Array, arrays,null) become$1..$nand never touch.text. A value that cannot be SENT — an Invalid Date, a ragged array — isX_INVARIANTbefore the driver is called, neverX_DB_UNAVAILABLE; aUint8Arrayinside an array is onebyteaelement. Both drivers refuse alike; - a nested fragment is spliced and its parameters are renumbered;
- anything else throws
X_SQL_UNSAFE— including an object shaped like aSqlFragmentthatsql/rawdid not produce; raw(trusted)is the one audited escape hatch,identifier(name)the safe way to interpolate a table or column,literal(text)for utility statements that reject bound parameters.As of 2026-11-09identifier()also refuses a NUL and a name over 63 bytes (sql.ts'sMAX_IDENTIFIER_BYTES), which Postgres would truncate without an error (X_SQL_UNSAFE).
Failure bundles: x_failures
postgresFailureStore() is the store failureCapture (app.config.ts) installs: every statement
runs outsideTransaction, because the request that failed rolled its own transaction back.
find(id) takes a bundle, request or trace id; latest(fingerprint) the newest of a group;
list({ code }) the summaries x repro --list prints. Retention has no default window:
failurePurgeTarget(store, { keepMs }) is a purge() target. The table is applied by the boot.
Paging a raw join: keyset()
As of 2026-11-06. The handle pages with .after(); a join it cannot say pages with this. Four
fragments to splice and page(rows), which answers core's Page.
| Rule | |
|---|---|
| A key | { column: SqlFragment, kind: 'timestamptz' \| 'uuid' \| 'text' \| 'integer' \| 'bigint', direction }, last key the tiebreak |
| Precision | selected as col::text under _keyset_<n>, bound back as $n::<kind>: a microsecond survives, a Date would floor it and drop rows |
| The seek | uniform direction: one row comparison, Index Only Scan on a matching index. Mixed: the or-chain |
| order by | the bare columns. date_trunc('milliseconds', …) there is a Parallel Seq Scan and a sort (100 ms against 0.2 ms, 300,000 rows); the scaffolded repo-raw-sql guard reports it |
| A nullable key | As of 2026-11-14: nullable: true, NULL placed by nulls: 'first' \| 'last' (default asc nulls last, desc nulls first, as the entity driver). Written into order by, carried in the cursor as present/absent, seeked by the or-chain. Never the last key |
| A null key | on an undeclared key, X_KEYSET_NULL_KEY on any row of a page, whatever its size; a nullable last key is the same code at keyset() |
| The cursor | core's signed codec; scoped to scope plus every key's column, kind and direction (and a nullable key's NULL placement). Another read's is X_CURSOR_INVALID |
| limit | a whole number ≥ 1 (finiteCount), read as limit + 1 |
| direction, kind | As of 2026-11-09: 'asc'/'desc' and the five kinds, exactly — anything else is X_INVARIANT at keyset(). The order by splice is re-derived from the closed set, never the caller's text. Map a request's sort onto the two literals yourself |
Proven on both engines: keyset.live.test.ts (Postgres) and keyset-embedded.test.ts (PGlite)
walk four rows inside one millisecond across page boundaries, and assert the plan holds no sort;
the same suites walk a nullable key under all four direction × placement orders, every row once.
Transactions that end badly
As of 2026-10-02. Postgres aborts the WHOLE transaction on any statement error and answers the
COMMIT that follows with the tag ROLLBACK and no error. withTransaction used to resolve on
that, fire onCommit, and store nothing.
| Situation | What happens |
|---|---|
| the body catches a failed statement and returns | X_DB_TRANSACTION_ABORTED, cause = the first failing statement; ROLLBACK, onRollback undos run, onCommit never fires |
| the fallible statement sits in a nested withTransaction and THAT is caught | only the savepoint rolls back; the outer scope commits. This is the fix the error names |
| a nested body swallows a failed statement | the nested call rejects with X_DB_TRANSACTION_ABORTED; its savepoint is rolled back and the outer scope is usable again |
| ROLLBACK TO SAVEPOINT itself fails | the nested call still rejects with the body's error; the root is marked aborted and its COMMIT is refused, never sent |
| two nested scopes under Promise.all | run one after the other, per parent scope — savepoints are a stack, and interleaved ones destroyed each other |
| a nested scope waits past siblingWaitMs (default SIBLING_SCOPE_WAIT_MS, 30 s; 0 = no deadline) for its sibling | X_DB_SIBLING_SCOPE_TIMEOUT, naming the parent and the savepoint holding the turn. The shape it exists for: a body awaiting a sibling started after it, which waits for itself — a permanent hang before the deadline. The waiter never opened and its place is handed on |
| any COMMIT answered ROLLBACK, on either driver | X_DB_TRANSACTION_ABORTED from the statement funnel (commit-tag.ts) — covers an abort the scope never saw and a hand-written COMMIT |
| COMMIT rejects with a SQLSTATE (a deferred constraint, 40001) | rolled back: the server's error surfaces, undos run |
| COMMIT rejects with NO SQLSTATE | X_DB_COMMIT_UNKNOWN: neither onCommit nor onRollback runs, and it is never retried |
| a nested scope passes isolation, readOnly: true, deferrable: true, or a client other than the root's | X_INVARIANT — a savepoint can honour none of them; retry was already refused |
| a statement on a handle whose scope ended, committed or rolled back: an un-awaited promise, a Promise.all loser | X_DB_TRANSACTION_CLOSED As of 2026-11-02, where it fell through to the pool and autocommitted. await it, or outsideTransaction(fn) |
| ctx.signal aborted with a coded reason (X_TIMEOUT, a job's cancellation), at a statement, a nested scope, a BEGIN or a COMMIT | As of 2026-11-02: that reason is rethrown, the same object, and the scope rolls back. An uncoded abort (a client hang-up) changes nothing. ROLLBACK and ROLLBACK TO are never refused. A statement on the pool, outside any transaction, is not refused here: @ultimat3/entity's writes ask at their own funnel |
| the same abort after completeTransaction() marked the root | statements and COMMIT go through: withIdempotency marks a reservation it created, because the settle rides that COMMIT |
Only a failure carrying a SQLSTATE marks the scope aborted: a refusal raised before the send left the transaction untouched.
Read-only access for anything an LLM drives
As of 2026-07: a bug in one defence must not become a write, so db.query on the MCP dev
server stacks independent layers rather than trusting a single gate. This package owns the two
layers that are Postgres facts rather than MCP facts — the tool-boundary layers (pre-parse scan,
policy) live above it, and @ultimat3/mcp imports nothing of this package but one lexer rule,
endOfBlockComment (a nested /* */ ends where Postgres ends it, null when it never closes).
import { db, ensureReadOnlyRole, readOnlyQuery } from '@ultimat3/db';
declare const statement: string;
const role = await ensureReadOnlyRole(db()); // layer 1, once at boot
const { rows, guards } = await readOnlyQuery(statement, { role }); // layer 2, per statement| Layer | Export | |
|---|---|---|
| 1 | ensureReadOnlyRole() | idempotent DDL (grantReadOnlySql()) for READONLY_ROLE, a NOLOGIN role granted SELECT on every table and nothing else. Returns null instead of throwing when the connection cannot create or grant roles — a managed Postgres where the app user isn't a role admin |
| 2 | readOnlyQuery() | runs one statement inside BEGIN READ ONLY, assumes role via SET LOCAL ROLE when given one, bounds it with SET LOCAL statement_timeout (READONLY_TIMEOUT_MS default, timeoutMs: 0 to disable), and always exits via ROLLBACK |
readOnlyQuery() reports which guards actually engaged (result.guards, e.g. ['txn:read-only',
'timeout:5000ms', 'role:ultimate_readonly']) instead of assuming every layer held — a silently
degraded layer is a caller's problem to surface, never this package's to hide.
Only layer 1 degrades. readOnlyQuery() throws — a pool that cannot reserve a connection
(X_DB_UNAVAILABLE), a refused SET LOCAL ROLE, a failed transaction command, or the
statement's own error. Every caller handles that failure; nothing here swallows it.
ALTER DEFAULT PRIVILEGES is scoped to whoever creates an object, so pass
creators: ['migrator'] when migrations run as a different DB user than the one that ran
ensureReadOnlyRole() — otherwise a table created later is not selectable by the role, and
layer 1 covers only what existed at grant time.
Diagnostics
As of 2026-11. dbDiagnostics({ client?, limit?, deadlineMs? }) answers facts, never a verdict: how bloated is
too bloated differs per app. checkDb() stays the readiness probe /readyz reads.
| Rule | |
|---|---|
| Read-only, bounded | every section is one catalog statement through readOnlyQuery(): BEGIN READ ONLY, DIAGNOSTICS_TIMEOUT_MS (2 s), a cursor capped at limit (default 20). Sequential, so one connection |
| deadlineMs | As of 2026-11-09: the whole command's budget, the select 1 probe included. Default: the probe waits 3 s, the command 15 s. On a cold embedded database the probe IS the boot, so x db diagnostics passes 30 s there |
| One failure stays one | a section that throws is { available: false, code, reason, fix }; the other six answer. The single throw is a probe (select 1) that cannot connect |
| No row values | no statement reads a user table. Session SQL (activity, blockers, slowQueries) has every literal replaced by ? before it leaves (db-diagnostics-redact.ts, over the package's one lexer); a scheme://user:pass@ in a reason is masked |
| slowQueries | reads pg_stat_statements; absent (always on PGlite) is available: false with the operator's create extension + shared_preload_libraries fix. The framework never creates an extension |
| unusedIndexes | idx_scan = 0, unique and primary excluded; each row carries statsAgeSeconds (since pg_stat_reset, null = never) and replica — counters are per server |
| activity | queryVisible: false (and query: null) for a session another role owns when this one lacks pg_read_all_stats |
| Who sees what | whoever runs it sees the SQL text (redacted) of every session on the app's database role, and of every role when that role holds pg_read_all_stats or is a superuser: other users' requests, background jobs, psql sessions. Literals are ?, statement shape and identifiers are not. Run it with the credentials of someone allowed to see that |
Server health gauges
As of 2026-11. startPostgresStatsGauges(executor, intervalMs?) samples the Postgres server every
POSTGRES_STATS_INTERVAL_MS (15 s) — at once, one round at a time, unref'd — and returns an async stop
that awaits the round in flight (release it before the pool closes);
postgresStatsSampler(executor).sample() is one round. Run by ONE role (the scheduler): these are server
facts, and every pod reading them would multiply the load for the same numbers.
| Series | What it is |
|---|---|
| db_server_connections / db_server_max_connections | client backends on the whole server, against its max_connections |
| db_longest_transaction_seconds | this database's oldest open transaction this role can see (pg_read_all_stats widens it), 0 when none |
| db_autovacuum_backlog_ratio | the worst table's dead tuples over its autovacuum trigger (global settings): above 1 it is due |
| db_replication_slot_retained_bytes{slot} | the WAL each of this database's logical slots holds on the primary; a dropped slot reads 0 |
| db_stats_sample_ok | 1 when the last round landed, 0 when it failed and every value above is stale |
Two constant catalog statements per round, no user table, no lock. A failed round never rejects
and logs db.stats.sample-failed once per streak; a value the driver did not send as a finite
number leaves the gauge at its last good value. The gauges are declared on the first sample, so a
process that samples nothing exposes none. The chart's alert rules read all six; a
zero autovacuum trigger (threshold 0 over an empty table) is skipped, never a division by zero.
Index access methods
btree is the default and is never written out; gin is what makes @> / <@ / && / ? on a
json() or arrayOf() column an index lookup rather than a sequential scan.
| | |
|---|---|
| declared | IndexDescriptionLike.using — 'btree' \| 'gin', closed. Anything else is X_SQL_UNSAFE before it reaches DDL |
| absent | btree, on every side, through indexMethodOf() — so a snapshot written before the field existed reads as what it always was |
| emitted | create index "posts_tags_idx" on "posts" using gin ("tags"); — and create index "posts_tags_idx" on "posts" ("tags"); when no method was declared, byte for byte what shipped before |
| refused | a unique GIN and an ordered GIN (X_INVARIANT) — Postgres has neither, and the alternative is a syntax error inside ROLE=migrate |
| recorded | only when declared, so no existing sidecar is rewritten |
| a method that moved | drop and recreate — Postgres cannot alter one in place |
| drift | a declared GIN against a live btree is changed-index, and the live method is reported by the name the catalog gave it |
Indexes built concurrently, and every index drop
As of 2026-10-31. A plain create index holds SHARE on the table for the whole build — every
insert, update and delete waits — and a plain drop index takes ACCESS EXCLUSIVE, so reads wait
too. create index concurrently / drop index concurrently take SHARE UPDATE EXCLUSIVE, which
queues neither, and Postgres refuses both inside a transaction block (25001).
import { entity, text, uuid } from '@ultimat3/entity';
entity('runs', {
columns: { id: uuid().primaryKey(), status: text({ max: 20 }), bank: text({ max: 40 }) },
indexes: [{ on: ['status'], concurrently: true }],
});| | |
|---|---|
| declared | IndexDescriptionLike.concurrently — true or absent. HOW the index is built, never WHAT it is: not in its name, not in the snapshot, and switching it on or off for an existing index generates nothing |
| emitted | create index concurrently if not exists "runs_status_idx" on "runs" ("status");, down drop index concurrently if exists "runs_status_idx"; |
| removed index | always drop index concurrently if exists, whether or not it was built concurrently — down rebuilds it concurrently from the recorded definition. A total unique btree (a shape a UNIQUE constraint may back, where drop index concurrently is 2BP01) is first unhooked by alter table … drop constraint if exists in the same step, right before its drop — never in an earlier transaction, whose rollback could not restore it |
| moved definition | a concurrently: true index whose columns, predicate, order or method moved is dropped and rebuilt, both concurrently — between the two the table has neither (name the new shape differently to build it beside the old one) |
| where it does not apply | an index on a table the same migration creates (empty, invisible until COMMIT), and one over a column a retype or a rebuild already holds ACCESS EXCLUSIVE for: both stay in the transaction |
| the files | no concurrent work: ONE transactional migration, as before. Concurrent work only: ONE migration marked -- transaction: false. Both: TWO — <id>.sql (the transaction) and <id>_concurrently.sql (outside it), sorting in that order, each with its own snapshot and hash. Expand → contract: inside the step every build precedes every drop and constraint unhook, so a renamed key's replacement exists before the old key goes |
| the runner | migrate() / rollback() run a -- transaction: false migration one statement at a time: a concurrent statement bare, with no lock_timeout (a concurrent build waits for every older transaction, and that wait is a lock wait); any other statement in a short transaction of its own under the migration's lock_timeout. The ledger row is written after the last statement |
| an interrupted build | leaves an INVALID index holding the name. Before each named create index concurrently, the runner reads pg_index.indisvalid through to_regclass(<name>) and drops an invalid one concurrently first; every statement is if [not] exists, so a failed step is simply re-run |
| refused | a concurrent statement in a migration WITHOUT the marker: X_MIGRATION_CONCURRENT_IN_TRANSACTION, before BEGIN |
| destructive | never — an index holds no row. A column or table drop in the same diff is still marked |
To drop an index on a hot table: delete it from the entity's indexes, x db gen "drop <name>",
commit what it writes, ship. The drop is its own non-transactional migration.
Reads with their own settings
| API | |
|---|---|
| setLocal(tx, settings) | the framework's ONE bound set_config caller (beginWith the one spliced one, below): select set_config($1, $2, true), parameter-bound and transaction-local, so a value ends with its transaction and a pooled connection hands nothing on (read-transaction.test.ts greps the tree for a second one) |
| withReadTransaction(fn, { settings, client }) | withTransaction(fn, { readOnly: true, client }), then setLocal. Inside an open transaction it joins it, applies the settings, runs fn and puts the prior values back |
| withStatementTimeout(ms, fn, { client }) | one read's own statement_timeout, transaction-local. Refused above the bound already in force, and non-positive (X_DB_STATEMENT_BOUND_INVALID); firing is X_DB_STATEMENT_TIMEOUT. A transaction is the primary's, so a bounded read never reaches a replica |
| setTransactionSettings(provider) | the settings every ROOT transaction sets right after BEGIN — row security's tenant. One provider; unset costs one comparison |
Row security (As of 2026-11, mechanism)
| API | |
|---|---|
| enableRowSecuritySql(table, column, type) | enable + force + one ultimate_tenant policy: using and with check both case when current_setting('x.cross', true) = 'on' then true else column = nullif(current_setting('x.tenant', true), '')::type end. Unset matches nothing. A case and not an or (As of 2026-11): the same rows, but the planner's guess for an or turned a tenant's keyset page into a bitmap scan and a sort; a case keeps the ordered index scan. A table generated before keeps its or policy until drop policy / create policy with this text runs in a migration |
| rowSecureClient(client) · rowSecureClientWithReach(client, reach) | a statement sent outside a transaction while the provider has a tenant is wrapped: BEGIN [READ ONLY]; select set_config(…), the statement, COMMIT; the second skips it only for a statement the repository generated (inside withStatementAttribution; raw sql is wrapped always) and when reachesRowSecurity(text, reach()) proves it a plain select of tables open lists, calling only pure built-ins (row-security-calls.ts), all ASCII, naming nothing in guarded. reach() answering undefined, or the first: every one is wrapped |
| rowSecurityReachOf(client) | the catalog, read as the serving role: open (tables with row security off), guarded (tables with it on, views, materialized and foreign tables, the app schemas' functions not in C), typesRunCode (an app cast or operator written in SQL, or an app domain with a CHECK, exists: every bare statement is framed) |
| watchRowSecurityReach(client) | that reading kept current: LISTEN x_schema_changed, which migrate() and rollback() send with each migration's commit (announceSchemaChange); on it, or a re-dialled session, the reading is dropped at once (every bare statement framed) and read again. No LISTEN, or pooler: 'transaction': current() is always undefined |
| sentAs(wire, shown) (internal, statement-shown.ts) | the BEGIN batch's spliced text goes on the wire only; spans, db.statement text, error excerpts and the sweep read its bound twin (db.statement.values carries the values, as for any bound statement). Postgres's own log_statement logs the wire text, value included |
| beginWith(connection, begin, settings) / beginBatch | a root transaction's BEGIN with its settings: one message, BEGIN; select set_config('x.tenant', '<v>', true), on a connection marked simpleBatches (the Bun.SQL pin) when every name is row security's own (x.tenant, x.cross: any other may carry a token, and stays bound) and every value [A-Za-z0-9_.:-]{0,128}, spliced by literal(); else the BEGIN, then setLocal |
| statementTables(sql) | best effort, never a complete dependency list: each name after from / join / update / into / using, and a comma list straight after one, last part lowercased. A comma item after a join's condition (from a join b on …, c) is missed, so reachesRowSecurity never trusts it alone |
| assertRowSecurityBinds(client) | X_DB_ROW_SECURITY_BYPASSED for a superuser, a bypassrls role, or the owner of an unforced table — Postgres exempts all three |
| rowSecurityRolesSql() | x_app (nosuperuser nobypassrls) and x_migrator (bypassrls, owns tables), with default privileges from one to the other, as text |
| serveAsAppRole(client) | PGlite's superuser session: the roles, DML on every existing table and sequence to x_app, then set role x_app |
| generateMigration({ rowSecurity: { enabled, tenants } }) | x db gen: the policy per tenant table, typed off the column, recorded rowSecurity: true on the snapshot; off drops it |
| rowSecurityDifferences(entities, snapshot, option) / rowSecurityDrift(d) | the flag against the migrations, X_DB_ROW_SECURITY_DRIFT. checkDrift raises the same code from policyNames (catalog: an enabled AND forced table's policies) |
This layer catches forgetting, not hostile SQL in the app's own process: a raw set_config('x.cross', 'on', true) lifts it.
Read replicas
Opt in twice, and the second one is why it is safe.
// 1. the pool — an environment variable, read once by baseClient()
// DATABASE_REPLICA_URL=postgres://[email protected]:5432/app
// 2. the scope — reads inside it may be served by the replica
import { db, sql, withReplicaReads, withTransaction } from '@ultimat3/db';
declare const id: string;
await withReplicaReads(async () => {
await db().query(sql`select id from posts limit 20`); // -> replica
await db().execute(sql`insert into posts (id) values (${id})`);
await db().query(sql`select id from posts limit 20`); // -> primary, for the rest of the scope
await withTransaction(async (tx) => {
await tx.query(sql`select 1`); // -> primary, always
});
});| Rule | |
|---|---|
| unconfigured | no DATABASE_REPLICA_URL → one pool, statement for statement what it always was |
| no scope | no withReplicaReads → nothing routes, whatever is configured |
| read-your-writes | one write anywhere in the scope, at any depth, across any await, and every later read in it is the primary's |
| a transaction | always the primary — reserve() is delegated there, so BEGIN, the body and COMMIT are one connection on one server. A readOnly: true transaction leaves the scope clean |
| eligibility | select / table / values / a read-only with, minus locking reads, select … into and the functions a standby answers instead of refusing (pg_advisory_lock, set_config, nextval). Everything else is the primary's |
| across requests (As of 2026-11) | withReplicaReads(fn, { minPosition }): a read goes to the standby only once its pg_last_wal_replay_lsn() has passed minPosition — sampled once per positionCacheMs (50 ms) per client, checked BEFORE the breaker's admit() so a read sent to the primary for being behind never spends the half-open probe. Unknown or null is the primary. A PARKED replica is not asked at all (As of 2026-11-19): the read is the primary's with no statement sent to the standby, so an outage adds no replica timeout to a request that carries a position. parsePosition / formatPosition / primaryPosition (replica-position.ts); ReplicatedClient.primaryPosition() reads the primary's WAL position. The boot carries it as __Host-x-pos + x-ultimate-position |
| a replica that fails | the statement is re-run on the primary — exactly-once, because only plain reads are sent there and a 25006 refusal never executed. Three failures in a row park it for ten seconds |
| observability | client.stats (replica, primary, fallbacks, parked), and a db.replica_fallback warning per fallback |
The URL must name a read-only standby. The server's own 25006 refusal is the safety net under
a classifier that cannot be complete; pointed at a writable node a misroute becomes a write on the
wrong server, silently.
The boot opens the scope per request (@ultimat3/cli's runtime-replica-position.ts) when DATABASE_REPLICA_URL is set.
The drift contract
checkDrift() compares introspectSchema() against the snapshot the newest applied migration carries —
expectedSchema(migrations, ledger). declaredSchema(migrations) is the same read with the ledger
left out: the schema the files declare, applied or not, which is what x db gen diffs the app's
entities against so generation needs no database at all. One implementation, two callers — a
snapshot that meant one thing to the generator and another to drift is exactly the divergence the
ledger exists to prevent.
One X_DB_DRIFT, two detectors, and which is which matters. checkDrift() is the post-migrate
verification: it needs a database, so it runs where one is open — runMigrations in
@ultimat3/cli, which is x db migrate, x db reset and ROLE=migrate alike. It is the only one
that can see a column added by hand. The other, checkSourceDrift() (also @ultimat3/cli), hashes
the entity source against what x db gen recorded, opens nothing, and is x verify's drift step
— the gate runs in CI with no database, so a check that needed one could not run at all.
A migration the ledger has not recorded is not drift: expectedSchema reads the ledger's own
subset, so a database that simply has not migrated yet is pending, not divergent. Neither is a
table in the x_ namespace — x_migrations, the queue's tables, the outbox and every
@ultimat3/auth table are created by create table if not exists at boot and appear in no
snapshot, so appTables() drops them before the diff. introspectSchema() keeps its own narrower
exclusion (the ledger alone), reserving x_users for a schema view that wants it.
A CHECK the catalog no longer holds is drift, As of 2026-08-25 — by NAME.
pg_get_constraintdef answers Postgres' own rewriting (status in ('draft', 'published') reads
back as CHECK ((status = ANY (ARRAY['draft'::text, 'published'::text])))), so the catalog side is
read as conname alone and lands on TableDescription.checkNames, a separate field from the
declaration's checks. Only the declared side is judged, so a NOT NULL, an enumerated() column's
old anonymous form and an extension's own constraint are all silent; a declared one the catalog
does not hold is missing-check, whose fix: is the add constraint statement as one
psql "$DATABASE_URL" -c '…' command against that database, because the migration that declares
it is already in the ledger and x db migrate would apply nothing. There is
no changed-check: presence is a boolean, a predicate is text, and normalising the text is an
expression parser competing with the server's.
Nor is a relation an extension owns, As of 2026-08-24. create extension pg_stat_statements
in public is the CNPG, RDS, Supabase and Neon default, and its view read as unexpected-table
with x db gen "add pg_stat_statements" as the fix — so every deploy failed terminally and the fix
would have written an extension's internal view into the app's migration set. introspectSchema() now
excludes every relation Postgres records as extension-owned (pg_depend, deptype = 'e'), which is
ownership rather than a name: a pg_* prefix rule covers that view and misses postgis'
spatial_ref_sys. Views, materialised views and foreign tables go with them — no snapshot records
one, so counting them could only ever produce a finding an author has no way to clear. A table
someone created by hand carries no such dependency and is still unexpected-table.
Rendered output is pinned byte-for-byte:
X_DB_DRIFT: schema differs from migrations
cause: table "posts" has column "publish_at" not present in any migration
fix: x db gen "add publish_at"| Difference | cause | fix |
|---|---|---|
| live column, no migration | table "T" has column "C" not present in any migration | x db gen "add C" — the name goes through shellInertIdentifier(), and one it refuses is left OUT of the command rather than escaped into it (x db gen "add the undeclared column", the name in the cause) |
| migrated column, not live | table "T" is missing column "C" that migrations declare | x db migrate |
| live table, no migration | table "T" is not present in any migration | psql "$DATABASE_URL" -c '\d "T"' — one harmless command that shows the table — with the two repairs as its comment: a create table if not exists in a migration, then x db migrate, or drop table where nothing owns it. Never x db gen, which diffs a table nothing declares against nothing and writes no file (issue #345). The name goes through shellInertIdentifier(), and one it refuses leaves psql "$DATABASE_URL" # <the steps> |
| migrated table, not live | table "T" is declared by migrations but does not exist | x db migrate |
| index rebuilt differently | index "I" on "T" covers (…) / is unique / is descending / is partial, not what migrations declare | x db migrate |
| foreign key, rule moved | foreign key "K" on "T" (C) to "R" is on delete cascade, not what migrations declare — K is the constraint the database holds | psql "$DATABASE_URL" -c '<the drop constraint + add constraint pair>' — one command, against the drifted database — then x db migrate |
| column nullability differs (changed-column) | table "T" allows NULL in column "C" that migrations declare not null / forbids NULL in column "C" that migrations declare nullable | psql "$DATABASE_URL" -c 'alter table "T" alter column "C" set not null;' (or drop not null) — one command, then x db migrate. A table read from a schema other than public gets set search_path = "<schema>"; ahead of the statement, in the same psql -c word, so it and every table it references resolve there. A name shellInertIdentifier() refuses degrades every one of these three to psql "$DATABASE_URL" # <the steps>: still a command that runs, with no name in it |
| append-only trigger gone (missing-append-only-trigger, As of 2026-10-06) — raised as X_APPEND_ONLY_TRIGGER_MISSING, the one kind with its own code | table "T" is declared appendOnly, and its trigger ultimate_append_only is missing or disabled — a disabled (D) or replica-only (R) trigger counts as missing, because an ordinary session fires neither | psql "$DATABASE_URL" -c '<create or replace function …; drop trigger if exists "ultimate_append_only" on "T"; create trigger "ultimate_append_only" …>' against the drifted database, then x db migrate. Drop-if-exists first: a disabled trigger still exists, and a bare create trigger would fail on it (42710) |
| primary key differs (changed-primary-key, As of 2026-10-02) | table "T" has primary key (id) as constraint "T_pkey", and migrations declare (slug) — the constraint named is the one the DATABASE holds — compared in column ORDER; has no primary key when the database holds none | psql "$DATABASE_URL" -c '<drop constraint "<the live key>"; add constraint "T_pkey" primary key (…)>' — one command, against the drifted database — then x db migrate. Nullability is skipped for the DECLARED key's columns only |
checkDrift() returns every difference; assertNoSchemaDrift() throws the first. x db migrate renders
them all as findings and exits non-zero; a ROLE=migrate container throws the first one
(assertNoSchemaDrift, in runRole) and exits non-zero too, because the release phase has one channel —
the exit code — and a deploy that rolled on past a schema nobody can reconstruct is the failure
drift exists to catch. There is no x db drift, and x verify's drift step is the source
detector (checkSourceDrift), which needs no database and never calls this.
Views
EntityDescriptionLike.view (from entity({ view: { sql, materialized? } })) is emitted by
generate-view.ts, never by a table arm: create [materialized] view after every table, its
indexes with it when materialized, recorded on the snapshot as views: [{ name, materialized?,
create }]. Anything that moved — a query, an index, a retype, drop column or drop table under it —
drops every recorded view first and recreates every declared one last. The catalog reading never
fills views, so drift never reports one.
Append-only tables
EntityDescriptionLike.appendOnly (from entity({ appendOnly: true })) is a trigger, written by
x db gen (generate-append-only.ts) and recorded on the snapshot as appendOnly: true:
create or replace function "ultimate_refuse_append_only"() returns trigger language plpgsql as $append_only$ begin raise exception 'X_ENTITY_APPEND_ONLY: % on %.% is refused, the table is append-only', tg_op, tg_table_schema, tg_table_name using errcode = '23001', hint = '…'; end; $append_only$;
create trigger "ultimate_append_only" before update or delete on "ledger" for each row execute function "ultimate_refuse_append_only"();| | |
|---|---|
| Names | fixed: the trigger is ultimate_append_only on every table (a trigger name is per table, so no 63-byte truncation), the function one shared ultimate_refuse_append_only() |
| Refuses | UPDATE, DELETE, and the update arm of insert … on conflict do update. Not truncate — no row write, and destructive.ts already gates it |
| The error | message leads with X_ENTITY_APPEND_ONLY, SQLSTATE 23001 (restrict_violation, class 23: an integrity rule refused it, so never retried) |
| On / off | adding appendOnly emits the function (once per migration) and the trigger (drop-if-exists first on an existing table), down drops the trigger; removing it drops the trigger, down restores both. A dropped table takes its trigger with it; the function is never dropped |
| NOT NULL with no backfill | a NEW NOT NULL column needs a default (or .nullable()), and an EXISTING column cannot be turned NOT NULL: x db gen refuses both (X_MIGRATION_APPEND_ONLY_BACKFILL) rather than emit the usual contract step — the backfill it waits for is an UPDATE the trigger refuses, and a default fills no NULL already stored (generate-append-only-column.test.ts) |
| Engines | Postgres and PGlite alike (generate-append-only.live.test.ts, generate-append-only-embedded.test.ts) |
| Drift | introspectSchema() writes triggerNames (enabled, non-internal) on every table — the catalog half; appendOnly is the snapshot half, never read from the catalog |
Partitioned tables (entity({ partitionBy }))
As of 2026-11-09. EntityDescriptionLike.partition (PartitionDescriptionLike: physical column, interval from PARTITION_INTERVALS, ahead, retain?: { after, afterMs }) is what generate-partition.ts reads.
| Part | What |
|---|---|
| x db gen, new table | create table … partition by range ("<column>"), its indexes, then create or replace function ultimate_partitions(…) and one call: the current partition plus ahead, judged at APPLY time (now()) — never a retention sweep |
| partitionMaintenance(description, now, { from? }) | the function call, every value bound: creates ahead (and back to from's partition, sweeping nothing then); NAMES expired partitions with their state (attached/pending/detached), never drops one; null on a plain table |
| maintainPartitions(client, description, now, { from?, lockTimeoutMs? }) | what @ultimat3/jobs' partitions() runs: the call in a transaction with set local lock_timeout (PARTITION_LOCK_TIMEOUT_MS, 5 s; a wait past it is X_DB_LOCK_TIMEOUT, retryable), then per expired partition: comment (RETIRING_COMMENT), detach … concurrently outside any transaction, drop. A pending detach is finalized, a marked detached one dropped. Answers { created, dropped }. Never inside a caller's transaction |
| Names and bounds | <table>_pYYYYMMDD (lower bound), UTC; week is ISO; to_char, so DateStyle/TimeZone never move a bound. Hand-made children are never touched |
| Snapshot | the parent records partitioned: true and partitionInterval (snapshot only, never read off the catalog) |
| Refusals | X_MIGRATION_PARTITION_CHANGE: from x db gen when a recorded partitioned table loses partitionBy (partitionDropped), from the function at migrate time when it meets a plain table (adoption on a table the hand recipe already partitioned passes) |
| Interval change | refused by x db gen with X_MIGRATION_PARTITION_CHANGE (partitionRewidened): the snapshot records partitionInterval (parsed back by parseSnapshot), and partitions of another width would overlap |
| No default partition | by decision: a default partition forbids detach … concurrently, and creating a month it holds rows for scans and moves them under ACCESS EXCLUSIVE. A row past every partition is 23514; ahead is the scheduler-outage budget |
Proof: generate-partition-fixture.ts, on PGlite (generate-partition-embedded.test.ts) and Postgres (generate-partition.live.test.ts); a reader holding the parent: generate-partition-lock.live.test.ts; the sidecar round trip: generate-partition-sidecar.test.ts.
The schema dump
Imported from @ultimat3/db/schema-dump, never from the barrel (23.0.0): introspectCatalog,
emptyCatalog, the Catalog* types, renderSchemaDump, loadSchemaDump, compareSchemaDump,
reloadDifferences, schemaDumpDrift, schemaDumpDifferenceOf and unexpectedObjects. Three
callers run them — x db gen, x db migrate, the gate's drift step — and @ultimat3/db is in
every role's boot graph, where these ten modules served nothing. schema-dump-entry.test.ts holds
both halves: the barrel evaluates none of them, and no name has two homes.
renderSchemaDump(await introspectCatalog({ client })) is the schema as files: one directory per
object kind, numbered in the order a database is built in, one file per named object.
| Directory | Holds |
|---|---|
| 01_extensions/ | create extension if not exists — never plpgsql |
| 02_types/ | enums, domains |
| 03_sequences/ | sequences no column owns |
| 04_tables/ | the table; a serial column's sequence before it and its ownership after; replica identity full |
| 05_indexes/ | per table, indexes no constraint backs; replica identity using index |
| 06_foreign_keys/ | per table, alter table … add constraint |
| 07_views/ | views; a materialized view with its indexes |
| 08_functions/ | per name, overloads together |
| 09_triggers/ | per table |
- An object whose owner — its table, else itself — starts with
x_goes to aframework/twin of the same layout. The rule isFRAMEWORK_TABLE_PREFIX, the oneappTables()already holds. - Postgres' own spellings (
format_type,pg_get_expr,pg_get_*def), so a loaded dump renders the same bytes. Sorted in JS, never byorder by: a name's order follows the server's collation. - No timestamp, version, owner or grant. Every sequence option is written, defaults included.
- A name becomes a file name with everything outside
[A-Za-z0-9_-]percent-encoded. - A file over 500 lines (
SCHEMA_DUMP_MAX_LINES, thefilesizecei
