@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.
@@ -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,
@@ -72,7 +80,7 @@
72
80
  * This is a line-and-regex reader, not a SQL parser, so where a construct is hard to read it is REFUSED in a policed
73
81
  * migration whatever it contains: any DO block, CREATE FUNCTION / PROCEDURE, any dollar quote, CREATE RULE, ALTER
74
82
  * ROLE, a CREATE VIEW without WITH (security_invoker = true) (a view runs as its owner, who bypasses RLS) or any
75
- * materialized view, CREATE TABLE … AS / LIKE, a nested block comment, a schema other than public, the runner markers
83
+ * materialized view, CREATE TABLE … AS / LIKE / OF / PARTITION OF (copiesColumns), a nested block comment, a schema other than public, the runner markers
76
84
  * `-- aria:covers-through` / `-- aria:no-transaction` (one makes later files ledgered WITHOUT running, the other drops
77
85
  * the transaction), ALTER VIEW, OWNER TO, SELECT … INTO (a table the SQLite classification guard never sees), SET
78
86
  * SCHEMA, session_replication_role (replica mode stops enforcing keys), DROP CONSTRAINT (except a lone drop of a CHECK
@@ -118,6 +126,7 @@ const fs = require('fs');
118
126
  const path = require('path');
119
127
  const { selectForDialect } = require('./database');
120
128
  const { TENANCY_POLICY_EXPRESSION, CUSTOMER_POLICY_EXPRESSION, assertSameCustomerPolicy } = require('./tenancyManifest');
129
+ const defs = require('./tableDefinitions');
121
130
 
122
131
  /** The Postgres partner_id definition, in the type the app states (aria.tenancy.json "partnerIdType"). */
123
132
  const PARTNER_ID_TYPES = ['BIGINT', 'INTEGER'];
@@ -292,7 +301,7 @@ function render(manifest, table, opts = {}) {
292
301
  customerColumn,
293
302
  pgPartnerId: pgDef,
294
303
  sqlitePartnerId: SQLITE_PARTNER_ID,
295
- index: `CREATE INDEX idx_${table}_partner ON ${table}(partner_id);`,
304
+ index: `CREATE INDEX ${defs.tenancyNames(table, customerColumn).partnerIndex} ON ${table}(partner_id);`,
296
305
  rls: [
297
306
  `ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;`,
298
307
  `ALTER TABLE ${table} FORCE ROW LEVEL SECURITY;`,
@@ -375,9 +384,11 @@ function fold(sql) {
375
384
  /** An identifier as Postgres resolves it: quoted kept, unquoted case-folded. */
376
385
  const ident = (s) => (s.startsWith('"') ? s.slice(1, -1) : s.toLowerCase());
377
386
 
387
+ const CREATE_TABLE_HEAD = /^\s*CREATE\s+(?:(?:GLOBAL|LOCAL)\s+)?(?:TEMP(?:ORARY)?\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?("\w+"|\w+)/i;
388
+
378
389
  /** The table a CREATE TABLE / ALTER TABLE statement acts on, else null. */
379
390
  function tableOf(sql) {
380
- let m = /^\s*CREATE\s+(?:(?:GLOBAL|LOCAL)\s+)?(?:TEMP(?:ORARY)?\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?("\w+"|\w+)/i.exec(sql);
391
+ let m = CREATE_TABLE_HEAD.exec(sql);
381
392
  if (m) return { kind: 'create', table: ident(m[1]) };
382
393
  m = /^\s*ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?("\w+"|\w+)/i.exec(sql);
383
394
  if (m) return { kind: 'alter', table: ident(m[1]) };
@@ -405,12 +416,49 @@ function bodyItems(sql) {
405
416
  return items.map((s) => s.trim()).filter(Boolean);
406
417
  }
407
418
 
419
+ /**
420
+ * Does this CREATE TABLE (its normalised head) take its columns from somewhere else, so they cannot be read: AS (a
421
+ * query's), LIKE (another table's), OF (a type's), PARTITION OF (a parent's)? Decided from the statement's SHAPE, not
422
+ * from a keyword next to the name: a table that writes out its own columns has `(` straight after its name, has no
423
+ * top-level LIKE item in that body, and no top-level AS after it. So `cameras (` is never `camer` + AS, and
424
+ * `copies (a, b) AS SELECT …`, `copies WITH (fillfactor = 70) AS …` and `copies (x INT, LIKE notes)` are refused.
425
+ * The name is read as tableOf reads it (CREATE_TABLE_HEAD), so both see the same name.
426
+ */
427
+ function copiesColumns(head) {
428
+ const m = CREATE_TABLE_HEAD.exec(head);
429
+ // Not reached from checkTree, which calls this only after tableOf matched the same pattern; kept so another caller
430
+ // fails closed. A name the pattern cannot read at all (a quoted name with a space, say) makes tableOf return null,
431
+ // and checkTree then checks nothing about that statement: an older gap this function does not close.
432
+ if (!m) return true;
433
+ const rest = head.slice(m[0].length);
434
+ if (!/^\s*\(/.test(rest)) return true;
435
+ // The body: from that `(` to its own closing paren. Literals' contents are already blanked in `head`; a
436
+ // double-quoted identifier is skipped whole, so a paren or the word AS inside one counts for nothing.
437
+ const open = rest.indexOf('(');
438
+ let depth = 0;
439
+ let close = -1;
440
+ for (let i = open; i < rest.length; i++) {
441
+ const c = rest[i];
442
+ if (c === '"') { const j = rest.indexOf('"', i + 1); if (j < 0) return true; i = j; continue; }
443
+ if (c === '(') depth++;
444
+ else if (c === ')' && --depth === 0) { close = i; break; }
445
+ }
446
+ if (close < 0) return true;
447
+ if (bodyItems(rest.slice(open, close + 1)).some((it) => /^LIKE\b/i.test(it))) return true;
448
+ // After the body, outside any parens and quoted names: WITH (…), PARTITION BY RANGE (…), TABLESPACE, ON COMMIT
449
+ // never say AS; a column-name list followed by AS SELECT does.
450
+ let after = rest.slice(close + 1).replace(/"(?:[^"]|"")*"/g, ' ');
451
+ for (let prev = null; prev !== after;) { prev = after; after = after.replace(/\([^()]*\)/g, ' '); }
452
+ return /\bAS\b/i.test(after);
453
+ }
454
+
408
455
  const cols = (s) => s.split(',').map((x) => x.trim()).filter(Boolean).map(ident);
409
456
 
410
457
  /** Every key declared in a statement: { cols, parent, parentCols, onDelete, onUpdate, inline }. */
411
458
  function keysIn(sql) {
412
459
  const keys = [];
413
- const re = /REFERENCES\s*("\w+"|\w+)\s*(?:\(([^)]*)\))?/gi;
460
+ // `\b`: the keyword, not the end of a word (a column `preferences users` is not a key into users).
461
+ const re = /\bREFERENCES\s*("\w+"|\w+)\s*(?:\(([^)]*)\))?/gi;
414
462
  let m;
415
463
  while ((m = re.exec(sql))) {
416
464
  const before = sql.slice(0, m.index);
@@ -741,7 +789,9 @@ function checkTree({ files, manifest, frozen, partnerIdType, principalTable = 'u
741
789
  const child = on.table;
742
790
  if (on.kind === 'create') {
743
791
  if (!classified.has(child)) problems.push(`${f}: creates ${child}, which ${manifestName} does not classify`);
744
- if (/^CREATE\s+.*?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?("\w+"|\w+)\s*(?:\(\s*LIKE\b|AS\b|PARTITION\s+OF\b|OF\b)/i.test(head)) {
792
+ // By the statement's shape (copiesColumns), not a keyword after the name: 0.31.0 let the name give its tail
793
+ // to the keyword (`cameras (` read as `camer` + AS), and missed AS after a column list or WITH (…).
794
+ if (copiesColumns(head)) {
745
795
  refuse('CREATE TABLE … AS / LIKE / OF — its columns cannot be read');
746
796
  } else if (!scopedNames.has(child) && bodyItems(s.sql).some((it) => /^"?(partner_id|customer_id)"?\s/i.test(it))) {
747
797
  problems.push(`${f}: ${child} has a partner_id or customer_id column but is not scoped in ${manifestName}`);
@@ -801,7 +851,16 @@ function checkTree({ files, manifest, frozen, partnerIdType, principalTable = 'u
801
851
  problems.push(`only ${keysChecked} key(s) into scoped tables read in the policed migrations, below the floor of ${keysFloor} — the reader stopped seeing keys`);
802
852
  }
803
853
 
804
- return { problems, stats: { tables: A, created: B, preExisting, statementsCompared: compared, keysChecked, pgKeys: pgKeyList.length, pgKeyList, files: post.length } };
854
+ const stats = { tables: A, created: B, preExisting, statementsCompared: compared, keysChecked, pgKeys: pgKeyList.length, pgKeyList, files: post.length };
855
+ // 0.31.0 — pairs generated from a package's table definitions, held byte for byte. Only a manifest that carries sets,
856
+ // or a tree with a file that names one, gets this section (and the stats key): for any other, check is as before.
857
+ if (has(manifest, 'TABLE_DEFINITIONS') || post.some((f) => DEFINED_HEAD.test(firstLine(files[f])))) {
858
+ const d = checkDefinitionFiles(files, manifest, post, frozen, { partnerIdType, manifestName, preExisting, principalTable });
859
+ problems.push(...d.problems);
860
+ stats.definitionFiles = d.compared;
861
+ stats.definitionFilesFrozen = d.frozen;
862
+ }
863
+ return { problems, stats };
805
864
  }
806
865
 
807
866
  /** A view's WITH (…) options turn security_invoker on (bare, = true or = on) and nothing turns it off. */
@@ -831,6 +890,42 @@ function compareKeys(expected, rows, postTables) {
831
890
 
832
891
  // ── THE SKELETON ────────────────────────────────────────────────────────────────────────────────────────────────
833
892
 
893
+ const pad = (s) => s.padEnd(13) + ' ';
894
+
895
+ /**
896
+ * ONE TABLE'S CREATE TABLE and its generated indexes, as the skeleton writes it: the generated id, partner_id and
897
+ * customer column, the marker, then `own` (0.31.0: a definition's columns after the marker and its constraints after
898
+ * created_at — tableDefinitions.js renders them), then created_at, the generated unique key and the key to customers,
899
+ * the partner index and the customer index. Without `own` it is the skeleton's table, byte for byte as before.
900
+ */
901
+ function tableSql(g, dialect, own = null) {
902
+ const lines = [
903
+ `CREATE TABLE ${g.table} (`,
904
+ ` ${pad('id')}${dialect === 'pg' ? 'BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY' : 'INTEGER PRIMARY KEY AUTOINCREMENT'},`,
905
+ ` ${pad('partner_id')}${dialect === 'pg' ? g.pgPartnerId : g.sqlitePartnerId},`
906
+ ];
907
+ if (g.customerColumn) lines.push(` ${pad(g.customerColumn)}TEXT NOT NULL,`);
908
+ lines.push(' -- ── this table\'s own columns and keys ──');
909
+ if (own) for (const c of own.columns) lines.push(` ${pad(c.name)}${defs.columnSql(c, dialect)},`);
910
+ const ts = defs.UTC_NOW[dialect === 'pg' ? 'postgres' : 'sqlite'];
911
+ const tail = [` ${pad('created_at')}TEXT NOT NULL DEFAULT ${ts}`];
912
+ if (own) for (const k of own.constraints) tail.push(` ${defs.constraintSql(k)}`);
913
+ const n = defs.tenancyNames(g.table, g.customerColumn);
914
+ if (g.customerColumn) {
915
+ tail.push(` CONSTRAINT ${n.unique} UNIQUE (id, ${g.customerColumn}, partner_id)`);
916
+ tail.push(` CONSTRAINT ${n.customerKey} FOREIGN KEY (${g.customerColumn}, partner_id)\n`
917
+ + ' REFERENCES customers (id, partner_id) ON DELETE CASCADE ON UPDATE CASCADE');
918
+ } else {
919
+ tail.push(` CONSTRAINT ${n.unique} UNIQUE (id, partner_id)`);
920
+ }
921
+ lines.push(tail.join(',\n'), ');', g.index);
922
+ if (g.customerColumn) lines.push(`CREATE INDEX ${n.customerIndex} ON ${g.table}(${g.customerColumn}, partner_id);`);
923
+ return lines.join('\n');
924
+ }
925
+
926
+ /** The Postgres file's closing section: its heading, then each table's ENABLE, FORCE and policy. */
927
+ const rlsSection = (gens, heading) => [heading, '', gens.map((g) => g.rls.join('\n')).join('\n\n'), ''];
928
+
834
929
  /** The new pair's text: `{ pg, lite }`. `opts`: { preExisting, manifestName } as for render. */
835
930
  function skeleton(manifest, tables, base, opts = {}) {
836
931
  const manifestName = opts.manifestName || 'the manifest';
@@ -838,7 +933,6 @@ function skeleton(manifest, tables, base, opts = {}) {
838
933
  for (const g of gens) {
839
934
  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`);
840
935
  }
841
- const pad = (s) => s.padEnd(13) + ' ';
842
936
  const head = (dialect) => [
843
937
  `-- ${base}${dialect === 'pg' ? '.postgres' : ''}.sql — GENERATED SKELETON (aria-tenancy new ${tables.join(' ')}).`,
844
938
  '--',
@@ -857,32 +951,183 @@ function skeleton(manifest, tables, base, opts = {}) {
857
951
  : []),
858
952
  ''
859
953
  ];
860
- const table = (g, dialect) => {
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},`
954
+ const pg = [...head('pg'), gens.map((g) => tableSql(g, 'pg')).join('\n\n'), '',
955
+ ...rlsSection(gens, `-- ── ROW-LEVEL SECURITY (generated from ${manifestName}) ──`)].join('\n');
956
+ const lite = [...head('sqlite'), gens.map((g) => tableSql(g, 'sqlite')).join('\n\n'), ''].join('\n');
957
+ return { pg, lite };
958
+ }
959
+
960
+ // ── 0.31.0: A PACKAGE'S TABLE DEFINITIONS, WRITTEN INTO THE APP'S OWN MIGRATION ─────────────────────────────────────
961
+
962
+ /**
963
+ * The first line of a pair generated from a definition set: what check and new recognise it by. It names the file,
964
+ * the set, its version and the LAYOUT that wrote it. Groups: 1 base, 2 ".postgres", 3 set, 4 version, 5 layout, 6 set.
965
+ */
966
+ 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_]*)\)\.$/;
967
+
968
+ /** The definition sets a manifest carries (TABLE_DEFINITIONS, from tenancyFragment), each validated. */
969
+ function definitionSets(manifest, name = 'the manifest') {
970
+ if (!has(manifest, 'TABLE_DEFINITIONS')) return [];
971
+ const sets = manifest.TABLE_DEFINITIONS;
972
+ if (!Array.isArray(sets)) throw new Error(`${name}: TABLE_DEFINITIONS is what tenancyFragment(...sets) gives`);
973
+ sets.forEach((s, i) => defs.assertTableDefinitions(s, `${name}: TABLE_DEFINITIONS[${i}]`));
974
+ return sets;
975
+ }
976
+
977
+ /**
978
+ * ── THE LAYOUTS OF A DEFINITIONS FILE — FROZEN ──────────────────────────────────────────────────────────────────
979
+ * A definitions file is applied by apps and never edited, and check compares it WHOLE, byte for byte, with what the
980
+ * layout named in its first line writes. So a layout's output may never change. Its text is a function of ONLY:
981
+ * - the set (name, version, tables, indexes, anchors, comment) — a set changed in any part, its comment included,
982
+ * is a new version of the set;
983
+ * - the frozen policy texts (TENANCY_POLICY_EXPRESSION, CUSTOMER_POLICY_EXPRESSION);
984
+ * - the app's partnerIdType (the Postgres type of partner_id — the one tenancy parameter that differs per app);
985
+ * - the file's own base name (NNN_slug), fixed when it is written;
986
+ * - the layout number.
987
+ * NOT of the manifest's path, the app's folders, the date, or anything else about where or when it runs. (The manifest
988
+ * must classify each table as the set does; render() refuses otherwise, so it changes nothing in the text.)
989
+ * Layout 1 writes with tableSql, columnSql / constraintSql / indexSql, UTC_NOW, render() and tenancyNames — shared with
990
+ * the skeleton, and pinned by sha256 in test/tableDefinitions.js. ANY change that alters layout 1's output (a skeleton
991
+ * fix included) must instead: copy the current writers into a frozen layout-1 function, add the change as layout 2,
992
+ * and make CURRENT_LAYOUT 2 — old files keep being checked by layout 1, selected by the number in their first line.
993
+ */
994
+ const LAYOUTS = Object.freeze({
995
+ 1: function layout1(set, gens, base) {
996
+ const own = Object.fromEntries(set.tables.map((t) => [t.name, t]));
997
+ const head = (dialect) => [
998
+ `-- ${base}${dialect === 'pg' ? '.postgres' : ''}.sql — GENERATED from the table definitions ${set.name} ${set.version}, layout 1 (aria-tenancy new --definitions ${set.name}).`,
999
+ '--',
1000
+ `-- Every statement below is the generator's: the tables as ${set.name} ${set.version} defines them, and their TENANCY`,
1001
+ dialect === 'pg'
1002
+ ? '-- (the partner_id column, the partner index, and the row-level-security section at the end).'
1003
+ : '-- (the partner_id column and the partner index; no policies on SQLite, one tenant there).',
1004
+ '-- `aria-tenancy check` holds this file to layout 1 of the generator byte for byte: never edit it. The package\'s',
1005
+ `-- schema check compares the database with ${set.name} ${set.version} when the app starts.`,
1006
+ ...(set.comment.length ? ['--', ...set.comment.map((l) => (l ? `-- ${l}` : '--'))] : []),
1007
+ ''
865
1008
  ];
866
- if (g.customerColumn) lines.push(` ${pad(g.customerColumn)}TEXT NOT NULL,`);
867
- lines.push(' -- ── this table\'s own columns and keys ──');
868
- const ts = dialect === 'pg' ? "to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')" : "(datetime('now'))";
869
- const tail = [` ${pad('created_at')}TEXT NOT NULL DEFAULT ${ts}`];
870
- if (g.customerColumn) {
871
- tail.push(` CONSTRAINT uq_${g.table}_id_customer_partner UNIQUE (id, ${g.customerColumn}, partner_id)`);
872
- tail.push(` CONSTRAINT fk_${g.table}_${g.customerColumn}_partner FOREIGN KEY (${g.customerColumn}, partner_id)\n`
873
- + ' REFERENCES customers (id, partner_id) ON DELETE CASCADE ON UPDATE CASCADE');
874
- } else {
875
- tail.push(` CONSTRAINT uq_${g.table}_id_partner UNIQUE (id, partner_id)`);
1009
+ const body = (dialect) => gens.map((g) => tableSql(g, dialect, own[g.table])).join('\n\n')
1010
+ + set.indexes.map((x) => `\n${defs.indexSql(x)}`).join('');
1011
+ const pg = [...head('pg'), body('pg'), '', ...rlsSection(gens, '-- ── ROW-LEVEL SECURITY (generated) ──')].join('\n');
1012
+ const lite = [...head('sqlite'), body('sqlite'), ''].join('\n');
1013
+ return { pg, lite };
1014
+ }
1015
+ });
1016
+ /** The layout new files are written with. */
1017
+ const CURRENT_LAYOUT = 1;
1018
+
1019
+ /**
1020
+ * A definition set's migration pair: `{ pg, lite }`, by `layout` (default CURRENT_LAYOUT). Every CREATE TABLE body is
1021
+ * the set's, written by tableSql — the skeleton's own writer — and the tenancy is render()'s, so a defined table's
1022
+ * partner_id, indexes, ENABLE, FORCE and policy are the very statements a hand-filled skeleton carries and check holds.
1023
+ * Refused: a manifest that classifies a table differently from the set (render also refuses an unclassified,
1024
+ * platform, nullable or pre-existing one), and an anchor that is the app's principal table (opts.principalTable).
1025
+ * `opts` as for render: { partnerIdType, manifestName, preExisting, principalTable } — only partnerIdType reaches the text.
1026
+ */
1027
+ function renderDefinitions(manifest, set, base, opts = {}, layout = CURRENT_LAYOUT) {
1028
+ defs.assertTableDefinitions(set);
1029
+ if (typeof base !== 'string' || !/^[^/\\\s]+$/.test(base)) throw new Error(`renderDefinitions: base ${JSON.stringify(base)} is not a migration name`);
1030
+ if (!has(LAYOUTS, layout)) throw new Error(`renderDefinitions: no layout ${layout} (this db-worker has ${Object.keys(LAYOUTS).join(', ')})`);
1031
+ const manifestName = opts.manifestName || 'the manifest';
1032
+ const principal = opts.principalTable || 'users';
1033
+ if (has(set.anchors, principal)) {
1034
+ 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`);
1035
+ }
1036
+ const gens = set.tables.map((t) => {
1037
+ const g = render(manifest, t.name, opts);
1038
+ if ((g.customerColumn || null) !== (t.customer || null)) {
1039
+ throw new Error(`${t.name}: ${manifestName} classifies it ${g.customerColumn ? `as a CUSTOMER table (${g.customerColumn})` : 'as PARTNER only'}, `
1040
+ + `but ${set.name} ${set.version} defines it ${t.customer ? `as a CUSTOMER table (${t.customer})` : 'as PARTNER only'}`);
876
1041
  }
877
- lines.push(tail.join(',\n'), ');', g.index);
878
- if (g.customerColumn) lines.push(`CREATE INDEX idx_${g.table}_customer ON ${g.table}(${g.customerColumn}, partner_id);`);
879
- return lines.join('\n');
880
- };
881
- const pg = [...head('pg'), gens.map((g) => table(g, 'pg')).join('\n\n'), '',
882
- `-- ── ROW-LEVEL SECURITY (generated from ${manifestName}) ──`, '',
883
- gens.map((g) => g.rls.join('\n')).join('\n\n'), ''].join('\n');
884
- const lite = [...head('sqlite'), gens.map((g) => table(g, 'sqlite')).join('\n\n'), ''].join('\n');
885
- return { pg, lite };
1042
+ return g;
1043
+ });
1044
+ return LAYOUTS[layout](set, gens, base);
1045
+ }
1046
+
1047
+ /**
1048
+ * Where each set is named: policed files by their FIRST line (and that line must name the file itself); frozen files
1049
+ * by ANY line (a squashed baseline keeps the generated pair's first line as a line of its own).
1050
+ * A FROZEN FILE CARRYING THE GENERATED FIRST LINE IS COUNTED AS THE SET'S PAIR AND IS NOT COMPARED — so such a line
1051
+ * in a frozen file is believed. That is the trust model check already has for every frozen file: it never reads a
1052
+ * frozen file except to learn which tables it creates, because the app pins its frozen list (sha256) and reviews what
1053
+ * goes into it; a frozen file is the app's word, not the generator's to re-check.
1054
+ */
1055
+ function namedSets(files, post, frozen, problems) {
1056
+ const named = {};
1057
+ 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] });
1058
+ for (const f of post) {
1059
+ const first = firstLine(files[f]);
1060
+ const m = DEFINED_HEAD.exec(first);
1061
+ if (!m) continue;
1062
+ if (`${m[1]}${m[2] || ''}.sql` !== f || m[3] !== m[6]) { problems.push(`${f}: its first line names another file or set: ${first}`); continue; }
1063
+ add(m, { file: f, frozen: false });
1064
+ }
1065
+ for (const f of frozen) {
1066
+ if (!has(files, f)) continue;
1067
+ for (const line of files[f].replace(/\r\n/g, '\n').split('\n')) {
1068
+ const m = DEFINED_HEAD.exec(line);
1069
+ if (m && m[3] === m[6]) add(m, { file: f, frozen: true });
1070
+ }
1071
+ }
1072
+ return named;
1073
+ }
1074
+
1075
+ /**
1076
+ * check's half for definition sets: every policed pair whose first line names a set is held WHOLE, BYTE FOR BYTE (CRLF
1077
+ * read as LF), header included, to the layout its first line names, for the set the manifest carries; each set in
1078
+ * the manifest is generated by exactly one pair, at the version the manifest carries. A frozen file naming the set
1079
+ * counts as its pair and is not compared. → { problems, compared, frozen }.
1080
+ */
1081
+ function checkDefinitionFiles(files, manifest, post, frozen, opts) {
1082
+ const problems = [];
1083
+ let compared = 0;
1084
+ let frozenCount = 0;
1085
+ const sets = definitionSets(manifest, opts.manifestName);
1086
+ const named = namedSets(files, post, frozen, problems);
1087
+ for (const s of Object.keys(named)) {
1088
+ 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)`);
1089
+ }
1090
+ for (const set of sets) {
1091
+ const mine = named[set.name] || [];
1092
+ const pgs = mine.filter((x) => x.pg && !x.frozen);
1093
+ const fro = mine.filter((x) => x.frozen);
1094
+ const all = [...new Set([...pgs, ...fro].map((x) => x.file))];
1095
+ if (!all.length) { problems.push(`${set.name} ${set.version}: no migration is generated from it — run aria-tenancy new --definitions ${set.name}`); continue; }
1096
+ 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; }
1097
+ const p = pgs[0] || fro[0];
1098
+ if (p.version !== set.version) {
1099
+ 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`);
1100
+ continue;
1101
+ }
1102
+ if (p.frozen) { frozenCount++; continue; }
1103
+ 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; }
1104
+ const want = renderDefinitions(manifest, set, p.base, opts, p.layout);
1105
+ for (const [file, text] of [[p.file, want.pg], [`${p.base}.sql`, want.lite]]) {
1106
+ if (!has(files, file)) { problems.push(`${set.name}: no ${file} beside ${p.file}`); continue; }
1107
+ compared++;
1108
+ const d = firstDifference(files[file].replace(/\r\n/g, '\n'), text);
1109
+ if (d) {
1110
+ problems.push(`${file}: is not layout ${p.layout} of the generator for ${set.name} ${set.version} — ${d}. An applied file is never edited: `
1111
+ + `restore it. If it is unedited, the set changed (its comment included) without a new version — a changed set needs a new version`);
1112
+ }
1113
+ }
1114
+ 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`);
1115
+ }
1116
+ return { problems, compared, frozen: frozenCount };
1117
+ }
1118
+
1119
+ /** The first line at which two texts differ, for a message; null when equal. Never the whole text. */
1120
+ function firstDifference(have, want) {
1121
+ if (have === want) return null;
1122
+ const a = have.split('\n');
1123
+ const b = want.split('\n');
1124
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
1125
+ if (a[i] !== b[i]) {
1126
+ const cut = (s) => (s === undefined ? '(no line)' : JSON.stringify(s.length > 120 ? s.slice(0, 120) + '…' : s));
1127
+ return `line ${i + 1} is ${cut(a[i])}, the generator's is ${cut(b[i])}`;
1128
+ }
1129
+ }
1130
+ return 'they differ';
886
1131
  }
887
1132
 
888
1133
  /** Every *.sql in a folder, by name. */
@@ -909,6 +1154,11 @@ const renderOptions = (config, preExisting) => ({
909
1154
  * number, a number not after every frozen file, and whatever render refuses. → { base, files: { name: text } }.
910
1155
  */
911
1156
  function planNew(config, manifest, tables, { name = null, number = null, fillGap = false } = {}) {
1157
+ return planPair(config, manifest, tables, { name, number, fillGap }, (base, opts) => skeleton(manifest, tables, base, opts));
1158
+ }
1159
+
1160
+ /** planNew's checks and numbering, around a writer of the pair's text: `write(base, opts)` → { pg, lite }. */
1161
+ function planPair(config, manifest, tables, { name = null, number = null, fillGap = false } = {}, write) {
912
1162
  if (!tables.length) throw new Error(`name at least one table (classified in ${config.manifestName} first)`);
913
1163
  if (new Set(tables).size !== tables.length) throw new Error('a table is named twice');
914
1164
  for (const t of tables) if (!/^[a-z][a-z0-9_]*$/.test(t)) throw new Error(`"${t}" is not a table name`);
@@ -937,10 +1187,38 @@ function planNew(config, manifest, tables, { name = null, number = null, fillGap
937
1187
  if (!/^[a-z][a-z0-9_]*$/.test(slug)) throw new Error(`--name "${slug}" is not a slug`);
938
1188
  const base = `${nnn}_${slug}`;
939
1189
  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`);
940
- const { pg, lite } = skeleton(manifest, tables, base, opts);
1190
+ const { pg, lite } = write(base, opts);
941
1191
  return { base, files: { [`${base}.postgres.sql`]: pg, [`${base}.sql`]: lite } };
942
1192
  }
943
1193
 
1194
+ /**
1195
+ * 0.31.0 — plan the pair for the definition set named `setName` in the manifest's TABLE_DEFINITIONS (nothing is
1196
+ * written): planNew's refusals for its tables, plus a set some migration already names (it is generated once), and
1197
+ * then the tree WITH the new pair is checked: a pair that would fail `aria-tenancy check` (a key the app's
1198
+ * requireUpdateCascade refuses, a name an existing migration took) is refused before it is written. The slug defaults
1199
+ * to the set's name.
1200
+ */
1201
+ function planDefinitions(config, manifest, setName, { name = null, number = null, fillGap = false } = {}) {
1202
+ const sets = definitionSets(manifest, config.manifestName);
1203
+ const set = sets.find((s) => s.name === setName);
1204
+ if (!set) {
1205
+ throw new Error(`${config.manifestName} carries no table definitions named ${JSON.stringify(setName)} — spread tenancyFragment(set) into defineTenancy`
1206
+ + (sets.length ? ` (it carries ${sets.map((s) => s.name).join(', ')})` : ''));
1207
+ }
1208
+ const tree = readTree(config.migrationsDir);
1209
+ const named = namedSets(tree, Object.keys(tree).filter((f) => !config.frozen.includes(f)), config.frozen, []);
1210
+ 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`);
1211
+ const plan = planPair(config, manifest, set.tables.map((t) => t.name), { name: name || set.name, number, fillGap },
1212
+ (base, opts) => renderDefinitions(manifest, set, base, opts));
1213
+ const before = new Set(checkTree(checkOptions(config, manifest)).problems);
1214
+ const after = checkTree({ ...checkOptions(config, manifest), files: { ...tree, ...lfAll(plan.files) } }).problems.filter((p) => !before.has(p));
1215
+ if (after.length) throw new Error(`the generated pair would fail aria-tenancy check:\n ${after.join('\n ')}`);
1216
+ return plan;
1217
+ }
1218
+ const lfAll = (files) => Object.fromEntries(Object.entries(files).map(([k, v]) => [k, v.replace(/\r\n/g, '\n')]));
1219
+ /** A file's first line, CRLF read as LF. */
1220
+ const firstLine = (text) => text.replace(/\r\n/g, '\n').split('\n', 1)[0];
1221
+
944
1222
  /**
945
1223
  * Write a planned pair so that a failure cannot leave half of it: each file first to a temporary name in the same
946
1224
  * folder (not *.sql, so no runner ever reads it), then each LINKED to its name (a link refuses an existing file, so
@@ -965,6 +1243,7 @@ function writePair(dir, files, io = fs) {
965
1243
 
966
1244
  module.exports = {
967
1245
  CONFIG_FILE, loadConfig, loadManifest, render, skeleton, checkTree, checkOptions, renderOptions, planNew, writePair,
1246
+ renderDefinitions, planDefinitions, definitionSets, DEFINED_HEAD, CURRENT_LAYOUT, DEFINITION_LAYOUTS: Object.keys(LAYOUTS).map(Number),
968
1247
  splitStatements, keysIn, readTree, constraintNames, droppedCheck, compareKeys, createdByFrozen, pgPartnerId,
969
1248
  PARTNER_ID_TYPES, SQLITE_PARTNER_ID
970
1249
  };
@@ -139,6 +139,10 @@ function defineTenancy(lists) {
139
139
 
140
140
  const out = { ...lists };
141
141
  for (const k of DECIDED) if (out[k] === undefined) out[k] = {};
142
+ // 0.31.0 — tables a package defines (tableDefinitions.js), spread in as tenancyFragment(...sets): classified HERE,
143
+ // from the definitions, and a manifest that classifies one of them differently is refused. Without the key nothing
144
+ // below runs and the manifest gets exactly the keys and values it got before.
145
+ if (lists.TABLE_DEFINITIONS !== undefined) mergeDefinitions(lists, out);
142
146
  const { PARTNER, PLATFORM, PARTNER_NULLABLE, EXCLUDED } = out;
143
147
 
144
148
  // ── PLATFORM_POSTGRES_ONLY IS NEVER IN all() ───────────────────────────────────────────────
@@ -161,8 +165,8 @@ function defineTenancy(lists) {
161
165
 
162
166
  out.POLICY_EXPRESSION = POLICY_EXPRESSION;
163
167
  // Only for a manifest with a customer tier (or one that brought its own, equal, function): a manifest without one
164
- // gets exactly the keys it got before.
165
- if (lists.CUSTOMER !== undefined || ownCustomerPolicy) out.CUSTOMER_POLICY_EXPRESSION = CUSTOMER_POLICY_EXPRESSION;
168
+ // gets exactly the keys it got before. (out.CUSTOMER: a definition set's customer tables give a manifest one.)
169
+ if (out.CUSTOMER !== undefined || ownCustomerPolicy) out.CUSTOMER_POLICY_EXPRESSION = CUSTOMER_POLICY_EXPRESSION;
166
170
  /** Every table with a decision, in any list — what the classification guard checks against. */
167
171
  out.all = () => [
168
172
  ...Object.keys(PARTNER),
@@ -178,6 +182,44 @@ function defineTenancy(lists) {
178
182
  return out;
179
183
  }
180
184
 
185
+ /**
186
+ * 0.31.0 — the classification of the tables in lists.TABLE_DEFINITIONS (an array of sets built with defineTables, as
187
+ * tenancyFragment gives it), merged into `out`: each table into PARTNER (its description as the reason) and a
188
+ * customer table into CUSTOMER. Refused: a value that is not such an array, a table in two sets, and an app list that
189
+ * classifies a defined table differently — in PLATFORM, PARTNER_NULLABLE, EXCLUDED or PLATFORM_POSTGRES_ONLY, with
190
+ * another customer column, or with one where the definition has none. The app listing a table exactly as its
191
+ * definition does (PARTNER, and the same column) is the same classification and accepted.
192
+ */
193
+ function mergeDefinitions(lists, out) {
194
+ const { isTableDefinitions, classificationOf } = require('./tableDefinitions');
195
+ const sets = lists.TABLE_DEFINITIONS;
196
+ if (!Array.isArray(sets) || !sets.length || !sets.every(isTableDefinitions)) {
197
+ throw new Error('defineTenancy: TABLE_DEFINITIONS is what tenancyFragment(...sets) gives — sets built with defineTables');
198
+ }
199
+ const from = {};
200
+ const PARTNER = { ...out.PARTNER };
201
+ const CUSTOMER = { ...(lists.CUSTOMER || {}) };
202
+ let customerTables = false;
203
+ for (const set of sets) {
204
+ const c = classificationOf(set);
205
+ for (const t of Object.keys(c.PARTNER)) {
206
+ if (from[t]) throw new Error(`defineTenancy: ${t} is defined by both ${from[t]} and ${set.name}`);
207
+ from[t] = set.name;
208
+ const elsewhere = ['PLATFORM', 'PARTNER_NULLABLE', 'EXCLUDED', 'PLATFORM_POSTGRES_ONLY'].find((k) => Object.prototype.hasOwnProperty.call(lists[k] || {}, t));
209
+ if (elsewhere) throw new Error(`defineTenancy: ${t} is in ${elsewhere}, but ${set.name} ${set.version} defines it as a PARTNER${c.CUSTOMER[t] ? ' and CUSTOMER' : ''} table`);
210
+ const theirs = Object.prototype.hasOwnProperty.call(CUSTOMER, t) ? CUSTOMER[t] : null;
211
+ const ours = c.CUSTOMER[t] || null;
212
+ if (Object.prototype.hasOwnProperty.call(lists.CUSTOMER || {}, t) && theirs !== ours) {
213
+ throw new Error(`defineTenancy: CUSTOMER.${t} is ${JSON.stringify(theirs)}, but ${set.name} ${set.version} defines it as ${ours ? `a CUSTOMER table with the column ${ours}` : 'a PARTNER-only table'}`);
214
+ }
215
+ if (!Object.prototype.hasOwnProperty.call(PARTNER, t)) PARTNER[t] = c.PARTNER[t];
216
+ if (ours) { CUSTOMER[t] = ours; customerTables = true; }
217
+ }
218
+ }
219
+ out.PARTNER = PARTNER;
220
+ if (lists.CUSTOMER !== undefined || customerTables) out.CUSTOMER = CUSTOMER;
221
+ }
222
+
181
223
  module.exports = {
182
224
  defineTenancy, TENANCY_POLICY_EXPRESSION: POLICY_EXPRESSION, CUSTOMER_POLICY_EXPRESSION, assertSameCustomerPolicy
183
225
  };