@aria-framework/db-worker 0.6.0 → 0.7.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
@@ -10,7 +10,23 @@
10
10
  * that variant is now the `onOpen` hook).
11
11
  */
12
12
 
13
- const Database = require('better-sqlite3');
13
+ // LAZY, and load-bearing. better-sqlite3 is an OPTIONAL peer so a Postgres-only app never has to
14
+ // build a native module it will not use — but index.js exports `database: require('./database')`,
15
+ // so a top-level require here made merely LOADING the package fail with MODULE_NOT_FOUND for
16
+ // exactly those apps. The optional peer was therefore optional in the manifest and mandatory in
17
+ // practice, which defeats the point of shipping two drivers.
18
+ let _Database = null;
19
+ const loadDatabase = () => {
20
+ if (_Database) return _Database;
21
+ try { _Database = require('better-sqlite3'); }
22
+ catch (e) {
23
+ throw new Error(
24
+ 'db-worker: better-sqlite3 is not installed. It is an optional peer — install it for the ' +
25
+ 'sqlite driver, or use initDriver({ kind: "postgres" }). (' + e.message + ')'
26
+ );
27
+ }
28
+ return _Database;
29
+ };
14
30
  const fs = require('fs');
15
31
  const path = require('path');
16
32
 
@@ -37,7 +53,7 @@ function init(dbPath, opts = {}) {
37
53
  fs.mkdirSync(dir, { recursive: true });
38
54
  }
39
55
 
40
- _db = new Database(dbPath);
56
+ _db = new (loadDatabase())(dbPath);
41
57
 
42
58
  if (typeof opts.onOpen === 'function') opts.onOpen(_db);
43
59
 
@@ -140,36 +156,10 @@ function runMigrations(migrationsDir) {
140
156
  })();
141
157
  }
142
158
 
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
- */
159
+ /** Adopt the handle init() just opened — the driver must not open a second connection. */
150
160
  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;
161
+ const { createSqliteDriver } = require('./driver/sqlite');
162
+ return createSqliteDriver({ adopt: db });
173
163
  }
174
164
 
175
165
  function getDb() {
@@ -177,13 +167,25 @@ function getDb() {
177
167
  return _db;
178
168
  }
179
169
 
180
- /** Close the database connection. */
181
- function close() {
170
+ /**
171
+ * Close the database connection.
172
+ *
173
+ * Closes the DRIVER too. It previously only looked at `_db`, which initDriver() deliberately
174
+ * leaves null on Postgres — so close() was a complete no-op there, the pg Pool's sockets stayed
175
+ * open and the process would not exit on a graceful shutdown. On SQLite it closed the handle but
176
+ * left `_driver` wrapping it, so the next store call failed with better-sqlite3's "The database
177
+ * connection is not open" instead of this module's much clearer "not initialized".
178
+ */
179
+ async function close() {
180
+ if (_driver && typeof _driver.close === 'function') {
181
+ try { await _driver.close(); } catch (e) { _logger.warn(`Driver close failed: ${e.message}`); }
182
+ }
183
+ _driver = null;
182
184
  if (_db) {
183
185
  _db.close();
184
186
  _db = null;
185
- _logger.info('Database closed');
186
187
  }
188
+ _logger.info('Database closed');
187
189
  }
188
190
 
189
191
  /**
package/dialect.js CHANGED
@@ -38,6 +38,10 @@ const sqlite = {
38
38
  jsonPath: (col, path) => `json_extract(${col}, '${String(path).replace(/'/g, "''")}')`,
39
39
  /** Case-insensitive LIKE. SQLite's LIKE is already case-insensitive for ASCII. */
40
40
  ilike: () => 'LIKE',
41
+ // Case-insensitive EQUALITY. Deliberately NOT ilike(): LIKE/ILIKE are PATTERN operators, so
42
+ // `role LIKE 'read_only'` also matches 'read-only' because `_` is a single-character wildcard,
43
+ // and a value of '%' matches everything. Equality has to be spelled as equality.
44
+ ciEquals: (col, param) => `LOWER(${col}) = LOWER(${param})`,
41
45
  /** Suffix that makes run() report a new row's id. SQLite reports it out of band. */
42
46
  returning: () => '',
43
47
  /** DDL fragment for an auto-incrementing primary key (only secure-keystore needs this). */
@@ -71,6 +75,7 @@ const postgres = {
71
75
  return `((${col})::jsonb ->> '${key.replace(/'/g, "''")}')`;
72
76
  },
73
77
  ilike: () => 'ILIKE',
78
+ ciEquals: (col, param) => `LOWER(${col}) = LOWER(${param})`,
74
79
  returning: (col = 'id') => ` RETURNING ${ident(col)}`,
75
80
  autoIncrementPk: () => 'BIGSERIAL PRIMARY KEY',
76
81
  textType: () => 'TEXT'
@@ -0,0 +1,79 @@
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
+ // `@@` is the full-text match operator, and `tsv @@to_tsquery('x')` written without a space
59
+ // was being read as a parameter named `@to_tsquery`. Full-text search is core to app 3, so
60
+ // consume both characters before the named-parameter rule can see the second one.
61
+ if (c === '@' && sql[i + 1] === '@') { out += '@@'; i += 2; continue; }
62
+ if (c === '@' && NAME_CHAR.test(sql[i + 1] || '')) {
63
+ let j = i + 1;
64
+ while (j < sql.length && NAME_CHAR.test(sql[j])) j++;
65
+ const name = sql.slice(i + 1, j);
66
+ if (!(name in params)) {
67
+ throw new Error(`bindNamed: SQL references @${name} but no such key was supplied`);
68
+ }
69
+ values.push(params[name]);
70
+ out += '?';
71
+ i = j;
72
+ continue;
73
+ }
74
+ out += c; i++;
75
+ }
76
+ return { sql: out, values };
77
+ }
78
+
79
+ module.exports = { bindNamed };
@@ -19,6 +19,7 @@
19
19
  'use strict';
