@aria-framework/db-worker 0.24.0 → 0.26.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
@@ -350,8 +350,101 @@ table in `scoped()` is what keeps it true.
350
350
  After adopting, a partner can no longer be deleted while it owns rows — test clean-ups that
351
351
  delete a partner first and its rows second will now fail, which is the point.
352
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** — *superseded in 0.26.0: ownership keys only; keys into the
363
+ principal table are attribution and do not cascade (see the next section).* The child's
364
+ partner_id is a copy of its parent's; a copy
365
+ that cannot follow freezes the parent's tenant once it has a child. CASCADE writes the parent's
366
+ new value — the only one the key would accept — so a child can never land in a tenant its
367
+ parent is not in. The statement must still satisfy every *other* composite key of every row it
368
+ touched: a child whose second parent stays behind (a site pointing at another customer's
369
+ contact) makes the whole move fail, and nothing moves.
370
+ - **Unlike SET DEFAULT, CASCADE reads no session state.** `ON UPDATE SET NULL / SET DEFAULT` take
371
+ no column list in Postgres, so either would write partner_id itself. A source key declaring one
372
+ — or RESTRICT, which would silently be overridden — is refused at generate time, naming it.
373
+ - Postgres documents that referential integrity bypasses row security, so the cascade should
374
+ reach every child whatever the mover can see — one more reason the move must be platform-only.
375
+ This package's tests run as a BYPASSRLS owner and do not exercise that.
376
+
377
+ **An installation whose composite keys were generated before 0.25.0** adds one new, Postgres-only
378
+ file; nothing applied is edited:
379
+
380
+ ```js
381
+ const { generateCompositeOnUpdateAdoption } = require('@aria-framework/db-worker');
382
+ const { files } = generateCompositeOnUpdateAdoption({ manifest, prefix: '044' }); // → 044_composite_on_update.postgres.sql
383
+ ```
384
+
385
+ It reads the live catalogue at migration time and finds every composite key on a scoped table
386
+ **by shape** (two columns, one of them partner_id referencing the parent's partner_id), whatever it
387
+ is called. Before changing anything it refuses — naming every table and constraint — a key with
388
+ `ON UPDATE` RESTRICT / SET NULL / SET DEFAULT, or an `ON DELETE SET NULL / SET DEFAULT` that writes
389
+ partner_id (no column list): CASCADE is never added beside anything that can re-home a row. Then
390
+ it re-adds each `ON UPDATE NO ACTION` key under the **same name** in one `DROP CONSTRAINT x, ADD
391
+ CONSTRAINT x` — the definition is Postgres's own `pg_get_constraintdef()` with `ON UPDATE CASCADE`
392
+ inserted, so ON DELETE (and its column list), MATCH, DEFERRABLE and NOT VALID survive — and finally
393
+ raises if any key is still not CASCADE. A key already CASCADE is untouched: running it again
394
+ changes nothing. Each re-add re-validates its key (a scan of the child under the ALTER's lock).
395
+
396
+ `test/tenancyOnUpdate.pg.js` (needs `ARIA_TEST_PG`) drives it: a two-level chain with a diamond
397
+ (sites → contacts → customers and sites → customers, work items under sites) moved in one UPDATE;
398
+ every way of moving a row into a tenant its parent is not in, refused with nothing changed; and
399
+ the adoption on the old shape, its refusal, and its idempotence by constraint oid. **As of the
400
+ 0.25.0 commit it has not been run against a server** — see the commit message.
401
+
402
+ ## Cascade is for ownership, not attribution (0.26.0)
403
+
404
+ **0.25.0 over-reached.** It cascaded *every* composite key, including keys into the principal
405
+ table: `api_keys.created_by`, `records.owner_id`, `notifications.user_id`, the token tables.
406
+ A user's partner is the user's **identity**, not a container their rows live in. Through 0.24.0,
407
+ `UPDATE users SET partner_id = 2 WHERE id = 50` was refused. With 0.25.0 it succeeded and carried
408
+ partner 1's API keys and records into partner 2, because referential actions bypass RLS. An
409
+ integration key that belonged to partner 1 then read partner 2's data.
410
+
411
+ The rule from 0.26.0:
412
+
413
+ - **Ownership keys cascade.** A row whose parent is another tenant row follows that parent's
414
+ tenant: re-parenting a customer is still one UPDATE.
415
+ - **Attribution keys do not.** A key into the principal table (`principalTable`, default `users`),
416
+ or one the manifest lists in `NO_CASCADE: ['table.column']`, carries no update action. Moving a
417
+ user who owns or authored rows is **refused**, and the operator deals with those rows first. A
418
+ `NO_CASCADE` entry that matches no composite key is refused, because a typo would leave the key
419
+ cascading.
420
+
421
+ `generateCompositeOnUpdateAdoption` now **converges in both directions**. Ownership keys with no
422
+ update action gain CASCADE (the pre-0.25 path, as before). Attribution keys that cascade lose it
423
+ (the **0.25.0 repair**). The proof step checks both directions, and a key already on the right side
424
+ is untouched. **An installation that ran 0.25.0's adoption regenerates it with 0.26.0 under a new
425
+ prefix and runs it.** It takes the same `principalTable` option as the generator, and reads the
426
+ manifest's `NO_CASCADE`.
427
+
428
+ `test/tenancyAttribution.pglite.js` proves it on PostgreSQL, using PGlite (Postgres in WebAssembly,
429
+ in-process, a devDependency). Unlike the `.pg` suites, it runs on every `npm test`:
430
+ - a fresh 0.26 schema refuses the user move and still cascades a customer move;
431
+ - a 0.25 install first reproduces the leak, then the adoption repairs it, idempotent by constraint
432
+ oid;
433
+ - a pre-0.25 install gains CASCADE on ownership keys only;
434
+ - a `NO_CASCADE` typo is refused at migration time.
435
+
436
+ Against 0.25.0's code, 6 of its 10 checks fail.
437
+
353
438
  ## Changelog
354
439
 
440
+ - **0.26.0** — composite keys into the principal table (and any in `NO_CASCADE`) no longer
441
+ cascade; `generateCompositeOnUpdateAdoption` converges both ways and repairs a 0.25.0 install.
442
+ `stats.attributionKeys` (generator) and `stats.noCascade` (adoption). PGlite devDependency;
443
+ `test/tenancyAttribution.pglite.js` in `npm test`.
444
+ - **0.25.0** — every composite tenancy key is `ON UPDATE CASCADE`, as the frozen spec's §2 always
445
+ said; a source FK with `ON UPDATE` RESTRICT / SET NULL / SET DEFAULT is refused at generate
446
+ time. `generateCompositeOnUpdateAdoption` for installations whose keys predate it (above).
447
+ Regenerated output changes: every composite-key line gains ` ON UPDATE CASCADE`.
355
448
  - **0.24.0** — partner_id → partners(id) from the generator, and `generatePartnerFkAdoption`
356
449
  (above). `stats.partnerFks` added to the generator's result. The generator's partner-key lines
357
450
  are guarded, idempotent statements; both paths refuse an existing partner key with an unsafe
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.24.0",
3
+ "version": "0.26.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,
@@ -35,11 +35,12 @@
35
35
  }
36
36
  },
