@aria-framework/db-worker 0.23.0 → 0.25.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
@@ -304,8 +304,109 @@ ONE DIVERGENCE, ACCEPTED RATHER THAN HIDDEN: SQLite %W counts weeks from the fir
304
304
  Postgres IW is the ISO week. They can disagree by one at a year boundary. The value is a GROUP BY
305
305
  key on a chart axis, and an ISO week is the more defensible thing to show a person.
306
306
 
307
+ ## partner_id → partners(id), and adopting it (0.24.0)
308
+
309
+ The frozen spec (ARIA-PARTNER-TENANCY §2) declares every scoped table's
310
+ `partner_id … REFERENCES partners(id)`. `generateTenancyMigration` did not emit that key before
311
+ 0.24.0, so a row could outlive its partner or name one that never existed, and nothing refused
312
+ it. It now emits, on Postgres, one `fk_<table>_partner_id` per scoped table, `ON DELETE NO
313
+ ACTION` (the spec's bare `REFERENCES`, written out: a partner that still owns rows cannot be
314
+ deleted). Nullable tables get it too — NULL still means "installation-wide". SQLite gets none.
315
+
316
+ **An installation that already ran an older tenancy migration** does not regenerate it (those
317
+ files have run, and the ledger will not re-run them). It adds one new, Postgres-only file:
318
+
319
+ ```js
320
+ const { generatePartnerFkAdoption } = require('@aria-framework/db-worker');
321
+ const { files } = generatePartnerFkAdoption({ manifest, prefix: '041' }); // → 041_partner_fk.postgres.sql
322
+ ```
323
+
324
+ Before changing anything it refuses, in one error each, while (a) any scoped row names a missing
325
+ partner — listing **every** table with its count — or (b) a scoped table already has a partner
326
+ key whose `ON DELETE` is anything but NO ACTION or RESTRICT (a CASCADE would delete a partner's
327
+ data), naming table and constraint. Otherwise it adds each missing key `NOT VALID` and validates
328
+ it in a separate statement. A key that already exists **by shape** — including one an app wrote
329
+ inline, named `<table>_partner_id_fkey` — is kept, not duplicated. Running it again changes nothing.
330
+
331
+ **The NOT VALID / VALIDATE split saves no lock time under this package's runner.** The runner
332
+ applies each file in ONE transaction, so the locks the ADDs take — on `partners` and on every
333
+ scoped table — are held through every VALIDATE scan until commit, a large `audit_log` included.
334
+ All the split buys is the option to run the file's statements apart by hand (steps 1–2, commit,
335
+ then step 3) if a table is too large to hold those locks while it is scanned.
336
+
337
+ Run it as the migration role (BYPASSRLS). The count runs with `row_security = off`, which Postgres
338
+ documents as raising — rather than filtering — for a role policies would apply to, so a role
339
+ without BYPASSRLS gets an error, not a clean zero. `test/tenancyPartnerFk.pg.js` proves that only
340
+ when `ARIA_TEST_PG_NOBYPASS` names such a role, and prints `NOT RUN` otherwise.
341
+
342
+ **A scoped table added after adoption** gets its key from the generator's ordinary output: every
343
+ partner-key line `generateTenancyMigration` emits is one guarded, idempotent statement (refuse an
344
+ unsafe existing key, keep a safe one, add ours only when there is none), so running those lines —
345
+ or copying the new table's line into a hand-assembled migration — adds the new table's key and
346
+ leaves every existing one untouched. A table created by hand instead should declare `partner_id …
347
+ REFERENCES partners(id)` inline. Either way, an app check that reads `pg_constraint` for every
348
+ table in `scoped()` is what keeps it true.
349
+
350
+ After adopting, a partner can no longer be deleted while it owns rows — test clean-ups that
351
+ delete a partner first and its rows second will now fail, which is the point.
352
+
353
+ ## Composite keys are ON UPDATE CASCADE, and adopting it (0.25.0)
354
+
355
+ The frozen spec (ARIA-PARTNER-TENANCY §2) writes the child key as `FOREIGN KEY (customer_id,
356
+ partner_id) REFERENCES customers (id, partner_id) ON UPDATE CASCADE` — "re-parenting a customer is
357
+ one UPDATE; children follow atomically". Through 0.24.0 the generator emitted no `ON UPDATE`, so
358
+ `UPDATE customers SET partner_id` was refused for any customer with a child row (and updating the
359
+ children first fails the other way round). **Every** composite `(column, partner_id)` key now ends
360
+ `ON UPDATE CASCADE`, beside its ON DELETE (whose SET NULL / SET DEFAULT keep their column list):
361
+
362
+ - **Every key, not a configured few.** The child's partner_id is a copy of its parent's; a copy
363
+ that cannot follow freezes the parent's tenant once it has a child. CASCADE writes the parent's
364
+ new value — the only one the key would accept — so a child can never land in a tenant its
365
+ parent is not in. The statement must still satisfy every *other* composite key of every row it
366
+ touched: a child whose second parent stays behind (a site pointing at another customer's
367
+ contact) makes the whole move fail, and nothing moves.
368
+ - **Unlike SET DEFAULT, CASCADE reads no session state.** `ON UPDATE SET NULL / SET DEFAULT` take
369
+ no column list in Postgres, so either would write partner_id itself. A source key declaring one
370
+ — or RESTRICT, which would silently be overridden — is refused at generate time, naming it.
371
+ - Postgres documents that referential integrity bypasses row security, so the cascade should
372
+ reach every child whatever the mover can see — one more reason the move must be platform-only.
373
+ This package's tests run as a BYPASSRLS owner and do not exercise that.
374
+
375
+ **An installation whose composite keys were generated before 0.25.0** adds one new, Postgres-only
376
+ file; nothing applied is edited:
377
+
378
+ ```js
379
+ const { generateCompositeOnUpdateAdoption } = require('@aria-framework/db-worker');
380
+ const { files } = generateCompositeOnUpdateAdoption({ manifest, prefix: '044' }); // → 044_composite_on_update.postgres.sql
381
+ ```
382
+
383
+ It reads the live catalogue at migration time and finds every composite key on a scoped table
384
+ **by shape** (two columns, one of them partner_id referencing the parent's partner_id), whatever it
385
+ is called. Before changing anything it refuses — naming every table and constraint — a key with
386
+ `ON UPDATE` RESTRICT / SET NULL / SET DEFAULT, or an `ON DELETE SET NULL / SET DEFAULT` that writes
387
+ partner_id (no column list): CASCADE is never added beside anything that can re-home a row. Then
388
+ it re-adds each `ON UPDATE NO ACTION` key under the **same name** in one `DROP CONSTRAINT x, ADD
389
+ CONSTRAINT x` — the definition is Postgres's own `pg_get_constraintdef()` with `ON UPDATE CASCADE`
390
+ inserted, so ON DELETE (and its column list), MATCH, DEFERRABLE and NOT VALID survive — and finally
391
+ raises if any key is still not CASCADE. A key already CASCADE is untouched: running it again
392
+ changes nothing. Each re-add re-validates its key (a scan of the child under the ALTER's lock).
393
+
394
+ `test/tenancyOnUpdate.pg.js` (needs `ARIA_TEST_PG`) drives it: a two-level chain with a diamond
395
+ (sites → contacts → customers and sites → customers, work items under sites) moved in one UPDATE;
396
+ every way of moving a row into a tenant its parent is not in, refused with nothing changed; and
397
+ the adoption on the old shape, its refusal, and its idempotence by constraint oid. **As of the
398
+ 0.25.0 commit it has not been run against a server** — see the commit message.
399
+
307
400
  ## Changelog
308
401
 
402
+ - **0.25.0** — every composite tenancy key is `ON UPDATE CASCADE`, as the frozen spec's §2 always
403
+ said; a source FK with `ON UPDATE` RESTRICT / SET NULL / SET DEFAULT is refused at generate
404
+ time. `generateCompositeOnUpdateAdoption` for installations whose keys predate it (above).
405
+ Regenerated output changes: every composite-key line gains ` ON UPDATE CASCADE`.
406
+ - **0.24.0** — partner_id → partners(id) from the generator, and `generatePartnerFkAdoption`
407
+ (above). `stats.partnerFks` added to the generator's result. The generator's partner-key lines
408
+ are guarded, idempotent statements; both paths refuse an existing partner key with an unsafe
409
+ `ON DELETE`.
309
410
  - **0.15.0** — nowPlusMinutes, startOf, dateGroup, daysBetween (above).
310
411
 
311
412
  - **0.14.0** — `-- aria:covers-through NNN` (above).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
4
  "description": "Aria App Framework — db-worker module. Async RPC bridge over synchronous better-sqlite3: a worker-thread dispatcher (runWorker), a main-thread client with per-call timeouts and crash handling (DbClient), and a SQLite layer with WAL pragmas + a numbered-migration runner (database).",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -39,7 +39,7 @@
39
39
  "pg": "^8.23.0"
40
40
  },
41
41
  "scripts": {
42
- "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyNullable.pg.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/clientError.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js",
42
+ "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyNullable.pg.js && node test/tenancyPartnerFk.pg.js && node test/tenancyOnUpdate.pg.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/clientError.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js",
43
43
  "prepublishOnly": "node ../../test/packaging.js db-worker"
44
44
  }
45
45
  }
