@statewalker/db-sqlite 0.1.1 → 0.1.3
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 +45 -7
- package/dist/index.d.mts +37 -7
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +292 -33
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -6
- package/src/index.ts +4 -0
- package/src/serialised-db.ts +95 -0
- package/src/serialised-sqlite-db.ts +86 -37
- package/src/sql-statements.ts +109 -0
package/README.md
CHANGED
|
@@ -5,7 +5,9 @@
|
|
|
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
7
|
together or not at all. It also holds `newSerialisedSqliteDb`, the wrapper every SQLite driver
|
|
8
|
-
(`db-sqlite-node`, `db-sqlite-browser`, `db-sqlite-do`) builds its `Db` with
|
|
8
|
+
(`db-sqlite-node`, `db-sqlite-browser`, `db-sqlite-do`) builds its `Db` with, and
|
|
9
|
+
`newSerialisedDb`, the engine-neutral lifecycle wrapper the DuckDB and PGlite drivers use. Both
|
|
10
|
+
keep the lifecycle that the `Db` JSDoc in `@statewalker/db-api` promises.
|
|
9
11
|
|
|
10
12
|
## Why it exists
|
|
11
13
|
|
|
@@ -22,10 +24,39 @@ pnpm add @statewalker/db-sqlite
|
|
|
22
24
|
|
|
23
25
|
| Import | Gives | Environment |
|
|
24
26
|
| --- | --- | --- |
|
|
25
|
-
| `@statewalker/db-sqlite` | `inTransaction`, `newSerialisedSqliteDb`, `SQLITE_TRANSACTION`; types `SqliteEngine`, `SqliteTransactionHook` | any |
|
|
27
|
+
| `@statewalker/db-sqlite` | `inTransaction`, `newSerialisedDb`, `newSerialisedSqliteDb`, `SQLITE_TRANSACTION`; types `SerialisedDbEngine`, `SqliteEngine`, `SqliteTransactionHook` | any |
|
|
28
|
+
|
|
29
|
+
`newSerialisedDb(engine, { name })` wraps an asynchronous `SerialisedDbEngine` (`query(sql,
|
|
30
|
+
params)`, `exec(sql)`, optional `flush()`, `close()`) as a `Db`: calls run one at a time in call
|
|
31
|
+
order; `close()` waits for the calls made before it, then closes the engine once; a call made once
|
|
32
|
+
`close()` has started rejects with `<name>: the database is closed`; a second `close()` is a
|
|
33
|
+
no-op; integers in rows come back as numbers within ±(2^53 - 1) and as bigints beyond, also
|
|
34
|
+
inside arrays and plain objects. It lives here, not in `@statewalker/db-api`, because that
|
|
35
|
+
package is types-only; it has no SQLite code in it, so a DuckDB or PGlite driver depends on this
|
|
36
|
+
package without pulling in any engine.
|
|
26
37
|
|
|
27
38
|
`inTransaction(db, cb)` returns what `cb` returns. If `cb` throws, everything it wrote is rolled
|
|
28
|
-
back and the same error is rethrown
|
|
39
|
+
back and the same error is rethrown; so is a failing `COMMIT` (a deferred foreign key, for
|
|
40
|
+
example), which rejects with SQLite's error. While it runs, other calls on `db` wait for it.
|
|
41
|
+
|
|
42
|
+
Every SQLite driver handles input the same way, because the wrapper does it before the engine
|
|
43
|
+
sees the call (on the Db and on the `tx` handle alike):
|
|
44
|
+
|
|
45
|
+
| Input | Result |
|
|
46
|
+
| --- | --- |
|
|
47
|
+
| `query` with more than one statement (`"INSERT …; SELECT …"`) | rejects with `db-sqlite: query runs one statement, and this SQL has more after the first; …`; none of it runs. Use `exec` for scripts |
|
|
48
|
+
| empty SQL in `query` or `exec` (only whitespace, comments or `;`) | rejects with `db-sqlite: the SQL is empty (only whitespace, comments or semicolons)` |
|
|
49
|
+
| `true` / `false` parameter | binds `1` / `0` |
|
|
50
|
+
| `undefined` parameter | binds `NULL` |
|
|
51
|
+
| `Date` parameter | binds its ISO 8601 UTC text, `date.toISOString()` (`"2026-01-02T03:04:05.006Z"`), which SQLite date functions read; an invalid Date rejects with `db-sqlite: parameter N is an invalid Date` |
|
|
52
|
+
| `bigint` parameter | binds as an integer |
|
|
53
|
+
| `null`, `number`, `string` parameter | binds as given (an integer-valued number as an integer, any other as a real) |
|
|
54
|
+
| `ArrayBuffer`, or any ArrayBuffer view (`Uint8Array`, `DataView`, `Float32Array`, …) parameter | binds a BLOB of exactly the view's bytes (`byteOffset` to `byteOffset + byteLength`) |
|
|
55
|
+
| any other parameter: a plain object, `Map`, array, function, symbol, boxed primitive (`new String(…)`) | rejects with a `TypeError`, `db-sqlite: parameter N has type <type>, which SQLite cannot bind; …`, and nothing runs. node:sqlite would otherwise read a leading object as named parameters and bind the rest one place to the left. SQLite has no array type: bind a list as JSON text, `JSON.stringify(ids)`, and read it with `json_each(?)` |
|
|
56
|
+
| integer in a result | a `number` within ±(2^53 - 1), a `bigint` beyond, so no value loses precision |
|
|
57
|
+
|
|
58
|
+
A trailing `;`, comments, and semicolons inside literals or a `CREATE TRIGGER … BEGIN … END` body
|
|
59
|
+
do not count as a second statement. Parameter indexes in messages count from 1.
|
|
29
60
|
|
|
30
61
|
## Examples
|
|
31
62
|
|
|
@@ -55,8 +86,10 @@ await db.close();
|
|
|
55
86
|
Db, for **an object that wraps a SQLite Db** (copying `query`/`exec`/`close` drops the hook —
|
|
56
87
|
pass the driver's Db, or a spread copy `{ ...db }`, which keeps symbol keys), and for the `tx`
|
|
57
88
|
handle itself: **nested transactions are not supported**.
|
|
58
|
-
- **One call at a time.** Every `query`, `exec`, `close` and transaction goes through one queue
|
|
59
|
-
in call order. A
|
|
89
|
+
- **One call at a time.** Every `query`, `exec`, `close` and transaction goes through one queue
|
|
90
|
+
(the one `newSerialisedDb` uses), in call order. A call made once `close()` has started rejects
|
|
91
|
+
at once with `db-sqlite: the database is closed`; `close()` itself waits for earlier calls,
|
|
92
|
+
and a second `close()` is a no-op. A plain `db.exec` issued while another flow's transaction is open waits; it never
|
|
60
93
|
joins that transaction, so a rollback cannot take it down. `close` waits for a running
|
|
61
94
|
transaction.
|
|
62
95
|
- **The `tx` handle expires.** After the callback settles, `tx.query` rejects with
|
|
@@ -70,9 +103,14 @@ await db.close();
|
|
|
70
103
|
- **Row counts.** There is no "rows changed" result: use `SELECT changes()` or `RETURNING` inside
|
|
71
104
|
the transaction. Id lists longer than 100 go in one JSON parameter through `json_each(?)` —
|
|
72
105
|
Durable Objects reject more than 100 bound parameters with `too many SQL variables`.
|
|
73
|
-
- **`SqliteEngine` is the driver seam.** `all`
|
|
74
|
-
|
|
106
|
+
- **`SqliteEngine` is the driver seam.** `all` is given one non-empty statement with normalised
|
|
107
|
+
parameters, and returns BLOBs as `Uint8Array` and integers as numbers or bigints (an engine
|
|
108
|
+
should read an integer above 2^53 as a bigint rather than throw; the wrapper turns safe ones into
|
|
109
|
+
numbers); `exec` must run every statement of a non-empty string; `transaction` is given only by
|
|
75
110
|
engines that cannot run `BEGIN IMMEDIATE`.
|
|
111
|
+
- **How the statements are counted.** `query` checks its SQL with a port of SQLite's own
|
|
112
|
+
`sqlite3_complete()` scanner (literals, quoted identifiers, comments, trigger bodies), not by
|
|
113
|
+
splitting on `;`.
|
|
76
114
|
- **Dependencies:** `@statewalker/db-api` (types only).
|
|
77
115
|
|
|
78
116
|
## License
|
package/dist/index.d.mts
CHANGED
|
@@ -1,9 +1,35 @@
|
|
|
1
1
|
import { Db } from "@statewalker/db-api";
|
|
2
|
+
//#region src/serialised-db.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* The asynchronous engine a driver wraps with {@link newSerialisedDb}. It is called one call at a
|
|
5
|
+
* time and never after `close`; `query` returns rows with integers as numbers or bigints (the
|
|
6
|
+
* wrapper turns safe bigints into numbers).
|
|
7
|
+
*/
|
|
8
|
+
type SerialisedDbEngine = {
|
|
9
|
+
query(sql: string, params: unknown[]): Promise<Record<string, unknown>[]>;
|
|
10
|
+
exec(sql: string): Promise<void>;
|
|
11
|
+
flush?(): Promise<void>;
|
|
12
|
+
close(): void | Promise<void>;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Wrap an engine as a `Db` that keeps the lifecycle every driver shares: calls run one at a time,
|
|
16
|
+
* in call order; `close()` waits for the calls made before it, then closes the engine; calls made
|
|
17
|
+
* once `close()` has started reject with `<name>: the database is closed`; closing twice is a
|
|
18
|
+
* no-op. Integers come back as numbers when safe and as bigints beyond (see
|
|
19
|
+
* {@link toSafeIntegers}). `name` prefixes the error, e.g. `"db-pglite"`.
|
|
20
|
+
*/
|
|
21
|
+
export declare function newSerialisedDb(engine: SerialisedDbEngine, options: {
|
|
22
|
+
name: string;
|
|
23
|
+
}): Db;
|
|
24
|
+
//#endregion
|
|
2
25
|
//#region src/serialised-sqlite-db.d.ts
|
|
3
26
|
/**
|
|
4
|
-
* The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array
|
|
5
|
-
*
|
|
6
|
-
*
|
|
27
|
+
* The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array; integers
|
|
28
|
+
* as numbers or bigints, which the wrapper turns into numbers when they are safe) and is given
|
|
29
|
+
* exactly one non-empty statement and parameters already normalised and checked (only null,
|
|
30
|
+
* number, bigint, string and Uint8Array); `exec` runs every statement of a non-empty string.
|
|
31
|
+
* `transaction`, when present, replaces `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects
|
|
32
|
+
* forbid them in SQL).
|
|
7
33
|
*/
|
|
8
34
|
type SqliteEngine = {
|
|
9
35
|
all(sql: string, params: unknown[]): Record<string, unknown>[];
|
|
@@ -12,9 +38,13 @@ type SqliteEngine = {
|
|
|
12
38
|
transaction?<T>(fn: () => Promise<T>): Promise<T>;
|
|
13
39
|
};
|
|
14
40
|
/**
|
|
15
|
-
* Wrap an engine as a `Db`
|
|
16
|
-
*
|
|
17
|
-
*
|
|
41
|
+
* Wrap an engine as a `Db` with the lifecycle of `newSerialisedDb` (calls run one at a time, in
|
|
42
|
+
* call order; `close()` waits for earlier calls; later calls reject with
|
|
43
|
+
* `db-sqlite: the database is closed`; closing twice is a no-op) and the `inTransaction` hook.
|
|
44
|
+
* Every SQLite driver gets the same input handling here: empty SQL rejects, `query` rejects a
|
|
45
|
+
* second statement, parameters are normalised (one SQLite cannot bind rejects) and safe integers come back as numbers. The `tx`
|
|
46
|
+
* handed to a transaction callback bypasses the queue, has no hook (so nesting is rejected) and
|
|
47
|
+
* rejects once its transaction has finished.
|
|
18
48
|
*/
|
|
19
49
|
export declare function newSerialisedSqliteDb(engine: SqliteEngine): Db;
|
|
20
50
|
//#endregion
|
|
@@ -30,5 +60,5 @@ type SqliteTransactionHook = <T>(cb: (tx: Db) => Promise<T>) => Promise<T>;
|
|
|
30
60
|
*/
|
|
31
61
|
export declare function inTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T>;
|
|
32
62
|
//#endregion
|
|
33
|
-
export type { SqliteEngine, SqliteTransactionHook };
|
|
63
|
+
export type { SerialisedDbEngine, SqliteEngine, SqliteTransactionHook };
|
|
34
64
|
//# 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-sqlite-db.ts","../src/sqlite-transaction.ts"],"mappings":";;;;;;;
|
|
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;;;;;;;;;;;KCtE5E;EACV,IAAI,aAAa,oBAAoB;EACrC,KAAK;EACL;EACA,aAAa,GAAG,UAAU,QAAQ,KAAK,QAAQ;;;;;;;;;;;wBA8EjC,sBAAsB,QAAQ,eAAe;;;;qBC5FhD;;KAGD,yBAAyB,GAAG,KAAK,IAAI,OAAO,QAAQ,OAAO,QAAQ;;;;;;wBAY/D,cAAc,GAAG,IAAI,IAAI,KAAK,IAAI,OAAO,QAAQ,KAAK,QAAQ"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,236 @@
|
|
|
1
|
+
//#region src/serialised-db.ts
|
|
2
|
+
function newDbCallQueue(name, closeEngine) {
|
|
3
|
+
let tail = Promise.resolve();
|
|
4
|
+
let closing;
|
|
5
|
+
const enqueue = (fn) => {
|
|
6
|
+
const result = tail.then(fn);
|
|
7
|
+
tail = result.catch(() => void 0);
|
|
8
|
+
return result;
|
|
9
|
+
};
|
|
10
|
+
return {
|
|
11
|
+
run: (fn) => closing ? Promise.reject(/* @__PURE__ */ new Error(`${name}: the database is closed`)) : enqueue(fn),
|
|
12
|
+
close: () => {
|
|
13
|
+
closing ??= enqueue(closeEngine);
|
|
14
|
+
return closing;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);
|
|
19
|
+
const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);
|
|
20
|
+
const isPlainObject = (value) => {
|
|
21
|
+
const proto = Object.getPrototypeOf(value);
|
|
22
|
+
return proto === Object.prototype || proto === null;
|
|
23
|
+
};
|
|
24
|
+
/** A bigint within ±(2^53 - 1) as a number; arrays and plain objects converted in place. */
|
|
25
|
+
function safeInteger(value) {
|
|
26
|
+
if (typeof value === "bigint") return value >= MIN_SAFE && value <= MAX_SAFE ? Number(value) : value;
|
|
27
|
+
if (Array.isArray(value)) for (let i = 0; i < value.length; i++) value[i] = safeInteger(value[i]);
|
|
28
|
+
else if (value !== null && typeof value === "object" && isPlainObject(value)) {
|
|
29
|
+
const record = value;
|
|
30
|
+
for (const key in record) record[key] = safeInteger(record[key]);
|
|
31
|
+
}
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Integers within ±(2^53 - 1) become numbers, larger ones stay bigints (no precision loss), in
|
|
36
|
+
* every column and inside list, struct and map values. The rows are converted in place.
|
|
37
|
+
*/
|
|
38
|
+
function toSafeIntegers(rows) {
|
|
39
|
+
for (const row of rows) {
|
|
40
|
+
const record = row;
|
|
41
|
+
for (const key in record) record[key] = safeInteger(record[key]);
|
|
42
|
+
}
|
|
43
|
+
return rows;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Wrap an engine as a `Db` that keeps the lifecycle every driver shares: calls run one at a time,
|
|
47
|
+
* in call order; `close()` waits for the calls made before it, then closes the engine; calls made
|
|
48
|
+
* once `close()` has started reject with `<name>: the database is closed`; closing twice is a
|
|
49
|
+
* no-op. Integers come back as numbers when safe and as bigints beyond (see
|
|
50
|
+
* {@link toSafeIntegers}). `name` prefixes the error, e.g. `"db-pglite"`.
|
|
51
|
+
*/
|
|
52
|
+
function newSerialisedDb(engine, options) {
|
|
53
|
+
const queue = newDbCallQueue(options.name, () => engine.close());
|
|
54
|
+
const db = {
|
|
55
|
+
query: (sql, params = []) => queue.run(async () => toSafeIntegers(await engine.query(sql, params))),
|
|
56
|
+
exec: (sql) => queue.run(() => engine.exec(sql)),
|
|
57
|
+
close: () => queue.close()
|
|
58
|
+
};
|
|
59
|
+
const flush = engine.flush?.bind(engine);
|
|
60
|
+
if (flush) db.flush = () => queue.run(flush);
|
|
61
|
+
return db;
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/sql-statements.ts
|
|
65
|
+
const SEMI = 0;
|
|
66
|
+
const WS = 1;
|
|
67
|
+
const OTHER = 2;
|
|
68
|
+
const EXPLAIN = 3;
|
|
69
|
+
const CREATE = 4;
|
|
70
|
+
const TEMP = 5;
|
|
71
|
+
const TRIGGER = 6;
|
|
72
|
+
const END = 7;
|
|
73
|
+
/** trans[state][token]; states 0 INVALID, 1 START, 2 NORMAL, 3 EXPLAIN, 4 CREATE, 5 TRIGGER, 6 SEMI, 7 END. */
|
|
74
|
+
const TRANS = [
|
|
75
|
+
[
|
|
76
|
+
1,
|
|
77
|
+
0,
|
|
78
|
+
2,
|
|
79
|
+
3,
|
|
80
|
+
4,
|
|
81
|
+
2,
|
|
82
|
+
2,
|
|
83
|
+
2
|
|
84
|
+
],
|
|
85
|
+
[
|
|
86
|
+
1,
|
|
87
|
+
1,
|
|
88
|
+
2,
|
|
89
|
+
3,
|
|
90
|
+
4,
|
|
91
|
+
2,
|
|
92
|
+
2,
|
|
93
|
+
2
|
|
94
|
+
],
|
|
95
|
+
[
|
|
96
|
+
1,
|
|
97
|
+
2,
|
|
98
|
+
2,
|
|
99
|
+
2,
|
|
100
|
+
2,
|
|
101
|
+
2,
|
|
102
|
+
2,
|
|
103
|
+
2
|
|
104
|
+
],
|
|
105
|
+
[
|
|
106
|
+
1,
|
|
107
|
+
3,
|
|
108
|
+
3,
|
|
109
|
+
2,
|
|
110
|
+
4,
|
|
111
|
+
2,
|
|
112
|
+
2,
|
|
113
|
+
2
|
|
114
|
+
],
|
|
115
|
+
[
|
|
116
|
+
1,
|
|
117
|
+
4,
|
|
118
|
+
2,
|
|
119
|
+
2,
|
|
120
|
+
2,
|
|
121
|
+
4,
|
|
122
|
+
5,
|
|
123
|
+
2
|
|
124
|
+
],
|
|
125
|
+
[
|
|
126
|
+
6,
|
|
127
|
+
5,
|
|
128
|
+
5,
|
|
129
|
+
5,
|
|
130
|
+
5,
|
|
131
|
+
5,
|
|
132
|
+
5,
|
|
133
|
+
5
|
|
134
|
+
],
|
|
135
|
+
[
|
|
136
|
+
6,
|
|
137
|
+
6,
|
|
138
|
+
5,
|
|
139
|
+
5,
|
|
140
|
+
5,
|
|
141
|
+
5,
|
|
142
|
+
5,
|
|
143
|
+
7
|
|
144
|
+
],
|
|
145
|
+
[
|
|
146
|
+
1,
|
|
147
|
+
7,
|
|
148
|
+
5,
|
|
149
|
+
5,
|
|
150
|
+
5,
|
|
151
|
+
5,
|
|
152
|
+
5,
|
|
153
|
+
5
|
|
154
|
+
]
|
|
155
|
+
];
|
|
156
|
+
const KEYWORDS = {
|
|
157
|
+
create: CREATE,
|
|
158
|
+
temp: TEMP,
|
|
159
|
+
temporary: TEMP,
|
|
160
|
+
trigger: TRIGGER,
|
|
161
|
+
end: END,
|
|
162
|
+
explain: EXPLAIN
|
|
163
|
+
};
|
|
164
|
+
const isIdChar = (c) => /[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) >= 128;
|
|
165
|
+
function countSqlStatements(sql) {
|
|
166
|
+
return scanSqlStatements(sql).count;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* The first statement of `sql` without the semicolon that ends it and without the empty tail
|
|
170
|
+
* after it (whitespace, comments, semicolons), for engines that reject such a tail (Durable
|
|
171
|
+
* Object SQLite: "SQL code did not contain a statement"). Meant for SQL that
|
|
172
|
+
* {@link countSqlStatements} counts as "one"; SQL without an ending semicolon comes back as is.
|
|
173
|
+
*/
|
|
174
|
+
function firstSqlStatement(sql) {
|
|
175
|
+
const { firstEnd } = scanSqlStatements(sql);
|
|
176
|
+
return firstEnd < 0 ? sql : sql.slice(0, firstEnd);
|
|
177
|
+
}
|
|
178
|
+
function scanSqlStatements(sql) {
|
|
179
|
+
let firstEnd = -1;
|
|
180
|
+
let state = 0;
|
|
181
|
+
let content = false;
|
|
182
|
+
let firstEnded = false;
|
|
183
|
+
let i = 0;
|
|
184
|
+
const n = sql.length;
|
|
185
|
+
while (i < n) {
|
|
186
|
+
const c = sql[i];
|
|
187
|
+
let token;
|
|
188
|
+
if (c === ";") token = SEMI;
|
|
189
|
+
else if (c === " " || c === " " || c === "\n" || c === "\r" || c === "\f") token = WS;
|
|
190
|
+
else if (c === "/" && sql[i + 1] === "*") {
|
|
191
|
+
const close = sql.indexOf("*/", i + 2);
|
|
192
|
+
if (close < 0) break;
|
|
193
|
+
i = close + 1;
|
|
194
|
+
token = WS;
|
|
195
|
+
} else if (c === "-" && sql[i + 1] === "-") {
|
|
196
|
+
const eol = sql.indexOf("\n", i);
|
|
197
|
+
if (eol < 0) break;
|
|
198
|
+
i = eol;
|
|
199
|
+
token = WS;
|
|
200
|
+
} else if (c === "[" || c === "`" || c === "\"" || c === "'") {
|
|
201
|
+
const close = sql.indexOf(c === "[" ? "]" : c, i + 1);
|
|
202
|
+
if (close < 0) return {
|
|
203
|
+
count: firstEnded ? "many" : "one",
|
|
204
|
+
firstEnd
|
|
205
|
+
};
|
|
206
|
+
i = close;
|
|
207
|
+
token = OTHER;
|
|
208
|
+
} else if (isIdChar(c)) {
|
|
209
|
+
let j = i + 1;
|
|
210
|
+
while (j < n && isIdChar(sql[j])) j++;
|
|
211
|
+
token = KEYWORDS[sql.slice(i, j).toLowerCase()] ?? OTHER;
|
|
212
|
+
i = j - 1;
|
|
213
|
+
} else token = OTHER;
|
|
214
|
+
if (token !== SEMI && token !== WS) {
|
|
215
|
+
if (firstEnded) return {
|
|
216
|
+
count: "many",
|
|
217
|
+
firstEnd
|
|
218
|
+
};
|
|
219
|
+
content = true;
|
|
220
|
+
}
|
|
221
|
+
state = TRANS[state]?.[token] ?? 2;
|
|
222
|
+
if (token === SEMI && state === 1 && content && !firstEnded) {
|
|
223
|
+
firstEnded = true;
|
|
224
|
+
firstEnd = i;
|
|
225
|
+
}
|
|
226
|
+
i++;
|
|
227
|
+
}
|
|
228
|
+
return {
|
|
229
|
+
count: content ? "one" : "empty",
|
|
230
|
+
firstEnd
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
//#endregion
|
|
1
234
|
//#region src/sqlite-transaction.ts
|
|
2
235
|
/** Key under which a SQLite Db carries its transaction hook. Shared across bundles via Symbol.for. */
|
|
3
236
|
const SQLITE_TRANSACTION = Symbol.for("@statewalker/db-sqlite:transaction");
|
|
@@ -14,25 +247,62 @@ function inTransaction(db, cb) {
|
|
|
14
247
|
}
|
|
15
248
|
//#endregion
|
|
16
249
|
//#region src/serialised-sqlite-db.ts
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
250
|
+
const EMPTY_SQL = "db-sqlite: the SQL is empty (only whitespace, comments or semicolons)";
|
|
251
|
+
const MANY_STATEMENTS = "db-sqlite: query runs one statement, and this SQL has more after the first; run them one query at a time, or use exec (no parameters, no rows)";
|
|
252
|
+
function checkSql(sql, one) {
|
|
253
|
+
if (typeof sql !== "string") throw new TypeError("db-sqlite: the SQL must be a string");
|
|
254
|
+
const count = countSqlStatements(sql);
|
|
255
|
+
if (count === "empty") throw new Error(EMPTY_SQL);
|
|
256
|
+
if (one && count === "many") throw new Error(MANY_STATEMENTS);
|
|
257
|
+
}
|
|
258
|
+
/** The type a rejected parameter is named by: `symbol`, `function`, or the object's class. */
|
|
259
|
+
function typeName(value) {
|
|
260
|
+
if (typeof value !== "object" || value === null) return typeof value;
|
|
261
|
+
const name = value.constructor?.name;
|
|
262
|
+
return typeof name === "string" && name ? name : "Object";
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text, ArrayBuffer or any ArrayBuffer view →
|
|
266
|
+
* a Uint8Array over exactly its bytes; null, number, bigint and string are left as given. Anything
|
|
267
|
+
* else (a plain object, Map, array, function, symbol, boxed primitive) rejects: node:sqlite would
|
|
268
|
+
* take a leading object as named parameters and bind the rest one place to the left, and SQLite
|
|
269
|
+
* has no array type (bind a list as JSON text and read it with `json_each`).
|
|
270
|
+
*/
|
|
271
|
+
function toSqliteParam(value, index) {
|
|
272
|
+
if (value === null || typeof value === "string" || typeof value === "number") return value;
|
|
273
|
+
if (typeof value === "bigint") return value;
|
|
274
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
275
|
+
if (value === void 0) return null;
|
|
276
|
+
if (value instanceof Date) {
|
|
277
|
+
if (Number.isNaN(value.getTime())) throw new RangeError(`db-sqlite: parameter ${index + 1} is an invalid Date`);
|
|
278
|
+
return value.toISOString();
|
|
279
|
+
}
|
|
280
|
+
if ((ArrayBuffer.isView(value) || value instanceof ArrayBuffer) && value.byteLength === 0) return (/* @__PURE__ */ new Uint8Array(1)).subarray(0, 0);
|
|
281
|
+
if (value instanceof Uint8Array && value.constructor === Uint8Array) return value;
|
|
282
|
+
if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
283
|
+
if (value instanceof ArrayBuffer) return new Uint8Array(value);
|
|
284
|
+
const hint = Array.isArray(value) ? "; bind a list as JSON text and read it with json_each" : "";
|
|
285
|
+
throw new TypeError(`db-sqlite: parameter ${index + 1} has type ${typeName(value)}, which SQLite cannot bind; pass null, undefined, a boolean, number, bigint, string, Date, ArrayBuffer or ArrayBuffer view${hint}`);
|
|
286
|
+
}
|
|
287
|
+
function runAll(engine, sql, params) {
|
|
288
|
+
checkSql(sql, true);
|
|
289
|
+
return toSafeIntegers(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));
|
|
290
|
+
}
|
|
291
|
+
function runExec(engine, sql) {
|
|
292
|
+
checkSql(sql, false);
|
|
293
|
+
engine.exec(sql);
|
|
24
294
|
}
|
|
25
295
|
/**
|
|
26
|
-
* Wrap an engine as a `Db`
|
|
27
|
-
*
|
|
28
|
-
*
|
|
296
|
+
* Wrap an engine as a `Db` with the lifecycle of `newSerialisedDb` (calls run one at a time, in
|
|
297
|
+
* call order; `close()` waits for earlier calls; later calls reject with
|
|
298
|
+
* `db-sqlite: the database is closed`; closing twice is a no-op) and the `inTransaction` hook.
|
|
299
|
+
* Every SQLite driver gets the same input handling here: empty SQL rejects, `query` rejects a
|
|
300
|
+
* second statement, parameters are normalised (one SQLite cannot bind rejects) and safe integers come back as numbers. The `tx`
|
|
301
|
+
* handed to a transaction callback bypasses the queue, has no hook (so nesting is rejected) and
|
|
302
|
+
* rejects once its transaction has finished.
|
|
29
303
|
*/
|
|
30
304
|
function newSerialisedSqliteDb(engine) {
|
|
31
|
-
const
|
|
32
|
-
let closed = false;
|
|
33
|
-
const live = () => {
|
|
34
|
-
if (closed) throw new Error("db-sqlite: the database is closed");
|
|
35
|
-
};
|
|
305
|
+
const queue = newDbCallQueue("db-sqlite", () => engine.close());
|
|
36
306
|
const runTransaction = engine.transaction?.bind(engine) ?? (async (fn) => {
|
|
37
307
|
engine.exec("BEGIN IMMEDIATE");
|
|
38
308
|
try {
|
|
@@ -46,8 +316,7 @@ function newSerialisedSqliteDb(engine) {
|
|
|
46
316
|
throw error;
|
|
47
317
|
}
|
|
48
318
|
});
|
|
49
|
-
const transaction = (cb) =>
|
|
50
|
-
live();
|
|
319
|
+
const transaction = (cb) => queue.run(async () => {
|
|
51
320
|
let finished = false;
|
|
52
321
|
const open = () => {
|
|
53
322
|
if (finished) throw new Error("db-sqlite: the transaction is finished; use the outer Db");
|
|
@@ -55,11 +324,11 @@ function newSerialisedSqliteDb(engine) {
|
|
|
55
324
|
const tx = {
|
|
56
325
|
async query(sql, params = []) {
|
|
57
326
|
open();
|
|
58
|
-
return engine
|
|
327
|
+
return runAll(engine, sql, params);
|
|
59
328
|
},
|
|
60
329
|
async exec(sql) {
|
|
61
330
|
open();
|
|
62
|
-
engine
|
|
331
|
+
runExec(engine, sql);
|
|
63
332
|
},
|
|
64
333
|
async close() {
|
|
65
334
|
throw new Error("db-sqlite: close the outer Db, not the transaction handle");
|
|
@@ -72,23 +341,13 @@ function newSerialisedSqliteDb(engine) {
|
|
|
72
341
|
}
|
|
73
342
|
});
|
|
74
343
|
return {
|
|
75
|
-
query: (sql, params = []) =>
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
}),
|
|
79
|
-
exec: (sql) => lock(async () => {
|
|
80
|
-
live();
|
|
81
|
-
engine.exec(sql);
|
|
82
|
-
}),
|
|
83
|
-
close: () => lock(async () => {
|
|
84
|
-
if (closed) return;
|
|
85
|
-
closed = true;
|
|
86
|
-
engine.close();
|
|
87
|
-
}),
|
|
344
|
+
query: (sql, params = []) => queue.run(() => runAll(engine, sql, params)),
|
|
345
|
+
exec: (sql) => queue.run(() => runExec(engine, sql)),
|
|
346
|
+
close: () => queue.close(),
|
|
88
347
|
[SQLITE_TRANSACTION]: transaction
|
|
89
348
|
};
|
|
90
349
|
}
|
|
91
350
|
//#endregion
|
|
92
|
-
export { SQLITE_TRANSACTION, inTransaction, newSerialisedSqliteDb };
|
|
351
|
+
export { SQLITE_TRANSACTION, inTransaction, newSerialisedDb, newSerialisedSqliteDb };
|
|
93
352
|
|
|
94
353
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/sqlite-transaction.ts","../src/serialised-sqlite-db.ts"],"sourcesContent":["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 { SQLITE_TRANSACTION, type SqliteTransactionHook } from \"./sqlite-transaction.js\";\n\n/**\n * The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array) and must\n * run exactly one statement; `exec` runs every statement of a string. `transaction`, when present,\n * replaces `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects 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\nfunction newLock() {\n let tail: Promise<unknown> = Promise.resolve();\n return <T>(fn: () => Promise<T>): Promise<T> => {\n const run = tail.then(fn);\n tail = run.catch(() => undefined);\n return run;\n };\n}\n\n/**\n * Wrap an engine as a `Db` whose calls run one at a time, in call order, and which carries the\n * `inTransaction` hook. The `tx` handed to a transaction callback bypasses the queue, has no hook\n * (so nesting is rejected) and rejects once its transaction has finished.\n */\nexport function newSerialisedSqliteDb(engine: SqliteEngine): Db {\n const lock = newLock();\n let closed = false;\n const live = () => {\n if (closed) throw new Error(\"db-sqlite: the database is closed\");\n };\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 lock(async () => {\n live();\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 engine.all(sql, params) as T[];\n },\n async exec(sql: string): Promise<void> {\n open();\n engine.exec(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 lock(async () => {\n live();\n return engine.all(sql, params) as T[];\n }),\n exec: (sql: string) =>\n lock(async () => {\n live();\n engine.exec(sql);\n }),\n close: () =>\n lock(async ()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C3B,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,KAAK,YAAY;GACf,KAAK;GACL,OAAO,OAAO,IAAI,KAAK,MAAM;EAC/B,CAAC;EACH,OAAO,QACL,KAAK,YAAY;GACf,KAAK;GACL,OAAO,KAAK,GAAG;EACjB,CAAC;EACH,aACE,KAAK,YAAY;GACf,IAAI,QAAQ;GACZ,SAAS;GACT,OAAO,MAAM;EACf,CAAC;GACF,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\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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KAAK,iBAAiB;EAC7B,IAAI;GACF,MAAM,SAAS,MAAM,GAAG;GACxB,OAAO,KAAK,QAAQ;GACpB,OAAO;EACT,SAAS,OAAO;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"}
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@statewalker/db-sqlite",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
|
-
"description": "SQLite transactions for @statewalker/db-api: inTransaction(db, cb) and the serialised
|
|
6
|
+
"description": "SQLite transactions for @statewalker/db-api: inTransaction(db, cb), and the serialised Db wrappers every driver builds its lifecycle on.",
|
|
7
7
|
"bugs": {
|
|
8
8
|
"url": "https://github.com/statewalker/statewalker-db/issues"
|
|
9
9
|
},
|
|
@@ -22,15 +22,17 @@
|
|
|
22
22
|
".": {
|
|
23
23
|
"source": "./src/index.ts",
|
|
24
24
|
"types": "./dist/index.d.mts",
|
|
25
|
-
"import": "./dist/index.mjs"
|
|
25
|
+
"import": "./dist/index.mjs",
|
|
26
|
+
"default": "./dist/index.mjs"
|
|
26
27
|
}
|
|
27
28
|
},
|
|
28
29
|
"files": [
|
|
29
30
|
"dist",
|
|
30
|
-
"src"
|
|
31
|
+
"src",
|
|
32
|
+
"!src/**/*.test.ts"
|
|
31
33
|
],
|
|
32
34
|
"dependencies": {
|
|
33
|
-
"@statewalker/db-api": "^0.1.
|
|
35
|
+
"@statewalker/db-api": "^0.1.7"
|
|
34
36
|
},
|
|
35
37
|
"devDependencies": {
|
|
36
38
|
"@types/node": "^26.6.4",
|
|
@@ -46,7 +48,7 @@
|
|
|
46
48
|
"scripts": {
|
|
47
49
|
"build": "tsdown",
|
|
48
50
|
"dev": "tsdown --watch",
|
|
49
|
-
"test": "vitest run
|
|
51
|
+
"test": "vitest run",
|
|
50
52
|
"typecheck": "tsc --noEmit",
|
|
51
53
|
"clean": "rimraf dist",
|
|
52
54
|
"lint": "biome check --write .",
|
package/src/index.ts
CHANGED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { Db, DbEntry } from "@statewalker/db-api";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The calls of one `Db`, run one at a time in call order. Once `close()` has started, `run`
|
|
5
|
+
* rejects at once with `<name>: the database is closed`; `close()` itself queues behind every
|
|
6
|
+
* earlier call, closes the engine once, and returns the same promise to every later caller.
|
|
7
|
+
*/
|
|
8
|
+
export type DbCallQueue = {
|
|
9
|
+
run<T>(fn: () => T | Promise<T>): Promise<T>;
|
|
10
|
+
close(): Promise<void>;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export function newDbCallQueue(name: string, closeEngine: () => void | Promise<void>): DbCallQueue {
|
|
14
|
+
let tail: Promise<unknown> = Promise.resolve();
|
|
15
|
+
let closing: Promise<void> | undefined;
|
|
16
|
+
const enqueue = <T>(fn: () => T | Promise<T>): Promise<T> => {
|
|
17
|
+
const result = tail.then(fn);
|
|
18
|
+
tail = result.catch(() => undefined);
|
|
19
|
+
return result;
|
|
20
|
+
};
|
|
21
|
+
return {
|
|
22
|
+
run: (fn) =>
|
|
23
|
+
closing ? Promise.reject(new Error(`${name}: the database is closed`)) : enqueue(fn),
|
|
24
|
+
close: () => {
|
|
25
|
+
closing ??= enqueue(closeEngine);
|
|
26
|
+
return closing;
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);
|
|
32
|
+
const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);
|
|
33
|
+
|
|
34
|
+
const isPlainObject = (value: object): boolean => {
|
|
35
|
+
const proto = Object.getPrototypeOf(value);
|
|
36
|
+
return proto === Object.prototype || proto === null;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** A bigint within ±(2^53 - 1) as a number; arrays and plain objects converted in place. */
|
|
40
|
+
function safeInteger(value: unknown): unknown {
|
|
41
|
+
if (typeof value === "bigint") {
|
|
42
|
+
return value >= MIN_SAFE && value <= MAX_SAFE ? Number(value) : value;
|
|
43
|
+
}
|
|
44
|
+
if (Array.isArray(value)) {
|
|
45
|
+
for (let i = 0; i < value.length; i++) value[i] = safeInteger(value[i]);
|
|
46
|
+
} else if (value !== null && typeof value === "object" && isPlainObject(value)) {
|
|
47
|
+
const record = value as Record<string, unknown>;
|
|
48
|
+
for (const key in record) record[key] = safeInteger(record[key]);
|
|
49
|
+
}
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Integers within ±(2^53 - 1) become numbers, larger ones stay bigints (no precision loss), in
|
|
55
|
+
* every column and inside list, struct and map values. The rows are converted in place.
|
|
56
|
+
*/
|
|
57
|
+
export function toSafeIntegers<T extends Record<string, unknown>>(rows: T[]): T[] {
|
|
58
|
+
for (const row of rows) {
|
|
59
|
+
const record = row as Record<string, unknown>;
|
|
60
|
+
for (const key in record) record[key] = safeInteger(record[key]);
|
|
61
|
+
}
|
|
62
|
+
return rows;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The asynchronous engine a driver wraps with {@link newSerialisedDb}. It is called one call at a
|
|
67
|
+
* time and never after `close`; `query` returns rows with integers as numbers or bigints (the
|
|
68
|
+
* wrapper turns safe bigints into numbers).
|
|
69
|
+
*/
|
|
70
|
+
export type SerialisedDbEngine = {
|
|
71
|
+
query(sql: string, params: unknown[]): Promise<Record<string, unknown>[]>;
|
|
72
|
+
exec(sql: string): Promise<void>;
|
|
73
|
+
flush?(): Promise<void>;
|
|
74
|
+
close(): void | Promise<void>;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Wrap an engine as a `Db` that keeps the lifecycle every driver shares: calls run one at a time,
|
|
79
|
+
* in call order; `close()` waits for the calls made before it, then closes the engine; calls made
|
|
80
|
+
* once `close()` has started reject with `<name>: the database is closed`; closing twice is a
|
|
81
|
+
* no-op. Integers come back as numbers when safe and as bigints beyond (see
|
|
82
|
+
* {@link toSafeIntegers}). `name` prefixes the error, e.g. `"db-pglite"`.
|
|
83
|
+
*/
|
|
84
|
+
export function newSerialisedDb(engine: SerialisedDbEngine, options: { name: string }): Db {
|
|
85
|
+
const queue = newDbCallQueue(options.name, () => engine.close());
|
|
86
|
+
const db: Db = {
|
|
87
|
+
query: <T = DbEntry>(sql: string, params: unknown[] = []) =>
|
|
88
|
+
queue.run(async () => toSafeIntegers(await engine.query(sql, params)) as T[]),
|
|
89
|
+
exec: (sql: string) => queue.run(() => engine.exec(sql)),
|
|
90
|
+
close: () => queue.close(),
|
|
91
|
+
};
|
|
92
|
+
const flush = engine.flush?.bind(engine);
|
|
93
|
+
if (flush) db.flush = () => queue.run(flush);
|
|
94
|
+
return db;
|
|
95
|
+
}
|
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import type { Db, DbEntry } from "@statewalker/db-api";
|
|
2
|
+
import { newDbCallQueue, toSafeIntegers } from "./serialised-db.js";
|
|
3
|
+
import { countSqlStatements, firstSqlStatement } from "./sql-statements.js";
|
|
2
4
|
import { SQLITE_TRANSACTION, type SqliteTransactionHook } from "./sqlite-transaction.js";
|
|
3
5
|
|
|
4
6
|
/**
|
|
5
|
-
* The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array
|
|
6
|
-
*
|
|
7
|
-
*
|
|
7
|
+
* The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array; integers
|
|
8
|
+
* as numbers or bigints, which the wrapper turns into numbers when they are safe) and is given
|
|
9
|
+
* exactly one non-empty statement and parameters already normalised and checked (only null,
|
|
10
|
+
* number, bigint, string and Uint8Array); `exec` runs every statement of a non-empty string.
|
|
11
|
+
* `transaction`, when present, replaces `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects
|
|
12
|
+
* forbid them in SQL).
|
|
8
13
|
*/
|
|
9
14
|
export type SqliteEngine = {
|
|
10
15
|
all(sql: string, params: unknown[]): Record<string, unknown>[];
|
|
@@ -13,26 +18,83 @@ export type SqliteEngine = {
|
|
|
13
18
|
transaction?<T>(fn: () => Promise<T>): Promise<T>;
|
|
14
19
|
};
|
|
15
20
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
const EMPTY_SQL = "db-sqlite: the SQL is empty (only whitespace, comments or semicolons)";
|
|
22
|
+
const MANY_STATEMENTS =
|
|
23
|
+
"db-sqlite: query runs one statement, and this SQL has more after the first; " +
|
|
24
|
+
"run them one query at a time, or use exec (no parameters, no rows)";
|
|
25
|
+
|
|
26
|
+
function checkSql(sql: string, one: boolean): void {
|
|
27
|
+
if (typeof sql !== "string") throw new TypeError("db-sqlite: the SQL must be a string");
|
|
28
|
+
const count = countSqlStatements(sql);
|
|
29
|
+
if (count === "empty") throw new Error(EMPTY_SQL);
|
|
30
|
+
if (one && count === "many") throw new Error(MANY_STATEMENTS);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The type a rejected parameter is named by: `symbol`, `function`, or the object's class. */
|
|
34
|
+
function typeName(value: unknown): string {
|
|
35
|
+
if (typeof value !== "object" || value === null) return typeof value;
|
|
36
|
+
const name = (value as { constructor?: { name?: unknown } }).constructor?.name;
|
|
37
|
+
return typeof name === "string" && name ? name : "Object";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text, ArrayBuffer or any ArrayBuffer view →
|
|
42
|
+
* a Uint8Array over exactly its bytes; null, number, bigint and string are left as given. Anything
|
|
43
|
+
* else (a plain object, Map, array, function, symbol, boxed primitive) rejects: node:sqlite would
|
|
44
|
+
* take a leading object as named parameters and bind the rest one place to the left, and SQLite
|
|
45
|
+
* has no array type (bind a list as JSON text and read it with `json_each`).
|
|
46
|
+
*/
|
|
47
|
+
function toSqliteParam(value: unknown, index: number): unknown {
|
|
48
|
+
if (value === null || typeof value === "string" || typeof value === "number") return value;
|
|
49
|
+
if (typeof value === "bigint") return value;
|
|
50
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
51
|
+
if (value === undefined) return null;
|
|
52
|
+
if (value instanceof Date) {
|
|
53
|
+
if (Number.isNaN(value.getTime())) {
|
|
54
|
+
throw new RangeError(`db-sqlite: parameter ${index + 1} is an invalid Date`);
|
|
55
|
+
}
|
|
56
|
+
return value.toISOString();
|
|
57
|
+
}
|
|
58
|
+
// node:sqlite (Node 22) binds a view over a buffer with no backing store (any zero-length
|
|
59
|
+
// ArrayBuffer) as NULL: give an empty value a fresh empty Uint8Array, which binds as a BLOB.
|
|
60
|
+
if ((ArrayBuffer.isView(value) || value instanceof ArrayBuffer) && value.byteLength === 0) {
|
|
61
|
+
return new Uint8Array(1).subarray(0, 0);
|
|
62
|
+
}
|
|
63
|
+
if (value instanceof Uint8Array && value.constructor === Uint8Array) return value;
|
|
64
|
+
if (ArrayBuffer.isView(value)) {
|
|
65
|
+
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
66
|
+
}
|
|
67
|
+
if (value instanceof ArrayBuffer) return new Uint8Array(value);
|
|
68
|
+
const hint = Array.isArray(value) ? "; bind a list as JSON text and read it with json_each" : "";
|
|
69
|
+
throw new TypeError(
|
|
70
|
+
`db-sqlite: parameter ${index + 1} has type ${typeName(value)}, which SQLite cannot bind; ` +
|
|
71
|
+
"pass null, undefined, a boolean, number, bigint, string, Date, ArrayBuffer or " +
|
|
72
|
+
`ArrayBuffer view${hint}`,
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function runAll(engine: SqliteEngine, sql: string, params: unknown[]): Record<string, unknown>[] {
|
|
77
|
+
checkSql(sql, true);
|
|
78
|
+
// Only the statement itself reaches the engine: DO SQLite rejects an empty tail ("; -- c ;").
|
|
79
|
+
return toSafeIntegers(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function runExec(engine: SqliteEngine, sql: string): void {
|
|
83
|
+
checkSql(sql, false);
|
|
84
|
+
engine.exec(sql);
|
|
23
85
|
}
|
|
24
86
|
|
|
25
87
|
/**
|
|
26
|
-
* Wrap an engine as a `Db`
|
|
27
|
-
*
|
|
28
|
-
*
|
|
88
|
+
* Wrap an engine as a `Db` with the lifecycle of `newSerialisedDb` (calls run one at a time, in
|
|
89
|
+
* call order; `close()` waits for earlier calls; later calls reject with
|
|
90
|
+
* `db-sqlite: the database is closed`; closing twice is a no-op) and the `inTransaction` hook.
|
|
91
|
+
* Every SQLite driver gets the same input handling here: empty SQL rejects, `query` rejects a
|
|
92
|
+
* second statement, parameters are normalised (one SQLite cannot bind rejects) and safe integers come back as numbers. The `tx`
|
|
93
|
+
* handed to a transaction callback bypasses the queue, has no hook (so nesting is rejected) and
|
|
94
|
+
* rejects once its transaction has finished.
|
|
29
95
|
*/
|
|
30
96
|
export function newSerialisedSqliteDb(engine: SqliteEngine): Db {
|
|
31
|
-
const
|
|
32
|
-
let closed = false;
|
|
33
|
-
const live = () => {
|
|
34
|
-
if (closed) throw new Error("db-sqlite: the database is closed");
|
|
35
|
-
};
|
|
97
|
+
const queue = newDbCallQueue("db-sqlite", () => engine.close());
|
|
36
98
|
const runTransaction =
|
|
37
99
|
engine.transaction?.bind(engine) ??
|
|
38
100
|
(async <T>(fn: () => Promise<T>): Promise<T> => {
|
|
@@ -52,8 +114,7 @@ export function newSerialisedSqliteDb(engine: SqliteEngine): Db {
|
|
|
52
114
|
});
|
|
53
115
|
|
|
54
116
|
const transaction: SqliteTransactionHook = (cb) =>
|
|
55
|
-
|
|
56
|
-
live();
|
|
117
|
+
queue.run(async () => {
|
|
57
118
|
let finished = false;
|
|
58
119
|
const open = () => {
|
|
59
120
|
if (finished) throw new Error("db-sqlite: the transaction is finished; use the outer Db");
|
|
@@ -61,11 +122,11 @@ export function newSerialisedSqliteDb(engine: SqliteEngine): Db {
|
|
|
61
122
|
const tx: Db = {
|
|
62
123
|
async query<T = DbEntry>(sql: string, params: unknown[] = []): Promise<T[]> {
|
|
63
124
|
open();
|
|
64
|
-
return engine
|
|
125
|
+
return runAll(engine, sql, params) as T[];
|
|
65
126
|
},
|
|
66
127
|
async exec(sql: string): Promise<void> {
|
|
67
128
|
open();
|
|
68
|
-
engine
|
|
129
|
+
runExec(engine, sql);
|
|
69
130
|
},
|
|
70
131
|
async close(): Promise<void> {
|
|
71
132
|
throw new Error("db-sqlite: close the outer Db, not the transaction handle");
|
|
@@ -80,21 +141,9 @@ export function newSerialisedSqliteDb(engine: SqliteEngine): Db {
|
|
|
80
141
|
|
|
81
142
|
return {
|
|
82
143
|
query: <T = DbEntry>(sql: string, params: unknown[] = []) =>
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
}),
|
|
87
|
-
exec: (sql: string) =>
|
|
88
|
-
lock(async () => {
|
|
89
|
-
live();
|
|
90
|
-
engine.exec(sql);
|
|
91
|
-
}),
|
|
92
|
-
close: () =>
|
|
93
|
-
lock(async () => {
|
|
94
|
-
if (closed) return;
|
|
95
|
-
closed = true;
|
|
96
|
-
engine.close();
|
|
97
|
-
}),
|
|
144
|
+
queue.run(() => runAll(engine, sql, params) as T[]),
|
|
145
|
+
exec: (sql: string) => queue.run(() => runExec(engine, sql)),
|
|
146
|
+
close: () => queue.close(),
|
|
98
147
|
[SQLITE_TRANSACTION]: transaction,
|
|
99
148
|
} as Db;
|
|
100
149
|
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How many SQL statements a string holds, without running it: "empty" (only whitespace, comments
|
|
3
|
+
* and semicolons), "one" (one statement, maybe followed by such a tail) or "many".
|
|
4
|
+
*
|
|
5
|
+
* A port of SQLite's own `sqlite3_complete()` state machine (src/complete.c): it knows string
|
|
6
|
+
* literals ('…'), quoted identifiers ("…", `…`, […]), `--` and `/* … *\/` comments, and that
|
|
7
|
+
* the semicolons inside a `CREATE TRIGGER … BEGIN … END` body do not end the statement. An
|
|
8
|
+
* unterminated literal is content (SQLite reports the syntax error); an unterminated comment runs
|
|
9
|
+
* to the end of the text.
|
|
10
|
+
*/
|
|
11
|
+
export type SqlStatementCount = "empty" | "one" | "many";
|
|
12
|
+
|
|
13
|
+
const SEMI = 0;
|
|
14
|
+
const WS = 1;
|
|
15
|
+
const OTHER = 2;
|
|
16
|
+
const EXPLAIN = 3;
|
|
17
|
+
const CREATE = 4;
|
|
18
|
+
const TEMP = 5;
|
|
19
|
+
const TRIGGER = 6;
|
|
20
|
+
const END = 7;
|
|
21
|
+
|
|
22
|
+
/** trans[state][token]; states 0 INVALID, 1 START, 2 NORMAL, 3 EXPLAIN, 4 CREATE, 5 TRIGGER, 6 SEMI, 7 END. */
|
|
23
|
+
const TRANS = [
|
|
24
|
+
[1, 0, 2, 3, 4, 2, 2, 2],
|
|
25
|
+
[1, 1, 2, 3, 4, 2, 2, 2],
|
|
26
|
+
[1, 2, 2, 2, 2, 2, 2, 2],
|
|
27
|
+
[1, 3, 3, 2, 4, 2, 2, 2],
|
|
28
|
+
[1, 4, 2, 2, 2, 4, 5, 2],
|
|
29
|
+
[6, 5, 5, 5, 5, 5, 5, 5],
|
|
30
|
+
[6, 6, 5, 5, 5, 5, 5, 7],
|
|
31
|
+
[1, 7, 5, 5, 5, 5, 5, 5],
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
const KEYWORDS: Record<string, number> = {
|
|
35
|
+
create: CREATE,
|
|
36
|
+
temp: TEMP,
|
|
37
|
+
temporary: TEMP,
|
|
38
|
+
trigger: TRIGGER,
|
|
39
|
+
end: END,
|
|
40
|
+
explain: EXPLAIN,
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const isIdChar = (c: string) => /[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) >= 0x80;
|
|
44
|
+
|
|
45
|
+
export function countSqlStatements(sql: string): SqlStatementCount {
|
|
46
|
+
return scanSqlStatements(sql).count;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The first statement of `sql` without the semicolon that ends it and without the empty tail
|
|
51
|
+
* after it (whitespace, comments, semicolons), for engines that reject such a tail (Durable
|
|
52
|
+
* Object SQLite: "SQL code did not contain a statement"). Meant for SQL that
|
|
53
|
+
* {@link countSqlStatements} counts as "one"; SQL without an ending semicolon comes back as is.
|
|
54
|
+
*/
|
|
55
|
+
export function firstSqlStatement(sql: string): string {
|
|
56
|
+
const { firstEnd } = scanSqlStatements(sql);
|
|
57
|
+
return firstEnd < 0 ? sql : sql.slice(0, firstEnd);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function scanSqlStatements(sql: string): { count: SqlStatementCount; firstEnd: number } {
|
|
61
|
+
let firstEnd = -1; // index of the ";" that ends the first statement
|
|
62
|
+
let state = 0;
|
|
63
|
+
let content = false; // a token other than whitespace or ";" was seen
|
|
64
|
+
let firstEnded = false; // the first statement with content has reached its ";"
|
|
65
|
+
let i = 0;
|
|
66
|
+
const n = sql.length;
|
|
67
|
+
while (i < n) {
|
|
68
|
+
const c = sql[i] as string;
|
|
69
|
+
let token: number;
|
|
70
|
+
if (c === ";") {
|
|
71
|
+
token = SEMI;
|
|
72
|
+
} else if (c === " " || c === "\t" || c === "\n" || c === "\r" || c === "\f") {
|
|
73
|
+
token = WS;
|
|
74
|
+
} else if (c === "/" && sql[i + 1] === "*") {
|
|
75
|
+
const close = sql.indexOf("*/", i + 2);
|
|
76
|
+
if (close < 0) break; // an unterminated comment runs to the end, like whitespace
|
|
77
|
+
i = close + 1;
|
|
78
|
+
token = WS;
|
|
79
|
+
} else if (c === "-" && sql[i + 1] === "-") {
|
|
80
|
+
const eol = sql.indexOf("\n", i);
|
|
81
|
+
if (eol < 0) break;
|
|
82
|
+
i = eol;
|
|
83
|
+
token = WS;
|
|
84
|
+
} else if (c === "[" || c === "`" || c === '"' || c === "'") {
|
|
85
|
+
const close = sql.indexOf(c === "[" ? "]" : c, i + 1);
|
|
86
|
+
if (close < 0) return { count: firstEnded ? "many" : "one", firstEnd };
|
|
87
|
+
i = close;
|
|
88
|
+
token = OTHER;
|
|
89
|
+
} else if (isIdChar(c)) {
|
|
90
|
+
let j = i + 1;
|
|
91
|
+
while (j < n && isIdChar(sql[j] as string)) j++;
|
|
92
|
+
token = KEYWORDS[sql.slice(i, j).toLowerCase()] ?? OTHER;
|
|
93
|
+
i = j - 1;
|
|
94
|
+
} else {
|
|
95
|
+
token = OTHER;
|
|
96
|
+
}
|
|
97
|
+
if (token !== SEMI && token !== WS) {
|
|
98
|
+
if (firstEnded) return { count: "many", firstEnd };
|
|
99
|
+
content = true;
|
|
100
|
+
}
|
|
101
|
+
state = TRANS[state]?.[token] ?? 2;
|
|
102
|
+
if (token === SEMI && state === 1 && content && !firstEnded) {
|
|
103
|
+
firstEnded = true;
|
|
104
|
+
firstEnd = i;
|
|
105
|
+
}
|
|
106
|
+
i++;
|
|
107
|
+
}
|
|
108
|
+
return { count: content ? "one" : "empty", firstEnd };
|
|
109
|
+
}
|