@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 CHANGED
@@ -44,10 +44,40 @@ fresh one, so a rebuilt binary never keeps talking to an old owner.
44
44
  ## Protocol
45
45
 
46
46
  Newline-delimited JSON, correlated by `id`. Ops: `hello`, `query` (rows),
47
- `run` (changes), `batch` (all statements in one transaction, rolled back on
48
- the first failure), `begin` / `commit` / `rollback` (a leased transaction,
49
- below), `status`, `stop`. Protocol version 2; `hello` refuses a client that
50
- speaks another version.
47
+ `run` (changes), `statement` and `exec` (below), `batch` (all statements in
48
+ one transaction, rolled back on the first failure), `begin` / `commit` /
49
+ `rollback` (a leased transaction, below), `status`, `stop`. Protocol version
50
+ 3; `hello` refuses a client that speaks another version.
51
+
52
+ ### `statement` and `exec`
53
+
54
+ - `statement { sql, params?, txId? }` → `{ reader, rows, changes, lastInsertRowid }`.
55
+ Exactly one SQL statement of any kind (several, or none, is `bad-request`).
56
+ A statement with result columns — `SELECT`, `PRAGMA`, `INSERT … RETURNING` —
57
+ returns `reader: true` and its rows; any other returns `reader: false` and
58
+ `rows: []`. This distinguishes an empty result set from a write. It is executed once.
59
+ `changes` is the rows it changed (0 for a read or DDL).
60
+ - `exec { sql, txId? }` → `{ statements, changes, lastInsertRowid }`. Any
61
+ number of statements, no parameters, run in order and stopped at the first
62
+ failure (statements before it keep their effect, as with `sqlite3_exec`;
63
+ run it in a leased transaction to make it all-or-nothing). Statements are
64
+ split the way SQLite does it (`sqlite3_complete`): semicolons in strings,
65
+ quoted identifiers, comments and trigger bodies don't end a statement.
66
+ Every statement is checked before any runs, so transaction control anywhere
67
+ in the text — not only the first statement — is refused.
68
+
69
+ Both follow the transaction rules below (`txId`, leases, queueing).
70
+
71
+ ### Typed values
72
+
73
+ JSON has no 64-bit integers or bytes, so they travel as strictly validated
74
+ one-key tags: `{ "$bigint": "-9223372036854775808" }` (canonical decimal,
75
+ signed 64-bit range) and `{ "$blob": "AAH/" }` (canonical padded base64; `""`
76
+ is a zero-length blob). The client tags `bigint` and `Uint8Array` parameters
77
+ of every op; a `bigint` outside the 64-bit range fails with `bad-request`
78
+ before it is sent. `statement` / `exec` results return integers as numbers
79
+ when |n| ≤ 2^53-1 and as `bigint` otherwise, and blobs as `Uint8Array`.
80
+ `query` / `run` / `batch` results are unchanged (plain JSON numbers).
51
81
 
52
82
  ### Leased transactions
53
83
 
@@ -65,7 +95,7 @@ trusted to.
65
95
  whether the file is inside a transaction.
66
96
 
67
97
  While one is open, that client's statements run at once and every other
68
- client's `query` / `run` / `batch` / `begin` wait in arrival order (`status`
98
+ client's `query` / `run` / `statement` / `exec` / `batch` / `begin` wait in arrival order (`status`
69
99
  reports how many); `hello`, `status` and `stop` never wait. It is rolled back
70
100
  by the server, and later requests for it fail with `tx-expired`, when:
71
101
 
@@ -100,12 +130,19 @@ await db.run('INSERT INTO logs (…) VALUES (?, ?)', [a, b]);
100
130
  const rows = await db.query('SELECT … WHERE occurred_at_ms < ?', [cutoff]);
101
131
  await db.batch([{ sql: 'DELETE … LIMIT 5000' }, { sql: 'PRAGMA incremental_vacuum(256)' }]);
102
132
 
133
+ // One statement, rows and changes together; lossless bigint / Uint8Array.
134
+ const { rows: [created], changes } = await db.statement<{ id: bigint | number }>(
135
+ 'INSERT INTO files (hash, body) VALUES (?, ?) RETURNING id', [hash, bytes]);
136
+ // A whole schema or migration script (no params).
137
+ await db.exec(schemaSql);
138
+
103
139
  // Reads-then-writes with application logic in between: a leased transaction.
