@aria-framework/db-worker 0.30.0 → 0.31.1

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 };