@aria-framework/db-worker 0.20.2 → 0.20.4

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/database.js CHANGED
@@ -422,11 +422,15 @@ function runMigrations(migrationsDir, opts = {}) {
422
422
  : null;
423
423
  const md = owner || d;
424
424
 
425
+ let migrationError = null;
425
426
  try {
426
427
  // The LEDGER on the migration connection too. Created by the app role, `migrations` would be
427
428
  // one app-owned table in an otherwise correctly-owned schema — and one is enough.
428
429
  if (owner) await ensureMigrationsTable(owner);
429
430
  return await runMigrationsOn(md);
431
+ } catch (e) {
432
+ migrationError = e; // remembered so the finally does not overwrite it
433
+ throw e;
430
434
  } finally {
431
435
  if (owner) {
432
436
  // AWAITED, AND ITS FAILURE IS LOUD. A close that quietly failed would leave exactly the
@@ -445,6 +449,18 @@ function runMigrations(migrationsDir, opts = {}) {
445
449
  //
446
450
  // Deliberately AFTER the close and inside the finally: it must run even when a migration
447
451
  // threw, because a half-applied run leaves the connection state least understood.
452
+ // ── AND IT MUST NOT REPLACE THE REASON WE GOT HERE ────────────────────────────────────
453
+ //
454
+ // This runs in a `finally`, so it also runs when a MIGRATION FAILED. Throwing from here
455
+ // would discard that failure — the operator would see a connection error instead of the
456
+ // SQL that broke, at the one moment a half-applied chain makes the real cause matter most.
457
+ // So the proof is skipped when we are already unwinding an error, and any failure of the
458
+ // proof ITSELF is reported rather than thrown when there is a prior error to preserve.
459
+ if (migrationError) {
460
+ _logger.warn('Skipping the BYPASSRLS proof: a migration already failed, and its error is '
461
+ + 'the one worth keeping. Re-run once that is fixed.');
462
+ return;
463
+ }
448
464
  const [who] = await d.all(
449
465
  'SELECT current_user AS role, '
450
466
  + '(SELECT rolbypassrls FROM pg_roles WHERE rolname = current_user) AS bypassrls');
@@ -571,7 +587,7 @@ function driver() {
571
587
  * `initDriver({ kind: 'postgres', connectionString })` is how a Postgres-native app boots;
572
588
  * `kind: 'sqlite'` is identical to init() but hands back the driver as well.
573
589
  */
574
- async function ensureMigrationsTable(given) {
590
+ async function ensureMigrationsTable(given, opts = {}) {
575
591
  // TAKES A DRIVER, because the ledger must be created by whichever role runs the migrations. It
576
592
  // used to read the singleton unconditionally, so `migrations` was created — and therefore
577
593
  // OWNED — by the APPLICATION role even when a separate owner role applied everything else. One
@@ -611,6 +627,25 @@ async function ensureMigrationsTable(given) {
611
627
  // almost always that migrations have simply never been run against this database as the role
612
628
  // that is allowed to.
613
629
  if (d.kind === 'postgres' && /permission denied for schema/i.test(e.message || '')) {
630
+ // ── OPTIONAL AT init(), REQUIRED AT runMigrations() ────────────────────────────────────
631
+ //
632
+ // 0.20.1 fixed the case where the ledger ALREADY EXISTS and left the fresh-install case
633
+ // unbootable: an empty database plus an application role that correctly holds no CREATE
634
+ // means initDriver could not create the ledger and threw. Its own message said to run the
635
+ // migrations first — and runMigrations begins `const d = driver(); if (!d) throw`, so it
636
+ // cannot run until initDriver has succeeded. A chicken-and-egg that made every NEW,
637
+ // correctly provisioned Postgres database impossible to start, which is precisely the
638
+ // database every new app begins with.
639
+ //
640
+ // So initDriver ASKS and moves on. runMigrations creates the ledger on the migration
641
+ // connection, where the role may. A caller that never migrates and then queries the ledger
642
+ // still fails, loudly, naming the missing relation.
643
+ if (opts.optional) {
644
+ _logger.warn('db-worker: the migrations ledger does not exist yet and this role may not '
645
+ + 'create it — which is correct for an application role. runMigrations() will create it '
646
+ + 'on the migration connection. Continuing.');
647
+ return;
648
+ }
614
649
  throw new Error(
615
650
  'db-worker: the migrations ledger does not exist and this role may not create it — '
616
651
  + `${e.message}. This is the expected shape when the application connects as a role that `
@@ -637,7 +672,9 @@ async function initDriver(opts = {}) {
637
672
  } else {
638
673
  throw new Error(`initDriver: unknown kind '${kind}'`);
639
674
  }
640
- await ensureMigrationsTable();
675
+ // optional: a fresh database plus a non-owner app role is a legitimate state — see the note
676
+ // inside ensureMigrationsTable. runMigrations creates it as the role that may.
677
+ await ensureMigrationsTable(null, { optional: true });
641
678
  _logger = opts.logger || _logger;
642
679
  _logger.info(`Database opened (${kind})`);
643
680
  return _driver;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.20.2",
3
+ "version": "0.20.4",
4
4
  "description": "Aria App Framework \u2014 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,
@@ -64,6 +64,23 @@ function generateTenancyMigration(opts = {}) {
64
64
  // a schema that seeds a row is a row every future app inherits without choosing it.
65
65
  const seedHouse = opts.seedHousePartner !== false;
66
66
 
67
+ // THE ONE INPUT THAT IS THE BOUNDARY ITSELF, and it was the one not validated. An empty or
68
+ // missing POLICY_EXPRESSION generated `USING ()` for every table — a syntactically invalid
69
+ // migration, written to disk, reported as a success, failing only when it ran. manifest/dbPath/
70
+ // Database are all refused when absent; this deserves it more than any of them.
71
+ const policyExpr = String((manifest && manifest.POLICY_EXPRESSION) || '').trim();
72
+ if (!policyExpr) {
73
+ throw new Error('generateTenancyMigration: the manifest has no POLICY_EXPRESSION. That '
74
+ + 'expression IS the tenant boundary — generating `USING ()` would emit an invalid migration '
75
+ + 'that only fails when it runs, after the schema half has already applied.');
76
+ }
77
+
78
+ // Quoted for SQL, not interpolated raw. A name carrying an apostrophe — "O'Brien Holdings" —
79
+ // produced a syntax error inside a generated file nobody hand-reviews, and a name taken from
80
+ // configuration or a tenant record made this an injection seam into a migration that later runs
81
+ // as the OWNER role.
82
+ const sqlLiteral = (v) => `'${String(v).replace(/'/g, "''")}'`;
83
+
67
84
  const db = new Database(dbPath, { readonly: true });
68
85
  try {
69
86
  const scoped = manifest.scoped();
@@ -110,7 +127,7 @@ function generateTenancyMigration(opts = {}) {
110
127
  '-- a second partner is created. SEEDED HERE because this migration is a RETROFIT onto a',
111
128
  '-- database that already has rows: they are backfilled to partner 1, which therefore has',
112
129
  '-- to exist by the time the backfill runs.',
113
- `INSERT INTO partners (id, name, is_house) VALUES (1, '${houseName}', 1);`,
130
+ `INSERT INTO partners (id, name, is_house) VALUES (1, ${sqlLiteral(houseName)}, 1);`,
114
131
  ''
115
132
  ] : [
116
133
  '-- THE HOUSE PARTNER IS NOT SEEDED HERE. On a fresh installation there are no rows to',
@@ -197,7 +214,33 @@ function generateTenancyMigration(opts = {}) {
197
214
  let n = 0;
198
215
  for (const { table } of ordered) {
199
216
  for (const fk of tenantFks(table)) {
200
- const del = fk.onDelete && fk.onDelete !== 'NO ACTION' ? ` ON DELETE ${fk.onDelete}` : '';
217
+ // ── SET NULL ON A COMPOSITE KEY NULLS *BOTH* COLUMNS ──────────────────────────────
218
+ //
219
+ // The single-column FK this is derived from says ON DELETE SET NULL, and on
220
+ // (author_id) alone that is right: author_id is nullable, so deleting a user leaves
221
+ // their note attributed to nobody. Copied verbatim onto (author_id, partner_id) it also
222
+ // nulls the TENANT column — which is NOT NULL — so the delete fails outright:
223
+ //
224
+ // null value in column "partner_id" of relation "record_notes"
225
+ // violates not-null constraint
226
+ //
227
+ // MEASURED: deleting a user who had authored one note. The app could not remove a user
228
+ // who had ever done anything, on Postgres only, with an error naming a column nobody
229
+ // had touched. Postgres 15+ takes a column list on SET NULL, which nulls exactly the
230
+ // child column and leaves the tenant intact — the behaviour the original FK described.
231
+ //
232
+ // Only SET NULL needs this. CASCADE deletes the whole row (partner_id goes with it),
233
+ // and RESTRICT/NO ACTION write nothing.
234
+ const del = !fk.onDelete || fk.onDelete === 'NO ACTION'
235
+ ? ''
236
+ // SET DEFAULT IS THE SAME DEFECT. It fell through to the bare branch, so a composite
237
+ // key set BOTH columns to their defaults — and partner_id's default is
238
+ // current_setting('app.partner_id'), so a delete with no scope nulls a NOT NULL column
239
+ // and a delete under a DIFFERENT scope silently REPARENTS the child row to another
240
+ // tenant. Postgres 15+ takes a column list here too.
241
+ : (fk.onDelete === 'SET NULL' || fk.onDelete === 'SET DEFAULT'
242
+ ? ` ON DELETE ${fk.onDelete} (${fk.from})`
243
+ : ` ON DELETE ${fk.onDelete}`);
201
244
  out.push(
202
245
  `ALTER TABLE ${table} ADD CONSTRAINT fk_${table}_${fk.from}_partner`
203
246
  + ` FOREIGN KEY (${fk.from}, partner_id)`
@@ -223,7 +266,7 @@ function generateTenancyMigration(opts = {}) {
223
266
  for (const w of widen) {
224
267
  const cols = ['partner_id', ...w.columns].join(', ');
225
268
  if (w.index) {
226
- out.push(`DROP INDEX ${w.index};`);
269
+ out.push(`DROP INDEX IF EXISTS ${w.index};`);
227
270
  out.push(`CREATE UNIQUE INDEX ${w.index} ON ${w.table} (${cols})`
228
271
  + (w.where ? ` WHERE ${w.where}` : '') + ';');
229
272
  } else {