Open History to see the last commit
1import * as NodeSqlite from "node:sqlite";
2import * as NodeUtil from "node:util";
3import * as NodeWorkerThreads from "node:worker_threads";
4
5import * as Cache from "effect/Cache";
6import * as Clock from "effect/Clock";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Result from "effect/Result";
10import * as Exit from "effect/Exit";
11import * as Fiber from "effect/Fiber";
12import { identity } from "effect/Function";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Predicate from "effect/Predicate";
16import * as References from "effect/References";
17import * as Schema from "effect/Schema";
18import * as Scheduler from "effect/Scheduler";
19import * as Scope from "effect/Scope";
20import * as Semaphore from "effect/Semaphore";
21import * as Context from "effect/Context";
22import * as Stream from "effect/Stream";
23import * as Tracer from "effect/Tracer";
24import * as Reactivity from "effect/reactivity/Reactivity";
25import * as Client from "effect/sql/SqlClient";
26import type { Borrower, Connection } from "effect/sql/SqlConnection";
27import { SqlError, classifySqliteError } from "effect/sql/SqlError";
28import * as Statement from "effect/sql/Statement";
29
30const ATTR_DB_SYSTEM_NAME = "db.system.name";
31
32export interface SqliteClientConfig {
33 readonly filename: string;
34 readonly readonly?: boolean | undefined;
35 readonly spanAttributes?: Record<string, unknown> | undefined;
36 /** Ignored for in-memory databases, which cannot share a second connection. */
37 readonly readerWorker?: boolean | undefined;
38 /** Runs the writer and WAL checkpoints off the event loop. Ignored for in-memory databases. */
39 readonly writerWorker?: boolean | undefined;
40}
41
42// SqlClient masks transaction acquisition, so readOnly carries the caller's interruption policy.
43const ReadOnly = Context.Reference<typeof Effect.interruptible | undefined>(
44 "@t3tools/shared/nodeSqliteClient/ReadOnly",
45 { defaultValue: () => undefined },
46);
47
48/** Wrap the whole transaction; existing write transactions retain the writer, and writes on the reader fail as readonly. */
49export const readOnly = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
50 Effect.uninterruptibleMask((restore) =>
51 restore(Effect.provideService(effect, ReadOnly, restore)),
52 );
53
54interface Acquired {
55 readonly connection: "writer" | "reader";
56 readonly lockWaitMs: number;
57}
58
59interface ConnectionOwner {
60 readonly fiberId: number;
61 readonly name: string;
62 readonly traceId?: string;
63 readonly spanId?: string;
64}
65
66const connectionOwner = (fiber: Fiber.Fiber<unknown, unknown>): ConnectionOwner => {
67 const current = Context.getOrUndefined(fiber.context, Tracer.ParentSpan);
68 if (current?._tag !== "Span") return { fiberId: fiber.id, name: "untraced" };
69 let span: Tracer.Span = current;
70 while (span.name === "sqlite" || span.name === "sql.transaction") {
71 const parent: Tracer.AnySpan | undefined = Option.getOrUndefined(span.parent);
72 if (parent?._tag !== "Span") break;
73 span = parent;
74 }
75 return { fiberId: fiber.id, name: span.name, traceId: span.traceId, spanId: span.spanId };
76};
77
78const annotateAcquired = (
79 fiber: Fiber.Fiber<unknown, unknown>,
80 acquired: Acquired | undefined,
81 ownerAtWaitStart?: ConnectionOwner,
82) => {
83 const span = Context.getOrUndefined(fiber.context, Tracer.ParentSpan);
84 if (span?._tag !== "Span" || acquired === undefined) return;
85 span.attribute("db.connection", acquired.connection);
86 span.attribute("db.lock_wait_ms", acquired.lockWaitMs);
87 if (ownerAtWaitStart !== undefined) {
88 span.attribute("db.lock_owner_at_start.fiber_id", ownerAtWaitStart.fiberId);
89 span.attribute("db.lock_owner_at_start.name", ownerAtWaitStart.name);
90 if (ownerAtWaitStart.traceId !== undefined) {
91 span.attribute("db.lock_owner_at_start.trace_id", ownerAtWaitStart.traceId);
92 }
93 if (ownerAtWaitStart.spanId !== undefined) {
94 span.attribute("db.lock_owner_at_start.span_id", ownerAtWaitStart.spanId);
95 }
96 }
97};
98
99const TransactionAcquire = Context.Reference<
100 | {
101 acquired?: Acquired;
102 ownerAtWaitStart: ConnectionOwner | undefined;
103 restore: typeof Effect.interruptible | undefined;
104 }
105 | undefined
106>("@t3tools/shared/nodeSqliteClient/TransactionAcquire", { defaultValue: () => undefined });
107
108export class UnsupportedNodeSqliteVersionError extends Schema.TaggedError<UnsupportedNodeSqliteVersionError>()(
109 "UnsupportedNodeSqliteVersionError",
110 {
111 nodeVersion: Schema.String,
112 requirement: Schema.String,
113 },
114) {
115 override get message(): string {
116 return `Node.js ${this.nodeVersion} is missing required node:sqlite APIs. Upgrade to ${this.requirement}.`;
117 }
118}
119
120export class UnsupportedNodeSqliteOperationError extends Schema.TaggedError<UnsupportedNodeSqliteOperationError>()(
121 "UnsupportedNodeSqliteOperationError",
122 {},
123) {
124 override get message(): string {
125 return "Node SQLite does not support executeStream.";
126 }
127}
128
129const checkNodeSqliteCompat = Effect.fn("checkNodeSqliteCompat")(function () {
130 const parts = process.versions.node.split(".").map(Number);
131 const major = parts[0] ?? 0;
132 const minor = parts[1] ?? 0;
133 const supported = (major === 22 && minor >= 16) || (major === 23 && minor >= 11) || major >= 24;
134
135 if (!supported) {
136 return Effect.die(
137 new UnsupportedNodeSqliteVersionError({
138 nodeVersion: process.versions.node,
139 requirement: "Node.js >=22.16, >=23.11, or >=24",
140 }),
141 );
142 }
143 return Effect.void;
144});
145
146// node:sqlite supplies errcode; classifySqliteError expects errno.
147const classifyError = (cause: unknown, message: string, operation: string) => {
148 if (
149 Predicate.hasProperty(cause, "errcode") &&
150 typeof cause.errcode === "number" &&
151 !Predicate.hasProperty(cause, "errno")
152 ) {
153 Object.assign(cause, { errno: cause.errcode });
154 }
155 return classifySqliteError(cause, { message, operation });
156};
157
158// SQLite retains text/blob bindings until rebind or finalization; node:sqlite cannot clear them.
159const LARGE_BINDING_SIZE = 64 * 1024;
160
161const isBlob = (value: unknown): value is ArrayBufferView | ArrayBufferLike =>
162 ArrayBuffer.isView(value) || NodeUtil.types.isAnyArrayBuffer(value);
163
164const bindingSize = (value: unknown): number => {
165 if (typeof value === "string") {
166 return value.length;
167 }
168 return isBlob(value) ? value.byteLength : 0;
169};
170
171const hasLargeBinding = (params: ReadonlyArray<unknown>): boolean => {
172 try {
173 let size = 0;
174 for (const param of params) {
175 if (
176 (typeof param === "object" || typeof param === "function") &&
177 param !== null &&
178 !isBlob(param)
179 ) {
180 // Named parameters may be callable objects; read data properties only to avoid invoking getters twice.
181 for (const property of Object.values(Object.getOwnPropertyDescriptors(param))) {
182 if (!property.enumerable) continue;
183 if (!("value" in property)) return true;
184 size += bindingSize(property.value);
185 }
186 } else {
187 size += bindingSize(param);
188 }
189 }
190 return size > LARGE_BINDING_SIZE;
191 } catch {
192 return true;
193 }
194};
195
196// Inline worker source also runs in bundles and single-executable builds without module files.
197const workerSource = `
198const { parentPort, workerData } = require("node:worker_threads");
199const { DatabaseSync } = require("node:sqlite");
200const describe = (error) => ({
201 message: String(error && error.message ? error.message : error),
202 code: error && error.code,
203 errcode: error && error.errcode,
204 errstr: error && error.errstr,
205});
206let db;
207try {
208 // A read-only open cannot be undone by SQL, unlike PRAGMA query_only.
209 const next = new DatabaseSync(workerData.filename, {
210 readOnly: workerData.readOnly,
211 allowExtension: workerData.allowExtension,
212 });
213 next.exec("PRAGMA busy_timeout = 5000;");
214 // Reads the header, so a file that is not a database fails here rather than on first use.
215 const mode = String(next.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
216 // Without WAL a reader's shared lock blocks the writer's commits, so refuse.
217 if (workerData.requireWal && mode !== "wal") throw new Error("database uses journal_mode " + mode + ", not wal");
218 db = next;
219 parentPort.postMessage({ type: "ready" });
220} catch (error) {
221 parentPort.postMessage({ type: "unavailable", ...describe(error) });
222}
223const statements = new Map();
224const prepare = (sql, cached) => {
225 if (!cached) return db.prepare(sql);
226 let statement = statements.get(sql);
227 if (statement === undefined) {
228 statement = db.prepare(sql);
229 if (statements.size >= workerData.prepareCacheSize) statements.delete(statements.keys().next().value);
230 } else {
231 statements.delete(sql);
232 }
233 statements.set(sql, statement);
234 return statement;
235};
236parentPort.on("message", (request) => {
237 if (request.type === "close") {
238 // Closing lets SQLite checkpoint and remove the WAL, which terminating would skip.
239 try {
240 if (db !== undefined) db.close();
241 } catch {}
242 parentPort.close();
243 return;
244 }
245 const { id, sql, params, cached, values, raw, safeIntegers, received } = request;
246 let operation = "open";
247 let iterator;
248 try {
249 if (db === undefined) throw new Error("database connection is unavailable");
250 operation = "prepare";
251 const statement = prepare(sql, cached);
252 operation = "execute";
253 statement.setReadBigInts(safeIntegers);
254 if (statement.columns().length > 0) {
255 statement.setReturnArrays(values);
256 let rows = [];
257 let bytes = 0;
258 let pendingBatch = false;
259 iterator = statement.iterate(...params);
260 for (const row of iterator) {
261 let rowBytes = 0;
262 for (const key in row) {
263 const value = row[key];
264 rowBytes += typeof value === "string" ? value.length * 2
265 : ArrayBuffer.isView(value) ? value.byteLength : 8;
266 }
267 if (rows.length > 0 && (rows.length >= 16384 || bytes + rowBytes > 8 * 1024 * 1024)) {
268 // Build the next batch during receipt, but allow only one unacknowledged message.
269 if (pendingBatch) Atomics.wait(received, 0, 0);
270 Atomics.store(received, 0, 0);
271 parentPort.postMessage({ id, rows, more: true });
272 rows = [];
273 bytes = 0;
274 pendingBatch = true;
275 }
276 rows.push(row);
277 bytes += rowBytes;
278 }
279 if (pendingBatch) Atomics.wait(received, 0, 0);
280 parentPort.postMessage({ id, rows });
281 } else {
282 const result = statement.run(...params);
283 parentPort.postMessage({ id, rows: raw ? result : [] });
284 }
285 } catch (error) {
286 // A step that throws leaves its statement active; an active write blocks every later COMMIT.
287 try {
288 iterator?.return();
289 } catch {}
290 // A failed iterator can report its previous SQLite error when the statement is reused.
291 statements.delete(sql);
292 parentPort.postMessage({ id, error: { operation, ...describe(error) } });
293 }
294});
295`;
296
297interface WorkerRequest {
298 readonly sql: string;
299 readonly params: ReadonlyArray<unknown>;
300 readonly cached: boolean;
301 readonly values: boolean;
302 readonly raw: boolean;
303}
304
305interface WorkerFailure {
306 readonly message: string;
307 readonly code?: unknown;
308 readonly errcode?: unknown;
309 readonly errstr?: unknown;
310}
311
312type WorkerStartup =
313 | { readonly type: "ready" }
314 | ({ readonly type: "unavailable" } & WorkerFailure);
315
316type WorkerReply =
317 | { readonly id: number; readonly rows: ReadonlyArray<any>; readonly more?: boolean }
318 | {
319 readonly id: number;
320 readonly error: WorkerFailure & { readonly operation: "open" | "prepare" | "execute" };
321 };
322
323const workerFailureMessages = {
324 open: "Failed to open database",
325 prepare: "Failed to prepare statement",
326 execute: "Failed to execute statement",
327} as const;
328
329const failed = (cause: unknown, message: string, operation: string) =>
330 new SqlError({ reason: classifyError(cause, message, operation) });
331
332const failedWith = (
333 { message, code, errcode, errstr }: WorkerFailure,
334 operation: keyof typeof workerFailureMessages,
335) =>
336 failed(
337 Object.assign(new Error(message), { code, errcode, errstr }),
338 workerFailureMessages[operation],
339 operation,
340 );
341
342// Read-transaction cleanup succeeds after worker exit because it can no longer change anything.
343const endsReadTransaction = (sql: string) => /^\s*ROLLBACK\b|^\s*COMMIT\b/i.test(sql);
344
345// WAL readers run concurrently; one worker serialized every read behind the slowest transaction.
346const READER_POOL_SIZE = 4;
347const READER_STARTUP_TIMEOUT = Duration.seconds(10);
348
349// Bind transactions to one worker; fail after its exit instead of resuming outside the transaction on a replacement.
350const makeWorkerConnection = Effect.fnUntraced(function* (options: {
351 readonly filename: string;
352 readonly role: "reader" | "writer";
353 readonly readOnly: boolean;
354 readonly onReply?: () => void;
355}) {
356 const label = options.role === "reader" ? "Database reader" : "Database writer";
357 const readOnly = options.readOnly;
358 let current:
359 | {
360 readonly worker: NodeWorkerThreads.Worker;
361 readonly connection: Connection;
362 readonly started: Promise<WorkerStartup>;
363 }
364 | undefined;
365 let nextRequestId = 0;
366 // A replacement writer would lose the pragmas callers set on it, such as foreign_keys.
367 let writerStopped: string | undefined;
368
369 const start = () => {
370 const worker = new NodeWorkerThreads.Worker(workerSource, {
371 eval: true,
372 workerData: {
373 filename: options.filename,
374 readOnly,
375 requireWal: options.role === "reader",
376 allowExtension: false,
377 prepareCacheSize: 200,
378 },
379 });
380 let announce: (startup: WorkerStartup) => void = () => {};
381 const started = new Promise<WorkerStartup>((resolve) => {
382 announce = resolve;
383 });
384 let stoppedMessage: string | undefined;
385 const pending = new Map<
386 number,
387 {
388 readonly endsTransaction: boolean;
389 readonly received: Int32Array;
390 readonly rows: Array<unknown>;
391 readonly resume: (reply: WorkerReply) => void;
392 }
393 >();
394 const stop = (message: string) => {
395 stoppedMessage = message;
396 if (options.role === "writer") writerStopped = message;
397 announce({ type: "unavailable", message });
398 if (current?.worker === worker) current = undefined;
399 for (const [id, request] of pending) {
400 request.resume(
401 request.endsTransaction
402 ? { id, rows: [] }
403 : { id, error: { operation: "execute", message } },
404 );
405 }
406 pending.clear();
407 };
408 worker.on("message", (reply: WorkerReply | WorkerStartup) => {
409 if ("type" in reply) {
410 announce(reply);
411 if (pending.size === 0) worker.unref();
412 return;
413 }
414 const request = pending.get(reply.id);
415 if (request === undefined) return;
416 if ("rows" in reply && reply.more) {
417 for (const row of reply.rows) request.rows.push(row);
418 Atomics.store(request.received, 0, 1);
419 Atomics.notify(request.received, 0);
420 return;
421 }
422 pending.delete(reply.id);
423 if (pending.size === 0) worker.unref();
424 options.onReply?.();
425 if ("rows" in reply && request.rows.length > 0) {
426 for (const row of reply.rows) request.rows.push(row);
427 request.resume({ id: reply.id, rows: request.rows });
428 } else {
429 request.resume(reply);
430 }
431 });
432 worker.on("error", (cause) => stop(`${label} failed: ${cause.message}`));
433 worker.on("exit", (code) => stop(`${label} exited with code ${code}`));
434
435 const request = (input: WorkerRequest) =>
436 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
437 // A COMMIT that never reached a writer must fail; only its ROLLBACK is moot.
438 const endsTransaction = readOnly
439 ? endsReadTransaction(input.sql)
440 : /^\s*ROLLBACK\b/i.test(input.sql);
441 if (stoppedMessage !== undefined) {
442 return endsTransaction
443 ? Effect.succeed([])
444 : Effect.fail(failedWith({ message: stoppedMessage }, "execute"));
445 }
446 const safeIntegers = Boolean(Context.get(fiber.context, Client.SafeIntegers));
447 const reply = Effect.callback<ReadonlyArray<any>, SqlError>((resume) => {
448 const id = nextRequestId++;
449 const received = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
450 pending.set(id, {
451 endsTransaction,
452 received,
453 rows: [],
454 resume: (reply) =>
455 resume(
456 "rows" in reply
457 ? Effect.succeed(reply.rows)
458 : Effect.fail(failedWith(reply.error, reply.error.operation)),
459 ),
460 });
461 if (pending.size === 1) worker.ref();
462 const cached = input.cached && !hasLargeBinding(input.params);
463 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
464 worker.postMessage({ id, safeIntegers, ...input, cached, received });
465 });
466 // A posted write runs to the end, as it did on the event loop; the caller and its lock
467 // must not move on while the worker is still applying it. Reads stay cancellable.
468 return options.role === "writer" ? Effect.uninterruptible(reply) : reply;
469 });
470
471 const connection = identity<Connection>({
472 execute(sql, params, rowTransform) {
473 const effect = request({ sql, params, cached: true, values: false, raw: false });
474 return rowTransform ? Effect.map(effect, rowTransform) : effect;
475 },
476 executeRaw(sql, params) {
477 return request({ sql, params, cached: true, values: false, raw: true });
478 },
479 executeValues(sql, params) {
480 return request({ sql, params, cached: true, values: true, raw: false });
481 },
482 executeValuesUnprepared(sql, params) {
483 return request({ sql, params: params ?? [], cached: false, values: true, raw: false });
484 },
485 executeUnprepared(sql, params, rowTransform) {
486 // Read snapshots need deferred BEGIN; readonly connections reject IMMEDIATE and EXCLUSIVE.
487 const statement = readOnly && /^\s*BEGIN\b/i.test(sql) ? "BEGIN" : sql;
488 const effect = request({
489 sql: statement,
490 params: params ?? [],
491 cached: false,
492 values: false,
493 raw: false,
494 });
495 return rowTransform ? Effect.map(effect, rowTransform) : effect;
496 },
497 executeStream(_sql, _params) {
498 return Stream.die(new UnsupportedNodeSqliteOperationError());
499 },
500 });
501 current = { worker, connection, started };
502 return current;
503 };
504
505 yield* Effect.addFinalizer(() =>
506 Effect.promise(async () => {
507 const open = current;
508 if (open === undefined) return;
509 if (options.role === "writer") {
510 await new Promise<void>((resolve) => {
511 open.worker.once("exit", () => resolve());
512 open.worker.ref();
513 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
514 open.worker.postMessage({ type: "close" });
515 });
516 }
517 await open.worker.terminate();
518 }),
519 );
520
521 const retire = (worker: NodeWorkerThreads.Worker) => {
522 if (current?.worker === worker) current = undefined;
523 void worker.terminate();
524 };
525
526 return Effect.suspend((): Effect.Effect<Connection, SqlError> => {
527 if (current === undefined && writerStopped !== undefined) {
528 return Effect.fail(failedWith({ message: writerStopped }, "execute"));
529 }
530 let entry: NonNullable<typeof current>;
531 try {
532 entry = current ?? start();
533 } catch (cause) {
534 return Effect.fail(failed(cause, workerFailureMessages.open, "open"));
535 }
536 const started = Effect.promise(() => entry.started);
537 return Effect.flatMap(
538 Effect.withFiber((fiber) => {
539 const restore = Context.get(fiber.context, ReadOnly) ?? identity;
540 // Readers fall back to the writer; the writer has no fallback, so a slow disk only delays it.
541 return restore(
542 options.role === "reader"
543 ? Effect.timeoutOption(started, READER_STARTUP_TIMEOUT)
544 : Effect.asSome(started),
545 );
546 }),
547 (startup): Effect.Effect<Connection, SqlError> => {
548 const outcome = Option.getOrUndefined(startup);
549 if (outcome?.type === "ready") {
550 // A late ready event must not hand out a worker retired by another acquire timeout.
551 return current === entry
552 ? Effect.succeed(entry.connection)
553 : Effect.fail(failedWith({ message: `${label} stopped while starting` }, "open"));
554 }
555 retire(entry.worker);
556 return Effect.fail(
557 failedWith(
558 outcome ?? {
559 message: `${label} did not open the database within ${Duration.toMillis(READER_STARTUP_TIMEOUT)} ms`,
560 },
561 "open",
562 ),
563 );
564 },
565 );
566 });
567});
568
569// A reader that cannot start turns off the whole pool, so routing never picks a dead slot.
570const makeReader = Effect.fnUntraced(function* (filename: string, pool: { unavailable: boolean }) {
571 const acquire = yield* makeWorkerConnection({ filename, role: "reader", readOnly: true });
572 return Effect.suspend((): Effect.Effect<Connection | undefined> =>
573 pool.unavailable
574 ? Effect.undefined
575 : acquire.pipe(
576 Effect.map((connection) => (pool.unavailable ? undefined : connection)),
577 Effect.catch((error) => {
578 if (pool.unavailable) return Effect.undefined;
579 pool.unavailable = true;
580 const cause = error.reason.cause;
581 return Effect.logWarning("SQLite reader worker unavailable; reads use the writer", {
582 reason: cause instanceof Error ? cause.message : error.message,
583 }).pipe(Effect.as(undefined));
584 }),
585 ),
586 );
587});
588
589// A checkpoint copies WAL pages into the database and syncs it. On the writer's thread every
590// write would wait for that sync, so a second connection checkpoints beside the writes.
591const CHECKPOINT_FRAMES = 1000;
592const CHECKPOINT_IDLE_MS = 100;
593// If checkpoints fall behind constant writes, the writer checkpoints itself, delaying writes only.
594const WRITER_BACKSTOP_FRAMES = 10_000;
595
596const checkpointWorkerSource = `
597const { parentPort, workerData } = require("node:worker_threads");
598const { DatabaseSync } = require("node:sqlite");
599let db;
600let frames;
601let passive;
602let idle;
603const check = (force) => {
604 if (db === undefined) {
605 db = new DatabaseSync(workerData.filename);
606 db.exec("PRAGMA busy_timeout = 5000;");
607 // macOS requires F_FULLFSYNC to flush the drive cache.
608 db.exec("PRAGMA checkpoint_fullfsync = ON;");
609 frames = db.prepare("PRAGMA wal_checkpoint(NOOP)");
610 passive = db.prepare("PRAGMA wal_checkpoint(PASSIVE)");
611 }
612 const before = frames.get();
613 let state = before;
614 if (state.log - state.checkpointed >= workerData.frames || (force && state.log > state.checkpointed)) {
615 passive.get();
616 state = frames.get();
617 }
618 // The WAL restarts only once every frame is checkpointed, so catch up when writes pause.
619 // A reader pinning the WAL stops progress; the next write retries instead of a timer loop.
620 const progressed = !force || state.checkpointed > before.checkpointed;
621 if (state.log > state.checkpointed && progressed) {
622 idle = setTimeout(() => run(true), workerData.idleMs);
623 }
624 parentPort.postMessage({ type: "checked", log: state.log, checkpointed: state.checkpointed });
625};
626const run = (force) => {
627 clearTimeout(idle);
628 try {
629 check(force);
630 } catch (error) {
631 parentPort.postMessage({ type: "failed", message: String(error && error.message ? error.message : error) });
632 }
633};
634parentPort.on("message", () => run(false));
635`;
636
637const sqliteVersion = () => {
638 const db = new NodeSqlite.DatabaseSync(":memory:");
639 try {
640 return String(db.prepare("SELECT sqlite_version() AS version").get()?.version);
641 } finally {
642 db.close();
643 }
644};
645
646// Returns the writer's per-statement notification, or undefined when the writer checkpoints alone.
647const startCheckpointWorker = Effect.fnUntraced(function* (filename: string) {
648 const warn = (reason: string) =>
649 Effect.logWarning("SQLite checkpoint worker unavailable; the writer checkpoints its own WAL", {
650 reason,
651 });
652 const version = sqliteVersion();
653 const [major = 0, minor = 0] = version.split(".").map(Number);
654 // Older SQLite treats NOOP as PASSIVE, so counting frames would checkpoint on every write.
655 if (major < 3 || (major === 3 && minor < 51)) {
656 yield* warn(`SQLite ${version} has no NOOP checkpoint`);
657 return undefined;
658 }
659 const started = Result.try(
660 () =>
661 new NodeWorkerThreads.Worker(checkpointWorkerSource, {
662 eval: true,
663 workerData: { filename, frames: CHECKPOINT_FRAMES, idleMs: CHECKPOINT_IDLE_MS },
664 }),
665 );
666 if (Result.isFailure(started)) {
667 yield* warn(String(started.failure));
668 return undefined;
669 }
670 const worker = started.success;
671 worker.unref();
672 const runFork = Effect.runForkWith(yield* Effect.context<never>());
673 let stopped = false;
674 const stop = (reason: string) => {
675 if (stopped) return;
676 stopped = true;
677 void worker.terminate();
678 runFork(warn(reason));
679 };
680 worker.on("message", (message: { readonly type?: unknown; readonly message?: unknown }) => {
681 if (message?.type === "failed") stop(String(message.message));
682 });
683 worker.on("error", (cause) => stop(cause.message));
684 worker.on("exit", (code) => stop(`exited with code ${code}`));
685 yield* Effect.addFinalizer(() =>
686 Effect.promise(() => {
687 stopped = true;
688 return worker.terminate();
689 }),
690 );
691 let scheduled = false;
692 return () => {
693 if (stopped || scheduled) return;
694 scheduled = true;
695 // One check per event-loop turn is enough, however many statements finished in it.
696 setImmediate(() => {
697 scheduled = false;
698 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
699 if (!stopped) worker.postMessage(0);
700 });
701 };
702});
703
704const make = Effect.fn("makeWithDatabase")(function* (
705 options: SqliteClientConfig,
706): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
707 yield* checkNodeSqliteCompat();
708
709 const compiler = Statement.makeCompilerSqlite();
710 const isFileDatabase = options.filename !== ":memory:" && options.filename !== "";
711
712 const makeConnection = Effect.gen(function* () {
713 const scope = yield* Effect.scope;
714 const db = yield* Effect.try({
715 try: () =>
716 new NodeSqlite.DatabaseSync(options.filename, {
717 readOnly: options.readonly ?? false,
718 allowExtension: false,
719 }),
720 catch: (cause) =>
721 new SqlError({
722 reason: classifyError(cause, "Failed to open database", "open"),
723 }),
724 });
725 yield* Scope.addFinalizer(
726 scope,
727 Effect.try({
728 try: () => db.close(),
729 catch: (cause) =>
730 new SqlError({
731 reason: classifyError(cause, "Failed to close database", "close"),
732 }),
733 }).pipe(Effect.orDie),
734 );
735 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
736 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
737 const cached = statementReaderCache.get(statement);
738 if (cached !== undefined) {
739 return cached;
740 }
741 const value = statement.columns().length > 0;
742 statementReaderCache.set(statement, value);
743 return value;
744 };
745
746 const prepare = (sql: string) =>
747 Effect.try({
748 try: () => db.prepare(sql),
749 catch: (cause) =>
750 new SqlError({
751 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
752 }),
753 });
754
755 const prepareCache = yield* Cache.makeWith(prepare, {
756 capacity: 200,
757 // A transient prepare failure must not outlive the lock or missing schema.
758 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.minutes(10) : Duration.zero),
759 });
760
761 const statementFor = (sql: string, params: ReadonlyArray<unknown>) =>
762 hasLargeBinding(params) ? prepare(sql) : Cache.get(prepareCache, sql);
763
764 const runStatement = (
765 statement: NodeSqlite.StatementSync,
766 params: ReadonlyArray<unknown>,
767 mode: "rows" | "raw" | "values" = "rows",
768 ) =>
769 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
770 let arrays = false;
771 let result: Exit.Exit<ReadonlyArray<unknown>, SqlError>;
772 try {
773 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
774 if (hasRows(statement)) {
775 arrays = mode === "values";
776 if (arrays) statement.setReturnArrays(true);
777 result = Exit.succeed(statement.all(...(params as any)));
778 } else {
779 const value = statement.run(...(params as any));
780 result = Exit.succeed(
781 mode === "raw" ? (value as unknown as ReadonlyArray<unknown>) : [],
782 );
783 }
784 } catch (cause) {
785 result = Exit.fail(
786 new SqlError({
787 reason: classifyError(cause, "Failed to execute statement", "execute"),
788 }),
789 );
790 }
791 if (arrays) {
792 try {
793 statement.setReturnArrays(false);
794 } catch (cause) {
795 return Exit.die(
796 new SqlError({
797 reason: classifyError(
798 cause,
799 "Failed to reset statement result mode",
800 "resetResultMode",
801 ),
802 }),
803 );
804 }
805 }
806 return result;
807 });
808
809 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
810 Effect.flatMap(statementFor(sql, params), (statement) =>
811 runStatement(statement, params, raw ? "raw" : "rows"),
812 );
813 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
814 Effect.flatMap(statementFor(sql, params), (statement) =>
815 runStatement(statement, params, "values"),
816 );
817
818 return identity<Connection>({
819 execute(sql, params, rowTransform) {
820 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
821 },
822 executeRaw(sql, params) {
823 return run(sql, params, true);
824 },
825 executeValues(sql, params) {
826 return runValues(sql, params);
827 },
828 executeValuesUnprepared(sql, params) {
829 return Effect.flatMap(prepare(sql), (statement) =>
830 runStatement(statement, params ?? [], "values"),
831 );
832 },
833 executeUnprepared(sql, params, rowTransform) {
834 const effect = prepare(sql).pipe(
835 Effect.flatMap((statement) => runStatement(statement, params ?? [])),
836 );
837 return rowTransform ? Effect.map(effect, rowTransform) : effect;
838 },
839 executeStream(_sql, _params) {
840 return Stream.die(new UnsupportedNodeSqliteOperationError());
841 },
842 });
843 });
844
845 const semaphore = yield* Semaphore.make(1);
846 const writerWorker = options.writerWorker === true && isFileDatabase;
847 let checkpointAfterWrite: (() => void) | undefined;
848 const writerConnection: Effect.Effect<Connection, SqlError> = writerWorker
849 ? yield* makeWorkerConnection({
850 filename: options.filename,
851 role: "writer",
852 readOnly: options.readonly ?? false,
853 onReply: () => checkpointAfterWrite?.(),
854 })
855 : Effect.succeed(yield* makeConnection);
856 // Opening now fails the layer for a file that is not a database, not its first query.
857 const opened = yield* writerConnection;
858 // Started after the writer, so it stops first and the writer's close can checkpoint.
859 if (writerWorker && options.readonly !== true) {
860 checkpointAfterWrite = yield* startCheckpointWorker(options.filename);
861 if (checkpointAfterWrite !== undefined) {
862 yield* opened.executeUnprepared(
863 `PRAGMA wal_autocheckpoint = ${WRITER_BACKSTOP_FRAMES}`,
864 [],
865 undefined,
866 );
867 }
868 }
869 const readerPool = { unavailable: false };
870 const readers =
871 options.readerWorker && isFileDatabase
872 ? yield* Effect.forEach(Array.from({ length: READER_POOL_SIZE }), () =>
873 Effect.map(
874 Effect.all([makeReader(options.filename, readerPool), Semaphore.make(1)]),
875 ([acquire, lock]) => ({
876 acquire,
877 lock,
878 claims: 0,
879 }),
880 ),
881 )
882 : [];
883
884 interface Target {
885 readonly name: Acquired["connection"];
886 readonly lock: Semaphore.Semaphore;
887 readonly connection: Connection;
888 }
889 const writer = Effect.map(writerConnection, (connection): Target => ({
890 name: "writer",
891 lock: semaphore,
892 connection,
893 }));
894 let activeWriter: ConnectionOwner | undefined;
895 // Callers must run route uninterruptibly and pass `claimed` a finalizer that runs `release` once.
896 const route = (claimed: (release: Effect.Effect<void>) => Effect.Effect<void>) =>
897 Effect.withFiber((fiber): Effect.Effect<Target, SqlError> => {
898 if (readers.length === 0 || readerPool.unavailable || !Context.get(fiber.context, ReadOnly)) {
899 return writer;
900 }
901 // Least claimed wins and ties go to the lowest slot, so idle slots never start a worker.
902 let slot = readers[0]!;
903 for (const candidate of readers) if (candidate.claims < slot.claims) slot = candidate;
904 slot.claims++;
905 const reader = slot;
906 return Effect.andThen(
907 claimed(
908 Effect.sync(() => {
909 reader.claims--;
910 }),
911 ),
912 Effect.flatMap(reader.acquire, (readerConnection) =>
913 readerConnection === undefined
914 ? writer
915 : Effect.succeed<Target>({
916 name: "reader",
917 lock: reader.lock,
918 connection: readerConnection,
919 }),
920 ),
921 );
922 });
923
924 const acquired = (
925 target: { readonly name: Acquired["connection"] },
926 clock: Clock.Clock,
927 start: bigint,
928 ): Acquired => ({
929 connection: target.name,
930 lockWaitMs: Number((clock.monotonicTimeNanosUnsafe() - start) / 1000n) / 1000,
931 });
932
933 const borrower: Borrower = (use) =>
934 Effect.uninterruptibleMask((restore) => {
935 let release: Effect.Effect<void> = Effect.void;
936 const claimed = (next: Effect.Effect<void>) =>
937 Effect.sync(() => {
938 release = next;
939 });
940 return Effect.flatMap(route(claimed), (target) => restore(borrowTarget(target, use))).pipe(
941 Effect.ensuring(Effect.suspend(() => release)),
942 );
943 });
944 const borrowTarget = <A, E, R>(
945 target: Target,
946 use: (connection: Connection) => Effect.Effect<A, E, R>,
947 ): Effect.Effect<A, E, R> =>
948 Effect.withFiber((fiber) => {
949 const clock = fiber.getRef(Clock.Clock);
950 const start = clock.monotonicTimeNanosUnsafe();
951 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
952 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
953 const useConnection = Effect.suspend(() => {
954 if (target.name === "writer") activeWriter = owner;
955 if (
956 fiber.getRef(References.TracerEnabled) &&
957 fiber.getRef(Statement.SpanPropagationEnabled)
958 ) {
959 annotateAcquired(fiber, acquired(target, clock, start), ownerAtWaitStart);
960 }
961 return use(target.connection);
962 });
963 const useOwnedConnection =
964 target.name === "writer"
965 ? Effect.onExit(useConnection, () =>
966 Effect.sync(() => {
967 if (activeWriter === owner) activeWriter = undefined;
968 }),
969 )
970 : useConnection;
971 return target.lock.withPermits(1)(useOwnedConnection);
972 });
973 const claimedUntilScopeCloses = (release: Effect.Effect<void>) =>
974 Effect.withFiber((fiber) =>
975 Scope.addFinalizer(Context.getUnsafe(fiber.context, Scope.Scope), release),
976 );
977 const transactionAcquirer = Effect.uninterruptible(route(claimedUntilScopeCloses)).pipe(
978 Effect.flatMap((target) =>
979 Effect.uninterruptibleMask((restore) => {
980 const fiber = Fiber.getCurrent()!;
981 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
982 const clock = fiber.getRef(Clock.Clock);
983 const start = clock.monotonicTimeNanosUnsafe();
984 const pending = fiber.getRef(TransactionAcquire);
985 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
986 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
987 const acquire = Effect.tap((pending?.restore ?? restore)(target.lock.take(1)), () => {
988 if (target.name === "writer") activeWriter = owner;
989 if (pending !== undefined) {
990 pending.acquired = acquired(target, clock, start);
991 pending.ownerAtWaitStart = ownerAtWaitStart;
992 }
993 return Scope.addFinalizer(
994 scope,
995 Effect.sync(() => {
996 if (target.name === "writer" && activeWriter === owner) activeWriter = undefined;
997 }).pipe(Effect.andThen(target.lock.release(1))),
998 );
999 });
1000 return Effect.as(
1001 // A scheduler yield after taking the permit must not precede its release finalizer.
1002 Effect.provideService(acquire, Scheduler.PreventSchedulerYield, true),
1003 target.connection,
1004 );
1005 }),
1006 ),
1007 );
1008
1009 const client = yield* Client.make({
1010 driver: "node:sqlite",
1011 acquirer: transactionAcquirer,
1012 borrower,
1013 compiler,
1014 transactionAcquirer,
1015 // BEGIN IMMEDIATE avoids read-then-write SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot resolve.
1016 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
1017 spanAttributes: [
1018 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
1019 [ATTR_DB_SYSTEM_NAME, "sqlite"],
1020 ],
1021 });
1022 const withTransaction = client.withTransaction;
1023 return Object.assign(client, {
1024 withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1025 Effect.uninterruptibleMask((restore) => {
1026 // SqlClient masks setup; acquisition must preserve the caller's interruptibility.
1027 const pending: {
1028 acquired?: Acquired;
1029 ownerAtWaitStart: ConnectionOwner | undefined;
1030 restore: typeof Effect.interruptible | undefined;
1031 } = {
1032 ownerAtWaitStart: undefined,
1033 restore,
1034 };
1035 const body = Effect.withFiber<A, E, R>((fiber) => {
1036 annotateAcquired(fiber, pending.acquired, pending.ownerAtWaitStart);
1037 pending.restore = undefined;
1038 return effect;
1039 });
1040 return restore(
1041 withTransaction(body).pipe(Effect.provideService(TransactionAcquire, pending)),
1042 );
1043 }),
1044 });
1045});
1046
1047export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
1048 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));