@noego/sqlego 0.0.1-dev.0 → 0.0.1-dev.1

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/client.ts CHANGED
@@ -11,14 +11,17 @@ import {
11
11
  errorMessage,
12
12
  fromJson,
13
13
  parseBatchResult,
14
+ parseBeginResult,
14
15
  parseHelloResult,
15
16
  parseQueryResult,
16
17
  parseResponse,
17
18
  parseRunResult,
18
19
  parseStatusResult,
19
20
  parseStopResult,
21
+ parseTransactionEndResult,
20
22
  splitFrames,
21
23
  type BatchResult,
24
+ type BeginResult,
22
25
  type ErrorCode,
23
26
  type HelloResult,
24
27
  type Request,
@@ -27,6 +30,7 @@ import {
27
30
  type SqlRow,
28
31
  type Statement,
29
32
  type StatusResult,
33
+ type TransactionMode,
30
34
  } from './protocol.ts';
31
35
  import { isProcessAlive, resolvePaths, type FilePaths } from './paths.ts';
32
36
  import { VERSION } from './version.ts';
@@ -53,6 +57,19 @@ export type ClientOptions = Readonly<{
53
57
  requestTimeoutMs?: number;
54
58
  }>;
55
59
 
60
+ export type BeginOptions = Readonly<{
61
+ /** `immediate` takes the write lock at `begin`; `deferred` (default) on the first write. */
62
+ mode?: TransactionMode;
63
+ /**
64
+ * Roll the transaction back when no request for it arrives within this
65
+ * long; each request renews it. The server caps it at its own lease.
66
+ */
67
+ leaseMs?: number;
68
+ }>;
69
+
70
+ /** A savepoint name is spliced into SQL text, so it must be a bare identifier. */
71
+ const SAVEPOINT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
72
+
56
73
  // No TypeScript parameter properties anywhere in the client: Node's
57
74
  // strip-only type loading (`--experimental-strip-types`) rejects them, and the
58
75
  // client must load in plain Node without a build step.
@@ -152,6 +169,48 @@ export class SqlegoClient {
152
169
  return result.results;
153
170
  }
154
171
 
172
+ /**
173
+ * Opens a transaction held across requests. It is bound to this connection
174
+ * and rolled back by the server if the connection drops, the lease runs out
175
+ * between requests, or the server's hard cap is reached; other clients'
176
+ * statements wait until it ends. End it with `commit` or `rollback`.
177
+ */
178
+ async begin(options: BeginOptions = {}): Promise<SqlegoTransaction> {
179
+ const opened = unwrap(await this.call({ op: 'begin', mode: options.mode, leaseMs: options.leaseMs }, parseBeginResult));
180
+ return new SqlegoTransaction(this, opened);
181
+ }
182
+
183
+ /** Runs `work` in a transaction: commits when it resolves, rolls back when it rejects (and rethrows). */
184
+ async transaction<T>(work: (tx: SqlegoTransaction) => Promise<T>, options: BeginOptions = {}): Promise<T> {
185
+ const tx = await this.begin(options);
186
+ const outcome = await Trust.tryAsync(() => work(tx), (cause) => ({ kind: 'work-failed' as const, cause }));
187
+ if (outcome.ok) {
188
+ await tx.commit();
189
+ return outcome.value;
190
+ }
191
+ // The work's own error is what the caller must see; a rollback that
192
+ // fails (the server already rolled back an expired transaction) adds nothing.
193
+ await tx.rollback().catch(() => undefined);
194
+ //trust:accept public API contract: transaction(work) rethrows the work's own rejection after rolling back
195
+ throw outcome.error.cause;
196
+ }
197
+
198
+ /** @internal Statements inside a transaction; `SqlegoTransaction` is the public face. */
199
+ async transactionQuery<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<Row[]> {
200
+ const result = unwrap(await this.call({ op: 'query', sql, params, txId }, parseQueryResult));
201
+ return callerRows<Row>(result.rows);
202
+ }
203
+
204
+ /** @internal */
205
+ async transactionRun(txId: number, sql: string, params?: SqlParams): Promise<RunResult> {
206
+ return unwrap(await this.call({ op: 'run', sql, params, txId }, parseRunResult));
207
+ }
208
+
209
+ /** @internal */
210
+ async transactionEnd(txId: number, how: 'commit' | 'rollback'): Promise<void> {
211
+ unwrap(await this.call({ op: how, txId }, parseTransactionEndResult));
212
+ }
213
+
155
214
  async status(): Promise<StatusResult> {
156
215
  return unwrap(await this.call({ op: 'status' }, parseStatusResult));
157
216
  }
@@ -414,6 +473,71 @@ export class SqlegoClient {
414
473
  }
415
474
  }
