@aria-framework/db-worker 0.5.0 → 0.6.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/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,82 @@ 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
+ /** Adopt the handle init() just opened — the driver must not open a second connection. */
144
+ function _adoptSqliteDriver(db) {
145
+ const { createSqliteDriver } = require('./driver/sqlite');
146
+ return createSqliteDriver({ adopt: db });
100
147
  }
101
148
 
102
- /** Get the database instance. Throws if not initialized. */
103
149
  function getDb() {
104
150
  if (!_db) throw new Error('Database not initialized. Call init() first.');
105
151
  return _db;
@@ -114,4 +160,55 @@ function close() {
114
160
  }
115
161
  }
116
162
 
117
- module.exports = { init, runMigrations, getDb, close };
163
+ /**
164
+ * The DRIVER behind this database — the async, engine-agnostic contract stores are written
165
+ * against (0.6.0). `getDb()` still returns the raw better-sqlite3 handle and always will: 400+
166
+ * synchronous call sites in the first consumer depend on it, and breaking them to gain an
167
+ * abstraction they do not use would be the tail wagging the dog. The two coexist deliberately —
168
+ * app code keeps its handle, framework stores take the driver.
169
+ *
170
+ * Null until init(). The worker reads `.concurrency` off it to decide whether to serialise
171
+ * invokes, and treats a missing driver as 'serial' — the safe default.
172
+ */
173
+ function driver() {
174
+ return _driver;
175
+ }
176
+
177
+ /**
178
+ * Open a database through the DRIVER contract instead of the legacy sqlite path.
179
+ * `initDriver({ kind: 'postgres', connectionString })` is how a Postgres-native app boots;
180
+ * `kind: 'sqlite'` is identical to init() but hands back the driver as well.
181
+ */
182
+ async function ensureMigrationsTable() {
183
+ const d = driver();
184
+ const t = d.dialect;
185
+ // The LEDGER is the one table the framework owns, so it is the one DDL that must be
186
+ // dialect-aware. Everything else is the app's.
187
+ await d.exec(`
188
+ CREATE TABLE IF NOT EXISTS migrations (
189
+ id ${t.autoIncrementPk()},
190
+ filename TEXT NOT NULL UNIQUE,
191
+ applied_at TEXT NOT NULL DEFAULT (${t.now()})
192
+ )`);
193
+ }
194
+
195
+ async function initDriver(opts = {}) {
196
+ const kind = opts.kind || 'sqlite';
197
+ if (kind === 'sqlite') {
198
+ const { createSqliteDriver } = require('./driver/sqlite');
199
+ _driver = createSqliteDriver(opts);
200
+ _db = _driver.raw; // keep getDb() working for app code
201
+ } else if (kind === 'postgres') {
202
+ const { createPostgresDriver } = require('./driver/postgres');
203
+ _driver = createPostgresDriver(opts);
204
+ _db = null; // there IS no synchronous handle; getDb() must throw
205
+ } else {
206
+ throw new Error(`initDriver: unknown kind '${kind}'`);
207
+ }
208
+ await ensureMigrationsTable();
209
+ _logger = opts.logger || _logger;
210
+ _logger.info(`Database opened (${kind})`);
211
+ return _driver;
212
+ }
213
+
214
+ 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,75 @@
1
+ /**
2
+ * Named parameters, normalised to positional before either driver sees them.
3
+ *
4
+ * better-sqlite3 supports `@name` natively; `pg` supports only `$1..$n`. Rather than make every
5
+ * store choose a style per engine — or worse, rewrite caller-supplied WHERE fragments, which in
6
+ * this framework are built by the APP and passed in — the contract accepts both and converts
7
+ * here, once, for both drivers. A store's SQL is then identical on either engine.
8
+ *
9
+ * THE SCAN IS THE SAME ONE the placeholder rewriter uses, and for the same reason: an `@name`
10
+ * inside a string literal ('user@example.com') must not be treated as a parameter. Getting that
11
+ * wrong binds the wrong value silently rather than erroring, so it is tested directly.
12
+ */
13
+
14
+ 'use strict';
15
+
16
+ const NAME_CHAR = /[A-Za-z0-9_]/;
17
+
18
+ /**
19
+ * Convert `@name` placeholders to `?`, returning values in positional order.
20
+ *
21
+ * @param {string} sql
22
+ * @param {object|Array} params an object binds by name; an array is already positional
23
+ * @returns {{sql: string, values: Array}}
24
+ */
25
+ function bindNamed(sql, params) {
26
+ if (Array.isArray(params) || params == null) return { sql, values: params || [] };
27
+
28
+ const values = [];
29
+ let out = '';
30
+ let i = 0;
31
+ while (i < sql.length) {
32
+ const c = sql[i];
33
+
34
+ if (c === "'") { // string literal, '' escapes
35
+ let j = i + 1;
36
+ while (j < sql.length) {
37
+ if (sql[j] === "'" && sql[j + 1] === "'") { j += 2; continue; }
38
+ if (sql[j] === "'") break;
39
+ j++;
40
+ }
41
+ out += sql.slice(i, j + 1); i = j + 1; continue;
42
+ }
43
+ if (c === '"') { // quoted identifier
44
+ const j = sql.indexOf('"', i + 1);
45
+ const end = j === -1 ? sql.length - 1 : j;
46
+ out += sql.slice(i, end + 1); i = end + 1; continue;
47
+ }
48
+ if (c === '-' && sql[i + 1] === '-') { // line comment
49
+ const j = sql.indexOf('\n', i);
50
+ const end = j === -1 ? sql.length : j;
51
+ out += sql.slice(i, end); i = end; continue;
52
+ }
53
+ if (c === '/' && sql[i + 1] === '*') { // block comment
54
+ const j = sql.indexOf('*/', i + 2);
55
+ const end = j === -1 ? sql.length : j + 2;
56
+ out += sql.slice(i, end); i = end; continue;
57
+ }
58
+ if (c === '@' && NAME_CHAR.test(sql[i + 1] || '')) {
59
+ let j = i + 1;
60
+ while (j < sql.length && NAME_CHAR.test(sql[j])) j++;
61
+ const name = sql.slice(i + 1, j);
62
+ if (!(name in params)) {
63
+ throw new Error(`bindNamed: SQL references @${name} but no such key was supplied`);
64
+ }
65
+ values.push(params[name]);
66
+ out += '?';
67
+ i = j;
68
+ continue;
69
+ }
70
+ out += c; i++;
71
+ }
72
+ return { sql: out, values };
73
+ }
74
+
75
+ module.exports = { bindNamed };
@@ -0,0 +1,181 @@
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
+ const { bindNamed } = require('./params');
23
+
24
+ /**
25
+ * Rewrite `?` placeholders to `$1..$n`, leaving any `?` inside a literal alone.
26
+ *
27
+ * Handles: single-quoted strings with '' escapes, double-quoted identifiers, line comments,
28
+ * block comments, and $tag$ dollar-quoted bodies. Anything else is ordinary SQL.
29
+ */
30
+ function toDollarParams(sql) {
31
+ let out = '';
32
+ let n = 0;
33
+ let i = 0;
34
+ while (i < sql.length) {
35
+ const c = sql[i];
36
+
37
+ if (c === "'") { // string literal, '' is an escaped quote
38
+ let j = i + 1;
39
+ while (j < sql.length) {
40
+ if (sql[j] === "'" && sql[j + 1] === "'") { j += 2; continue; }
41
+ if (sql[j] === "'") break;
42
+ j++;
43
+ }
44
+ out += sql.slice(i, j + 1); i = j + 1; continue;
45
+ }
46
+ if (c === '"') { // quoted identifier
47
+ const j = sql.indexOf('"', i + 1);
48
+ const end = j === -1 ? sql.length - 1 : j;
49
+ out += sql.slice(i, end + 1); i = end + 1; continue;
50
+ }
51
+ if (c === '-' && sql[i + 1] === '-') { // line comment
52
+ const j = sql.indexOf('\n', i);
53
+ const end = j === -1 ? sql.length : j;
54
+ out += sql.slice(i, end); i = end; continue;
55
+ }
56
+ if (c === '/' && sql[i + 1] === '*') { // block comment
57
+ const j = sql.indexOf('*/', i + 2);
58
+ const end = j === -1 ? sql.length : j + 2;
59
+ out += sql.slice(i, end); i = end; continue;
60
+ }
61
+ if (c === '$') { // dollar-quoted body: $tag$ … $tag$
62
+ const m = /^\$[A-Za-z_0-9]*\$/.exec(sql.slice(i));
63
+ if (m) {
64
+ const tag = m[0];
65
+ const j = sql.indexOf(tag, i + tag.length);
66
+ const end = j === -1 ? sql.length : j + tag.length;
67
+ out += sql.slice(i, end); i = end; continue;
68
+ }
69
+ }
70
+ if (c === '?') { out += '$' + (++n); i++; continue; }
71
+
72
+ out += c; i++;
73
+ }
74
+ return out;
75
+ }
76
+
77
+ /**
78
+ * @param {object} opts
79
+ * connectionString postgres://user:pass@host:port/db (required unless host/user/… given)
80
+ * pool extra node-postgres Pool options (max, idleTimeoutMillis, ssl…)
81
+ * logger needs .info/.warn/.error
82
+ */
83
+ function createPostgresDriver(opts = {}) {
84
+ let pg;
85
+ try {
86
+ pg = require('pg');
87
+ } catch (e) {
88
+ throw new Error(
89
+ 'createPostgresDriver: `pg` is not installed. It is an optional peer — add it to the ' +
90
+ 'consuming app, or use the sqlite driver. (' + e.message + ')'
91
+ );
92
+ }
93
+ if (!opts.connectionString && !opts.host) {
94
+ throw new Error('createPostgresDriver({ connectionString }): a connection string (or host/user/database) is required');
95
+ }
96
+
97
+ const pool = new pg.Pool({
98
+ connectionString: opts.connectionString,
99
+ ...(opts.pool || {})
100
+ });
101
+
102
+ /** Build the contract over either the pool or one checked-out client (inside a transaction). */
103
+ const apiOver = (exec, extra = {}) => ({
104
+ kind: 'postgres',
105
+ dialect: dialectFor('postgres'),
106
+ concurrency: 'pool',
107
+
108
+ async get(sql, params = []) {
109
+ const b = bindNamed(sql, params);
110
+ const r = await exec(toDollarParams(b.sql), b.values);
111
+ return r.rows[0] || null;
112
+ },
113
+ async all(sql, params = []) {
114
+ const b = bindNamed(sql, params);
115
+ const r = await exec(toDollarParams(b.sql), b.values);
116
+ return r.rows;
117
+ },
118
+ /**
119
+ * `lastId` comes from a RETURNING clause. A store that needs the new id appends
120
+ * `d.returning('id')`, which is empty on SQLite (where it arrives out of band) and
121
+ * ` RETURNING "id"` here — so the store's SQL stays one string for both engines.
122
+ */
123
+ async run(sql, params = []) {
124
+ const b = bindNamed(sql, params);
125
+ const r = await exec(toDollarParams(b.sql), b.values);
126
+ const row = r.rows && r.rows[0];
127
+ const lastId = row ? (row.id !== undefined ? row.id : Object.values(row)[0]) : undefined;
128
+ return { changes: r.rowCount, lastId };
129
+ },
130
+ async exec(sql) {
131
+ await exec(sql); // DDL: never parameterised, so no rewrite
132
+ },
133
+ ...extra
134
+ });
135
+
136
+ const poolApi = apiOver((sql, params) => pool.query(sql, params), {
137
+ /**
138
+ * A dedicated client for the whole transaction. Without this, a pooled query from another
139
+ * concurrent invoke could land between the BEGIN and the COMMIT — the same interleaving
140
+ * hazard the SQLite driver avoids by serialising, solved here the way Postgres intends.
141
+ */
142
+ async transaction(fn) {
143
+ const client = await pool.connect();
144
+ let depth = 0;
145
+ const txApi = apiOver((sql, params) => client.query(sql, params), {
146
+ // Nested transaction() reuses the same CLIENT (a second pooled connection would
147
+ // deadlock against this one's locks) and brackets the body in a SAVEPOINT, so an inner
148
+ // failure rolls back only its own work rather than discarding the outer transaction.
149
+ async transaction(inner) {
150
+ const sp = `aria_sp_${depth++}`;
151
+ await client.query(`SAVEPOINT ${sp}`);
152
+ try {
153
+ const out = await inner(txApi);
154
+ await client.query(`RELEASE SAVEPOINT ${sp}`);
155
+ return out;
156
+ } catch (e) {
157
+ try { await client.query(`ROLLBACK TO SAVEPOINT ${sp}`); } catch (_) { /* noop */ }
158
+ throw e;
159
+ } finally { depth--; }
160
+ }
161
+ });
162
+ try {
163
+ await client.query('BEGIN');
164
+ const out = await fn(txApi);
165
+ await client.query('COMMIT');
166
+ return out;
167
+ } catch (e) {
168
+ try { await client.query('ROLLBACK'); } catch (_) { /* the original error is what matters */ }
169
+ throw e;
170
+ } finally {
171
+ client.release();
172
+ }
173
+ },
174
+ async close() { await pool.end(); },
175
+ raw: pool
176
+ });
177
+
178
+ return poolApi;
179
+ }
180
+
181
+ module.exports = { createPostgresDriver, toDollarParams };
@@ -0,0 +1,134 @@
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
+ const { bindNamed } = require('./params');
25
+
26
+ /**
27
+ * @param {object} opts
28
+ * path database file (required)
29
+ * onOpen (db) => void, BEFORE pragmas — the SQLCipher `pragma key` hook
30
+ * logger needs .info/.warn/.error
31
+ * pragmas override/extend the defaults
32
+ */
33
+ function createSqliteDriver(opts = {}) {
34
+ // ADOPT an already-open handle rather than opening a second one. Two connections to the same
35
+ // file is how a writer ends up fighting its own lock, so a consumer that already owns a handle
36
+ // (the legacy init() path, or a store handed a getDb) passes it here instead.
37
+ if (opts.adopt) return wrap(opts.adopt);
38
+
39
+ if (!opts.path) throw new Error("createSqliteDriver({ path }) or ({ adopt }): a database file path or an open handle is required");
40
+ let Database;
41
+ try {
42
+ Database = require('better-sqlite3');
43
+ } catch (e) {
44
+ throw new Error(
45
+ 'createSqliteDriver: better-sqlite3 is not installed. It is an optional peer — add it to ' +
46
+ 'the consuming app, or use the postgres driver. (' + e.message + ')'
47
+ );
48
+ }
49
+
50
+ const dir = path.dirname(opts.path);
51
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
52
+
53
+ const db = new Database(opts.path);
54
+ // BEFORE the pragmas: an encrypted database must be keyed before it will answer anything.
55
+ if (typeof opts.onOpen === 'function') opts.onOpen(db);
56
+
57
+ const pragmas = {
58
+ journal_mode: 'WAL', // concurrent readers + one writer
59
+ synchronous: 'NORMAL', // the recommended pairing with WAL (FULL fsyncs every write)
60
+ foreign_keys: 'ON',
61
+ busy_timeout: 5000,
62
+ ...(opts.pragmas || {})
63
+ };
64
+ for (const [k, v] of Object.entries(pragmas)) db.pragma(`${k} = ${v}`);
65
+
66
+ return wrap(db);
67
+ }
68
+
69
+ /** The contract over an open better-sqlite3 handle. */
70
+ function wrap(db) {
71
+ const stmt = (sql) => db.prepare(sql);
72
+ let txDepth = 0;
73
+
74
+ const api = {
75
+ kind: 'sqlite',
76
+ dialect: dialectFor('sqlite'),
77
+ concurrency: 'serial',
78
+ /** The raw handle, for the few things that genuinely need it (backup's VACUUM INTO). */
79
+ raw: db,
80
+
81
+ async get(sql, params = []) {
82
+ const b = bindNamed(sql, params);
83
+ return stmt(b.sql).get(...b.values) || null;
84
+ },
85
+ async all(sql, params = []) {
86
+ const b = bindNamed(sql, params);
87
+ return stmt(b.sql).all(...b.values);
88
+ },
89
+ async run(sql, params = []) {
90
+ const b = bindNamed(sql, params);
91
+ const info = stmt(b.sql).run(...b.values);
92
+ return { changes: info.changes, lastId: info.lastInsertRowid };
93
+ },
94
+ /** Multi-statement DDL. Never parameterised — migrations only. */
95
+ async exec(sql) {
96
+ db.exec(sql);
97
+ },
98
+
99
+ /**
100
+ * Transactions are run with explicit BEGIN/COMMIT rather than better-sqlite3's
101
+ * `db.transaction(fn)`, because that helper REFUSES an async callback — and every callback
102
+ * here is async by contract. Safe only because this driver declares 'serial': nothing else
103
+ * can issue a statement between the BEGIN and the COMMIT.
104
+ */
105
+ async transaction(fn) {
106
+ // NESTING VIA SAVEPOINTS. Stores compose — an app wrapper can put its own transaction
107
+ // around a store call that already opens one (a role rename that must retarget users in
108
+ // the same atomic step is the case that surfaced this). A second BEGIN is an error in
109
+ // SQLite, so depth is tracked: the outermost is a real transaction, inner ones are
110
+ // savepoints that can roll back independently without discarding the outer work.
111
+ const depth = txDepth++;
112
+ const sp = `aria_sp_${depth}`;
113
+ db.exec(depth === 0 ? 'BEGIN' : `SAVEPOINT ${sp}`);
114
+ try {
115
+ const out = await fn(api);
116
+ db.exec(depth === 0 ? 'COMMIT' : `RELEASE ${sp}`);
117
+ return out;
118
+ } catch (e) {
119
+ // The original error is what matters; a failed rollback must not mask it.
120
+ try { db.exec(depth === 0 ? 'ROLLBACK' : `ROLLBACK TO ${sp}`); } catch (_) { /* noop */ }
121
+ throw e;
122
+ } finally {
123
+ txDepth = depth;
124
+ }
125
+ },
126
+
127
+ async close() {
128
+ db.close();
129
+ }
130
+ };
131
+ return api;
132
+ }
133
+
134
+ 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,30 +1,38 @@
1
- {
2
- "name": "@aria-framework/db-worker",
3
- "version": "0.5.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
- ],
21
- "peerDependencies": {
22
- "better-sqlite3": ">=9"
23
- },
24
- "devDependencies": {
25
- "better-sqlite3": "^12.10.0"
26
- },
27
- "scripts": {
28
- "test": "node test/smoke.js && node test/tier2.js"
29
- }
30
- }
1
+ {
2
+ "name": "@aria-framework/db-worker",
3
+ "version": "0.6.1",
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": { "optional": true },
29
+ "pg": { "optional": true }
30
+ },
31
+ "devDependencies": {
32
+ "better-sqlite3": "^12.10.0",
33
+ "pg": "^8.23.0"
34
+ },
35
+ "scripts": {
36
+ "test": "node test/driverContract.js && node test/migrations.js && node test/smoke.js && node test/tier2.js"
37
+ }
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
  }