@noego/sqlego 0.0.1 → 0.0.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 CHANGED
@@ -44,10 +44,71 @@ fresh one, so a rebuilt binary never keeps talking to an old owner.
44
44
  ## Protocol
45
45
 
46
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), `status`, `stop`. There is no `BEGIN` over the wire on
49
- purpose: a client-held transaction would hold the only writer hostage to that
50
- client's liveness. `batch` is the transactional unit.
47
+ `run` (changes), `statement` and `exec` (below), `batch` (all statements in
48
+ one transaction, rolled back on the first failure), `begin` / `commit` /
49
+ `rollback` (a leased transaction, below), `status`, `stop`. Protocol version
50
+ 3; `hello` refuses a client that speaks another version.
51
+
52
+ ### `statement` and `exec`
53
+
54
+ - `statement { sql, params?, txId? }` → `{ reader, rows, changes, lastInsertRowid }`.
55
+ Exactly one SQL statement of any kind (several, or none, is `bad-request`).
56
+ A statement with result columns — `SELECT`, `PRAGMA`, `INSERT … RETURNING` —
57
+ returns `reader: true` and its rows; any other returns `reader: false` and
58
+ `rows: []`. This distinguishes an empty result set from a write. It is executed once.
59
+ `changes` is the rows it changed (0 for a read or DDL).
60
+ - `exec { sql, txId? }` → `{ statements, changes, lastInsertRowid }`. Any
61
+ number of statements, no parameters, run in order and stopped at the first
62
+ failure (statements before it keep their effect, as with `sqlite3_exec`;
63
+ run it in a leased transaction to make it all-or-nothing). Statements are
64
+ split the way SQLite does it (`sqlite3_complete`): semicolons in strings,
65
+ quoted identifiers, comments and trigger bodies don't end a statement.
66
+ Every statement is checked before any runs, so transaction control anywhere
67
+ in the text — not only the first statement — is refused.
68
+
69
+ Both follow the transaction rules below (`txId`, leases, queueing).
70
+
71
+ ### Typed values
72
+
73
+ JSON has no 64-bit integers or bytes, so they travel as strictly validated
74
+ one-key tags: `{ "$bigint": "-9223372036854775808" }` (canonical decimal,
75
+ signed 64-bit range) and `{ "$blob": "AAH/" }` (canonical padded base64; `""`
76
+ is a zero-length blob). The client tags `bigint` and `Uint8Array` parameters
77
+ of every op; a `bigint` outside the 64-bit range fails with `bad-request`
78
+ before it is sent. `statement` / `exec` results return integers as numbers
79
+ when |n| ≤ 2^53-1 and as `bigint` otherwise, and blobs as `Uint8Array`.
80
+ `query` / `run` / `batch` results are unchanged (plain JSON numbers).
81
+
82
+ ### Leased transactions
83
+
84
+ A client-held transaction holds the file's only writer, so it is never bare:
85
+ the server owns its lifetime and rolls it back the moment the client cannot be
86
+ trusted to.
87
+
88
+ - `begin { mode?: 'deferred' | 'immediate', leaseMs? }` → `{ txId, leaseMs, maxDurationMs }`.
89
+ The transaction is bound to the socket that opened it; one per connection.
90
+ - `query` / `run` carry `txId` to run inside it. Each such request renews the
91
+ lease. `SAVEPOINT` / `RELEASE` / `ROLLBACK TO` are plain SQL inside it.
92
+ - `commit { txId }` / `rollback { txId }` end it.
93
+ - Plain `query` / `run` / `batch` refuse `BEGIN`, `COMMIT`, `ROLLBACK`,
94
+ `SAVEPOINT` and `RELEASE` (`bad-request`): the server must always know
95
+ whether the file is inside a transaction.
96
+
97
+ While one is open, that client's statements run at once and every other
98
+ client's `query` / `run` / `statement` / `exec` / `batch` / `begin` wait in arrival order (`status`
99
+ reports how many); `hello`, `status` and `stop` never wait. It is rolled back
100
+ by the server, and later requests for it fail with `tx-expired`, when:
101
+
102
+ | Trigger | Server flag | Default |
103
+ | --- | --- | --- |
104
+ | The owning socket closes | — | immediate |
105
+ | No request for it within the lease (`begin` may ask for less, never more) | `--tx-lease-ms` | 10 s |
106
+ | Open longer than the hard cap, renewed or not | `--tx-max-ms` | 60 s |
107
+ | SQLite itself aborted it (e.g. `SQLITE_FULL`) | — | immediate |
108
+
109
+ A waiting request from another client fails with `tx-busy` after
110
+ `--tx-queue-ms` (default 30 s) rather than hanging. The idle exit never fires
111
+ while a transaction is open.
51
112
 
