@aria-framework/db-worker 0.7.0 → 0.9.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/README.md +66 -0
- package/database.js +193 -17
- package/package.json +42 -38
- package/settingsStore.js +66 -26
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
|
@@ -61,10 +61,7 @@ function init(dbPath, opts = {}) {
|
|
|
61
61
|
|
|
62
62
|
// Performance + safety pragmas. WAL gives concurrent readers + one writer;
|
|
63
63
|
// synchronous=NORMAL is the recommended pairing (FULL fsyncs every write).
|
|
64
|
-
_db.pragma(
|
|
65
|
-
_db.pragma('synchronous = NORMAL');
|
|
66
|
-
_db.pragma('foreign_keys = ON');
|
|
67
|
-
_db.pragma('busy_timeout = 5000');
|
|
64
|
+
for (const pr of CONNECTION_PRAGMAS) _db.pragma(pr);
|
|
68
65
|
|
|
69
66
|
_driver = _adoptSqliteDriver(_db);
|
|
70
67
|
|
|
@@ -81,13 +78,153 @@ function init(dbPath, opts = {}) {
|
|
|
81
78
|
return _db;
|
|
82
79
|
}
|
|
83
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
|
+
|
|
84
137
|
/**
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
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.
|
|
88
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
|
+
|
|
189
|
+
/**
|
|
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.
|
|
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
|
+
|
|
89
225
|
/**
|
|
90
|
-
* 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).
|
|
91
228
|
*
|
|
92
229
|
* RETURNS A PROMISE, BUT THE SQLITE PATH HAS ALREADY FINISHED BY THE TIME IT DOES — and that
|
|
93
230
|
* asymmetry is deliberate, not an oversight. The first consumer has 31 TOP-LEVEL call sites in
|
|
@@ -124,12 +261,23 @@ function runMigrations(migrationsDir) {
|
|
|
124
261
|
for (const file of files) {
|
|
125
262
|
if (applied.has(file)) continue;
|
|
126
263
|
const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
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.
|
|
131
272
|
db.prepare('INSERT INTO migrations (filename) VALUES (?)').run(file);
|
|
132
|
-
}
|
|
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
|
+
}
|
|
133
281
|
count++;
|
|
134
282
|
_logger.info(`Migration applied: ${file}`);
|
|
135
283
|
}
|
|
@@ -144,10 +292,38 @@ function runMigrations(migrationsDir) {
|
|
|
144
292
|
for (const file of files) {
|
|
145
293
|
if (applied.has(file)) continue;
|
|
146
294
|
const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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
|
+
}
|
|
151
327
|
count++;
|
|
152
328
|
_logger.info(`Migration applied: ${file}`);
|
|
153
329
|
}
|
package/package.json
CHANGED
|
@@ -1,38 +1,42 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@aria-framework/db-worker",
|
|
3
|
-
"version": "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
|
-
"license": "UNLICENSED",
|
|
6
|
-
"private": false,
|
|
7
|
-
"publishConfig": {
|
|
8
|
-
"access": "public"
|
|
9
|
-
},
|
|
10
|
-
"main": "index.js",
|
|
11
|
-
"files": [
|
|
12
|
-
"index.js",
|
|
13
|
-
"database.js",
|
|
14
|
-
"worker.js",
|
|
15
|
-
"client.js",
|
|
16
|
-
"tableOrder.js",
|
|
17
|
-
"schemaSnapshot.js",
|
|
18
|
-
"workerRegistry.js",
|
|
19
|
-
"settingsStore.js",
|
|
20
|
-
"dialect.js",
|
|
21
|
-
"driver/"
|
|
22
|
-
],
|
|
23
|
-
"peerDependencies": {
|
|
24
|
-
"better-sqlite3": ">=9",
|
|
25
|
-
"pg": ">=8"
|
|
26
|
-
},
|
|
27
|
-
"peerDependenciesMeta": {
|
|
28
|
-
"better-sqlite3": {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
},
|
|
35
|
-
"
|
|
36
|
-
"
|
|
37
|
-
|
|
38
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@aria-framework/db-worker",
|
|
3
|
+
"version": "0.9.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
|
+
"license": "UNLICENSED",
|
|
6
|
+
"private": false,
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
10
|
+
"main": "index.js",
|
|
11
|
+
"files": [
|
|
12
|
+
"index.js",
|
|
13
|
+
"database.js",
|
|
14
|
+
"worker.js",
|
|
15
|
+
"client.js",
|
|
16
|
+
"tableOrder.js",
|
|
17
|
+
"schemaSnapshot.js",
|
|
18
|
+
"workerRegistry.js",
|
|
19
|
+
"settingsStore.js",
|
|
20
|
+
"dialect.js",
|
|
21
|
+
"driver/"
|
|
22
|
+
],
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"better-sqlite3": ">=9",
|
|
25
|
+
"pg": ">=8"
|
|
26
|
+
},
|
|
27
|
+
"peerDependenciesMeta": {
|
|
28
|
+
"better-sqlite3": {
|
|
29
|
+
"optional": true
|
|
30
|
+
},
|
|
31
|
+
"pg": {
|
|
32
|
+
"optional": true
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"better-sqlite3": "^12.10.0",
|
|
37
|
+
"pg": "^8.23.0"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"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"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/settingsStore.js
CHANGED
|
@@ -9,52 +9,78 @@
|
|
|
9
9
|
*
|
|
10
10
|
* The typed accessors (session-timeout parsing, brand-name defaults, currency tables) are app
|
|
11
11
|
* CONTENT and stay in the consuming model, which keeps this store as its base.
|
|
12
|
+
*
|
|
13
|
+
* EVERY METHOD IS ASYNC as of 0.9.0, and takes the DRIVER. There is no synchronous Postgres
|
|
14
|
+
* driver, so a store that runs on both engines has no choice. `{ getDb }` is still accepted and
|
|
15
|
+
* adopted — a consumer can upgrade this package before it rewires — but the handle it returns is
|
|
16
|
+
* wrapped rather than used, because the app owns the connection and opening a second one to the
|
|
17
|
+
* same SQLite file is how a writer ends up fighting its own lock.
|
|
18
|
+
*
|
|
19
|
+
* This store needs no lazy require for that adoption, unlike its siblings in auth/notify/backup/
|
|
20
|
+
* api-auth: it lives INSIDE db-worker, so createSqliteDriver is a local module.
|
|
12
21
|
*/
|
|
13
22
|
|
|
14
23
|
'use strict';
|
|
15
24
|
|
|
25
|
+
const { createSqliteDriver } = require('./driver/sqlite');
|
|
26
|
+
|
|
16
27
|
/**
|
|
17
|
-
* @param {
|
|
28
|
+
* @param {object} opts
|
|
29
|
+
* driver the db-worker driver (preferred since 0.9.0) — engine-agnostic
|
|
30
|
+
* getDb LEGACY: a function returning a better-sqlite3 handle, adopted into a driver here
|
|
31
|
+
* table defaults to 'settings'
|
|
18
32
|
* touchUpdatedAt: set true when the table carries an updated_at column to stamp on write.
|
|
19
33
|
*/
|
|
20
34
|
function createSettingsStore(opts = {}) {
|
|
21
|
-
|
|
22
|
-
if (
|
|
35
|
+
let driver = opts.driver || null;
|
|
36
|
+
if (!driver) {
|
|
37
|
+
if (typeof opts.getDb !== 'function') {
|
|
38
|
+
throw new Error('createSettingsStore: pass { driver } (preferred) or { getDb } (legacy)');
|
|
39
|
+
}
|
|
40
|
+
// LAZY, and it has to be. getDb() throws until the worker has opened the database, while
|
|
41
|
+
// stores are constructed at module load — so the handle is fetched on first use, not here.
|
|
42
|
+
let adopted = null;
|
|
43
|
+
driver = new Proxy({}, {
|
|
44
|
+
get(_t, prop) {
|
|
45
|
+
if (!adopted) adopted = createSqliteDriver({ adopt: opts.getDb() });
|
|
46
|
+
return adopted[prop];
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
23
51
|
const table = opts.table || 'settings';
|
|
24
52
|
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) throw new Error(`createSettingsStore: suspicious table name "${table}"`);
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
const
|
|
30
|
-
const upsert = `INSERT INTO ${table} ${insertCols} VALUES ${insertVals}
|
|
31
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value${touch}`;
|
|
53
|
+
|
|
54
|
+
// The timestamp comes from the DIALECT rather than being spelled out. SQLite has no date type
|
|
55
|
+
// and stores 'YYYY-MM-DD HH:MM:SS' UTC text; Postgres has a real timestamptz. A hand-written
|
|
56
|
+
// datetime() would be a silent wrong value on the second engine rather than a syntax error on it.
|
|
57
|
+
const now = () => driver.dialect.now();
|
|
32
58
|
|
|
33
59
|
return {
|
|
34
60
|
/** Raw value (string) or null if unset. */
|
|
35
|
-
get(key) {
|
|
36
|
-
const row =
|
|
61
|
+
async get(key) {
|
|
62
|
+
const row = await driver.get(`SELECT value FROM ${table} WHERE key = ?`, [key]);
|
|
37
63
|
return row ? row.value : null;
|
|
38
64
|
},
|
|
39
65
|
|
|
40
66
|
/** Upsert one setting (non-destructive; see the header). */
|
|
41
|
-
set(key, value) {
|
|
42
|
-
return
|
|
67
|
+
async set(key, value) {
|
|
68
|
+
return driver.run(upsertSql(), [key, value == null ? null : String(value)]);
|
|
43
69
|
},
|
|
44
70
|
|
|
45
71
|
/**
|
|
46
72
|
* Upsert several settings in ONE transaction. `undefined` values are skipped (an absent form
|
|
47
73
|
* field is not a request to clear); null is stored as null.
|
|
48
74
|
*/
|
|
49
|
-
setMultiple(keyValues) {
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
75
|
+
async setMultiple(keyValues) {
|
|
76
|
+
const sql = upsertSql();
|
|
77
|
+
await driver.transaction(async (tx) => {
|
|
78
|
+
// for...of, not forEach: forEach discards the promise, so the transaction would commit
|
|
79
|
+
// before a single row was written.
|
|
53
80
|
for (const [key, value] of Object.entries(keyValues || {})) {
|
|
54
|
-
if (value !== undefined)
|
|
81
|
+
if (value !== undefined) await tx.run(sql, [key, value == null ? null : String(value)]);
|
|
55
82
|
}
|
|
56
83
|
});
|
|
57
|
-
run();
|
|
58
84
|
},
|
|
59
85
|
|
|
60
86
|
/**
|
|
@@ -62,21 +88,35 @@ function createSettingsStore(opts = {}) {
|
|
|
62
88
|
* `_` is a LIKE wildcard, so an unescaped 'company_' would also match 'companyXname' — a
|
|
63
89
|
* latent bug in the hand-rolled version this replaces.
|
|
64
90
|
*/
|
|
65
|
-
getByPrefix(prefix) {
|
|
91
|
+
async getByPrefix(prefix) {
|
|
66
92
|
const esc = String(prefix).replace(/[\\%_]/g, (c) => '\\' + c);
|
|
67
|
-
const rows =
|
|
68
|
-
|
|
69
|
-
|
|
93
|
+
const rows = await driver.all(
|
|
94
|
+
`SELECT key, value FROM ${table} WHERE key LIKE ? ESCAPE '\\'`, [esc + '%']
|
|
95
|
+
);
|
|
70
96
|
const out = {};
|
|
71
97
|
for (const r of rows) out[r.key] = r.value;
|
|
72
98
|
return out;
|
|
73
99
|
},
|
|
74
100
|
|
|
75
101
|
/** All settings as an array of { key, value }, ordered by key. */
|
|
76
|
-
all() {
|
|
77
|
-
return
|
|
102
|
+
async all() {
|
|
103
|
+
return driver.all(`SELECT key, value FROM ${table} ORDER BY key`);
|
|
78
104
|
}
|
|
79
105
|
};
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Built per call rather than once at construction, because it reads the dialect — and with a
|
|
109
|
+
* LEGACY { getDb } the driver is a lazy proxy whose dialect is not resolvable until the first
|
|
110
|
+
* real use. Building it at construction would call getDb() before the worker opened the
|
|
111
|
+
* database, which is the failure the proxy exists to avoid.
|
|
112
|
+
*/
|
|
113
|
+
function upsertSql() {
|
|
114
|
+
const touch = opts.touchUpdatedAt ? `, updated_at = ${now()}` : '';
|
|
115
|
+
const insertCols = opts.touchUpdatedAt ? '(key, value, updated_at)' : '(key, value)';
|
|
116
|
+
const insertVals = opts.touchUpdatedAt ? `(?, ?, ${now()})` : '(?, ?)';
|
|
117
|
+
return `INSERT INTO ${table} ${insertCols} VALUES ${insertVals}
|
|
118
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value${touch}`;
|
|
119
|
+
}
|
|
80
120
|
}
|
|
81
121
|
|
|
82
122
|
module.exports = { createSettingsStore };
|