@noego/sqlego 0.1.2-dev.1 → 0.1.2-dev.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +125 -26
- package/bin/sqlego.cjs +49 -11
- package/dist/binary.d.ts +47 -0
- package/dist/client.d.ts +16 -10
- package/dist/index.d.ts +2 -1
- package/dist/index.js +160 -63
- package/dist/protocol.d.ts +14 -9
- package/package.json +10 -2
- package/src/binary.ts +89 -0
- package/src/client.ts +62 -29
- package/src/index.ts +4 -1
- package/src/protocol.ts +21 -7
- package/src/server.ts +103 -55
- package/bin/sqlego +0 -4
package/src/client.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { closeSync, openSync, readdirSync, readFileSync, rmSync, writeSync, existsSync } from 'node:fs';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
3
4
|
import net from 'node:net';
|
|
4
5
|
import path from 'node:path';
|
|
5
6
|
import { fileURLToPath } from 'node:url';
|
|
6
7
|
import { Result, Trust } from '@noego/trust';
|
|
8
|
+
import { locateServerBinary, type BinaryMissing } from './binary.ts';
|
|
7
9
|
import {
|
|
8
10
|
PROTOCOL_VERSION,
|
|
9
11
|
encodeRequestFrame,
|
|
@@ -194,6 +196,15 @@ export class SqlegoClient {
|
|
|
194
196
|
return unwrap(Result.err({ kind: 'not-connected', message: 'client is not connected' }));
|
|
195
197
|
}
|
|
196
198
|
|
|
199
|
+
/** Opt this socket into committed-snapshot plain reads and queued plain writes. */
|
|
200
|
+
async enableDetachedPlain(): Promise<boolean> {
|
|
201
|
+
if (!this.server.capabilities.includes('detached-plain')) return false;
|
|
202
|
+
this.hello = unwrap(await this.call({
|
|
203
|
+
op: 'hello', clientVersion: VERSION, protocol: PROTOCOL_VERSION, features: ['detached-plain'],
|
|
204
|
+
}, parseHelloResult));
|
|
205
|
+
return this.hello.capabilities.includes('detached-plain');
|
|
206
|
+
}
|
|
207
|
+
|
|
197
208
|
async query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]> {
|
|
198
209
|
const result = unwrap(await this.call({ op: 'query', sql, params }, parseQueryResult));
|
|
199
210
|
return callerRows<Row>(result.rows);
|
|
@@ -509,7 +520,9 @@ export class SqlegoClient {
|
|
|
509
520
|
}
|
|
510
521
|
|
|
511
522
|
private spawnServer() {
|
|
512
|
-
const
|
|
523
|
+
const resolved = this.options.serverCommand ? Result.ok(this.options.serverCommand) : resolveServerCommand();
|
|
524
|
+
if (!resolved.ok) return resolved;
|
|
525
|
+
const [command, ...args] = resolved.value;
|
|
513
526
|
const pragmaArgs = (this.options.serverPragmas ?? []).flatMap((pragma) => ['--pragma', pragma]);
|
|
514
527
|
return Trust.try(
|
|
515
528
|
() => {
|
|
@@ -765,48 +778,68 @@ function savepointName(name: string): string {
|
|
|
765
778
|
}
|
|
766
779
|
|
|
767
780
|
/**
|
|
768
|
-
*
|
|
769
|
-
*
|
|
770
|
-
*
|
|
781
|
+
* How to start a server, or why there is no way to:
|
|
782
|
+
* 1. `SQLEGO_BIN`, when set;
|
|
783
|
+
* 2. under Bun only — this very process when it is the compiled `sqlego`
|
|
784
|
+
* binary, or the source entry (`bun src/cli.ts`) when running from
|
|
785
|
+
* source; both run on the host by definition;
|
|
786
|
+
* 3. the platform package `@noego/sqlego-<platform>-<arch>`;
|
|
787
|
+
* 4. a local `bin/sqlego-<platform>-<arch>[.exe]` build.
|
|
788
|
+
* Nothing else: not an unqualified `bin/sqlego` (in 0.1.2-dev.0 and earlier
|
|
789
|
+
* that was the publisher's darwin-arm64 build, wrong on every other host),
|
|
790
|
+
* not `sqlego` on PATH. See `locateServerBinary` for 1, 3 and 4.
|
|
771
791
|
*/
|
|
772
|
-
export function
|
|
773
|
-
const suffix = platform === 'win32' ? '.exe' : '';
|
|
774
|
-
return [`sqlego${suffix}`, `sqlego-${platform}-${arch}${suffix}`];
|
|
775
|
-
}
|
|
776
|
-
|
|
777
|
-
/**
|
|
778
|
-
* How to start a server: SQLEGO_BIN if set; the compiled `sqlego` binary when
|
|
779
|
-
* running as one; the dev entry (`bun src/cli.ts`) when running from source
|
|
780
|
-
* under Bun; the binary for this platform in the package's `bin/`; else
|
|
781
|
-
* `sqlego` on PATH.
|
|
782
|
-
*/
|
|
783
|
-
export function defaultServerCommand(): readonly string[] {
|
|
792
|
+
export function resolveServerCommand(): Result<readonly string[], BinaryMissing> {
|
|
784
793
|
const configured = process.env.SQLEGO_BIN;
|
|
785
|
-
if (configured && configured.length > 0) return [configured];
|
|
786
|
-
const entry = process.argv[1] ?? '';
|
|
794
|
+
if (configured && configured.length > 0) return Result.ok([configured]);
|
|
787
795
|
const located = Trust.try(
|
|
788
796
|
() => path.dirname(fileURLToPath(import.meta.url)),
|
|
789
797
|
(cause) => ({ kind: 'module-path' as const, message: errorMessage(cause) }),
|
|
790
798
|
);
|
|
791
|
-
// A module that cannot locate itself has no sibling cli.ts or bin/ to offer.
|
|
799
|
+
// A module that cannot locate itself has no sibling cli.ts, package or bin/ to offer.
|
|
792
800
|
let here: string | null = null;
|
|
793
801
|
if (located.ok) here = located.value;
|
|
794
802
|
else if (located.error.kind === 'module-path') here = null;
|
|
795
803
|
if (process.versions.bun) {
|
|
796
|
-
|
|
804
|
+
const entry = process.argv[1] ?? '';
|
|
805
|
+
if (path.basename(process.execPath).startsWith('sqlego')) return Result.ok([process.execPath]);
|
|
806
|
+
if (entry.endsWith('cli.ts')) return Result.ok([process.execPath, entry]);
|
|
797
807
|
if (entry.endsWith('.ts') && here !== null) {
|
|
798
808
|
const cli = path.join(here, 'cli.ts');
|
|
799
|
-
if (existsSync(cli)) return [process.execPath, cli];
|
|
800
|
-
}
|
|
801
|
-
if (!entry.endsWith('.js') && !entry.endsWith('.ts')) return [process.execPath];
|
|
802
|
-
}
|
|
803
|
-
if (here !== null) {
|
|
804
|
-
for (const name of platformBinaryNames()) {
|
|
805
|
-
const local = path.join(here, '..', 'bin', name);
|
|
806
|
-
if (existsSync(local)) return [local];
|
|
809
|
+
if (existsSync(cli)) return Result.ok([process.execPath, cli]);
|
|
807
810
|
}
|
|
808
811
|
}
|
|
809
|
-
|
|
812
|
+
const binary = locateServerBinary({
|
|
813
|
+
platform: process.platform,
|
|
814
|
+
arch: process.arch,
|
|
815
|
+
configured: undefined,
|
|
816
|
+
resolvePackageJson: (name) => resolvePackageJson(name, here),
|
|
817
|
+
exists: existsSync,
|
|
818
|
+
localBinDirectory: here === null ? null : path.join(here, '..', 'bin'),
|
|
819
|
+
});
|
|
820
|
+
if (!binary.ok) return binary;
|
|
821
|
+
return Result.ok([binary.value]);
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/** Public, exception-based form of `resolveServerCommand`: throws an Error naming what to install or set. */
|
|
825
|
+
export function defaultServerCommand(): readonly string[] {
|
|
826
|
+
const command = resolveServerCommand();
|
|
827
|
+
if (command.ok) return command.value;
|
|
828
|
+
//trust:accept public API contract: defaultServerCommand throws an Error when no server binary can be found
|
|
829
|
+
throw new Error(command.error.message);
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/** A package's `package.json`, resolved the way Node resolves an import from this module; null when not installed. */
|
|
833
|
+
function resolvePackageJson(name: string, here: string | null): string | null {
|
|
834
|
+
if (here === null) return null;
|
|
835
|
+
const resolved = Trust.try(
|
|
836
|
+
(): unknown => createRequire(path.join(here, 'index.js')).resolve(`${name}/package.json`),
|
|
837
|
+
(cause) => ({ kind: 'not-installed' as const, message: errorMessage(cause) }),
|
|
838
|
+
);
|
|
839
|
+
if (resolved.ok) return typeof resolved.value === 'string' ? resolved.value : null;
|
|
840
|
+
if (resolved.error.kind === 'not-installed') return null;
|
|
841
|
+
const unhandled: never = resolved.error.kind;
|
|
842
|
+
return unhandled;
|
|
810
843
|
}
|
|
811
844
|
|
|
812
845
|
/** Why a one-shot request to another owner got no result: the transport, or the owner's own error reply. */
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
export {
|
|
2
|
-
DEFAULT_MAX_OWNERS, SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand,
|
|
2
|
+
DEFAULT_MAX_OWNERS, SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, type BeginOptions, type ClientOptions,
|
|
3
3
|
} from './client.ts';
|
|
4
|
+
export {
|
|
5
|
+
SUPPORTED_PLATFORMS, binaryFileName, localBinaryName, locateServerBinary, platformPackageName, unpackedAsarPath, type BinaryLookup,
|
|
6
|
+
} from './binary.ts';
|
|
4
7
|
export { USES_NAMED_PIPES, isNamedPipe, pathsFor, runtimeDirectory, canonicalFile, type FilePaths, type ServerMeta } from './paths.ts';
|
|
5
8
|
export {
|
|
6
9
|
PROTOCOL_VERSION,
|
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;
|
package/bin/sqlego
DELETED