52
113
  ## CLI
53
114
 
@@ -57,6 +118,7 @@ sqlego <file> "DELETE …"
57
118
  sqlego <file> status | stop
58
119
  sqlego <file> watch "SELECT count(*) FROM logs" --every 2s
59
120
  sqlego ls
121
+ sqlego serve <file> [--idle-ms 30000] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-ms 30000]
60
122
  ```
61
123
 
62
124
  ## Library
@@ -67,9 +129,31 @@ const db = await SqlegoClient.connect('/path/to/logs.db');
67
129
  await db.run('INSERT INTO logs (…) VALUES (?, ?)', [a, b]);
68
130
  const rows = await db.query('SELECT … WHERE occurred_at_ms < ?', [cutoff]);
69
131
  await db.batch([{ sql: 'DELETE … LIMIT 5000' }, { sql: 'PRAGMA incremental_vacuum(256)' }]);
132
+
133
+ // One statement, rows and changes together; lossless bigint / Uint8Array.
134
+ const { rows: [created], changes } = await db.statement<{ id: bigint | number }>(
135
+ 'INSERT INTO files (hash, body) VALUES (?, ?) RETURNING id', [hash, bytes]);
136
+ // A whole schema or migration script (no params).
137
+ await db.exec(schemaSql);
138
+
139
+ // Reads-then-writes with application logic in between: a leased transaction.
140
+ const tx = await db.begin({ mode: 'immediate' });
141
+ const [{ balance }] = await tx.query<{ balance: number }>('SELECT balance FROM accounts WHERE id = ?', [id]);
142
+ await tx.savepoint('s1');
143
+ await tx.run('UPDATE accounts SET balance = ? WHERE id = ?', [balance - amount, id]);
144
+ await tx.release('s1'); // or tx.rollbackTo('s1')
145
+ await tx.statement('DELETE FROM holds WHERE id = ? RETURNING amount', [holdId]); // tx.exec(sql) too
146
+ await tx.commit(); // or tx.rollback()
147
+
148
+ // Or let the client commit on resolve and roll back on throw:
149
+ await db.transaction(async (tx) => { await tx.run('…'); });
70
150
  await db.close();
71
151
  ```
72
152
 
153
+ A `SqlegoClientError` with code `tx-expired` means the server rolled the
154
+ transaction back (lease, hard cap, or disconnect); `tx-busy` means another
155
+ client's transaction kept the request waiting too long.
156
+
73
157
  Server location: `SQLEGO_BIN`, else the compiled `bin/sqlego` next to the
74
158
  package, else `sqlego` on `PATH`; pass `serverCommand` to override.
75
159
 
package/bin/sqlego CHANGED
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/sqlego
3
- size: 62243442 bytes
4
- sha256: 721e0dee76219c45e7f34b6be82f3ef9b87e555bb30a6d041dfdaac12b337a33
3
+ size: 62276466 bytes
4
+ sha256: f3c0c81ff2125491379617417e3ddd4160c404e111d560aeb37164f934ab7e29
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type BatchResult, type HelloResult, type RunResult, type SqlParams, type SqlRow, type Statement, type StatusResult } from './protocol.ts';
1
+ import { type BatchResult, type BeginResult, type ExecResult, type HelloResult, type RunResult, type SqlParams, type SqlRow, type Statement, type StatementResult, type StatusResult, type TransactionMode } from './protocol.ts';
2
2
  import { type FilePaths } from './paths.ts';
3
3
  /**
4
4
  * Runs in Node and Bun alike (node:net, node:child_process only; no SQLite
@@ -21,6 +21,15 @@ export type ClientOptions = Readonly<{
21
21
  /** Per-request timeout. Default 60 000. */
22
22
  requestTimeoutMs?: number;
