# @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](https://github.com/developerz-ai/ultimate/wiki/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 ```ts 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(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](#paging-a-raw-join-keyset) | | `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`](#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](#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](#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 `LedgerRow`s 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](#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 `alter`s 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 `.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 `.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, `__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 ""` โ€” 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 `
__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 "` 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](#indexes-built-concurrently-and-every-index-drop) | | `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](#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::`, 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](#diagnostics). `x db diagnostics` prints it | | `DbStatementEvent` / `StatementAttribution` (types, core's) | `As of 2026-11` (v31): every settled statement, both drivers, is one `db.` 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: ''` | | `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..$n` and never touch `.text`. A value that cannot be SENT โ€” an Invalid Date, a ragged array โ€” is `X_INVARIANT` before the driver is called, never `X_DB_UNAVAILABLE`; a `Uint8Array` inside an array is one `bytea` element. 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 a `SqlFragment` that `sql`/`raw` did 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-09` `identifier()` also refuses a NUL and a name over 63 **bytes** (`sql.ts`'s `MAX_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_`, bound back as `$n::`: 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). ```ts 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`). ```ts 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 โ€” `.sql` (the transaction) and `_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()` 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 "`, 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 `set_config` caller: `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 `column = nullif(current_setting('x.tenant', true), '')::type or current_setting('x.cross', true) = 'on'`. Unset matches nothing | | `rowSecureClient(client)` | a statement sent outside a transaction while the provider has a tenant is wrapped: `BEGIN [READ ONLY]`, `set_config`, the statement, `COMMIT` | | `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. ```ts // 1. the pool โ€” an environment variable, read once by baseClient() // DATABASE_REPLICA_URL=postgres://reader@replica.internal: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" # ` | | 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 ''` โ€” 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 = "";` 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" # `: 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 ''` 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 '"; 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`: ```sql 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 ("")`, 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 | `
_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 a `framework/` twin of the same layout. The rule is `FRAMEWORK_TABLE_PREFIX`, the one `appTables()` 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 by `order 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`, the `filesize` ceiling) is split `.1.sql`, `.2.sql`; `loadSchemaDump()` joins the parts in numeric order. - A partitioned table is rendered with `partition by`, each partition `partition of โ€ฆ for values` in its root's file, parent first (`partition-order.ts`); a partition's attached indexes, cloned keys and cloned triggers are not, the parent's recreate them. `As of 2026-11-06`. - Row security is `10_policies/
.sql`: `enable`, `force`, then each policy with every clause (`catalog-policies.ts`, `schema-dump-policies.ts`). `As of 2026-11-06`. - What cannot be spelled โ€” inheritance children, foreign tables, composite and range types, aggregates, a policy on a relation the dump does not create, rules, extended statistics, a column's non-default `storage`, a materialized view created `with no data`, and a trigger on a relation the dump does not create โ€” is named in `unrendered.sql` as comments. - A generated column is spelled `stored` or `virtual` (Postgres 18), as `attgenerated` says. `loadSchemaDump()` runs kind by kind, the framework twin first, each file in a savepoint. A file refused with `42P01`, `42883` or `42704` โ€” "not created yet" โ€” is retried after the rest; a pass that loads nothing ends with `X_SCHEMA_DUMP_DRIFT` naming the file. **Not the snapshot.** `.snapshot.json` is `x db gen`'s diff base, in the entity's vocabulary: both sides of that diff are generator spellings. The dump is what the database holds, in SQL: both sides of ITS comparison are catalog spellings. Neither can be compared with the other. Which engine, where the files live, when they are written and what holds them is `@ultimat3/cli`'s (`x db gen`, `x db migrate`, the `drift` step). This package renders, loads and compares. ## The embedded database No `DATABASE_URL` means no Docker: `pgliteClient()` runs Postgres as WASM inside this process. The module is resolved on the first statement, never at import, so an image that only ever talks to a managed Postgres never loads it. ```ts import { branchPglite, pgliteClient, pgliteDataDir, setDbClient } from '@ultimat3/db'; declare const services: { readonly db: { readonly url: string } }; const dev = pgliteClient({ dataDir: pgliteDataDir(services.db.url) }); // or memory:// await dev.ping(); // pay the ~3s boot before serving setDbClient(dev); const branch = await branchPglite('feature_x', { from: '.x/pgdata' }); setDbClient(pgliteClient({ dataDir: branch.dataDir })); ``` PGlite has no `CREATE DATABASE ... TEMPLATE`, so `branchPglite()` copies the data directory โ€” close the source first, and expect `X_NOT_IMPLEMENTED` on `memory://`, which has no directory to copy. Branch names go through the same `assertBranchName()` as the Postgres path: here the name lands in a filesystem path, so an unvalidated one is traversal rather than a typo. ### One session, so callers take turns Embedded Postgres is a single session, not a pool. `pgliteClient()` is therefore `ReservableClient`: `withTransaction()` and `readOnlyQuery()` pin it, and every other statement waits for its turn. Without that pin two concurrent units of work each run `BEGIN` on the same connection โ€” the second `COMMIT` commits the first's rows and the first `ROLLBACK` finds no transaction left to undo. | On a pooled server | Embedded, on one session | |---|---| | concurrent transactions run side by side | they run consecutively; throughput is one at a time | | a statement outside a transaction gets its own connection | it waits for the open transaction to finish | | `enqueue(input, { outbox: false })` inside a transaction survives its rollback | it joins that transaction, and rolls back with it | The last row is the one divergence a second connection would remove and PGlite cannot: a statement issued *inside* an open transaction's scope runs immediately rather than waiting for a turn that scope is already holding, because waiting would be a deadlock with no error to explain it. ## Bulk load: `copyIn` `As of 2026-11-11`. `postgresClient().copyIn(target, rows)`, `target` a parameterless `copy
() from stdin` built with `identifier()`/`join()`, streams `rows` (each the column list's values, in order) through `Bun.SQL`'s `writable()` in the text format and resolves with the server's count. One statement: all or nothing. `copy-in.ts`; `copy-in.live.test.ts`. 100k rows ร— 4 columns: ~0.5 s against ~1.9 s for the same rows as chunked `insert`s (loopback, Postgres 17, a loaded box). | Case | | |---|---| | a cell | encoded as the bound parameter would be: `\N` for null, ISO instant for a `Date`, bytea hex, an array literal; a plain object is `X_SQL_UNSAFE` and the stream aborts โ€” nothing stored | | the target | exactly `copy [.] (, โ€ฆ) from stdin`, no `;`, no value โ€” anything else (`to program`, a file path, a second statement) is `X_SQL_UNSAFE` before any send | | the caller's `rows` iterator throws | `X_INVARIANT` naming the throw; the stream aborts, nothing stored, a pin stays usable (never `X_DB_UNAVAILABLE`) | | a server refusal (`23505`, `22P02`, โ€ฆ) | typed by SQLSTATE like any statement; the connection stays usable | | a pin (`reserve()`), a `DbTx` | the copy is that transaction's, under the pin's deadline, rolled back with it | | the replica router | forwarded to the primary, and the `withReplicaReads` scope is marked written | | `canCopyIn(client)` | `false` for PGlite and a fake, and whenever a row-security settings provider is INSTALLED, tenant in scope or not: Postgres refuses `COPY FROM` under RLS (`0A000`). Callers fall back to `insert` | ## A pooled read stops when its caller does `As of 2026-11-09`. A `select` sent on the pool, in flight when the ambient `ctx.signal` aborts, is cancelled on the SERVER (`Bun.SQL`'s `cancel()`, `57014`) and its connection goes back at once โ€” before, a hung-up caller held it until `statement_timeout`, so firing requests and disconnecting emptied the pool past any rate limit. `statement-cancel.ts`; `statement-cancel.live.test.ts`. | Case | | |---|---| | a pooled `select`, abort while it runs | cancelled. A client hang-up throws `X_ABORTED`; a coded reason (`X_TIMEOUT`, a job's) is thrown as itself | | a write (`insert`/`update`/โ€ฆ, or a `with` that may hide one) | never cancelled: a click followed by a navigation must keep landing | | any statement on a pin (`withTransaction`, `readOnlyQuery`) | never cancelled here: aborting the statement aborts the transaction, which `transaction-guard.ts` decides | | a statement sent after the abort | sent as before: a job's settle and a fenced write go out past it on purpose | | no context, or PGlite | nothing to cancel: in-process, one session | ## Pool sizing by role `ROLE` picks the profile โ€” a `worker` draining a queue must not size like a `web` process. | Role | max | statement timeout | idle timeout | lock timeout | acquire timeout | |---|---|---|---|---|---| | `web` | 20 | 10s | 30s | none | 5s | | `sync` | 10 | 10s | 60s | none | 5s | | `worker` | 8 | 120s | 30s | none | 10s | | `scheduler` | 2 | 15s | 60s | none | 10s | | `migrate` | 1 | none | 10s | 3s | none | | `replicator` | 4 | none | 60s | none | none | The statement timeout is pinned per connection via libpq `options=-c statement_timeout=`, and it does reach the backend: `client.live.test.ts` asserts `current_setting('statement_timeout')`, which is the only reading a DSN test cannot fake. `Bun.SQL` is reached lazily, so importing this package never opens a socket. **That setting is MERGED into the operator's own `options`, never assigned over them** (`As of 2026-08`). `?options=-c search_path=app` in `DATABASE_URL` survives on every role, and the role's `statement_timeout` is appended to it; if the URL sets `statement_timeout` itself, the **role wins** โ€” it is a bound the pool is sized around โ€” and every other flag is kept. It is emitted for all six roles, `migrate`'s and `replicator`'s `0` included: `0` is "this role may take as long as it takes", and left unsaid a server-side `alter database โ€ฆ set statement_timeout` would kill the one role that has to outlive it. Before this, `set` replaced the whole value and only on the roles with a non-zero timeout, so a `search_path` survived on `migrate` and vanished on `web` โ€” the role that runs the migrations and the role that serves the traffic reading different schemas. **`DATABASE_POOLER=session|transaction` names a pooler in the path** (`As of 2026-11-02`): `postgresClient({ env })` reads it, with `ROLE` and, absent a `url`, `DATABASE_URL`, from that one environment (`process.env` when absent); `client.pooler` is the answer everything after asks. Behind a pooler the unanswered-statement deadline grows by `poolerWaitMs` (default `POOLER_WAIT_MS`, 120 s, PgBouncer's `query_wait_timeout`): the server's bound starts only once the pooler assigns a backend, so a saturated pooler is not a dead path. Set, neither bound is sent as `options`, the operator's own stay and an empty one is not emitted; the bounds become `alter role` ([`docs/ops/04-datastores.md`](../../docs/ops/04-datastores.md#pooling-and-the-trap-under-it)). `statementBound(client)` reads both as the session does, `{ applied, expected }` per setting, in ms. **`idleInTransactionMs`** (`As of 2026-11-02`) is sent as `idle_in_transaction_session_timeout` beside the statement bound: `web`, `sync` 30 s, `worker`, `scheduler` 120 s, `migrate`, `replicator` 0. Past it the server closes the transaction, `X_DB_STATEMENT_FAILED` with `sqlState: '25P03'`. **`DATABASE_POOL_MAX` overrides `max`** (`As of 2026-08`), and it is the only pool knob an operator can turn without shipping an image โ€” 400 `web` pods ร— the frozen `max: 20` is 8,000 backends. A value that is not a positive integer refuses at boot rather than falling back. **`acquireTimeoutMs` bounds a plain statement and `reserve()` alike** (`As of 2026-11-02`, for the statement), because queueing turns exhaustion into a hang: `/readyz`'s `select 1` joins the same queue, the kubelet kills the pod, and the replacement inherits the same saturated database. 0 waits, which is what a run-once role wants. `max` is one count in front of `Bun.SQL`, FIFO: a statement holds a slot until it settles, a pin until it is released, and a statement on a pin takes none. **A statement nobody answers replaces the pool** (`As of 2026-11-02`). `statement_timeout` is the server's, so it cannot fire when the server or the path is gone, and the kernel's retransmit window is about 15 minutes. A statement unanswered past `statementTimeoutMs` + 5 s is `X_DB_UNAVAILABLE`, its cause naming the bound and the statement; an autocommit write may have landed. The old pool closes in the background (`db.pool.retired`, at error), the next statement opens a new one, a statement still queued moves to it unsent, and a `LISTEN` is dialled again, `onListening` firing as on any re-dial. `statementTimeoutMs: 0` has no deadline. **A statement on a pin โ€” a transaction's โ€” is bound the same way** (`As of 2026-11-06`), against the `statement_timeout` in force on that connection: the role's, until a `set_config('statement_timeout', โ€ฆ)` or `SET [LOCAL] statement_timeout` it answered moves it (`0`: no deadline), and the role's again after `COMMIT`/`ROLLBACK`. After a miss the pin sends nothing more: its `ROLLBACK` is refused `X_DB_UNAVAILABLE` at once rather than waiting out a second bound, and a missed `COMMIT` is `X_DB_COMMIT_UNKNOWN`. `X_DB_UNAVAILABLE` is unclassified for retry, so a job worker re-runs the attempt: a write that landed runs again, at least once, as every job. `reserve()`'s two waits share one `acquireTimeoutMs`. The cost is one unref'd 1 s timer per pool while statements are in flight, and a set insert and delete per statement: measured 2026-11-02 on Postgres, 20,000 sends a side, `max: 4`, p50 216-268 ยตs against 227-258 ยตs before, inside the noise. **`lockTimeoutMs` bounds a *wait*, never the work.** `alter table โ€ฆ add column` takes `ACCESS EXCLUSIVE`; a long `SELECT` holding `ACCESS SHARE` makes it queue, and Postgres' lock queue is FIFO, so every later query on that table queues behind the ALTER. `migrate` runs `statement_timeout = 0`, so nothing else would ever end that wait. `migrate()` emits it as `SET LOCAL lock_timeout` inside each migration's own transaction โ€” it reverts at COMMIT, so a DDL value never leaks onto the session the ledger insert runs on. ## `LISTEN` on a session of its own A pooled statement cannot hold a subscription: the next one runs on another connection. Both clients hold ONE session beside the pool for it. ```ts import { postgresClient } from '@ultimat3/db'; const client = postgresClient({ url: 'postgres://localhost:5432/app_test' }); const subscription = await client.listen( 'x_jobs_wake', (payload) => console.log('notified', payload), () => console.log('listening'), // again after every re-dial ); await subscription.unlisten(); ``` | Fact | Detail | |---|---| | the session | `Bun.SQL.listen` on the pooled client โ€” outside `max`, untouched by `idleTimeout`, ended by `unlisten()` or `close()`; PGlite's own `listen` on the embedded one. Every channel a client listens on shares it | | `onListening` | fires each time the subscription is (re-)established. The driver re-dials a session that died, and what was notified in between is LOST โ€” re-read the source of truth there | | the channel | a lower-case identifier of at most 63 characters, refused otherwise before a driver sees it | | a transaction-pooling proxy | `listen()` resolves and nothing is ever delivered. Only a notification that arrives proves the path | | `canListen(client)` | `true` for both shipped clients. `false` for a replicated pair โ€” listen on the primary it was built from, as the boot does | `@ultimat3/jobs`' `startQueueWake` is the framework's one caller. ## Migrations `As of 2026-11-02`: **a foreign key on a live table** is written to the deferred step (`not valid`, then `validate constraint`, an old key held until the contract phase), **a CHECK** `not valid` in the transaction with its validate deferred, **a column drop** takes two releases (`retired`, `X_MIGRATION_ROLLING_UNSAFE`), and **`migrate()` / `rollback()` send it again** (a transactional step whole, a `-- transaction: false` step per statement) when `lock_timeout` fires (`lockRetries`, default 5). The user-facing page: `wiki/Migrations-And-Backfills.md`. **A column becoming NOT NULL is written whole** (`As of 2026-11-17`, `not-null-contract.ts`): a NOT NULL column added with no default is added nullable in the transaction, and an existing column turned NOT NULL โ€” or that one โ€” is contracted in the `-- transaction: false` step: `add constraint "__not_null_check" check (โ€ฆ is not null) not valid`, `validate constraint`, `set not null` (proved from the check, no full-scan lock), the check dropped. Each file's snapshot says what its SQL leaves โ€” the expand file records the column nullable โ€” so a fresh database is never `changed-column`, and the next `x db gen` has nothing left to write. A NULL row stops the contract step alone (`X_DB_STATEMENT_FAILED` naming the check); backfill those rows, then `x db migrate` re-runs it. A key column owes no contract (`add primary key` makes it NOT NULL). It replaced a `-- backfill โ€ฆ, then: โ€ฆ set not null;` comment whose file recorded NOT NULL: `x db migrate` was `X_DB_DRIFT` on every database, fresh ones included. **A declared collation** (`As of 2026-11`, `text().collate('C')`): `collate "C"` follows the type in a `create table` or `add column`, the snapshot records `collation` only when declared, and declaring or dropping it on an existing column is `alter column โ€ฆ type collate "C"` (or `"default"`) in place, its reverse in `down`. A retype states the collation it keeps โ€” Postgres resets it otherwise (`generate-collation.test.ts`). Drift does not read the catalog's collation, as it reads no column type. `migrate()` takes the advisory lock by **polling** `pg_try_advisory_lock(4919202607)` every 500ms until `lockWaitMs` (default 60s) and then throwing `X_MIGRATE_CONCURRENT` (`As of 2026-08`). `pg_advisory_lock` has no timeout, and a predecessor OOM-killed on a partition keeps its backend โ€” and the lock โ€” for hours, so a deploy hook sat inside one statement printing nothing while `helm upgrade --wait` blocked and `backoffLimit` never fired, because a job that never finishes never fails. It then ensures `x_migrations` (`id, name, checksum, applied_at, app_version, duration_ms`, and `destructive` โ€” added `if not exists`, written at apply from `isDestructiveMigration(up)`), audits, then applies each pending migration inside its own transaction โ€” or, for one marked `-- transaction: false`, one autocommitted statement at a time ([Indexes built concurrently](#indexes-built-concurrently-and-every-index-drop)). It refuses **before applying anything** when: - the ledger records a migration this build does not ship **and** its `app_version` differs from the running one โ€” another version owns the database; or - an applied migration's `up` SQL no longer matches its recorded checksum. **Except a rollback** (`As of 2026-10-05`, `migrate-rollback.ts`): when every unknown ledger row sorts after the newest migration this build ships, and this build has nothing left to apply, the ledger is an older image rolled back onto a newer build's schema. Nothing is applied, the rows are reported in `ahead` and logged as `ultimate migrate ledger ahead of build`; any other unknown row is still `X_MIGRATION_CONFLICT`. A row ahead whose `destructive` bit is `true` refuses that rollback (`X_MIGRATION_ROLLBACK_DESTRUCTIVE`, `As of 2026-11`) unless `ROLLBACK_ALLOW_DESTRUCTIVE` names it (comma-separated ids); a `null` bit โ€” a row applied before the ledger kept one โ€” still warns. `readLedger()` reads the bit through the row's JSON, so a ledger an older release created answers `null` rather than `42703`. The refusal is the ROLLED-BACK build's code: it protects from the release after the one that ships it. Report (`--json`): `{ applied: [{ id, name, durationMs }], skipped: [id], durationMs, appVersion, ahead: [id] }`. ## A loop of queries that is deliberate says so `As of 2026-08`: ```ts return expectedQueryLoop('one indexed lookup per text field beats one unindexed OR', async () => { for (const field of fields) hits.push(...(await repo.list({ where: [match(field)] }))); return hits; }); ``` One mechanism, and only one: no comment pragma, no config list of exempt call sites (axiom 1). `reason` is required and non-blank โ€” an exemption with no argument is a pragma, and the next reader cannot tell a considered loop from a silenced one. | | | |---|---| | Scope | core's `asyncContext('the expected-loop reason')`, never a `new AsyncLocalStorage` here: it survives every `await` at any depth, and two loops running at once never read each other. Nesting keeps the innermost reason | | What it carries | `DbStatementEvent.expected`, stamped by both funnels at settle time โ€” a diagnostic judging a whole request runs after every scope in it closed | | What it suppresses | a **verdict**, never a statement. The SQL is still sent, still observed, still a span: only the thing that warns is told the author already answered | | What it costs | nothing without a diagnostic โ€” the reason is read only while `db.statement` has a subscriber | The framework's own deliberate loops declare themselves at source: `migrate()` and `rollback()` (one transaction per migration, so a failure leaves an exact ledger) and `@ultimat3/admin`'s cross-entity search (one indexed lookup per text field). **Every ambient scope in this package opens through `asyncContext(subject)` from `@ultimat3/core`** โ€” the transaction store, the attribution pair and this reason โ€” and none of the three constructs an `AsyncLocalStorage`, `As of 2026-08`. What changed is what a browser bundle does with these three modules: a bundler stubs `node:async_hooks` to `{}`, so the module-scope `new` threw `TypeError: undefined is not a constructor` at module **evaluation** โ€” before a line of app code ran, and taking every importer of the file with it. Now the module evaluates, a read answers `undefined` (nothing is in flight in a browser, so that is the true answer), and a write throws `X_ASYNC_CONTEXT_UNAVAILABLE` naming the scope it could not open. A server saves no allocation โ€” the store is built on the first `get()` **or** `run()`, so a read constructs it too. What the laziness costs is nothing observable: `getStore()` outside a scope answers `undefined` whether the storage was ever constructed or not. Not a claim that the whole package bundles: `pglite-branch.ts` imports `node:fs/promises`, which is a separate question. The rule is a **build error**, not a convention: `scripts/async-context-guard.ts` refuses a `new AsyncLocalStorage` โ€” and the import that binds the class, aliased or namespaced โ€” anywhere but `packages/core/src/async-context.ts`, and `scripts/async-context-guard.test.ts` runs it over the tree in the gate's `unit` step. ## A statement knows who compiled it `As of 2026-08`: `DbStatementEvent.attribution` is no longer always `undefined`. ```ts return withStatementAttribution('members', 'findById', () => client.query(sql`select * from members where id = any(${ids})`), ); ``` | | | |---|---| | Scope | core's `asyncContext()`, `expectedQueryLoop()`'s own shape: it survives every `await` at any depth, and nesting keeps the innermost pair | | What it carries | `DbStatementEvent.attribution`, stamped by both funnels at settle time, next to `expected` | | Producer | `@ultimat3/entity`'s `postgresRepo` โ€” the last caller that still knows the entity and the operation once the SQL exists | | What it costs | nothing unsubscribed โ€” `subscribed('db.statement')` is read first, and with no subscriber `fn` runs directly; no scope entered, no object allocated | Hand-written SQL, a migration, a health probe, `x db` commands and `@ultimat3/jobs`' own queue statements still carry no `attribution` โ€” nothing above them knows an entity to name, so the field is optional and a detector must fall back to the statement text either way. ## Error codes Every driver failure is typed by the **SQLSTATE the server sent**, `As of 2026-08`. The state was always on the error and nothing read it, so a `23505` from two clicks racing a signup answered "cannot reach the database" and paged on-call for an outage that never happened. The table (`sqlstate.ts`) is closed; everything outside it is still `X_DB_UNAVAILABLE`, unchanged. **Four of them carry `retry: "retryable"` in `--json`, `As of 2026-08-23`** โ€” `DB_ERROR_RETRY`: `X_DB_SERIALIZATION_FAILURE`, `X_DB_LOCK_TIMEOUT`, `X_DB_POOL_EXHAUSTED`, `X_MIGRATE_CONCURRENT`. Each is a resource that frees, so the same call has a real chance of a different answer with no edit in between. Everything else keeps core's fail-closed `terminal`, and is deliberately left UNREGISTERED rather than registered as terminal: `@ultimat3/jobs` dead-letters a registered `terminal` on attempt 1, so classifying `X_DB_UNAVAILABLE` that way would dead-letter every in-flight job the moment Postgres fails over. | Code | Meaning | |---|---| | `X_DB_UNAVAILABLE` | no reachable database, or a SQLSTATE the table does not name; `fix:` names `DATABASE_URL` | | `X_DB_UNIQUE_VIOLATION` | `23505` โ€” `fix:` names `upsertAll(rows, { onConflict: [...] })` and the constraint the server named | | `X_DB_FOREIGN_KEY_VIOLATION` | `23503` | | `X_DB_SERIALIZATION_FAILURE` | `40001` / `40P01`, and an exhausted `withTransaction(fn, { retry: n })` budget | | `X_DB_TRANSACTION_ABORTED` | a statement failed inside a transaction and its error was caught; the server rolled the unit of work back. Also any `COMMIT` answered with the tag `ROLLBACK` | | `X_DB_COMMIT_UNKNOWN` | `COMMIT` was sent and the connection failed before the answer: durable or rolled back, unknowable from here | | `X_DB_SIBLING_SCOPE_TIMEOUT` | a nested `withTransaction` waited past `siblingWaitMs` for a sibling scope that never finished | | `X_DB_STATEMENT_TIMEOUT` | `57014` โ€” the statement ran past `statement_timeout` | | `X_DB_LOCK_TIMEOUT` | `55P03` โ€” it waited past `lock_timeout` for a lock it never got; `migrate()` raises it only once `lockRetries` are spent | | `X_MIGRATION_ROLLING_UNSAFE` | a drop or rename the previous release would still read, from `x db gen`, the `drift` rail past `rollingSince`, or `migrate()` with a retire and its drop both pending in production | | `X_DB_POOL_EXHAUSTED` | `53300` / `53200`, or a statement or `reserve()` past `acquireTimeoutMs` | | `X_DB_DRIFT` | live schema differs from migrations | | `X_MIGRATION_CONFLICT` | ledger app-version fence or checksum mismatch โ€” never for rows that are all newer than the build (a rollback). A mismatch's fix restores the file: `git log -- packages/db/migrations/.sql`, then `git checkout -- โ€ฆ` the revision whose checksum the ledger names, then `x db gen ""` | | `X_MIGRATE_CONCURRENT` | another migrator still held the lock when the wait ran out | | `X_MIGRATION_IRREVERSIBLE` | generated `down` would lose data | | `X_SQL_UNSAFE` | non-bindable interpolation, or an unsafe identifier/branch name | | `X_BRANCH_EXISTS` | branch database already exists (or is the connected one) | | `X_SCHEMA_DUMP_DRIFT` | the committed schema dump is not what the migrations produce, or does not load back | | `X_NOT_IMPLEMENTED` | branching an in-memory PGlite โ€” a copy needs a directory | | `X_ENV_MISSING` | core's โ€” `DATABASE_POOL_MAX` is set to something that is not a positive integer, or `DATABASE_POOLER` to something that is neither `session` nor `transaction` | | `X_DB_POOLER_OPTIONS_REFUSED` | `08P01` with `unsupported startup parameter`: a pooler refused the libpq `options`. `DATABASE_POOLER`, then `alter role` | | `X_DB_POOLER_SESSION_REQUIRED` | `migrate` or `replicator` under `DATABASE_POOLER=transaction`, before a socket | | `X_DB_STATEMENT_BOUND_LOST` | a report, never thrown by a statement: `lostStatementBound(statementBound(client), role, pooler)` | ```bash x db migrate --json x db gen "add publish_at" x db branch list --json x db branch create feature_x x db branch delete feature_x ``` **Drift has no subcommand of its own.** The database half runs *inside* `x db migrate`, which calls `checkDrift()` on the connection it already holds and exits non-zero on a difference; the source half is the `drift` step of `x verify`, which hashes entity source against what `x db gen` recorded and opens no database. Two questions, two owners, and no `drift` subcommand under `x db` โ€” the `DB_SUBCOMMANDS` set is `gen`, `migrate`, `reset`, `studio`, `branch`, `backfill`. ### Error classes Every error class `src/index.ts` exports, for `instanceof` inside one process. Across a wire or a job boundary the class is gone and the `code` is what survives โ€” match on that. | Class | Code | Declared in | |---|---|---| | `DbError` | any `DbErrorCode` โ€” `DB_ERROR_CODES`, including the SQLSTATE codes a driver error maps to (`DB_SQLSTATE_CODES`) | `src/errors.ts` | ## Supporting exports `As of 2026-11-02`. | Name | What | |---|---| | `unretiredColumnsIn(up)` | the columns this `up` takes back, as `columnKey`: a retire before it earns no later drop | | `RollingUnsafeKind` | `'drop-column'`, `'rename-column'` or `'rename-table'`: the closed list | | `RollingUnsafeStatement` | one finding of `rollingUnsafeStatements`, carrying its `kind` |