@statewalker/db-sqlite 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -2
- package/dist/index.d.mts +17 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +182 -30
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +3 -0
- package/src/serialised-sqlite-db.ts +138 -27
- package/src/sql-statements.ts +96 -13
- package/src/sqlite-transaction.ts +39 -0
package/README.md
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
Transactions for SQLite databases behind `Db` from `@statewalker/db-api`:
|
|
6
6
|
`inTransaction(db, cb)` runs `cb` so that every statement issued through its `tx` handle commits
|
|
7
|
-
together or not at all
|
|
7
|
+
together or not at all; `inReadOnlyTransaction(db, cb)` runs it in a transaction that is always
|
|
8
|
+
rolled back, so nothing it writes persists. It also holds `newSerialisedSqliteDb`, the wrapper every SQLite driver
|
|
8
9
|
(`db-sqlite-node`, `db-sqlite-browser`, `db-sqlite-do`) builds its `Db` with, and
|
|
9
10
|
`newSerialisedDb`, the engine-neutral lifecycle wrapper the DuckDB and PGlite drivers use. Both
|
|
10
11
|
keep the lifecycle that the `Db` JSDoc in `@statewalker/db-api` promises.
|
|
@@ -24,7 +25,7 @@ pnpm add @statewalker/db-sqlite
|
|
|
24
25
|
|
|
25
26
|
| Import | Gives | Environment |
|
|
26
27
|
| --- | --- | --- |
|
|
27
|
-
| `@statewalker/db-sqlite` | `inTransaction`, `newSerialisedDb`, `newSerialisedSqliteDb`, `SQLITE_TRANSACTION`; types `SerialisedDbEngine`, `SqliteEngine`, `SqliteTransactionHook` | any |
|
|
28
|
+
| `@statewalker/db-sqlite` | `inTransaction`, `inReadOnlyTransaction`, `hasReadOnlyTransaction`, `newSerialisedDb`, `newSerialisedSqliteDb`, `SQLITE_TRANSACTION`, `SQLITE_READ_ONLY_TRANSACTION`; types `SerialisedDbEngine`, `SqliteEngine`, `SqliteTransactionHook` | any |
|
|
28
29
|
|
|
29
30
|
`newSerialisedDb(engine, { name })` wraps an asynchronous `SerialisedDbEngine` (`query(sql,
|
|
30
31
|
params)`, `exec(sql)`, optional `flush()`, `close()`) as a `Db`: calls run one at a time in call
|
|
@@ -39,6 +40,33 @@ package without pulling in any engine.
|
|
|
39
40
|
back and the same error is rethrown; so is a failing `COMMIT` (a deferred foreign key, for
|
|
40
41
|
example), which rejects with SQLite's error. While it runs, other calls on `db` wait for it.
|
|
41
42
|
|
|
43
|
+
`inReadOnlyTransaction(db, cb)` returns what `cb` returns, or rethrows its error, and in both
|
|
44
|
+
cases rolls back everything it wrote: `tx` sees the committed data and its own writes, and none
|
|
45
|
+
of them persist. It is what a reader gets the full SQL surface through without the risk
|
|
46
|
+
(`@statewalker/db-rpc`'s read-only server uses it for every call). Two rules keep a statement from
|
|
47
|
+
slipping out of the transaction:
|
|
48
|
+
- SQL that would end the transaction or reach outside it is refused before it runs, on `query`
|
|
49
|
+
and `exec` alike: a statement starting with BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, RELEASE,
|
|
50
|
+
ATTACH, DETACH, PRAGMA or VACUUM rejects with
|
|
51
|
+
`db-sqlite: a read-only transaction refuses COMMIT (it would end the transaction or reach outside it)`.
|
|
52
|
+
Statements are split as SQLite splits them, so the words inside literals, comments and trigger
|
|
53
|
+
bodies do not count. A statement that does not start with a word (such as `(SELECT 1)`) is
|
|
54
|
+
refused too, so that a separator SQLite skips and the splitter might not can never hide the
|
|
55
|
+
word that starts it. The splitter follows SQLite's tokenizer where it matters: whitespace
|
|
56
|
+
includes `\v`, and a Tcl-style variable (`$a(…)`, `:a(…)`, `@a(…)`, `#a(…)`) runs to the first
|
|
57
|
+
`)` or whitespace, quotes included.
|
|
58
|
+
- `exec` inside it runs one statement per engine call, each through the engine's `all`. On
|
|
59
|
+
Node.js, `all` compiles only the first statement of what it is given, so even text the splitter
|
|
60
|
+
misreads as part of a statement never runs as a statement of its own. The browser engine's
|
|
61
|
+
`all` runs every statement of its text, so there the splitter is the only guard; on a Durable
|
|
62
|
+
Object the platform itself refuses transaction control in SQL.
|
|
63
|
+
- Once a statement fails, `tx` refuses every later call, with
|
|
64
|
+
`db-sqlite: a statement of this read-only transaction failed, so it refuses later calls (SQLite may have ended the transaction)`:
|
|
65
|
+
SQLite ends a transaction itself on some errors (`INSERT OR ROLLBACK`, `RAISE(ROLLBACK)`), and
|
|
66
|
+
what ran after that would run, and persist, outside it.
|
|
67
|
+
|
|
68
|
+
`hasReadOnlyTransaction(db)` tells whether `db` carries the hook it needs.
|
|
69
|
+
|
|
42
70
|
Every SQLite driver handles input the same way, because the wrapper does it before the engine
|
|
43
71
|
sees the call (on the Db and on the `tx` handle alike):
|
|
44
72
|
|
|
@@ -79,6 +107,14 @@ await db.close();
|
|
|
79
107
|
|
|
80
108
|
## Internals
|
|
81
109
|
|
|
110
|
+
- **Read-only rollback.** On Node.js and in the browser the transaction is `BEGIN` (deferred)
|
|
111
|
+
… `ROLLBACK`; a `ROLLBACK` failing with `no transaction is active` (SQLite already ended it) is
|
|
112
|
+
ignored, any other failure rejects. On a Durable Object, whose `storage.transaction` commits
|
|
113
|
+
when the closure returns, the closure throws a marker error after `cb` returns, so the platform
|
|
114
|
+
rolls back, and the marker is turned back into `cb`'s value. The read-only hook has its own key,
|
|
115
|
+
`Symbol.for("@statewalker/db-sqlite:read-only-transaction")`, so a Db built by an older
|
|
116
|
+
db-sqlite (which has only the committing hook) is refused, never committed:
|
|
117
|
+
`inReadOnlyTransaction: this Db has no SQLite read-only transaction hook. ...`.
|
|
82
118
|
- **The hook travels on the Db object.** `newSerialisedSqliteDb` stores the transaction function
|
|
83
119
|
under `Symbol.for("@statewalker/db-sqlite:transaction")`; `inTransaction` looks it up. A Db
|
|
84
120
|
without it rejects with
|
package/dist/index.d.mts
CHANGED
|
@@ -51,6 +51,11 @@ export declare function newSerialisedSqliteDb(engine: SqliteEngine): Db;
|
|
|
51
51
|
//#region src/sqlite-transaction.d.ts
|
|
52
52
|
/** Key under which a SQLite Db carries its transaction hook. Shared across bundles via Symbol.for. */
|
|
53
53
|
export declare const SQLITE_TRANSACTION: unique symbol;
|
|
54
|
+
/**
|
|
55
|
+
* Key under which a SQLite Db carries its read-only transaction hook (a separate key, so that a Db
|
|
56
|
+
* from an older db-sqlite, which has only the committing hook, is refused rather than committed).
|
|
57
|
+
*/
|
|
58
|
+
export declare const SQLITE_READ_ONLY_TRANSACTION: unique symbol;
|
|
54
59
|
/** Runs `cb` inside one transaction of the Db that carries it. */
|
|
55
60
|
type SqliteTransactionHook = <T>(cb: (tx: Db) => Promise<T>) => Promise<T>;
|
|
56
61
|
/**
|
|
@@ -59,6 +64,18 @@ type SqliteTransactionHook = <T>(cb: (tx: Db) => Promise<T>) => Promise<T>;
|
|
|
59
64
|
* external I/O and must be idempotent: a Durable Object may run it more than once.
|
|
60
65
|
*/
|
|
61
66
|
export declare function inTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T>;
|
|
67
|
+
/**
|
|
68
|
+
* Run `cb` in one SQLite transaction that is always rolled back: `tx` sees the committed data and
|
|
69
|
+
* its own writes, and nothing it writes persists, whether `cb` returns (its value is returned) or
|
|
70
|
+
* throws (its error is rethrown). Statements that would end the transaction or reach outside it
|
|
71
|
+
* (BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, RELEASE, ATTACH, DETACH, PRAGMA, VACUUM) are refused,
|
|
72
|
+
* and once a statement fails, `tx` refuses every later call (SQLite may have ended the transaction
|
|
73
|
+
* itself, as `INSERT OR ROLLBACK` does). Other calls on `db` wait until it ends. `cb` must not do
|
|
74
|
+
* external I/O and must be idempotent: a Durable Object may run it more than once.
|
|
75
|
+
*/
|
|
76
|
+
export declare function inReadOnlyTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T>;
|
|
77
|
+
/** Whether `db` carries the hook {@link inReadOnlyTransaction} needs. */
|
|
78
|
+
export declare function hasReadOnlyTransaction(db: Db): boolean;
|
|
62
79
|
//#endregion
|
|
63
80
|
export type { SerialisedDbEngine, SqliteEngine, SqliteTransactionHook };
|
|
64
81
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/serialised-db.ts","../src/serialised-sqlite-db.ts","../src/sqlite-transaction.ts"],"mappings":";;;;;;;KAqEY;EACV,MAAM,aAAa,oBAAoB,QAAQ;EAC/C,KAAK,cAAc;EACnB,UAAU;EACV,gBAAgB;;;;;;;;;wBAUF,gBAAgB,QAAQ,oBAAoB;EAAW;IAAiB;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/serialised-db.ts","../src/serialised-sqlite-db.ts","../src/sqlite-transaction.ts"],"mappings":";;;;;;;KAqEY;EACV,MAAM,aAAa,oBAAoB,QAAQ;EAC/C,KAAK,cAAc;EACnB,UAAU;EACV,gBAAgB;;;;;;;;;wBAUF,gBAAgB,QAAQ,oBAAoB;EAAW;IAAiB;;;;;;;;;;;KC7D5E;EACV,IAAI,aAAa,oBAAoB;EACrC,KAAK;EACL;EACA,aAAa,GAAG,UAAU,QAAQ,KAAK,QAAQ;;;;;;;;;;;wBAoHjC,sBAAsB,QAAQ,eAAe;;;;qBC3IhD;;;;;qBAMA;;KAKD,yBAAyB,GAAG,KAAK,IAAI,OAAO,QAAQ,OAAO,QAAQ;;;;;;wBAY/D,cAAc,GAAG,IAAI,IAAI,KAAK,IAAI,OAAO,QAAQ,KAAK,QAAQ;;;;;;;;;;wBAqB9D,sBAAsB,GAAG,IAAI,IAAI,KAAK,IAAI,OAAO,QAAQ,KAAK,QAAQ;;wBAStE,uBAAuB,IAAI"}
|
package/dist/index.mjs
CHANGED
|
@@ -162,6 +162,31 @@ const KEYWORDS = {
|
|
|
162
162
|
explain: EXPLAIN
|
|
163
163
|
};
|
|
164
164
|
const isIdChar = (c) => /[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) >= 128;
|
|
165
|
+
/** SQLite's whitespace (sqlite3Isspace): space, \t, \n, \v, \f, \r. */
|
|
166
|
+
const isSpace = (c) => c === " " || c === " " || c === "\n" || c === "\v" || c === "\f" || c === "\r";
|
|
167
|
+
/**
|
|
168
|
+
* The end (exclusive) of a variable token starting at `i` (`$`, `:`, `@` or `#`), as SQLite's
|
|
169
|
+
* tokenizer reads it: identifier characters and `::`, and the Tcl form `$name(…)`, which runs to
|
|
170
|
+
* the first `)` (included) or whitespace, quotes and semicolons included.
|
|
171
|
+
*/
|
|
172
|
+
function variableEnd(sql, i) {
|
|
173
|
+
let j = i + 1;
|
|
174
|
+
let n = 0;
|
|
175
|
+
while (j < sql.length) {
|
|
176
|
+
const c = sql[j];
|
|
177
|
+
if (isIdChar(c)) {
|
|
178
|
+
n++;
|
|
179
|
+
j++;
|
|
180
|
+
} else if (c === "(" && n > 0) {
|
|
181
|
+
j++;
|
|
182
|
+
while (j < sql.length && !isSpace(sql[j]) && sql[j] !== ")") j++;
|
|
183
|
+
if (sql[j] === ")") j++;
|
|
184
|
+
break;
|
|
185
|
+
} else if (c === ":" && sql[j + 1] === ":") j += 2;
|
|
186
|
+
else break;
|
|
187
|
+
}
|
|
188
|
+
return j;
|
|
189
|
+
}
|
|
165
190
|
function countSqlStatements(sql) {
|
|
166
191
|
return scanSqlStatements(sql).count;
|
|
167
192
|
}
|
|
@@ -175,18 +200,44 @@ function firstSqlStatement(sql) {
|
|
|
175
200
|
const { firstEnd } = scanSqlStatements(sql);
|
|
176
201
|
return firstEnd < 0 ? sql : sql.slice(0, firstEnd);
|
|
177
202
|
}
|
|
203
|
+
/**
|
|
204
|
+
* The first word of every statement of `sql`, lowercased, in order ("" for a statement that does
|
|
205
|
+
* not start with a word, such as `(SELECT 1)`). Statements are split as SQLite splits them, so a
|
|
206
|
+
* keyword inside a literal, a comment or a trigger body is not a head. Empty statements are
|
|
207
|
+
* skipped.
|
|
208
|
+
*/
|
|
209
|
+
function sqlStatementHeads(sql) {
|
|
210
|
+
return scanSqlStatements(sql).heads;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* The statements of `sql`, split as {@link sqlStatementHeads} splits them: each from its first
|
|
214
|
+
* token to just before the semicolon that ends it (the last to the end of the text).
|
|
215
|
+
*/
|
|
216
|
+
function splitSqlStatements(sql) {
|
|
217
|
+
return scanSqlStatements(sql).statements;
|
|
218
|
+
}
|
|
178
219
|
function scanSqlStatements(sql) {
|
|
220
|
+
const heads = [];
|
|
221
|
+
const statements = [];
|
|
222
|
+
let start = 0;
|
|
179
223
|
let firstEnd = -1;
|
|
180
224
|
let state = 0;
|
|
181
|
-
let
|
|
182
|
-
let firstEnded = false;
|
|
225
|
+
let inStatement = false;
|
|
183
226
|
let i = 0;
|
|
184
227
|
const n = sql.length;
|
|
228
|
+
const result = () => ({
|
|
229
|
+
count: heads.length === 0 ? "empty" : heads.length === 1 ? "one" : "many",
|
|
230
|
+
firstEnd,
|
|
231
|
+
heads,
|
|
232
|
+
statements: inStatement ? [...statements, sql.slice(start)] : statements
|
|
233
|
+
});
|
|
185
234
|
while (i < n) {
|
|
186
235
|
const c = sql[i];
|
|
236
|
+
const tokenStart = i;
|
|
187
237
|
let token;
|
|
238
|
+
let word = "";
|
|
188
239
|
if (c === ";") token = SEMI;
|
|
189
|
-
else if (c
|
|
240
|
+
else if (isSpace(c)) token = WS;
|
|
190
241
|
else if (c === "/" && sql[i + 1] === "*") {
|
|
191
242
|
const close = sql.indexOf("*/", i + 2);
|
|
192
243
|
if (close < 0) break;
|
|
@@ -199,41 +250,50 @@ function scanSqlStatements(sql) {
|
|
|
199
250
|
token = WS;
|
|
200
251
|
} else if (c === "[" || c === "`" || c === "\"" || c === "'") {
|
|
201
252
|
const close = sql.indexOf(c === "[" ? "]" : c, i + 1);
|
|
202
|
-
if (close < 0)
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
253
|
+
if (close < 0) {
|
|
254
|
+
if (!inStatement) {
|
|
255
|
+
heads.push("");
|
|
256
|
+
start = tokenStart;
|
|
257
|
+
inStatement = true;
|
|
258
|
+
}
|
|
259
|
+
return result();
|
|
260
|
+
}
|
|
206
261
|
i = close;
|
|
207
262
|
token = OTHER;
|
|
263
|
+
} else if (c === "$" || c === ":" || c === "@" || c === "#") {
|
|
264
|
+
i = variableEnd(sql, i) - 1;
|
|
265
|
+
token = OTHER;
|
|
208
266
|
} else if (isIdChar(c)) {
|
|
209
267
|
let j = i + 1;
|
|
210
268
|
while (j < n && isIdChar(sql[j])) j++;
|
|
211
|
-
|
|
269
|
+
word = sql.slice(i, j).toLowerCase();
|
|
270
|
+
token = KEYWORDS[word] ?? OTHER;
|
|
212
271
|
i = j - 1;
|
|
213
272
|
} else token = OTHER;
|
|
214
|
-
if (token !== SEMI && token !== WS) {
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
};
|
|
219
|
-
content = true;
|
|
273
|
+
if (token !== SEMI && token !== WS && !inStatement) {
|
|
274
|
+
inStatement = true;
|
|
275
|
+
heads.push(word);
|
|
276
|
+
start = tokenStart;
|
|
220
277
|
}
|
|
221
278
|
state = TRANS[state]?.[token] ?? 2;
|
|
222
|
-
if (token === SEMI && state === 1 &&
|
|
223
|
-
|
|
224
|
-
|
|
279
|
+
if (token === SEMI && state === 1 && inStatement) {
|
|
280
|
+
inStatement = false;
|
|
281
|
+
statements.push(sql.slice(start, i));
|
|
282
|
+
if (firstEnd < 0) firstEnd = i;
|
|
225
283
|
}
|
|
226
284
|
i++;
|
|
227
285
|
}
|
|
228
|
-
return
|
|
229
|
-
count: content ? "one" : "empty",
|
|
230
|
-
firstEnd
|
|
231
|
-
};
|
|
286
|
+
return result();
|
|
232
287
|
}
|
|
233
288
|
//#endregion
|
|
234
289
|
//#region src/sqlite-transaction.ts
|
|
235
290
|
/** Key under which a SQLite Db carries its transaction hook. Shared across bundles via Symbol.for. */
|
|
236
291
|
const SQLITE_TRANSACTION = Symbol.for("@statewalker/db-sqlite:transaction");
|
|
292
|
+
/**
|
|
293
|
+
* Key under which a SQLite Db carries its read-only transaction hook (a separate key, so that a Db
|
|
294
|
+
* from an older db-sqlite, which has only the committing hook, is refused rather than committed).
|
|
295
|
+
*/
|
|
296
|
+
const SQLITE_READ_ONLY_TRANSACTION = Symbol.for("@statewalker/db-sqlite:read-only-transaction");
|
|
237
297
|
const NO_HOOK = "inTransaction: this Db has no SQLite transaction hook. It is not a @statewalker/db-sqlite* Db, or it wraps one (a wrapper object loses the hook - pass the driver's Db itself), or it is the handle of a running transaction (nesting is not supported).";
|
|
238
298
|
/**
|
|
239
299
|
* Run `cb` in one SQLite transaction: every statement issued through `tx` commits together, or
|
|
@@ -245,6 +305,25 @@ function inTransaction(db, cb) {
|
|
|
245
305
|
if (typeof hook !== "function") return Promise.reject(/* @__PURE__ */ new Error(NO_HOOK));
|
|
246
306
|
return hook(cb);
|
|
247
307
|
}
|
|
308
|
+
const NO_READ_ONLY_HOOK = "inReadOnlyTransaction: this Db has no SQLite read-only transaction hook. It is not a @statewalker/db-sqlite* Db (or one from a db-sqlite older than 0.1.4), or it wraps one (a wrapper object loses the hook - pass the driver's Db itself), or it is the handle of a running transaction (nesting is not supported).";
|
|
309
|
+
/**
|
|
310
|
+
* Run `cb` in one SQLite transaction that is always rolled back: `tx` sees the committed data and
|
|
311
|
+
* its own writes, and nothing it writes persists, whether `cb` returns (its value is returned) or
|
|
312
|
+
* throws (its error is rethrown). Statements that would end the transaction or reach outside it
|
|
313
|
+
* (BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, RELEASE, ATTACH, DETACH, PRAGMA, VACUUM) are refused,
|
|
314
|
+
* and once a statement fails, `tx` refuses every later call (SQLite may have ended the transaction
|
|
315
|
+
* itself, as `INSERT OR ROLLBACK` does). Other calls on `db` wait until it ends. `cb` must not do
|
|
316
|
+
* external I/O and must be idempotent: a Durable Object may run it more than once.
|
|
317
|
+
*/
|
|
318
|
+
function inReadOnlyTransaction(db, cb) {
|
|
319
|
+
const hook = db[SQLITE_READ_ONLY_TRANSACTION];
|
|
320
|
+
if (typeof hook !== "function") return Promise.reject(/* @__PURE__ */ new Error(NO_READ_ONLY_HOOK));
|
|
321
|
+
return hook(cb);
|
|
322
|
+
}
|
|
323
|
+
/** Whether `db` carries the hook {@link inReadOnlyTransaction} needs. */
|
|
324
|
+
function hasReadOnlyTransaction(db) {
|
|
325
|
+
return typeof db[SQLITE_READ_ONLY_TRANSACTION] === "function";
|
|
326
|
+
}
|
|
248
327
|
//#endregion
|
|
249
328
|
//#region src/serialised-sqlite-db.ts
|
|
250
329
|
const EMPTY_SQL = "db-sqlite: the SQL is empty (only whitespace, comments or semicolons)";
|
|
@@ -292,6 +371,28 @@ function runExec(engine, sql) {
|
|
|
292
371
|
checkSql(sql, false);
|
|
293
372
|
engine.exec(sql);
|
|
294
373
|
}
|
|
374
|
+
/** Statements a read-only transaction refuses: they end it, or reach outside it. */
|
|
375
|
+
const READ_ONLY_REFUSED = /* @__PURE__ */ new Set([
|
|
376
|
+
"begin",
|
|
377
|
+
"commit",
|
|
378
|
+
"end",
|
|
379
|
+
"rollback",
|
|
380
|
+
"savepoint",
|
|
381
|
+
"release",
|
|
382
|
+
"attach",
|
|
383
|
+
"detach",
|
|
384
|
+
"pragma",
|
|
385
|
+
"vacuum"
|
|
386
|
+
]);
|
|
387
|
+
function checkReadOnly(sql) {
|
|
388
|
+
if (typeof sql !== "string") return;
|
|
389
|
+
for (const head of sqlStatementHeads(sql)) {
|
|
390
|
+
if (head === "") throw new Error("db-sqlite: a read-only transaction refuses a statement that does not start with a keyword");
|
|
391
|
+
if (READ_ONLY_REFUSED.has(head)) throw new Error(`db-sqlite: a read-only transaction refuses ${head.toUpperCase()} (it would end the transaction or reach outside it)`);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
const READ_ONLY_FAILED = "db-sqlite: a statement of this read-only transaction failed, so it refuses later calls (SQLite may have ended the transaction)";
|
|
395
|
+
const ROLLBACK_ON_PURPOSE = "db-sqlite: the read-only transaction is rolled back";
|
|
295
396
|
/**
|
|
296
397
|
* Wrap an engine as a `Db` with the lifecycle of `newSerialisedDb` (calls run one at a time, in
|
|
297
398
|
* call order; `close()` waits for earlier calls; later calls reject with
|
|
@@ -316,26 +417,76 @@ function newSerialisedSqliteDb(engine) {
|
|
|
316
417
|
throw error;
|
|
317
418
|
}
|
|
318
419
|
});
|
|
319
|
-
const
|
|
420
|
+
const platformTransaction = engine.transaction?.bind(engine);
|
|
421
|
+
const runReadOnlyTransaction = platformTransaction ? async (fn) => {
|
|
422
|
+
let result;
|
|
423
|
+
let returned = false;
|
|
424
|
+
try {
|
|
425
|
+
await platformTransaction(async () => {
|
|
426
|
+
returned = false;
|
|
427
|
+
result = await fn();
|
|
428
|
+
returned = true;
|
|
429
|
+
throw new Error(ROLLBACK_ON_PURPOSE);
|
|
430
|
+
});
|
|
431
|
+
} catch (error) {
|
|
432
|
+
if (returned && error instanceof Error && error.message === ROLLBACK_ON_PURPOSE) return result;
|
|
433
|
+
throw error;
|
|
434
|
+
}
|
|
435
|
+
throw new Error("db-sqlite: the platform did not roll back the read-only transaction");
|
|
436
|
+
} : async (fn) => {
|
|
437
|
+
const rollback = () => {
|
|
438
|
+
try {
|
|
439
|
+
engine.exec("ROLLBACK");
|
|
440
|
+
} catch (error) {
|
|
441
|
+
if (!/no transaction is active/i.test(String(error?.message))) throw error;
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
engine.exec("BEGIN");
|
|
445
|
+
let result;
|
|
446
|
+
try {
|
|
447
|
+
result = await fn();
|
|
448
|
+
} catch (error) {
|
|
449
|
+
rollback();
|
|
450
|
+
throw error;
|
|
451
|
+
}
|
|
452
|
+
rollback();
|
|
453
|
+
return result;
|
|
454
|
+
};
|
|
455
|
+
const newTransactionHook = (readOnly) => (cb) => queue.run(async () => {
|
|
320
456
|
let finished = false;
|
|
321
|
-
|
|
457
|
+
let failed = false;
|
|
458
|
+
const run = (fn) => {
|
|
322
459
|
if (finished) throw new Error("db-sqlite: the transaction is finished; use the outer Db");
|
|
460
|
+
if (!readOnly) return fn();
|
|
461
|
+
if (failed) throw new Error(READ_ONLY_FAILED);
|
|
462
|
+
try {
|
|
463
|
+
return fn();
|
|
464
|
+
} catch (error) {
|
|
465
|
+
failed = true;
|
|
466
|
+
throw error;
|
|
467
|
+
}
|
|
323
468
|
};
|
|
324
469
|
const tx = {
|
|
325
470
|
async query(sql, params = []) {
|
|
326
|
-
|
|
327
|
-
|
|
471
|
+
return run(() => {
|
|
472
|
+
if (readOnly) checkReadOnly(sql);
|
|
473
|
+
return runAll(engine, sql, params);
|
|
474
|
+
});
|
|
328
475
|
},
|
|
329
476
|
async exec(sql) {
|
|
330
|
-
|
|
331
|
-
|
|
477
|
+
run(() => {
|
|
478
|
+
if (!readOnly) return runExec(engine, sql);
|
|
479
|
+
checkReadOnly(sql);
|
|
480
|
+
checkSql(sql, false);
|
|
481
|
+
for (const statement of splitSqlStatements(sql)) runAll(engine, statement, []);
|
|
482
|
+
});
|
|
332
483
|
},
|
|
333
484
|
async close() {
|
|
334
485
|
throw new Error("db-sqlite: close the outer Db, not the transaction handle");
|
|
335
486
|
}
|
|
336
487
|
};
|
|
337
488
|
try {
|
|
338
|
-
return await runTransaction(() => cb(tx));
|
|
489
|
+
return await (readOnly ? runReadOnlyTransaction : runTransaction)(() => cb(tx));
|
|
339
490
|
} finally {
|
|
340
491
|
finished = true;
|
|
341
492
|
}
|
|
@@ -344,10 +495,11 @@ function newSerialisedSqliteDb(engine) {
|
|
|
344
495
|
query: (sql, params = []) => queue.run(() => runAll(engine, sql, params)),
|
|
345
496
|
exec: (sql) => queue.run(() => runExec(engine, sql)),
|
|
346
497
|
close: () => queue.close(),
|
|
347
|
-
[SQLITE_TRANSACTION]:
|
|
498
|
+
[SQLITE_TRANSACTION]: newTransactionHook(false),
|
|
499
|
+
[SQLITE_READ_ONLY_TRANSACTION]: newTransactionHook(true)
|
|
348
500
|
};
|
|
349
501
|
}
|
|
350
502
|
//#endregion
|
|
351
|
-
export { SQLITE_TRANSACTION, inTransaction, newSerialisedDb, newSerialisedSqliteDb };
|
|
503
|
+
export { SQLITE_READ_ONLY_TRANSACTION, SQLITE_TRANSACTION, hasReadOnlyTransaction, inReadOnlyTransaction, inTransaction, newSerialisedDb, newSerialisedSqliteDb };
|
|
352
504
|
|
|
353
505
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/serialised-db.ts","../src/sql-statements.ts","../src/sqlite-transaction.ts","../src/serialised-sqlite-db.ts"],"sourcesContent":["import type { Db, DbEntry } from \"@statewalker/db-api\";\n\n/**\n * The calls of one `Db`, run one at a time in call order. Once `close()` has started, `run`\n * rejects at once with `<name>: the database is closed`; `close()` itself queues behind every\n * earlier call, closes the engine once, and returns the same promise to every later caller.\n */\nexport type DbCallQueue = {\n run<T>(fn: () => T | Promise<T>): Promise<T>;\n close(): Promise<void>;\n};\n\nexport function newDbCallQueue(name: string, closeEngine: () => void | Promise<void>): DbCallQueue {\n let tail: Promise<unknown> = Promise.resolve();\n let closing: Promise<void> | undefined;\n const enqueue = <T>(fn: () => T | Promise<T>): Promise<T> => {\n const result = tail.then(fn);\n tail = result.catch(() => undefined);\n return result;\n };\n return {\n run: (fn) =>\n closing ? Promise.reject(new Error(`${name}: the database is closed`)) : enqueue(fn),\n close: () => {\n closing ??= enqueue(closeEngine);\n return closing;\n },\n };\n}\n\nconst MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);\nconst MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);\n\nconst isPlainObject = (value: object): boolean => {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n};\n\n/** A bigint within ±(2^53 - 1) as a number; arrays and plain objects converted in place. */\nfunction safeInteger(value: unknown): unknown {\n if (typeof value === \"bigint\") {\n return value >= MIN_SAFE && value <= MAX_SAFE ? Number(value) : value;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) value[i] = safeInteger(value[i]);\n } else if (value !== null && typeof value === \"object\" && isPlainObject(value)) {\n const record = value as Record<string, unknown>;\n for (const key in record) record[key] = safeInteger(record[key]);\n }\n return value;\n}\n\n/**\n * Integers within ±(2^53 - 1) become numbers, larger ones stay bigints (no precision loss), in\n * every column and inside list, struct and map values. The rows are converted in place.\n */\nexport function toSafeIntegers<T extends Record<string, unknown>>(rows: T[]): T[] {\n for (const row of rows) {\n const record = row as Record<string, unknown>;\n for (const key in record) record[key] = safeInteger(record[key]);\n }\n return rows;\n}\n\n/**\n * The asynchronous engine a driver wraps with {@link newSerialisedDb}. It is called one call at a\n * time and never after `close`; `query` returns rows with integers as numbers or bigints (the\n * wrapper turns safe bigints into numbers).\n */\nexport type SerialisedDbEngine = {\n query(sql: string, params: unknown[]): Promise<Record<string, unknown>[]>;\n exec(sql: string): Promise<void>;\n flush?(): Promise<void>;\n close(): void | Promise<void>;\n};\n\n/**\n * Wrap an engine as a `Db` that keeps the lifecycle every driver shares: calls run one at a time,\n * in call order; `close()` waits for the calls made before it, then closes the engine; calls made\n * once `close()` has started reject with `<name>: the database is closed`; closing twice is a\n * no-op. Integers come back as numbers when safe and as bigints beyond (see\n * {@link toSafeIntegers}). `name` prefixes the error, e.g. `\"db-pglite\"`.\n */\nexport function newSerialisedDb(engine: SerialisedDbEngine, options: { name: string }): Db {\n const queue = newDbCallQueue(options.name, () => engine.close());\n const db: Db = {\n query: <T = DbEntry>(sql: string, params: unknown[] = []) =>\n queue.run(async () => toSafeIntegers(await engine.query(sql, params)) as T[]),\n exec: (sql: string) => queue.run(() => engine.exec(sql)),\n close: () => queue.close(),\n };\n const flush = engine.flush?.bind(engine);\n if (flush) db.flush = () => queue.run(flush);\n return db;\n}\n","/**\n * How many SQL statements a string holds, without running it: \"empty\" (only whitespace, comments\n * and semicolons), \"one\" (one statement, maybe followed by such a tail) or \"many\".\n *\n * A port of SQLite's own `sqlite3_complete()` state machine (src/complete.c): it knows string\n * literals ('…'), quoted identifiers (\"…\", `…`, […]), `--` and `/* … *\\/` comments, and that\n * the semicolons inside a `CREATE TRIGGER … BEGIN … END` body do not end the statement. An\n * unterminated literal is content (SQLite reports the syntax error); an unterminated comment runs\n * to the end of the text.\n */\nexport type SqlStatementCount = \"empty\" | \"one\" | \"many\";\n\nconst SEMI = 0;\nconst WS = 1;\nconst OTHER = 2;\nconst EXPLAIN = 3;\nconst CREATE = 4;\nconst TEMP = 5;\nconst TRIGGER = 6;\nconst END = 7;\n\n/** trans[state][token]; states 0 INVALID, 1 START, 2 NORMAL, 3 EXPLAIN, 4 CREATE, 5 TRIGGER, 6 SEMI, 7 END. */\nconst TRANS = [\n [1, 0, 2, 3, 4, 2, 2, 2],\n [1, 1, 2, 3, 4, 2, 2, 2],\n [1, 2, 2, 2, 2, 2, 2, 2],\n [1, 3, 3, 2, 4, 2, 2, 2],\n [1, 4, 2, 2, 2, 4, 5, 2],\n [6, 5, 5, 5, 5, 5, 5, 5],\n [6, 6, 5, 5, 5, 5, 5, 7],\n [1, 7, 5, 5, 5, 5, 5, 5],\n];\n\nconst KEYWORDS: Record<string, number> = {\n create: CREATE,\n temp: TEMP,\n temporary: TEMP,\n trigger: TRIGGER,\n end: END,\n explain: EXPLAIN,\n};\n\nconst isIdChar = (c: string) => /[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) >= 0x80;\n\nexport function countSqlStatements(sql: string): SqlStatementCount {\n return scanSqlStatements(sql).count;\n}\n\n/**\n * The first statement of `sql` without the semicolon that ends it and without the empty tail\n * after it (whitespace, comments, semicolons), for engines that reject such a tail (Durable\n * Object SQLite: \"SQL code did not contain a statement\"). Meant for SQL that\n * {@link countSqlStatements} counts as \"one\"; SQL without an ending semicolon comes back as is.\n */\nexport function firstSqlStatement(sql: string): string {\n const { firstEnd } = scanSqlStatements(sql);\n return firstEnd < 0 ? sql : sql.slice(0, firstEnd);\n}\n\nfunction scanSqlStatements(sql: string): { count: SqlStatementCount; firstEnd: number } {\n let firstEnd = -1; // index of the \";\" that ends the first statement\n let state = 0;\n let content = false; // a token other than whitespace or \";\" was seen\n let firstEnded = false; // the first statement with content has reached its \";\"\n let i = 0;\n const n = sql.length;\n while (i < n) {\n const c = sql[i] as string;\n let token: number;\n if (c === \";\") {\n token = SEMI;\n } else if (c === \" \" || c === \"\\t\" || c === \"\\n\" || c === \"\\r\" || c === \"\\f\") {\n token = WS;\n } else if (c === \"/\" && sql[i + 1] === \"*\") {\n const close = sql.indexOf(\"*/\", i + 2);\n if (close < 0) break; // an unterminated comment runs to the end, like whitespace\n i = close + 1;\n token = WS;\n } else if (c === \"-\" && sql[i + 1] === \"-\") {\n const eol = sql.indexOf(\"\\n\", i);\n if (eol < 0) break;\n i = eol;\n token = WS;\n } else if (c === \"[\" || c === \"`\" || c === '\"' || c === \"'\") {\n const close = sql.indexOf(c === \"[\" ? \"]\" : c, i + 1);\n if (close < 0) return { count: firstEnded ? \"many\" : \"one\", firstEnd };\n i = close;\n token = OTHER;\n } else if (isIdChar(c)) {\n let j = i + 1;\n while (j < n && isIdChar(sql[j] as string)) j++;\n token = KEYWORDS[sql.slice(i, j).toLowerCase()] ?? OTHER;\n i = j - 1;\n } else {\n token = OTHER;\n }\n if (token !== SEMI && token !== WS) {\n if (firstEnded) return { count: \"many\", firstEnd };\n content = true;\n }\n state = TRANS[state]?.[token] ?? 2;\n if (token === SEMI && state === 1 && content && !firstEnded) {\n firstEnded = true;\n firstEnd = i;\n }\n i++;\n }\n return { count: content ? \"one\" : \"empty\", firstEnd };\n}\n","import type { Db } from \"@statewalker/db-api\";\n\n/** Key under which a SQLite Db carries its transaction hook. Shared across bundles via Symbol.for. */\nexport const SQLITE_TRANSACTION: unique symbol = Symbol.for(\"@statewalker/db-sqlite:transaction\");\n\n/** Runs `cb` inside one transaction of the Db that carries it. */\nexport type SqliteTransactionHook = <T>(cb: (tx: Db) => Promise<T>) => Promise<T>;\n\nconst NO_HOOK =\n \"inTransaction: this Db has no SQLite transaction hook. It is not a @statewalker/db-sqlite* Db, \" +\n \"or it wraps one (a wrapper object loses the hook - pass the driver's Db itself), \" +\n \"or it is the handle of a running transaction (nesting is not supported).\";\n\n/**\n * Run `cb` in one SQLite transaction: every statement issued through `tx` commits together, or\n * none does if `cb` throws. Other calls on `db` wait until the transaction ends. `cb` must not do\n * external I/O and must be idempotent: a Durable Object may run it more than once.\n */\nexport function inTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T> {\n const hook = (db as { [SQLITE_TRANSACTION]?: SqliteTransactionHook })[SQLITE_TRANSACTION];\n if (typeof hook !== \"function\") return Promise.reject(new Error(NO_HOOK));\n return hook(cb);\n}\n","import type { Db, DbEntry } from \"@statewalker/db-api\";\nimport { newDbCallQueue, toSafeIntegers } from \"./serialised-db.js\";\nimport { countSqlStatements, firstSqlStatement } from \"./sql-statements.js\";\nimport { SQLITE_TRANSACTION, type SqliteTransactionHook } from \"./sqlite-transaction.js\";\n\n/**\n * The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array; integers\n * as numbers or bigints, which the wrapper turns into numbers when they are safe) and is given\n * exactly one non-empty statement and parameters already normalised and checked (only null,\n * number, bigint, string and Uint8Array); `exec` runs every statement of a non-empty string.\n * `transaction`, when present, replaces `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects\n * forbid them in SQL).\n */\nexport type SqliteEngine = {\n all(sql: string, params: unknown[]): Record<string, unknown>[];\n exec(sql: string): void;\n close(): void;\n transaction?<T>(fn: () => Promise<T>): Promise<T>;\n};\n\nconst EMPTY_SQL = \"db-sqlite: the SQL is empty (only whitespace, comments or semicolons)\";\nconst MANY_STATEMENTS =\n \"db-sqlite: query runs one statement, and this SQL has more after the first; \" +\n \"run them one query at a time, or use exec (no parameters, no rows)\";\n\nfunction checkSql(sql: string, one: boolean): void {\n if (typeof sql !== \"string\") throw new TypeError(\"db-sqlite: the SQL must be a string\");\n const count = countSqlStatements(sql);\n if (count === \"empty\") throw new Error(EMPTY_SQL);\n if (one && count === \"many\") throw new Error(MANY_STATEMENTS);\n}\n\n/** The type a rejected parameter is named by: `symbol`, `function`, or the object's class. */\nfunction typeName(value: unknown): string {\n if (typeof value !== \"object\" || value === null) return typeof value;\n const name = (value as { constructor?: { name?: unknown } }).constructor?.name;\n return typeof name === \"string\" && name ? name : \"Object\";\n}\n\n/**\n * boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text, ArrayBuffer or any ArrayBuffer view →\n * a Uint8Array over exactly its bytes; null, number, bigint and string are left as given. Anything\n * else (a plain object, Map, array, function, symbol, boxed primitive) rejects: node:sqlite would\n * take a leading object as named parameters and bind the rest one place to the left, and SQLite\n * has no array type (bind a list as JSON text and read it with `json_each`).\n */\nfunction toSqliteParam(value: unknown, index: number): unknown {\n if (value === null || typeof value === \"string\" || typeof value === \"number\") return value;\n if (typeof value === \"bigint\") return value;\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (value === undefined) return null;\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n throw new RangeError(`db-sqlite: parameter ${index + 1} is an invalid Date`);\n }\n return value.toISOString();\n }\n // node:sqlite (Node 22) binds a view over a buffer with no backing store (any zero-length\n // ArrayBuffer) as NULL: give an empty value a fresh empty Uint8Array, which binds as a BLOB.\n if ((ArrayBuffer.isView(value) || value instanceof ArrayBuffer) && value.byteLength === 0) {\n return new Uint8Array(1).subarray(0, 0);\n }\n if (value instanceof Uint8Array && value.constructor === Uint8Array) return value;\n if (ArrayBuffer.isView(value)) {\n return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n }\n if (value instanceof ArrayBuffer) return new Uint8Array(value);\n const hint = Array.isArray(value) ? \"; bind a list as JSON text and read it with json_each\" : \"\";\n throw new TypeError(\n `db-sqlite: parameter ${index + 1} has type ${typeName(value)}, which SQLite cannot bind; ` +\n \"pass null, undefined, a boolean, number, bigint, string, Date, ArrayBuffer or \" +\n `ArrayBuffer view${hint}`,\n );\n}\n\nfunction runAll(engine: SqliteEngine, sql: string, params: unknown[]): Record<string, unknown>[] {\n checkSql(sql, true);\n // Only the statement itself reaches the engine: DO SQLite rejects an empty tail (\"; -- c ;\").\n return toSafeIntegers(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));\n}\n\nfunction runExec(engine: SqliteEngine, sql: string): void {\n checkSql(sql, false);\n engine.exec(sql);\n}\n\n/**\n * Wrap an engine as a `Db` with the lifecycle of `newSerialisedDb` (calls run one at a time, in\n * call order; `close()` waits for earlier calls; later calls reject with\n * `db-sqlite: the database is closed`; closing twice is a no-op) and the `inTransaction` hook.\n * Every SQLite driver gets the same input handling here: empty SQL rejects, `query` rejects a\n * second statement, parameters are normalised (one SQLite cannot bind rejects) and safe integers come back as numbers. The `tx`\n * handed to a transaction callback bypasses the queue, has no hook (so nesting is rejected) and\n * rejects once its transaction has finished.\n */\nexport function newSerialisedSqliteDb(engine: SqliteEngine): Db {\n const queue = newDbCallQueue(\"db-sqlite\", () => engine.close());\n const runTransaction =\n engine.transaction?.bind(engine) ??\n (async <T>(fn: () => Promise<T>): Promise<T> => {\n engine.exec(\"BEGIN IMMEDIATE\");\n try {\n const result = await fn();\n engine.exec(\"COMMIT\");\n return result;\n } catch (error) {\n try {\n engine.exec(\"ROLLBACK\");\n } catch {\n // SQLite already ended the transaction itself (ON CONFLICT ROLLBACK, auto-rollback)\n }\n throw error;\n }\n });\n\n const transaction: SqliteTransactionHook = (cb) =>\n queue.run(async () => {\n let finished = false;\n const open = () => {\n if (finished) throw new Error(\"db-sqlite: the transaction is finished; use the outer Db\");\n };\n const tx: Db = {\n async query<T = DbEntry>(sql: string, params: unknown[] = []): Promise<T[]> {\n open();\n return runAll(engine, sql, params) as T[];\n },\n async exec(sql: string): Promise<void> {\n open();\n runExec(engine, sql);\n },\n async close(): Promise<void> {\n throw new Error(\"db-sqlite: close the outer Db, not the transaction handle\");\n },\n };\n try {\n return await runTransaction(() => cb(tx));\n } finally {\n finished = true;\n }\n });\n\n return {\n query: <T = DbEntry>(sql: string, params: unknown[] = []) =>\n queue.run(() => runAll(engine, sql, params) as T[]),\n exec: (sql: string) => queue.run(() => runExec(engine, sql)),\n close: () => queue.close(),\n [SQLITE_TRANSACTION]: transaction,\n } as Db;\n}\n"],"mappings":";AAYA,SAAgB,eAAe,MAAc,aAAsD;CACjG,IAAI,OAAyB,QAAQ,QAAQ;CAC7C,IAAI;CACJ,MAAM,WAAc,OAAyC;EAC3D,MAAM,SAAS,KAAK,KAAK,EAAE;EAC3B,OAAO,OAAO,YAAY,KAAA,CAAS;EACnC,OAAO;CACT;CACA,OAAO;EACL,MAAM,OACJ,UAAU,QAAQ,uBAAO,IAAI,MAAM,GAAG,KAAK,yBAAyB,CAAC,IAAI,QAAQ,EAAE;EACrF,aAAa;GACX,YAAY,QAAQ,WAAW;GAC/B,OAAO;EACT;CACF;AACF;AAEA,MAAM,WAAW,OAAO,OAAO,gBAAgB;AAC/C,MAAM,WAAW,OAAO,OAAO,gBAAgB;AAE/C,MAAM,iBAAiB,UAA2B;CAChD,MAAM,QAAQ,OAAO,eAAe,KAAK;CACzC,OAAO,UAAU,OAAO,aAAa,UAAU;AACjD;;AAGA,SAAS,YAAY,OAAyB;CAC5C,IAAI,OAAO,UAAU,UACnB,OAAO,SAAS,YAAY,SAAS,WAAW,OAAO,KAAK,IAAI;CAElE,IAAI,MAAM,QAAQ,KAAK,GACrB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MAAM,KAAK,YAAY,MAAM,EAAE;MACjE,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,cAAc,KAAK,GAAG;EAC9E,MAAM,SAAS;EACf,KAAK,MAAM,OAAO,QAAQ,OAAO,OAAO,YAAY,OAAO,IAAI;CACjE;CACA,OAAO;AACT;;;;;AAMA,SAAgB,eAAkD,MAAgB;CAChF,KAAK,MAAM,OAAO,MAAM;EAC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AAO;GACd,IAAI;IACF,OAAO,KAAK,UAAU;GACxB,QAAQ,CAER;GACA,MAAM;EACR;CACF;CAEF,MAAM,eAAsC,OAC1C,MAAM,IAAI,YAAY;EACpB,IAAI,WAAW;EACf,MAAM,aAAa;GACjB,IAAI,UAAU,MAAM,IAAI,MAAM,0DAA0D;EAC1F;EACA,MAAM,KAAS;GACb,MAAM,MAAmB,KAAa,SAAoB,CAAC,GAAiB;IAC1E,KAAK;IACL,OAAO,OAAO,QAAQ,KAAK,MAAM;GACnC;GACA,MAAM,KAAK,KAA4B;IACrC,KAAK;IACL,QAAQ,QAAQ,GAAG;GACrB;GACA,MAAM,QAAuB;IAC3B,MAAM,IAAI,MAAM,2DAA2D;GAC7E;EACF;EACA,IAAI;GACF,OAAO,MAAM,qBAAqB,GAAG,EAAE,CAAC;EAC1C,UAAU;GACR,WAAW;EACb;CACF,CAAC;CAEH,OAAO;EACL,QAAqB,KAAa,SAAoB,CAAC,MACrD,MAAM,UAAU,OAAO,QAAQ,KAAK,MAAM,CAAQ;EACpD,OAAO,QAAgB,MAAM,UAAU,QAAQ,QAAQ,GAAG,CAAC;EAC3D,aAAa,MAAM,MAAM;GACxB,qBAAqB;CACxB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/serialised-db.ts","../src/sql-statements.ts","../src/sqlite-transaction.ts","../src/serialised-sqlite-db.ts"],"sourcesContent":["import type { Db, DbEntry } from \"@statewalker/db-api\";\n\n/**\n * The calls of one `Db`, run one at a time in call order. Once `close()` has started, `run`\n * rejects at once with `<name>: the database is closed`; `close()` itself queues behind every\n * earlier call, closes the engine once, and returns the same promise to every later caller.\n */\nexport type DbCallQueue = {\n run<T>(fn: () => T | Promise<T>): Promise<T>;\n close(): Promise<void>;\n};\n\nexport function newDbCallQueue(name: string, closeEngine: () => void | Promise<void>): DbCallQueue {\n let tail: Promise<unknown> = Promise.resolve();\n let closing: Promise<void> | undefined;\n const enqueue = <T>(fn: () => T | Promise<T>): Promise<T> => {\n const result = tail.then(fn);\n tail = result.catch(() => undefined);\n return result;\n };\n return {\n run: (fn) =>\n closing ? Promise.reject(new Error(`${name}: the database is closed`)) : enqueue(fn),\n close: () => {\n closing ??= enqueue(closeEngine);\n return closing;\n },\n };\n}\n\nconst MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);\nconst MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);\n\nconst isPlainObject = (value: object): boolean => {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n};\n\n/** A bigint within ±(2^53 - 1) as a number; arrays and plain objects converted in place. */\nfunction safeInteger(value: unknown): unknown {\n if (typeof value === \"bigint\") {\n return value >= MIN_SAFE && value <= MAX_SAFE ? Number(value) : value;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) value[i] = safeInteger(value[i]);\n } else if (value !== null && typeof value === \"object\" && isPlainObject(value)) {\n const record = value as Record<string, unknown>;\n for (const key in record) record[key] = safeInteger(record[key]);\n }\n return value;\n}\n\n/**\n * Integers within ±(2^53 - 1) become numbers, larger ones stay bigints (no precision loss), in\n * every column and inside list, struct and map values. The rows are converted in place.\n */\nexport function toSafeIntegers<T extends Record<string, unknown>>(rows: T[]): T[] {\n for (const row of rows) {\n const record = row as Record<string, unknown>;\n for (const key in record) record[key] = safeInteger(record[key]);\n }\n return rows;\n}\n\n/**\n * The asynchronous engine a driver wraps with {@link newSerialisedDb}. It is called one call at a\n * time and never after `close`; `query` returns rows with integers as numbers or bigints (the\n * wrapper turns safe bigints into numbers).\n */\nexport type SerialisedDbEngine = {\n query(sql: string, params: unknown[]): Promise<Record<string, unknown>[]>;\n exec(sql: string): Promise<void>;\n flush?(): Promise<void>;\n close(): void | Promise<void>;\n};\n\n/**\n * Wrap an engine as a `Db` that keeps the lifecycle every driver shares: calls run one at a time,\n * in call order; `close()` waits for the calls made before it, then closes the engine; calls made\n * once `close()` has started reject with `<name>: the database is closed`; closing twice is a\n * no-op. Integers come back as numbers when safe and as bigints beyond (see\n * {@link toSafeIntegers}). `name` prefixes the error, e.g. `\"db-pglite\"`.\n */\nexport function newSerialisedDb(engine: SerialisedDbEngine, options: { name: string }): Db {\n const queue = newDbCallQueue(options.name, () => engine.close());\n const db: Db = {\n query: <T = DbEntry>(sql: string, params: unknown[] = []) =>\n queue.run(async () => toSafeIntegers(await engine.query(sql, params)) as T[]),\n exec: (sql: string) => queue.run(() => engine.exec(sql)),\n close: () => queue.close(),\n };\n const flush = engine.flush?.bind(engine);\n if (flush) db.flush = () => queue.run(flush);\n return db;\n}\n","/**\n * How many SQL statements a string holds, without running it: \"empty\" (only whitespace, comments\n * and semicolons), \"one\" (one statement, maybe followed by such a tail) or \"many\".\n *\n * A port of SQLite's own `sqlite3_complete()` state machine (src/complete.c): it knows string\n * literals ('…'), quoted identifiers (\"…\", `…`, […]), `--` and `/* … *\\/` comments, and that\n * the semicolons inside a `CREATE TRIGGER … BEGIN … END` body do not end the statement. An\n * unterminated literal is content (SQLite reports the syntax error); an unterminated comment runs\n * to the end of the text.\n */\nexport type SqlStatementCount = \"empty\" | \"one\" | \"many\";\n\nconst SEMI = 0;\nconst WS = 1;\nconst OTHER = 2;\nconst EXPLAIN = 3;\nconst CREATE = 4;\nconst TEMP = 5;\nconst TRIGGER = 6;\nconst END = 7;\n\n/** trans[state][token]; states 0 INVALID, 1 START, 2 NORMAL, 3 EXPLAIN, 4 CREATE, 5 TRIGGER, 6 SEMI, 7 END. */\nconst TRANS = [\n [1, 0, 2, 3, 4, 2, 2, 2],\n [1, 1, 2, 3, 4, 2, 2, 2],\n [1, 2, 2, 2, 2, 2, 2, 2],\n [1, 3, 3, 2, 4, 2, 2, 2],\n [1, 4, 2, 2, 2, 4, 5, 2],\n [6, 5, 5, 5, 5, 5, 5, 5],\n [6, 6, 5, 5, 5, 5, 5, 7],\n [1, 7, 5, 5, 5, 5, 5, 5],\n];\n\nconst KEYWORDS: Record<string, number> = {\n create: CREATE,\n temp: TEMP,\n temporary: TEMP,\n trigger: TRIGGER,\n end: END,\n explain: EXPLAIN,\n};\n\nconst isIdChar = (c: string) => /[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) >= 0x80;\n\n/** SQLite's whitespace (sqlite3Isspace): space, \\t, \\n, \\v, \\f, \\r. */\nconst isSpace = (c: string | undefined) =>\n c === \" \" || c === \"\\t\" || c === \"\\n\" || c === \"\\v\" || c === \"\\f\" || c === \"\\r\";\n\n/**\n * The end (exclusive) of a variable token starting at `i` (`$`, `:`, `@` or `#`), as SQLite's\n * tokenizer reads it: identifier characters and `::`, and the Tcl form `$name(…)`, which runs to\n * the first `)` (included) or whitespace, quotes and semicolons included.\n */\nfunction variableEnd(sql: string, i: number): number {\n let j = i + 1;\n let n = 0;\n while (j < sql.length) {\n const c = sql[j] as string;\n if (isIdChar(c)) {\n n++;\n j++;\n } else if (c === \"(\" && n > 0) {\n j++;\n while (j < sql.length && !isSpace(sql[j]) && sql[j] !== \")\") j++;\n if (sql[j] === \")\") j++;\n break;\n } else if (c === \":\" && sql[j + 1] === \":\") {\n j += 2;\n } else {\n break;\n }\n }\n return j;\n}\n\nexport function countSqlStatements(sql: string): SqlStatementCount {\n return scanSqlStatements(sql).count;\n}\n\n/**\n * The first statement of `sql` without the semicolon that ends it and without the empty tail\n * after it (whitespace, comments, semicolons), for engines that reject such a tail (Durable\n * Object SQLite: \"SQL code did not contain a statement\"). Meant for SQL that\n * {@link countSqlStatements} counts as \"one\"; SQL without an ending semicolon comes back as is.\n */\nexport function firstSqlStatement(sql: string): string {\n const { firstEnd } = scanSqlStatements(sql);\n return firstEnd < 0 ? sql : sql.slice(0, firstEnd);\n}\n\n/**\n * The first word of every statement of `sql`, lowercased, in order (\"\" for a statement that does\n * not start with a word, such as `(SELECT 1)`). Statements are split as SQLite splits them, so a\n * keyword inside a literal, a comment or a trigger body is not a head. Empty statements are\n * skipped.\n */\nexport function sqlStatementHeads(sql: string): string[] {\n return scanSqlStatements(sql).heads;\n}\n\n/**\n * The statements of `sql`, split as {@link sqlStatementHeads} splits them: each from its first\n * token to just before the semicolon that ends it (the last to the end of the text).\n */\nexport function splitSqlStatements(sql: string): string[] {\n return scanSqlStatements(sql).statements;\n}\n\nfunction scanSqlStatements(sql: string): {\n count: SqlStatementCount;\n firstEnd: number;\n heads: string[];\n statements: string[];\n} {\n const heads: string[] = [];\n const statements: string[] = [];\n let start = 0; // where the current statement's first token starts\n let firstEnd = -1; // index of the \";\" that ends the first statement\n let state = 0;\n let inStatement = false; // a token other than whitespace or \";\" was seen since the last end\n let i = 0;\n const n = sql.length;\n const result = () => ({\n count: (heads.length === 0\n ? \"empty\"\n : heads.length === 1\n ? \"one\"\n : \"many\") as SqlStatementCount,\n firstEnd,\n heads,\n statements: inStatement ? [...statements, sql.slice(start)] : statements,\n });\n while (i < n) {\n const c = sql[i] as string;\n const tokenStart = i;\n let token: number;\n let word = \"\";\n if (c === \";\") {\n token = SEMI;\n } else if (isSpace(c)) {\n token = WS;\n } else if (c === \"/\" && sql[i + 1] === \"*\") {\n const close = sql.indexOf(\"*/\", i + 2);\n if (close < 0) break; // an unterminated comment runs to the end, like whitespace\n i = close + 1;\n token = WS;\n } else if (c === \"-\" && sql[i + 1] === \"-\") {\n const eol = sql.indexOf(\"\\n\", i);\n if (eol < 0) break;\n i = eol;\n token = WS;\n } else if (c === \"[\" || c === \"`\" || c === '\"' || c === \"'\") {\n const close = sql.indexOf(c === \"[\" ? \"]\" : c, i + 1);\n if (close < 0) {\n // An unterminated literal runs to the end: content, which SQLite reports as an error.\n if (!inStatement) {\n heads.push(\"\");\n start = tokenStart;\n inStatement = true;\n }\n return result();\n }\n i = close;\n token = OTHER;\n } else if (c === \"$\" || c === \":\" || c === \"@\" || c === \"#\") {\n // A variable, not a word: SQLite reads `$a(';x')` as one token, quotes and all.\n i = variableEnd(sql, i) - 1;\n token = OTHER;\n } else if (isIdChar(c)) {\n let j = i + 1;\n while (j < n && isIdChar(sql[j] as string)) j++;\n word = sql.slice(i, j).toLowerCase();\n token = KEYWORDS[word] ?? OTHER;\n i = j - 1;\n } else {\n token = OTHER;\n }\n if (token !== SEMI && token !== WS && !inStatement) {\n inStatement = true;\n heads.push(word);\n start = tokenStart;\n }\n state = TRANS[state]?.[token] ?? 2;\n if (token === SEMI && state === 1 && inStatement) {\n inStatement = false;\n statements.push(sql.slice(start, i));\n if (firstEnd < 0) firstEnd = i;\n }\n i++;\n }\n return result();\n}\n","import type { Db } from \"@statewalker/db-api\";\n\n/** Key under which a SQLite Db carries its transaction hook. Shared across bundles via Symbol.for. */\nexport const SQLITE_TRANSACTION: unique symbol = Symbol.for(\"@statewalker/db-sqlite:transaction\");\n\n/**\n * Key under which a SQLite Db carries its read-only transaction hook (a separate key, so that a Db\n * from an older db-sqlite, which has only the committing hook, is refused rather than committed).\n */\nexport const SQLITE_READ_ONLY_TRANSACTION: unique symbol = Symbol.for(\n \"@statewalker/db-sqlite:read-only-transaction\",\n);\n\n/** Runs `cb` inside one transaction of the Db that carries it. */\nexport type SqliteTransactionHook = <T>(cb: (tx: Db) => Promise<T>) => Promise<T>;\n\nconst NO_HOOK =\n \"inTransaction: this Db has no SQLite transaction hook. It is not a @statewalker/db-sqlite* Db, \" +\n \"or it wraps one (a wrapper object loses the hook - pass the driver's Db itself), \" +\n \"or it is the handle of a running transaction (nesting is not supported).\";\n\n/**\n * Run `cb` in one SQLite transaction: every statement issued through `tx` commits together, or\n * none does if `cb` throws. Other calls on `db` wait until the transaction ends. `cb` must not do\n * external I/O and must be idempotent: a Durable Object may run it more than once.\n */\nexport function inTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T> {\n const hook = (db as { [SQLITE_TRANSACTION]?: SqliteTransactionHook })[SQLITE_TRANSACTION];\n if (typeof hook !== \"function\") return Promise.reject(new Error(NO_HOOK));\n return hook(cb);\n}\n\nconst NO_READ_ONLY_HOOK =\n \"inReadOnlyTransaction: this Db has no SQLite read-only transaction hook. It is not a \" +\n \"@statewalker/db-sqlite* Db (or one from a db-sqlite older than 0.1.4), \" +\n \"or it wraps one (a wrapper object loses the hook - pass the driver's Db itself), \" +\n \"or it is the handle of a running transaction (nesting is not supported).\";\n\n/**\n * Run `cb` in one SQLite transaction that is always rolled back: `tx` sees the committed data and\n * its own writes, and nothing it writes persists, whether `cb` returns (its value is returned) or\n * throws (its error is rethrown). Statements that would end the transaction or reach outside it\n * (BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, RELEASE, ATTACH, DETACH, PRAGMA, VACUUM) are refused,\n * and once a statement fails, `tx` refuses every later call (SQLite may have ended the transaction\n * itself, as `INSERT OR ROLLBACK` does). Other calls on `db` wait until it ends. `cb` must not do\n * external I/O and must be idempotent: a Durable Object may run it more than once.\n */\nexport function inReadOnlyTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T> {\n const hook = (db as { [SQLITE_READ_ONLY_TRANSACTION]?: SqliteTransactionHook })[\n SQLITE_READ_ONLY_TRANSACTION\n ];\n if (typeof hook !== \"function\") return Promise.reject(new Error(NO_READ_ONLY_HOOK));\n return hook(cb);\n}\n\n/** Whether `db` carries the hook {@link inReadOnlyTransaction} needs. */\nexport function hasReadOnlyTransaction(db: Db): boolean {\n return (\n typeof (db as { [SQLITE_READ_ONLY_TRANSACTION]?: unknown })[SQLITE_READ_ONLY_TRANSACTION] ===\n \"function\"\n );\n}\n","import type { Db, DbEntry } from \"@statewalker/db-api\";\nimport { newDbCallQueue, toSafeIntegers } from \"./serialised-db.js\";\nimport {\n countSqlStatements,\n firstSqlStatement,\n splitSqlStatements,\n sqlStatementHeads,\n} from \"./sql-statements.js\";\nimport {\n SQLITE_READ_ONLY_TRANSACTION,\n SQLITE_TRANSACTION,\n type SqliteTransactionHook,\n} from \"./sqlite-transaction.js\";\n\n/**\n * The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array; integers\n * as numbers or bigints, which the wrapper turns into numbers when they are safe) and is given\n * exactly one non-empty statement and parameters already normalised and checked (only null,\n * number, bigint, string and Uint8Array); `exec` runs every statement of a non-empty string.\n * `transaction`, when present, replaces `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects\n * forbid them in SQL).\n */\nexport type SqliteEngine = {\n all(sql: string, params: unknown[]): Record<string, unknown>[];\n exec(sql: string): void;\n close(): void;\n transaction?<T>(fn: () => Promise<T>): Promise<T>;\n};\n\nconst EMPTY_SQL = \"db-sqlite: the SQL is empty (only whitespace, comments or semicolons)\";\nconst MANY_STATEMENTS =\n \"db-sqlite: query runs one statement, and this SQL has more after the first; \" +\n \"run them one query at a time, or use exec (no parameters, no rows)\";\n\nfunction checkSql(sql: string, one: boolean): void {\n if (typeof sql !== \"string\") throw new TypeError(\"db-sqlite: the SQL must be a string\");\n const count = countSqlStatements(sql);\n if (count === \"empty\") throw new Error(EMPTY_SQL);\n if (one && count === \"many\") throw new Error(MANY_STATEMENTS);\n}\n\n/** The type a rejected parameter is named by: `symbol`, `function`, or the object's class. */\nfunction typeName(value: unknown): string {\n if (typeof value !== \"object\" || value === null) return typeof value;\n const name = (value as { constructor?: { name?: unknown } }).constructor?.name;\n return typeof name === \"string\" && name ? name : \"Object\";\n}\n\n/**\n * boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text, ArrayBuffer or any ArrayBuffer view →\n * a Uint8Array over exactly its bytes; null, number, bigint and string are left as given. Anything\n * else (a plain object, Map, array, function, symbol, boxed primitive) rejects: node:sqlite would\n * take a leading object as named parameters and bind the rest one place to the left, and SQLite\n * has no array type (bind a list as JSON text and read it with `json_each`).\n */\nfunction toSqliteParam(value: unknown, index: number): unknown {\n if (value === null || typeof value === \"string\" || typeof value === \"number\") return value;\n if (typeof value === \"bigint\") return value;\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (value === undefined) return null;\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n throw new RangeError(`db-sqlite: parameter ${index + 1} is an invalid Date`);\n }\n return value.toISOString();\n }\n // node:sqlite (Node 22) binds a view over a buffer with no backing store (any zero-length\n // ArrayBuffer) as NULL: give an empty value a fresh empty Uint8Array, which binds as a BLOB.\n if ((ArrayBuffer.isView(value) || value instanceof ArrayBuffer) && value.byteLength === 0) {\n return new Uint8Array(1).subarray(0, 0);\n }\n if (value instanceof Uint8Array && value.constructor === Uint8Array) return value;\n if (ArrayBuffer.isView(value)) {\n return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n }\n if (value instanceof ArrayBuffer) return new Uint8Array(value);\n const hint = Array.isArray(value) ? \"; bind a list as JSON text and read it with json_each\" : \"\";\n throw new TypeError(\n `db-sqlite: parameter ${index + 1} has type ${typeName(value)}, which SQLite cannot bind; ` +\n \"pass null, undefined, a boolean, number, bigint, string, Date, ArrayBuffer or \" +\n `ArrayBuffer view${hint}`,\n );\n}\n\nfunction runAll(engine: SqliteEngine, sql: string, params: unknown[]): Record<string, unknown>[] {\n checkSql(sql, true);\n // Only the statement itself reaches the engine: DO SQLite rejects an empty tail (\"; -- c ;\").\n return toSafeIntegers(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));\n}\n\nfunction runExec(engine: SqliteEngine, sql: string): void {\n checkSql(sql, false);\n engine.exec(sql);\n}\n\n/** Statements a read-only transaction refuses: they end it, or reach outside it. */\nconst READ_ONLY_REFUSED = new Set([\n \"begin\",\n \"commit\",\n \"end\",\n \"rollback\",\n \"savepoint\",\n \"release\",\n \"attach\",\n \"detach\",\n \"pragma\",\n \"vacuum\",\n]);\n\nfunction checkReadOnly(sql: string): void {\n if (typeof sql !== \"string\") return; // checkSql reports it\n for (const head of sqlStatementHeads(sql)) {\n // A statement that does not start with a word is refused too: where this scanner and SQLite\n // could disagree on where a statement starts, the word SQLite sees is never checked.\n if (head === \"\") {\n throw new Error(\n \"db-sqlite: a read-only transaction refuses a statement that does not start with a keyword\",\n );\n }\n if (READ_ONLY_REFUSED.has(head)) {\n throw new Error(\n `db-sqlite: a read-only transaction refuses ${head.toUpperCase()} ` +\n \"(it would end the transaction or reach outside it)\",\n );\n }\n }\n}\n\nconst READ_ONLY_FAILED =\n \"db-sqlite: a statement of this read-only transaction failed, so it refuses later calls \" +\n \"(SQLite may have ended the transaction)\";\nconst ROLLBACK_ON_PURPOSE = \"db-sqlite: the read-only transaction is rolled back\";\n\n/**\n * Wrap an engine as a `Db` with the lifecycle of `newSerialisedDb` (calls run one at a time, in\n * call order; `close()` waits for earlier calls; later calls reject with\n * `db-sqlite: the database is closed`; closing twice is a no-op) and the `inTransaction` hook.\n * Every SQLite driver gets the same input handling here: empty SQL rejects, `query` rejects a\n * second statement, parameters are normalised (one SQLite cannot bind rejects) and safe integers come back as numbers. The `tx`\n * handed to a transaction callback bypasses the queue, has no hook (so nesting is rejected) and\n * rejects once its transaction has finished.\n */\nexport function newSerialisedSqliteDb(engine: SqliteEngine): Db {\n const queue = newDbCallQueue(\"db-sqlite\", () => engine.close());\n const runTransaction =\n engine.transaction?.bind(engine) ??\n (async <T>(fn: () => Promise<T>): Promise<T> => {\n engine.exec(\"BEGIN IMMEDIATE\");\n try {\n const result = await fn();\n engine.exec(\"COMMIT\");\n return result;\n } catch (error) {\n try {\n engine.exec(\"ROLLBACK\");\n } catch {\n // SQLite already ended the transaction itself (ON CONFLICT ROLLBACK, auto-rollback)\n }\n throw error;\n }\n });\n\n const platformTransaction = engine.transaction?.bind(engine);\n const runReadOnlyTransaction = platformTransaction\n ? async <T>(fn: () => Promise<T>): Promise<T> => {\n // The platform commits when the closure returns: throw to make it roll back.\n let result: T | undefined;\n let returned = false;\n try {\n await platformTransaction(async () => {\n returned = false;\n result = await fn();\n returned = true;\n throw new Error(ROLLBACK_ON_PURPOSE);\n });\n } catch (error) {\n if (returned && error instanceof Error && error.message === ROLLBACK_ON_PURPOSE) {\n return result as T;\n }\n throw error;\n }\n throw new Error(\"db-sqlite: the platform did not roll back the read-only transaction\");\n }\n : async <T>(fn: () => Promise<T>): Promise<T> => {\n // A ROLLBACK that fails for any reason but \"no transaction\" (SQLite ended it itself, as\n // INSERT OR ROLLBACK does: nothing to undo) leaves the transaction open: report it.\n const rollback = () => {\n try {\n engine.exec(\"ROLLBACK\");\n } catch (error) {\n if (!/no transaction is active/i.test(String((error as Error)?.message))) throw error;\n }\n };\n engine.exec(\"BEGIN\");\n let result: T;\n try {\n result = await fn();\n } catch (error) {\n rollback();\n throw error;\n }\n rollback();\n return result;\n };\n\n const newTransactionHook =\n (readOnly: boolean): SqliteTransactionHook =>\n (cb) =>\n queue.run(async () => {\n let finished = false;\n let failed = false;\n const run = <R>(fn: () => R): R => {\n if (finished) throw new Error(\"db-sqlite: the transaction is finished; use the outer Db\");\n if (!readOnly) return fn();\n if (failed) throw new Error(READ_ONLY_FAILED);\n try {\n return fn();\n } catch (error) {\n failed = true;\n throw error;\n }\n };\n const tx: Db = {\n async query<T = DbEntry>(sql: string, params: unknown[] = []): Promise<T[]> {\n return run(() => {\n if (readOnly) checkReadOnly(sql);\n return runAll(engine, sql, params) as T[];\n });\n },\n async exec(sql: string): Promise<void> {\n run(() => {\n if (!readOnly) return runExec(engine, sql);\n checkReadOnly(sql);\n checkSql(sql, false);\n // One statement per engine call, through `all`, which runs exactly one (node:sqlite\n // compiles only the first): text the splitter might misread as part of a statement\n // never runs as a statement of its own, whatever it says.\n for (const statement of splitSqlStatements(sql)) runAll(engine, statement, []);\n });\n },\n async close(): Promise<void> {\n throw new Error(\"db-sqlite: close the outer Db, not the transaction handle\");\n },\n };\n try {\n return await (readOnly ? runReadOnlyTransaction : runTransaction)(() => cb(tx));\n } finally {\n finished = true;\n }\n });\n\n return {\n query: <T = DbEntry>(sql: string, params: unknown[] = []) =>\n queue.run(() => runAll(engine, sql, params) as T[]),\n exec: (sql: string) => queue.run(() => runExec(engine, sql)),\n close: () => queue.close(),\n [SQLITE_TRANSACTION]: newTransactionHook(false),\n [SQLITE_READ_ONLY_TRANSACTION]: newTransactionHook(true),\n } as Db;\n}\n"],"mappings":";AAYA,SAAgB,eAAe,MAAc,aAAsD;CACjG,IAAI,OAAyB,QAAQ,QAAQ;CAC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AAI,MAAM,gBAAgB;GAC5C,IAAI;IACF,OAAO,GAAG;GACZ,SAAS,OAAO;IACd,SAAS;IACT,MAAM;GACR;EACF;EACA,MAAM,KAAS;GACb,MAAM,MAAmB,KAAa,SAAoB,CAAC,GAAiB;IAC1E,OAAO,UAAU;KACf,IAAI,UAAU,cAAc,GAAG;KAC/B,OAAO,OAAO,QAAQ,KAAK,MAAM;IACnC,CAAC;GACH;GACA,MAAM,KAAK,KAA4B;IACrC,UAAU;KACR,IAAI,CAAC,UAAU,OAAO,QAAQ,QAAQ,GAAG;KACzC,cAAc,GAAG;KACjB,SAAS,KAAK,KAAK;KAInB,KAAK,MAAM,aAAa,mBAAmB,GAAG,GAAG,OAAO,QAAQ,WAAW,CAAC,CAAC;IAC/E,CAAC;GACH;GACA,MAAM,QAAuB;IAC3B,MAAM,IAAI,MAAM,2DAA2D;GAC7E;EACF;EACA,IAAI;GACF,OAAO,OAAO,WAAW,yBAAyB,eAAA,OAAsB,GAAG,EAAE,CAAC;EAChF,UAAU;GACR,WAAW;EACb;CACF,CAAC;CAEL,OAAO;EACL,QAAqB,KAAa,SAAoB,CAAC,MACrD,MAAM,UAAU,OAAO,QAAQ,KAAK,MAAM,CAAQ;EACpD,OAAO,QAAgB,MAAM,UAAU,QAAQ,QAAQ,GAAG,CAAC;EAC3D,aAAa,MAAM,MAAM;GACxB,qBAAqB,mBAAmB,KAAK;GAC7C,+BAA+B,mBAAmB,IAAI;CACzD;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@statewalker/db-sqlite",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "SQLite transactions for @statewalker/db-api: inTransaction(db, cb), and the serialised Db wrappers every driver builds its lifecycle on.",
|
package/src/index.ts
CHANGED
|
@@ -7,7 +7,10 @@ export {
|
|
|
7
7
|
type SqliteEngine,
|
|
8
8
|
} from "./serialised-sqlite-db.js";
|
|
9
9
|
export {
|
|
10
|
+
hasReadOnlyTransaction,
|
|
11
|
+
inReadOnlyTransaction,
|
|
10
12
|
inTransaction,
|
|
13
|
+
SQLITE_READ_ONLY_TRANSACTION,
|
|
11
14
|
SQLITE_TRANSACTION,
|
|
12
15
|
type SqliteTransactionHook,
|
|
13
16
|
} from "./sqlite-transaction.js";
|
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
import type { Db, DbEntry } from "@statewalker/db-api";
|
|
2
2
|
import { newDbCallQueue, toSafeIntegers } from "./serialised-db.js";
|
|
3
|
-
import {
|
|
4
|
-
|
|
3
|
+
import {
|
|
4
|
+
countSqlStatements,
|
|
5
|
+
firstSqlStatement,
|
|
6
|
+
splitSqlStatements,
|
|
7
|
+
sqlStatementHeads,
|
|
8
|
+
} from "./sql-statements.js";
|
|
9
|
+
import {
|
|
10
|
+
SQLITE_READ_ONLY_TRANSACTION,
|
|
11
|
+
SQLITE_TRANSACTION,
|
|
12
|
+
type SqliteTransactionHook,
|
|
13
|
+
} from "./sqlite-transaction.js";
|
|
5
14
|
|
|
6
15
|
/**
|
|
7
16
|
* The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array; integers
|
|
@@ -84,6 +93,44 @@ function runExec(engine: SqliteEngine, sql: string): void {
|
|
|
84
93
|
engine.exec(sql);
|
|
85
94
|
}
|
|
86
95
|
|
|
96
|
+
/** Statements a read-only transaction refuses: they end it, or reach outside it. */
|
|
97
|
+
const READ_ONLY_REFUSED = new Set([
|
|
98
|
+
"begin",
|
|
99
|
+
"commit",
|
|
100
|
+
"end",
|
|
101
|
+
"rollback",
|
|
102
|
+
"savepoint",
|
|
103
|
+
"release",
|
|
104
|
+
"attach",
|
|
105
|
+
"detach",
|
|
106
|
+
"pragma",
|
|
107
|
+
"vacuum",
|
|
108
|
+
]);
|
|
109
|
+
|
|
110
|
+
function checkReadOnly(sql: string): void {
|
|
111
|
+
if (typeof sql !== "string") return; // checkSql reports it
|
|
112
|
+
for (const head of sqlStatementHeads(sql)) {
|
|
113
|
+
// A statement that does not start with a word is refused too: where this scanner and SQLite
|
|
114
|
+
// could disagree on where a statement starts, the word SQLite sees is never checked.
|
|
115
|
+
if (head === "") {
|
|
116
|
+
throw new Error(
|
|
117
|
+
"db-sqlite: a read-only transaction refuses a statement that does not start with a keyword",
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
if (READ_ONLY_REFUSED.has(head)) {
|
|
121
|
+
throw new Error(
|
|
122
|
+
`db-sqlite: a read-only transaction refuses ${head.toUpperCase()} ` +
|
|
123
|
+
"(it would end the transaction or reach outside it)",
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const READ_ONLY_FAILED =
|
|
130
|
+
"db-sqlite: a statement of this read-only transaction failed, so it refuses later calls " +
|
|
131
|
+
"(SQLite may have ended the transaction)";
|
|
132
|
+
const ROLLBACK_ON_PURPOSE = "db-sqlite: the read-only transaction is rolled back";
|
|
133
|
+
|
|
87
134
|
/**
|
|
88
135
|
* Wrap an engine as a `Db` with the lifecycle of `newSerialisedDb` (calls run one at a time, in
|
|
89
136
|
* call order; `close()` waits for earlier calls; later calls reject with
|
|
@@ -113,37 +160,101 @@ export function newSerialisedSqliteDb(engine: SqliteEngine): Db {
|
|
|
113
160
|
}
|
|
114
161
|
});
|
|
115
162
|
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
return await runTransaction(() => cb(tx));
|
|
137
|
-
} finally {
|
|
138
|
-
finished = true;
|
|
163
|
+
const platformTransaction = engine.transaction?.bind(engine);
|
|
164
|
+
const runReadOnlyTransaction = platformTransaction
|
|
165
|
+
? async <T>(fn: () => Promise<T>): Promise<T> => {
|
|
166
|
+
// The platform commits when the closure returns: throw to make it roll back.
|
|
167
|
+
let result: T | undefined;
|
|
168
|
+
let returned = false;
|
|
169
|
+
try {
|
|
170
|
+
await platformTransaction(async () => {
|
|
171
|
+
returned = false;
|
|
172
|
+
result = await fn();
|
|
173
|
+
returned = true;
|
|
174
|
+
throw new Error(ROLLBACK_ON_PURPOSE);
|
|
175
|
+
});
|
|
176
|
+
} catch (error) {
|
|
177
|
+
if (returned && error instanceof Error && error.message === ROLLBACK_ON_PURPOSE) {
|
|
178
|
+
return result as T;
|
|
179
|
+
}
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
throw new Error("db-sqlite: the platform did not roll back the read-only transaction");
|
|
139
183
|
}
|
|
140
|
-
|
|
184
|
+
: async <T>(fn: () => Promise<T>): Promise<T> => {
|
|
185
|
+
// A ROLLBACK that fails for any reason but "no transaction" (SQLite ended it itself, as
|
|
186
|
+
// INSERT OR ROLLBACK does: nothing to undo) leaves the transaction open: report it.
|
|
187
|
+
const rollback = () => {
|
|
188
|
+
try {
|
|
189
|
+
engine.exec("ROLLBACK");
|
|
190
|
+
} catch (error) {
|
|
191
|
+
if (!/no transaction is active/i.test(String((error as Error)?.message))) throw error;
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
engine.exec("BEGIN");
|
|
195
|
+
let result: T;
|
|
196
|
+
try {
|
|
197
|
+
result = await fn();
|
|
198
|
+
} catch (error) {
|
|
199
|
+
rollback();
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
rollback();
|
|
203
|
+
return result;
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
const newTransactionHook =
|
|
207
|
+
(readOnly: boolean): SqliteTransactionHook =>
|
|
208
|
+
(cb) =>
|
|
209
|
+
queue.run(async () => {
|
|
210
|
+
let finished = false;
|
|
211
|
+
let failed = false;
|
|
212
|
+
const run = <R>(fn: () => R): R => {
|
|
213
|
+
if (finished) throw new Error("db-sqlite: the transaction is finished; use the outer Db");
|
|
214
|
+
if (!readOnly) return fn();
|
|
215
|
+
if (failed) throw new Error(READ_ONLY_FAILED);
|
|
216
|
+
try {
|
|
217
|
+
return fn();
|
|
218
|
+
} catch (error) {
|
|
219
|
+
failed = true;
|
|
220
|
+
throw error;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
const tx: Db = {
|
|
224
|
+
async query<T = DbEntry>(sql: string, params: unknown[] = []): Promise<T[]> {
|
|
225
|
+
return run(() => {
|
|
226
|
+
if (readOnly) checkReadOnly(sql);
|
|
227
|
+
return runAll(engine, sql, params) as T[];
|
|
228
|
+
});
|
|
229
|
+
},
|
|
230
|
+
async exec(sql: string): Promise<void> {
|
|
231
|
+
run(() => {
|
|
232
|
+
if (!readOnly) return runExec(engine, sql);
|
|
233
|
+
checkReadOnly(sql);
|
|
234
|
+
checkSql(sql, false);
|
|
235
|
+
// One statement per engine call, through `all`, which runs exactly one (node:sqlite
|
|
236
|
+
// compiles only the first): text the splitter might misread as part of a statement
|
|
237
|
+
// never runs as a statement of its own, whatever it says.
|
|
238
|
+
for (const statement of splitSqlStatements(sql)) runAll(engine, statement, []);
|
|
239
|
+
});
|
|
240
|
+
},
|
|
241
|
+
async close(): Promise<void> {
|
|
242
|
+
throw new Error("db-sqlite: close the outer Db, not the transaction handle");
|
|
243
|
+
},
|
|
244
|
+
};
|
|
245
|
+
try {
|
|
246
|
+
return await (readOnly ? runReadOnlyTransaction : runTransaction)(() => cb(tx));
|
|
247
|
+
} finally {
|
|
248
|
+
finished = true;
|
|
249
|
+
}
|
|
250
|
+
});
|
|
141
251
|
|
|
142
252
|
return {
|
|
143
253
|
query: <T = DbEntry>(sql: string, params: unknown[] = []) =>
|
|
144
254
|
queue.run(() => runAll(engine, sql, params) as T[]),
|
|
145
255
|
exec: (sql: string) => queue.run(() => runExec(engine, sql)),
|
|
146
256
|
close: () => queue.close(),
|
|
147
|
-
[SQLITE_TRANSACTION]:
|
|
257
|
+
[SQLITE_TRANSACTION]: newTransactionHook(false),
|
|
258
|
+
[SQLITE_READ_ONLY_TRANSACTION]: newTransactionHook(true),
|
|
148
259
|
} as Db;
|
|
149
260
|
}
|
package/src/sql-statements.ts
CHANGED
|
@@ -42,6 +42,37 @@ const KEYWORDS: Record<string, number> = {
|
|
|
42
42
|
|
|
43
43
|
const isIdChar = (c: string) => /[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) >= 0x80;
|
|
44
44
|
|
|
45
|
+
/** SQLite's whitespace (sqlite3Isspace): space, \t, \n, \v, \f, \r. */
|
|
46
|
+
const isSpace = (c: string | undefined) =>
|
|
47
|
+
c === " " || c === "\t" || c === "\n" || c === "\v" || c === "\f" || c === "\r";
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The end (exclusive) of a variable token starting at `i` (`$`, `:`, `@` or `#`), as SQLite's
|
|
51
|
+
* tokenizer reads it: identifier characters and `::`, and the Tcl form `$name(…)`, which runs to
|
|
52
|
+
* the first `)` (included) or whitespace, quotes and semicolons included.
|
|
53
|
+
*/
|
|
54
|
+
function variableEnd(sql: string, i: number): number {
|
|
55
|
+
let j = i + 1;
|
|
56
|
+
let n = 0;
|
|
57
|
+
while (j < sql.length) {
|
|
58
|
+
const c = sql[j] as string;
|
|
59
|
+
if (isIdChar(c)) {
|
|
60
|
+
n++;
|
|
61
|
+
j++;
|
|
62
|
+
} else if (c === "(" && n > 0) {
|
|
63
|
+
j++;
|
|
64
|
+
while (j < sql.length && !isSpace(sql[j]) && sql[j] !== ")") j++;
|
|
65
|
+
if (sql[j] === ")") j++;
|
|
66
|
+
break;
|
|
67
|
+
} else if (c === ":" && sql[j + 1] === ":") {
|
|
68
|
+
j += 2;
|
|
69
|
+
} else {
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return j;
|
|
74
|
+
}
|
|
75
|
+
|
|
45
76
|
export function countSqlStatements(sql: string): SqlStatementCount {
|
|
46
77
|
return scanSqlStatements(sql).count;
|
|
47
78
|
}
|
|
@@ -57,19 +88,56 @@ export function firstSqlStatement(sql: string): string {
|
|
|
57
88
|
return firstEnd < 0 ? sql : sql.slice(0, firstEnd);
|
|
58
89
|
}
|
|
59
90
|
|
|
60
|
-
|
|
91
|
+
/**
|
|
92
|
+
* The first word of every statement of `sql`, lowercased, in order ("" for a statement that does
|
|
93
|
+
* not start with a word, such as `(SELECT 1)`). Statements are split as SQLite splits them, so a
|
|
94
|
+
* keyword inside a literal, a comment or a trigger body is not a head. Empty statements are
|
|
95
|
+
* skipped.
|
|
96
|
+
*/
|
|
97
|
+
export function sqlStatementHeads(sql: string): string[] {
|
|
98
|
+
return scanSqlStatements(sql).heads;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The statements of `sql`, split as {@link sqlStatementHeads} splits them: each from its first
|
|
103
|
+
* token to just before the semicolon that ends it (the last to the end of the text).
|
|
104
|
+
*/
|
|
105
|
+
export function splitSqlStatements(sql: string): string[] {
|
|
106
|
+
return scanSqlStatements(sql).statements;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function scanSqlStatements(sql: string): {
|
|
110
|
+
count: SqlStatementCount;
|
|
111
|
+
firstEnd: number;
|
|
112
|
+
heads: string[];
|
|
113
|
+
statements: string[];
|
|
114
|
+
} {
|
|
115
|
+
const heads: string[] = [];
|
|
116
|
+
const statements: string[] = [];
|
|
117
|
+
let start = 0; // where the current statement's first token starts
|
|
61
118
|
let firstEnd = -1; // index of the ";" that ends the first statement
|
|
62
119
|
let state = 0;
|
|
63
|
-
let
|
|
64
|
-
let firstEnded = false; // the first statement with content has reached its ";"
|
|
120
|
+
let inStatement = false; // a token other than whitespace or ";" was seen since the last end
|
|
65
121
|
let i = 0;
|
|
66
122
|
const n = sql.length;
|
|
123
|
+
const result = () => ({
|
|
124
|
+
count: (heads.length === 0
|
|
125
|
+
? "empty"
|
|
126
|
+
: heads.length === 1
|
|
127
|
+
? "one"
|
|
128
|
+
: "many") as SqlStatementCount,
|
|
129
|
+
firstEnd,
|
|
130
|
+
heads,
|
|
131
|
+
statements: inStatement ? [...statements, sql.slice(start)] : statements,
|
|
132
|
+
});
|
|
67
133
|
while (i < n) {
|
|
68
134
|
const c = sql[i] as string;
|
|
135
|
+
const tokenStart = i;
|
|
69
136
|
let token: number;
|
|
137
|
+
let word = "";
|
|
70
138
|
if (c === ";") {
|
|
71
139
|
token = SEMI;
|
|
72
|
-
} else if (c
|
|
140
|
+
} else if (isSpace(c)) {
|
|
73
141
|
token = WS;
|
|
74
142
|
} else if (c === "/" && sql[i + 1] === "*") {
|
|
75
143
|
const close = sql.indexOf("*/", i + 2);
|
|
@@ -83,27 +151,42 @@ function scanSqlStatements(sql: string): { count: SqlStatementCount; firstEnd: n
|
|
|
83
151
|
token = WS;
|
|
84
152
|
} else if (c === "[" || c === "`" || c === '"' || c === "'") {
|
|
85
153
|
const close = sql.indexOf(c === "[" ? "]" : c, i + 1);
|
|
86
|
-
if (close < 0)
|
|
154
|
+
if (close < 0) {
|
|
155
|
+
// An unterminated literal runs to the end: content, which SQLite reports as an error.
|
|
156
|
+
if (!inStatement) {
|
|
157
|
+
heads.push("");
|
|
158
|
+
start = tokenStart;
|
|
159
|
+
inStatement = true;
|
|
160
|
+
}
|
|
161
|
+
return result();
|
|
162
|
+
}
|
|
87
163
|
i = close;
|
|
88
164
|
token = OTHER;
|
|
165
|
+
} else if (c === "$" || c === ":" || c === "@" || c === "#") {
|
|
166
|
+
// A variable, not a word: SQLite reads `$a(';x')` as one token, quotes and all.
|
|
167
|
+
i = variableEnd(sql, i) - 1;
|
|
168
|
+
token = OTHER;
|
|
89
169
|
} else if (isIdChar(c)) {
|
|
90
170
|
let j = i + 1;
|
|
91
171
|
while (j < n && isIdChar(sql[j] as string)) j++;
|
|
92
|
-
|
|
172
|
+
word = sql.slice(i, j).toLowerCase();
|
|
173
|
+
token = KEYWORDS[word] ?? OTHER;
|
|
93
174
|
i = j - 1;
|
|
94
175
|
} else {
|
|
95
176
|
token = OTHER;
|
|
96
177
|
}
|
|
97
|
-
if (token !== SEMI && token !== WS) {
|
|
98
|
-
|
|
99
|
-
|
|
178
|
+
if (token !== SEMI && token !== WS && !inStatement) {
|
|
179
|
+
inStatement = true;
|
|
180
|
+
heads.push(word);
|
|
181
|
+
start = tokenStart;
|
|
100
182
|
}
|
|
101
183
|
state = TRANS[state]?.[token] ?? 2;
|
|
102
|
-
if (token === SEMI && state === 1 &&
|
|
103
|
-
|
|
104
|
-
|
|
184
|
+
if (token === SEMI && state === 1 && inStatement) {
|
|
185
|
+
inStatement = false;
|
|
186
|
+
statements.push(sql.slice(start, i));
|
|
187
|
+
if (firstEnd < 0) firstEnd = i;
|
|
105
188
|
}
|
|
106
189
|
i++;
|
|
107
190
|
}
|
|
108
|
-
return
|
|
191
|
+
return result();
|
|
109
192
|
}
|
|
@@ -3,6 +3,14 @@ import type { Db } from "@statewalker/db-api";
|
|
|
3
3
|
/** Key under which a SQLite Db carries its transaction hook. Shared across bundles via Symbol.for. */
|
|
4
4
|
export const SQLITE_TRANSACTION: unique symbol = Symbol.for("@statewalker/db-sqlite:transaction");
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Key under which a SQLite Db carries its read-only transaction hook (a separate key, so that a Db
|
|
8
|
+
* from an older db-sqlite, which has only the committing hook, is refused rather than committed).
|
|
9
|
+
*/
|
|
10
|
+
export const SQLITE_READ_ONLY_TRANSACTION: unique symbol = Symbol.for(
|
|
11
|
+
"@statewalker/db-sqlite:read-only-transaction",
|
|
12
|
+
);
|
|
13
|
+
|
|
6
14
|
/** Runs `cb` inside one transaction of the Db that carries it. */
|
|
7
15
|
export type SqliteTransactionHook = <T>(cb: (tx: Db) => Promise<T>) => Promise<T>;
|
|
8
16
|
|
|
@@ -21,3 +29,34 @@ export function inTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T>
|
|
|
21
29
|
if (typeof hook !== "function") return Promise.reject(new Error(NO_HOOK));
|
|
22
30
|
return hook(cb);
|
|
23
31
|
}
|
|
32
|
+
|
|
33
|
+
const NO_READ_ONLY_HOOK =
|
|
34
|
+
"inReadOnlyTransaction: this Db has no SQLite read-only transaction hook. It is not a " +
|
|
35
|
+
"@statewalker/db-sqlite* Db (or one from a db-sqlite older than 0.1.4), " +
|
|
36
|
+
"or it wraps one (a wrapper object loses the hook - pass the driver's Db itself), " +
|
|
37
|
+
"or it is the handle of a running transaction (nesting is not supported).";
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Run `cb` in one SQLite transaction that is always rolled back: `tx` sees the committed data and
|
|
41
|
+
* its own writes, and nothing it writes persists, whether `cb` returns (its value is returned) or
|
|
42
|
+
* throws (its error is rethrown). Statements that would end the transaction or reach outside it
|
|
43
|
+
* (BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, RELEASE, ATTACH, DETACH, PRAGMA, VACUUM) are refused,
|
|
44
|
+
* and once a statement fails, `tx` refuses every later call (SQLite may have ended the transaction
|
|
45
|
+
* itself, as `INSERT OR ROLLBACK` does). Other calls on `db` wait until it ends. `cb` must not do
|
|
46
|
+
* external I/O and must be idempotent: a Durable Object may run it more than once.
|
|
47
|
+
*/
|
|
48
|
+
export function inReadOnlyTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T> {
|
|
49
|
+
const hook = (db as { [SQLITE_READ_ONLY_TRANSACTION]?: SqliteTransactionHook })[
|
|
50
|
+
SQLITE_READ_ONLY_TRANSACTION
|
|
51
|
+
];
|
|
52
|
+
if (typeof hook !== "function") return Promise.reject(new Error(NO_READ_ONLY_HOOK));
|
|
53
|
+
return hook(cb);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Whether `db` carries the hook {@link inReadOnlyTransaction} needs. */
|
|
57
|
+
export function hasReadOnlyTransaction(db: Db): boolean {
|
|
58
|
+
return (
|
|
59
|
+
typeof (db as { [SQLITE_READ_ONLY_TRANSACTION]?: unknown })[SQLITE_READ_ONLY_TRANSACTION] ===
|
|
60
|
+
"function"
|
|
61
|
+
);
|
|
62
|
+
}
|