@noego/sqlego 0.0.0-stage → 0.0.1-dev.1
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 +128 -2
- package/bin/sqlego +4 -0
- package/dist/client.d.ts +125 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +870 -0
- package/dist/paths.d.ts +70 -0
- package/dist/protocol.d.ts +287 -0
- package/dist/version.d.ts +23 -0
- package/package.json +43 -4
- package/src/cli.ts +314 -0
- package/src/client.ts +621 -0
- package/src/index.ts +18 -0
- package/src/paths.ts +154 -0
- package/src/protocol.ts +477 -0
- package/src/server.ts +723 -0
- package/src/version.ts +78 -0
package/src/cli.ts
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
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] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-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 millis = (flag: string) => (typeof flags[flag] === 'string' ? Number(flags[flag]) : undefined);
|
|
130
|
+
const opened = SqlegoServer.open({
|
|
131
|
+
file,
|
|
132
|
+
idleTimeoutMs,
|
|
133
|
+
pragmas: pragmas.length > 0 ? pragmas : DEFAULT_PRAGMAS,
|
|
134
|
+
txLeaseMs: millis('tx-lease-ms'),
|
|
135
|
+
txMaxDurationMs: millis('tx-max-ms'),
|
|
136
|
+
txQueueTimeoutMs: millis('tx-queue-ms'),
|
|
137
|
+
log: flags.verbose ? (message, fields) => err(`[sqlego] ${message} ${displayJson(fields ?? {})}\n`) : undefined,
|
|
138
|
+
});
|
|
139
|
+
if (!opened.ok) return opened;
|
|
140
|
+
const server = opened.value;
|
|
141
|
+
const listening = server.listen();
|
|
142
|
+
if (!listening.ok) return listening;
|
|
143
|
+
const shutdown = (signal: string) => { server.stop(signal); process.exit(0); };
|
|
144
|
+
return Trust.try(
|
|
145
|
+
() => {
|
|
146
|
+
// The claimer's lock is ours to release now that the socket is live.
|
|
147
|
+
rmSync(server.paths.lock, { force: true });
|
|
148
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
149
|
+
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
150
|
+
process.on('SIGHUP', () => shutdown('SIGHUP'));
|
|
151
|
+
},
|
|
152
|
+
(cause) => ({ kind: 'failed' as const, message: `server started but could not finish setup: ${errorMessage(cause)}` }),
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function list() {
|
|
157
|
+
const directory = resolveRuntimeDirectory();
|
|
158
|
+
if (!directory.ok) return directory;
|
|
159
|
+
const names = Trust.try(
|
|
160
|
+
() => readdirSync(directory.value),
|
|
161
|
+
(cause) => ({ kind: 'failed' as const, message: `cannot list ${directory.value}: ${errorMessage(cause)}` }),
|
|
162
|
+
);
|
|
163
|
+
if (!names.ok) return names;
|
|
164
|
+
const rows: SqlRow[] = [];
|
|
165
|
+
for (const name of names.value) {
|
|
166
|
+
if (!name.endsWith('.json')) continue;
|
|
167
|
+
const text = Trust.try(
|
|
168
|
+
() => readFileSync(path.join(directory.value, name), 'utf8'),
|
|
169
|
+
() => ({ kind: 'invalid' as const, message: 'unreadable' }),
|
|
170
|
+
);
|
|
171
|
+
const json = text.ok ? fromJson(text.value) : text;
|
|
172
|
+
const meta = json.ok ? parseServerMeta(json.value) : json;
|
|
173
|
+
if (meta.ok) {
|
|
174
|
+
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 });
|
|
175
|
+
} else if (meta.error.kind === 'invalid') {
|
|
176
|
+
// A meta being written or removed, or not one of ours: skip it.
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
out(renderBox(rows));
|
|
180
|
+
return Result.ok(undefined);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Runs `work` against a connected client and always closes it. The client's
|
|
185
|
+
* public API throws `SqlegoClientError`; this is where the CLI turns that back
|
|
186
|
+
* into a failure with its code.
|
|
187
|
+
*/
|
|
188
|
+
function withClient<T>(file: string, flags: Flags, work: (client: SqlegoClient) => Promise<T>) {
|
|
189
|
+
return Trust.tryAsync(
|
|
190
|
+
async () => {
|
|
191
|
+
const client = await SqlegoClient.connect(file, { spawn: flags['no-spawn'] ? false : true });
|
|
192
|
+
try {
|
|
193
|
+
return await work(client);
|
|
194
|
+
} finally {
|
|
195
|
+
await client.close();
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
(cause) => (cause instanceof SqlegoClientError
|
|
199
|
+
? { kind: 'client' as const, code: cause.code, message: cause.message }
|
|
200
|
+
: { kind: 'failed' as const, message: errorMessage(cause) }),
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function stop(file: string, flags: Flags) {
|
|
205
|
+
const stopped = await withClient(file, { ...flags, 'no-spawn': true }, (client) => client.stop());
|
|
206
|
+
if (stopped.ok) {
|
|
207
|
+
out('stopped\n');
|
|
208
|
+
return stopped;
|
|
209
|
+
}
|
|
210
|
+
if (stopped.error.kind === 'client' && stopped.error.code === 'not-running') {
|
|
211
|
+
out('not running\n');
|
|
212
|
+
return Result.ok(undefined);
|
|
213
|
+
}
|
|
214
|
+
return stopped;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function watch(file: string, sql: string, flags: Flags) {
|
|
218
|
+
const everyMs = parseDuration(typeof flags.every === 'string' ? flags.every : '1s');
|
|
219
|
+
if (!everyMs.ok) return everyMs;
|
|
220
|
+
const params = parseParams(flags);
|
|
221
|
+
if (!params.ok) return params;
|
|
222
|
+
return withClient(file, flags, async (client) => {
|
|
223
|
+
for (;;) {
|
|
224
|
+
const rows = await client.query(sql, params.value);
|
|
225
|
+
out(`\x1b[2J\x1b[H${new Date().toISOString()}\n${render(rows, flags)}`);
|
|
226
|
+
await new Promise((resolve) => setTimeout(resolve, everyMs.value));
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function execute(file: string, sql: string, flags: Flags) {
|
|
232
|
+
const params = parseParams(flags);
|
|
233
|
+
if (!params.ok) return params;
|
|
234
|
+
const isRead = /^\s*(select|with|pragma|explain)\b/i.test(sql);
|
|
235
|
+
return withClient(file, flags, async (client) => {
|
|
236
|
+
if (isRead) {
|
|
237
|
+
out(render(await client.query(sql, params.value), flags));
|
|
238
|
+
} else {
|
|
239
|
+
const result = await client.run(sql, params.value);
|
|
240
|
+
out(`${displayJson(result)}\n`);
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function status(file: string, flags: Flags) {
|
|
246
|
+
const result = await withClient(file, flags, (client) => client.status());
|
|
247
|
+
if (!result.ok) return result;
|
|
248
|
+
out(`${displayJson(result.value, 2)}\n`);
|
|
249
|
+
return Result.ok(undefined);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Runs one command; every failure stays a `Result` until `main` decides it. */
|
|
253
|
+
async function command(argv: string[]) {
|
|
254
|
+
const { positional, flags, pragmas } = parseArgs(argv);
|
|
255
|
+
if (flags.version) { out(`${VERSION}\n`); return Result.ok(exit(0)); }
|
|
256
|
+
const [first, second, third] = positional;
|
|
257
|
+
if (!first || flags.help) return Result.ok(usage());
|
|
258
|
+
if (first === 'ls') {
|
|
259
|
+
const listed = list();
|
|
260
|
+
if (!listed.ok) return listed;
|
|
261
|
+
return Result.ok(exit(0));
|
|
262
|
+
}
|
|
263
|
+
if (first === 'serve') {
|
|
264
|
+
if (!second) return Result.ok(usage());
|
|
265
|
+
const served = await serve(second, flags, pragmas);
|
|
266
|
+
if (!served.ok) return served;
|
|
267
|
+
const serving: Outcome = { kind: 'serving' };
|
|
268
|
+
return Result.ok(serving);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const file = first;
|
|
272
|
+
if (!second) return Result.ok(usage());
|
|
273
|
+
if (second === 'watch' && !third) return Result.ok(usage());
|
|
274
|
+
const ran = second === 'status' ? await status(file, flags)
|
|
275
|
+
: second === 'stop' ? await stop(file, flags)
|
|
276
|
+
: second === 'watch' && third ? await watch(file, third, flags)
|
|
277
|
+
: await execute(file, second, flags);
|
|
278
|
+
if (!ran.ok) return ran;
|
|
279
|
+
return Result.ok(exit(0));
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** The edge: every failure becomes a message on stderr and exit status 1. */
|
|
283
|
+
async function main(argv: string[]): Promise<Outcome> {
|
|
284
|
+
const outcome = await command(argv);
|
|
285
|
+
if (outcome.ok) return outcome.value;
|
|
286
|
+
switch (outcome.error.kind) {
|
|
287
|
+
case 'bad-argument':
|
|
288
|
+
case 'client':
|
|
289
|
+
case 'failed':
|
|
290
|
+
case 'runtime-directory':
|
|
291
|
+
case 'canonical-path':
|
|
292
|
+
case 'hash-failed':
|
|
293
|
+
case 'socket-path-too-long':
|
|
294
|
+
case 'open-failed':
|
|
295
|
+
case 'listen-failed':
|
|
296
|
+
err(`sqlego: ${outcome.error.message}\n`);
|
|
297
|
+
return exit(1);
|
|
298
|
+
default: {
|
|
299
|
+
const unhandled: never = outcome.error;
|
|
300
|
+
return unhandled;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
main(process.argv.slice(2)).then(
|
|
306
|
+
(outcome) => {
|
|
307
|
+
if (outcome.kind === 'exit' && outcome.code !== 0) process.exit(outcome.code);
|
|
308
|
+
},
|
|
309
|
+
(error: unknown) => {
|
|
310
|
+
// Only a defect in sqlego itself lands here: every expected failure is decided in `main`.
|
|
311
|
+
err(`sqlego: ${errorMessage(error)}\n`);
|
|
312
|
+
process.exit(1);
|
|
313
|
+
},
|
|
314
|
+
);
|