@@ -37,6 +37,83 @@ const NOW = (d) => (d === 'postgres'
37
37
  ? "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD HH24:MI:SS')"
38
38
  : "(datetime('now'))");
39
39
 
40
+ // ── partner_id → partners(id) ─────────────────────────────────────────────────────────────────
41
+ //
42
+ // THE FROZEN SPEC DECLARES IT (ARIA-PARTNER-TENANCY §2: `partner_id … REFERENCES partners(id)`)
43
+ // AND THIS GENERATOR NEVER EMITTED IT, through 0.23.0. The composite keys below bind a child to
44
+ // its PARENT's partner; nothing bound any row to a partner that EXISTS. Measured downstream: a test
45
+ // database holding 135 roles, 110 customers and 415 audit rows for partners that had been deleted
46
+ // or never existed — every one accepted without an error, and every one invisible to every
47
+ // partner-scoped read, because RLS compares against a partner nobody can be.
48
+ //
49
+ // ON DELETE NO ACTION, WRITTEN OUT. The spec's bare `REFERENCES partners(id)` IS NO ACTION, and so
50
+ // is every `REFERENCES partners(id)` apps have written by hand beside these; RESTRICT would give
51
+ // one schema two behaviours. Both refuse to delete a partner that still owns rows, which is the
52
+ // property that matters — NO ACTION merely checks at the end of the statement instead of at the
53
+ // row, so a single statement that removes a partner's rows and the partner together still works.
54
+ // CASCADE and SET NULL are not candidates: deleting a partner must never quietly take its data
55
+ // with it, and partner_id is NOT NULL.
56
+ //
57
+ // POSTGRES ONLY. SQLite is single-tenant (one partner, which is never deleted), and it refuses
58
+ // `ADD COLUMN … REFERENCES` with a non-NULL default while foreign keys are on.
59
+ const PARTNER_FK_ON_DELETE = 'NO ACTION';
60
+ // Postgres truncates identifiers to 63 bytes WITHOUT an error, so two long table names could
61
+ // share one constraint name and the second ADD would fail mid-migration. Refused at generate time.
62
+ const PG_MAX_IDENT = 63;
63
+ function partnerFkName(table) {
64
+ const name = `fk_${table}_partner_id`;
65
+ if (Buffer.byteLength(name) > PG_MAX_IDENT) {
66
+ throw new Error(`tenancy: the constraint name "${name}" is longer than Postgres's ${PG_MAX_IDENT}-byte `
67
+ + 'identifier limit and would be silently truncated. Rename the table or raise this with the framework.');
68
+ }
69
+ return name;
70
+ }
71
+ function partnerFkSql(table, { notValid = false } = {}) {
72
+ return `ALTER TABLE ${table} ADD CONSTRAINT ${partnerFkName(table)} FOREIGN KEY (partner_id)`
73
+ + ` REFERENCES partners (id) ON DELETE ${PARTNER_FK_ON_DELETE}${notValid ? ' NOT VALID' : ''};`;
74
+ }
75
+ /**
76
+ * The pg_constraint predicate for "a partner_id → partners(id) key on the table `rel`", for use as
77
+ * `FROM pg_constraint c WHERE <this>`. `rel` is a SQL regclass expression — `'users'::regclass`
78
+ * in a literal statement, `to_regclass(t)` inside a PL/pgSQL loop.
79
+ *
80
+ * BY SHAPE, NOT BY NAME: an app that declared the key inline got Postgres's
81
+ * `<table>_partner_id_fkey`, and that one counts. Only the exact single-column key counts. (The
82
+ * spec's §5 `users (partner_id, is_house_partner) → partners (id, is_house)` would, with both
83
+ * columns NOT NULL, also prove the partner exists — but no aria app has it: this generator never
84
+ * emitted it, the first adopter's 005 declines it, and its boolean column cannot even reference
85
+ * the BIGINT `is_house`. So users is treated like every other table.)
86
+ */
87
+ function partnerFkShape(rel) {
88
+ return `c.conrelid = ${rel} AND c.contype = 'f'`
89
+ + ` AND c.confrelid = 'partners'::regclass`
90
+ + ` AND c.conkey = ARRAY[(SELECT attnum FROM pg_attribute WHERE attrelid = ${rel}`
91
+ + ` AND attname = 'partner_id' AND NOT attisdropped)]`
92
+ + ` AND c.confkey = ARRAY[(SELECT attnum FROM pg_attribute WHERE attrelid = 'partners'::regclass`
93
+ + ` AND attname = 'id' AND NOT attisdropped)]`;
94
+ }
95
+ // pg_constraint.confdeltype: 'a' NO ACTION, 'r' RESTRICT — the two that refuse to delete a partner
96
+ // that still owns rows. 'c' CASCADE would delete its data; 'n'/'d' SET NULL/DEFAULT would re-home it.
97
+ const PARTNER_FK_SAFE_ACTIONS = "('a', 'r')";
98
+
99
+ /**
100
+ * ENSURE the key on `table`, idempotently, as ONE statement: REFUSE if a key of the shape exists
101
+ * with an unsafe ON DELETE (naming it), add ours if none exists, otherwise leave the existing one.
102
+ * Used by the fresh generator too, so its partner-key lines can be run against a schema that
103
+ * already has some — which is how a scoped table added after adoption gets its key.
104
+ */
105
+ function partnerFkEnsureSql(table, { notValid = false } = {}) {
106
+ const rel = `'${table}'::regclass`;
107
+ return `DO $$ DECLARE r record; BEGIN`
108
+ + ` SELECT c.conname, c.confdeltype INTO r FROM pg_constraint c WHERE ${partnerFkShape(rel)}`
109
+ + ` AND c.confdeltype NOT IN ${PARTNER_FK_SAFE_ACTIONS} LIMIT 1;`
110
+ + ` IF FOUND THEN RAISE EXCEPTION 'partner key: ${table}.% references partners with ON DELETE `
111
+ + `(confdeltype %), which deletes or re-homes a partner''s rows instead of refusing. Replace it `
112
+ + `with NO ACTION or RESTRICT, then re-run.', r.conname, r.confdeltype; END IF;`
113
+ + ` IF NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE ${partnerFkShape(rel)}) THEN`
114
+ + ` ${partnerFkSql(table, { notValid })} END IF; END $$;`;
115
+ }
116
+
40
117
  /**
41
118
  * @param {{
42
119
  * manifest: object, the app's tenancy manifest (see above)
@@ -125,7 +202,7 @@ function generateTenancyMigration(opts = {}) {
125
202
  // pass a driver instead of a file — it removes a second spelling of the same question.
126
203
  const tenantFks = (table) => db.prepare(sqliteDialect.foreignKeys(table)).all()
127
204
  .filter((f) => scopedNames.has(f.table))
128
- .map((f) => ({ from: f.from, table: f.table, to: f.to || 'id', onDelete: f.on_delete }))
205
+ .map((f) => ({ from: f.from, table: f.table, to: f.to || 'id', onDelete: f.on_delete, onUpdate: f.on_update }))
129
206
  // PRAGMA lists newest first; sorting keeps a regenerated file diff-free.
130
207
  .sort((a, b) => (a.from + a.table).localeCompare(b.from + b.table));
131
208
 
@@ -220,6 +297,25 @@ function generateTenancyMigration(opts = {}) {
220
297
  return out.join('\n');
221
298
  }
222
299
 
300
+ /** partner_id → partners(id) on every scoped table (see PARTNER_FK_ON_DELETE above). */
301
+ function partnerFks() {
302
+ const out = [
303
+ '-- EVERY partner_id NAMES A PARTNER THAT EXISTS. Without this a row can outlive its partner, or',
304
+ '-- name one that never existed, and nothing refuses it. After the backfill, so on a retrofit',
305
+ '-- it validates against the partner the backfill used. ON DELETE NO ACTION is the spec\'s bare',
306
+ '-- REFERENCES written out: a partner that still owns rows cannot be deleted.'
307
+ ];
308
+ out.push(
309
+ '--',
310
+ '-- Each is ONE guarded statement, idempotent by shape: it refuses an existing key of this shape',
311
+ '-- whose ON DELETE would delete or re-home a partner\'s rows, keeps any other existing one, and',
312
+ '-- adds ours only when there is none. So these lines are safe to run against a schema that',
313
+ '-- already has some — which is how a scoped table added later gets its key.'
314
+ );
315
+ for (const { table } of ordered) out.push(partnerFkEnsureSql(table));
316
+ return out.join('\n');
317
+ }
318
+
223
319
  // ── postgres-only pieces ──────────────────────────────────────────────────────────────────