416
475
 
476
+ /**
477
+ * One open transaction on a `SqlegoClient`. Every method rejects with a
478
+ * `SqlegoClientError` whose code is `tx-expired` once the server has rolled
479
+ * it back (lease, hard cap, disconnect) and `tx-invalid` after it ended.
480
+ */
481
+ export class SqlegoTransaction {
482
+ readonly id: number;
483
+ /** The lease the server granted, which may be shorter than requested. */
484
+ readonly leaseMs: number;
485
+ /** The server's hard cap on this transaction's life. */
486
+ readonly maxDurationMs: number;
487
+ private readonly client: SqlegoClient;
488
+ private ended = false;
489
+
490
+ constructor(client: SqlegoClient, opened: BeginResult) {
491
+ this.client = client;
492
+ this.id = opened.txId;
493
+ this.leaseMs = opened.leaseMs;
494
+ this.maxDurationMs = opened.maxDurationMs;
495
+ }
496
+
497
+ /** True once `commit` or `rollback` has been sent; the server may also have ended it on its own. */
498
+ get closed(): boolean {
499
+ return this.ended;
500
+ }
501
+
502
+ query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]> {
503
+ return this.client.transactionQuery<Row>(this.id, sql, params);
504
+ }
505
+
506
+ run(sql: string, params?: SqlParams): Promise<RunResult> {
507
+ return this.client.transactionRun(this.id, sql, params);
508
+ }
509
+
510
+ /** `SAVEPOINT name`: a nested scope that `rollbackTo` can undo and `release` folds into the transaction. */
511
+ async savepoint(name: string): Promise<void> {
512
+ await this.run(`SAVEPOINT ${savepointName(name)}`);
513
+ }
514
+
515
+ async release(name: string): Promise<void> {
516
+ await this.run(`RELEASE SAVEPOINT ${savepointName(name)}`);
517
+ }
518
+
519
+ /** Undoes everything since the savepoint; the savepoint itself stays until released. */
520
+ async rollbackTo(name: string): Promise<void> {
521
+ await this.run(`ROLLBACK TO SAVEPOINT ${savepointName(name)}`);
522
+ }
523
+
524
+ async commit(): Promise<void> {
525
+ this.ended = true;
526
+ await this.client.transactionEnd(this.id, 'commit');
527
+ }
528
+
529
+ async rollback(): Promise<void> {
530
+ this.ended = true;
531
+ await this.client.transactionEnd(this.id, 'rollback');
532
+ }
533
+ }
534
+
535
+ /** A savepoint name is spliced into SQL, so only an identifier is accepted. */
536
+ function savepointName(name: string): string {
537
+ if (SAVEPOINT_NAME.test(name)) return name;
538
+ return unwrap(Result.err({ kind: 'bad-request', message: `savepoint name must be an identifier (letters, digits, _), not "${name}"` }));
539
+ }
540
+
417
541
  /**
418
542
  * How to start a server: SQLEGO_BIN if set; the compiled `sqlego` binary when
419
543
  * running as one; the dev entry (`bun src/cli.ts`) when running from source
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { SqlegoClient, SqlegoClientError, defaultServerCommand, type ClientOptions } from './client.ts';
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
3
  export {
4
4
  PROTOCOL_VERSION,
@@ -9,7 +9,10 @@ export {
9
9
  type RunResult,
10
10
  type QueryResult,
11
11
  type BatchResult,
12
+ type BeginResult,
12
13
  type StatusResult,
13
14
  type HelloResult,
15
+ type TransactionMode,
16
+ type TransactionStatus,
14
17
  } from './protocol.ts';
15
18
  export { VERSION } from './version.ts';
package/src/protocol.ts CHANGED
@@ -6,14 +6,18 @@
6
6
  * two clients' statements interleave at statement (or batch) granularity and
7
7
  * never contend for SQLite's write lock.
8
8
  *
9
- * There is deliberately no BEGIN/COMMIT over the wire: a client-held
10
- * transaction would hold the file's only writer hostage to that client's
11
- * liveness. `batch` is the transactional unit.
9
+ * Transactions over the wire are leased, never bare: `begin` opens one bound
10
+ * to the client's socket, `query`/`run` carry its `txId`, and `commit` or
11
+ * `rollback` ends it. The server rolls it back on its own when the socket
12
+ * closes, when no request arrives within the lease, or when it has been open
13
+ * longer than the server's hard cap, so a client can never hold the file's
14
+ * only writer hostage. Transaction-control SQL (`BEGIN`, `COMMIT`, ...) is
15
+ * refused as plain `query`/`run`; savepoints are allowed inside a transaction.
12
16
  */
