@aria-framework/db-worker 0.25.0 → 0.27.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
@@ -359,7 +359,9 @@ one UPDATE; children follow atomically". Through 0.24.0 the generator emitted no
359
359
  children first fails the other way round). **Every** composite `(column, partner_id)` key now ends
360
360
  `ON UPDATE CASCADE`, beside its ON DELETE (whose SET NULL / SET DEFAULT keep their column list):
361
361
 
362
- - **Every key, not a configured few.** The child's partner_id is a copy of its parent's; a copy
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
363
365
  that cannot follow freezes the parent's tenant once it has a child. CASCADE writes the parent's
364
366
  new value — the only one the key would accept — so a child can never land in a tenant its
365
367
  parent is not in. The statement must still satisfy every *other* composite key of every row it
@@ -397,8 +399,64 @@ every way of moving a row into a tenant its parent is not in, refused with nothi
397
399
  the adoption on the old shape, its refusal, and its idempotence by constraint oid. **As of the
398
400
  0.25.0 commit it has not been run against a server** — see the commit message.
399
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
+
400
438
  ## Changelog
401
439
 
440
+ - **0.27.0** — "Time is UTC" (repo README): a Postgres session and a Date on the wire no longer
441
+ depend on the server's, the role's, the connection string's or the process's timezone.
442
+ - **Every connection the driver opens runs `SET TIME ZONE 'UTC'` first** — the app pool and the
443
+ short-lived migration connection. `'now'::timestamp`, `CURRENT_DATE`, `date_trunc` on a
444
+ timestamptz and a `timestamp` compared with a timestamptz all resolve in the session zone;
445
+ it is now always UTC. SET rather than `options=-c TimeZone=UTC` because a connection
446
+ string's own `options=` silently overrides one passed beside it.
447
+ - **`pinPoolUtc(pool)` is exported** for a pg Pool the app builds itself.
448
+ - **PROCESS-WIDE node-postgres changes** (one parser table per process, like the int8 parser):
449
+ a Date PARAMETER is sent as UTC (`parseInputDatesAsUTC`) where it was sent with the process's
450
+ local offset — which a `timestamp` column discards, storing the host's wall clock; a
451
+ `timestamp` column is READ as UTC where it was read as local; a `date` column is read as the
452
+ string `'YYYY-MM-DD'` where it was a Date at local midnight. An app that relied on a `date`
453
+ arriving as a Date must parse it.
454
+ - `test/timezone.pg.js`: four process zones, against a connection string that asks for
455
+ America/Chicago, temp tables only. 26 of its 37 checks fail on 0.26.0.
456
+ - **0.26.0** — composite keys into the principal table (and any in `NO_CASCADE`) no longer
457
+ cascade; `generateCompositeOnUpdateAdoption` converges both ways and repairs a 0.25.0 install.
458
+ `stats.attributionKeys` (generator) and `stats.noCascade` (adoption). PGlite devDependency;
459
+ `test/tenancyAttribution.pglite.js` in `npm test`.
402
460
  - **0.25.0** — every composite tenancy key is `ON UPDATE CASCADE`, as the frozen spec's §2 always
403
461
  said; a source FK with `ON UPDATE` RESTRICT / SET NULL / SET DEFAULT is refused at generate
