@aria-framework/db-worker 0.15.0 → 0.18.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 +71 -1
- package/driver/postgres.js +79 -16
- package/package.json +2 -2
- package/settingsStore.js +20 -1
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,24 @@ 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
|
+
* Seconds, because some windows are short and expressing them as a fraction of a minute is a
|
|
41
|
+
* rounding error waiting to be argued about. api-auth's key-touch throttle is the caller.
|
|
42
|
+
*/
|
|
43
|
+
nowMinusSeconds: (n) => `datetime('now', '-${Number(n)} seconds')`,
|
|
44
|
+
/**
|
|
45
|
+
* WHICH COLUMNS A TABLE HAS, as SQL returning rows with a `name` column.
|
|
46
|
+
*
|
|
47
|
+
* `PRAGMA table_info(...)` is one of the last SQLite-isms an application reaches for, because
|
|
48
|
+
* "does this table have that column yet?" is a real question during a migration window and
|
|
49
|
+
* there is no portable spelling of it. The two engines answer from completely different places
|
|
50
|
+
* — a pragma and a catalogue view — so the column NAME is aliased to the same thing on both,
|
|
51
|
+
* and a caller can just look for it.
|
|
52
|
+
*
|
|
53
|
+
* The table name is interpolated because a PRAGMA cannot take a bound parameter. It is quoted
|
|
54
|
+
* for the context each engine puts it in: an identifier there, a string literal here.
|
|
55
|
+
*/
|
|
56
|
+
columns: (table) => `PRAGMA table_info(${ident(table)})`,
|
|
35
57
|
/**
|
|
36
58
|
* N minutes AFTER now — an expiry window.
|
|
37
59
|
*
|
|
@@ -64,7 +86,21 @@ const sqlite = {
|
|
|
64
86
|
*
|
|
65
87
|
* Raw and unrounded on purpose: every caller wraps it in AVG or SUM and multiplies to the
|
|
66
88
|
* unit it wants (x24 for hours, x1440 for minutes). A helper that rounded would not compose.
|
|
67
|
-
*
|
|
89
|
+
*
|
|
90
|
+
* NEVER PASS THE LITERAL 'now'. This used to say "either side may be the literal 'now', which
|
|
91
|
+
* both engines understand" — true, and wrong, which is the worst kind of doc. Both engines
|
|
92
|
+
* PARSE it and they mean different instants:
|
|
93
|
+
*
|
|
94
|
+
* sqlite julianday('now') UTC, always
|
|
95
|
+
* postgres 'now'::timestamp the SESSION's time zone
|
|
96
|
+
*
|
|
97
|
+
* Every timestamp this framework writes is UTC text (see now() above), so on a server whose
|
|
98
|
+
* session time zone is not UTC the subtraction is off by exactly the offset. Support101 met it
|
|
99
|
+
* on an America/Chicago server: stopping a timer computed elapsed minutes 300 SHORT, negative
|
|
100
|
+
* for anything under five hours, and the caller's own MAX(1, …) floor turned that into a
|
|
101
|
+
* plausible "1 minute" instead of an obvious absurdity. Billable data, quietly wrong.
|
|
102
|
+
*
|
|
103
|
+
* Pass now() instead, so both sides are in the same frame. Two stored COLUMNS are always safe.
|
|
68
104
|
*/
|
|
69
105
|
daysBetween: (from, to) => `(julianday(${to}) - julianday(${from}))`,
|
|
70
106
|
/** Read a JSON path out of a column: jsonPath('detail', '$.model'). */
|
|
@@ -75,6 +111,19 @@ const sqlite = {
|
|
|
75
111
|
// `role LIKE 'read_only'` also matches 'read-only' because `_` is a single-character wildcard,
|
|
76
112
|
// and a value of '%' matches everything. Equality has to be spelled as equality.
|
|
77
113
|
ciEquals: (col, param) => `LOWER(${col}) = LOWER(${param})`,
|
|
114
|
+
/**
|
|
115
|
+
* The larger / smaller of two VALUES — the scalar, not the aggregate.
|
|
116
|
+
*
|
|
117
|
+
* SQLite's MAX is two functions wearing one name: an aggregate with one argument, a scalar with
|
|
118
|
+
* two. Postgres has only the aggregate and spells the scalar GREATEST, so `MAX(1, x)` there is
|
|
119
|
+
* not a wrong answer — it is `function max(integer, integer) does not exist`.
|
|
120
|
+
*
|
|
121
|
+
* Named here rather than solved in each app: Support101 hit it in two places, both on paths
|
|
122
|
+
* nothing routine exercises (stopping a timer; requeueing a refused job), and an app that fixes
|
|
123
|
+
* it locally leaves every other consumer to rediscover the same thing.
|
|
124
|
+
*/
|
|
125
|
+
greatest: (a, b) => `MAX(${a}, ${b})`,
|
|
126
|
+
least: (a, b) => `MIN(${a}, ${b})`,
|
|
78
127
|
/** Suffix that makes run() report a new row's id. SQLite reports it out of band. */
|
|
79
128
|
returning: () => '',
|
|
80
129
|
/** DDL fragment for an auto-incrementing primary key (only secure-keystore needs this). */
|
|
@@ -93,6 +142,21 @@ const postgres = {
|
|
|
93
142
|
// for both; an app wanting a real timestamptz column in its OWN tables uses nowTz().
|
|
94
143
|
now: () => "to_char(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')",
|
|
95
144
|
nowMinusDays: (n) => `to_char((NOW() - INTERVAL '${Number(n)} days') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
|
|
145
|
+
nowMinusSeconds: (n) => `to_char((NOW() - INTERVAL '${Number(n)} seconds') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
|
|
146
|
+
/**
|
|
147
|
+
* WHICH COLUMNS A TABLE HAS, as SQL returning rows with a `name` column.
|
|
148
|
+
*
|
|
149
|
+
* `PRAGMA table_info(...)` is one of the last SQLite-isms an application reaches for, because
|
|
150
|
+
* "does this table have that column yet?" is a real question during a migration window and
|
|
151
|
+
* there is no portable spelling of it. The two engines answer from completely different places
|
|
152
|
+
* — a pragma and a catalogue view — so the column NAME is aliased to the same thing on both,
|
|
153
|
+
* and a caller can just look for it.
|
|
154
|
+
*
|
|
155
|
+
* The table name is interpolated because a PRAGMA cannot take a bound parameter. It is quoted
|
|
156
|
+
* for the context each engine puts it in: an identifier there, a string literal here.
|
|
157
|
+
*/
|
|
158
|
+
columns: (table) => `SELECT column_name AS name FROM information_schema.columns`
|
|
159
|
+
+ ` WHERE table_schema = 'public' AND table_name = ${strLit(table)}`,
|
|
96
160
|
nowPlusMinutes: (n) => `to_char((NOW() + INTERVAL '${Number(n)} minutes') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
|
|
97
161
|
// date_trunc on the UTC value, not on NOW(): truncating a timestamptz uses the SESSION time
|
|
98
162
|
// zone, so 'start of month' would land on a different instant depending on where the server
|
|
@@ -113,6 +177,9 @@ const postgres = {
|
|
|
113
177
|
if (unit === 'week') return `to_char(${col}::timestamp, 'IYYY-"W"IW')`;
|
|
114
178
|
throw new Error(`dateGroup: expected 'month' or 'week', got ${JSON.stringify(unit)}`);
|
|
115
179
|
},
|
|
180
|
+
// NEVER PASS THE LITERAL 'now' — see the sqlite twin. `'now'::timestamp` is resolved in the
|
|
181
|
+
// SESSION's time zone, and everything this framework stores is UTC text, so the subtraction is
|
|
182
|
+
// silently off by the server's offset. Pass now().
|
|
116
183
|
daysBetween: (from, to) =>
|
|
117
184
|
`(EXTRACT(EPOCH FROM (${to}::timestamp - ${from}::timestamp)) / 86400)`,
|
|
118
185
|
/** Native timestamptz, for an app that declares real timestamp columns. */
|
|
@@ -131,6 +198,9 @@ const postgres = {
|
|
|
131
198
|
},
|
|
132
199
|
ilike: () => 'ILIKE',
|
|
133
200
|
ciEquals: (col, param) => `LOWER(${col}) = LOWER(${param})`,
|
|
201
|
+
// The scalar, not the aggregate — see the sqlite twin for why this needs naming at all.
|
|
202
|
+
greatest: (a, b) => `GREATEST(${a}, ${b})`,
|
|
203
|
+
least: (a, b) => `LEAST(${a}, ${b})`,
|
|
134
204
|
returning: (col = 'id') => ` RETURNING ${ident(col)}`,
|
|
135
205
|
autoIncrementPk: () => 'BIGSERIAL PRIMARY KEY',
|
|
136
206
|
textType: () => 'TEXT'
|
package/driver/postgres.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
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
|
|
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.
|
|
3
|
+
"version": "0.18.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
|
}
|
package/settingsStore.js
CHANGED
|
@@ -30,6 +30,20 @@ const { createSqliteDriver } = require('./driver/sqlite');
|
|
|
30
30
|
* getDb LEGACY: a function returning a better-sqlite3 handle, adopted into a driver here
|
|
31
31
|
* table defaults to 'settings'
|
|
32
32
|
* touchUpdatedAt: set true when the table carries an updated_at column to stamp on write.
|
|
33
|
+
* conflictTarget: the column list the upsert conflicts on, defaulting to 'key'.
|
|
34
|
+
*
|
|
35
|
+
* WHY conflictTarget EXISTS. An upsert's conflict target must match a real unique constraint, and
|
|
36
|
+
* a MULTI-TENANT settings table is not unique on `key` — two partners each need their own
|
|
37
|
+
* `brand_name`, so the constraint becomes `(partner_id, key)`. `ON CONFLICT(key)` against that is
|
|
38
|
+
* not a wrong answer; Postgres refuses the statement outright with "there is no unique or
|
|
39
|
+
* exclusion constraint matching the ON CONFLICT specification".
|
|
40
|
+
*
|
|
41
|
+
* Support101 met this after its tenancy migration: reads worked, and EVERY WRITE failed — brand
|
|
42
|
+
* name, timezone, session timeout, AI ceilings, audit retention. It stayed hidden through a full
|
|
43
|
+
* Postgres test pass because nothing in that pass CHANGED a setting; the first person to edit one
|
|
44
|
+
* in the admin UI found it immediately.
|
|
45
|
+
*
|
|
46
|
+
* Defaults to 'key', so every existing consumer is unaffected.
|
|
33
47
|
*/
|
|
34
48
|
function createSettingsStore(opts = {}) {
|
|
35
49
|
let driver = opts.driver || null;
|
|
@@ -114,8 +128,13 @@ function createSettingsStore(opts = {}) {
|
|
|
114
128
|
const touch = opts.touchUpdatedAt ? `, updated_at = ${now()}` : '';
|
|
115
129
|
const insertCols = opts.touchUpdatedAt ? '(key, value, updated_at)' : '(key, value)';
|
|
116
130
|
const insertVals = opts.touchUpdatedAt ? `(?, ?, ${now()})` : '(?, ?)';
|
|
131
|
+
// The INSERT still names only key/value: a tenant column is supplied by its own DEFAULT
|
|
132
|
+
// (`current_setting('app.partner_id')` under RLS), so the row lands on the right tenant
|
|
133
|
+
// without this store knowing that tenants exist. Only the CONFLICT TARGET has to agree with
|
|
134
|
+
// the constraint the app actually built.
|
|
135
|
+
const conflict = opts.conflictTarget || 'key';
|
|
117
136
|
return `INSERT INTO ${table} ${insertCols} VALUES ${insertVals}
|
|
118
|
-
ON CONFLICT(
|
|
137
|
+
ON CONFLICT(${conflict}) DO UPDATE SET value = excluded.value${touch}`;
|
|
119
138
|
}
|
|
120
139
|
}
|
|
121
140
|
|