@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/src/server.ts CHANGED
@@ -5,15 +5,19 @@ import { Result, Trust } from '@noego/trust';
5
5
  import {
6
6
  PROTOCOL_VERSION,
7
7
  encodeFrame,
8
+ encodeResultRows,
9
+ encodeWireInteger,
8
10
  errorMessage,
9
11
  fromJson,
10
12
  parseRequest,
11
13
  parseRows,
12
14
  splitFrames,
15
+ splitSqlStatements,
13
16
  toJson,
14
17
  transactionControl,
15
18
  type BatchResult,
16
19
  type BeginResult,
20
+ type ExecWireResult,
17
21
  type HelloResult,
18
22
  type QueryResult,
19
23
  type Request,
@@ -22,6 +26,7 @@ import {
22
26
  type SqlParams,
23
27
  type SqlValue,
24
28
  type Statement,
29
+ type StatementWireResult,
25
30
  type StatusResult,
26
31
  type TransactionEndResult,
27
32
  type TransactionMode,
@@ -66,6 +71,13 @@ type BadRequest = { readonly kind: 'bad-request'; readonly message: string };
66
71
  type TransactionFailure = { readonly kind: 'tx-expired' | 'tx-invalid'; readonly message: string };
67
72
  type CleanupFailure = { readonly kind: 'cleanup-failed'; readonly message: string };
68
73
  type WriteFailure = { readonly kind: 'write-failed'; readonly message: string };
74
+ type EncodeFailure = { readonly kind: 'encode-failed'; readonly message: string };
75
+
76
+ /** One statement as `executeOne` ran it: its raw rows and what it changed. */
77
+ type Executed = { reader: boolean; rows: unknown; changes: number; lastInsertRowid: number | bigint };
78
+ /** The connection's counters around a statement (`changes()`, `total_changes()`, `last_insert_rowid()`). */
79
+ type Counters = { changes: number; total: number; lastInsertRowid: number | bigint };
80
+ type TxControl = ReturnType<typeof transactionControl>;
69
81
 
70
82
  const sqliteFailure = (cause: unknown): SqliteFailure => ({ kind: 'sqlite', message: errorMessage(cause) });
71
83
  const cleanupFailure = (cause: unknown): CleanupFailure => ({ kind: 'cleanup-failed', message: errorMessage(cause) });
@@ -156,7 +168,9 @@ export class SqlegoServer {
156
168
  const db = Trust.try(
157
169
  () => {
158
170
  mkdirSync(path.dirname(paths.value.file), { recursive: true });
159
- const opened = new Database(paths.value.file, { create: true, strict: false });
171
+ // safeIntegers: SQLite integers arrive as bigint so `statement`/`exec`
172
+ // can return all 64 bits; `query`/`run`/`batch` still send JSON numbers.
173
+ const opened = new Database(paths.value.file, { create: true, strict: false, safeIntegers: true });
160
174
  for (const pragma of options.pragmas ?? DEFAULT_PRAGMAS) opened.exec(`PRAGMA ${pragma}`);
161
175
  return opened;
162
176
  },
@@ -341,7 +355,9 @@ export class SqlegoServer {
341
355
  if (!open || open.connection === connection) return false;
342
356
  switch (request.op) {
343
357
  case 'query':
344
- case 'run': return request.txId === undefined;
358
+ case 'run':
359
+ case 'statement':
360
+ case 'exec': return request.txId === undefined;
345
361
  case 'batch':
346
362
  case 'begin': return true;
347
363
  default: return false;
@@ -393,6 +409,7 @@ export class SqlegoServer {
393
409
  case 'sqlite': return { id: request.id, ok: false, error: { code: 'sqlite', message: outcome.error.message } };
394
410
  case 'tx-expired': return { id: request.id, ok: false, error: { code: 'tx-expired', message: outcome.error.message } };
395
411
  case 'tx-invalid': return { id: request.id, ok: false, error: { code: 'tx-invalid', message: outcome.error.message } };
412
+ case 'encode-failed': return { id: request.id, ok: false, error: { code: 'encode-failed', message: outcome.error.message } };
396
413
  default: {
397
414
  const unhandled: never = outcome.error;
398
415
  return unhandled;
@@ -405,6 +422,8 @@ export class SqlegoServer {
405
422
  case 'hello': return this.hello(request.protocol);
406
423
  case 'query':
407
424
  case 'run': return this.statement(connection, request.op, request.sql, request.params, request.txId);
425
+ case 'statement': return this.unifiedStatement(connection, request.sql, request.params, request.txId);
426
+ case 'exec': return this.exec(connection, request.sql, request.txId);
408
427
  case 'batch': return this.batch(connection, request.statements);
409
428
  case 'begin': return this.begin(connection, request.mode ?? 'deferred', request.leaseMs);
410
429
  case 'commit': return this.finish(connection, request.txId, 'commit');
@@ -433,19 +452,58 @@ export class SqlegoServer {
433
452
  * only through `commit`/`rollback`, so the server always knows its state.
434
453
  */
435
454
  private statement(connection: Connection, op: 'query' | 'run', sql: string, params: SqlParams | undefined, txId: number | undefined) {
436
- const control = transactionControl(sql);
455
+ return this.scoped<QueryResult | RunResult, SqliteFailure>(connection, op, txId, [transactionControl(sql)], () => this.runStatement(op, sql, params));
456
+ }
457
+
458
+ /**
459
+ * One `statement`: exactly one SQL statement (a second one would otherwise
460
+ * be silently ignored by prepare), under the same transaction-control rules
461
+ * as `query`/`run`.
462
+ */
463
+ private unifiedStatement(connection: Connection, sql: string, params: SqlParams | undefined, txId: number | undefined) {
464
+ const pieces = splitSqlStatements(sql);
465
+ if (pieces.length === 0) return badRequest('statement needs one SQL statement; the text has none');
466
+ if (pieces.length > 1) return badRequest(`statement takes one SQL statement, the text has ${pieces.length}: use exec for several`);
467
+ const piece = pieces[0];
468
+ return this.scoped<StatementWireResult, SqliteFailure | EncodeFailure>(connection, 'statement', txId, [transactionControl(piece)], () => this.encodeExecuted(this.executeOne(piece, params)));
469
+ }
470
+
471
+ /**
472
+ * `exec`: every statement of the text, in order, stopping at the first
473
+ * failure (statements before it keep their effect, as with sqlite3_exec).
474
+ * Each statement is classified before any runs, so transaction control
475
+ * hidden after a harmless first statement is refused just like a leading one.
476
+ */
477
+ private exec(connection: Connection, sql: string, txId: number | undefined) {
478
+ const pieces = splitSqlStatements(sql);
479
+ return this.scoped(connection, 'exec', txId, pieces.map((piece) => transactionControl(piece)), () => this.runScript(pieces));
480
+ }
481
+
482
+ /**
483
+ * Runs `work` under the transaction rules shared by every statement op:
484
+ * outside a transaction no transaction-control SQL at all; inside the
485
+ * caller's own transaction, savepoints only, and its lease is renewed (or
486
+ * the transaction closed when SQLite aborted it). Outside a transaction,
487
+ * work that somehow left one open is rolled back and reported.
488
+ */
489
+ private scoped<T, E>(connection: Connection, op: string, txId: number | undefined, controls: readonly TxControl[], work: () => Result<T, E>) {
437
490
  if (txId === undefined) {
438
- if (control !== null) {
439
- return badRequest(`${control.toUpperCase()} is not allowed as a plain ${op}: open a transaction with begin and end it with commit or rollback`);
491
+ const refused = refuseControl(controls, op, undefined);
492
+ if (!refused.ok) return refused;
493
+ const wasInTransaction = this.db.inTransaction;
494
+ const outcome = work();
495
+ if (!wasInTransaction && this.db.inTransaction) {
496
+ const rolledBack = Trust.try(() => this.db.exec('ROLLBACK'), sqliteFailure);
497
+ if (!rolledBack.ok && rolledBack.error.kind === 'sqlite') this.log('rollback failed', { op, error: rolledBack.error.message });
498
+ return Result.err<SqliteFailure>({ kind: 'sqlite', message: `${op} left a transaction open, which only begin may do; it was rolled back` });
440
499
  }
441
- return this.runStatement(op, sql, params);
500
+ return outcome;
442
501
  }
443
502
  const owned = this.ownedTransaction(connection, txId);
444
503
  if (!owned.ok) return owned;
445
- if (control === 'begin' || control === 'commit' || control === 'rollback') {
446
- return badRequest(`${control.toUpperCase()} is not allowed inside transaction ${txId}: end it with commit or rollback`);
447
- }
448
- const outcome = this.runStatement(op, sql, params);
504
+ const refused = refuseControl(controls, op, txId);
505
+ if (!refused.ok) return refused;
506
+ const outcome = work();
449
507
  this.afterTransactionStatement(owned.value);
450
508
  return outcome;
451
509
  }
@@ -483,13 +541,107 @@ export class SqlegoServer {
483
541
  () => {
484
542
  const statement = this.db.query(sql);
485
543
  const outcome = params === undefined ? statement.run() : statement.run(...bindings(params));
486
- const result: RunResult = { changes: outcome.changes, lastInsertRowid: outcome.lastInsertRowid };
544
+ // safeIntegers may report either counter as bigint; `run` keeps answering with numbers.
545
+ const result: RunResult = { changes: Number(outcome.changes), lastInsertRowid: outcome.lastInsertRowid };
487
546
  return result;
488
547
  },
489
548
  sqliteFailure,
490
549
  );
491
550
  }
492
551
 
552
+ /**
553
+ * Prepares and steps one statement exactly once. A statement with result
554
+ * columns (SELECT, PRAGMA, `INSERT … RETURNING`) is stepped through `all()`
555
+ * and never re-run for its changes; one without is stepped through `run()`.
556
+ * `changes` is SQLite's own count when the statement changed anything
557
+ * (`total_changes()` moved), else 0 — `changes()` alone would repeat the
558
+ * previous write's count after a read or DDL.
559
+ */
560
+ private executeOne(sql: string, params: SqlParams | undefined) {
561
+ const before = this.counters();
562
+ if (!before.ok) return before;
563
+ const prepared = Trust.try(() => this.db.prepare(sql), sqliteFailure);
564
+ if (!prepared.ok) return prepared;
565
+ const statement = prepared.value;
566
+ const args: SQLQueryBindings[] = params === undefined ? [] : bindings(params);
567
+ const ran = Trust.try(
568
+ () => {
569
+ const columns: unknown = statement.columnNames;
570
+ if (!Array.isArray(columns)) throw new Error('SQLite returned invalid column metadata');
571
+ const reader = columns.length > 0;
572
+ if (reader) {
573
+ const rows: unknown = statement.all(...args);
574
+ return { reader, rows };
575
+ }
576
+ statement.run(...args);
577
+ return { reader, rows: [] };
578
+ },
579
+ sqliteFailure,
580
+ );
581
+ const finalized = Trust.try(() => statement.finalize(), sqliteFailure);
582
+ if (!finalized.ok && finalized.error.kind === 'sqlite') this.log('finalize failed', { error: finalized.error.message });
583
+ if (!ran.ok) return ran;
584
+ const after = this.counters();
585
+ if (!after.ok) return after;
586
+ const executed: Executed = {
587
+ reader: ran.value.reader,
588
+ rows: ran.value.rows,
589
+ changes: after.value.total === before.value.total ? 0 : after.value.changes,
590
+ lastInsertRowid: after.value.lastInsertRowid,
591
+ };
592
+ return Result.ok(executed);
593
+ }
594
+
595
+ private counters() {
596
+ const read = Trust.try(
597
+ (): unknown => this.db.query('SELECT changes() AS changes, total_changes() AS total, last_insert_rowid() AS rowid').get(),
598
+ sqliteFailure,
599
+ );
600
+ if (!read.ok) return read;
601
+ return parseCounters(read.value);
602
+ }
603
+
604
+ /** A `statement` reply in wire form: lossless integers and blobs. */
605
+ private encodeExecuted(executed: Result<Executed, SqliteFailure>) {
606
+ if (!executed.ok) return executed;
607
+ const rows = encodeResultRows(executed.value.rows);
608
+ if (!rows.ok) return Result.err<EncodeFailure>({ kind: 'encode-failed', message: rows.error.message });
609
+ const result: StatementWireResult = {
610
+ reader: executed.value.reader,
611
+ rows: rows.value,
612
+ changes: executed.value.changes,
613
+ lastInsertRowid: encodeWireInteger(executed.value.lastInsertRowid),
614
+ };
615
+ return Result.ok(result);
616
+ }
617
+
618
+ /**
619
+ * The statements of one `exec`, in order. Stops at the first failure, and
620
+ * also when a statement changed whether the connection is inside a
621
+ * transaction (which only begin/commit/rollback may do) — `scoped` and
622
+ * `afterTransactionStatement` then settle the transaction itself.
623
+ */
624
+ private runScript(pieces: readonly string[]) {
625
+ const wasInTransaction = this.db.inTransaction;
626
+ let changes = 0;
627
+ for (const [index, piece] of pieces.entries()) {
628
+ const at = pieces.length > 1 ? `statement ${index + 1} of ${pieces.length}` : 'the statement';
629
+ const executed = this.executeOne(piece, undefined);
630
+ if (!executed.ok) {
631
+ const applied = index > 0 ? ' (the statements before it took effect)' : '';
632
+ return Result.err<SqliteFailure>({ kind: 'sqlite', message: `${at} failed${applied}: ${executed.error.message}` });
633
+ }
634
+ changes += executed.value.changes;
635
+ if (this.db.inTransaction !== wasInTransaction) {
636
+ return Result.err<SqliteFailure>({ kind: 'sqlite', message: `${at} changed the transaction state; exec stopped there` });
637
+ }
638
+ }
639
+ const counters = this.counters();
640
+ if (!counters.ok) return counters;
641
+ const result: ExecWireResult = { statements: pieces.length, changes, lastInsertRowid: encodeWireInteger(counters.value.lastInsertRowid) };
642
+ return Result.ok(result);
643
+ }
644
+
493
645
  /** All statements in one transaction; any failure rolls the whole batch back. */
494
646
  private batch(connection: Connection, statements: readonly Statement[]) {
495
647
  if (statements.length === 0) return badRequest('batch requires a non-empty statements array');
@@ -710,6 +862,44 @@ export class SqlegoServer {
710
862
  }
711
863
  }
712
864
 
865
+ /**
866
+ * Refuses transaction-control statements: all of them outside a transaction
867
+ * (a stray `BEGIN` or `SAVEPOINT` would wrap every client's later statements),
868
+ * and those that would end or nest the transaction inside one. With several
869
+ * statements (`exec`) the message names which one.
870
+ */
871
+ function refuseControl(controls: readonly TxControl[], op: string, txId: number | undefined) {
872
+ for (const [index, control] of controls.entries()) {
873
+ if (control === null) continue;
874
+ const at = controls.length > 1 ? `statement ${index + 1}: ` : '';
875
+ if (txId === undefined) {
876
+ return badRequest(`${at}${control.toUpperCase()} is not allowed as a plain ${op}: open a transaction with begin and end it with commit or rollback`);
877
+ }
878
+ if (control === 'begin' || control === 'commit' || control === 'rollback') {
879
+ return badRequest(`${at}${control.toUpperCase()} is not allowed inside transaction ${txId}: end it with commit or rollback`);
880
+ }
881
+ }
882
+ return Result.ok(undefined);
883
+ }
884
+
885
+ /** The counters row: each an integer, as a number or (safeIntegers) a bigint. */
886
+ //trust:validator_function
887
+ function parseCounters(input: unknown) {
888
+ const fields = typeof input === 'object' && input !== null ? (input as Readonly<Record<string, unknown>>) : null;
889
+ const changes = fields?.changes;
890
+ const total = fields?.total;
891
+ const rowid = fields?.rowid;
892
+ if (
893
+ (typeof changes !== 'number' && typeof changes !== 'bigint')
894
+ || (typeof total !== 'number' && typeof total !== 'bigint')
895
+ || (typeof rowid !== 'number' && typeof rowid !== 'bigint')
896
+ ) {
897
+ return Result.err<SqliteFailure>({ kind: 'sqlite', message: 'unexpected shape of changes()/total_changes()/last_insert_rowid()' });
898
+ }
899
+ const counters: Counters = { changes: Number(changes), total: Number(total), lastInsertRowid: rowid };
900
+ return Result.ok(counters);
901
+ }
902
+
713
903
  /**
714
904
  * bun:sqlite binds positional params from an array spread and named params
715
905
  * from one object argument. Every SqlValue is a binding bun:sqlite accepts;