13
17
 
14
18
  import { Result, Trust } from '@noego/trust';
15
19
 
16
- export const PROTOCOL_VERSION = 1;
20
+ export const PROTOCOL_VERSION = 2;
17
21
 
18
22
  export type SqlParams = ReadonlyArray<SqlValue> | Readonly<Record<string, SqlValue>>;
19
23
  export type SqlValue = string | number | bigint | boolean | null | Uint8Array;
@@ -26,17 +30,38 @@ export type Statement = Readonly<{
26
30
  mode?: 'query' | 'run';
27
31
  }>;
28
32
 
33
+ export type TransactionMode = 'deferred' | 'immediate';
34
+
29
35
  export type Request =
30
36
  | { id: number; op: 'hello'; clientVersion: string; protocol: number }
31
- | { id: number; op: 'query'; sql: string; params?: SqlParams }
32
- | { id: number; op: 'run'; sql: string; params?: SqlParams }
37
+ | { id: number; op: 'query'; sql: string; params?: SqlParams; txId?: number }
38
+ | { id: number; op: 'run'; sql: string; params?: SqlParams; txId?: number }
33
39
  | { id: number; op: 'batch'; statements: readonly Statement[] }
40
+ | { id: number; op: 'begin'; mode?: TransactionMode; leaseMs?: number }
41
+ | { id: number; op: 'commit'; txId: number }
42
+ | { id: number; op: 'rollback'; txId: number }
34
43
  | { id: number; op: 'status' }
35
44
  | { id: number; op: 'stop' };
36
45
 
37
46
  export type RunResult = Readonly<{ changes: number; lastInsertRowid: number | bigint }>;
38
47
  export type QueryResult = Readonly<{ rows: SqlRow[] }>;
39
48
  export type BatchResult = Readonly<{ results: ReadonlyArray<RunResult | QueryResult> }>;
49
+ /** The lease the server granted (its own cap applies) and the hard cap on the transaction's life. */
50
+ export type BeginResult = Readonly<{ txId: number; leaseMs: number; maxDurationMs: number }>;
51
+ export type TransactionEndResult = Readonly<{ txId: number }>;
52
+
53
+ /** The open transaction as `status` reports it. */
54
+ export type TransactionStatus = Readonly<{
55
+ txId: number;
56
+ /** How long it has been open. */
57
+ ageMs: number;
58
+ /** Since its last request. */
59
+ idleMs: number;
60
+ leaseMs: number;
61
+ maxDurationMs: number;
62
+ /** Requests from other clients waiting for it to end. */
63
+ queued: number;
64
+ }>;
40
65
 