104
140
  const tx = await db.begin({ mode: 'immediate' });
105
141
  const [{ balance }] = await tx.query<{ balance: number }>('SELECT balance FROM accounts WHERE id = ?', [id]);
106
142
  await tx.savepoint('s1');
107
143
  await tx.run('UPDATE accounts SET balance = ? WHERE id = ?', [balance - amount, id]);
108
144
  await tx.release('s1'); // or tx.rollbackTo('s1')
145
+ await tx.statement('DELETE FROM holds WHERE id = ? RETURNING amount', [holdId]); // tx.exec(sql) too
109
146
  await tx.commit(); // or tx.rollback()
110
147
 
111
148
  // Or let the client commit on resolve and roll back on throw:
package/bin/sqlego CHANGED
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/sqlego
3
- size: 62259954 bytes
4
- sha256: 33ee2e96b2c3ff0fce805e1a09469118b13e8f6aa4f9e533826e75ff81e07bce
3
+ size: 62276466 bytes
4
+ sha256: f3c0c81ff2125491379617417e3ddd4160c404e111d560aeb37164f934ab7e29
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type BatchResult, type BeginResult, type HelloResult, type RunResult, type SqlParams, type SqlRow, type Statement, type StatusResult, type TransactionMode } from './protocol.ts';
1
+ import { type BatchResult, type BeginResult, type ExecResult, type HelloResult, type RunResult, type SqlParams, type SqlRow, type Statement, type StatementResult, type StatusResult, type TransactionMode } from './protocol.ts';
2
2
  import { type FilePaths } from './paths.ts';
3
3
  /**
4
4
  * Runs in Node and Bun alike (node:net, node:child_process only; no SQLite
@@ -49,6 +49,21 @@ export declare class SqlegoClient {
49
49
  get server(): HelloResult;
50
50
  query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]>;
51
51
  run(sql: string, params?: SqlParams): Promise<RunResult>;
52
+ /**
53
+ * Exactly one statement, any kind: `rows` holds what it returned (SELECT,
54
+ * PRAGMA, `INSERT … RETURNING`; empty otherwise), `reader` identifies even
55
+ * an empty result set, and `changes` the rows it
56
+ * changed (0 for a read). Integers beyond ±2^53-1 come back as `bigint`,
57
+ * blobs as `Uint8Array`; `bigint` and `Uint8Array` parameters bind losslessly.
58
+ */
59
+ statement<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<StatementResult<Row>>;
60
+ /**
61
+ * Several statements in one text (a schema, a migration), no parameters, run
62
+ * in order until the first failure; earlier statements keep their effect
63
+ * unless this runs inside a transaction that is then rolled back.
64
+ * Transaction control anywhere in the text is refused, as with `run`.
65
+ */
66
+ exec(sql: string): Promise<ExecResult>;
52
67
  /** One transaction; the whole batch rolls back on the first failure. */
53
68
  batch(statements: readonly Statement[]): Promise<BatchResult['results']>;
54
69
  /**
@@ -65,6 +80,10 @@ export declare class SqlegoClient {
65
80
  /** @internal */
66
81
  transactionRun(txId: number, sql: string, params?: SqlParams): Promise<RunResult>;
67
82
  /** @internal */
83
+ transactionStatement<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<StatementResult<Row>>;
84
+ /** @internal */
85
+ transactionExec(txId: number, sql: string): Promise<ExecResult>;
86
+ /** @internal */
68
87
  transactionEnd(txId: number, how: 'commit' | 'rollback'): Promise<void>;
69
88
  status(): Promise<StatusResult>;
70
89
  /** Asks the server to shut down; the connection closes as a consequence. */
@@ -109,6 +128,10 @@ export declare class SqlegoTransaction {
109
128
  get closed(): boolean;
110
129
  query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]>;
111
130
  run(sql: string, params?: SqlParams): Promise<RunResult>;
131
+ /** `SqlegoClient.statement` inside this transaction. */
132
+ statement<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<StatementResult<Row>>;
133
+ /** `SqlegoClient.exec` inside this transaction; savepoints are allowed, ending the transaction is not. */
134
+ exec(sql: string): Promise<ExecResult>;
112
135
  /** `SAVEPOINT name`: a nested scope that `rollbackTo` can undo and `release` folds into the transaction. */
