@aria-framework/db-worker 0.20.5 → 0.23.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.
@@ -223,6 +223,30 @@ function createPostgresDriver(opts = {}) {
223
223
  if (parent && parent.pool === pool) return parent.nest(fn);
224
224
 
225
225
  const client = await pool.connect();
226
+
227
+ // ── A CHECKED-OUT CLIENT EMITS ON ITSELF, NOT ON THE POOL ────────────────────────────────
228
+ //
229
+ // The `pool.on('error')` above covers clients sitting IDLE in the pool. Once `connect()` has
230
+ // handed one over, node-postgres emits connection errors on the CLIENT — and with nothing
231
+ // listening, Node turns an unhandled 'error' event into an uncaught exception and the process
232
+ // exits. So a Postgres restart, a failover or a stray pg_terminate_backend during any
233
+ // transaction took the whole app down, including every unrelated request in flight, at
234
+ // precisely the moment it should have been riding out a short outage.
235
+ //
236
+ // ONLY THIS PATH NEEDED IT. `pool.query()` — everything outside a transaction — already
237
+ // rejects cleanly, because pg's own pool machinery owns the client for the length of that
238
+ // call. Verified both ways rather than assumed; test/clientError.pg.js keeps the distinction.
239
+ //
240
+ // The query still rejects exactly as before. This changes only whether the process survives
241
+ // to see the rejection.
242
+ let connError = null;
243
+ const onClientError = (err) => {
244
+ connError = err;
245
+ try { (opts.logger || console).warn(`postgres: connection lost mid-transaction (${err.message})`); }
246
+ catch (_) { /* a logger that throws must not become the crash it replaced */ }
247
+ };
248
+ client.on('error', onClientError);
249
+
226
250
  const q = (sql, params) => client.query(sql, params);
227
251
 
228
252
  /**
@@ -287,7 +311,14 @@ function createPostgresDriver(opts = {}) {
287
311
  try { await client.query('ROLLBACK'); } catch (_) { /* the original error is what matters */ }
288
312
  throw e;
289
313
  } finally {
290
- client.release();
314
+ // REMOVE THE LISTENER, because the pool reuses client objects across checkouts: one added
315
+ // per transaction and never removed accumulates, and an old handler fires for a later
316
+ // transaction's error.
317
+ client.removeListener('error', onClientError);
318
+ // RELEASE WITH THE ERROR, which destroys the connection instead of returning it to the
319
+ // pool. A client whose connection died must not be handed to the next caller — that is how
320
+ // a dead connection gets reused and fails somebody else's request for no reason of its own.
321
+ client.release(connError || undefined);
291
322
  }
292
323
  },
293
324
  async close() { await pool.end(); },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.20.5",
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).",
3
+ "version": "0.23.0",
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,
7
7
  "publishConfig": {
@@ -39,7 +39,7 @@
39
39
  "pg": "^8.23.0"
40
40
  },
41
41
  "scripts": {
42
- "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js",
42
+ "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyNullable.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",
43
43
  "prepublishOnly": "node ../../test/packaging.js db-worker"
44
44
  }
45
45
  }
