@aria-framework/db-worker 0.29.0 → 0.31.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.
@@ -0,0 +1,204 @@
1
+ /**
2
+ * 0.31.0 — THE SCHEMA CHECK for table definitions (tableDefinitions.js): does the app's database hold the tables a
3
+ * package's definition set requires, as that version of the set defines them? A package calls it when the app starts
4
+ * and refuses to start on any problem (assertDefinedSchema). It reads through the app's own driver with the dialect's
5
+ * introspection (dialect.js: tables, columnDetails, indexes, keyColumns, policies) — no second reader of the schema.
6
+ *
7
+ * WHAT IT COMPARES, per table of the set (the expected side is expectedSchema(set, engine, partnerIdType)):
8
+ * - the table exists;
9
+ * - its columns: every defined and generated column, with its type and NOT NULL; and EVERY OTHER COLUMN IS A
10
+ * PROBLEM too. "Extra" is read the less permissive way: a column the app added to a package's table is reported,
11
+ * because the package's code and its generated migration do not know it (a NOT NULL one without a default would
12
+ * break the package's inserts), and a table that differs from its definition is not the definition's table;
13
+ * - its primary key (id), its unique keys (the generated one, and the set's own) — missing or extra;
14
+ * - its named indexes (the generated partner and customer indexes, and the set's): present, unique or not, the same
15
+ * columns in order, partial or not — and an index the set does not have is a problem;
16
+ * - its foreign keys: column list, target table, target columns and both actions — missing or extra;
17
+ * - on Postgres, its row-level security: ENABLE and FORCE on, exactly ONE policy, named tenant_isolation, PERMISSIVE,
18
+ * FOR ALL, TO public, whose USING and WITH CHECK are the package's frozen text (TENANCY_POLICY_EXPRESSION, or
19
+ * CUSTOMER_POLICY_EXPRESSION(column) for a customer table).
20
+ * Per anchor (a table the set relies on but does not define): it exists, each column the set states is there with
21
+ * its type and NOT NULL, and each unique key it states is a primary key, a unique constraint or a unique, non-partial
22
+ * index on exactly those columns (in any order: that is what a key into it needs). Other columns of an anchor are
23
+ * the app's and are not reported.
24
+ *
25
+ * And partner_id's DEFAULT, against what the generator writes (pgPartnerId / SQLITE_PARTNER_ID), in the same form as the
26
+ * policy below: a default changed by hand would put a platform-scope insert into the wrong partner.
27
+ *
28
+ * WHAT IT DOES NOT COMPARE, said plainly: CHECK constraints and the other columns' defaults (the engines rewrite their text),
29
+ * an index's WHERE text (only that it is partial), and the policy text up to parentheses, whitespace and the casts the
30
+ * server adds (`::text`, `::integer` read as `::int`): the server stores a policy deparsed, so a policy differing from
31
+ * the package's ONLY in parenthesisation would pass here. `aria-tenancy check` holds the migration file itself byte for
32
+ * byte, so such a policy can only come from a database changed by hand. SQLite has no policies: there the policy part
33
+ * is skipped, and the result says so (compared.policies is 0).
34
+ *
35
+ * → { problems: [string, …], compared: { tables, columns, keys, indexes, policies, anchors } } — the counts are what
36
+ * was looked at, so a caller can floor them: a check that compared nothing is not a pass.
37
+ */
38
+ 'use strict';
39
+
40
+ const { expectedSchema, assertTableDefinitions } = require('./tableDefinitions');
41
+ const { TENANCY_POLICY_EXPRESSION, CUSTOMER_POLICY_EXPRESSION } = require('./tenancyManifest');
42
+ const { pgPartnerId, SQLITE_PARTNER_ID } = require('./tenancyGenerator');
43
+
44
+ /** A policy expression (or a default) read as the server deparses it, and as the package's text, to one comparable form. */
45
+ const policyForm = (s) => String(s == null ? '' : s).replace(/::text\b/g, '').replace(/::integer\b/g, '::int').replace(/[\s()]/g, '');
46
+
47
+ /** partner_id's DEFAULT as the generator writes it (pgPartnerId / SQLITE_PARTNER_ID — read from there, not copied). */
48
+ const partnerDefault = (engine, partnerIdType) => /\bDEFAULT (.*) REFERENCES\b/.exec(engine === 'postgres' ? pgPartnerId(partnerIdType) : SQLITE_PARTNER_ID)[1];
49
+
50
+ const keyText = (k) => `(${k.columns.join(', ')}) → ${k.parent} (${k.parentColumns.join(', ')}) ON DELETE ${k.onDelete} ON UPDATE ${k.onUpdate}`;
51
+ const list = (cols) => `(${cols.join(', ')})`;
52
+
53
+ /** Rows grouped by `by`, each group's rows in their order. */
54
+ function groups(rows, by) {
55
+ const out = new Map();
56
+ for (const r of rows) { const k = String(r[by]); if (!out.has(k)) out.set(k, []); out.get(k).push(r); }
57
+ return out;
58
+ }
59
+ /** The elements of multiset `a` not matched in `b`. */
60
+ function minus(a, b) {
61
+ const left = [...b];
62
+ return a.filter((x) => { const i = left.indexOf(x); if (i === -1) return true; left.splice(i, 1); return false; });
63
+ }
64
+
65
+ /** What the database holds for one table, read through the driver. */
66
+ async function readTable(driver, d, table) {
67
+ const columns = (await driver.all(d.columnDetails(table))).map((r) => ({ name: r.name, type: String(r.type).toUpperCase(), notNull: Number(r.notnull) === 1, pk: Number(r.pk) || 0, dflt: r.dflt == null ? null : String(r.dflt) }));
68
+ const idx = [...groups(await driver.all(d.indexes(table)), 'name').entries()].map(([name, rows]) => ({
69
+ name, unique: Number(rows[0].unique) === 1, origin: rows[0].origin, partial: Number(rows[0].partial) === 1,
70
+ columns: rows.sort((a, b) => Number(a.seq) - Number(b.seq)).map((r) => (r.col == null ? '(expression)' : r.col))
71
+ }));
72
+ const keys = [...groups(await driver.all(d.keyColumns(table)), 'id').values()].map((rows) => {
73
+ rows.sort((a, b) => Number(a.seq) - Number(b.seq));
74
+ return { columns: rows.map((r) => r.col), parent: rows[0].parent, parentColumns: rows.map((r) => r.parent_col),
75
+ onDelete: String(rows[0].on_delete).toUpperCase(), onUpdate: String(rows[0].on_update).toUpperCase() };
76
+ });
77
+ const policySql = d.policies(table);
78
+ const policies = policySql ? await driver.all(policySql) : null;
79
+ return { columns, indexes: idx, keys, policies };
80
+ }
81
+
82
+ /**
83
+ * Compare the database the driver reaches with each definition set. `opts.partnerIdType`: the app's stated Postgres
84
+ * type of partner_id (BIGINT or INTEGER), required on Postgres. Never throws for a difference — it reports; it throws
85
+ * for a bad call (no driver, a set not built with defineTables, no partnerIdType on Postgres).
86
+ */
87
+ async function checkDefinedSchema(driver, sets, opts = {}) {
88
+ if (!driver || typeof driver.all !== 'function' || !driver.dialect) throw new Error('checkDefinedSchema: pass the app\'s driver (database.driver())');
89
+ const list_ = Array.isArray(sets) ? sets : [sets];
90
+ if (!list_.length) throw new Error('checkDefinedSchema: pass the definition set(s)');
91
+ list_.forEach((s, i) => assertTableDefinitions(s, `checkDefinedSchema: set ${i + 1}`));
92
+ const d = driver.dialect;
93
+ const engine = d.kind;
94
+ if (engine !== 'postgres' && engine !== 'sqlite') throw new Error(`checkDefinedSchema: unknown engine ${engine}`);
95
+ const problems = [];
96
+ const compared = { tables: 0, columns: 0, keys: 0, indexes: 0, policies: 0, anchors: 0 };
97
+ const present = new Set((await driver.all(d.tables())).map((r) => r.name));
98
+
99
+ for (const set of list_) {
100
+ const want = expectedSchema(set, engine, opts.partnerIdType);
101
+ const at = `${set.name} ${set.version}`;
102
+ for (const t of want.tables) {
103
+ if (!present.has(t.name)) { problems.push(`${at}: ${t.name}: missing table`); continue; }
104
+ compared.tables++;
105
+ const have = await readTable(driver, d, t.name);
106
+ // columns, both ways
107
+ for (const c of t.columns) {
108
+ compared.columns++;
109
+ const h = have.columns.find((x) => x.name === c.name);
110
+ if (!h) { problems.push(`${at}: ${t.name}.${c.name}: missing column`); continue; }
111
+ if (h.type !== c.type) problems.push(`${at}: ${t.name}.${c.name}: type ${h.type}, the definition's is ${c.type}`);
112
+ if (h.notNull !== c.notNull) problems.push(`${at}: ${t.name}.${c.name}: ${h.notNull ? 'NOT NULL' : 'nullable'}, the definition's is ${c.notNull ? 'NOT NULL' : 'nullable'}`);
113
+ // partner_id's default decides which partner a row lands in when the session sets none (a platform-scope insert)
114
+ if (c.name === 'partner_id') {
115
+ const want = partnerDefault(engine, opts.partnerIdType);
116
+ if (policyForm(h.dflt) !== policyForm(want)) problems.push(`${at}: ${t.name}.partner_id: DEFAULT ${h.dflt === null ? '(none)' : h.dflt}, the generator's is ${want}`);
117
+ }
118
+ }
119
+ for (const h of have.columns) if (!t.columns.some((c) => c.name === h.name)) problems.push(`${at}: ${t.name}.${h.name}: a column the definition does not have`);
120
+ // primary key
121
+ compared.keys++;
122
+ const pk = have.columns.filter((c) => c.pk > 0).sort((a, b) => a.pk - b.pk).map((c) => c.name);
123
+ if (list(pk) !== list(t.primaryKey)) problems.push(`${at}: ${t.name}: primary key ${pk.length ? list(pk) : '(none)'}, the definition's is ${list(t.primaryKey)}`);
124
+ // unique keys (constraint-backed indexes that are not the primary key)
125
+ const uq = have.indexes.filter((x) => x.origin === 'u' && x.unique).map((x) => list(x.columns));
126
+ const wantUq = t.unique.map(list);
127
+ compared.keys += wantUq.length;
128
+ for (const u of minus(wantUq, uq)) problems.push(`${at}: ${t.name}: missing unique key ${u}`);
129
+ for (const u of minus(uq, wantUq)) problems.push(`${at}: ${t.name}: a unique key the definition does not have ${u}`);
130
+ // named indexes
131
+ const named = have.indexes.filter((x) => x.origin === 'c');
132
+ for (const x of t.indexes) {
133
+ compared.indexes++;
134
+ const h = named.find((y) => y.name === x.name);
135
+ if (!h) { problems.push(`${at}: ${t.name}: missing index ${x.name}`); continue; }
136
+ if (h.unique !== x.unique) problems.push(`${at}: ${t.name}: index ${x.name} is ${h.unique ? '' : 'not '}unique, the definition's is ${x.unique ? '' : 'not '}unique`);
137
+ if (list(h.columns) !== list(x.columns)) problems.push(`${at}: ${t.name}: index ${x.name} is on ${list(h.columns)}, the definition's on ${list(x.columns)}`);
138
+ if (h.partial !== x.partial) problems.push(`${at}: ${t.name}: index ${x.name} is ${h.partial ? '' : 'not '}partial, the definition's is ${x.partial ? '' : 'not '}partial`);
139
+ }
140
+ for (const h of named) if (!t.indexes.some((x) => x.name === h.name)) problems.push(`${at}: ${t.name}: an index the definition does not have: ${h.name} ${list(h.columns)}`);
141
+ // foreign keys, as multisets
142
+ const wantK = t.keys.map(keyText);
143
+ const haveK = have.keys.map(keyText);
144
+ compared.keys += wantK.length;
145
+ for (const k of minus(wantK, haveK)) problems.push(`${at}: ${t.name}: missing foreign key ${k}`);
146
+ for (const k of minus(haveK, wantK)) problems.push(`${at}: ${t.name}: a foreign key the definition does not have ${k}`);
147
+ // row-level security (Postgres)
148
+ if (have.policies) {
149
+ compared.policies++;
150
+ const expr = policyForm(t.customer ? CUSTOMER_POLICY_EXPRESSION(t.customer) : TENANCY_POLICY_EXPRESSION);
151
+ const rows = have.policies;
152
+ if (!rows.length || rows[0].rls !== true) problems.push(`${at}: ${t.name}: row-level security is not ENABLEd`);
153
+ if (!rows.length || rows[0].force !== true) problems.push(`${at}: ${t.name}: row-level security is not FORCEd (the owner reads past it)`);
154
+ const pols = rows.filter((r) => r.name != null);
155
+ if (pols.length !== 1) problems.push(`${at}: ${t.name}: ${pols.length} policies (${pols.map((p) => p.name).join(', ') || 'none'}), the definition's is exactly one, tenant_isolation`);
156
+ for (const p of pols) {
157
+ const why = [];
158
+ if (p.name !== 'tenant_isolation') why.push(`named ${p.name}`);
159
+ if (p.permissive !== 'PERMISSIVE') why.push(String(p.permissive));
160
+ if (p.cmd !== 'ALL') why.push(`FOR ${p.cmd}`);
161
+ if (p.roles !== 'public') why.push(`TO ${p.roles}`);
162
+ if (policyForm(p.qual) !== expr) why.push('its USING is not the package\'s policy text');
163
+ if (policyForm(p.with_check) !== expr) why.push('its WITH CHECK is not the package\'s policy text');
164
+ if (why.length) problems.push(`${at}: ${t.name}: policy ${p.name}: ${why.join('; ')}`);
165
+ }
166
+ }
167
+ }
168
+ for (const a of want.anchors) {
169
+ if (!present.has(a.name)) { problems.push(`${at}: anchor ${a.name}: missing table`); continue; }
170
+ compared.anchors++;
171
+ const have = await readTable(driver, d, a.name);
172
+ for (const c of a.columns) {
173
+ compared.columns++;
174
+ const h = have.columns.find((x) => x.name === c.name);
175
+ if (!h) { problems.push(`${at}: anchor ${a.name}.${c.name}: missing column`); continue; }
176
+ if (h.type !== c.type) problems.push(`${at}: anchor ${a.name}.${c.name}: type ${h.type}, the set requires ${c.type}`);
177
+ if (c.notNull && !h.notNull && !(h.pk > 0)) problems.push(`${at}: anchor ${a.name}.${c.name}: nullable, the set requires NOT NULL`);
178
+ }
179
+ const sets_ = [
180
+ have.columns.filter((c) => c.pk > 0).map((c) => c.name),
181
+ ...have.indexes.filter((x) => x.unique && !x.partial).map((x) => x.columns)
182
+ ].filter((s) => s.length).map((s) => [...s].sort().join(','));
183
+ for (const u of a.unique) {
184
+ compared.keys++;
185
+ if (!sets_.includes([...u].sort().join(','))) problems.push(`${at}: anchor ${a.name}: no unique key on ${list(u)}`);
186
+ }
187
+ }
188
+ }
189
+ return { problems, compared };
190
+ }
191
+
192
+ /** For boot: checkDefinedSchema, and throw (naming every problem) unless there is none. */
193
+ async function assertDefinedSchema(driver, sets, opts = {}) {
194
+ const r = await checkDefinedSchema(driver, sets, opts);
195
+ if (r.problems.length) {
196
+ const e = new Error(`the database does not hold the tables its table definitions require — refusing to start:\n ${r.problems.join('\n ')}`);
197
+ e.code = 'TABLE_DEFINITIONS_MISMATCH';
198
+ e.problems = r.problems;
199
+ throw e;
200
+ }
201
+ return r;
202
+ }
203
+
204
+ module.exports = { checkDefinedSchema, assertDefinedSchema, policyForm };
@@ -12,6 +12,14 @@
12
12
  * aria-tenancy check
