@aria-framework/db-worker 0.30.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.
package/README.md CHANGED
@@ -761,8 +761,151 @@ app's applied customer policies (one per table in its `CUSTOMER` map) from this
761
761
  CUSTOMER table. A manifest that still carries its own `CUSTOMER_POLICY_EXPRESSION` is accepted only when it produces
762
762
  the same text (for every column its `CUSTOMER` names, and `customer_id`), and refused otherwise.
763
763
 
764
+ ## Table definitions as data (0.31.0)
765
+
766
+ A package that needs tables in the app's database (a shared feature's grants, requests, settings) cannot apply SQL
767
+ from `node_modules` (a second ledger, and an upgrade would change an applied file) and must not create tables at boot.
768
+ So it ships the tables as a DEFINITION SET, and the app's own generator writes them into the app's own migration pair,
769
+ which the app commits, applies and never edits, like any other.
770
+
771
+ ```js
772
+ // in the package
773
+ const { defineTables } = require('@aria-framework/db-worker');
774
+ module.exports = defineTables({
775
+ name: 'access', version: '1.0.0',
776
+ comment: ['what these tables are for — carried into the migration as its comment block'],
777
+ anchors: { // tables the APP owns that this set relies on, what they are, and what the set needs of them
778
+ customers: { tenancy: { customer: 'id' }, columns: [{ name: 'id', type: 'TEXT', notNull: true }, { name: 'partner_id', type: 'PARTNER_ID', notNull: true }],
779
+ unique: [['id', 'partner_id']] }
780
+ },
781
+ tables: [{
782
+ name: 'grants', description: 'a customer letting its helper in for a while', tenancy: { customer: 'customer_id' },
783
+ columns: [
784
+ { name: 'level', type: 'TEXT', notNull: true, check: "level IN ('look', 'change')" },
785
+ { name: 'given_by', type: { postgres: 'BIGINT', sqlite: 'INTEGER' } },
786
+ { name: 'state', type: 'TEXT', notNull: true, default: { text: 'live' } },
787
+ { name: 'ended_at', type: 'TEXT' }
788
+ ],
789
+ constraints: [{ name: 'ck_grants_ended', check: "(state = 'live') = (ended_at IS NULL)" }]
790
+ }],
791
+ indexes: [{ name: 'uq_grants_live', table: 'grants', unique: true, columns: ['customer_id', 'partner_id'], where: "state = 'live'" }]
792
+ });
793
+
794
+ // in the app's config/tenancy.js — all its sets in ONE call
795
+ module.exports = defineTenancy({ PARTNER: {...}, PLATFORM: {...}, CUSTOMER: {...}, ...tenancyFragment(accessTables) });
796
+ ```
797
+
798
+ ```
799
+ npx aria-tenancy new --definitions access [--name <slug>] [--number <NNN> [--fill-gap]] [--print]
800
+ npx aria-tenancy check
801
+ ```
802
+
803
+ | Export | What it does | What it refuses |
804
+ |---|---|---|
805
+ | `defineTables(set)` | validates the set and returns a deep-frozen copy | each refusal has a code (`err.refusal`, the list is `REFUSALS` in `tableDefinitions.js`): a name that is not a plain identifier (or is over 63 characters); a reserved word of PostgreSQL or SQLite (`RESERVED`: PostgreSQL's reserved key words and every SQLite keyword, e.g. `user`, `order`, `key`); a table whose name makes a name the GENERATOR writes for it (`uq_…`, `fk_…`, `idx_…`) longer than 63 bytes — PostgreSQL would truncate it; a name used twice or one the generator writes; a unique key or unique index without `partner_id`; a PARTNER-only table with a column named `customer_id` (or like any CUSTOMER table's customer column in the set), or with a key into customer data — a CUSTOMER table of the set or a CUSTOMER anchor (a PARTNER table keys only into PARTNER tables and PARTNER anchors); an anchor without its tenancy (`'PARTNER'`, or `{ customer: <column> }` naming one of its columns; `customers` is always `{ customer: 'id' }`); an anchor named `users`; two string literals side by side; a column the generator writes (`id`, `partner_id`, the customer column, `created_at`); a type other than `TEXT`, `INTEGER`, `BIGINT` (or `{ postgres, sqlite }` of them); a default other than `{ text }`, `{ integer }`, `{ utcNow: true }` or one that does not fit its type; an expression (a CHECK, an index's WHERE) using anything but its table's columns, literals, the comparison and arithmetic operators, `AND OR NOT IN IS NULL BETWEEN LIKE TRUE FALSE` and `length lower upper`; a key into a table that is neither in the set nor an anchor, whose sides differ in length, without `partner_id` at the same position on both sides, or into columns that are not a unique key of the target; `ON DELETE` / `ON UPDATE` other than `NO ACTION`, `RESTRICT`, `CASCADE`; an anchor without `partner_id` (type `PARTNER_ID`, not null); a CUSTOMER table without the anchor `customers (id, partner_id)` and that key |
806
+ | `tenancyFragment(...sets)` | `{ TABLE_DEFINITIONS: [...sets] }`, for the app to spread into `defineTenancy` | a value not built with `defineTables`, a set passed twice, a table in two sets |
807
+ | `defineTenancy({ ..., TABLE_DEFINITIONS })` | classifies each defined table: `PARTNER` (its description as the reason), and `CUSTOMER` with its column; a set's customer tables give a manifest a `CUSTOMER` map (and the package's policy text) | the app classifying a defined table differently: in `PLATFORM`, `PARTNER_NULLABLE`, `EXCLUDED` or `PLATFORM_POSTGRES_ONLY`, with another customer column, or as a customer table where the set has none. Listing it exactly as the set does is accepted |
808
+ | `classificationOf(set)` | `{ PARTNER, CUSTOMER }` of the set's tables | |
809
+ | `aria-tenancy new --definitions <set>` | writes the set's pair: the generator's header naming the set, its version and the layout, the set's comment, each `CREATE TABLE` with the skeleton's generated parts and the set's own columns and constraints, the set's indexes after the tables, and on Postgres the generated ENABLE, FORCE and policy — the same writer and the same tenancy as a hand-filled skeleton. `--print` writes nothing | a set the manifest does not carry, table names beside it, a set some migration already names (a set is generated once), everything `new` refuses for its tables, an anchor that is the app's `principalTable`, and a pair that would fail `aria-tenancy check` (for example a key without `ON UPDATE CASCADE` in an app with `requireUpdateCascade`) |
810
+ | `aria-tenancy check` | additionally holds every policed pair whose first line names a set WHOLE, header line included, BYTE FOR BYTE (CRLF read as LF) to the output of the layout that first line names, for the set the manifest carries. A FROZEN file that names the set (on any line) counts as its pair and is not compared | a set the manifest carries that no pair generates; a pair generated from another version of it; a pair naming a set the manifest does not carry; a layout this db-worker does not have; a file that differs (the message says: restore it, or, if unedited, the set changed without a new version) |
811
+ | `checkDefinedSchema(driver, sets, { partnerIdType })` | compares the database with the sets, through the driver and the dialect's introspection; returns `{ problems, compared }` (counts of tables, columns, keys, indexes, policies and anchors looked at) | a driver, a set or (on Postgres) a `partnerIdType` missing |
812
+ | `assertDefinedSchema(...)` | the same, throwing `TABLE_DEFINITIONS_MISMATCH` naming every problem: what a package calls when the app starts | |
813
+
814
+ **A definitions file is frozen, and so is the layout that wrote it.** Its first line reads, for example,
815
+
816
+ ```
817
+ -- 099_demo.postgres.sql — GENERATED from the table definitions demo 1.2.0, layout 1 (aria-tenancy new --definitions demo).
818
+ ```
819
+
820
+ and `check` compares the whole file with what THAT layout writes. A layout's output is a function of the set (name,
821
+ version, tables, indexes, anchors, comment), the frozen policy texts, the app's `partnerIdType` and the file's own
822
+ name — never of the manifest's path, the app's folders or when it runs — so an applied file stays equal to its
823
+ layout for ever. Two rules follow:
824
+
825
+ - **Changing any part of a set, its comment included, needs a new version.** `defineTables` cannot know that a
826
+ comment changed; `check` then reports the applied file as different, and its message names that possibility.
827
+ - **Changing how a definitions file is written is a NEW LAYOUT**, never an edit of layout 1: layout 1's output for
828
+ four fixture sets (one of them, `test/fixtures/tenancy-definitions-edge.js`, exists to take every branch of the writer
829
+ the others do not; the branch table is above the pins) is pinned by sha256 in `test/tableDefinitions.js` ("this text is inside migrations apps have
830
+ applied"), so a change to the shared writers that alters it fails the package's own tests. The new layout gets its
831
+ number; layout 1 stays in `tenancyGenerator.js` (`LAYOUTS`) for the files it wrote, selected by their first line.
832
+
833
+ An app that later puts a generated pair in its `frozen` list, or squashes it into a frozen baseline, keeps the pair's
834
+ first line somewhere in a frozen file: `check` then counts that file as the set's pair and does not compare it (the
835
+ app pins it). A squash that drops the line leaves the set "not generated".
836
+
837
+ **Conventions for a package author.** A column naming a user is a plain column with no key (as the reproduced
838
+ migrations have it): a key into the principal table is attribution, and `defineTables` refuses an anchor named
839
+ `users` (and `new` the app's own `principalTable`). Whether a set's keys pass an app's `requireUpdateCascade` /
840
+ `NO_CASCADE` rules is found when that app generates, not in `defineTables`: write every key of a set `ON UPDATE
841
+ CASCADE` — an app that re-parents rows (`requireUpdateCascade`) requires it of every key that is not attribution, and
842
+ an app that does not accepts it — and have no attribution keys at all (a user is a plain column, above), so no app's
843
+ `NO_CASCADE` can name one.
844
+
845
+ A customer's id is held only in the table's declared customer column (`tenancy: { customer }`): a PARTNER table that
846
+ holds a customer's id under another name (`client_id`) cannot be caught by name — that is the author's error and the
847
+ reviewer's to catch.
848
+
849
+ The reserved-word refusal covers common names an author may reach for: `key`, `action`, `index`, `plan`, `row`,
850
+ `filter`, `first`, `last`, `desc`, `query`, `match`, `range`, `current`, `database`, `temp`, `view`, `values`,
851
+ `generated` (and `user`, `order`, `group`, …). Name them `key_name`, `row_count` and so on.
852
+
853
+ **Expressions that mean different things on the two engines, with no error on either** (the tokenizer cannot see
854
+ these; write CHECKs and WHERE clauses with `IN` lists, `=` / `<>`, numbers and `length`):
855
+ - a comparison of TEXT with `<` / `>` (or `BETWEEN` on text) follows collation: the PostgreSQL database's locale
856
+ against SQLite's byte order;
857
+ - `LIKE` is case-sensitive only on PostgreSQL (SQLite ignores ASCII case); `lower` / `upper` differ on non-ASCII text.
858
+
859
+ String literals assume `standard_conforming_strings` is on (the PostgreSQL default): a backslash is an ordinary
860
+ character inside `'…'`. A parenthesised operand of `BETWEEN` is accepted (`v BETWEEN (1) AND 2`).
861
+
862
+ **What the schema check compares.** Per defined table: it exists; every column (defined and generated) with its type
863
+ and NOT NULL; `partner_id`'s DEFAULT against the one the generator writes (a default changed by hand would put a
864
+ platform-scope insert into the wrong partner); the primary key `id`; the unique keys; the named indexes (unique or not, columns in order, partial or
865
+ not); the foreign keys (columns, target, target columns, both actions); and on Postgres ENABLE and FORCE, exactly one
866
+ policy, `tenant_isolation`, PERMISSIVE, FOR ALL, TO public, its USING and WITH CHECK the package's frozen text. **Any
867
+ column, unique key, named index, key or policy the set does not have is a problem too**: a column an app adds to a
868
+ package's table is reported, because the package's code and migration do not know it. Per anchor: the stated columns
869
+ (type, NOT NULL) and a primary key, unique constraint or unique non-partial index on each stated key (any column
870
+ order); its other columns are the app's. **What it does not compare:** CHECK constraints and the other defaults (the engines
871
+ rewrite their text), an index's WHERE text (only that it is partial), and the policy text beyond parentheses,
872
+ whitespace and the casts the server adds (the server keeps a policy deparsed), so a policy differing only in
873
+ parenthesisation would pass; `aria-tenancy check` holds the file itself byte for byte. SQLite has no policies, and the
874
+ result says so (`compared.policies` is 0).
875
+
876
+ **Dialect introspection added** (`dialectFor(kind)`, both engines, one row shape): `columnDetails(table)`,
877
+ `indexes(table)`, `keyColumns(table)`, `policies(table)` (null on SQLite). `columns()` and `foreignKeys()` are
878
+ unchanged. On Postgres `foreignKeys()` joins its catalogue views by constraint name only, so a key of n columns answers
879
+ n × n rows, and it reads a view that lists only tables the current role owns, so an app role that owns nothing gets
880
+ no rows; both measured in `test/tableDefinitions.pglite.js`. `keyColumns()` pairs by position from `pg_constraint`.
881
+
882
+ **What the format cannot express**, refused rather than approximated: a primary key other than `id`; a table without
883
+ `created_at`; another column type; `SET NULL` or `SET DEFAULT` actions (SQLite cannot name a `SET NULL` column, a bare
884
+ one nulls `partner_id`, `SET DEFAULT` re-parents a row); a key into a table outside the set and its anchors (so never
885
+ into `users`); a `PARTNER_NULLABLE` table; and any change to tables that exist — a set is created once, and a changed
886
+ version is reported by `check`, not generated (there is no upgrade path yet).
887
+
888
+ `test/tableDefinitions.js` reproduces one app's applied 053 and 054 (four files) from a definition fixture
889
+ (`test/fixtures/tenancy-definitions-wall.js`): every line of each body is the generator's but for 053's own-column
890
+ lines, which that app aligned by hand two spaces wider (the residue is derived from the definitions and checked), the
891
+ header its own generator wrote, and the row-level-security heading, which named its manifest's path (layout 1 never
892
+ writes one). It also runs every refusal with an accepted control, holds manifests without sets
893
+ and every skeleton to the hashes origin/main produced, runs the SQLite twins and the command. `test/tableDefinitions.pglite.js`
894
+ applies the generated Postgres files on PGlite as a role the policies apply to (partner and customer-pinned reads,
895
+ cross-partner references refused by the composite keys) and plants a difference of each kind for the schema check.
896
+
764
897
  ## Changelog
