@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/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 = 1;
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,7 +156,69 @@ 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
  }
73
- var ERROR_CODES = ["sqlite", "bad-request", "protocol-mismatch", "shutting-down", "encode-failed"];
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
+ }
212
+ var ERROR_CODES = [
213
+ "sqlite",
214
+ "bad-request",
215
+ "protocol-mismatch",
216
+ "shutting-down",
217
+ "encode-failed",
218
+ "tx-expired",
219
+ "tx-invalid",
220
+ "tx-busy"
221
+ ];
74
222
  function parseErrorCode(input) {
75
223
  const code = ERROR_CODES.find((known) => known === input);
76
224
  return code === undefined ? invalid(`unknown error code ${String(input)}`) : Result.ok(code);
@@ -151,6 +299,52 @@ function parseBatchResult(input) {
151
299
  const result = { results };
152
300
  return Result.ok(result);
153
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
+ }
154
348
  function parseHelloResult(input) {
155
349
  const fields = fieldsOf(input);
156
350
  if (!fields || typeof fields.serverVersion !== "string" || typeof fields.protocol !== "number" || typeof fields.file !== "string" || typeof fields.pid !== "number") {
@@ -159,11 +353,46 @@ function parseHelloResult(input) {
159
353
  const result = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid };
160
354
  return Result.ok(result);
161
355
  }
356
+ function parseBeginResult(input) {
357
+ const f = fieldsOf(input);
358
+ if (!f || typeof f.txId !== "number" || typeof f.leaseMs !== "number" || typeof f.maxDurationMs !== "number") {
359
+ return invalid("a begin result needs txId, leaseMs and maxDurationMs (numbers)");
360
+ }
361
+ const result = { txId: f.txId, leaseMs: f.leaseMs, maxDurationMs: f.maxDurationMs };
362
+ return Result.ok(result);
363
+ }
364
+ function parseTransactionEndResult(input) {
365
+ const f = fieldsOf(input);
366
+ if (!f || typeof f.txId !== "number")
367
+ return invalid("a commit/rollback result needs txId (number)");
368
+ const result = { txId: f.txId };
369
+ return Result.ok(result);
370
+ }
371
+ function parseTransactionStatus(input) {
372
+ if (input === null)
373
+ return Result.ok(null);
374
+ const f = fieldsOf(input);
375
+ if (!f || typeof f.txId !== "number" || typeof f.ageMs !== "number" || typeof f.idleMs !== "number" || typeof f.leaseMs !== "number" || typeof f.maxDurationMs !== "number" || typeof f.queued !== "number") {
376
+ return invalid("status.transaction must be null or carry txId, ageMs, idleMs, leaseMs, maxDurationMs and queued");
377
+ }
378
+ const status = {
379
+ txId: f.txId,
380
+ ageMs: f.ageMs,
381
+ idleMs: f.idleMs,
382
+ leaseMs: f.leaseMs,
383
+ maxDurationMs: f.maxDurationMs,
384
+ queued: f.queued
385
+ };
386
+ return Result.ok(status);
387
+ }
162
388
  function parseStatusResult(input) {
163
389
  const f = fieldsOf(input);
164
390
  if (!f || typeof f.file !== "string" || typeof f.socket !== "string" || typeof f.pid !== "number" || typeof f.serverVersion !== "string" || typeof f.protocol !== "number" || typeof f.clients !== "number" || typeof f.uptimeMs !== "number" || f.idleMs !== null && typeof f.idleMs !== "number" || typeof f.idleTimeoutMs !== "number" || typeof f.requestsServed !== "number") {
165
391
  return invalid("a status result is missing a field or has one of the wrong type");
166
392
  }
393
+ const transaction = parseTransactionStatus(f.transaction);
394
+ if (!transaction.ok)
395
+ return transaction;
167
396
  const result = {
168
397
  file: f.file,
169
398
  socket: f.socket,
@@ -174,10 +403,13 @@ function parseStatusResult(input) {
174
403
  uptimeMs: f.uptimeMs,
175
404
  idleMs: f.idleMs,
176
405
  idleTimeoutMs: f.idleTimeoutMs,
177
- requestsServed: f.requestsServed
406
+ requestsServed: f.requestsServed,
407
+ transaction: transaction.value
178
408
  };
179
409
  return Result.ok(result);
180
410
  }
411
+ var SQL_SPACE = new Set([" ", "\t", `
412
+ `, "\f", "\r", "\uFEFF"]);
181
413
  function parseStopResult(input) {
182
414
  const fields = fieldsOf(input);
183
415
  if (!fields || fields.stopping !== true)
@@ -299,7 +531,7 @@ import { fileURLToPath } from "node:url";
299
531
  // package.json
300
532
  var package_default = {
301
533
  name: "@noego/sqlego",
302
- version: "0.0.1",
534
+ version: "0.0.3",
303
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.",
304
536
  type: "module",
305
537
  license: "ISC",
@@ -357,8 +589,8 @@ function sourceBuildId(sourceDirectory) {
357
589
  }, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
358
590
  }
359
591
  function resolveBuildId() {
360
- if ("c91af7f0abe9".length > 0)
361
- return "c91af7f0abe9";
592
+ if ("ed6f3704ee47".length > 0)
593
+ return "ed6f3704ee47";
362
594
  const directory = Trust.try(() => path2.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
363
595
  if (!directory.ok)
364
596
  return decideUnknownBuild(directory.error.kind);
@@ -383,6 +615,8 @@ var BUILD_ID = resolveBuildId();
383
615
  var VERSION = process.env.SQLEGO_VERSION_OVERRIDE || `${package_default.version}+${BUILD_ID}`;
384
616
 
385
617
  // src/client.ts
618
+ var SAVEPOINT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
619
+
386
620
  class SqlegoClientError extends Error {
387
621
  code;
388
622
  constructor(code, message) {
@@ -399,6 +633,9 @@ function unwrap(outcome) {
399
633
  function callerRows(rows) {
400
634
  return rows;
401
635
  }
636
+ function callerStatement(result) {
637
+ return { reader: result.reader, rows: callerRows(result.rows), changes: result.changes, lastInsertRowid: result.lastInsertRowid };
638
+ }
402
639
 
403
640
  class SqlegoClient {
404
641
  paths;
@@ -434,10 +671,48 @@ class SqlegoClient {
434
671
  async run(sql, params) {
435
672
  return unwrap(await this.call({ op: "run", sql, params }, parseRunResult));
436
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
+ }
437
680
  async batch(statements) {
438
681
  const result = unwrap(await this.call({ op: "batch", statements }, parseBatchResult));
439
682
  return result.results;
440
683
  }
684
+ async begin(options = {}) {
685
+ const opened = unwrap(await this.call({ op: "begin", mode: options.mode, leaseMs: options.leaseMs }, parseBeginResult));
686
+ return new SqlegoTransaction(this, opened);
687
+ }
688
+ async transaction(work, options = {}) {
689
+ const tx = await this.begin(options);
690
+ const outcome = await Trust.tryAsync(() => work(tx), (cause) => ({ kind: "work-failed", cause }));
691
+ if (outcome.ok) {
692
+ await tx.commit();
693
+ return outcome.value;
694
+ }
695
+ await tx.rollback().catch(() => {
696
+ return;
697
+ });
698
+ throw outcome.error.cause;
699
+ }
700
+ async transactionQuery(txId, sql, params) {
701
+ const result = unwrap(await this.call({ op: "query", sql, params, txId }, parseQueryResult));
702
+ return callerRows(result.rows);
703
+ }
704
+ async transactionRun(txId, sql, params) {
705
+ return unwrap(await this.call({ op: "run", sql, params, txId }, parseRunResult));
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
+ }
713
+ async transactionEnd(txId, how) {
714
+ unwrap(await this.call({ op: how, txId }, parseTransactionEndResult));
715
+ }
441
716
  async status() {
442
717
  return unwrap(await this.call({ op: "status" }, parseStatusResult));
443
718
  }
@@ -637,7 +912,7 @@ class SqlegoClient {
637
912
  return Promise.resolve(Result.err({ kind: "not-connected", message: "client is not connected" }));
638
913
  }
639
914
  const id = this.nextId++;
640
- const frame = encodeFrame({ id, ...body });
915
+ const frame = encodeRequestFrame({ id, ...body });
641
916
  if (!frame.ok)
642
917
  return Promise.resolve(frame);
643
918
  return new Promise((settle) => {
@@ -666,6 +941,57 @@ class SqlegoClient {
666
941
  await sleep(25);
667
942
  }
668
943
  }
944
+
945
+ class SqlegoTransaction {
946
+ id;
947
+ leaseMs;
948
+ maxDurationMs;
949
+ client;
950
+ ended = false;
951
+ constructor(client, opened) {
952
+ this.client = client;
953
+ this.id = opened.txId;
954
+ this.leaseMs = opened.leaseMs;
955
+ this.maxDurationMs = opened.maxDurationMs;
956
+ }
957
+ get closed() {
958
+ return this.ended;
959
+ }
960
+ query(sql, params) {
961
+ return this.client.transactionQuery(this.id, sql, params);
962
+ }
963
+ run(sql, params) {
964
+ return this.client.transactionRun(this.id, sql, params);
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
+ }
972
+ async savepoint(name) {
973
+ await this.run(`SAVEPOINT ${savepointName(name)}`);
974
+ }
975
+ async release(name) {
976
+ await this.run(`RELEASE SAVEPOINT ${savepointName(name)}`);
977
+ }
978
+ async rollbackTo(name) {
979
+ await this.run(`ROLLBACK TO SAVEPOINT ${savepointName(name)}`);
980
+ }
981
+ async commit() {
982
+ this.ended = true;
983
+ await this.client.transactionEnd(this.id, "commit");
984
+ }
985
+ async rollback() {
986
+ this.ended = true;
987
+ await this.client.transactionEnd(this.id, "rollback");
988
+ }
989
+ }
990
+ function savepointName(name) {
991
+ if (SAVEPOINT_NAME.test(name))
992
+ return name;
993
+ return unwrap(Result.err({ kind: "bad-request", message: `savepoint name must be an identifier (letters, digits, _), not "${name}"` }));
994
+ }
669
995
  function defaultServerCommand() {
670
996
  const configured = process.env.SQLEGO_BIN;
671
997
  if (configured && configured.length > 0)
@@ -743,6 +1069,7 @@ export {
743
1069
  PROTOCOL_VERSION,
744
1070
  SqlegoClient,
745
1071
  SqlegoClientError,
1072
+ SqlegoTransaction,
746
1073
  VERSION,
747
1074
  canonicalFile,
748
1075
  defaultServerCommand,