@noego/sqlego 0.0.1 → 0.0.2
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 +50 -3
- package/bin/sqlego +2 -2
- package/dist/client.d.ts +51 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +125 -6
- package/dist/protocol.d.ts +74 -5
- package/package.json +1 -1
- package/src/cli.ts +5 -1
- package/src/client.ts +124 -0
- package/src/index.ts +4 -1
- package/src/protocol.ts +116 -9
- package/src/server.ts +378 -68
package/README.md
CHANGED
|
@@ -45,9 +45,40 @@ fresh one, so a rebuilt binary never keeps talking to an old owner.
|
|
|
45
45
|
|
|
46
46
|
Newline-delimited JSON, correlated by `id`. Ops: `hello`, `query` (rows),
|
|
47
47
|
`run` (changes), `batch` (all statements in one transaction, rolled back on
|
|
48
|
-
the first failure), `
|
|
49
|
-
|
|
50
|
-
|
|
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.
|
|
51
|
+
|
|
52
|
+
### Leased transactions
|
|
53
|
+
|
|
54
|
+
A client-held transaction holds the file's only writer, so it is never bare:
|
|
55
|
+
the server owns its lifetime and rolls it back the moment the client cannot be
|
|
56
|
+
trusted to.
|
|
57
|
+
|
|
58
|
+
- `begin { mode?: 'deferred' | 'immediate', leaseMs? }` → `{ txId, leaseMs, maxDurationMs }`.
|
|
59
|
+
The transaction is bound to the socket that opened it; one per connection.
|
|
60
|
+
- `query` / `run` carry `txId` to run inside it. Each such request renews the
|
|
61
|
+
lease. `SAVEPOINT` / `RELEASE` / `ROLLBACK TO` are plain SQL inside it.
|
|
62
|
+
- `commit { txId }` / `rollback { txId }` end it.
|
|
63
|
+
- Plain `query` / `run` / `batch` refuse `BEGIN`, `COMMIT`, `ROLLBACK`,
|
|
64
|
+
`SAVEPOINT` and `RELEASE` (`bad-request`): the server must always know
|
|
65
|
+
whether the file is inside a transaction.
|
|
66
|
+
|
|
67
|
+
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`
|
|
69
|
+
reports how many); `hello`, `status` and `stop` never wait. It is rolled back
|
|
70
|
+
by the server, and later requests for it fail with `tx-expired`, when:
|
|
71
|
+
|
|
72
|
+
| Trigger | Server flag | Default |
|
|
73
|
+
| --- | --- | --- |
|
|
74
|
+
| The owning socket closes | — | immediate |
|
|
75
|
+
| No request for it within the lease (`begin` may ask for less, never more) | `--tx-lease-ms` | 10 s |
|
|
76
|
+
| Open longer than the hard cap, renewed or not | `--tx-max-ms` | 60 s |
|
|
77
|
+
| SQLite itself aborted it (e.g. `SQLITE_FULL`) | — | immediate |
|
|
78
|
+
|
|
79
|
+
A waiting request from another client fails with `tx-busy` after
|
|
80
|
+
`--tx-queue-ms` (default 30 s) rather than hanging. The idle exit never fires
|
|
81
|
+
while a transaction is open.
|
|
51
82
|
|
|
52
83
|
## CLI
|
|
53
84
|
|
|
@@ -57,6 +88,7 @@ sqlego <file> "DELETE …"
|
|
|
57
88
|
sqlego <file> status | stop
|
|
58
89
|
sqlego <file> watch "SELECT count(*) FROM logs" --every 2s
|
|
59
90
|
sqlego ls
|
|
91
|
+
sqlego serve <file> [--idle-ms 30000] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-ms 30000]
|
|
60
92
|
```
|
|
61
93
|
|
|
62
94
|
## Library
|
|
@@ -67,9 +99,24 @@ const db = await SqlegoClient.connect('/path/to/logs.db');
|
|
|
67
99
|
await db.run('INSERT INTO logs (…) VALUES (?, ?)', [a, b]);
|
|
68
100
|
const rows = await db.query('SELECT … WHERE occurred_at_ms < ?', [cutoff]);
|
|
69
101
|
await db.batch([{ sql: 'DELETE … LIMIT 5000' }, { sql: 'PRAGMA incremental_vacuum(256)' }]);
|
|
102
|
+
|
|
103
|
+
// Reads-then-writes with application logic in between: a leased transaction.
|
|
104
|
+
const tx = await db.begin({ mode: 'immediate' });
|
|
105
|
+
const [{ balance }] = await tx.query<{ balance: number }>('SELECT balance FROM accounts WHERE id = ?', [id]);
|
|
106
|
+
await tx.savepoint('s1');
|
|
107
|
+
await tx.run('UPDATE accounts SET balance = ? WHERE id = ?', [balance - amount, id]);
|
|
108
|
+
await tx.release('s1'); // or tx.rollbackTo('s1')
|
|
109
|
+
await tx.commit(); // or tx.rollback()
|
|
110
|
+
|
|
111
|
+
// Or let the client commit on resolve and roll back on throw:
|
|
112
|
+
await db.transaction(async (tx) => { await tx.run('…'); });
|
|
70
113
|
await db.close();
|
|
71
114
|
```
|
|
72
115
|
|
|
116
|
+
A `SqlegoClientError` with code `tx-expired` means the server rolled the
|
|
117
|
+
transaction back (lease, hard cap, or disconnect); `tx-busy` means another
|
|
118
|
+
client's transaction kept the request waiting too long.
|
|
119
|
+
|
|
73
120
|
Server location: `SQLEGO_BIN`, else the compiled `bin/sqlego` next to the
|
|
74
121
|
package, else `sqlego` on `PATH`; pass `serverCommand` to override.
|
|
75
122
|
|
package/bin/sqlego
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
[diffend] Oversized file quarantined before diffing.
|
|
2
2
|
name: package/bin/sqlego
|
|
3
|
-
size:
|
|
4
|
-
sha256:
|
|
3
|
+
size: 62259954 bytes
|
|
4
|
+
sha256: 33ee2e96b2c3ff0fce805e1a09469118b13e8f6aa4f9e533826e75ff81e07bce
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type BatchResult, type HelloResult, type RunResult, type SqlParams, type SqlRow, type Statement, type StatusResult } from './protocol.ts';
|
|
1
|
+
import { type BatchResult, type BeginResult, type HelloResult, type RunResult, type SqlParams, type SqlRow, type Statement, 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
|
|
@@ -21,6 +21,15 @@ export type ClientOptions = Readonly<{
|
|
|
21
21
|
/** Per-request timeout. Default 60 000. */
|
|
22
22
|
requestTimeoutMs?: number;
|
|
23
23
|
}>;
|
|
24
|
+
export type BeginOptions = Readonly<{
|
|
25
|
+
/** `immediate` takes the write lock at `begin`; `deferred` (default) on the first write. */
|
|
26
|
+
mode?: TransactionMode;
|
|
27
|
+
/**
|
|
28
|
+
* Roll the transaction back when no request for it arrives within this
|
|
29
|
+
* long; each request renews it. The server caps it at its own lease.
|
|
30
|
+
*/
|
|
31
|
+
leaseMs?: number;
|
|
32
|
+
}>;
|
|
24
33
|
export declare class SqlegoClientError extends Error {
|
|
25
34
|
readonly code: string;
|
|
26
35
|
constructor(code: string, message: string);
|
|
@@ -42,6 +51,21 @@ export declare class SqlegoClient {
|
|
|
42
51
|
run(sql: string, params?: SqlParams): Promise<RunResult>;
|
|
43
52
|
/** One transaction; the whole batch rolls back on the first failure. */
|
|
44
53
|
batch(statements: readonly Statement[]): Promise<BatchResult['results']>;
|
|
54
|
+
/**
|
|
55
|
+
* Opens a transaction held across requests. It is bound to this connection
|
|
56
|
+
* and rolled back by the server if the connection drops, the lease runs out
|
|
57
|
+
* between requests, or the server's hard cap is reached; other clients'
|
|
58
|
+
* statements wait until it ends. End it with `commit` or `rollback`.
|
|
59
|
+
*/
|
|
60
|
+
begin(options?: BeginOptions): Promise<SqlegoTransaction>;
|
|
61
|
+
/** Runs `work` in a transaction: commits when it resolves, rolls back when it rejects (and rethrows). */
|
|
62
|
+
transaction<T>(work: (tx: SqlegoTransaction) => Promise<T>, options?: BeginOptions): Promise<T>;
|
|
63
|
+
/** @internal Statements inside a transaction; `SqlegoTransaction` is the public face. */
|
|
64
|
+
transactionQuery<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<Row[]>;
|
|
65
|
+
/** @internal */
|
|
66
|
+
transactionRun(txId: number, sql: string, params?: SqlParams): Promise<RunResult>;
|
|
67
|
+
/** @internal */
|
|
68
|
+
transactionEnd(txId: number, how: 'commit' | 'rollback'): Promise<void>;
|
|
45
69
|
status(): Promise<StatusResult>;
|
|
46
70
|
/** Asks the server to shut down; the connection closes as a consequence. */
|
|
47
71
|
stop(): Promise<void>;
|
|
@@ -67,6 +91,32 @@ export declare class SqlegoClient {
|
|
|
67
91
|
private settleAll;
|
|
68
92
|
private waitForExit;
|
|
69
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* One open transaction on a `SqlegoClient`. Every method rejects with a
|
|
96
|
+
* `SqlegoClientError` whose code is `tx-expired` once the server has rolled
|
|
97
|
+
* it back (lease, hard cap, disconnect) and `tx-invalid` after it ended.
|
|
98
|
+
*/
|
|
99
|
+
export declare class SqlegoTransaction {
|
|
100
|
+
readonly id: number;
|
|
101
|
+
/** The lease the server granted, which may be shorter than requested. */
|
|
102
|
+
readonly leaseMs: number;
|
|
103
|
+
/** The server's hard cap on this transaction's life. */
|
|
104
|
+
readonly maxDurationMs: number;
|
|
105
|
+
private readonly client;
|
|
106
|
+
private ended;
|
|
107
|
+
constructor(client: SqlegoClient, opened: BeginResult);
|
|
108
|
+
/** True once `commit` or `rollback` has been sent; the server may also have ended it on its own. */
|
|
109
|
+
get closed(): boolean;
|
|
110
|
+
query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]>;
|
|
111
|
+
run(sql: string, params?: SqlParams): Promise<RunResult>;
|
|
112
|
+
/** `SAVEPOINT name`: a nested scope that `rollbackTo` can undo and `release` folds into the transaction. */
|
|
113
|
+
savepoint(name: string): Promise<void>;
|
|
114
|
+
release(name: string): Promise<void>;
|
|
115
|
+
/** Undoes everything since the savepoint; the savepoint itself stays until released. */
|
|
116
|
+
rollbackTo(name: string): Promise<void>;
|
|
117
|
+
commit(): Promise<void>;
|
|
118
|
+
rollback(): Promise<void>;
|
|
119
|
+
}
|
|
70
120
|
/**
|
|
71
121
|
* How to start a server: SQLEGO_BIN if set; the compiled `sqlego` binary when
|
|
72
122
|
* running as one; the dev entry (`bun src/cli.ts`) when running from source
|
package/dist/index.d.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
|
-
export { PROTOCOL_VERSION, type SqlParams, type SqlRow, type SqlValue, type Statement, type RunResult, type QueryResult, type BatchResult, type StatusResult, type HelloResult, } from './protocol.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';
|
|
4
4
|
export { VERSION } from './version.ts';
|
package/dist/index.js
CHANGED
|
@@ -47,7 +47,7 @@ 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 =
|
|
50
|
+
var PROTOCOL_VERSION = 2;
|
|
51
51
|
function toJson(value, indent) {
|
|
52
52
|
const encoded = Trust.try(() => JSON.stringify(value, replaceBigInt, indent), (cause) => ({ kind: "encode-failed", message: errorMessage(cause) }));
|
|
53
53
|
if (!encoded.ok)
|
|
@@ -70,7 +70,16 @@ var invalid = (message) => Result.err({ kind: "invalid", message });
|
|
|
70
70
|
function fieldsOf(input) {
|
|
71
71
|
return typeof input === "object" && input !== null && !Array.isArray(input) ? input : null;
|
|
72
72
|
}
|
|
73
|
-
var ERROR_CODES = [
|
|
73
|
+
var ERROR_CODES = [
|
|
74
|
+
"sqlite",
|
|
75
|
+
"bad-request",
|
|
76
|
+
"protocol-mismatch",
|
|
77
|
+
"shutting-down",
|
|
78
|
+
"encode-failed",
|
|
79
|
+
"tx-expired",
|
|
80
|
+
"tx-invalid",
|
|
81
|
+
"tx-busy"
|
|
82
|
+
];
|
|
74
83
|
function parseErrorCode(input) {
|
|
75
84
|
const code = ERROR_CODES.find((known) => known === input);
|
|
76
85
|
return code === undefined ? invalid(`unknown error code ${String(input)}`) : Result.ok(code);
|
|
@@ -159,11 +168,46 @@ function parseHelloResult(input) {
|
|
|
159
168
|
const result = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid };
|
|
160
169
|
return Result.ok(result);
|
|
161
170
|
}
|
|
171
|
+
function parseBeginResult(input) {
|
|
172
|
+
const f = fieldsOf(input);
|
|
173
|
+
if (!f || typeof f.txId !== "number" || typeof f.leaseMs !== "number" || typeof f.maxDurationMs !== "number") {
|
|
174
|
+
return invalid("a begin result needs txId, leaseMs and maxDurationMs (numbers)");
|
|
175
|
+
}
|
|
176
|
+
const result = { txId: f.txId, leaseMs: f.leaseMs, maxDurationMs: f.maxDurationMs };
|
|
177
|
+
return Result.ok(result);
|
|
178
|
+
}
|
|
179
|
+
function parseTransactionEndResult(input) {
|
|
180
|
+
const f = fieldsOf(input);
|
|
181
|
+
if (!f || typeof f.txId !== "number")
|
|
182
|
+
return invalid("a commit/rollback result needs txId (number)");
|
|
183
|
+
const result = { txId: f.txId };
|
|
184
|
+
return Result.ok(result);
|
|
185
|
+
}
|
|
186
|
+
function parseTransactionStatus(input) {
|
|
187
|
+
if (input === null)
|
|
188
|
+
return Result.ok(null);
|
|
189
|
+
const f = fieldsOf(input);
|
|
190
|
+
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") {
|
|
191
|
+
return invalid("status.transaction must be null or carry txId, ageMs, idleMs, leaseMs, maxDurationMs and queued");
|
|
192
|
+
}
|
|
193
|
+
const status = {
|
|
194
|
+
txId: f.txId,
|
|
195
|
+
ageMs: f.ageMs,
|
|
196
|
+
idleMs: f.idleMs,
|
|
197
|
+
leaseMs: f.leaseMs,
|
|
198
|
+
maxDurationMs: f.maxDurationMs,
|
|
199
|
+
queued: f.queued
|
|
200
|
+
};
|
|
201
|
+
return Result.ok(status);
|
|
202
|
+
}
|
|
162
203
|
function parseStatusResult(input) {
|
|
163
204
|
const f = fieldsOf(input);
|
|
164
205
|
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
206
|
return invalid("a status result is missing a field or has one of the wrong type");
|
|
166
207
|
}
|
|
208
|
+
const transaction = parseTransactionStatus(f.transaction);
|
|
209
|
+
if (!transaction.ok)
|
|
210
|
+
return transaction;
|
|
167
211
|
const result = {
|
|
168
212
|
file: f.file,
|
|
169
213
|
socket: f.socket,
|
|
@@ -174,7 +218,8 @@ function parseStatusResult(input) {
|
|
|
174
218
|
uptimeMs: f.uptimeMs,
|
|
175
219
|
idleMs: f.idleMs,
|
|
176
220
|
idleTimeoutMs: f.idleTimeoutMs,
|
|
177
|
-
requestsServed: f.requestsServed
|
|
221
|
+
requestsServed: f.requestsServed,
|
|
222
|
+
transaction: transaction.value
|
|
178
223
|
};
|
|
179
224
|
return Result.ok(result);
|
|
180
225
|
}
|
|
@@ -299,7 +344,7 @@ import { fileURLToPath } from "node:url";
|
|
|
299
344
|
// package.json
|
|
300
345
|
var package_default = {
|
|
301
346
|
name: "@noego/sqlego",
|
|
302
|
-
version: "0.0.
|
|
347
|
+
version: "0.0.2",
|
|
303
348
|
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
349
|
type: "module",
|
|
305
350
|
license: "ISC",
|
|
@@ -357,8 +402,8 @@ function sourceBuildId(sourceDirectory) {
|
|
|
357
402
|
}, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
|
|
358
403
|
}
|
|
359
404
|
function resolveBuildId() {
|
|
360
|
-
if ("
|
|
361
|
-
return "
|
|
405
|
+
if ("3acec59ea032".length > 0)
|
|
406
|
+
return "3acec59ea032";
|
|
362
407
|
const directory = Trust.try(() => path2.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
|
|
363
408
|
if (!directory.ok)
|
|
364
409
|
return decideUnknownBuild(directory.error.kind);
|
|
@@ -383,6 +428,8 @@ var BUILD_ID = resolveBuildId();
|
|
|
383
428
|
var VERSION = process.env.SQLEGO_VERSION_OVERRIDE || `${package_default.version}+${BUILD_ID}`;
|
|
384
429
|
|
|
385
430
|
// src/client.ts
|
|
431
|
+
var SAVEPOINT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
432
|
+
|
|
386
433
|
class SqlegoClientError extends Error {
|
|
387
434
|
code;
|
|
388
435
|
constructor(code, message) {
|
|
@@ -438,6 +485,32 @@ class SqlegoClient {
|
|
|
438
485
|
const result = unwrap(await this.call({ op: "batch", statements }, parseBatchResult));
|
|
439
486
|
return result.results;
|
|
440
487
|
}
|
|
488
|
+
async begin(options = {}) {
|
|
489
|
+
const opened = unwrap(await this.call({ op: "begin", mode: options.mode, leaseMs: options.leaseMs }, parseBeginResult));
|
|
490
|
+
return new SqlegoTransaction(this, opened);
|
|
491
|
+
}
|
|
492
|
+
async transaction(work, options = {}) {
|
|
493
|
+
const tx = await this.begin(options);
|
|
494
|
+
const outcome = await Trust.tryAsync(() => work(tx), (cause) => ({ kind: "work-failed", cause }));
|
|
495
|
+
if (outcome.ok) {
|
|
496
|
+
await tx.commit();
|
|
497
|
+
return outcome.value;
|
|
498
|
+
}
|
|
499
|
+
await tx.rollback().catch(() => {
|
|
500
|
+
return;
|
|
501
|
+
});
|
|
502
|
+
throw outcome.error.cause;
|
|
503
|
+
}
|
|
504
|
+
async transactionQuery(txId, sql, params) {
|
|
505
|
+
const result = unwrap(await this.call({ op: "query", sql, params, txId }, parseQueryResult));
|
|
506
|
+
return callerRows(result.rows);
|
|
507
|
+
}
|
|
508
|
+
async transactionRun(txId, sql, params) {
|
|
509
|
+
return unwrap(await this.call({ op: "run", sql, params, txId }, parseRunResult));
|
|
510
|
+
}
|
|
511
|
+
async transactionEnd(txId, how) {
|
|
512
|
+
unwrap(await this.call({ op: how, txId }, parseTransactionEndResult));
|
|
513
|
+
}
|
|
441
514
|
async status() {
|
|
442
515
|
return unwrap(await this.call({ op: "status" }, parseStatusResult));
|
|
443
516
|
}
|
|
@@ -666,6 +739,51 @@ class SqlegoClient {
|
|
|
666
739
|
await sleep(25);
|
|
667
740
|
}
|
|
668
741
|
}
|
|
742
|
+
|
|
743
|
+
class SqlegoTransaction {
|
|
744
|
+
id;
|
|
745
|
+
leaseMs;
|
|
746
|
+
maxDurationMs;
|
|
747
|
+
client;
|
|
748
|
+
ended = false;
|
|
749
|
+
constructor(client, opened) {
|
|
750
|
+
this.client = client;
|
|
751
|
+
this.id = opened.txId;
|
|
752
|
+
this.leaseMs = opened.leaseMs;
|
|
753
|
+
this.maxDurationMs = opened.maxDurationMs;
|
|
754
|
+
}
|
|
755
|
+
get closed() {
|
|
756
|
+
return this.ended;
|
|
757
|
+
}
|
|
758
|
+
query(sql, params) {
|
|
759
|
+
return this.client.transactionQuery(this.id, sql, params);
|
|
760
|
+
}
|
|
761
|
+
run(sql, params) {
|
|
762
|
+
return this.client.transactionRun(this.id, sql, params);
|
|
763
|
+
}
|
|
764
|
+
async savepoint(name) {
|
|
765
|
+
await this.run(`SAVEPOINT ${savepointName(name)}`);
|
|
766
|
+
}
|
|
767
|
+
async release(name) {
|
|
768
|
+
await this.run(`RELEASE SAVEPOINT ${savepointName(name)}`);
|
|
769
|
+
}
|
|
770
|
+
async rollbackTo(name) {
|
|
771
|
+
await this.run(`ROLLBACK TO SAVEPOINT ${savepointName(name)}`);
|
|
772
|
+
}
|
|
773
|
+
async commit() {
|
|
774
|
+
this.ended = true;
|
|
775
|
+
await this.client.transactionEnd(this.id, "commit");
|
|
776
|
+
}
|
|
777
|
+
async rollback() {
|
|
778
|
+
this.ended = true;
|
|
779
|
+
await this.client.transactionEnd(this.id, "rollback");
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
function savepointName(name) {
|
|
783
|
+
if (SAVEPOINT_NAME.test(name))
|
|
784
|
+
return name;
|
|
785
|
+
return unwrap(Result.err({ kind: "bad-request", message: `savepoint name must be an identifier (letters, digits, _), not "${name}"` }));
|
|
786
|
+
}
|
|
669
787
|
function defaultServerCommand() {
|
|
670
788
|
const configured = process.env.SQLEGO_BIN;
|
|
671
789
|
if (configured && configured.length > 0)
|
|
@@ -743,6 +861,7 @@ export {
|
|
|
743
861
|
PROTOCOL_VERSION,
|
|
744
862
|
SqlegoClient,
|
|
745
863
|
SqlegoClientError,
|
|
864
|
+
SqlegoTransaction,
|
|
746
865
|
VERSION,
|
|
747
866
|
canonicalFile,
|
|
748
867
|
defaultServerCommand,
|
package/dist/protocol.d.ts
CHANGED
|
@@ -6,12 +6,16 @@
|
|
|
6
6
|
* two clients' statements interleave at statement (or batch) granularity and
|
|
7
7
|
* never contend for SQLite's write lock.
|
|
8
8
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
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
|
import { Result } from '@noego/trust';
|
|
14
|
-
export declare const PROTOCOL_VERSION =
|
|
18
|
+
export declare const PROTOCOL_VERSION = 2;
|
|
15
19
|
export type SqlParams = ReadonlyArray<SqlValue> | Readonly<Record<string, SqlValue>>;
|
|
16
20
|
export type SqlValue = string | number | bigint | boolean | null | Uint8Array;
|
|
17
21
|
export type SqlRow = Record<string, unknown>;
|
|
@@ -21,6 +25,7 @@ export type Statement = Readonly<{
|
|
|
21
25
|
/** `query` returns rows; `run` returns the change count. Default `run`. */
|
|
22
26
|
mode?: 'query' | 'run';
|
|
23
27
|
}>;
|
|
28
|
+
export type TransactionMode = 'deferred' | 'immediate';
|
|
24
29
|
export type Request = {
|
|
25
30
|
id: number;
|
|
26
31
|
op: 'hello';
|
|
@@ -31,15 +36,30 @@ export type Request = {
|
|
|
31
36
|
op: 'query';
|
|
32
37
|
sql: string;
|
|
33
38
|
params?: SqlParams;
|
|
39
|
+
txId?: number;
|
|
34
40
|
} | {
|
|
35
41
|
id: number;
|
|
36
42
|
op: 'run';
|
|
37
43
|
sql: string;
|
|
38
44
|
params?: SqlParams;
|
|
45
|
+
txId?: number;
|
|
39
46
|
} | {
|
|
40
47
|
id: number;
|
|
41
48
|
op: 'batch';
|
|
42
49
|
statements: readonly Statement[];
|
|
50
|
+
} | {
|
|
51
|
+
id: number;
|
|
52
|
+
op: 'begin';
|
|
53
|
+
mode?: TransactionMode;
|
|
54
|
+
leaseMs?: number;
|
|
55
|
+
} | {
|
|
56
|
+
id: number;
|
|
57
|
+
op: 'commit';
|
|
58
|
+
txId: number;
|
|
59
|
+
} | {
|
|
60
|
+
id: number;
|
|
61
|
+
op: 'rollback';
|
|
62
|
+
txId: number;
|
|
43
63
|
} | {
|
|
44
64
|
id: number;
|
|
45
65
|
op: 'status';
|
|
@@ -57,6 +77,27 @@ export type QueryResult = Readonly<{
|
|
|
57
77
|
export type BatchResult = Readonly<{
|
|
58
78
|
results: ReadonlyArray<RunResult | QueryResult>;
|
|
59
79
|
}>;
|
|
80
|
+
/** The lease the server granted (its own cap applies) and the hard cap on the transaction's life. */
|
|
81
|
+
export type BeginResult = Readonly<{
|
|
82
|
+
txId: number;
|
|
83
|
+
leaseMs: number;
|
|
84
|
+
maxDurationMs: number;
|
|
85
|
+
}>;
|
|
86
|
+
export type TransactionEndResult = Readonly<{
|
|
87
|
+
txId: number;
|
|
88
|
+
}>;
|
|
89
|
+
/** The open transaction as `status` reports it. */
|
|
90
|
+
export type TransactionStatus = Readonly<{
|
|
91
|
+
txId: number;
|
|
92
|
+
/** How long it has been open. */
|
|
93
|
+
ageMs: number;
|
|
94
|
+
/** Since its last request. */
|
|
95
|
+
idleMs: number;
|
|
96
|
+
leaseMs: number;
|
|
97
|
+
maxDurationMs: number;
|
|
98
|
+
/** Requests from other clients waiting for it to end. */
|
|
99
|
+
queued: number;
|
|
100
|
+
}>;
|
|
60
101
|
export type HelloResult = Readonly<{
|
|
61
102
|
serverVersion: string;
|
|
62
103
|
protocol: number;
|
|
@@ -74,10 +115,17 @@ export type StatusResult = Readonly<{
|
|
|
74
115
|
idleMs: number | null;
|
|
75
116
|
idleTimeoutMs: number;
|
|
76
117
|
requestsServed: number;
|
|
118
|
+
transaction: TransactionStatus | null;
|
|
77
119
|
}>;
|
|
78
120
|
export type ErrorCode = 'sqlite' | 'bad-request' | 'protocol-mismatch' | 'shutting-down'
|
|
79
121
|
/** The server could not serialize a result (a value JSON cannot hold). */
|
|
80
|
-
| 'encode-failed'
|
|
122
|
+
| 'encode-failed'
|
|
123
|
+
/** The transaction was rolled back by the server: lease ran out, hard cap hit, or SQLite aborted it. */
|
|
124
|
+
| 'tx-expired'
|
|
125
|
+
/** No such open transaction on this connection (wrong id, already ended, or a second `begin`). */
|
|
126
|
+
| 'tx-invalid'
|
|
127
|
+
/** Another client's transaction kept the request waiting past the server's queue limit. */
|
|
128
|
+
| 'tx-busy';
|
|
81
129
|
export type Response = {
|
|
82
130
|
id: number;
|
|
83
131
|
ok: true;
|
|
@@ -180,6 +228,20 @@ export declare function parseHelloResult(input: unknown): import("@noego/trust")
|
|
|
180
228
|
file: string;
|
|
181
229
|
pid: number;
|
|
182
230
|
}>>;
|
|
231
|
+
export declare function parseBeginResult(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
232
|
+
kind: "invalid";
|
|
233
|
+
message: string;
|
|
234
|
+
}>> | import("@noego/trust").Ok<Readonly<{
|
|
235
|
+
txId: number;
|
|
236
|
+
leaseMs: number;
|
|
237
|
+
maxDurationMs: number;
|
|
238
|
+
}>>;
|
|
239
|
+
export declare function parseTransactionEndResult(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
240
|
+
kind: "invalid";
|
|
241
|
+
message: string;
|
|
242
|
+
}>> | import("@noego/trust").Ok<Readonly<{
|
|
243
|
+
txId: number;
|
|
244
|
+
}>>;
|
|
183
245
|
export declare function parseStatusResult(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
184
246
|
kind: "invalid";
|
|
185
247
|
message: string;
|
|
@@ -194,7 +256,14 @@ export declare function parseStatusResult(input: unknown): import("@noego/trust"
|
|
|
194
256
|
idleMs: number | null;
|
|
195
257
|
idleTimeoutMs: number;
|
|
196
258
|
requestsServed: number;
|
|
259
|
+
transaction: TransactionStatus | null;
|
|
197
260
|
}>>;
|
|
261
|
+
/**
|
|
262
|
+
* The transaction-control statement a SQL text starts with, or null. Leading
|
|
263
|
+
* whitespace and comments are skipped so `/* x *\/ BEGIN` is still seen.
|
|
264
|
+
* `ROLLBACK TO` (a savepoint) is told apart from a bare `ROLLBACK`.
|
|
265
|
+
*/
|
|
266
|
+
export declare function transactionControl(sql: string): 'begin' | 'commit' | 'rollback' | 'savepoint' | 'release' | 'rollback-to' | null;
|
|
198
267
|
export declare function parseStopResult(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
199
268
|
kind: "invalid";
|
|
200
269
|
message: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noego/sqlego",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.2",
|
|
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;
|