23
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
+ }>;
24
33
  export declare class SqlegoClientError extends Error {
25
34
  readonly code: string;
26
35
  constructor(code: string, message: string);
@@ -40,8 +49,42 @@ export declare class SqlegoClient {
40
49
  get server(): HelloResult;
41
50
  query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]>;
42
51
  run(sql: string, params?: SqlParams): Promise<RunResult>;
52
+ /**
53
+ * Exactly one statement, any kind: `rows` holds what it returned (SELECT,
54
+ * PRAGMA, `INSERT … RETURNING`; empty otherwise), `reader` identifies even
55
+ * an empty result set, and `changes` the rows it
56
+ * changed (0 for a read). Integers beyond ±2^53-1 come back as `bigint`,
57
+ * blobs as `Uint8Array`; `bigint` and `Uint8Array` parameters bind losslessly.
58
+ */
59
+ statement<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<StatementResult<Row>>;
60
+ /**
61
+ * Several statements in one text (a schema, a migration), no parameters, run
62
+ * in order until the first failure; earlier statements keep their effect
63
+ * unless this runs inside a transaction that is then rolled back.
64
+ * Transaction control anywhere in the text is refused, as with `run`.
65
+ */
66
+ exec(sql: string): Promise<ExecResult>;
43
67
  /** One transaction; the whole batch rolls back on the first failure. */
44
68
  batch(statements: readonly Statement[]): Promise<BatchResult['results']>;
69
+ /**
70
+ * Opens a transaction held across requests. It is bound to this connection
71
+ * and rolled back by the server if the connection drops, the lease runs out
72
+ * between requests, or the server's hard cap is reached; other clients'
73
+ * statements wait until it ends. End it with `commit` or `rollback`.
74
+ */
75
+ begin(options?: BeginOptions): Promise<SqlegoTransaction>;
76
+ /** Runs `work` in a transaction: commits when it resolves, rolls back when it rejects (and rethrows). */
77
+ transaction<T>(work: (tx: SqlegoTransaction) => Promise<T>, options?: BeginOptions): Promise<T>;
78
+ /** @internal Statements inside a transaction; `SqlegoTransaction` is the public face. */
79
+ transactionQuery<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<Row[]>;
80
+ /** @internal */
81
+ transactionRun(txId: number, sql: string, params?: SqlParams): Promise<RunResult>;
82
+ /** @internal */
83
+ transactionStatement<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<StatementResult<Row>>;
84
+ /** @internal */
85
+ transactionExec(txId: number, sql: string): Promise<ExecResult>;
86
+ /** @internal */
87
+ transactionEnd(txId: number, how: 'commit' | 'rollback'): Promise<void>;
45
88
  status(): Promise<StatusResult>;
46
89
  /** Asks the server to shut down; the connection closes as a consequence. */
47
90
  stop(): Promise<void>;
@@ -67,6 +110,36 @@ export declare class SqlegoClient {
67
110
  private settleAll;
68
111
  private waitForExit;
69
112
  }
113
+ /**
114
+ * One open transaction on a `SqlegoClient`. Every method rejects with a
115
+ * `SqlegoClientError` whose code is `tx-expired` once the server has rolled
116
+ * it back (lease, hard cap, disconnect) and `tx-invalid` after it ended.
117
+ */
118
+ export declare class SqlegoTransaction {
119
+ readonly id: number;
120
+ /** The lease the server granted, which may be shorter than requested. */
121
+ readonly leaseMs: number;
122
+ /** The server's hard cap on this transaction's life. */
123
+ readonly maxDurationMs: number;
124
+ private readonly client;
125
+ private ended;
126
+ constructor(client: SqlegoClient, opened: BeginResult);
127
+ /** True once `commit` or `rollback` has been sent; the server may also have ended it on its own. */
128
+ get closed(): boolean;
129
+ query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]>;
130
+ run(sql: string, params?: SqlParams): Promise<RunResult>;
131
+ /** `SqlegoClient.statement` inside this transaction. */
132
+ statement<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<StatementResult<Row>>;
133
+ /** `SqlegoClient.exec` inside this transaction; savepoints are allowed, ending the transaction is not. */
134
+ exec(sql: string): Promise<ExecResult>;
135
+ /** `SAVEPOINT name`: a nested scope that `rollbackTo` can undo and `release` folds into the transaction. */
136
+ savepoint(name: string): Promise<void>;
137
+ release(name: string): Promise<void>;
138
+ /** Undoes everything since the savepoint; the savepoint itself stays until released. */
139
+ rollbackTo(name: string): Promise<void>;
140
+ commit(): Promise<void>;
141
+ rollback(): Promise<void>;
142
+ }
70
143
  /**
71
144
  * How to start a server: SQLEGO_BIN if set; the compiled `sqlego` binary when
72
145
  * running as one; the dev entry (`bun src/cli.ts`) when running from source
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { SqlegoClient, SqlegoClientError, defaultServerCommand, type ClientOptions } from './client.ts';
1
+ export { SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, type BeginOptions, type ClientOptions } from './client.ts';
2
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 StatusResult, type HelloResult, } from './protocol.ts';
3
+ export { PROTOCOL_VERSION, type SqlParams, type SqlRow, type SqlValue, type Statement, type RunResult, type QueryResult, type BatchResult, type StatementResult, type ExecResult, type BeginResult, type StatusResult, type HelloResult, type TransactionMode, type TransactionStatus, } from './protocol.ts';
4
4
  export { VERSION } from './version.ts';