404
462
  time. `generateCompositeOnUpdateAdoption` for installations whose keys predate it (above).
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Every Postgres session this framework opens runs in UTC, whatever the server, the database,
3
+ * the role or the connection string says.
4
+ *
5
+ * WHY A SESSION HAS A ZONE AT ALL. Postgres resolves a zoneless value in the SESSION's `TimeZone`:
6
+ * `'now'::timestamp`, `to_timestamp(n)` assigned to a `timestamp` column, `date_trunc` on a
7
+ * timestamptz, `CURRENT_DATE`, a `timestamp` compared with a timestamptz. That setting defaults
8
+ * from postgresql.conf, can be overridden per database and per role, and can be set by the client
9
+ * — so it is not the application's unless the application takes it.
10
+ *
11
+ * WHAT IT COST. connect-pg-simple stores a session's expiry as `to_timestamp(n)` in a
12
+ * `timestamp` (no zone) column and compares it the same way: correct while the zone never
13
+ * changes, and off by the whole offset the moment it does. Measured against a real server — a
14
+ * one-hour session written under UTC and read under America/Chicago lived six hours; written
15
+ * under Chicago and read under UTC, or written under UTC and read under Asia/Kolkata, it was
16
+ * dead on arrival. No error either way.
17
+ *
18
+ * WHY `SET` ON CONNECT, NOT `options=-c TimeZone=UTC`. The startup option is the obvious spelling
19
+ * and it has a hole: in node-postgres a connection STRING's own `options=` silently wins over an
20
+ * `options` passed beside it, so a URL carrying one un-pins the pool with nothing to say so. A
21
+ * SET issued after the session starts overrides the server default, the database default, the
22
+ * role default and the startup packet alike.
23
+ *
24
+ * WHY IT IS IN TIME. pg-pool emits 'connect' synchronously, BEFORE handing the new client to
25
+ * whoever asked for it, and a client runs its queries in the order they were queued. The SET is
26
+ * therefore the first statement on every connection, ahead of the caller's first query.
27
+ * test/timezone.pg.js proves it against a pool whose connection string asks for another zone.
28
+ *
29
+ * LIMIT, stated: only connections opened AFTER the call are pinned. Call it on a pool before
30
+ * its first query — which is what the driver and the session-store factory both do.
31
+ */
32
+
33
+ 'use strict';
34
+
35
+ const PINNED = new WeakSet();
36
+
37
+ /**
38
+ * @param {object} pool a node-postgres Pool
39
+ * @param {{logger?: object}} [opts]
40
+ * @returns {object} the same pool
41
+ */
42
+ function pinPoolUtc(pool, opts = {}) {
43
+ if (!pool || typeof pool.on !== 'function') throw new Error('pinPoolUtc(pool): a pg Pool is required');
44
+ if (PINNED.has(pool)) return pool;
45
+ PINNED.add(pool);
46
+ pool.on('connect', (client) => {
47
+ client.query("SET TIME ZONE 'UTC'").catch((err) => {
48
+ // Loud, because an unpinned session is exactly the silent failure this exists to prevent.
49
+ try { (opts.logger || console).error(`postgres: could not pin a session to UTC (${err.message})`); }
50
+ catch (_) { /* a logging failure must not become an unhandled rejection */ }
51
+ });
52
+ });
53
+ return pool;
54
+ }
55
+
56
+ /**
57
+ * Process-wide node-postgres settings, so a Date crosses the wire as the instant it is.
58
+ *
59
+ * A Date PARAMETER is serialised with the process's local offset by default. Postgres discards
60
+ * the offset when the target is a `timestamp` (no zone) column, so the column receives the
61
+ * HOST's wall clock. `parseInputDatesAsUTC` sends UTC wall clock instead — the same instant for
62
+ * a timestamptz, and the right digits for a timestamp.
63
+ *
64
+ * A `timestamp` (OID 1114) is parsed as LOCAL time by default — the same misreading on the way
65
+ * out. Here its digits are UTC, because that is the only thing this framework ever writes.
66
+ *
67
+ * A `date` (OID 1082) becomes a Date at LOCAL midnight by default: a calendar day turned into
68
+ * an instant, which then prints as the day before anywhere west of UTC. It stays the string
69
+ * 'YYYY-MM-DD' — a date has no zone, and kit's dbTime renders a bare date literally.
70
+ *
71
+ * Array columns of these types (1115, 1182) are left at pg's defaults; nothing here uses one.
72
+ * pg keeps ONE parser table per process, which is why this sits beside the int8 parser in the
73
+ * driver rather than with each consumer.
74
+ */
75
+ function configurePgTypes(pg) {
76
+ pg.defaults.parseInputDatesAsUTC = true;
77
+ pg.types.setTypeParser(1114, (v) => {
78
+ if (v === null) return null;
79
+ if (v === 'infinity') return Infinity;
80
+ if (v === '-infinity') return -Infinity;
81
+ return new Date(v.replace(' ', 'T') + 'Z');
82
+ });
83
+ pg.types.setTypeParser(1082, (v) => v);
84
+ }
85
+
86
+ module.exports = { pinPoolUtc, configurePgTypes };
@@ -30,6 +30,7 @@ const txContext = new AsyncLocalStorage();
30
30
 
31
31
  const { dialectFor } = require('../dialect');
32
32
  const { bindNamed } = require('./params');
33
+ const { pinPoolUtc, configurePgTypes } = require('./pgUtc');
33
34
 
34
35
  /**
35
36
  * Rewrite `?` placeholders to `$1..$n`, leaving any `?` inside a literal alone.
@@ -132,6 +133,8 @@ function createPostgresDriver(opts = {}) {
132
133
  * point the driver is built, rather than by each consumer remembering to.
133
134
  */