41
66
  export type HelloResult = Readonly<{
42
67
  serverVersion: string;
@@ -56,6 +81,7 @@ export type StatusResult = Readonly<{
56
81
  idleMs: number | null;
57
82
  idleTimeoutMs: number;
58
83
  requestsServed: number;
84
+ transaction: TransactionStatus | null;
59
85
  }>;
60
86
 
61
87
  export type ErrorCode =
@@ -64,7 +90,13 @@ export type ErrorCode =
64
90
  | 'protocol-mismatch'
65
91
  | 'shutting-down'
66
92
  /** The server could not serialize a result (a value JSON cannot hold). */
67
- | 'encode-failed';
93
+ | 'encode-failed'
94
+ /** The transaction was rolled back by the server: lease ran out, hard cap hit, or SQLite aborted it. */
95
+ | 'tx-expired'
96
+ /** No such open transaction on this connection (wrong id, already ended, or a second `begin`). */
97
+ | 'tx-invalid'
98
+ /** Another client's transaction kept the request waiting past the server's queue limit. */
99
+ | 'tx-busy';
68
100
 
69
101
  export type Response =
70
102
  | { id: number; ok: true; result: unknown }
@@ -194,7 +226,23 @@ export function parseRequest(input: unknown) {
194
226
  if (typeof fields.sql !== 'string') return reject(id, `${fields.op} needs sql (string)`);
195
227
  const params = parseOptionalParams(fields.params);
196
228
  if (!params.ok) return reject(id, params.error.message);
197
- const request: Request = { id, op: fields.op, sql: fields.sql, params: params.value };
229
+ const txId = fields.txId;
230
+ if (txId !== undefined && typeof txId !== 'number') return reject(id, 'txId must be a number');
231
+ const request: Request = { id, op: fields.op, sql: fields.sql, params: params.value, txId };
232
+ return Result.ok(request);
233
+ }
234
+ case 'begin': {
235
+ const mode = fields.mode;
236
+ if (mode !== undefined && mode !== 'deferred' && mode !== 'immediate') return reject(id, 'begin mode must be "deferred" or "immediate"');
237
+ const leaseMs = fields.leaseMs;
238
+ if (leaseMs !== undefined && (typeof leaseMs !== 'number' || !(leaseMs > 0))) return reject(id, 'leaseMs must be a positive number');
239
+ const request: Request = { id, op: 'begin', mode, leaseMs };
240
+ return Result.ok(request);
241
+ }
242
+ case 'commit':
243
+ case 'rollback': {
244
+ if (typeof fields.txId !== 'number') return reject(id, `${fields.op} needs txId (number)`);
245
+ const request: Request = { id, op: fields.op, txId: fields.txId };
198
246
  return Result.ok(request);
199
247
  }
200
248
  case 'batch': {
@@ -218,7 +266,9 @@ export function parseRequest(input: unknown) {
218
266
  }
219
267
  }
220
268
 
221
- const ERROR_CODES: readonly ErrorCode[] = ['sqlite', 'bad-request', 'protocol-mismatch', 'shutting-down', 'encode-failed'];
269
+ const ERROR_CODES: readonly ErrorCode[] = [
270
+ 'sqlite', 'bad-request', 'protocol-mismatch', 'shutting-down', 'encode-failed', 'tx-expired', 'tx-invalid', 'tx-busy',
271
+ ];
222
272
 
223
273
  //trust:validator_function
224
274
  function parseErrorCode(input: unknown) {
@@ -315,6 +365,40 @@ export function parseHelloResult(input: unknown) {
315
365
  return Result.ok(result);
316
366
  }
317
367
 
368
+ //trust:validator_function
369
+ export function parseBeginResult(input: unknown) {
370
+ const f = fieldsOf(input);
371
+ if (!f || typeof f.txId !== 'number' || typeof f.leaseMs !== 'number' || typeof f.maxDurationMs !== 'number') {
372
+ return invalid('a begin result needs txId, leaseMs and maxDurationMs (numbers)');
373
+ }
374
+ const result: BeginResult = { txId: f.txId, leaseMs: f.leaseMs, maxDurationMs: f.maxDurationMs };
375
+ return Result.ok(result);
376
+ }
377
+
378
+ //trust:validator_function
379
+ export function parseTransactionEndResult(input: unknown) {
380
+ const f = fieldsOf(input);
381
+ if (!f || typeof f.txId !== 'number') return invalid('a commit/rollback result needs txId (number)');
382
+ const result: TransactionEndResult = { txId: f.txId };
383
+ return Result.ok(result);
384
+ }
385
+
386
+ //trust:validator_function
387
+ function parseTransactionStatus(input: unknown) {
388
+ if (input === null) return Result.ok<TransactionStatus | null>(null);
389
+ const f = fieldsOf(input);
390
+ if (
391
+ !f || typeof f.txId !== 'number' || typeof f.ageMs !== 'number' || typeof f.idleMs !== 'number'
392
+ || typeof f.leaseMs !== 'number' || typeof f.maxDurationMs !== 'number' || typeof f.queued !== 'number'
393
+ ) {
394
+ return invalid('status.transaction must be null or carry txId, ageMs, idleMs, leaseMs, maxDurationMs and queued');
395
+ }
396
+ const status: TransactionStatus = {
397
+ txId: f.txId, ageMs: f.ageMs, idleMs: f.idleMs, leaseMs: f.leaseMs, maxDurationMs: f.maxDurationMs, queued: f.queued,
398
+ };
399
+ return Result.ok<TransactionStatus | null>(status);
400
+ }
401
+
318
402
  //trust:validator_function
319
403
  export function parseStatusResult(input: unknown) {
320
404
  const f = fieldsOf(input);
@@ -327,13 +411,36 @@ export function parseStatusResult(input: unknown) {
327
411
  ) {
328
412
  return invalid('a status result is missing a field or has one of the wrong type');
329
413
  }
414
+ const transaction = parseTransactionStatus(f.transaction);
415
+ if (!transaction.ok) return transaction;
330
416
  const result: StatusResult = {
331
417
  file: f.file, socket: f.socket, pid: f.pid, serverVersion: f.serverVersion, protocol: f.protocol,
332
418
  clients: f.clients, uptimeMs: f.uptimeMs, idleMs: f.idleMs, idleTimeoutMs: f.idleTimeoutMs, requestsServed: f.requestsServed,
419
+ transaction: transaction.value,
333
420
  };
334
421
  return Result.ok(result);
335
422
  }
336
423
 
424
+ /**
425
+ * The transaction-control statement a SQL text starts with, or null. Leading
426
+ * whitespace and comments are skipped so `/* x *\/ BEGIN` is still seen.
427
+ * `ROLLBACK TO` (a savepoint) is told apart from a bare `ROLLBACK`.
428
+ */
429
+ export function transactionControl(sql: string): 'begin' | 'commit' | 'rollback' | 'savepoint' | 'release' | 'rollback-to' | null {
430
+ const body = sql.replace(/^(?:\s+|--[^\n]*\n?|\/\*[\s\S]*?\*\/)+/, '');
431
+ const match = /^(BEGIN|START|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b(\s+TRANSACTION\b)?(\s+TO\b)?/i.exec(body);
432
+ if (!match) return null;
433
+ switch (match[1].toUpperCase()) {
434
+ case 'BEGIN':
435
+ case 'START': return 'begin';
436
+ case 'COMMIT':
437
+ case 'END': return 'commit';
438
+ case 'ROLLBACK': return match[3] ? 'rollback-to' : 'rollback';
439
+ case 'SAVEPOINT': return 'savepoint';
440
+ default: return 'release';
441
+ }
442
+ }
443
+
337
444
  //trust:validator_function
338
445
  export function parseStopResult(input: unknown) {
339
446
  const fields = fieldsOf(input);