765
898
 
899
+ - **0.31.0** — Table definitions as data (above): `defineTables`, `tenancyFragment`, `classificationOf`,
900
+ `isTableDefinitions`, `TableDefinitionError`, `checkDefinedSchema`, `assertDefinedSchema`; `defineTenancy` reads
901
+ `TABLE_DEFINITIONS`; `aria-tenancy new --definitions <set>`, and `check` holds generated pairs byte for byte; the
902
+ library `tenancyGenerator.js` gains `renderDefinitions`, `planDefinitions`, `definitionSets`, `DEFINED_HEAD`,
903
+ `CURRENT_LAYOUT`, `DEFINITION_LAYOUTS` (layout 1, frozen and pinned); the
904
+ dialects gain `columnDetails`, `indexes`, `keyColumns`, `policies`. Additive: a manifest without `TABLE_DEFINITIONS`
905
+ gets exactly the keys and values it got before, the skeleton and `check` render and answer byte for byte as before
906
+ (hashed against origin/main in `test/tableDefinitions.js`), and the skeleton's table writer is now the one writer
907
+ both use. Tests (in `npm test`): `tableDefinitions.js`, `tableDefinitions.pglite.js`.
908
+
766
909
  - **0.30.0** — The customer pin (above), moved in from the first app that built it: `runPinned`, `runUnpinnedFor`,
