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

nodeSqliteClient.ts

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