@aria-framework/db-worker 0.24.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
@@ -350,8 +350,59 @@ 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.** 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
+
353
400
  ## Changelog
354
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`.
355
406
  - **0.24.0** — partner_id → partners(id) from the generator, and `generatePartnerFkAdoption`
356
407
  (above). `stats.partnerFks` added to the generator's result. The generator's partner-key lines
357
408
  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.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/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",
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
  }
@@ -202,7 +202,7 @@ function generateTenancyMigration(opts = {}) {
202
202
  // pass a driver instead of a file — it removes a second spelling of the same question.
203
203
  const tenantFks = (table) => db.prepare(sqliteDialect.foreignKeys(table)).all()
204
204
  .filter((f) => scopedNames.has(f.table))
205
- .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 }))
206
206
  // PRAGMA lists newest first; sorting keeps a regenerated file diff-free.
207
207
  .sort((a, b) => (a.from + a.table).localeCompare(b.from + b.table));
208
208
 
@@ -372,10 +372,36 @@ function generateTenancyMigration(opts = {}) {
372
372
  : (fk.onDelete === 'SET NULL' || fk.onDelete === 'SET DEFAULT'
373
373
  ? ` ON DELETE ${fk.onDelete} (${fk.from})`
374
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
+ }
375
401
  out.push(
376
402
  `ALTER TABLE ${table} ADD CONSTRAINT fk_${table}_${fk.from}_partner`
377
403
  + ` FOREIGN KEY (${fk.from}, partner_id)`
378
- + ` REFERENCES ${fk.table} (${fk.to}, partner_id)${del};`);
404
+ + ` REFERENCES ${fk.table} (${fk.to}, partner_id)${del} ON UPDATE CASCADE;`);
379
405
  // ── AND DROP THE ONE IT SUPERSEDES ──────────────────────────────────────────────────
380
406
  //
381
407
  // The composite key is strictly stronger: it enforces everything the single-column key
@@ -695,4 +721,135 @@ function generatePartnerFkAdoption(opts = {}) {
695
721
  return { files: { [file]: sql.join('\n') }, stats: { tables: tables.length } };
696
722
  }
697
723
 
698
- module.exports = { generateTenancyMigration, generatePartnerFkAdoption };
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 };