@aria-framework/db-worker 0.6.1 → 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 +33 -5
- package/dialect.js +5 -0
- package/driver/params.js +4 -0
- package/driver/postgres.js +27 -3
- package/driver/sqlite.js +11 -3
- package/package.json +2 -2
package/database.js
CHANGED
|
@@ -10,7 +10,23 @@
|
|
|
10
10
|
* that variant is now the `onOpen` hook).
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
// LAZY, and load-bearing. better-sqlite3 is an OPTIONAL peer so a Postgres-only app never has to
|
|
14
|
+
// build a native module it will not use — but index.js exports `database: require('./database')`,
|
|
15
|
+
// so a top-level require here made merely LOADING the package fail with MODULE_NOT_FOUND for
|
|
16
|
+
// exactly those apps. The optional peer was therefore optional in the manifest and mandatory in
|
|
17
|
+
// practice, which defeats the point of shipping two drivers.
|
|
18
|
+
let _Database = null;
|
|
19
|
+
const loadDatabase = () => {
|
|
20
|
+
if (_Database) return _Database;
|
|
21
|
+
try { _Database = require('better-sqlite3'); }
|
|
22
|
+
catch (e) {
|
|
23
|
+
throw new Error(
|
|
24
|
+
'db-worker: better-sqlite3 is not installed. It is an optional peer — install it for the ' +
|
|
25
|
+
'sqlite driver, or use initDriver({ kind: "postgres" }). (' + e.message + ')'
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
return _Database;
|
|
29
|
+
};
|
|
14
30
|
const fs = require('fs');
|
|
15
31
|
const path = require('path');
|
|
16
32
|
|
|
@@ -37,7 +53,7 @@ function init(dbPath, opts = {}) {
|
|
|
37
53
|
fs.mkdirSync(dir, { recursive: true });
|
|
38
54
|
}
|
|
39
55
|
|
|
40
|
-
_db = new
|
|
56
|
+
_db = new (loadDatabase())(dbPath);
|
|
41
57
|
|
|
42
58
|
if (typeof opts.onOpen === 'function') opts.onOpen(_db);
|
|
43
59
|
|
|
@@ -151,13 +167,25 @@ function getDb() {
|
|
|
151
167
|
return _db;
|
|
152
168
|
}
|
|
153
169
|
|
|
154
|
-
/**
|
|
155
|
-
|
|
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;
|
|
156
184
|
if (_db) {
|
|
157
185
|
_db.close();
|
|
158
186
|
_db = null;
|
|
159
|
-
_logger.info('Database closed');
|
|
160
187
|
}
|
|
188
|
+
_logger.info('Database closed');
|
|
161
189
|
}
|
|
162
190
|
|
|
163
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'
|
package/driver/params.js
CHANGED
|
@@ -55,6 +55,10 @@ function bindNamed(sql, params) {
|
|
|
55
55
|
const end = j === -1 ? sql.length : j + 2;
|
|
56
56
|
out += sql.slice(i, end); i = end; continue;
|
|
57
57
|
}
|
|
58
|
+
// `@@` is the full-text match operator, and `tsv @@to_tsquery('x')` written without a space
|
|
59
|
+
// was being read as a parameter named `@to_tsquery`. Full-text search is core to app 3, so
|
|
60
|
+
// consume both characters before the named-parameter rule can see the second one.
|
|
61
|
+
if (c === '@' && sql[i + 1] === '@') { out += '@@'; i += 2; continue; }
|
|
58
62
|
if (c === '@' && NAME_CHAR.test(sql[i + 1] || '')) {
|
|
59
63
|
let j = i + 1;
|
|
60
64
|
while (j < sql.length && NAME_CHAR.test(sql[j])) j++;
|
package/driver/postgres.js
CHANGED
|
@@ -67,6 +67,14 @@ function toDollarParams(sql) {
|
|
|
67
67
|
out += sql.slice(i, end); i = end; continue;
|
|
68
68
|
}
|
|
69
69
|
}
|
|
70
|
+
// JSONB EXISTENCE OPERATORS. `?`, `?|` and `?&` are real Postgres operators, and rewriting
|
|
71
|
+
// them into placeholders both breaks the query and shifts every later placeholder number by
|
|
72
|
+
// one — so the remaining binds silently land on the wrong columns. App 3 makes JSON core, so
|
|
73
|
+
// this is a query it will actually write.
|
|
74
|
+
// ?| and ?& are unambiguous (a placeholder is never followed by | or &) and pass through.
|
|
75
|
+
// A BARE ? is genuinely ambiguous, so `??` is the escape for a literal one.
|
|
76
|
+
if (c === '?' && (sql[i + 1] === '|' || sql[i + 1] === '&')) { out += sql.slice(i, i + 2); i += 2; continue; }
|
|
77
|
+
if (c === '?' && sql[i + 1] === '?') { out += '?'; i += 2; continue; }
|
|
70
78
|
if (c === '?') { out += '$' + (++n); i++; continue; }
|
|
71
79
|
|
|
72
80
|
out += c; i++;
|
|
@@ -94,9 +102,25 @@ function createPostgresDriver(opts = {}) {
|
|
|
94
102
|
throw new Error('createPostgresDriver({ connectionString }): a connection string (or host/user/database) is required');
|
|
95
103
|
}
|
|
96
104
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
105
|
+
// Pass the CONNECTION OPTIONS THROUGH. The guard above accepts host/user/database as an
|
|
106
|
+
// alternative to a connection string and the JSDoc documents it, but only connectionString was
|
|
107
|
+
// ever handed to pg — so those callers silently fell back to PGHOST/PGUSER or localhost and
|
|
108
|
+
// connected to the wrong server.
|
|
109
|
+
const { connectionString, host, port, user, password, database, ssl } = opts;
|
|
110
|
+
const poolCfg = { ...(opts.pool || {}) };
|
|
111
|
+
if (connectionString) poolCfg.connectionString = connectionString;
|
|
112
|
+
for (const [k, v] of Object.entries({ host, port, user, password, database, ssl })) {
|
|
113
|
+
if (v !== undefined) poolCfg[k] = v;
|
|
114
|
+
}
|
|
115
|
+
const pool = new pg.Pool(poolCfg);
|
|
116
|
+
|
|
117
|
+
// An unhandled 'error' on a Pool CRASHES THE PROCESS, and this is not hypothetical: the restore
|
|
118
|
+
// path issues pg_terminate_backend and DROP DATABASE ... WITH (FORCE), which kill this pool's
|
|
119
|
+
// idle clients out from under it. A server restart, failover or idle_in_transaction_session_
|
|
120
|
+
// timeout does the same. An idle-client failure must not take the worker thread down.
|
|
121
|
+
pool.on('error', (err) => {
|
|
122
|
+
try { (opts.logger || console).warn(`postgres pool: idle client error (${err.message})`); }
|
|
123
|
+
catch (_) { /* a logging failure must not become the crash this listener exists to prevent */ }
|
|
100
124
|
});
|
|
101
125
|
|
|
102
126
|
/** Build the contract over either the pool or one checked-out client (inside a transaction). */
|
package/driver/sqlite.js
CHANGED
|
@@ -67,9 +67,17 @@ function createSqliteDriver(opts = {}) {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
/** The contract over an open better-sqlite3 handle. */
|
|
70
|
+
// The nesting depth belongs to the CONNECTION, not to the wrapper around it. Each store that
|
|
71
|
+
// resolves a legacy { getDb } mints its OWN driver over the shared handle (auth/resolveDriver.js),
|
|
72
|
+
// so a per-closure counter gave every store a private depth of 0 — and the exact composition
|
|
73
|
+
// savepoint nesting was released for (an app wrapper's transaction around a store's own) issued
|
|
74
|
+
// a second BEGIN and threw "cannot start a transaction within a transaction", leaving the outer
|
|
75
|
+
// transaction open. Hanging it off the handle makes every wrapper over one connection agree.
|
|
76
|
+
const DEPTH = Symbol.for('aria.db-worker.depth');
|
|
77
|
+
|
|
70
78
|
function wrap(db) {
|
|
71
79
|
const stmt = (sql) => db.prepare(sql);
|
|
72
|
-
|
|
80
|
+
if (typeof db[DEPTH] !== 'number') db[DEPTH] = 0;
|
|
73
81
|
|
|
74
82
|
const api = {
|
|
75
83
|
kind: 'sqlite',
|
|
@@ -108,7 +116,7 @@ function wrap(db) {
|
|
|
108
116
|
// the same atomic step is the case that surfaced this). A second BEGIN is an error in
|
|
109
117
|
// SQLite, so depth is tracked: the outermost is a real transaction, inner ones are
|
|
110
118
|
// savepoints that can roll back independently without discarding the outer work.
|
|
111
|
-
const depth =
|
|
119
|
+
const depth = db[DEPTH]++;
|
|
112
120
|
const sp = `aria_sp_${depth}`;
|
|
113
121
|
db.exec(depth === 0 ? 'BEGIN' : `SAVEPOINT ${sp}`);
|
|
114
122
|
try {
|
|
@@ -120,7 +128,7 @@ function wrap(db) {
|
|
|
120
128
|
try { db.exec(depth === 0 ? 'ROLLBACK' : `ROLLBACK TO ${sp}`); } catch (_) { /* noop */ }
|
|
121
129
|
throw e;
|
|
122
130
|
} finally {
|
|
123
|
-
|
|
131
|
+
db[DEPTH] = depth;
|
|
124
132
|
}
|
|
125
133
|
},
|
|
126
134
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aria-framework/db-worker",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.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,
|
|
@@ -33,6 +33,6 @@
|
|
|
33
33
|
"pg": "^8.23.0"
|
|
34
34
|
},
|
|
35
35
|
"scripts": {
|
|
36
|
-
"test": "node test/driverContract.js && node test/migrations.js && node test/smoke.js && node test/tier2.js"
|
|
36
|
+
"test": "node test/driverContract.js && node test/migrations.js && node test/regressions.js && node test/smoke.js && node test/tier2.js"
|
|
37
37
|
}
|
|
38
38
|
}
|