@aria-framework/db-worker 0.6.1 → 0.8.1
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/README.md +66 -0
- package/database.js +226 -22
- package/dialect.js +5 -0
- package/driver/params.js +4 -0
- package/driver/postgres.js +27 -3
- package/driver/sqlite.js +11 -3
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -108,10 +108,76 @@ Model methods may be sync or async (thenables are awaited). BigInts in results
|
|
|
108
108
|
SQLCipher hook: an encrypted DB needs `pragma key` before anything touches it.
|
|
109
109
|
- `runMigrations(migrationsDir)` — applies `*.sql` sorted by filename, each in
|
|
110
110
|
a transaction with its tracking-row insert; already-applied files skipped.
|
|
111
|
+
A file can opt out — see below.
|
|
111
112
|
- `getDb()` / `close()`
|
|
112
113
|
|
|
114
|
+
## Migrations that cannot run inside a transaction (0.8.0)
|
|
115
|
+
|
|
116
|
+
Some DDL is illegal inside a transaction. A migration declares that with a
|
|
117
|
+
marker line, which must be **exactly** this, on its own line, in the file's
|
|
118
|
+
leading comment block:
|
|
119
|
+
|
|
120
|
+
```sql
|
|
121
|
+
-- aria:no-transaction
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Why it exists, measured on both engines:
|
|
125
|
+
|
|
126
|
+
| engine | statement | inside a transaction |
|
|
127
|
+
|---|---|---|
|
|
128
|
+
| SQLite | the table-rebuild recipe (`PRAGMA foreign_keys = OFF`) | the pragma is a **no-op**, so dropping a referenced table fails with `FOREIGN KEY constraint failed` |
|
|
129
|
+
| PostgreSQL | `CREATE INDEX CONCURRENTLY` | `ERROR: cannot run inside a transaction block` |
|
|
130
|
+
|
|
131
|
+
**The trade: such a file is not atomic.** A failure part-way leaves an
|
|
132
|
+
intermediate state *and* leaves the ledger row unwritten, so the next boot runs
|
|
133
|
+
it again. **A no-transaction migration must therefore be idempotent.** This is
|
|
134
|
+
the same trade Rails makes with `disable_ddl_transaction!` and Django with
|
|
135
|
+
`atomic = False`.
|
|
136
|
+
|
|
137
|
+
Three things that are easy to get wrong:
|
|
138
|
+
|
|
139
|
+
- **On PostgreSQL the file must contain exactly ONE statement.** A
|
|
140
|
+
multi-statement send still runs in an *implicit* transaction, so
|
|
141
|
+
`CREATE INDEX CONCURRENTLY` still refuses. A table and its concurrent index
|
|
142
|
+
belong in two migration files. The runner rewrites that failure into this
|
|
143
|
+
instruction rather than leaving the raw error.
|
|
144
|
+
- **A failed `CREATE INDEX CONCURRENTLY` leaves an INVALID index behind.** The
|
|
145
|
+
file is unledgered, so the next boot re-runs it and hits *"relation already
|
|
146
|
+
exists"* — a wedged boot. `IF NOT EXISTS` is worse: it skips silently and the
|
|
147
|
+
invalid, planner-ignored index stays forever. Use a separate marked migration
|
|
148
|
+
that runs `DROP INDEX IF EXISTS <name>;` first.
|
|
149
|
+
- **On SQLite, close every `BEGIN` the file opens.** The runner rolls back a
|
|
150
|
+
transaction left open and fails loudly, rather than letting later migrations
|
|
151
|
+
silently join it.
|
|
152
|
+
|
|
153
|
+
A line that *looks* like the marker but is not exactly it (a trailing
|
|
154
|
+
explanation, different case, `aria: no-transaction`) is a hard error, not a
|
|
155
|
+
silent fall-back to the wrapped path. The marker is only recognised in the
|
|
156
|
+
leading comment block, so one appearing inside a string literal or a function
|
|
157
|
+
body does not strip that file's transaction.
|
|
158
|
+
|
|
159
|
+
Connection pragmas (`journal_mode`, `synchronous`, `foreign_keys`,
|
|
160
|
+
`busy_timeout`) are re-asserted after any unwrapped file, so a migration that
|
|
161
|
+
turns foreign keys off cannot leave them off for the process.
|
|
162
|
+
|
|
113
163
|
## Changelog
|
|
114
164
|
|
|
165
|
+
- **0.8.0** — `-- aria:no-transaction` (above). Also: the SQLite path now rolls
|
|
166
|
+
back a transaction an unwrapped file left open, and restores the connection
|
|
167
|
+
pragmas afterwards — without that, one failing marked migration left
|
|
168
|
+
`foreign_keys = 0` and the next insert of an orphan row was accepted
|
|
169
|
+
silently, for the life of the process.
|
|
170
|
+
- **0.7.0** — `dialect.ciEquals()` for case-insensitive **equality**
|
|
171
|
+
(`ilike()` is a *pattern* operator: `role LIKE 'read_only'` matched
|
|
172
|
+
`read-only`). `better-sqlite3` is now loaded lazily, so a Postgres-only app
|
|
173
|
+
can load this package at all. Transaction depth moved onto the connection, so
|
|
174
|
+
two drivers over one handle no longer both issue `BEGIN`. The pg `Pool` gets
|
|
175
|
+
an `'error'` listener; host/user/database options actually reach it; jsonb
|
|
176
|
+
`?`/`?|`/`?&` and `@@` survive placeholder rewriting.
|
|
177
|
+
- **0.6.1** — nested transactions via savepoints.
|
|
178
|
+
- **0.6.0** — driver contract (SQLite + PostgreSQL, selected per app),
|
|
179
|
+
`dialectFor()`, driver-aware migration runner.
|
|
180
|
+
|
|
115
181
|
- **0.4.2** — sanitizeForTransfer passes `Map`/`Set` through untouched (like
|
|
116
182
|
Date/Buffer/typed arrays — structured clone handles them natively; the
|
|
117
183
|
generic object branch would silently mangle them to `{}`). Latent-bug guard
|
package/database.js
CHANGED
|
@@ -10,7 +10,23 @@
|
|
|
10
10
|
* that variant is now the `onOpen` hook).
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
// LAZY, and load-bearing. better-sqlite3 is an OPTIONAL peer so a Postgres-only app never has to
|
|
14
|
+
// build a native module it will not use — but index.js exports `database: require('./database')`,
|
|
15
|
+
// so a top-level require here made merely LOADING the package fail with MODULE_NOT_FOUND for
|
|
16
|
+
// exactly those apps. The optional peer was therefore optional in the manifest and mandatory in
|
|
17
|
+
// practice, which defeats the point of shipping two drivers.
|
|
18
|
+
let _Database = null;
|
|
19
|
+
const loadDatabase = () => {
|
|
20
|
+
if (_Database) return _Database;
|
|
21
|
+
try { _Database = require('better-sqlite3'); }
|
|
22
|
+
catch (e) {
|
|
23
|
+
throw new Error(
|
|
24
|
+
'db-worker: better-sqlite3 is not installed. It is an optional peer — install it for the ' +
|
|
25
|
+
'sqlite driver, or use initDriver({ kind: "postgres" }). (' + e.message + ')'
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
return _Database;
|
|
29
|
+
};
|
|
14
30
|
const fs = require('fs');
|
|
15
31
|
const path = require('path');
|
|
16
32
|
|
|
@@ -37,7 +53,7 @@ function init(dbPath, opts = {}) {
|
|
|
37
53
|
fs.mkdirSync(dir, { recursive: true });
|
|
38
54
|
}
|
|
39
55
|
|
|
40
|
-
_db = new
|
|
56
|
+
_db = new (loadDatabase())(dbPath);
|
|
41
57
|
|
|
42
58
|
if (typeof opts.onOpen === 'function') opts.onOpen(_db);
|
|
43
59
|
|
|
@@ -45,10 +61,7 @@ function init(dbPath, opts = {}) {
|
|
|
45
61
|
|
|
46
62
|
// Performance + safety pragmas. WAL gives concurrent readers + one writer;
|
|
47
63
|
// synchronous=NORMAL is the recommended pairing (FULL fsyncs every write).
|
|
48
|
-
_db.pragma(
|
|
49
|
-
_db.pragma('synchronous = NORMAL');
|
|
50
|
-
_db.pragma('foreign_keys = ON');
|
|
51
|
-
_db.pragma('busy_timeout = 5000');
|
|
64
|
+
for (const pr of CONNECTION_PRAGMAS) _db.pragma(pr);
|
|
52
65
|
|
|
53
66
|
_driver = _adoptSqliteDriver(_db);
|
|
54
67
|
|
|
@@ -65,13 +78,153 @@ function init(dbPath, opts = {}) {
|
|
|
65
78
|
return _db;
|
|
66
79
|
}
|
|
67
80
|
|
|
81
|
+
// The connection-level pragmas init() establishes as invariants. Hoisted so the no-transaction
|
|
82
|
+
// path can RE-ASSERT them: a migration that runs unwrapped can change session state, and
|
|
83
|
+
// `PRAGMA foreign_keys = OFF` is literally the first line of the recipe this feature exists for.
|
|
84
|
+
// Measured consequence of not restoring them: after one failing marked migration the connection
|
|
85
|
+
// kept foreign_keys = 0 and silently accepted an ORPHAN row on the next insert, for the lifetime
|
|
86
|
+
// of the process.
|
|
87
|
+
const CONNECTION_PRAGMAS = [
|
|
88
|
+
'journal_mode = WAL',
|
|
89
|
+
'synchronous = NORMAL',
|
|
90
|
+
'foreign_keys = ON',
|
|
91
|
+
'busy_timeout = 5000'
|
|
92
|
+
];
|
|
93
|
+
|
|
94
|
+
/* eslint-disable no-useless-escape */
|
|
95
|
+
// Some DDL cannot run inside a transaction, and a migration says so with a marker line:
|
|
96
|
+
//
|
|
97
|
+
// -- aria:no-transaction
|
|
98
|
+
//
|
|
99
|
+
// MEASURED ON BOTH ENGINES, which is why this exists rather than being a SQLite workaround:
|
|
100
|
+
// - SQLite: the docs' table-rebuild recipe needs `PRAGMA foreign_keys = OFF`, and that pragma
|
|
101
|
+
// is a NO-OP inside a transaction (verified: it reads back 1). With foreign keys enforced,
|
|
102
|
+
// dropping a table that others reference fails with "FOREIGN KEY constraint failed".
|
|
103
|
+
// - PostgreSQL: `CREATE INDEX CONCURRENTLY` refuses outright — "cannot run inside a transaction
|
|
104
|
+
// block" — and a concurrent index build is exactly what a high-write table needs.
|
|
105
|
+
//
|
|
106
|
+
// THE TRADE the author of such a migration accepts: that file is NOT atomic. A failure part-way
|
|
107
|
+
// leaves the database in an intermediate state AND leaves the ledger row unwritten, so the next
|
|
108
|
+
// boot runs it again. Such a migration MUST therefore be idempotent. Same trade Rails makes with
|
|
109
|
+
// disable_ddl_transaction! and Django with atomic = False.
|
|
110
|
+
//
|
|
111
|
+
// WHAT THE MARKER MEANS DIFFERS BY ENGINE, and both were measured rather than assumed:
|
|
112
|
+
// SQLite statements really do run unwrapped, one after another. A failure part-way leaves
|
|
113
|
+
// the earlier ones applied.
|
|
114
|
+
// Postgres it removes only the runner's EXPLICIT transaction. A multi-statement send still
|
|
115
|
+
// runs inside an IMPLICIT one, so such a file is still all-or-nothing — and
|
|
116
|
+
// `CREATE INDEX CONCURRENTLY` STILL REFUSES when it is one of several statements.
|
|
117
|
+
// So on Postgres a no-transaction migration must contain exactly ONE statement. A
|
|
118
|
+
// table and its concurrent index belong in two migration files anyway.
|
|
119
|
+
//
|
|
120
|
+
// POSTGRES IDEMPOTENCY HAS A SHARP EDGE worth spelling out, because "must be idempotent" is not
|
|
121
|
+
// enough guidance on its own: a FAILED `CREATE INDEX CONCURRENTLY` leaves the index behind in an
|
|
122
|
+
// INVALID state. The file is unledgered, so the next boot re-runs it and hits "relation already
|
|
123
|
+
// exists" — a permanently wedged boot. Writing `IF NOT EXISTS` is worse: it skips silently and
|
|
124
|
+
// the invalid, planner-ignored index stays forever. Such a migration needs an explicit
|
|
125
|
+
// `DROP INDEX IF EXISTS <name>;` preamble... which then makes it multi-statement, so it must be
|
|
126
|
+
// split: one marked file to drop, one marked file to create.
|
|
127
|
+
//
|
|
128
|
+
// Deliberately a MARKER rather than sniffing the SQL: guessing which statements need this is a
|
|
129
|
+
// parser problem with silent failure modes, and this way the decision is recorded by the person
|
|
130
|
+
// who understood it.
|
|
131
|
+
const NO_TX_MARKER = /^[ \t]*--[ \t]*aria:no-transaction[ \t]*$/;
|
|
132
|
+
// A near miss must FAIL rather than silently fall back to the wrapped path — an author staring at
|
|
133
|
+
// a file that visibly contains the marker, while the runner ignored it, is the worst outcome the
|
|
134
|
+
// design can produce. Catches trailing explanations, wrong case, and `aria: no-transaction`.
|
|
135
|
+
const NO_TX_NEARMISS = /^[ \t]*--[ \t]*aria:[ \t]*no[-_ ]?transaction\b/i;
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Does this file opt out of the runner's transaction?
|
|
139
|
+
*
|
|
140
|
+
* Scans ONLY the leading comment block — every line before the first line that is neither blank
|
|
141
|
+
* nor a `--` comment. Scanning the whole file honoured a marker that appeared inside a string
|
|
142
|
+
* literal, a dollar-quoted body or a block comment (`INSERT INTO docs (body) VALUES ('… put
|
|
143
|
+
* -- aria:no-transaction on its own line …')` matched), silently stripping that migration's
|
|
144
|
+
* transaction. A marker is a file-level declaration, so the header is the only place it belongs.
|
|
145
|
+
*
|
|
146
|
+
* @throws if a line in the header LOOKS like the marker but is not exactly it.
|
|
147
|
+
*/
|
|
148
|
+
function wantsNoTransaction(sql, file) {
|
|
149
|
+
for (const raw of String(sql).split(/\r?\n/)) {
|
|
150
|
+
const line = raw.replace(/\uFEFF/g, '');
|
|
151
|
+
if (/^[ \t]*$/.test(line)) continue; // blank
|
|
152
|
+
if (!/^[ \t]*--/.test(line)) return false; // first real SQL ends the header
|
|
153
|
+
if (NO_TX_MARKER.test(line)) return true;
|
|
154
|
+
if (NO_TX_NEARMISS.test(line)) {
|
|
155
|
+
throw new Error(
|
|
156
|
+
`Migration ${file || ''} has a line that looks like the no-transaction marker but is not ` +
|
|
157
|
+
`exactly it: ${JSON.stringify(line.trim())}. It must be exactly "-- aria:no-transaction" ` +
|
|
158
|
+
'on its own line. Refusing to run it wrapped, which is what silently ignoring it would do.'
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Does this file contain more than one statement? Used ONLY to decide whether Postgres's
|
|
167
|
+
* "cannot run inside a transaction block" should be rewritten into split-the-file guidance.
|
|
168
|
+
*
|
|
169
|
+
* Deliberately conservative and comment/string aware enough for that one job: it strips line and
|
|
170
|
+
* block comments and single-quoted, double-quoted and dollar-quoted bodies, then asks whether any
|
|
171
|
+
* `;` has non-blank content after it. Being wrong only changes which of two true error messages
|
|
172
|
+
* an operator sees, never whether the migration runs.
|
|
173
|
+
*/
|
|
174
|
+
function looksMultiStatement(sql) {
|
|
175
|
+
const stripped = String(sql)
|
|
176
|
+
.replace(/\$([A-Za-z_0-9]*)\$[\s\S]*?\$\1\$/g, '') // dollar-quoted bodies
|
|
177
|
+
.replace(/'(?:[^']|'')*'/g, "''") // single-quoted literals
|
|
178
|
+
.replace(/"(?:[^"]|"")*"/g, '""') // quoted identifiers
|
|
179
|
+
.replace(/\/\*[\s\S]*?\*\//g, ' ') // block comments
|
|
180
|
+
.replace(/--[^\n]*/g, ' '); // line comments
|
|
181
|
+
const parts = stripped.split(';').map((x) => x.trim()).filter(Boolean);
|
|
182
|
+
return parts.length > 1;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const noTxWarning = (file) =>
|
|
186
|
+
`Migration ${file} runs OUTSIDE a transaction (-- aria:no-transaction). It is not atomic and ` +
|
|
187
|
+
'must be idempotent; a partial failure will re-run it.';
|
|
188
|
+
|
|
68
189
|
/**
|
|
69
|
-
* Run
|
|
70
|
-
*
|
|
71
|
-
*
|
|
190
|
+
* Run one unwrapped SQLite file, then put the CONNECTION back the way it was found.
|
|
191
|
+
*
|
|
192
|
+
* Two failures this repairs, both measured against the real runner:
|
|
193
|
+
* - A file whose own BEGIN…COMMIT failed part-way left the connection INSIDE an uncommitted
|
|
194
|
+
* transaction (db.inTransaction === true). The ledger insert and every later migration then
|
|
195
|
+
* silently joined it — better-sqlite3 downgrades db.transaction() to a SAVEPOINT when one is
|
|
196
|
+
* already open, so per-file atomicity was gone — the write lock was held for the process
|
|
197
|
+
* lifetime, and the lot was discarded at close().
|
|
198
|
+
* - `PRAGMA foreign_keys = OFF` (the first line of the recipe) survived the file. The next
|
|
199
|
+
* insert of an orphan row was ACCEPTED with no error.
|
|
72
200
|
*/
|
|
201
|
+
function execUnwrappedSqlite(db, sql) {
|
|
202
|
+
let failure = null;
|
|
203
|
+
try {
|
|
204
|
+
db.exec(sql);
|
|
205
|
+
} catch (e) {
|
|
206
|
+
failure = e;
|
|
207
|
+
}
|
|
208
|
+
let dangling = false;
|
|
209
|
+
if (db.inTransaction) {
|
|
210
|
+
dangling = true;
|
|
211
|
+
try { db.exec('ROLLBACK'); } catch (_) { /* nothing better to do; the throw below still fires */ }
|
|
212
|
+
}
|
|
213
|
+
// Restore the invariants unconditionally — the file may have changed them and succeeded.
|
|
214
|
+
for (const pr of CONNECTION_PRAGMAS) { try { db.pragma(pr); } catch (_) { /* best effort */ } }
|
|
215
|
+
|
|
216
|
+
if (failure) throw failure;
|
|
217
|
+
if (dangling) {
|
|
218
|
+
throw new Error(
|
|
219
|
+
'A no-transaction migration finished with a transaction still open (a BEGIN with no ' +
|
|
220
|
+
'matching COMMIT). It was rolled back. Fix the file so every BEGIN it opens is closed.'
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
73
225
|
/**
|
|
74
|
-
* Apply pending numbered migrations, in filename order, each in its own transaction
|
|
226
|
+
* Apply pending numbered migrations, in filename order, each in its own transaction — unless
|
|
227
|
+
* the file opts out with `-- aria:no-transaction` (see the marker notes above).
|
|
75
228
|
*
|
|
76
229
|
* RETURNS A PROMISE, BUT THE SQLITE PATH HAS ALREADY FINISHED BY THE TIME IT DOES — and that
|
|
77
230
|
* asymmetry is deliberate, not an oversight. The first consumer has 31 TOP-LEVEL call sites in
|
|
@@ -108,12 +261,23 @@ function runMigrations(migrationsDir) {
|
|
|
108
261
|
for (const file of files) {
|
|
109
262
|
if (applied.has(file)) continue;
|
|
110
263
|
const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
264
|
+
if (wantsNoTransaction(sql, file)) {
|
|
265
|
+
// Announced, not silent: an operator reading boot output should see which file gave up
|
|
266
|
+
// atomicity, because that is the file to inspect if the boot dies mid-migration.
|
|
267
|
+
_logger.warn(noTxWarning(file));
|
|
268
|
+
execUnwrappedSqlite(db, sql);
|
|
269
|
+
// The ledger row lands in its OWN transaction, immediately after. If the DDL succeeded
|
|
270
|
+
// and this insert somehow does not, the migration re-runs — which is precisely the case
|
|
271
|
+
// the idempotency requirement covers.
|
|
115
272
|
db.prepare('INSERT INTO migrations (filename) VALUES (?)').run(file);
|
|
116
|
-
}
|
|
273
|
+
} else {
|
|
274
|
+
// One transaction per FILE, not per run: a failing migration must not roll back the ones
|
|
275
|
+
// that already succeeded, or a half-fixed database re-runs work it has already done.
|
|
276
|
+
db.transaction(() => {
|
|
277
|
+
db.exec(sql);
|
|
278
|
+
db.prepare('INSERT INTO migrations (filename) VALUES (?)').run(file);
|
|
279
|
+
})();
|
|
280
|
+
}
|
|
117
281
|
count++;
|
|
118
282
|
_logger.info(`Migration applied: ${file}`);
|
|
119
283
|
}
|
|
@@ -128,10 +292,38 @@ function runMigrations(migrationsDir) {
|
|
|
128
292
|
for (const file of files) {
|
|
129
293
|
if (applied.has(file)) continue;
|
|
130
294
|
const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
295
|
+
if (wantsNoTransaction(sql, file)) {
|
|
296
|
+
_logger.warn(noTxWarning(file));
|
|
297
|
+
try {
|
|
298
|
+
await d.exec(sql);
|
|
299
|
+
} catch (e) {
|
|
300
|
+
// Rewrite the multi-statement failure into the instruction that fixes it — but ONLY
|
|
301
|
+
// when the file really does contain more than one statement. Gating matters: VACUUM,
|
|
302
|
+
// CREATE DATABASE and ALTER TYPE … ADD VALUE raise the SAME message from a single
|
|
303
|
+
// statement, and telling that author to "split it into two files" sends them down a
|
|
304
|
+
// dead end while hiding the real cause.
|
|
305
|
+
if (/cannot run inside a transaction block/i.test(e.message || '') && looksMultiStatement(sql)) {
|
|
306
|
+
throw new Error(
|
|
307
|
+
`Migration ${file} is marked -- aria:no-transaction, but Postgres still refused: ` +
|
|
308
|
+
`${e.message}. A multi-statement file runs in an IMPLICIT transaction, so a ` +
|
|
309
|
+
'no-transaction migration must contain exactly ONE statement here. Split it into ' +
|
|
310
|
+
'two migration files — the ordinary DDL in one, the concurrent statement in another.'
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
throw e;
|
|
314
|
+
} finally {
|
|
315
|
+
// A marked file that opened a transaction and did not close it would otherwise return
|
|
316
|
+
// an "idle in transaction" client to the pool, holding its locks and snapshot for every
|
|
317
|
+
// later caller that draws it. Cheap to assert, unbounded to leave.
|
|
318
|
+
try { await d.exec('ROLLBACK'); } catch (_) { /* no transaction open: the normal case */ }
|
|
319
|
+
}
|
|
320
|
+
await d.run('INSERT INTO migrations (filename) VALUES (?)', [file]);
|
|
321
|
+
} else {
|
|
322
|
+
await d.transaction(async (tx) => {
|
|
323
|
+
await tx.exec(sql);
|
|
324
|
+
await tx.run('INSERT INTO migrations (filename) VALUES (?)', [file]);
|
|
325
|
+
});
|
|
326
|
+
}
|
|
135
327
|
count++;
|
|
136
328
|
_logger.info(`Migration applied: ${file}`);
|
|
137
329
|
}
|
|
@@ -151,13 +343,25 @@ function getDb() {
|
|
|
151
343
|
return _db;
|
|
152
344
|
}
|
|
153
345
|
|
|
154
|
-
/**
|
|
155
|
-
|
|
346
|
+
/**
|
|
347
|
+
* Close the database connection.
|
|
348
|
+
*
|
|
349
|
+
* Closes the DRIVER too. It previously only looked at `_db`, which initDriver() deliberately
|
|
350
|
+
* leaves null on Postgres — so close() was a complete no-op there, the pg Pool's sockets stayed
|
|
351
|
+
* open and the process would not exit on a graceful shutdown. On SQLite it closed the handle but
|
|
352
|
+
* left `_driver` wrapping it, so the next store call failed with better-sqlite3's "The database
|
|
353
|
+
* connection is not open" instead of this module's much clearer "not initialized".
|
|
354
|
+
*/
|
|
355
|
+
async function close() {
|
|
356
|
+
if (_driver && typeof _driver.close === 'function') {
|
|
357
|
+
try { await _driver.close(); } catch (e) { _logger.warn(`Driver close failed: ${e.message}`); }
|
|
358
|
+
}
|
|
359
|
+
_driver = null;
|
|
156
360
|
if (_db) {
|
|
157
361
|
_db.close();
|
|
158
362
|
_db = null;
|
|
159
|
-
_logger.info('Database closed');
|
|
160
363
|
}
|
|
364
|
+
_logger.info('Database closed');
|
|
161
365
|
}
|
|
162
366
|
|
|
163
367
|
/**
|
package/dialect.js
CHANGED
|
@@ -38,6 +38,10 @@ const sqlite = {
|
|
|
38
38
|
jsonPath: (col, path) => `json_extract(${col}, '${String(path).replace(/'/g, "''")}')`,
|
|
39
39
|
/** Case-insensitive LIKE. SQLite's LIKE is already case-insensitive for ASCII. */
|
|
40
40
|
ilike: () => 'LIKE',
|
|
41
|
+
// Case-insensitive EQUALITY. Deliberately NOT ilike(): LIKE/ILIKE are PATTERN operators, so
|
|
42
|
+
// `role LIKE 'read_only'` also matches 'read-only' because `_` is a single-character wildcard,
|
|
43
|
+
// and a value of '%' matches everything. Equality has to be spelled as equality.
|
|
44
|
+
ciEquals: (col, param) => `LOWER(${col}) = LOWER(${param})`,
|
|
41
45
|
/** Suffix that makes run() report a new row's id. SQLite reports it out of band. */
|
|
42
46
|
returning: () => '',
|
|
43
47
|
/** DDL fragment for an auto-incrementing primary key (only secure-keystore needs this). */
|
|
@@ -71,6 +75,7 @@ const postgres = {
|
|
|
71
75
|
return `((${col})::jsonb ->> '${key.replace(/'/g, "''")}')`;
|
|
72
76
|
},
|
|
73
77
|
ilike: () => 'ILIKE',
|
|
78
|
+
ciEquals: (col, param) => `LOWER(${col}) = LOWER(${param})`,
|
|
74
79
|
returning: (col = 'id') => ` RETURNING ${ident(col)}`,
|
|
75
80
|
autoIncrementPk: () => 'BIGSERIAL PRIMARY KEY',
|
|
76
81
|
textType: () => 'TEXT'
|
package/driver/params.js
CHANGED
|
@@ -55,6 +55,10 @@ function bindNamed(sql, params) {
|
|
|
55
55
|
const end = j === -1 ? sql.length : j + 2;
|
|
56
56
|
out += sql.slice(i, end); i = end; continue;
|
|
57
57
|
}
|
|
58
|
+
// `@@` is the full-text match operator, and `tsv @@to_tsquery('x')` written without a space
|
|
59
|
+
// was being read as a parameter named `@to_tsquery`. Full-text search is core to app 3, so
|
|
60
|
+
// consume both characters before the named-parameter rule can see the second one.
|
|
61
|
+
if (c === '@' && sql[i + 1] === '@') { out += '@@'; i += 2; continue; }
|
|
58
62
|
if (c === '@' && NAME_CHAR.test(sql[i + 1] || '')) {
|
|
59
63
|
let j = i + 1;
|
|
60
64
|
while (j < sql.length && NAME_CHAR.test(sql[j])) j++;
|
package/driver/postgres.js
CHANGED
|
@@ -67,6 +67,14 @@ function toDollarParams(sql) {
|
|
|
67
67
|
out += sql.slice(i, end); i = end; continue;
|
|
68
68
|
}
|
|
69
69
|
}
|
|
70
|
+
// JSONB EXISTENCE OPERATORS. `?`, `?|` and `?&` are real Postgres operators, and rewriting
|
|
71
|
+
// them into placeholders both breaks the query and shifts every later placeholder number by
|
|
72
|
+
// one — so the remaining binds silently land on the wrong columns. App 3 makes JSON core, so
|
|
73
|
+
// this is a query it will actually write.
|
|
74
|
+
// ?| and ?& are unambiguous (a placeholder is never followed by | or &) and pass through.
|
|
75
|
+
// A BARE ? is genuinely ambiguous, so `??` is the escape for a literal one.
|
|
76
|
+
if (c === '?' && (sql[i + 1] === '|' || sql[i + 1] === '&')) { out += sql.slice(i, i + 2); i += 2; continue; }
|
|
77
|
+
if (c === '?' && sql[i + 1] === '?') { out += '?'; i += 2; continue; }
|
|
70
78
|
if (c === '?') { out += '$' + (++n); i++; continue; }
|
|
71
79
|
|
|
72
80
|
out += c; i++;
|
|
@@ -94,9 +102,25 @@ function createPostgresDriver(opts = {}) {
|
|
|
94
102
|
throw new Error('createPostgresDriver({ connectionString }): a connection string (or host/user/database) is required');
|
|
95
103
|
}
|
|
96
104
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
105
|
+
// Pass the CONNECTION OPTIONS THROUGH. The guard above accepts host/user/database as an
|
|
106
|
+
// alternative to a connection string and the JSDoc documents it, but only connectionString was
|
|
107
|
+
// ever handed to pg — so those callers silently fell back to PGHOST/PGUSER or localhost and
|
|
108
|
+
// connected to the wrong server.
|
|
109
|
+
const { connectionString, host, port, user, password, database, ssl } = opts;
|
|
110
|
+
const poolCfg = { ...(opts.pool || {}) };
|
|
111
|
+
if (connectionString) poolCfg.connectionString = connectionString;
|
|
112
|
+
for (const [k, v] of Object.entries({ host, port, user, password, database, ssl })) {
|
|
113
|
+
if (v !== undefined) poolCfg[k] = v;
|
|
114
|
+
}
|
|
115
|
+
const pool = new pg.Pool(poolCfg);
|
|
116
|
+
|
|
117
|
+
// An unhandled 'error' on a Pool CRASHES THE PROCESS, and this is not hypothetical: the restore
|
|
118
|
+
// path issues pg_terminate_backend and DROP DATABASE ... WITH (FORCE), which kill this pool's
|
|
119
|
+
// idle clients out from under it. A server restart, failover or idle_in_transaction_session_
|
|
120
|
+
// timeout does the same. An idle-client failure must not take the worker thread down.
|
|
121
|
+
pool.on('error', (err) => {
|
|
122
|
+
try { (opts.logger || console).warn(`postgres pool: idle client error (${err.message})`); }
|
|
123
|
+
catch (_) { /* a logging failure must not become the crash this listener exists to prevent */ }
|
|
100
124
|
});
|
|
101
125
|
|
|
102
126
|
/** Build the contract over either the pool or one checked-out client (inside a transaction). */
|
package/driver/sqlite.js
CHANGED
|
@@ -67,9 +67,17 @@ function createSqliteDriver(opts = {}) {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
/** The contract over an open better-sqlite3 handle. */
|
|
70
|
+
// The nesting depth belongs to the CONNECTION, not to the wrapper around it. Each store that
|
|
71
|
+
// resolves a legacy { getDb } mints its OWN driver over the shared handle (auth/resolveDriver.js),
|
|
72
|
+
// so a per-closure counter gave every store a private depth of 0 — and the exact composition
|
|
73
|
+
// savepoint nesting was released for (an app wrapper's transaction around a store's own) issued
|
|
74
|
+
// a second BEGIN and threw "cannot start a transaction within a transaction", leaving the outer
|
|
75
|
+
// transaction open. Hanging it off the handle makes every wrapper over one connection agree.
|
|
76
|
+
const DEPTH = Symbol.for('aria.db-worker.depth');
|
|
77
|
+
|
|
70
78
|
function wrap(db) {
|
|
71
79
|
const stmt = (sql) => db.prepare(sql);
|
|
72
|
-
|
|
80
|
+
if (typeof db[DEPTH] !== 'number') db[DEPTH] = 0;
|
|
73
81
|
|
|
74
82
|
const api = {
|
|
75
83
|
kind: 'sqlite',
|
|
@@ -108,7 +116,7 @@ function wrap(db) {
|
|
|
108
116
|
// the same atomic step is the case that surfaced this). A second BEGIN is an error in
|
|
109
117
|
// SQLite, so depth is tracked: the outermost is a real transaction, inner ones are
|
|
110
118
|
// savepoints that can roll back independently without discarding the outer work.
|
|
111
|
-
const depth =
|
|
119
|
+
const depth = db[DEPTH]++;
|
|
112
120
|
const sp = `aria_sp_${depth}`;
|
|
113
121
|
db.exec(depth === 0 ? 'BEGIN' : `SAVEPOINT ${sp}`);
|
|
114
122
|
try {
|
|
@@ -120,7 +128,7 @@ function wrap(db) {
|
|
|
120
128
|
try { db.exec(depth === 0 ? 'ROLLBACK' : `ROLLBACK TO ${sp}`); } catch (_) { /* noop */ }
|
|
121
129
|
throw e;
|
|
122
130
|
} finally {
|
|
123
|
-
|
|
131
|
+
db[DEPTH] = depth;
|
|
124
132
|
}
|
|
125
133
|
},
|
|
126
134
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aria-framework/db-worker",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.1",
|
|
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,
|
|
@@ -33,6 +33,6 @@
|
|
|
33
33
|
"pg": "^8.23.0"
|
|
34
34
|
},
|
|
35
35
|
"scripts": {
|
|
36
|
-
"test": "node test/driverContract.js && node test/migrations.js && node test/smoke.js && node test/tier2.js"
|
|
36
|
+
"test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/regressions.js && node test/smoke.js && node test/tier2.js"
|
|
37
37
|
}
|
|
38
38
|
}
|