@aria-framework/db-worker 0.23.0 → 0.24.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 +50 -0
- package/package.json +2 -2
- package/tenancyMigration.js +226 -8
package/README.md
CHANGED
|
@@ -304,8 +304,58 @@ 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
|
+
|
|
307
353
|
## Changelog
|
|
308
354
|
|
|
355
|
+
- **0.24.0** — partner_id → partners(id) from the generator, and `generatePartnerFkAdoption`
|
|
356
|
+
(above). `stats.partnerFks` added to the generator's result. The generator's partner-key lines
|
|
357
|
+
are guarded, idempotent statements; both paths refuse an existing partner key with an unsafe
|
|
358
|
+
`ON DELETE`.
|
|
309
359
|
- **0.15.0** — nowPlusMinutes, startOf, dateGroup, daysBetween (above).
|
|
310
360
|
|
|
311
361
|
- **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.
|
|
3
|
+
"version": "0.24.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/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
|
}
|
package/tenancyMigration.js
CHANGED
|
@@ -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)
|
|
@@ -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. */
|
|
@@ -364,10 +460,10 @@ function generateTenancyMigration(opts = {}) {
|
|
|
364
460
|
'-- partner_id so the application code is identical on both engines — a query written once is',
|
|
365
461
|
'-- correct on both.',
|
|
366
462
|
'--',
|
|
367
|
-
'-- The composite foreign keys and the per-partner unique constraints
|
|
368
|
-
'-- sibling, and their absence here is deliberate twice over: SQLite
|
|
369
|
-
'-- table constraint without rebuilding the table, and with one partner
|
|
370
|
-
'-- partner_id to prevent and nothing to disambiguate.',
|
|
463
|
+
'-- The composite foreign keys, partner_id → partners(id), and the per-partner unique constraints',
|
|
464
|
+
'-- live in the .postgres.sql sibling, and their absence here is deliberate twice over: SQLite',
|
|
465
|
+
'-- cannot alter an inline table constraint without rebuilding the table, and with one partner',
|
|
466
|
+
'-- there is no wrong partner_id to prevent and nothing to disambiguate.',
|
|
371
467
|
'',
|
|
372
468
|
partnersTable('sqlite'),
|
|
373
469
|
'',
|
|
@@ -378,9 +474,10 @@ function generateTenancyMigration(opts = {}) {
|
|
|
378
474
|
const postgresFile = [
|
|
379
475
|
`-- ${prefix}_partner_tenancy.postgres.sql — GENERATED by ${generatedBy}`,
|
|
380
476
|
'--',
|
|
381
|
-
'-- The Postgres half. The same columns as the sqlite sibling, plus the
|
|
477
|
+
'-- The Postgres half. The same columns as the sqlite sibling, plus the four things that only',
|
|
382
478
|
'-- mean something with more than one tenant: a partner_id that DEFAULTS FROM THE SESSION',
|
|
383
|
-
`-- SCOPE, ${fks.count} composite foreign keys, and
|
|
479
|
+
`-- SCOPE and REFERENCES partners(id) (${ordered.length} tables), ${fks.count} composite foreign keys, and`,
|
|
480
|
+
`-- ${widenCount} unique constraints scoped per partner.`,
|
|
384
481
|
'--',
|
|
385
482
|
'-- The default is why no model sets partner_id. A platform user acting for a particular',
|
|
386
483
|
'-- partner has to establish that scope first, which is the intent rather than a limitation.',
|
|
@@ -391,6 +488,8 @@ function generateTenancyMigration(opts = {}) {
|
|
|
391
488
|
'-- see could not be joined to.',
|
|
392
489
|
partnerIdColumns('postgres'),
|
|
393
490
|
'',
|
|
491
|
+
partnerFks(),
|
|
492
|
+
'',
|
|
394
493
|
uniqueTargets(),
|
|
395
494
|
'',
|
|
396
495
|
fks.sql,
|
|
@@ -470,11 +569,130 @@ function generateTenancyMigration(opts = {}) {
|
|
|
470
569
|
[`${prefix}_partner_tenancy.postgres.sql`]: postgresFile,
|
|
471
570
|
[`${rlsPrefix}_partner_rls.postgres.sql`]: rlsFile
|
|
472
571
|
},
|
|
473
|
-
stats: { tables: ordered.length, compositeFks: fks.count, widened: widenCount }
|
|
572
|
+
stats: { tables: ordered.length, compositeFks: fks.count, widened: widenCount, partnerFks: ordered.length }
|
|
474
573
|
};
|
|
475
574
|
} finally {
|
|
476
575
|
try { db.close(); } catch (_) { /* best effort */ }
|
|
477
576
|
}
|
|
478
577
|
}
|
|
479
578
|
|
|
480
|
-
|
|
579
|
+
/**
|
|
580
|
+
* generatePartnerFkAdoption — the migration an installation that ALREADY RAN a pre-0.24.0 tenancy
|
|
581
|
+
* migration needs, to gain partner_id → partners(id) on every scoped table.
|
|
582
|
+
*
|
|
583
|
+
* Regenerating the tenancy pair would change files that have already run (the ledger is keyed by
|
|
584
|
+
* filename and would never re-run them), so this is a NEW, Postgres-only file (no plain sibling:
|
|
585
|
+
* SQLite never runs it). It needs only the manifest — no schema file — because it asks the live
|
|
586
|
+
* catalogue, at migration time, what is already there.
|
|
587
|
+
*
|
|
588
|
+
* FOUR STEPS, in this order, and the order is the design:
|
|
589
|
+
* 1. REFUSE if any scoped table holds a partner_id naming a partner that does not exist, naming
|
|
590
|
+
* EVERY such table with its count in one error — so an operator fixes them all in one pass,
|
|
591
|
+
* and so nothing below has run: the migration never half-adopts. IN THE SAME PASS, refuse an
|
|
592
|
+
* EXISTING key of the right shape whose ON DELETE is not NO ACTION/RESTRICT, naming table and
|
|
593
|
+
* constraint: skipping it "because it exists" would keep a CASCADE that deletes a partner's
|
|
594
|
+
* data. (It runs in the runner's transaction, so even a later failure rolls everything back.)
|
|
595
|
+
* 2. ADD each missing key NOT VALID.
|
|
596
|
+
* 3. VALIDATE each one as a SEPARATE statement. UNDER THIS PACKAGE'S RUNNER THAT SAVES NO LOCK
|
|
597
|
+
* TIME: it applies a file in one transaction, so every lock step 2 takes (on partners and on
|
|
598
|
+
* each scoped table) is held through every VALIDATE scan until commit. What the split buys is
|
|
599
|
+
* only an OPTION: the file's statements can be run apart — steps 1–2, commit, then step 3 —
|
|
600
|
+
* by an operator who needs that on a very large table.
|
|
601
|
+
* 4. Idempotent throughout: a key that already exists BY SHAPE (see partnerFkShape) is kept,
|
|
602
|
+
* whatever it is called — including one the app declared inline itself.
|
|
603
|
+
*
|
|
604
|
+
* ROW SECURITY IS SWITCHED OFF FOR THE COUNT, deliberately. The migration role should hold
|
|
605
|
+
* BYPASSRLS (frozen spec §3). If it does not, a FORCE'd table would silently filter the orphan
|
|
606
|
+
* count to zero; with `row_security = off` Postgres instead RAISES ("query would be affected by
|
|
607
|
+
* row-level security policy") — Postgres's documented behaviour. test/tenancyPartnerFk.pg.js
|
|
608
|
+
* proves it only when given a non-BYPASSRLS role (ARIA_TEST_PG_NOBYPASS), and reports it NOT RUN
|
|
609
|
+
* otherwise. (VALIDATE would catch orphans anyway — referential checks ignore RLS — but with a
|
|
610
|
+
* message naming one constraint, not every table.)
|
|
611
|
+
*
|
|
612
|
+
* @param {{ manifest: object, prefix: string, generatedBy?: string }} opts
|
|
613
|
+
* @returns {{files: Object<string,string>, stats: {tables:number}}}
|
|
614
|
+
*/
|
|
615
|
+
function generatePartnerFkAdoption(opts = {}) {
|
|
616
|
+
const { manifest } = opts;
|
|
617
|
+
if (!manifest || typeof manifest.scoped !== 'function') {
|
|
618
|
+
throw new Error('generatePartnerFkAdoption({ manifest, prefix }): a tenancy manifest with scoped() is required');
|
|
619
|
+
}
|
|
620
|
+
// No default: this file lands in an app's existing chain, and only the app knows the next number.
|
|
621
|
+
if (!opts.prefix) {
|
|
622
|
+
throw new Error('generatePartnerFkAdoption({ manifest, prefix }): prefix is required — the next '
|
|
623
|
+
+ 'free migration number in the app\'s chain');
|
|
624
|
+
}
|
|
625
|
+
const generatedBy = opts.generatedBy || '@aria-framework/db-worker generatePartnerFkAdoption';
|
|
626
|
+
const tables = manifest.scoped().map((s) => s.table).sort();
|
|
627
|
+
if (!tables.length) {
|
|
628
|
+
throw new Error('generatePartnerFkAdoption: the manifest has no scoped tables, so this would emit '
|
|
629
|
+
+ 'a migration that adopts nothing and reports success.');
|
|
630
|
+
}
|
|
631
|
+
for (const t of tables) partnerFkName(t); // refuse a name Postgres would truncate, up front
|
|
632
|
+
|
|
633
|
+
const file = `${opts.prefix}_partner_fk.postgres.sql`;
|
|
634
|
+
const arr = `ARRAY[${tables.map((t) => `'${t}'`).join(', ')}]`;
|
|
635
|
+
const sql = [
|
|
636
|
+
`-- ${file} — GENERATED by ${generatedBy}`,
|
|
637
|
+
'--',
|
|
638
|
+
'-- ADOPTION: partner_id → partners(id) on every scoped table, for an installation whose tenancy',
|
|
639
|
+
'-- migration predates it. The frozen spec always required this key; the generator did not emit',
|
|
640
|
+
'-- it before db-worker 0.24.0, so rows could outlive their partner or name one that never',
|
|
641
|
+
'-- existed. Refuses while such rows exist, naming them; adds NOT VALID; validates separately;',
|
|
642
|
+
`-- skips a key that already exists by shape. Idempotent. ${tables.length} tables.`,
|
|
643
|
+
'',
|
|
644
|
+
'-- 1. Refuse orphans — every table and its count — and any existing partner key whose ON DELETE',
|
|
645
|
+
'-- would delete or re-home a partner\'s rows, before anything changes.',
|
|
646
|
+
'DO $$',
|
|
647
|
+
'DECLARE',
|
|
648
|
+
' t text;',
|
|
649
|
+
' n bigint;',
|
|
650
|
+
' k record;',
|
|
651
|
+
" found text := '';",
|
|
652
|
+
" unsafe text := '';",
|
|
653
|
+
" prev text := current_setting('row_security');",
|
|
654
|
+
'BEGIN',
|
|
655
|
+
" PERFORM set_config('row_security', 'off', true);",
|
|
656
|
+
` FOREACH t IN ARRAY ${arr} LOOP`,
|
|
657
|
+
' IF NOT EXISTS (SELECT 1 FROM pg_attribute',
|
|
658
|
+
" WHERE attrelid = to_regclass(t) AND attname = 'partner_id' AND NOT attisdropped) THEN",
|
|
659
|
+
" RAISE EXCEPTION 'partner FK adoption: table % has no partner_id column (or does not exist). '",
|
|
660
|
+
" 'The manifest names it as scoped; run its tenancy migration first.', t;",
|
|
661
|
+
' END IF;',
|
|
662
|
+
` FOR k IN SELECT c.conname, c.confdeltype FROM pg_constraint c WHERE ${partnerFkShape('to_regclass(t)')}`,
|
|
663
|
+
` AND c.confdeltype NOT IN ${PARTNER_FK_SAFE_ACTIONS} LOOP`,
|
|
664
|
+
" unsafe := unsafe || format('%s.%s (ON DELETE %s); ', t, k.conname,",
|
|
665
|
+
" CASE k.confdeltype WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' ELSE k.confdeltype::text END);",
|
|
666
|
+
' END LOOP;',
|
|
667
|
+
' EXECUTE format(',
|
|
668
|
+
" 'SELECT count(*) FROM %I x WHERE x.partner_id IS NOT NULL '",
|
|
669
|
+
" 'AND NOT EXISTS (SELECT 1 FROM partners p WHERE p.id = x.partner_id)', t) INTO n;",
|
|
670
|
+
" IF n > 0 THEN found := found || format('%s: %s; ', t, n); END IF;",
|
|
671
|
+
' END LOOP;',
|
|
672
|
+
" IF unsafe <> '' THEN",
|
|
673
|
+
" RAISE EXCEPTION 'partner FK adoption refused: an existing partner key would delete or re-home a partner''s rows instead of refusing — %', unsafe",
|
|
674
|
+
" USING HINT = 'Replace each with ON DELETE NO ACTION (or RESTRICT), then re-run. Nothing was changed.';",
|
|
675
|
+
' END IF;',
|
|
676
|
+
" IF found <> '' THEN",
|
|
677
|
+
" RAISE EXCEPTION 'partner FK adoption refused: rows name a partner that does not exist — %', found",
|
|
678
|
+
" USING HINT = 'Delete or re-home those rows (they are invisible to every partner under RLS), then re-run. Nothing was changed.';",
|
|
679
|
+
' END IF;',
|
|
680
|
+
" PERFORM set_config('row_security', prev, true);",
|
|
681
|
+
'END $$;',
|
|
682
|
+
'',
|
|
683
|
+
'-- 2. Add each missing key NOT VALID.'
|
|
684
|
+
];
|
|
685
|
+
for (const t of tables) sql.push(partnerFkEnsureSql(t, { notValid: true }));
|
|
686
|
+
sql.push('', '-- 3. Validate, as separate statements — every key of the shape not yet validated.',
|
|
687
|
+
'-- Under a one-transaction-per-file runner this holds step 2\'s locks through each scan; the',
|
|
688
|
+
'-- split only lets an operator run steps 1–2 and 3 apart if a table is too large for that.');
|
|
689
|
+
for (const t of tables) {
|
|
690
|
+
sql.push(`DO $$ DECLARE r record; BEGIN FOR r IN SELECT c.conname FROM pg_constraint c`
|
|
691
|
+
+ ` WHERE ${partnerFkShape(`'${t}'::regclass`)} AND NOT c.convalidated`
|
|
692
|
+
+ ` LOOP EXECUTE format('ALTER TABLE ${t} VALIDATE CONSTRAINT %I', r.conname); END LOOP; END $$;`);
|
|
693
|
+
}
|
|
694
|
+
sql.push('');
|
|
695
|
+
return { files: { [file]: sql.join('\n') }, stats: { tables: tables.length } };
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
module.exports = { generateTenancyMigration, generatePartnerFkAdoption };
|