@aria-framework/db-worker 0.18.0 → 0.20.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 +34 -3
- package/database.js +88 -10
- package/dialect.js +30 -0
- package/index.js +11 -1
- package/package.json +12 -11
- package/tenancyMigration.js +333 -0
package/README.md
CHANGED
|
@@ -106,11 +106,42 @@ Model methods may be sync or async (thenables are awaited). BigInts in results
|
|
|
106
106
|
busy_timeout=5000` and creates the `migrations` tracking table.
|
|
107
107
|
**`onOpen(db)` runs FIRST, before any pragma or table access** — this is the
|
|
108
108
|
SQLCipher hook: an encrypted DB needs `pragma key` before anything touches it.
|
|
109
|
-
- `runMigrations(migrationsDir)` — applies `*.sql` sorted by
|
|
110
|
-
a transaction with its tracking-row insert; already-applied files
|
|
111
|
-
A file can opt out — see below.
|
|
109
|
+
- `runMigrations(migrationsDir, { connectionString } = {})` — applies `*.sql` sorted by
|
|
110
|
+
filename, each in a transaction with its tracking-row insert; already-applied files
|
|
111
|
+
skipped. A file can opt out — see below. `connectionString` runs the migrations as a
|
|
112
|
+
different role — see next section.
|
|
112
113
|
- `getDb()` / `close()`
|
|
113
114
|
|
|
115
|
+
## Migrations as a separate owner role (0.20.0, Postgres)
|
|
116
|
+
|
|
117
|
+
**In Postgres the role that creates a table owns it, and an owner bypasses `ENABLE ROW LEVEL
|
|
118
|
+
SECURITY`.** So an application that runs its own migrations owns every table it migrated, and a
|
|
119
|
+
tenant boundary built on RLS then rests entirely on `FORCE` being set on every table, for ever —
|
|
120
|
+
including the ones tomorrow's migration adds.
|
|
121
|
+
|
|
122
|
+
```js
|
|
123
|
+
await database.initDriver({ kind: 'postgres', connectionString: process.env.DATABASE_URL });
|
|
124
|
+
await database.runMigrations(dir, { connectionString: process.env.MIGRATION_DATABASE_URL });
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
With `connectionString`, migrations run on a **separate, short-lived connection** as that role, and
|
|
128
|
+
the application's own driver is never touched. That connection is **destroyed** afterwards, not
|
|
129
|
+
returned to a pool: a pooled privileged connection that a later application query could draw would
|
|
130
|
+
bypass every partner boundary silently — no error, no symptom, wrong rows.
|
|
131
|
+
|
|
132
|
+
The migrations **ledger** is created on that connection too. Created by the app role it would be
|
|
133
|
+
one app-owned table in an otherwise correctly-owned schema, and one is enough.
|
|
134
|
+
|
|
135
|
+
Afterwards the runner asks the *application's* driver who it actually is and **throws** if it holds
|
|
136
|
+
`BYPASSRLS`. Everything above is intent; that check is what makes it a fact.
|
|
137
|
+
|
|
138
|
+
On SQLite there are no roles, so the option is ignored — and says so in the log rather than being
|
|
139
|
+
silently dropped.
|
|
140
|
+
|
|
141
|
+
> Provisioning the roles is the consuming app's job. `aria-starter` ships
|
|
142
|
+
> `scripts/test-pg-provisioning.js`, which asserts the application role owns nothing and holds no
|
|
143
|
+
> `BYPASSRLS`, that every RLS table is also `FORCE`d, and that the backup role can actually read.
|
|
144
|
+
|
|
114
145
|
## Migrations that cannot run inside a transaction (0.8.0)
|
|
115
146
|
|
|
116
147
|
Some DDL is illegal inside a transaction. A migration declares that with a
|
package/database.js
CHANGED
|
@@ -330,10 +330,19 @@ function coveredBy(file, through, files) {
|
|
|
330
330
|
*
|
|
331
331
|
* @returns {Promise<{applied: number}>}
|
|
332
332
|
*/
|
|
333
|
-
function runMigrations(migrationsDir) {
|
|
333
|
+
function runMigrations(migrationsDir, opts = {}) {
|
|
334
334
|
const d = driver();
|
|
335
335
|
if (!d) throw new Error('runMigrations: call init()/initDriver() first');
|
|
336
336
|
|
|
337
|
+
// ANNOUNCED, NOT SILENTLY DROPPED. SQLite has no roles, so a migration connection string is
|
|
338
|
+
// meaningless there — but an argument that is quietly ignored is how a dual-engine app ends up
|
|
339
|
+
// believing its migrations run as a separate role when they never have. Said out loud instead.
|
|
340
|
+
if (opts.connectionString && d.kind !== 'postgres') {
|
|
341
|
+
_logger.warn(`runMigrations: a migration connectionString was supplied but the driver is `
|
|
342
|
+
+ `'${d.kind}', which has no roles — it is being IGNORED and migrations run on the ordinary `
|
|
343
|
+
+ 'connection. Pass it only on Postgres.');
|
|
344
|
+
}
|
|
345
|
+
|
|
337
346
|
if (!migrationsDir || !fs.existsSync(migrationsDir)) {
|
|
338
347
|
_logger.warn('No migrations directory found');
|
|
339
348
|
return Promise.resolve({ applied: 0 });
|
|
@@ -391,7 +400,71 @@ function runMigrations(migrationsDir) {
|
|
|
391
400
|
|
|
392
401
|
// ── the async path, for engines that have no synchronous driver ───────────────────────────
|
|
393
402
|
return (async () => {
|
|
394
|
-
|
|
403
|
+
// ── THE MIGRATION CONNECTION ────────────────────────────────────────────────────────────
|
|
404
|
+
//
|
|
405
|
+
// In Postgres THE ROLE THAT CREATES A TABLE OWNS IT, and an owner bypasses ENABLE ROW LEVEL
|
|
406
|
+
// SECURITY. So an application that runs its own migrations owns every table it migrated, and
|
|
407
|
+
// the whole tenant boundary then rests on FORCE being present on every table for ever —
|
|
408
|
+
// including the ones tomorrow's migration adds. Frozen spec §3: the application connects as a
|
|
409
|
+
// role that owns nothing; the migration role and the backup role are the only BYPASSRLS
|
|
410
|
+
// holders.
|
|
411
|
+
//
|
|
412
|
+
// Given `connectionString`, migrations run on a SEPARATE, SHORT-LIVED connection as that
|
|
413
|
+
// owner/migration role, and the application's own driver is never touched. It is opened here
|
|
414
|
+
// and destroyed in the finally below — NOT returned to a pool, because a pooled privileged
|
|
415
|
+
// connection that a later app query could draw would bypass every partner boundary silently,
|
|
416
|
+
// with no error and no symptom. That is the one outcome worse than the problem being fixed.
|
|
417
|
+
const owner = opts.connectionString
|
|
418
|
+
? require('./driver/postgres').createPostgresDriver({
|
|
419
|
+
connectionString: opts.connectionString,
|
|
420
|
+
logger: _logger
|
|
421
|
+
})
|
|
422
|
+
: null;
|
|
423
|
+
const md = owner || d;
|
|
424
|
+
|
|
425
|
+
try {
|
|
426
|
+
// The LEDGER on the migration connection too. Created by the app role, `migrations` would be
|
|
427
|
+
// one app-owned table in an otherwise correctly-owned schema — and one is enough.
|
|
428
|
+
if (owner) await ensureMigrationsTable(owner);
|
|
429
|
+
return await runMigrationsOn(md);
|
|
430
|
+
} finally {
|
|
431
|
+
if (owner) {
|
|
432
|
+
// AWAITED, AND ITS FAILURE IS LOUD. A close that quietly failed would leave exactly the
|
|
433
|
+
// privileged pool this design exists to avoid, and the run would still report success.
|
|
434
|
+
await owner.close();
|
|
435
|
+
_logger.info('Migration connection closed (the application keeps its own, unprivileged)');
|
|
436
|
+
|
|
437
|
+
// ── AND THEN PROVE IT, rather than trusting that we did ────────────────────────────────
|
|
438
|
+
//
|
|
439
|
+
// Everything above is intent. This is the only line that turns it into a fact: ask the
|
|
440
|
+
// APPLICATION's driver who it actually is, now that migrations are done. If a privileged
|
|
441
|
+
// connection ever leaked into the pool the app draws from — a close that silently failed,
|
|
442
|
+
// a driver that shared a pool, a future refactor that reused the handle — every partner
|
|
443
|
+
// boundary in the schema would be off, with no error and no symptom. That is a failure
|
|
444
|
+
// you discover from a customer, so it is checked at boot instead.
|
|
445
|
+
//
|
|
446
|
+
// Deliberately AFTER the close and inside the finally: it must run even when a migration
|
|
447
|
+
// threw, because a half-applied run leaves the connection state least understood.
|
|
448
|
+
const [who] = await d.all(
|
|
449
|
+
'SELECT current_user AS role, '
|
|
450
|
+
+ '(SELECT rolbypassrls FROM pg_roles WHERE rolname = current_user) AS bypassrls');
|
|
451
|
+
if (who && who.bypassrls) {
|
|
452
|
+
throw new Error(
|
|
453
|
+
`runMigrations: after closing the migration connection the APPLICATION driver is still `
|
|
454
|
+
+ `connected as ${who.role}, which holds BYPASSRLS. Row-level security does not apply `
|
|
455
|
+
+ 'to it, so every partner boundary in this schema is inert. The application must '
|
|
456
|
+
+ 'connect as a role that owns nothing and has no BYPASSRLS (frozen spec §3); only the '
|
|
457
|
+
+ 'migration and backup roles may hold it.');
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
})();
|
|
462
|
+
|
|
463
|
+
// HOISTED, and called from the wrapper above. The body is unchanged from the version that ran
|
|
464
|
+
// on the singleton; the only difference is that the driver arrives as an argument, so the same
|
|
465
|
+
// code path serves both the ordinary case and the separate-owner case. Two copies would drift.
|
|
466
|
+
async function runMigrationsOn(md) {
|
|
467
|
+
const applied = new Set((await md.all('SELECT filename FROM migrations')).map((r) => r.filename));
|
|
395
468
|
let count = 0;
|
|
396
469
|
for (const file of files) {
|
|
397
470
|
if (applied.has(file)) continue;
|
|
@@ -402,7 +475,7 @@ function runMigrations(migrationsDir) {
|
|
|
402
475
|
if (wantsNoTransaction(sql, file)) {
|
|
403
476
|
_logger.warn(noTxWarning(file));
|
|
404
477
|
try {
|
|
405
|
-
await
|
|
478
|
+
await md.exec(sql);
|
|
406
479
|
} catch (e) {
|
|
407
480
|
// Rewrite the multi-statement failure into the instruction that fixes it — but ONLY
|
|
408
481
|
// when the file really does contain more than one statement. Gating matters: VACUUM,
|
|
@@ -422,11 +495,11 @@ function runMigrations(migrationsDir) {
|
|
|
422
495
|
// A marked file that opened a transaction and did not close it would otherwise return
|
|
423
496
|
// an "idle in transaction" client to the pool, holding its locks and snapshot for every
|
|
424
497
|
// later caller that draws it. Cheap to assert, unbounded to leave.
|
|
425
|
-
try { await
|
|
498
|
+
try { await md.exec('ROLLBACK'); } catch (_) { /* no transaction open: the normal case */ }
|
|
426
499
|
}
|
|
427
|
-
await
|
|
500
|
+
await md.run('INSERT INTO migrations (filename) VALUES (?)', [file]);
|
|
428
501
|
} else {
|
|
429
|
-
await
|
|
502
|
+
await md.transaction(async (tx) => {
|
|
430
503
|
await tx.exec(sql);
|
|
431
504
|
await tx.run('INSERT INTO migrations (filename) VALUES (?)', [file]);
|
|
432
505
|
});
|
|
@@ -434,7 +507,7 @@ function runMigrations(migrationsDir) {
|
|
|
434
507
|
if (through !== null) {
|
|
435
508
|
for (const covered of coveredBy(file, through, files)) {
|
|
436
509
|
if (applied.has(covered)) continue;
|
|
437
|
-
await
|
|
510
|
+
await md.run('INSERT INTO migrations (filename) VALUES (?)', [covered]);
|
|
438
511
|
applied.add(covered);
|
|
439
512
|
}
|
|
440
513
|
_logger.info(`Migration ${file} covers everything through ${through} — ledgered, not run`);
|
|
@@ -444,7 +517,7 @@ function runMigrations(migrationsDir) {
|
|
|
444
517
|
}
|
|
445
518
|
_logger.info(count === 0 ? 'No pending migrations' : `Applied ${count} migration(s)`);
|
|
446
519
|
return { applied: count };
|
|
447
|
-
}
|
|
520
|
+
}
|
|
448
521
|
}
|
|
449
522
|
|
|
450
523
|
/** Adopt the handle init() just opened — the driver must not open a second connection. */
|
|
@@ -498,8 +571,13 @@ function driver() {
|
|
|
498
571
|
* `initDriver({ kind: 'postgres', connectionString })` is how a Postgres-native app boots;
|
|
499
572
|
* `kind: 'sqlite'` is identical to init() but hands back the driver as well.
|
|
500
573
|
*/
|
|
501
|
-
async function ensureMigrationsTable() {
|
|
502
|
-
|
|
574
|
+
async function ensureMigrationsTable(given) {
|
|
575
|
+
// TAKES A DRIVER, because the ledger must be created by whichever role runs the migrations. It
|
|
576
|
+
// used to read the singleton unconditionally, so `migrations` was created — and therefore
|
|
577
|
+
// OWNED — by the APPLICATION role even when a separate owner role applied everything else. One
|
|
578
|
+
// table with the wrong owner is enough to reintroduce the whole problem, because an owner
|
|
579
|
+
// bypasses ENABLE ROW LEVEL SECURITY.
|
|
580
|
+
const d = given || driver();
|
|
503
581
|
const t = d.dialect;
|
|
504
582
|
// The LEDGER is the one table the framework owns, so it is the one DDL that must be
|
|
505
583
|
// dialect-aware. Everything else is the app's.
|
package/dialect.js
CHANGED
|
@@ -54,6 +54,23 @@ const sqlite = {
|
|
|
54
54
|
* for the context each engine puts it in: an identifier there, a string literal here.
|
|
55
55
|
*/
|
|
56
56
|
columns: (table) => `PRAGMA table_info(${ident(table)})`,
|
|
57
|
+
/**
|
|
58
|
+
* EVERY ORDINARY TABLE, as rows with a `name` column.
|
|
59
|
+
*
|
|
60
|
+
* Aliased to `name` on both engines exactly as columns() is, so a caller reads one shape. An app
|
|
61
|
+
* introspecting its own schema — a "what references this row" screen, a fixture builder — would
|
|
62
|
+
* otherwise branch, and `SELECT name FROM sqlite_master` is a query Postgres refuses outright.
|
|
63
|
+
* Internal tables are excluded on both: sqlite_% here, the system catalogues there.
|
|
64
|
+
*/
|
|
65
|
+
tables: () => "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",
|
|
66
|
+
/**
|
|
67
|
+
* THE FOREIGN KEYS DECLARED ON A TABLE, as rows of `{ from, table, to }`.
|
|
68
|
+
*
|
|
69
|
+
* The column names follow SQLite's PRAGMA, which is the spelling existing code already reads.
|
|
70
|
+
* Postgres reconstructs the same three facts from its constraint catalogues — a great deal more
|
|
71
|
+
* SQL for the same answer, which is precisely why it belongs here once rather than in each app.
|
|
72
|
+
*/
|
|
73
|
+
foreignKeys: (table) => `PRAGMA foreign_key_list(${ident(table)})`,
|
|
57
74
|
/**
|
|
58
75
|
* N minutes AFTER now — an expiry window.
|
|
59
76
|
*
|
|
@@ -157,6 +174,19 @@ const postgres = {
|
|
|
157
174
|
*/
|
|
158
175
|
columns: (table) => `SELECT column_name AS name FROM information_schema.columns`
|
|
159
176
|
+ ` WHERE table_schema = 'public' AND table_name = ${strLit(table)}`,
|
|
177
|
+
tables: () => "SELECT table_name AS name FROM information_schema.tables"
|
|
178
|
+
+ " WHERE table_schema = 'public' AND table_type = 'BASE TABLE'",
|
|
179
|
+
// The same three facts SQLite's PRAGMA reports, reconstructed from the constraint catalogues and
|
|
180
|
+
// aliased to the PRAGMA's own column names so a caller reads one shape on both engines.
|
|
181
|
+
foreignKeys: (table) => `SELECT kcu.column_name AS "from", ccu.table_name AS "table",`
|
|
182
|
+
+ ` ccu.column_name AS "to"`
|
|
183
|
+
+ ` FROM information_schema.table_constraints tc`
|
|
184
|
+
+ ` JOIN information_schema.key_column_usage kcu`
|
|
185
|
+
+ ` ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema`
|
|
186
|
+
+ ` JOIN information_schema.constraint_column_usage ccu`
|
|
187
|
+
+ ` ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema`
|
|
188
|
+
+ ` WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = 'public'`
|
|
189
|
+
+ ` AND tc.table_name = ${strLit(table)}`,
|
|
160
190
|
nowPlusMinutes: (n) => `to_char((NOW() + INTERVAL '${Number(n)} minutes') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
|
|
161
191
|
// date_trunc on the UTC value, not on NOW(): truncating a timestamptz uses the SESSION time
|
|
162
192
|
// zone, so 'start of month' would land on a different instant depending on where the server
|
package/index.js
CHANGED
|
@@ -33,5 +33,15 @@ module.exports = {
|
|
|
33
33
|
// 0.11.0 — the tenant-context contract. One mechanism for both apps: RLS reads its scope
|
|
34
34
|
// from transaction-local session settings, and a security boundary with two copies has one
|
|
35
35
|
// that drifts.
|
|
36
|
-
...require('./tenantContext')
|
|
36
|
+
...require('./tenantContext'),
|
|
37
|
+
// 0.19.0 — SURFACED, not new. `selectForDialect` has always been exported from database.js and
|
|
38
|
+
// used by the migration runner, but it was not on this index, so every consumer that reads
|
|
39
|
+
// migrations/ for itself invented its own filter instead. Those filters match `.postgres.sql`:
|
|
40
|
+
// one app had NINE such readers, four of which would have fed Postgres DDL to a SQLite fixture
|
|
41
|
+
// the moment a dialect sibling appeared. A helper nobody can find is a helper nobody uses.
|
|
42
|
+
selectForDialect: require('./database').selectForDialect,
|
|
43
|
+
// 0.19.0 — the tenancy migration generator. The manifest of which tables belong to a tenant is
|
|
44
|
+
// the app's; turning it into partner_id columns, composite foreign keys and RLS policies is
|
|
45
|
+
// mechanical, identical everywhere, and far too intricate to retype per app.
|
|
46
|
+
...require('./tenancyMigration')
|
|
37
47
|
};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aria-framework/db-worker",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Aria App Framework
|
|
3
|
+
"version": "0.20.0",
|
|
4
|
+
"description": "Aria App Framework \u2014 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,
|
|
7
7
|
"publishConfig": {
|
|
@@ -9,17 +9,18 @@
|
|
|
9
9
|
},
|
|
10
10
|
"main": "index.js",
|
|
11
11
|
"files": [
|
|
12
|
-
"index.js",
|
|
13
|
-
"database.js",
|
|
14
|
-
"worker.js",
|
|
15
12
|
"client.js",
|
|
16
|
-
"
|
|
17
|
-
"schemaSnapshot.js",
|
|
18
|
-
"workerRegistry.js",
|
|
19
|
-
"settingsStore.js",
|
|
13
|
+
"database.js",
|
|
20
14
|
"dialect.js",
|
|
21
15
|
"driver/",
|
|
22
|
-
"
|
|
16
|
+
"index.js",
|
|
17
|
+
"schemaSnapshot.js",
|
|
18
|
+
"settingsStore.js",
|
|
19
|
+
"tableOrder.js",
|
|
20
|
+
"tenancyMigration.js",
|
|
21
|
+
"tenantContext.js",
|
|
22
|
+
"worker.js",
|
|
23
|
+
"workerRegistry.js"
|
|
23
24
|
],
|
|
24
25
|
"peerDependencies": {
|
|
25
26
|
"better-sqlite3": ">=9",
|
|
@@ -38,6 +39,6 @@
|
|
|
38
39
|
"pg": "^8.23.0"
|
|
39
40
|
},
|
|
40
41
|
"scripts": {
|
|
41
|
-
"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/tenantRls.pg.js && node test/nestedTransaction.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/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js"
|
|
42
43
|
}
|
|
43
44
|
}
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* generateTenancyMigration — turn a tenancy manifest and a live schema into the migrations that
|
|
3
|
+
* add a tenant column, bind it structurally, and enforce it with row-level security.
|
|
4
|
+
*
|
|
5
|
+
* WHY THIS IS A PACKAGE. The DECISION — which tables belong to a tenant — is the app's, and nobody
|
|
6
|
+
* can make it for them. Everything downstream of that decision is mechanical and identical
|
|
7
|
+
* everywhere: forty tables, forty-nine foreign keys and eleven unique constraints is not a list
|
|
8
|
+
* anybody should transcribe, and a hand-written version drifts from the classification the moment
|
|
9
|
+
* either changes.
|
|
10
|
+
*
|
|
11
|
+
* THREE FILES, and the split is the whole design:
|
|
12
|
+
*
|
|
13
|
+
* <p>_partner_tenancy.sql sqlite — partners, partner_id, indexes
|
|
14
|
+
* <p>_partner_tenancy.postgres.sql postgres — the same, plus composite FKs and the widenings
|
|
15
|
+
* <r>_partner_rls.postgres.sql postgres — ENABLE + FORCE, one policy per table
|
|
16
|
+
*
|
|
17
|
+
* The two share a base name, so db-worker's dialect selection gives Postgres its own and skips the
|
|
18
|
+
* plain one. The RLS file has no plain sibling, so it exists only on Postgres.
|
|
19
|
+
*
|
|
20
|
+
* WHY THE POSTGRES HALF CARRIES EVERYTHING INTERESTING. SQLite stays SINGLE-TENANT: one partner, no
|
|
21
|
+
* policies. It still gets `partner_id`, so application code is identical on both engines — a query
|
|
22
|
+
* written once is correct on both, which is what makes the whole arrangement affordable. But the
|
|
23
|
+
* two things that only mean something with more than one tenant — composite foreign keys, and
|
|
24
|
+
* unique constraints scoped per partner — are Postgres-only, for the same reason twice: SQLite
|
|
25
|
+
* cannot alter an inline table constraint without rebuilding the table, and with one partner there
|
|
26
|
+
* is nothing for either to protect against.
|
|
27
|
+
*
|
|
28
|
+
* THE MANIFEST this expects (the app's own module):
|
|
29
|
+
* scoped() -> [{ table, nullable }] every tenant-scoped table
|
|
30
|
+
* WIDEN_UNIQUE -> [{ table, columns, index?, where?, primaryKey?, nullsNotDistinct? }]
|
|
31
|
+
* POLICY_EXPRESSION -> the RLS predicate, used verbatim for USING and WITH CHECK
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
'use strict';
|
|
35
|
+
|
|
36
|
+
const NOW = (d) => (d === 'postgres'
|
|
37
|
+
? "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD HH24:MI:SS')"
|
|
38
|
+
: "(datetime('now'))");
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {{
|
|
42
|
+
* manifest: object, the app's tenancy manifest (see above)
|
|
43
|
+
* dbPath: string, a SQLite database carrying the current schema
|
|
44
|
+
* Database: Function, better-sqlite3's constructor, injected
|
|
45
|
+
* prefix?: string, migration number for the tenancy pair; default '036'
|
|
46
|
+
* rlsPrefix?: string, migration number for the RLS file; default '037'
|
|
47
|
+
* generatedBy?: string, named in every header so nobody hand-edits the output
|
|
48
|
+
* housePartnerName?: string default 'House'
|
|
49
|
+
* }} opts
|
|
50
|
+
* @returns {{files: Object<string,string>, stats: {tables:number, compositeFks:number, widened:number}}}
|
|
51
|
+
*/
|
|
52
|
+
function generateTenancyMigration(opts = {}) {
|
|
53
|
+
const { manifest, dbPath, Database } = opts;
|
|
54
|
+
if (!manifest || !dbPath || typeof Database !== 'function') {
|
|
55
|
+
throw new Error('generateTenancyMigration({ manifest, dbPath, Database }): all three are required');
|
|
56
|
+
}
|
|
57
|
+
const prefix = opts.prefix || '036';
|
|
58
|
+
const rlsPrefix = opts.rlsPrefix || '037';
|
|
59
|
+
const generatedBy = opts.generatedBy || '@aria-framework/db-worker generateTenancyMigration';
|
|
60
|
+
const houseName = opts.housePartnerName || 'House';
|
|
61
|
+
// SEEDED BY THE MIGRATION, OR BY THE APP AT BOOT — and which is right depends on whether this is
|
|
62
|
+
// a RETROFIT. Retrofitting a populated database backfills every existing row to partner 1, so
|
|
63
|
+
// that row has to exist during the migration. A fresh installation has nothing to backfill, and
|
|
64
|
+
// a schema that seeds a row is a row every future app inherits without choosing it.
|
|
65
|
+
const seedHouse = opts.seedHousePartner !== false;
|
|
66
|
+
|
|
67
|
+
const db = new Database(dbPath, { readonly: true });
|
|
68
|
+
try {
|
|
69
|
+
const scoped = manifest.scoped();
|
|
70
|
+
const scopedNames = new Set(scoped.map((s) => s.table));
|
|
71
|
+
const ordered = [...scoped].sort((a, b) => a.table.localeCompare(b.table));
|
|
72
|
+
|
|
73
|
+
/** Foreign keys from one tenant-scoped table to another. These become composite. */
|
|
74
|
+
const tenantFks = (table) => db.prepare(`PRAGMA foreign_key_list("${table}")`).all()
|
|
75
|
+
.filter((f) => scopedNames.has(f.table))
|
|
76
|
+
.map((f) => ({ from: f.from, table: f.table, to: f.to || 'id', onDelete: f.on_delete }))
|
|
77
|
+
// PRAGMA lists newest first; sorting keeps a regenerated file diff-free.
|
|
78
|
+
.sort((a, b) => (a.from + a.table).localeCompare(b.from + b.table));
|
|
79
|
+
|
|
80
|
+
// ── shared structure ──────────────────────────────────────────────────────────────────────
|
|
81
|
+
|
|
82
|
+
function partnersTable(dialect) {
|
|
83
|
+
// BIGINT on Postgres wherever an integer appears, because that is what a SQLite→Postgres
|
|
84
|
+
// schema translation maps SQLite's INTEGER to — and SQLite's INTEGER really is 64-bit. The
|
|
85
|
+
// two routes have to agree, or the column's type depends on which one built the schema.
|
|
86
|
+
// SQLite keeps INTEGER for the primary key: INTEGER PRIMARY KEY is the rowid alias there,
|
|
87
|
+
// and BIGINT would silently make it an ordinary column.
|
|
88
|
+
const pk = dialect === 'postgres'
|
|
89
|
+
? 'BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY'
|
|
90
|
+
: 'INTEGER PRIMARY KEY AUTOINCREMENT';
|
|
91
|
+
const int = dialect === 'postgres' ? 'BIGINT' : 'INTEGER';
|
|
92
|
+
return [
|
|
93
|
+
'-- The tenant. One row per partner; the platform\'s own is flagged is_house.',
|
|
94
|
+
'CREATE TABLE partners (',
|
|
95
|
+
` id ${pk},`,
|
|
96
|
+
' name TEXT NOT NULL,',
|
|
97
|
+
' -- An external system may address partners by a reference it owns.',
|
|
98
|
+
' external_ref TEXT,',
|
|
99
|
+
' -- The platform\'s own partner. Platform-scoped users may only belong to this one.',
|
|
100
|
+
` is_house ${int} NOT NULL DEFAULT 0,`,
|
|
101
|
+
` created_at TEXT NOT NULL DEFAULT ${NOW(dialect)}`,
|
|
102
|
+
');',
|
|
103
|
+
'',
|
|
104
|
+
'-- At most one house partner.',
|
|
105
|
+
'CREATE UNIQUE INDEX idx_partners_one_house ON partners(is_house) WHERE is_house = 1;',
|
|
106
|
+
'CREATE UNIQUE INDEX idx_partners_external_ref ON partners(external_ref) WHERE external_ref IS NOT NULL;',
|
|
107
|
+
'',
|
|
108
|
+
...(seedHouse ? [
|
|
109
|
+
'-- Everything that exists today belongs to the house: one installation, one tenant, until',
|
|
110
|
+
'-- a second partner is created. SEEDED HERE because this migration is a RETROFIT onto a',
|
|
111
|
+
'-- database that already has rows: they are backfilled to partner 1, which therefore has',
|
|
112
|
+
'-- to exist by the time the backfill runs.',
|
|
113
|
+
`INSERT INTO partners (id, name, is_house) VALUES (1, '${houseName}', 1);`,
|
|
114
|
+
''
|
|
115
|
+
] : [
|
|
116
|
+
'-- THE HOUSE PARTNER IS NOT SEEDED HERE. On a fresh installation there are no rows to',
|
|
117
|
+
'-- backfill, so nothing needs it to exist during the migration — and a schema that seeds',
|
|
118
|
+
'-- a row is a row every future app inherits without choosing it. It is created from CODE',
|
|
119
|
+
'-- at boot instead, beside the other idempotent seeds, where an app can change it without',
|
|
120
|
+
'-- a migration.',
|
|
121
|
+
''
|
|
122
|
+
]),
|
|
123
|
+
'-- The RLS scope, read by the policy through app.scope. platform sees every tenant.',
|
|
124
|
+
'--',
|
|
125
|
+
'-- THE HOUSE-ONLY RULE IS NOT A CHECK CONSTRAINT. "scope_kind may be platform only for a',
|
|
126
|
+
'-- user of the house partner" has to consult another table, which a CHECK cannot do on',
|
|
127
|
+
'-- either engine. It is enforced in the application and by a test; recording the limitation',
|
|
128
|
+
'-- here beats leaving somebody to assume the database is holding it.',
|
|
129
|
+
"ALTER TABLE users ADD COLUMN scope_kind TEXT NOT NULL DEFAULT 'partner';"
|
|
130
|
+
].join('\n');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function partnerIdColumns(dialect) {
|
|
134
|
+
const out = [];
|
|
135
|
+
// TWO STEPS ON POSTGRES, AND THE FIRST ATTEMPT AT ONE STEP IS WHY.
|
|
136
|
+
//
|
|
137
|
+
// The eventual default reads the session scope, so no model ever has to set partner_id. But
|
|
138
|
+
// a migration runs with no scope established, so that expression evaluates to NULL — and
|
|
139
|
+
// adding a NOT NULL column whose default is NULL fails immediately on any table that already
|
|
140
|
+
// has rows: `column "partner_id" of relation "x" contains null values`.
|
|
141
|
+
//
|
|
142
|
+
// So the column arrives with the house partner as its default, which backfills every
|
|
143
|
+
// existing row, and the default is only then switched to the session scope for everything
|
|
144
|
+
// written afterwards.
|
|
145
|
+
const intType = dialect === 'postgres' ? 'BIGINT' : 'INTEGER';
|
|
146
|
+
for (const { table, nullable } of ordered) {
|
|
147
|
+
out.push(`ALTER TABLE ${table} ADD COLUMN partner_id ${intType}${nullable ? '' : ' NOT NULL'} DEFAULT 1;`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (dialect === 'postgres') {
|
|
151
|
+
out.push('');
|
|
152
|
+
out.push('-- Now the session scope supplies it. A platform user acting FOR a partner has to');
|
|
153
|
+
out.push('-- establish that scope first, which is the intent rather than a limitation.');
|
|
154
|
+
for (const { table } of ordered) {
|
|
155
|
+
// NULLIF, and it earns its place. A platform scope with no partner sends an EMPTY
|
|
156
|
+
// STRING, so a bare `current_setting(…)::int` fails with `invalid input syntax for type
|
|
157
|
+
// integer: ""` — a message naming a cast rather than the missing tenant, raised from
|
|
158
|
+
// inside whatever store happened to insert first. With NULLIF the value is NULL and the
|
|
159
|
+
// NOT NULL constraint refuses it by name: the same refusal, saying what it means.
|
|
160
|
+
out.push(`ALTER TABLE ${table} ALTER COLUMN partner_id SET DEFAULT NULLIF(current_setting('app.partner_id', true), '')::int;`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
out.push('');
|
|
165
|
+
for (const { table } of ordered) {
|
|
166
|
+
out.push(`CREATE INDEX idx_${table}_partner ON ${table}(partner_id);`);
|
|
167
|
+
}
|
|
168
|
+
return out.join('\n');
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ── postgres-only pieces ──────────────────────────────────────────────────────────────────
|
|
172
|
+
|
|
173
|
+
/** The unique keys the composite foreign keys point at, derived from the keys themselves. */
|
|
174
|
+
function uniqueTargets() {
|
|
175
|
+
const targets = new Map();
|
|
176
|
+
for (const { table } of ordered) {
|
|
177
|
+
for (const fk of tenantFks(table)) targets.set(`${fk.table}.${fk.to}`, { table: fk.table, column: fk.to });
|
|
178
|
+
}
|
|
179
|
+
const out = [
|
|
180
|
+
'-- What the composite foreign keys below point AT. The referenced column is already unique,',
|
|
181
|
+
'-- which makes (column, partner_id) unique as well — Postgres still requires it to be',
|
|
182
|
+
'-- declared before anything may reference it. Collected from the foreign keys rather than',
|
|
183
|
+
'-- assumed: not every scoped table has an id column at all.'
|
|
184
|
+
];
|
|
185
|
+
for (const t of [...targets.values()].sort((a, b) => (a.table + a.column).localeCompare(b.table + b.column))) {
|
|
186
|
+
out.push(`ALTER TABLE ${t.table} ADD CONSTRAINT uq_${t.table}_${t.column}_partner UNIQUE (${t.column}, partner_id);`);
|
|
187
|
+
}
|
|
188
|
+
return out.join('\n');
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function compositeFks() {
|
|
192
|
+
const out = [
|
|
193
|
+
'-- THE POINT OF THE WHOLE ARRANGEMENT. A denormalised partner_id that disagrees with its',
|
|
194
|
+
'-- parent becomes impossible to WRITE rather than merely discouraged: the row it points at',
|
|
195
|
+
'-- has to belong to the same partner.'
|
|
196
|
+
];
|
|
197
|
+
let n = 0;
|
|
198
|
+
for (const { table } of ordered) {
|
|
199
|
+
for (const fk of tenantFks(table)) {
|
|
200
|
+
const del = fk.onDelete && fk.onDelete !== 'NO ACTION' ? ` ON DELETE ${fk.onDelete}` : '';
|
|
201
|
+
out.push(
|
|
202
|
+
`ALTER TABLE ${table} ADD CONSTRAINT fk_${table}_${fk.from}_partner`
|
|
203
|
+
+ ` FOREIGN KEY (${fk.from}, partner_id)`
|
|
204
|
+
+ ` REFERENCES ${fk.table} (${fk.to}, partner_id)${del};`);
|
|
205
|
+
n++;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return { sql: out.join('\n'), count: n };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Unique constraints that must become per-partner. */
|
|
212
|
+
function widenUniques() {
|
|
213
|
+
const widen = manifest.WIDEN_UNIQUE || [];
|
|
214
|
+
const out = [
|
|
215
|
+
'-- WITHOUT THESE THE SCHEMA REFUSES A SECOND TENANT. A global UNIQUE on users.username means',
|
|
216
|
+
'-- two partners cannot both have a user called admin; likewise a role name, a default team,',
|
|
217
|
+
'-- a settings key. Everything NOT here stays global deliberately.',
|
|
218
|
+
'--',
|
|
219
|
+
'-- WATCH FOR A PARTIAL UNIQUE INDEX ON A BOOLEAN (`... WHERE is_default`). That means ONE ROW',
|
|
220
|
+
'-- PER DATABASE: the first partner to set a default locks every other partner out, with an',
|
|
221
|
+
'-- opaque constraint violation at INSERT. Sweep for the shape, not for the word UNIQUE.'
|
|
222
|
+
];
|
|
223
|
+
for (const w of widen) {
|
|
224
|
+
const cols = ['partner_id', ...w.columns].join(', ');
|
|
225
|
+
if (w.index) {
|
|
226
|
+
out.push(`DROP INDEX ${w.index};`);
|
|
227
|
+
out.push(`CREATE UNIQUE INDEX ${w.index} ON ${w.table} (${cols})`
|
|
228
|
+
+ (w.where ? ` WHERE ${w.where}` : '') + ';');
|
|
229
|
+
} else {
|
|
230
|
+
// Postgres names an inline constraint <table>_<column>_key, or <table>_pkey for a
|
|
231
|
+
// primary key. IF EXISTS keeps this idempotent whichever it turns out to be.
|
|
232
|
+
const guessed = w.primaryKey ? `${w.table}_pkey` : `${w.table}_${w.columns[0]}_key`;
|
|
233
|
+
const nulls = w.nullsNotDistinct ? ' NULLS NOT DISTINCT' : '';
|
|
234
|
+
const suffix = w.columns[0].replace(/\W/g, '');
|
|
235
|
+
out.push(`ALTER TABLE ${w.table} DROP CONSTRAINT IF EXISTS ${guessed};`);
|
|
236
|
+
out.push(`ALTER TABLE ${w.table} ADD CONSTRAINT uq_${w.table}_partner_${suffix} UNIQUE${nulls} (${cols});`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return out.join('\n');
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ── the files ─────────────────────────────────────────────────────────────────────────────
|
|
243
|
+
|
|
244
|
+
const fks = compositeFks();
|
|
245
|
+
const widenCount = (manifest.WIDEN_UNIQUE || []).length;
|
|
246
|
+
|
|
247
|
+
const sqliteFile = [
|
|
248
|
+
`-- ${prefix}_partner_tenancy.sql — GENERATED by ${generatedBy}`,
|
|
249
|
+
'--',
|
|
250
|
+
'-- SQLite is SINGLE-TENANT and stays that way: one partner, no policies. It still gets',
|
|
251
|
+
'-- partner_id so the application code is identical on both engines — a query written once is',
|
|
252
|
+
'-- correct on both.',
|
|
253
|
+
'--',
|
|
254
|
+
'-- The composite foreign keys and the per-partner unique constraints live in the .postgres.sql',
|
|
255
|
+
'-- sibling, and their absence here is deliberate twice over: SQLite cannot alter an inline',
|
|
256
|
+
'-- table constraint without rebuilding the table, and with one partner there is no wrong',
|
|
257
|
+
'-- partner_id to prevent and nothing to disambiguate.',
|
|
258
|
+
'',
|
|
259
|
+
partnersTable('sqlite'),
|
|
260
|
+
'',
|
|
261
|
+
partnerIdColumns('sqlite'),
|
|
262
|
+
''
|
|
263
|
+
].join('\n');
|
|
264
|
+
|
|
265
|
+
const postgresFile = [
|
|
266
|
+
`-- ${prefix}_partner_tenancy.postgres.sql — GENERATED by ${generatedBy}`,
|
|
267
|
+
'--',
|
|
268
|
+
'-- The Postgres half. The same columns as the sqlite sibling, plus the three things that only',
|
|
269
|
+
'-- mean something with more than one tenant: a partner_id that DEFAULTS FROM THE SESSION',
|
|
270
|
+
`-- SCOPE, ${fks.count} composite foreign keys, and ${widenCount} unique constraints scoped per partner.`,
|
|
271
|
+
'--',
|
|
272
|
+
'-- The default is why no model sets partner_id. A platform user acting for a particular',
|
|
273
|
+
'-- partner has to establish that scope first, which is the intent rather than a limitation.',
|
|
274
|
+
'',
|
|
275
|
+
partnersTable('postgres'),
|
|
276
|
+
'',
|
|
277
|
+
'-- partners is not itself tenant-scoped: it IS the tenant list, and a partner nobody could',
|
|
278
|
+
'-- see could not be joined to.',
|
|
279
|
+
partnerIdColumns('postgres'),
|
|
280
|
+
'',
|
|
281
|
+
uniqueTargets(),
|
|
282
|
+
'',
|
|
283
|
+
fks.sql,
|
|
284
|
+
'',
|
|
285
|
+
widenUniques(),
|
|
286
|
+
'',
|
|
287
|
+
'-- The identity sequence starts after the house partner.',
|
|
288
|
+
"SELECT setval(pg_get_serial_sequence('partners', 'id'), 1, true);",
|
|
289
|
+
''
|
|
290
|
+
].join('\n');
|
|
291
|
+
|
|
292
|
+
const expr = String(manifest.POLICY_EXPRESSION || '').trim();
|
|
293
|
+
const body = [];
|
|
294
|
+
for (const { table } of ordered) {
|
|
295
|
+
body.push(`ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;`);
|
|
296
|
+
body.push(`ALTER TABLE ${table} FORCE ROW LEVEL SECURITY;`);
|
|
297
|
+
body.push(`CREATE POLICY tenant_isolation ON ${table} FOR ALL`);
|
|
298
|
+
body.push(` USING (${expr})`);
|
|
299
|
+
body.push(` WITH CHECK (${expr});`);
|
|
300
|
+
body.push('');
|
|
301
|
+
}
|
|
302
|
+
const rlsFile = [
|
|
303
|
+
`-- ${rlsPrefix}_partner_rls.postgres.sql — GENERATED by ${generatedBy}`,
|
|
304
|
+
'--',
|
|
305
|
+
'-- Row-level security, Postgres only. No plain sibling exists, so this file runs nowhere else.',
|
|
306
|
+
'--',
|
|
307
|
+
'-- BOTH HALVES, ALWAYS. USING scopes what a caller can SEE; WITH CHECK scopes what it can',
|
|
308
|
+
'-- LEAVE BEHIND. With only the first, a partner reads their own rows and can still write into',
|
|
309
|
+
'-- somebody else.',
|
|
310
|
+
'--',
|
|
311
|
+
'-- FORCE matters as much as ENABLE: without it the table OWNER bypasses every policy, and',
|
|
312
|
+
'-- migrations run as the owner. A superuser bypasses regardless, which is why the application',
|
|
313
|
+
'-- must connect as a non-owner, non-superuser role — a deployment step, not a migration.',
|
|
314
|
+
'--',
|
|
315
|
+
`-- The expression is the manifest's POLICY_EXPRESSION, verbatim, for all ${ordered.length} tables.`,
|
|
316
|
+
'',
|
|
317
|
+
body.join('\n')
|
|
318
|
+
].join('\n');
|
|
319
|
+
|
|
320
|
+
return {
|
|
321
|
+
files: {
|
|
322
|
+
[`${prefix}_partner_tenancy.sql`]: sqliteFile,
|
|
323
|
+
[`${prefix}_partner_tenancy.postgres.sql`]: postgresFile,
|
|
324
|
+
[`${rlsPrefix}_partner_rls.postgres.sql`]: rlsFile
|
|
325
|
+
},
|
|
326
|
+
stats: { tables: ordered.length, compositeFks: fks.count, widened: widenCount }
|
|
327
|
+
};
|
|
328
|
+
} finally {
|
|
329
|
+
try { db.close(); } catch (_) { /* best effort */ }
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
module.exports = { generateTenancyMigration };
|