@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 CHANGED
@@ -1,3 +1,129 @@
1
- # Temporary Holding Version
1
+ # sqlego
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One owner process per SQLite file. Every client — the `sqlego` CLI, the Node
4
+ library, a Bun script — passes SQL over a local Unix socket to the one process
5
+ holding the file. The server boots on first connect and exits when idle.
6
+
7
+ Why: SQLite's write lock is per-process. Two processes (an app, a log host, a
8
+ retention job, a debugging CLI) writing the same file contend, time out, and
9
+ freeze each other. With a single owner there is nothing to contend: statements
10
+ from all clients run in arrival order on one connection, and a reader from any
11
+ process just asks the owner.
12
+
13
+ ## Pieces
14
+
15
+ | Piece | Runtime | Role |
16
+ | --- | --- | --- |
17
+ | `bin/sqlego` | Bun, compiled single binary | CLI **and** server (`sqlego serve <file>` is what clients spawn) |
18
+ | `@noego/sqlego` (`src/client.ts`) | Node or Bun; `node:net` only | Protocol-only client — no SQLite dependency, no native addon |
19
+ | `src/server.ts` | Bun (`bun:sqlite`) | The owner: one `Database`, one Unix socket, idle exit |
20
+
21
+ ## Lifecycle
22
+
23
+ ```
24
+ client: connect(socket) ──ok──▶ hello ──▶ requests
25
+ │ refused/absent
26
+ ▼
27
+ claim <key>.lock (O_EXCL; stale lock of a dead pid is reclaimed)
28
+ │ won │ lost
29
+ ▼ ▼
30
+ spawn `sqlego serve <file>` wait for socket to appear
31
+ └──────────────▶ connect ◀──────────────┘
32
+
33
+ server: listen ▶ write <key>.json ▶ release lock ▶ serve
34
+ last client leaves ▶ idle timer (default 30 s) ▶ rm socket+meta ▶ close db ▶ exit 0
35
+ ```
36
+
37
+ Socket, lock, and meta live in `$SQLEGO_RUNTIME_DIR` (default `<tmpdir>/sqlego/`)
38
+ keyed by a hash of the canonical file path — never beside the database, because
39
+ Unix socket paths cap at 104 bytes.
40
+
41
+ A client whose version differs from the server's asks it to stop and spawns a
42
+ fresh one, so a rebuilt binary never keeps talking to an old owner.
43
+
44
+ ## Protocol
45
+
46
+ Newline-delimited JSON, correlated by `id`. Ops: `hello`, `query` (rows),
47
+ `run` (changes), `batch` (all statements in one transaction, rolled back on
48
+ the first failure), `begin` / `commit` / `rollback` (a leased transaction,
49
+ below), `status`, `stop`. Protocol version 2; `hello` refuses a client that
50
+ speaks another version.
51
+
52
+ ### Leased transactions
53
+
54
+ A client-held transaction holds the file's only writer, so it is never bare:
55
+ the server owns its lifetime and rolls it back the moment the client cannot be
56
+ trusted to.
57
+
58
+ - `begin { mode?: 'deferred' | 'immediate', leaseMs? }` → `{ txId, leaseMs, maxDurationMs }`.
59
+ The transaction is bound to the socket that opened it; one per connection.
60
+ - `query` / `run` carry `txId` to run inside it. Each such request renews the
61
+ lease. `SAVEPOINT` / `RELEASE` / `ROLLBACK TO` are plain SQL inside it.
62
+ - `commit { txId }` / `rollback { txId }` end it.
63
+ - Plain `query` / `run` / `batch` refuse `BEGIN`, `COMMIT`, `ROLLBACK`,
64
+ `SAVEPOINT` and `RELEASE` (`bad-request`): the server must always know
65
+ whether the file is inside a transaction.
66
+
67
+ While one is open, that client's statements run at once and every other
68
+ client's `query` / `run` / `batch` / `begin` wait in arrival order (`status`
69
+ reports how many); `hello`, `status` and `stop` never wait. It is rolled back
70
+ by the server, and later requests for it fail with `tx-expired`, when:
71
+
72
+ | Trigger | Server flag | Default |
73
+ | --- | --- | --- |
74
+ | The owning socket closes | — | immediate |
75
+ | No request for it within the lease (`begin` may ask for less, never more) | `--tx-lease-ms` | 10 s |
76
+ | Open longer than the hard cap, renewed or not | `--tx-max-ms` | 60 s |
77
+ | SQLite itself aborted it (e.g. `SQLITE_FULL`) | — | immediate |
78
+
79
+ A waiting request from another client fails with `tx-busy` after
80
+ `--tx-queue-ms` (default 30 s) rather than hanging. The idle exit never fires
81
+ while a transaction is open.
82
+
83
+ ## CLI
84
+
85
+ ```
86
+ sqlego <file> "SELECT …" [--params '[1,"a"]'] [--json|--csv]
87
+ sqlego <file> "DELETE …"
88
+ sqlego <file> status | stop
89
+ sqlego <file> watch "SELECT count(*) FROM logs" --every 2s
90
+ sqlego ls
91
+ sqlego serve <file> [--idle-ms 30000] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-ms 30000]
92
+ ```
93
+
94
+ ## Library
95
+
96
+ ```ts
97
+ import { SqlegoClient } from '@noego/sqlego';
98
+ const db = await SqlegoClient.connect('/path/to/logs.db');
99
+ await db.run('INSERT INTO logs (…) VALUES (?, ?)', [a, b]);
100
+ const rows = await db.query('SELECT … WHERE occurred_at_ms < ?', [cutoff]);
101
+ await db.batch([{ sql: 'DELETE … LIMIT 5000' }, { sql: 'PRAGMA incremental_vacuum(256)' }]);
102
+
103
+ // Reads-then-writes with application logic in between: a leased transaction.
104
+ const tx = await db.begin({ mode: 'immediate' });
105
+ const [{ balance }] = await tx.query<{ balance: number }>('SELECT balance FROM accounts WHERE id = ?', [id]);
106
+ await tx.savepoint('s1');
107
+ await tx.run('UPDATE accounts SET balance = ? WHERE id = ?', [balance - amount, id]);
108
+ await tx.release('s1'); // or tx.rollbackTo('s1')
109
+ await tx.commit(); // or tx.rollback()
110
+
111
+ // Or let the client commit on resolve and roll back on throw:
112
+ await db.transaction(async (tx) => { await tx.run('…'); });
113
+ await db.close();
114
+ ```
115
+
116
+ A `SqlegoClientError` with code `tx-expired` means the server rolled the
117
+ transaction back (lease, hard cap, or disconnect); `tx-busy` means another
118
+ client's transaction kept the request waiting too long.
119
+
120
+ Server location: `SQLEGO_BIN`, else the compiled `bin/sqlego` next to the
121
+ package, else `sqlego` on `PATH`; pass `serverCommand` to override.
122
+
123
+ ## Develop
124
+
125
+ ```
126
+ bun install
127
+ bun test
128
+ bun run build # → bin/sqlego (single executable)
129
+ ```
package/bin/sqlego ADDED
@@ -0,0 +1,4 @@
1
+ [diffend] Oversized file quarantined before diffing.
2
+ name: package/bin/sqlego
3
+ size: 62259954 bytes
4
+ sha256: e86c1e4cee3a9a0397df24603c5d08aa12cbacbd1a52416f87f183adb8fcb802
@@ -0,0 +1,125 @@
1
+ import { type BatchResult, type BeginResult, type HelloResult, type RunResult, type SqlParams, type SqlRow, type Statement, type StatusResult, type TransactionMode } from './protocol.ts';
2
+ import { type FilePaths } from './paths.ts';
3
+ /**
4
+ * Runs in Node and Bun alike (node:net, node:child_process only; no SQLite
5
+ * dependency). Connects to the file's owner, spawning one when none is
6
+ * listening. The sequence is always: connect → else claim lock → spawn → wait
7
+ * for the socket → connect. A claimer that loses the lock waits for the
8
+ * winner's socket instead.
9
+ */
10
+ export type ClientOptions = Readonly<{
11
+ /** Spawn a server when none is listening. Default true. */
12
+ spawn?: boolean;
13
+ /** How the server is started when needed; see `serverCommand`. */
14
+ serverCommand?: readonly string[];
15
+ /** Idle timeout passed to a spawned server. Default 30 000. */
16
+ idleTimeoutMs?: number;
17
+ /** Pragmas a spawned server applies on open (`--pragma`), replacing its defaults. Ignored when a server is already running. */
18
+ serverPragmas?: readonly string[];
19
+ /** Total time to obtain a connection, including spawn. Default 10 000. */
20
+ connectTimeoutMs?: number;
21
+ /** Per-request timeout. Default 60 000. */
22
+ requestTimeoutMs?: number;
23
+ }>;
24
+ export type BeginOptions = Readonly<{
25
+ /** `immediate` takes the write lock at `begin`; `deferred` (default) on the first write. */
26
+ mode?: TransactionMode;
27
+ /**
28
+ * Roll the transaction back when no request for it arrives within this
29
+ * long; each request renews it. The server caps it at its own lease.
30
+ */
31
+ leaseMs?: number;
32
+ }>;
33
+ export declare class SqlegoClientError extends Error {
34
+ readonly code: string;
35
+ constructor(code: string, message: string);
36
+ }
37
+ export declare class SqlegoClient {
38
+ readonly paths: FilePaths;
39
+ private socket;
40
+ private buffer;
41
+ private nextId;
42
+ private readonly pending;
43
+ private hello;
44
+ /** Why the server this client spawned did not come up, if it did not. */
45
+ private spawnFailure;
46
+ private readonly options;
47
+ private constructor();
48
+ static connect(file: string, options?: ClientOptions): Promise<SqlegoClient>;
49
+ get server(): HelloResult;
50
+ query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]>;
51
+ run(sql: string, params?: SqlParams): Promise<RunResult>;
52
+ /** One transaction; the whole batch rolls back on the first failure. */
53
+ batch(statements: readonly Statement[]): Promise<BatchResult['results']>;
54
+ /**
55
+ * Opens a transaction held across requests. It is bound to this connection
56
+ * and rolled back by the server if the connection drops, the lease runs out
57
+ * between requests, or the server's hard cap is reached; other clients'
58
+ * statements wait until it ends. End it with `commit` or `rollback`.
59
+ */
60
+ begin(options?: BeginOptions): Promise<SqlegoTransaction>;
61
+ /** Runs `work` in a transaction: commits when it resolves, rolls back when it rejects (and rethrows). */
62
+ transaction<T>(work: (tx: SqlegoTransaction) => Promise<T>, options?: BeginOptions): Promise<T>;
63
+ /** @internal Statements inside a transaction; `SqlegoTransaction` is the public face. */
64
+ transactionQuery<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<Row[]>;
65
+ /** @internal */
66
+ transactionRun(txId: number, sql: string, params?: SqlParams): Promise<RunResult>;
67
+ /** @internal */
68
+ transactionEnd(txId: number, how: 'commit' | 'rollback'): Promise<void>;
69
+ status(): Promise<StatusResult>;
70
+ /** Asks the server to shut down; the connection closes as a consequence. */
71
+ stop(): Promise<void>;
72
+ close(): Promise<void>;
73
+ private stopServer;
74
+ private open;
75
+ private connectOrSpawn;
76
+ /** O_EXCL create; a lock left by a dead process (or unreadable) is reclaimed. */
77
+ private claimLock;
78
+ private spawnServer;
79
+ /** The spawn never started: record why, and release the lock so another claimer can try. */
80
+ private onSpawnError;
81
+ private attach;
82
+ private onClose;
83
+ private onData;
84
+ /**
85
+ * One request whose reply `parse` turns from `unknown` into its typed
86
+ * result; a reply that does not parse is a `protocol` failure.
87
+ */
88
+ private call;
89
+ /** Never rejects: every outcome, including transport failures, is a `Result`. The reply is `unknown` until parsed. */
90
+ private request;
91
+ private settleAll;
92
+ private waitForExit;
93
+ }
94
+ /**
95
+ * One open transaction on a `SqlegoClient`. Every method rejects with a
96
+ * `SqlegoClientError` whose code is `tx-expired` once the server has rolled
97
+ * it back (lease, hard cap, disconnect) and `tx-invalid` after it ended.
98
+ */
99
+ export declare class SqlegoTransaction {
100
+ readonly id: number;
101
+ /** The lease the server granted, which may be shorter than requested. */
102
+ readonly leaseMs: number;
103
+ /** The server's hard cap on this transaction's life. */
104
+ readonly maxDurationMs: number;
105
+ private readonly client;
106
+ private ended;
107
+ constructor(client: SqlegoClient, opened: BeginResult);
108
+ /** True once `commit` or `rollback` has been sent; the server may also have ended it on its own. */
109
+ get closed(): boolean;
110
+ query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]>;
111
+ run(sql: string, params?: SqlParams): Promise<RunResult>;
112
+ /** `SAVEPOINT name`: a nested scope that `rollbackTo` can undo and `release` folds into the transaction. */
113
+ savepoint(name: string): Promise<void>;
114
+ release(name: string): Promise<void>;
115
+ /** Undoes everything since the savepoint; the savepoint itself stays until released. */
116
+ rollbackTo(name: string): Promise<void>;
117
+ commit(): Promise<void>;
118
+ rollback(): Promise<void>;
119
+ }
120
+ /**
121
+ * How to start a server: SQLEGO_BIN if set; the compiled `sqlego` binary when
122
+ * running as one; the dev entry (`bun src/cli.ts`) when running from source
123
+ * under Bun; else `sqlego` on PATH.
124
+ */
125
+ export declare function defaultServerCommand(): readonly string[];
@@ -0,0 +1,4 @@
1
+ export { SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, type BeginOptions, type ClientOptions } from './client.ts';
2
+ export { pathsFor, runtimeDirectory, canonicalFile, type FilePaths, type ServerMeta } from './paths.ts';
3
+ export { PROTOCOL_VERSION, type SqlParams, type SqlRow, type SqlValue, type Statement, type RunResult, type QueryResult, type BatchResult, type BeginResult, type StatusResult, type HelloResult, type TransactionMode, type TransactionStatus, } from './protocol.ts';
4
+ export { VERSION } from './version.ts';