@aria-framework/db-worker 0.15.0 → 0.16.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/dialect.js CHANGED
@@ -25,6 +25,10 @@
25
25
  /** Quote an identifier. Both engines accept double quotes; this exists so callers never hand-roll. */
26
26
  const ident = (name) => `"${String(name).replace(/"/g, '""')}"`;
27
27
 
28
+ /** A SQL string literal. `ident` quotes a NAME; this quotes a VALUE, which is what a catalogue
29
+ * lookup needs — information_schema compares table_name against text, not against an id. */
30
+ const strLit = (v) => `'${String(v).replace(/'/g, "''")}'`;
31
+
28
32
  const sqlite = {
29
33
  kind: 'sqlite',
30
34
  ident,
@@ -32,6 +36,19 @@ const sqlite = {
32
36
  now: () => "datetime('now')",
33
37
  /** N whole days before now — used by retention cuts. */
34
38
  nowMinusDays: (n) => `datetime('now', '-${Number(n)} days')`,
39
+ /**
40
+ * WHICH COLUMNS A TABLE HAS, as SQL returning rows with a `name` column.
41
+ *
42
+ * `PRAGMA table_info(...)` is one of the last SQLite-isms an application reaches for, because
43
+ * "does this table have that column yet?" is a real question during a migration window and
44
+ * there is no portable spelling of it. The two engines answer from completely different places
45
+ * — a pragma and a catalogue view — so the column NAME is aliased to the same thing on both,
46
+ * and a caller can just look for it.
47
+ *
48
+ * The table name is interpolated because a PRAGMA cannot take a bound parameter. It is quoted
49
+ * for the context each engine puts it in: an identifier there, a string literal here.
50
+ */
51
+ columns: (table) => `PRAGMA table_info(${ident(table)})`,
35
52
  /**
36
53
  * N minutes AFTER now — an expiry window.
37
54
  *
@@ -93,6 +110,20 @@ const postgres = {
93
110
  // for both; an app wanting a real timestamptz column in its OWN tables uses nowTz().
94
111
  now: () => "to_char(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')",
95
112
  nowMinusDays: (n) => `to_char((NOW() - INTERVAL '${Number(n)} days') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
113
+ /**
114
+ * WHICH COLUMNS A TABLE HAS, as SQL returning rows with a `name` column.
115
+ *
116
+ * `PRAGMA table_info(...)` is one of the last SQLite-isms an application reaches for, because
117
+ * "does this table have that column yet?" is a real question during a migration window and
118
+ * there is no portable spelling of it. The two engines answer from completely different places
119
+ * — a pragma and a catalogue view — so the column NAME is aliased to the same thing on both,
120
+ * and a caller can just look for it.
121
+ *
122
+ * The table name is interpolated because a PRAGMA cannot take a bound parameter. It is quoted
123
+ * for the context each engine puts it in: an identifier there, a string literal here.
124
+ */
125
+ columns: (table) => `SELECT column_name AS name FROM information_schema.columns`
126
+ + ` WHERE table_schema = 'public' AND table_name = ${strLit(table)}`,
96
127
  nowPlusMinutes: (n) => `to_char((NOW() + INTERVAL '${Number(n)} minutes') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
97
128
  // date_trunc on the UTC value, not on NOW(): truncating a timestamptz uses the SESSION time
98
129
  // zone, so 'start of month' would land on a different instant depending on where the server
@@ -18,6 +18,16 @@
18
18
 
19
19
  'use strict';
20
20
 
21
+ // WHICH TRANSACTION AM I INSIDE? — the same question the SQLite driver answers, and for the
22
+ // same reason. transaction() called on the handle a callback was GIVEN is obviously nested;
23
+ // transaction() called on the DRIVER from within that callback is nested too, and nothing but
24
+ // the async call chain can tell. A driver that answers "not nested" there takes a second
25
+ // pooled connection: two BEGINs, one holding the locks the other waits on, and — the failure
26
+ // that found this — no transaction-local settings, so every RLS policy on the far side reads
27
+ // an unset app.scope and refuses the query.
28
+ const { AsyncLocalStorage } = require('node:async_hooks');
29
+ const txContext = new AsyncLocalStorage();
30
+
21
31
  const { dialectFor } = require('../dialect');
22
32
  const { bindNamed } = require('./params');
23
33
 
@@ -102,6 +112,27 @@ function createPostgresDriver(opts = {}) {
102
112
  throw new Error('createPostgresDriver({ connectionString }): a connection string (or host/user/database) is required');
103
113
  }
104
114
 
115
+ /**
116
+ * COUNT(*) COMES BACK AS A NUMBER, the way it does on SQLite.
117
+ *
118
+ * node-postgres returns int8 as a STRING, because a 64-bit integer does not fit a JS number.
119
+ * That is defensible in the abstract and wrong for a driver whose entire purpose is to make
120
+ * two engines answer alike: the same query returns 0 on SQLite and '0' on Postgres, and every
121
+ * `=== 0`, `> 100` and `n + 1` in an application quietly changes meaning.
122
+ *
123
+ * IT ALREADY COST A REAL FAILURE. Support101 seeds its first administrator when
124
+ * `User.count() === 0`. On Postgres that is `'0' === 0`, which is false — so a fresh install
125
+ * came up with no users, no way to sign in, and nothing in the log to say why.
126
+ *
127
+ * THE PRECISION CAVEAT, stated rather than buried: above 2^53 a JS number cannot hold an int8
128
+ * exactly. Nothing this framework generates goes near it — identity columns, counts and sums
129
+ * of rows — and an application that genuinely needs 9 quadrillion should read that column as
130
+ * text with an explicit cast rather than have every other query be a string. The setting is
131
+ * process-wide (pg keeps one parser table), which is why it is applied HERE, once, at the
132
+ * point the driver is built, rather than by each consumer remembering to.
133
+ */
134
+ pg.types.setTypeParser(20, (v) => (v === null ? null : Number(v)));
135
+
105
136
  // Pass the CONNECTION OPTIONS THROUGH. The guard above accepts host/user/database as an
106
137
  // alternative to a connection string and the JSDoc documents it, but only connectionString was
107
138
  // ever handed to pg — so those callers silently fell back to PGHOST/PGUSER or localhost and
@@ -157,13 +188,40 @@ function createPostgresDriver(opts = {}) {
157
188
  ...extra
158
189
  });
159
190
 
160
- const poolApi = apiOver((sql, params) => pool.query(sql, params), {
191
+ /**
192
+ * A QUERY THROUGH THE DRIVER, INSIDE A TRANSACTION, IS PART OF THAT TRANSACTION.
193
+ *
194
+ * This is the other half of the nesting bug and the more dangerous one, because it does not
195
+ * even look like nesting. A store that holds the DRIVER and calls d.all() from inside somebody
196
+ * else's transaction used to get a fresh pooled connection: it could not see the transaction's
197
+ * uncommitted rows, and — the failure that found it — it carried none of the transaction-local
198
+ * settings the tenant boundary is made of. @aria-framework/auth's permissionList does exactly
199
+ * that, and every row-level security policy it touched refused the query.
200
+ *
201
+ * The SQLite driver never had the problem: one connection, so a statement is inside whatever
202
+ * that connection is inside. This makes the pool behave the same way.
203
+ */
204
+ const poolExec = (sql, params) => {
205
+ const parent = txContext.getStore();
206
+ return (parent && parent.pool === pool)
207
+ ? parent.client.query(sql, params)
208
+ : pool.query(sql, params);
209
+ };
210
+
211
+ const poolApi = apiOver(poolExec, {
161
212
  /**
162
213
  * A dedicated client for the whole transaction. Without this, a pooled query from another
163
214
  * concurrent invoke could land between the BEGIN and the COMMIT — the same interleaving
164
215
  * hazard the SQLite driver avoids by serialising, solved here the way Postgres intends.
165
216
  */
166
217
  async transaction(fn) {
218
+ // ALREADY INSIDE ONE, ON THIS POOL? Then this is a savepoint on the client that
219
+ // transaction is holding, not a new connection. The pool identity matters: two drivers
220
+ // over two different databases must stay independent, exactly as the SQLite driver keys
221
+ // its context on the connection handle.
222
+ const parent = txContext.getStore();
223
+ if (parent && parent.pool === pool) return parent.nest(fn);
224
+
167
225
  const client = await pool.connect();
168
226
  const q = (sql, params) => client.query(sql, params);
169
227
 
@@ -182,25 +240,30 @@ function createPostgresDriver(opts = {}) {
182
240
  */
183
241
  const levelApi = (depth) => {
184
242
  let queue = Promise.resolve();
185
- return apiOver(q, {
186
- // Nested transaction() reuses the same CLIENT (a second pooled connection would
187
- // deadlock against this one's locks) and brackets the body in a SAVEPOINT, so an
188
- // inner failure rolls back only its own work rather than discarding the outer.
189
- async transaction(inner) {
190
- const run = () => runNested(inner, depth + 1);
191
- // Chained on BOTH settle paths, so one failed child does not wedge its siblings.
192
- const mine = queue.then(run, run);
193
- queue = mine.then(() => {}, () => {});
194
- return mine;
195
- }
196
- });
243
+ // Nested transaction() reuses the same CLIENT (a second pooled connection would
244
+ // deadlock against this one's locks) and brackets the body in a SAVEPOINT, so an
245
+ // inner failure rolls back only its own work rather than discarding the outer.
246
+ //
247
+ // Chained on BOTH settle paths, so one failed child does not wedge its siblings.
248
+ const nest = (inner) => {
249
+ const run = () => runNested(inner, depth + 1);
250
+ const mine = queue.then(run, run);
251
+ queue = mine.then(() => {}, () => {});
252
+ return mine;
253
+ };
254
+ // The context is what a driver.transaction() call deeper in the async chain will find.
255
+ // It carries nest() rather than the api, so both entrances to a nested transaction —
256
+ // the handle and the driver — go through one queue.
257
+ const ctx = { pool, client, depth, nest };
258
+ return { api: apiOver(q, { transaction: nest }), ctx };
197
259
  };
198
260
 
199
261
  async function runNested(inner, depth) {
200
262
  const sp = `aria_sp_${depth}`;
263
+ const { api, ctx } = levelApi(depth);
201
264
  await q(`SAVEPOINT ${sp}`);
202
265
  try {
203
- const out = await inner(levelApi(depth));
266
+ const out = await txContext.run(ctx, () => inner(api));
204
267
  await q(`RELEASE SAVEPOINT ${sp}`);
205
268
  return out;
206
269
  } catch (e) {
@@ -214,10 +277,10 @@ function createPostgresDriver(opts = {}) {
214
277
  }
215
278
  }
216
279
 
217
- const txApi = levelApi(0);
280
+ const { api: txApi, ctx: txCtx } = levelApi(0);
218
281
  try {
219
282
  await client.query('BEGIN');
220
- const out = await fn(txApi);
283
+ const out = await txContext.run(txCtx, () => fn(txApi));
221
284
  await client.query('COMMIT');
222
285
  return out;
223
286
  } catch (e) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.15.0",
3
+ "version": "0.16.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,
@@ -38,6 +38,6 @@
38
38
  "pg": "^8.23.0"
39
39
  },
40
40
  "scripts": {
41
- "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/tenantRls.pg.js && node test/smoke.js && node test/tier2.js"
41
+ "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/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/smoke.js && node test/tier2.js"
42
42
  }
43
43
  }