@aria-framework/db-worker 0.5.0 → 0.6.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/database.js CHANGED
@@ -15,6 +15,7 @@ const fs = require('fs');
15
15
  const path = require('path');
16
16
 
17
17
  let _db = null;
18
+ let _driver = null;
18
19
  let _logger = console;
19
20
 
20
21
  /**
@@ -40,6 +41,8 @@ function init(dbPath, opts = {}) {
40
41
 
41
42
  if (typeof opts.onOpen === 'function') opts.onOpen(_db);
42
43
 
44
+
45
+
43
46
  // Performance + safety pragmas. WAL gives concurrent readers + one writer;
44
47
  // synchronous=NORMAL is the recommended pairing (FULL fsyncs every write).
45
48
  _db.pragma('journal_mode = WAL');
@@ -47,6 +50,8 @@ function init(dbPath, opts = {}) {
47
50
  _db.pragma('foreign_keys = ON');
48
51
  _db.pragma('busy_timeout = 5000');
49
52
 
53
+ _driver = _adoptSqliteDriver(_db);
54
+
50
55
  // Migration tracking table.
51
56
  _db.exec(`
52
57
  CREATE TABLE IF NOT EXISTS migrations (
@@ -65,41 +70,108 @@ function init(dbPath, opts = {}) {
65
70
  * Each migration runs inside a transaction with its tracking-row insert.
66
71
  * @param {string} migrationsDir - Directory of .sql files (numbered names)
67
72
  */