13
13
  * exit 1 unless every scoped table created after the app's frozen migrations carries EXACTLY the generator's
14
14
  * statements, and every key in those migrations keeps the tenant columns intact. Read-only.
15
+ * aria-tenancy new --definitions <set> [--name <slug>] [--number <NNN>]
16
+ * 0.31.0 — writes a NEW pair for a package's table definition set (tableDefinitions.js) that the manifest
17
+ * carries (TABLE_DEFINITIONS, from tenancyFragment): every CREATE TABLE whole from the set, by the SAME table
18
+ * writer as the skeleton (tableSql) and the same render(). check then holds such a pair (its first line names
19
+ * the set, its version and the LAYOUT that wrote it — DEFINED_HEAD) WHOLE, header line included, and BYTE FOR
20
+ * BYTE (CRLF read as LF) to that layout's output for the set the manifest carries — safe because a layout's
21
+ * inputs are frozen (LAYOUTS below) — and requires each carried set to be generated by exactly one pair, at that
22
+ * version. A FROZEN file naming the set (on any line: a squash keeps it) counts as its pair and is not compared.
15
23
  *
16
24
  * WHAT THE APP PASSES: `aria.tenancy.json` beside its package.json (loadConfig below) — where its manifest is (built with
17
25
  * defineTenancy), its migrations folder, its frozen file list, its principal table. Nothing else of the app is loaded,