224
320
 
225
321
  /** The unique keys the composite foreign keys point at, derived from the keys themselves. */
@@ -276,10 +372,36 @@ function generateTenancyMigration(opts = {}) {
276
372
  : (fk.onDelete === 'SET NULL' || fk.onDelete === 'SET DEFAULT'
277
373
  ? ` ON DELETE ${fk.onDelete} (${fk.from})`
278
374
  : ` ON DELETE ${fk.onDelete}`);
375
+ // ── ON UPDATE CASCADE, ON EVERY COMPOSITE KEY (0.25.0) ─────────────────────────────
376
+ //
377
+ // The frozen spec's §2 writes it on the child key: "re-parenting a customer is one
378
+ // UPDATE; children follow atomically". Through 0.24.0 nothing was emitted, so the key
379
+ // was ON UPDATE NO ACTION and `UPDATE <parent> SET partner_id` was refused for any parent
380
+ // with a child row — and updating the children first fails the other way round.
381
+ //
382
+ // EVERY KEY, NOT A CONFIGURED FEW. The child's partner_id is by construction a copy of
383
+ // its parent's; a copy that cannot follow its source freezes the parent's tenant the
384
+ // moment it has a child. CASCADE writes the parent's NEW value — the only value this key
385
+ // would accept anyway — so it cannot place a child in a tenant its parent is not in. And
386
+ // the statement as a whole must still satisfy every OTHER composite key of every row it
387
+ // touched: a child whose second parent stays behind makes the whole move fail.
388
+ //
389
+ // UNLIKE SET DEFAULT (the hazard above), CASCADE reads no session state. ON UPDATE
390
+ // SET NULL / SET DEFAULT take no column list in Postgres, so either would write
391
+ // partner_id itself — which is why a source key declaring one is refused below rather
392
+ // than carried over, and RESTRICT is refused because overriding it would silently
393
+ // change what its author chose.
394
+ if (fk.onUpdate && fk.onUpdate !== 'NO ACTION' && fk.onUpdate !== 'CASCADE') {
395
+ throw new Error(`tenancy: ${table}.${fk.from} → ${fk.table}(${fk.to}) declares ON UPDATE ${fk.onUpdate}. `
396
+ + 'Its composite (column, partner_id) key must be ON UPDATE CASCADE so the row follows its '
397
+ + `parent's partner; ${fk.onUpdate} would ${fk.onUpdate === 'RESTRICT' ? 'refuse every move of the parent'
398
+ : 'write partner_id itself (Postgres takes no column list on ON UPDATE)'}. `
399
+ + 'Change the source key to NO ACTION or CASCADE, then regenerate.');
400
+ }
279
401
  out.push(
280
402
  `ALTER TABLE ${table} ADD CONSTRAINT fk_${table}_${fk.from}_partner`
281
403
  + ` FOREIGN KEY (${fk.from}, partner_id)`
282
- + ` REFERENCES ${fk.table} (${fk.to}, partner_id)${del};`);
404
+ + ` REFERENCES ${fk.table} (${fk.to}, partner_id)${del} ON UPDATE CASCADE;`);
283
405
  // ── AND DROP THE ONE IT SUPERSEDES ──────────────────────────────────────────────────