73
+ /**
74
+ * Apply pending numbered migrations, in filename order, each in its own transaction.
75
+ *
76
+ * RETURNS A PROMISE, BUT THE SQLITE PATH HAS ALREADY FINISHED BY THE TIME IT DOES — and that
77
+ * asymmetry is deliberate, not an oversight. The first consumer has 31 TOP-LEVEL call sites in
78
+ * CommonJS scripts (`database.runMigrations();` at module scope) which physically cannot await.
79
+ * Making this unconditionally async broke every one of them with "no such table: users", because
80
+ * the schema was still being created when the next line queried it.
81
+ *
82
+ * So: on SQLite the work runs synchronously and THROWS synchronously, then hands back an
83
+ * already-resolved promise — an ignored return value is safe. On Postgres it is genuinely async
84
+ * and a caller MUST await; not awaiting there fails loudly on the first query against a missing
85
+ * relation, which is the right kind of failure.
86
+ *
87
+ * The migration FILES stay app-side and app-dialect: an app owns its schema, and a portable DDL
88
+ * layer would be a leaky translation of the one thing engines differ on most. The framework
89
+ * guarantees only the LEDGER (which files ran) and the transaction around each.
90
+ *
91
+ * @returns {Promise<{applied: number}>}
92
+ */
68
93
  function runMigrations(migrationsDir) {
69
- const db = getDb();
94
+ const d = driver();
95
+ if (!d) throw new Error('runMigrations: call init()/initDriver() first');
70
96
 
71
97
  if (!migrationsDir || !fs.existsSync(migrationsDir)) {
72
98
  _logger.warn('No migrations directory found');
73
- return;
99
+ return Promise.resolve({ applied: 0 });
74
100
  }
75
-
76
- const files = fs.readdirSync(migrationsDir)
77
- .filter(f => f.endsWith('.sql'))
78
- .sort();
79
-
80
- const applied = new Set(
81
- db.prepare('SELECT filename FROM migrations').all().map(r => r.filename)
82
- );
83
-
84
- let count = 0;
85
- for (const file of files) {
86
- if (applied.has(file)) continue;
87
-
88
- const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
89
- const runMigration = db.transaction(() => {
90
- db.exec(sql);
91
- db.prepare('INSERT INTO migrations (filename) VALUES (?)').run(file);
92
- });
93
-
94
- runMigration();
95
- count++;
96
- _logger.info(`Migration applied: ${file}`);
101
+ const files = fs.readdirSync(migrationsDir).filter((f) => f.endsWith('.sql')).sort();
102
+
103
+ // ── the synchronous path, unchanged in behaviour since 0.1.0 ──────────────────────────────
104
+ if (d.kind === 'sqlite') {
105
+ const db = d.raw;
106
+ const applied = new Set(db.prepare('SELECT filename FROM migrations').all().map((r) => r.filename));
107
+ let count = 0;
108
+ for (const file of files) {
109
+ if (applied.has(file)) continue;
110
+ const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
111
+ // One transaction per FILE, not per run: a failing migration must not roll back the ones
112
+ // that already succeeded, or a half-fixed database re-runs work it has already done.
113
+ db.transaction(() => {
114
+ db.exec(sql);
115
+ db.prepare('INSERT INTO migrations (filename) VALUES (?)').run(file);
116
+ })();
117
+ count++;
118
+ _logger.info(`Migration applied: ${file}`);
119
+ }
120
+ _logger.info(count === 0 ? 'No pending migrations' : `Applied ${count} migration(s)`);
121
+ return Promise.resolve({ applied: count });
97
122
  }
98
123
 
99
- _logger.info(count === 0 ? 'No pending migrations' : `Applied ${count} migration(s)`);
124
+ // ── the async path, for engines that have no synchronous driver ───────────────────────────
125
+ return (async () => {
126
+ const applied = new Set((await d.all('SELECT filename FROM migrations')).map((r) => r.filename));
127
+ let count = 0;
128
+ for (const file of files) {
129
+ if (applied.has(file)) continue;
130
+ const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
131
+ await d.transaction(async (tx) => {
132
+ await tx.exec(sql);
133
+ await tx.run('INSERT INTO migrations (filename) VALUES (?)', [file]);
134
+ });
135
+ count++;
136
+ _logger.info(`Migration applied: ${file}`);
137
+ }
138
+ _logger.info(count === 0 ? 'No pending migrations' : `Applied ${count} migration(s)`);
139
+ return { applied: count };
140
+ })();
141
+ }
142
+
143
+ /**
144
+ * Wrap an ALREADY-OPEN better-sqlite3 handle in the driver contract.
145
+ *
146
+ * The legacy init() path opens and configures the handle itself, so the driver must adopt it
147
+ * rather than open a second one — two connections to the same file is how you get a writer
148
+ * fighting its own lock.
149
+ */
150
+ function _adoptSqliteDriver(db) {
151
+ const { dialectFor } = require('./dialect');
152
+ const stmt = (sql) => db.prepare(sql);
153
+ const api = {
154
+ kind: 'sqlite',
155
+ dialect: dialectFor('sqlite'),
156
+ concurrency: 'serial',
157
+ raw: db,
158
+ async get(sql, params = []) { return stmt(sql).get(...params) || null; },
159
+ async all(sql, params = []) { return stmt(sql).all(...params); },
160
+ async run(sql, params = []) {
161
+ const info = stmt(sql).run(...params);
162
+ return { changes: info.changes, lastId: info.lastInsertRowid };
163
+ },
164
+ async exec(sql) { db.exec(sql); },
165
+ async transaction(fn) {
166
+ db.exec('BEGIN');
167
+ try { const out = await fn(api); db.exec('COMMIT'); return out; }
168
+ catch (e) { try { db.exec('ROLLBACK'); } catch (_) {} throw e; }
169
+ },
170
+ async close() { db.close(); }
171
+ };
172
+ return api;
100
173
  }
101
174
 
102
- /** Get the database instance. Throws if not initialized. */
103
175
  function getDb() {
104
176
  if (!_db) throw new Error('Database not initialized. Call init() first.');
105
177
  return _db;
@@ -114,4 +186,55 @@ function close() {
114
186
  }
115
187
  }
116
188
 
117
- module.exports = { init, runMigrations, getDb, close };
189
+ /**
190
+ * The DRIVER behind this database — the async, engine-agnostic contract stores are written
191
+ * against (0.6.0). `getDb()` still returns the raw better-sqlite3 handle and always will: 400+
192
+ * synchronous call sites in the first consumer depend on it, and breaking them to gain an
193
+ * abstraction they do not use would be the tail wagging the dog. The two coexist deliberately —
194
+ * app code keeps its handle, framework stores take the driver.
195
+ *
196
+ * Null until init(). The worker reads `.concurrency` off it to decide whether to serialise
197
+ * invokes, and treats a missing driver as 'serial' — the safe default.
198
+ */
199
+ function driver() {
200
+ return _driver;
201
+ }
202
+
203
+ /**
204
+ * Open a database through the DRIVER contract instead of the legacy sqlite path.
205
+ * `initDriver({ kind: 'postgres', connectionString })` is how a Postgres-native app boots;
206
+ * `kind: 'sqlite'` is identical to init() but hands back the driver as well.
207
+ */
208
+ async function ensureMigrationsTable() {
209
+ const d = driver();
210
+ const t = d.dialect;
211
+ // The LEDGER is the one table the framework owns, so it is the one DDL that must be
212
+ // dialect-aware. Everything else is the app's.
213
+ await d.exec(`
214
+ CREATE TABLE IF NOT EXISTS migrations (
215
+ id ${t.autoIncrementPk()},
216
+ filename TEXT NOT NULL UNIQUE,
217
+ applied_at TEXT NOT NULL DEFAULT (${t.now()})
218
+ )`);
219
+ }
220
+
221
+ async function initDriver(opts = {}) {
222
+ const kind = opts.kind || 'sqlite';
223
+ if (kind === 'sqlite') {
224
+ const { createSqliteDriver } = require('./driver/sqlite');
225
+ _driver = createSqliteDriver(opts);
226
+ _db = _driver.raw; // keep getDb() working for app code
227
+ } else if (kind === 'postgres') {
228
+ const { createPostgresDriver } = require('./driver/postgres');
229
+ _driver = createPostgresDriver(opts);
230
+ _db = null; // there IS no synchronous handle; getDb() must throw
231
+ } else {
232
+ throw new Error(`initDriver: unknown kind '${kind}'`);
233
+ }
234
+ await ensureMigrationsTable();
235
+ _logger = opts.logger || _logger;
236
+ _logger.info(`Database opened (${kind})`);
237
+ return _driver;
238
+ }
239
+
240
+ module.exports = { init, initDriver, runMigrations, getDb, driver, close };
package/dialect.js ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The SQL differences between SQLite and PostgreSQL, NAMED rather than scattered.
3
+ *
4
+ * A store writes `d.now()` instead of `datetime('now')`, so the divergence lives in one
5
+ * reviewable file instead of 159 call sites. Everything NOT in here is deliberately absent
6
+ * because both engines already agree on it — and that list is longer than it looks:
7
+ *
8
+ * - `ON CONFLICT (...) DO UPDATE/NOTHING` is standard in both (SQLite since 3.24; the
9
+ * framework requires far newer). So there is no `insertOrIgnore()` here — stores write the
10
+ * portable form and `INSERT OR IGNORE` never appears.
11
+ * - LIMIT/OFFSET, CTEs, window functions, `COUNT(*) FILTER (WHERE …)` — all shared.
12
+ * - Placeholders are NOT a dialect concern: stores always write `?` and the driver rewrites
13
+ * to `$1…$n` for pg (see driver/postgres.js, which scans string literals properly rather
14
+ * than blindly replacing).
15
+ *
16
+ * TIMESTAMPS ARE THE ONE MODELLING DECISION, not just a syntax swap. SQLite has no date type
17
+ * and this framework stores `YYYY-MM-DD HH:MM:SS` UTC text; Postgres has real `timestamptz`.
18
+ * `now()` therefore emits each engine's native value and a store must COMPARE using the same
19
+ * helpers (`now()`, `nowMinusDays()`) rather than hand-built strings — mixing a literal
20
+ * '2026-01-01' comparison with a timestamptz column is the silent-wrong-answer this prevents.
21
+ */
22
+
23
+ 'use strict';
24
+
25
+ /** Quote an identifier. Both engines accept double quotes; this exists so callers never hand-roll. */
26
+ const ident = (name) => `"${String(name).replace(/"/g, '""')}"`;
27
+
28
+ const sqlite = {
29
+ kind: 'sqlite',
30
+ ident,
31
+ /** Current UTC timestamp, in this engine's native form. */
32
+ now: () => "datetime('now')",
33
+ /** N whole days before now — used by retention cuts. */
34
+ nowMinusDays: (n) => `datetime('now', '-${Number(n)} days')`,
35
+ /** Native timestamp type. SQLite has none, so this is the same text value. */
36
+ nowTz: () => "datetime('now')",
37
+ /** Read a JSON path out of a column: jsonPath('detail', '$.model'). */
38
+ jsonPath: (col, path) => `json_extract(${col}, '${String(path).replace(/'/g, "''")}')`,
39
+ /** Case-insensitive LIKE. SQLite's LIKE is already case-insensitive for ASCII. */
40
+ ilike: () => 'LIKE',
41
+ /** Suffix that makes run() report a new row's id. SQLite reports it out of band. */
42
+ returning: () => '',
43
+ /** DDL fragment for an auto-incrementing primary key (only secure-keystore needs this). */
44
+ autoIncrementPk: () => 'INTEGER PRIMARY KEY AUTOINCREMENT',
45
+ /** Portable-ish text column. */
46
+ textType: () => 'TEXT'
47
+ };
48
+
49
+ const postgres = {
50
+ kind: 'postgres',
51
+ ident,
52
+ // TEXT, not timestamptz — and the live contract suite is why. Every framework store inherited
53
+ // TEXT timestamps from SQLite (`YYYY-MM-DD HH:MM:SS` UTC), and `NOW()` returns timestamptz,
54
+ // so `created_at < NOW()` failed outright with "operator does not exist: text < timestamp
55
+ // with time zone". Emitting the same text shape on both engines keeps one store SQL correct
56
+ // for both; an app wanting a real timestamptz column in its OWN tables uses nowTz().
57
+ now: () => "to_char(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')",
58
+ nowMinusDays: (n) => `to_char((NOW() - INTERVAL '${Number(n)} days') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
59
+ /** Native timestamptz, for an app that declares real timestamp columns. */
60
+ nowTz: () => 'NOW()',
61
+ // The ::jsonb cast is load-bearing: `->>` is not defined on TEXT, and the framework's JSON
62
+ // columns are TEXT by SQLite heritage ("operator does not exist: text ->> unknown"). On a
63
+ // column already declared jsonb the cast is a no-op, so an app SHOULD declare jsonb for
64
+ // indexability without this needing to know which it got.
65
+ jsonPath: (col, path) => {
66
+ const key = String(path).replace(/^\$\./, '');
67
+ if (key.includes('.') || key.includes('[')) {
68
+ const parts = key.replace(/\[\]$/, '').split('.').map((p) => p.replace(/'/g, "''"));
69
+ return `((${col})::jsonb #>> '{${parts.join(',')}}')`;
70
+ }
71
+ return `((${col})::jsonb ->> '${key.replace(/'/g, "''")}')`;
72
+ },
73
+ ilike: () => 'ILIKE',
74
+ returning: (col = 'id') => ` RETURNING ${ident(col)}`,
75
+ autoIncrementPk: () => 'BIGSERIAL PRIMARY KEY',
76
+ textType: () => 'TEXT'
77
+ };
78
+
79
+ function dialectFor(kind) {
80
+ if (kind === 'sqlite') return sqlite;
81
+ if (kind === 'postgres') return postgres;
82
+ throw new Error(`dialectFor: unknown driver kind '${kind}' (expected 'sqlite' or 'postgres')`);
83
+ }
84
+
85
+ module.exports = { dialectFor, sqlite, postgres };
@@ -0,0 +1,163 @@
1
+ /**
2
+ * The PostgreSQL driver — `pg` behind the same async driver contract as SQLite.
3
+ *
4
+ * CONCURRENCY IS 'pool', which is the point of using it. Where the SQLite driver serialises
5
+ * (single writer, so nothing is lost by it), this one runs invokes concurrently against a
6
+ * connection pool — and `transaction()` takes a DEDICATED client for its whole duration, so
7
+ * concurrent work can never interleave inside somebody else's BEGIN.
8
+ *
9
+ * PLACEHOLDERS. Stores write `?` because that is what the SQLite half has always used and
10
+ * rewriting 400 call sites to `$1` would be the tail wagging the dog. Converting them is NOT a
11
+ * blind replace: a `?` inside a string literal ('what?') must survive untouched, so the
12
+ * rewriter scans the statement and tracks quote state, including doubled '' escapes and
13
+ * dollar-quoted bodies. Getting that wrong corrupts data silently rather than erroring, which
14
+ * is why it has its own tests.
15
+ *
16
+ * `pg` is an OPTIONAL PEER — a SQLite-only consumer (Support101) must never install it.
17
+ */
18
+
19
+ 'use strict';
20
+
21
+ const { dialectFor } = require('../dialect');
22
+
23
+ /**
24
+ * Rewrite `?` placeholders to `$1..$n`, leaving any `?` inside a literal alone.
25
+ *
26
+ * Handles: single-quoted strings with '' escapes, double-quoted identifiers, line comments,
27
+ * block comments, and $tag$ dollar-quoted bodies. Anything else is ordinary SQL.
28
+ */
29
+ function toDollarParams(sql) {
30
+ let out = '';
31
+ let n = 0;
32
+ let i = 0;
33
+ while (i < sql.length) {
34
+ const c = sql[i];
35
+
36
+ if (c === "'") { // string literal, '' is an escaped quote
37
+ let j = i + 1;
38
+ while (j < sql.length) {
39
+ if (sql[j] === "'" && sql[j + 1] === "'") { j += 2; continue; }
40
+ if (sql[j] === "'") break;
41
+ j++;
42
+ }
43
+ out += sql.slice(i, j + 1); i = j + 1; continue;
44
+ }
45
+ if (c === '"') { // quoted identifier
46
+ const j = sql.indexOf('"', i + 1);
47
+ const end = j === -1 ? sql.length - 1 : j;
48
+ out += sql.slice(i, end + 1); i = end + 1; continue;
49
+ }
50
+ if (c === '-' && sql[i + 1] === '-') { // line comment
51
+ const j = sql.indexOf('\n', i);
52
+ const end = j === -1 ? sql.length : j;
53
+ out += sql.slice(i, end); i = end; continue;
54
+ }
55
+ if (c === '/' && sql[i + 1] === '*') { // block comment
56
+ const j = sql.indexOf('*/', i + 2);
57
+ const end = j === -1 ? sql.length : j + 2;
58
+ out += sql.slice(i, end); i = end; continue;
59
+ }
60
+ if (c === '$') { // dollar-quoted body: $tag$ … $tag$
61
+ const m = /^\$[A-Za-z_0-9]*\$/.exec(sql.slice(i));
62
+ if (m) {
63
+ const tag = m[0];
64
+ const j = sql.indexOf(tag, i + tag.length);
65
+ const end = j === -1 ? sql.length : j + tag.length;
66
+ out += sql.slice(i, end); i = end; continue;
67
+ }
68
+ }
69
+ if (c === '?') { out += '$' + (++n); i++; continue; }
70
+
71
+ out += c; i++;
72
+ }
73
+ return out;
74
+ }
75
+
76
+ /**
77
+ * @param {object} opts
78
+ * connectionString postgres://user:pass@host:port/db (required unless host/user/… given)
79
+ * pool extra node-postgres Pool options (max, idleTimeoutMillis, ssl…)
80
+ * logger needs .info/.warn/.error
81
+ */
82
+ function createPostgresDriver(opts = {}) {
83
+ let pg;
84
+ try {
85
+ pg = require('pg');
86
+ } catch (e) {
87
+ throw new Error(
88
+ 'createPostgresDriver: `pg` is not installed. It is an optional peer — add it to the ' +
89
+ 'consuming app, or use the sqlite driver. (' + e.message + ')'
90
+ );
91
+ }
92
+ if (!opts.connectionString && !opts.host) {
93
+ throw new Error('createPostgresDriver({ connectionString }): a connection string (or host/user/database) is required');
94
+ }
95
+
96
+ const pool = new pg.Pool({
97
+ connectionString: opts.connectionString,
98
+ ...(opts.pool || {})
99
+ });
100
+
101
+ /** Build the contract over either the pool or one checked-out client (inside a transaction). */
102
+ const apiOver = (exec, extra = {}) => ({
103
+ kind: 'postgres',
104
+ dialect: dialectFor('postgres'),
105
+ concurrency: 'pool',
106
+
107
+ async get(sql, params = []) {
108
+ const r = await exec(toDollarParams(sql), params);
109
+ return r.rows[0] || null;
110
+ },
111
+ async all(sql, params = []) {
112
+ const r = await exec(toDollarParams(sql), params);
113
+ return r.rows;
114
+ },
115
+ /**
116
+ * `lastId` comes from a RETURNING clause. A store that needs the new id appends
117
+ * `d.returning('id')`, which is empty on SQLite (where it arrives out of band) and
118
+ * ` RETURNING "id"` here — so the store's SQL stays one string for both engines.
119
+ */
120
+ async run(sql, params = []) {
121
+ const r = await exec(toDollarParams(sql), params);
122
+ const row = r.rows && r.rows[0];
123
+ const lastId = row ? (row.id !== undefined ? row.id : Object.values(row)[0]) : undefined;
124
+ return { changes: r.rowCount, lastId };
125
+ },
126
+ async exec(sql) {
127
+ await exec(sql); // DDL: never parameterised, so no rewrite
128
+ },
129
+ ...extra
130
+ });
131
+
132
+ const poolApi = apiOver((sql, params) => pool.query(sql, params), {
133
+ /**
134
+ * A dedicated client for the whole transaction. Without this, a pooled query from another
135
+ * concurrent invoke could land between the BEGIN and the COMMIT — the same interleaving
136
+ * hazard the SQLite driver avoids by serialising, solved here the way Postgres intends.
137
+ */
138
+ async transaction(fn) {
139
+ const client = await pool.connect();
140
+ const txApi = apiOver((sql, params) => client.query(sql, params), {
141
+ // Nested transaction() reuses the same client rather than deadlocking on a second one.
142
+ transaction: (inner) => inner(txApi)
143
+ });
144
+ try {
145
+ await client.query('BEGIN');
146
+ const out = await fn(txApi);
147
+ await client.query('COMMIT');
148
+ return out;
149
+ } catch (e) {
150
+ try { await client.query('ROLLBACK'); } catch (_) { /* the original error is what matters */ }
151
+ throw e;
152
+ } finally {
153
+ client.release();
154
+ }
155
+ },
156
+ async close() { await pool.end(); },
157
+ raw: pool
158
+ });
159
+
160
+ return poolApi;
161
+ }
162
+
163
+ module.exports = { createPostgresDriver, toDollarParams };
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The SQLite driver — better-sqlite3 behind the async driver contract.
3
+ *
4
+ * Synchronous underneath, Promise-returning on the surface. That is not a wrapper for its own
5
+ * sake: it lets every store be written ONCE, async, against one contract, and the SQLite path
6
+ * pays only a microtask for it.
7
+ *
8
+ * CONCURRENCY IS 'serial', AND THAT IS A CORRECTNESS REQUIREMENT, not a performance choice.
9
+ * Before the stores went async, a model method ran to completion before the worker handled the
10
+ * next message — transactions were atomic by construction. The moment a store awaits, a second
11
+ * queued invoke can interleave BETWEEN statements, and if either is mid-transaction the
12
+ * atomicity is gone. The worker honours `concurrency` by processing one invoke at a time for
13
+ * this driver. Nothing is lost: SQLite is single-writer regardless.
14
+ *
15
+ * better-sqlite3 stays an OPTIONAL PEER — a Postgres-only consumer must not build a native
16
+ * module it never opens.
17
+ */
18
+
19
+ 'use strict';
20
+
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+ const { dialectFor } = require('../dialect');
24
+
25
+ /**
26
+ * @param {object} opts
27
+ * path database file (required)
28
+ * onOpen (db) => void, BEFORE pragmas — the SQLCipher `pragma key` hook
29
+ * logger needs .info/.warn/.error
30
+ * pragmas override/extend the defaults
31
+ */
32
+ function createSqliteDriver(opts = {}) {
33
+ if (!opts.path) throw new Error("createSqliteDriver({ path }): the database file path is required");
34
+ let Database;
35
+ try {
36
+ Database = require('better-sqlite3');
37
+ } catch (e) {
38
+ throw new Error(
39
+ 'createSqliteDriver: better-sqlite3 is not installed. It is an optional peer — add it to ' +
40
+ 'the consuming app, or use the postgres driver. (' + e.message + ')'
41
+ );
42
+ }
43
+
44
+ const dir = path.dirname(opts.path);
45
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
46
+
47
+ const db = new Database(opts.path);
48
+ // BEFORE the pragmas: an encrypted database must be keyed before it will answer anything.
49
+ if (typeof opts.onOpen === 'function') opts.onOpen(db);
50
+
51
+ const pragmas = {
52
+ journal_mode: 'WAL', // concurrent readers + one writer
53
+ synchronous: 'NORMAL', // the recommended pairing with WAL (FULL fsyncs every write)
54
+ foreign_keys: 'ON',
55
+ busy_timeout: 5000,
56
+ ...(opts.pragmas || {})
57
+ };
58
+ for (const [k, v] of Object.entries(pragmas)) db.pragma(`${k} = ${v}`);
59
+
60
+ const stmt = (sql) => db.prepare(sql);
61
+
62
+ const api = {
63
+ kind: 'sqlite',
64
+ dialect: dialectFor('sqlite'),
65
+ concurrency: 'serial',
66
+ /** The raw handle, for the few things that genuinely need it (backup's VACUUM INTO). */
67
+ raw: db,
68
+
69
+ async get(sql, params = []) {
70
+ return stmt(sql).get(...params) || null;
71
+ },
72
+ async all(sql, params = []) {
73
+ return stmt(sql).all(...params);
74
+ },
75
+ async run(sql, params = []) {
76
+ const info = stmt(sql).run(...params);
77
+ return { changes: info.changes, lastId: info.lastInsertRowid };
78
+ },
79
+ /** Multi-statement DDL. Never parameterised — migrations only. */
80
+ async exec(sql) {
81
+ db.exec(sql);
82
+ },
83
+
84
+ /**
85
+ * Transactions are run with explicit BEGIN/COMMIT rather than better-sqlite3's
86
+ * `db.transaction(fn)`, because that helper REFUSES an async callback — and every callback
87
+ * here is async by contract. Safe only because this driver declares 'serial': nothing else
88
+ * can issue a statement between the BEGIN and the COMMIT.
89
+ */
90
+ async transaction(fn) {
91
+ db.exec('BEGIN');
92
+ try {
93
+ const out = await fn(api);
94
+ db.exec('COMMIT');
95
+ return out;
96
+ } catch (e) {
97
+ try { db.exec('ROLLBACK'); } catch (_) { /* the failure that matters is the original */ }
98
+ throw e;
99
+ }
100
+ },
101
+
102
+ async close() {
103
+ db.close();
104
+ }
105
+ };
106
+ return api;
107
+ }
108
+
109
+ module.exports = { createSqliteDriver };
package/index.js CHANGED
@@ -9,7 +9,18 @@
9
9
  * runMigrations(dir) + getDb() + close(). Singleton per thread.
