@noego/sqlego 0.0.2 → 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/README.md +42 -5
- package/bin/sqlego +2 -2
- package/dist/client.d.ts +24 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +215 -7
- package/dist/protocol.d.ts +132 -4
- package/package.json +1 -1
- package/src/client.ts +52 -2
- package/src/index.ts +2 -0
- package/src/protocol.ts +430 -7
- package/src/server.ts +201 -11
package/src/client.ts
CHANGED
|
@@ -6,16 +6,18 @@ import { fileURLToPath } from 'node:url';
|
|
|
6
6
|
import { Result, Trust } from '@noego/trust';
|
|
7
7
|
import {
|
|
8
8
|
PROTOCOL_VERSION,
|
|
9
|
-
|
|
9
|
+
encodeRequestFrame,
|
|
10
10
|
errnoCode,
|
|
11
11
|
errorMessage,
|
|
12
12
|
fromJson,
|
|
13
13
|
parseBatchResult,
|
|
14
14
|
parseBeginResult,
|
|
15
|
+
parseExecResult,
|
|
15
16
|
parseHelloResult,
|
|
16
17
|
parseQueryResult,
|
|
17
18
|
parseResponse,
|
|
18
19
|
parseRunResult,
|
|
20
|
+
parseStatementResult,
|
|
19
21
|
parseStatusResult,
|
|
20
22
|
parseStopResult,
|
|
21
23
|
parseTransactionEndResult,
|
|
@@ -23,12 +25,14 @@ import {
|
|
|
23
25
|
type BatchResult,
|
|
24
26
|
type BeginResult,
|
|
25
27
|
type ErrorCode,
|
|
28
|
+
type ExecResult,
|
|
26
29
|
type HelloResult,
|
|
27
30
|
type Request,
|
|
28
31
|
type RunResult,
|
|
29
32
|
type SqlParams,
|
|
30
33
|
type SqlRow,
|
|
31
34
|
type Statement,
|
|
35
|
+
type StatementResult,
|
|
32
36
|
type StatusResult,
|
|
33
37
|
type TransactionMode,
|
|
34
38
|
} from './protocol.ts';
|
|
@@ -122,6 +126,11 @@ function callerRows<Row extends SqlRow>(rows: SqlRow[]): Row[] {
|
|
|
122
126
|
return rows as Row[];
|
|
123
127
|
}
|
|
124
128
|
|
|
129
|
+
/** `statement<Row>`: the caller names its rows' shape, as with `query<Row>`. */
|
|
130
|
+
function callerStatement<Row extends SqlRow>(result: StatementResult): StatementResult<Row> {
|
|
131
|
+
return { reader: result.reader, rows: callerRows<Row>(result.rows), changes: result.changes, lastInsertRowid: result.lastInsertRowid };
|
|
132
|
+
}
|
|
133
|
+
|
|
125
134
|
export class SqlegoClient {
|
|
126
135
|
readonly paths: FilePaths;
|
|
127
136
|
private socket: net.Socket | null = null;
|
|
@@ -163,6 +172,27 @@ export class SqlegoClient {
|
|
|
163
172
|
return unwrap(await this.call({ op: 'run', sql, params }, parseRunResult));
|
|
164
173
|
}
|
|
165
174
|
|
|
175
|
+
/**
|
|
176
|
+
* Exactly one statement, any kind: `rows` holds what it returned (SELECT,
|
|
177
|
+
* PRAGMA, `INSERT … RETURNING`; empty otherwise), `reader` identifies even
|
|
178
|
+
* an empty result set, and `changes` the rows it
|
|
179
|
+
* changed (0 for a read). Integers beyond ±2^53-1 come back as `bigint`,
|
|
180
|
+
* blobs as `Uint8Array`; `bigint` and `Uint8Array` parameters bind losslessly.
|
|
181
|
+
*/
|
|
182
|
+
async statement<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<StatementResult<Row>> {
|
|
183
|
+
return callerStatement<Row>(unwrap(await this.call({ op: 'statement', sql, params }, parseStatementResult)));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Several statements in one text (a schema, a migration), no parameters, run
|
|
188
|
+
* in order until the first failure; earlier statements keep their effect
|
|
189
|
+
* unless this runs inside a transaction that is then rolled back.
|
|
190
|
+
* Transaction control anywhere in the text is refused, as with `run`.
|
|
191
|
+
*/
|
|
192
|
+
async exec(sql: string): Promise<ExecResult> {
|
|
193
|
+
return unwrap(await this.call({ op: 'exec', sql }, parseExecResult));
|
|
194
|
+
}
|
|
195
|
+
|
|
166
196
|
/** One transaction; the whole batch rolls back on the first failure. */
|
|
167
197
|
async batch(statements: readonly Statement[]): Promise<BatchResult['results']> {
|
|
168
198
|
const result = unwrap(await this.call({ op: 'batch', statements }, parseBatchResult));
|
|
@@ -206,6 +236,16 @@ export class SqlegoClient {
|
|
|
206
236
|
return unwrap(await this.call({ op: 'run', sql, params, txId }, parseRunResult));
|
|
207
237
|
}
|
|
208
238
|
|
|
239
|
+
/** @internal */
|
|
240
|
+
async transactionStatement<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<StatementResult<Row>> {
|
|
241
|
+
return callerStatement<Row>(unwrap(await this.call({ op: 'statement', sql, params, txId }, parseStatementResult)));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** @internal */
|
|
245
|
+
async transactionExec(txId: number, sql: string): Promise<ExecResult> {
|
|
246
|
+
return unwrap(await this.call({ op: 'exec', sql, txId }, parseExecResult));
|
|
247
|
+
}
|
|
248
|
+
|
|
209
249
|
/** @internal */
|
|
210
250
|
async transactionEnd(txId: number, how: 'commit' | 'rollback'): Promise<void> {
|
|
211
251
|
unwrap(await this.call({ op: how, txId }, parseTransactionEndResult));
|
|
@@ -440,7 +480,7 @@ export class SqlegoClient {
|
|
|
440
480
|
return Promise.resolve(Result.err({ kind: 'not-connected', message: 'client is not connected' }));
|
|
441
481
|
}
|
|
442
482
|
const id = this.nextId++;
|
|
443
|
-
const frame =
|
|
483
|
+
const frame = encodeRequestFrame({ id, ...body } as Request);
|
|
444
484
|
if (!frame.ok) return Promise.resolve(frame);
|
|
445
485
|
return new Promise<Result<unknown, RequestFailure>>((settle) => {
|
|
446
486
|
const timer = setTimeout(() => {
|
|
@@ -507,6 +547,16 @@ export class SqlegoTransaction {
|
|
|
507
547
|
return this.client.transactionRun(this.id, sql, params);
|
|
508
548
|
}
|
|
509
549
|
|
|
550
|
+
/** `SqlegoClient.statement` inside this transaction. */
|
|
551
|
+
statement<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<StatementResult<Row>> {
|
|
552
|
+
return this.client.transactionStatement<Row>(this.id, sql, params);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** `SqlegoClient.exec` inside this transaction; savepoints are allowed, ending the transaction is not. */
|
|
556
|
+
exec(sql: string): Promise<ExecResult> {
|
|
557
|
+
return this.client.transactionExec(this.id, sql);
|
|
558
|
+
}
|
|
559
|
+
|
|
510
560
|
/** `SAVEPOINT name`: a nested scope that `rollbackTo` can undo and `release` folds into the transaction. */
|
|
511
561
|
async savepoint(name: string): Promise<void> {
|
|
512
562
|
await this.run(`SAVEPOINT ${savepointName(name)}`);
|
package/src/index.ts
CHANGED
package/src/protocol.ts
CHANGED
|
@@ -13,16 +13,41 @@
|
|
|
13
13
|
* longer than the server's hard cap, so a client can never hold the file's
|
|
14
14
|
* only writer hostage. Transaction-control SQL (`BEGIN`, `COMMIT`, ...) is
|
|
15
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).
|
|
16
22
|
*/
|
|
17
23
|
|
|
18
24
|
import { Result, Trust } from '@noego/trust';
|
|
19
25
|
|
|
20
|
-
export const PROTOCOL_VERSION =
|
|
26
|
+
export const PROTOCOL_VERSION = 3;
|
|
21
27
|
|
|
22
28
|
export type SqlParams = ReadonlyArray<SqlValue> | Readonly<Record<string, SqlValue>>;
|
|
23
29
|
export type SqlValue = string | number | bigint | boolean | null | Uint8Array;
|
|
24
30
|
export type SqlRow = Record<string, unknown>;
|
|
25
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
|
+
|
|
26
51
|
export type Statement = Readonly<{
|
|
27
52
|
sql: string;
|
|
28
53
|
params?: SqlParams;
|
|
@@ -36,6 +61,10 @@ export type Request =
|
|
|
36
61
|
| { id: number; op: 'hello'; clientVersion: string; protocol: number }
|
|
37
62
|
| { id: number; op: 'query'; sql: string; params?: SqlParams; txId?: number }
|
|
38
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 }
|
|
39
68
|
| { id: number; op: 'batch'; statements: readonly Statement[] }
|
|
40
69
|
| { id: number; op: 'begin'; mode?: TransactionMode; leaseMs?: number }
|
|
41
70
|
| { id: number; op: 'commit'; txId: number }
|
|
@@ -46,6 +75,17 @@ export type Request =
|
|
|
46
75
|
export type RunResult = Readonly<{ changes: number; lastInsertRowid: number | bigint }>;
|
|
47
76
|
export type QueryResult = Readonly<{ rows: SqlRow[] }>;
|
|
48
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 }>;
|
|
49
89
|
/** The lease the server granted (its own cap applies) and the hard cap on the transaction's life. */
|
|
50
90
|
export type BeginResult = Readonly<{ txId: number; leaseMs: number; maxDurationMs: number }>;
|
|
51
91
|
export type TransactionEndResult = Readonly<{ txId: number }>;
|
|
@@ -124,6 +164,150 @@ export function encodeFrame(message: Request | Response) {
|
|
|
124
164
|
return Result.ok(`${json.value}\n`);
|
|
125
165
|
}
|
|
126
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
|
+
|
|
127
311
|
/** Parses JSON text into `unknown`; what it holds is for a validator to decide. */
|
|
128
312
|
export function fromJson(text: string) {
|
|
129
313
|
return Trust.try(
|
|
@@ -150,15 +334,70 @@ function fieldsOf(input: unknown): Fields | null {
|
|
|
150
334
|
return typeof input === 'object' && input !== null && !Array.isArray(input) ? (input as Fields) : null;
|
|
151
335
|
}
|
|
152
336
|
|
|
153
|
-
/**
|
|
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
|
+
*/
|
|
154
341
|
//trust:validator_function
|
|
155
342
|
export function parseSqlValue(input: unknown) {
|
|
156
|
-
if (input === null || typeof input === 'string' || typeof input === '
|
|
343
|
+
if (input === null || typeof input === 'string' || typeof input === 'boolean' || (typeof input === 'number' && Number.isFinite(input))) {
|
|
157
344
|
return Result.ok<SqlValue>(input);
|
|
158
345
|
}
|
|
346
|
+
const fields = fieldsOf(input);
|
|
347
|
+
if (fields && ('$bigint' in fields || '$blob' in fields)) return parseTypedValue(fields);
|
|
159
348
|
return invalid(`a SQL value must be a string, number, boolean or null, not ${Array.isArray(input) ? 'an array' : typeof input}`);
|
|
160
349
|
}
|
|
161
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
|
+
|
|
162
401
|
/** Positional (`[...]`) or named (`{ name: value }`) parameters. */
|
|
163
402
|
//trust:validator_function
|
|
164
403
|
export function parseSqlParams(input: unknown) {
|
|
@@ -173,13 +412,13 @@ export function parseSqlParams(input: unknown) {
|
|
|
173
412
|
}
|
|
174
413
|
const fields = fieldsOf(input);
|
|
175
414
|
if (!fields) return invalid('params must be an array or an object');
|
|
176
|
-
const
|
|
415
|
+
const entries: Array<[string, SqlValue]> = [];
|
|
177
416
|
for (const [name, item] of Object.entries(fields)) {
|
|
178
417
|
const value = parseSqlValue(item);
|
|
179
418
|
if (!value.ok) return invalid(`params.${name}: ${value.error.message}`);
|
|
180
|
-
|
|
419
|
+
entries.push([name, value.value]);
|
|
181
420
|
}
|
|
182
|
-
return Result.ok<SqlParams>(
|
|
421
|
+
return Result.ok<SqlParams>(Object.fromEntries(entries));
|
|
183
422
|
}
|
|
184
423
|
|
|
185
424
|
/** `params` when present; absent (`undefined`) is allowed. */
|
|
@@ -222,7 +461,8 @@ export function parseRequest(input: unknown) {
|
|
|
222
461
|
return Result.ok(request);
|
|
223
462
|
}
|
|
224
463
|
case 'query':
|
|
225
|
-
case 'run':
|
|
464
|
+
case 'run':
|
|
465
|
+
case 'statement': {
|
|
226
466
|
if (typeof fields.sql !== 'string') return reject(id, `${fields.op} needs sql (string)`);
|
|
227
467
|
const params = parseOptionalParams(fields.params);
|
|
228
468
|
if (!params.ok) return reject(id, params.error.message);
|
|
@@ -231,6 +471,14 @@ export function parseRequest(input: unknown) {
|
|
|
231
471
|
const request: Request = { id, op: fields.op, sql: fields.sql, params: params.value, txId };
|
|
232
472
|
return Result.ok(request);
|
|
233
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
|
+
}
|
|
234
482
|
case 'begin': {
|
|
235
483
|
const mode = fields.mode;
|
|
236
484
|
if (mode !== undefined && mode !== 'deferred' && mode !== 'immediate') return reject(id, 'begin mode must be "deferred" or "immediate"');
|
|
@@ -351,6 +599,52 @@ export function parseBatchResult(input: unknown) {
|
|
|
351
599
|
return Result.ok(result);
|
|
352
600
|
}
|
|
353
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
|
+
|
|
354
648
|
//trust:validator_function
|
|
355
649
|
export function parseHelloResult(input: unknown) {
|
|
356
650
|
const fields = fieldsOf(input);
|
|
@@ -441,6 +735,135 @@ export function transactionControl(sql: string): 'begin' | 'commit' | 'rollback'
|
|
|
441
735
|
}
|
|
442
736
|
}
|
|
443
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
|
+
|
|
444
867
|
//trust:validator_function
|
|
445
868
|
export function parseStopResult(input: unknown) {
|
|
446
869
|
const fields = fieldsOf(input);
|