@noego/sqlego 0.0.1 → 0.0.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/src/protocol.ts CHANGED
@@ -6,19 +6,48 @@
6
6
  * two clients' statements interleave at statement (or batch) granularity and
7
7
  * never contend for SQLite's write lock.
8
8
  *
9
- * There is deliberately no BEGIN/COMMIT over the wire: a client-held
10
- * transaction would hold the file's only writer hostage to that client's
11
- * liveness. `batch` is the transactional unit.
9
+ * Transactions over the wire are leased, never bare: `begin` opens one bound
10
+ * to the client's socket, `query`/`run` carry its `txId`, and `commit` or
11
+ * `rollback` ends it. The server rolls it back on its own when the socket
12
+ * closes, when no request arrives within the lease, or when it has been open
13
+ * longer than the server's hard cap, so a client can never hold the file's
14
+ * only writer hostage. Transaction-control SQL (`BEGIN`, `COMMIT`, ...) is
15
+ * refused as plain `query`/`run`; savepoints are allowed inside a transaction.
16
+ *
17
+ * Values JSON cannot hold travel as one-key tagged objects, validated
18
+ * strictly in both directions: `{ "$bigint": "<decimal>" }` for a signed
19
+ * 64-bit integer and `{ "$blob": "<base64>" }` for bytes (possibly zero of
20
+ * them). Parameters of every op may use them; `statement` and `exec` results
21
+ * use them (`query`/`run`/`batch` results keep their protocol-2 encoding).
12
22
  */
13
23
 
14
24
  import { Result, Trust } from '@noego/trust';
15
25
 
16
- export const PROTOCOL_VERSION = 1;
26
+ export const PROTOCOL_VERSION = 3;
17
27
 
18
28
  export type SqlParams = ReadonlyArray<SqlValue> | Readonly<Record<string, SqlValue>>;
19
29
  export type SqlValue = string | number | bigint | boolean | null | Uint8Array;
20
30
  export type SqlRow = Record<string, unknown>;
21
31
 