20
20
 
21
21
  const { dialectFor } = require('../dialect');
22
+ const { bindNamed } = require('./params');
22
23
 
23
24
  /**
24
25
  * Rewrite `?` placeholders to `$1..$n`, leaving any `?` inside a literal alone.
@@ -66,6 +67,14 @@ function toDollarParams(sql) {
66
67
  out += sql.slice(i, end); i = end; continue;
67
68
  }
68
69
  }
70
+ // JSONB EXISTENCE OPERATORS. `?`, `?|` and `?&` are real Postgres operators, and rewriting
71
+ // them into placeholders both breaks the query and shifts every later placeholder number by
72
+ // one — so the remaining binds silently land on the wrong columns. App 3 makes JSON core, so
73
+ // this is a query it will actually write.
74
+ // ?| and ?& are unambiguous (a placeholder is never followed by | or &) and pass through.
75
+ // A BARE ? is genuinely ambiguous, so `??` is the escape for a literal one.
76
+ if (c === '?' && (sql[i + 1] === '|' || sql[i + 1] === '&')) { out += sql.slice(i, i + 2); i += 2; continue; }
77
+ if (c === '?' && sql[i + 1] === '?') { out += '?'; i += 2; continue; }
69
78
  if (c === '?') { out += '$' + (++n); i++; continue; }
70
79
 
71
80
  out += c; i++;
@@ -93,9 +102,25 @@ function createPostgresDriver(opts = {}) {
93
102
  throw new Error('createPostgresDriver({ connectionString }): a connection string (or host/user/database) is required');
94
103
  }
95
104
 
96
- const pool = new pg.Pool({
97
- connectionString: opts.connectionString,
98
- ...(opts.pool || {})
105
+ // Pass the CONNECTION OPTIONS THROUGH. The guard above accepts host/user/database as an
106
+ // alternative to a connection string and the JSDoc documents it, but only connectionString was
107
+ // ever handed to pg — so those callers silently fell back to PGHOST/PGUSER or localhost and
108
+ // connected to the wrong server.
109
+ const { connectionString, host, port, user, password, database, ssl } = opts;
110
+ const poolCfg = { ...(opts.pool || {}) };
111
+ if (connectionString) poolCfg.connectionString = connectionString;
112
+ for (const [k, v] of Object.entries({ host, port, user, password, database, ssl })) {
113
+ if (v !== undefined) poolCfg[k] = v;
114
+ }
115
+ const pool = new pg.Pool(poolCfg);
116
+
117
+ // An unhandled 'error' on a Pool CRASHES THE PROCESS, and this is not hypothetical: the restore
118
+ // path issues pg_terminate_backend and DROP DATABASE ... WITH (FORCE), which kill this pool's
119
+ // idle clients out from under it. A server restart, failover or idle_in_transaction_session_
120
+ // timeout does the same. An idle-client failure must not take the worker thread down.
121
+ pool.on('error', (err) => {
122
+ try { (opts.logger || console).warn(`postgres pool: idle client error (${err.message})`); }
123
+ catch (_) { /* a logging failure must not become the crash this listener exists to prevent */ }
99
124
  });