@@ -25,7 +33,7 @@
25
33
  * the policy at the end of the same file, a plain-SQLite twin beside it (one tenant there, no policies).
26
34
  *
27
35
  * ── 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):
36
+ * Decided by the manifest alone (PARTNER, and an optional CUSTOMER map):
29
37
  * Postgres the partner_id column definition, inside the CREATE TABLE — compared WHITESPACE-NORMALISED, the one
30
38
  * comparison that is not byte for byte (a hand-typed migration may wrap it; same tokens);
31
39
  * and, byte for byte as whole statements (CRLF read as LF):
@@ -34,7 +42,8 @@
34
42
  * ALTER TABLE <t> FORCE ROW LEVEL SECURITY;
35
43
  * CREATE POLICY tenant_isolation ON <t> FOR ALL USING (…) WITH CHECK (…);
36
44
  * 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.
45
+ * table's is the package's CUSTOMER_POLICY_EXPRESSION(column) (0.30.0; a manifest's own function is
46
+ * accepted only when it produces the same text, and refused otherwise).
38
47
  * SQLite the partner_id column definition (normalised as above). The skeleton writes the partner index there
39
48
  * too, but check does not hold it: on SQLite — one tenant, no policies — it is an index, not tenancy.
40
49
  * The skeleton also writes, for a CUSTOMER table, the customer column, the composite target UNIQUE (id, <col>,
@@ -116,7 +125,8 @@
116
125
  const fs = require('fs');
117
126
  const path = require('path');
118
127
  const { selectForDialect } = require('./database');
119
- const { TENANCY_POLICY_EXPRESSION } = require('./tenancyManifest');
128
+ const { TENANCY_POLICY_EXPRESSION, CUSTOMER_POLICY_EXPRESSION, assertSameCustomerPolicy } = require('./tenancyManifest');
129
+ const defs = require('./tableDefinitions');
120
130
 
121
131
  /** The Postgres partner_id definition, in the type the app states (aria.tenancy.json "partnerIdType"). */
122
132
  const PARTNER_ID_TYPES = ['BIGINT', 'INTEGER'];
@@ -229,6 +239,10 @@ function checkManifest(manifest, name = 'the manifest') {
229
239
  if (has(manifest, 'POLICY_EXPRESSION') && manifest.POLICY_EXPRESSION !== TENANCY_POLICY_EXPRESSION) {
230
240
  throw new Error(`${name}: its POLICY_EXPRESSION is not the frozen TENANCY_POLICY_EXPRESSION — the policy every applied migration carries`);
231
241
  }
242
+ // 0.30.0 — a manifest's own customer policy function must produce the package's text (assertSameCustomerPolicy).
243
+ if (has(manifest, 'CUSTOMER_POLICY_EXPRESSION') && manifest.CUSTOMER_POLICY_EXPRESSION !== CUSTOMER_POLICY_EXPRESSION) {
244
+ assertSameCustomerPolicy(manifest.CUSTOMER_POLICY_EXPRESSION, manifest.CUSTOMER, name);
245
+ }
232
246
  }
233
247
 
234
248
  // ── RENDERING ───────────────────────────────────────────────────────────────────────────────────────────────────
@@ -238,10 +252,11 @@ function policyExpression(manifest, table) {
238
252
  const col = (manifest.CUSTOMER || {})[table];
239
253
  let raw = TENANCY_POLICY_EXPRESSION;
240
254
  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)`);
255
+ // 0.30.0 — the package's text. A manifest still carrying its own function must produce the same text.
256
+ if (has(manifest, 'CUSTOMER_POLICY_EXPRESSION') && manifest.CUSTOMER_POLICY_EXPRESSION !== CUSTOMER_POLICY_EXPRESSION) {
257
+ assertSameCustomerPolicy(manifest.CUSTOMER_POLICY_EXPRESSION, manifest.CUSTOMER, 'the manifest');
243
258
  }
244
- raw = manifest.CUSTOMER_POLICY_EXPRESSION(col);
259
+ raw = CUSTOMER_POLICY_EXPRESSION(col);
245
260
  }
246
261
  // The rendering assumes the frozen layout; if that ever changes, refuse rather than emit a policy re-indented
247
262
  // into something check would then call "the generator's".
@@ -286,7 +301,7 @@ function render(manifest, table, opts = {}) {
286
301
  customerColumn,
287
302
  pgPartnerId: pgDef,
288
303
  sqlitePartnerId: SQLITE_PARTNER_ID,
289
- index: `CREATE INDEX idx_${table}_partner ON ${table}(partner_id);`,
304
+ index: `CREATE INDEX ${defs.tenancyNames(table, customerColumn).partnerIndex} ON ${table}(partner_id);`,
290
305
  rls: [
291
306
  `ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;`,
292
307
  `ALTER TABLE ${table} FORCE ROW LEVEL SECURITY;`,
@@ -795,7 +810,16 @@ function checkTree({ files, manifest, frozen, partnerIdType, principalTable = 'u
795
810
  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
811
  }
797
812
 
798
- return { problems, stats: { tables: A, created: B, preExisting, statementsCompared: compared, keysChecked, pgKeys: pgKeyList.length, pgKeyList, files: post.length } };
813
+ const stats = { tables: A, created: B, preExisting, statementsCompared: compared, keysChecked, pgKeys: pgKeyList.length, pgKeyList, files: post.length };
814
+ // 0.31.0 — pairs generated from a package's table definitions, held byte for byte. Only a manifest that carries sets,
815
+ // or a tree with a file that names one, gets this section (and the stats key): for any other, check is as before.
816
+ if (has(manifest, 'TABLE_DEFINITIONS') || post.some((f) => DEFINED_HEAD.test(firstLine(files[f])))) {
817
+ const d = checkDefinitionFiles(files, manifest, post, frozen, { partnerIdType, manifestName, preExisting, principalTable });
818
+ problems.push(...d.problems);
819
+ stats.definitionFiles = d.compared;
820
+ stats.definitionFilesFrozen = d.frozen;
821
+ }
822
+ return { problems, stats };
799
823
  }
800
824
 
801
825
  /** A view's WITH (…) options turn security_invoker on (bare, = true or = on) and nothing turns it off. */
@@ -825,6 +849,42 @@ function compareKeys(expected, rows, postTables) {
825
849
 
826
850
  // ── THE SKELETON ────────────────────────────────────────────────────────────────────────────────────────────────
827
851
 
852
+ const pad = (s) => s.padEnd(13) + ' ';
853
+
854
+ /**
855
+ * ONE TABLE'S CREATE TABLE and its generated indexes, as the skeleton writes it: the generated id, partner_id and
856
+ * customer column, the marker, then `own` (0.31.0: a definition's columns after the marker and its constraints after
857
+ * created_at — tableDefinitions.js renders them), then created_at, the generated unique key and the key to customers,
858
+ * the partner index and the customer index. Without `own` it is the skeleton's table, byte for byte as before.
859
+ */
860
+ function tableSql(g, dialect, own = null) {
861
+ const lines = [
862
+ `CREATE TABLE ${g.table} (`,
863
+ ` ${pad('id')}${dialect === 'pg' ? 'BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY' : 'INTEGER PRIMARY KEY AUTOINCREMENT'},`,
864
+ ` ${pad('partner_id')}${dialect === 'pg' ? g.pgPartnerId : g.sqlitePartnerId},`
865
+ ];
866
+ if (g.customerColumn) lines.push(` ${pad(g.customerColumn)}TEXT NOT NULL,`);
867
+ lines.push(' -- ── this table\'s own columns and keys ──');
868
+ if (own) for (const c of own.columns) lines.push(` ${pad(c.name)}${defs.columnSql(c, dialect)},`);
869
+ const ts = defs.UTC_NOW[dialect === 'pg' ? 'postgres' : 'sqlite'];
870
+ const tail = [` ${pad('created_at')}TEXT NOT NULL DEFAULT ${ts}`];
871
+ if (own) for (const k of own.constraints) tail.push(` ${defs.constraintSql(k)}`);
872
+ const n = defs.tenancyNames(g.table, g.customerColumn);
873
+ if (g.customerColumn) {
874
+ tail.push(` CONSTRAINT ${n.unique} UNIQUE (id, ${g.customerColumn}, partner_id)`);
875
+ tail.push(` CONSTRAINT ${n.customerKey} FOREIGN KEY (${g.customerColumn}, partner_id)\n`
876
+ + ' REFERENCES customers (id, partner_id) ON DELETE CASCADE ON UPDATE CASCADE');
877
+ } else {
878
+ tail.push(` CONSTRAINT ${n.unique} UNIQUE (id, partner_id)`);
879
+ }
880
+ lines.push(tail.join(',\n'), ');', g.index);
881
+ if (g.customerColumn) lines.push(`CREATE INDEX ${n.customerIndex} ON ${g.table}(${g.customerColumn}, partner_id);`);
882
+ return lines.join('\n');
883
+ }
884
+
885
+ /** The Postgres file's closing section: its heading, then each table's ENABLE, FORCE and policy. */
886
+ const rlsSection = (gens, heading) => [heading, '', gens.map((g) => g.rls.join('\n')).join('\n\n'), ''];
887
+
828
888
  /** The new pair's text: `{ pg, lite }`. `opts`: { preExisting, manifestName } as for render. */
829
889
  function skeleton(manifest, tables, base, opts = {}) {
830
890
  const manifestName = opts.manifestName || 'the manifest';
@@ -832,7 +892,6 @@ function skeleton(manifest, tables, base, opts = {}) {
832
892
  for (const g of gens) {
833
893
  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
894
  }
835
- const pad = (s) => s.padEnd(13) + ' ';
836
895
  const head = (dialect) => [
837
896
  `-- ${base}${dialect === 'pg' ? '.postgres' : ''}.sql — GENERATED SKELETON (aria-tenancy new ${tables.join(' ')}).`,
838
897
  '--',
@@ -851,32 +910,183 @@ function skeleton(manifest, tables, base, opts = {}) {
851
910
  : []),
852
911
  ''
853
912
  ];
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},`
913
+ const pg = [...head('pg'), gens.map((g) => tableSql(g, 'pg')).join('\n\n'), '',
914
+ ...rlsSection(gens, `-- ── ROW-LEVEL SECURITY (generated from ${manifestName}) ──`)].join('\n');
915
+ const lite = [...head('sqlite'), gens.map((g) => tableSql(g, 'sqlite')).join('\n\n'), ''].join('\n');
916
+ return { pg, lite };
917
+ }
918
+
919
+ // ── 0.31.0: A PACKAGE'S TABLE DEFINITIONS, WRITTEN INTO THE APP'S OWN MIGRATION ─────────────────────────────────────
920
+
921
+ /**
922
+ * The first line of a pair generated from a definition set: what check and new recognise it by. It names the file,
923
+ * the set, its version and the LAYOUT that wrote it. Groups: 1 base, 2 ".postgres", 3 set, 4 version, 5 layout, 6 set.
924
+ */
925
+ const DEFINED_HEAD = /^-- (\S+?)(\.postgres)?\.sql — GENERATED from the table definitions ([a-z][a-z0-9_]*) (\d+\.\d+\.\d+), layout (\d+) \(aria-tenancy new --definitions ([a-z][a-z0-9_]*)\)\.$/;
926
+
927
+ /** The definition sets a manifest carries (TABLE_DEFINITIONS, from tenancyFragment), each validated. */
928
+ function definitionSets(manifest, name = 'the manifest') {
929
+ if (!has(manifest, 'TABLE_DEFINITIONS')) return [];
930
+ const sets = manifest.TABLE_DEFINITIONS;
931
+ if (!Array.isArray(sets)) throw new Error(`${name}: TABLE_DEFINITIONS is what tenancyFragment(...sets) gives`);
932
+ sets.forEach((s, i) => defs.assertTableDefinitions(s, `${name}: TABLE_DEFINITIONS[${i}]`));
933
+ return sets;
934
+ }
935
+
936
+ /**
937
+ * ── THE LAYOUTS OF A DEFINITIONS FILE — FROZEN ──────────────────────────────────────────────────────────────────
938
+ * A definitions file is applied by apps and never edited, and check compares it WHOLE, byte for byte, with what the
939
+ * layout named in its first line writes. So a layout's output may never change. Its text is a function of ONLY:
940
+ * - the set (name, version, tables, indexes, anchors, comment) — a set changed in any part, its comment included,
941
+ * is a new version of the set;
942
+ * - the frozen policy texts (TENANCY_POLICY_EXPRESSION, CUSTOMER_POLICY_EXPRESSION);
943
+ * - the app's partnerIdType (the Postgres type of partner_id — the one tenancy parameter that differs per app);
944
+ * - the file's own base name (NNN_slug), fixed when it is written;
945
+ * - the layout number.
946
+ * NOT of the manifest's path, the app's folders, the date, or anything else about where or when it runs. (The manifest
947
+ * must classify each table as the set does; render() refuses otherwise, so it changes nothing in the text.)
948
+ * Layout 1 writes with tableSql, columnSql / constraintSql / indexSql, UTC_NOW, render() and tenancyNames — shared with
949
+ * the skeleton, and pinned by sha256 in test/tableDefinitions.js. ANY change that alters layout 1's output (a skeleton
950
+ * fix included) must instead: copy the current writers into a frozen layout-1 function, add the change as layout 2,
951
+ * and make CURRENT_LAYOUT 2 — old files keep being checked by layout 1, selected by the number in their first line.
952
+ */
953
+ const LAYOUTS = Object.freeze({
954
+ 1: function layout1(set, gens, base) {
955
+ const own = Object.fromEntries(set.tables.map((t) => [t.name, t]));
956
+ const head = (dialect) => [
957
+ `-- ${base}${dialect === 'pg' ? '.postgres' : ''}.sql — GENERATED from the table definitions ${set.name} ${set.version}, layout 1 (aria-tenancy new --definitions ${set.name}).`,
958
+ '--',
959
+ `-- Every statement below is the generator's: the tables as ${set.name} ${set.version} defines them, and their TENANCY`,
960
+ dialect === 'pg'
961
+ ? '-- (the partner_id column, the partner index, and the row-level-security section at the end).'
962
+ : '-- (the partner_id column and the partner index; no policies on SQLite, one tenant there).',
963
+ '-- `aria-tenancy check` holds this file to layout 1 of the generator byte for byte: never edit it. The package\'s',
964
+ `-- schema check compares the database with ${set.name} ${set.version} when the app starts.`,
965
+ ...(set.comment.length ? ['--', ...set.comment.map((l) => (l ? `-- ${l}` : '--'))] : []),
966
+ ''
859
967
  ];
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)`);
968
+ const body = (dialect) => gens.map((g) => tableSql(g, dialect, own[g.table])).join('\n\n')
969
+ + set.indexes.map((x) => `\n${defs.indexSql(x)}`).join('');
970
+ const pg = [...head('pg'), body('pg'), '', ...rlsSection(gens, '-- ── ROW-LEVEL SECURITY (generated) ──')].join('\n');
971
+ const lite = [...head('sqlite'), body('sqlite'), ''].join('\n');
972
+ return { pg, lite };
973
+ }
974
+ });
975
+ /** The layout new files are written with. */
976
+ const CURRENT_LAYOUT = 1;
977
+
978
+ /**
979
+ * A definition set's migration pair: `{ pg, lite }`, by `layout` (default CURRENT_LAYOUT). Every CREATE TABLE body is
980
+ * the set's, written by tableSql — the skeleton's own writer — and the tenancy is render()'s, so a defined table's
981
+ * partner_id, indexes, ENABLE, FORCE and policy are the very statements a hand-filled skeleton carries and check holds.
982
+ * Refused: a manifest that classifies a table differently from the set (render also refuses an unclassified,
983
+ * platform, nullable or pre-existing one), and an anchor that is the app's principal table (opts.principalTable).
984
+ * `opts` as for render: { partnerIdType, manifestName, preExisting, principalTable } — only partnerIdType reaches the text.
985
+ */
986
+ function renderDefinitions(manifest, set, base, opts = {}, layout = CURRENT_LAYOUT) {
987
+ defs.assertTableDefinitions(set);
988
+ if (typeof base !== 'string' || !/^[^/\\\s]+$/.test(base)) throw new Error(`renderDefinitions: base ${JSON.stringify(base)} is not a migration name`);
989
+ if (!has(LAYOUTS, layout)) throw new Error(`renderDefinitions: no layout ${layout} (this db-worker has ${Object.keys(LAYOUTS).join(', ')})`);
990
+ const manifestName = opts.manifestName || 'the manifest';
991
+ const principal = opts.principalTable || 'users';
992
+ if (has(set.anchors, principal)) {
993
+ throw new Error(`${set.name} ${set.version}: its anchor ${principal} is the app's principal table — a key into it is attribution; a set names a user in a plain column with no key`);
994
+ }
995
+ const gens = set.tables.map((t) => {
996
+ const g = render(manifest, t.name, opts);
997
+ if ((g.customerColumn || null) !== (t.customer || null)) {
998
+ throw new Error(`${t.name}: ${manifestName} classifies it ${g.customerColumn ? `as a CUSTOMER table (${g.customerColumn})` : 'as PARTNER only'}, `
999
+ + `but ${set.name} ${set.version} defines it ${t.customer ? `as a CUSTOMER table (${t.customer})` : 'as PARTNER only'}`);
870
1000
  }
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 };
1001
+ return g;
1002
+ });
1003
+ return LAYOUTS[layout](set, gens, base);
1004
+ }
1005
+
1006
+ /**
1007
+ * Where each set is named: policed files by their FIRST line (and that line must name the file itself); frozen files
1008
+ * by ANY line (a squashed baseline keeps the generated pair's first line as a line of its own).
1009
+ * A FROZEN FILE CARRYING THE GENERATED FIRST LINE IS COUNTED AS THE SET'S PAIR AND IS NOT COMPARED — so such a line
1010
+ * in a frozen file is believed. That is the trust model check already has for every frozen file: it never reads a
1011
+ * frozen file except to learn which tables it creates, because the app pins its frozen list (sha256) and reviews what
1012
+ * goes into it; a frozen file is the app's word, not the generator's to re-check.
1013
+ */
1014
+ function namedSets(files, post, frozen, problems) {
1015
+ const named = {};
1016
+ const add = (m, x) => (named[m[3]] = named[m[3]] || []).push({ ...x, version: m[4], layout: Number(m[5]), base: m[1], pg: !!m[2] });
1017
+ for (const f of post) {
1018
+ const first = firstLine(files[f]);
1019
+ const m = DEFINED_HEAD.exec(first);
1020
+ if (!m) continue;
1021
+ if (`${m[1]}${m[2] || ''}.sql` !== f || m[3] !== m[6]) { problems.push(`${f}: its first line names another file or set: ${first}`); continue; }
1022
+ add(m, { file: f, frozen: false });
1023
+ }
1024
+ for (const f of frozen) {
1025
+ if (!has(files, f)) continue;
1026
+ for (const line of files[f].replace(/\r\n/g, '\n').split('\n')) {
1027
+ const m = DEFINED_HEAD.exec(line);
1028
+ if (m && m[3] === m[6]) add(m, { file: f, frozen: true });
1029
+ }
1030
+ }
1031
+ return named;
1032
+ }
1033
+
1034
+ /**
1035
+ * check's half for definition sets: every policed pair whose first line names a set is held WHOLE, BYTE FOR BYTE (CRLF
1036
+ * read as LF), header included, to the layout its first line names, for the set the manifest carries; each set in
1037
+ * the manifest is generated by exactly one pair, at the version the manifest carries. A frozen file naming the set
1038
+ * counts as its pair and is not compared. → { problems, compared, frozen }.
1039
+ */
1040
+ function checkDefinitionFiles(files, manifest, post, frozen, opts) {
1041
+ const problems = [];
1042
+ let compared = 0;
1043
+ let frozenCount = 0;
1044
+ const sets = definitionSets(manifest, opts.manifestName);
1045
+ const named = namedSets(files, post, frozen, problems);
1046
+ for (const s of Object.keys(named)) {
1047
+ if (!sets.some((x) => x.name === s)) problems.push(`${[...new Set(named[s].map((x) => x.file))].join(', ')}: generated from the table definitions ${s}, which ${opts.manifestName} does not carry (TABLE_DEFINITIONS)`);
1048
+ }
1049
+ for (const set of sets) {
1050
+ const mine = named[set.name] || [];
1051
+ const pgs = mine.filter((x) => x.pg && !x.frozen);
1052
+ const fro = mine.filter((x) => x.frozen);
1053
+ const all = [...new Set([...pgs, ...fro].map((x) => x.file))];
1054
+ if (!all.length) { problems.push(`${set.name} ${set.version}: no migration is generated from it — run aria-tenancy new --definitions ${set.name}`); continue; }
1055
+ if (pgs.length > 1 || (pgs.length && fro.length)) { problems.push(`${set.name}: generated by more than one migration (${all.join(', ')}) — a set's tables are created once`); continue; }
1056
+ const p = pgs[0] || fro[0];
1057
+ if (p.version !== set.version) {
1058
+ problems.push(`${p.file}: generated from ${set.name} ${p.version}, but the manifest carries ${set.name} ${set.version} — a set is generated once; a changed version needs a migration of its own, which this generator does not write`);
1059
+ continue;
1060
+ }
1061
+ if (p.frozen) { frozenCount++; continue; }
1062
+ if (!has(LAYOUTS, p.layout)) { problems.push(`${p.file}: written by layout ${p.layout}, which this db-worker does not have (it has ${Object.keys(LAYOUTS).join(', ')})`); continue; }
1063
+ const want = renderDefinitions(manifest, set, p.base, opts, p.layout);
1064
+ for (const [file, text] of [[p.file, want.pg], [`${p.base}.sql`, want.lite]]) {
1065
+ if (!has(files, file)) { problems.push(`${set.name}: no ${file} beside ${p.file}`); continue; }
1066
+ compared++;
1067
+ const d = firstDifference(files[file].replace(/\r\n/g, '\n'), text);
1068
+ if (d) {
1069
+ problems.push(`${file}: is not layout ${p.layout} of the generator for ${set.name} ${set.version} — ${d}. An applied file is never edited: `
1070
+ + `restore it. If it is unedited, the set changed (its comment included) without a new version — a changed set needs a new version`);
1071
+ }
1072
+ }
1073
+ for (const x of mine.filter((y) => !y.pg && !y.frozen && y.base !== p.base)) problems.push(`${x.file}: names ${set.name} but is not ${p.base}.sql`);
1074
+ }
1075
+ return { problems, compared, frozen: frozenCount };
1076
+ }
1077
+
1078
+ /** The first line at which two texts differ, for a message; null when equal. Never the whole text. */
1079
+ function firstDifference(have, want) {
1080
+ if (have === want) return null;
1081
+ const a = have.split('\n');
1082
+ const b = want.split('\n');
1083
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
1084
+ if (a[i] !== b[i]) {
1085
+ const cut = (s) => (s === undefined ? '(no line)' : JSON.stringify(s.length > 120 ? s.slice(0, 120) + '…' : s));
1086
+ return `line ${i + 1} is ${cut(a[i])}, the generator's is ${cut(b[i])}`;
1087
+ }
1088
+ }
1089
+ return 'they differ';
880
1090
  }
