Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

nodeSqliteClient.ts

1,299 lines46.8 KB

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