@noego/sqlego 0.0.0-stage → 0.0.1-dev.0
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 +81 -2
- package/bin/sqlego +4 -0
- package/dist/client.d.ts +75 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +751 -0
- package/dist/paths.d.ts +70 -0
- package/dist/protocol.d.ts +218 -0
- package/dist/version.d.ts +23 -0
- package/package.json +43 -4
- package/src/cli.ts +310 -0
- package/src/client.ts +497 -0
- package/src/index.ts +15 -0
- package/src/paths.ts +154 -0
- package/src/protocol.ts +370 -0
- package/src/server.ts +413 -0
- package/src/version.ts +78 -0
package/dist/paths.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { Result } from '@noego/trust';
|
|
2
|
+
/**
|
|
3
|
+
* Where a file's socket, lock, and meta live. Never beside the database:
|
|
4
|
+
* Unix socket paths cap at 104 bytes on macOS and application-support paths
|
|
5
|
+
* already exceed that. The runtime dir is short and per-user.
|
|
6
|
+
*
|
|
7
|
+
* Override with SQLEGO_RUNTIME_DIR (tests use a scratch dir).
|
|
8
|
+
*/
|
|
9
|
+
export declare function resolveRuntimeDirectory(): import("@noego/trust").Ok<string> | import("@noego/trust").Err<{
|
|
10
|
+
kind: "runtime-directory";
|
|
11
|
+
message: string;
|
|
12
|
+
}>;
|
|
13
|
+
/** Canonical absolute path of the database; the identity every client and server agree on. */
|
|
14
|
+
export declare function resolveCanonicalFile(file: string): Result<string, {
|
|
15
|
+
kind: "canonical-path";
|
|
16
|
+
message: string;
|
|
17
|
+
}>;
|
|
18
|
+
export type FilePaths = Readonly<{
|
|
19
|
+
file: string;
|
|
20
|
+
key: string;
|
|
21
|
+
socket: string;
|
|
22
|
+
lock: string;
|
|
23
|
+
meta: string;
|
|
24
|
+
}>;
|
|
25
|
+
export declare function resolvePaths(file: string): import("@noego/trust").Err<{
|
|
26
|
+
kind: "runtime-directory";
|
|
27
|
+
message: string;
|
|
28
|
+
}> | import("@noego/trust").Err<{
|
|
29
|
+
kind: "canonical-path";
|
|
30
|
+
message: string;
|
|
31
|
+
}> | import("@noego/trust").Err<{
|
|
32
|
+
kind: "hash-failed";
|
|
33
|
+
message: string;
|
|
34
|
+
}> | import("@noego/trust").Err<{
|
|
35
|
+
kind: "socket-path-too-long";
|
|
36
|
+
message: string;
|
|
37
|
+
}> | import("@noego/trust").Ok<Readonly<{
|
|
38
|
+
file: string;
|
|
39
|
+
key: string;
|
|
40
|
+
socket: string;
|
|
41
|
+
lock: string;
|
|
42
|
+
meta: string;
|
|
43
|
+
}>>;
|
|
44
|
+
/** Public, exception-based form of `resolveRuntimeDirectory`. */
|
|
45
|
+
export declare function runtimeDirectory(): string;
|
|
46
|
+
/** Public, exception-based form of `resolveCanonicalFile`. */
|
|
47
|
+
export declare function canonicalFile(file: string): string;
|
|
48
|
+
/** Public, exception-based form of `resolvePaths`. */
|
|
49
|
+
export declare function pathsFor(file: string): FilePaths;
|
|
50
|
+
/** Written by the server once it is listening; read by `sqlego ls` and status. */
|
|
51
|
+
export type ServerMeta = Readonly<{
|
|
52
|
+
file: string;
|
|
53
|
+
socket: string;
|
|
54
|
+
pid: number;
|
|
55
|
+
serverVersion: string;
|
|
56
|
+
startedAt: number;
|
|
57
|
+
}>;
|
|
58
|
+
/** A meta file's parsed JSON; another process wrote it, so every field is checked. */
|
|
59
|
+
export declare function parseServerMeta(input: unknown): import("@noego/trust").Err<{
|
|
60
|
+
kind: "invalid";
|
|
61
|
+
message: string;
|
|
62
|
+
}> | import("@noego/trust").Ok<Readonly<{
|
|
63
|
+
file: string;
|
|
64
|
+
socket: string;
|
|
65
|
+
pid: number;
|
|
66
|
+
serverVersion: string;
|
|
67
|
+
startedAt: number;
|
|
68
|
+
}>>;
|
|
69
|
+
/** Signal 0 probes without signalling: EPERM means alive but not ours, anything else means gone. */
|
|
70
|
+
export declare function isProcessAlive(pid: number): boolean;
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* sqlego wire protocol: newline-delimited JSON over a local socket.
|
|
3
|
+
*
|
|
4
|
+
* One request per line, one response per line, correlated by `id`. The server
|
|
5
|
+
* executes requests in arrival order on its single connection to the file, so
|
|
6
|
+
* two clients' statements interleave at statement (or batch) granularity and
|
|
7
|
+
* never contend for SQLite's write lock.
|
|
8
|
+
*
|
|
9
|
+
* There is deliberately no BEGIN/COMMIT over the wire: a client-held
|
|
10
|
+
* transaction would hold the file's only writer hostage to that client's
|
|
11
|
+
* liveness. `batch` is the transactional unit.
|
|
12
|
+
*/
|
|
13
|
+
import { Result } from '@noego/trust';
|
|
14
|
+
export declare const PROTOCOL_VERSION = 1;
|
|
15
|
+
export type SqlParams = ReadonlyArray<SqlValue> | Readonly<Record<string, SqlValue>>;
|
|
16
|
+
export type SqlValue = string | number | bigint | boolean | null | Uint8Array;
|
|
17
|
+
export type SqlRow = Record<string, unknown>;
|
|
18
|
+
export type Statement = Readonly<{
|
|
19
|
+
sql: string;
|
|
20
|
+
params?: SqlParams;
|
|
21
|
+
/** `query` returns rows; `run` returns the change count. Default `run`. */
|
|
22
|
+
mode?: 'query' | 'run';
|
|
23
|
+
}>;
|
|
24
|
+
export type Request = {
|
|
25
|
+
id: number;
|
|
26
|
+
op: 'hello';
|
|
27
|
+
clientVersion: string;
|
|
28
|
+
protocol: number;
|
|
29
|
+
} | {
|
|
30
|
+
id: number;
|
|
31
|
+
op: 'query';
|
|
32
|
+
sql: string;
|
|
33
|
+
params?: SqlParams;
|
|
34
|
+
} | {
|
|
35
|
+
id: number;
|
|
36
|
+
op: 'run';
|
|
37
|
+
sql: string;
|
|
38
|
+
params?: SqlParams;
|
|
39
|
+
} | {
|
|
40
|
+
id: number;
|
|
41
|
+
op: 'batch';
|
|
42
|
+
statements: readonly Statement[];
|
|
43
|
+
} | {
|
|
44
|
+
id: number;
|
|
45
|
+
op: 'status';
|
|
46
|
+
} | {
|
|
47
|
+
id: number;
|
|
48
|
+
op: 'stop';
|
|
49
|
+
};
|
|
50
|
+
export type RunResult = Readonly<{
|
|
51
|
+
changes: number;
|
|
52
|
+
lastInsertRowid: number | bigint;
|
|
53
|
+
}>;
|
|
54
|
+
export type QueryResult = Readonly<{
|
|
55
|
+
rows: SqlRow[];
|
|
56
|
+
}>;
|
|
57
|
+
export type BatchResult = Readonly<{
|
|
58
|
+
results: ReadonlyArray<RunResult | QueryResult>;
|
|
59
|
+
}>;
|
|
60
|
+
export type HelloResult = Readonly<{
|
|
61
|
+
serverVersion: string;
|
|
62
|
+
protocol: number;
|
|
63
|
+
file: string;
|
|
64
|
+
pid: number;
|
|
65
|
+
}>;
|
|
66
|
+
export type StatusResult = Readonly<{
|
|
67
|
+
file: string;
|
|
68
|
+
socket: string;
|
|
69
|
+
pid: number;
|
|
70
|
+
serverVersion: string;
|
|
71
|
+
protocol: number;
|
|
72
|
+
clients: number;
|
|
73
|
+
uptimeMs: number;
|
|
74
|
+
idleMs: number | null;
|
|
75
|
+
idleTimeoutMs: number;
|
|
76
|
+
requestsServed: number;
|
|
77
|
+
}>;
|
|
78
|
+
export type ErrorCode = 'sqlite' | 'bad-request' | 'protocol-mismatch' | 'shutting-down'
|
|
79
|
+
/** The server could not serialize a result (a value JSON cannot hold). */
|
|
80
|
+
| 'encode-failed';
|
|
81
|
+
export type Response = {
|
|
82
|
+
id: number;
|
|
83
|
+
ok: true;
|
|
84
|
+
result: unknown;
|
|
85
|
+
} | {
|
|
86
|
+
id: number;
|
|
87
|
+
ok: false;
|
|
88
|
+
error: {
|
|
89
|
+
code: ErrorCode;
|
|
90
|
+
message: string;
|
|
91
|
+
};
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* JSON text of a value. `JSON.stringify` is declared `string` but returns
|
|
95
|
+
* `undefined` for `undefined`, a function or a symbol, and throws on a cycle
|
|
96
|
+
* or a `toJSON` that throws; both are this one failure.
|
|
97
|
+
*/
|
|
98
|
+
export declare function toJson(value: unknown, indent?: number): import("@noego/trust").Err<{
|
|
99
|
+
kind: "encode-failed";
|
|
100
|
+
message: string;
|
|
101
|
+
}> | import("@noego/trust").Ok<string>;
|
|
102
|
+
/** One frame: the message's JSON and the newline that ends it. */
|
|
103
|
+
export declare function encodeFrame(message: Request | Response): import("@noego/trust").Err<{
|
|
104
|
+
kind: "encode-failed";
|
|
105
|
+
message: string;
|
|
106
|
+
}> | import("@noego/trust").Ok<string>;
|
|
107
|
+
/** Parses JSON text into `unknown`; what it holds is for a validator to decide. */
|
|
108
|
+
export declare function fromJson(text: string): Result<unknown, {
|
|
109
|
+
kind: "invalid";
|
|
110
|
+
message: string;
|
|
111
|
+
}>;
|
|
112
|
+
/** A value that survives JSON and SQLite binding: string, number, boolean or null. */
|
|
113
|
+
export declare function parseSqlValue(input: unknown): import("@noego/trust").Ok<SqlValue> | import("@noego/trust").Err<Readonly<{
|
|
114
|
+
kind: "invalid";
|
|
115
|
+
message: string;
|
|
116
|
+
}>>;
|
|
117
|
+
/** Positional (`[...]`) or named (`{ name: value }`) parameters. */
|
|
118
|
+
export declare function parseSqlParams(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
119
|
+
kind: "invalid";
|
|
120
|
+
message: string;
|
|
121
|
+
}>> | import("@noego/trust").Ok<SqlParams>;
|
|
122
|
+
/**
|
|
123
|
+
* A request frame. The failure carries the request's `id` when it had a
|
|
124
|
+
* numeric one, so the server can answer the request that was malformed.
|
|
125
|
+
*/
|
|
126
|
+
export declare function parseRequest(input: unknown): import("@noego/trust").Err<{
|
|
127
|
+
kind: "invalid";
|
|
128
|
+
id: number;
|
|
129
|
+
message: string;
|
|
130
|
+
}> | import("@noego/trust").Ok<Request>;
|
|
131
|
+
/** A response frame; `result` stays `unknown` until the parser for its op has seen it. */
|
|
132
|
+
export declare function parseResponse(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
133
|
+
kind: "invalid";
|
|
134
|
+
message: string;
|
|
135
|
+
}>> | import("@noego/trust").Ok<{
|
|
136
|
+
id: number;
|
|
137
|
+
ok: true;
|
|
138
|
+
result: unknown;
|
|
139
|
+
}> | import("@noego/trust").Ok<{
|
|
140
|
+
id: number;
|
|
141
|
+
ok: false;
|
|
142
|
+
error: {
|
|
143
|
+
code: ErrorCode;
|
|
144
|
+
message: string;
|
|
145
|
+
};
|
|
146
|
+
}>;
|
|
147
|
+
export declare function parseRow(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
148
|
+
kind: "invalid";
|
|
149
|
+
message: string;
|
|
150
|
+
}>> | import("@noego/trust").Ok<SqlRow>;
|
|
151
|
+
export declare function parseRows(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
152
|
+
kind: "invalid";
|
|
153
|
+
message: string;
|
|
154
|
+
}>> | import("@noego/trust").Ok<SqlRow[]>;
|
|
155
|
+
export declare function parseQueryResult(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
156
|
+
kind: "invalid";
|
|
157
|
+
message: string;
|
|
158
|
+
}>> | import("@noego/trust").Ok<Readonly<{
|
|
159
|
+
rows: SqlRow[];
|
|
160
|
+
}>>;
|
|
161
|
+
export declare function parseRunResult(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
162
|
+
kind: "invalid";
|
|
163
|
+
message: string;
|
|
164
|
+
}>> | import("@noego/trust").Ok<Readonly<{
|
|
165
|
+
changes: number;
|
|
166
|
+
lastInsertRowid: number | bigint;
|
|
167
|
+
}>>;
|
|
168
|
+
export declare function parseBatchResult(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
169
|
+
kind: "invalid";
|
|
170
|
+
message: string;
|
|
171
|
+
}>> | import("@noego/trust").Ok<Readonly<{
|
|
172
|
+
results: ReadonlyArray<RunResult | QueryResult>;
|
|
173
|
+
}>>;
|
|
174
|
+
export declare function parseHelloResult(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
175
|
+
kind: "invalid";
|
|
176
|
+
message: string;
|
|
177
|
+
}>> | import("@noego/trust").Ok<Readonly<{
|
|
178
|
+
serverVersion: string;
|
|
179
|
+
protocol: number;
|
|
180
|
+
file: string;
|
|
181
|
+
pid: number;
|
|
182
|
+
}>>;
|
|
183
|
+
export declare function parseStatusResult(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
184
|
+
kind: "invalid";
|
|
185
|
+
message: string;
|
|
186
|
+
}>> | import("@noego/trust").Ok<Readonly<{
|
|
187
|
+
file: string;
|
|
188
|
+
socket: string;
|
|
189
|
+
pid: number;
|
|
190
|
+
serverVersion: string;
|
|
191
|
+
protocol: number;
|
|
192
|
+
clients: number;
|
|
193
|
+
uptimeMs: number;
|
|
194
|
+
idleMs: number | null;
|
|
195
|
+
idleTimeoutMs: number;
|
|
196
|
+
requestsServed: number;
|
|
197
|
+
}>>;
|
|
198
|
+
export declare function parseStopResult(input: unknown): import("@noego/trust").Err<Readonly<{
|
|
199
|
+
kind: "invalid";
|
|
200
|
+
message: string;
|
|
201
|
+
}>> | import("@noego/trust").Ok<{
|
|
202
|
+
stopping: true;
|
|
203
|
+
}>;
|
|
204
|
+
/**
|
|
205
|
+
* The `code` of a thrown Node error (`EEXIST`, `EPERM`, ...), or undefined.
|
|
206
|
+
* Read through `in` on `unknown`, so nothing about the error is assumed.
|
|
207
|
+
*/
|
|
208
|
+
export declare function errnoCode(cause: unknown): unknown;
|
|
209
|
+
/** The message of a caught value, whatever was thrown. */
|
|
210
|
+
export declare function errorMessage(cause: unknown): string;
|
|
211
|
+
/**
|
|
212
|
+
* Splits accumulated socket bytes into complete frames; returns the frames
|
|
213
|
+
* and the unterminated remainder to carry into the next chunk.
|
|
214
|
+
*/
|
|
215
|
+
export declare function splitFrames(buffer: string): {
|
|
216
|
+
frames: string[];
|
|
217
|
+
rest: string;
|
|
218
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Result } from '@noego/trust';
|
|
2
|
+
/**
|
|
3
|
+
* Hash of every `src/*.ts` file, so the two artifacts built from one tree
|
|
4
|
+
* (Node client in dist/, Bun server in bin/) and a source run agree, while any
|
|
5
|
+
* edit yields a new id. `source` when the tree is not there.
|
|
6
|
+
*/
|
|
7
|
+
export declare function sourceBuildId(sourceDirectory: string): Result<string, {
|
|
8
|
+
kind: "source-unreadable";
|
|
9
|
+
message: string;
|
|
10
|
+
}>;
|
|
11
|
+
/** Exception-based form of `sourceBuildId` for the build script, which must stop on an unreadable tree. */
|
|
12
|
+
export declare function computeSourceBuildId(sourceDirectory: string): string;
|
|
13
|
+
/** Build identity of this artifact: the source hash it was built from. */
|
|
14
|
+
export declare const BUILD_ID: string;
|
|
15
|
+
/**
|
|
16
|
+
* What the client/server handshake compares: `<package version>+<build id>`.
|
|
17
|
+
* A rebuilt binary or dist — even at an unchanged package version — therefore
|
|
18
|
+
* retires owners started from the previous build instead of leaving stale
|
|
19
|
+
* code serving (2026-09-04: a framing fix shipped under the same version and
|
|
20
|
+
* the old owners kept running until stopped by hand).
|
|
21
|
+
* `SQLEGO_VERSION_OVERRIDE` lets a test start a deliberately stale server.
|
|
22
|
+
*/
|
|
23
|
+
export declare const VERSION: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noego/sqlego",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1-dev.0",
|
|
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
|
+
"type": "module",
|
|
6
|
+
"license": "ISC",
|
|
7
|
+
"author": "Shavauhn Gabay",
|
|
8
|
+
"bin": {
|
|
9
|
+
"sqlego": "./bin/sqlego"
|
|
10
|
+
},
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"bun": "./src/index.ts",
|
|
17
|
+
"import": "./dist/index.js",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./package.json": "./package.json"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"src",
|
|
24
|
+
"dist",
|
|
25
|
+
"bin",
|
|
26
|
+
"README.md"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"prepare": "bun scripts/build.ts all",
|
|
30
|
+
"build": "bun scripts/build.ts all",
|
|
31
|
+
"build:lib": "bun scripts/build.ts lib",
|
|
32
|
+
"build:bin": "bun scripts/build.ts bin",
|
|
33
|
+
"typecheck": "bunx tsc --noEmit",
|
|
34
|
+
"trust": "trust check src",
|
|
35
|
+
"test": "bun test"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@types/bun": "^1.2.0",
|
|
39
|
+
"@types/node": "^22.0.0",
|
|
40
|
+
"typescript": "^5.6.0"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@noego/trust": "0.5.0-dev.0"
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* sqlego — one owner process per SQLite file.
|
|
4
|
+
*
|
|
5
|
+
* sqlego <file> "<sql>" [--params '<json array>'] [--json|--csv]
|
|
6
|
+
* sqlego <file> status | stop
|
|
7
|
+
* sqlego <file> watch "<sql>" [--every 1s]
|
|
8
|
+
* sqlego ls
|
|
9
|
+
* sqlego serve <file> [--idle-ms 30000] (what clients spawn; rarely typed)
|
|
10
|
+
*/
|
|
11
|
+
import { readdirSync, readFileSync, rmSync } from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { Result, Trust } from '@noego/trust';
|
|
14
|
+
import { SqlegoClient, SqlegoClientError } from './client.ts';
|
|
15
|
+
import { isProcessAlive, parseServerMeta, resolveRuntimeDirectory } from './paths.ts';
|
|
16
|
+
import { errorMessage, fromJson, parseSqlParams, toJson, type SqlRow } from './protocol.ts';
|
|
17
|
+
import { VERSION } from './version.ts';
|
|
18
|
+
|
|
19
|
+
type Flags = Record<string, string | boolean>;
|
|
20
|
+
|
|
21
|
+
/** What `main` decides into an exit code: keep running (a server), or exit with this status. */
|
|
22
|
+
type Outcome = { readonly kind: 'serving' } | { readonly kind: 'exit'; readonly code: number };
|
|
23
|
+
|
|
24
|
+
const exit = (code: number): Outcome => ({ kind: 'exit', code });
|
|
25
|
+
|
|
26
|
+
function parseArgs(argv: string[]): { positional: string[]; flags: Flags; pragmas: string[] } {
|
|
27
|
+
const positional: string[] = [];
|
|
28
|
+
const flags: Flags = {};
|
|
29
|
+
const pragmas: string[] = [];
|
|
30
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
31
|
+
const arg = argv[index];
|
|
32
|
+
if (arg.startsWith('--')) {
|
|
33
|
+
const key = arg.slice(2);
|
|
34
|
+
const next = argv[index + 1];
|
|
35
|
+
if (key === 'pragma' && next !== undefined) { pragmas.push(next); index += 1; continue; }
|
|
36
|
+
if (next !== undefined && !next.startsWith('--')) { flags[key] = next; index += 1; } else flags[key] = true;
|
|
37
|
+
} else {
|
|
38
|
+
positional.push(arg);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return { positional, flags, pragmas };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function out(text: string): void {
|
|
45
|
+
report(Trust.try(() => process.stdout.write(text), () => ({ kind: 'output-closed' as const })));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function err(text: string): void {
|
|
49
|
+
report(Trust.try(() => process.stderr.write(text), () => ({ kind: 'output-closed' as const })));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A terminal write that fails has nowhere left to be reported; the exit
|
|
54
|
+
* status is the one signal that still reaches the caller, so it says failure.
|
|
55
|
+
*/
|
|
56
|
+
function report(written: Result<unknown, { readonly kind: 'output-closed' }>): void {
|
|
57
|
+
if (!written.ok && written.error.kind === 'output-closed' && !process.exitCode) process.exitCode = 1;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function usage(): Outcome {
|
|
61
|
+
err(`sqlego ${VERSION}
|
|
62
|
+
sqlego <file> "<sql>" [--params '[..]'] [--json|--csv]
|
|
63
|
+
sqlego <file> status | stop
|
|
64
|
+
sqlego <file> watch "<sql>" [--every 1s]
|
|
65
|
+
sqlego ls
|
|
66
|
+
sqlego serve <file> [--idle-ms 30000] [--pragma "<name = value>"]...
|
|
67
|
+
`);
|
|
68
|
+
return exit(2);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function parseDuration(value: string) {
|
|
72
|
+
const match = /^(\d+(?:\.\d+)?)(ms|s|m)?$/.exec(value.trim());
|
|
73
|
+
if (!match) return Result.err({ kind: 'bad-argument', message: `bad duration: ${value}` });
|
|
74
|
+
const unit = match[2] ?? 'ms';
|
|
75
|
+
return Result.ok(Number(match[1]) * (unit === 'm' ? 60_000 : unit === 's' ? 1_000 : 1));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function parseParams(flags: Flags) {
|
|
79
|
+
if (typeof flags.params !== 'string') return Result.ok(undefined);
|
|
80
|
+
const json = fromJson(flags.params);
|
|
81
|
+
if (!json.ok) return Result.err({ kind: 'bad-argument', message: `--params is ${json.error.message}` });
|
|
82
|
+
if (!Array.isArray(json.value)) return Result.err({ kind: 'bad-argument', message: '--params must be a JSON array' });
|
|
83
|
+
const params = parseSqlParams(json.value);
|
|
84
|
+
if (!params.ok) return Result.err({ kind: 'bad-argument', message: `--params: ${params.error.message}` });
|
|
85
|
+
return Result.ok(params.value);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** JSON for display; a value JSON cannot hold (a cycle, undefined) is shown as its string form instead. */
|
|
89
|
+
function displayJson(value: unknown, indent?: number): string {
|
|
90
|
+
return Trust.decide(toJson(value, indent), { 'encode-failed': () => String(value) }).value;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function renderBox(rows: SqlRow[]): string {
|
|
94
|
+
if (rows.length === 0) return '(0 rows)\n';
|
|
95
|
+
const columns = Object.keys(rows[0]);
|
|
96
|
+
const cell = (value: unknown): string => (value === null ? 'NULL' : typeof value === 'object' ? displayJson(value) : String(value));
|
|
97
|
+
const widths = columns.map((column) => Math.max(column.length, ...rows.map((row) => cell(row[column]).length)));
|
|
98
|
+
const line = (values: string[]) => `│ ${values.map((value, i) => value.padEnd(widths[i])).join(' │ ')} │\n`;
|
|
99
|
+
const rule = (left: string, mid: string, right: string) => `${left}${widths.map((w) => '─'.repeat(w + 2)).join(mid)}${right}\n`;
|
|
100
|
+
return rule('┌', '┬', '┐') + line(columns) + rule('├', '┼', '┤')
|
|
101
|
+
+ rows.map((row) => line(columns.map((column) => cell(row[column])))).join('') + rule('└', '┴', '┘')
|
|
102
|
+
+ `(${rows.length} row${rows.length === 1 ? '' : 's'})\n`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function renderCsv(rows: SqlRow[]): string {
|
|
106
|
+
if (rows.length === 0) return '';
|
|
107
|
+
const columns = Object.keys(rows[0]);
|
|
108
|
+
const escape = (value: unknown): string => {
|
|
109
|
+
const text = value === null ? '' : String(value);
|
|
110
|
+
return /[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
|
|
111
|
+
};
|
|
112
|
+
return `${columns.join(',')}\n${rows.map((row) => columns.map((column) => escape(row[column])).join(',')).join('\n')}\n`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function render(rows: SqlRow[], flags: Flags): string {
|
|
116
|
+
if (flags.json) return `${displayJson(rows)}\n`;
|
|
117
|
+
if (flags.csv) return renderCsv(rows);
|
|
118
|
+
return renderBox(rows);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function serve(file: string, flags: Flags, pragmas: readonly string[]) {
|
|
122
|
+
const loaded = await Trust.tryAsync(
|
|
123
|
+
() => import('./server.ts'),
|
|
124
|
+
(cause) => ({ kind: 'failed' as const, message: `cannot load the server: ${errorMessage(cause)}` }),
|
|
125
|
+
);
|
|
126
|
+
if (!loaded.ok) return loaded;
|
|
127
|
+
const { SqlegoServer, DEFAULT_PRAGMAS } = loaded.value;
|
|
128
|
+
const idleTimeoutMs = flags['idle-ms'] ? Number(flags['idle-ms']) : 30_000;
|
|
129
|
+
const opened = SqlegoServer.open({
|
|
130
|
+
file,
|
|
131
|
+
idleTimeoutMs,
|
|
132
|
+
pragmas: pragmas.length > 0 ? pragmas : DEFAULT_PRAGMAS,
|
|
133
|
+
log: flags.verbose ? (message, fields) => err(`[sqlego] ${message} ${displayJson(fields ?? {})}\n`) : undefined,
|
|
134
|
+
});
|
|
135
|
+
if (!opened.ok) return opened;
|
|
136
|
+
const server = opened.value;
|
|
137
|
+
const listening = server.listen();
|
|
138
|
+
if (!listening.ok) return listening;
|
|
139
|
+
const shutdown = (signal: string) => { server.stop(signal); process.exit(0); };
|
|
140
|
+
return Trust.try(
|
|
141
|
+
() => {
|
|
142
|
+
// The claimer's lock is ours to release now that the socket is live.
|
|
143
|
+
rmSync(server.paths.lock, { force: true });
|
|
144
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
145
|
+
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
146
|
+
process.on('SIGHUP', () => shutdown('SIGHUP'));
|
|
147
|
+
},
|
|
148
|
+
(cause) => ({ kind: 'failed' as const, message: `server started but could not finish setup: ${errorMessage(cause)}` }),
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function list() {
|
|
153
|
+
const directory = resolveRuntimeDirectory();
|
|
154
|
+
if (!directory.ok) return directory;
|
|
155
|
+
const names = Trust.try(
|
|
156
|
+
() => readdirSync(directory.value),
|
|
157
|
+
(cause) => ({ kind: 'failed' as const, message: `cannot list ${directory.value}: ${errorMessage(cause)}` }),
|
|
158
|
+
);
|
|
159
|
+
if (!names.ok) return names;
|
|
160
|
+
const rows: SqlRow[] = [];
|
|
161
|
+
for (const name of names.value) {
|
|
162
|
+
if (!name.endsWith('.json')) continue;
|
|
163
|
+
const text = Trust.try(
|
|
164
|
+
() => readFileSync(path.join(directory.value, name), 'utf8'),
|
|
165
|
+
() => ({ kind: 'invalid' as const, message: 'unreadable' }),
|
|
166
|
+
);
|
|
167
|
+
const json = text.ok ? fromJson(text.value) : text;
|
|
168
|
+
const meta = json.ok ? parseServerMeta(json.value) : json;
|
|
169
|
+
if (meta.ok) {
|
|
170
|
+
rows.push({ pid: meta.value.pid, alive: isProcessAlive(meta.value.pid), version: meta.value.serverVersion, uptime: `${Math.round((Date.now() - meta.value.startedAt) / 1000)}s`, file: meta.value.file });
|
|
171
|
+
} else if (meta.error.kind === 'invalid') {
|
|
172
|
+
// A meta being written or removed, or not one of ours: skip it.
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
out(renderBox(rows));
|
|
176
|
+
return Result.ok(undefined);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Runs `work` against a connected client and always closes it. The client's
|
|
181
|
+
* public API throws `SqlegoClientError`; this is where the CLI turns that back
|
|
182
|
+
* into a failure with its code.
|
|
183
|
+
*/
|
|
184
|
+
function withClient<T>(file: string, flags: Flags, work: (client: SqlegoClient) => Promise<T>) {
|
|
185
|
+
return Trust.tryAsync(
|
|
186
|
+
async () => {
|
|
187
|
+
const client = await SqlegoClient.connect(file, { spawn: flags['no-spawn'] ? false : true });
|
|
188
|
+
try {
|
|
189
|
+
return await work(client);
|
|
190
|
+
} finally {
|
|
191
|
+
await client.close();
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
(cause) => (cause instanceof SqlegoClientError
|
|
195
|
+
? { kind: 'client' as const, code: cause.code, message: cause.message }
|
|
196
|
+
: { kind: 'failed' as const, message: errorMessage(cause) }),
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function stop(file: string, flags: Flags) {
|
|
201
|
+
const stopped = await withClient(file, { ...flags, 'no-spawn': true }, (client) => client.stop());
|
|
202
|
+
if (stopped.ok) {
|
|
203
|
+
out('stopped\n');
|
|
204
|
+
return stopped;
|
|
205
|
+
}
|
|
206
|
+
if (stopped.error.kind === 'client' && stopped.error.code === 'not-running') {
|
|
207
|
+
out('not running\n');
|
|
208
|
+
return Result.ok(undefined);
|
|
209
|
+
}
|
|
210
|
+
return stopped;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function watch(file: string, sql: string, flags: Flags) {
|
|
214
|
+
const everyMs = parseDuration(typeof flags.every === 'string' ? flags.every : '1s');
|
|
215
|
+
if (!everyMs.ok) return everyMs;
|
|
216
|
+
const params = parseParams(flags);
|
|
217
|
+
if (!params.ok) return params;
|
|
218
|
+
return withClient(file, flags, async (client) => {
|
|
219
|
+
for (;;) {
|
|
220
|
+
const rows = await client.query(sql, params.value);
|
|
221
|
+
out(`\x1b[2J\x1b[H${new Date().toISOString()}\n${render(rows, flags)}`);
|
|
222
|
+
await new Promise((resolve) => setTimeout(resolve, everyMs.value));
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async function execute(file: string, sql: string, flags: Flags) {
|
|
228
|
+
const params = parseParams(flags);
|
|
229
|
+
if (!params.ok) return params;
|
|
230
|
+
const isRead = /^\s*(select|with|pragma|explain)\b/i.test(sql);
|
|
231
|
+
return withClient(file, flags, async (client) => {
|
|
232
|
+
if (isRead) {
|
|
233
|
+
out(render(await client.query(sql, params.value), flags));
|
|
234
|
+
} else {
|
|
235
|
+
const result = await client.run(sql, params.value);
|
|
236
|
+
out(`${displayJson(result)}\n`);
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function status(file: string, flags: Flags) {
|
|
242
|
+
const result = await withClient(file, flags, (client) => client.status());
|
|
243
|
+
if (!result.ok) return result;
|
|
244
|
+
out(`${displayJson(result.value, 2)}\n`);
|
|
245
|
+
return Result.ok(undefined);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Runs one command; every failure stays a `Result` until `main` decides it. */
|
|
249
|
+
async function command(argv: string[]) {
|
|
250
|
+
const { positional, flags, pragmas } = parseArgs(argv);
|
|
251
|
+
if (flags.version) { out(`${VERSION}\n`); return Result.ok(exit(0)); }
|
|
252
|
+
const [first, second, third] = positional;
|
|
253
|
+
if (!first || flags.help) return Result.ok(usage());
|
|
254
|
+
if (first === 'ls') {
|
|
255
|
+
const listed = list();
|
|
256
|
+
if (!listed.ok) return listed;
|
|
257
|
+
return Result.ok(exit(0));
|
|
258
|
+
}
|
|
259
|
+
if (first === 'serve') {
|
|
260
|
+
if (!second) return Result.ok(usage());
|
|
261
|
+
const served = await serve(second, flags, pragmas);
|
|
262
|
+
if (!served.ok) return served;
|
|
263
|
+
const serving: Outcome = { kind: 'serving' };
|
|
264
|
+
return Result.ok(serving);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const file = first;
|
|
268
|
+
if (!second) return Result.ok(usage());
|
|
269
|
+
if (second === 'watch' && !third) return Result.ok(usage());
|
|
270
|
+
const ran = second === 'status' ? await status(file, flags)
|
|
271
|
+
: second === 'stop' ? await stop(file, flags)
|
|
272
|
+
: second === 'watch' && third ? await watch(file, third, flags)
|
|
273
|
+
: await execute(file, second, flags);
|
|
274
|
+
if (!ran.ok) return ran;
|
|
275
|
+
return Result.ok(exit(0));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** The edge: every failure becomes a message on stderr and exit status 1. */
|
|
279
|
+
async function main(argv: string[]): Promise<Outcome> {
|
|
280
|
+
const outcome = await command(argv);
|
|
281
|
+
if (outcome.ok) return outcome.value;
|
|
282
|
+
switch (outcome.error.kind) {
|
|
283
|
+
case 'bad-argument':
|
|
284
|
+
case 'client':
|
|
285
|
+
case 'failed':
|
|
286
|
+
case 'runtime-directory':
|
|
287
|
+
case 'canonical-path':
|
|
288
|
+
case 'hash-failed':
|
|
289
|
+
case 'socket-path-too-long':
|
|
290
|
+
case 'open-failed':
|
|
291
|
+
case 'listen-failed':
|
|
292
|
+
err(`sqlego: ${outcome.error.message}\n`);
|
|
293
|
+
return exit(1);
|
|
294
|
+
default: {
|
|
295
|
+
const unhandled: never = outcome.error;
|
|
296
|
+
return unhandled;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
main(process.argv.slice(2)).then(
|
|
302
|
+
(outcome) => {
|
|
303
|
+
if (outcome.kind === 'exit' && outcome.code !== 0) process.exit(outcome.code);
|
|
304
|
+
},
|
|
305
|
+
(error: unknown) => {
|
|
306
|
+
// Only a defect in sqlego itself lands here: every expected failure is decided in `main`.
|
|
307
|
+
err(`sqlego: ${errorMessage(error)}\n`);
|
|
308
|
+
process.exit(1);
|
|
309
|
+
},
|
|
310
|
+
);
|