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 Exit from "effect/Exit";
10import * as Fiber from "effect/Fiber";
11import { identity } from "effect/Function";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Predicate from "effect/Predicate";
15import * as References from "effect/References";
16import * as Schema from "effect/Schema";
17import * as Scheduler from "effect/Scheduler";
18import * as Scope from "effect/Scope";
19import * as Semaphore from "effect/Semaphore";
20import * as Context from "effect/Context";
21import * as Stream from "effect/Stream";
22import * as Tracer from "effect/Tracer";
23import * as Reactivity from "effect/reactivity/Reactivity";
24import * as Client from "effect/sql/SqlClient";
25import type { Borrower, Connection } from "effect/sql/SqlConnection";
26import { SqlError, classifySqliteError } from "effect/sql/SqlError";
27import * as Statement from "effect/sql/Statement";
28
29const ATTR_DB_SYSTEM_NAME = "db.system.name";
30
31export interface SqliteClientConfig {
32 readonly filename: string;
33 readonly readonly?: boolean | undefined;
34 readonly allowExtension?: boolean | undefined;
35 readonly prepareCacheSize?: number | undefined;
36 readonly prepareCacheTTL?: Duration.Input | undefined;
37 readonly spanAttributes?: Record<string, unknown> | undefined;
38 readonly transformResultNames?: ((str: string) => string) | undefined;
39 readonly transformQueryNames?: ((str: string) => string) | undefined;
40 /**
41 * Ignored for in-memory databases, which a second connection cannot share.
42 */
43 readonly readerWorker?: boolean | undefined;
44 readonly readerStartupTimeout?: Duration.Input | undefined;
45 /**
46 * Ignored for in-memory databases.
47 */
48 readonly checkpointWorker?: boolean | undefined;
49}
50
51const ReadOnly = Context.Reference<boolean>("@t3tools/shared/nodeSqliteClient/ReadOnly", {
52 defaultValue: () => false,
53});
54
55/**
56 * Wrap the whole transaction, as in
57 * `sql.withTransaction(reads).pipe(readOnly)`. Inside an open write transaction
58 * the reads keep using the writer, and a write attempted on the reader fails
59 * with "attempt to write a readonly database".
60 */
61export const readOnly = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
62 Effect.provideService(effect, ReadOnly, true);
63
64interface Acquired {
65 readonly connection: "writer" | "reader";
66 readonly lockWaitMs: number;
67}
68
69const annotateAcquired = (fiber: Fiber.Fiber<unknown, unknown>, acquired: Acquired | undefined) => {
70 const span = Context.getOrUndefined(fiber.context, Tracer.ParentSpan);
71 if (span?._tag !== "Span" || acquired === undefined) return;
72 span.attribute("db.connection", acquired.connection);
73 span.attribute("db.lock_wait_ms", acquired.lockWaitMs);
74};
75
76const TransactionAcquire = Context.Reference<
77 { acquired?: Acquired; restore: typeof Effect.interruptible | undefined } | undefined
78>("@t3tools/shared/nodeSqliteClient/TransactionAcquire", { defaultValue: () => undefined });
79
80export class UnsupportedNodeSqliteVersionError extends Schema.TaggedError<UnsupportedNodeSqliteVersionError>()(
81 "UnsupportedNodeSqliteVersionError",
82 {
83 nodeVersion: Schema.String,
84 requirement: Schema.String,
85 },
86) {
87 override get message(): string {
88 return `Node.js ${this.nodeVersion} is missing required node:sqlite APIs. Upgrade to ${this.requirement}.`;
89 }
90}
91
92export class UnsupportedNodeSqliteOperationError extends Schema.TaggedError<UnsupportedNodeSqliteOperationError>()(
93 "UnsupportedNodeSqliteOperationError",
94 {},
95) {
96 override get message(): string {
97 return "Node SQLite does not support executeStream.";
98 }
99}
100
101const checkNodeSqliteCompat = () => {
102 const parts = process.versions.node.split(".").map(Number);
103 const major = parts[0] ?? 0;
104 const minor = parts[1] ?? 0;
105 const supported = (major === 22 && minor >= 16) || (major === 23 && minor >= 11) || major >= 24;
106
107 if (!supported) {
108 return Effect.die(
109 new UnsupportedNodeSqliteVersionError({
110 nodeVersion: process.versions.node,
111 requirement: "Node.js >=22.16, >=23.11, or >=24",
112 }),
113 );
114 }
115 return Effect.void;
116};
117
118/**
119 * `node:sqlite` reports the SQLite result code as `errcode`, while
120 * `classifySqliteError` reads `errno`.
121 */
122const classifyError = (cause: unknown, message: string, operation: string) => {
123 if (
124 Predicate.hasProperty(cause, "errcode") &&
125 typeof cause.errcode === "number" &&
126 !Predicate.hasProperty(cause, "errno")
127 ) {
128 Object.assign(cause, { errno: cause.errcode });
129 }
130 return classifySqliteError(cause, { message, operation });
131};
132
133/**
134 * SQLite keeps its copy of a statement's text and blob parameters until the
135 * statement is bound again or finalized, and `node:sqlite` cannot clear them.
136 */
137const LARGE_BINDING_SIZE = 64 * 1024;
138
139const isBlob = (value: unknown): value is ArrayBufferView | ArrayBufferLike =>
140 ArrayBuffer.isView(value) || NodeUtil.types.isAnyArrayBuffer(value);
141
142const bindingSize = (value: unknown): number => {
143 if (typeof value === "string") {
144 return value.length;
145 }
146 return isBlob(value) ? value.byteLength : 0;
147};
148
149const hasLargeBinding = (params: ReadonlyArray<unknown>): boolean => {
150 try {
151 let size = 0;
152 for (const param of params) {
153 if (
154 (typeof param === "object" || typeof param === "function") &&
155 param !== null &&
156 !isBlob(param)
157 ) {
158 // `node:sqlite` takes named parameters as one object, callable or not.
159 // Read data properties only: calling a getter here would run it twice.
160 for (const property of Object.values(Object.getOwnPropertyDescriptors(param))) {
161 if (!property.enumerable) continue;
162 if (!("value" in property)) return true;
163 size += bindingSize(property.value);
164 }
165 } else {
166 size += bindingSize(param);
167 }
168 }
169 return size > LARGE_BINDING_SIZE;
170 } catch {
171 return true;
172 }
173};
174
175// Evaluated source instead of a worker file, so the reader also starts from
176// bundles and single-executable builds that have no module file on disk.
177const readerWorkerSource = `
178const { parentPort, workerData } = require("node:worker_threads");
179const { DatabaseSync } = require("node:sqlite");
180let db;
181try {
182 // A read-only open cannot be undone by SQL, unlike PRAGMA query_only.
183 const next = new DatabaseSync(workerData.filename, {
184 readOnly: true,
185 allowExtension: workerData.allowExtension,
186 });
187 next.exec("PRAGMA busy_timeout = 5000;");
188 // Without WAL a reader's shared lock blocks the writer's commits, so refuse.
189 const mode = String(next.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
190 if (mode !== "wal") throw new Error("database uses journal_mode " + mode + ", not wal");
191 db = next;
192 parentPort.postMessage({ type: "ready" });
193} catch (error) {
194 parentPort.postMessage({ type: "unavailable", message: String(error && error.message ? error.message : error) });
195}
196const statements = new Map();
197const prepare = (sql, cached) => {
198 if (!cached) return db.prepare(sql);
199 let statement = statements.get(sql);
200 if (statement === undefined) {
201 statement = db.prepare(sql);
202 if (statements.size >= workerData.prepareCacheSize) statements.delete(statements.keys().next().value);
203 } else {
204 statements.delete(sql);
205 }
206 statements.set(sql, statement);
207 return statement;
208};
209parentPort.on("message", ({ id, sql, params, cached, values, raw, safeIntegers }) => {
210 let operation = "open";
211 try {
212 if (db === undefined) throw new Error("database reader is unavailable");
213 operation = "prepare";
214 const statement = prepare(sql, cached);
215 operation = "execute";
216 statement.setReadBigInts(safeIntegers);
217 if (statement.columns().length > 0) {
218 statement.setReturnArrays(values);
219 parentPort.postMessage({ id, rows: statement.all(...params) });
220 } else {
221 const result = statement.run(...params);
222 parentPort.postMessage({ id, rows: raw ? result : [] });
223 }
224 } catch (error) {
225 parentPort.postMessage({
226 id,
227 error: {
228 operation,
229 message: String(error && error.message ? error.message : error),
230 code: error && error.code,
231 errcode: error && error.errcode,
232 errstr: error && error.errstr,
233 },
234 });
235 }
236});
237`;
238
239interface ReaderRequest {
240 readonly sql: string;
241 readonly params: ReadonlyArray<unknown>;
242 readonly cached: boolean;
243 readonly values: boolean;
244 readonly raw: boolean;
245}
246
247type ReaderStartup =
248 | { readonly type: "ready" }
249 | { readonly type: "unavailable"; readonly message: string };
250
251type ReaderReply =
252 | { readonly id: number; readonly rows: ReadonlyArray<any> }
253 | {
254 readonly id: number;
255 readonly error: {
256 readonly operation: "open" | "prepare" | "execute";
257 readonly message: string;
258 readonly code?: unknown;
259 readonly errcode?: unknown;
260 readonly errstr?: unknown;
261 };
262 };
263
264const readerFailureMessages = {
265 open: "Failed to open database",
266 prepare: "Failed to prepare statement",
267 execute: "Failed to execute statement",
268} as const;
269
270const failed = (cause: unknown, message: string, operation: string) =>
271 new SqlError({ reason: classifyError(cause, message, operation) });
272
273// COMMIT, ROLLBACK and ROLLBACK TO SAVEPOINT. On a reader they change nothing,
274// so they succeed once the worker is gone instead of failing the cleanup.
275const endsReadTransaction = (sql: string) => /^\s*ROLLBACK\b|^\s*COMMIT\b/i.test(sql);
276
277/**
278 * Each worker gets its own `Connection`, so a transaction stays on the worker
279 * it began on: once that worker exits, its statements fail rather than silently
280 * continuing outside the transaction on a replacement.
281 */
282const makeReader = Effect.fnUntraced(function* (options: SqliteClientConfig) {
283 let current:
284 | {
285 readonly worker: NodeWorkerThreads.Worker;
286 readonly connection: Connection;
287 readonly started: Promise<ReaderStartup>;
288 }
289 | undefined;
290 let unavailable = false;
291 let nextRequestId = 0;
292
293 const start = () => {
294 const worker = new NodeWorkerThreads.Worker(readerWorkerSource, {
295 eval: true,
296 workerData: {
297 filename: options.filename,
298 allowExtension: options.allowExtension ?? false,
299 prepareCacheSize: options.prepareCacheSize ?? 200,
300 },
301 });
302 let announce: (startup: ReaderStartup) => void = () => {};
303 const started = new Promise<ReaderStartup>((resolve) => {
304 announce = resolve;
305 });
306 let stoppedMessage: string | undefined;
307 const pending = new Map<
308 number,
309 { readonly endsTransaction: boolean; readonly resume: (reply: ReaderReply) => void }
310 >();
311 const stop = (message: string) => {
312 stoppedMessage = message;
313 announce({ type: "unavailable", message });
314 if (current?.worker === worker) current = undefined;
315 for (const [id, request] of pending) {
316 request.resume(
317 request.endsTransaction
318 ? { id, rows: [] }
319 : { id, error: { operation: "execute", message } },
320 );
321 }
322 pending.clear();
323 };
324 worker.on("message", (reply: ReaderReply | ReaderStartup) => {
325 if ("type" in reply) {
326 announce(reply);
327 if (pending.size === 0) worker.unref();
328 return;
329 }
330 const request = pending.get(reply.id);
331 if (request === undefined) return;
332 pending.delete(reply.id);
333 if (pending.size === 0) worker.unref();
334 request.resume(reply);
335 });
336 worker.on("error", (cause) => stop(`Database reader failed: ${cause.message}`));
337 worker.on("exit", (code) => stop(`Database reader exited with code ${code}`));
338
339 const request = (input: ReaderRequest) =>
340 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
341 const endsTransaction = endsReadTransaction(input.sql);
342 if (stoppedMessage !== undefined) {
343 return endsTransaction
344 ? Effect.succeed([])
345 : Effect.fail(
346 failed(new Error(stoppedMessage), readerFailureMessages.execute, "execute"),
347 );
348 }
349 const safeIntegers = Boolean(Context.get(fiber.context, Client.SafeIntegers));
350 return Effect.callback<ReadonlyArray<any>, SqlError>((resume) => {
351 const id = nextRequestId++;
352 pending.set(id, {
353 endsTransaction,
354 resume: (reply) => {
355 if ("rows" in reply) {
356 resume(Effect.succeed(reply.rows));
357 return;
358 }
359 const { operation, message, ...codes } = reply.error;
360 resume(
361 Effect.fail(
362 failed(
363 Object.assign(new Error(message), codes),
364 readerFailureMessages[operation],
365 operation,
366 ),
367 ),
368 );
369 },
370 });
371 if (pending.size === 1) worker.ref();
372 const cached = input.cached && !hasLargeBinding(input.params);
373 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
374 worker.postMessage({ id, safeIntegers, ...input, cached });
375 });
376 });
377
378 const connection = identity<Connection>({
379 execute(sql, params, rowTransform) {
380 const effect = request({ sql, params, cached: true, values: false, raw: false });
381 return rowTransform ? Effect.map(effect, rowTransform) : effect;
382 },
383 executeRaw(sql, params) {
384 return request({ sql, params, cached: true, values: false, raw: true });
385 },
386 executeValues(sql, params) {
387 return request({ sql, params, cached: true, values: true, raw: false });
388 },
389 executeValuesUnprepared(sql, params) {
390 return request({ sql, params: params ?? [], cached: false, values: true, raw: false });
391 },
392 executeUnprepared(sql, params, rowTransform) {
393 // A read-only connection rejects BEGIN IMMEDIATE and BEGIN EXCLUSIVE,
394 // and a deferred BEGIN is all a read snapshot needs.
395 const statement = /^\s*BEGIN\b/i.test(sql) ? "BEGIN" : sql;
396 const effect = request({
397 sql: statement,
398 params: params ?? [],
399 cached: false,
400 values: false,
401 raw: false,
402 });
403 return rowTransform ? Effect.map(effect, rowTransform) : effect;
404 },
405 executeStream(_sql, _params) {
406 return Stream.die(new UnsupportedNodeSqliteOperationError());
407 },
408 });
409 current = { worker, connection, started };
410 return current;
411 };
412
413 yield* Effect.addFinalizer(() =>
414 Effect.promise(async () => {
415 await current?.worker.terminate();
416 }),
417 );
418
419 const startupTimeout = Duration.fromInputUnsafe(
420 options.readerStartupTimeout ?? Duration.seconds(10),
421 );
422
423 const turnOff = (reader: typeof current, reason: string) =>
424 Effect.suspend(() => {
425 if (reader !== undefined) {
426 if (current === reader) current = undefined;
427 void reader.worker.terminate();
428 }
429 if (unavailable) return Effect.succeed(undefined);
430 unavailable = true;
431 return Effect.logWarning("SQLite reader worker unavailable; reads use the main connection", {
432 reason,
433 }).pipe(Effect.as(undefined));
434 });
435
436 return Effect.suspend((): Effect.Effect<Connection | undefined> => {
437 if (unavailable) return Effect.succeed(undefined);
438 let reader: NonNullable<typeof current>;
439 try {
440 reader = current ?? start();
441 } catch (cause) {
442 return turnOff(undefined, String(cause));
443 }
444 // SqlClient acquires transaction connections uninterruptibly. Waiting for the
445 // worker happens before any lock is taken, so let a cancelled request leave.
446 return Effect.flatMap(
447 Effect.interruptible(
448 Effect.timeoutOption(
449 Effect.promise(() => reader.started),
450 startupTimeout,
451 ),
452 ),
453 (startup): Effect.Effect<Connection | undefined> =>
454 // Another acquire may have timed out and retired this worker while this one
455 // waited; a late "ready" must not hand out a worker that is being terminated.
456 unavailable || current !== reader
457 ? Effect.succeed(undefined)
458 : Option.isSome(startup) && startup.value.type === "ready"
459 ? Effect.succeed(reader.connection)
460 : turnOff(
461 reader,
462 Option.isSome(startup) && startup.value.type === "unavailable"
463 ? startup.value.message
464 : `worker did not open the database within ${Duration.toMillis(startupTimeout)} ms`,
465 ),
466 );
467 });
468});
469
470const CHECKPOINT_FRAMES = 1000;
471const CHECKPOINT_IDLE_MS = 100;
472const CHECKPOINT_BACKPRESSURE_FRAMES = 10 * CHECKPOINT_FRAMES;
473
474const readSafeSqliteInteger = (value: unknown) => {
475 const number = typeof value === "bigint" ? Number(value) : value;
476 return typeof number === "number" && Number.isSafeInteger(number) ? number : undefined;
477};
478
479// Evaluated source also works in bundles and single-executable builds.
480const checkpointWorkerSource = `
481const { parentPort, workerData } = require("node:worker_threads");
482const { DatabaseSync } = require("node:sqlite");
483const { statSync } = require("node:fs");
484let db;
485let frames;
486let checkpoint;
487let truncate;
488let journalSizeLimit = -1;
489let generation = 0;
490let nextTruncateId = 0;
491let pendingTruncate;
492let pendingBarriers = 0;
493let idle;
494const initialize = () => {
495 if (db !== undefined) return;
496 // The writer switches to WAL after constructing the client.
497 db = new DatabaseSync(workerData.filename);
498 db.exec("PRAGMA busy_timeout = 5000;");
499 const mode = String(db.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
500 if (mode !== "wal") throw new Error("database uses journal_mode " + mode + ", not wal");
501 // macOS requires F_FULLFSYNC to flush the drive cache.
502 db.exec("PRAGMA checkpoint_fullfsync = ON;");
503 frames = db.prepare("PRAGMA wal_checkpoint(NOOP)");
504 checkpoint = db.prepare("PRAGMA wal_checkpoint(PASSIVE)");
505 truncate = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)");
506};
507const atCeiling = (state) => state.log >= workerData.backpressureFrames;
508const exceedsSizeLimit = () =>
509 journalSizeLimit >= 0 && statSync(workerData.filename + "-wal").size > journalSizeLimit;
510const schedule = (state, blocked) => {
511 if (blocked || state.log - state.checkpointed >= workerData.frames) {
512 idle = setTimeout(() => check(undefined, undefined, true), workerData.idleMs);
513 }
514};
515const check = (id, nextJournalSizeLimit, force, nextGeneration = generation) => {
516 initialize();
517 if (Number.isSafeInteger(nextGeneration)) generation = Math.max(generation, nextGeneration);
518 if (Number.isSafeInteger(nextJournalSizeLimit)) journalSizeLimit = nextJournalSizeLimit;
519 let state = frames.get();
520 const oversized = exceedsSizeLimit();
521 if (force || state.log - state.checkpointed >= workerData.frames || oversized) {
522 checkpoint.get();
523 state = frames.get();
524 }
525 if (state.checkpointed === state.log && (atCeiling(state) || oversized)) {
526 pendingTruncate = { truncateId: ++nextTruncateId, checkId: id, generation, state };
527 parentPort.postMessage({
528 type: "truncate-request",
529 truncateId: pendingTruncate.truncateId,
530 checkId: id,
531 generation,
532 ...state,
533 });
534 return;
535 }
536 const blocked = (atCeiling(state) || oversized) && state.checkpointed < state.log;
537 parentPort.postMessage({ type: "checkpoint", id, generation, ...state, blocked });
538 schedule(state, blocked);
539};
540const finishTruncate = (truncateId) => {
541 if (pendingTruncate === undefined || pendingTruncate.truncateId !== truncateId) return;
542 const pending = pendingTruncate;
543 parentPort.postMessage({ type: "truncate-start", truncateId });
544 let busy;
545 // Admission is paused here; a pinned reader must not make truncation wait.
546 db.exec("PRAGMA busy_timeout = 0;");
547 try {
548 busy = truncate.get().busy !== 0;
549 } finally {
550 db.exec("PRAGMA busy_timeout = 5000;");
551 }
552 const state = frames.get();
553 const blocked = (atCeiling(state) && (busy || state.checkpointed < state.log)) || exceedsSizeLimit();
554 pendingTruncate = undefined;
555 parentPort.postMessage({
556 type: "checkpoint",
557 id: pending.checkId,
558 generation: pending.generation,
559 truncateId,
560 ...state,
561 blocked,
562 });
563 while (pendingBarriers > 0) {
564 pendingBarriers--;
565 parentPort.postMessage("barrier");
566 }
567 schedule(state, blocked);
568};
569parentPort.on("message", (request) => {
570 clearTimeout(idle);
571 if (request && request.type === "truncate") {
572 finishTruncate(request.truncateId);
573 return;
574 }
575 const isBarrier = request === "barrier";
576 if (pendingTruncate !== undefined) {
577 if (isBarrier) pendingBarriers++;
578 else if (request && request.type === "check") {
579 // Retire the request without labeling the pending snapshot with a newer generation.
580 parentPort.postMessage({
581 type: "checkpoint",
582 id: request.id,
583 generation: pendingTruncate.generation,
584 ...pendingTruncate.state,
585 blocked: true,
586 });
587 }
588 return;
589 }
590 const input = request && typeof request === "object" ? request : {};
591 check(input.id, input.journalSizeLimit, input.force, input.generation);
592 if (isBarrier) {
593 if (pendingTruncate !== undefined) pendingBarriers++;
594 else parentPort.postMessage("barrier");
595 }
596});
597`;
598
599const startCheckpointWorker = Effect.fnUntraced(function* (
600 filename: string,
601 writer: NodeSqlite.DatabaseSync,
602) {
603 const warn = (reason: string) =>
604 Effect.logWarning(
605 "SQLite checkpoint worker unavailable; checkpoints run on the main connection",
606 { reason },
607 );
608 if (typeof writer.isTransaction !== "boolean" || typeof writer.setAuthorizer !== "function") {
609 yield* warn("Node SQLite lacks transaction-state or statement-authorizer support");
610 return undefined;
611 }
612 const version = String(writer.prepare("SELECT sqlite_version() AS version").get()?.version);
613 const [major = 0, minor = 0] = version.split(".").map(Number);
614 // Older SQLite treats NOOP as PASSIVE, which would checkpoint on the writer.
615 if (major < 3 || (major === 3 && minor < 51)) {
616 yield* warn(`SQLite ${version} has no NOOP checkpoint`);
617 return undefined;
618 }
619 const frames = writer.prepare("PRAGMA wal_checkpoint(NOOP)");
620 const sizeLimit = writer.prepare("PRAGMA journal_size_limit");
621 let worker: NodeWorkerThreads.Worker;
622 try {
623 worker = new NodeWorkerThreads.Worker(checkpointWorkerSource, {
624 eval: true,
625 workerData: {
626 filename,
627 frames: CHECKPOINT_FRAMES,
628 backpressureFrames: CHECKPOINT_BACKPRESSURE_FRAMES,
629 idleMs: CHECKPOINT_IDLE_MS,
630 },
631 });
632 } catch (cause) {
633 yield* warn(String(cause));
634 return undefined;
635 }
636 const runFork = Effect.runForkWith(yield* Effect.context<never>());
637 let stopped = false;
638 let generation = 0;
639 let nextId = 0;
640 let inFlight: number | undefined;
641 let checkAgain = false;
642 let blocked = false;
643 let log = 0;
644 let checkpointed = 0;
645 let unknown = false;
646 let truncate: { id: number; acknowledged: boolean } | undefined;
647 type Waiter = { resume: () => void; cancelled: boolean };
648 const waiters: Array<Waiter> = [];
649 let elected: Waiter | undefined;
650 const gated = () =>
651 !stopped &&
652 !writer.isTransaction &&
653 (unknown || blocked || truncate !== undefined || log >= CHECKPOINT_BACKPRESSURE_FRAMES);
654 const wake = () => {
655 if (!gated() && elected === undefined) {
656 elected = waiters.shift();
657 elected?.resume();
658 }
659 if (waiters.length === 0 && elected === undefined) worker.unref();
660 };
661 const release = (waiter: Waiter) => {
662 waiter.cancelled = true;
663 const index = waiters.indexOf(waiter);
664 if (index !== -1) waiters.splice(index, 1);
665 if (elected === waiter) elected = undefined;
666 wake();
667 };
668 const handBack = (reason: string) => {
669 if (stopped) return;
670 stopped = true;
671 truncate = undefined;
672 try {
673 writer.exec(`PRAGMA wal_autocheckpoint = ${CHECKPOINT_FRAMES};`);
674 } catch {}
675 wake();
676 runFork(warn(reason));
677 };
678 const send = (message: unknown) => {
679 try {
680 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
681 worker.postMessage(message);
682 } catch (cause) {
683 handBack(String(cause));
684 }
685 };
686 const acknowledge = () => {
687 if (truncate === undefined || truncate.acknowledged || stopped || writer.isTransaction) return;
688 truncate.acknowledged = true;
689 send({ type: "truncate", truncateId: truncate.id });
690 };
691 const observe = () => {
692 try {
693 const state = frames.get();
694 const nextLog = readSafeSqliteInteger(state?.log);
695 const nextCheckpointed = readSafeSqliteInteger(state?.checkpointed);
696 if (nextLog === undefined || nextCheckpointed === undefined)
697 throw new Error("Invalid WAL frame counts");
698 log = nextLog;
699 checkpointed = nextCheckpointed;
700 unknown = false;
701 } catch {
702 unknown = true;
703 }
704 };
705 const request = (force = false) => {
706 if (stopped || writer.isTransaction) return;
707 if (truncate !== undefined) {
708 acknowledge();
709 return;
710 }
711 if (inFlight !== undefined) {
712 checkAgain = true;
713 return;
714 }
715 if (!force && !gated() && log - checkpointed < CHECKPOINT_FRAMES) return;
716 inFlight = ++nextId;
717 try {
718 send({
719 type: "check",
720 id: inFlight,
721 generation,
722 journalSizeLimit: readSafeSqliteInteger(sizeLimit.get()?.journal_size_limit),
723 force: force || gated(),
724 });
725 } catch (cause) {
726 handBack(String(cause));
727 }
728 };
729 const check = () => {
730 if (stopped || writer.isTransaction) return;
731 generation++;
732 observe();
733 request();
734 wake();
735 };
736 worker.on("error", (cause) => handBack(cause.message));
737 worker.on("exit", (code) => handBack(`exited with code ${code}`));
738 worker.on("message", (message: unknown) => {
739 if (stopped || typeof message !== "object" || message === null || !("type" in message)) return;
740 if (
741 message.type === "truncate-request" &&
742 "truncateId" in message &&
743 typeof message.truncateId === "number"
744 ) {
745 truncate = { id: message.truncateId, acknowledged: false };
746 blocked = true;
747 acknowledge();
748 return;
749 }
750 if (message.type !== "checkpoint") return;
751 const completedTruncate =
752 truncate !== undefined && "truncateId" in message && message.truncateId === truncate.id;
753 if (completedTruncate) truncate = undefined;
754 // An acknowledged truncate excludes new writer mutations, so its result is current.
755 if (
756 (completedTruncate || ("generation" in message && message.generation === generation)) &&
757 "log" in message &&
758 typeof message.log === "number" &&
759 "checkpointed" in message &&
760 typeof message.checkpointed === "number" &&
761 "blocked" in message &&
762 typeof message.blocked === "boolean"
763 ) {
764 log = message.log;
765 checkpointed = message.checkpointed;
766 blocked = message.blocked;
767 unknown = false;
768 }
769 // Even a stale snapshot must retire its request so a newer check can run.
770 if ("id" in message && message.id === inFlight) inFlight = undefined;
771 if (checkAgain && inFlight === undefined) {
772 checkAgain = false;
773 request(true);
774 }
775 wake();
776 });
777 yield* Effect.addFinalizer(() =>
778 Effect.promise(() => {
779 stopped = true;
780 truncate = undefined;
781 wake();
782 return worker.terminate();
783 }),
784 );
785 writer.exec("PRAGMA wal_autocheckpoint = 0;");
786 observe();
787 worker.unref();
788
789 const runWithAdmission = <A, E>(
790 execute: () => Exit.Exit<A, E>,
791 admitted?: Waiter,
792 ): Effect.Effect<A, E> =>
793 Effect.suspend(() => {
794 if (!gated()) {
795 // Release the election after executing; its successor must see the new WAL state.
796 try {
797 return execute();
798 } finally {
799 if (admitted !== undefined) release(admitted);
800 }
801 }
802 if (admitted !== undefined) release(admitted);
803 const waiter: Waiter = { resume: () => {}, cancelled: false };
804 const wait = Effect.uninterruptibleMask((restore) =>
805 Effect.withFiber((fiber) =>
806 (fiber.getRef(TransactionAcquire)?.restore ?? restore)(
807 Effect.callback<void>(function (this: Scheduler.Scheduler, resume) {
808 const dispatcher = this.makeDispatcher();
809 waiter.resume = () => {
810 dispatcher.scheduleTask(() => {
811 if (!waiter.cancelled) resume(Effect.void);
812 }, 0);
813 };
814 waiters.push(waiter);
815 worker.ref();
816 request(true);
817 wake();
818 return Effect.sync(() => release(waiter));
819 }),
820 ),
821 ),
822 );
823 return wait.pipe(
824 Effect.flatMap(() => runWithAdmission(execute, waiter)),
825 Effect.onInterrupt(() => Effect.sync(() => release(waiter))),
826 );
827 });
828 return { check, runWithAdmission };
829});
830
831const make = Effect.fn("makeWithDatabase")(function* (
832 options: SqliteClientConfig,
833): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
834 yield* checkNodeSqliteCompat();
835
836 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
837 const isFileDatabase = options.filename !== ":memory:" && options.filename !== "";
838 const transformRows = options.transformResultNames
839 ? Statement.defaultTransforms(options.transformResultNames).array
840 : undefined;
841
842 const makeConnection = Effect.gen(function* () {
843 const scope = yield* Effect.scope;
844 const db = yield* Effect.try({
845 try: () =>
846 new NodeSqlite.DatabaseSync(options.filename, {
847 readOnly: options.readonly ?? false,
848 allowExtension: options.allowExtension ?? false,
849 }),
850 catch: (cause) =>
851 new SqlError({
852 reason: classifyError(cause, "Failed to open database", "open"),
853 }),
854 });
855 yield* Scope.addFinalizer(
856 scope,
857 Effect.try({
858 try: () => db.close(),
859 catch: (cause) =>
860 new SqlError({
861 reason: classifyError(cause, "Failed to close database", "close"),
862 }),
863 }).pipe(Effect.orDie),
864 );
865 // Started after the close finalizer, so the worker stops before the writer closes.
866 const checkpoint =
867 options.checkpointWorker && isFileDatabase
868 ? yield* startCheckpointWorker(options.filename, db)
869 : undefined;
870
871 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
872 interface CheckpointClassification {
873 backpressure: boolean;
874 check: boolean;
875 }
876 const checkpointClassifications = new WeakMap<
877 NodeSqlite.StatementSync,
878 CheckpointClassification
879 >();
880 const mutatingPragmasWithValues = new Set([
881 "application_id",
882 "auto_vacuum",
883 "journal_mode",
884 "schema_version",
885 "user_version",
886 ]);
887 const mutatesPragma = (name: string | null, value: string | null) => {
888 const pragma = name?.toLowerCase();
889 if (pragma === undefined) return false;
890 if (pragma === "incremental_vacuum" || pragma === "optimize") return true;
891 if (pragma === "wal_checkpoint") return value?.toLowerCase() !== "noop";
892 return value !== null && mutatingPragmasWithValues.has(pragma);
893 };
894 let activeClassification: CheckpointClassification | undefined;
895 const withClassification = <A>(
896 classification: CheckpointClassification | undefined,
897 f: () => A,
898 ): A => {
899 if (classification === undefined) return f();
900 const previous = activeClassification;
901 activeClassification = classification;
902 try {
903 return f();
904 } finally {
905 activeClassification = previous;
906 }
907 };
908 if (checkpoint !== undefined) {
909 // SQLite may reprepare an expired statement while it executes. Keep this
910 // callback installed and collect only around that statement's prepare/run.
911 db.setAuthorizer((actionCode, action, argument) => {
912 const classification = activeClassification;
913 if (classification === undefined) return NodeSqlite.constants.SQLITE_OK;
914 const constants = NodeSqlite.constants;
915 if (actionCode === constants.SQLITE_TRANSACTION) {
916 classification.backpressure ||= action === "BEGIN";
917 classification.check ||= action === "COMMIT" || action === "ROLLBACK";
918 } else if (actionCode === constants.SQLITE_SAVEPOINT) {
919 classification.backpressure ||= action === "BEGIN";
920 classification.check = true;
921 } else if (actionCode === constants.SQLITE_PRAGMA && mutatesPragma(action, argument)) {
922 classification.backpressure = true;
923 classification.check = true;
924 } else if (
925 actionCode !== constants.SQLITE_READ &&
926 actionCode !== constants.SQLITE_SELECT &&
927 actionCode !== constants.SQLITE_FUNCTION &&
928 actionCode !== constants.SQLITE_RECURSIVE &&
929 actionCode !== constants.SQLITE_PRAGMA
930 ) {
931 classification.backpressure = true;
932 classification.check = true;
933 }
934 return constants.SQLITE_OK;
935 });
936 }
937 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
938 const cached = statementReaderCache.get(statement);
939 if (cached !== undefined) {
940 return cached;
941 }
942 const value = statement.columns().length > 0;
943 statementReaderCache.set(statement, value);
944 return value;
945 };
946
947 const prepare = (sql: string) =>
948 Effect.try({
949 try: () => {
950 const classification = { backpressure: false, check: false };
951 const statement = withClassification(classification, () => db.prepare(sql));
952 if (checkpoint !== undefined) checkpointClassifications.set(statement, classification);
953 return statement;
954 },
955 catch: (cause) =>
956 new SqlError({
957 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
958 }),
959 });
960
961 const prepareCache = yield* Cache.makeWith(prepare, {
962 capacity: options.prepareCacheSize ?? 200,
963 // A transient prepare failure must not outlive the lock or missing schema.
964 timeToLive: (exit) =>
965 Exit.isSuccess(exit) ? (options.prepareCacheTTL ?? Duration.minutes(10)) : Duration.zero,
966 });
967
968 const statementFor = (sql: string, params: ReadonlyArray<unknown>) =>
969 hasLargeBinding(params) ? prepare(sql) : Cache.get(prepareCache, sql);
970
971 const runStatement = (
972 statement: NodeSqlite.StatementSync,
973 params: ReadonlyArray<unknown>,
974 mode: "rows" | "raw" | "values" = "rows",
975 ) =>
976 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
977 const classification = checkpointClassifications.get(statement);
978 const execute = () => {
979 let arrays = false;
980 let result: Exit.Exit<ReadonlyArray<unknown>, SqlError>;
981 try {
982 const value = withClassification(classification, () => {
983 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
984 if (hasRows(statement)) {
985 arrays = mode === "values";
986 if (arrays) statement.setReturnArrays(true);
987 return statement.all(...(params as any));
988 }
989 const result = statement.run(...(params as any));
990 return mode === "raw" ? (result as unknown as ReadonlyArray<unknown>) : [];
991 });
992 result = Exit.succeed(value);
993 } catch (cause) {
994 result = Exit.fail(
995 new SqlError({
996 reason: classifyError(cause, "Failed to execute statement", "execute"),
997 }),
998 );
999 } finally {
1000 // OR FAIL may have committed earlier rows even when execution throws.
1001 if (classification?.check) checkpoint?.check();
1002 }
1003 if (arrays) {
1004 try {
1005 statement.setReturnArrays(false);
1006 } catch (cause) {
1007 return Exit.die(
1008 new SqlError({
1009 reason: classifyError(
1010 cause,
1011 "Failed to reset statement result mode",
1012 "resetResultMode",
1013 ),
1014 }),
1015 );
1016 }
1017 }
1018 return result;
1019 };
1020 return checkpoint !== undefined && classification?.backpressure
1021 ? checkpoint.runWithAdmission(execute)
1022 : execute();
1023 });
1024
1025 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
1026 Effect.flatMap(statementFor(sql, params), (statement) =>
1027 runStatement(statement, params, raw ? "raw" : "rows"),
1028 );
1029 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
1030 Effect.flatMap(statementFor(sql, params), (statement) =>
1031 runStatement(statement, params, "values"),
1032 );
1033
1034 return identity<Connection>({
1035 execute(sql, params, rowTransform) {
1036 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
1037 },
1038 executeRaw(sql, params) {
1039 return run(sql, params, true);
1040 },
1041 executeValues(sql, params) {
1042 return runValues(sql, params);
1043 },
1044 executeValuesUnprepared(sql, params) {
1045 return Effect.flatMap(prepare(sql), (statement) =>
1046 runStatement(statement, params ?? [], "values"),
1047 );
1048 },
1049 executeUnprepared(sql, params, rowTransform) {
1050 const effect = prepare(sql).pipe(
1051 Effect.flatMap((statement) => runStatement(statement, params ?? [])),
1052 );
1053 return rowTransform ? Effect.map(effect, rowTransform) : effect;
1054 },
1055 executeStream(_sql, _params) {
1056 return Stream.die(new UnsupportedNodeSqliteOperationError());
1057 },
1058 });
1059 });
1060
1061 const semaphore = yield* Semaphore.make(1);
1062 const connection = yield* makeConnection;
1063 const acquireReader =
1064 options.readerWorker && isFileDatabase ? yield* makeReader(options) : undefined;
1065 const readerSemaphore = yield* Semaphore.make(1);
1066
1067 const writer = { name: "writer" as const, lock: semaphore, connection };
1068 const route = Effect.withFiber((fiber) =>
1069 acquireReader !== undefined && Context.get(fiber.context, ReadOnly)
1070 ? Effect.map(acquireReader, (readerConnection) =>
1071 readerConnection === undefined
1072 ? writer
1073 : { name: "reader" as const, lock: readerSemaphore, connection: readerConnection },
1074 )
1075 : Effect.succeed(writer),
1076 );
1077
1078 const acquired = (
1079 target: { readonly name: Acquired["connection"] },
1080 clock: Clock.Clock,
1081 start: bigint,
1082 ): Acquired => ({
1083 connection: target.name,
1084 lockWaitMs: Number((clock.monotonicTimeNanosUnsafe() - start) / 1000n) / 1000,
1085 });
1086
1087 const writerBorrowBatchSize = 16;
1088 let writerBorrowsSinceYield = 0;
1089 const borrower: Borrower = (use) =>
1090 Effect.flatMap(route, (target) =>
1091 Effect.withFiber((fiber) => {
1092 const clock = fiber.getRef(Clock.Clock);
1093 const start = clock.monotonicTimeNanosUnsafe();
1094 const useConnection = Effect.suspend(() => {
1095 if (
1096 fiber.getRef(References.TracerEnabled) &&
1097 fiber.getRef(Statement.SpanPropagationEnabled)
1098 ) {
1099 annotateAcquired(fiber, acquired(target, clock, start));
1100 }
1101 return use(target.connection);
1102 });
1103 if (!options.checkpointWorker || target.name !== "writer") {
1104 return target.lock.withPermits(1)(useConnection);
1105 }
1106 const writerUse = Effect.onExit(useConnection, (exit) =>
1107 Effect.sync(() => {
1108 writerBorrowsSinceYield = Exit.hasInterrupts(exit)
1109 ? 0
1110 : Math.min(writerBorrowsSinceYield + 1, writerBorrowBatchSize);
1111 }),
1112 );
1113 return Effect.flatMap(target.lock.withPermitsIfAvailable(1)(writerUse), (result) =>
1114 Option.isSome(result)
1115 ? Effect.succeed(result.value)
1116 : target.lock.withPermits(1)(
1117 Effect.andThen(
1118 // Failed SQL also consumes the batch; cancellation hands off immediately.
1119 Effect.suspend(() => {
1120 if (writerBorrowsSinceYield < writerBorrowBatchSize) return Effect.void;
1121 writerBorrowsSinceYield = 0;
1122 return Effect.callback<void>((resume) => {
1123 const immediate = setImmediate(() => resume(Effect.void));
1124 return Effect.sync(() => clearImmediate(immediate));
1125 });
1126 }),
1127 writerUse,
1128 ),
1129 ),
1130 );
1131 }),
1132 );
1133 const transactionAcquirer = Effect.flatMap(route, (target) =>
1134 Effect.uninterruptibleMask((restore) => {
1135 const fiber = Fiber.getCurrent()!;
1136 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
1137 const clock = fiber.getRef(Clock.Clock);
1138 const start = clock.monotonicTimeNanosUnsafe();
1139 const pending = fiber.getRef(TransactionAcquire);
1140 const acquire = Effect.tap((pending?.restore ?? restore)(target.lock.take(1)), () => {
1141 if (pending !== undefined) pending.acquired = acquired(target, clock, start);
1142 return Scope.addFinalizer(scope, target.lock.release(1));
1143 });
1144 return Effect.as(
1145 // A scheduler yield after taking the permit must not precede its release finalizer.
1146 Effect.provideService(acquire, Scheduler.PreventSchedulerYield, true),
1147 target.connection,
1148 );
1149 }),
1150 );
1151
1152 const client = yield* Client.make({
1153 acquirer: transactionAcquirer,
1154 borrower,
1155 compiler,
1156 transactionAcquirer,
1157 // A deferred BEGIN only takes the write lock at the first write. If another
1158 // process commits after this transaction's first read, that write fails at
1159 // once with SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot wait out.
1160 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
1161 spanAttributes: [
1162 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
1163 [ATTR_DB_SYSTEM_NAME, "sqlite"],
1164 ],
1165 transformRows,
1166 });
1167 const withTransaction = client.withTransaction;
1168 return Object.assign(client, {
1169 withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1170 Effect.uninterruptibleMask((restore) => {
1171 // SqlClient masks setup; acquisition must preserve the caller's interruptibility.
1172 const pending: { acquired?: Acquired; restore: typeof Effect.interruptible | undefined } = {
1173 restore,
1174 };
1175 const body = Effect.withFiber<A, E, R>((fiber) => {
1176 annotateAcquired(fiber, pending.acquired);
1177 pending.restore = undefined;
1178 return effect;
1179 });
1180 return restore(
1181 withTransaction(body).pipe(Effect.provideService(TransactionAcquire, pending)),
1182 );
1183 }),
1184 });
1185});
1186
1187export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
1188 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));