@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.
@@ -6,21 +6,46 @@
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.
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).
12
22
  */
13
23
  import { Result } from '@noego/trust';
14
- export declare const PROTOCOL_VERSION = 1;
24
+ export declare const PROTOCOL_VERSION = 3;
15
25
  export type SqlParams = ReadonlyArray<SqlValue> | Readonly<Record<string, SqlValue>>;
16
26
  export type SqlValue = string | number | bigint | boolean | null | Uint8Array;
17
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;
18
42
  export type Statement = Readonly<{
19
43
  sql: string;
20
44
  params?: SqlParams;
21
45
  /** `query` returns rows; `run` returns the change count. Default `run`. */
22
46
  mode?: 'query' | 'run';
23
47
  }>;
48
+ export type TransactionMode = 'deferred' | 'immediate';
24
49
  export type Request = {
25
50
  id: number;
26
51
  op: 'hello';
@@ -31,15 +56,45 @@ export type Request = {
31
56
  op: 'query';
32
57
  sql: string;
33
58
  params?: SqlParams;
59
+ txId?: number;
34
60
  } | {
35
61
  id: number;
36
62
  op: 'run';
37
63
  sql: string;
38
64
  params?: SqlParams;
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;
39
81
  } | {
40
82
  id: number;
41
83
  op: 'batch';
42
84
  statements: readonly Statement[];
85
+ } | {
86
+ id: number;
87
+ op: 'begin';
88
+ mode?: TransactionMode;
89
+ leaseMs?: number;
90
+ } | {
91
+ id: number;
92
+ op: 'commit';
93
+ txId: number;
94
+ } | {
95
+ id: number;
96
+ op: 'rollback';
97
+ txId: number;
43
98
  } | {
44
99
  id: number;
45
100
  op: 'status';
@@ -57,6 +112,56 @@ export type QueryResult = Readonly<{
57
112
  export type BatchResult = Readonly<{
58
113
  results: ReadonlyArray<RunResult | QueryResult>;
59
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
+ }>;
144
+ /** The lease the server granted (its own cap applies) and the hard cap on the transaction's life. */
145
+ export type BeginResult = Readonly<{
146
+ txId: number;
147
+ leaseMs: number;
148
+ maxDurationMs: number;
149
+ }>;
150
+ export type TransactionEndResult = Readonly<{
151
+ txId: number;
152
+ }>;
153
+ /** The open transaction as `status` reports it. */
154
+ export type TransactionStatus = Readonly<{
155
+ txId: number;
156
+ /** How long it has been open. */
157
+ ageMs: number;
158
+ /** Since its last request. */
159
+ idleMs: number;
160
+ leaseMs: number;
161
+ maxDurationMs: number;
162
+ /** Requests from other clients waiting for it to end. */
163
+ queued: number;
164
+ }>;
60
165
  export type HelloResult = Readonly<{
61
166
  serverVersion: string;
62
167
  protocol: number;
@@ -74,10 +179,17 @@ export type StatusResult = Readonly<{
74
179
  idleMs: number | null;
75
180
  idleTimeoutMs: number;
76
181
  requestsServed: number;
182
+ transaction: TransactionStatus | null;
77
183
  }>;
78
184
  export type ErrorCode = 'sqlite' | 'bad-request' | 'protocol-mismatch' | 'shutting-down'
79
185
  /** The server could not serialize a result (a value JSON cannot hold). */
80
- | 'encode-failed';
186
+ | 'encode-failed'
187
+ /** The transaction was rolled back by the server: lease ran out, hard cap hit, or SQLite aborted it. */
188
+ | 'tx-expired'
189
+ /** No such open transaction on this connection (wrong id, already ended, or a second `begin`). */
190
+ | 'tx-invalid'
191
+ /** Another client's transaction kept the request waiting past the server's queue limit. */
192
+ | 'tx-busy';
81
193
  export type Response = {
82
194
  id: number;
83
195
  ok: true;
@@ -104,16 +216,56 @@ export declare function encodeFrame(message: Request | Response): import("@noego
104
216
  kind: "encode-failed";
105
217
  message: string;
106
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[]>;
107
256
  /** Parses JSON text into `unknown`; what it holds is for a validator to decide. */
108
257
  export declare function fromJson(text: string): Result<unknown, {
109
258
  kind: "invalid";
110
259
  message: string;
111
260
  }>;
112
- /** A value that survives JSON and SQLite binding: string, number, boolean or null. */
113
- 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<{
114
266
  kind: "invalid";
115
267
  message: string;
116
- }>>;
268
+ }>> | import("@noego/trust").Ok<SqlValue>;
117
269
  /** Positional (`[...]`) or named (`{ name: value }`) parameters. */
118
270
  export declare function parseSqlParams(input: unknown): import("@noego/trust").Err<Readonly<{
119
271
  kind: "invalid";
@@ -171,6 +323,23 @@ export declare function parseBatchResult(input: unknown): import("@noego/trust")
171
323
  }>> | import("@noego/trust").Ok<Readonly<{
172
324
  results: ReadonlyArray<RunResult | QueryResult>;
173
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
+ }>>;
174
343
  export declare function parseHelloResult(input: unknown): import("@noego/trust").Err<Readonly<{
175
344
  kind: "invalid";
176
345
  message: string;
@@ -180,6 +349,20 @@ export declare function parseHelloResult(input: unknown): import("@noego/trust")
180
349
  file: string;
181
350
  pid: number;
182
351
  }>>;
352
+ export declare function parseBeginResult(input: unknown): import("@noego/trust").Err<Readonly<{
353
+ kind: "invalid";
354
+ message: string;
355
+ }>> | import("@noego/trust").Ok<Readonly<{
356
+ txId: number;
357
+ leaseMs: number;
358
+ maxDurationMs: number;
359
+ }>>;
360
+ export declare function parseTransactionEndResult(input: unknown): import("@noego/trust").Err<Readonly<{
361
+ kind: "invalid";
362
+ message: string;
363
+ }>> | import("@noego/trust").Ok<Readonly<{
364
+ txId: number;
365
+ }>>;
183
366
  export declare function parseStatusResult(input: unknown): import("@noego/trust").Err<Readonly<{
184
367
  kind: "invalid";
185
368
  message: string;
@@ -194,7 +377,21 @@ export declare function parseStatusResult(input: unknown): import("@noego/trust"
194
377
  idleMs: number | null;
195
378
  idleTimeoutMs: number;
196
379
  requestsServed: number;
380
+ transaction: TransactionStatus | null;
197
381
  }>>;
382
+ /**
383
+ * The transaction-control statement a SQL text starts with, or null. Leading
384
+ * whitespace and comments are skipped so `/* x *\/ BEGIN` is still seen.
385
+ * `ROLLBACK TO` (a savepoint) is told apart from a bare `ROLLBACK`.
386
+ */
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[];
198
395
  export declare function parseStopResult(input: unknown): import("@noego/trust").Err<Readonly<{
199
396
  kind: "invalid";
200
397
  message: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noego/sqlego",
3
- "version": "0.0.1",
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",
package/src/cli.ts CHANGED
@@ -63,7 +63,7 @@ function usage(): Outcome {
63
63
  sqlego <file> status | stop
64
64
  sqlego <file> watch "<sql>" [--every 1s]
65
65
  sqlego ls
66
- sqlego serve <file> [--idle-ms 30000] [--pragma "<name = value>"]...
66
+ sqlego serve <file> [--idle-ms 30000] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-ms 30000] [--pragma "<name = value>"]...
67
67
  `);
68
68
  return exit(2);
69
69
  }
@@ -126,10 +126,14 @@ async function serve(file: string, flags: Flags, pragmas: readonly string[]) {
126
126
  if (!loaded.ok) return loaded;
127
127
  const { SqlegoServer, DEFAULT_PRAGMAS } = loaded.value;
128
128
  const idleTimeoutMs = flags['idle-ms'] ? Number(flags['idle-ms']) : 30_000;
129
+ const millis = (flag: string) => (typeof flags[flag] === 'string' ? Number(flags[flag]) : undefined);
129
130
  const opened = SqlegoServer.open({
130
131
  file,
131
132
  idleTimeoutMs,
132
133
  pragmas: pragmas.length > 0 ? pragmas : DEFAULT_PRAGMAS,
134
+ txLeaseMs: millis('tx-lease-ms'),
135
+ txMaxDurationMs: millis('tx-max-ms'),
136
+ txQueueTimeoutMs: millis('tx-queue-ms'),
133
137
  log: flags.verbose ? (message, fields) => err(`[sqlego] ${message} ${displayJson(fields ?? {})}\n`) : undefined,
134
138
  });
135
139
  if (!opened.ok) return opened;
package/src/client.ts CHANGED
@@ -6,27 +6,35 @@ import { fileURLToPath } from 'node:url';
6
6
  import { Result, Trust } from '@noego/trust';
7
7
  import {
8
8
  PROTOCOL_VERSION,
9
- encodeFrame,
9
+ encodeRequestFrame,
10
10
  errnoCode,
11
11
  errorMessage,
12
12
  fromJson,
13
13
  parseBatchResult,
14
+ parseBeginResult,
15
+ parseExecResult,
14
16
  parseHelloResult,
15
17
  parseQueryResult,
16
18
  parseResponse,
17
19
  parseRunResult,
20
+ parseStatementResult,
18
21
  parseStatusResult,
19
22
  parseStopResult,
23
+ parseTransactionEndResult,
20
24
  splitFrames,
21
25
  type BatchResult,
26
+ type BeginResult,
22
27
  type ErrorCode,
28
+ type ExecResult,
23
29
  type HelloResult,
24
30
  type Request,
25
31
  type RunResult,
26
32
  type SqlParams,
27
33
  type SqlRow,
28
34
  type Statement,
35
+ type StatementResult,
29
36
  type StatusResult,
37
+ type TransactionMode,
30
38
  } from './protocol.ts';
31
39
  import { isProcessAlive, resolvePaths, type FilePaths } from './paths.ts';
32
40
  import { VERSION } from './version.ts';
@@ -53,6 +61,19 @@ export type ClientOptions = Readonly<{
53
61
  requestTimeoutMs?: number;
54
62
  }>;
55
63
 
64
+ export type BeginOptions = Readonly<{
65
+ /** `immediate` takes the write lock at `begin`; `deferred` (default) on the first write. */
66
+ mode?: TransactionMode;
67
+ /**
68
+ * Roll the transaction back when no request for it arrives within this
69
+ * long; each request renews it. The server caps it at its own lease.
70
+ */
71
+ leaseMs?: number;
72
+ }>;
73
+
74
+ /** A savepoint name is spliced into SQL text, so it must be a bare identifier. */
75
+ const SAVEPOINT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
76
+
56
77
  // No TypeScript parameter properties anywhere in the client: Node's
57
78
  // strip-only type loading (`--experimental-strip-types`) rejects them, and the
58
79
  // client must load in plain Node without a build step.
@@ -105,6 +126,11 @@ function callerRows<Row extends SqlRow>(rows: SqlRow[]): Row[] {
105
126
  return rows as Row[];
106
127
  }
107
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
+
108
134
  export class SqlegoClient {
109
135
  readonly paths: FilePaths;
110
136
  private socket: net.Socket | null = null;
@@ -146,12 +172,85 @@ export class SqlegoClient {
146
172
  return unwrap(await this.call({ op: 'run', sql, params }, parseRunResult));
147
173
  }
148
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
+
149
196
  /** One transaction; the whole batch rolls back on the first failure. */
150
197
  async batch(statements: readonly Statement[]): Promise<BatchResult['results']> {
151
198
  const result = unwrap(await this.call({ op: 'batch', statements }, parseBatchResult));
152
199
  return result.results;
153
200
  }
154
201
 
202
+ /**
203
+ * Opens a transaction held across requests. It is bound to this connection
204
+ * and rolled back by the server if the connection drops, the lease runs out
205
+ * between requests, or the server's hard cap is reached; other clients'
206
+ * statements wait until it ends. End it with `commit` or `rollback`.
207
+ */
208
+ async begin(options: BeginOptions = {}): Promise<SqlegoTransaction> {
209
+ const opened = unwrap(await this.call({ op: 'begin', mode: options.mode, leaseMs: options.leaseMs }, parseBeginResult));
210
+ return new SqlegoTransaction(this, opened);
211
+ }
212
+
213
+ /** Runs `work` in a transaction: commits when it resolves, rolls back when it rejects (and rethrows). */
214
+ async transaction<T>(work: (tx: SqlegoTransaction) => Promise<T>, options: BeginOptions = {}): Promise<T> {
215
+ const tx = await this.begin(options);
216
+ const outcome = await Trust.tryAsync(() => work(tx), (cause) => ({ kind: 'work-failed' as const, cause }));
217
+ if (outcome.ok) {
218
+ await tx.commit();
219
+ return outcome.value;
220
+ }
221
+ // The work's own error is what the caller must see; a rollback that
222
+ // fails (the server already rolled back an expired transaction) adds nothing.
223
+ await tx.rollback().catch(() => undefined);
224
+ //trust:accept public API contract: transaction(work) rethrows the work's own rejection after rolling back
225
+ throw outcome.error.cause;
226
+ }
227
+
228
+ /** @internal Statements inside a transaction; `SqlegoTransaction` is the public face. */
229
+ async transactionQuery<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<Row[]> {
230
+ const result = unwrap(await this.call({ op: 'query', sql, params, txId }, parseQueryResult));
231
+ return callerRows<Row>(result.rows);
232
+ }
233
+
234
+ /** @internal */
235
+ async transactionRun(txId: number, sql: string, params?: SqlParams): Promise<RunResult> {
236
+ return unwrap(await this.call({ op: 'run', sql, params, txId }, parseRunResult));
237
+ }
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
+
249
+ /** @internal */
250
+ async transactionEnd(txId: number, how: 'commit' | 'rollback'): Promise<void> {
251
+ unwrap(await this.call({ op: how, txId }, parseTransactionEndResult));
252
+ }
253
+
155
254
  async status(): Promise<StatusResult> {
156
255
  return unwrap(await this.call({ op: 'status' }, parseStatusResult));
157
256
  }
@@ -381,7 +480,7 @@ export class SqlegoClient {
381
480
  return Promise.resolve(Result.err({ kind: 'not-connected', message: 'client is not connected' }));
382
481
  }
383
482
  const id = this.nextId++;
384
- const frame = encodeFrame({ id, ...body } as Request);
483
+ const frame = encodeRequestFrame({ id, ...body } as Request);
385
484
  if (!frame.ok) return Promise.resolve(frame);
386
485
  return new Promise<Result<unknown, RequestFailure>>((settle) => {
387
486
  const timer = setTimeout(() => {
@@ -414,6 +513,81 @@ export class SqlegoClient {
414
513
  }
415
514
  }
416
515
 
516
+ /**
517
+ * One open transaction on a `SqlegoClient`. Every method rejects with a
518
+ * `SqlegoClientError` whose code is `tx-expired` once the server has rolled
519
+ * it back (lease, hard cap, disconnect) and `tx-invalid` after it ended.
520
+ */
521
+ export class SqlegoTransaction {
522
+ readonly id: number;
523
+ /** The lease the server granted, which may be shorter than requested. */
524
+ readonly leaseMs: number;
525
+ /** The server's hard cap on this transaction's life. */
526
+ readonly maxDurationMs: number;
527
+ private readonly client: SqlegoClient;
528
+ private ended = false;
529
+
530
+ constructor(client: SqlegoClient, opened: BeginResult) {
531
+ this.client = client;
532
+ this.id = opened.txId;
533
+ this.leaseMs = opened.leaseMs;
534
+ this.maxDurationMs = opened.maxDurationMs;
535
+ }
536
+
537
+ /** True once `commit` or `rollback` has been sent; the server may also have ended it on its own. */
538
+ get closed(): boolean {
539
+ return this.ended;
540
+ }
541
+
542
+ query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]> {
543
+ return this.client.transactionQuery<Row>(this.id, sql, params);
544
+ }
545
+
546
+ run(sql: string, params?: SqlParams): Promise<RunResult> {
547
+ return this.client.transactionRun(this.id, sql, params);
548
+ }
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
+
560
+ /** `SAVEPOINT name`: a nested scope that `rollbackTo` can undo and `release` folds into the transaction. */
561
+ async savepoint(name: string): Promise<void> {
562
+ await this.run(`SAVEPOINT ${savepointName(name)}`);
563
+ }
564
+
565
+ async release(name: string): Promise<void> {
566
+ await this.run(`RELEASE SAVEPOINT ${savepointName(name)}`);
567
+ }
568
+
569
+ /** Undoes everything since the savepoint; the savepoint itself stays until released. */
570
+ async rollbackTo(name: string): Promise<void> {
571
+ await this.run(`ROLLBACK TO SAVEPOINT ${savepointName(name)}`);
572
+ }
573
+
574
+ async commit(): Promise<void> {
575
+ this.ended = true;
576
+ await this.client.transactionEnd(this.id, 'commit');
577
+ }
578
+
579
+ async rollback(): Promise<void> {
580
+ this.ended = true;
581
+ await this.client.transactionEnd(this.id, 'rollback');
582
+ }
583
+ }
584
+
585
+ /** A savepoint name is spliced into SQL, so only an identifier is accepted. */
586
+ function savepointName(name: string): string {
587
+ if (SAVEPOINT_NAME.test(name)) return name;
588
+ return unwrap(Result.err({ kind: 'bad-request', message: `savepoint name must be an identifier (letters, digits, _), not "${name}"` }));
589
+ }
590
+
417
591
  /**
418
592
  * How to start a server: SQLEGO_BIN if set; the compiled `sqlego` binary when
419
593
  * 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,12 @@ export {
9
9
  type RunResult,
10
10
  type QueryResult,
11
11
  type BatchResult,
12
+ type StatementResult,
13
+ type ExecResult,
14
+ type BeginResult,
12
15
  type StatusResult,
13
16
  type HelloResult,
17
+ type TransactionMode,
18
+ type TransactionStatus,
14
19
  } from './protocol.ts';
15
20
  export { VERSION } from './version.ts';