881
1091
 
882
1092
  /** Every *.sql in a folder, by name. */
@@ -903,6 +1113,11 @@ const renderOptions = (config, preExisting) => ({
903
1113
  * number, a number not after every frozen file, and whatever render refuses. → { base, files: { name: text } }.
904
1114
  */
905
1115
  function planNew(config, manifest, tables, { name = null, number = null, fillGap = false } = {}) {
1116
+ return planPair(config, manifest, tables, { name, number, fillGap }, (base, opts) => skeleton(manifest, tables, base, opts));
1117
+ }
1118
+
1119
+ /** planNew's checks and numbering, around a writer of the pair's text: `write(base, opts)` → { pg, lite }. */
1120
+ function planPair(config, manifest, tables, { name = null, number = null, fillGap = false } = {}, write) {
906
1121
  if (!tables.length) throw new Error(`name at least one table (classified in ${config.manifestName} first)`);
907
1122
  if (new Set(tables).size !== tables.length) throw new Error('a table is named twice');
908
1123
  for (const t of tables) if (!/^[a-z][a-z0-9_]*$/.test(t)) throw new Error(`"${t}" is not a table name`);
@@ -931,10 +1146,38 @@ function planNew(config, manifest, tables, { name = null, number = null, fillGap
931
1146
  if (!/^[a-z][a-z0-9_]*$/.test(slug)) throw new Error(`--name "${slug}" is not a slug`);
932
1147
  const base = `${nnn}_${slug}`;
933
1148
  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);
1149
+ const { pg, lite } = write(base, opts);
935
1150
  return { base, files: { [`${base}.postgres.sql`]: pg, [`${base}.sql`]: lite } };
936
1151
  }
937
1152
 
1153
+ /**
1154
+ * 0.31.0 — plan the pair for the definition set named `setName` in the manifest's TABLE_DEFINITIONS (nothing is
1155
+ * written): planNew's refusals for its tables, plus a set some migration already names (it is generated once), and
1156
+ * then the tree WITH the new pair is checked: a pair that would fail `aria-tenancy check` (a key the app's
1157
+ * requireUpdateCascade refuses, a name an existing migration took) is refused before it is written. The slug defaults
1158
+ * to the set's name.
1159
+ */
1160
+ function planDefinitions(config, manifest, setName, { name = null, number = null, fillGap = false } = {}) {
1161
+ const sets = definitionSets(manifest, config.manifestName);
1162
+ const set = sets.find((s) => s.name === setName);
1163
+ if (!set) {
1164
+ throw new Error(`${config.manifestName} carries no table definitions named ${JSON.stringify(setName)} — spread tenancyFragment(set) into defineTenancy`
1165
+ + (sets.length ? ` (it carries ${sets.map((s) => s.name).join(', ')})` : ''));
1166
+ }
1167
+ const tree = readTree(config.migrationsDir);
1168
+ const named = namedSets(tree, Object.keys(tree).filter((f) => !config.frozen.includes(f)), config.frozen, []);
1169
+ for (const x of named[set.name] || []) throw new Error(`${x.file} is already generated from ${set.name} ${x.version} — a set's tables are created once`);
1170
+ const plan = planPair(config, manifest, set.tables.map((t) => t.name), { name: name || set.name, number, fillGap },
1171
+ (base, opts) => renderDefinitions(manifest, set, base, opts));
1172
+ const before = new Set(checkTree(checkOptions(config, manifest)).problems);
1173
+ const after = checkTree({ ...checkOptions(config, manifest), files: { ...tree, ...lfAll(plan.files) } }).problems.filter((p) => !before.has(p));
1174
+ if (after.length) throw new Error(`the generated pair would fail aria-tenancy check:\n ${after.join('\n ')}`);
1175
+ return plan;
1176
+ }
1177
+ const lfAll = (files) => Object.fromEntries(Object.entries(files).map(([k, v]) => [k, v.replace(/\r\n/g, '\n')]));
1178
+ /** A file's first line, CRLF read as LF. */
1179
+ const firstLine = (text) => text.replace(/\r\n/g, '\n').split('\n', 1)[0];
1180
+
938
1181
  /**
939
1182
  * Write a planned pair so that a failure cannot leave half of it: each file first to a temporary name in the same
940
1183
  * folder (not *.sql, so no runner ever reads it), then each LINKED to its name (a link refuses an existing file, so
@@ -959,6 +1202,7 @@ function writePair(dir, files, io = fs) {
959
1202
 
960
1203
  module.exports = {
961
1204
  CONFIG_FILE, loadConfig, loadManifest, render, skeleton, checkTree, checkOptions, renderOptions, planNew, writePair,
1205
+ renderDefinitions, planDefinitions, definitionSets, DEFINED_HEAD, CURRENT_LAYOUT, DEFINITION_LAYOUTS: Object.keys(LAYOUTS).map(Number),
962
1206
  splitStatements, keysIn, readTree, constraintNames, droppedCheck, compareKeys, createdByFrozen, pgPartnerId,
963
1207
  PARTNER_ID_TYPES, SQLITE_PARTNER_ID
964
1208
  };