113
136
  savepoint(name: string): Promise<void>;
114
137
  release(name: string): Promise<void>;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, type BeginOptions, type ClientOptions } from './client.ts';
2
2
  export { pathsFor, runtimeDirectory, canonicalFile, type FilePaths, type ServerMeta } from './paths.ts';
3
- export { PROTOCOL_VERSION, type SqlParams, type SqlRow, type SqlValue, type Statement, type RunResult, type QueryResult, type BatchResult, type BeginResult, type StatusResult, type HelloResult, type TransactionMode, type TransactionStatus, } from './protocol.ts';
3
+ export { PROTOCOL_VERSION, type SqlParams, type SqlRow, type SqlValue, type Statement, type RunResult, type QueryResult, type BatchResult, type StatementResult, type ExecResult, type BeginResult, type StatusResult, type HelloResult, type TransactionMode, type TransactionStatus, } from './protocol.ts';
4
4
  export { VERSION } from './version.ts';
package/dist/index.js CHANGED
@@ -47,7 +47,12 @@ var Result = { ok, err };
47
47
  var Trust = { try: tryResult, tryAsync: tryResultAsync, decide, translate };
48
48
 
49
49
  // src/protocol.ts
50
- var PROTOCOL_VERSION = 2;
50
+ var PROTOCOL_VERSION = 3;
51
+ var INT64_MIN = -9223372036854775808n;
52
+ var INT64_MAX = 9223372036854775807n;
53
+ var SAFE_MIN = -9007199254740991n;
54
+ var DECIMAL_INTEGER = /^(?:0|-?[1-9][0-9]{0,18})$/;
55
+ var BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
51
56
  function toJson(value, indent) {
52
57
  const encoded = Trust.try(() => JSON.stringify(value, replaceBigInt, indent), (cause) => ({ kind: "encode-failed", message: errorMessage(cause) }));
53
58
  if (!encoded.ok)
@@ -56,13 +61,94 @@ function toJson(value, indent) {
56
61
  return Result.err({ kind: "encode-failed", message: `${typeof value} has no JSON form` });
57
62
  return Result.ok(encoded.value);
58
63
  }
59
- function encodeFrame(message) {
60
- const json = toJson(message);
64
+ function encodeRequestFrame(request) {
65
+ const wire = encodeRequestParams(request);
66
+ if (!wire.ok)
67
+ return Result.err({ kind: "bad-request", message: wire.error.message });
68
+ const json = toJson(wire.value);
61
69
  if (!json.ok)
62
70
  return json;
63
71
  return Result.ok(`${json.value}
64
72
  `);
65
73
  }
74
+ function encodeRequestParams(request) {
75
+ switch (request.op) {
76
+ case "query":
77
+ case "run":
78
+ case "statement": {
79
+ if (request.params === undefined)
80
+ return Result.ok(request);
81
+ const params = encodeSqlParams(request.params);
82
+ if (!params.ok)
83
+ return params;
84
+ return Result.ok({ ...request, params: params.value });
85
+ }
86
+ case "batch": {
87
+ const statements = [];
88
+ for (const [index, statement] of request.statements.entries()) {
89
+ if (statement.params === undefined) {
90
+ statements.push(statement);
91
+ continue;
92
+ }
93
+ const params = encodeSqlParams(statement.params);
94
+ if (!params.ok)
95
+ return invalid(`statements[${index}].${params.error.message}`);
96
+ statements.push({ ...statement, params: params.value });
97
+ }
98
+ return Result.ok({ ...request, statements });
99
+ }
100
+ default:
101
+ return Result.ok(request);
102
+ }
103
+ }
104
+ function encodeSqlParams(params) {
105
+ if (typeof params !== "object" || params === null)
106
+ return invalid("params must be an array or an object");
107
+ const shape = paramsShape(params);
108
+ if (shape.kind === "positional") {
109
+ const values = [];
110
+ for (const [index, item] of shape.values.entries()) {
111
+ const value = encodeParamValue(item);
112
+ if (!value.ok)
113
+ return invalid(`params[${index}]: ${value.error.message}`);
114
+ values.push(value.value);
115
+ }
116
+ return Result.ok(values);
117
+ }
118
+ const entries = [];
119
+ for (const [name, item] of Object.entries(shape.values)) {
120
+ const value = encodeParamValue(item);
121
+ if (!value.ok)
122
+ return invalid(`params.${name}: ${value.error.message}`);
123
+ entries.push([name, value.value]);
124
+ }
125
+ return Result.ok(Object.fromEntries(entries));
126
+ }
127
+ function paramsShape(params) {
128
+ return Array.isArray(params) ? { kind: "positional", values: params } : { kind: "named", values: params };
129
+ }
130
+ function encodeParamValue(value) {
131
+ if (typeof value === "bigint")
132
+ return encodeBigInt(value);
133
+ if (value instanceof Uint8Array)
134
+ return encodeBlob(value);
135
+ if (value === null || typeof value === "string" || typeof value === "boolean")
136
+ return Result.ok(value);
137
+ if (typeof value === "number" && Number.isFinite(value))
138
+ return Result.ok(value);
139
+ return invalid("a parameter must be a finite number, string, boolean, null, bigint or Uint8Array");
140
+ }
141
+ function encodeBigInt(value) {
142
+ if (value < INT64_MIN || value > INT64_MAX)
143
+ return invalid(`integer ${value} overflows a signed 64-bit integer`);
144
+ return Result.ok({ $bigint: String(value) });
145
+ }
146
+ function encodeBlob(bytes) {
147
+ const encoded = Trust.try(() => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64"), (cause) => ({ kind: "invalid", message: `cannot encode a blob: ${errorMessage(cause)}` }));
148
+ if (!encoded.ok)
149
+ return encoded;
150
+ return Result.ok({ $blob: encoded.value });
151
+ }
66
152
  function fromJson(text) {
67
153
  return Trust.try(() => JSON.parse(text), (cause) => ({ kind: "invalid", message: `not JSON: ${errorMessage(cause)}` }));
68
154
  }
@@ -70,6 +156,59 @@ var invalid = (message) => Result.err({ kind: "invalid", message });
70
156
  function fieldsOf(input) {
71
157
  return typeof input === "object" && input !== null && !Array.isArray(input) ? input : null;
72
158
  }
159
+ function parseSqlValue(input) {
160
+ if (input === null || typeof input === "string" || typeof input === "boolean" || typeof input === "number" && Number.isFinite(input)) {
161
+ return Result.ok(input);
162
+ }
163
+ const fields = fieldsOf(input);
164
+ if (fields && (("$bigint" in fields) || ("$blob" in fields)))
165
+ return parseTypedValue(fields);
166
+ return invalid(`a SQL value must be a string, number, boolean or null, not ${Array.isArray(input) ? "an array" : typeof input}`);
167
+ }
168
+ function parseTypedValue(fields) {
169
+ const keys = Object.keys(fields);
170
+ if (keys.length !== 1)
171
+ return invalid(`a typed value has exactly one key ($bigint or $blob), not ${keys.length}`);
172
+ if (keys[0] === "$bigint")
173
+ return parseWireBigInt(fields.$bigint);
174
+ if (keys[0] === "$blob")
175
+ return parseWireBlob(fields.$blob);
176
+ return invalid(`unknown typed value ${keys[0]}`);
177
+ }
178
+ function parseWireBigInt(input) {
179
+ if (typeof input !== "string" || !DECIMAL_INTEGER.test(input))
180
+ return invalid("$bigint must be a canonical decimal integer string");
181
+ const parsed = Trust.try(() => BigInt(input), (cause) => ({ kind: "invalid", message: `$bigint ${input}: ${errorMessage(cause)}` }));
182
+ if (!parsed.ok)
183
+ return parsed;
184
+ if (parsed.value < INT64_MIN || parsed.value > INT64_MAX)
185
+ return invalid(`$bigint ${input} overflows a signed 64-bit integer`);
186
+ return Result.ok(parsed.value);
187
+ }
188
+ function parseWireBlob(input) {
189
+ if (typeof input !== "string" || !BASE64.test(input))
190
+ return invalid("$blob must be canonical padded base64");
191
+ const decoded = Trust.try(() => {
192
+ const bytes = Buffer.from(input, "base64");
193
+ return { bytes: new Uint8Array(bytes), canonical: bytes.toString("base64") };
194
+ }, (cause) => ({ kind: "invalid", message: `$blob: ${errorMessage(cause)}` }));
195
+ if (!decoded.ok)
196
+ return decoded;
197
+ if (decoded.value.canonical !== input)
198
+ return invalid("$blob must be canonical padded base64");
199
+ return Result.ok(decoded.value.bytes);
200
+ }
201
+ function parseWireInteger(input, at) {
202
+ if (typeof input === "number" && Number.isSafeInteger(input))
203
+ return Result.ok(input);
204
+ const fields = fieldsOf(input);
205
+ if (!fields || !("$bigint" in fields) || Object.keys(fields).length !== 1)
206
+ return invalid(`${at} must be a number or a $bigint`);
207
+ const value = parseWireBigInt(fields.$bigint);
208
+ if (!value.ok)
209
+ return invalid(`${at}: ${value.error.message}`);
210
+ return typeof value.value === "bigint" ? Result.ok(value.value) : invalid(`${at} must be a number or a $bigint`);
211
+ }
73
212
  var ERROR_CODES = [
74
213
  "sqlite",
75
214
  "bad-request",
@@ -160,6 +299,52 @@ function parseBatchResult(input) {
160
299
  const result = { results };
161
300
  return Result.ok(result);
162
301
  }
302
+ function parseWireRows(input) {
303
+ if (!Array.isArray(input))
304
+ return invalid("rows must be an array");
305
+ const rows = [];
306
+ for (const [index, item] of input.entries()) {
307
+ const fields = fieldsOf(item);
308
+ if (!fields)
309
+ return invalid(`rows[${index}] must be an object`);
310
+ const entries = [];
311
+ for (const [column, raw] of Object.entries(fields)) {
312
+ const value = parseSqlValue(raw);
313
+ if (!value.ok)
314
+ return invalid(`rows[${index}].${column}: ${value.error.message}`);
315
+ entries.push([column, value.value]);
316
+ }
317
+ const row = Object.fromEntries(entries);
318
+ rows.push(row);
319
+ }
320
+ return Result.ok(rows);
321
+ }
322
+ function parseStatementResult(input) {
323
+ const fields = fieldsOf(input);
324
+ if (!fields || typeof fields.reader !== "boolean" || typeof fields.changes !== "number")
325
+ return invalid("a statement result needs reader (boolean), rows, changes (number) and lastInsertRowid");
326
+ const rows = parseWireRows(fields.rows);
327
+ if (!rows.ok)
328
+ return rows;
329
+ const rowid = parseWireInteger(fields.lastInsertRowid, "lastInsertRowid");
330
+ if (!rowid.ok)
331
+ return rowid;
332
+ if (!fields.reader && rows.value.length > 0)
333
+ return invalid("a non-reader statement cannot return rows");
334
+ const result = { reader: fields.reader, rows: rows.value, changes: fields.changes, lastInsertRowid: rowid.value };
335
+ return Result.ok(result);
336
+ }
337
+ function parseExecResult(input) {
338
+ const fields = fieldsOf(input);
339
+ if (!fields || typeof fields.changes !== "number" || typeof fields.statements !== "number") {
340
+ return invalid("an exec result needs statements (number), changes (number) and lastInsertRowid");
341
+ }
342
+ const rowid = parseWireInteger(fields.lastInsertRowid, "lastInsertRowid");
343
+ if (!rowid.ok)
344
+ return rowid;
345
+ const result = { statements: fields.statements, changes: fields.changes, lastInsertRowid: rowid.value };
346
+ return Result.ok(result);
347
+ }
163
348
  function parseHelloResult(input) {
164
349
  const fields = fieldsOf(input);
165
350
  if (!fields || typeof fields.serverVersion !== "string" || typeof fields.protocol !== "number" || typeof fields.file !== "string" || typeof fields.pid !== "number") {
@@ -223,6 +408,8 @@ function parseStatusResult(input) {
223
408
  };
224
409
  return Result.ok(result);
225
410
  }
411
+ var SQL_SPACE = new Set([" ", "\t", `
412
+ `, "\f", "\r", "\uFEFF"]);
226
413
  function parseStopResult(input) {
227
414
  const fields = fieldsOf(input);
228
415
  if (!fields || fields.stopping !== true)
@@ -344,7 +531,7 @@ import { fileURLToPath } from "node:url";
344
531
  // package.json
345
532
  var package_default = {
346
533
  name: "@noego/sqlego",
347
- version: "0.0.2",
534
+ version: "0.0.3",
348
535
  description: "One owner process per SQLite file. Clients (CLI, Node, Bun) pass SQL over a local socket; the server boots on demand and exits when idle.",
349
536
  type: "module",
350
537
  license: "ISC",
@@ -402,8 +589,8 @@ function sourceBuildId(sourceDirectory) {
402
589
  }, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
403
590
  }
404
591
  function resolveBuildId() {
405
- if ("3acec59ea032".length > 0)
406
- return "3acec59ea032";
592
+ if ("ed6f3704ee47".length > 0)
593
+ return "ed6f3704ee47";
407
594
  const directory = Trust.try(() => path2.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
408
595
  if (!directory.ok)
409
596
  return decideUnknownBuild(directory.error.kind);
@@ -446,6 +633,9 @@ function unwrap(outcome) {
446
633
  function callerRows(rows) {
447
634
  return rows;
448
635
  }
636
+ function callerStatement(result) {
637
+ return { reader: result.reader, rows: callerRows(result.rows), changes: result.changes, lastInsertRowid: result.lastInsertRowid };
638
+ }
449
639
 
450
640
  class SqlegoClient {
451
641
  paths;
@@ -481,6 +671,12 @@ class SqlegoClient {
481
671
  async run(sql, params) {
482
672
  return unwrap(await this.call({ op: "run", sql, params }, parseRunResult));
483
673
  }
674
+ async statement(sql, params) {
675
+ return callerStatement(unwrap(await this.call({ op: "statement", sql, params }, parseStatementResult)));
676
+ }
677
+ async exec(sql) {
678
+ return unwrap(await this.call({ op: "exec", sql }, parseExecResult));
679
+ }
484
680
  async batch(statements) {
485
681
  const result = unwrap(await this.call({ op: "batch", statements }, parseBatchResult));
486
682
  return result.results;
@@ -508,6 +704,12 @@ class SqlegoClient {
508
704
  async transactionRun(txId, sql, params) {
509
705
  return unwrap(await this.call({ op: "run", sql, params, txId }, parseRunResult));
510
706
  }
707
+ async transactionStatement(txId, sql, params) {
708
+ return callerStatement(unwrap(await this.call({ op: "statement", sql, params, txId }, parseStatementResult)));
709
+ }
710
+ async transactionExec(txId, sql) {
711
+ return unwrap(await this.call({ op: "exec", sql, txId }, parseExecResult));
712
+ }
511
713
  async transactionEnd(txId, how) {
512
714
  unwrap(await this.call({ op: how, txId }, parseTransactionEndResult));
513
715
  }
@@ -710,7 +912,7 @@ class SqlegoClient {
710
912
  return Promise.resolve(Result.err({ kind: "not-connected", message: "client is not connected" }));
711
913
  }
712
914
  const id = this.nextId++;
713
- const frame = encodeFrame({ id, ...body });
915
+ const frame = encodeRequestFrame({ id, ...body });
714
916
  if (!frame.ok)
715
917
  return Promise.resolve(frame);
716
918
  return new Promise((settle) => {
@@ -761,6 +963,12 @@ class SqlegoTransaction {
761
963
  run(sql, params) {
762
964
  return this.client.transactionRun(this.id, sql, params);
763
965
  }
966
+ statement(sql, params) {
967
+ return this.client.transactionStatement(this.id, sql, params);
968
+ }
969
+ exec(sql) {
970
+ return this.client.transactionExec(this.id, sql);
971
+ }
764
972
  async savepoint(name) {
765
973
  await this.run(`SAVEPOINT ${savepointName(name)}`);
766
974
  }
@@ -13,12 +13,32 @@
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
  import { Result } from '@noego/trust';
18
- export declare const PROTOCOL_VERSION = 2;
24
+ export declare const PROTOCOL_VERSION = 3;
19
25
  export type SqlParams = ReadonlyArray<SqlValue> | Readonly<Record<string, SqlValue>>;
20
26
  export type SqlValue = string | number | bigint | boolean | null | Uint8Array;
21
27
  export type SqlRow = Record<string, unknown>;
28
+ /** A signed 64-bit integer on the wire: its decimal text. */
29
+ export type WireBigInt = Readonly<{
30
+ $bigint: string;
31
+ }>;
32
+ /** Bytes on the wire: standard base64 (padded); `""` is a zero-length blob. */
33
+ export type WireBlob = Readonly<{
34
+ $blob: string;
35
+ }>;
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
+ export declare const INT64_MIN = -9223372036854775808n;
41
+ export declare const INT64_MAX = 9223372036854775807n;
22
42
  export type Statement = Readonly<{
23
43
  sql: string;
24
44
  params?: SqlParams;
@@ -43,6 +63,21 @@ export type Request = {
43
63
  sql: string;
44
64
  params?: SqlParams;
45
65
  txId?: number;
66
+ }
67
+ /** Exactly one statement; rows when it has result columns (incl. `RETURNING`), plus its changes. */
68
+ | {
69
+ id: number;
70
+ op: 'statement';
71
+ sql: string;
72
+ params?: SqlParams;
73
+ txId?: number;
74
+ }
75
+ /** Any number of statements, no parameters, run in order until the first failure. */
76
+ | {
77
+ id: number;
78
+ op: 'exec';
79
+ sql: string;
80
+ txId?: number;
46
81
  } | {
47
82
  id: number;
48
83
  op: 'batch';
@@ -77,6 +112,35 @@ export type QueryResult = Readonly<{
77
112
  export type BatchResult = Readonly<{
78
113
  results: ReadonlyArray<RunResult | QueryResult>;
79
114
  }>;
115
+ /**
116
+ * One `statement`: whether it has result columns (`reader`), its rows, the rows
117
+ * it changed (0 for a read), and the connection's last insert rowid. Integers
118
+ * beyond ±2^53-1 come back as `bigint`, blobs as `Uint8Array`.
119
+ */
120
+ export type StatementResult<Row extends SqlRow = SqlRow> = Readonly<{
121
+ reader: boolean;
122
+ rows: Row[];
123
+ changes: number;
124
+ lastInsertRowid: number | bigint;
125
+ }>;
126
+ /** One `exec`: how many statements ran and the rows they changed in total. */
127
+ export type ExecResult = Readonly<{
128
+ statements: number;
129
+ changes: number;
130
+ lastInsertRowid: number | bigint;
131
+ }>;
132
+ /** The wire forms the server sends for `statement` / `exec`. */
133
+ export type StatementWireResult = Readonly<{
134
+ reader: boolean;
135
+ rows: WireRow[];
136
+ changes: number;
137
+ lastInsertRowid: WireInteger;
138
+ }>;
139
+ export type ExecWireResult = Readonly<{
140
+ statements: number;
141
+ changes: number;
142
+ lastInsertRowid: WireInteger;
143
+ }>;
80
144
  /** The lease the server granted (its own cap applies) and the hard cap on the transaction's life. */
81
145
  export type BeginResult = Readonly<{
82
146
  txId: number;
@@ -152,16 +216,56 @@ export declare function encodeFrame(message: Request | Response): import("@noego
152
216
  kind: "encode-failed";
153
217
  message: string;
154
218
  }> | import("@noego/trust").Ok<string>;
219
+ /**
220
+ * One request frame with its parameters in wire form: every `bigint` and
221
+ * `Uint8Array` parameter becomes its tag; other values go as they are (the
222
+ * server validates them). A `bigint` outside the signed 64-bit range is a
223
+ * `bad-request` here, before anything is sent.
224
+ */
225
+ export declare function encodeRequestFrame(request: Request): import("@noego/trust").Err<{
226
+ kind: "encode-failed";
227
+ message: string;
228
+ }> | import("@noego/trust").Ok<string> | import("@noego/trust").Err<{
229
+ kind: "bad-request";
230
+ message: string;
231
+ }>;
232
+ /** Positional or named parameters in wire form; see `encodeRequestFrame`. */
233
+ export declare function encodeSqlParams(params: SqlParams): import("@noego/trust").Err<Readonly<{
234
+ kind: "invalid";
235
+ message: string;
236
+ }>> | import("@noego/trust").Ok<WireParams>;
237
+ /**
238
+ * An integer result in wire form: a JSON number when it is exactly
239
+ * representable (|n| ≤ 2^53-1), else its `$bigint` tag.
240
+ */
241
+ export declare function encodeWireInteger(value: number | bigint): WireInteger;
242
+ /**
243
+ * One value SQLite returned, in wire form, losslessly: integers as
244
+ * `encodeWireInteger`, bytes as `$blob`. A REAL JSON cannot hold (±Infinity)
245
+ * is refused rather than sent as `null`.
246
+ */
247
+ export declare function encodeResultValue(value: unknown): import("@noego/trust").Err<Readonly<{
248
+ kind: "invalid";
249
+ message: string;
250
+ }>> | import("@noego/trust").Ok<WireValue>;
251
+ /** Rows as SQLite returned them (`unknown`), in wire form. */
252
+ export declare function encodeResultRows(input: unknown): import("@noego/trust").Err<Readonly<{
253
+ kind: "invalid";
254
+ message: string;
255
+ }>> | import("@noego/trust").Ok<WireRow[]>;
155
256
  /** Parses JSON text into `unknown`; what it holds is for a validator to decide. */
156
257
  export declare function fromJson(text: string): Result<unknown, {
157
258
  kind: "invalid";
158
259
  message: string;
159
260
  }>;
160
- /** A value that survives JSON and SQLite binding: string, number, boolean or null. */
161
- export declare function parseSqlValue(input: unknown): import("@noego/trust").Ok<SqlValue> | import("@noego/trust").Err<Readonly<{
261
+ /**
262
+ * A value that survives JSON and SQLite binding: string, number, boolean or
263
+ * null, or a `$bigint` / `$blob` tag decoded to `bigint` / `Uint8Array`.
264
+ */
265
+ export declare function parseSqlValue(input: unknown): import("@noego/trust").Err<Readonly<{
162
266
  kind: "invalid";
163
267
  message: string;
164
- }>>;
268
+ }>> | import("@noego/trust").Ok<SqlValue>;
165
269
  /** Positional (`[...]`) or named (`{ name: value }`) parameters. */
166
270
  export declare function parseSqlParams(input: unknown): import("@noego/trust").Err<Readonly<{
167
271
  kind: "invalid";
@@ -219,6 +323,23 @@ export declare function parseBatchResult(input: unknown): import("@noego/trust")
219
323
  }>> | import("@noego/trust").Ok<Readonly<{
220
324
  results: ReadonlyArray<RunResult | QueryResult>;
221
325
  }>>;
326
+ export declare function parseStatementResult(input: unknown): import("@noego/trust").Err<Readonly<{
327
+ kind: "invalid";
328
+ message: string;
329
+ }>> | import("@noego/trust").Ok<Readonly<{
330
+ reader: boolean;
331
+ rows: SqlRow[];
332
+ changes: number;
333
+ lastInsertRowid: number | bigint;
334
+ }>>;
335
+ export declare function parseExecResult(input: unknown): import("@noego/trust").Err<Readonly<{
336
+ kind: "invalid";
337
+ message: string;
338
+ }>> | import("@noego/trust").Ok<Readonly<{
339
+ statements: number;
340
+ changes: number;
341
+ lastInsertRowid: number | bigint;
342
+ }>>;
222
343
  export declare function parseHelloResult(input: unknown): import("@noego/trust").Err<Readonly<{
223
344
  kind: "invalid";
224
345
  message: string;
@@ -264,6 +385,13 @@ export declare function parseStatusResult(input: unknown): import("@noego/trust"
264
385
  * `ROLLBACK TO` (a savepoint) is told apart from a bare `ROLLBACK`.
265
386
  */
266
387
  export declare function transactionControl(sql: string): 'begin' | 'commit' | 'rollback' | 'savepoint' | 'release' | 'rollback-to' | null;
388
+ /**
389
+ * The statements of a SQL text, in order, each without its terminating `;`.
390
+ * Statement ends are found as SQLite finds them (`sqlite3_complete`): a `;`
391
+ * inside a string, quoted identifier, comment or trigger body does not end a
392
+ * statement. Statements that are only whitespace or comments are dropped.
393
+ */
394
+ export declare function splitSqlStatements(sql: string): string[];
267
395
  export declare function parseStopResult(input: unknown): import("@noego/trust").Err<Readonly<{
268
396
  kind: "invalid";
269
397
  message: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noego/sqlego",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "One owner process per SQLite file. Clients (CLI, Node, Bun) pass SQL over a local socket; the server boots on demand and exits when idle.",
5
5
  "type": "module",
6
6
  "license": "ISC",