100
125
 
101
126
  /** Build the contract over either the pool or one checked-out client (inside a transaction). */
@@ -105,11 +130,13 @@ function createPostgresDriver(opts = {}) {
105
130
  concurrency: 'pool',
106
131
 
107
132
  async get(sql, params = []) {
108
- const r = await exec(toDollarParams(sql), params);
133
+ const b = bindNamed(sql, params);
134
+ const r = await exec(toDollarParams(b.sql), b.values);
109
135
  return r.rows[0] || null;
110
136
  },
111
137
  async all(sql, params = []) {
112
- const r = await exec(toDollarParams(sql), params);
138
+ const b = bindNamed(sql, params);
139
+ const r = await exec(toDollarParams(b.sql), b.values);
113
140
  return r.rows;
114
141
  },
115
142
  /**
@@ -118,7 +145,8 @@ function createPostgresDriver(opts = {}) {
118
145
  * ` RETURNING "id"` here — so the store's SQL stays one string for both engines.
119
146
  */
120
147
  async run(sql, params = []) {
121
- const r = await exec(toDollarParams(sql), params);
148
+ const b = bindNamed(sql, params);
149
+ const r = await exec(toDollarParams(b.sql), b.values);
122
150
  const row = r.rows && r.rows[0];
123
151
  const lastId = row ? (row.id !== undefined ? row.id : Object.values(row)[0]) : undefined;
124
152
  return { changes: r.rowCount, lastId };
@@ -137,9 +165,23 @@ function createPostgresDriver(opts = {}) {
137
165
  */
138
166
  async transaction(fn) {
139
167
  const client = await pool.connect();
168
+ let depth = 0;
140
169
  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)
170
+ // Nested transaction() reuses the same CLIENT (a second pooled connection would
171
+ // deadlock against this one's locks) and brackets the body in a SAVEPOINT, so an inner
172
+ // failure rolls back only its own work rather than discarding the outer transaction.
173
+ async transaction(inner) {
174
+ const sp = `aria_sp_${depth++}`;
175
+ await client.query(`SAVEPOINT ${sp}`);
176
+ try {
177
+ const out = await inner(txApi);
178
+ await client.query(`RELEASE SAVEPOINT ${sp}`);
179
+ return out;
180
+ } catch (e) {
181
+ try { await client.query(`ROLLBACK TO SAVEPOINT ${sp}`); } catch (_) { /* noop */ }
182
+ throw e;
183
+ } finally { depth--; }
184
+ }
143
185
  });
144
186
  try {
145
187
  await client.query('BEGIN');
package/driver/sqlite.js CHANGED
@@ -21,6 +21,7 @@
21
21
  const fs = require('fs');
22
22
  const path = require('path');
23
23
  const { dialectFor } = require('../dialect');
24
+ const { bindNamed } = require('./params');
24
25
 
25
26
  /**
26
27
  * @param {object} opts
@@ -30,7 +31,12 @@ const { dialectFor } = require('../dialect');
30
31
  * pragmas override/extend the defaults
31
32
  */
32
33
  function createSqliteDriver(opts = {}) {
33
- if (!opts.path) throw new Error("createSqliteDriver({ path }): the database file path is required");
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");
34
40
  let Database;
35
41
  try {
36
42
  Database = require('better-sqlite3');
@@ -57,7 +63,21 @@ function createSqliteDriver(opts = {}) {
57
63
  };
58
64
  for (const [k, v] of Object.entries(pragmas)) db.pragma(`${k} = ${v}`);
59
65
 
66
+ return wrap(db);
67
+ }
68
+
69
+ /** The contract over an open better-sqlite3 handle. */
70
+ // The nesting depth belongs to the CONNECTION, not to the wrapper around it. Each store that
71
+ // resolves a legacy { getDb } mints its OWN driver over the shared handle (auth/resolveDriver.js),
72
+ // so a per-closure counter gave every store a private depth of 0 — and the exact composition
73
+ // savepoint nesting was released for (an app wrapper's transaction around a store's own) issued
74
+ // a second BEGIN and threw "cannot start a transaction within a transaction", leaving the outer
75
+ // transaction open. Hanging it off the handle makes every wrapper over one connection agree.
76
+ const DEPTH = Symbol.for('aria.db-worker.depth');
77
+
78
+ function wrap(db) {
60
79
  const stmt = (sql) => db.prepare(sql);
80
+ if (typeof db[DEPTH] !== 'number') db[DEPTH] = 0;
61
81
 
62
82
  const api = {
63
83
  kind: 'sqlite',
@@ -67,13 +87,16 @@ function createSqliteDriver(opts = {}) {
67
87
  raw: db,
68
88
 
69
89
  async get(sql, params = []) {
70
- return stmt(sql).get(...params) || null;
90
+ const b = bindNamed(sql, params);
91
+ return stmt(b.sql).get(...b.values) || null;
71
92
  },
72
93
  async all(sql, params = []) {
73
- return stmt(sql).all(...params);
94
+ const b = bindNamed(sql, params);
95
+ return stmt(b.sql).all(...b.values);
74
96
  },
75
97
  async run(sql, params = []) {
76
- const info = stmt(sql).run(...params);
98
+ const b = bindNamed(sql, params);
99
+ const info = stmt(b.sql).run(...b.values);
77
100
  return { changes: info.changes, lastId: info.lastInsertRowid };
78
101
  },
79
102
  /** Multi-statement DDL. Never parameterised — migrations only. */
@@ -88,14 +111,24 @@ function createSqliteDriver(opts = {}) {
88
111
  * can issue a statement between the BEGIN and the COMMIT.
89
112
  */
90
113
  async transaction(fn) {
91
- db.exec('BEGIN');
114
+ // NESTING VIA SAVEPOINTS. Stores compose — an app wrapper can put its own transaction
115
+ // around a store call that already opens one (a role rename that must retarget users in
116
+ // the same atomic step is the case that surfaced this). A second BEGIN is an error in
117
+ // SQLite, so depth is tracked: the outermost is a real transaction, inner ones are
118
+ // savepoints that can roll back independently without discarding the outer work.
119
+ const depth = db[DEPTH]++;
120
+ const sp = `aria_sp_${depth}`;
121
+ db.exec(depth === 0 ? 'BEGIN' : `SAVEPOINT ${sp}`);
92
122
  try {
93
123
  const out = await fn(api);
94
- db.exec('COMMIT');
124
+ db.exec(depth === 0 ? 'COMMIT' : `RELEASE ${sp}`);
95
125
  return out;
96
126
  } catch (e) {
97
- try { db.exec('ROLLBACK'); } catch (_) { /* the failure that matters is the original */ }
127
+ // The original error is what matters; a failed rollback must not mask it.
128
+ try { db.exec(depth === 0 ? 'ROLLBACK' : `ROLLBACK TO ${sp}`); } catch (_) { /* noop */ }
98
129
  throw e;
130
+ } finally {
131
+ db[DEPTH] = depth;
99
132
  }
100
133
  },
101
134
 
package/package.json CHANGED
@@ -1,38 +1,38 @@
1
- {
2
- "name": "@aria-framework/db-worker",
3
- "version": "0.6.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": { "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
- }
1
+ {
2
+ "name": "@aria-framework/db-worker",
3
+ "version": "0.7.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": { "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/regressions.js && node test/smoke.js && node test/tier2.js"
37
+ }
38
+ }