@aria-framework/db-worker 0.25.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 +43 -1
- package/package.json +3 -2
- package/tenancyMigration.js +137 -39
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
|
|
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,48 @@ 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.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`.
|
|
402
444
|
- **0.25.0** — every composite tenancy key is `ON UPDATE CASCADE`, as the frozen spec's §2 always
|
|
403
445
|
said; a source FK with `ON UPDATE` RESTRICT / SET NULL / SET DEFAULT is refused at generate
|
|
404
446
|
time. `generateCompositeOnUpdateAdoption` for installations whose keys predate it (above).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aria-framework/db-worker",
|
|
3
|
-
"version": "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/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",
|
|
43
44
|
"prepublishOnly": "node ../../test/packaging.js db-worker"
|
|
44
45
|
}
|
|
45
46
|
}
|
package/tenancyMigration.js
CHANGED
|
@@ -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: {
|
|
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
|
|
740
|
-
*
|
|
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
|
-
*
|
|
743
|
-
*
|
|
744
|
-
*
|
|
745
|
-
*
|
|
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
|
|
751
|
-
*
|
|
752
|
-
*
|
|
753
|
-
*
|
|
754
|
-
*
|
|
755
|
-
*
|
|
756
|
-
*
|
|
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:
|
|
760
|
-
*
|
|
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:
|
|
790
|
-
'--
|
|
791
|
-
'--
|
|
792
|
-
|
|
793
|
-
'--
|
|
794
|
-
'--
|
|
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
|
-
'
|
|
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
|
|
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>))
|
|
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
|
-
' --
|
|
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
|
-
|
|
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
|
-
'
|
|
919
|
+
' added := added + 1;',
|
|
839
920
|
' END LOOP;',
|
|
840
921
|
' END LOOP;',
|
|
841
922
|
'',
|
|
842
|
-
' --
|
|
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}
|
|
845
|
-
|
|
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
|
-
|
|
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 };
|