@aria-framework/db-worker 0.16.0 → 0.19.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/dialect.js +70 -1
- package/index.js +11 -1
- package/package.json +44 -43
- package/settingsStore.js +20 -1
- package/tenancyMigration.js +333 -0
package/dialect.js
CHANGED
|
@@ -36,6 +36,11 @@ const sqlite = {
|
|
|
36
36
|
now: () => "datetime('now')",
|
|
37
37
|
/** N whole days before now — used by retention cuts. */
|
|
38
38
|
nowMinusDays: (n) => `datetime('now', '-${Number(n)} days')`,
|
|
39
|
+
/**
|
|
40
|
+
* Seconds, because some windows are short and expressing them as a fraction of a minute is a
|
|
41
|
+
* rounding error waiting to be argued about. api-auth's key-touch throttle is the caller.
|
|
42
|
+
*/
|
|
43
|
+
nowMinusSeconds: (n) => `datetime('now', '-${Number(n)} seconds')`,
|
|
39
44
|
/**
|
|
40
45
|
* WHICH COLUMNS A TABLE HAS, as SQL returning rows with a `name` column.
|
|
41
46
|
*
|
|
@@ -49,6 +54,23 @@ const sqlite = {
|
|
|
49
54
|
* for the context each engine puts it in: an identifier there, a string literal here.
|
|
50
55
|
*/
|
|
51
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)})`,
|
|
52
74
|
/**
|
|
53
75
|
* N minutes AFTER now — an expiry window.
|
|
54
76
|
*
|
|
@@ -81,7 +103,21 @@ const sqlite = {
|
|
|
81
103
|
*
|
|
82
104
|
* Raw and unrounded on purpose: every caller wraps it in AVG or SUM and multiplies to the
|
|
83
105
|
* unit it wants (x24 for hours, x1440 for minutes). A helper that rounded would not compose.
|
|
84
|
-
*
|
|
106
|
+
*
|
|
107
|
+
* NEVER PASS THE LITERAL 'now'. This used to say "either side may be the literal 'now', which
|
|
108
|
+
* both engines understand" — true, and wrong, which is the worst kind of doc. Both engines
|
|
109
|
+
* PARSE it and they mean different instants:
|
|
110
|
+
*
|
|
111
|
+
* sqlite julianday('now') UTC, always
|
|
112
|
+
* postgres 'now'::timestamp the SESSION's time zone
|
|
113
|
+
*
|
|
114
|
+
* Every timestamp this framework writes is UTC text (see now() above), so on a server whose
|
|
115
|
+
* session time zone is not UTC the subtraction is off by exactly the offset. Support101 met it
|
|
116
|
+
* on an America/Chicago server: stopping a timer computed elapsed minutes 300 SHORT, negative
|
|
117
|
+
* for anything under five hours, and the caller's own MAX(1, …) floor turned that into a
|
|
118
|
+
* plausible "1 minute" instead of an obvious absurdity. Billable data, quietly wrong.
|
|
119
|
+
*
|
|
120
|
+
* Pass now() instead, so both sides are in the same frame. Two stored COLUMNS are always safe.
|
|
85
121
|
*/
|
|
86
122
|
daysBetween: (from, to) => `(julianday(${to}) - julianday(${from}))`,
|
|
87
123
|
/** Read a JSON path out of a column: jsonPath('detail', '$.model'). */
|
|
@@ -92,6 +128,19 @@ const sqlite = {
|
|
|
92
128
|
// `role LIKE 'read_only'` also matches 'read-only' because `_` is a single-character wildcard,
|
|
93
129
|
// and a value of '%' matches everything. Equality has to be spelled as equality.
|
|
94
130
|
ciEquals: (col, param) => `LOWER(${col}) = LOWER(${param})`,
|
|
131
|
+
/**
|
|
132
|
+
* The larger / smaller of two VALUES — the scalar, not the aggregate.
|
|
133
|
+
*
|
|
134
|
+
* SQLite's MAX is two functions wearing one name: an aggregate with one argument, a scalar with
|
|
135
|
+
* two. Postgres has only the aggregate and spells the scalar GREATEST, so `MAX(1, x)` there is
|
|
136
|
+
* not a wrong answer — it is `function max(integer, integer) does not exist`.
|
|
137
|
+
*
|
|
138
|
+
* Named here rather than solved in each app: Support101 hit it in two places, both on paths
|
|
139
|
+
* nothing routine exercises (stopping a timer; requeueing a refused job), and an app that fixes
|
|
140
|
+
* it locally leaves every other consumer to rediscover the same thing.
|
|
141
|
+
*/
|
|
142
|
+
greatest: (a, b) => `MAX(${a}, ${b})`,
|
|
143
|
+
least: (a, b) => `MIN(${a}, ${b})`,
|
|
95
144
|
/** Suffix that makes run() report a new row's id. SQLite reports it out of band. */
|
|
96
145
|
returning: () => '',
|
|
97
146
|
/** DDL fragment for an auto-incrementing primary key (only secure-keystore needs this). */
|
|
@@ -110,6 +159,7 @@ const postgres = {
|
|
|
110
159
|
// for both; an app wanting a real timestamptz column in its OWN tables uses nowTz().
|
|
111
160
|
now: () => "to_char(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')",
|
|
112
161
|
nowMinusDays: (n) => `to_char((NOW() - INTERVAL '${Number(n)} days') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
|
|
162
|
+
nowMinusSeconds: (n) => `to_char((NOW() - INTERVAL '${Number(n)} seconds') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
|
|
113
163
|
/**
|
|
114
164
|
* WHICH COLUMNS A TABLE HAS, as SQL returning rows with a `name` column.
|
|
115
165
|
*
|
|
@@ -124,6 +174,19 @@ const postgres = {
|
|
|
124
174
|
*/
|
|
125
175
|
columns: (table) => `SELECT column_name AS name FROM information_schema.columns`
|
|
126
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)}`,
|
|
127
190
|
nowPlusMinutes: (n) => `to_char((NOW() + INTERVAL '${Number(n)} minutes') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
|
|
128
191
|
// date_trunc on the UTC value, not on NOW(): truncating a timestamptz uses the SESSION time
|
|
129
192
|
// zone, so 'start of month' would land on a different instant depending on where the server
|
|
@@ -144,6 +207,9 @@ const postgres = {
|
|
|
144
207
|
if (unit === 'week') return `to_char(${col}::timestamp, 'IYYY-"W"IW')`;
|
|
145
208
|
throw new Error(`dateGroup: expected 'month' or 'week', got ${JSON.stringify(unit)}`);
|
|
146
209
|
},
|
|
210
|
+
// NEVER PASS THE LITERAL 'now' — see the sqlite twin. `'now'::timestamp` is resolved in the
|
|
211
|
+
// SESSION's time zone, and everything this framework stores is UTC text, so the subtraction is
|
|
212
|
+
// silently off by the server's offset. Pass now().
|
|
147
213
|
daysBetween: (from, to) =>
|
|
148
214
|
`(EXTRACT(EPOCH FROM (${to}::timestamp - ${from}::timestamp)) / 86400)`,
|
|
149
215
|
/** Native timestamptz, for an app that declares real timestamp columns. */
|
|
@@ -162,6 +228,9 @@ const postgres = {
|
|
|
162
228
|
},
|
|
163
229
|
ilike: () => 'ILIKE',
|
|
164
230
|
ciEquals: (col, param) => `LOWER(${col}) = LOWER(${param})`,
|
|
231
|
+
// The scalar, not the aggregate — see the sqlite twin for why this needs naming at all.
|
|
232
|
+
greatest: (a, b) => `GREATEST(${a}, ${b})`,
|
|
233
|
+
least: (a, b) => `LEAST(${a}, ${b})`,
|
|
165
234
|
returning: (col = 'id') => ` RETURNING ${ident(col)}`,
|
|
166
235
|
autoIncrementPk: () => 'BIGSERIAL PRIMARY KEY',
|
|
167
236
|
textType: () => 'TEXT'
|
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,43 +1,44 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@aria-framework/db-worker",
|
|
3
|
-
"version": "0.
|
|
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
|
-
"license": "UNLICENSED",
|
|
6
|
-
"private": false,
|
|
7
|
-
"publishConfig": {
|
|
8
|
-
"access": "public"
|
|
9
|
-
},
|
|
10
|
-
"main": "index.js",
|
|
11
|
-
"files": [
|
|
12
|
-
"
|
|
13
|
-
"database.js",
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
"
|
|
17
|
-
"schemaSnapshot.js",
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
"
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
"
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@aria-framework/db-worker",
|
|
3
|
+
"version": "0.19.0",
|
|
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
|
+
"license": "UNLICENSED",
|
|
6
|
+
"private": false,
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
10
|
+
"main": "index.js",
|
|
11
|
+
"files": [
|
|
12
|
+
"client.js",
|
|
13
|
+
"database.js",
|
|
14
|
+
"dialect.js",
|
|
15
|
+
"driver/",
|
|
16
|
+
"index.js",
|
|
17
|
+
"schemaSnapshot.js",
|
|
18
|
+
"settingsStore.js",
|
|
19
|
+
"tableOrder.js",
|
|
20
|
+
"tenancyMigration.js",
|
|
21
|
+
"tenantContext.js",
|
|
22
|
+
"worker.js",
|
|
23
|
+
"workerRegistry.js"
|
|
24
|
+
],
|
|
25
|
+
"peerDependencies": {
|
|
26
|
+
"better-sqlite3": ">=9",
|
|
27
|
+
"pg": ">=8"
|
|
28
|
+
},
|
|
29
|
+
"peerDependenciesMeta": {
|
|
30
|
+
"better-sqlite3": {
|
|
31
|
+
"optional": true
|
|
32
|
+
},
|
|
33
|
+
"pg": {
|
|
34
|
+
"optional": true
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"better-sqlite3": "^12.10.0",
|
|
39
|
+
"pg": "^8.23.0"
|
|
40
|
+
},
|
|
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/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/smoke.js && node test/tier2.js"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/settingsStore.js
CHANGED
|
@@ -30,6 +30,20 @@ const { createSqliteDriver } = require('./driver/sqlite');
|
|
|
30
30
|
* getDb LEGACY: a function returning a better-sqlite3 handle, adopted into a driver here
|
|
31
31
|
* table defaults to 'settings'
|
|
32
32
|
* touchUpdatedAt: set true when the table carries an updated_at column to stamp on write.
|
|
33
|
+
* conflictTarget: the column list the upsert conflicts on, defaulting to 'key'.
|
|
34
|
+
*
|
|
35
|
+
* WHY conflictTarget EXISTS. An upsert's conflict target must match a real unique constraint, and
|
|
36
|
+
* a MULTI-TENANT settings table is not unique on `key` — two partners each need their own
|
|
37
|
+
* `brand_name`, so the constraint becomes `(partner_id, key)`. `ON CONFLICT(key)` against that is
|
|
38
|
+
* not a wrong answer; Postgres refuses the statement outright with "there is no unique or
|
|
39
|
+
* exclusion constraint matching the ON CONFLICT specification".
|
|
40
|
+
*
|
|
41
|
+
* Support101 met this after its tenancy migration: reads worked, and EVERY WRITE failed — brand
|
|
42
|
+
* name, timezone, session timeout, AI ceilings, audit retention. It stayed hidden through a full
|
|
43
|
+
* Postgres test pass because nothing in that pass CHANGED a setting; the first person to edit one
|
|
44
|
+
* in the admin UI found it immediately.
|
|
45
|
+
*
|
|
46
|
+
* Defaults to 'key', so every existing consumer is unaffected.
|
|
33
47
|
*/
|
|
34
48
|
function createSettingsStore(opts = {}) {
|
|
35
49
|
let driver = opts.driver || null;
|
|
@@ -114,8 +128,13 @@ function createSettingsStore(opts = {}) {
|
|
|
114
128
|
const touch = opts.touchUpdatedAt ? `, updated_at = ${now()}` : '';
|
|
115
129
|
const insertCols = opts.touchUpdatedAt ? '(key, value, updated_at)' : '(key, value)';
|
|
116
130
|
const insertVals = opts.touchUpdatedAt ? `(?, ?, ${now()})` : '(?, ?)';
|
|
131
|
+
// The INSERT still names only key/value: a tenant column is supplied by its own DEFAULT
|
|
132
|
+
// (`current_setting('app.partner_id')` under RLS), so the row lands on the right tenant
|
|
133
|
+
// without this store knowing that tenants exist. Only the CONFLICT TARGET has to agree with
|
|
134
|
+
// the constraint the app actually built.
|
|
135
|
+
const conflict = opts.conflictTarget || 'key';
|
|
117
136
|
return `INSERT INTO ${table} ${insertCols} VALUES ${insertVals}
|
|
118
|
-
ON CONFLICT(
|
|
137
|
+
ON CONFLICT(${conflict}) DO UPDATE SET value = excluded.value${touch}`;
|
|
119
138
|
}
|
|
120
139
|
}
|
|
121
140
|
|
|
@@ -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 };
|