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

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.
Files changed (3) hide show
  1. package/dist/index.js +32 -32
  2. package/package.json +6 -6
  3. package/src/server.ts +137 -42
package/dist/index.js CHANGED
@@ -276,8 +276,8 @@ function parseResponse(input) {
276
276
  if (typeof id !== "number")
277
277
  return invalid("a response needs a numeric id");
278
278
  if (fields.ok === true) {
279
- const response2 = { id, ok: true, result: fields.result };
280
- return Result.ok(response2);
279
+ const response = { id, ok: true, result: fields.result };
280
+ return Result.ok(response);
281
281
  }
282
282
  if (fields.ok !== false)
283
283
  return invalid("a response needs ok: true or false");
@@ -563,10 +563,10 @@ function resolvePaths(file) {
563
563
  if (!directory.ok)
564
564
  return directory;
565
565
  const derived = Trust.try(() => {
566
- const key2 = createHash("sha1").update(canonical.value).digest("hex").slice(0, 16);
566
+ const key = createHash("sha1").update(canonical.value).digest("hex").slice(0, 16);
567
567
  const scope = createHash("sha1").update(directory.value.toLowerCase()).digest("hex").slice(0, 8);
568
- const socket2 = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${scope}-${key2}` : path2.join(directory.value, `${key2}.sock`);
569
- return { key: key2, socket: socket2, socketBytes: Buffer.byteLength(socket2) };
568
+ const socket = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${scope}-${key}` : path2.join(directory.value, `${key}.sock`);
569
+ return { key, socket, socketBytes: Buffer.byteLength(socket) };
570
570
  }, (cause) => ({ kind: "hash-failed", message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }));
571
571
  if (!derived.ok)
572
572
  return derived;
@@ -638,7 +638,7 @@ import { fileURLToPath } from "node:url";
638
638
  // package.json
639
639
  var package_default = {
640
640
  name: "@noego/sqlego",
641
- version: "0.1.2-dev.4",
641
+ version: "0.1.2-dev.5",
642
642
  description: "One owner per SQLite file, many files per owner process. Clients (CLI, Node, Bun) pass SQL over a local socket (Unix) or named pipe (Windows); the owner starts on demand and exits when idle.",
643
643
  type: "module",
644
644
  license: "ISC",
@@ -689,11 +689,11 @@ var package_default = {
689
689
  "@noego/trust": "0.5.0-dev.0"
690
690
  },
691
691
  optionalDependencies: {
692
- "@noego/sqlego-darwin-arm64": "0.1.2-dev.4",
693
- "@noego/sqlego-darwin-x64": "0.1.2-dev.4",
694
- "@noego/sqlego-linux-x64": "0.1.2-dev.4",
695
- "@noego/sqlego-linux-arm64": "0.1.2-dev.4",
696
- "@noego/sqlego-win32-x64": "0.1.2-dev.4"
692
+ "@noego/sqlego-darwin-arm64": "0.1.2-dev.5",
693
+ "@noego/sqlego-darwin-x64": "0.1.2-dev.5",
694
+ "@noego/sqlego-linux-x64": "0.1.2-dev.5",
695
+ "@noego/sqlego-linux-arm64": "0.1.2-dev.5",
696
+ "@noego/sqlego-win32-x64": "0.1.2-dev.5"
697
697
  }
698
698
  };
699
699
 
@@ -711,8 +711,8 @@ function sourceBuildId(sourceDirectory) {
711
711
  }, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
712
712
  }
713
713
  function resolveBuildId() {
714
- if ("e5711cce187d".length > 0)
715
- return "e5711cce187d";
714
+ if ("7c2ccfa0a0c5".length > 0)
715
+ return "7c2ccfa0a0c5";
716
716
  const directory = Trust.try(() => path3.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
717
717
  if (!directory.ok)
718
718
  return decideUnknownBuild(directory.error.kind);
@@ -1340,8 +1340,8 @@ function parseOneShotReply(line, parse) {
1340
1340
  if (!response.ok) {
1341
1341
  if (response.error.kind === "invalid")
1342
1342
  return probeFailed(`malformed reply: ${response.error.message}`);
1343
- const unhandled2 = response.error.kind;
1344
- return unhandled2;
1343
+ const unhandled = response.error.kind;
1344
+ return unhandled;
1345
1345
  }
1346
1346
  if (!response.value.ok)
1347
1347
  return probeFailed(`${response.value.error.code}: ${response.value.error.message}`);
@@ -1398,22 +1398,22 @@ function sleep(ms) {
1398
1398
  return new Promise((resolve) => setTimeout(resolve, ms));
1399
1399
  }
1400
1400
  export {
1401
- unpackedAsarPath,
1402
- runtimeDirectory,
1403
- platformPackageName,
1404
- pathsFor,
1405
- locateServerBinary,
1406
- localBinaryName,
1407
- isNamedPipe,
1408
- defaultServerCommand,
1409
- canonicalFile,
1410
- binaryFileName,
1411
- VERSION,
1412
- USES_NAMED_PIPES,
1413
- SqlegoTransaction,
1414
- SqlegoClientError,
1415
- SqlegoClient,
1416
- SUPPORTED_PLATFORMS,
1401
+ DEFAULT_MAX_OWNERS,
1417
1402
  PROTOCOL_VERSION,
1418
- DEFAULT_MAX_OWNERS
1403
+ SUPPORTED_PLATFORMS,
1404
+ SqlegoClient,
1405
+ SqlegoClientError,
1406
+ SqlegoTransaction,
1407
+ USES_NAMED_PIPES,
1408
+ VERSION,
1409
+ binaryFileName,
1410
+ canonicalFile,
1411
+ defaultServerCommand,
1412
+ isNamedPipe,
1413
+ localBinaryName,
1414
+ locateServerBinary,
1415
+ pathsFor,
1416
+ platformPackageName,
1417
+ runtimeDirectory,
1418
+ unpackedAsarPath
1419
1419
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noego/sqlego",
3
- "version": "0.1.2-dev.4",
3
+ "version": "0.1.2-dev.5",
4
4
  "description": "One owner per SQLite file, many files per owner process. Clients (CLI, Node, Bun) pass SQL over a local socket (Unix) or named pipe (Windows); the owner starts on demand and exits when idle.",
5
5
  "type": "module",
6
6
  "license": "ISC",
@@ -51,10 +51,10 @@
51
51
  "@noego/trust": "0.5.0-dev.0"
52
52
  },
53
53
  "optionalDependencies": {
54
- "@noego/sqlego-darwin-arm64": "0.1.2-dev.4",
55
- "@noego/sqlego-darwin-x64": "0.1.2-dev.4",
56
- "@noego/sqlego-linux-x64": "0.1.2-dev.4",
57
- "@noego/sqlego-linux-arm64": "0.1.2-dev.4",
58
- "@noego/sqlego-win32-x64": "0.1.2-dev.4"
54
+ "@noego/sqlego-darwin-arm64": "0.1.2-dev.5",
55
+ "@noego/sqlego-darwin-x64": "0.1.2-dev.5",
56
+ "@noego/sqlego-linux-x64": "0.1.2-dev.5",
57
+ "@noego/sqlego-linux-arm64": "0.1.2-dev.5",
58
+ "@noego/sqlego-win32-x64": "0.1.2-dev.5"
59
59
  }
60
60
  }
package/src/server.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Database, type SQLQueryBindings } from 'bun:sqlite';
1
+ import { Database, type SQLQueryBindings, type Statement as SqliteStatement } from 'bun:sqlite';
2
2
  import { rmSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { Result, Trust } from '@noego/trust';
@@ -90,16 +90,64 @@ const cleanupFailure = (cause: unknown): CleanupFailure => ({ kind: 'cleanup-fai
90
90
  const writeFailure = (cause: unknown): WriteFailure => ({ kind: 'write-failed', message: errorMessage(cause) });
91
91
  const badRequest = (message: string) => Result.err<BadRequest>({ kind: 'bad-request', message });
92
92
 
93
+ /** Distinct statements each connection keeps prepared; past this, the least recently used is finalized. */
94
+ const STATEMENT_CACHE_SIZE = 64;
95
+
96
+ type PreparedStatement = SqliteStatement<unknown, SQLQueryBindings[]>;
97
+
93
98
  /**
94
- * Carries one statement's failure out of a `db.transaction` callback: bun:sqlite
95
- * rolls the transaction back only when that callback throws.
99
+ * The prepared statements one connection reuses. Every statement handed out
100
+ * here is finalized here, when evicted and by `clear()` before the connection
101
+ * closes, never left to garbage collection: bun:sqlite's `close()` is
102
+ * sqlite3_close_v2, which keeps a connection with an unfinalized statement
103
+ * open, descriptors and all, until that statement is collected. bun:sqlite's
104
+ * own `db.query()` cache cannot serve: it keeps its first 20 statements and
105
+ * returns every later one uncached and unfinalized (2026-10-17: owners kept
106
+ * thousands of descriptors on released, deleted files).
96
107
  */
97
- class BatchStatementFailed extends Error {
98
- readonly failure: SqliteFailure;
108
+ class StatementCache {
109
+ private readonly statements = new Map<string, PreparedStatement>();
110
+ private readonly db: Database;
111
+ private readonly onFinalizeFailed: (message: string) => void;
112
+
113
+ constructor(db: Database, onFinalizeFailed: (message: string) => void) {
114
+ this.db = db;
115
+ this.onFinalizeFailed = onFinalizeFailed;
116
+ }
117
+
118
+ /** The prepared statement for `sql`; SQL that SQLite cannot prepare is a sqlite failure. */
119
+ prepare(sql: string) {
120
+ const cached = this.statements.get(sql);
121
+ if (cached !== undefined) {
122
+ // Re-inserted so the first key is always the least recently used.
123
+ this.statements.delete(sql);
124
+ this.statements.set(sql, cached);
125
+ return Result.ok(cached);
126
+ }
127
+ const prepared = Trust.try((): PreparedStatement => this.db.prepare<unknown, SQLQueryBindings[]>(sql), sqliteFailure);
128
+ if (!prepared.ok) return prepared;
129
+ this.statements.set(sql, prepared.value);
130
+ if (this.statements.size > STATEMENT_CACHE_SIZE) this.evictLeastRecentlyUsed();
131
+ return prepared;
132
+ }
133
+
134
+ /** Finalizes every statement, so the connection can then close for real. */
135
+ clear(): void {
136
+ for (const statement of this.statements.values()) this.finalize(statement);
137
+ this.statements.clear();
138
+ }
139
+
140
+ private evictLeastRecentlyUsed(): void {
141
+ const oldest = this.statements.entries().next();
142
+ if (oldest.done) return;
143
+ const [sql, statement] = oldest.value;
144
+ this.statements.delete(sql);
145
+ this.finalize(statement);
146
+ }
99
147
 
100
- constructor(failure: SqliteFailure) {
101
- super(failure.message);
102
- this.failure = failure;
148
+ private finalize(statement: PreparedStatement): void {
149
+ const finalized = Trust.try(() => statement.finalize(), sqliteFailure);
150
+ if (!finalized.ok && finalized.error.kind === 'sqlite') this.onFinalizeFailed(finalized.error.message);
103
151
  }
104
152
  }
105
153
 
@@ -172,6 +220,8 @@ export class SqlegoServer {
172
220
  readonly pragmas: readonly string[];
173
221
  private readonly db: Database;
174
222
  private readonly reader: Database | null;
223
+ private readonly statements: StatementCache;
224
+ private readonly readerStatements: StatementCache | null;
175
225
 
176
226
  get capabilities(): readonly string[] {
177
227
  return this.reader ? ['detached-plain'] : [];
@@ -198,6 +248,9 @@ export class SqlegoServer {
198
248
  this.reader = reader;
199
249
  this.pragmas = pragmas;
200
250
  this.log = options.log ?? (() => undefined);
251
+ const finalizeFailed = (message: string) => this.log('finalize failed', { error: message });
252
+ this.statements = new StatementCache(db, finalizeFailed);
253
+ this.readerStatements = reader ? new StatementCache(reader, finalizeFailed) : null;
201
254
  }
202
255
 
203
256
  /** Opens (creating if needed) the database file and applies the pragmas. */
@@ -210,15 +263,19 @@ export class SqlegoServer {
210
263
  mkdirSync(path.dirname(paths.value.file), { recursive: true });
211
264
  // safeIntegers: SQLite integers arrive as bigint so `statement`/`exec`
212
265
  // 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;
266
+ return new Database(paths.value.file, { create: true, strict: false, safeIntegers: true });
216
267
  },
217
268
  (cause) => ({ kind: 'open-failed', message: `cannot open ${paths.value.file}: ${errorMessage(cause)}` }),
218
269
  );
219
270
  if (!db.ok) return db;
271
+ const configured = Trust.try(
272
+ () => {
273
+ for (const pragma of pragmas) db.value.exec(`PRAGMA ${pragma}`);
274
+ },
275
+ (cause) => ({ kind: 'open-failed', message: `cannot open ${paths.value.file}: ${errorMessage(cause)}` }),
276
+ );
220
277
  let reader: Database | null = null;
221
- const openedReader = Trust.try(() => {
278
+ const openedReader = !configured.ok ? configured : Trust.try(() => {
222
279
  const mode = db.value.query('PRAGMA journal_mode').values()[0]?.[0];
223
280
  if (String(mode).toLowerCase() !== 'wal') return;
224
281
  reader = new Database(paths.value.file, { readonly: true, safeIntegers: true });
@@ -228,9 +285,8 @@ export class SqlegoServer {
228
285
  }, (cause) => ({ kind: 'open-failed', message: `cannot open reader for ${paths.value.file}: ${errorMessage(cause)}` }));
229
286
  const server = new SqlegoServer(options, paths.value, db.value, [...pragmas], reader);
230
287
  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));
288
+ // No socket/metadata has been created yet; only the connections opened here must go.
289
+ server.closeConnections();
234
290
  return openedReader;
235
291
  }
236
292
  return Result.ok(server);
@@ -317,8 +373,7 @@ export class SqlegoServer {
317
373
  }
318
374
  const listener = this.listener;
319
375
  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));
376
+ this.closeConnections();
322
377
  }
323
378
 
324
379
  /**
@@ -334,6 +389,31 @@ export class SqlegoServer {
334
389
  }
335
390
  }
336
391
 
392
+ /**
393
+ * Closes the reader, then the writer: the last connection to close
394
+ * checkpoints the WAL and removes it, which a readonly one cannot do.
395
+ */
396
+ private closeConnections(): void {
397
+ if (this.reader) this.closeConnection('reader', this.reader, this.readerStatements);
398
+ this.closeConnection('database', this.db, this.statements);
399
+ }
400
+
401
+ /**
402
+ * Finalizes the connection's statements, then closes it at once with
403
+ * `close(true)` (sqlite3_close), which refuses while any statement is still
404
+ * unfinalized; plain `close()` would leave the connection a zombie that keeps
405
+ * the file's descriptors until garbage collection. A refusal (SQLite words it
406
+ * "database is locked") is logged and the deferred close still runs, so the
407
+ * file is released no later than that statement is collected.
408
+ */
409
+ private closeConnection(name: 'reader' | 'database', database: Database, statements: StatementCache | null): void {
410
+ statements?.clear();
411
+ const closed = Trust.try(() => database.close(true), cleanupFailure);
412
+ if (closed.ok) return;
413
+ this.reportCleanup(`close ${name} (deferred: a statement is still unfinalized)`, closed);
414
+ this.reportCleanup(`close ${name}`, Trust.try(() => database.close(), cleanupFailure));
415
+ }
416
+
337
417
  status(): StatusResult {
338
418
  return {
339
419
  file: this.paths.file,
@@ -671,11 +751,10 @@ export class SqlegoServer {
671
751
  }
672
752
 
673
753
  private query(sql: string, params?: SqlParams, db = this.db) {
754
+ const statement = this.statementsOf(db).prepare(sql);
755
+ if (!statement.ok) return statement;
674
756
  const fetched = Trust.try(
675
- (): unknown => {
676
- const statement = db.query(sql);
677
- return params === undefined ? statement.all() : statement.all(...bindings(params));
678
- },
757
+ (): unknown => (params === undefined ? statement.value.all() : statement.value.all(...bindings(params))),
679
758
  sqliteFailure,
680
759
  );
681
760
  if (!fetched.ok) return fetched;
@@ -686,10 +765,11 @@ export class SqlegoServer {
686
765
  }
687
766
 
688
767
  private run(sql: string, params?: SqlParams, db = this.db) {
768
+ const statement = this.statementsOf(db).prepare(sql);
769
+ if (!statement.ok) return statement;
689
770
  return Trust.try(
690
771
  () => {
691
- const statement = db.query(sql);
692
- const outcome = params === undefined ? statement.run() : statement.run(...bindings(params));
772
+ const outcome = params === undefined ? statement.value.run() : statement.value.run(...bindings(params));
693
773
  // safeIntegers may report either counter as bigint; `run` keeps answering with numbers.
694
774
  const result: RunResult = db === this.reader
695
775
  ? { changes: 0, lastInsertRowid: 0 }
@@ -700,6 +780,11 @@ export class SqlegoServer {
700
780
  );
701
781
  }
702
782
 
783
+ /** The statement cache of `db`, which is this file's writer or its reader. */
784
+ private statementsOf(db: Database): StatementCache {
785
+ return db === this.reader && this.readerStatements !== null ? this.readerStatements : this.statements;
786
+ }
787
+
703
788
  /**
704
789
  * Prepares and steps one statement exactly once. A statement with result
705
790
  * columns (SELECT, PRAGMA, `INSERT … RETURNING`) is stepped through `all()`
@@ -744,10 +829,9 @@ export class SqlegoServer {
744
829
  }
745
830
 
746
831
  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(),
749
- sqliteFailure,
750
- );
832
+ const statement = this.statementsOf(db).prepare('SELECT changes() AS changes, total_changes() AS total, last_insert_rowid() AS rowid');
833
+ if (!statement.ok) return statement;
834
+ const read = Trust.try((): unknown => statement.value.get(), sqliteFailure);
751
835
  if (!read.ok) return read;
752
836
  return parseCounters(read.value);
753
837
  }
@@ -793,7 +877,12 @@ export class SqlegoServer {
793
877
  return Result.ok(result);
794
878
  }
795
879
 
796
- /** All statements in one transaction; any failure rolls the whole batch back. */
880
+ /**
881
+ * All statements in one transaction; any failure rolls the whole batch back.
882
+ * Plain BEGIN/COMMIT/ROLLBACK, not `db.transaction()`: bun:sqlite prepares
883
+ * that helper's statements once per connection and never finalizes them, so
884
+ * every file that had run a batch stayed open after it was released.
885
+ */
797
886
  private batch(connection: Connection, statements: readonly Statement[]) {
798
887
  if (statements.length === 0) return badRequest('batch requires a non-empty statements array');
799
888
  if (this.transaction && this.transaction.connection === connection) {
@@ -803,22 +892,28 @@ export class SqlegoServer {
803
892
  const control = transactionControl(item.sql);
804
893
  if (control !== null) return badRequest(`statements[${index}]: ${control.toUpperCase()} is not allowed in a batch, which is already one transaction`);
805
894
  }
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
- );
895
+ // A BEGIN that fails opened nothing, so there is nothing to roll back.
896
+ const begun = Trust.try(() => this.db.exec('BEGIN'), sqliteFailure);
897
+ if (!begun.ok) return begun;
898
+ const results: Array<RunResult | QueryResult> = [];
899
+ for (const item of statements) {
900
+ const outcome = item.mode === 'query' ? this.query(item.sql, item.params) : this.run(item.sql, item.params);
901
+ if (!outcome.ok) return this.abandonBatch(outcome);
902
+ results.push(outcome.value);
903
+ }
904
+ const committed = Trust.try(() => this.db.exec('COMMIT'), sqliteFailure);
905
+ if (!committed.ok) return this.abandonBatch(committed);
906
+ const result: BatchResult = { results };
907
+ return Result.ok(result);
814
908
  }
815
909
 
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);
910
+ /** Rolls back what a failed batch (or its failed COMMIT) left open, and hands its failure on. */
911
+ private abandonBatch<Failed>(failed: Failed): Failed {
912
+ if (this.db.inTransaction) {
913
+ const rolledBack = Trust.try(() => this.db.exec('ROLLBACK'), sqliteFailure);
914
+ if (!rolledBack.ok && rolledBack.error.kind === 'sqlite') this.log('rollback failed', { op: 'batch', error: rolledBack.error.message });
915
+ }
916
+ return failed;
822
917
  }
823
918
 
824
919
  /* ------------------------------------------------------------------ *