@ultimat3/db 31.43.0 → 31.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -453,7 +453,7 @@ create trigger "ultimate_append_only" before update or delete on "ledger" for ea
453
453
  | Refuses | UPDATE, DELETE, and the update arm of `insert … on conflict do update`. Not `truncate` — no row write, and `destructive.ts` already gates it |
454
454
  | The error | message leads with `X_ENTITY_APPEND_ONLY`, SQLSTATE `23001` (`restrict_violation`, class 23: an integrity rule refused it, so never retried) |
455
455
  | 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 |
456
- | 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 `-- backfill …, then: set not null` note — that backfill is an UPDATE the trigger refuses, and a default fills no NULL already stored (`generate-append-only-column.test.ts`) |
456
+ | 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`) |
457
457
  | Engines | Postgres and PGlite alike (`generate-append-only.live.test.ts`, `generate-append-only-embedded.test.ts`) |
458
458
  | Drift | `introspectSchema()` writes `triggerNames` (enabled, non-internal) on every table — the catalog half; `appendOnly` is the snapshot half, never read from the catalog |
459
459
 
@@ -707,6 +707,8 @@ await subscription.unlisten();
707
707
 
708
708
  `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`.
709
709
 
710
+ **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 "<t>_<c>_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.
711
+
710
712
  **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 <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.
711
713
 
712
714
  `migrate()` takes the advisory lock by **polling** `pg_try_advisory_lock(4919202607)` every 500ms
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/db",
3
- "version": "31.43.0",
3
+ "version": "31.44.0",
4
4
  "description": "Postgres access, transactions, migrations and drift detection",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -45,7 +45,7 @@
45
45
  "test": "bun test"
46
46
  },
47
47
  "dependencies": {
48
- "@ultimat3/core": "31.43.0"
48
+ "@ultimat3/core": "31.44.0"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@electric-sql/pglite": ">=0.5.0"
@@ -12,6 +12,7 @@ import type { ColumnDescriptionLike, EntityDescriptionLike } from './entity-shap
12
12
  import type { Plan } from './foreign-key-plan';
13
13
  import { appendOnlyBackfillRefused } from './generate-append-only';
14
14
  import type { ColumnDescription } from './introspect';
15
+ import { contractNotNull, type NotNullContracts } from './not-null-contract';
15
16
  import { identifier } from './sql';
16
17
  import { sqlType } from './sql-type';
17
18
  import { statementsOf } from './statement-split';
@@ -89,10 +90,10 @@ export function retypeOverDefault(
89
90
 
90
91
  /**
91
92
  * `set default` / `drop default` and `drop not null`, each with its reverse in `down` — the shape
92
- * `redefineIndex` (`index-ddl.ts`) gives a moved index. Becoming NOT NULL is deliberately NOT a
93
- * bare `set not null`: rows already holding `NULL` make it fail inside `ROLE=migrate`, so it gets
94
- * the expand/contract note `diffTable` writes for a NOT NULL column added to a populated table —
95
- * refused on an append-only table, whose backfill the trigger would refuse.
93
+ * `redefineIndex` (`index-ddl.ts`) gives a moved index. Becoming NOT NULL is the CONTRACT
94
+ * (`not-null-contract.ts`), in the non-transactional step, never a bare `set not null` that holds
95
+ * the table for a full scan — refused on an append-only table, whose backfill the trigger would
96
+ * refuse. A column the primary key covers owes none: `add primary key` makes it NOT NULL.
96
97
  *
97
98
  * A default this generator cannot render (`hasUnrenderedDefault`) moves nothing: dropping the one
98
99
  * the database holds would lose a rule the entity still states, and `unrenderedOf` already reports
@@ -103,6 +104,7 @@ export function alterColumnInPlace(
103
104
  column: ColumnDescriptionLike,
104
105
  recorded: ColumnDescription,
105
106
  plan: Plan,
107
+ contracts: NotNullContracts,
106
108
  ): void {
107
109
  const { table } = entity;
108
110
  const alter = `alter table ${identifier(table).text} alter column ${identifier(column.column).text}`;
@@ -132,8 +134,6 @@ export function alterColumnInPlace(
132
134
  // That backfill is an UPDATE, and an append-only table's trigger refuses every one. Refused even
133
135
  // with a default now declared: `set default` fills no row that already holds NULL.
134
136
  if (entity.appendOnly === true) throw appendOnlyBackfillRefused(entity, column, 'made-not-null');
135
- // `drop not null` in `down` is a no-op on a column that never became NOT NULL, so the reverse is
136
- // right whether or not the backfill and its `set not null` were ever run.
137
- plan.up.push(`-- backfill ${identifier(column.column).text}, then: ${alter} set not null;`);
138
- plan.down.push(`${alter} drop not null;`);
137
+ if (entity.primaryKey.includes(column.column)) return;
138
+ contractNotNull(table, column.column, contracts);
139
139
  }
@@ -142,17 +142,16 @@ export function unexpectedColumn(table: string, column: string): DriftDifference
142
142
  /**
143
143
  * The column exists on both sides and one of them lets it be `NULL`.
144
144
  *
145
- * This is the finding the expand/contract flow needs and never had. `generate.ts` emits a `NOT
146
- * NULL` add as nullable plus a `-- backfill "c", then: … set not null;` comment, because the
147
- * strict version cannot succeed on a populated table — and phase 2 is a comment, so it is a thing
148
- * a human has to remember. Nobody did, and `compareTable` compared columns by name and by type
149
- * while `snapshotOf` had recorded `nullable` all along, so the column stayed nullable forever
150
- * against an entity schema that said otherwise, with `ok: true` on every check. The first
151
- * `undefined` write then lands as `NULL` and crashes three services away from the migration.
145
+ * Nullability compared at all because a column left nullable against an entity that says NOT NULL
146
+ * once read `ok: true` on every check, and the first `undefined` write landed as `NULL` three
147
+ * services away from the migration.
152
148
  *
153
- * `x db gen` is deliberately not the fix: it diffs types and indexes and has never emitted a
154
- * `set not null`, so naming it would send a reader to a command that generates an empty migration.
155
- * The fix is the statement, run against this database (`repair`).
149
+ * Never the expand/contract flow's own state: `x db gen` records an expanded column nullable until
150
+ * the step that contracts it has run (`not-null-contract.ts`), so a database the migrations left
151
+ * is never this finding. What remains is a database that LEFT them — a `drop not null` by hand, or
152
+ * an expand file an older generator wrote with a `-- backfill` note and a NOT NULL snapshot
153
+ * (wiki/Upgrading.md has that one's two `x db gen` runs). A migration is not the fix for the first:
154
+ * every database that is already right would replay it. So the fix is the statement (`repair`).
156
155
  */
157
156
  export function changedColumn(
158
157
  schema: string,
@@ -119,9 +119,9 @@ export type AppendOnlyBackfillArm = 'added' | 'made-not-null';
119
119
 
120
120
  /**
121
121
  * A column an append-only table must hold NOT NULL with no default to fill it. Both arms of the
122
- * diff would emit `-- backfill …, then: set not null` — `diffTable` for a new column,
123
- * `alterColumnInPlace` for an existing one — and on this table that backfill is an UPDATE the
124
- * trigger refuses: an instruction nobody can carry out, leaving the column nullable forever.
122
+ * diff would add it nullable and contract it to NOT NULL (`not-null-contract.ts`) — `diffTable` for
123
+ * a new column, `alterColumnInPlace` for an existing one — and on this table the backfill between
124
+ * the two is an UPDATE the trigger refuses: a contract no existing row can ever satisfy.
125
125
  * Refused at generation instead; a default is the one way every row gets a value with no UPDATE.
126
126
  */
127
127
  export const appendOnlyBackfillRefused = (
package/src/generate.ts CHANGED
@@ -7,7 +7,7 @@ import { systemClock } from '@ultimat3/core';
7
7
  import { checkClauses, checkPlan } from './check-ddl';
8
8
  import { alterColumnInPlace, retypeOverDefault, typeClause, wantedDefault } from './column-alter';
9
9
  import { defaultExpression } from './column-default';
10
- import { type ConcurrentPlan, emptyConcurrentPlan } from './concurrent-plan';
10
+ import { emptyConcurrentPlan } from './concurrent-plan';
11
11
  import { dropOrder } from './drop-order';
12
12
  import type { ColumnDescriptionLike, EntityDescriptionLike } from './entity-shape';
13
13
  import { type ConstraintPlans, foreignKeyPlan, type Plan } from './foreign-key-plan';
@@ -31,6 +31,7 @@ import {
31
31
  } from './introspect';
32
32
  import { declaredIndexes } from './invariant-ddl';
33
33
  import { migrationIrreversible } from './migration-errors';
34
+ import { beforeContract, contractNotNull, type NotNullContracts } from './not-null-contract';
34
35
  import { addChangedKey, dropChangedKey, migrationNameArg } from './primary-key';
35
36
  import type { ReplicaIdentityInput } from './replica-identity';
36
37
  import { replicaIdentityFullAfter, replicaIdentityPlan } from './replica-identity';
@@ -131,8 +132,9 @@ function diffTable(
131
132
  live: TableDescription,
132
133
  plan: Plan,
133
134
  retyped: ReadonlySet<string>,
134
- concurrent: ConcurrentPlan,
135
+ contracts: NotNullContracts,
135
136
  ): void {
137
+ const { concurrent } = contracts;
136
138
  const existing = new Map(live.columns.map((column) => [column.name, column]));
137
139
  const added = new Set<string>();
138
140
  // A column `regenerate` had to replace outright: `add column` implies no index, so every index
@@ -161,29 +163,30 @@ function diffTable(
161
163
  }
162
164
  : recorded,
163
165
  plan,
166
+ contracts,
164
167
  );
165
168
  }
166
169
  continue;
167
170
  }
168
171
  added.add(column.column);
169
- // A NOT NULL add with no default cannot succeed on a populated table; emit it nullable and
170
- // leave the agent the exact follow-up rather than a migration that fails at 3am.
172
+ // A NOT NULL add with no default cannot succeed on a populated table: it is EXPANDED here —
173
+ // added nullable, which is what this file's snapshot records (`beforeContract`) — and
174
+ // CONTRACTED in the non-transactional step (`not-null-contract.ts`). A NULL row stops that step
175
+ // alone; backfilled, the next `x db migrate` finishes it. A key column owes no contract: `add
176
+ // primary key` makes it NOT NULL.
171
177
  //