10
10
  */
11
11
 
12
+ // 0.6.0 — MULTI-ENGINE. The driver contract (get/all/run/exec/transaction + dialect +
13
+ // concurrency) lets a store be written once and run on either engine, selected per APP. SQLite
14
+ // stays the default and Support101 never moves; app 3 boots with kind:'postgres'. `pg` and
15
+ // better-sqlite3 are both OPTIONAL peers — neither consumer installs the other's driver.
16
+ const { createSqliteDriver } = require('./driver/sqlite');
17
+ const { createPostgresDriver } = require('./driver/postgres');
18
+ const { dialectFor } = require('./dialect');
19
+
12
20
  module.exports = {
21
+ createSqliteDriver,
22
+ createPostgresDriver,
23
+ dialectFor,
13
24
  DbClient: require('./client').DbClient,
14
25
  runWorker: require('./worker').runWorker,
15
26
  database: require('./database'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.5.0",
3
+ "version": "0.6.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,
@@ -16,15 +16,23 @@
16
16
  "tableOrder.js",
17
17
  "schemaSnapshot.js",
18
18
  "workerRegistry.js",
19
- "settingsStore.js"
19
+ "settingsStore.js",
20
+ "dialect.js",
21
+ "driver/"
20
22
  ],
21
23
  "peerDependencies": {
22
- "better-sqlite3": ">=9"
24
+ "better-sqlite3": ">=9",
25
+ "pg": ">=8"
26
+ },
27
+ "peerDependenciesMeta": {
28
+ "better-sqlite3": { "optional": true },
29
+ "pg": { "optional": true }
23
30
  },
24
31
  "devDependencies": {
25
- "better-sqlite3": "^12.10.0"
32
+ "better-sqlite3": "^12.10.0",
33
+ "pg": "^8.23.0"
26
34
  },
27
35
  "scripts": {
28
- "test": "node test/smoke.js && node test/tier2.js"
36
+ "test": "node test/driverContract.js && node test/migrations.js && node test/smoke.js && node test/tier2.js"
29
37
  }
30
38
  }
