@aria-framework/db-worker 0.28.0 → 0.30.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/sql.js ADDED
@@ -0,0 +1,395 @@
1
+ /**
2
+ * `sql` (0.29.0) — date and dialect expressions spelled by whichever engine is underneath, the tenant
3
+ * filter, and the small error and column helpers every app carried as its own `lib/sql.js`.
4
+ *
5
+ * const { sql } = require('@aria-framework/db-worker');
6
+ * `UPDATE users SET updated_at = ${sql.now()} WHERE id = ?${sql.andTenant()}`
7
+ *
8
+ * Six apps had a copy. This is the starter's file whole (the CASE tenant filter, `uniqueViolation`,
9
+ * `isUniqueViolation` with the primary-key code, `tables`, `foreignKeys`), plus the hub's
10
+ * `andPrintableAscii`, `jsonColumn`, `arrayColumn`, `arrayParam`, `jsonParam`, plus the desk app's
11
+ * `isDatabaseError`, plus `isDeadlock`. An app's `lib/sql.js` becomes a one-line re-export.
12
+ *
13
+ * LAZY, AND IT HAS TO BE: `database.driver()` is null until the worker opens the database, while
14
+ * this module is required at load. Every function here resolves the engine at CALL time, from this
15
+ * package's own `database.driver()` — never a handle captured at require time, which would bind to
16
+ * the first driver in the process and keep answering for it after a test bridge opened a second.
17
+ *
18
+ * ON SQLITE THE DATE HELPERS RETURN EXACTLY WHAT THEY REPLACED (`datetime('now')`), and the tenant
19
+ * helpers return the empty string (see tenantPredicate).
20
+ */
21
+
22
+ 'use strict';
23
+
24
+ const database = require('./database');
25
+
26
+ /** The dialect of the connection the worker opened. Throws, clearly, if called too early. */
27
+ function dialect() {
28
+ const d = database.driver();
29
+ if (!d) {
30
+ throw new Error('db-worker sql: no driver yet — these render at query time, after database.init()');
31
+ }
32
+ return d.dialect;
33
+ }
34
+
35
+ // ── THE TENANT PREDICATE, AND WHY A MODEL NEEDS ONE WHEN RLS ALREADY EXISTS ────────────────────
36
+ //
37
+ // The frozen policy (see tenancyManifest.js) is
38
+ //
39
+ // CASE current_setting('app.scope') WHEN 'platform' THEN true
40
+ // ELSE partner_id = current_setting('app.partner_id') END
41
+ //
42
+ // so AT PLATFORM SCOPE THE POLICY IS `true` AND EVERY TENANT'S ROWS COME BACK. That is correct for
43
+ // the questions platform scope exists to ask — a login looked up by username, the partner list —
44
+ // and silently wrong for a read that expects ONE tenant's rows and takes what it is given.
45
+ //
46
+ // And platform scope is neither rare nor conspicuous. `asHouse()` is
47
+ // `{ scope: 'platform', partnerId: house }` — one word from `asPartner(house)` — and it is what an
48
+ // anonymous request gets, what the API can open a request in, and what a bare `asPlatform()`
49
+ // maintenance job runs under. A read that is safe today because all of its callers happen to be
50
+ // partner-scoped is one refactor away from not being.
51
+ //
52
+ // So the predicate goes in the MODEL, where it is a property of the query rather than of the
53
+ // caller. The desk app learned this the expensive way: a list that said 96 when the tenant owned
54
+ // 94, a contacts page reporting another tenant's rows, twelve roles where there were three, and a
55
+ // provisioning step that seeded the second partner with the first one's data. Every one was fixed
56
+ // at the CALL SITE first, and every one came back.
57
+ //
58
+ // IT FALLS BACK TO THE HOUSE rather than to nothing. A bare `asPlatform()` — a scheduled job, a
59
+ // boot task — leaves `app.partner_id` unset, and for a table whose rows all belong to somebody the
60
+ // honest answer there is the installation's own, not an empty list that reads as "none configured".
61
+ //
62
+ // ── A CASE, NOT A COALESCE, AND THE DIFFERENCE IS AN INDEX SCAN ────────────────────────────────
63
+ //
64
+ // These two are semantically identical — unset or empty resolves to the house, anything else is the
65
+ // id — and Postgres treats them completely differently on an RLS-protected table.
66
+ //
67
+ // A predicate can only be pushed into an Index Cond if the planner may evaluate it BEFORE the
68
+ // table's security quals; `contain_leaked_vars` decides that, and it treats a CoalesceExpr as leaky
69
+ // while CaseExpr is on its whitelist. So with COALESCE the planner refuses to promote the tenant
70
+ // predicate and demotes `partner_id` to a Filter — on exactly the tables where partner_id leads a
71
+ // composite key, which is every key the tenancy migration widened.
72
+ //
73
+ // MEASURED in an app (PG 18, 20k rows per partner, one row by a two-column key):
74
+ //
75
+ // literal `partner_id = 61` Index Cond, 4-7 buffers, 1 index search
76
+ // COALESCE (the older form) FILTER, 27 buffers, 6 index searches
77
+ // CASE (what this is) Index Cond, 4 buffers, 1 index search
78
+ //
79
+ // Four partners made it 27 buffers against 4. The cost is linear in TENANT COUNT, so it grows with
80
+ // exactly the thing the partner tier exists to add, and on PG <= 17 there is no skip scan at all —
81
+ // it degrades to reading every partner's slice of the index on every lookup.
82
+ //
83
+ // THE TEXT IS BYTE-EQUAL to every app copy that has the CASE form (test/sql.js holds it against
84
+ // fixtures copied from each). Interpolated into every andTenant/whereTenant call site, so the shape
85
+ // here is the shape all of them get.
86
+ const TENANT = `CASE
87
+ WHEN NULLIF(current_setting('app.partner_id', true), '') IS NULL
88
+ THEN (SELECT id FROM partners WHERE is_house = 1)
89
+ ELSE current_setting('app.partner_id', true)::integer
90
+ END`;
91
+
92
+ /**
93
+ * `partner_id = <this tenant>`, or an empty string on SQLite.
94
+ *
95
+ * NOTHING ON SQLITE, and that is not a gap. The tenancy migration gives every partner_id column
96
+ * DEFAULT 1 there and creates no policies at all — there is one tenant, so a predicate would be
97
+ * answering a question that cannot be asked.
98
+ *
99
+ * @param {string} [alias] table alias, for a query that joins — `andTenant('c')` → `c.partner_id`
100
+ */
101
+ function tenantPredicate(alias) {
102
+ if (dialect().kind !== 'postgres') return '';
103
+ return `${alias ? alias + '.' : ''}partner_id = ${TENANT}`;
104
+ }
105
+
106
+ /** Was this rejection a UNIQUE constraint refusing a duplicate? Knows both engines' codes. */
107
+ function isUniqueViolation(err) {
108
+ if (!err) return false;
109
+ // SQLite reports a string code; Postgres reports SQLSTATE 23505. By CODE, never by message —
110
+ // message text is not a contract and differs between versions.
111
+ return err.code === 'SQLITE_CONSTRAINT_UNIQUE' || err.code === 'SQLITE_CONSTRAINT_PRIMARYKEY'
112
+ || err.code === '23505';
113
+ }
114
+
115
+ module.exports = {
116
+ /** The dialect itself, for a caller that renders several expressions and wants it once. */
117
+ dialect,
118
+
119
+ /**
120
+ * ` WHERE partner_id = <this tenant>` — for a SELECT with no other conditions.
121
+ *
122
+ * Renders the leading space and the keyword, so a caller interpolating it into a query that has
123
+ * no other WHERE does not have to decide whether to write one. Empty on SQLite.
124
+ */
125
+ whereTenant: (alias) => {
126
+ const p = tenantPredicate(alias);
127
+ return p ? ` WHERE ${p}` : '';
128
+ },
129
+
130
+ /** ` AND partner_id = <this tenant>` — for a SELECT that already has a WHERE. Empty on SQLite. */
131
+ andTenant: (alias) => {
132
+ const p = tenantPredicate(alias);
133
+ return p ? ` AND ${p}` : '';
134
+ },
135
+
136
+ /** The bare predicate, for a caller composing its own clause. Empty on SQLite. */
137
+ tenantPredicate,
138
+
139
+ /**
140
+ * The tenant EXPRESSION itself, for a caller that has its own dialect and cannot ask for one —
141
+ * a query builder that takes its dialect as an argument so it stays driver-free and testable.
142
+ * Exported rather than copied: a second copy of this is how two models in one app came to be
143
+ * missing the predicate a third one beside them already had.
144
+ */
145
+ TENANT_EXPR: TENANT,
146
+
147
+ /**
148
+ * ` AND <column> holds printable ASCII only` — for a comparison through `lower()` that must agree
149
+ * with JavaScript's toLowerCase: on ASCII the two are the same function, and beyond it they are
150
+ * not (PostgreSQL lowers the Kelvin sign to `k`; JavaScript lowers `İ` to two code points).
151
+ */
152
+ andPrintableAscii: (column) => (dialect().kind === 'postgres'
153
+ ? ` AND ${column} ~ '^[ -~]*$'`
154
+ : ` AND ${column} NOT GLOB '*[^ -~]*'`),
155
+
156
+ /** Now, as this engine writes a UTC timestamp. */
157
+ now: () => dialect().now(),
158
+
159
+ /** N whole days before now — retention cuts. */
160
+ nowMinusDays: (n) => dialect().nowMinusDays(n),
161
+
162
+ /** N seconds before now — a short expiry window. */
163
+ nowMinusSeconds: (n) => dialect().nowMinusSeconds(n),
164
+
165
+ /** N minutes after now — an expiry. Negative goes backwards. */
166
+ nowPlusMinutes: (n) => dialect().nowPlusMinutes(n),
167
+
168
+ /** The first instant of the current 'month' or 'year'. */
169
+ startOf: (unit) => dialect().startOf(unit),
170
+
171
+ /** The period a timestamp column falls in: 'month' or 'week'. A report axis key. */
172
+ dateGroup: (col, unit) => dialect().dateGroup(col, unit),
173
+
174
+ /**
175
+ * The fractional difference in days between two timestamp expressions.
176
+ *
177
+ * NEVER PASS THE LITERAL `'now'`. Both engines PARSE it and they mean different instants:
178
+ *
179
+ * SQLite julianday('now') UTC, always
180
+ * Postgres 'now'::timestamp the SESSION's time zone
181
+ *
182
+ * Every timestamp here is stored as UTC text, so on a server whose session zone is not UTC the
183
+ * subtraction is off by exactly the offset — not an error, a wrong number, on a value nobody
184
+ * would think to re-derive. Pass `sql.now()` instead so both sides are in the same frame.
185
+ * Comparing two stored COLUMNS is always safe; they are both UTC already.
186
+ */
187
+ daysBetween: (from, to) => dialect().daysBetween(from, to),
188
+
189
+ /**
190
+ * The larger of two VALUES — `GREATEST(a, b)` on Postgres, `MAX(a, b)` on SQLite.
191
+ *
192
+ * THE SAME WORD MEANS TWO THINGS. SQLite's MAX is overloaded: one argument makes it an aggregate,
193
+ * two make it a scalar. Postgres has only the aggregate and spells the scalar GREATEST, so
194
+ * `MAX(1, x)` is not a wrong answer there — it is `function max(integer, integer) does not exist`.
195
+ */
196
+ greatest: (a, b) => dialect().greatest(a, b),
197
+
198
+ /** The smaller of two VALUES — `LEAST(a, b)` on Postgres, `MIN(a, b)` on SQLite. */
199
+ least: (a, b) => dialect().least(a, b),
200
+
201
+ /**
202
+ * The clause an INSERT needs before `run()` can report the new row's id.
203
+ *
204
+ * EMPTY ON SQLITE, ` RETURNING "id"` ON POSTGRES, and the emptiness is why this is easy to miss.
205
+ * better-sqlite3 hands back `lastInsertRowid` for nothing, so reading the id works on SQLite
206
+ * whether or not the clause is there; Postgres has no such thing and returns `undefined`, which
207
+ * `Number()` turns into NaN and the database rejects as `invalid input syntax for type bigint:
208
+ * "NaN"`. Every create path then works in development and none of them work in production.
209
+ *
210
+ * APPENDED, NOT INTERPOLATED MID-STATEMENT: it goes at the very end of the INSERT, after any
211
+ * ON CONFLICT clause. testkit's assertDriverDiscipline checks both that it is present wherever an
212
+ * id is read back, and that nothing follows it in the statement.
213
+ */
214
+ returningId: (col = 'id') => dialect().returning(col),
215
+
216
+ // ── schema introspection, straight from the dialect ──────────────────────────────────────────
217
+
218
+ /** Every ordinary table, one `name` column on both engines. */
219
+ tables: () => dialect().tables(),
220
+
221
+ /** The foreign keys declared on a table, as `{ from, table, to }` on both engines. */
222
+ foreignKeys: (table) => dialect().foreignKeys(table),
223
+
224
+ // ── READING A JSON OR ARRAY COLUMN, WHICH THE TWO ENGINES HAND BACK IN DIFFERENT SHAPES ──────
225
+ //
226
+ // node-postgres PARSES jsonb and text[] for you and hands over an object or a JS array;
227
+ // better-sqlite3 hands over the TEXT exactly as stored. So a page that renders one of these has
228
+ // to reconcile two shapes, and doing that in each model is several copies of one asymmetry.
229
+ //
230
+ // SHAPE-BASED, NOT DIALECT-BASED, AND THAT IS DELIBERATE. Every other function in this file
231
+ // resolves `dialect()` and therefore needs `database.driver()`, which exists ONLY inside the DB
232
+ // worker thread. These two must be callable from a ROUTE — the main thread, where driver() is
233
+ // null — so they branch on what they were handed, not on which engine handed it over.
234
+ //
235
+ // THE LIMIT: a parsed value from a column whose default is an object or an array is never a
236
+ // string, while the stored TEXT always is. A `jsonb` column holding a bare scalar (the document
237
+ // `"hello"`) cannot be read with these — node-postgres hands back the JS string `hello`, already
238
+ // parsed, and this would parse it a second time. Know that before adding such a column.
239
+ //
240
+ // AND A MALFORMED VALUE THROWS. Not `{}`, not `[]`: a catch that degrades to an empty collection
241
+ // reads as "nothing to show" and is indistinguishable downstream from a column that really is
242
+ // empty. JSON.parse's own message is kept and the column named beside it.
243
+
244
+ /**
245
+ * A JSON/JSONB column as a plain object. `null`/`undefined` — which only a nullable column can
246
+ * produce — comes back as `null`, distinct from the `{}` an empty document gives.
247
+ *
248
+ * @param {*} v the column value as the driver returned it
249
+ * @param {string} [label] column name, for the error message
250
+ */
251
+ jsonColumn: (v, label = 'json column') => {
252
+ if (v === null || v === undefined) return null;
253
+ if (typeof v !== 'string') return v;
254
+ try { return JSON.parse(v); }
255
+ catch (e) { throw new Error(`sql.jsonColumn(${label}): not JSON — ${e.message}`); }
256
+ },
257
+
258
+ /**
259
+ * A `TEXT[]` / JSON-array-in-TEXT column as a JS array.
260
+ *
261
+ * A parsed value that is NOT an array is an error rather than something to wrap: a scalar there
262
+ * means the column holds something nobody intended, and silently making it `[value]` would hide
263
+ * that for good.
264
+ *
265
+ * `null` COMES BACK AS `[]` HERE WHILE jsonColumn RETURNS `null` — ON PURPOSE. A document is
266
+ * rendered on PRESENCE, so `null` (no document) and `{}` (an empty one) must stay apart; an array
267
+ * is ITERATED, and to every caller of this one "absent" and "empty" are the same thing. Nothing
268
+ * is caught: a malformed value throws. `[]` is the answer to "no value", not to "the read failed".
269
+ */
270
+ arrayColumn: (v, label = 'array column') => {
271
+ if (v === null || v === undefined) return [];
272
+ const parsed = (typeof v === 'string')
273
+ ? (() => {
274
+ try { return JSON.parse(v); }
275
+ catch (e) { throw new Error(`sql.arrayColumn(${label}): not JSON — ${e.message}`); }
276
+ })()
277
+ : v;
278
+ if (!Array.isArray(parsed)) {
279
+ throw new Error(`sql.arrayColumn(${label}): expected an array, got ${typeof parsed}`);
280
+ }
281
+ return parsed;
282
+ },
283
+
284
+ // ── WRITING ONE, WHICH IS A DIFFERENT PROBLEM AND A DIFFERENT CALLER ─────────────────────────
285
+ //
286
+ // The pair above reconciles two shapes that ARRIVE. These two produce the shape that must be
287
+ // SENT. A `TEXT[]` column on Postgres and a JSON array in `TEXT` on SQLite share no literal: a
288
+ // Postgres array literal (`{primary,billing}`) stored on SQLite is exactly the value
289
+ // `arrayColumn` throws on; a JSON array string sent to a `text[]` column is `malformed array
290
+ // literal`. So an array write has to branch on the DIALECT, which makes it WORKER-ONLY: a route
291
+ // hands the model a plain JS array or object and the model converts it.
292
+ //
293
+ // `jsonParam` needs no dialect at all — Postgres accepts a JSON *string* for a `jsonb` parameter
294
+ // and SQLite stores it as the TEXT it already is — and is documented as dialect-free rather than
295
+ // dressed up as needing the driver it does not need.
296
+ //
297
+ // BOTH REFUSE A WRONG SHAPE rather than coercing it: silently wrapping a scalar (`[v]`, `{v}`)
298
+ // writes a value nobody intended into a column nobody will re-read.
299
+
300
+ /**
301
+ * A JS array as this engine's parameter for a `TEXT[]` / JSON-array-in-TEXT column.
302
+ *
303
+ * WORKER-ONLY — it resolves the dialect.
304
+ *
305
+ * @param {string[]} v the array to write
306
+ * @param {string} [label] column name, for the error message
307
+ */
308
+ arrayParam: (v, label = 'array column') => {
309
+ if (!Array.isArray(v)) {
310
+ throw new Error(`sql.arrayParam(${label}): expected an array, got ${v === null ? 'null' : typeof v}`);
311
+ }
312
+ // THE JS ARRAY ITSELF on Postgres: node-postgres serialises it to the `{"a","b"}` literal
313
+ // `text[]` wants. JSON on SQLite, the shape `arrayColumn` parses back.
314
+ return dialect().kind === 'postgres' ? v : JSON.stringify(v);
315
+ },
316
+
317
+ /**
318
+ * A plain object as this engine's parameter for a `JSONB` / JSON-document-in-TEXT column.
319
+ *
320
+ * ONE SPELLING FOR BOTH ENGINES — see the note above on why this one needs no dialect.
321
+ *
322
+ * @param {object} v the document to write
323
+ * @param {string} [label] column name, for the error message
324
+ */
325
+ jsonParam: (v, label = 'json column') => {
326
+ if (v === null || v === undefined || typeof v !== 'object' || Array.isArray(v)) {
327
+ throw new Error(`sql.jsonParam(${label}): expected an object, got `
328
+ + `${v === null ? 'null' : Array.isArray(v) ? 'an array' : typeof v}`);
329
+ }
330
+ return JSON.stringify(v);
331
+ },
332
+
333
+ /** Was this rejection a UNIQUE constraint refusing a duplicate? Knows both engines' codes. */
334
+ isUniqueViolation,
335
+
336
+ /**
337
+ * WHICH unique rule refused it: `{ table, columns, index }`, or null when `err` is not a unique
338
+ * violation. For mapping one index to one message ("that name is taken"). The fields survive
339
+ * dbClient.invoke (the worker keeps an error's own properties), so a route can call it too.
340
+ *
341
+ * The two engines report different facts, so match on the one your index gives on both:
342
+ * - `columns` — the key's columns, without the table: `['board_id', 'name']`. SQLite names
343
+ * them in its message; Postgres in `detail` ("Key (board_id, name)=(...)"), whose values are
344
+ * never returned. An EXPRESSION index has no columns on SQLite (null) and its expression on
345
+ * Postgres (`['lower(name)']`).
346
+ * - `index` — the constraint or index name. Postgres always has it (`err.constraint`); SQLite
347
+ * only for an expression index ("UNIQUE constraint failed: index 'x'"), null otherwise.
348
+ * So: a plain-column index, match `columns`; an expression index, match `index`.
349
+ *
350
+ * ON A TABLE UNDER ROW-LEVEL SECURITY Postgres withholds that detail from a role the policy
351
+ * applies to (the application role), so `columns` is null there and only `index` names the rule
352
+ * (measured in test/sql.js). On a scoped table, match `index`.
353
+ *
354
+ * SQLite's facts come from its MESSAGE, because it has nowhere else to put them — the yes/no
355
+ * stays by code, above. A message or detail in an unexpected shape gives nulls, never a throw.
356
+ * `table` is null on SQLite for an expression index. test/sql.js holds the shapes against both
357
+ * engines.
358
+ */
359
+ uniqueViolation: (err) => {
360
+ if (!isUniqueViolation(err)) return null;
361
+ if (err.code === '23505') {
362
+ const m = /^Key \((.*)\)=\(/.exec(String(err.detail || ''));
363
+ return { table: err.table || null, columns: m ? m[1].split(', ') : null, index: err.constraint || null };
364
+ }
365
+ const msg = String(err.message || '');
366
+ const idx = /UNIQUE constraint failed: index '([^']+)'/.exec(msg);
367
+ if (idx) return { table: null, columns: null, index: idx[1] };
368
+ const cols = /UNIQUE constraint failed: (.+)$/.exec(msg);
369
+ if (!cols) return { table: null, columns: null, index: null };
370
+ const parts = cols[1].split(', ').map((c) => c.trim());
371
+ const table = parts[0].includes('.') ? parts[0].slice(0, parts[0].indexOf('.')) : null;
372
+ return { table, columns: parts.map((c) => c.slice(c.indexOf('.') + 1)), index: null };
373
+ },
374
+
375
+ /**
376
+ * Did this rejection come from the DATABASE rather than from the application?
377
+ *
378
+ * It decides whether an API caller is told "you sent something wrong" or "we broke". Asking
379
+ * `code.startsWith('SQLITE_')` alone made every Postgres failure read as a CLIENT error: a 400
380
+ * instead of a 500, with the driver's own message in the response body — wrong status and a
381
+ * small information leak in one line. Postgres codes are five-character SQLSTATEs (23505,
382
+ * 42601, …), which is what the second test matches; SQLite's are the prefixed names.
383
+ */
384
+ isDatabaseError: (err) => {
385
+ const code = !err || err.code == null ? '' : String(err.code);
386
+ return code.startsWith('SQLITE_') || /^[0-9A-Z]{5}$/.test(code);
387
+ },
388
+
389
+ /**
390
+ * Did Postgres break a deadlock by aborting THIS transaction (SQLSTATE 40P01)? The transaction
391
+ * is gone; the caller may retry it whole. Never true on SQLite, which has one writer and reports
392
+ * contention as SQLITE_BUSY instead.
393
+ */
394
+ isDeadlock: (err) => !!err && String(err.code) === '40P01'
395
+ };