@statewalker/db-sqlite 0.1.0 → 0.1.2
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 +25 -3
- package/dist/index.d.mts +8 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +213 -5
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -6
- package/src/serialised-sqlite-db.ts +65 -8
- package/src/sql-statements.ts +109 -0
package/README.md
CHANGED
|
@@ -25,7 +25,24 @@ pnpm add @statewalker/db-sqlite
|
|
|
25
25
|
| `@statewalker/db-sqlite` | `inTransaction`, `newSerialisedSqliteDb`, `SQLITE_TRANSACTION`; types `SqliteEngine`, `SqliteTransactionHook` | any |
|
|
26
26
|
|
|
27
27
|
`inTransaction(db, cb)` returns what `cb` returns. If `cb` throws, everything it wrote is rolled
|
|
28
|
-
back and the same error is rethrown
|
|
28
|
+
back and the same error is rethrown; so is a failing `COMMIT` (a deferred foreign key, for
|
|
29
|
+
example), which rejects with SQLite's error. While it runs, other calls on `db` wait for it.
|
|
30
|
+
|
|
31
|
+
Every SQLite driver handles input the same way, because the wrapper does it before the engine
|
|
32
|
+
sees the call (on the Db and on the `tx` handle alike):
|
|
33
|
+
|
|
34
|
+
| Input | Result |
|
|
35
|
+
| --- | --- |
|
|
36
|
+
| `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 |
|
|
37
|
+
| empty SQL in `query` or `exec` (only whitespace, comments or `;`) | rejects with `db-sqlite: the SQL is empty (only whitespace, comments or semicolons)` |
|
|
38
|
+
| `true` / `false` parameter | binds `1` / `0` |
|
|
39
|
+
| `undefined` parameter | binds `NULL` |
|
|
40
|
+
| `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` |
|
|
41
|
+
| `bigint` parameter | binds as an integer |
|
|
42
|
+
| integer in a result | a `number` within ±(2^53 - 1), a `bigint` beyond, so no value loses precision |
|
|
43
|
+
|
|
44
|
+
A trailing `;`, comments, and semicolons inside literals or a `CREATE TRIGGER … BEGIN … END` body
|
|
45
|
+
do not count as a second statement. Other parameter types go to the engine unchanged.
|
|
29
46
|
|
|
30
47
|
## Examples
|
|
31
48
|
|
|
@@ -70,9 +87,14 @@ await db.close();
|
|
|
70
87
|
- **Row counts.** There is no "rows changed" result: use `SELECT changes()` or `RETURNING` inside
|
|
71
88
|
the transaction. Id lists longer than 100 go in one JSON parameter through `json_each(?)` —
|
|
72
89
|
Durable Objects reject more than 100 bound parameters with `too many SQL variables`.
|
|
73
|
-
- **`SqliteEngine` is the driver seam.** `all`
|
|
74
|
-
|
|
90
|
+
- **`SqliteEngine` is the driver seam.** `all` is given one non-empty statement with normalised
|
|
91
|
+
parameters, and returns BLOBs as `Uint8Array` and integers as numbers or bigints (an engine
|
|
92
|
+
should read an integer above 2^53 as a bigint rather than throw; the wrapper turns safe ones into
|
|
93
|
+
numbers); `exec` must run every statement of a non-empty string; `transaction` is given only by
|
|
75
94
|
engines that cannot run `BEGIN IMMEDIATE`.
|
|
95
|
+
- **How the statements are counted.** `query` checks its SQL with a port of SQLite's own
|
|
96
|
+
`sqlite3_complete()` scanner (literals, quoted identifiers, comments, trigger bodies), not by
|
|
97
|
+
splitting on `;`.
|
|
76
98
|
- **Dependencies:** `@statewalker/db-api` (types only).
|
|
77
99
|
|
|
78
100
|
## License
|
package/dist/index.d.mts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { Db } from "@statewalker/db-api";
|
|
2
2
|
//#region src/serialised-sqlite-db.d.ts
|
|
3
3
|
/**
|
|
4
|
-
* The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array; integers
|
|
5
|
+
* as numbers or bigints, which the wrapper turns into numbers when they are safe) and is given
|
|
6
|
+
* exactly one non-empty statement and parameters already normalised (no boolean, undefined or
|
|
7
|
+
* Date); `exec` runs every statement of a non-empty string. `transaction`, when present, replaces
|
|
8
|
+
* `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects forbid them in SQL).
|
|
7
9
|
*/
|
|
8
10
|
type SqliteEngine = {
|
|
9
11
|
all(sql: string, params: unknown[]): Record<string, unknown>[];
|
|
@@ -13,7 +15,9 @@ type SqliteEngine = {
|
|
|
13
15
|
};
|
|
14
16
|
/**
|
|
15
17
|
* Wrap an engine as a `Db` whose calls run one at a time, in call order, and which carries the
|
|
16
|
-
* `inTransaction` hook.
|
|
18
|
+
* `inTransaction` hook. Every SQLite driver gets the same input handling here: empty SQL rejects,
|
|
19
|
+
* `query` rejects a second statement, parameters are normalised and safe integers come back as
|
|
20
|
+
* numbers. The `tx` handed to a transaction callback bypasses the queue, has no hook
|
|
17
21
|
* (so nesting is rejected) and rejects once its transaction has finished.
|
|
18
22
|
*/
|
|
19
23
|
export declare function newSerialisedSqliteDb(engine: SqliteEngine): Db;
|
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-sqlite-db.ts","../src/sqlite-transaction.ts"],"mappings":";;;;;;;;;KAWY;EACV,IAAI,aAAa,oBAAoB;EACrC,KAAK;EACL;EACA,aAAa,GAAG,UAAU,QAAQ,KAAK,QAAQ;;;;;;;;;wBAuEjC,sBAAsB,QAAQ,eAAe;;;;qBCnFhD;;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,173 @@
|
|
|
1
|
+
//#region src/sql-statements.ts
|
|
2
|
+
const SEMI = 0;
|
|
3
|
+
const WS = 1;
|
|
4
|
+
const OTHER = 2;
|
|
5
|
+
const EXPLAIN = 3;
|
|
6
|
+
const CREATE = 4;
|
|
7
|
+
const TEMP = 5;
|
|
8
|
+
const TRIGGER = 6;
|
|
9
|
+
const END = 7;
|
|
10
|
+
/** trans[state][token]; states 0 INVALID, 1 START, 2 NORMAL, 3 EXPLAIN, 4 CREATE, 5 TRIGGER, 6 SEMI, 7 END. */
|
|
11
|
+
const TRANS = [
|
|
12
|
+
[
|
|
13
|
+
1,
|
|
14
|
+
0,
|
|
15
|
+
2,
|
|
16
|
+
3,
|
|
17
|
+
4,
|
|
18
|
+
2,
|
|
19
|
+
2,
|
|
20
|
+
2
|
|
21
|
+
],
|
|
22
|
+
[
|
|
23
|
+
1,
|
|
24
|
+
1,
|
|
25
|
+
2,
|
|
26
|
+
3,
|
|
27
|
+
4,
|
|
28
|
+
2,
|
|
29
|
+
2,
|
|
30
|
+
2
|
|
31
|
+
],
|
|
32
|
+
[
|
|
33
|
+
1,
|
|
34
|
+
2,
|
|
35
|
+
2,
|
|
36
|
+
2,
|
|
37
|
+
2,
|
|
38
|
+
2,
|
|
39
|
+
2,
|
|
40
|
+
2
|
|
41
|
+
],
|
|
42
|
+
[
|
|
43
|
+
1,
|
|
44
|
+
3,
|
|
45
|
+
3,
|
|
46
|
+
2,
|
|
47
|
+
4,
|
|
48
|
+
2,
|
|
49
|
+
2,
|
|
50
|
+
2
|
|
51
|
+
],
|
|
52
|
+
[
|
|
53
|
+
1,
|
|
54
|
+
4,
|
|
55
|
+
2,
|
|
56
|
+
2,
|
|
57
|
+
2,
|
|
58
|
+
4,
|
|
59
|
+
5,
|
|
60
|
+
2
|
|
61
|
+
],
|
|
62
|
+
[
|
|
63
|
+
6,
|
|
64
|
+
5,
|
|
65
|
+
5,
|
|
66
|
+
5,
|
|
67
|
+
5,
|
|
68
|
+
5,
|
|
69
|
+
5,
|
|
70
|
+
5
|
|
71
|
+
],
|
|
72
|
+
[
|
|
73
|
+
6,
|
|
74
|
+
6,
|
|
75
|
+
5,
|
|
76
|
+
5,
|
|
77
|
+
5,
|
|
78
|
+
5,
|
|
79
|
+
5,
|
|
80
|
+
7
|
|
81
|
+
],
|
|
82
|
+
[
|
|
83
|
+
1,
|
|
84
|
+
7,
|
|
85
|
+
5,
|
|
86
|
+
5,
|
|
87
|
+
5,
|
|
88
|
+
5,
|
|
89
|
+
5,
|
|
90
|
+
5
|
|
91
|
+
]
|
|
92
|
+
];
|
|
93
|
+
const KEYWORDS = {
|
|
94
|
+
create: CREATE,
|
|
95
|
+
temp: TEMP,
|
|
96
|
+
temporary: TEMP,
|
|
97
|
+
trigger: TRIGGER,
|
|
98
|
+
end: END,
|
|
99
|
+
explain: EXPLAIN
|
|
100
|
+
};
|
|
101
|
+
const isIdChar = (c) => /[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) >= 128;
|
|
102
|
+
function countSqlStatements(sql) {
|
|
103
|
+
return scanSqlStatements(sql).count;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The first statement of `sql` without the semicolon that ends it and without the empty tail
|
|
107
|
+
* after it (whitespace, comments, semicolons), for engines that reject such a tail (Durable
|
|
108
|
+
* Object SQLite: "SQL code did not contain a statement"). Meant for SQL that
|
|
109
|
+
* {@link countSqlStatements} counts as "one"; SQL without an ending semicolon comes back as is.
|
|
110
|
+
*/
|
|
111
|
+
function firstSqlStatement(sql) {
|
|
112
|
+
const { firstEnd } = scanSqlStatements(sql);
|
|
113
|
+
return firstEnd < 0 ? sql : sql.slice(0, firstEnd);
|
|
114
|
+
}
|
|
115
|
+
function scanSqlStatements(sql) {
|
|
116
|
+
let firstEnd = -1;
|
|
117
|
+
let state = 0;
|
|
118
|
+
let content = false;
|
|
119
|
+
let firstEnded = false;
|
|
120
|
+
let i = 0;
|
|
121
|
+
const n = sql.length;
|
|
122
|
+
while (i < n) {
|
|
123
|
+
const c = sql[i];
|
|
124
|
+
let token;
|
|
125
|
+
if (c === ";") token = SEMI;
|
|
126
|
+
else if (c === " " || c === " " || c === "\n" || c === "\r" || c === "\f") token = WS;
|
|
127
|
+
else if (c === "/" && sql[i + 1] === "*") {
|
|
128
|
+
const close = sql.indexOf("*/", i + 2);
|
|
129
|
+
if (close < 0) break;
|
|
130
|
+
i = close + 1;
|
|
131
|
+
token = WS;
|
|
132
|
+
} else if (c === "-" && sql[i + 1] === "-") {
|
|
133
|
+
const eol = sql.indexOf("\n", i);
|
|
134
|
+
if (eol < 0) break;
|
|
135
|
+
i = eol;
|
|
136
|
+
token = WS;
|
|
137
|
+
} else if (c === "[" || c === "`" || c === "\"" || c === "'") {
|
|
138
|
+
const close = sql.indexOf(c === "[" ? "]" : c, i + 1);
|
|
139
|
+
if (close < 0) return {
|
|
140
|
+
count: firstEnded ? "many" : "one",
|
|
141
|
+
firstEnd
|
|
142
|
+
};
|
|
143
|
+
i = close;
|
|
144
|
+
token = OTHER;
|
|
145
|
+
} else if (isIdChar(c)) {
|
|
146
|
+
let j = i + 1;
|
|
147
|
+
while (j < n && isIdChar(sql[j])) j++;
|
|
148
|
+
token = KEYWORDS[sql.slice(i, j).toLowerCase()] ?? OTHER;
|
|
149
|
+
i = j - 1;
|
|
150
|
+
} else token = OTHER;
|
|
151
|
+
if (token !== SEMI && token !== WS) {
|
|
152
|
+
if (firstEnded) return {
|
|
153
|
+
count: "many",
|
|
154
|
+
firstEnd
|
|
155
|
+
};
|
|
156
|
+
content = true;
|
|
157
|
+
}
|
|
158
|
+
state = TRANS[state]?.[token] ?? 2;
|
|
159
|
+
if (token === SEMI && state === 1 && content && !firstEnded) {
|
|
160
|
+
firstEnded = true;
|
|
161
|
+
firstEnd = i;
|
|
162
|
+
}
|
|
163
|
+
i++;
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
count: content ? "one" : "empty",
|
|
167
|
+
firstEnd
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
//#endregion
|
|
1
171
|
//#region src/sqlite-transaction.ts
|
|
2
172
|
/** Key under which a SQLite Db carries its transaction hook. Shared across bundles via Symbol.for. */
|
|
3
173
|
const SQLITE_TRANSACTION = Symbol.for("@statewalker/db-sqlite:transaction");
|
|
@@ -22,9 +192,47 @@ function newLock() {
|
|
|
22
192
|
return run;
|
|
23
193
|
};
|
|
24
194
|
}
|
|
195
|
+
const EMPTY_SQL = "db-sqlite: the SQL is empty (only whitespace, comments or semicolons)";
|
|
196
|
+
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)";
|
|
197
|
+
function checkSql(sql, one) {
|
|
198
|
+
if (typeof sql !== "string") throw new TypeError("db-sqlite: the SQL must be a string");
|
|
199
|
+
const count = countSqlStatements(sql);
|
|
200
|
+
if (count === "empty") throw new Error(EMPTY_SQL);
|
|
201
|
+
if (one && count === "many") throw new Error(MANY_STATEMENTS);
|
|
202
|
+
}
|
|
203
|
+
/** boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text; anything else is left as given. */
|
|
204
|
+
function toSqliteParam(value, index) {
|
|
205
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
206
|
+
if (value === void 0) return null;
|
|
207
|
+
if (value instanceof Date) {
|
|
208
|
+
if (Number.isNaN(value.getTime())) throw new RangeError(`db-sqlite: parameter ${index + 1} is an invalid Date`);
|
|
209
|
+
return value.toISOString();
|
|
210
|
+
}
|
|
211
|
+
return value;
|
|
212
|
+
}
|
|
213
|
+
const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);
|
|
214
|
+
const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);
|
|
215
|
+
/** Integers within ±(2^53 - 1) become numbers; larger ones stay bigints (no precision loss). */
|
|
216
|
+
function fromSqliteRows(rows) {
|
|
217
|
+
for (const row of rows) for (const key in row) {
|
|
218
|
+
const value = row[key];
|
|
219
|
+
if (typeof value === "bigint" && value >= MIN_SAFE && value <= MAX_SAFE) row[key] = Number(value);
|
|
220
|
+
}
|
|
221
|
+
return rows;
|
|
222
|
+
}
|
|
223
|
+
function runAll(engine, sql, params) {
|
|
224
|
+
checkSql(sql, true);
|
|
225
|
+
return fromSqliteRows(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));
|
|
226
|
+
}
|
|
227
|
+
function runExec(engine, sql) {
|
|
228
|
+
checkSql(sql, false);
|
|
229
|
+
engine.exec(sql);
|
|
230
|
+
}
|
|
25
231
|
/**
|
|
26
232
|
* Wrap an engine as a `Db` whose calls run one at a time, in call order, and which carries the
|
|
27
|
-
* `inTransaction` hook.
|
|
233
|
+
* `inTransaction` hook. Every SQLite driver gets the same input handling here: empty SQL rejects,
|
|
234
|
+
* `query` rejects a second statement, parameters are normalised and safe integers come back as
|
|
235
|
+
* numbers. The `tx` handed to a transaction callback bypasses the queue, has no hook
|
|
28
236
|
* (so nesting is rejected) and rejects once its transaction has finished.
|
|
29
237
|
*/
|
|
30
238
|
function newSerialisedSqliteDb(engine) {
|
|
@@ -55,11 +263,11 @@ function newSerialisedSqliteDb(engine) {
|
|
|
55
263
|
const tx = {
|
|
56
264
|
async query(sql, params = []) {
|
|
57
265
|
open();
|
|
58
|
-
return engine
|
|
266
|
+
return runAll(engine, sql, params);
|
|
59
267
|
},
|
|
60
268
|
async exec(sql) {
|
|
61
269
|
open();
|
|
62
|
-
engine
|
|
270
|
+
runExec(engine, sql);
|
|
63
271
|
},
|
|
64
272
|
async close() {
|
|
65
273
|
throw new Error("db-sqlite: close the outer Db, not the transaction handle");
|
|
@@ -74,11 +282,11 @@ function newSerialisedSqliteDb(engine) {
|
|
|
74
282
|
return {
|
|
75
283
|
query: (sql, params = []) => lock(async () => {
|
|
76
284
|
live();
|
|
77
|
-
return engine
|
|
285
|
+
return runAll(engine, sql, params);
|
|
78
286
|
}),
|
|
79
287
|
exec: (sql) => lock(async () => {
|
|
80
288
|
live();
|
|
81
|
-
engine
|
|
289
|
+
runExec(engine, sql);
|
|
82
290
|
}),
|
|
83
291
|
close: () => lock(async () => {
|
|
84
292
|
if (closed) return;
|
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 () => {\n if (closed)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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/sql-statements.ts","../src/sqlite-transaction.ts","../src/serialised-sqlite-db.ts"],"sourcesContent":["/**\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 { 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 (no boolean, undefined or\n * Date); `exec` runs every statement of a non-empty string. `transaction`, when present, replaces\n * `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\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/** boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text; anything else is left as given. */\nfunction toSqliteParam(value: unknown, index: number): unknown {\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 return value;\n}\n\nconst MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);\nconst MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);\n\n/** Integers within ±(2^53 - 1) become numbers; larger ones stay bigints (no precision loss). */\nfunction fromSqliteRows(rows: Record<string, unknown>[]): Record<string, unknown>[] {\n for (const row of rows) {\n for (const key in row) {\n const value = row[key];\n if (typeof value === \"bigint\" && value >= MIN_SAFE && value <= MAX_SAFE) {\n row[key] = Number(value);\n }\n }\n }\n return rows;\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 fromSqliteRows(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` whose calls run one at a time, in call order, and which carries the\n * `inTransaction` hook. Every SQLite driver gets the same input handling here: empty SQL rejects,\n * `query` rejects a second statement, parameters are normalised and safe integers come back as\n * numbers. 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 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 lock(async () => {\n live();\n return runAll(engine, sql, params) as T[];\n }),\n exec: (sql: string) =>\n lock(async () => {\n live();\n runExec(engine, sql);\n }),\n close: () =>\n lock(async () => {\n if (closed) return;\n closed = true;\n engine.close();\n }),\n [SQLITE_TRANSACTION]: transaction,\n } as Db;\n}\n"],"mappings":";AAYA,MAAM,OAAO;AACb,MAAM,KAAK;AACX,MAAM,QAAQ;AACd,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,MAAM;;AAGZ,MAAM,QAAQ;CACZ;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;AACzB;AAEA,MAAM,WAAmC;CACvC,QAAQ;CACR,MAAM;CACN,WAAW;CACX,SAAS;CACT,KAAK;CACL,SAAS;AACX;AAEA,MAAM,YAAY,MAAc,gBAAgB,KAAK,CAAC,KAAK,EAAE,WAAW,CAAC,KAAK;AAE9E,SAAgB,mBAAmB,KAAgC;CACjE,OAAO,kBAAkB,GAAG,CAAC,CAAC;AAChC;;;;;;;AAQA,SAAgB,kBAAkB,KAAqB;CACrD,MAAM,EA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A2D;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,QAAQ,KAAK,MAAM;EACnC,CAAC;EACH,OAAO,QACL,KAAK,YAAY;GACf,KAAK;GACL,QAAQ,QAAQ,GAAG;EACrB,CAAC;EACH,aACE,KAAK,YAAY;GACf,IAAI,QAAQ;GACZ,SAAS;GACT,OAAO,MAAM;EACf,CAAC;GACF,qBAAqB;CACxB;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.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "SQLite transactions for @statewalker/db-api: inTransaction(db, cb) and the serialised engine wrapper every SQLite driver uses.",
|
|
@@ -22,22 +22,24 @@
|
|
|
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.6"
|
|
34
36
|
},
|
|
35
37
|
"devDependencies": {
|
|
36
38
|
"@types/node": "^26.6.4",
|
|
37
39
|
"rimraf": "^6.1.3",
|
|
38
40
|
"tsdown": "^0.23.0",
|
|
39
41
|
"typescript": "^7.0.2",
|
|
40
|
-
"vitest": "^5.0.3"
|
|
42
|
+
"vitest": "^4.1.10 || ^5.0.3"
|
|
41
43
|
},
|
|
42
44
|
"sideEffects": false,
|
|
43
45
|
"publishConfig": {
|
|
@@ -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 .",
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import type { Db, DbEntry } from "@statewalker/db-api";
|
|
2
|
+
import { countSqlStatements, firstSqlStatement } from "./sql-statements.js";
|
|
2
3
|
import { SQLITE_TRANSACTION, type SqliteTransactionHook } from "./sqlite-transaction.js";
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
|
-
* The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array
|
|
6
|
-
*
|
|
7
|
-
*
|
|
6
|
+
* The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array; integers
|
|
7
|
+
* as numbers or bigints, which the wrapper turns into numbers when they are safe) and is given
|
|
8
|
+
* exactly one non-empty statement and parameters already normalised (no boolean, undefined or
|
|
9
|
+
* Date); `exec` runs every statement of a non-empty string. `transaction`, when present, replaces
|
|
10
|
+
* `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects forbid them in SQL).
|
|
8
11
|
*/
|
|
9
12
|
export type SqliteEngine = {
|
|
10
13
|
all(sql: string, params: unknown[]): Record<string, unknown>[];
|
|
@@ -22,9 +25,63 @@ function newLock() {
|
|
|
22
25
|
};
|
|
23
26
|
}
|
|
24
27
|
|
|
28
|
+
const EMPTY_SQL = "db-sqlite: the SQL is empty (only whitespace, comments or semicolons)";
|
|
29
|
+
const MANY_STATEMENTS =
|
|
30
|
+
"db-sqlite: query runs one statement, and this SQL has more after the first; " +
|
|
31
|
+
"run them one query at a time, or use exec (no parameters, no rows)";
|
|
32
|
+
|
|
33
|
+
function checkSql(sql: string, one: boolean): void {
|
|
34
|
+
if (typeof sql !== "string") throw new TypeError("db-sqlite: the SQL must be a string");
|
|
35
|
+
const count = countSqlStatements(sql);
|
|
36
|
+
if (count === "empty") throw new Error(EMPTY_SQL);
|
|
37
|
+
if (one && count === "many") throw new Error(MANY_STATEMENTS);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text; anything else is left as given. */
|
|
41
|
+
function toSqliteParam(value: unknown, index: number): unknown {
|
|
42
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
43
|
+
if (value === undefined) return null;
|
|
44
|
+
if (value instanceof Date) {
|
|
45
|
+
if (Number.isNaN(value.getTime())) {
|
|
46
|
+
throw new RangeError(`db-sqlite: parameter ${index + 1} is an invalid Date`);
|
|
47
|
+
}
|
|
48
|
+
return value.toISOString();
|
|
49
|
+
}
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);
|
|
54
|
+
const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);
|
|
55
|
+
|
|
56
|
+
/** Integers within ±(2^53 - 1) become numbers; larger ones stay bigints (no precision loss). */
|
|
57
|
+
function fromSqliteRows(rows: Record<string, unknown>[]): Record<string, unknown>[] {
|
|
58
|
+
for (const row of rows) {
|
|
59
|
+
for (const key in row) {
|
|
60
|
+
const value = row[key];
|
|
61
|
+
if (typeof value === "bigint" && value >= MIN_SAFE && value <= MAX_SAFE) {
|
|
62
|
+
row[key] = Number(value);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return rows;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function runAll(engine: SqliteEngine, sql: string, params: unknown[]): Record<string, unknown>[] {
|
|
70
|
+
checkSql(sql, true);
|
|
71
|
+
// Only the statement itself reaches the engine: DO SQLite rejects an empty tail ("; -- c ;").
|
|
72
|
+
return fromSqliteRows(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function runExec(engine: SqliteEngine, sql: string): void {
|
|
76
|
+
checkSql(sql, false);
|
|
77
|
+
engine.exec(sql);
|
|
78
|
+
}
|
|
79
|
+
|
|
25
80
|
/**
|
|
26
81
|
* Wrap an engine as a `Db` whose calls run one at a time, in call order, and which carries the
|
|
27
|
-
* `inTransaction` hook.
|
|
82
|
+
* `inTransaction` hook. Every SQLite driver gets the same input handling here: empty SQL rejects,
|
|
83
|
+
* `query` rejects a second statement, parameters are normalised and safe integers come back as
|
|
84
|
+
* numbers. The `tx` handed to a transaction callback bypasses the queue, has no hook
|
|
28
85
|
* (so nesting is rejected) and rejects once its transaction has finished.
|
|
29
86
|
*/
|
|
30
87
|
export function newSerialisedSqliteDb(engine: SqliteEngine): Db {
|
|
@@ -61,11 +118,11 @@ export function newSerialisedSqliteDb(engine: SqliteEngine): Db {
|
|
|
61
118
|
const tx: Db = {
|
|
62
119
|
async query<T = DbEntry>(sql: string, params: unknown[] = []): Promise<T[]> {
|
|
63
120
|
open();
|
|
64
|
-
return engine
|
|
121
|
+
return runAll(engine, sql, params) as T[];
|
|
65
122
|
},
|
|
66
123
|
async exec(sql: string): Promise<void> {
|
|
67
124
|
open();
|
|
68
|
-
engine
|
|
125
|
+
runExec(engine, sql);
|
|
69
126
|
},
|
|
70
127
|
async close(): Promise<void> {
|
|
71
128
|
throw new Error("db-sqlite: close the outer Db, not the transaction handle");
|
|
@@ -82,12 +139,12 @@ export function newSerialisedSqliteDb(engine: SqliteEngine): Db {
|
|
|
82
139
|
query: <T = DbEntry>(sql: string, params: unknown[] = []) =>
|
|
83
140
|
lock(async () => {
|
|
84
141
|
live();
|
|
85
|
-
return engine
|
|
142
|
+
return runAll(engine, sql, params) as T[];
|
|
86
143
|
}),
|
|
87
144
|
exec: (sql: string) =>
|
|
88
145
|
lock(async () => {
|
|
89
146
|
live();
|
|
90
|
-
engine
|
|
147
|
+
runExec(engine, sql);
|
|
91
148
|
}),
|
|
92
149
|
close: () =>
|
|
93
150
|
lock(async () => {
|
|
@@ -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
|
+
}
|