@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,603 @@
1
+ /**
2
+ * 0.31.0 — TABLE DEFINITIONS AS DATA: how a package says which tables it needs in an app's database, without running
3
+ * SQL of its own. A package cannot apply a migration from node_modules (a second ledger, and an upgrade would change an
4
+ * applied file) and must not create tables at boot. So it ships a DEFINITION SET built with `defineTables`, and:
5
+ *
6
+ * 1. the app spreads `tenancyFragment(set)` into `defineTenancy`, which classifies the set's tables (PARTNER, and
7
+ * CUSTOMER with the customer column) and refuses a manifest that classifies one of them differently;
8
+ * 2. `aria-tenancy new --definitions <set name>` writes the set into the app's OWN migration pair (tenancyGenerator.js
9
+ * renderDefinitions): the whole CREATE TABLE bodies from the set, the tenancy by the same code that writes a
10
+ * skeleton. The pair is committed in the app and never edited; `aria-tenancy check` holds it to the generator
11
+ * byte for byte;
12
+ * 3. the package calls `checkDefinedSchema` (tableDefinitionsCheck.js) when the app starts, and refuses to start on a
13
+ * difference between the database and the set;
14
+ * 4. the set names the columns and keys it needs of tables it does NOT define (`anchors`: the app's `customers`,
15
+ * `customer_contacts`), and the schema check verifies them.
16
+ *
17
+ * THE FORMAT (a plain object; `defineTables` validates it, freezes a deep copy and returns that):
18
+ *
19
+ * {
20
+ * name: 'access', // a slug: the migration's default name, and what its header names
21
+ * version: '1.0.0', // x.y.z, named in the migration's header
22
+ * comment: ['line', '', 'line'], // optional: the migration's comment block, one entry per line ('' = "--")
23
+ * anchors: { // optional: tables the app owns that this set relies on, with their
24
+ * // tenancy: 'PARTNER' or { customer: <column> } (customers: { customer: 'id' })
25
+ * customers: { tenancy: { customer: 'id' }, columns: [{ name: 'id', type: 'TEXT', notNull: true },
26
+ * { name: 'partner_id', type: 'PARTNER_ID', notNull: true }],
27
+ * unique: [['id', 'partner_id']] }
28
+ * },
29
+ * tables: [{
30
+ * name: 'grants', description: 'one sentence (the manifest reason)',
31
+ * tenancy: 'PARTNER' | { customer: 'customer_id' },
32
+ * columns: [{ name, type: 'TEXT' | 'INTEGER' | 'BIGINT' | { postgres, sqlite }, notNull?, default?, check? }],
33
+ * constraints: [{ name, check } | { name, unique: [cols] }
34
+ * | { name, foreignKey: { columns, references: { table, columns }, onDelete?, onUpdate? } }]
35
+ * }],
36
+ * indexes: [{ name, table, columns, unique?, where? }] // in the order the migration carries them
37
+ * }
38
+ *
39
+ * WHAT THE GENERATOR ADDS, ALWAYS (the skeleton's part, not the set's — so a set may not name these columns):
40
+ * `id` (BIGINT identity / INTEGER AUTOINCREMENT, the primary key), `partner_id` (the app's stated type, from the
41
+ * session), the customer column of a CUSTOMER table (TEXT NOT NULL), `created_at` (UTC text), UNIQUE (id, partner_id)
42
+ * or UNIQUE (id, <customer column>, partner_id), a CUSTOMER table's key to customers (id, partner_id) ON DELETE
43
+ * CASCADE ON UPDATE CASCADE, the partner and customer indexes, and on Postgres ENABLE, FORCE and the frozen policy.
44
+ *
45
+ * WHAT IT CANNOT EXPRESS (refused, not approximated): a primary key other than `id`; a table without `created_at`; a
46
+ * column type other than TEXT / INTEGER / BIGINT; a default other than a text literal, a whole number or the UTC time;
47
+ * ON DELETE / ON UPDATE SET NULL or SET DEFAULT (SET DEFAULT re-parents a row into another tenant, a bare SET NULL
48
+ * nulls partner_id, and SQLite cannot render SET NULL (column)); a key into a table that is neither in the set nor
49
+ * an anchor (and no anchor named users: a user is a plain column); a key into a scoped table without partner_id at
50
+ * the same position on both sides; a unique key or unique index without partner_id; a PARTNER-only table with a
51
+ * customer column or a key into customers; a reserved word of either engine as a name; a table name that makes a
52
+ * generated name longer than 63 bytes; an expression using anything but the table's own columns, the operators
53
+ * in OPERATORS, string and whole-number literals (each set apart: no e'…', 1e5), AND / OR / NOT / IN / IS / NULL /
54
+ * BETWEEN / LIKE / TRUE / FALSE and length / lower / upper; a PARTNER_NULLABLE table; ALTERs of tables that already
55
+ * exist (a set is created once: there is no upgrade yet).
56
+ */
57
+ 'use strict';
58
+
59
+ /** Why a definition is refused: every `refuse(code, …)` below names one of these. */
60
+ const REFUSALS = Object.freeze({
61
+ 'set-shape': 'the set is not an object of the known keys, or lacks name, version or tables',
62
+ 'set-name': 'the set name is not a slug (a lower-case letter, then letters, digits, _)',
63
+ 'set-version': 'the version is not x.y.z',
64
+ comment: 'the comment is not a list of single-line strings',
65
+ 'table-shape': 'a table is not an object of the known keys, or lacks name, description, tenancy or columns',
66
+ identifier: 'a name is not a plain lower-case identifier of at most 63 characters',
67
+ 'name-taken': 'a name is used twice, or is one the generator writes',
68
+ 'reserved-column': 'a column the generator writes itself (id, partner_id, the customer column, created_at)',
69
+ tenancy: 'the tenancy is not PARTNER or { customer: <column> } (and the column is not id)',
70
+ 'column-shape': 'a column is not an object of the known keys, or notNull is not true / false',
71
+ 'column-type': 'a type the generator cannot render on both engines',
72
+ default: 'a default that is not a text literal, a whole number or the UTC time, or that does not fit the type',
73
+ expression: 'an expression (a CHECK or an index WHERE) the generator cannot render exactly',
74
+ 'expression-name': 'an expression naming something that is not a column of its table, a keyword or a known function',
75
+ 'constraint-shape': 'a constraint that is not exactly one of check, unique, foreignKey with a name',
76
+ 'unique-columns': 'a key or index naming no column, an unknown column, or one column twice',
77
+ 'key-target': 'a key into a table that is neither in the set nor an anchor, or into columns the target does not declare',
78
+ 'key-partner': 'a key whose two sides differ in length, or that does not carry partner_id at the same position',
79
+ 'key-parent-unique': 'a key into columns that are not a unique key of its target',
80
+ 'key-action': 'an ON DELETE / ON UPDATE action other than NO ACTION, RESTRICT, CASCADE',
81
+ 'index-shape': 'an index that is not an object of the known keys, or on a table not in the set',
82
+ anchor: 'an anchor that is not { columns, unique } with partner_id, or that shares a name with a set table',
83
+ 'anchor-missing': 'a CUSTOMER table, but no anchor customers with id, partner_id and the key (id, partner_id)',
84
+ // 0.31.0 review round
85
+ 'reserved-word': 'a name that is a reserved word of PostgreSQL or SQLite (RESERVED below)',
86
+ 'name-length': 'a table whose name makes a name the generator writes (an index, a key) longer than 63 bytes, which PostgreSQL would truncate',
87
+ 'unique-partner': 'a unique key or unique index without partner_id (one partner\'s rows would block, and reveal, another\'s)',
88
+ 'partner-customer': 'a PARTNER-only table with a customer column, or with a key into the customers anchor (its one-arm policy would show a pinned customer every customer\'s rows)'
89
+ });
90
+
91
+ class TableDefinitionError extends Error {
92
+ constructor(refusal, message) {
93
+ super(`table definitions: ${message}`);
94
+ this.code = 'TABLE_DEFINITION_REFUSED';
95
+ this.refusal = refusal;
96
+ }
97
+ }
98
+ function refuse(code, message) {
99
+ if (!Object.prototype.hasOwnProperty.call(REFUSALS, code)) throw new Error(`internal: unknown refusal ${code}`);
100
+ throw new TableDefinitionError(code, message);
101
+ }
102
+
103
+ const has = (o, k) => o != null && Object.prototype.hasOwnProperty.call(o, k);
104
+ const isMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
105
+ const IDENT = /^[a-z_][a-z0-9_]*$/;
106
+ const SLUG = /^[a-z][a-z0-9_]*$/;
107
+ const TYPES = ['TEXT', 'INTEGER', 'BIGINT'];
108
+ const ACTIONS = ['NO ACTION', 'RESTRICT', 'CASCADE'];
109
+ const KEYWORDS = new Set(['and', 'or', 'not', 'in', 'is', 'null', 'between', 'like', 'true', 'false']);
110
+ const FUNCTIONS = new Set(['length', 'lower', 'upper']);
111
+ /** The keywords after which a parenthesis is a list or grouping (IN (…), NOT (…), … OR (…), BETWEEN (…)), never a call. */
112
+ const BEFORE_PAREN = new Set(['in', 'and', 'or', 'not', 'between']);
113
+ /** Every operator an expression may use, matched against the WHOLE run of operator characters (so `<<`, `==`, `|/`, `=-` are refused). */
114
+ const OPERATORS = new Set(['=', '<>', '!=', '<', '>', '<=', '>=', '+', '-', '*', '/', '%', '||']);
115
+
116
+ /**
117
+ * Names refused as identifiers: the UNION of PostgreSQL's reserved key words (the "reserved" and "reserved (can be
118
+ * function or type)" entries of the PostgreSQL documentation, Appendix C "SQL Key Words") and every SQLite keyword
119
+ * (sqlite.org/lang_keywords.html, all of them, including those SQLite would accept as a name) — erring towards refusing.
120
+ */
121
+ const RESERVED = new Set(`all analyse analyze and any array as asc asymmetric authorization binary both case cast check collate
122
+ collation column concurrently constraint create cross current_catalog current_date current_role current_schema current_time
123
+ current_timestamp current_user default deferrable desc distinct do else end except false fetch for foreign freeze from full
124
+ grant group having ilike in initially inner intersect into is isnull join lateral leading left like limit localtime
125
+ localtimestamp natural not notnull null offset on only or order outer overlaps placing primary references returning right
126
+ select session_user similar some symmetric system_user table tablesample then to trailing true union unique user using
127
+ variadic verbose when where window with
128
+ abort action add after alter always attach autoincrement before begin between by cascade commit conflict current database
129
+ deferred delete detach drop each escape exclude exclusive exists explain fail filter first following generated glob groups
130
+ if ignore immediate index indexed insert instead key last match materialized no nothing nulls of others over partition
131
+ plan pragma preceding query raise range recursive regexp reindex release rename replace restrict rollback row rows
132
+ savepoint set temp temporary ties transaction trigger unbounded update vacuum values view virtual without`.split(/\s+/));
133
+
134
+ /**
135
+ * THE NAMES THE GENERATOR WRITES for a table — the one definition: tenancyGenerator.js writes skeleton and definition
136
+ * tables with these, defineTables measures them, and the schema check expects them.
137
+ */
138
+ function tenancyNames(table, customer) {
139
+ return {
140
+ unique: customer ? `uq_${table}_id_customer_partner` : `uq_${table}_id_partner`,
141
+ customerKey: customer ? `fk_${table}_${customer}_partner` : null,
142
+ partnerIndex: `idx_${table}_partner`,
143
+ customerIndex: customer ? `idx_${table}_customer` : null
144
+ };
145
+ }
146
+
147
+ /** The UTC time as each engine writes it: the skeleton's created_at default, and `default: { utcNow: true }`. */
148
+ const UTC_NOW = Object.freeze({
149
+ postgres: "to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')",
150
+ sqlite: "(datetime('now'))"
151
+ });
152
+
153
+ function name(v, where) {
154
+ if (typeof v !== 'string' || !IDENT.test(v) || v.length > 63) refuse('identifier', `${where}: ${JSON.stringify(v)} is not a plain identifier`);
155
+ if (RESERVED.has(v)) refuse('reserved-word', `${where}: ${v} is a reserved word of PostgreSQL or SQLite`);
156
+ return v;
157
+ }
158
+ function keys(o, allowed, code, where) {
159
+ const bad = Object.keys(o).filter((k) => !allowed.includes(k));
160
+ if (bad.length) refuse(code, `${where}: unknown key(s) ${bad.join(', ')} (the keys are ${allowed.join(', ')})`);
161
+ }
162
+ /** A list of distinct column names, each one of `known`. */
163
+ function columnList(list, known, where) {
164
+ if (!Array.isArray(list) || !list.length) refuse('unique-columns', `${where}: names no column`);
165
+ for (const c of list) {
166
+ name(c, where);
167
+ if (!known.includes(c)) refuse('unique-columns', `${where}: ${c} is not a column of it`);
168
+ }
169
+ if (new Set(list).size !== list.length) refuse('unique-columns', `${where}: names a column twice`);
170
+ return [...list];
171
+ }
172
+
173
+ /**
174
+ * Read an expression (a CHECK or an index WHERE) token by token, refusing anything outside the small grammar the
175
+ * generator can render identically on both engines. Returns it unchanged.
176
+ */
177
+ function expression(text, columns, where) {
178
+ if (typeof text !== 'string' || !text.trim() || text !== text.trim()) refuse('expression', `${where}: an expression is a non-empty string without leading or trailing space`);
179
+ let depth = 0;
180
+ let i = 0;
181
+ let afterString = false; // the last token was a string literal (spaces do not end that)
182
+ while (i < text.length) {
183
+ const c = text[i];
184
+ if (c === ' ') { i++; continue; }
185
+ const wasString = afterString;
186
+ afterString = false;
187
+ if (c === "'") {
188
+ // 'a' 'b' is one literal on PostgreSQL across a newline and an error otherwise; SQLite refuses it: refused here
189
+ if (wasString) refuse('expression', `${where}: two string literals side by side`);
190
+ afterString = true;
191
+ let j = i + 1;
192
+ for (;;) {
193
+ if (j >= text.length) refuse('expression', `${where}: an unterminated string`);
194
+ if (text[j] === "'") { if (text[j + 1] === "'") { j += 2; continue; } break; }
195
+ if (/[\x00-\x1f\x7f]/.test(text[j])) refuse('expression', `${where}: a control character in a string`);
196
+ j++;
197
+ }
198
+ i = j + 1; continue;
199
+ }
200
+ const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(text.slice(i));
201
+ if (word) {
202
+ const w = word[0];
203
+ const next = text[i + w.length];
204
+ // a word glued to a quote is a prefixed literal on PostgreSQL (e'…' escapes, x'…', b'…', n'…'): refused
205
+ if (next === "'") refuse('expression', `${where}: ${w}' — a word directly before a quote (a prefixed literal on PostgreSQL)`);
206
+ const call = /^\s*\(/.test(text.slice(i + w.length));
207
+ const kw = KEYWORDS.has(w.toLowerCase());
208
+ if (call) {
209
+ // a parenthesis after a word: a call of an allowed function, or a list / grouping after IN, AND, OR, NOT, BETWEEN
210
+ if (kw ? !BEFORE_PAREN.has(w.toLowerCase()) : !FUNCTIONS.has(w)) refuse('expression-name', `${where}: ${w}( is not one of the functions ${[...FUNCTIONS].join(', ')}`);
211
+ } else if (!kw && !columns.includes(w)) refuse('expression-name', `${where}: ${w} is not a column of its table`);
212
+ i += w.length; continue;
213
+ }
214
+ const num = /^[0-9]+/.exec(text.slice(i));
215
+ if (num) {
216
+ const next = text[i + num[0].length];
217
+ // 1e5 is a number on PostgreSQL; 1'x' is not what it looks like: a number is followed by a separator
218
+ if (next !== undefined && /[A-Za-z_'.]/.test(next)) refuse('expression', `${where}: ${num[0]}${next} — a number directly before a letter, a point or a quote`);
219
+ i += num[0].length; continue;
220
+ }
221
+ if (text.startsWith('--', i) || text.startsWith('/*', i) || text.startsWith('*/', i)) refuse('expression', `${where}: a comment marker`);
222
+ if (c === '(') { depth++; i++; continue; }
223
+ if (c === ')') { if (--depth < 0) refuse('expression', `${where}: unbalanced parentheses`); i++; continue; }
224
+ if (c === ',') { i++; continue; }
225
+ const op = /^[<>=!+\-*/%|]+/.exec(text.slice(i));
226
+ if (op) {
227
+ if (!OPERATORS.has(op[0])) refuse('expression', `${where}: the operator ${op[0]} is not one of ${[...OPERATORS].join(' ')}`);
228
+ i += op[0].length; continue;
229
+ }
230
+ refuse('expression', `${where}: the character ${JSON.stringify(c)} is outside what the generator renders`);
231
+ }
232
+ if (depth !== 0) refuse('expression', `${where}: unbalanced parentheses`);
233
+ return text;
234
+ }
235
+
236
+ /** A column type: one of TYPES, or { postgres, sqlite } each one of them. `extra`: more accepted words (anchors). */
237
+ function columnType(t, where, extra = []) {
238
+ const ok = (x) => typeof x === 'string' && (TYPES.includes(x) || extra.includes(x));
239
+ if (ok(t)) return t;
240
+ if (isMap(t) && Object.keys(t).length === 2 && ok(t.postgres) && ok(t.sqlite)) return { postgres: t.postgres, sqlite: t.sqlite };
241
+ refuse('column-type', `${where}: type ${JSON.stringify(t)} — one of ${[...TYPES, ...extra].join(', ')}, or { postgres, sqlite } each one of them`);
242
+ }
243
+ const typeIn = (t, dialect) => (typeof t === 'string' ? t : t[dialect]);
244
+
245
+ function columnDefault(d, type, where) {
246
+ if (!isMap(d) || Object.keys(d).length !== 1) refuse('default', `${where}: a default is { text } or { integer } or { utcNow: true }`);
247
+ const both = ['postgres', 'sqlite'].map((x) => typeIn(type, x));
248
+ if (has(d, 'text')) {
249
+ if (typeof d.text !== 'string' || /[\x00-\x1f\x7f]/.test(d.text)) refuse('default', `${where}: a text default is a single-line string`);
250
+ if (both.some((x) => x !== 'TEXT')) refuse('default', `${where}: a text default on a column that is not TEXT`);
251
+ } else if (has(d, 'integer')) {
252
+ if (!Number.isSafeInteger(d.integer)) refuse('default', `${where}: an integer default is a whole number`);
253
+ if (both.some((x) => x === 'TEXT')) refuse('default', `${where}: an integer default on a TEXT column`);
254
+ } else if (has(d, 'utcNow')) {
255
+ if (d.utcNow !== true) refuse('default', `${where}: utcNow is true`);
256
+ if (both.some((x) => x !== 'TEXT')) refuse('default', `${where}: the UTC time is TEXT here`);
257
+ } else refuse('default', `${where}: a default is { text } or { integer } or { utcNow: true }`);
258
+ return { ...d };
259
+ }
260
+
261
+ /** The columns the generator writes in every table, by tenancy. */
262
+ const generatedColumns = (customer) => ['id', 'partner_id', ...(customer ? [customer] : []), 'created_at'];
263
+ /** The unique key the generator writes in every table, by tenancy. */
264
+ const generatedUnique = (customer) => (customer ? ['id', customer, 'partner_id'] : ['id', 'partner_id']);
265
+ /** The constraint and index names the generator writes for a table (tenancyNames, the generator's own). */
266
+ const generatedNames = (t, customer) => Object.values(tenancyNames(t, customer)).filter(Boolean);
267
+
268
+ /**
269
+ * An anchor: { tenancy, columns, unique }. Its TENANCY says what it is, like a table's: 'PARTNER', or { customer:
270
+ * <column> } for customer data (only a CUSTOMER table may key into it). `customers` is the customer anchor by
271
+ * definition: its customer column is its own `id` (the generator's skeleton refuses a table naming its customer by its
272
+ * own id for the same reason — that is the anchor's shape), so it must say { customer: 'id' }.
273
+ */
274
+ function anchorOf(a, aname, where) {
275
+ if (!isMap(a)) refuse('anchor', `${where} must be { tenancy, columns, unique }`);
276
+ keys(a, ['tenancy', 'columns', 'unique'], 'anchor', where);
277
+ if (!has(a, 'tenancy')) refuse('anchor', `${where}: an anchor states its tenancy — 'PARTNER', or { customer: <column> }`);
278
+ let customer = null;
279
+ if (a.tenancy !== 'PARTNER') {
280
+ if (!isMap(a.tenancy) || Object.keys(a.tenancy).length !== 1 || !has(a.tenancy, 'customer')) refuse('anchor', `${where}: tenancy is 'PARTNER' or { customer: <column> }`);
281
+ customer = name(a.tenancy.customer, `${where}: the customer column`);
282
+ }
283
+ if (aname === 'customers' && customer !== 'id') refuse('anchor', `${where}: customers is the customer anchor — its tenancy is { customer: 'id' }`);
284
+ if (!Array.isArray(a.columns) || !a.columns.length) refuse('anchor', `${where}: columns is a non-empty list`);
285
+ const columns = a.columns.map((c, i) => {
286
+ const w = `${where}.columns[${i}]`;
287
+ if (!isMap(c)) refuse('anchor', `${w} must be { name, type, notNull }`);
288
+ keys(c, ['name', 'type', 'notNull'], 'anchor', w);
289
+ const n = name(c.name, w);
290
+ if (has(c, 'notNull') && typeof c.notNull !== 'boolean') refuse('anchor', `${w}: notNull is true or false`);
291
+ return { name: n, type: columnType(c.type, `${w} (${n})`, ['PARTNER_ID']), notNull: c.notNull === true };
292
+ });
293
+ const names = columns.map((c) => c.name);
294
+ if (new Set(names).size !== names.length) refuse('name-taken', `${where}: a column named twice`);
295
+ const pid = columns.find((c) => c.name === 'partner_id');
296
+ if (!pid || pid.type !== 'PARTNER_ID' || !pid.notNull) refuse('anchor', `${where}: an anchor is a tenant table — it declares partner_id, type PARTNER_ID, notNull`);
297
+ if (!Array.isArray(a.unique)) refuse('anchor', `${where}: unique is a list of column lists`);
298
+ const unique = a.unique.map((u, i) => columnList(u, names, `${where}.unique[${i}]`));
299
+ if (customer && !names.includes(customer)) refuse('anchor', `${where}: its customer column ${customer} is not one of its columns`);
300
+ return { name: aname, tenancy: customer ? { customer } : 'PARTNER', customer, columns, unique };
301
+ }
302
+
303
+ function foreignKeyOf(fk, ctx, where) {
304
+ if (!isMap(fk)) refuse('constraint-shape', `${where}: foreignKey is { columns, references, onDelete?, onUpdate? }`);
305
+ keys(fk, ['columns', 'references', 'onDelete', 'onUpdate'], 'constraint-shape', where);
306
+ const columns = columnList(fk.columns, ctx.columns, `${where}.columns`);
307
+ if (!isMap(fk.references)) refuse('constraint-shape', `${where}: references is { table, columns }`);
308
+ keys(fk.references, ['table', 'columns'], 'constraint-shape', `${where}.references`);
309
+ const parent = name(fk.references.table, `${where}.references.table`);
310
+ const target = ctx.targets[parent];
311
+ if (!target) refuse('key-target', `${where}: ${parent} is neither a table of this set nor one of its anchors`);
312
+ const parentColumns = columnList(fk.references.columns, target.columns, `${where}.references.columns (of ${parent})`);
313
+ if (columns.length !== parentColumns.length) refuse('key-partner', `${where}: ${columns.length} column(s) into ${parentColumns.length}`);
314
+ const i = columns.indexOf('partner_id');
315
+ if (i === -1 || parentColumns[i] !== 'partner_id') refuse('key-partner', `${where}: a key into tenant data carries partner_id on both sides at the same position`);
316
+ const same = (u) => u.length === parentColumns.length && u.every((c) => parentColumns.includes(c));
317
+ if (!target.unique.some(same)) refuse('key-parent-unique', `${where}: (${parentColumns.join(', ')}) is not a unique key of ${parent}`);
318
+ const action = (a, which) => {
319
+ if (a === undefined) return 'NO ACTION';
320
+ if (!ACTIONS.includes(a)) {
321
+ refuse('key-action', `${where}: ON ${which} ${JSON.stringify(a)} — one of ${ACTIONS.join(', ')} (SET DEFAULT re-parents a row into another tenant; SET NULL nulls partner_id, and SQLite cannot name its column)`);
322
+ }
323
+ return a;
324
+ };
325
+ return { columns, references: { table: parent, columns: parentColumns }, onDelete: action(fk.onDelete, 'DELETE'), onUpdate: action(fk.onUpdate, 'UPDATE') };
326
+ }
327
+
328
+ /**
329
+ * A unique key or unique index of a set table carries partner_id: the same customer id exists under two partners, so a
330
+ * key without it would refuse the second partner's row, and let one partner probe for another's by insert conflicts.
331
+ * (The generator's own UNIQUE (id, …, partner_id) is the only way to key on id.)
332
+ */
333
+ function partnerUnique(cols, where) {
334
+ if (!cols.includes('partner_id')) refuse('unique-partner', `${where}: a unique key without partner_id (${cols.join(', ')})`);
335
+ return cols;
336
+ }
337
+
338
+ const DEFINED = new WeakSet();
339
+ function deepFreeze(o) {
340
+ if (o && typeof o === 'object' && !Object.isFrozen(o)) { Object.freeze(o); for (const v of Object.values(o)) deepFreeze(v); }
341
+ return o;
342
+ }
343
+
344
+ /**
345
+ * Validate a definition set and return a deep-frozen copy (the input is not changed or kept). Throws a
346
+ * TableDefinitionError (code TABLE_DEFINITION_REFUSED, `refusal` one of REFUSALS) on the first thing it cannot render
347
+ * exactly.
348
+ */
349
+ function defineTables(set) {
350
+ if (!isMap(set)) refuse('set-shape', 'pass { name, version, tables, comment?, anchors?, indexes? }');
351
+ keys(set, ['name', 'version', 'comment', 'anchors', 'tables', 'indexes'], 'set-shape', 'the set');
352
+ for (const k of ['name', 'version', 'tables']) if (!has(set, k)) refuse('set-shape', `the set lacks "${k}"`);
353
+ if (typeof set.name !== 'string' || !SLUG.test(set.name) || set.name.length > 40) refuse('set-name', `${JSON.stringify(set.name)} is not a slug`);
354
+ const where = `set ${set.name}`;
355
+ if (typeof set.version !== 'string' || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(set.version)) refuse('set-version', `${where}: version ${JSON.stringify(set.version)} is not x.y.z`);
356
+ let comment = [];
357
+ if (has(set, 'comment')) {
358
+ if (!Array.isArray(set.comment) || set.comment.some((l) => typeof l !== 'string' || /[\x00-\x1f\x7f]/.test(l) || l !== l.trimEnd())) {
359
+ refuse('comment', `${where}: comment is a list of single-line strings without trailing space`);
360
+ }
361
+ comment = [...set.comment];
362
+ }
363
+ // anchors
364
+ const anchors = {};
365
+ if (has(set, 'anchors')) {
366
+ if (!isMap(set.anchors)) refuse('anchor', `${where}: anchors is { table: { columns, unique } }`);
367
+ for (const [a, def] of Object.entries(set.anchors)) {
368
+ // a key into the app's principal table is attribution, which the generator's rules treat apart; a set names a
369
+ // user in a plain column with no key (as the reproduced migrations do). defineTables cannot read the app's
370
+ // principalTable, so it refuses the default name here, and renderDefinitions refuses the app's own.
371
+ if (a === 'users') refuse('anchor', `${where}: an anchor named users — a column naming a user is a plain column, with no key`);
372
+ anchors[name(a, `${where}: anchor`)] = anchorOf(def, a, `${where}: anchor ${a}`);
373
+ }
374
+ }
375
+ // tables: first pass, names and tenancy (a key may point at a table defined later in the list)
376
+ if (!Array.isArray(set.tables) || !set.tables.length) refuse('set-shape', `${where}: tables is a non-empty list`);
377
+ const heads = set.tables.map((t, i) => {
378
+ const w = `${where}: tables[${i}]`;
379
+ if (!isMap(t)) refuse('table-shape', `${w} must be an object`);
380
+ keys(t, ['name', 'description', 'tenancy', 'columns', 'constraints'], 'table-shape', w);
381
+ for (const k of ['name', 'description', 'tenancy', 'columns']) if (!has(t, k)) refuse('table-shape', `${w} lacks "${k}"`);
382
+ const tn = name(t.name, w);
383
+ if (typeof t.description !== 'string' || t.description.trim().length < 10) refuse('table-shape', `${where}: ${tn}: description is a sentence (it is the manifest's reason)`);
384
+ let customer = null;
385
+ if (t.tenancy !== 'PARTNER') {
386
+ if (!isMap(t.tenancy) || Object.keys(t.tenancy).length !== 1 || !has(t.tenancy, 'customer')) refuse('tenancy', `${where}: ${tn}: tenancy is 'PARTNER' or { customer: <column> }`);
387
+ customer = name(t.tenancy.customer, `${where}: ${tn}: the customer column`);
388
+ if (customer === 'id' || customer === 'partner_id' || customer === 'created_at') refuse('tenancy', `${where}: ${tn}: the customer column cannot be ${customer}`);
389
+ }
390
+ // every name the generator will write for this table, by the generator's own naming, fits PostgreSQL's 63 bytes
391
+ for (const n of generatedNames(tn, customer)) {
392
+ if (Buffer.byteLength(n) > 63) refuse('name-length', `${where}: ${tn}: the generator would write ${n} (${Buffer.byteLength(n)} bytes; PostgreSQL truncates past 63)`);
393
+ }
394
+ return { name: tn, customer, raw: t, where: `${where}: ${tn}` };
395
+ });
396
+ const tableNames = heads.map((h) => h.name);
397
+ if (new Set(tableNames).size !== tableNames.length) refuse('name-taken', `${where}: a table is defined twice`);
398
+ for (const a of Object.keys(anchors)) if (tableNames.includes(a)) refuse('anchor', `${where}: ${a} is both a table of the set and an anchor`);
399
+ if (heads.some((h) => h.customer)) {
400
+ const c = anchors.customers;
401
+ const ok = c && ['id', 'partner_id'].every((x) => c.columns.some((col) => col.name === x))
402
+ && c.unique.some((u) => u.length === 2 && u.includes('id') && u.includes('partner_id'));
403
+ if (!ok) refuse('anchor-missing', `${where}: a CUSTOMER table keys to customers (id, partner_id) — declare the anchor customers with id, partner_id and that unique key`);
404
+ }
405
+ // second pass: columns, then constraints (which need every table's columns and unique keys)
406
+ const objectNames = new Set();
407
+ const claim = (n, w) => { if (objectNames.has(n)) refuse('name-taken', `${w}: the name ${n} is used twice in the set (or is one the generator writes)`); objectNames.add(n); };
408
+ for (const h of heads) for (const n of generatedNames(h.name, h.customer)) claim(n, h.where);
409
+ const tables = heads.map((h) => {
410
+ const t = h.raw;
411
+ if (!Array.isArray(t.columns)) refuse('table-shape', `${h.where}: columns is a list`);
412
+ const reserved = generatedColumns(h.customer);
413
+ const cols = t.columns.map((c, i) => {
414
+ const w = `${h.where}: columns[${i}]`;
415
+ if (!isMap(c)) refuse('column-shape', `${w} must be an object`);
416
+ keys(c, ['name', 'type', 'notNull', 'default', 'check'], 'column-shape', w);
417
+ const cn = name(c.name, w);
418
+ if (reserved.includes(cn)) refuse('reserved-column', `${h.where}: ${cn} is written by the generator — do not define it`);
419
+ if (has(c, 'notNull') && typeof c.notNull !== 'boolean') refuse('column-shape', `${h.where}.${cn}: notNull is true or false`);
420
+ const type = columnType(c.type, `${h.where}.${cn}`);
421
+ return { name: cn, type, notNull: c.notNull === true, ...(has(c, 'default') ? { default: columnDefault(c.default, type, `${h.where}.${cn}`) } : {}), check: has(c, 'check') ? c.check : null };
422
+ });
423
+ const all = [...reserved.slice(0, -1), ...cols.map((c) => c.name), 'created_at'];
424
+ if (new Set(all).size !== all.length) refuse('name-taken', `${h.where}: a column is defined twice`);
425
+ if (!h.customer) {
426
+ // a PARTNER-only table gets the one-arm policy: a customer column on it would be readable across customers
427
+ const customerCols = new Set(['customer_id', ...heads.map((x) => x.customer).filter(Boolean)]);
428
+ const bad = cols.find((c) => customerCols.has(c.name));
429
+ if (bad) refuse('partner-customer', `${h.where}: a PARTNER-only table with the customer column ${bad.name} — make it a CUSTOMER table`);
430
+ }
431
+ for (const c of cols) {
432
+ if (c.check === null) delete c.check;
433
+ else c.check = expression(c.check, all, `${h.where}.${c.name} CHECK`);
434
+ }
435
+ return { name: h.name, description: t.description, tenancy: h.customer ? { customer: h.customer } : 'PARTNER', customer: h.customer, columns: cols, all, constraintsRaw: t.constraints, where: h.where };
436
+ });
437
+ // what a key may point at: each set table (its columns, its unique keys) and each anchor
438
+ const targets = {};
439
+ for (const a of Object.values(anchors)) targets[a.name] = { columns: a.columns.map((c) => c.name), unique: a.unique, customer: a.customer };
440
+ for (const t of tables) targets[t.name] = { columns: t.all, unique: [['id'], generatedUnique(t.customer)], customer: t.customer };
441
+ for (const t of tables) {
442
+ // unique constraints first, so a key may point at one declared later in the same table
443
+ for (const k of Array.isArray(t.constraintsRaw) ? t.constraintsRaw : []) if (isMap(k) && has(k, 'unique')) targets[t.name].unique.push(Array.isArray(k.unique) ? k.unique : []);
444
+ }
445
+ for (const t of tables) {
446
+ const raw = t.constraintsRaw === undefined ? [] : t.constraintsRaw;
447
+ if (!Array.isArray(raw)) refuse('table-shape', `${t.where}: constraints is a list`);
448
+ t.constraints = raw.map((k, i) => {
449
+ const w = `${t.where}: constraints[${i}]`;
450
+ if (!isMap(k)) refuse('constraint-shape', `${w} must be an object`);
451
+ const kinds = ['check', 'unique', 'foreignKey'].filter((x) => has(k, x));
452
+ keys(k, ['name', ...['check', 'unique', 'foreignKey']], 'constraint-shape', w);
453
+ if (kinds.length !== 1) refuse('constraint-shape', `${w}: exactly one of check, unique, foreignKey`);
454
+ const kn = name(k.name, `${w} name`);
455
+ claim(kn, w);
456
+ if (kinds[0] === 'check') return { name: kn, check: expression(k.check, t.all, `${t.where}: ${kn}`) };
457
+ if (kinds[0] === 'unique') return { name: kn, unique: partnerUnique(columnList(k.unique, t.all, `${t.where}: ${kn}`), `${t.where}: ${kn}`) };
458
+ const fk = foreignKeyOf(k.foreignKey, { columns: t.all, targets }, `${t.where}: ${kn}`);
459
+ // a PARTNER table keys only into PARTNER tables of the set and PARTNER anchors: a key into customer data would let
460
+ // its one-arm policy show a pinned customer the rows of every customer of the partner
461
+ if (!t.customer && targets[fk.references.table].customer) {
462
+ refuse('partner-customer', `${t.where}: ${kn}: a PARTNER-only table keyed into ${fk.references.table}, which is customer data — make it a CUSTOMER table`);
463
+ }
464
+ return { name: kn, foreignKey: fk };
465
+ });
466
+ delete t.constraintsRaw;
467
+ delete t.where;
468
+ }
469
+ // indexes, in the set's order
470
+ if (has(set, 'indexes') && !Array.isArray(set.indexes)) refuse('index-shape', `${where}: indexes is a list`);
471
+ const indexes = (set.indexes || []).map((x, i) => {
472
+ const w = `${where}: indexes[${i}]`;
473
+ if (!isMap(x)) refuse('index-shape', `${w} must be an object`);
474
+ keys(x, ['name', 'table', 'columns', 'unique', 'where'], 'index-shape', w);
475
+ const xn = name(x.name, w);
476
+ claim(xn, w);
477
+ const t = tables.find((tb) => tb.name === x.table);
478
+ if (!t) refuse('index-shape', `${w}: ${JSON.stringify(x.table)} is not a table of this set`);
479
+ if (has(x, 'unique') && typeof x.unique !== 'boolean') refuse('index-shape', `${w}: unique is true or false`);
480
+ const cols = columnList(x.columns, t.all, `${w} ${xn}`);
481
+ if (x.unique === true) partnerUnique(cols, `${w} ${xn}`);
482
+ return { name: xn, table: t.name, columns: cols, unique: x.unique === true,
483
+ ...(has(x, 'where') ? { where: expression(x.where, t.all, `${w} ${xn} WHERE`) } : {}) };
484
+ });
485
+ for (const t of tables) delete t.all;
486
+ const out = deepFreeze({ name: set.name, version: set.version, comment, anchors, tables, indexes });
487
+ DEFINED.add(out);
488
+ return out;
489
+ }
490
+
491
+ const isDefined = (x) => x !== null && typeof x === 'object' && DEFINED.has(x);
492
+ function assertDefined(set, where = 'a table definition set') {
493
+ if (!isDefined(set)) throw new Error(`${where} must be built with defineTables (@aria-framework/db-worker)`);
494
+ return set;
495
+ }
496
+
497
+ /** The classification a set gives its tables: { PARTNER: { table: description }, CUSTOMER: { table: column } }. */
498
+ function classificationOf(set) {
499
+ assertDefined(set);
500
+ const PARTNER = {};
501
+ const CUSTOMER = {};
502
+ for (const t of set.tables) {
503
+ PARTNER[t.name] = t.description;
504
+ if (t.customer) CUSTOMER[t.name] = t.customer;
505
+ }
506
+ return { PARTNER, CUSTOMER };
507
+ }
508
+
509
+ /**
510
+ * The fragment an app spreads into defineTenancy: `defineTenancy({ PARTNER: {...}, ..., ...tenancyFragment(a, b) })`.
511
+ * All the app's sets in ONE call (a second spread would replace the first). defineTenancy derives the classification
512
+ * from it and refuses a manifest that classifies one of these tables differently.
513
+ */
514
+ function tenancyFragment(...sets) {
515
+ if (!sets.length) throw new Error('tenancyFragment: pass the definition set(s)');
516
+ sets.forEach((s, i) => assertDefined(s, `tenancyFragment: argument ${i + 1}`));
517
+ const names = sets.map((s) => s.name);
518
+ if (new Set(names).size !== names.length) throw new Error('tenancyFragment: a set is passed twice');
519
+ const seen = {};
520
+ for (const s of sets) {
521
+ for (const t of s.tables) {
522
+ if (seen[t.name]) throw new Error(`tenancyFragment: ${t.name} is defined by both ${seen[t.name]} and ${s.name}`);
523
+ seen[t.name] = s.name;
524
+ }
525
+ }
526
+ return { TABLE_DEFINITIONS: Object.freeze([...sets]) };
527
+ }
528
+
529
+ // ── RENDERING THE SET'S OWN PARTS (tenancyGenerator.js writes the rest, and calls these) ───────────────────────────
530
+
531
+ const DIALECT = { pg: 'postgres', sqlite: 'sqlite', postgres: 'postgres' };
532
+ const literal = (d, dialect) => {
533
+ if (has(d, 'text')) return `'${d.text.replace(/'/g, "''")}'`;
534
+ if (has(d, 'integer')) return String(d.integer);
535
+ return UTC_NOW[DIALECT[dialect]];
536
+ };
537
+ /** A column's definition after its padded name: `TYPE[ NOT NULL][ DEFAULT x][ CHECK (e)]`. */
538
+ function columnSql(c, dialect) {
539
+ return `${typeIn(c.type, DIALECT[dialect])}${c.notNull ? ' NOT NULL' : ''}${c.default ? ` DEFAULT ${literal(c.default, dialect)}` : ''}${c.check ? ` CHECK (${c.check})` : ''}`;
540
+ }
541
+ /** A table constraint, as the skeleton lays out its own key. */
542
+ function constraintSql(k) {
543
+ if (k.check) return `CONSTRAINT ${k.name} CHECK (${k.check})`;
544
+ if (k.unique) return `CONSTRAINT ${k.name} UNIQUE (${k.unique.join(', ')})`;
545
+ const f = k.foreignKey;
546
+ const act = (w, a) => (a === 'NO ACTION' ? '' : ` ON ${w} ${a}`);
547
+ return `CONSTRAINT ${k.name} FOREIGN KEY (${f.columns.join(', ')})\n REFERENCES ${f.references.table} (${f.references.columns.join(', ')})${act('DELETE', f.onDelete)}${act('UPDATE', f.onUpdate)}`;
548
+ }
549
+ function indexSql(x) {
550
+ return `CREATE ${x.unique ? 'UNIQUE ' : ''}INDEX ${x.name} ON ${x.table}(${x.columns.join(', ')})${x.where ? ` WHERE ${x.where}` : ''};`;
551
+ }
552
+
553
+ // ── WHAT THE DATABASE MUST HOLD (tableDefinitionsCheck.js compares it) ────────────────────────────────────────────
554
+
555
+ /**
556
+ * The schema a set requires on one engine: per table its columns (name, type, notNull), primary key, unique keys,
557
+ * named indexes, foreign keys and (Postgres) policy column; per anchor its declared columns and unique keys.
558
+ * `partnerIdType` is the app's stated Postgres type of partner_id (BIGINT or INTEGER; SQLite is always INTEGER).
559
+ */
560
+ function expectedSchema(set, dialect, partnerIdType) {
561
+ assertDefined(set);
562
+ const d = DIALECT[dialect];
563
+ if (!d) throw new Error(`expectedSchema: dialect is postgres or sqlite, got ${JSON.stringify(dialect)}`);
564
+ if (d === 'postgres' && !['BIGINT', 'INTEGER'].includes(partnerIdType)) throw new Error('expectedSchema: partnerIdType is BIGINT or INTEGER (the app states it)');
565
+ const pid = d === 'postgres' ? partnerIdType : 'INTEGER';
566
+ const tables = set.tables.map((t) => ({
567
+ name: t.name,
568
+ customer: t.customer,
569
+ columns: [
570
+ { name: 'id', type: d === 'postgres' ? 'BIGINT' : 'INTEGER', notNull: d === 'postgres' },
571
+ { name: 'partner_id', type: pid, notNull: true },
572
+ ...(t.customer ? [{ name: t.customer, type: 'TEXT', notNull: true }] : []),
573
+ ...t.columns.map((c) => ({ name: c.name, type: typeIn(c.type, d), notNull: c.notNull })),
574
+ { name: 'created_at', type: 'TEXT', notNull: true }
575
+ ],
576
+ primaryKey: ['id'],
577
+ unique: [generatedUnique(t.customer), ...t.constraints.filter((k) => k.unique).map((k) => [...k.unique])],
578
+ indexes: [
579
+ { name: tenancyNames(t.name, t.customer).partnerIndex, unique: false, columns: ['partner_id'], partial: false },
580
+ ...(t.customer ? [{ name: tenancyNames(t.name, t.customer).customerIndex, unique: false, columns: [t.customer, 'partner_id'], partial: false }] : []),
581
+ ...set.indexes.filter((x) => x.table === t.name).map((x) => ({ name: x.name, unique: x.unique, columns: [...x.columns], partial: !!x.where }))
582
+ ],
583
+ keys: [
584
+ { columns: ['partner_id'], parent: 'partners', parentColumns: ['id'], onDelete: 'NO ACTION', onUpdate: 'NO ACTION' },
585
+ ...(t.customer ? [{ columns: [t.customer, 'partner_id'], parent: 'customers', parentColumns: ['id', 'partner_id'], onDelete: 'CASCADE', onUpdate: 'CASCADE' }] : []),
586
+ ...t.constraints.filter((k) => k.foreignKey).map((k) => ({ columns: [...k.foreignKey.columns], parent: k.foreignKey.references.table,
587
+ parentColumns: [...k.foreignKey.references.columns], onDelete: k.foreignKey.onDelete, onUpdate: k.foreignKey.onUpdate }))
588
+ ]
589
+ }));
590
+ const anchors = Object.values(set.anchors).map((a) => ({
591
+ name: a.name,
592
+ columns: a.columns.map((c) => ({ name: c.name, type: c.type === 'PARTNER_ID' ? pid : typeIn(c.type, d), notNull: c.notNull })),
593
+ unique: a.unique.map((u) => [...u])
594
+ }));
595
+ return { tables, anchors };
596
+ }
597
+
598
+ module.exports = {
599
+ defineTables, isTableDefinitions: isDefined, assertTableDefinitions: assertDefined, classificationOf, tenancyFragment,
600
+ expectedSchema, TableDefinitionError, REFUSALS, UTC_NOW,
601
+ // for tenancyGenerator.js
602
+ columnSql, constraintSql, indexSql, tenancyNames, RESERVED
603
+ };