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

nodeSqliteClient.ts

821 lines30.2 KB

1/**
2 * Port of `@effect/sql-sqlite-node` that uses the native `node:sqlite`
3 * bindings instead of `better-sqlite3`.
4 *
5 * @module SqliteClient
6 */
7import * as NodeSqlite from "node:sqlite";
8import * as NodeUtil from "node:util";
9import * as NodeWorkerThreads from "node:worker_threads";
10​
11import * as Cache from "effect/Cache";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Exit from "effect/Exit";
15import * as Fiber from "effect/Fiber";
16import { identity } from "effect/Function";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Predicate from "effect/Predicate";
20import * as Schema from "effect/Schema";
21import * as Scope from "effect/Scope";
22import * as Semaphore from "effect/Semaphore";
23import * as Context from "effect/Context";
24import * as Stream from "effect/Stream";
25import * as Reactivity from "effect/reactivity/Reactivity";
26import * as Client from "effect/sql/SqlClient";
27import type { Connection } from "effect/sql/SqlConnection";
28import { SqlError, classifySqliteError } from "effect/sql/SqlError";
29import * as Statement from "effect/sql/Statement";
30​
31const ATTR_DB_SYSTEM_NAME = "db.system.name";
32​
33export interface SqliteClientConfig {
34 readonly filename: string;
35 readonly readonly?: boolean | undefined;
36 readonly allowExtension?: boolean | undefined;
37 readonly prepareCacheSize?: number | undefined;
38 readonly prepareCacheTTL?: Duration.Input | undefined;
39 readonly spanAttributes?: Record<string, unknown> | undefined;
40 readonly transformResultNames?: ((str: string) => string) | undefined;
41 readonly transformQueryNames?: ((str: string) => string) | undefined;
42 /**
43 * Run transactions marked with `readOnly` on a second connection in a worker
44 * thread, so long reads block neither the event loop nor writes. Ignored for
45 * in-memory databases, which a second connection cannot share.
46 */
47 readonly readerWorker?: boolean | undefined;
48 /** How long a reader worker may take to open the database before reads use the writer. Default 10 seconds. */
49 readonly readerStartupTimeout?: Duration.Input | undefined;
50 /**
51 * Run WAL checkpoints on a read-write connection in a worker thread, so
52 * copying pages into the database and syncing it never block the event loop.
53 * Ignored for in-memory databases.
54 */
55 readonly checkpointWorker?: boolean | undefined;
57​
58/**
59 * Set by `readOnly`. A top-level transaction started while it is true runs on
60 * the reader worker when the client has one, and on the writer otherwise.
61 */
62const ReadOnly = Context.Reference<boolean>("@t3tools/shared/nodeSqliteClient/ReadOnly", {
63 defaultValue: () => false,
64});
65​
66/**
67 * Marks the SQL in `effect` as read-only. Wrap the whole transaction, as in
68 * `sql.withTransaction(reads).pipe(readOnly)`. Inside an open write
69 * transaction the reads keep using the writer, and a write attempted on the
70 * reader fails with "attempt to write a readonly database".
71 */
72export const readOnly = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
73 Effect.provideService(effect, ReadOnly, true);
74​
75export class UnsupportedNodeSqliteVersionError extends Schema.TaggedError<UnsupportedNodeSqliteVersionError>()(
76 "UnsupportedNodeSqliteVersionError",
77 {
78 nodeVersion: Schema.String,
79 requirement: Schema.String,
80 },
81) {
82 override get message(): string {
83 return `Node.js ${this.nodeVersion} is missing required node:sqlite APIs. Upgrade to ${this.requirement}.`;
84 }
86​
87export class UnsupportedNodeSqliteOperationError extends Schema.TaggedError<UnsupportedNodeSqliteOperationError>()(
88 "UnsupportedNodeSqliteOperationError",
89 {},
90) {
91 override get message(): string {
92 return "Node SQLite does not support executeStream.";
93 }
95​
96/**
97 * Verify that the current Node.js version includes the `node:sqlite` APIs
98 * used by `NodeSqliteClient` — specifically `StatementSync.columns()` (added
99 * in Node 22.16.0 / 23.11.0).
100 *
101 * @see https://github.com/nodejs/node/pull/57490
102 */
103const checkNodeSqliteCompat = () => {
104 const parts = process.versions.node.split(".").map(Number);
105 const major = parts[0] ?? 0;
106 const minor = parts[1] ?? 0;
107 const supported = (major === 22 && minor >= 16) || (major === 23 && minor >= 11) || major >= 24;
108​
109 if (!supported) {
110 return Effect.die(
111 new UnsupportedNodeSqliteVersionError({
112 nodeVersion: process.versions.node,
113 requirement: "Node.js >=22.16, >=23.11, or >=24",
114 }),
115 );
116 }
117 return Effect.void;
118};
119​
120/**
121 * `node:sqlite` reports the SQLite result code as `errcode`, while
122 * `classifySqliteError` reads `errno`. Copy it across so busy, locked and
123 * constraint failures get their own reasons instead of `UnknownError`.
124 */
125const classifyError = (cause: unknown, message: string, operation: string) => {
126 if (
127 Predicate.hasProperty(cause, "errcode") &&
128 typeof cause.errcode === "number" &&
129 !Predicate.hasProperty(cause, "errno")
130 ) {
131 Object.assign(cause, { errno: cause.errcode });
132 }
133 return classifySqliteError(cause, { message, operation });
134};
135​
136/**
137 * SQLite keeps its copy of a statement's text and blob parameters until the
138 * statement is bound again or finalized, and `node:sqlite` cannot clear them.
139 * A cached statement would hold its last payload for as long as it stays
140 * cached, so executions binding more than this many string code units and
141 * blob bytes, or a named parameter behind a getter, get a throwaway statement
142 * instead.
143 */
144const LARGE_BINDING_SIZE = 64 * 1024;
145​
146// `node:sqlite` binds both buffer views and raw buffers as blobs.
147const isBlob = (value: unknown): value is ArrayBufferView | ArrayBufferLike =>
148 ArrayBuffer.isView(value) || NodeUtil.types.isAnyArrayBuffer(value);
149​
150const bindingSize = (value: unknown): number => {
151 if (typeof value === "string") {
152 return value.length;
153 }
154 return isBlob(value) ? value.byteLength : 0;
155};
156​
157const hasLargeBinding = (params: ReadonlyArray<unknown>): boolean => {
158 try {
159 let size = 0;
160 for (const param of params) {
161 if (
162 (typeof param === "object" || typeof param === "function") &&
163 param !== null &&
164 !isBlob(param)
165 ) {
166 // `node:sqlite` takes named parameters as one object, callable or not.
167 // Read data properties only: calling a getter here would run it twice.
168 for (const property of Object.values(Object.getOwnPropertyDescriptors(param))) {
169 if (!property.enumerable) continue;
170 if (!("value" in property)) return true;
171 size += bindingSize(property.value);
172 }
173 } else {
174 size += bindingSize(param);
175 }
176 }
177 return size > LARGE_BINDING_SIZE;
178 } catch {
179 // A parameter that cannot be measured is left for the statement to report.
180 return true;
181 }
182};
183​
184// Evaluated source instead of a worker file, so the reader also starts from
185// bundles and single-executable builds that have no module file on disk.
186const readerWorkerSource = `
187const { parentPort, workerData } = require("node:worker_threads");
188const { DatabaseSync } = require("node:sqlite");
189let db;
190try {
191 // A read-only open cannot be undone by SQL, unlike PRAGMA query_only.
192 const next = new DatabaseSync(workerData.filename, {
193 readOnly: true,
194 allowExtension: workerData.allowExtension,
195 });
196 next.exec("PRAGMA busy_timeout = 5000;");
197 // Without WAL a reader's shared lock blocks the writer's commits, so refuse.
198 const mode = String(next.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
199 if (mode !== "wal") throw new Error("database uses journal_mode " + mode + ", not wal");
200 db = next;
201 parentPort.postMessage({ type: "ready" });
202} catch (error) {
203 parentPort.postMessage({ type: "unavailable", message: String(error && error.message ? error.message : error) });
205const statements = new Map();
206const prepare = (sql, cached) => {
207 if (!cached) return db.prepare(sql);
208 let statement = statements.get(sql);
209 if (statement === undefined) {
210 statement = db.prepare(sql);
211 if (statements.size >= workerData.prepareCacheSize) statements.delete(statements.keys().next().value);
212 } else {
213 statements.delete(sql);
214 }
215 statements.set(sql, statement);
216 return statement;
217};
218parentPort.on("message", ({ id, sql, params, cached, values, raw, safeIntegers }) => {
219 let operation = "open";
220 try {
221 if (db === undefined) throw new Error("database reader is unavailable");
222 operation = "prepare";
223 const statement = prepare(sql, cached);
224 operation = "execute";
225 statement.setReadBigInts(safeIntegers);
226 if (statement.columns().length > 0) {
227 statement.setReturnArrays(values);
228 parentPort.postMessage({ id, rows: statement.all(...params) });
229 } else {
230 const result = statement.run(...params);
231 parentPort.postMessage({ id, rows: raw ? result : [] });
232 }
233 } catch (error) {
234 parentPort.postMessage({
235 id,
236 error: {
237 operation,
238 message: String(error && error.message ? error.message : error),
239 code: error && error.code,
240 errcode: error && error.errcode,
241 errstr: error && error.errstr,
242 },
243 });
244 }
245});
246`;
247​
248interface ReaderRequest {
249 readonly sql: string;
250 readonly params: ReadonlyArray<unknown>;
251 readonly cached: boolean;
252 readonly values: boolean;
253 readonly raw: boolean;
255​
256type ReaderStartup =
257 | { readonly type: "ready" }
258 | { readonly type: "unavailable"; readonly message: string };
259​
260type ReaderReply =
261 | { readonly id: number; readonly rows: ReadonlyArray<any> }
262 | {
263 readonly id: number;
264 readonly error: {
265 readonly operation: "open" | "prepare" | "execute";
266 readonly message: string;
267 readonly code?: unknown;
268 readonly errcode?: unknown;
269 readonly errstr?: unknown;
270 };
271 };
272​
273const readerFailureMessages = {
274 open: "Failed to open database",
275 prepare: "Failed to prepare statement",
276 execute: "Failed to execute statement",
277} as const;
278​
279const failed = (cause: unknown, message: string, operation: string) =>
280 new SqlError({ reason: classifyError(cause, message, operation) });
281​
282// COMMIT, ROLLBACK and ROLLBACK TO SAVEPOINT. On a reader they change nothing,
283// so they succeed once the worker is gone instead of failing the cleanup.
284const endsReadTransaction = (sql: string) => /^\s*ROLLBACK\b|^\s*COMMIT\b/i.test(sql);
285​
286/**
287 * Read-only connections served by one worker thread at a time. Each worker
288 * gets its own `Connection`, so a transaction stays on the worker it began on:
289 * once that worker exits, its statements fail rather than silently continuing
290 * outside the transaction on a replacement. The next acquire starts a new one.
291 * A worker that cannot open the database read-only, or finds it outside WAL
292 * mode, turns the reader off for the life of the client: reads use the writer.
293 */
294const makeReader = Effect.fnUntraced(function* (options: SqliteClientConfig) {
295 let current:
296 | {
297 readonly worker: NodeWorkerThreads.Worker;
298 readonly connection: Connection;
299 readonly started: Promise<ReaderStartup>;
300 }
301 | undefined;
302 let unavailable = false;
303 let nextRequestId = 0;
304​
305 const start = () => {
306 const worker = new NodeWorkerThreads.Worker(readerWorkerSource, {
307 eval: true,
308 workerData: {
309 filename: options.filename,
310 allowExtension: options.allowExtension ?? false,
311 prepareCacheSize: options.prepareCacheSize ?? 200,
312 },
313 });
314 let announce: (startup: ReaderStartup) => void = () => {};
315 const started = new Promise<ReaderStartup>((resolve) => {
316 announce = resolve;
317 });
318 let stoppedMessage: string | undefined;
319 const pending = new Map<
320 number,
321 { readonly endsTransaction: boolean; readonly resume: (reply: ReaderReply) => void }
322 >();
323 const stop = (message: string) => {
324 stoppedMessage = message;
325 announce({ type: "unavailable", message });
326 if (current?.worker === worker) current = undefined;
327 for (const [id, request] of pending) {
328 request.resume(
329 request.endsTransaction
330 ? { id, rows: [] }
331 : { id, error: { operation: "execute", message } },
332 );
333 }
334 pending.clear();
335 };
336 worker.on("message", (reply: ReaderReply | ReaderStartup) => {
337 if ("type" in reply) {
338 announce(reply);
339 // An idle reader must not keep the process alive.
340 if (pending.size === 0) worker.unref();
341 return;
342 }
343 const request = pending.get(reply.id);
344 if (request === undefined) return;
345 pending.delete(reply.id);
346 if (pending.size === 0) worker.unref();
347 request.resume(reply);
348 });
349 worker.on("error", (cause) => stop(`Database reader failed: ${cause.message}`));
350 worker.on("exit", (code) => stop(`Database reader exited with code ${code}`));
351​
352 const request = (input: ReaderRequest) =>
353 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
354 const endsTransaction = endsReadTransaction(input.sql);
355 if (stoppedMessage !== undefined) {
356 return endsTransaction
357 ? Effect.succeed([])
358 : Effect.fail(
359 failed(new Error(stoppedMessage), readerFailureMessages.execute, "execute"),
360 );
361 }
362 const safeIntegers = Boolean(Context.get(fiber.context, Client.SafeIntegers));
363 return Effect.callback<ReadonlyArray<any>, SqlError>((resume) => {
364 const id = nextRequestId++;
365 pending.set(id, {
366 endsTransaction,
367 resume: (reply) => {
368 if ("rows" in reply) {
369 resume(Effect.succeed(reply.rows));
370 return;
371 }
372 const { operation, message, ...codes } = reply.error;
373 resume(
374 Effect.fail(
375 failed(
376 Object.assign(new Error(message), codes),
377 readerFailureMessages[operation],
378 operation,
379 ),
380 ),
381 );
382 },
383 });
384 if (pending.size === 1) worker.ref();
385 // The worker's statement cache would pin large parameters the same way.
386 const cached = input.cached && !hasLargeBinding(input.params);
387 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
388 worker.postMessage({ id, safeIntegers, ...input, cached });
389 });
390 });
391​
392 const connection = identity<Connection>({
393 execute(sql, params, rowTransform) {
394 const effect = request({ sql, params, cached: true, values: false, raw: false });
395 return rowTransform ? Effect.map(effect, rowTransform) : effect;
396 },
397 executeRaw(sql, params) {
398 return request({ sql, params, cached: true, values: false, raw: true });
399 },
400 executeValues(sql, params) {
401 return request({ sql, params, cached: true, values: true, raw: false });
402 },
403 executeValuesUnprepared(sql, params) {
404 return request({ sql, params: params ?? [], cached: false, values: true, raw: false });
405 },
406 executeUnprepared(sql, params, rowTransform) {
407 // A read-only connection rejects BEGIN IMMEDIATE and BEGIN EXCLUSIVE,
408 // and a deferred BEGIN is all a read snapshot needs.
409 const statement = /^\s*BEGIN\b/i.test(sql) ? "BEGIN" : sql;
410 const effect = request({
411 sql: statement,
412 params: params ?? [],
413 cached: false,
414 values: false,
415 raw: false,
416 });
417 return rowTransform ? Effect.map(effect, rowTransform) : effect;
418 },
419 executeStream(_sql, _params) {
420 return Stream.die(new UnsupportedNodeSqliteOperationError());
421 },
422 });
423 current = { worker, connection, started };
424 return current;
425 };
426​
427 yield* Effect.addFinalizer(() =>
428 Effect.promise(async () => {
429 await current?.worker.terminate();
430 }),
431 );
432​
433 const startupTimeout = Duration.fromInputUnsafe(
434 options.readerStartupTimeout ?? Duration.seconds(10),
435 );
436​
437 // Runs once: concurrent first acquires share one startup and may all see it fail.
438 const turnOff = (reader: typeof current, reason: string) =>
439 Effect.suspend(() => {
440 if (reader !== undefined) {
441 if (current === reader) current = undefined;
442 void reader.worker.terminate();
443 }
444 if (unavailable) return Effect.succeed(undefined);
445 unavailable = true;
446 return Effect.logWarning("SQLite reader worker unavailable; reads use the main connection", {
447 reason,
448 }).pipe(Effect.as(undefined));
449 });
450​
451 /** The live worker's connection once it is ready, or undefined to use the writer. */
452 return Effect.suspend((): Effect.Effect<Connection | undefined> => {
453 if (unavailable) return Effect.succeed(undefined);
454 let reader: NonNullable<typeof current>;
455 try {
456 reader = current ?? start();
457 } catch (cause) {
458 return turnOff(undefined, String(cause));
459 }
460 // SqlClient acquires transaction connections uninterruptibly. Waiting for the
461 // worker happens before any lock is taken, so let a cancelled request leave.
462 return Effect.flatMap(
463 Effect.interruptible(
464 Effect.timeoutOption(
465 Effect.promise(() => reader.started),
466 startupTimeout,
467 ),
468 ),
469 (startup): Effect.Effect<Connection | undefined> =>
470 // Another acquire may have timed out and retired this worker while this one
471 // waited; a late "ready" must not hand out a worker that is being terminated.
472 unavailable || current !== reader
473 ? Effect.succeed(undefined)
474 : Option.isSome(startup) && startup.value.type === "ready"
475 ? Effect.succeed(reader.connection)
476 : turnOff(
477 reader,
478 Option.isSome(startup) && startup.value.type === "unavailable"
479 ? startup.value.message
480 : `worker did not open the database within ${Duration.toMillis(startupTimeout)} ms`,
481 ),
482 );
483 });
484});
485​
486// SQLite's default wal_autocheckpoint, in WAL frames (pages).
487const CHECKPOINT_FRAMES = 1000;
488// While the worker runs, the writer still checkpoints a WAL this long. Writes
489// with no pause leave the worker behind, and the WAL can only restart once
490// every frame is checkpointed, so this keeps the file from growing forever.
491const WRITER_BACKSTOP_FRAMES = 10 * CHECKPOINT_FRAMES;
492// How long writes must pause before the worker checkpoints the rest of a long WAL.
493const CHECKPOINT_IDLE_MS = 100;
494​
495// Each message asks the worker to checkpoint if CHECKPOINT_FRAMES frames are
496// waiting, and it replies with the same message when done. Once writes pause, it also checkpoints the
497// frames that arrived during its last checkpoint, so the writer can restart the
498// WAL. NOOP only counts frames. SQLite before 3.51 reads NOOP as PASSIVE and
499// would checkpoint on every request, so the worker refuses to start there and
500// the writer keeps checkpointing.
501const checkpointWorkerSource = `
502const { parentPort, workerData } = require("node:worker_threads");
503const { DatabaseSync } = require("node:sqlite");
504const db = new DatabaseSync(workerData.filename);
505const version = db.prepare("SELECT sqlite_version() AS version").get().version;
506const [major, minor] = version.split(".").map(Number);
507if (major < 3 || (major === 3 && minor < 51)) throw new Error("SQLite " + version + " has no NOOP checkpoint");
508// macOS fsync() does not flush the drive cache; F_FULLFSYNC does. Other platforms ignore this.
509db.exec("PRAGMA checkpoint_fullfsync = ON;");
510const frames = db.prepare("PRAGMA wal_checkpoint(NOOP)");
511const checkpoint = db.prepare("PRAGMA wal_checkpoint(PASSIVE)");
512const finish = () => {
513 const { log, checkpointed } = frames.get();
514 if (log >= workerData.frames && checkpointed < log) checkpoint.get();
515};
516let idle;
517parentPort.on("message", (request) => {
518 const { log, checkpointed } = frames.get();
519 if (log - checkpointed >= workerData.frames) checkpoint.get();
520 clearTimeout(idle);
521 idle = setTimeout(finish, workerData.idleMs);
522 parentPort.postMessage(request);
523});
524`;
525​
526/**
527 * Moves the writer's WAL checkpoints to a worker. Call the returned function
528 * after each statement on the writer. While the worker runs, the writer only
529 * checkpoints at WRITER_BACKSTOP_FRAMES. If the worker fails or exits, the
530 * writer goes back to SQLite's default.
531 */
532const startCheckpointWorker = Effect.fnUntraced(function* (
533 filename: string,
534 writer: NodeSqlite.DatabaseSync,
535) {
536 let worker: NodeWorkerThreads.Worker;
537 try {
538 worker = new NodeWorkerThreads.Worker(checkpointWorkerSource, {
539 eval: true,
540 workerData: { filename, frames: CHECKPOINT_FRAMES, idleMs: CHECKPOINT_IDLE_MS },
541 });
542 } catch {
543 // No worker threads here: the writer keeps checkpointing.
544 return undefined;
545 }
546 writer.exec(`PRAGMA wal_autocheckpoint = ${WRITER_BACKSTOP_FRAMES};`);
547 let stopped = false;
548 let checking = false;
549 let checkAgain = false;
550 const handBack = () => {
551 if (stopped) return;
552 stopped = true;
553 try {
554 writer.exec(`PRAGMA wal_autocheckpoint = ${CHECKPOINT_FRAMES};`);
555 } catch {
556 // The writer is already closed.
557 }
558 };
559 worker.on("error", handBack);
560 worker.on("exit", handBack);
561 yield* Effect.addFinalizer(() => Effect.promise(() => worker.terminate()));
562​
563 // At most one request is in flight. A statement that runs during it asks for
564 // one more check, so the frames of a last commit before idle still get one.
565 const check = () => {
566 if (stopped) return;
567 if (checking) {
568 checkAgain = true;
569 return;
570 }
571 checking = true;
572 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
573 worker.postMessage(null);
574 };
575 worker.on("message", () => {
576 checking = false;
577 if (checkAgain) {
578 checkAgain = false;
579 check();
580 }
581 });
582 // After the listeners: adding a "message" listener refs the worker again.
583 // A checkpoint in progress must not keep the process alive.
584 worker.unref();
585 return check;
586});
587​
588const make = Effect.fn("makeWithDatabase")(function* (
589 options: SqliteClientConfig,
590): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
591 yield* checkNodeSqliteCompat();
592​
593 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
594 const isFileDatabase = options.filename !== ":memory:" && options.filename !== "";
595 const transformRows = options.transformResultNames
596 ? Statement.defaultTransforms(options.transformResultNames).array
597 : undefined;
598​
599 const makeConnection = Effect.gen(function* () {
600 const scope = yield* Effect.scope;
601 const db = yield* Effect.try({
602 try: () =>
603 new NodeSqlite.DatabaseSync(options.filename, {
604 readOnly: options.readonly ?? false,
605 allowExtension: options.allowExtension ?? false,
606 }),
607 catch: (cause) =>
608 new SqlError({
609 reason: classifyError(cause, "Failed to open database", "open"),
610 }),
611 });
612 yield* Scope.addFinalizer(
613 scope,
614 Effect.try({
615 try: () => db.close(),
616 catch: (cause) =>
617 new SqlError({
618 reason: classifyError(cause, "Failed to close database", "close"),
619 }),
620 }).pipe(Effect.orDie),
621 );
622 // Started after the close finalizer, so the worker stops before the writer closes.
623 const checkpoint =
624 options.checkpointWorker && isFileDatabase
625 ? yield* startCheckpointWorker(options.filename, db)
626 : undefined;
627​
628 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
629 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
630 const cached = statementReaderCache.get(statement);
631 if (cached !== undefined) {
632 return cached;
633 }
634 const value = statement.columns().length > 0;
635 statementReaderCache.set(statement, value);
636 return value;
637 };
638​
639 const prepare = (sql: string) =>
640 Effect.try({
641 try: () => db.prepare(sql),
642 catch: (cause) =>
643 new SqlError({
644 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
645 }),
646 });
647​
648 const prepareCache = yield* Cache.makeWith(prepare, {
649 capacity: options.prepareCacheSize ?? 200,
650 // A transient prepare failure must not outlive the lock or missing schema.
651 timeToLive: (exit) =>
652 Exit.isSuccess(exit) ? (options.prepareCacheTTL ?? Duration.minutes(10)) : Duration.zero,
653 });
654​
655 const statementFor = (sql: string, params: ReadonlyArray<unknown>) =>
656 hasLargeBinding(params) ? prepare(sql) : Cache.get(prepareCache, sql);
657​
658 const runStatement = (
659 statement: NodeSqlite.StatementSync,
660 params: ReadonlyArray<unknown>,
661 raw: boolean,
662 ) =>
663 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
664 try {
665 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
666 if (hasRows(statement)) {
667 const rows = statement.all(...(params as any));
668 checkpoint?.();
669 return Effect.succeed(rows);
670 }
671 const result = statement.run(...(params as any));
672 checkpoint?.();
673 return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
674 } catch (cause) {
675 return Effect.fail(
676 new SqlError({
677 reason: classifyError(cause, "Failed to execute statement", "execute"),
678 }),
679 );
680 }
681 });
682​
683 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
684 Effect.flatMap(statementFor(sql, params), (s) => runStatement(s, params, raw));
685​
686 const runStatementValues = (
687 statement: NodeSqlite.StatementSync,
688 params: ReadonlyArray<unknown>,
689 ) =>
690 Effect.acquireUseRelease(
691 Effect.succeed(statement),
692 (statement) =>
693 Effect.try({
694 try: () => {
695 statement.setReadBigInts(
696 Boolean(Context.get(Fiber.getCurrent()!.context, Client.SafeIntegers)),
697 );
698 if (hasRows(statement)) {
699 statement.setReturnArrays(true);
700 // Safe to cast to array after we've setReturnArrays(true)
701 const rows = statement.all(...(params as any)) as unknown as ReadonlyArray<
702 ReadonlyArray<unknown>
703 >;
704 checkpoint?.();
705 return rows;
706 }
707 statement.run(...(params as any));
708 checkpoint?.();
709 return [];
710 },
711 catch: (cause) =>
712 new SqlError({
713 reason: classifyError(cause, "Failed to execute statement", "execute"),
714 }),
715 }),
716 (statement) =>
717 Effect.try({
718 try: () => {
719 if (hasRows(statement)) {
720 statement.setReturnArrays(false);
721 }
722 },
723 catch: (cause) =>
724 new SqlError({
725 reason: classifyError(
726 cause,
727 "Failed to reset statement result mode",
728 "resetResultMode",
729 ),
730 }),
731 }).pipe(Effect.orDie),
732 );
733​
734 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
735 Effect.flatMap(statementFor(sql, params), (statement) =>
736 runStatementValues(statement, params),
737 );
738​
739 return identity<Connection>({
740 execute(sql, params, rowTransform) {
741 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
742 },
743 executeRaw(sql, params) {
744 return run(sql, params, true);
745 },
746 executeValues(sql, params) {
747 return runValues(sql, params);
748 },
749 executeValuesUnprepared(sql, params) {
750 return Effect.flatMap(prepare(sql), (statement) =>
751 runStatementValues(statement, params ?? []),
752 );
753 },
754 executeUnprepared(sql, params, rowTransform) {
755 const effect = prepare(sql).pipe(
756 Effect.flatMap((statement) => runStatement(statement, params ?? [], false)),
757 );
758 return rowTransform ? Effect.map(effect, rowTransform) : effect;
759 },
760 executeStream(_sql, _params) {
761 return Stream.die(new UnsupportedNodeSqliteOperationError());
762 },
763 });
764 });
765​
766 const semaphore = yield* Semaphore.make(1);
767 const connection = yield* makeConnection;
768 const acquireReader =
769 options.readerWorker && isFileDatabase ? yield* makeReader(options) : undefined;
770 const readerSemaphore = yield* Semaphore.make(1);
771​
772 const writer = { lock: semaphore, connection };
773 // Picks the reader only for `readOnly` work, and the writer whenever the
774 // reader is turned off.
775 const route = Effect.withFiber((fiber) =>
776 acquireReader !== undefined && Context.get(fiber.context, ReadOnly)
777 ? Effect.map(acquireReader, (readerConnection) =>
778 readerConnection === undefined
779 ? writer
780 : { lock: readerSemaphore, connection: readerConnection },
781 )
782 : Effect.succeed(writer),
783 );
784​
785 const acquirer = Effect.flatMap(route, (target) =>
786 target.lock.withPermits(1)(Effect.succeed(target.connection)),
787 );
788 const transactionAcquirer = Effect.flatMap(route, (target) =>
789 Effect.uninterruptibleMask((restore) => {
790 const fiber = Fiber.getCurrent()!;
791 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
792 return Effect.as(
793 Effect.tap(restore(target.lock.take(1)), () =>
794 Scope.addFinalizer(scope, target.lock.release(1)),
795 ),
796 target.connection,
797 );
798 }),
799 );
800​
801 return yield* Client.make({
802 acquirer,
803 compiler,
804 transactionAcquirer,
805 // A deferred BEGIN only takes the write lock at the first write. If another
806 // process commits after this transaction's first read, that write fails at
807 // once with SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot wait out. Taking
808 // the lock up front makes it wait instead, at the cost of serializing
809 // read-only transactions behind other processes' writers. Read-only
810 // connections cannot write, so they keep the deferred BEGIN.
811 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
812 spanAttributes: [
813 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
814 [ATTR_DB_SYSTEM_NAME, "sqlite"],
815 ],
816 transformRows,
817 });
818});
819​
820export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
821 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));