767
910
  `currentPin`, `activePin`, `pinnedCustomer`, `pinClause`, `normalisePin`, `isPinId`, `PIN_SQL`, `pinParams`;
768
911
  `createCustomerScope`; the `DbClient` option `customerPin` and the `runWorker` option `customerScope`;
package/bin/tenancy.js CHANGED
@@ -4,6 +4,9 @@
4
4
  *
5
5
  * aria-tenancy new <table...> [--name <slug>] [--number <NNN> [--fill-gap]] write a NEW .sql / .postgres.sql pair
6
6
  * aria-tenancy new --print <table...> print the generated statements; write nothing
7
+ * aria-tenancy new --definitions <set> [--name …] [--number …] [--print]
8
+ * 0.31.0: write (or print) the pair for a package's
9
+ * table definitions the manifest carries
7
10
  * aria-tenancy check exit 1 unless every policed migration carries
8
11
  * exactly the generated statements
9
12
  *
@@ -17,7 +20,8 @@ const fs = require('fs');
17
20
  const path = require('path');
18
21
  const gen = require('../tenancyGenerator');
19
22
 
20
- const USAGE = 'usage: aria-tenancy new <table...> [--name <slug>] [--number <NNN> [--fill-gap]] [--print]\n aria-tenancy check';
23
+ const USAGE = 'usage: aria-tenancy new <table...> [--name <slug>] [--number <NNN> [--fill-gap]] [--print]\n'
24
+ + ' aria-tenancy new --definitions <set> [--name <slug>] [--number <NNN> [--fill-gap]] [--print]\n aria-tenancy check';
21
25
  const fail = (msg) => { console.error(`aria-tenancy: ${msg}`); process.exit(1); };
