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

nodeSqliteClient.ts

1,299 lines47.1 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 // @effect-diagnostics-next-line effectSucceedWithVoid:off - The connection result distinguishes undefined from void.
455 if (pool.unavailable) return Effect.succeed(undefined);
456 pool.unavailable = true;
457 return Effect.logWarning("SQLite reader worker unavailable; reads use the main connection", {
458 reason,
459 }).pipe(Effect.as(undefined));
460 });
461​
462 return Effect.suspend((): Effect.Effect<Connection | undefined> => {
463 // @effect-diagnostics-next-line effectSucceedWithVoid:off - The connection result distinguishes undefined from void.
464 if (pool.unavailable) return Effect.succeed(undefined);
465 let reader: NonNullable<typeof current>;
466 try {
467 reader = current ?? start();
468 } catch (cause) {
469 return turnOff(undefined, String(cause));
470 }
471 return Effect.flatMap(
472 Effect.withFiber((fiber) => {
473 const restore = Context.get(fiber.context, ReadOnly) ?? identity;
474 return restore(
475 Effect.timeoutOption(
476 Effect.promise(() => reader.started),
477 startupTimeout,
478 ),
479 );
480 }),
481 (startup): Effect.Effect<Connection | undefined> =>
482 // A late ready event must not hand out a worker retired by another acquire timeout.
483 pool.unavailable || current !== reader
484 ? // @effect-diagnostics-next-line effectSucceedWithVoid:off - The connection result distinguishes undefined from void.
485 Effect.succeed(undefined)
486 : Option.isSome(startup) && startup.value.type === "ready"
487 ? Effect.succeed(reader.connection)
488 : turnOff(
489 reader,
490 Option.isSome(startup) && startup.value.type === "unavailable"
491 ? startup.value.message
492 : `worker did not open the database within ${Duration.toMillis(startupTimeout)} ms`,
493 ),
494 );
495 });
496});
497​
498const CHECKPOINT_FRAMES = 1000;
499const CHECKPOINT_IDLE_MS = 100;
500const CHECKPOINT_BACKPRESSURE_FRAMES = 10 * CHECKPOINT_FRAMES;
501​
502const readSafeSqliteInteger = (value: unknown) => {
503 const number = typeof value === "bigint" ? Number(value) : value;
504 return typeof number === "number" && Number.isSafeInteger(number) ? number : undefined;
505};
506​
507// Evaluated source also works in bundles and single-executable builds.
508const checkpointWorkerSource = `
509const { parentPort, workerData } = require("node:worker_threads");
510const { DatabaseSync } = require("node:sqlite");
511const { statSync } = require("node:fs");
512let db;
513let frames;
514let checkpoint;
515let truncate;
516let journalSizeLimit = -1;
517let generation = 0;
518let nextTruncateId = 0;
519let pendingTruncate;
520let pendingBarriers = 0;
521let idle;
522const initialize = () => {
523 if (db !== undefined) return;
524 // The writer switches to WAL after constructing the client.
525 db = new DatabaseSync(workerData.filename);
526 db.exec("PRAGMA busy_timeout = 5000;");
527 const mode = String(db.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
528 if (mode !== "wal") throw new Error("database uses journal_mode " + mode + ", not wal");
529 // macOS requires F_FULLFSYNC to flush the drive cache.
530 db.exec("PRAGMA checkpoint_fullfsync = ON;");
531 frames = db.prepare("PRAGMA wal_checkpoint(NOOP)");
532 checkpoint = db.prepare("PRAGMA wal_checkpoint(PASSIVE)");
533 truncate = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)");
534};
535const atCeiling = (state) => state.log >= workerData.backpressureFrames;
536const exceedsSizeLimit = () =>
537 journalSizeLimit >= 0 && statSync(workerData.filename + "-wal").size > journalSizeLimit;
538const schedule = (state, blocked) => {
539 if (blocked || state.log - state.checkpointed >= workerData.frames) {
540 idle = setTimeout(() => check(undefined, undefined, true), workerData.idleMs);
541 }
542};
543const check = (id, nextJournalSizeLimit, force, nextGeneration = generation) => {
544 initialize();
545 if (Number.isSafeInteger(nextGeneration)) generation = Math.max(generation, nextGeneration);
546 if (Number.isSafeInteger(nextJournalSizeLimit)) journalSizeLimit = nextJournalSizeLimit;
547 let state = frames.get();
548 const oversized = exceedsSizeLimit();
549 if (force || state.log - state.checkpointed >= workerData.frames || oversized) {
550 checkpoint.get();
551 state = frames.get();
552 }
553 if (state.checkpointed === state.log && (atCeiling(state) || oversized)) {
554 pendingTruncate = { truncateId: ++nextTruncateId, checkId: id, generation, state };
555 parentPort.postMessage({
556 type: "truncate-request",
557 truncateId: pendingTruncate.truncateId,
558 checkId: id,
559 generation,
560 ...state,
561 });
562 return;
563 }
564 const blocked = (atCeiling(state) || oversized) && state.checkpointed < state.log;
565 parentPort.postMessage({ type: "checkpoint", id, generation, ...state, blocked });
566 schedule(state, blocked);
567};
568const finishTruncate = (truncateId) => {
569 if (pendingTruncate === undefined || pendingTruncate.truncateId !== truncateId) return;
570 const pending = pendingTruncate;
571 parentPort.postMessage({ type: "truncate-start", truncateId });
572 let busy;
573 // Admission is paused here; a pinned reader must not make truncation wait.
574 db.exec("PRAGMA busy_timeout = 0;");
575 try {
576 busy = truncate.get().busy !== 0;
577 } finally {
578 db.exec("PRAGMA busy_timeout = 5000;");
579 }
580 const state = frames.get();
581 const blocked = (atCeiling(state) && (busy || state.checkpointed < state.log)) || exceedsSizeLimit();
582 pendingTruncate = undefined;
583 parentPort.postMessage({
584 type: "checkpoint",
585 id: pending.checkId,
586 generation: pending.generation,
587 truncateId,
588 ...state,
589 blocked,
590 });
591 while (pendingBarriers > 0) {
592 pendingBarriers--;
593 parentPort.postMessage("barrier");
594 }
595 schedule(state, blocked);
596};
597parentPort.on("message", (request) => {
598 clearTimeout(idle);
599 if (request && request.type === "truncate") {
600 finishTruncate(request.truncateId);
601 return;
602 }
603 const isBarrier = request === "barrier";
604 if (pendingTruncate !== undefined) {
605 if (isBarrier) pendingBarriers++;
606 else if (request && request.type === "check") {
607 // Retire the request without labeling the pending snapshot with a newer generation.
608 parentPort.postMessage({
609 type: "checkpoint",
610 id: request.id,
611 generation: pendingTruncate.generation,
612 ...pendingTruncate.state,
613 blocked: true,
614 });
615 }
616 return;
617 }
618 const input = request && typeof request === "object" ? request : {};
619 check(input.id, input.journalSizeLimit, input.force, input.generation);
620 if (isBarrier) {
621 if (pendingTruncate !== undefined) pendingBarriers++;
622 else parentPort.postMessage("barrier");
623 }
624});
625`;
626​
627const startCheckpointWorker = Effect.fnUntraced(function* (
628 filename: string,
629 writer: NodeSqlite.DatabaseSync,
630) {
631 const warn = (reason: string) =>
632 Effect.logWarning(
633 "SQLite checkpoint worker unavailable; checkpoints run on the main connection",
634 { reason },
635 );
636 if (typeof writer.isTransaction !== "boolean" || typeof writer.setAuthorizer !== "function") {
637 yield* warn("Node SQLite lacks transaction-state or statement-authorizer support");
638 return undefined;
639 }
640 const version = String(writer.prepare("SELECT sqlite_version() AS version").get()?.version);
641 const [major = 0, minor = 0] = version.split(".").map(Number);
642 // Older SQLite treats NOOP as PASSIVE, which would checkpoint on the writer.
643 if (major < 3 || (major === 3 && minor < 51)) {
644 yield* warn(`SQLite ${version} has no NOOP checkpoint`);
645 return undefined;
646 }
647 const frames = writer.prepare("PRAGMA wal_checkpoint(NOOP)");
648 const sizeLimit = writer.prepare("PRAGMA journal_size_limit");
649 const started = yield* Effect.try(
650 () =>
651 new NodeWorkerThreads.Worker(checkpointWorkerSource, {
652 eval: true,
653 workerData: {
654 filename,
655 frames: CHECKPOINT_FRAMES,
656 backpressureFrames: CHECKPOINT_BACKPRESSURE_FRAMES,
657 idleMs: CHECKPOINT_IDLE_MS,
658 },
659 }),
660 ).pipe(Effect.result);
661 if (Result.isFailure(started)) {
662 yield* warn(String(started.failure.cause));
663 return undefined;
664 }
665 const worker = started.success;
666 const runFork = Effect.runForkWith(yield* Effect.context<never>());
667 let stopped = false;
668 let generation = 0;
669 let nextId = 0;
670 let inFlight: number | undefined;
671 let checkAgain = false;
672 let blocked = false;
673 let log = 0;
674 let checkpointed = 0;
675 let unknown = false;
676 let truncate: { id: number; acknowledged: boolean } | undefined;
677 type Waiter = { resume: () => void; cancelled: boolean };
678 const waiters: Array<Waiter> = [];
679 let elected: Waiter | undefined;
680 const gated = () =>
681 !stopped &&
682 !writer.isTransaction &&
683 (unknown || blocked || truncate !== undefined || log >= CHECKPOINT_BACKPRESSURE_FRAMES);
684 const wake = () => {
685 if (!gated() && elected === undefined) {
686 elected = waiters.shift();
687 elected?.resume();
688 }
689 if (waiters.length === 0 && elected === undefined) worker.unref();
690 };
691 const release = (waiter: Waiter) => {
692 waiter.cancelled = true;
693 const index = waiters.indexOf(waiter);
694 if (index !== -1) waiters.splice(index, 1);
695 if (elected === waiter) elected = undefined;
696 wake();
697 };
698 const handBack = (reason: string) => {
699 if (stopped) return;
700 stopped = true;
701 truncate = undefined;
702 try {
703 writer.exec(`PRAGMA wal_autocheckpoint = ${CHECKPOINT_FRAMES};`);
704 } catch {}
705 wake();
706 runFork(warn(reason));
707 };
708 const send = (message: unknown) => {
709 try {
710 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
711 worker.postMessage(message);
712 } catch (cause) {
713 handBack(String(cause));
714 }
715 };
716 const acknowledge = () => {
717 if (truncate === undefined || truncate.acknowledged || stopped || writer.isTransaction) return;
718 truncate.acknowledged = true;
719 send({ type: "truncate", truncateId: truncate.id });
720 };
721 const observe = () => {
722 try {
723 const state = frames.get();
724 const nextLog = readSafeSqliteInteger(state?.log);
725 const nextCheckpointed = readSafeSqliteInteger(state?.checkpointed);
726 if (nextLog === undefined || nextCheckpointed === undefined)
727 throw new Error("Invalid WAL frame counts");
728 log = nextLog;
729 checkpointed = nextCheckpointed;
730 unknown = false;
731 } catch {
732 unknown = true;
733 }
734 };
735 const request = (force = false) => {
736 if (stopped || writer.isTransaction) return;
737 if (truncate !== undefined) {
738 acknowledge();
739 return;
740 }
741 if (inFlight !== undefined) {
742 checkAgain = true;
743 return;
744 }
745 if (!force && !gated() && log - checkpointed < CHECKPOINT_FRAMES) return;
746 inFlight = ++nextId;
747 try {
748 send({
749 type: "check",
750 id: inFlight,
751 generation,
752 journalSizeLimit: readSafeSqliteInteger(sizeLimit.get()?.journal_size_limit),
753 force: force || gated(),
754 });
755 } catch (cause) {
756 handBack(String(cause));
757 }
758 };
759 const check = () => {
760 if (stopped || writer.isTransaction) return;
761 generation++;
762 observe();
763 request();
764 wake();
765 };
766 worker.on("error", (cause) => handBack(cause.message));
767 worker.on("exit", (code) => handBack(`exited with code ${code}`));
768 worker.on("message", (message: unknown) => {
769 if (stopped || typeof message !== "object" || message === null || !("type" in message)) return;
770 if (
771 message.type === "truncate-request" &&
772 "truncateId" in message &&
773 typeof message.truncateId === "number"
774 ) {
775 truncate = { id: message.truncateId, acknowledged: false };
776 blocked = true;
777 acknowledge();
778 return;
779 }
780 if (message.type !== "checkpoint") return;
781 const completedTruncate =
782 truncate !== undefined && "truncateId" in message && message.truncateId === truncate.id;
783 if (completedTruncate) truncate = undefined;
784 // An acknowledged truncate excludes new writer mutations, so its result is current.
785 if (
786 (completedTruncate || ("generation" in message && message.generation === generation)) &&
787 "log" in message &&
788 typeof message.log === "number" &&
789 "checkpointed" in message &&
790 typeof message.checkpointed === "number" &&
791 "blocked" in message &&
792 typeof message.blocked === "boolean"
793 ) {
794 log = message.log;
795 checkpointed = message.checkpointed;
796 blocked = message.blocked;
797 unknown = false;
798 }
799 // Even a stale snapshot must retire its request so a newer check can run.
800 if ("id" in message && message.id === inFlight) inFlight = undefined;
801 if (checkAgain && inFlight === undefined) {
802 checkAgain = false;
803 request(true);
804 }
805 wake();
806 });
807 yield* Effect.addFinalizer(() =>
808 Effect.promise(() => {
809 stopped = true;
810 truncate = undefined;
811 wake();
812 return worker.terminate();
813 }),
814 );
815 writer.exec("PRAGMA wal_autocheckpoint = 0;");
816 observe();
817 worker.unref();
818​
819 const runWithAdmission = <A, E>(
820 execute: () => Exit.Exit<A, E>,
821 admitted?: Waiter,
822 ): Effect.Effect<A, E> =>
823 Effect.suspend(() => {
824 if (!gated()) {
825 // Release the election after executing; its successor must see the new WAL state.
826 try {
827 return execute();
828 } finally {
829 if (admitted !== undefined) release(admitted);
830 }
831 }
832 if (admitted !== undefined) release(admitted);
833 const waiter: Waiter = { resume: () => {}, cancelled: false };
834 const wait = Effect.uninterruptibleMask((restore) =>
835 Effect.withFiber((fiber) =>
836 (fiber.getRef(TransactionAcquire)?.restore ?? restore)(
837 Effect.callback<void>(function (this: Scheduler.Scheduler, resume) {
838 const dispatcher = this.makeDispatcher();
839 waiter.resume = () => {
840 dispatcher.scheduleTask(() => {
841 if (!waiter.cancelled) resume(Effect.void);
842 }, 0);
843 };
844 waiters.push(waiter);
845 worker.ref();
846 request(true);
847 wake();
848 return Effect.sync(() => release(waiter));
849 }),
850 ),
851 ),
852 );
853 return wait.pipe(
854 Effect.flatMap(() => runWithAdmission(execute, waiter)),
855 Effect.onInterrupt(() => Effect.sync(() => release(waiter))),
856 );
857 });
858 return { check, runWithAdmission };
859});
860​
861const make = Effect.fn("makeWithDatabase")(function* (
862 options: SqliteClientConfig,
863): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
864 yield* checkNodeSqliteCompat();
865​
866 const compiler = Statement.makeCompilerSqlite();
867 const isFileDatabase = options.filename !== ":memory:" && options.filename !== "";
868​
869 const makeConnection = Effect.gen(function* () {
870 const scope = yield* Effect.scope;
871 const db = yield* Effect.try({
872 try: () => {
873 const connection = new NodeSqlite.DatabaseSync(options.filename, {
874 readOnly: options.readonly ?? false,
875 allowExtension: false,
876 });
877 try {
878 if (options.cacheSizeKiB !== undefined)
879 connection.exec(`PRAGMA cache_size = ${-Math.trunc(options.cacheSizeKiB)}`);
880 if (options.mmapSizeBytes !== undefined)
881 connection.exec(`PRAGMA mmap_size = ${Math.trunc(options.mmapSizeBytes)}`);
882 return connection;
883 } catch (cause) {
884 connection.close();
885 throw cause;
886 }
887 },
888 catch: (cause) =>
889 new SqlError({
890 reason: classifyError(cause, "Failed to open database", "open"),
891 }),
892 });
893 yield* Scope.addFinalizer(
894 scope,
895 Effect.try({
896 try: () => db.close(),
897 catch: (cause) =>
898 new SqlError({
899 reason: classifyError(cause, "Failed to close database", "close"),
900 }),
901 }).pipe(Effect.orDie),
902 );
903 // Started after the close finalizer, so the worker stops before the writer closes.
904 const checkpoint =
905 options.checkpointWorker && isFileDatabase
906 ? yield* startCheckpointWorker(options.filename, db)
907 : undefined;
908​
909 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
910 interface CheckpointClassification {
911 backpressure: boolean;
912 check: boolean;
913 }
914 const checkpointClassifications = new WeakMap<
915 NodeSqlite.StatementSync,
916 CheckpointClassification
917 >();
918 const mutatingPragmasWithValues = new Set([
919 "application_id",
920 "auto_vacuum",
921 "journal_mode",
922 "schema_version",
923 "user_version",
924 ]);
925 const mutatesPragma = (name: string | null, value: string | null) => {
926 const pragma = name?.toLowerCase();
927 if (pragma === undefined) return false;
928 if (pragma === "incremental_vacuum" || pragma === "optimize") return true;
929 if (pragma === "wal_checkpoint") return value?.toLowerCase() !== "noop";
930 return value !== null && mutatingPragmasWithValues.has(pragma);
931 };
932 let activeClassification: CheckpointClassification | undefined;
933 const withClassification = <A>(
934 classification: CheckpointClassification | undefined,
935 f: () => A,
936 ): A => {
937 if (classification === undefined) return f();
938 const previous = activeClassification;
939 activeClassification = classification;
940 try {
941 return f();
942 } finally {
943 activeClassification = previous;
944 }
945 };
946 if (checkpoint !== undefined) {
947 // SQLite may reprepare an expired statement while it executes. Keep this
948 // callback installed and collect only around that statement's prepare/run.
949 db.setAuthorizer((actionCode, action, argument) => {
950 const classification = activeClassification;
951 if (classification === undefined) return NodeSqlite.constants.SQLITE_OK;
952 const constants = NodeSqlite.constants;
953 if (actionCode === constants.SQLITE_TRANSACTION) {
954 classification.backpressure ||= action === "BEGIN";
955 classification.check ||= action === "COMMIT" || action === "ROLLBACK";
956 } else if (actionCode === constants.SQLITE_SAVEPOINT) {
957 classification.backpressure ||= action === "BEGIN";
958 classification.check = true;
959 } else if (actionCode === constants.SQLITE_PRAGMA && mutatesPragma(action, argument)) {
960 classification.backpressure = true;
961 classification.check = true;
962 } else if (
963 actionCode !== constants.SQLITE_READ &&
964 actionCode !== constants.SQLITE_SELECT &&
965 actionCode !== constants.SQLITE_FUNCTION &&
966 actionCode !== constants.SQLITE_RECURSIVE &&
967 actionCode !== constants.SQLITE_PRAGMA
968 ) {
969 classification.backpressure = true;
970 classification.check = true;
971 }
972 return constants.SQLITE_OK;
973 });
974 }
975 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
976 const cached = statementReaderCache.get(statement);
977 if (cached !== undefined) {
978 return cached;
979 }
980 const value = statement.columns().length > 0;
981 statementReaderCache.set(statement, value);
982 return value;
983 };
984​
985 const prepare = (sql: string) =>
986 Effect.try({
987 try: () => {
988 const classification = { backpressure: false, check: false };
989 const statement = withClassification(classification, () => db.prepare(sql));
990 if (checkpoint !== undefined) checkpointClassifications.set(statement, classification);
991 return statement;
992 },
993 catch: (cause) =>
994 new SqlError({
995 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
996 }),
997 });
998​
999 const prepareCache = yield* Cache.makeWith(prepare, {
1000 capacity: 200,
1001 // A transient prepare failure must not outlive the lock or missing schema.
1002 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.minutes(10) : Duration.zero),
1003 });
1004​
1005 const statementFor = (sql: string, params: ReadonlyArray<unknown>) =>
1006 hasLargeBinding(params) ? prepare(sql) : Cache.get(prepareCache, sql);
1007​
1008 const runStatement = (
1009 statement: NodeSqlite.StatementSync,
1010 params: ReadonlyArray<unknown>,
1011 mode: "rows" | "raw" | "values" = "rows",
1012 ) =>
1013 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
1014 const classification = checkpointClassifications.get(statement);
1015 const execute = () => {
1016 let arrays = false;
1017 let result: Exit.Exit<ReadonlyArray<unknown>, SqlError>;
1018 try {
1019 const value = withClassification(classification, () => {
1020 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
1021 if (hasRows(statement)) {
1022 arrays = mode === "values";
1023 if (arrays) statement.setReturnArrays(true);
1024 return statement.all(...(params as any));
1026 const result = statement.run(...(params as any));
1027 return mode === "raw" ? (result as unknown as ReadonlyArray<unknown>) : [];
1028 });
1029 result = Exit.succeed(value);
1030 } catch (cause) {
1031 result = Exit.fail(
1032 new SqlError({
1033 reason: classifyError(cause, "Failed to execute statement", "execute"),
1034 }),
1035 );
1036 } finally {
1037 // OR FAIL may have committed earlier rows even when execution throws.
1038 if (classification?.check) checkpoint?.check();
1040 if (arrays) {
1041 try {
1042 statement.setReturnArrays(false);
1043 } catch (cause) {
1044 return Exit.die(
1045 new SqlError({
1046 reason: classifyError(
1047 cause,
1048 "Failed to reset statement result mode",
1049 "resetResultMode",
1050 ),
1051 }),
1052 );
1055 return result;
1056 };
1057 return checkpoint !== undefined && classification?.backpressure
1058 ? checkpoint.runWithAdmission(execute)
1059 : execute();
1060 });
1061​
1062 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
1063 Effect.flatMap(statementFor(sql, params), (statement) =>
1064 runStatement(statement, params, raw ? "raw" : "rows"),
1065 );
1066 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
1067 Effect.flatMap(statementFor(sql, params), (statement) =>
1068 runStatement(statement, params, "values"),
1069 );
1070​
1071 return identity<Connection>({
1072 execute(sql, params, rowTransform) {
1073 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
1074 },
1075 executeRaw(sql, params) {
1076 return run(sql, params, true);
1077 },
1078 executeValues(sql, params) {
1079 return runValues(sql, params);
1080 },
1081 executeValuesUnprepared(sql, params) {
1082 return Effect.flatMap(prepare(sql), (statement) =>
1083 runStatement(statement, params ?? [], "values"),
1084 );
1085 },
1086 executeUnprepared(sql, params, rowTransform) {
1087 const effect = prepare(sql).pipe(
1088 Effect.flatMap((statement) => runStatement(statement, params ?? [])),
1089 );
1090 return rowTransform ? Effect.map(effect, rowTransform) : effect;
1091 },
1092 executeStream(_sql, _params) {
1093 return Stream.die(new UnsupportedNodeSqliteOperationError());
1094 },
1095 });
1096 });
1097​
1098 const semaphore = yield* Semaphore.make(1);
1099 const connection = yield* makeConnection;
1100 // A reader that cannot start turns off the whole pool, so routing never picks a dead slot.
1101 const readerPool = { unavailable: false };
1102 const readers =
1103 options.readerWorker && isFileDatabase
1104 ? yield* Effect.forEach(Array.from({ length: READER_POOL_SIZE }), () =>
1105 Effect.map(
1106 Effect.all([makeReader(options, readerPool), Semaphore.make(1)]),
1107 ([acquire, lock]) => ({
1108 acquire,
1109 lock,
1110 claims: 0,
1111 }),
1112 ),
1114 : [];
1115​
1116 const writer = { name: "writer" as const, lock: semaphore, connection };
1117 let activeWriter: ConnectionOwner | undefined;
1118 // Callers must run route uninterruptibly and pass `claimed` a finalizer that runs `release` once.
1119 const route = (claimed: (release: Effect.Effect<void>) => Effect.Effect<void>) =>
1120 Effect.withFiber((fiber) => {
1121 if (readers.length === 0 || readerPool.unavailable || !Context.get(fiber.context, ReadOnly)) {
1122 return Effect.succeed(writer);
1124 // Least claimed wins and ties go to the lowest slot, so idle slots never start a worker.
1125 let slot = readers[0]!;
1126 for (const candidate of readers) if (candidate.claims < slot.claims) slot = candidate;
1127 slot.claims++;
1128 const reader = slot;
1129 return Effect.andThen(
1130 claimed(
1131 Effect.sync(() => {
1132 reader.claims--;
1133 }),
1134 ),
1135 Effect.map(reader.acquire, (readerConnection) =>
1136 readerConnection === undefined
1137 ? writer
1138 : { name: "reader" as const, lock: reader.lock, connection: readerConnection },
1139 ),
1140 );
1141 });
1142​
1143 const acquired = (
1144 target: { readonly name: Acquired["connection"] },
1145 clock: Clock.Clock,
1146 start: bigint,
1147 ): Acquired => ({
1148 connection: target.name,
1149 lockWaitMs: Number((clock.monotonicTimeNanosUnsafe() - start) / 1000n) / 1000,
1150 });
1151​
1152 const writerBorrowBatchSize = 16;
1153 let writerBorrowsSinceYield = 0;
1154 const borrower: Borrower = (use) =>
1155 Effect.uninterruptibleMask((restore) => {
1156 let release: Effect.Effect<void> = Effect.void;
1157 const claimed = (next: Effect.Effect<void>) =>
1158 Effect.sync(() => {
1159 release = next;
1160 });
1161 return Effect.flatMap(route(claimed), (target) => restore(borrowTarget(target, use))).pipe(
1162 Effect.ensuring(Effect.suspend(() => release)),
1163 );
1164 });
1165 const borrowTarget = <A, E, R>(
1166 target: {
1167 readonly name: Acquired["connection"];
1168 readonly lock: Semaphore.Semaphore;
1169 readonly connection: Connection;
1170 },
1171 use: (connection: Connection) => Effect.Effect<A, E, R>,
1172 ): Effect.Effect<A, E, R> =>
1173 Effect.withFiber((fiber) => {
1174 const clock = fiber.getRef(Clock.Clock);
1175 const start = clock.monotonicTimeNanosUnsafe();
1176 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1177 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1178 const useConnection = Effect.suspend(() => {
1179 if (target.name === "writer") activeWriter = owner;
1180 if (
1181 fiber.getRef(References.TracerEnabled) &&
1182 fiber.getRef(Statement.SpanPropagationEnabled)
1183 ) {
1184 annotateAcquired(fiber, acquired(target, clock, start), ownerAtWaitStart);
1186 return use(target.connection);
1187 });
1188 const useOwnedConnection =
1189 target.name === "writer"
1190 ? Effect.onExit(useConnection, () =>
1191 Effect.sync(() => {
1192 if (activeWriter === owner) activeWriter = undefined;
1193 }),
1195 : useConnection;
1196 if (!options.checkpointWorker || target.name !== "writer") {
1197 return target.lock.withPermits(1)(useOwnedConnection);
1199 const writerUse = Effect.onExit(useOwnedConnection, (exit) =>
1200 Effect.sync(() => {
1201 writerBorrowsSinceYield = Exit.hasInterrupts(exit)
1202 ? 0
1203 : Math.min(writerBorrowsSinceYield + 1, writerBorrowBatchSize);
1204 }),
1205 );
1206 return Effect.flatMap(target.lock.withPermitsIfAvailable(1)(writerUse), (result) =>
1207 Option.isSome(result)
1208 ? Effect.succeed(result.value)
1209 : target.lock.withPermits(1)(
1210 Effect.andThen(
1211 // Failed SQL also consumes the batch; cancellation hands off immediately.
1212 Effect.suspend(() => {
1213 if (writerBorrowsSinceYield < writerBorrowBatchSize) return Effect.void;
1214 writerBorrowsSinceYield = 0;
1215 return Effect.callback<void>((resume) => {
1216 const immediate = setImmediate(() => resume(Effect.void));
1217 return Effect.sync(() => clearImmediate(immediate));
1218 });
1219 }),
1220 writerUse,
1221 ),
1222 ),
1223 );
1224 });
1225 const claimedUntilScopeCloses = (release: Effect.Effect<void>) =>
1226 Effect.withFiber((fiber) =>
1227 Scope.addFinalizer(Context.getUnsafe(fiber.context, Scope.Scope), release),
1228 );
1229 const transactionAcquirer = Effect.uninterruptible(route(claimedUntilScopeCloses)).pipe(
1230 Effect.flatMap((target) =>
1231 Effect.uninterruptibleMask((restore) => {
1232 const fiber = Fiber.getCurrent()!;
1233 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
1234 const clock = fiber.getRef(Clock.Clock);
1235 const start = clock.monotonicTimeNanosUnsafe();
1236 const pending = fiber.getRef(TransactionAcquire);
1237 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1238 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1239 const acquire = Effect.tap((pending?.restore ?? restore)(target.lock.take(1)), () => {
1240 if (target.name === "writer") activeWriter = owner;
1241 if (pending !== undefined) {
1242 pending.acquired = acquired(target, clock, start);
1243 pending.ownerAtWaitStart = ownerAtWaitStart;
1245 return Scope.addFinalizer(
1246 scope,
1247 Effect.sync(() => {
1248 if (target.name === "writer" && activeWriter === owner) activeWriter = undefined;
1249 }).pipe(Effect.andThen(target.lock.release(1))),
1250 );
1251 });
1252 return Effect.as(
1253 // A scheduler yield after taking the permit must not precede its release finalizer.
1254 Effect.provideService(acquire, Scheduler.PreventSchedulerYield, true),
1255 target.connection,
1256 );
1257 }),
1258 ),
1259 );
1260​
1261 const client = yield* Client.make({
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));