134
135
  pg.types.setTypeParser(20, (v) => (v === null ? null : Number(v)));
136
+ // Dates cross the wire as the instants they are, not as the host's wall clock. See pgUtc.js.
137
+ configurePgTypes(pg);
135
138
 
136
139
  // Pass the CONNECTION OPTIONS THROUGH. The guard above accepts host/user/database as an
137
140
  // alternative to a connection string and the JSDoc documents it, but only connectionString was
@@ -144,6 +147,9 @@ function createPostgresDriver(opts = {}) {
144
147
  if (v !== undefined) poolCfg[k] = v;
145
148
  }
146
149
  const pool = new pg.Pool(poolCfg);
150
+ // Every session in UTC, before the first query on it — the app pool AND the short-lived
151
+ // migration connection, since both are built here. See pgUtc.js for why SET and not `options`.
152
+ pinPoolUtc(pool, { logger: opts.logger });
147
153
 
148
154
  // An unhandled 'error' on a Pool CRASHES THE PROCESS, and this is not hypothetical: the restore
149
155
  // path issues pg_terminate_backend and DROP DATABASE ... WITH (FORCE), which kill this pool's
package/index.js CHANGED
@@ -20,6 +20,9 @@ const { dialectFor } = require('./dialect');
20
20
  module.exports = {
21
21
  createSqliteDriver,
22
22
  createPostgresDriver,
23
+ // 0.27.0 — for a pg Pool the app builds ITSELF (a session store's, a reporting pool). The
24
+ // driver pins its own. Does not load `pg`.
25
+ pinPoolUtc: require('./driver/pgUtc').pinPoolUtc,
23
26
  dialectFor,
24
27
  DbClient: require('./client').DbClient,
25
28
  runWorker: require('./worker').runWorker,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.25.0",
3
+ "version": "0.27.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/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
+ "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 && node test/timezone.pg.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 {
@@ -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) {
@@ -398,10 +422,22 @@ function generateTenancyMigration(opts = {}) {
398
422
  : 'write partner_id itself (Postgres takes no column list on ON UPDATE)'}. `
399
423
  + 'Change the source key to NO ACTION or CASCADE, then regenerate.');
400
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
+ }
401
437
  out.push(
402
438
  `ALTER TABLE ${table} ADD CONSTRAINT fk_${table}_${fk.from}_partner`
403
439
  + ` FOREIGN KEY (${fk.from}, partner_id)`
404
- + ` REFERENCES ${fk.table} (${fk.to}, partner_id)${del} ON UPDATE CASCADE;`);
440
+ + ` REFERENCES ${fk.table} (${fk.to}, partner_id)${del}${attribution ? '' : ' ON UPDATE CASCADE'};`);
405
441
  // ── AND DROP THE ONE IT SUPERSEDES ──────────────────────────────────────────────────
406
442
  //
407
443
  // The composite key is strictly stronger: it enforces everything the single-column key
@@ -477,6 +513,14 @@ function generateTenancyMigration(opts = {}) {
477
513
  // ── the files ─────────────────────────────────────────────────────────────────────────────
478
514
 
479
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
+ }
480
524
  const widenCount = (manifest.WIDEN_UNIQUE || []).length;
481
525
 
482
526
  const sqliteFile = [
@@ -595,7 +639,10 @@ function generateTenancyMigration(opts = {}) {
595
639
  [`${prefix}_partner_tenancy.postgres.sql`]: postgresFile,
596
640
  [`${rlsPrefix}_partner_rls.postgres.sql`]: rlsFile
597
641
  },
598
- 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
+ }
599
646
  };
600
647
  } finally {
601
648
  try { db.close(); } catch (_) { /* best effort */ }
@@ -736,34 +783,41 @@ function compositeKeyShape(rel) {
736
783
  }
737
784
 
738
785
  /**
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.
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).
741
795
  *
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.
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.
747
801
  *
748
802
  * THREE STEPS, in one DO block (and so in the runner's one transaction):
749
803
  * 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
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
758
811
  * 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.
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.
761
815
  *
762
816
  * The re-add re-validates each key (a scan of the child under the ALTER's lock). The rows already
763
817
  * satisfied it, so this cannot fail on data; it costs time on a very large child table.
764
818
  *
765
- * @param {{ manifest: object, prefix: string, generatedBy?: string }} opts
766
- * @returns {{files: Object<string,string>, stats: {tables:number}}}
819
+ * @param {{ manifest: object, prefix: string, principalTable?: string, generatedBy?: string }} opts
820
+ * @returns {{files: Object<string,string>, stats: {tables:number, noCascade:number}}}
767
821
  */
768
822
  function generateCompositeOnUpdateAdoption(opts = {}) {
769
823
  const { manifest } = opts;
@@ -775,23 +829,43 @@ function generateCompositeOnUpdateAdoption(opts = {}) {
775
829
  + 'free migration number in the app\'s chain');
776
830
  }
777
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
+ }
778
836
  const tables = manifest.scoped().map((s) => s.table).sort();
779
837
  if (!tables.length) {
780
838
  throw new Error('generateCompositeOnUpdateAdoption: the manifest has no scoped tables, so this would emit '
781
839
  + 'a migration that changes nothing and reports success.');
782
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
+ }
783
847
  const file = `${opts.prefix}_composite_on_update.postgres.sql`;
784
848
  const arr = `ARRAY[${tables.map((t) => `'${t}'`).join(', ')}]`;
785
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
+ + ')';
786
858
  const sql = [
787
859
  `-- ${file} — GENERATED by ${generatedBy}`,
788
860
  '--',
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.',
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.',
795
869
  `-- ${tables.length} tables.`,
796
870
  '',
797
871
  'DO $$',
@@ -800,7 +874,8 @@ function generateCompositeOnUpdateAdoption(opts = {}) {
800
874
  ' k record;',
801
875
  ' def text;',
802
876
  ' newdef text;',
803
- ' n int := 0;',
877
+ ' added int := 0;',
878
+ ' removed int := 0;',
804
879
  " bad text := '';",
805
880
  'BEGIN',
806
881
  ' -- 1. Refuse, before anything changes.',
@@ -818,15 +893,21 @@ function generateCompositeOnUpdateAdoption(opts = {}) {
818
893
  " bad := bad || format('%s.%s (ON UPDATE %s, ON DELETE %s); ', t, k.conname, k.confupdtype, k.confdeltype);",
819
894
  ' END LOOP;',
820
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')),
821
902
  " 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.';",
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.';",
824
905
  ' END IF;',
825
906
  '',
826
- ' -- 2. Re-add each NO ACTION key, same name, its own definition plus ON UPDATE CASCADE.',
907
+ ' -- 2a. OWNERSHIP keys with no update action gain ON UPDATE CASCADE.',
827
908
  ` FOREACH t IN ARRAY ${arr} LOOP`,
828
909
  ` 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",
910
+ ` AND c.confupdtype = 'a' AND NOT ${attribution} ORDER BY c.conname LOOP`,
830
911
  ' def := pg_get_constraintdef(k.oid);',
831
912
  // After `REFERENCES t(cols)` and any MATCH clause — Postgres's grammar puts MATCH before the
832
913
  // key actions, and either order of ON UPDATE / ON DELETE is accepted.
@@ -835,21 +916,38 @@ function generateCompositeOnUpdateAdoption(opts = {}) {
835
916
  " RAISE EXCEPTION 'composite ON UPDATE adoption: cannot rewrite %.% — unexpected definition: %', t, k.conname, def;",
836
917
  ' END IF;',
837
918
  " EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I, ADD CONSTRAINT %I %s', k.conrelid::regclass, k.conname, k.conname, newdef);",
838
- ' n := n + 1;',
919
+ ' added := added + 1;',
839
920
  ' END LOOP;',
840
921
  ' END LOOP;',
841
922
  '',
842
- ' -- 3. Prove it: no composite key on a scoped table is left without ON UPDATE CASCADE.',
923
+ ' -- 2b. ATTRIBUTION keys that cascade (db-worker 0.25.0) lose it.',
843
924
  ` 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;",
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;',
846
934
  ' END LOOP;',
847
935
  ' END LOOP;',
848
- " RAISE NOTICE 'composite ON UPDATE adoption: % key(s) re-added with ON UPDATE CASCADE', n;",
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;",
849
947
  'END $$;',
850
948
  ''
851
949
  ];
852
- return { files: { [file]: sql.join('\n') }, stats: { tables: tables.length } };
950
+ return { files: { [file]: sql.join('\n') }, stats: { tables: tables.length, noCascade: noCascade.length } };
853
951
  }
854
952
 
855
953
  module.exports = { generateTenancyMigration, generatePartnerFkAdoption, generateCompositeOnUpdateAdoption };