@@ -81,14 +81,49 @@ function generateTenancyMigration(opts = {}) {
81
81
  // as the OWNER role.
82
82
  const sqlLiteral = (v) => `'${String(v).replace(/'/g, "''")}'`;
83
83
 
84
+ const { dialectFor } = require('./dialect');
85
+ const sqliteDialect = dialectFor('sqlite');
86
+
87
+ // ── WHICH TABLE HOLDS THE PRINCIPAL, AND WHAT THE SCOPE COLUMN IS CALLED ────────────────────
88
+ //
89
+ // This emitted `ALTER TABLE users ADD COLUMN scope_kind` unconditionally — a framework package
90
+ // hardcoding one app's table name. An app whose principal table is `staff`, `accounts` or
91
+ // `app_user` got a migration that failed at `relation "users" does not exist` AFTER
92
+ // CREATE TABLE partners and every partner_id column had already applied, leaving the chain
93
+ // half-way. Neither name appears in the documented manifest contract (scoped / WIDEN_UNIQUE /
94
+ // POLICY_EXPRESSION), so nothing told an author the dependency existed.
95
+ //
96
+ // Defaulted to the old values so existing callers are unchanged, and CHECKED against the schema
97
+ // being read: a name that is not there fails HERE, with the tables that do exist named, rather
98
+ // than in the middle of a migration.
99
+ const principalTable = opts.principalTable || 'users';
100
+ const scopeColumn = opts.scopeColumn || 'scope_kind';
101
+
84
102
  const db = new Database(dbPath, { readonly: true });
85
103
  try {
104
+ const present = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all()
105
+ .map((r) => r.name);
106
+ if (!present.includes(principalTable)) {
107
+ throw new Error(`generateTenancyMigration: no table named "${principalTable}" in this schema, `
108
+ + `so the ${scopeColumn} column has nowhere to go. Pass { principalTable } naming the table `
109
+ + `that holds your signed-in principals. Tables here: ${present.sort().join(', ')}`);
110
+ }
111
+
86
112
  const scoped = manifest.scoped();
87
113
  const scopedNames = new Set(scoped.map((s) => s.table));
88
114
  const ordered = [...scoped].sort((a, b) => a.table.localeCompare(b.table));
89
115
 
90
116
  /** Foreign keys from one tenant-scoped table to another. These become composite. */
91
- const tenantFks = (table) => db.prepare(`PRAGMA foreign_key_list("${table}")`).all()
117
+ // THE DIALECT'S OWN SQL, not a hand-rolled PRAGMA. dialect.foreignKeys() was added to this
118
+ // package for exactly this, with both engines aliased to the PRAGMA's own from/table/to column
119
+ // names — and this generator, added in the same release, inlined the PRAGMA anyway with
120
+ // hand-written quotes. Using it centralises the identifier quoting and means the one place
121
+ // that knows how to ask a schema about its foreign keys is the one place that does it.
122
+ //
123
+ // STILL SQLITE-ONLY, and honestly so: this reads a SQLite file by construction (dbPath +
124
+ // Database). Sharing the SQL does not make it engine-agnostic — that would need the caller to
125
+ // pass a driver instead of a file — it removes a second spelling of the same question.
126
+ const tenantFks = (table) => db.prepare(sqliteDialect.foreignKeys(table)).all()
92
127
  .filter((f) => scopedNames.has(f.table))
93
128
  .map((f) => ({ from: f.from, table: f.table, to: f.to || 'id', onDelete: f.on_delete }))
94
129
  // PRAGMA lists newest first; sorting keeps a regenerated file diff-free.
@@ -143,7 +178,7 @@ function generateTenancyMigration(opts = {}) {
143
178
  '-- user of the house partner" has to consult another table, which a CHECK cannot do on',
144
179
  '-- either engine. It is enforced in the application and by a test; recording the limitation',
145
180
  '-- here beats leaving somebody to assume the database is holding it.',
146
- "ALTER TABLE users ADD COLUMN scope_kind TEXT NOT NULL DEFAULT 'partner';"
181
+ `ALTER TABLE ${principalTable} ADD COLUMN ${scopeColumn} TEXT NOT NULL DEFAULT 'partner';`
147
182
  ].join('\n');
148
183
  }
149
184
 
@@ -245,6 +280,41 @@ function generateTenancyMigration(opts = {}) {
245
280
  `ALTER TABLE ${table} ADD CONSTRAINT fk_${table}_${fk.from}_partner`
246
281
  + ` FOREIGN KEY (${fk.from}, partner_id)`
247
282
  + ` REFERENCES ${fk.table} (${fk.to}, partner_id)${del};`);
283
+ // ── AND DROP THE ONE IT SUPERSEDES ──────────────────────────────────────────────────
284
+ //
285
+ // The composite key is strictly stronger: it enforces everything the single-column key
286
+ // did AND that the child agrees with its parent about the tenant. Leaving the original
287
+ // in place is therefore not WRONG, which is exactly why it went unnoticed — a consuming
288
+ // app measured 49 duplicated pairs across 28 tables, every one of them redundant and
289
+ // none of them broken. What they cost is writes: every INSERT and UPDATE of the child
290
+ // takes two lookups on the parent instead of one, and every DELETE of a parent row
291
+ // checks both, on the hot path, for ever.
292
+ //
293
+ // BY SHAPE, NOT BY NAME. `<table>_<column>_fkey` is only Postgres's default; a schema
294
+ // that named its constraint would keep its duplicate while the generator reported
295
+ // success. This drops any FK on this table whose key is EXACTLY this one column and
296
+ // which points at the same parent — the precise set the line above supersedes, and
297
+ // nothing else. It runs after the ADD, so a failure leaves the stronger key in place
298
+ // rather than no key at all.
299
+ //
300
+ // GUARDED ON partner_id BEING NOT NULL, which is the condition that makes "supersedes"
301
+ // true at all. Foreign keys are MATCH SIMPLE: if ANY column of a composite key is NULL
302
+ // the constraint is satisfied trivially, so on a table whose partner_id is NULLABLE — a
303
+ // PARTNER_NULLABLE table, where NULL means "the installation" — a row could carry a
304
+ // dangling reference with partner_id NULL and pass the composite while failing the
305
+ // single. There the single key is NOT redundant and must stay. Checked here rather than
306
+ // asserted in a comment, because the manifest can move a table between those lists.
307
+ out.push(
308
+ `DO $$ DECLARE c record; BEGIN`
309
+ + ` IF (SELECT attnotnull FROM pg_attribute`
310
+ + ` WHERE attrelid = '${table}'::regclass AND attname = 'partner_id') THEN`
311
+ + ` FOR c IN SELECT conname FROM pg_constraint`
312
+ + ` WHERE conrelid = '${table}'::regclass AND contype = 'f'`
313
+ + ` AND confrelid = '${fk.table}'::regclass`
314
+ + ` AND conkey = ARRAY[(SELECT attnum FROM pg_attribute`
315
+ + ` WHERE attrelid = '${table}'::regclass AND attname = '${fk.from}' AND NOT attisdropped)]`
316
+ + ` LOOP EXECUTE format('ALTER TABLE ${table} DROP CONSTRAINT %I', c.conname);`
317
+ + ` END LOOP; END IF; END $$;`);
248
318
  n++;
249
319
  }
250
320
  }