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