@noego/sqlego 0.1.2-dev.2 → 0.1.2-dev.4
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 +55 -15
- package/dist/client.d.ts +8 -5
- package/dist/index.js +57 -36
- package/dist/protocol.d.ts +8 -3
- package/package.json +6 -6
- package/src/client.ts +15 -5
- package/src/protocol.ts +21 -7
- package/src/server.ts +103 -55
package/README.md
CHANGED
|
@@ -9,8 +9,8 @@ been idle.
|
|
|
9
9
|
Why: SQLite's write lock is per-process. Two processes (an app, a log host, a
|
|
10
10
|
retention job, a debugging CLI) writing the same file contend, time out, and
|
|
11
11
|
freeze each other. With a single owner there is nothing to contend: statements
|
|
12
|
-
from all clients
|
|
13
|
-
|
|
12
|
+
from all clients use one writer, and a reader from any process just asks the
|
|
13
|
+
owner. WAL files also have a readonly connection for opted-in plain reads.
|
|
14
14
|
|
|
15
15
|
## Pieces
|
|
16
16
|
|
|
@@ -19,7 +19,7 @@ process just asks the owner.
|
|
|
19
19
|
| `@noego/sqlego-<platform>-<arch>` (`npm/<platform>/`) | Bun, compiled single binary | CLI **and** server (`sqlego serve <file>` is what clients spawn); one package per platform, one binary each |
|
|
20
20
|
| `bin/sqlego.cjs` | Node | The `sqlego` command npm installs: runs the binary for this platform (npm shims cannot launch a native `.exe` on Windows) |
|
|
21
21
|
| `@noego/sqlego` (`src/client.ts`) | Node or Bun; `node:net` only | Protocol-only client — no SQLite dependency, no native addon, no binary |
|
|
22
|
-
| `src/server.ts` | Bun (`bun:sqlite`) | The owner: per file one
|
|
22
|
+
| `src/server.ts` | Bun (`bun:sqlite`) | The owner: per file one writer, a readonly connection for WAL files, and one socket; many files per process; idle release |
|
|
23
23
|
|
|
24
24
|
Platforms: macOS (arm64, x64), Linux (x64, arm64, glibc), Windows x64. The
|
|
25
25
|
Windows build is cross-compiled and exercised only as a build; it has not been
|
|
@@ -116,12 +116,14 @@ An owner is a Bun process (tens of MB), so one serves many files. A file
|
|
|
116
116
|
with no owner is adopted by the running owner (of the client's build, under
|
|
117
117
|
the same runtime directory) that serves the fewest files; a new process is
|
|
118
118
|
spawned only while fewer than `maxOwners` exist (`SQLEGO_MAX_OWNERS` or the
|
|
119
|
-
`maxOwners` client option). Default `
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
119
|
+
`maxOwners` client option). Default `4`: files are spread over up to four
|
|
120
|
+
processes — SQL for files sharing a process runs on one thread, so a long
|
|
121
|
+
statement on one file delays only the files that share its process, while an
|
|
122
|
+
app holding tens of databases open still costs a handful of processes, not
|
|
123
|
+
tens. `1` puts every file in one process; `0` means one process per file, as
|
|
124
|
+
before owners could adopt. The limit counts every owner of the client's
|
|
125
|
+
build under the runtime directory, whichever app started it. Nothing is ever
|
|
126
|
+
refused for lack of a process.
|
|
125
127
|
|
|
126
128
|
Each file keeps its own socket, database connection, leased transaction and
|
|
127
129
|
idle timer. `sqlego <file> stop` and the idle timeout release that one file;
|
|
@@ -133,8 +135,11 @@ share one process instead of starting 40.
|
|
|
133
135
|
|
|
134
136
|
An owner applies, in order, `auto_vacuum = INCREMENTAL`, `journal_mode = WAL`,
|
|
135
137
|
`busy_timeout = 5000`, `foreign_keys = ON` (foreign keys are per connection in
|
|
136
|
-
SQLite and off by default;
|
|
138
|
+
SQLite and off by default; enabled on the writer). `--pragma`
|
|
137
139
|
on `serve`, or `serverPragmas` on the client, replaces the whole list.
|
|
140
|
+
After applying them, a WAL file gets a second connection opened readonly with
|
|
141
|
+
safe integers, the writer's busy timeout, and `query_only = ON`. Non-WAL files
|
|
142
|
+
keep one connection and do not advertise detached-read support.
|
|
138
143
|
|
|
139
144
|
## Protocol
|
|
140
145
|
|
|
@@ -189,10 +194,11 @@ trusted to.
|
|
|
189
194
|
`SAVEPOINT` and `RELEASE` (`bad-request`): the server must always know
|
|
190
195
|
whether the file is inside a transaction.
|
|
191
196
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
197
|
+
Without the detached-plain opt-in below, the owning client's statements run at
|
|
198
|
+
once (plain statements implicitly join its transaction), and every other
|
|
199
|
+
client's `query` / `run` / `statement` / `exec` / `batch` / `begin` waits in arrival
|
|
200
|
+
order (`status` reports how many). `hello`, `status` and `stop` never wait.
|
|
201
|
+
It is rolled back by the server, and later requests for it fail with `tx-expired`, when:
|
|
196
202
|
|
|
197
203
|
| Trigger | Server flag | Default |
|
|
198
204
|
| --- | --- | --- |
|
|
@@ -201,10 +207,44 @@ by the server, and later requests for it fail with `tx-expired`, when:
|
|
|
201
207
|
| Open longer than the hard cap, renewed or not | `--tx-max-ms` | 60 s |
|
|
202
208
|
| SQLite itself aborted it (e.g. `SQLITE_FULL`) | — | immediate |
|
|
203
209
|
|
|
204
|
-
A waiting request
|
|
210
|
+
A waiting request fails with `tx-busy` after
|
|
205
211
|
`--tx-queue-ms` (default 30 s) rather than hanging. The idle exit never fires
|
|
206
212
|
while a transaction is open.
|
|
207
213
|
|
|
214
|
+
### Detached plain statements (opt-in)
|
|
215
|
+
|
|
216
|
+
WAL owners advertise `capabilities: ['detached-plain']` in `hello` and `status`.
|
|
217
|
+
Missing capabilities parse as `[]`. A socket opts in by sending
|
|
218
|
+
`hello { clientVersion, protocol: 3, features: ['detached-plain'] }`, or by
|
|
219
|
+
calling `await client.enableDetachedPlain()` after connecting (returns false
|
|
220
|
+
when unsupported). Opt-in is sticky for that socket. Other sockets, including
|
|
221
|
+
older clients using the same owner, retain their existing transaction semantics.
|
|
222
|
+
|
|
223
|
+
For an opted-in socket:
|
|
224
|
+
- A single plain statement (no `txId`) starting with `SELECT`, `WITH`,
|
|
225
|
+
`VALUES` or `EXPLAIN`, after comments, runs on the readonly connection,
|
|
226
|
+
irrespective of whether its op is `query`, `run` or `statement`.
|
|
227
|
+
- Only `SQLITE_READONLY` retries on the writer under normal queueing rules
|
|
228
|
+
(for example, a CTE-prefixed write). Every other error is returned as-is.
|
|
229
|
+
- All `PRAGMA`s, other SQL keywords, `exec`, `batch` and transaction operations
|
|
230
|
+
stay on the writer. Statements with a `txId` always use the writer.
|
|
231
|
+
- Plain writer-path requests wait for **any** open transaction, including one
|
|
232
|
+
owned by this same socket. They never implicitly join it. Requests carrying
|
|
233
|
+
its `txId`, including commit/rollback, still run without waiting.
|
|
234
|
+
- Plain reads see the last committed snapshot, not uncommitted writes.
|
|
235
|
+
Reads that accidentally escape a transaction's scope therefore return
|
|
236
|
+
committed data rather than blocking.
|
|
237
|
+
- Standalone `SELECT last_insert_rowid()` / `changes()` reports the reader's
|
|
238
|
+
values, not the writer's. Reader reply metadata is `changes: 0` and
|
|
239
|
+
`lastInsertRowid: 0`.
|
|
240
|
+
- Plain reads of a TEMP table created on the writer fail. Use the transaction
|
|
241
|
+
handle for transaction-local state; audit any existing TEMP-table use.
|
|
242
|
+
- Queued plain writes may now fail with `tx-busy` after the default 30 seconds,
|
|
243
|
+
rather than waiting indefinitely in a client's local gate.
|
|
244
|
+
|
|
245
|
+
Both connections close when the file is stopped; adopted WAL files get the
|
|
246
|
+
same reader automatically.
|
|
247
|
+
|
|
208
248
|
## CLI
|
|
209
249
|
|
|
210
250
|
```
|
package/dist/client.d.ts
CHANGED
|
@@ -31,10 +31,11 @@ export type ClientOptions = Readonly<{
|
|
|
31
31
|
* How many owner processes (of this client's build, under this runtime
|
|
32
32
|
* directory) may exist. A file with no owner is adopted by the running
|
|
33
33
|
* owner serving the fewest files; a new process is spawned only while
|
|
34
|
-
* there are fewer than this many.
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
34
|
+
* there are fewer than this many. N spreads files over up to N processes
|
|
35
|
+
* (SQL for files sharing a process runs on one thread, so a busy file only
|
|
36
|
+
* delays the files that share its process); 1 means one process serves
|
|
37
|
+
* every file; 0 means one process per file, as before owners could adopt.
|
|
38
|
+
* Default `SQLEGO_MAX_OWNERS`, else 4. Never refuses.
|
|
38
39
|
*/
|
|
39
40
|
maxOwners?: number;
|
|
40
41
|
/** Total time to obtain a connection, including spawn. Default 10 000. */
|
|
@@ -42,7 +43,7 @@ export type ClientOptions = Readonly<{
|
|
|
42
43
|
/** Per-request timeout. Default 60 000. */
|
|
43
44
|
requestTimeoutMs?: number;
|
|
44
45
|
}>;
|
|
45
|
-
export declare const DEFAULT_MAX_OWNERS =
|
|
46
|
+
export declare const DEFAULT_MAX_OWNERS = 4;
|
|
46
47
|
export type BeginOptions = Readonly<{
|
|
47
48
|
/** `immediate` takes the write lock at `begin`; `deferred` (default) on the first write. */
|
|
48
49
|
mode?: TransactionMode;
|
|
@@ -71,6 +72,8 @@ export declare class SqlegoClient {
|
|
|
71
72
|
private constructor();
|
|
72
73
|
static connect(file: string, options?: ClientOptions): Promise<SqlegoClient>;
|
|
73
74
|
get server(): HelloResult;
|
|
75
|
+
/** Opt this socket into committed-snapshot plain reads and queued plain writes. */
|
|
76
|
+
enableDetachedPlain(): Promise<boolean>;
|
|
74
77
|
query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]>;
|
|
75
78
|
run(sql: string, params?: SqlParams): Promise<RunResult>;
|
|
76
79
|
/**
|
package/dist/index.js
CHANGED
|
@@ -276,8 +276,8 @@ function parseResponse(input) {
|
|
|
276
276
|
if (typeof id !== "number")
|
|
277
277
|
return invalid("a response needs a numeric id");
|
|
278
278
|
if (fields.ok === true) {
|
|
279
|
-
const
|
|
280
|
-
return Result.ok(
|
|
279
|
+
const response2 = { id, ok: true, result: fields.result };
|
|
280
|
+
return Result.ok(response2);
|
|
281
281
|
}
|
|
282
282
|
if (fields.ok !== false)
|
|
283
283
|
return invalid("a response needs ok: true or false");
|
|
@@ -391,10 +391,13 @@ function parseExecResult(input) {
|
|
|
391
391
|
return Result.ok(result);
|
|
392
392
|
}
|
|
393
393
|
function parsePragmas(input) {
|
|
394
|
+
return parseStringList(input, "pragmas");
|
|
395
|
+
}
|
|
396
|
+
function parseStringList(input, name) {
|
|
394
397
|
if (input === undefined)
|
|
395
398
|
return Result.ok([]);
|
|
396
399
|
if (!Array.isArray(input) || !input.every((item) => typeof item === "string")) {
|
|
397
|
-
return invalid(
|
|
400
|
+
return invalid(`${name} must be an array of strings`);
|
|
398
401
|
}
|
|
399
402
|
return Result.ok([...input]);
|
|
400
403
|
}
|
|
@@ -406,7 +409,10 @@ function parseHelloResult(input) {
|
|
|
406
409
|
const pragmas = parsePragmas(fields.pragmas);
|
|
407
410
|
if (!pragmas.ok)
|
|
408
411
|
return pragmas;
|
|
409
|
-
const
|
|
412
|
+
const capabilities = parseStringList(fields.capabilities, "capabilities");
|
|
413
|
+
if (!capabilities.ok)
|
|
414
|
+
return capabilities;
|
|
415
|
+
const result = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid, pragmas: pragmas.value, capabilities: capabilities.value };
|
|
410
416
|
return Result.ok(result);
|
|
411
417
|
}
|
|
412
418
|
function parseBeginResult(input) {
|
|
@@ -460,6 +466,9 @@ function parseStatusResult(input) {
|
|
|
460
466
|
const pragmas = parsePragmas(f.pragmas);
|
|
461
467
|
if (!pragmas.ok)
|
|
462
468
|
return pragmas;
|
|
469
|
+
const capabilities = parseStringList(f.capabilities, "capabilities");
|
|
470
|
+
if (!capabilities.ok)
|
|
471
|
+
return capabilities;
|
|
463
472
|
const files = f.files === undefined ? 1 : f.files;
|
|
464
473
|
if (typeof files !== "number")
|
|
465
474
|
return invalid("status.files must be a number");
|
|
@@ -476,7 +485,8 @@ function parseStatusResult(input) {
|
|
|
476
485
|
idleMs: f.idleMs,
|
|
477
486
|
idleTimeoutMs: f.idleTimeoutMs,
|
|
478
487
|
requestsServed: f.requestsServed,
|
|
479
|
-
transaction: transaction.value
|
|
488
|
+
transaction: transaction.value,
|
|
489
|
+
capabilities: capabilities.value
|
|
480
490
|
};
|
|
481
491
|
return Result.ok(result);
|
|
482
492
|
}
|
|
@@ -553,10 +563,10 @@ function resolvePaths(file) {
|
|
|
553
563
|
if (!directory.ok)
|
|
554
564
|
return directory;
|
|
555
565
|
const derived = Trust.try(() => {
|
|
556
|
-
const
|
|
566
|
+
const key2 = createHash("sha1").update(canonical.value).digest("hex").slice(0, 16);
|
|
557
567
|
const scope = createHash("sha1").update(directory.value.toLowerCase()).digest("hex").slice(0, 8);
|
|
558
|
-
const
|
|
559
|
-
return { key, socket, socketBytes: Buffer.byteLength(
|
|
568
|
+
const socket2 = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${scope}-${key2}` : path2.join(directory.value, `${key2}.sock`);
|
|
569
|
+
return { key: key2, socket: socket2, socketBytes: Buffer.byteLength(socket2) };
|
|
560
570
|
}, (cause) => ({ kind: "hash-failed", message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }));
|
|
561
571
|
if (!derived.ok)
|
|
562
572
|
return derived;
|
|
@@ -628,7 +638,7 @@ import { fileURLToPath } from "node:url";
|
|
|
628
638
|
// package.json
|
|
629
639
|
var package_default = {
|
|
630
640
|
name: "@noego/sqlego",
|
|
631
|
-
version: "0.1.2-dev.
|
|
641
|
+
version: "0.1.2-dev.4",
|
|
632
642
|
description: "One owner per SQLite file, many files per owner process. Clients (CLI, Node, Bun) pass SQL over a local socket (Unix) or named pipe (Windows); the owner starts on demand and exits when idle.",
|
|
633
643
|
type: "module",
|
|
634
644
|
license: "ISC",
|
|
@@ -679,11 +689,11 @@ var package_default = {
|
|
|
679
689
|
"@noego/trust": "0.5.0-dev.0"
|
|
680
690
|
},
|
|
681
691
|
optionalDependencies: {
|
|
682
|
-
"@noego/sqlego-darwin-arm64": "0.1.2-dev.
|
|
683
|
-
"@noego/sqlego-darwin-x64": "0.1.2-dev.
|
|
684
|
-
"@noego/sqlego-linux-x64": "0.1.2-dev.
|
|
685
|
-
"@noego/sqlego-linux-arm64": "0.1.2-dev.
|
|
686
|
-
"@noego/sqlego-win32-x64": "0.1.2-dev.
|
|
692
|
+
"@noego/sqlego-darwin-arm64": "0.1.2-dev.4",
|
|
693
|
+
"@noego/sqlego-darwin-x64": "0.1.2-dev.4",
|
|
694
|
+
"@noego/sqlego-linux-x64": "0.1.2-dev.4",
|
|
695
|
+
"@noego/sqlego-linux-arm64": "0.1.2-dev.4",
|
|
696
|
+
"@noego/sqlego-win32-x64": "0.1.2-dev.4"
|
|
687
697
|
}
|
|
688
698
|
};
|
|
689
699
|
|
|
@@ -701,8 +711,8 @@ function sourceBuildId(sourceDirectory) {
|
|
|
701
711
|
}, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
|
|
702
712
|
}
|
|
703
713
|
function resolveBuildId() {
|
|
704
|
-
if ("
|
|
705
|
-
return "
|
|
714
|
+
if ("e5711cce187d".length > 0)
|
|
715
|
+
return "e5711cce187d";
|
|
706
716
|
const directory = Trust.try(() => path3.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
|
|
707
717
|
if (!directory.ok)
|
|
708
718
|
return decideUnknownBuild(directory.error.kind);
|
|
@@ -727,7 +737,7 @@ var BUILD_ID = resolveBuildId();
|
|
|
727
737
|
var VERSION = process.env.SQLEGO_VERSION_OVERRIDE || `${package_default.version}+${BUILD_ID}`;
|
|
728
738
|
|
|
729
739
|
// src/client.ts
|
|
730
|
-
var DEFAULT_MAX_OWNERS =
|
|
740
|
+
var DEFAULT_MAX_OWNERS = 4;
|
|
731
741
|
var ADOPT_TIMEOUT_MS = 5000;
|
|
732
742
|
var SAVEPOINT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
733
743
|
|
|
@@ -779,6 +789,17 @@ class SqlegoClient {
|
|
|
779
789
|
return this.hello;
|
|
780
790
|
return unwrap(Result.err({ kind: "not-connected", message: "client is not connected" }));
|
|
781
791
|
}
|
|
792
|
+
async enableDetachedPlain() {
|
|
793
|
+
if (!this.server.capabilities.includes("detached-plain"))
|
|
794
|
+
return false;
|
|
795
|
+
this.hello = unwrap(await this.call({
|
|
796
|
+
op: "hello",
|
|
797
|
+
clientVersion: VERSION,
|
|
798
|
+
protocol: PROTOCOL_VERSION,
|
|
799
|
+
features: ["detached-plain"]
|
|
800
|
+
}, parseHelloResult));
|
|
801
|
+
return this.hello.capabilities.includes("detached-plain");
|
|
802
|
+
}
|
|
782
803
|
async query(sql, params) {
|
|
783
804
|
const result = unwrap(await this.call({ op: "query", sql, params }, parseQueryResult));
|
|
784
805
|
return callerRows(result.rows);
|
|
@@ -1319,8 +1340,8 @@ function parseOneShotReply(line, parse) {
|
|
|
1319
1340
|
if (!response.ok) {
|
|
1320
1341
|
if (response.error.kind === "invalid")
|
|
1321
1342
|
return probeFailed(`malformed reply: ${response.error.message}`);
|
|
1322
|
-
const
|
|
1323
|
-
return
|
|
1343
|
+
const unhandled2 = response.error.kind;
|
|
1344
|
+
return unhandled2;
|
|
1324
1345
|
}
|
|
1325
1346
|
if (!response.value.ok)
|
|
1326
1347
|
return probeFailed(`${response.value.error.code}: ${response.value.error.message}`);
|
|
@@ -1377,22 +1398,22 @@ function sleep(ms) {
|
|
|
1377
1398
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1378
1399
|
}
|
|
1379
1400
|
export {
|
|
1380
|
-
|
|
1381
|
-
PROTOCOL_VERSION,
|
|
1382
|
-
SUPPORTED_PLATFORMS,
|
|
1383
|
-
SqlegoClient,
|
|
1384
|
-
SqlegoClientError,
|
|
1385
|
-
SqlegoTransaction,
|
|
1386
|
-
USES_NAMED_PIPES,
|
|
1387
|
-
VERSION,
|
|
1388
|
-
binaryFileName,
|
|
1389
|
-
canonicalFile,
|
|
1390
|
-
defaultServerCommand,
|
|
1391
|
-
isNamedPipe,
|
|
1392
|
-
localBinaryName,
|
|
1393
|
-
locateServerBinary,
|
|
1394
|
-
pathsFor,
|
|
1395
|
-
platformPackageName,
|
|
1401
|
+
unpackedAsarPath,
|
|
1396
1402
|
runtimeDirectory,
|
|
1397
|
-
|
|
1403
|
+
platformPackageName,
|
|
1404
|
+
pathsFor,
|
|
1405
|
+
locateServerBinary,
|
|
1406
|
+
localBinaryName,
|
|
1407
|
+
isNamedPipe,
|
|
1408
|
+
defaultServerCommand,
|
|
1409
|
+
canonicalFile,
|
|
1410
|
+
binaryFileName,
|
|
1411
|
+
VERSION,
|
|
1412
|
+
USES_NAMED_PIPES,
|
|
1413
|
+
SqlegoTransaction,
|
|
1414
|
+
SqlegoClientError,
|
|
1415
|
+
SqlegoClient,
|
|
1416
|
+
SUPPORTED_PLATFORMS,
|
|
1417
|
+
PROTOCOL_VERSION,
|
|
1418
|
+
DEFAULT_MAX_OWNERS
|
|
1398
1419
|
};
|
package/dist/protocol.d.ts
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
* sqlego wire protocol: newline-delimited JSON over a local socket.
|
|
3
3
|
*
|
|
4
4
|
* One request per line, one response per line, correlated by `id`. The server
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* serializes writer requests on one connection per file. WAL files also have
|
|
6
|
+
* a readonly connection: sockets opting into detached-plain can read committed
|
|
7
|
+
* data without waiting for the writer's open transaction.
|
|
8
8
|
*
|
|
9
9
|
* Transactions over the wire are leased, never bare: `begin` opens one bound
|
|
10
10
|
* to the client's socket, `query`/`run` carry its `txId`, and `commit` or
|
|
@@ -51,6 +51,7 @@ export type Request = {
|
|
|
51
51
|
op: 'hello';
|
|
52
52
|
clientVersion: string;
|
|
53
53
|
protocol: number;
|
|
54
|
+
features?: readonly string[];
|
|
54
55
|
} | {
|
|
55
56
|
id: number;
|
|
56
57
|
op: 'query';
|
|
@@ -187,6 +188,7 @@ export type HelloResult = Readonly<{
|
|
|
187
188
|
pid: number;
|
|
188
189
|
/** The pragmas the owner applied on open (its defaults, or its `--pragma` list). */
|
|
189
190
|
pragmas: readonly string[];
|
|
191
|
+
capabilities: readonly string[];
|
|
190
192
|
}>;
|
|
191
193
|
export type StatusResult = Readonly<{
|
|
192
194
|
file: string;
|
|
@@ -195,6 +197,7 @@ export type StatusResult = Readonly<{
|
|
|
195
197
|
serverVersion: string;
|
|
196
198
|
protocol: number;
|
|
197
199
|
pragmas: readonly string[];
|
|
200
|
+
capabilities: readonly string[];
|
|
198
201
|
/** Files this owner process serves, this one included. */
|
|
199
202
|
files: number;
|
|
200
203
|
clients: number;
|
|
@@ -375,6 +378,7 @@ export declare function parseHelloResult(input: unknown): import("@noego/trust")
|
|
|
375
378
|
pid: number;
|
|
376
379
|
/** The pragmas the owner applied on open (its defaults, or its `--pragma` list). */
|
|
377
380
|
pragmas: readonly string[];
|
|
381
|
+
capabilities: readonly string[];
|
|
378
382
|
}>>;
|
|
379
383
|
export declare function parseBeginResult(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
380
384
|
kind: "invalid";
|
|
@@ -408,6 +412,7 @@ export declare function parseStatusResult(input: unknown): import("@noego/trust"
|
|
|
408
412
|
serverVersion: string;
|
|
409
413
|
protocol: number;
|
|
410
414
|
pragmas: readonly string[];
|
|
415
|
+
capabilities: readonly string[];
|
|
411
416
|
/** Files this owner process serves, this one included. */
|
|
412
417
|
files: number;
|
|
413
418
|
clients: number;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noego/sqlego",
|
|
3
|
-
"version": "0.1.2-dev.
|
|
3
|
+
"version": "0.1.2-dev.4",
|
|
4
4
|
"description": "One owner per SQLite file, many files per owner process. Clients (CLI, Node, Bun) pass SQL over a local socket (Unix) or named pipe (Windows); the owner starts on demand and exits when idle.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "ISC",
|
|
@@ -51,10 +51,10 @@
|
|
|
51
51
|
"@noego/trust": "0.5.0-dev.0"
|
|
52
52
|
},
|
|
53
53
|
"optionalDependencies": {
|
|
54
|
-
"@noego/sqlego-darwin-arm64": "0.1.2-dev.
|
|
55
|
-
"@noego/sqlego-darwin-x64": "0.1.2-dev.
|
|
56
|
-
"@noego/sqlego-linux-x64": "0.1.2-dev.
|
|
57
|
-
"@noego/sqlego-linux-arm64": "0.1.2-dev.
|
|
58
|
-
"@noego/sqlego-win32-x64": "0.1.2-dev.
|
|
54
|
+
"@noego/sqlego-darwin-arm64": "0.1.2-dev.4",
|
|
55
|
+
"@noego/sqlego-darwin-x64": "0.1.2-dev.4",
|
|
56
|
+
"@noego/sqlego-linux-x64": "0.1.2-dev.4",
|
|
57
|
+
"@noego/sqlego-linux-arm64": "0.1.2-dev.4",
|
|
58
|
+
"@noego/sqlego-win32-x64": "0.1.2-dev.4"
|
|
59
59
|
}
|
|
60
60
|
}
|
package/src/client.ts
CHANGED
|
@@ -72,10 +72,11 @@ export type ClientOptions = Readonly<{
|
|
|
72
72
|
* How many owner processes (of this client's build, under this runtime
|
|
73
73
|
* directory) may exist. A file with no owner is adopted by the running
|
|
74
74
|
* owner serving the fewest files; a new process is spawned only while
|
|
75
|
-
* there are fewer than this many.
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
75
|
+
* there are fewer than this many. N spreads files over up to N processes
|
|
76
|
+
* (SQL for files sharing a process runs on one thread, so a busy file only
|
|
77
|
+
* delays the files that share its process); 1 means one process serves
|
|
78
|
+
* every file; 0 means one process per file, as before owners could adopt.
|
|
79
|
+
* Default `SQLEGO_MAX_OWNERS`, else 4. Never refuses.
|
|
79
80
|
*/
|
|
80
81
|
maxOwners?: number;
|
|
81
82
|
/** Total time to obtain a connection, including spawn. Default 10 000. */
|
|
@@ -84,7 +85,7 @@ export type ClientOptions = Readonly<{
|
|
|
84
85
|
requestTimeoutMs?: number;
|
|
85
86
|
}>;
|
|
86
87
|
|
|
87
|
-
export const DEFAULT_MAX_OWNERS =
|
|
88
|
+
export const DEFAULT_MAX_OWNERS = 4;
|
|
88
89
|
|
|
89
90
|
/** One live owner process of this build, as the meta files of the files it serves report it. */
|
|
90
91
|
type OwnerProcess = Readonly<{ pid: number; socket: string; files: number; startedAt: number }>;
|
|
@@ -196,6 +197,15 @@ export class SqlegoClient {
|
|
|
196
197
|
return unwrap(Result.err({ kind: 'not-connected', message: 'client is not connected' }));
|
|
197
198
|
}
|
|
198
199
|
|
|
200
|
+
/** Opt this socket into committed-snapshot plain reads and queued plain writes. */
|
|
201
|
+
async enableDetachedPlain(): Promise<boolean> {
|
|
202
|
+
if (!this.server.capabilities.includes('detached-plain')) return false;
|
|
203
|
+
this.hello = unwrap(await this.call({
|
|
204
|
+
op: 'hello', clientVersion: VERSION, protocol: PROTOCOL_VERSION, features: ['detached-plain'],
|
|
205
|
+
}, parseHelloResult));
|
|
206
|
+
return this.hello.capabilities.includes('detached-plain');
|
|
207
|
+
}
|
|
208
|
+
|
|
199
209
|
async query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]> {
|
|
200
210
|
const result = unwrap(await this.call({ op: 'query', sql, params }, parseQueryResult));
|
|
201
211
|
return callerRows<Row>(result.rows);
|
package/src/protocol.ts
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
* sqlego wire protocol: newline-delimited JSON over a local socket.
|
|
3
3
|
*
|
|
4
4
|
* One request per line, one response per line, correlated by `id`. The server
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* serializes writer requests on one connection per file. WAL files also have
|
|
6
|
+
* a readonly connection: sockets opting into detached-plain can read committed
|
|
7
|
+
* data without waiting for the writer's open transaction.
|
|
8
8
|
*
|
|
9
9
|
* Transactions over the wire are leased, never bare: `begin` opens one bound
|
|
10
10
|
* to the client's socket, `query`/`run` carry its `txId`, and `commit` or
|
|
@@ -58,7 +58,7 @@ export type Statement = Readonly<{
|
|
|
58
58
|
export type TransactionMode = 'deferred' | 'immediate';
|
|
59
59
|
|
|
60
60
|
export type Request =
|
|
61
|
-
| { id: number; op: 'hello'; clientVersion: string; protocol: number }
|
|
61
|
+
| { id: number; op: 'hello'; clientVersion: string; protocol: number; features?: readonly string[] }
|
|
62
62
|
| { id: number; op: 'query'; sql: string; params?: SqlParams; txId?: number }
|
|
63
63
|
| { id: number; op: 'run'; sql: string; params?: SqlParams; txId?: number }
|
|
64
64
|
/** Exactly one statement; rows when it has result columns (incl. `RETURNING`), plus its changes. */
|
|
@@ -118,6 +118,7 @@ export type HelloResult = Readonly<{
|
|
|
118
118
|
pid: number;
|
|
119
119
|
/** The pragmas the owner applied on open (its defaults, or its `--pragma` list). */
|
|
120
120
|
pragmas: readonly string[];
|
|
121
|
+
capabilities: readonly string[];
|
|
121
122
|
}>;
|
|
122
123
|
|
|
123
124
|
export type StatusResult = Readonly<{
|
|
@@ -127,6 +128,7 @@ export type StatusResult = Readonly<{
|
|
|
127
128
|
serverVersion: string;
|
|
128
129
|
protocol: number;
|
|
129
130
|
pragmas: readonly string[];
|
|
131
|
+
capabilities: readonly string[];
|
|
130
132
|
/** Files this owner process serves, this one included. */
|
|
131
133
|
files: number;
|
|
132
134
|
clients: number;
|
|
@@ -472,7 +474,9 @@ export function parseRequest(input: unknown) {
|
|
|
472
474
|
if (typeof fields.clientVersion !== 'string' || typeof fields.protocol !== 'number') {
|
|
473
475
|
return reject(id, 'hello needs clientVersion (string) and protocol (number)');
|
|
474
476
|
}
|
|
475
|
-
const
|
|
477
|
+
const features = parseStringList(fields.features, 'features');
|
|
478
|
+
if (!features.ok) return reject(id, features.error.message);
|
|
479
|
+
const request: Request = { id, op: 'hello', clientVersion: fields.clientVersion, protocol: fields.protocol, features: features.value };
|
|
476
480
|
return Result.ok(request);
|
|
477
481
|
}
|
|
478
482
|
case 'query':
|
|
@@ -678,9 +682,14 @@ export function parseExecResult(input: unknown) {
|
|
|
678
682
|
*/
|
|
679
683
|
//trust:validator_function
|
|
680
684
|
function parsePragmas(input: unknown) {
|
|
685
|
+
return parseStringList(input, 'pragmas');
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
//trust:validator_function
|
|
689
|
+
function parseStringList(input: unknown, name: string) {
|
|
681
690
|
if (input === undefined) return Result.ok<readonly string[]>([]);
|
|
682
691
|
if (!Array.isArray(input) || !input.every((item): item is string => typeof item === 'string')) {
|
|
683
|
-
return invalid(
|
|
692
|
+
return invalid(`${name} must be an array of strings`);
|
|
684
693
|
}
|
|
685
694
|
return Result.ok<readonly string[]>([...input]);
|
|
686
695
|
}
|
|
@@ -697,7 +706,9 @@ export function parseHelloResult(input: unknown) {
|
|
|
697
706
|
}
|
|
698
707
|
const pragmas = parsePragmas(fields.pragmas);
|
|
699
708
|
if (!pragmas.ok) return pragmas;
|
|
700
|
-
const
|
|
709
|
+
const capabilities = parseStringList(fields.capabilities, 'capabilities');
|
|
710
|
+
if (!capabilities.ok) return capabilities;
|
|
711
|
+
const result: HelloResult = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid, pragmas: pragmas.value, capabilities: capabilities.value };
|
|
701
712
|
return Result.ok(result);
|
|
702
713
|
}
|
|
703
714
|
|
|
@@ -761,6 +772,8 @@ export function parseStatusResult(input: unknown) {
|
|
|
761
772
|
if (!transaction.ok) return transaction;
|
|
762
773
|
const pragmas = parsePragmas(f.pragmas);
|
|
763
774
|
if (!pragmas.ok) return pragmas;
|
|
775
|
+
const capabilities = parseStringList(f.capabilities, 'capabilities');
|
|
776
|
+
if (!capabilities.ok) return capabilities;
|
|
764
777
|
// An owner from before multi-file owners served exactly one file.
|
|
765
778
|
const files = f.files === undefined ? 1 : f.files;
|
|
766
779
|
if (typeof files !== 'number') return invalid('status.files must be a number');
|
|
@@ -768,6 +781,7 @@ export function parseStatusResult(input: unknown) {
|
|
|
768
781
|
file: f.file, socket: f.socket, pid: f.pid, serverVersion: f.serverVersion, protocol: f.protocol, pragmas: pragmas.value, files,
|
|
769
782
|
clients: f.clients, uptimeMs: f.uptimeMs, idleMs: f.idleMs, idleTimeoutMs: f.idleTimeoutMs, requestsServed: f.requestsServed,
|
|
770
783
|
transaction: transaction.value,
|
|
784
|
+
capabilities: capabilities.value,
|
|
771
785
|
};
|
|
772
786
|
return Result.ok(result);
|
|
773
787
|
}
|
package/src/server.ts
CHANGED
|
@@ -69,7 +69,7 @@ export const DEFAULT_TX_LEASE_MS = 10_000;
|
|
|
69
69
|
export const DEFAULT_TX_MAX_DURATION_MS = 60_000;
|
|
70
70
|
export const DEFAULT_TX_QUEUE_TIMEOUT_MS = 30_000;
|
|
71
71
|
|
|
72
|
-
type SqliteFailure = { readonly kind: 'sqlite'; readonly message: string };
|
|
72
|
+
type SqliteFailure = { readonly kind: 'sqlite'; readonly message: string; readonly code?: string };
|
|
73
73
|
type BadRequest = { readonly kind: 'bad-request'; readonly message: string };
|
|
74
74
|
type TransactionFailure = { readonly kind: 'tx-expired' | 'tx-invalid'; readonly message: string };
|
|
75
75
|
type CleanupFailure = { readonly kind: 'cleanup-failed'; readonly message: string };
|
|
@@ -82,7 +82,10 @@ type Executed = { reader: boolean; rows: unknown; changes: number; lastInsertRow
|
|
|
82
82
|
type Counters = { changes: number; total: number; lastInsertRowid: number | bigint };
|
|
83
83
|
type TxControl = ReturnType<typeof transactionControl>;
|
|
84
84
|
|
|
85
|
-
const sqliteFailure = (cause: unknown): SqliteFailure => ({
|
|
85
|
+
const sqliteFailure = (cause: unknown): SqliteFailure => ({
|
|
86
|
+
kind: 'sqlite', message: errorMessage(cause),
|
|
87
|
+
code: typeof cause === 'object' && cause !== null && 'code' in cause && typeof cause.code === 'string' ? cause.code : undefined,
|
|
88
|
+
});
|
|
86
89
|
const cleanupFailure = (cause: unknown): CleanupFailure => ({ kind: 'cleanup-failed', message: errorMessage(cause) });
|
|
87
90
|
const writeFailure = (cause: unknown): WriteFailure => ({ kind: 'write-failed', message: errorMessage(cause) });
|
|
88
91
|
const badRequest = (message: string) => Result.err<BadRequest>({ kind: 'bad-request', message });
|
|
@@ -106,7 +109,7 @@ class BatchStatementFailed extends Error {
|
|
|
106
109
|
* so a large result followed by another frame corrupts the stream unless the
|
|
107
110
|
* remainder is carried and flushed on `drain`.
|
|
108
111
|
*/
|
|
109
|
-
type Connection = { id: number; buffer: string; outbound: Buffer | null; socket: ServerSocket };
|
|
112
|
+
type Connection = { id: number; buffer: string; outbound: Buffer | null; socket: ServerSocket; detachedPlain: boolean };
|
|
110
113
|
|
|
111
114
|
/** Each socket carries its connection in Bun's typed `data` slot: null until `open` assigns it. */
|
|
112
115
|
type ServerSocket = import('bun').Socket<Connection | null>;
|
|
@@ -152,13 +155,11 @@ export function stopAll(reason: string): void {
|
|
|
152
155
|
}
|
|
153
156
|
|
|
154
157
|
/**
|
|
155
|
-
* The single owner of one SQLite file
|
|
156
|
-
* in
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
* and every other client's statements wait in arrival order; the transaction
|
|
161
|
-
* cannot outlive its socket, its lease, or the server's hard cap.
|
|
158
|
+
* The single owner of one SQLite file: one writer and, for WAL, one readonly
|
|
159
|
+
* connection. Opted-in plain reads use the reader without waiting for the
|
|
160
|
+
* writer's transaction; plain writes queue even on the owning socket.
|
|
161
|
+
* Legacy sockets keep implicit joining on the writer. A transaction cannot
|
|
162
|
+
* outlive its socket, its lease, or the server's hard cap.
|
|
162
163
|
*
|
|
163
164
|
* One owner process serves any number of files: the first through `start`
|
|
164
165
|
* (what `sqlego serve` does), the rest through the `adopt` request a client
|
|
@@ -170,6 +171,11 @@ export class SqlegoServer {
|
|
|
170
171
|
/** The pragmas applied on open, as given; reported to clients so one asking for others can tell. */
|
|
171
172
|
readonly pragmas: readonly string[];
|
|
172
173
|
private readonly db: Database;
|
|
174
|
+
private readonly reader: Database | null;
|
|
175
|
+
|
|
176
|
+
get capabilities(): readonly string[] {
|
|
177
|
+
return this.reader ? ['detached-plain'] : [];
|
|
178
|
+
}
|
|
173
179
|
private readonly options: ServerOptions;
|
|
174
180
|
private readonly startedAt = Date.now();
|
|
175
181
|
private readonly connections = new Map<number, Connection>();
|
|
@@ -185,10 +191,11 @@ export class SqlegoServer {
|
|
|
185
191
|
private readonly ended = new Map<number, EndedTransaction>();
|
|
186
192
|
private readonly log: NonNullable<ServerOptions['log']>;
|
|
187
193
|
|
|
188
|
-
private constructor(options: ServerOptions, paths: FilePaths, db: Database, pragmas: readonly string[]) {
|
|
194
|
+
private constructor(options: ServerOptions, paths: FilePaths, db: Database, pragmas: readonly string[], reader: Database | null) {
|
|
189
195
|
this.options = options;
|
|
190
196
|
this.paths = paths;
|
|
191
197
|
this.db = db;
|
|
198
|
+
this.reader = reader;
|
|
192
199
|
this.pragmas = pragmas;
|
|
193
200
|
this.log = options.log ?? (() => undefined);
|
|
194
201
|
}
|
|
@@ -210,7 +217,23 @@ export class SqlegoServer {
|
|
|
210
217
|
(cause) => ({ kind: 'open-failed', message: `cannot open ${paths.value.file}: ${errorMessage(cause)}` }),
|
|
211
218
|
);
|
|
212
219
|
if (!db.ok) return db;
|
|
213
|
-
|
|
220
|
+
let reader: Database | null = null;
|
|
221
|
+
const openedReader = Trust.try(() => {
|
|
222
|
+
const mode = db.value.query('PRAGMA journal_mode').values()[0]?.[0];
|
|
223
|
+
if (String(mode).toLowerCase() !== 'wal') return;
|
|
224
|
+
reader = new Database(paths.value.file, { readonly: true, safeIntegers: true });
|
|
225
|
+
const timeout = db.value.query('PRAGMA busy_timeout').values()[0]?.[0] ?? 5000;
|
|
226
|
+
reader.exec(`PRAGMA busy_timeout = ${Number(timeout)}`);
|
|
227
|
+
reader.exec('PRAGMA query_only = ON');
|
|
228
|
+
}, (cause) => ({ kind: 'open-failed', message: `cannot open reader for ${paths.value.file}: ${errorMessage(cause)}` }));
|
|
229
|
+
const server = new SqlegoServer(options, paths.value, db.value, [...pragmas], reader);
|
|
230
|
+
if (!openedReader.ok) {
|
|
231
|
+
// No socket/metadata has been created yet; only release these handles.
|
|
232
|
+
if (server.reader) server.reportCleanup('close reader', Trust.try(() => server.reader?.close(), cleanupFailure));
|
|
233
|
+
server.reportCleanup('close database', Trust.try(() => db.value.close(), cleanupFailure));
|
|
234
|
+
return openedReader;
|
|
235
|
+
}
|
|
236
|
+
return Result.ok(server);
|
|
214
237
|
}
|
|
215
238
|
|
|
216
239
|
/**
|
|
@@ -294,6 +317,7 @@ export class SqlegoServer {
|
|
|
294
317
|
}
|
|
295
318
|
const listener = this.listener;
|
|
296
319
|
if (listener) this.reportCleanup('stop listener', Trust.try(() => listener.stop(true), cleanupFailure));
|
|
320
|
+
if (this.reader) this.reportCleanup('close reader', Trust.try(() => this.reader?.close(), cleanupFailure));
|
|
297
321
|
this.reportCleanup('close database', Trust.try(() => this.db.close(), cleanupFailure));
|
|
298
322
|
}
|
|
299
323
|
|
|
@@ -318,6 +342,7 @@ export class SqlegoServer {
|
|
|
318
342
|
serverVersion: VERSION,
|
|
319
343
|
protocol: PROTOCOL_VERSION,
|
|
320
344
|
pragmas: this.pragmas,
|
|
345
|
+
capabilities: this.capabilities,
|
|
321
346
|
files: owned.has(this) ? owned.size : 1,
|
|
322
347
|
clients: this.connections.size,
|
|
323
348
|
uptimeMs: Date.now() - this.startedAt,
|
|
@@ -365,7 +390,7 @@ export class SqlegoServer {
|
|
|
365
390
|
return;
|
|
366
391
|
}
|
|
367
392
|
const id = this.nextConnectionId++;
|
|
368
|
-
const connection: Connection = { id, buffer: '', outbound: null, socket };
|
|
393
|
+
const connection: Connection = { id, buffer: '', outbound: null, socket, detachedPlain: false };
|
|
369
394
|
this.connections.set(id, connection);
|
|
370
395
|
socket.data = connection;
|
|
371
396
|
this.disarmIdleTimer();
|
|
@@ -407,6 +432,15 @@ export class SqlegoServer {
|
|
|
407
432
|
const parsed = this.parseFrame(frame);
|
|
408
433
|
if (!parsed.ok) return this.reply(connection, { id: parsed.error.id, ok: false, error: { code: 'bad-request', message: parsed.error.message } });
|
|
409
434
|
const request = parsed.value;
|
|
435
|
+
if (this.reader && this.isDetachedRead(connection, request)) {
|
|
436
|
+
const outcome = this.execute(connection, request, this.reader);
|
|
437
|
+
// A write-shaped CTE is retried only when SQLite refused it as readonly.
|
|
438
|
+
// All other failures (including TEMP-table misses) must be returned once.
|
|
439
|
+
if (outcome.ok || outcome.error.kind !== 'sqlite' || outcome.error.code !== 'SQLITE_READONLY') {
|
|
440
|
+
this.serve(connection, request, outcome);
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
410
444
|
if (this.mustWait(connection, request)) {
|
|
411
445
|
const timer = setTimeout(() => this.expireQueued(connection, request), this.txQueueTimeoutMs());
|
|
412
446
|
this.queue.push({ connection, request, timer });
|
|
@@ -425,25 +459,35 @@ export class SqlegoServer {
|
|
|
425
459
|
}
|
|
426
460
|
|
|
427
461
|
/**
|
|
428
|
-
*
|
|
429
|
-
*
|
|
430
|
-
*
|
|
431
|
-
*
|
|
462
|
+
* Detached reads have already run on the reader. Plain writer-path requests
|
|
463
|
+
* wait behind any transaction for opted-in sockets; legacy sockets still
|
|
464
|
+
* join their own transaction. Explicit txId requests and control replies
|
|
465
|
+
* must bypass the queue so the owner can finish and release waiting work.
|
|
432
466
|
*/
|
|
433
467
|
private mustWait(connection: Connection, request: Request): boolean {
|
|
434
468
|
const open = this.transaction;
|
|
435
|
-
if (!open || open.connection === connection) return false;
|
|
469
|
+
if (!open || (open.connection === connection && !connection.detachedPlain)) return false;
|
|
436
470
|
switch (request.op) {
|
|
437
471
|
case 'query':
|
|
438
472
|
case 'run':
|
|
439
473
|
case 'statement':
|
|
440
474
|
case 'exec': return request.txId === undefined;
|
|
441
|
-
case 'batch':
|
|
442
|
-
case 'begin': return
|
|
475
|
+
case 'batch': return true;
|
|
476
|
+
case 'begin': return open.connection !== connection;
|
|
443
477
|
default: return false;
|
|
444
478
|
}
|
|
445
479
|
}
|
|
446
480
|
|
|
481
|
+
private isDetachedRead(connection: Connection, request: Request): boolean {
|
|
482
|
+
if (!connection.detachedPlain) return false;
|
|
483
|
+
if (request.op !== 'query' && request.op !== 'run' && request.op !== 'statement') return false;
|
|
484
|
+
if (request.txId !== undefined) return false;
|
|
485
|
+
const pieces = splitSqlStatements(request.sql);
|
|
486
|
+
if (pieces.length !== 1) return false;
|
|
487
|
+
const body = pieces[0].replace(/^(?:\s+|--[^\n]*\n?|\/\*[\s\S]*?\*\/)+/, '');
|
|
488
|
+
return /^(SELECT|WITH|VALUES|EXPLAIN)\b/i.test(body);
|
|
489
|
+
}
|
|
490
|
+
|
|
447
491
|
private expireQueued(connection: Connection, request: Request): void {
|
|
448
492
|
const index = this.queue.findIndex((queued) => queued.request === request);
|
|
449
493
|
if (index < 0) return;
|
|
@@ -451,7 +495,7 @@ export class SqlegoServer {
|
|
|
451
495
|
const waited = this.txQueueTimeoutMs();
|
|
452
496
|
this.reply(connection, {
|
|
453
497
|
id: request.id, ok: false,
|
|
454
|
-
error: { code: 'tx-busy', message: `
|
|
498
|
+
error: { code: 'tx-busy', message: `an open transaction kept this ${request.op} waiting for ${waited} ms` },
|
|
455
499
|
});
|
|
456
500
|
}
|
|
457
501
|
|
|
@@ -465,9 +509,9 @@ export class SqlegoServer {
|
|
|
465
509
|
}
|
|
466
510
|
}
|
|
467
511
|
|
|
468
|
-
private serve(connection: Connection, request: Request): void {
|
|
512
|
+
private serve(connection: Connection, request: Request, outcome?: ReturnType<SqlegoServer['execute']>): void {
|
|
469
513
|
this.requestsServed += 1;
|
|
470
|
-
const response = this.respond(connection, request);
|
|
514
|
+
const response = this.respond(connection, request, outcome);
|
|
471
515
|
this.reply(connection, response);
|
|
472
516
|
if (response.ok && request.op === 'stop') {
|
|
473
517
|
// Only this file: an owner serving other files keeps serving them.
|
|
@@ -479,9 +523,10 @@ export class SqlegoServer {
|
|
|
479
523
|
}
|
|
480
524
|
|
|
481
525
|
/** Decides every failure of one request into a wire response. */
|
|
482
|
-
private respond(connection: Connection, request: Request): Response {
|
|
483
|
-
|
|
484
|
-
const outcome = this.execute(connection, request);
|
|
526
|
+
private respond(connection: Connection, request: Request, executed?: ReturnType<SqlegoServer['execute']>): Response {
|
|
527
|
+
// A detached read already ran on the reader: answer it as it ran, even while stopping.
|
|
528
|
+
const outcome = executed ?? (this.stopping ? null : this.execute(connection, request));
|
|
529
|
+
if (outcome === null) return { id: request.id, ok: false, error: { code: 'shutting-down', message: 'server is shutting down' } };
|
|
485
530
|
if (outcome.ok) return { id: request.id, ok: true, result: outcome.value };
|
|
486
531
|
switch (outcome.error.kind) {
|
|
487
532
|
case 'bad-request': return { id: request.id, ok: false, error: { code: 'bad-request', message: outcome.error.message } };
|
|
@@ -498,12 +543,12 @@ export class SqlegoServer {
|
|
|
498
543
|
}
|
|
499
544
|
}
|
|
500
545
|
|
|
501
|
-
private execute(connection: Connection, request: Request) {
|
|
546
|
+
private execute(connection: Connection, request: Request, db = this.db) {
|
|
502
547
|
switch (request.op) {
|
|
503
|
-
case 'hello': return this.hello(request.protocol);
|
|
548
|
+
case 'hello': return this.hello(connection, request.protocol, request.features);
|
|
504
549
|
case 'query':
|
|
505
|
-
case 'run': return this.statement(connection, request.op, request.sql, request.params, request.txId);
|
|
506
|
-
case 'statement': return this.unifiedStatement(connection, request.sql, request.params, request.txId);
|
|
550
|
+
case 'run': return this.statement(connection, request.op, request.sql, request.params, request.txId, db);
|
|
551
|
+
case 'statement': return this.unifiedStatement(connection, request.sql, request.params, request.txId, db);
|
|
507
552
|
case 'exec': return this.exec(connection, request.sql, request.txId);
|
|
508
553
|
case 'batch': return this.batch(connection, request.statements);
|
|
509
554
|
case 'begin': return this.begin(connection, request.mode ?? 'deferred', request.leaseMs);
|
|
@@ -540,11 +585,12 @@ export class SqlegoServer {
|
|
|
540
585
|
return Result.ok(result);
|
|
541
586
|
}
|
|
542
587
|
|
|
543
|
-
private hello(protocol: number) {
|
|
588
|
+
private hello(connection: Connection, protocol: number, features: readonly string[] = []) {
|
|
544
589
|
if (protocol !== PROTOCOL_VERSION) {
|
|
545
590
|
return Result.err({ kind: 'protocol-mismatch', message: `server speaks protocol ${PROTOCOL_VERSION}, client sent ${protocol}` });
|
|
546
591
|
}
|
|
547
|
-
|
|
592
|
+
if (this.reader && features.includes('detached-plain')) connection.detachedPlain = true;
|
|
593
|
+
const hello: HelloResult = { serverVersion: VERSION, protocol: PROTOCOL_VERSION, file: this.paths.file, pid: process.pid, pragmas: this.pragmas, capabilities: this.capabilities };
|
|
548
594
|
return Result.ok(hello);
|
|
549
595
|
}
|
|
550
596
|
|
|
@@ -554,8 +600,8 @@ export class SqlegoServer {
|
|
|
554
600
|
* statements. Inside one, savepoints are SQL but the transaction itself ends
|
|
555
601
|
* only through `commit`/`rollback`, so the server always knows its state.
|
|
556
602
|
*/
|
|
557
|
-
private statement(connection: Connection, op: 'query' | 'run', sql: string, params: SqlParams | undefined, txId: number | undefined) {
|
|
558
|
-
return this.scoped<QueryResult | RunResult, SqliteFailure>(connection, op, txId, [transactionControl(sql)], () => this.runStatement(op, sql, params));
|
|
603
|
+
private statement(connection: Connection, op: 'query' | 'run', sql: string, params: SqlParams | undefined, txId: number | undefined, db = this.db) {
|
|
604
|
+
return this.scoped<QueryResult | RunResult, SqliteFailure>(connection, op, txId, [transactionControl(sql)], () => this.runStatement(op, sql, params, db), db);
|
|
559
605
|
}
|
|
560
606
|
|
|
561
607
|
/**
|
|
@@ -563,12 +609,12 @@ export class SqlegoServer {
|
|
|
563
609
|
* be silently ignored by prepare), under the same transaction-control rules
|
|
564
610
|
* as `query`/`run`.
|
|
565
611
|
*/
|
|
566
|
-
private unifiedStatement(connection: Connection, sql: string, params: SqlParams | undefined, txId: number | undefined) {
|
|
612
|
+
private unifiedStatement(connection: Connection, sql: string, params: SqlParams | undefined, txId: number | undefined, db = this.db) {
|
|
567
613
|
const pieces = splitSqlStatements(sql);
|
|
568
614
|
if (pieces.length === 0) return badRequest('statement needs one SQL statement; the text has none');
|
|
569
615
|
if (pieces.length > 1) return badRequest(`statement takes one SQL statement, the text has ${pieces.length}: use exec for several`);
|
|
570
616
|
const piece = pieces[0];
|
|
571
|
-
return this.scoped<StatementWireResult, SqliteFailure | EncodeFailure>(connection, 'statement', txId, [transactionControl(piece)], () => this.encodeExecuted(this.executeOne(piece, params)));
|
|
617
|
+
return this.scoped<StatementWireResult, SqliteFailure | EncodeFailure>(connection, 'statement', txId, [transactionControl(piece)], () => this.encodeExecuted(this.executeOne(piece, params, db)), db);
|
|
572
618
|
}
|
|
573
619
|
|
|
574
620
|
/**
|
|
@@ -589,14 +635,14 @@ export class SqlegoServer {
|
|
|
589
635
|
* the transaction closed when SQLite aborted it). Outside a transaction,
|
|
590
636
|
* work that somehow left one open is rolled back and reported.
|
|
591
637
|
*/
|
|
592
|
-
private scoped<T, E>(connection: Connection, op: string, txId: number | undefined, controls: readonly TxControl[], work: () => Result<T, E
|
|
638
|
+
private scoped<T, E>(connection: Connection, op: string, txId: number | undefined, controls: readonly TxControl[], work: () => Result<T, E>, db = this.db) {
|
|
593
639
|
if (txId === undefined) {
|
|
594
640
|
const refused = refuseControl(controls, op, undefined);
|
|
595
641
|
if (!refused.ok) return refused;
|
|
596
|
-
const wasInTransaction =
|
|
642
|
+
const wasInTransaction = db.inTransaction;
|
|
597
643
|
const outcome = work();
|
|
598
|
-
if (!wasInTransaction &&
|
|
599
|
-
const rolledBack = Trust.try(() =>
|
|
644
|
+
if (!wasInTransaction && db.inTransaction) {
|
|
645
|
+
const rolledBack = Trust.try(() => db.exec('ROLLBACK'), sqliteFailure);
|
|
600
646
|
if (!rolledBack.ok && rolledBack.error.kind === 'sqlite') this.log('rollback failed', { op, error: rolledBack.error.message });
|
|
601
647
|
return Result.err<SqliteFailure>({ kind: 'sqlite', message: `${op} left a transaction open, which only begin may do; it was rolled back` });
|
|
602
648
|
}
|
|
@@ -611,8 +657,8 @@ export class SqlegoServer {
|
|
|
611
657
|
return outcome;
|
|
612
658
|
}
|
|
613
659
|
|
|
614
|
-
private runStatement(op: 'query' | 'run', sql: string, params: SqlParams | undefined) {
|
|
615
|
-
return op === 'query' ? this.query(sql, params) : this.run(sql, params);
|
|
660
|
+
private runStatement(op: 'query' | 'run', sql: string, params: SqlParams | undefined, db = this.db) {
|
|
661
|
+
return op === 'query' ? this.query(sql, params, db) : this.run(sql, params, db);
|
|
616
662
|
}
|
|
617
663
|
|
|
618
664
|
/** SQLite aborts a transaction by itself on some errors; the server must not believe it is still open. */
|
|
@@ -624,10 +670,10 @@ export class SqlegoServer {
|
|
|
624
670
|
this.renewLease(open);
|
|
625
671
|
}
|
|
626
672
|
|
|
627
|
-
private query(sql: string, params?: SqlParams) {
|
|
673
|
+
private query(sql: string, params?: SqlParams, db = this.db) {
|
|
628
674
|
const fetched = Trust.try(
|
|
629
675
|
(): unknown => {
|
|
630
|
-
const statement =
|
|
676
|
+
const statement = db.query(sql);
|
|
631
677
|
return params === undefined ? statement.all() : statement.all(...bindings(params));
|
|
632
678
|
},
|
|
633
679
|
sqliteFailure,
|
|
@@ -639,13 +685,15 @@ export class SqlegoServer {
|
|
|
639
685
|
return Result.ok(result);
|
|
640
686
|
}
|
|
641
687
|
|
|
642
|
-
private run(sql: string, params?: SqlParams) {
|
|
688
|
+
private run(sql: string, params?: SqlParams, db = this.db) {
|
|
643
689
|
return Trust.try(
|
|
644
690
|
() => {
|
|
645
|
-
const statement =
|
|
691
|
+
const statement = db.query(sql);
|
|
646
692
|
const outcome = params === undefined ? statement.run() : statement.run(...bindings(params));
|
|
647
693
|
// safeIntegers may report either counter as bigint; `run` keeps answering with numbers.
|
|
648
|
-
const result: RunResult =
|
|
694
|
+
const result: RunResult = db === this.reader
|
|
695
|
+
? { changes: 0, lastInsertRowid: 0 }
|
|
696
|
+
: { changes: Number(outcome.changes), lastInsertRowid: outcome.lastInsertRowid };
|
|
649
697
|
return result;
|
|
650
698
|
},
|
|
651
699
|
sqliteFailure,
|
|
@@ -660,10 +708,10 @@ export class SqlegoServer {
|
|
|
660
708
|
* (`total_changes()` moved), else 0 — `changes()` alone would repeat the
|
|
661
709
|
* previous write's count after a read or DDL.
|
|
662
710
|
*/
|
|
663
|
-
private executeOne(sql: string, params: SqlParams | undefined) {
|
|
664
|
-
const before = this.counters();
|
|
711
|
+
private executeOne(sql: string, params: SqlParams | undefined, db = this.db) {
|
|
712
|
+
const before = this.counters(db);
|
|
665
713
|
if (!before.ok) return before;
|
|
666
|
-
const prepared = Trust.try(() =>
|
|
714
|
+
const prepared = Trust.try(() => db.prepare(sql), sqliteFailure);
|
|
667
715
|
if (!prepared.ok) return prepared;
|
|
668
716
|
const statement = prepared.value;
|
|
669
717
|
const args: SQLQueryBindings[] = params === undefined ? [] : bindings(params);
|
|
@@ -684,20 +732,20 @@ export class SqlegoServer {
|
|
|
684
732
|
const finalized = Trust.try(() => statement.finalize(), sqliteFailure);
|
|
685
733
|
if (!finalized.ok && finalized.error.kind === 'sqlite') this.log('finalize failed', { error: finalized.error.message });
|
|
686
734
|
if (!ran.ok) return ran;
|
|
687
|
-
const after = this.counters();
|
|
735
|
+
const after = this.counters(db);
|
|
688
736
|
if (!after.ok) return after;
|
|
689
737
|
const executed: Executed = {
|
|
690
738
|
reader: ran.value.reader,
|
|
691
739
|
rows: ran.value.rows,
|
|
692
|
-
changes: after.value.total === before.value.total ? 0 : after.value.changes,
|
|
693
|
-
lastInsertRowid: after.value.lastInsertRowid,
|
|
740
|
+
changes: db === this.reader || after.value.total === before.value.total ? 0 : after.value.changes,
|
|
741
|
+
lastInsertRowid: db === this.reader ? 0 : after.value.lastInsertRowid,
|
|
694
742
|
};
|
|
695
743
|
return Result.ok(executed);
|
|
696
744
|
}
|
|
697
745
|
|
|
698
|
-
private counters() {
|
|
746
|
+
private counters(db = this.db) {
|
|
699
747
|
const read = Trust.try(
|
|
700
|
-
(): unknown =>
|
|
748
|
+
(): unknown => db.query('SELECT changes() AS changes, total_changes() AS total, last_insert_rowid() AS rowid').get(),
|
|
701
749
|
sqliteFailure,
|
|
702
750
|
);
|
|
703
751
|
if (!read.ok) return read;
|