32
+ /** A signed 64-bit integer on the wire: its decimal text. */
33
+ export type WireBigInt = Readonly<{ $bigint: string }>;
34
+ /** Bytes on the wire: standard base64 (padded); `""` is a zero-length blob. */
35
+ export type WireBlob = Readonly<{ $blob: string }>;
36
+ export type WireValue = string | number | boolean | null | WireBigInt | WireBlob;
37
+ export type WireInteger = number | WireBigInt;
38
+ export type WireRow = Record<string, WireValue>;
39
+ export type WireParams = ReadonlyArray<unknown> | Readonly<Record<string, unknown>>;
40
+
41
+ export const INT64_MIN = -9223372036854775808n;
42
+ export const INT64_MAX = 9223372036854775807n;
43
+ /** ±(2^53 - 1): the integers a JSON number carries exactly. */
44
+ const SAFE_MIN = -9007199254740991n;
45
+ const SAFE_MAX = 9007199254740991n;
46
+ /** Canonical decimal: no leading zeros, no `-0`, no sign on zero, at most 19 digits. */
47
+ const DECIMAL_INTEGER = /^(?:0|-?[1-9][0-9]{0,18})$/;
48
+ /** Canonical padded base64. */
49
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
50
+
22
51
  export type Statement = Readonly<{
23
52
  sql: string;
24
53
  params?: SqlParams;
@@ -26,17 +55,53 @@ export type Statement = Readonly<{
26
55
  mode?: 'query' | 'run';
27
56
  }>;
28
57
 
58
+ export type TransactionMode = 'deferred' | 'immediate';
59
+
29
60
  export type Request =
30
61
  | { id: number; op: 'hello'; clientVersion: string; protocol: number }
31
- | { id: number; op: 'query'; sql: string; params?: SqlParams }
32
- | { id: number; op: 'run'; sql: string; params?: SqlParams }
62
+ | { id: number; op: 'query'; sql: string; params?: SqlParams; txId?: number }
63
+ | { id: number; op: 'run'; sql: string; params?: SqlParams; txId?: number }
64
+ /** Exactly one statement; rows when it has result columns (incl. `RETURNING`), plus its changes. */
65
+ | { id: number; op: 'statement'; sql: string; params?: SqlParams; txId?: number }
66
+ /** Any number of statements, no parameters, run in order until the first failure. */
67
+ | { id: number; op: 'exec'; sql: string; txId?: number }
33
68
  | { id: number; op: 'batch'; statements: readonly Statement[] }
69
+ | { id: number; op: 'begin'; mode?: TransactionMode; leaseMs?: number }
70
+ | { id: number; op: 'commit'; txId: number }
71
+ | { id: number; op: 'rollback'; txId: number }
34
72
  | { id: number; op: 'status' }
35
73
  | { id: number; op: 'stop' };
36
74
 
37
75
  export type RunResult = Readonly<{ changes: number; lastInsertRowid: number | bigint }>;
38
76
  export type QueryResult = Readonly<{ rows: SqlRow[] }>;
39
77
  export type BatchResult = Readonly<{ results: ReadonlyArray<RunResult | QueryResult> }>;
78
+ /**
79
+ * One `statement`: whether it has result columns (`reader`), its rows, the rows
80
+ * it changed (0 for a read), and the connection's last insert rowid. Integers
81
+ * beyond ±2^53-1 come back as `bigint`, blobs as `Uint8Array`.
82
+ */
83
+ export type StatementResult<Row extends SqlRow = SqlRow> = Readonly<{ reader: boolean; rows: Row[]; changes: number; lastInsertRowid: number | bigint }>;
84
+ /** One `exec`: how many statements ran and the rows they changed in total. */
85
+ export type ExecResult = Readonly<{ statements: number; changes: number; lastInsertRowid: number | bigint }>;
86
+ /** The wire forms the server sends for `statement` / `exec`. */
87
+ export type StatementWireResult = Readonly<{ reader: boolean; rows: WireRow[]; changes: number; lastInsertRowid: WireInteger }>;
88
+ export type ExecWireResult = Readonly<{ statements: number; changes: number; lastInsertRowid: WireInteger }>;
89
+ /** The lease the server granted (its own cap applies) and the hard cap on the transaction's life. */
90
+ export type BeginResult = Readonly<{ txId: number; leaseMs: number; maxDurationMs: number }>;
91
+ export type TransactionEndResult = Readonly<{ txId: number }>;
92
+
93
+ /** The open transaction as `status` reports it. */
94
+ export type TransactionStatus = Readonly<{
95
+ txId: number;
96
+ /** How long it has been open. */
97
+ ageMs: number;
98
+ /** Since its last request. */
99
+ idleMs: number;
100
+ leaseMs: number;
101
+ maxDurationMs: number;
102
+ /** Requests from other clients waiting for it to end. */
103
+ queued: number;
104
+ }>;
40
105
 
41
106
  export type HelloResult = Readonly<{
42
107
  serverVersion: string;
@@ -56,6 +121,7 @@ export type StatusResult = Readonly<{
56
121
  idleMs: number | null;
57
122
  idleTimeoutMs: number;
58
123
  requestsServed: number;
124
+ transaction: TransactionStatus | null;
59
125
  }>;
60
126
 
61
127
  export type ErrorCode =
@@ -64,7 +130,13 @@ export type ErrorCode =
64
130
  | 'protocol-mismatch'
65
131
  | 'shutting-down'
66
132
  /** The server could not serialize a result (a value JSON cannot hold). */
67
- | 'encode-failed';
133
+ | 'encode-failed'
134
+ /** The transaction was rolled back by the server: lease ran out, hard cap hit, or SQLite aborted it. */
135
+ | 'tx-expired'
136
+ /** No such open transaction on this connection (wrong id, already ended, or a second `begin`). */
137
+ | 'tx-invalid'
138
+ /** Another client's transaction kept the request waiting past the server's queue limit. */
139
+ | 'tx-busy';
68
140
 
69
141
  export type Response =
70
142
  | { id: number; ok: true; result: unknown }
@@ -92,6 +164,150 @@ export function encodeFrame(message: Request | Response) {
92
164
  return Result.ok(`${json.value}\n`);
93
165
  }
94
166
 
167
+ /**
168
+ * One request frame with its parameters in wire form: every `bigint` and
169
+ * `Uint8Array` parameter becomes its tag; other values go as they are (the
170
+ * server validates them). A `bigint` outside the signed 64-bit range is a
171
+ * `bad-request` here, before anything is sent.
172
+ */
173
+ export function encodeRequestFrame(request: Request) {
174
+ const wire = encodeRequestParams(request);
175
+ if (!wire.ok) return Result.err({ kind: 'bad-request' as const, message: wire.error.message });
176
+ const json = toJson(wire.value);
177
+ if (!json.ok) return json;
178
+ return Result.ok(`${json.value}\n`);
179
+ }
180
+
181
+ function encodeRequestParams(request: Request) {
182
+ switch (request.op) {
183
+ case 'query':
184
+ case 'run':
185
+ case 'statement': {
186
+ if (request.params === undefined) return Result.ok<unknown>(request);
187
+ const params = encodeSqlParams(request.params);
188
+ if (!params.ok) return params;
189
+ return Result.ok<unknown>({ ...request, params: params.value });
190
+ }
191
+ case 'batch': {
192
+ const statements: unknown[] = [];
193
+ for (const [index, statement] of request.statements.entries()) {
194
+ if (statement.params === undefined) {
195
+ statements.push(statement);
196
+ continue;
197
+ }
198
+ const params = encodeSqlParams(statement.params);
199
+ if (!params.ok) return invalid(`statements[${index}].${params.error.message}`);
200
+ statements.push({ ...statement, params: params.value });
201
+ }
202
+ return Result.ok<unknown>({ ...request, statements });
203
+ }
204
+ default:
205
+ return Result.ok<unknown>(request);
206
+ }
207
+ }
208
+
209
+ /** Positional or named parameters in wire form; see `encodeRequestFrame`. */
210
+ export function encodeSqlParams(params: SqlParams) {
211
+ if (typeof params !== 'object' || params === null) return invalid('params must be an array or an object');
212
+ const shape = paramsShape(params);
213
+ if (shape.kind === 'positional') {
214
+ const values: unknown[] = [];
215
+ for (const [index, item] of shape.values.entries()) {
216
+ const value = encodeParamValue(item);
217
+ if (!value.ok) return invalid(`params[${index}]: ${value.error.message}`);
218
+ values.push(value.value);
219
+ }
220
+ return Result.ok<WireParams>(values);
221
+ }
222
+ const entries: Array<[string, unknown]> = [];
223
+ for (const [name, item] of Object.entries(shape.values)) {
224
+ const value = encodeParamValue(item);
225
+ if (!value.ok) return invalid(`params.${name}: ${value.error.message}`);
226
+ entries.push([name, value.value]);
227
+ }
228
+ return Result.ok<WireParams>(Object.fromEntries(entries));
229
+ }
230
+
231
+ /**
232
+ * Tells the positional form from the named one; `Array.isArray` cannot narrow
233
+ * a readonly array without widening it to `any[]`.
234
+ */
235
+ //trust:validator_function
236
+ function paramsShape(params: SqlParams):
237
+ | { kind: 'positional'; values: readonly SqlValue[] }
238
+ | { kind: 'named'; values: Readonly<Record<string, SqlValue>> } {
239
+ return Array.isArray(params)
240
+ ? { kind: 'positional', values: params as readonly SqlValue[] }
241
+ : { kind: 'named', values: params as Readonly<Record<string, SqlValue>> };
242
+ }
243
+
244
+ /** A parameter's wire form: `bigint` and bytes are tagged, anything else passes through unchanged. */
245
+ function encodeParamValue(value: unknown) {
246
+ if (typeof value === 'bigint') return encodeBigInt(value);
247
+ if (value instanceof Uint8Array) return encodeBlob(value);
248
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return Result.ok<WireValue>(value);
249
+ if (typeof value === 'number' && Number.isFinite(value)) return Result.ok<WireValue>(value);
250
+ return invalid('a parameter must be a finite number, string, boolean, null, bigint or Uint8Array');
251
+ }
252
+
253
+ function encodeBigInt(value: bigint) {
254
+ if (value < INT64_MIN || value > INT64_MAX) return invalid(`integer ${value} overflows a signed 64-bit integer`);
255
+ return Result.ok<WireValue>({ $bigint: String(value) });
256
+ }
257
+
258
+ function encodeBlob(bytes: Uint8Array) {
259
+ const encoded = Trust.try(
260
+ () => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64'),
261
+ (cause) => ({ kind: 'invalid' as const, message: `cannot encode a blob: ${errorMessage(cause)}` }),
262
+ );
263
+ if (!encoded.ok) return encoded;
264
+ return Result.ok<WireValue>({ $blob: encoded.value });
265
+ }
266
+
267
+ /**
268
+ * An integer result in wire form: a JSON number when it is exactly
269
+ * representable (|n| ≤ 2^53-1), else its `$bigint` tag.
270
+ */
271
+ export function encodeWireInteger(value: number | bigint): WireInteger {
272
+ if (typeof value === 'number') return value;
273
+ if (value >= SAFE_MIN && value <= SAFE_MAX) return Number(value);
274
+ return { $bigint: String(value) };
275
+ }
276
+
277
+ /**
278
+ * One value SQLite returned, in wire form, losslessly: integers as
279
+ * `encodeWireInteger`, bytes as `$blob`. A REAL JSON cannot hold (±Infinity)
280
+ * is refused rather than sent as `null`.
281
+ */
282
+ export function encodeResultValue(value: unknown) {
283
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return Result.ok<WireValue>(value);
284
+ if (typeof value === 'number') {
285
+ return Number.isFinite(value) ? Result.ok<WireValue>(value) : invalid(`the REAL ${value} has no JSON form`);
286
+ }
287
+ if (typeof value === 'bigint') return Result.ok<WireValue>(encodeWireInteger(value));
288
+ if (value instanceof Uint8Array) return encodeBlob(value);
289
+ return invalid(`a result value must be a string, number, bigint, blob or null, not ${typeof value}`);
290
+ }
291
+
292
+ /** Rows as SQLite returned them (`unknown`), in wire form. */
293
+ export function encodeResultRows(input: unknown) {
294
+ if (!Array.isArray(input)) return invalid('rows must be an array');
295
+ const rows: WireRow[] = [];
296
+ for (const [index, item] of input.entries()) {
297
+ const fields = fieldsOf(item);
298
+ if (!fields) return invalid(`rows[${index}] must be an object`);
299
+ const entries: Array<[string, WireValue]> = [];
300
+ for (const [column, raw] of Object.entries(fields)) {
301
+ const value = encodeResultValue(raw);
302
+ if (!value.ok) return invalid(`rows[${index}].${column}: ${value.error.message}`);
303
+ entries.push([column, value.value]);
304
+ }
305
+ const row: WireRow = Object.fromEntries(entries);
306
+ rows.push(row);
307
+ }
308
+ return Result.ok(rows);
309
+ }
310
+
95
311
  /** Parses JSON text into `unknown`; what it holds is for a validator to decide. */
96
312
  export function fromJson(text: string) {
97
313
  return Trust.try(
@@ -118,15 +334,70 @@ function fieldsOf(input: unknown): Fields | null {
118
334
  return typeof input === 'object' && input !== null && !Array.isArray(input) ? (input as Fields) : null;
119
335
  }
120
336
 
121
- /** A value that survives JSON and SQLite binding: string, number, boolean or null. */
337
+ /**
338
+ * A value that survives JSON and SQLite binding: string, number, boolean or
339
+ * null, or a `$bigint` / `$blob` tag decoded to `bigint` / `Uint8Array`.
340
+ */
122
341
  //trust:validator_function
123
342
  export function parseSqlValue(input: unknown) {
124
- if (input === null || typeof input === 'string' || typeof input === 'number' || typeof input === 'boolean') {
343
+ if (input === null || typeof input === 'string' || typeof input === 'boolean' || (typeof input === 'number' && Number.isFinite(input))) {
125
344
  return Result.ok<SqlValue>(input);
126
345
  }
346
+ const fields = fieldsOf(input);
347
+ if (fields && ('$bigint' in fields || '$blob' in fields)) return parseTypedValue(fields);
127
348
  return invalid(`a SQL value must be a string, number, boolean or null, not ${Array.isArray(input) ? 'an array' : typeof input}`);
128
349
  }
129
350
 
351
+ /** A tagged value: exactly one key, `$bigint` or `$blob`, holding its canonical text. */
352
+ //trust:validator_function
353
+ function parseTypedValue(fields: Fields) {
354
+ const keys = Object.keys(fields);
355
+ if (keys.length !== 1) return invalid(`a typed value has exactly one key ($bigint or $blob), not ${keys.length}`);
356
+ if (keys[0] === '$bigint') return parseWireBigInt(fields.$bigint);
357
+ if (keys[0] === '$blob') return parseWireBlob(fields.$blob);
358
+ return invalid(`unknown typed value ${keys[0]}`);
359
+ }
360
+
361
+ /** Canonical decimal text of a signed 64-bit integer. */
362
+ //trust:validator_function
363
+ function parseWireBigInt(input: unknown) {
364
+ if (typeof input !== 'string' || !DECIMAL_INTEGER.test(input)) return invalid('$bigint must be a canonical decimal integer string');
365
+ const parsed = Trust.try(
366
+ () => BigInt(input),
367
+ (cause) => ({ kind: 'invalid' as const, message: `$bigint ${input}: ${errorMessage(cause)}` }),
368
+ );
369
+ if (!parsed.ok) return parsed;
370
+ if (parsed.value < INT64_MIN || parsed.value > INT64_MAX) return invalid(`$bigint ${input} overflows a signed 64-bit integer`);
371
+ return Result.ok<SqlValue>(parsed.value);
372
+ }
373
+
374
+ /** Canonical padded base64; the empty string is a zero-length blob. */
375
+ //trust:validator_function
376
+ function parseWireBlob(input: unknown) {
377
+ if (typeof input !== 'string' || !BASE64.test(input)) return invalid('$blob must be canonical padded base64');
378
+ const decoded = Trust.try(
379
+ () => {
380
+ const bytes = Buffer.from(input, 'base64');
381
+ return { bytes: new Uint8Array(bytes), canonical: bytes.toString('base64') };
382
+ },
383
+ (cause) => ({ kind: 'invalid' as const, message: `$blob: ${errorMessage(cause)}` }),
384
+ );
385
+ if (!decoded.ok) return decoded;
386
+ if (decoded.value.canonical !== input) return invalid('$blob must be canonical padded base64');
387
+ return Result.ok<SqlValue>(decoded.value.bytes);
388
+ }
389
+
390
+ /** An integer result: a JSON number or a `$bigint` tag. */
391
+ //trust:validator_function
392
+ function parseWireInteger(input: unknown, at: string) {
393
+ if (typeof input === 'number' && Number.isSafeInteger(input)) return Result.ok<number | bigint>(input);
394
+ const fields = fieldsOf(input);
395
+ if (!fields || !('$bigint' in fields) || Object.keys(fields).length !== 1) return invalid(`${at} must be a number or a $bigint`);
396
+ const value = parseWireBigInt(fields.$bigint);
397
+ if (!value.ok) return invalid(`${at}: ${value.error.message}`);
398
+ return typeof value.value === 'bigint' ? Result.ok<number | bigint>(value.value) : invalid(`${at} must be a number or a $bigint`);
399
+ }
400
+
130
401
  /** Positional (`[...]`) or named (`{ name: value }`) parameters. */
131
402
  //trust:validator_function
132
403
  export function parseSqlParams(input: unknown) {
@@ -141,13 +412,13 @@ export function parseSqlParams(input: unknown) {
141
412
  }
142
413
  const fields = fieldsOf(input);
143
414
  if (!fields) return invalid('params must be an array or an object');
144
- const named: Record<string, SqlValue> = {};
415
+ const entries: Array<[string, SqlValue]> = [];
145
416
  for (const [name, item] of Object.entries(fields)) {
146
417
  const value = parseSqlValue(item);
147
418
  if (!value.ok) return invalid(`params.${name}: ${value.error.message}`);
148
- named[name] = value.value;
419
+ entries.push([name, value.value]);
149
420
  }
150
- return Result.ok<SqlParams>(named);
421
+ return Result.ok<SqlParams>(Object.fromEntries(entries));
151
422
  }
152
423
 
153
424
  /** `params` when present; absent (`undefined`) is allowed. */
@@ -190,11 +461,36 @@ export function parseRequest(input: unknown) {
190
461
  return Result.ok(request);
191
462
  }
192
463
  case 'query':
193
- case 'run': {
464
+ case 'run':
465
+ case 'statement': {
194
466
  if (typeof fields.sql !== 'string') return reject(id, `${fields.op} needs sql (string)`);
195
467
  const params = parseOptionalParams(fields.params);
196
468
  if (!params.ok) return reject(id, params.error.message);
197
- const request: Request = { id, op: fields.op, sql: fields.sql, params: params.value };
469
+ const txId = fields.txId;
470
+ if (txId !== undefined && typeof txId !== 'number') return reject(id, 'txId must be a number');
471
+ const request: Request = { id, op: fields.op, sql: fields.sql, params: params.value, txId };
472
+ return Result.ok(request);
473
+ }
474
+ case 'exec': {
475
+ if (typeof fields.sql !== 'string') return reject(id, 'exec needs sql (string)');
476
+ if (fields.params !== undefined) return reject(id, 'exec takes no params: bind values with statement');
477
+ const txId = fields.txId;
478
+ if (txId !== undefined && typeof txId !== 'number') return reject(id, 'txId must be a number');
479
+ const request: Request = { id, op: 'exec', sql: fields.sql, txId };
480
+ return Result.ok(request);
481
+ }
482
+ case 'begin': {
483
+ const mode = fields.mode;
484
+ if (mode !== undefined && mode !== 'deferred' && mode !== 'immediate') return reject(id, 'begin mode must be "deferred" or "immediate"');
485
+ const leaseMs = fields.leaseMs;
486
+ if (leaseMs !== undefined && (typeof leaseMs !== 'number' || !(leaseMs > 0))) return reject(id, 'leaseMs must be a positive number');
487
+ const request: Request = { id, op: 'begin', mode, leaseMs };
488
+ return Result.ok(request);
489
+ }
490
+ case 'commit':
491
+ case 'rollback': {
492
+ if (typeof fields.txId !== 'number') return reject(id, `${fields.op} needs txId (number)`);
493
+ const request: Request = { id, op: fields.op, txId: fields.txId };
198
494
  return Result.ok(request);
199
495
  }
200
496
  case 'batch': {
@@ -218,7 +514,9 @@ export function parseRequest(input: unknown) {
218
514
  }
219
515
  }
220
516
 
221
- const ERROR_CODES: readonly ErrorCode[] = ['sqlite', 'bad-request', 'protocol-mismatch', 'shutting-down', 'encode-failed'];
517
+ const ERROR_CODES: readonly ErrorCode[] = [
518
+ 'sqlite', 'bad-request', 'protocol-mismatch', 'shutting-down', 'encode-failed', 'tx-expired', 'tx-invalid', 'tx-busy',
519
+ ];
222
520
 
223
521
  //trust:validator_function
224
522
  function parseErrorCode(input: unknown) {
@@ -301,6 +599,52 @@ export function parseBatchResult(input: unknown) {
301
599
  return Result.ok(result);
302
600
  }
303
601
 
602
+ /** Rows whose every value is a wire value; tags are decoded, and a malformed one fails the whole reply. */
603
+ //trust:validator_function
604
+ function parseWireRows(input: unknown) {
605
+ if (!Array.isArray(input)) return invalid('rows must be an array');
606
+ const rows: SqlRow[] = [];
607
+ for (const [index, item] of input.entries()) {
608
+ const fields = fieldsOf(item);
609
+ if (!fields) return invalid(`rows[${index}] must be an object`);
610
+ const entries: Array<[string, SqlValue]> = [];
611
+ for (const [column, raw] of Object.entries(fields)) {
612
+ const value = parseSqlValue(raw);
613
+ if (!value.ok) return invalid(`rows[${index}].${column}: ${value.error.message}`);
614
+ entries.push([column, value.value]);
615
+ }
616
+ // fromEntries defines own properties, so a column named __proto__ stays a column.
617
+ const row: SqlRow = Object.fromEntries(entries);
618
+ rows.push(row);
619
+ }
620
+ return Result.ok(rows);
621
+ }
622
+
623
+ //trust:validator_function
624
+ export function parseStatementResult(input: unknown) {
625
+ const fields = fieldsOf(input);
626
+ if (!fields || typeof fields.reader !== 'boolean' || typeof fields.changes !== 'number') return invalid('a statement result needs reader (boolean), rows, changes (number) and lastInsertRowid');
627
+ const rows = parseWireRows(fields.rows);
628
+ if (!rows.ok) return rows;
629
+ const rowid = parseWireInteger(fields.lastInsertRowid, 'lastInsertRowid');
630
+ if (!rowid.ok) return rowid;
631
+ if (!fields.reader && rows.value.length > 0) return invalid('a non-reader statement cannot return rows');
632
+ const result: StatementResult = { reader: fields.reader, rows: rows.value, changes: fields.changes, lastInsertRowid: rowid.value };
633
+ return Result.ok(result);
634
+ }
635
+
636
+ //trust:validator_function
637
+ export function parseExecResult(input: unknown) {
638
+ const fields = fieldsOf(input);
639
+ if (!fields || typeof fields.changes !== 'number' || typeof fields.statements !== 'number') {
640
+ return invalid('an exec result needs statements (number), changes (number) and lastInsertRowid');
641
+ }
642
+ const rowid = parseWireInteger(fields.lastInsertRowid, 'lastInsertRowid');
643
+ if (!rowid.ok) return rowid;
644
+ const result: ExecResult = { statements: fields.statements, changes: fields.changes, lastInsertRowid: rowid.value };
645
+ return Result.ok(result);
646
+ }
647
+
304
648
  //trust:validator_function
305
649
  export function parseHelloResult(input: unknown) {
306
650
  const fields = fieldsOf(input);
@@ -315,6 +659,40 @@ export function parseHelloResult(input: unknown) {
315
659
  return Result.ok(result);
316
660
  }
317
661
 
662
+ //trust:validator_function
663
+ export function parseBeginResult(input: unknown) {
664
+ const f = fieldsOf(input);
665
+ if (!f || typeof f.txId !== 'number' || typeof f.leaseMs !== 'number' || typeof f.maxDurationMs !== 'number') {
666
+ return invalid('a begin result needs txId, leaseMs and maxDurationMs (numbers)');
667
+ }
668
+ const result: BeginResult = { txId: f.txId, leaseMs: f.leaseMs, maxDurationMs: f.maxDurationMs };
669
+ return Result.ok(result);
670
+ }
671
+
672
+ //trust:validator_function
673
+ export function parseTransactionEndResult(input: unknown) {
674
+ const f = fieldsOf(input);
675
+ if (!f || typeof f.txId !== 'number') return invalid('a commit/rollback result needs txId (number)');
676
+ const result: TransactionEndResult = { txId: f.txId };
677
+ return Result.ok(result);
678
+ }
679
+
680
+ //trust:validator_function
681
+ function parseTransactionStatus(input: unknown) {
682
+ if (input === null) return Result.ok<TransactionStatus | null>(null);
683
+ const f = fieldsOf(input);
684
+ if (
685
+ !f || typeof f.txId !== 'number' || typeof f.ageMs !== 'number' || typeof f.idleMs !== 'number'
686
+ || typeof f.leaseMs !== 'number' || typeof f.maxDurationMs !== 'number' || typeof f.queued !== 'number'
687
+ ) {
688
+ return invalid('status.transaction must be null or carry txId, ageMs, idleMs, leaseMs, maxDurationMs and queued');
689
+ }
690
+ const status: TransactionStatus = {
691
+ txId: f.txId, ageMs: f.ageMs, idleMs: f.idleMs, leaseMs: f.leaseMs, maxDurationMs: f.maxDurationMs, queued: f.queued,
692
+ };
693
+ return Result.ok<TransactionStatus | null>(status);
694
+ }
695
+
318
696
  //trust:validator_function
319
697
  export function parseStatusResult(input: unknown) {
320
698
  const f = fieldsOf(input);
@@ -327,13 +705,165 @@ export function parseStatusResult(input: unknown) {
327
705
  ) {
328
706
  return invalid('a status result is missing a field or has one of the wrong type');
329
707
  }
708
+ const transaction = parseTransactionStatus(f.transaction);
709
+ if (!transaction.ok) return transaction;
330
710
  const result: StatusResult = {
331
711
  file: f.file, socket: f.socket, pid: f.pid, serverVersion: f.serverVersion, protocol: f.protocol,
332
712
  clients: f.clients, uptimeMs: f.uptimeMs, idleMs: f.idleMs, idleTimeoutMs: f.idleTimeoutMs, requestsServed: f.requestsServed,
713
+ transaction: transaction.value,
333
714
  };
334
715
  return Result.ok(result);
335
716
  }
336
717
 
718
+ /**
719
+ * The transaction-control statement a SQL text starts with, or null. Leading
720
+ * whitespace and comments are skipped so `/* x *\/ BEGIN` is still seen.
721
+ * `ROLLBACK TO` (a savepoint) is told apart from a bare `ROLLBACK`.
722
+ */
723
+ export function transactionControl(sql: string): 'begin' | 'commit' | 'rollback' | 'savepoint' | 'release' | 'rollback-to' | null {
724
+ const body = sql.replace(/^(?:\s+|--[^\n]*\n?|\/\*[\s\S]*?\*\/)+/, '');
725
+ const match = /^(BEGIN|START|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b(\s+TRANSACTION\b)?(\s+TO\b)?/i.exec(body);
726
+ if (!match) return null;
727
+ switch (match[1].toUpperCase()) {
728
+ case 'BEGIN':
729
+ case 'START': return 'begin';
730
+ case 'COMMIT':
731
+ case 'END': return 'commit';
732
+ case 'ROLLBACK': return match[3] ? 'rollback-to' : 'rollback';
733
+ case 'SAVEPOINT': return 'savepoint';
734
+ default: return 'release';
735
+ }
736
+ }
737
+
738
+ /* Token classes and states of SQLite's own `sqlite3_complete` (complete.c). */
739
+ const TK_SEMI = 0;
740
+ const TK_OTHER = 1;
741
+ const TK_EXPLAIN = 2;
742
+ const TK_CREATE = 3;
743
+ const TK_TEMP = 4;
744
+ const TK_TRIGGER = 5;
745
+ const TK_END = 6;
746
+ const STATE_START = 1;
747
+
748
+ /**
749
+ * Next state by [state][token]; whitespace and comments never change state.
750
+ * State 5 is inside a trigger body, where `;` ends the statement only when it
751
+ * follows `; END` — the same rule SQLite uses, so a `CASE … END` inside the
752
+ * body never ends it early.
753
+ */
754
+ const TRANSITIONS: readonly (readonly number[])[] = [
755
+ /* 0 INVALID */ [1, 2, 3, 4, 2, 2, 2],
756
+ /* 1 START */ [1, 2, 3, 4, 2, 2, 2],
757
+ /* 2 NORMAL */ [1, 2, 2, 2, 2, 2, 2],
758
+ /* 3 EXPLAIN */ [1, 3, 2, 4, 2, 2, 2],
759
+ /* 4 CREATE */ [1, 2, 2, 2, 4, 5, 2],
760
+ /* 5 TRIGGER */ [6, 5, 5, 5, 5, 5, 5],
761
+ /* 6 SEMI */ [6, 5, 5, 5, 5, 5, 7],
762
+ /* 7 END */ [1, 5, 5, 5, 5, 5, 5],
763
+ ];
764
+
765
+ function keywordToken(word: string): number {
766
+ switch (word.toUpperCase()) {
767
+ case 'EXPLAIN': return TK_EXPLAIN;
768
+ case 'CREATE': return TK_CREATE;
769
+ case 'TEMP':
770
+ case 'TEMPORARY': return TK_TEMP;
771
+ case 'TRIGGER': return TK_TRIGGER;
772
+ case 'END': return TK_END;
773
+ default: return TK_OTHER;
774
+ }
775
+ }
776
+
777
+ const SQL_SPACE = new Set([' ', '\t', '\n', '\f', '\r', '\uFEFF']);
778
+ const ASCII_LETTER = /[A-Za-z_]/;
779
+ const ASCII_IDENTIFIER = /[A-Za-z0-9_$]/;
780
+
781
+ /** SQLite treats every character at or above U+0080 as part of an identifier. */
782
+ function isIdentifierStart(char: string): boolean {
783
+ return ASCII_LETTER.test(char) || char.charCodeAt(0) >= 0x80;
784
+ }
785
+
786
+ function isIdentifierPart(char: string): boolean {
787
+ return ASCII_IDENTIFIER.test(char) || char.charCodeAt(0) >= 0x80;
788
+ }
789
+
790
+ /** Index just past the quote that closes the one at `open` (a doubled quote is an escape); the text's end when unclosed. */
791
+ function closeQuote(sql: string, open: number, quote: string): number {
792
+ let index = open + 1;
793
+ while (index < sql.length) {
794
+ if (sql[index] === quote) {
795
+ if (sql[index + 1] !== quote) return index + 1;
796
+ index += 2;
797
+ continue;
798
+ }
799
+ index += 1;
800
+ }
801
+ return sql.length;
802
+ }
803
+
804
+ /**
805
+ * The statements of a SQL text, in order, each without its terminating `;`.
806
+ * Statement ends are found as SQLite finds them (`sqlite3_complete`): a `;`
807
+ * inside a string, quoted identifier, comment or trigger body does not end a
808
+ * statement. Statements that are only whitespace or comments are dropped.
809
+ */
810
+ export function splitSqlStatements(sql: string): string[] {
811
+ const statements: string[] = [];
812
+ let state = 0;
813
+ let start = 0;
814
+ let hasToken = false;
815
+ let index = 0;
816
+ const step = (token: number) => {
817
+ state = TRANSITIONS[state][token];
818
+ };
819
+ while (index < sql.length) {
820
+ const char = sql[index];
821
+ const next = sql[index + 1];
822
+ if (SQL_SPACE.has(char)) {
823
+ index += 1;
824
+ } else if (char === '-' && next === '-') {
825
+ const end = sql.indexOf('\n', index);
826
+ index = end < 0 ? sql.length : end + 1;
827
+ } else if (char === '/' && next === '*') {
828
+ const end = sql.indexOf('*/', index + 2);
829
+ index = end < 0 ? sql.length : end + 2;
830
+ } else if (char === ';') {
831
+ step(TK_SEMI);
832
+ index += 1;
833
+ if (state === STATE_START) {
834
+ if (hasToken) statements.push(sql.slice(start, index - 1));
835
+ start = index;
836
+ hasToken = false;
837
+ }
838
+ } else {
839
+ hasToken = true;
840
+ if (char === "'" || char === '"' || char === '`') {
841
+ index = closeQuote(sql, index, char);
842
+ step(TK_OTHER);
843
+ } else if (char === '[') {
844
+ const end = sql.indexOf(']', index + 1);
845
+ index = end < 0 ? sql.length : end + 1;
846
+ step(TK_OTHER);
847
+ } else if (isIdentifierStart(char)) {
848
+ let end = index + 1;
849
+ while (end < sql.length && isIdentifierPart(sql[end])) end += 1;
850
+ step(keywordToken(sql.slice(index, end)));
851
+ index = end;
852
+ } else if (char >= '0' && char <= '9') {
853
+ let end = index + 1;
854
+ while (end < sql.length && isIdentifierPart(sql[end])) end += 1;
855
+ step(TK_OTHER);
856
+ index = end;
857
+ } else {
858
+ step(TK_OTHER);
859
+ index += 1;
860
+ }
861
+ }
862
+ }
863
+ if (hasToken) statements.push(sql.slice(start));
864
+ return statements;
865
+ }
866
+
337
867
  //trust:validator_function
338
868
  export function parseStopResult(input: unknown) {
339
869
  const fields = fieldsOf(input);