@noego/sqlego 0.1.2-dev.4 → 0.1.2-dev.6

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/src/server.ts CHANGED
@@ -1,17 +1,18 @@
1
- import { Database, type SQLQueryBindings } from 'bun:sqlite';
2
- import { rmSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
1
+ import { Database, type SQLQueryBindings, type Statement as SqliteStatement } from 'bun:sqlite';
2
+ import { rmSync, writeFileSync, existsSync, mkdirSync, statSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { Result, Trust } from '@noego/trust';
5
5
  import {
6
+ FrameReader,
6
7
  PROTOCOL_VERSION,
7
8
  encodeFrame,
8
9
  encodeResultRows,
9
10
  encodeWireInteger,
11
+ errnoCode,
10
12
  errorMessage,
11
13
  fromJson,
12
14
  parseRequest,
13
15
  parseRows,
14
- splitFrames,
15
16
  splitSqlStatements,
16
17
  toJson,
17
18
  transactionControl,
@@ -53,6 +54,12 @@ export type ServerOptions = Readonly<{
53
54
  txMaxDurationMs?: number;
54
55
  /** How long another client's request waits behind an open transaction before failing with `tx-busy`. Default 30 000. */
55
56
  txQueueTimeoutMs?: number;
57
+ /**
58
+ * How often the owner checks that the file is still where it opened it; a
59
+ * file deleted (or its directory), or replaced by another file, is
60
+ * released at once, clients or not. Default 5 000.
61
+ */
62
+ fileCheckMs?: number;
56
63
  }>;
57
64
 
58
65
  /**
@@ -68,6 +75,7 @@ export const DEFAULT_PRAGMAS: readonly string[] = ['auto_vacuum = INCREMENTAL',
68
75
  export const DEFAULT_TX_LEASE_MS = 10_000;
69
76
  export const DEFAULT_TX_MAX_DURATION_MS = 60_000;
70
77
  export const DEFAULT_TX_QUEUE_TIMEOUT_MS = 30_000;
78
+ export const DEFAULT_FILE_CHECK_MS = 5_000;
71
79
 
72
80
  type SqliteFailure = { readonly kind: 'sqlite'; readonly message: string; readonly code?: string };
73
81
  type BadRequest = { readonly kind: 'bad-request'; readonly message: string };
@@ -75,6 +83,12 @@ type TransactionFailure = { readonly kind: 'tx-expired' | 'tx-invalid'; readonly
75
83
  type CleanupFailure = { readonly kind: 'cleanup-failed'; readonly message: string };
76
84
  type WriteFailure = { readonly kind: 'write-failed'; readonly message: string };
77
85
  type EncodeFailure = { readonly kind: 'encode-failed'; readonly message: string };
86
+ type OwnerBusy = { readonly kind: 'owner-busy'; readonly message: string };
87
+
88
+ /** Which file the owner opened at its path: a different identity there means the path now leads elsewhere. */
89
+ type FileIdentity = Readonly<{ dev: bigint; ino: bigint }>;
90
+ /** Whether the file is still at its path: there, gone (deleted, or its directory), or replaced by another file. */
91
+ type FilePresence = 'present' | 'gone' | 'replaced';
78
92
 
79
93
  /** One statement as `executeOne` ran it: its raw rows and what it changed. */
80
94
  type Executed = { reader: boolean; rows: unknown; changes: number; lastInsertRowid: number | bigint };
@@ -90,26 +104,111 @@ const cleanupFailure = (cause: unknown): CleanupFailure => ({ kind: 'cleanup-fai
90
104
  const writeFailure = (cause: unknown): WriteFailure => ({ kind: 'write-failed', message: errorMessage(cause) });
91
105
  const badRequest = (message: string) => Result.err<BadRequest>({ kind: 'bad-request', message });
92
106
 
107
+ /** Distinct statements each connection keeps prepared; past this, the least recently used is finalized. */
108
+ const STATEMENT_CACHE_SIZE = 256;
109
+
110
+ type PreparedStatement = SqliteStatement<unknown, SQLQueryBindings[]>;
111
+
93
112
  /**
94
- * Carries one statement's failure out of a `db.transaction` callback: bun:sqlite
95
- * rolls the transaction back only when that callback throws.
113
+ * The prepared statements one connection reuses. Every statement handed out
114
+ * here is finalized here, when evicted and by `clear()` before the connection
115
+ * closes, never left to garbage collection: bun:sqlite's `close()` is
116
+ * sqlite3_close_v2, which keeps a connection with an unfinalized statement
117
+ * open, descriptors and all, until that statement is collected. bun:sqlite's
118
+ * own `db.query()` cache cannot serve: it keeps its first 20 statements and
119
+ * returns every later one uncached and unfinalized (2026-10-17: owners kept
120
+ * thousands of descriptors on released, deleted files).
121
+ *
122
+ * SQL with a `*` anywhere is prepared for one use and finalized after it,
123
+ * never cached. Its result columns (`SELECT *`, `t.*`, `RETURNING *`) follow
124
+ * the schema, and a reused bun:sqlite statement keeps the column names it
125
+ * last read whenever the schema changes without bun:sqlite seeing it: on the
126
+ * reader after the writer's DDL, on the writer after a rollback undoes DDL
127
+ * (2026-10-18, Bun 1.3.6: a cached `SELECT *` on the reader left out a column
128
+ * the writer had just added). A column named in the SQL cannot change that
129
+ * way; one that no longer exists fails when SQLite prepares the statement again.
96
130
  */
97
- class BatchStatementFailed extends Error {
98
- readonly failure: SqliteFailure;
131
+ class StatementCache {
132
+ private readonly statements = new Map<string, PreparedStatement>();
133
+ private readonly db: Database;
134
+ private readonly onFinalizeFailed: (message: string) => void;
135
+ private used = 0;
136
+
137
+ constructor(db: Database, onFinalizeFailed: (message: string) => void) {
138
+ this.db = db;
139
+ this.onFinalizeFailed = onFinalizeFailed;
140
+ }
141
+
142
+ /** How many statements `use` has run on this connection, failed ones included. */
143
+ get runs(): number {
144
+ return this.used;
145
+ }
146
+
147
+ /**
148
+ * Runs `work` on the prepared statement for `sql` and returns its outcome;
149
+ * SQL that SQLite cannot prepare is a sqlite failure.
150
+ */
151
+ use<T, E>(sql: string, work: (statement: PreparedStatement) => Result<T, E>) {
152
+ this.used += 1;
153
+ if (sql.includes('*')) return this.useOnce(sql, work);
154
+ const prepared = this.prepare(sql);
155
+ if (!prepared.ok) return prepared;
156
+ return work(prepared.value);
157
+ }
99
158
 
100
- constructor(failure: SqliteFailure) {
101
- super(failure.message);
102
- this.failure = failure;
159
+ /** Finalizes every statement, so the connection can then close for real. */
160
+ clear(): void {
161
+ for (const statement of this.statements.values()) this.finalize(statement);
162
+ this.statements.clear();
163
+ }
164
+
165
+ /** The cached statement for `sql`, prepared on first use. */
166
+ private prepare(sql: string) {
167
+ const cached = this.statements.get(sql);
168
+ if (cached !== undefined) {
169
+ // Re-inserted so the first key is always the least recently used.
170
+ this.statements.delete(sql);
171
+ this.statements.set(sql, cached);
172
+ return Result.ok(cached);
173
+ }
174
+ const prepared = Trust.try((): PreparedStatement => this.db.prepare<unknown, SQLQueryBindings[]>(sql), sqliteFailure);
175
+ if (!prepared.ok) return prepared;
176
+ this.statements.set(sql, prepared.value);
177
+ if (this.statements.size > STATEMENT_CACHE_SIZE) this.evictLeastRecentlyUsed();
178
+ return prepared;
179
+ }
180
+
181
+ /** `use` for SQL that is never cached: prepared, run, finalized. */
182
+ private useOnce<T, E>(sql: string, work: (statement: PreparedStatement) => Result<T, E>) {
183
+ const prepared = Trust.try((): PreparedStatement => this.db.prepare<unknown, SQLQueryBindings[]>(sql), sqliteFailure);
184
+ if (!prepared.ok) return prepared;
185
+ const outcome = work(prepared.value);
186
+ this.finalize(prepared.value);
187
+ return outcome;
188
+ }
189
+
190
+ private evictLeastRecentlyUsed(): void {
191
+ const oldest = this.statements.entries().next();
192
+ if (oldest.done) return;
193
+ const [sql, statement] = oldest.value;
194
+ this.statements.delete(sql);
195
+ this.finalize(statement);
196
+ }
197
+
198
+ private finalize(statement: PreparedStatement): void {
199
+ const finalized = Trust.try(() => statement.finalize(), sqliteFailure);
200
+ if (!finalized.ok && finalized.error.kind === 'sqlite') this.onFinalizeFailed(finalized.error.message);
103
201
  }
104
202
  }
105
203
 
106
204
  /**
107
- * `outbound` holds bytes the kernel buffer refused (null when there are none).
108
- * Bun's `socket.write` returns the byte count it accepted and drops the rest,
109
- * so a large result followed by another frame corrupts the stream unless the
110
- * remainder is carried and flushed on `drain`.
205
+ * `frames` reads the request frames of this socket from its raw bytes (see
206
+ * `FrameReader.pushBytes`). `outbound` holds bytes the kernel buffer refused
207
+ * (null when there are none). Bun's `socket.write` returns the byte count it
208
+ * accepted and drops the rest, so a large result followed by another frame
209
+ * corrupts the stream unless the remainder is carried and flushed on `drain`.
111
210
  */
112
- type Connection = { id: number; buffer: string; outbound: Buffer | null; socket: ServerSocket; detachedPlain: boolean };
211
+ type Connection = { id: number; frames: FrameReader; outbound: Buffer | null; socket: ServerSocket; detachedPlain: boolean };
113
212
 
114
213
  /** Each socket carries its connection in Bun's typed `data` slot: null until `open` assigns it. */
115
214
  type ServerSocket = import('bun').Socket<Connection | null>;
@@ -172,6 +271,16 @@ export class SqlegoServer {
172
271
  readonly pragmas: readonly string[];
173
272
  private readonly db: Database;
174
273
  private readonly reader: Database | null;
274
+ private readonly statements: StatementCache;
275
+ private readonly readerStatements: StatementCache | null;
276
+ /**
277
+ * The writer's `total_changes()` as the last `statement`/`exec` statement
278
+ * left it, and `statements.runs` then. While no statement has run since,
279
+ * it is the next one's "before" and costs no read; every statement that can
280
+ * change rows runs through `statements`, so a changed count means it may be
281
+ * stale. (BEGIN, COMMIT and ROLLBACK, run past the cache, never move it.)
282
+ */
283
+ private lastTotal: Readonly<{ total: number; runs: number }> | null = null;
175
284
 
176
285
  get capabilities(): readonly string[] {
177
286
  return this.reader ? ['detached-plain'] : [];
@@ -182,6 +291,9 @@ export class SqlegoServer {
182
291
  private listener: import('bun').UnixSocketListener<Connection | null> | null = null;
183
292
  private idleTimer: ReturnType<typeof setTimeout> | null = null;
184
293
  private idleSince: number | null = null;
294
+ /** The file as `listen` found it at its path (null when it could not be read then: only its presence is checked). */
295
+ private identity: FileIdentity | null = null;
296
+ private fileCheckTimer: ReturnType<typeof setTimeout> | null = null;
185
297
  private nextConnectionId = 1;
186
298
  private nextTransactionId = 1;
187
299
  private requestsServed = 0;
@@ -198,6 +310,9 @@ export class SqlegoServer {
198
310
  this.reader = reader;
199
311
  this.pragmas = pragmas;
200
312
  this.log = options.log ?? (() => undefined);
313
+ const finalizeFailed = (message: string) => this.log('finalize failed', { error: message });
314
+ this.statements = new StatementCache(db, finalizeFailed);
315
+ this.readerStatements = reader ? new StatementCache(reader, finalizeFailed) : null;
201
316
  }
202
317
 
203
318
  /** Opens (creating if needed) the database file and applies the pragmas. */
@@ -210,15 +325,19 @@ export class SqlegoServer {
210
325
  mkdirSync(path.dirname(paths.value.file), { recursive: true });
211
326
  // safeIntegers: SQLite integers arrive as bigint so `statement`/`exec`
212
327
  // can return all 64 bits; `query`/`run`/`batch` still send JSON numbers.
213
- const opened = new Database(paths.value.file, { create: true, strict: false, safeIntegers: true });
214
- for (const pragma of pragmas) opened.exec(`PRAGMA ${pragma}`);
215
- return opened;
328
+ return new Database(paths.value.file, { create: true, strict: false, safeIntegers: true });
216
329
  },
217
330
  (cause) => ({ kind: 'open-failed', message: `cannot open ${paths.value.file}: ${errorMessage(cause)}` }),
218
331
  );
219
332
  if (!db.ok) return db;
333
+ const configured = Trust.try(
334
+ () => {
335
+ for (const pragma of pragmas) db.value.exec(`PRAGMA ${pragma}`);
336
+ },
337
+ (cause) => ({ kind: 'open-failed', message: `cannot open ${paths.value.file}: ${errorMessage(cause)}` }),
338
+ );
220
339
  let reader: Database | null = null;
221
- const openedReader = Trust.try(() => {
340
+ const openedReader = !configured.ok ? configured : Trust.try(() => {
222
341
  const mode = db.value.query('PRAGMA journal_mode').values()[0]?.[0];
223
342
  if (String(mode).toLowerCase() !== 'wal') return;
224
343
  reader = new Database(paths.value.file, { readonly: true, safeIntegers: true });
@@ -228,9 +347,8 @@ export class SqlegoServer {
228
347
  }, (cause) => ({ kind: 'open-failed', message: `cannot open reader for ${paths.value.file}: ${errorMessage(cause)}` }));
229
348
  const server = new SqlegoServer(options, paths.value, db.value, [...pragmas], reader);
230
349
  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));
350
+ // No socket/metadata has been created yet; only the connections opened here must go.
351
+ server.closeConnections();
234
352
  return openedReader;
235
353
  }
236
354
  return Result.ok(server);
@@ -292,33 +410,43 @@ export class SqlegoServer {
292
410
  (cause) => ({ kind: 'listen-failed', message: `cannot listen on ${this.paths.socket}: ${errorMessage(cause)}` }),
293
411
  );
294
412
  if (!bound.ok) return bound;
413
+ this.identity = this.fileIdentity();
295
414
  this.armIdleTimer();
415
+ this.armFileCheck();
296
416
  this.log('listening', { file: this.paths.file, socket: this.paths.socket, pid: process.pid, idleTimeoutMs: this.options.idleTimeoutMs });
297
417
  return Result.ok(undefined);
298
418
  }
299
419
 
300
- /** Graceful stop: refuse new work, drop clients, release the file, remove socket/meta/lock. Every step is attempted. */
420
+ /**
421
+ * Graceful stop: refuse new work, drop clients, close the database, then
422
+ * remove lock, socket and meta and stop listening. Every step is attempted.
423
+ * The database closes before the socket stops answering: a client waiting
424
+ * for the file to be released (one retiring this owner) sees nothing answer
425
+ * only once the file is closed, so the owner it places the file with next
426
+ * never holds the file alongside this one. A client whose connect landed
427
+ * while this ran is dropped with the listener and connects again.
428
+ */
301
429
  stop(reason: string): void {
302
430
  if (this.stopping) return;
303
431
  this.stopping = true;
304
432
  this.log('stopping', { reason, clients: this.connections.size, requestsServed: this.requestsServed });
305
433
  if (this.idleTimer) clearTimeout(this.idleTimer);
434
+ if (this.fileCheckTimer) clearTimeout(this.fileCheckTimer);
306
435
  if (this.transaction) this.endTransaction('server stopping', 'tx-expired', true);
307
436
  for (const queued of this.queue.splice(0)) clearTimeout(queued.timer);
308
- // Socket file first: a client that connects after this point falls through
309
- // to claim-and-spawn instead of racing a closing server.
437
+ for (const connection of this.connections.values()) {
438
+ this.reportCleanup('end connection', Trust.try(() => connection.socket.end(), cleanupFailure));
439
+ }
440
+ this.closeConnections();
441
+ // The lock before the socket: once the socket is gone a client claims the
442
+ // lock to place the file anew, and that claim is not this owner's to remove.
443
+ this.reportCleanup('remove lock', Trust.try(() => rmSync(this.paths.lock, { force: true }), cleanupFailure));
310
444
  if (!isNamedPipe(this.paths.socket)) {
311
445
  this.reportCleanup('remove socket', Trust.try(() => rmSync(this.paths.socket, { force: true }), cleanupFailure));
312
446
  }
313
447
  this.reportCleanup('remove meta', Trust.try(() => rmSync(this.paths.meta, { force: true }), cleanupFailure));
314
- this.reportCleanup('remove lock', Trust.try(() => rmSync(this.paths.lock, { force: true }), cleanupFailure));
315
- for (const connection of this.connections.values()) {
316
- this.reportCleanup('end connection', Trust.try(() => connection.socket.end(), cleanupFailure));
317
- }
318
448
  const listener = this.listener;
319
449
  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));
321
- this.reportCleanup('close database', Trust.try(() => this.db.close(), cleanupFailure));
322
450
  }
323
451
 
324
452
  /**
@@ -334,6 +462,31 @@ export class SqlegoServer {
334
462
  }
335
463
  }
336
464
 
465
+ /**
466
+ * Closes the reader, then the writer: the last connection to close
467
+ * checkpoints the WAL and removes it, which a readonly one cannot do.
468
+ */
469
+ private closeConnections(): void {
470
+ if (this.reader) this.closeConnection('reader', this.reader, this.readerStatements);
471
+ this.closeConnection('database', this.db, this.statements);
472
+ }
473
+
474
+ /**
475
+ * Finalizes the connection's statements, then closes it at once with
476
+ * `close(true)` (sqlite3_close), which refuses while any statement is still
477
+ * unfinalized; plain `close()` would leave the connection a zombie that keeps
478
+ * the file's descriptors until garbage collection. A refusal (SQLite words it
479
+ * "database is locked") is logged and the deferred close still runs, so the
480
+ * file is released no later than that statement is collected.
481
+ */
482
+ private closeConnection(name: 'reader' | 'database', database: Database, statements: StatementCache | null): void {
483
+ statements?.clear();
484
+ const closed = Trust.try(() => database.close(true), cleanupFailure);
485
+ if (closed.ok) return;
486
+ this.reportCleanup(`close ${name} (deferred: a statement is still unfinalized)`, closed);
487
+ this.reportCleanup(`close ${name}`, Trust.try(() => database.close(), cleanupFailure));
488
+ }
489
+
337
490
  status(): StatusResult {
338
491
  return {
339
492
  file: this.paths.file,
@@ -390,7 +543,7 @@ export class SqlegoServer {
390
543
  return;
391
544
  }
392
545
  const id = this.nextConnectionId++;
393
- const connection: Connection = { id, buffer: '', outbound: null, socket, detachedPlain: false };
546
+ const connection: Connection = { id, frames: new FrameReader(), outbound: null, socket, detachedPlain: false };
394
547
  this.connections.set(id, connection);
395
548
  socket.data = connection;
396
549
  this.disarmIdleTimer();
@@ -419,9 +572,7 @@ export class SqlegoServer {
419
572
  private onData(socket: ServerSocket, data: Buffer): void {
420
573
  const connection = socket.data;
421
574
  if (!connection) return;
422
- const { frames, rest } = splitFrames(connection.buffer + data.toString('utf8'));
423
- connection.buffer = rest;
424
- for (const frame of frames) {
575
+ for (const frame of connection.frames.pushBytes(data)) {
425
576
  if (this.stopping) return;
426
577
  this.accept(connection, frame);
427
578
  }
@@ -536,6 +687,7 @@ export class SqlegoServer {
536
687
  case 'tx-invalid': return { id: request.id, ok: false, error: { code: 'tx-invalid', message: outcome.error.message } };
537
688
  case 'encode-failed': return { id: request.id, ok: false, error: { code: 'encode-failed', message: outcome.error.message } };
538
689
  case 'adopt-failed': return { id: request.id, ok: false, error: { code: 'adopt-failed', message: outcome.error.message } };
690
+ case 'owner-busy': return { id: request.id, ok: false, error: { code: 'owner-busy', message: outcome.error.message } };
539
691
  default: {
540
692
  const unhandled: never = outcome.error;
541
693
  return unhandled;
@@ -555,7 +707,7 @@ export class SqlegoServer {
555
707
  case 'commit': return this.finish(connection, request.txId, 'commit');
556
708
  case 'rollback': return this.finish(connection, request.txId, 'rollback');
557
709
  case 'status': return Result.ok(this.status());
558
- case 'stop': return Result.ok({ stopping: true });
710
+ case 'stop': return this.stopRequest(connection);
559
711
  case 'adopt': return this.adopt(request.file, request.pragmas, request.idleTimeoutMs);
560
712
  default: {
561
713
  const unhandled: never = request;
@@ -564,6 +716,25 @@ export class SqlegoServer {
564
716
  }
565
717
  }
566
718
 
719
+ /**
720
+ * A client's `stop`: granted only to the file's sole connection, then
721
+ * `serve` releases this file (and the process exits when it was the last).
722
+ * While other clients are connected, or another connection's transaction is
723
+ * open, it is refused with `owner-busy` and nothing is released: a client
724
+ * must never take a file away from the clients using it (2026-10-18: a CLI
725
+ * from another build stopped the running app's files, a 7-minute outage).
726
+ */
727
+ private stopRequest(connection: Connection) {
728
+ const others = this.connections.size - (this.connections.has(connection.id) ? 1 : 0);
729
+ const foreign = this.transaction !== null && this.transaction.connection !== connection;
730
+ if (others > 0 || foreign) {
731
+ const held = foreign && this.transaction ? `; transaction ${this.transaction.id} of another client is open` : '';
732
+ const clients = `${others} other client${others === 1 ? '' : 's'}`;
733
+ return Result.err<OwnerBusy>({ kind: 'owner-busy', message: `${this.paths.file} is in use by ${clients}${held}; nothing was released` });
734
+ }
735
+ return Result.ok({ stopping: true as const });
736
+ }
737
+
567
738
  /**
568
739
  * Serves one more file from this process, with this file's transaction
569
740
  * settings and log but its own pragmas and idle timeout. Only a standalone
@@ -671,13 +842,10 @@ export class SqlegoServer {
671
842
  }
672
843
 
673
844
  private query(sql: string, params?: SqlParams, db = this.db) {
674
- const fetched = Trust.try(
675
- (): unknown => {
676
- const statement = db.query(sql);
677
- return params === undefined ? statement.all() : statement.all(...bindings(params));
678
- },
845
+ const fetched = this.statementsOf(db).use(sql, (statement) => Trust.try(
846
+ (): unknown => (params === undefined ? statement.all() : statement.all(...bindings(params))),
679
847
  sqliteFailure,
680
- );
848
+ ));
681
849
  if (!fetched.ok) return fetched;
682
850
  const rows = parseRows(fetched.value);
683
851
  if (!rows.ok) return Result.err<SqliteFailure>({ kind: 'sqlite', message: `unexpected row shape: ${rows.error.message}` });
@@ -686,9 +854,8 @@ export class SqlegoServer {
686
854
  }
687
855
 
688
856
  private run(sql: string, params?: SqlParams, db = this.db) {
689
- return Trust.try(
857
+ return this.statementsOf(db).use(sql, (statement) => Trust.try(
690
858
  () => {
691
- const statement = db.query(sql);
692
859
  const outcome = params === undefined ? statement.run() : statement.run(...bindings(params));
693
860
  // safeIntegers may report either counter as bigint; `run` keeps answering with numbers.
694
861
  const result: RunResult = db === this.reader
@@ -697,56 +864,83 @@ export class SqlegoServer {
697
864
  return result;
698
865
  },
699
866
  sqliteFailure,
700
- );
867
+ ));
868
+ }
869
+
870
+ /** The statement cache of `db`, which is this file's writer or its reader. */
871
+ private statementsOf(db: Database): StatementCache {
872
+ return db === this.reader && this.readerStatements !== null ? this.readerStatements : this.statements;
701
873
  }
702
874
 
703
875
  /**
704
- * Prepares and steps one statement exactly once. A statement with result
705
- * columns (SELECT, PRAGMA, `INSERT … RETURNING`) is stepped through `all()`
706
- * and never re-run for its changes; one without is stepped through `run()`.
707
- * `changes` is SQLite's own count when the statement changed anything
708
- * (`total_changes()` moved), else 0 — `changes()` alone would repeat the
709
- * previous write's count after a read or DDL.
876
+ * Steps one statement exactly once (see `step`), prepared once per
877
+ * connection (see `StatementCache`). A statement with result columns
878
+ * (SELECT, PRAGMA, `INSERT … RETURNING`) is a reader and returns its rows;
879
+ * it is never re-run for its changes. `changes` is SQLite's own count when
880
+ * the statement changed anything (`total_changes()` moved), else 0 —
881
+ * `changes()` alone would repeat the previous write's count after a read or
882
+ * DDL. On the writer one counters read follows the statement; the total
883
+ * before it is the one the previous statement's read left (`lastTotal`),
884
+ * read afresh only when another statement ran in between. The reader cannot
885
+ * write: its statements report 0 and 0 and read no counters.
710
886
  */
711
887
  private executeOne(sql: string, params: SqlParams | undefined, db = this.db) {
712
- const before = this.counters(db);
713
- if (!before.ok) return before;
714
- const prepared = Trust.try(() => db.prepare(sql), sqliteFailure);
715
- if (!prepared.ok) return prepared;
716
- const statement = prepared.value;
717
888
  const args: SQLQueryBindings[] = params === undefined ? [] : bindings(params);
718
- const ran = Trust.try(
719
- () => {
720
- const columns: unknown = statement.columnNames;
721
- if (!Array.isArray(columns)) throw new Error('SQLite returned invalid column metadata');
722
- const reader = columns.length > 0;
723
- if (reader) {
724
- const rows: unknown = statement.all(...args);
725
- return { reader, rows };
726
- }
727
- statement.run(...args);
728
- return { reader, rows: [] };
729
- },
730
- sqliteFailure,
731
- );
732
- const finalized = Trust.try(() => statement.finalize(), sqliteFailure);
733
- if (!finalized.ok && finalized.error.kind === 'sqlite') this.log('finalize failed', { error: finalized.error.message });
889
+ if (db === this.reader) {
890
+ const ran = this.step(sql, args, db);
891
+ if (!ran.ok) return ran;
892
+ const executed: Executed = { reader: ran.value.reader, rows: ran.value.rows, changes: 0, lastInsertRowid: 0 };
893
+ return Result.ok(executed);
894
+ }
895
+ const before = this.writerTotal();
896
+ if (!before.ok) return before;
897
+ const ran = this.step(sql, args, db);
734
898
  if (!ran.ok) return ran;
735
899
  const after = this.counters(db);
736
900
  if (!after.ok) return after;
901
+ this.lastTotal = { total: after.value.total, runs: this.statements.runs };
737
902
  const executed: Executed = {
738
903
  reader: ran.value.reader,
739
904
  rows: ran.value.rows,
740
- changes: db === this.reader || after.value.total === before.value.total ? 0 : after.value.changes,
741
- lastInsertRowid: db === this.reader ? 0 : after.value.lastInsertRowid,
905
+ changes: after.value.total === before.value ? 0 : after.value.changes,
906
+ lastInsertRowid: after.value.lastInsertRowid,
742
907
  };
743
908
  return Result.ok(executed);
744
909
  }
745
910
 
746
- private counters(db = this.db) {
747
- const read = Trust.try(
748
- (): unknown => db.query('SELECT changes() AS changes, total_changes() AS total, last_insert_rowid() AS rowid').get(),
911
+ /**
912
+ * Steps one statement on `db` through `all()`, then reads its columns: when
913
+ * another connection changed the schema, SQLite prepares the statement again
914
+ * as it steps, and only then do its columns match the rows. Read before the
915
+ * step they were the old ones, and `SELECT *` on the reader dropped the
916
+ * columns the writer had just added (2026-10-18). A statement without
917
+ * result columns steps to its end in `all()` just as in `run()`.
918
+ */
919
+ private step(sql: string, args: SQLQueryBindings[], db: Database) {
920
+ return this.statementsOf(db).use(sql, (statement) => Trust.try(
921
+ () => {
922
+ const rows: unknown = statement.all(...args);
923
+ const columns: unknown = statement.columnNames;
924
+ if (!Array.isArray(columns)) throw new Error('SQLite returned invalid column metadata');
925
+ return { reader: columns.length > 0, rows };
926
+ },
749
927
  sqliteFailure,
928
+ ));
929
+ }
930
+
931
+ /** The writer's `total_changes()` now: `lastTotal` while no statement has run since, else read. */
932
+ private writerTotal() {
933
+ const last = this.lastTotal;
934
+ if (last !== null && last.runs === this.statements.runs) return Result.ok(last.total);
935
+ const read = this.counters();
936
+ if (!read.ok) return read;
937
+ return Result.ok(read.value.total);
938
+ }
939
+
940
+ private counters(db = this.db) {
941
+ const read = this.statementsOf(db).use(
942
+ 'SELECT changes() AS changes, total_changes() AS total, last_insert_rowid() AS rowid',
943
+ (statement) => Trust.try((): unknown => statement.get(), sqliteFailure),
750
944
  );
751
945
  if (!read.ok) return read;
752
946
  return parseCounters(read.value);
@@ -793,7 +987,12 @@ export class SqlegoServer {
793
987
  return Result.ok(result);
794
988
  }
795
989
 
796
- /** All statements in one transaction; any failure rolls the whole batch back. */
990
+ /**
991
+ * All statements in one transaction; any failure rolls the whole batch back.
992
+ * Plain BEGIN/COMMIT/ROLLBACK, not `db.transaction()`: bun:sqlite prepares
993
+ * that helper's statements once per connection and never finalizes them, so
994
+ * every file that had run a batch stayed open after it was released.
995
+ */
797
996
  private batch(connection: Connection, statements: readonly Statement[]) {
798
997
  if (statements.length === 0) return badRequest('batch requires a non-empty statements array');
799
998
  if (this.transaction && this.transaction.connection === connection) {
@@ -803,22 +1002,28 @@ export class SqlegoServer {
803
1002
  const control = transactionControl(item.sql);
804
1003
  if (control !== null) return badRequest(`statements[${index}]: ${control.toUpperCase()} is not allowed in a batch, which is already one transaction`);
805
1004
  }
806
- return Trust.try(
807
- () => {
808
- const transaction = this.db.transaction((items: readonly Statement[]) => items.map((item) => this.batchItem(item)));
809
- const result: BatchResult = { results: transaction(statements) };
810
- return result;
811
- },
812
- (cause) => (cause instanceof BatchStatementFailed ? cause.failure : sqliteFailure(cause)),
813
- );
1005
+ // A BEGIN that fails opened nothing, so there is nothing to roll back.
1006
+ const begun = Trust.try(() => this.db.exec('BEGIN'), sqliteFailure);
1007
+ if (!begun.ok) return begun;
1008
+ const results: Array<RunResult | QueryResult> = [];
1009
+ for (const item of statements) {
1010
+ const outcome = item.mode === 'query' ? this.query(item.sql, item.params) : this.run(item.sql, item.params);
1011
+ if (!outcome.ok) return this.abandonBatch(outcome);
1012
+ results.push(outcome.value);
1013
+ }
1014
+ const committed = Trust.try(() => this.db.exec('COMMIT'), sqliteFailure);
1015
+ if (!committed.ok) return this.abandonBatch(committed);
1016
+ const result: BatchResult = { results };
1017
+ return Result.ok(result);
814
1018
  }
815
1019
 
816
- /** One statement of a batch, inside its transaction: a failure must throw so bun:sqlite rolls back. */
817
- private batchItem(item: Statement): RunResult | QueryResult {
818
- const outcome = item.mode === 'query' ? this.query(item.sql, item.params) : this.run(item.sql, item.params);
819
- if (outcome.ok) return outcome.value;
820
- //trust:accept bun:sqlite rolls a transaction back only when its callback throws; batch() turns this back into a Result
821
- throw new BatchStatementFailed(outcome.error);
1020
+ /** Rolls back what a failed batch (or its failed COMMIT) left open, and hands its failure on. */
1021
+ private abandonBatch<Failed>(failed: Failed): Failed {
1022
+ if (this.db.inTransaction) {
1023
+ const rolledBack = Trust.try(() => this.db.exec('ROLLBACK'), sqliteFailure);
1024
+ if (!rolledBack.ok && rolledBack.error.kind === 'sqlite') this.log('rollback failed', { op: 'batch', error: rolledBack.error.message });
1025
+ }
1026
+ return failed;
822
1027
  }
823
1028
 
824
1029
  /* ------------------------------------------------------------------ *
@@ -1010,6 +1215,85 @@ export class SqlegoServer {
1010
1215
  this.idleTimer = null;
1011
1216
  }
1012
1217
  }
1218
+
1219
+ /* ------------------------------------------------------------------ *
1220
+ * A file that left its path
1221
+ * ------------------------------------------------------------------ */
1222
+
1223
+ /**
1224
+ * Checks every `fileCheckMs` that the file is still at its path. One deleted
1225
+ * (or its directory), or replaced by another file, is released at once,
1226
+ * whoever is connected: nobody reaches that database by its path any more,
1227
+ * and an owner that kept it would hold a deleted file's space and
1228
+ * descriptors for as long as it lives (sqlego#8: owners still held test
1229
+ * fixtures deleted days before). The timer never keeps the process alive.
1230
+ */
1231
+ private armFileCheck(): void {
1232
+ if (this.fileCheckTimer) clearTimeout(this.fileCheckTimer);
1233
+ const timer = setTimeout(() => this.checkFile(), this.options.fileCheckMs ?? DEFAULT_FILE_CHECK_MS);
1234
+ timer.unref();
1235
+ this.fileCheckTimer = timer;
1236
+ }
1237
+
1238
+ private checkFile(): void {
1239
+ this.fileCheckTimer = null;
1240
+ if (this.stopping) return;
1241
+ const presence = this.filePresence();
1242
+ switch (presence) {
1243
+ case 'present':
1244
+ this.armFileCheck();
1245
+ return;
1246
+ case 'gone':
1247
+ case 'replaced':
1248
+ this.log('file left its path; releasing', { file: this.paths.file, presence, clients: this.connections.size });
1249
+ this.release(presence === 'gone' ? 'file gone' : 'file replaced');
1250
+ return;
1251
+ default: {
1252
+ const unhandled: never = presence;
1253
+ return unhandled;
1254
+ }
1255
+ }
1256
+ }
1257
+
1258
+ /**
1259
+ * Where the file stands at its path now. A path that cannot be read for
1260
+ * another reason (permissions, I/O) counts as present: only a file that is
1261
+ * known to be gone or different is released.
1262
+ */
1263
+ private filePresence(): FilePresence {
1264
+ const stat = Trust.try(
1265
+ () => statSync(this.paths.file, { bigint: true }),
1266
+ (cause) => {
1267
+ const code = errnoCode(cause);
1268
+ return code === 'ENOENT' || code === 'ENOTDIR' ? { kind: 'gone' as const } : { kind: 'unreadable' as const };
1269
+ },
1270
+ );
1271
+ if (!stat.ok) {
1272
+ switch (stat.error.kind) {
1273
+ case 'gone': return 'gone';
1274
+ case 'unreadable': return 'present';
1275
+ default: {
1276
+ const unhandled: never = stat.error;
1277
+ return unhandled;
1278
+ }
1279
+ }
1280
+ }
1281
+ const known = this.identity;
1282
+ if (known === null) return 'present';
1283
+ return stat.value.dev === known.dev && stat.value.ino === known.ino ? 'present' : 'replaced';
1284
+ }
1285
+
1286
+ /** The identity of the file at its path, or null when it cannot be read. */
1287
+ private fileIdentity(): FileIdentity | null {
1288
+ const stat = Trust.try(
1289
+ () => statSync(this.paths.file, { bigint: true }),
1290
+ (cause) => ({ kind: 'unreadable' as const, message: errorMessage(cause) }),
1291
+ );
1292
+ if (stat.ok) return { dev: stat.value.dev, ino: stat.value.ino };
1293
+ if (stat.error.kind === 'unreadable') return null;
1294
+ const unhandled: never = stat.error.kind;
1295
+ return unhandled;
1296
+ }
1013
1297
  }
1014
1298
 
1015
1299
  /**