@aria-framework/db-worker 0.28.0 → 0.29.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 +257 -0
- package/bin/tenancy.js +97 -0
- package/client.js +26 -1
- package/database.js +54 -0
- package/index.js +10 -2
- package/package.json +11 -2
- package/sql.js +395 -0
- package/tenancyGenerator.js +964 -0
- package/tenancyManifest.js +115 -0
- package/tenantScope.js +120 -0
- package/tenantSettings.js +301 -0
|
@@ -0,0 +1,964 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 0.29.0 — THE TENANCY OF A NEW TABLE, generated from the app's manifest, never typed. The library half of the
|
|
3
|
+
* `aria-tenancy` command (bin/tenancy.js); moved from an app's own new-table generator and made generic.
|
|
4
|
+
*
|
|
5
|
+
* aria-tenancy new <table...> [--name <slug>] [--number <NNN>]
|
|
6
|
+
* writes a NEW migration pair, <migrations>/<NNN>_<slug>.sql + .postgres.sql: a CREATE TABLE skeleton per table
|
|
7
|
+
* carrying the generated tenancy, and the generated row-level-security section. Add the table's own columns
|
|
8
|
+
* and keys where marked. NNN defaults to the next free number, slug to the first table. Refuses a file or a
|
|
9
|
+
* number that exists: an applied migration is never rewritten (the runner's ledger is keyed by file name).
|
|
10
|
+
* aria-tenancy new --print <table...>
|
|
11
|
+
* prints the generated statements for both dialects; writes nothing.
|
|
12
|
+
* aria-tenancy check
|
|
13
|
+
* exit 1 unless every scoped table created after the app's frozen migrations carries EXACTLY the generator's
|
|
14
|
+
* statements, and every key in those migrations keeps the tenant columns intact. Read-only.
|
|
15
|
+
*
|
|
16
|
+
* WHAT THE APP PASSES: `aria.tenancy.json` beside its package.json (loadConfig below) — where its manifest is (built with
|
|
17
|
+
* defineTenancy), its migrations folder, its frozen file list, its principal table. Nothing else of the app is loaded,
|
|
18
|
+
* and no database is opened: everything is rendered from the manifest and read from the files.
|
|
19
|
+
*
|
|
20
|
+
* ── WHY GENERATED ────────────────────────────────────────────────────────────────────────────────────────────────
|
|
21
|
+
* On a composite key a bare ON DELETE SET NULL also nulls partner_id (NOT NULL), and SET DEFAULT silently re-parents
|
|
22
|
+
* the row into another tenant. A table typed by hand with its policy "rendered" by eye is a table every partner can
|
|
23
|
+
* read the day one character is wrong. The older generator (tenancyMigration.js) adds tenancy by ALTER over a SQLite
|
|
24
|
+
* snapshot; this one declares it INLINE: partner_id in the CREATE TABLE, the partner index after it, ENABLE + FORCE +
|
|
25
|
+
* the policy at the end of the same file, a plain-SQLite twin beside it (one tenant there, no policies).
|
|
26
|
+
*
|
|
27
|
+
* ── WHAT IS GENERATED — AND HELD BY check — PER TABLE ───────────────────────────────────────────────────────────
|
|
28
|
+
* Decided by the manifest alone (PARTNER, and an optional CUSTOMER map with its CUSTOMER_POLICY_EXPRESSION):
|
|
29
|
+
* Postgres the partner_id column definition, inside the CREATE TABLE — compared WHITESPACE-NORMALISED, the one
|
|
30
|
+
* comparison that is not byte for byte (a hand-typed migration may wrap it; same tokens);
|
|
31
|
+
* and, byte for byte as whole statements (CRLF read as LF):
|
|
32
|
+
* CREATE INDEX idx_<t>_partner ON <t>(partner_id);
|
|
33
|
+
* ALTER TABLE <t> ENABLE ROW LEVEL SECURITY;
|
|
34
|
+
* ALTER TABLE <t> FORCE ROW LEVEL SECURITY;
|
|
35
|
+
* CREATE POLICY tenant_isolation ON <t> FOR ALL USING (…) WITH CHECK (…);
|
|
36
|
+
* The policy text is TENANCY_POLICY_EXPRESSION (tenancyManifest.js), never a copy held here; a CUSTOMER
|
|
37
|
+
* table's is the manifest's own CUSTOMER_POLICY_EXPRESSION(column) until the customer tier moves here.
|
|
38
|
+
* SQLite the partner_id column definition (normalised as above). The skeleton writes the partner index there
|
|
39
|
+
* too, but check does not hold it: on SQLite — one tenant, no policies — it is an index, not tenancy.
|
|
40
|
+
* The skeleton also writes, for a CUSTOMER table, the customer column, the composite target UNIQUE (id, <col>,
|
|
41
|
+
* partner_id), the key to `customers` and the customer index — but check does NOT hold those to the generator,
|
|
42
|
+
* because real migrations are not uniform there (a table may key to another customer table, not `customers`). They
|
|
43
|
+
* are held by RULES instead:
|
|
44
|
+
* - every key to a scoped table names partner_id on both sides, at the same position (no single-column key into
|
|
45
|
+
* tenant data, and no key into tenant data from a platform table);
|
|
46
|
+
* - never ON DELETE / ON UPDATE SET DEFAULT; SET NULL only with a column list naming none of the row's tenant
|
|
47
|
+
* columns (partner_id, and its CUSTOMER column) — PostgreSQL 15+'s `SET NULL (site_id)`;
|
|
48
|
+
* - a key into the principal table, or one the manifest names in NO_CASCADE, is ATTRIBUTION and is never ON UPDATE
|
|
49
|
+
* CASCADE (re-homing a user must not carry the rows they authored into another partner; the older generator's
|
|
50
|
+
* 0.26.0 rule, which one app's wrapper also asserts);
|
|
51
|
+
* - with `requireUpdateCascade` (an app that moves rows between partners by re-parenting them), every OTHER
|
|
52
|
+
* composite key into a scoped table is ON UPDATE CASCADE, so children follow their parent;
|
|
53
|
+
* - no policy, RLS or partner_id-altering statement in a policed migration other than the generated ones: no ALTER,
|
|
54
|
+
* DROP, RENAME or ADD of a scoped table's partner_id, and no data statement that SETs partner_id (a row moved
|
|
55
|
+
* between tenants by a migration) unless the file is declared;
|
|
56
|
+
* - a table of a scoped name comes into existence only through the generated CREATE TABLE: a DROP TABLE of a tenant
|
|
57
|
+
* table (one the manifest scopes, or one any migration gave a partner_id) is refused unless declared, and then the
|
|
58
|
+
* manifest must no longer classify it; a RENAME TO, a view or a foreign table that takes a tenant table's name is
|
|
59
|
+
* refused;
|
|
60
|
+
* - privileges: a GRANT of anything but SELECT, INSERT, UPDATE, DELETE on a table (or USAGE on a sequence or a
|
|
61
|
+
* schema), GRANT ALL, WITH GRANT OPTION, a role granted to a role, CREATE / ALTER ROLE (USER, GROUP), ALTER DEFAULT
|
|
62
|
+
* PRIVILEGES, ALTER FUNCTION / PROCEDURE / ROUTINE, SECURITY DEFINER anywhere, OWNER TO, REASSIGN OWNED, SET ROLE
|
|
63
|
+
* and SET SESSION AUTHORIZATION are refused unless the exact statement is declared. Row-level security filters
|
|
64
|
+
* rows; it does not stop TRUNCATE (which ignores policies), a second role's membership, or an owner.
|
|
65
|
+
* A declaration is an `exceptions` entry in aria.tenancy.json: { file, kind: dropTable | moveRows | privilege, table
|
|
66
|
+
* or statement, reason }. One that matches nothing is itself a problem.
|
|
67
|
+
* The customer column is NOT required in a composite key (a hub push may re-file a site under another customer).
|
|
68
|
+
* Only partner_id is.
|
|
69
|
+
*
|
|
70
|
+
* ── WHAT IT REFUSES TO READ, RATHER THAN READ BADLY ─────────────────────────────────────────────────────────────
|
|
71
|
+
* This is a line-and-regex reader, not a SQL parser, so where a construct is hard to read it is REFUSED in a policed
|
|
72
|
+
* migration whatever it contains: any DO block, CREATE FUNCTION / PROCEDURE, any dollar quote, CREATE RULE, ALTER
|
|
73
|
+
* ROLE, a CREATE VIEW without WITH (security_invoker = true) (a view runs as its owner, who bypasses RLS) or any
|
|
74
|
+
* materialized view, CREATE TABLE … AS / LIKE, a nested block comment, a schema other than public, the runner markers
|
|
75
|
+
* `-- aria:covers-through` / `-- aria:no-transaction` (one makes later files ledgered WITHOUT running, the other drops
|
|
76
|
+
* the transaction), ALTER VIEW, OWNER TO, SELECT … INTO (a table the SQLite classification guard never sees), SET
|
|
77
|
+
* SCHEMA, session_replication_role (replica mode stops enforcing keys), DROP CONSTRAINT (except a lone drop of a CHECK
|
|
78
|
+
* the tree declares — constraintNames) / RENAME TO on a scoped table, search_path, U&"…", triggers, ATTACH PARTITION /
|
|
79
|
+
* INHERIT, CREATE FOREIGN TABLE. Block comments are blanked, `public.` /
|
|
80
|
+
* "public". is folded away, unquoted names are case-folded, E'…' strings honour backslash escapes. The key and
|
|
81
|
+
* refusal scans read each statement with its string literals' CONTENTS blanked, so key-shaped text in a COMMENT is
|
|
82
|
+
* not a key; a plain .sql with no .postgres.sql twin runs on Postgres too (selectForDialect decides), so its keys and
|
|
83
|
+
* tables count as Postgres ones.
|
|
84
|
+
*
|
|
85
|
+
* ── WHICH FILES ARE POLICED ─────────────────────────────────────────────────────────────────────────────────────
|
|
86
|
+
* Every migration file NOT in the app's frozen list. Not "numbered after N": a `020a_x`, a `25_x` or a `zz_x` sorts
|
|
87
|
+
* somewhere the runner will run it, and is policed like any other. A frozen name that is not on disk is a problem (it
|
|
88
|
+
* would freeze nothing and hide a typo). An EMPTY policed set fails too, unless the app declares `noneAfterFrozen`
|
|
89
|
+
* (and that declaration fails as soon as a policed file exists), so a check pointed at the wrong folder is not a pass.
|
|
90
|
+
*
|
|
91
|
+
* ── THE POPULATION, FLOORED TWO WAYS ────────────────────────────────────────────────────────────────────────────
|
|
92
|
+
* A the manifest's scoped tables that no frozen migration creates
|
|
93
|
+
* B the scoped tables a policed migration that runs on Postgres CREATEs — read from the files
|
|
94
|
+
* A must equal B (a table in A no migration creates, or one in B a frozen file creates too, fails), each created by
|
|
95
|
+
* exactly one migration, and |A| >= floors.tables — which, like every floor, fails only when the set SHRINKS.
|
|
96
|
+
* Independently of the manifest's scoped list: EVERY table a policed file creates must be classified at all (all() or
|
|
97
|
+
* PLATFORM_POSTGRES_ONLY), and one that declares (or later gains) a partner_id or customer_id column must be scoped.
|
|
98
|
+
* The keys check reads in the policed files are floored too (floors.keys), so a reader that stopped seeing keys fails
|
|
99
|
+
* instead of finding none bad.
|
|
100
|
+
*
|
|
101
|
+
* ── WHAT WOULD PASS WHILE THE CLAIM IS FALSE (named, and where it is caught instead) ─────────────────────────────
|
|
102
|
+
* - A table never classified at all and never created: nothing here looks at it. The app's classification guard
|
|
103
|
+
* (every live table in the manifest) fails it.
|
|
104
|
+
* - A table with a customer_id classified PARTNER-only: the generator writes the one-arm policy, the file carries
|
|
105
|
+
* it, they agree. The app's live policy test is where that is caught.
|
|
106
|
+
* - A database changed by hand, a half-applied migration, a restore with row_security off: none changes a file.
|
|
107
|
+
* The app's live checks catch those; compareKeys below is the offline half of its live key comparison.
|
|
108
|
+
* - A key whose ON DELETE is CASCADE where the model meant NO ACTION: it keeps the tenant columns intact, so the
|
|
109
|
+
* rules above allow it.
|
|
110
|
+
* Caught HERE because they were the obvious ways round a presence check: a SECOND permissive policy (Postgres ORs
|
|
111
|
+
* permissive policies, so `USING (true)` beside the generated one opens the table while the generated one is still
|
|
112
|
+
* there), a later DISABLE / NO FORCE / DROP POLICY, and a later ALTER / RENAME / DROP COLUMN partner_id.
|
|
113
|
+
*/
|
|
114
|
+
'use strict';
|
|
115
|
+
|
|
116
|
+
const fs = require('fs');
|
|
117
|
+
const path = require('path');
|
|
118
|
+
const { selectForDialect } = require('./database');
|
|
119
|
+
const { TENANCY_POLICY_EXPRESSION } = require('./tenancyManifest');
|
|
120
|
+
|
|
121
|
+
/** The Postgres partner_id definition, in the type the app states (aria.tenancy.json "partnerIdType"). */
|
|
122
|
+
const PARTNER_ID_TYPES = ['BIGINT', 'INTEGER'];
|
|
123
|
+
const pgPartnerId = (type) => {
|
|
124
|
+
if (!PARTNER_ID_TYPES.includes(type)) throw new Error(`partnerIdType must be one of ${PARTNER_ID_TYPES.join(', ')} (stated by the app; there is no default), got ${JSON.stringify(type)}`);
|
|
125
|
+
return `${type} NOT NULL DEFAULT NULLIF(current_setting('app.partner_id', true), '')::int REFERENCES partners(id)`;
|
|
126
|
+
};
|
|
127
|
+
/** Kinds of declared exception (aria.tenancy.json "exceptions"), and what each names. */
|
|
128
|
+
const EXCEPTION_KINDS = { dropTable: 'table', moveRows: 'table', privilege: 'statement' };
|
|
129
|
+
const SQLITE_PARTNER_ID = 'INTEGER NOT NULL DEFAULT 1 REFERENCES partners(id)';
|
|
130
|
+
|
|
131
|
+
const norm = (s) => s.replace(/\s+/g, ' ').trim();
|
|
132
|
+
const has = (o, k) => o != null && Object.prototype.hasOwnProperty.call(o, k);
|
|
133
|
+
|
|
134
|
+
// ── THE APP'S FILE ──────────────────────────────────────────────────────────────────────────────────────────────
|
|
135
|
+
|
|
136
|
+
const CONFIG_FILE = 'aria.tenancy.json';
|
|
137
|
+
const CONFIG_KEYS = ['manifest', 'migrations', 'frozen', 'partnerIdType', 'principalTable', 'requireUpdateCascade', 'noneAfterFrozen', 'floors', 'exceptions'];
|
|
138
|
+
const FLOOR_KEYS = ['tables', 'keys'];
|
|
139
|
+
|
|
140
|
+
/** `p`, resolved against `root`, must stay inside it (after symlinks, where it exists). */
|
|
141
|
+
function inside(root, p, what) {
|
|
142
|
+
if (typeof p !== 'string' || !p.trim()) throw new Error(`${CONFIG_FILE}: ${what} must be a non-empty path`);
|
|
143
|
+
if (path.isAbsolute(p)) throw new Error(`${CONFIG_FILE}: ${what} "${p}" is absolute — give a path inside the app's folder`);
|
|
144
|
+
const abs = path.resolve(root, p);
|
|
145
|
+
const real = (x) => { try { return fs.realpathSync(x); } catch (_) { return x; } };
|
|
146
|
+
const rel = path.relative(real(root), real(abs));
|
|
147
|
+
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) throw new Error(`${CONFIG_FILE}: ${what} "${p}" is outside the app's folder`);
|
|
148
|
+
return abs;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Read and validate `aria.tenancy.json` in `appDir` (the folder holding the app's package.json). Strict: an unknown
|
|
153
|
+
* key, a wrong type, or a path outside the app's folder is refused. Returns resolved paths and the frozen list.
|
|
154
|
+
*/
|
|
155
|
+
function loadConfig(appDir) {
|
|
156
|
+
const root = path.resolve(appDir);
|
|
157
|
+
if (!fs.existsSync(path.join(root, 'package.json'))) throw new Error(`no package.json in ${root} — ${CONFIG_FILE} sits beside it`);
|
|
158
|
+
const file = path.join(root, CONFIG_FILE);
|
|
159
|
+
if (!fs.existsSync(file)) throw new Error(`no ${CONFIG_FILE} beside ${path.join(root, 'package.json')}`);
|
|
160
|
+
let raw;
|
|
161
|
+
try { raw = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { throw new Error(`${CONFIG_FILE}: not JSON (${e.message})`); }
|
|
162
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(`${CONFIG_FILE}: must be an object`);
|
|
163
|
+
const unknown = Object.keys(raw).filter((k) => !CONFIG_KEYS.includes(k));
|
|
164
|
+
if (unknown.length) throw new Error(`${CONFIG_FILE}: unknown key(s) ${unknown.join(', ')} — the keys are ${CONFIG_KEYS.join(', ')}`);
|
|
165
|
+
for (const k of ['manifest', 'migrations', 'frozen', 'partnerIdType']) if (!has(raw, k)) throw new Error(`${CONFIG_FILE}: "${k}" is required`);
|
|
166
|
+
const manifest = inside(root, raw.manifest, '"manifest"');
|
|
167
|
+
const migrations = inside(root, raw.migrations, '"migrations"');
|
|
168
|
+
if (!fs.existsSync(migrations) || !fs.statSync(migrations).isDirectory()) throw new Error(`${CONFIG_FILE}: "migrations" ${raw.migrations} is not a folder`);
|
|
169
|
+
if (!Array.isArray(raw.frozen)) throw new Error(`${CONFIG_FILE}: "frozen" must be a list of migration file names`);
|
|
170
|
+
for (const f of raw.frozen) {
|
|
171
|
+
if (typeof f !== 'string' || !/^[^/\\]+\.sql$/.test(f)) throw new Error(`${CONFIG_FILE}: "frozen" entry ${JSON.stringify(f)} is not a migration file name (a bare *.sql name)`);
|
|
172
|
+
}
|
|
173
|
+
if (new Set(raw.frozen).size !== raw.frozen.length) throw new Error(`${CONFIG_FILE}: "frozen" names a file twice`);
|
|
174
|
+
const principalTable = has(raw, 'principalTable') ? raw.principalTable : 'users';
|
|
175
|
+
if (typeof principalTable !== 'string' || !/^[a-z_][a-z0-9_]*$/.test(principalTable)) throw new Error(`${CONFIG_FILE}: "principalTable" must be a plain table name`);
|
|
176
|
+
if (!PARTNER_ID_TYPES.includes(raw.partnerIdType)) {
|
|
177
|
+
throw new Error(`${CONFIG_FILE}: "partnerIdType" must be "BIGINT" or "INTEGER" — a new app chooses BIGINT (partners.id is BIGINT); an app whose policed files carry INTEGER says INTEGER`);
|
|
178
|
+
}
|
|
179
|
+
for (const k of ['noneAfterFrozen', 'requireUpdateCascade']) {
|
|
180
|
+
if (has(raw, k) && typeof raw[k] !== 'boolean') throw new Error(`${CONFIG_FILE}: "${k}" must be true or false`);
|
|
181
|
+
}
|
|
182
|
+
const exceptions = has(raw, 'exceptions') ? raw.exceptions : [];
|
|
183
|
+
if (!Array.isArray(exceptions)) throw new Error(`${CONFIG_FILE}: "exceptions" must be a list`);
|
|
184
|
+
exceptions.forEach((x, i) => checkException(x, `${CONFIG_FILE}: exceptions[${i}]`, raw.frozen));
|
|
185
|
+
const floors = { tables: 0, keys: 0 };
|
|
186
|
+
if (has(raw, 'floors')) {
|
|
187
|
+
if (raw.floors === null || typeof raw.floors !== 'object' || Array.isArray(raw.floors)) throw new Error(`${CONFIG_FILE}: "floors" must be { tables, keys }`);
|
|
188
|
+
const bad = Object.keys(raw.floors).filter((k) => !FLOOR_KEYS.includes(k));
|
|
189
|
+
if (bad.length) throw new Error(`${CONFIG_FILE}: unknown key(s) in "floors": ${bad.join(', ')}`);
|
|
190
|
+
for (const k of FLOOR_KEYS) {
|
|
191
|
+
if (!has(raw.floors, k)) continue;
|
|
192
|
+
if (!Number.isInteger(raw.floors[k]) || raw.floors[k] < 0) throw new Error(`${CONFIG_FILE}: floors.${k} must be a whole number >= 0`);
|
|
193
|
+
floors[k] = raw.floors[k];
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return {
|
|
197
|
+
root, manifestPath: manifest, manifestName: path.relative(root, manifest).split(path.sep).join('/'),
|
|
198
|
+
migrationsDir: migrations, migrationsName: path.relative(root, migrations).split(path.sep).join('/'),
|
|
199
|
+
frozen: Object.freeze([...raw.frozen]), partnerIdType: raw.partnerIdType, principalTable,
|
|
200
|
+
requireUpdateCascade: raw.requireUpdateCascade === true, noneAfterFrozen: raw.noneAfterFrozen === true, floors,
|
|
201
|
+
exceptions: Object.freeze(exceptions.map((x) => Object.freeze({ ...x })))
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** One declared exception: { file, kind, table | statement, reason }, strictly. */
|
|
206
|
+
function checkException(x, where, frozen = []) {
|
|
207
|
+
if (x === null || typeof x !== 'object' || Array.isArray(x)) throw new Error(`${where} must be { file, kind, table | statement, reason }`);
|
|
208
|
+
if (!has(EXCEPTION_KINDS, x.kind)) throw new Error(`${where}: kind must be one of ${Object.keys(EXCEPTION_KINDS).join(', ')}`);
|
|
209
|
+
const names = EXCEPTION_KINDS[x.kind];
|
|
210
|
+
const bad = Object.keys(x).filter((k) => !['file', 'kind', 'reason', names].includes(k));
|
|
211
|
+
if (bad.length) throw new Error(`${where}: unknown key(s) ${bad.join(', ')} for kind ${x.kind}`);
|
|
212
|
+
if (typeof x.file !== 'string' || !/^[^/\\]+\.sql$/.test(x.file)) throw new Error(`${where}: file must be a bare *.sql name`);
|
|
213
|
+
if (frozen.includes(x.file)) throw new Error(`${where}: ${x.file} is frozen — check never reads a frozen file, so it needs no exception`);
|
|
214
|
+
if (typeof x[names] !== 'string' || !x[names].trim()) throw new Error(`${where}: kind ${x.kind} names its ${names}`);
|
|
215
|
+
if (typeof x.reason !== 'string' || x.reason.trim().length < 10) throw new Error(`${where}: a reason (a sentence) is required`);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** The app's manifest, by the one path its config names; refused unless it has the defineTenancy shape. */
|
|
219
|
+
function loadManifest(config) {
|
|
220
|
+
const manifest = require(config.manifestPath);
|
|
221
|
+
checkManifest(manifest, config.manifestName);
|
|
222
|
+
return manifest;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function checkManifest(manifest, name = 'the manifest') {
|
|
226
|
+
if (!manifest || typeof manifest.scoped !== 'function' || typeof manifest.all !== 'function') {
|
|
227
|
+
throw new Error(`${name} has no scoped() / all() — build it with defineTenancy (@aria-framework/db-worker)`);
|
|
228
|
+
}
|
|
229
|
+
if (has(manifest, 'POLICY_EXPRESSION') && manifest.POLICY_EXPRESSION !== TENANCY_POLICY_EXPRESSION) {
|
|
230
|
+
throw new Error(`${name}: its POLICY_EXPRESSION is not the frozen TENANCY_POLICY_EXPRESSION — the policy every applied migration carries`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// ── RENDERING ───────────────────────────────────────────────────────────────────────────────────────────────────
|
|
235
|
+
|
|
236
|
+
/** The policy expression as the migrations carry it: the frozen text without its leading "\n ". */
|
|
237
|
+
function policyExpression(manifest, table) {
|
|
238
|
+
const col = (manifest.CUSTOMER || {})[table];
|
|
239
|
+
let raw = TENANCY_POLICY_EXPRESSION;
|
|
240
|
+
if (col) {
|
|
241
|
+
if (typeof manifest.CUSTOMER_POLICY_EXPRESSION !== 'function') {
|
|
242
|
+
throw new Error(`${table} is in CUSTOMER, but the manifest has no CUSTOMER_POLICY_EXPRESSION(column)`);
|
|
243
|
+
}
|
|
244
|
+
raw = manifest.CUSTOMER_POLICY_EXPRESSION(col);
|
|
245
|
+
}
|
|
246
|
+
// The rendering assumes the frozen layout; if that ever changes, refuse rather than emit a policy re-indented
|
|
247
|
+
// into something check would then call "the generator's".
|
|
248
|
+
if (typeof raw !== 'string' || !/^\n {2}CASE current_setting\('app\.scope', true\)\n/.test(raw) || !/\n {2}END$/.test(raw)) {
|
|
249
|
+
throw new Error('the policy expression is not in the expected layout');
|
|
250
|
+
}
|
|
251
|
+
return raw.slice(3);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Where a table that is not scoped sits, for the refusal's sentence. */
|
|
255
|
+
function whereClassified(manifest, table) {
|
|
256
|
+
for (const k of ['PLATFORM', 'PLATFORM_POSTGRES_ONLY', 'EXCLUDED']) if (has(manifest[k], table)) return k;
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Refuse a table the generator does not write. Returns its CUSTOMER column (or null). `preExisting`: the scoped
|
|
262
|
+
* tables a frozen migration creates — their tenancy is the app's own adoption, not born with its keys.
|
|
263
|
+
*/
|
|
264
|
+
function classify(manifest, table, { preExisting = [], manifestName = 'the manifest' } = {}) {
|
|
265
|
+
const s = manifest.scoped().find((x) => x.table === table);
|
|
266
|
+
if (!s) {
|
|
267
|
+
const k = whereClassified(manifest, table);
|
|
268
|
+
if (k) {
|
|
269
|
+
throw new Error(`${table} is ${k} in ${manifestName} — it gets no partner_id and no policy, so there is no tenancy to generate; `
|
|
270
|
+
+ 'create it in an ordinary migration (check still holds that it carries no partner_id or customer_id column)');
|
|
271
|
+
}
|
|
272
|
+
throw new Error(`${table} is not classified in ${manifestName} — classify it (PARTNER, and CUSTOMER if it carries a customer) first`);
|
|
273
|
+
}
|
|
274
|
+
if (s.nullable) throw new Error(`${table} is PARTNER_NULLABLE — the generator writes NOT NULL tenancy only`);
|
|
275
|
+
if (preExisting.includes(table)) throw new Error(`${table} is created by a frozen migration — its tenancy is the app's adoption, not born with its keys`);
|
|
276
|
+
return (manifest.CUSTOMER || {})[table] || null;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** The generated tenancy of one table. Statements carry their `;`. */
|
|
280
|
+
function render(manifest, table, opts = {}) {
|
|
281
|
+
const pgDef = pgPartnerId(opts.partnerIdType);
|
|
282
|
+
const customerColumn = classify(manifest, table, opts);
|
|
283
|
+
const e = policyExpression(manifest, table);
|
|
284
|
+
return {
|
|
285
|
+
table,
|
|
286
|
+
customerColumn,
|
|
287
|
+
pgPartnerId: pgDef,
|
|
288
|
+
sqlitePartnerId: SQLITE_PARTNER_ID,
|
|
289
|
+
index: `CREATE INDEX idx_${table}_partner ON ${table}(partner_id);`,
|
|
290
|
+
rls: [
|
|
291
|
+
`ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;`,
|
|
292
|
+
`ALTER TABLE ${table} FORCE ROW LEVEL SECURITY;`,
|
|
293
|
+
`CREATE POLICY tenant_isolation ON ${table} FOR ALL\n USING (${e})\n WITH CHECK (${e});`
|
|
294
|
+
]
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// ── READING SQL ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Split a migration into statements: `raw` is the exact text from its first character to its `;`, `sql` the same with
|
|
302
|
+
* `--` comments blanked (so a parse never reads prose), `bare` as `sql` with every '…' literal's CONTENT blanked,
|
|
303
|
+
* `dollar` the bodies of any $tag$…$tag$ quotes in it. Quote-aware ('…', "…", $tag$…$tag$), so a `;` or `--` inside a
|
|
304
|
+
* literal is not a boundary.
|
|
305
|
+
*/
|
|
306
|
+
function splitStatements(text) {
|
|
307
|
+
const out = [];
|
|
308
|
+
let i = 0;
|
|
309
|
+
let start = -1;
|
|
310
|
+
let clean = '';
|
|
311
|
+
let bare = '';
|
|
312
|
+
let dollar = [];
|
|
313
|
+
const n = text.length;
|
|
314
|
+
while (i < n) {
|
|
315
|
+
const c = text[i];
|
|
316
|
+
const blockEnd = () => {
|
|
317
|
+
const e = text.indexOf('*/', i + 2);
|
|
318
|
+
if (e === -1) throw new Error('an unterminated block comment');
|
|
319
|
+
if (text.slice(i + 2, e).includes('/*')) throw new Error('a nested block comment — refused, not read');
|
|
320
|
+
return e + 2;
|
|
321
|
+
};
|
|
322
|
+
if (start === -1) {
|
|
323
|
+
if (/\s/.test(c)) { i++; continue; }
|
|
324
|
+
if (c === '-' && text[i + 1] === '-') { const e = text.indexOf('\n', i); i = e === -1 ? n : e + 1; continue; }
|
|
325
|
+
if (c === '/' && text[i + 1] === '*') { i = blockEnd(); continue; }
|
|
326
|
+
start = i; clean = ''; bare = ''; dollar = [];
|
|
327
|
+
}
|
|
328
|
+
if (c === '-' && text[i + 1] === '-') {
|
|
329
|
+
const e = text.indexOf('\n', i);
|
|
330
|
+
const stop = e === -1 ? n : e;
|
|
331
|
+
clean += ' '.repeat(stop - i); bare += ' '.repeat(stop - i); i = stop; continue;
|
|
332
|
+
}
|
|
333
|
+
if (c === '/' && text[i + 1] === '*') { const e = blockEnd(); clean += ' '.repeat(e - i); bare += ' '.repeat(e - i); i = e; continue; }
|
|
334
|
+
if (c === "'" || c === '"') {
|
|
335
|
+
// E'…' honours backslash escapes; a plain literal does not (standard_conforming_strings is on).
|
|
336
|
+
const escaped = c === "'" && /[Ee]/.test(text[i - 1] || '') && !/\w/.test(text[i - 2] || '');
|
|
337
|
+
let j = i + 1;
|
|
338
|
+
for (;;) {
|
|
339
|
+
if (j >= n) throw new Error('an unterminated quote');
|
|
340
|
+
if (escaped && text[j] === '\\') { j += 2; continue; }
|
|
341
|
+
if (text[j] === c) { if (text[j + 1] === c) { j += 2; continue; } break; }
|
|
342
|
+
j++;
|
|
343
|
+
}
|
|
344
|
+
clean += text.slice(i, j + 1);
|
|
345
|
+
bare += c === "'" ? "'" + ' '.repeat(j - i - 1) + "'" : text.slice(i, j + 1);
|
|
346
|
+
i = j + 1; continue;
|
|
347
|
+
}
|
|
348
|
+
if (c === '$') {
|
|
349
|
+
const m = /^\$([A-Za-z_]\w*)?\$/.exec(text.slice(i, i + 64));
|
|
350
|
+
if (m) {
|
|
351
|
+
const end = text.indexOf(m[0], i + m[0].length);
|
|
352
|
+
if (end === -1) throw new Error('an unterminated dollar quote');
|
|
353
|
+
dollar.push(text.slice(i + m[0].length, end));
|
|
354
|
+
clean += text.slice(i, end + m[0].length); bare += ' '.repeat(end + m[0].length - i); i = end + m[0].length; continue;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
if (c === ';') { out.push({ raw: text.slice(start, i + 1), sql: fold(clean + ';'), bare: fold(bare + ';'), dollar }); start = -1; i++; continue; }
|
|
358
|
+
clean += c; bare += c; i++;
|
|
359
|
+
}
|
|
360
|
+
if (start !== -1 && text.slice(start).trim()) throw new Error('an unterminated statement at the end of the file');
|
|
361
|
+
return out;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** `public.` and "public". dropped (the only schema an app has), so a qualified name reads as the bare one. */
|
|
365
|
+
function fold(sql) {
|
|
366
|
+
return sql.replace(/(?:"public"|\bpublic)\s*\.\s*/gi, '');
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** An identifier as Postgres resolves it: quoted kept, unquoted case-folded. */
|
|
370
|
+
const ident = (s) => (s.startsWith('"') ? s.slice(1, -1) : s.toLowerCase());
|
|
371
|
+
|
|
372
|
+
/** The table a CREATE TABLE / ALTER TABLE statement acts on, else null. */
|
|
373
|
+
function tableOf(sql) {
|
|
374
|
+
let m = /^\s*CREATE\s+(?:(?:GLOBAL|LOCAL)\s+)?(?:TEMP(?:ORARY)?\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?("\w+"|\w+)/i.exec(sql);
|
|
375
|
+
if (m) return { kind: 'create', table: ident(m[1]) };
|
|
376
|
+
m = /^\s*ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?("\w+"|\w+)/i.exec(sql);
|
|
377
|
+
if (m) return { kind: 'alter', table: ident(m[1]) };
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** The comma-separated items of a CREATE TABLE body, split at depth 0. */
|
|
382
|
+
function bodyItems(sql) {
|
|
383
|
+
const open = sql.indexOf('(');
|
|
384
|
+
const close = sql.lastIndexOf(')');
|
|
385
|
+
const body = sql.slice(open + 1, close);
|
|
386
|
+
const items = [];
|
|
387
|
+
let depth = 0;
|
|
388
|
+
let cur = '';
|
|
389
|
+
let q = null;
|
|
390
|
+
for (const ch of body) {
|
|
391
|
+
if (q) { if (ch === q) q = null; cur += ch; continue; }
|
|
392
|
+
if (ch === "'" || ch === '"') q = ch;
|
|
393
|
+
if (ch === '(') depth++;
|
|
394
|
+
if (ch === ')') depth--;
|
|
395
|
+
if (ch === ',' && depth === 0) { items.push(cur); cur = ''; continue; }
|
|
396
|
+
cur += ch;
|
|
397
|
+
}
|
|
398
|
+
if (cur.trim()) items.push(cur);
|
|
399
|
+
return items.map((s) => s.trim()).filter(Boolean);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const cols = (s) => s.split(',').map((x) => x.trim()).filter(Boolean).map(ident);
|
|
403
|
+
|
|
404
|
+
/** Every key declared in a statement: { cols, parent, parentCols, onDelete, onUpdate, inline }. */
|
|
405
|
+
function keysIn(sql) {
|
|
406
|
+
const keys = [];
|
|
407
|
+
const re = /REFERENCES\s*("\w+"|\w+)\s*(?:\(([^)]*)\))?/gi;
|
|
408
|
+
let m;
|
|
409
|
+
while ((m = re.exec(sql))) {
|
|
410
|
+
const before = sql.slice(0, m.index);
|
|
411
|
+
const fk = /FOREIGN\s+KEY\s*\(([^)]*)\)\s*$/i.exec(before);
|
|
412
|
+
const after = sql.slice(re.lastIndex);
|
|
413
|
+
const actions = /^(?:\s*(?:ON\s+(?:DELETE|UPDATE)\s+(?:SET\s+NULL(?:\s*\([^)]*\))?|SET\s+DEFAULT(?:\s*\([^)]*\))?|CASCADE|RESTRICT|NO\s+ACTION)|MATCH\s+\w+|(?:NOT\s+)?DEFERRABLE|INITIALLY\s+\w+))*/i.exec(after)[0];
|
|
414
|
+
const action = (which) => {
|
|
415
|
+
const a = new RegExp(`ON\\s+${which}\\s+(SET\\s+NULL(?:\\s*\\(([^)]*)\\))?|SET\\s+DEFAULT(?:\\s*\\([^)]*\\))?|CASCADE|RESTRICT|NO\\s+ACTION)`, 'i').exec(actions);
|
|
416
|
+
if (!a) return { kind: 'NO ACTION', list: null };
|
|
417
|
+
return { kind: norm(a[1]).replace(/\s*\(.*$/, '').toUpperCase(), list: a[2] !== undefined ? cols(a[2]) : null };
|
|
418
|
+
};
|
|
419
|
+
keys.push({
|
|
420
|
+
inline: !fk,
|
|
421
|
+
cols: fk ? cols(fk[1]) : null,
|
|
422
|
+
parent: ident(m[1]),
|
|
423
|
+
parentCols: m[2] !== undefined ? cols(m[2]) : null,
|
|
424
|
+
onDelete: action('DELETE'),
|
|
425
|
+
onUpdate: action('UPDATE'),
|
|
426
|
+
text: norm(sql.slice(fk ? fk.index : m.index, re.lastIndex + actions.length))
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
return keys;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// ── THE CHECK ───────────────────────────────────────────────────────────────────────────────────────────────────
|
|
433
|
+
|
|
434
|
+
const baseOf = (f) => f.replace(/(\.postgres)?\.sql$/, '');
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* THE CHECK CONSTRAINTS EACH TABLE DECLARES, read from the migrations that run on Postgres (frozen ones too; `before`:
|
|
438
|
+
* only those earlier than one migration; `only`: one file): `{table: {checks, others}}`.
|
|
439
|
+
* `checks` holds each `CONSTRAINT <name> CHECK` (in a CREATE TABLE body or an ADD CONSTRAINT) and Postgres's own name
|
|
440
|
+
* for a column's inline CHECK, `<table>_<column>_check` (in a CREATE TABLE or an ADD COLUMN); `others` every other
|
|
441
|
+
* named constraint (FOREIGN KEY, UNIQUE, PRIMARY KEY, EXCLUDE) — a name in both is not a CHECK for the rule below.
|
|
442
|
+
* Used for the ONE DROP CONSTRAINT a policed migration may make on a scoped table: dropping a CHECK cannot hide, drop
|
|
443
|
+
* or balance a key, which is what the refusal exists for.
|
|
444
|
+
*/
|
|
445
|
+
function constraintNames(files, { before = null, only = null } = {}) {
|
|
446
|
+
const out = {};
|
|
447
|
+
const of = (t) => (out[t] = out[t] || { checks: new Set(), others: new Set() });
|
|
448
|
+
const colCheck = (t, item) => {
|
|
449
|
+
const m = /^("\w+"|\w+)\s+/.exec(item);
|
|
450
|
+
if (!m || /^(?:CONSTRAINT|PRIMARY|UNIQUE|FOREIGN|CHECK|EXCLUDE)$/i.test(m[1])) return;
|
|
451
|
+
const col = ident(m[1]);
|
|
452
|
+
if (/\bCHECK\s*\(/i.test(item)) of(t).checks.add(`${t}_${col}_check`);
|
|
453
|
+
// Postgres's own names for a column's inline keys: never mistaken for a CHECK
|
|
454
|
+
if (/\bPRIMARY\s+KEY\b/i.test(item)) of(t).others.add(`${t}_pkey`);
|
|
455
|
+
if (/\bUNIQUE\b/i.test(item)) of(t).others.add(`${t}_${col}_key`);
|
|
456
|
+
if (/\bREFERENCES\b/i.test(item)) of(t).others.add(`${t}_${col}_fkey`);
|
|
457
|
+
};
|
|
458
|
+
const named = (t, text) => {
|
|
459
|
+
const re = /\bCONSTRAINT\s+("\w+"|\w+)\s+(\w+)/gi;
|
|
460
|
+
let m;
|
|
461
|
+
while ((m = re.exec(text))) (/^CHECK$/i.test(m[2]) ? of(t).checks : of(t).others).add(ident(m[1]));
|
|
462
|
+
};
|
|
463
|
+
// Only migrations that RUN ON POSTGRES (a SQLite twin's text declares nothing there), and with `before` only those
|
|
464
|
+
// EARLIER than that migration (its own file and twin never vouch for themselves); `only` reads one file alone.
|
|
465
|
+
const all = Object.keys(files).filter((x) => x.endsWith('.sql'));
|
|
466
|
+
const pg = only ? [only] : selectForDialect(all, 'postgres').filter((x) => before == null || baseOf(x) < baseOf(before));
|
|
467
|
+
for (const f of pg) {
|
|
468
|
+
let stmts;
|
|
469
|
+
try { stmts = splitStatements(files[f].replace(/\r\n/g, '\n')); } catch (_) { continue; } // refused elsewhere
|
|
470
|
+
for (const s of stmts) {
|
|
471
|
+
const on = tableOf(s.bare);
|
|
472
|
+
if (!on) continue;
|
|
473
|
+
if (on.kind === 'create') {
|
|
474
|
+
for (const item of bodyItems(s.bare)) { if (/^CONSTRAINT\b/i.test(item)) named(on.table, item); else colCheck(on.table, item); }
|
|
475
|
+
} else {
|
|
476
|
+
named(on.table, s.bare);
|
|
477
|
+
const add = /\bADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?(.*)$/is.exec(norm(s.bare));
|
|
478
|
+
if (add) colCheck(on.table, add[1]);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return out;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* `ALTER TABLE [ONLY] <t> DROP CONSTRAINT <name>` — one action; the name a CHECK of <t> that an EARLIER Postgres migration
|
|
487
|
+
* declares (`earlier`) and never anything else; never a key-shaped name (Postgres's own *_pkey / *_key / *_fkey /
|
|
488
|
+
* *_excl); and not re-declared in this same migration (`same`) as anything but a CHECK. → the name, or null (refused).
|
|
489
|
+
*/
|
|
490
|
+
function droppedCheck(head, earlier, same = {}) {
|
|
491
|
+
const m = /^ALTER\s+TABLE\s+(?:ONLY\s+)?(\w+)\s+DROP\s+CONSTRAINT\s+(\w+)\s*;?$/i.exec(head);
|
|
492
|
+
if (!m) return null;
|
|
493
|
+
const t = ident(m[1]);
|
|
494
|
+
const c = ident(m[2]);
|
|
495
|
+
if (/_(?:pkey|key|fkey|excl)$/.test(c)) return null;
|
|
496
|
+
const n = earlier[t];
|
|
497
|
+
const here = same[t];
|
|
498
|
+
if (here && here.others.has(c)) return null;
|
|
499
|
+
return n && n.checks.has(c) && !n.others.has(c) ? c : null;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const numberOf = (f) => Number((/^(\d{3})/.exec(f) || [])[1]);
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* The scoped tables the FROZEN files create: read with comments stripped, by a plain CREATE TABLE scan (a frozen file
|
|
506
|
+
* is not policed, so it is not split and refused; a table it names only in prose is not counted).
|
|
507
|
+
*/
|
|
508
|
+
function createdByFrozen(files, frozen, scopedNames) {
|
|
509
|
+
const out = new Set();
|
|
510
|
+
for (const f of frozen) {
|
|
511
|
+
if (!has(files, f)) continue;
|
|
512
|
+
const text = files[f].replace(/\r\n/g, '\n').replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/--[^\n]*/g, '');
|
|
513
|
+
const re = /\bCREATE\s+(?:(?:GLOBAL|LOCAL)\s+)?(?:TEMP(?:ORARY)?\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:(?:"public"|public)\s*\.\s*)?("\w+"|\w+)/gi;
|
|
514
|
+
let m;
|
|
515
|
+
while ((m = re.exec(text))) { const t = ident(m[1]); if (scopedNames.has(t)) out.add(t); }
|
|
516
|
+
}
|
|
517
|
+
return [...out].sort();
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Hold a migrations tree to the generator. `files` maps a migration file name to its text; nothing is read from disk,
|
|
522
|
+
* so a test can hand it a broken tree. Returns { problems, stats }.
|
|
523
|
+
*
|
|
524
|
+
* @param {object} o
|
|
525
|
+
* @param {object} o.files { 'NNN_x.sql': text, ... }
|
|
526
|
+
* @param {object} o.manifest built with defineTenancy
|
|
527
|
+
* @param {string[]} o.frozen the app's frozen file names (applied before this generator; not policed)
|
|
528
|
+
* @param {string} [o.principalTable] default 'users': keys into it are attribution, never ON UPDATE CASCADE
|
|
529
|
+
* @param {{tables?: number, keys?: number}} [o.floors] fail when the population shrinks below these
|
|
530
|
+
* @param {boolean} [o.noneAfterFrozen] the app declares that no migration follows the frozen list yet
|
|
531
|
+
* @param {string} [o.manifestName] for the messages
|
|
532
|
+
*/
|
|
533
|
+
function checkTree({ files, manifest, frozen, partnerIdType, principalTable = 'users', requireUpdateCascade = false, floors = {},
|
|
534
|
+
noneAfterFrozen = false, exceptions = [], manifestName = 'the manifest' }) {
|
|
535
|
+
if (!Array.isArray(frozen)) throw new Error('checkTree: pass the app\'s frozen file list (an empty list freezes nothing)');
|
|
536
|
+
pgPartnerId(partnerIdType); // stated, never defaulted
|
|
537
|
+
checkManifest(manifest, manifestName);
|
|
538
|
+
exceptions.forEach((x, i) => checkException(x, `exceptions[${i}]`, frozen));
|
|
539
|
+
const used = new Set();
|
|
540
|
+
/** The declared exception for this file, kind and table / statement, marked used; or null. */
|
|
541
|
+
const declared = (file, kind, what) => {
|
|
542
|
+
const i = exceptions.findIndex((x) => x.file === file && x.kind === kind && (kind === 'privilege' ? norm(x.statement) === what : x.table === what));
|
|
543
|
+
if (i === -1) return null;
|
|
544
|
+
used.add(i);
|
|
545
|
+
return exceptions[i];
|
|
546
|
+
};
|
|
547
|
+
const tablesFloor = floors.tables || 0;
|
|
548
|
+
const keysFloor = floors.keys || 0;
|
|
549
|
+
const problems = [];
|
|
550
|
+
const scopedNames = new Set(manifest.scoped().map((s) => s.table));
|
|
551
|
+
const customerCol = manifest.CUSTOMER || {};
|
|
552
|
+
const noCascade = new Set(Array.isArray(manifest.NO_CASCADE) ? manifest.NO_CASCADE : Object.keys(manifest.NO_CASCADE || {}));
|
|
553
|
+
const names = Object.keys(files).sort();
|
|
554
|
+
for (const f of frozen) if (!has(files, f)) problems.push(`${f}: in the frozen list but not in the migrations folder — it freezes nothing and hides a typo`);
|
|
555
|
+
// POLICED: every file not frozen — whatever its name looks like (020a_x, 25_x, zz_x all run somewhere in the chain).
|
|
556
|
+
const post = names.filter((f) => f.endsWith('.sql') && !frozen.includes(f));
|
|
557
|
+
if (!post.length && !noneAfterFrozen) {
|
|
558
|
+
problems.push(`no migration after the frozen list to check (${names.filter((f) => f.endsWith('.sql')).length} file(s) in the folder, all frozen) — `
|
|
559
|
+
+ 'a check over nothing is not a pass; if the app really has none yet, say "noneAfterFrozen": true');
|
|
560
|
+
}
|
|
561
|
+
if (post.length && noneAfterFrozen) problems.push(`"noneAfterFrozen" is set, but ${post.length} migration(s) follow the frozen list (${post[0]}…) — remove it`);
|
|
562
|
+
const parsed = {};
|
|
563
|
+
for (const f of post) {
|
|
564
|
+
const text = files[f].replace(/\r\n/g, '\n');
|
|
565
|
+
// The runner's markers: covers-through ledgers later files WITHOUT running them; no-transaction drops the wrapper.
|
|
566
|
+
const marker = /--\s*aria:(covers-through|no-transaction)\b/i.exec(text);
|
|
567
|
+
if (marker) problems.push(`${f}: carries the runner marker "aria:${marker[1]}" — refused in a policed migration`);
|
|
568
|
+
try { parsed[f] = splitStatements(text); } catch (e) { problems.push(`${f}: ${e.message}`); }
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
// The files that RUN ON POSTGRES: a plain .sql with no twin runs there too, so its keys count.
|
|
572
|
+
const pgFiles = new Set(selectForDialect(post, 'postgres'));
|
|
573
|
+
|
|
574
|
+
// ── the population, two ways ──
|
|
575
|
+
const preExisting = createdByFrozen(files, frozen, scopedNames);
|
|
576
|
+
const A = manifest.scoped().map((s) => s.table).filter((t) => !preExisting.includes(t)).sort();
|
|
577
|
+
const createdIn = {};
|
|
578
|
+
for (const f of post.filter((x) => pgFiles.has(x) && parsed[x])) {
|
|
579
|
+
for (const s of parsed[f]) {
|
|
580
|
+
const t = tableOf(s.sql);
|
|
581
|
+
if (t && t.kind === 'create' && scopedNames.has(t.table)) (createdIn[t.table] = createdIn[t.table] || []).push(f);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
const B = Object.keys(createdIn).sort();
|
|
585
|
+
for (const t of A.filter((x) => !B.includes(x))) {
|
|
586
|
+
problems.push(`${t}: scoped, no frozen migration creates it, and no policed migration that runs on Postgres creates it`);
|
|
587
|
+
}
|
|
588
|
+
for (const t of B.filter((x) => !A.includes(x))) problems.push(`${t}: created by ${createdIn[t].join(', ')}, but a frozen migration creates it too`);
|
|
589
|
+
for (const t of B.filter((x) => createdIn[x].length > 1)) problems.push(`${t}: created by more than one migration (${createdIn[t].join(', ')})`);
|
|
590
|
+
if (A.length < tablesFloor) {
|
|
591
|
+
problems.push(`only ${A.length} scoped table(s) born after the frozen migrations, below the floor of ${tablesFloor} — the manifest lost tables, or this check is reading the wrong one`);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// ── the generated statements, per table ──
|
|
595
|
+
const generated = new Set(); // raw generated statements, to tell "ours" from a stranger below
|
|
596
|
+
let compared = 0;
|
|
597
|
+
for (const t of A.filter((x) => B.includes(x) && createdIn[x].length === 1)) {
|
|
598
|
+
let g;
|
|
599
|
+
try { g = render(manifest, t, { preExisting, manifestName, partnerIdType }); } catch (e) { problems.push(`${t}: ${e.message}`); continue; }
|
|
600
|
+
const pgFile = createdIn[t][0];
|
|
601
|
+
if (!pgFile.endsWith('.postgres.sql')) { problems.push(`${pgFile}: creates scoped table ${t} in a plain .sql with no .postgres.sql twin — a scoped table needs the pair (the defaults differ)`); continue; }
|
|
602
|
+
const liteFile = pgFile.replace(/\.postgres\.sql$/, '.sql');
|
|
603
|
+
const pg = parsed[pgFile];
|
|
604
|
+
for (const stmt of [g.index, ...g.rls]) {
|
|
605
|
+
generated.add(stmt);
|
|
606
|
+
const n = pg.filter((s) => s.raw === stmt).length;
|
|
607
|
+
compared++;
|
|
608
|
+
if (n !== 1) problems.push(`${pgFile}: ${t}: ${n === 0 ? 'lacks' : `carries ${n} copies of`} the generated statement: ${stmt.split('\n')[0]}`);
|
|
609
|
+
}
|
|
610
|
+
const partnerIdOf = (stmts, file) => {
|
|
611
|
+
const create = stmts.find((s) => { const x = tableOf(s.sql); return x && x.kind === 'create' && x.table === t; });
|
|
612
|
+
if (!create) { problems.push(`${file}: does not create ${t}`); return null; }
|
|
613
|
+
const defs = bodyItems(create.sql).filter((it) => /^"?partner_id"?\s/i.test(it));
|
|
614
|
+
if (defs.length !== 1) { problems.push(`${file}: ${t} declares partner_id ${defs.length} times`); return null; }
|
|
615
|
+
return norm(defs[0].replace(/^"?partner_id"?\s+/i, ''));
|
|
616
|
+
};
|
|
617
|
+
compared++;
|
|
618
|
+
const pgDef = partnerIdOf(pg, pgFile);
|
|
619
|
+
if (pgDef !== null && pgDef !== norm(g.pgPartnerId)) problems.push(`${pgFile}: ${t}.partner_id is "${pgDef}", the generator's is "${g.pgPartnerId}"`);
|
|
620
|
+
if (!parsed[liteFile]) {
|
|
621
|
+
problems.push(`${t}: no SQLite twin ${liteFile} beside ${pgFile}`);
|
|
622
|
+
} else {
|
|
623
|
+
compared++;
|
|
624
|
+
const liteDef = partnerIdOf(parsed[liteFile], liteFile);
|
|
625
|
+
if (liteDef !== null && liteDef !== norm(g.sqlitePartnerId)) problems.push(`${liteFile}: ${t}.partner_id is "${liteDef}", the generator's is "${g.sqlitePartnerId}"`);
|
|
626
|
+
// NOT the SQLite partner index: on SQLite there is one tenant and no policy, so it is an index, not tenancy.
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// ── TENANT TABLES: every name that is, or ever was, a tenant table — scoped now, or given a partner_id by any
|
|
631
|
+
// migration (frozen ones too). Nothing else may take such a name, and none may be dropped undeclared.
|
|
632
|
+
const tenantTables = new Set(scopedNames);
|
|
633
|
+
for (const f of names.filter((x) => x.endsWith('.sql'))) {
|
|
634
|
+
let stmts;
|
|
635
|
+
try { stmts = parsed[f] || splitStatements(files[f].replace(/\r\n/g, '\n')); } catch (_) { continue; } // a policed one is reported above
|
|
636
|
+
for (const st of stmts) {
|
|
637
|
+
const on = tableOf(st.bare);
|
|
638
|
+
if (!on) continue;
|
|
639
|
+
if (on.kind === 'create' && bodyItems(st.bare).some((it) => /^"?partner_id"?\s/i.test(it))) tenantTables.add(on.table);
|
|
640
|
+
if (on.kind === 'alter' && /\bADD\s+(?:COLUMN\s+)?(?:IF\s+NOT\s+EXISTS\s+)?"?partner_id"?\s/i.test(norm(st.bare))) tenantTables.add(on.table);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// ── exactly these, refusals, and the keys keep the tenant columns ──
|
|
645
|
+
const classified = new Set([...manifest.all(), ...Object.keys(manifest.PLATFORM_POSTGRES_ONLY || {})]);
|
|
646
|
+
let keysChecked = 0;
|
|
647
|
+
// The keys from born-after-frozen tables in the files that run on Postgres, as (child, column list, parent) — the
|
|
648
|
+
// multiset an app's live check compares with pg_constraint (compareKeys below).
|
|
649
|
+
const pgKeyList = [];
|
|
650
|
+
for (const f of post.filter((x) => parsed[x])) {
|
|
651
|
+
// what a DROP CONSTRAINT here may rely on: the earlier Postgres migrations' CHECKs, and this file's own declarations
|
|
652
|
+
const ckEarlier = constraintNames(files, { before: f });
|
|
653
|
+
const ckSame = constraintNames(files, { only: f });
|
|
654
|
+
for (const s of parsed[f]) {
|
|
655
|
+
// Read with literal CONTENTS blanked: key-shaped or statement-shaped text inside a string is not a statement.
|
|
656
|
+
const head = norm(s.bare);
|
|
657
|
+
const refuse = (why) => problems.push(`${f}: ${why} — refused in a policed migration: ${head.slice(0, 120)}`);
|
|
658
|
+
// HARD TO READ, SO REFUSED, whatever is inside (the header lists why).
|
|
659
|
+
if (s.dollar.length) refuse('a dollar-quoted body');
|
|
660
|
+
if (/^DO\b/i.test(head)) refuse('a DO block');
|
|
661
|
+
if (/^CREATE\s+(?:OR\s+REPLACE\s+)?(?:FUNCTION|PROCEDURE)\b/i.test(head)) refuse('a function or procedure');
|
|
662
|
+
if (/^CREATE\s+(?:OR\s+REPLACE\s+)?RULE\b/i.test(head)) refuse('a rule');
|
|
663
|
+
// ── PRIVILEGES: row-level security filters rows; it does not stop TRUNCATE (which ignores policies), a role's
|
|
664
|
+
// membership in another, an owner, or a function that runs as its definer. Each refusal here can be declared.
|
|
665
|
+
const privileged = (why) => { if (!declared(f, 'privilege', head)) refuse(`${why} (declare the exact statement as a "privilege" exception if the app needs it)`); };
|
|
666
|
+
if (/^GRANT\b/i.test(head)) {
|
|
667
|
+
const m = /^GRANT\s+([\s\S]*?)\s+ON\s+([\s\S]*?)\s+TO\s+/i.exec(head);
|
|
668
|
+
if (!m) privileged('a GRANT of a role to a role');
|
|
669
|
+
else {
|
|
670
|
+
const privs = m[1].replace(/\([^)]*\)/g, '').split(',').map((p) => norm(p).toUpperCase());
|
|
671
|
+
const target = m[2];
|
|
672
|
+
const bad = privs.filter((p) => !['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'USAGE'].includes(p));
|
|
673
|
+
if (bad.length) privileged(`a GRANT of ${bad.join(', ')} (only SELECT, INSERT, UPDATE, DELETE on a table, or USAGE on a sequence or a schema)`);
|
|
674
|
+
else if (privs.includes('USAGE') && !/^(?:SEQUENCE|ALL\s+SEQUENCES\s+IN\s+SCHEMA|SCHEMA)\b/i.test(target)) privileged('a GRANT of USAGE on something that is not a sequence or a schema');
|
|
675
|
+
if (/\bWITH\s+GRANT\s+OPTION\b/i.test(head)) privileged('WITH GRANT OPTION');
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
if (/^(?:CREATE|ALTER)\s+(?:ROLE|USER|GROUP)\b/i.test(head)) privileged('CREATE / ALTER ROLE');
|
|
679
|
+
if (/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(head)) privileged('ALTER DEFAULT PRIVILEGES');
|
|
680
|
+
if (/^ALTER\s+(?:FUNCTION|PROCEDURE|ROUTINE)\b/i.test(head)) privileged('ALTER FUNCTION / PROCEDURE / ROUTINE');
|
|
681
|
+
if (/\bSECURITY\s+DEFINER\b/i.test(head)) privileged('SECURITY DEFINER');
|
|
682
|
+
// The owner of a table bypasses a policy that is not FORCEd, so a hand-over to any other role is refused.
|
|
683
|
+
if (/\bOWNER\s+TO\b/i.test(head)) privileged('OWNER TO');
|
|
684
|
+
if (/^REASSIGN\s+OWNED\b/i.test(head)) privileged('REASSIGN OWNED');
|
|
685
|
+
if (/^(?:SET|RESET)\s+(?:LOCAL\s+|SESSION\s+)?(?:ROLE|SESSION\s+AUTHORIZATION)\b/i.test(head)) privileged('SET ROLE / SESSION AUTHORIZATION');
|
|
686
|
+
// ── A TENANT TABLE'S NAME: born only through the generated CREATE TABLE ──
|
|
687
|
+
const dropT = /^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?(.+?)(?:\s+(?:CASCADE|RESTRICT))?\s*;$/i.exec(head);
|
|
688
|
+
if (dropT) {
|
|
689
|
+
for (const t of dropT[1].split(',').map((x) => ident(x.trim()))) {
|
|
690
|
+
if (!tenantTables.has(t)) continue;
|
|
691
|
+
const x = declared(f, 'dropTable', t);
|
|
692
|
+
if (!x) refuse(`DROP TABLE of tenant table ${t} (declare it as a "dropTable" exception, and take it out of ${manifestName})`);
|
|
693
|
+
else if (manifest.all().includes(t) || has(manifest.PLATFORM_POSTGRES_ONLY, t)) {
|
|
694
|
+
problems.push(`${f}: drops ${t} under a declared exception, but ${manifestName} still classifies it — take it out of the manifest`);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
const renamed = /\bRENAME\s+TO\s+("\w+"|\w+)/i.exec(head);
|
|
699
|
+
if (renamed && tenantTables.has(ident(renamed[1]))) refuse(`RENAME TO ${ident(renamed[1])}, the name of a tenant table`);
|
|
700
|
+
const viewish = /^CREATE\s+(?:OR\s+REPLACE\s+)?(?:(?:TEMP|TEMPORARY)\s+)?(?:RECURSIVE\s+|MATERIALIZED\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?("\w+"|\w+)/i.exec(head);
|
|
701
|
+
if (viewish && tenantTables.has(ident(viewish[1]))) refuse(`a view named ${ident(viewish[1])}, the name of a tenant table`);
|
|
702
|
+
if (/^(?:CREATE|ALTER)\s+FOREIGN\s+TABLE\b/i.test(head)) refuse('a foreign table');
|
|
703
|
+
// ── ROWS MOVED BETWEEN TENANTS BY A MIGRATION ──
|
|
704
|
+
if (/^(?:UPDATE|INSERT|MERGE|WITH)\b/i.test(head) && /\bSET\b[\s\S]*?(?:^|[\s,(])"?partner_id"?\s*=/i.test(head)) {
|
|
705
|
+
const u = /^UPDATE\s+(?:ONLY\s+)?("\w+"|\w+)/i.exec(head) || /^INSERT\s+INTO\s+("\w+"|\w+)/i.exec(head) || /^MERGE\s+INTO\s+(?:ONLY\s+)?("\w+"|\w+)/i.exec(head);
|
|
706
|
+
const t = u ? ident(u[1]) : '?';
|
|
707
|
+
if (!declared(f, 'moveRows', t)) refuse(`a data statement that sets partner_id on ${t} — it moves rows between tenants (declare it as a "moveRows" exception)`);
|
|
708
|
+
}
|
|
709
|
+
if (/^CREATE\s+MATERIALIZED\s+VIEW\b/i.test(head)) refuse('a materialized view (it cannot be security_invoker)');
|
|
710
|
+
else if (/^CREATE\s+(?:OR\s+REPLACE\s+)?(?:(?:TEMP|TEMPORARY)\s+)?(?:RECURSIVE\s+)?VIEW\b/i.test(head) && !invokerView(head)) {
|
|
711
|
+
refuse('a view without WITH (security_invoker = true) — it would read as its owner, past RLS');
|
|
712
|
+
}
|
|
713
|
+
// An ALTER VIEW can turn security_invoker off again: refused, all of it.
|
|
714
|
+
if (/^ALTER\s+(?:MATERIALIZED\s+)?VIEW\b/i.test(head)) refuse('ALTER VIEW');
|
|
715
|
+
// SELECT … INTO creates a table, Postgres-only — out of sight of the SQLite classification guard.
|
|
716
|
+
if (/^(?:SELECT|WITH)\b.*\bINTO\b/i.test(head)) refuse('SELECT … INTO (it creates a table)');
|
|
717
|
+
if (/\bSET\s+SCHEMA\b/i.test(head)) refuse('SET SCHEMA');
|
|
718
|
+
// Replica mode switches off triggers, and with them every foreign key's enforcement. Read with literals intact.
|
|
719
|
+
if (/session_replication_role/i.test(s.sql)) refuse('session_replication_role');
|
|
720
|
+
// Names this reader cannot resolve: a search_path change moves every unqualified name; U&"…" is an escaped one.
|
|
721
|
+
if (/search_path/i.test(s.sql)) refuse('search_path');
|
|
722
|
+
if (/\bU&["']/i.test(head)) refuse('a U& identifier or string');
|
|
723
|
+
// Code that writes tenant rows without a statement here to read, and tables that take on another's rows/columns.
|
|
724
|
+
if (/^CREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\b/i.test(head)) refuse('a trigger');
|
|
725
|
+
if (/\bATTACH\s+PARTITION\b|\bINHERITS?\b/i.test(head)) refuse('ATTACH PARTITION / INHERIT');
|
|
726
|
+
// `public.` is already folded away, so a qualified name left after one of these words is another schema.
|
|
727
|
+
if (/\b(?:TABLE|ON|REFERENCES|VIEW|INTO)\s*(?:IF\s+(?:NOT\s+)?EXISTS\s+)?(?:ONLY\s+)?"?\w+"?\s*\.\s*"?\w/i.test(head)) {
|
|
728
|
+
refuse('a name in a schema other than public');
|
|
729
|
+
}
|
|
730
|
+
if (/^(CREATE|ALTER|DROP)\s+POLICY\b/i.test(head) || /ROW\s+LEVEL\s+SECURITY/i.test(head)) {
|
|
731
|
+
if (!generated.has(s.raw)) problems.push(`${f}: a policy / row-level-security statement the generator did not write: ${head.slice(0, 140)}`);
|
|
732
|
+
}
|
|
733
|
+
const on = tableOf(s.sql);
|
|
734
|
+
if (!on) continue;
|
|
735
|
+
const child = on.table;
|
|
736
|
+
if (on.kind === 'create') {
|
|
737
|
+
if (!classified.has(child)) problems.push(`${f}: creates ${child}, which ${manifestName} does not classify`);
|
|
738
|
+
if (/^CREATE\s+.*?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?("\w+"|\w+)\s*(?:\(\s*LIKE\b|AS\b|PARTITION\s+OF\b|OF\b)/i.test(head)) {
|
|
739
|
+
refuse('CREATE TABLE … AS / LIKE / OF — its columns cannot be read');
|
|
740
|
+
} else if (!scopedNames.has(child) && bodyItems(s.sql).some((it) => /^"?(partner_id|customer_id)"?\s/i.test(it))) {
|
|
741
|
+
problems.push(`${f}: ${child} has a partner_id or customer_id column but is not scoped in ${manifestName}`);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
if (on.kind === 'alter') {
|
|
745
|
+
if (scopedNames.has(child) && /\b(?:ALTER|DROP|RENAME|ADD)\s+(?:COLUMN\s+)?(?:IF\s+(?:NOT\s+)?EXISTS\s+)?"?partner_id"?\b/i.test(head)) {
|
|
746
|
+
problems.push(`${f}: adds, alters, renames or drops ${child}.partner_id: ${head.slice(0, 140)}`);
|
|
747
|
+
}
|
|
748
|
+
// A dropped key could balance a hidden one in the live multiset; a renamed table leaves its name to a stranger.
|
|
749
|
+
// ...except a lone DROP CONSTRAINT of a CHECK the tree declares (constraintNames): no key can hide behind it.
|
|
750
|
+
if (scopedNames.has(child) && /\bDROP\s+CONSTRAINT\b/i.test(head) && !droppedCheck(head, ckEarlier, ckSame)) refuse(`DROP CONSTRAINT on scoped table ${child}`);
|
|
751
|
+
if (scopedNames.has(child) && /\bRENAME\s+TO\b/i.test(head)) refuse(`RENAME TO on scoped table ${child}`);
|
|
752
|
+
if (!scopedNames.has(child) && /\bADD\s+(?:COLUMN\s+)?(?:IF\s+NOT\s+EXISTS\s+)?"?(partner_id|customer_id)"?\s/i.test(head)) {
|
|
753
|
+
problems.push(`${f}: ${child} gains a partner_id or customer_id column but is not scoped in ${manifestName}`);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
const tenantCols = ['partner_id', ...(customerCol[child] ? [customerCol[child]] : [])];
|
|
757
|
+
for (const k of keysIn(s.bare)) {
|
|
758
|
+
if (!scopedNames.has(k.parent)) continue; // partners, or a platform table — no tenant column to carry
|
|
759
|
+
keysChecked++;
|
|
760
|
+
// The SAME child filter the live comparison uses: born-after-frozen tables only.
|
|
761
|
+
if (pgFiles.has(f) && A.includes(child)) pgKeyList.push(keyId(child, k.cols || ['?'], k.parent));
|
|
762
|
+
const where = `${f}: ${child} → ${k.parent} (${k.text})`;
|
|
763
|
+
if (!scopedNames.has(child)) { problems.push(`${where}: a table outside the tenancy keyed into tenant data`); continue; }
|
|
764
|
+
if (k.inline || !k.cols || !k.parentCols) { problems.push(`${where}: a single-column key into a scoped table — it can point into another partner`); continue; }
|
|
765
|
+
const i = k.cols.indexOf('partner_id');
|
|
766
|
+
if (i === -1 || k.parentCols[i] !== 'partner_id' || k.cols.length !== k.parentCols.length) {
|
|
767
|
+
problems.push(`${where}: does not carry partner_id on both sides at the same position`);
|
|
768
|
+
}
|
|
769
|
+
for (const [which, a] of [['DELETE', k.onDelete], ['UPDATE', k.onUpdate]]) {
|
|
770
|
+
if (a.kind === 'SET DEFAULT') problems.push(`${where}: ON ${which} SET DEFAULT — on a composite key it re-parents the row into another tenant`);
|
|
771
|
+
if (a.kind === 'SET NULL') {
|
|
772
|
+
if (which === 'UPDATE') problems.push(`${where}: ON UPDATE SET NULL`);
|
|
773
|
+
else if (!a.list) problems.push(`${where}: ON DELETE SET NULL without a column list — it nulls partner_id too`);
|
|
774
|
+
else if (a.list.some((c) => tenantCols.includes(c))) problems.push(`${where}: ON DELETE SET NULL (${a.list.join(', ')}) nulls a tenant column`);
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
// ATTRIBUTION (the older generator's 0.26.0 rule): a key into the principal table, or one NO_CASCADE names,
|
|
778
|
+
// records who acted, not what contains the row — cascading it carries a user's rows into another partner.
|
|
779
|
+
const own = k.cols.filter((c) => c !== 'partner_id');
|
|
780
|
+
const attribution = k.parent === principalTable || own.some((c) => noCascade.has(`${child}.${c}`));
|
|
781
|
+
if (attribution && k.onUpdate.kind === 'CASCADE') {
|
|
782
|
+
problems.push(`${where}: ON UPDATE CASCADE on an attribution key (into ${k.parent === principalTable ? `the principal table ${principalTable}` : 'a NO_CASCADE column'}) — re-homing the parent would carry this row into another partner`);
|
|
783
|
+
}
|
|
784
|
+
// OWNERSHIP, for an app that moves rows by re-parenting them (requireUpdateCascade): the child follows.
|
|
785
|
+
if (requireUpdateCascade && !attribution && k.onUpdate.kind !== 'CASCADE') {
|
|
786
|
+
problems.push(`${where}: an ownership key without ON UPDATE CASCADE — this app re-parents rows, and its children must follow (requireUpdateCascade)`);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
exceptions.forEach((x, i) => {
|
|
792
|
+
if (!used.has(i)) problems.push(`${x.file}: the declared ${x.kind} exception (${x.table || x.statement}) matches no statement in it — remove or correct it`);
|
|
793
|
+
});
|
|
794
|
+
if (keysChecked < keysFloor) {
|
|
795
|
+
problems.push(`only ${keysChecked} key(s) into scoped tables read in the policed migrations, below the floor of ${keysFloor} — the reader stopped seeing keys`);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
return { problems, stats: { tables: A, created: B, preExisting, statementsCompared: compared, keysChecked, pgKeys: pgKeyList.length, pgKeyList, files: post.length } };
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/** A view's WITH (…) options turn security_invoker on (bare, = true or = on) and nothing turns it off. */
|
|
802
|
+
function invokerView(head) {
|
|
803
|
+
const m = /\bWITH\s*\(([^)]*)\)/i.exec(head);
|
|
804
|
+
if (!m) return false;
|
|
805
|
+
const opts = m[1].split(',').map((o) => o.trim().toLowerCase().replace(/\s*=\s*/, '='));
|
|
806
|
+
return opts.some((o) => o === 'security_invoker' || o === 'security_invoker=true' || o === 'security_invoker=on')
|
|
807
|
+
&& !opts.some((o) => /^security_invoker=(false|off|0)$/.test(o));
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
const keyId = (child, list, parent) => `${child}(${list.join(', ')}) → ${parent}`;
|
|
811
|
+
|
|
812
|
+
/**
|
|
813
|
+
* The live comparison, kept here so it runs offline in a test and a false red shows there first. `expected` is
|
|
814
|
+
* checkTree's pgKeyList; `rows` are pg_constraint rows { tbl, parent, cols } for the keys between scoped tables. Only
|
|
815
|
+
* rows whose CHILD is a born-after-frozen table are compared — checkTree's own filter — and as MULTISETS of (child,
|
|
816
|
+
* column list, parent), so a key the reader missed cannot be balanced by one it saw that is gone.
|
|
817
|
+
*/
|
|
818
|
+
function compareKeys(expected, rows, postTables) {
|
|
819
|
+
const count = (list) => list.reduce((m, k) => m.set(k, (m.get(k) || 0) + 1), new Map());
|
|
820
|
+
const want = count(expected);
|
|
821
|
+
const have = count(rows.filter((r) => postTables.includes(r.tbl)).map((r) => keyId(r.tbl, r.cols, r.parent)));
|
|
822
|
+
const diff = (a, b) => [...a].flatMap(([k, n]) => Array(Math.max(0, n - (b.get(k) || 0))).fill(k));
|
|
823
|
+
return { missing: diff(want, have), extra: diff(have, want), compared: [...have.values()].reduce((x, y) => x + y, 0) };
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// ── THE SKELETON ────────────────────────────────────────────────────────────────────────────────────────────────
|
|
827
|
+
|
|
828
|
+
/** The new pair's text: `{ pg, lite }`. `opts`: { preExisting, manifestName } as for render. */
|
|
829
|
+
function skeleton(manifest, tables, base, opts = {}) {
|
|
830
|
+
const manifestName = opts.manifestName || 'the manifest';
|
|
831
|
+
const gens = tables.map((t) => render(manifest, t, opts));
|
|
832
|
+
for (const g of gens) {
|
|
833
|
+
if (g.customerColumn === 'id') throw new Error(`${g.table} names its customer by its own id — that is the anchor's shape (customers), not a table the skeleton writes`);
|
|
834
|
+
}
|
|
835
|
+
const pad = (s) => s.padEnd(13) + ' ';
|
|
836
|
+
const head = (dialect) => [
|
|
837
|
+
`-- ${base}${dialect === 'pg' ? '.postgres' : ''}.sql — GENERATED SKELETON (aria-tenancy new ${tables.join(' ')}).`,
|
|
838
|
+
'--',
|
|
839
|
+
`-- The TENANCY below is the generator's, from ${manifestName}: the partner_id column, the partner index`
|
|
840
|
+
+ (dialect === 'pg' ? ', and the' : '.'),
|
|
841
|
+
...(dialect === 'pg' ? ['-- row-level-security section at the end. `aria-tenancy check` holds those'] : []),
|
|
842
|
+
...(dialect === 'pg'
|
|
843
|
+
? [`-- to the generator: do not edit them — change ${manifestName} and regenerate before this migration is applied.`]
|
|
844
|
+
: ['-- No policies on SQLite (one tenant there); `aria-tenancy check` holds the partner_id column to the generator.']),
|
|
845
|
+
'-- Add each table\'s own columns and keys where marked, and its sibling in the other dialect the same way. A key to',
|
|
846
|
+
'-- another scoped table is composite — (col, partner_id), or (col, customer_id, partner_id) between customer tables —',
|
|
847
|
+
'-- and never ON DELETE SET DEFAULT, nor SET NULL unless it names only its own column, e.g. SET NULL (site_id)',
|
|
848
|
+
'-- (check refuses both: on a composite key they null partner_id, or re-parent the row into another tenant).',
|
|
849
|
+
...(opts.requireUpdateCascade
|
|
850
|
+
? [`-- This app re-parents rows: every key to a scoped table that is not into ${opts.principalTable || 'users'} is ON UPDATE CASCADE (check requires it).`]
|
|
851
|
+
: []),
|
|
852
|
+
''
|
|
853
|
+
];
|
|
854
|
+
const table = (g, dialect) => {
|
|
855
|
+
const lines = [
|
|
856
|
+
`CREATE TABLE ${g.table} (`,
|
|
857
|
+
` ${pad('id')}${dialect === 'pg' ? 'BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY' : 'INTEGER PRIMARY KEY AUTOINCREMENT'},`,
|
|
858
|
+
` ${pad('partner_id')}${dialect === 'pg' ? g.pgPartnerId : g.sqlitePartnerId},`
|
|
859
|
+
];
|
|
860
|
+
if (g.customerColumn) lines.push(` ${pad(g.customerColumn)}TEXT NOT NULL,`);
|
|
861
|
+
lines.push(' -- ── this table\'s own columns and keys ──');
|
|
862
|
+
const ts = dialect === 'pg' ? "to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')" : "(datetime('now'))";
|
|
863
|
+
const tail = [` ${pad('created_at')}TEXT NOT NULL DEFAULT ${ts}`];
|
|
864
|
+
if (g.customerColumn) {
|
|
865
|
+
tail.push(` CONSTRAINT uq_${g.table}_id_customer_partner UNIQUE (id, ${g.customerColumn}, partner_id)`);
|
|
866
|
+
tail.push(` CONSTRAINT fk_${g.table}_${g.customerColumn}_partner FOREIGN KEY (${g.customerColumn}, partner_id)\n`
|
|
867
|
+
+ ' REFERENCES customers (id, partner_id) ON DELETE CASCADE ON UPDATE CASCADE');
|
|
868
|
+
} else {
|
|
869
|
+
tail.push(` CONSTRAINT uq_${g.table}_id_partner UNIQUE (id, partner_id)`);
|
|
870
|
+
}
|
|
871
|
+
lines.push(tail.join(',\n'), ');', g.index);
|
|
872
|
+
if (g.customerColumn) lines.push(`CREATE INDEX idx_${g.table}_customer ON ${g.table}(${g.customerColumn}, partner_id);`);
|
|
873
|
+
return lines.join('\n');
|
|
874
|
+
};
|
|
875
|
+
const pg = [...head('pg'), gens.map((g) => table(g, 'pg')).join('\n\n'), '',
|
|
876
|
+
`-- ── ROW-LEVEL SECURITY (generated from ${manifestName}) ──`, '',
|
|
877
|
+
gens.map((g) => g.rls.join('\n')).join('\n\n'), ''].join('\n');
|
|
878
|
+
const lite = [...head('sqlite'), gens.map((g) => table(g, 'sqlite')).join('\n\n'), ''].join('\n');
|
|
879
|
+
return { pg, lite };
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/** Every *.sql in a folder, by name. */
|
|
883
|
+
function readTree(dir) {
|
|
884
|
+
const files = {};
|
|
885
|
+
for (const f of fs.readdirSync(dir)) if (f.endsWith('.sql')) files[f] = fs.readFileSync(path.join(dir, f), 'utf8');
|
|
886
|
+
return files;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/** The checkTree options an app's config gives. */
|
|
890
|
+
const checkOptions = (config, manifest) => ({
|
|
891
|
+
files: readTree(config.migrationsDir), manifest, frozen: config.frozen, partnerIdType: config.partnerIdType,
|
|
892
|
+
principalTable: config.principalTable, requireUpdateCascade: config.requireUpdateCascade, floors: config.floors,
|
|
893
|
+
noneAfterFrozen: config.noneAfterFrozen, exceptions: config.exceptions, manifestName: config.manifestName
|
|
894
|
+
});
|
|
895
|
+
/** The render / skeleton options an app's config gives. */
|
|
896
|
+
const renderOptions = (config, preExisting) => ({
|
|
897
|
+
preExisting, manifestName: config.manifestName, partnerIdType: config.partnerIdType,
|
|
898
|
+
requireUpdateCascade: config.requireUpdateCascade, principalTable: config.principalTable
|
|
899
|
+
});
|
|
900
|
+
|
|
901
|
+
/**
|
|
902
|
+
* Plan a NEW pair for `tables` (nothing is written): refuses a table already created by any migration, a taken
|
|
903
|
+
* number, a number not after every frozen file, and whatever render refuses. → { base, files: { name: text } }.
|
|
904
|
+
*/
|
|
905
|
+
function planNew(config, manifest, tables, { name = null, number = null, fillGap = false } = {}) {
|
|
906
|
+
if (!tables.length) throw new Error(`name at least one table (classified in ${config.manifestName} first)`);
|
|
907
|
+
if (new Set(tables).size !== tables.length) throw new Error('a table is named twice');
|
|
908
|
+
for (const t of tables) if (!/^[a-z][a-z0-9_]*$/.test(t)) throw new Error(`"${t}" is not a table name`);
|
|
909
|
+
const tree = readTree(config.migrationsDir);
|
|
910
|
+
const existing = Object.keys(tree);
|
|
911
|
+
const scopedNames = new Set(manifest.scoped().map((s) => s.table));
|
|
912
|
+
const preExisting = createdByFrozen(tree, config.frozen, scopedNames);
|
|
913
|
+
const { stats } = checkTree(checkOptions(config, manifest));
|
|
914
|
+
for (const t of tables) if (stats.created.includes(t)) throw new Error(`${t} is already created by a migration — a table is born once`);
|
|
915
|
+
const opts = renderOptions(config, preExisting);
|
|
916
|
+
for (const t of tables) render(manifest, t, opts); // every refusal before any number is chosen
|
|
917
|
+
const numbers = existing.map(numberOf).filter(Number.isFinite);
|
|
918
|
+
const next = String((numbers.length ? Math.max(...numbers) : 0) + 1).padStart(3, '0');
|
|
919
|
+
const nnn = number || next;
|
|
920
|
+
if (!/^\d{3}$/.test(nnn)) throw new Error(`--number must be three digits, got "${nnn}"`);
|
|
921
|
+
const lastFrozen = Math.max(0, ...config.frozen.map(numberOf).filter(Number.isFinite));
|
|
922
|
+
if (Number(nnn) <= lastFrozen) throw new Error(`--number ${nnn} is not after the frozen migrations (the last is ${String(lastFrozen).padStart(3, '0')})`);
|
|
923
|
+
const taken = existing.filter((f) => f.startsWith(nnn + '_'));
|
|
924
|
+
if (taken.length) throw new Error(`number ${nnn} is taken by ${taken.join(', ')} — an applied migration is never rewritten`);
|
|
925
|
+
// A file numbered below applied ones runs out of order on a fresh database and is easy to miss in review.
|
|
926
|
+
const highest = numbers.length ? Math.max(...numbers) : 0;
|
|
927
|
+
if (Number(nnn) < highest && !fillGap) {
|
|
928
|
+
throw new Error(`--number ${nnn} is below the highest existing migration (${String(highest).padStart(3, '0')}) — it would sort before files already applied; pass --fill-gap if that is meant`);
|
|
929
|
+
}
|
|
930
|
+
const slug = name || tables[0];
|
|
931
|
+
if (!/^[a-z][a-z0-9_]*$/.test(slug)) throw new Error(`--name "${slug}" is not a slug`);
|
|
932
|
+
const base = `${nnn}_${slug}`;
|
|
933
|
+
for (const f of [`${base}.postgres.sql`, `${base}.sql`]) if (fs.existsSync(path.join(config.migrationsDir, f))) throw new Error(`${f} exists — an applied migration is never rewritten`);
|
|
934
|
+
const { pg, lite } = skeleton(manifest, tables, base, opts);
|
|
935
|
+
return { base, files: { [`${base}.postgres.sql`]: pg, [`${base}.sql`]: lite } };
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
/**
|
|
939
|
+
* Write a planned pair so that a failure cannot leave half of it: each file first to a temporary name in the same
|
|
940
|
+
* folder (not *.sql, so no runner ever reads it), then each LINKED to its name (a link refuses an existing file, so
|
|
941
|
+
* nothing is overwritten) and the temporary removed. On any failure every temporary and every file already linked is
|
|
942
|
+
* removed. `io` is for a test that injects a failure; it defaults to fs.
|
|
943
|
+
*/
|
|
944
|
+
function writePair(dir, files, io = fs) {
|
|
945
|
+
const names = Object.keys(files);
|
|
946
|
+
const tmp = (f) => path.join(dir, `.${f}.${process.pid}.tmp`);
|
|
947
|
+
const done = [];
|
|
948
|
+
try {
|
|
949
|
+
for (const f of names) io.writeFileSync(tmp(f), files[f], { flag: 'wx' });
|
|
950
|
+
for (const f of names) { io.linkSync(tmp(f), path.join(dir, f)); done.push(f); }
|
|
951
|
+
} catch (e) {
|
|
952
|
+
for (const f of done) { try { fs.unlinkSync(path.join(dir, f)); } catch (_) { /* already gone */ } }
|
|
953
|
+
throw e;
|
|
954
|
+
} finally {
|
|
955
|
+
for (const f of names) { try { fs.unlinkSync(tmp(f)); } catch (_) { /* never written */ } }
|
|
956
|
+
}
|
|
957
|
+
return names;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
module.exports = {
|
|
961
|
+
CONFIG_FILE, loadConfig, loadManifest, render, skeleton, checkTree, checkOptions, renderOptions, planNew, writePair,
|
|
962
|
+
splitStatements, keysIn, readTree, constraintNames, droppedCheck, compareKeys, createdByFrozen, pgPartnerId,
|
|
963
|
+
PARTNER_ID_TYPES, SQLITE_PARTNER_ID
|
|
964
|
+
};
|