package/worker.js CHANGED
@@ -24,17 +24,53 @@ const { performance } = require('perf_hooks');
24
24
  * @param {Object} opts
25
25
  * @param {(workerData: any) => Object} opts.init - App boot; returns the model registry
26
26
  */
27
- function runWorker({ init }) {
27
+ async function runWorker({ init }) {
28
28
  if (typeof init !== 'function') {
29
29
  throw new Error('runWorker({ init }): init must be a function (workerData) => modelRegistry');
30
30
  }
31
31
 
32
32
  try {
33
- const models = init(workerData) || {};
33
+ // AWAITED since 0.6.0. An app's init opens the database and runs migrations, and on
34
+ // Postgres both of those are async — an un-awaited init would hand back a Promise as the
35
+ // model registry and serve queries against an unmigrated database. `await` on a synchronous
36
+ // init returns the same object it always did, so the SQLite path is unchanged.
37
+ const models = (await init(workerData)) || {};
34
38
 
35
39
  parentPort.postMessage({ type: 'ready' });
36
40
 
41
+ // SERIALISATION — a correctness requirement, not a throttle.
42
+ //
43
+ // Before the stores went async, a model method ran to completion before the next message was
44
+ // handled, so a transaction could not be interrupted. The moment a store awaits, a second
45
+ // queued invoke can interleave BETWEEN a BEGIN and its COMMIT and break atomicity. Drivers
46
+ // therefore DECLARE their concurrency: 'serial' chains every invoke behind the last (SQLite
47
+ // is single-writer anyway, so nothing is lost), 'pool' lets them run concurrently because a
48
+ // Postgres transaction holds its own dedicated client.
49
+ //
50
+ // Default 'serial': a driver that forgets to declare gets the SAFE behaviour, not the fast one.
51
+ let tail = Promise.resolve();
52
+ const serial = () => {
53
+ // Required lazily: the app's init() opens the database, so the driver does not exist when
54
+ // this module loads. Reading it per message also means a driver swapped at runtime (tests
55
+ // do this) is honoured rather than cached wrong.
56
+ try {
57
+ const d = require('./database').driver();
58
+ return !d || d.concurrency !== 'pool';
59
+ } catch (_) {
60
+ return true; // no driver, no information — take the SAFE branch
61
+ }
62
+ };
63
+
37
64
  parentPort.on('message', async (msg) => {
65
+ if (serial()) {
66
+ const mine = tail.then(() => handle(msg));
67
+ tail = mine.catch(() => {}); // one failed invoke must not stall the queue behind it
68
+ return mine;
69
+ }
70
+ return handle(msg);
71
+ });
72
+
73
+ async function handle(msg) {
38
74
  const { id, model, method, args } = msg;
39
75
  // Worker-side execution time, shipped back so the client's slow-call log
40
76
  // attributes slowness to the query that WAS slow, not to calls that were
@@ -70,7 +106,7 @@ function runWorker({ init }) {
70
106
  }
71
107
  parentPort.postMessage({ id, error: payload, execMs: Math.round(performance.now() - t0) });
72
108
  }
73
- });
109
+ }
74
110
  } catch (err) {
75
111
  parentPort.postMessage({ type: 'init-error', error: err.message });
76
112
  }