37
37
  "devDependencies": {
38
+ "@electric-sql/pglite": "^0.5.8",
38
39
  "better-sqlite3": "^12.10.0",
39
40
  "pg": "^8.23.0"
40
41
  },
41
42
  "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/tenancyPartnerFk.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
+ "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/tenancyAttribution.pglite.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
44
  "prepublishOnly": "node ../../test/packaging.js db-worker"
44
45
  }
45
46
  }
@@ -126,6 +126,21 @@ function partnerFkEnsureSql(table, { notValid = false } = {}) {
126
126
  * }} opts
127
127
  * @returns {{files: Object<string,string>, stats: {tables:number, compositeFks:number, widened:number}}}
128
128
  */
129
+ /**
130
+ * The manifest's NO_CASCADE list as a Set of 'table.column', shape-checked. Shared by the generator
131
+ * and the adoption so the two cannot disagree about which keys are attribution.
132
+ */
133
+ function noCascadeSet(manifest, who) {
134
+ const list = (manifest && manifest.NO_CASCADE) || [];
135
+ if (!Array.isArray(list)) throw new Error(`${who}: manifest.NO_CASCADE must be an array of "table.column"`);
136
+ for (const k of list) {
137
+ if (typeof k !== 'string' || !/^[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*$/i.test(k)) {
138
+ throw new Error(`${who}: NO_CASCADE entry ${JSON.stringify(k)} is not "table.column"`);
139
+ }
140
+ }
141
+ return new Set(list);
142
+ }
143
+
129
144
  function generateTenancyMigration(opts = {}) {
130
145
  const { manifest, dbPath, Database } = opts;
131
146
  if (!manifest || !dbPath || typeof Database !== 'function') {
@@ -175,6 +190,11 @@ function generateTenancyMigration(opts = {}) {
175
190
  // than in the middle of a migration.
176
191
  const principalTable = opts.principalTable || 'users';
177
192
  const scopeColumn = opts.scopeColumn || 'scope_kind';
193
+ // ATTRIBUTION keys (0.26.0): composite keys that must NOT cascade on a partner move. Keys into the
194
+ // principal table always; NO_CASCADE ('table.column') names any other. See compositeFks().
195
+ const noCascade = noCascadeSet(manifest, 'generateTenancyMigration');
196
+ const usedNoCascade = new Set();
197
+ let attributionKeys = 0;
178
198
 
179
199
  const db = new Database(dbPath, { readonly: true });
180
200
  try {
@@ -202,7 +222,7 @@ function generateTenancyMigration(opts = {}) {
202
222
  // pass a driver instead of a file — it removes a second spelling of the same question.
203
223
  const tenantFks = (table) => db.prepare(sqliteDialect.foreignKeys(table)).all()
204
224
  .filter((f) => scopedNames.has(f.table))
205
- .map((f) => ({ from: f.from, table: f.table, to: f.to || 'id', onDelete: f.on_delete }))
225
+ .map((f) => ({ from: f.from, table: f.table, to: f.to || 'id', onDelete: f.on_delete, onUpdate: f.on_update }))
206
226
  // PRAGMA lists newest first; sorting keeps a regenerated file diff-free.
207
227
  .sort((a, b) => (a.from + a.table).localeCompare(b.from + b.table));
208
228
 
@@ -340,7 +360,11 @@ function generateTenancyMigration(opts = {}) {
340
360
  const out = [
341
361
  '-- THE POINT OF THE WHOLE ARRANGEMENT. A denormalised partner_id that disagrees with its',
342
362
  '-- parent becomes impossible to WRITE rather than merely discouraged: the row it points at',
343
- '-- has to belong to the same partner.'
363
+ '-- has to belong to the same partner.',
364
+ '--',
365
+ `-- OWNERSHIP keys are ON UPDATE CASCADE (a row follows its parent's tenant). Keys into ${principalTable}`,
366
+ '-- and any named in NO_CASCADE are ATTRIBUTION — who acted, not what contains the row — and carry',
367
+ '-- no update action at all, so moving a user who owns or authored rows is refused, not obeyed.'
344
368
  ];
345
369
  let n = 0;
346
370
  for (const { table } of ordered) {
@@ -372,10 +396,48 @@ function generateTenancyMigration(opts = {}) {
372
396
  : (fk.onDelete === 'SET NULL' || fk.onDelete === 'SET DEFAULT'
373
397
  ? ` ON DELETE ${fk.onDelete} (${fk.from})`
374
398
  : ` ON DELETE ${fk.onDelete}`);
399
+ // ── ON UPDATE CASCADE, ON EVERY COMPOSITE KEY (0.25.0) ─────────────────────────────
400
+ //
401
+ // The frozen spec's §2 writes it on the child key: "re-parenting a customer is one
402
+ // UPDATE; children follow atomically". Through 0.24.0 nothing was emitted, so the key
403
+ // was ON UPDATE NO ACTION and `UPDATE <parent> SET partner_id` was refused for any parent
404
+ // with a child row — and updating the children first fails the other way round.
405
+ //
406
+ // EVERY KEY, NOT A CONFIGURED FEW. The child's partner_id is by construction a copy of
407
+ // its parent's; a copy that cannot follow its source freezes the parent's tenant the
408
+ // moment it has a child. CASCADE writes the parent's NEW value — the only value this key
409
+ // would accept anyway — so it cannot place a child in a tenant its parent is not in. And
410
+ // the statement as a whole must still satisfy every OTHER composite key of every row it
411
+ // touched: a child whose second parent stays behind makes the whole move fail.
412
+ //
413
+ // UNLIKE SET DEFAULT (the hazard above), CASCADE reads no session state. ON UPDATE
414
+ // SET NULL / SET DEFAULT take no column list in Postgres, so either would write
415
+ // partner_id itself — which is why a source key declaring one is refused below rather
416
+ // than carried over, and RESTRICT is refused because overriding it would silently
417
+ // change what its author chose.
418
+ if (fk.onUpdate && fk.onUpdate !== 'NO ACTION' && fk.onUpdate !== 'CASCADE') {
419
+ throw new Error(`tenancy: ${table}.${fk.from} → ${fk.table}(${fk.to}) declares ON UPDATE ${fk.onUpdate}. `
420
+ + 'Its composite (column, partner_id) key must be ON UPDATE CASCADE so the row follows its '
421
+ + `parent's partner; ${fk.onUpdate} would ${fk.onUpdate === 'RESTRICT' ? 'refuse every move of the parent'
422
+ : 'write partner_id itself (Postgres takes no column list on ON UPDATE)'}. `
423
+ + 'Change the source key to NO ACTION or CASCADE, then regenerate.');
424
+ }
425
+ // ── BUT NOT FOR ATTRIBUTION (0.26.0) ─────────────────────────────────────────────────
426
+ //
427
+ // 0.25.0 cascaded this key too when its parent was the PRINCIPAL table. A user's partner is
428
+ // the user's identity, not a container their rows live in: with `api_keys.created_by`
429
+ // cascading, re-homing a staff user carried the tenant's integration keys and records into
430
+ // the other partner (RI cascades bypass RLS). Keys into the principal, and any the manifest
431
+ // names in NO_CASCADE, keep ON UPDATE NO ACTION — so that move is REFUSED, as through 0.24.
432
+ const attribution = fk.table === principalTable || noCascade.has(`${table}.${fk.from}`);
433
+ if (attribution) {
434
+ usedNoCascade.add(`${table}.${fk.from}`);
435
+ attributionKeys += 1;
436
+ }
375
437
  out.push(
376
438
  `ALTER TABLE ${table} ADD CONSTRAINT fk_${table}_${fk.from}_partner`
377
439
  + ` FOREIGN KEY (${fk.from}, partner_id)`
378
- + ` REFERENCES ${fk.table} (${fk.to}, partner_id)${del};`);
440
+ + ` REFERENCES ${fk.table} (${fk.to}, partner_id)${del}${attribution ? '' : ' ON UPDATE CASCADE'};`);
379
441
  // ── AND DROP THE ONE IT SUPERSEDES ──────────────────────────────────────────────────
380
442
  //
381
443
  // The composite key is strictly stronger: it enforces everything the single-column key
@@ -451,6 +513,14 @@ function generateTenancyMigration(opts = {}) {
451
513
  // ── the files ─────────────────────────────────────────────────────────────────────────────
452
514
 
453
515
  const fks = compositeFks();
516
+ // A NO_CASCADE entry that named no composite key is a typo, and a typo here leaves an
517
+ // attribution key cascading — the hazard the list exists to prevent. Refused, naming it.
518
+ const unused = [...noCascade].filter((k) => !usedNoCascade.has(k));
519
+ if (unused.length) {
520
+ throw new Error(`generateTenancyMigration: NO_CASCADE names ${unused.join(', ')}, which is not a `
521
+ + 'composite tenant-to-tenant key in this schema. Each entry is "table.column" for a scoped '
522
+ + 'table\'s foreign key into another scoped table.');
523
+ }
454
524
  const widenCount = (manifest.WIDEN_UNIQUE || []).length;
455
525
 
456
526
  const sqliteFile = [
@@ -569,7 +639,10 @@ function generateTenancyMigration(opts = {}) {
569
639
  [`${prefix}_partner_tenancy.postgres.sql`]: postgresFile,
570
640
  [`${rlsPrefix}_partner_rls.postgres.sql`]: rlsFile
571
641
  },
572
- stats: { tables: ordered.length, compositeFks: fks.count, widened: widenCount, partnerFks: ordered.length }
642
+ stats: {
643
+ tables: ordered.length, compositeFks: fks.count, widened: widenCount, partnerFks: ordered.length,
644
+ attributionKeys
645
+ }
573
646
  };
574
647
  } finally {
575
648
  try { db.close(); } catch (_) { /* best effort */ }
@@ -695,4 +768,186 @@ function generatePartnerFkAdoption(opts = {}) {
695
768
  return { files: { [file]: sql.join('\n') }, stats: { tables: tables.length } };
696
769
  }
697
770
 
698
- module.exports = { generateTenancyMigration, generatePartnerFkAdoption };
771
+ /**
772
+ * The pg_constraint predicate for "a composite tenancy key on `rel`": a two-column foreign key one
773
+ * of whose columns is partner_id and references the PARENT's partner_id. BY SHAPE, not by the name
774
+ * the generator gives it (`fk_<table>_<col>_partner`), so a hand-written key of the same shape —
775
+ * which has exactly the same move hazard — is treated the same.
776
+ */
777
+ function compositeKeyShape(rel) {
778
+ return `c.conrelid = ${rel} AND c.contype = 'f' AND cardinality(c.conkey) = 2`
779
+ + ' AND EXISTS (SELECT 1 FROM generate_subscripts(c.conkey, 1) AS i'
780
+ + ' JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[i]'
781
+ + ' JOIN pg_attribute ra ON ra.attrelid = c.confrelid AND ra.attnum = c.confkey[i]'
782
+ + " WHERE a.attname = 'partner_id' AND ra.attname = 'partner_id')";
783
+ }
784
+
785
+ /**
786
+ * generateCompositeOnUpdateAdoption — the migration that brings an installation's composite tenancy
787
+ * keys to the rule the generator now emits: OWNERSHIP keys ON UPDATE CASCADE, ATTRIBUTION keys not.
788
+ *
789
+ * TWO INSTALLATIONS NEED IT, AND ONE FILE SERVES BOTH, because it CONVERGES rather than adds:
790
+ * - keys generated through 0.24.0 carry no ON UPDATE, so `UPDATE <parent> SET partner_id` is
791
+ * refused for any parent with a child row — ownership keys gain CASCADE;
792
+ * - keys adopted with 0.25.0 cascade into the PRINCIPAL table too, so re-homing a user carried the
793
+ * tenant's rows with them — attribution keys LOSE CASCADE (the 0.25.0 repair: regenerate this
794
+ * under a new prefix and run it).
795
+ *
796
+ * ATTRIBUTION = a key whose parent is `principalTable` (default `users`), or one named in the
797
+ * manifest's NO_CASCADE ('table.column'). The same rule generateTenancyMigration applies.
798
+ *
799
+ * Postgres-only (no plain sibling — SQLite has no composite keys), and it needs only the manifest: it
800
+ * asks the live catalogue, at migration time, which keys exist.
801
+ *
802
+ * THREE STEPS, in one DO block (and so in the runner's one transaction):
803
+ * 1. REFUSE, before anything changes, naming every table and constraint, if any scoped table
804
+ * lacks partner_id; any composite key has ON UPDATE RESTRICT / SET NULL / SET DEFAULT, or an
805
+ * ON DELETE SET NULL / SET DEFAULT that writes partner_id; or a NO_CASCADE entry names no
806
+ * composite key (a typo would leave an attribution key cascading).
807
+ * 2. RE-ADD each key that is on the wrong side, under the SAME name, in one
808
+ * `ALTER TABLE … DROP CONSTRAINT x, ADD CONSTRAINT x <def>` — <def> is Postgres's own
809
+ * pg_get_constraintdef() with ON UPDATE CASCADE inserted (ownership) or removed (attribution),
810
+ * so ON DELETE (with its column list), MATCH, DEFERRABLE and NOT VALID survive verbatim, and a
811
+ * definition this cannot rewrite is refused rather than guessed at.
812
+ * 3. PROVE it, both directions: an ownership key not CASCADE raises; an attribution key that is
813
+ * CASCADE raises.
814
+ * A key already on the right side is untouched, so a second run changes nothing.
815
+ *
816
+ * The re-add re-validates each key (a scan of the child under the ALTER's lock). The rows already
817
+ * satisfied it, so this cannot fail on data; it costs time on a very large child table.
818
+ *
819
+ * @param {{ manifest: object, prefix: string, principalTable?: string, generatedBy?: string }} opts
820
+ * @returns {{files: Object<string,string>, stats: {tables:number, noCascade:number}}}
821
+ */
822
+ function generateCompositeOnUpdateAdoption(opts = {}) {
823
+ const { manifest } = opts;
824
+ if (!manifest || typeof manifest.scoped !== 'function') {
825
+ throw new Error('generateCompositeOnUpdateAdoption({ manifest, prefix }): a tenancy manifest with scoped() is required');
826
+ }
827
+ if (!opts.prefix) {
828
+ throw new Error('generateCompositeOnUpdateAdoption({ manifest, prefix }): prefix is required — the next '
829
+ + 'free migration number in the app\'s chain');
830
+ }
831
+ const generatedBy = opts.generatedBy || '@aria-framework/db-worker generateCompositeOnUpdateAdoption';
832
+ const principalTable = opts.principalTable || 'users';
833
+ if (!/^[a-z_][a-z0-9_]*$/i.test(principalTable)) {
834
+ throw new Error(`generateCompositeOnUpdateAdoption: principalTable ${JSON.stringify(principalTable)} is not a plain table name`);
835
+ }
836
+ const tables = manifest.scoped().map((s) => s.table).sort();
837
+ if (!tables.length) {
838
+ throw new Error('generateCompositeOnUpdateAdoption: the manifest has no scoped tables, so this would emit '
839
+ + 'a migration that changes nothing and reports success.');
840
+ }
841
+ const noCascade = [...noCascadeSet(manifest, 'generateCompositeOnUpdateAdoption')].map((k) => k.split('.'));
842
+ for (const [t] of noCascade) {
843
+ if (!tables.includes(t)) {
844
+ throw new Error(`generateCompositeOnUpdateAdoption: NO_CASCADE names ${t}, which is not a scoped table`);
845
+ }
846
+ }
847
+ const file = `${opts.prefix}_composite_on_update.postgres.sql`;
848
+ const arr = `ARRAY[${tables.map((t) => `'${t}'`).join(', ')}]`;
849
+ const shape = compositeKeyShape('to_regclass(t)');
850
+ // The key's own (non-partner_id) column, for matching a NO_CASCADE 'table.column'.
851
+ const keyCol = "(SELECT a.attname::text FROM pg_attribute a WHERE a.attrelid = c.conrelid"
852
+ + " AND a.attnum = ANY (c.conkey) AND a.attname <> 'partner_id' LIMIT 1)";
853
+ const attribution = `(c.confrelid = to_regclass('${principalTable}')`
854
+ + (noCascade.length
855
+ ? ` OR (t, ${keyCol}) IN (${noCascade.map(([tb, col]) => `('${tb}', '${col}')`).join(', ')})`
856
+ : '')
857
+ + ')';
858
+ const sql = [
859
+ `-- ${file} — GENERATED by ${generatedBy}`,
860
+ '--',
861
+ '-- ADOPTION: composite (column, partner_id) keys converge on the rule — OWNERSHIP keys ON UPDATE',
862
+ '-- CASCADE (`UPDATE <parent> SET partner_id` carries every child, and every child of a child, in',
863
+ '-- one statement), ATTRIBUTION keys not (keys into ' + principalTable + (noCascade.length ? ', and NO_CASCADE: '
864
+ + noCascade.map((p) => p.join('.')).join(', ') : '') + '): re-homing a',
865
+ '-- user who owns or authored rows is refused rather than carrying the tenant\'s rows with them.',
866
+ '-- Serves a pre-0.25 install (adds CASCADE) and a 0.25 one (removes it from attribution keys).',
867
+ '-- Refuses keys it must not touch; re-adds the rest under the same name from their own',
868
+ '-- definition; proves both directions. Idempotent.',
869
+ `-- ${tables.length} tables.`,
870
+ '',
871
+ 'DO $$',
872
+ 'DECLARE',
873
+ ' t text;',
874
+ ' k record;',
875
+ ' def text;',
876
+ ' newdef text;',
877
+ ' added int := 0;',
878
+ ' removed int := 0;',
879
+ " bad text := '';",
880
+ 'BEGIN',
881
+ ' -- 1. Refuse, before anything changes.',
882
+ ` FOREACH t IN ARRAY ${arr} LOOP`,
883
+ ' IF NOT EXISTS (SELECT 1 FROM pg_attribute',
884
+ " WHERE attrelid = to_regclass(t) AND attname = 'partner_id' AND NOT attisdropped) THEN",
885
+ " RAISE EXCEPTION 'composite ON UPDATE adoption: table % has no partner_id column (or does not exist). '",
886
+ " 'The manifest names it as scoped; run its tenancy migration first.', t;",
887
+ ' END IF;',
888
+ ` FOR k IN SELECT c.conname, c.confupdtype, c.confdeltype FROM pg_constraint c WHERE ${shape}`,
889
+ " AND (c.confupdtype IN ('r', 'n', 'd')",
890
+ " OR (c.confdeltype IN ('n', 'd') AND (c.confdelsetcols IS NULL OR cardinality(c.confdelsetcols) = 0",
891
+ " OR (SELECT attnum FROM pg_attribute WHERE attrelid = c.conrelid AND attname = 'partner_id')",
892
+ ' = ANY (c.confdelsetcols)))) LOOP',
893
+ " bad := bad || format('%s.%s (ON UPDATE %s, ON DELETE %s); ', t, k.conname, k.confupdtype, k.confdeltype);",
894
+ ' END LOOP;',
895
+ ' END LOOP;',
896
+ ...noCascade.map(([tb, col]) => [
897
+ ` t := '${tb}';`,
898
+ ` IF NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE ${shape} AND ${keyCol} = '${col}') THEN`,
899
+ ` bad := bad || 'NO_CASCADE ${tb}.${col} names no composite key; ';`,
900
+ ' END IF;'
901
+ ].join('\n')),
902
+ " IF bad <> '' THEN",
903
+ " RAISE EXCEPTION 'composite ON UPDATE adoption refused — %', bad",
904
+ " 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>)); correct any NO_CASCADE entry; then re-run. Nothing was changed.';",
905
+ ' END IF;',
906
+ '',
907
+ ' -- 2a. OWNERSHIP keys with no update action gain ON UPDATE CASCADE.',
908
+ ` FOREACH t IN ARRAY ${arr} LOOP`,
909
+ ` FOR k IN SELECT c.oid, c.conname, c.conrelid FROM pg_constraint c WHERE ${shape}`,
910
+ ` AND c.confupdtype = 'a' AND NOT ${attribution} ORDER BY c.conname LOOP`,
911
+ ' def := pg_get_constraintdef(k.oid);',
912
+ // After `REFERENCES t(cols)` and any MATCH clause — Postgres's grammar puts MATCH before the
913
+ // key actions, and either order of ON UPDATE / ON DELETE is accepted.
914
+ " newdef := regexp_replace(def, '^(FOREIGN KEY \\([^)]*\\) REFERENCES [^(]+\\([^)]*\\)( MATCH [A-Z]+)?)', '\\1 ON UPDATE CASCADE');",
915
+ ' IF newdef = def THEN',
916
+ " RAISE EXCEPTION 'composite ON UPDATE adoption: cannot rewrite %.% — unexpected definition: %', t, k.conname, def;",
917
+ ' END IF;',
918
+ " EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I, ADD CONSTRAINT %I %s', k.conrelid::regclass, k.conname, k.conname, newdef);",
919
+ ' added := added + 1;',
920
+ ' END LOOP;',
921
+ ' END LOOP;',
922
+ '',
923
+ ' -- 2b. ATTRIBUTION keys that cascade (db-worker 0.25.0) lose it.',
924
+ ` FOREACH t IN ARRAY ${arr} LOOP`,
925
+ ` FOR k IN SELECT c.oid, c.conname, c.conrelid FROM pg_constraint c WHERE ${shape}`,
926
+ ` AND c.confupdtype = 'c' AND ${attribution} ORDER BY c.conname LOOP`,
927
+ ' def := pg_get_constraintdef(k.oid);',
928
+ " newdef := regexp_replace(def, ' ON UPDATE CASCADE', '');",
929
+ ' IF newdef = def THEN',
930
+ " RAISE EXCEPTION 'composite ON UPDATE adoption: cannot rewrite %.% — unexpected definition: %', t, k.conname, def;",
931
+ ' END IF;',
932
+ " EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I, ADD CONSTRAINT %I %s', k.conrelid::regclass, k.conname, k.conname, newdef);",
933
+ ' removed := removed + 1;',
934
+ ' END LOOP;',
935
+ ' END LOOP;',
936
+ '',
937
+ ' -- 3. Prove it, both directions.',
938
+ ` FOREACH t IN ARRAY ${arr} LOOP`,
939
+ ` FOR k IN SELECT c.conname FROM pg_constraint c WHERE ${shape} AND c.confupdtype <> 'c' AND NOT ${attribution} LOOP`,
940
+ " RAISE EXCEPTION 'composite ON UPDATE adoption: ownership key %.% is still not ON UPDATE CASCADE', t, k.conname;",
941
+ ' END LOOP;',
942
+ ` FOR k IN SELECT c.conname FROM pg_constraint c WHERE ${shape} AND c.confupdtype = 'c' AND ${attribution} LOOP`,
943
+ " RAISE EXCEPTION 'composite ON UPDATE adoption: attribution key %.% must not be ON UPDATE CASCADE', t, k.conname;",
944
+ ' END LOOP;',
945
+ ' END LOOP;',
946
+ " RAISE NOTICE 'composite ON UPDATE adoption: % ownership key(s) given ON UPDATE CASCADE, % attribution key(s) relieved of it', added, removed;",
947
+ 'END $$;',
948
+ ''
949
+ ];
950
+ return { files: { [file]: sql.join('\n') }, stats: { tables: tables.length, noCascade: noCascade.length } };
951
+ }
952
+
953
+ module.exports = { generateTenancyMigration, generatePartnerFkAdoption, generateCompositeOnUpdateAdoption };