284
406
  //
285
407
  // The composite key is strictly stronger: it enforces everything the single-column key
@@ -364,10 +486,10 @@ function generateTenancyMigration(opts = {}) {
364
486
  '-- partner_id so the application code is identical on both engines — a query written once is',
365
487
  '-- correct on both.',
366
488
  '--',
367
- '-- The composite foreign keys and the per-partner unique constraints live in the .postgres.sql',
368
- '-- sibling, and their absence here is deliberate twice over: SQLite cannot alter an inline',
369
- '-- table constraint without rebuilding the table, and with one partner there is no wrong',
370
- '-- partner_id to prevent and nothing to disambiguate.',
489
+ '-- The composite foreign keys, partner_id → partners(id), and the per-partner unique constraints',
490
+ '-- live in the .postgres.sql sibling, and their absence here is deliberate twice over: SQLite',
491
+ '-- cannot alter an inline table constraint without rebuilding the table, and with one partner',
492
+ '-- there is no wrong partner_id to prevent and nothing to disambiguate.',
371
493
  '',
372
494
  partnersTable('sqlite'),
373
495
  '',
@@ -378,9 +500,10 @@ function generateTenancyMigration(opts = {}) {
378
500
  const postgresFile = [
379
501
  `-- ${prefix}_partner_tenancy.postgres.sql — GENERATED by ${generatedBy}`,
380
502
  '--',
381
- '-- The Postgres half. The same columns as the sqlite sibling, plus the three things that only',
503
+ '-- The Postgres half. The same columns as the sqlite sibling, plus the four things that only',
382
504
  '-- mean something with more than one tenant: a partner_id that DEFAULTS FROM THE SESSION',
383
- `-- SCOPE, ${fks.count} composite foreign keys, and ${widenCount} unique constraints scoped per partner.`,
505
+ `-- SCOPE and REFERENCES partners(id) (${ordered.length} tables), ${fks.count} composite foreign keys, and`,
506
+ `-- ${widenCount} unique constraints scoped per partner.`,
384
507
  '--',
385
508
  '-- The default is why no model sets partner_id. A platform user acting for a particular',
386
509
  '-- partner has to establish that scope first, which is the intent rather than a limitation.',
@@ -391,6 +514,8 @@ function generateTenancyMigration(opts = {}) {
391
514
  '-- see could not be joined to.',
392
515
  partnerIdColumns('postgres'),
393
516
  '',
517
+ partnerFks(),
518
+ '',
394
519
  uniqueTargets(),
395
520
  '',
396
521
  fks.sql,
@@ -470,11 +595,261 @@ function generateTenancyMigration(opts = {}) {
470
595
  [`${prefix}_partner_tenancy.postgres.sql`]: postgresFile,
471
596
  [`${rlsPrefix}_partner_rls.postgres.sql`]: rlsFile
472
597
  },
473
- stats: { tables: ordered.length, compositeFks: fks.count, widened: widenCount }
598
+ stats: { tables: ordered.length, compositeFks: fks.count, widened: widenCount, partnerFks: ordered.length }
474
599
  };
475
600
  } finally {
476
601
  try { db.close(); } catch (_) { /* best effort */ }
477
602
  }
478
603
  }
479
604
 
480
- module.exports = { generateTenancyMigration };
605
+ /**
606
+ * generatePartnerFkAdoption — the migration an installation that ALREADY RAN a pre-0.24.0 tenancy
607
+ * migration needs, to gain partner_id → partners(id) on every scoped table.
608
+ *
609
+ * Regenerating the tenancy pair would change files that have already run (the ledger is keyed by
610
+ * filename and would never re-run them), so this is a NEW, Postgres-only file (no plain sibling:
611
+ * SQLite never runs it). It needs only the manifest — no schema file — because it asks the live
612
+ * catalogue, at migration time, what is already there.
613
+ *
614
+ * FOUR STEPS, in this order, and the order is the design:
615
+ * 1. REFUSE if any scoped table holds a partner_id naming a partner that does not exist, naming
616
+ * EVERY such table with its count in one error — so an operator fixes them all in one pass,
617
+ * and so nothing below has run: the migration never half-adopts. IN THE SAME PASS, refuse an
618
+ * EXISTING key of the right shape whose ON DELETE is not NO ACTION/RESTRICT, naming table and
619
+ * constraint: skipping it "because it exists" would keep a CASCADE that deletes a partner's
620
+ * data. (It runs in the runner's transaction, so even a later failure rolls everything back.)
621
+ * 2. ADD each missing key NOT VALID.
622
+ * 3. VALIDATE each one as a SEPARATE statement. UNDER THIS PACKAGE'S RUNNER THAT SAVES NO LOCK
623
+ * TIME: it applies a file in one transaction, so every lock step 2 takes (on partners and on
624
+ * each scoped table) is held through every VALIDATE scan until commit. What the split buys is
625
+ * only an OPTION: the file's statements can be run apart — steps 1–2, commit, then step 3 —
626
+ * by an operator who needs that on a very large table.
627
+ * 4. Idempotent throughout: a key that already exists BY SHAPE (see partnerFkShape) is kept,
628
+ * whatever it is called — including one the app declared inline itself.
629
+ *
630
+ * ROW SECURITY IS SWITCHED OFF FOR THE COUNT, deliberately. The migration role should hold
631
+ * BYPASSRLS (frozen spec §3). If it does not, a FORCE'd table would silently filter the orphan
632
+ * count to zero; with `row_security = off` Postgres instead RAISES ("query would be affected by
633
+ * row-level security policy") — Postgres's documented behaviour. test/tenancyPartnerFk.pg.js
634
+ * proves it only when given a non-BYPASSRLS role (ARIA_TEST_PG_NOBYPASS), and reports it NOT RUN
635
+ * otherwise. (VALIDATE would catch orphans anyway — referential checks ignore RLS — but with a
636
+ * message naming one constraint, not every table.)
637
+ *
638
+ * @param {{ manifest: object, prefix: string, generatedBy?: string }} opts
639
+ * @returns {{files: Object<string,string>, stats: {tables:number}}}
640
+ */
641
+ function generatePartnerFkAdoption(opts = {}) {
642
+ const { manifest } = opts;
643
+ if (!manifest || typeof manifest.scoped !== 'function') {
644
+ throw new Error('generatePartnerFkAdoption({ manifest, prefix }): a tenancy manifest with scoped() is required');
645
+ }
646
+ // No default: this file lands in an app's existing chain, and only the app knows the next number.
647
+ if (!opts.prefix) {
648
+ throw new Error('generatePartnerFkAdoption({ manifest, prefix }): prefix is required — the next '
649
+ + 'free migration number in the app\'s chain');
650
+ }
651
+ const generatedBy = opts.generatedBy || '@aria-framework/db-worker generatePartnerFkAdoption';
652
+ const tables = manifest.scoped().map((s) => s.table).sort();
653
+ if (!tables.length) {
654
+ throw new Error('generatePartnerFkAdoption: the manifest has no scoped tables, so this would emit '
655
+ + 'a migration that adopts nothing and reports success.');
656
+ }
657
+ for (const t of tables) partnerFkName(t); // refuse a name Postgres would truncate, up front
658
+
659
+ const file = `${opts.prefix}_partner_fk.postgres.sql`;
660
+ const arr = `ARRAY[${tables.map((t) => `'${t}'`).join(', ')}]`;
661
+ const sql = [
662
+ `-- ${file} — GENERATED by ${generatedBy}`,
663
+ '--',
664
+ '-- ADOPTION: partner_id → partners(id) on every scoped table, for an installation whose tenancy',
665
+ '-- migration predates it. The frozen spec always required this key; the generator did not emit',
666
+ '-- it before db-worker 0.24.0, so rows could outlive their partner or name one that never',
667
+ '-- existed. Refuses while such rows exist, naming them; adds NOT VALID; validates separately;',
668
+ `-- skips a key that already exists by shape. Idempotent. ${tables.length} tables.`,
669
+ '',
670
+ '-- 1. Refuse orphans — every table and its count — and any existing partner key whose ON DELETE',
671
+ '-- would delete or re-home a partner\'s rows, before anything changes.',
672
+ 'DO $$',
673
+ 'DECLARE',
674
+ ' t text;',
675
+ ' n bigint;',
676
+ ' k record;',
677
+ " found text := '';",
678
+ " unsafe text := '';",
679
+ " prev text := current_setting('row_security');",
680
+ 'BEGIN',
681
+ " PERFORM set_config('row_security', 'off', true);",
682
+ ` FOREACH t IN ARRAY ${arr} LOOP`,
683
+ ' IF NOT EXISTS (SELECT 1 FROM pg_attribute',
684
+ " WHERE attrelid = to_regclass(t) AND attname = 'partner_id' AND NOT attisdropped) THEN",
685
+ " RAISE EXCEPTION 'partner FK adoption: table % has no partner_id column (or does not exist). '",
686
+ " 'The manifest names it as scoped; run its tenancy migration first.', t;",
687
+ ' END IF;',
688
+ ` FOR k IN SELECT c.conname, c.confdeltype FROM pg_constraint c WHERE ${partnerFkShape('to_regclass(t)')}`,
689
+ ` AND c.confdeltype NOT IN ${PARTNER_FK_SAFE_ACTIONS} LOOP`,
690
+ " unsafe := unsafe || format('%s.%s (ON DELETE %s); ', t, k.conname,",
691
+ " CASE k.confdeltype WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' ELSE k.confdeltype::text END);",
692
+ ' END LOOP;',
693
+ ' EXECUTE format(',
694
+ " 'SELECT count(*) FROM %I x WHERE x.partner_id IS NOT NULL '",
695
+ " 'AND NOT EXISTS (SELECT 1 FROM partners p WHERE p.id = x.partner_id)', t) INTO n;",
696
+ " IF n > 0 THEN found := found || format('%s: %s; ', t, n); END IF;",
697
+ ' END LOOP;',
698
+ " IF unsafe <> '' THEN",
699
+ " RAISE EXCEPTION 'partner FK adoption refused: an existing partner key would delete or re-home a partner''s rows instead of refusing — %', unsafe",
700
+ " USING HINT = 'Replace each with ON DELETE NO ACTION (or RESTRICT), then re-run. Nothing was changed.';",
701
+ ' END IF;',
702
+ " IF found <> '' THEN",
703
+ " RAISE EXCEPTION 'partner FK adoption refused: rows name a partner that does not exist — %', found",
704
+ " USING HINT = 'Delete or re-home those rows (they are invisible to every partner under RLS), then re-run. Nothing was changed.';",
705
+ ' END IF;',
706
+ " PERFORM set_config('row_security', prev, true);",
707
+ 'END $$;',
708
+ '',
709
+ '-- 2. Add each missing key NOT VALID.'
710
+ ];
711
+ for (const t of tables) sql.push(partnerFkEnsureSql(t, { notValid: true }));
712
+ sql.push('', '-- 3. Validate, as separate statements — every key of the shape not yet validated.',
713
+ '-- Under a one-transaction-per-file runner this holds step 2\'s locks through each scan; the',
714
+ '-- split only lets an operator run steps 1–2 and 3 apart if a table is too large for that.');
715
+ for (const t of tables) {
716
+ sql.push(`DO $$ DECLARE r record; BEGIN FOR r IN SELECT c.conname FROM pg_constraint c`
717
+ + ` WHERE ${partnerFkShape(`'${t}'::regclass`)} AND NOT c.convalidated`
718
+ + ` LOOP EXECUTE format('ALTER TABLE ${t} VALIDATE CONSTRAINT %I', r.conname); END LOOP; END $$;`);
719
+ }
720
+ sql.push('');
721
+ return { files: { [file]: sql.join('\n') }, stats: { tables: tables.length } };
722
+ }
723
+
724
+ /**
725
+ * The pg_constraint predicate for "a composite tenancy key on `rel`": a two-column foreign key one
726
+ * of whose columns is partner_id and references the PARENT's partner_id. BY SHAPE, not by the name
727
+ * the generator gives it (`fk_<table>_<col>_partner`), so a hand-written key of the same shape —
728
+ * which has exactly the same move hazard — is treated the same.
729
+ */
730
+ function compositeKeyShape(rel) {
731
+ return `c.conrelid = ${rel} AND c.contype = 'f' AND cardinality(c.conkey) = 2`
732
+ + ' AND EXISTS (SELECT 1 FROM generate_subscripts(c.conkey, 1) AS i'
733
+ + ' JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[i]'
734
+ + ' JOIN pg_attribute ra ON ra.attrelid = c.confrelid AND ra.attnum = c.confkey[i]'
735
+ + " WHERE a.attname = 'partner_id' AND ra.attname = 'partner_id')";
736
+ }
737
+
738
+ /**
739
+ * generateCompositeOnUpdateAdoption — the migration an installation whose composite tenancy keys
740
+ * were generated before 0.25.0 needs, so that `UPDATE <parent> SET partner_id` carries the children.
741
+ *
742
+ * Through 0.24.0 the generator emitted those keys with no ON UPDATE (= NO ACTION), against the
743
+ * frozen spec's §2. The files that created them have run and are never edited, so this is a NEW,
744
+ * Postgres-only file (no plain sibling — SQLite has no composite keys). Like
745
+ * generatePartnerFkAdoption it needs only the manifest: it asks the live catalogue, at migration
746
+ * time, which keys exist.
747
+ *
748
+ * THREE STEPS, in one DO block (and so in the runner's one transaction):
749
+ * 1. REFUSE, before anything changes, naming every table and constraint, if any scoped table
750
+ * lacks partner_id, or any composite key on one has ON UPDATE RESTRICT / SET NULL / SET
751
+ * DEFAULT, or an ON DELETE SET NULL / SET DEFAULT that writes partner_id (no column list, or
752
+ * one naming partner_id). CASCADE must never sit beside anything that can re-home a row; such
753
+ * a key was not written by this generator and is the author's to fix.
754
+ * 2. RE-ADD each composite key whose ON UPDATE is NO ACTION, under the SAME name, in one
755
+ * `ALTER TABLE … DROP CONSTRAINT x, ADD CONSTRAINT x <def>` — where <def> is Postgres's own
756
+ * pg_get_constraintdef() with ON UPDATE CASCADE inserted after the REFERENCES clause. So
757
+ * ON DELETE (with its column list), MATCH, DEFERRABLE and NOT VALID survive verbatim, and a
758
+ * definition this cannot rewrite is refused rather than guessed at.
759
+ * 3. PROVE it: any composite key on a scoped table still not CASCADE raises.
760
+ * A key already ON UPDATE CASCADE is untouched, so a second run changes nothing.
761
+ *
762
+ * The re-add re-validates each key (a scan of the child under the ALTER's lock). The rows already
763
+ * satisfied it, so this cannot fail on data; it costs time on a very large child table.
764
+ *
765
+ * @param {{ manifest: object, prefix: string, generatedBy?: string }} opts
766
+ * @returns {{files: Object<string,string>, stats: {tables:number}}}
767
+ */
768
+ function generateCompositeOnUpdateAdoption(opts = {}) {
769
+ const { manifest } = opts;
770
+ if (!manifest || typeof manifest.scoped !== 'function') {
771
+ throw new Error('generateCompositeOnUpdateAdoption({ manifest, prefix }): a tenancy manifest with scoped() is required');
772
+ }
773
+ if (!opts.prefix) {
774
+ throw new Error('generateCompositeOnUpdateAdoption({ manifest, prefix }): prefix is required — the next '
775
+ + 'free migration number in the app\'s chain');
776
+ }
777
+ const generatedBy = opts.generatedBy || '@aria-framework/db-worker generateCompositeOnUpdateAdoption';
778
+ const tables = manifest.scoped().map((s) => s.table).sort();
779
+ if (!tables.length) {
780
+ throw new Error('generateCompositeOnUpdateAdoption: the manifest has no scoped tables, so this would emit '
781
+ + 'a migration that changes nothing and reports success.');
782
+ }
783
+ const file = `${opts.prefix}_composite_on_update.postgres.sql`;
784
+ const arr = `ARRAY[${tables.map((t) => `'${t}'`).join(', ')}]`;
785
+ const shape = compositeKeyShape('to_regclass(t)');
786
+ const sql = [
787
+ `-- ${file} — GENERATED by ${generatedBy}`,
788
+ '--',
789
+ '-- ADOPTION: ON UPDATE CASCADE on every composite (column, partner_id) key of a scoped table, for',
790
+ '-- an installation whose tenancy keys predate db-worker 0.25.0 (which emitted no ON UPDATE). With',
791
+ '-- it, `UPDATE <parent> SET partner_id` carries every child — and every child of a child — to the',
792
+ '-- new partner in one statement, and the statement still fails if any row it moves would then',
793
+ '-- disagree with another parent that did not move. Refuses keys it must not combine with CASCADE;',
794
+ '-- re-adds the rest under the same name from their own definition; proves the result. Idempotent.',
795
+ `-- ${tables.length} tables.`,
796
+ '',
797
+ 'DO $$',
798
+ 'DECLARE',
799
+ ' t text;',
800
+ ' k record;',
801
+ ' def text;',
802
+ ' newdef text;',
803
+ ' n int := 0;',
804
+ " bad text := '';",
805
+ 'BEGIN',
806
+ ' -- 1. Refuse, before anything changes.',
807
+ ` FOREACH t IN ARRAY ${arr} LOOP`,
808
+ ' IF NOT EXISTS (SELECT 1 FROM pg_attribute',
809
+ " WHERE attrelid = to_regclass(t) AND attname = 'partner_id' AND NOT attisdropped) THEN",
810
+ " RAISE EXCEPTION 'composite ON UPDATE adoption: table % has no partner_id column (or does not exist). '",
811
+ " 'The manifest names it as scoped; run its tenancy migration first.', t;",
812
+ ' END IF;',
813
+ ` FOR k IN SELECT c.conname, c.confupdtype, c.confdeltype FROM pg_constraint c WHERE ${shape}`,
814
+ " AND (c.confupdtype IN ('r', 'n', 'd')",
815
+ " OR (c.confdeltype IN ('n', 'd') AND (c.confdelsetcols IS NULL OR cardinality(c.confdelsetcols) = 0",
816
+ " OR (SELECT attnum FROM pg_attribute WHERE attrelid = c.conrelid AND attname = 'partner_id')",
817
+ ' = ANY (c.confdelsetcols)))) LOOP',
818
+ " bad := bad || format('%s.%s (ON UPDATE %s, ON DELETE %s); ', t, k.conname, k.confupdtype, k.confdeltype);",
819
+ ' END LOOP;',
820
+ ' END LOOP;',
821
+ " IF bad <> '' THEN",
822
+ " RAISE EXCEPTION 'composite ON UPDATE adoption refused: these keys can write partner_id themselves, or refuse a move, so ON UPDATE CASCADE must not be added beside them — %', bad",
823
+ " USING HINT = 'Codes: r RESTRICT, n SET NULL, d SET DEFAULT. Give each ON UPDATE NO ACTION and an ON DELETE that does not touch partner_id (SET NULL (<column>)), then re-run. Nothing was changed.';",
824
+ ' END IF;',
825
+ '',
826
+ ' -- 2. Re-add each NO ACTION key, same name, its own definition plus ON UPDATE CASCADE.',
827
+ ` FOREACH t IN ARRAY ${arr} LOOP`,
828
+ ` FOR k IN SELECT c.oid, c.conname, c.conrelid FROM pg_constraint c WHERE ${shape}`,
829
+ " AND c.confupdtype = 'a' ORDER BY c.conname LOOP",
830
+ ' def := pg_get_constraintdef(k.oid);',
831
+ // After `REFERENCES t(cols)` and any MATCH clause — Postgres's grammar puts MATCH before the
832
+ // key actions, and either order of ON UPDATE / ON DELETE is accepted.
833
+ " newdef := regexp_replace(def, '^(FOREIGN KEY \\([^)]*\\) REFERENCES [^(]+\\([^)]*\\)( MATCH [A-Z]+)?)', '\\1 ON UPDATE CASCADE');",
834
+ ' IF newdef = def THEN',
835
+ " RAISE EXCEPTION 'composite ON UPDATE adoption: cannot rewrite %.% — unexpected definition: %', t, k.conname, def;",
836
+ ' END IF;',
837
+ " EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I, ADD CONSTRAINT %I %s', k.conrelid::regclass, k.conname, k.conname, newdef);",
838
+ ' n := n + 1;',
839
+ ' END LOOP;',
840
+ ' END LOOP;',
841
+ '',
842
+ ' -- 3. Prove it: no composite key on a scoped table is left without ON UPDATE CASCADE.',
843
+ ` FOREACH t IN ARRAY ${arr} LOOP`,
844
+ ` FOR k IN SELECT c.conname FROM pg_constraint c WHERE ${shape} AND c.confupdtype <> 'c' LOOP`,
845
+ " RAISE EXCEPTION 'composite ON UPDATE adoption: %.% is still not ON UPDATE CASCADE', t, k.conname;",
846
+ ' END LOOP;',
847
+ ' END LOOP;',
848
+ " RAISE NOTICE 'composite ON UPDATE adoption: % key(s) re-added with ON UPDATE CASCADE', n;",
849
+ 'END $$;',
850
+ ''
851
+ ];
852
+ return { files: { [file]: sql.join('\n') }, stats: { tables: tables.length } };
853
+ }
854
+
855
+ module.exports = { generateTenancyMigration, generatePartnerFkAdoption, generateCompositeOnUpdateAdoption };