22
26
 
23
27
  function appDir() {
@@ -49,6 +53,7 @@ if (command === 'check') {
49
53
  console.log(`tenancy of the tables born after the frozen migrations (aria-tenancy check, ${config.migrationsName}/):`);
50
54
  console.log(` ${stats.tables.length} scoped table(s) in ${config.manifestName} born after the frozen migrations; ${stats.created.length} created by a policed migration`);
51
55
  console.log(` ${stats.statementsCompared} generated statement(s) compared, ${stats.keysChecked} key(s) into scoped tables checked (${stats.pgKeys} Postgres), across ${stats.files} policed migration file(s)`);
56
+ if (stats.definitionFiles !== undefined) console.log(` ${stats.definitionFiles} file(s) generated from table definitions held to the generator byte for byte`);
52
57
  if (problems.length) {
53
58
  for (const p of problems) console.log(` ✗ ${p}`);
54
59
  console.log(`\n${problems.length} problem(s) — regenerate with aria-tenancy new; never hand-write tenancy.`);
@@ -72,8 +77,23 @@ const print = flag('print');
72
77
  const fillGap = flag('fill-gap');
73
78
  const name = opt('name');
74
79
  const number = opt('number');
80
+ const definitions = opt('definitions');
75
81
  if (argv.some((a) => a.startsWith('--'))) fail(`unknown option ${argv.find((a) => a.startsWith('--'))}\n${USAGE}`);
76
82
  const tables = argv;
83
+ if (definitions !== null) {
84
+ // 0.31.0 — the tables are the set's; the pair is written whole or not at all, as below.
85
+ if (tables.length) fail(`--definitions takes no table names (the set names its tables), got ${tables.join(' ')}`);
86
+ try {
87
+ const { files } = gen.planDefinitions(config, manifest, definitions, { name, number, fillGap });
88
+ if (print) {
89
+ for (const [f, text] of Object.entries(files)) console.log(`-- ═══ ${f} ═══\n${text}`);
90
+ } else {
91
+ gen.writePair(config.migrationsDir, files);
92
+ console.log(` wrote ${Object.keys(files).map((f) => `${config.migrationsName}/${f}`).join(' and ')} — generated whole from ${definitions}; commit them and never edit them`);
93
+ }
94
+ } catch (e) { fail(e.message); }
95
+ process.exit(0);
96
+ }
77
97
  if (!tables.length) fail(`name at least one table (classified in ${config.manifestName} first)`);
78
98
 
79
99
  try {
package/dialect.js CHANGED
@@ -71,6 +71,26 @@ const sqlite = {
71
71
  * SQL for the same answer, which is precisely why it belongs here once rather than in each app.
72
72
  */
73
73
  foreignKeys: (table) => `PRAGMA foreign_key_list(${ident(table)})`,
74
+ // 0.31.0 — THE REST OF A TABLE'S SHAPE, for the table-definitions schema check (tableDefinitionsCheck.js), in one
75
+ // row shape on both engines like the three above. columns() and foreignKeys() stay as they are: columns() answers
76
+ // names only, and foreignKeys() pairs no columns by position (see the postgres twin), so a composite key needs
77
+ // keyColumns().
78
+ /**
79
+ * Each column: `{ name, type (upper case), notnull (0/1), pk (its position in the primary key, 0 if none), dflt (its
80
+ * default as the engine keeps it, or null) }`.
81
+ */
82
+ columnDetails: (table) => `SELECT name, upper(type) AS type, "notnull" AS "notnull", pk, dflt_value AS dflt FROM pragma_table_info(${strLit(table)}) ORDER BY cid`,
83
+ /**
84
+ * Each index, one row per column in order: `{ name, unique (0/1), origin ('pk' | 'u' (backs a UNIQUE / PRIMARY KEY
85
+ * constraint) | 'c' (CREATE INDEX)), partial (0/1), seq, col }`. A rowid primary key has no index here.
86
+ */
87
+ indexes: (table) => `SELECT il.name AS name, il."unique" AS "unique", il.origin AS origin, il.partial AS partial, ii.seqno AS seq, ii.name AS col`
88
+ + ` FROM pragma_index_list(${strLit(table)}) AS il JOIN pragma_index_info(il.name) AS ii ORDER BY il.name, ii.seqno`,
89
+ /** Each foreign key, one row per column pair in order: `{ id, seq, parent, col, parent_col, on_delete, on_update }`. */
90
+ keyColumns: (table) => `SELECT id, seq, "table" AS parent, "from" AS col, "to" AS parent_col, on_delete, on_update`
91
+ + ` FROM pragma_foreign_key_list(${strLit(table)}) ORDER BY id, seq`,
92
+ /** Row-level security: SQLite has none, so there is no query (null). */
93
+ policies: () => null,
74
94
  /**
75
95
  * N minutes AFTER now — an expiry window.
76
96
  *
@@ -187,6 +207,52 @@ const postgres = {
187
207
  + ` ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema`
188
208
  + ` WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = 'public'`
189
209
  + ` AND tc.table_name = ${strLit(table)}`,
210
+ // 0.31.0 — the sqlite twin's four, from the system catalogues. (foreignKeys() above joins key_column_usage to
211
+ // constraint_column_usage by the constraint's NAME only, so a key of n columns answers n × n rows with no pairing,
212
+ // and constraint_column_usage lists only tables the current role OWNS, so for an app role that owns nothing it
213
+ // answers no rows at all — both measured on PGlite in test/tableDefinitions.pglite.js. It is left as it is;
214
+ // keyColumns() pairs by position and reads pg_constraint, which every role can.)
215
+ columnDetails: (table) => 'SELECT c.column_name AS name, upper(c.data_type) AS type,'
216
+ + " CASE WHEN c.is_nullable = 'NO' THEN 1 ELSE 0 END AS \"notnull\","
217
+ + ' COALESCE((SELECT k.ord::int FROM pg_constraint pk'
218
+ + ' JOIN pg_class pt ON pt.oid = pk.conrelid JOIN pg_namespace pn ON pn.oid = pt.relnamespace'
219
+ + ' CROSS JOIN LATERAL unnest(pk.conkey) WITH ORDINALITY AS k(att, ord)'
220
+ + ' JOIN pg_attribute a ON a.attrelid = pk.conrelid AND a.attnum = k.att'
221
+ + " WHERE pk.contype = 'p' AND pn.nspname = 'public' AND pt.relname = c.table_name AND a.attname = c.column_name), 0) AS pk,"
222
+ + ' c.column_default AS dflt'
223
+ + ' FROM information_schema.columns c'
224
+ + ` WHERE c.table_schema = 'public' AND c.table_name = ${strLit(table)} ORDER BY c.ordinal_position`,
225
+ indexes: (table) => 'SELECT ic.relname AS name, CASE WHEN x.indisunique THEN 1 ELSE 0 END AS "unique",'
226
+ + " CASE WHEN x.indisprimary THEN 'pk' WHEN EXISTS (SELECT 1 FROM pg_constraint con WHERE con.conindid = x.indexrelid"
227
+ + " AND con.conrelid = x.indrelid AND con.contype IN ('u', 'p')) THEN 'u' ELSE 'c' END AS origin,"
228
+ + ' CASE WHEN x.indpred IS NULL THEN 0 ELSE 1 END AS partial, (k.ord - 1)::int AS seq, a.attname AS col'
229
+ + ' FROM pg_index x JOIN pg_class t ON t.oid = x.indrelid JOIN pg_namespace n ON n.oid = t.relnamespace'
230
+ + ' JOIN pg_class ic ON ic.oid = x.indexrelid'
231
+ + ' CROSS JOIN LATERAL unnest(x.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord)'
232
+ + ' LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum'
233
+ + ` WHERE n.nspname = 'public' AND t.relname = ${strLit(table)} ORDER BY ic.relname, k.ord`,
234
+ keyColumns: (table) => {
235
+ const act = (c) => `CASE ${c} WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE'`
236
+ + ` WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END`;
237
+ return `SELECT c.conname AS id, (k.ord - 1)::int AS seq, p.relname AS parent, a.attname AS col, pa.attname AS parent_col,`
238
+ + ` ${act('c.confdeltype')} AS on_delete, ${act('c.confupdtype')} AS on_update`
239
+ + ' FROM pg_constraint c JOIN pg_class t ON t.oid = c.conrelid JOIN pg_namespace n ON n.oid = t.relnamespace'
240
+ + ' JOIN pg_class p ON p.oid = c.confrelid'
241
+ + ' CROSS JOIN LATERAL unnest(c.conkey, c.confkey) WITH ORDINALITY AS k(att, patt, ord)'
242
+ + ' JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.att'
243
+ + ' JOIN pg_attribute pa ON pa.attrelid = c.confrelid AND pa.attnum = k.patt'
244
+ + ` WHERE c.contype = 'f' AND n.nspname = 'public' AND t.relname = ${strLit(table)} ORDER BY c.conname, k.ord`;
245
+ },
246
+ /**
247
+ * A table's row-level security and its policies, one row per policy (one row with name NULL when it has none):
248
+ * `{ rls, force, name, permissive, roles (comma-joined), cmd, qual, with_check }` — qual and with_check as the
249
+ * server deparses them, not as the migration typed them.
250
+ */
251
+ policies: (table) => 'SELECT c.relrowsecurity AS rls, c.relforcerowsecurity AS "force", p.policyname AS name,'
252
+ + " p.permissive AS permissive, array_to_string(p.roles, ',') AS roles, p.cmd AS cmd, p.qual AS qual, p.with_check AS with_check"
253
+ + ' FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace'
254
+ + ' LEFT JOIN pg_policies p ON p.schemaname = n.nspname AND p.tablename = c.relname'
255
+ + ` WHERE n.nspname = 'public' AND c.relname = ${strLit(table)} AND c.relkind IN ('r', 'p') ORDER BY p.policyname`,
190
256
  nowPlusMinutes: (n) => `to_char((NOW() + INTERVAL '${Number(n)} minutes') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
191
257
  // date_trunc on the UTC value, not on NOW(): truncating a timestamptz uses the SESSION time
192
258
  // zone, so 'start of month' would land on a different instant depending on where the server
package/index.js CHANGED
@@ -58,5 +58,14 @@ module.exports = {
58
58
  // 0.30.0 — the customer pin: the third level under the tenant context's two (customerPin.js), the worker's
59
59
  // customer-safe lock (createCustomerScope), and — on tenancyManifest above — the frozen CUSTOMER_POLICY_EXPRESSION.
60
60
  ...require('./customerPin'),
61
- createCustomerScope: require('./customerScope').createCustomerScope
61
+ createCustomerScope: require('./customerScope').createCustomerScope,
62
+ // 0.31.0 — tables a package needs, as DATA (tableDefinitions.js): the app's own generator writes them into the app's
63
+ // own migration (aria-tenancy new --definitions), and the package checks the database against them at boot.
64
+ defineTables: require('./tableDefinitions').defineTables,
65
+ tenancyFragment: require('./tableDefinitions').tenancyFragment,
66
+ classificationOf: require('./tableDefinitions').classificationOf,
67
+ isTableDefinitions: require('./tableDefinitions').isTableDefinitions,
68
+ TableDefinitionError: require('./tableDefinitions').TableDefinitionError,
69
+ checkDefinedSchema: require('./tableDefinitionsCheck').checkDefinedSchema,
70
+ assertDefinedSchema: require('./tableDefinitionsCheck').assertDefinedSchema
62
71
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.30.0",
3
+ "version": "0.31.0",
4
4
  "description": "Aria App Framework — db-worker module. Async RPC bridge over synchronous better-sqlite3: a worker-thread dispatcher (runWorker), a main-thread client with per-call timeouts and crash handling (DbClient), and a SQLite layer with WAL pragmas + a numbered-migration runner (database).",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -24,6 +24,8 @@
24
24
  "settingsStore.js",
25
25
  "sql.js",
26
26
  "tableOrder.js",
27
+ "tableDefinitions.js",
28
+ "tableDefinitionsCheck.js",
27
29
  "tenancyManifest.js",
28
30
  "tenancyGenerator.js",
29
31
  "tenancyMigration.js",
@@ -51,7 +53,7 @@
51
53
  "pg": "^8.23.0"
52
54
  },
53
55
  "scripts": {
54
- "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationFailureSurfaces.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyAttribution.pglite.js && node test/tenancyNullable.pg.js && node test/tenancyPartnerFk.pg.js && node test/tenancyOnUpdate.pg.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/clientError.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js && node test/timezone.pg.js && node test/pinPoolUtc.js && node test/pinAwaited.pg.js && node test/inTransaction.js && node test/sql.js && node test/tenancyManifest.js && node test/tenantScope.js && node test/tenantSettings.js && node test/dbClientRefusal.js && node test/migrationsSquash.js && node test/tenancyGenerator.js && node test/customerPin.js && node test/customerPin.pglite.js",
56
+ "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationFailureSurfaces.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyAttribution.pglite.js && node test/tenancyNullable.pg.js && node test/tenancyPartnerFk.pg.js && node test/tenancyOnUpdate.pg.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/clientError.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js && node test/timezone.pg.js && node test/pinPoolUtc.js && node test/pinAwaited.pg.js && node test/inTransaction.js && node test/sql.js && node test/tenancyManifest.js && node test/tenantScope.js && node test/tenantSettings.js && node test/dbClientRefusal.js && node test/migrationsSquash.js && node test/tenancyGenerator.js && node test/customerPin.js && node test/customerPin.pglite.js && node test/tableDefinitions.js && node test/tableDefinitions.pglite.js",
55
57
  "prepublishOnly": "node ../../test/packaging.js db-worker"
56
58
  }
57
59
  }