172
178
  // A GENERATED column is the exception and not a special case of it: the database computes it
173
179
  // for every existing row inside the same `add column`, so it lands NOT NULL and populated in
174
- // one statement — measured. Emitting it nullable would leave a `-- backfill` comment naming a
175
- // step nobody can perform, since a generated column cannot be written to.
180
+ // one statement — measured. Emitting it nullable would leave a contract step whose backfill
181
+ // nobody can perform, since a generated column cannot be written to.
176
182
  const nullable = column.notNull && !isGenerated(column) && defaultExpression(column) === null;
177
183
  // That follow-up is an UPDATE, and an append-only table's trigger refuses every one.
178
184
  if (nullable && entity.appendOnly === true)
179
185
  throw appendOnlyBackfillRefused(entity, column, 'added');
180
186
  const clause = nullable ? columnClause({ ...column, notNull: false }) : columnClause(column);
181
187
  plan.up.push(`alter table ${identifier(entity.table).text} add column ${clause};`);
182
- if (nullable) {
183
- plan.up.push(
184
- `-- backfill ${identifier(column.column).text}, then: alter table ` +
185
- `${identifier(entity.table).text} alter column ${identifier(column.column).text} set not null;`,
186
- );
188
+ if (nullable && !entity.primaryKey.includes(column.column)) {
189
+ contractNotNull(entity.table, column.column, contracts);
187
190
  }
188
191
  plan.down.push(
189
192
  `alter table ${identifier(entity.table).text} drop column ${identifier(column.column).text};`,
@@ -297,6 +300,8 @@ export function generateMigration(given: GenerateOptions): GeneratedMigration {
297
300
  const plan: Plan = { up: [], down: [] };
298
301
  // Applied AFTER `plan`, outside its transaction, in a step of its own (`concurrent-plan.ts`).
299
302
  const concurrent = emptyConcurrentPlan();
303
+ // Every column that step makes NOT NULL: the files ahead of it record each one nullable.
304
+ const contracts: NotNullContracts = { concurrent, columns: [] };
300
305
  // Merged into `plan` once every table statement is in, never interleaved with them.
301
306
  const constraints: Plan = { up: [], down: [] };
302
307
  // Merged in BEFORE them, for the mirror-image reason: a key still pointing at a table this
@@ -333,7 +338,7 @@ export function generateMigration(given: GenerateOptions): GeneratedMigration {
333
338
  // snapshot below records `entity.primaryKey`, and until this arm existed nothing produced it.
334
339
  retirePlan(entity, live, plan, options.entities);
335
340
  dropChangedKey(entity, live, current, plan, options.name);
336
- diffTable(entity, live, plan, retypedIn(retyped, entity.table), concurrent);
341
+ diffTable(entity, live, plan, retypedIn(retyped, entity.table), contracts);
337
342
  const kept = new Set([
338
343
  ...entity.columns.map((column) => column.column),
339
344
  ...(entity.retired ?? []),
@@ -440,7 +445,7 @@ export function generateMigration(given: GenerateOptions): GeneratedMigration {
440
445
  // Dropped ahead of every table statement and created after the last one: a view compiled against
441
446
  // a column this migration retypes or drops is `0A000`/`2BP01` otherwise.
442
447
  const viewed = viewPlan(views, current, [...preAlters.up, ...plan.up]);
443
- return assembleSteps({
448
+ const steps = assembleSteps({
444
449
  id,
445
450
  name: options.name,
446
451
  // An index's extension first (`index-extension.ts`): `gin_trgm_ops` does not exist before it.
@@ -471,4 +476,8 @@ export function generateMigration(given: GenerateOptions): GeneratedMigration {
471
476
  unrendered,
472
477
  ...(droppedUnretired ? { rollingUnsafe: true } : {}),
473
478
  });
479
+ // A contract always lands in the non-transactional step, so with a transactional file ahead of
480
+ // it that file's snapshot is what the database holds until the step runs: the columns nullable.
481
+ if (steps.followUp === undefined) return steps;
482
+ return { ...steps, snapshot: beforeContract(steps.snapshot, contracts.columns) };
474
483
  }
@@ -0,0 +1,88 @@
1
+ // Single responsibility: a column BECOMING NOT NULL as `x db gen` writes it — the online contract in
2
+ // the non-transactional step, and the snapshot each file records about that column.
3
+ //
4
+ // It replaced a `-- backfill "c", then: … set not null;` comment whose file still recorded NOT NULL:
5
+ // every database that ran it, a fresh one included, failed `x db migrate` with `X_DB_DRIFT`, and the
6
+ // next `x db gen` found nothing to write, because the snapshot already claimed the contract.
7
+
8
+ import type { ConcurrentPlan } from './concurrent-plan';
9
+ import { validateConstraint } from './foreign-key';
10
+ import type { SchemaDescription } from './introspect';
11
+ import { identifier, MAX_IDENTIFIER_BYTES } from './sql';
12
+
13
+ /** One column the follow-up step makes NOT NULL: until that step runs, it is nullable. */
14
+ export interface ContractedColumn {
15
+ readonly table: string;
16
+ readonly column: string;
17
+ }
18
+
19
+ /** What `generateMigration` threads through its arms: the step, and what the step contracts. */
20
+ export interface NotNullContracts {
21
+ readonly concurrent: ConcurrentPlan;
22
+ readonly columns: ContractedColumn[];
23
+ }
24
+
25
+ /**
26
+ * The transient CHECK's name. `_not_null_check`, never `_not_null`: Postgres 18 names a NOT NULL
27
+ * constraint `<table>_<column>_not_null` itself. Past 63 bytes the server would truncate it in
28
+ * silence, so a long pair takes a stable hashed name instead — the constraint lives for one step.
29
+ */
30
+ export function notNullCheckName(table: string, column: string): string {
31
+ const spelled = `${table}_${column}_not_null_check`;
32
+ if (new TextEncoder().encode(spelled).length <= MAX_IDENTIFIER_BYTES) return spelled;
33
+ return `not_null_check_${Bun.hash(`${table}.${column}`).toString(16)}`;
34
+ }
35
+
36
+ /**
37
+ * `set not null` without a full-scan lock, in the deferred step's phases (`stepStatements`): the
38
+ * CHECK added `not valid` (`keys`), its scan (`validate`), then `set not null` — which Postgres 12+
39
+ * proves from the validated CHECK — and the CHECK dropped (`contract`). The form
40
+ * `X_MIGRATION_LOCK_HEAVY` asks for. Every statement is safe to re-run, so a step stopped by a NULL
41
+ * row is finished by the next `x db migrate` once the rows are backfilled.
42
+ */
43
+ export function contractNotNull(table: string, column: string, contracts: NotNullContracts): void {
44
+ const { concurrent } = contracts;
45
+ const name = notNullCheckName(table, column);
46
+ const relation = identifier(table).text;
47
+ const attribute = identifier(column).text;
48
+ const check = identifier(name).text;
49
+ const dropCheck = `alter table ${relation} drop constraint if exists ${check};`;
50
+ concurrent.keys.push(
51
+ dropCheck,
52
+ `alter table ${relation} add constraint ${check} check (${attribute} is not null) not valid;`,
53
+ );
54
+ concurrent.keysDown.push(dropCheck);
55
+ concurrent.validate.push(
56
+ `-- a row holding NULL in ${attribute} fails this validate: backfill those rows, then x db migrate re-runs this step`,
57
+ validateConstraint(table, name),
58
+ );
59
+ concurrent.contract.push(
60
+ `alter table ${relation} alter column ${attribute} set not null;`,
61
+ dropCheck,
62
+ );
63
+ concurrent.contractDown.push(`alter table ${relation} alter column ${attribute} drop not null;`);
64
+ contracts.columns.push({ table, column });
65
+ }
66
+
67
+ /** The schema with every contracted column nullable — what a file ahead of the contract leaves. */
68
+ export function beforeContract(
69
+ snapshot: SchemaDescription,
70
+ columns: readonly ContractedColumn[],
71
+ ): SchemaDescription {
72
+ if (columns.length === 0) return snapshot;
73
+ return {
74
+ ...snapshot,
75
+ tables: snapshot.tables.map((table) => {
76
+ const owed = new Set(
77
+ columns.filter((each) => each.table === table.name).map((c) => c.column),
78
+ );
79
+ if (owed.size === 0) return table;
80
+ return {
81
+ ...table,
82
+ columns: table.columns.map((each) =>
83
+ owed.has(each.name) ? { ...each, nullable: true } : each,
84
+ ),
85
+ };
86
+ }),
87
+ };
88
+ }