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

nodeSqliteClient.ts

646 lines23.3 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 NodeWorkerThreads from "node:worker_threads";
9​
10import * as Cache from "effect/Cache";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Fiber from "effect/Fiber";
15import { identity } from "effect/Function";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Predicate from "effect/Predicate";
19import * as Schema from "effect/Schema";
20import * as Scope from "effect/Scope";
21import * as Semaphore from "effect/Semaphore";
22import * as Context from "effect/Context";
23import * as Stream from "effect/Stream";
24import * as Reactivity from "effect/reactivity/Reactivity";
25import * as Client from "effect/sql/SqlClient";
26import type { 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 allowExtension?: boolean | undefined;
36 readonly prepareCacheSize?: number | undefined;
37 readonly prepareCacheTTL?: Duration.Input | undefined;
38 readonly spanAttributes?: Record<string, unknown> | undefined;
39 readonly transformResultNames?: ((str: string) => string) | undefined;
40 readonly transformQueryNames?: ((str: string) => string) | undefined;
41 /**
42 * Run transactions marked with `readOnly` on a second connection in a worker
43 * thread, so long reads block neither the event loop nor writes. Ignored for
44 * in-memory databases, which a second connection cannot share.
45 */
46 readonly readerWorker?: boolean | undefined;
47 /** How long a reader worker may take to open the database before reads use the writer. Default 10 seconds. */
48 readonly readerStartupTimeout?: Duration.Input | undefined;
50​
51/**
52 * Set by `readOnly`. A top-level transaction started while it is true runs on
53 * the reader worker when the client has one, and on the writer otherwise.
54 */
55const ReadOnly = Context.Reference<boolean>("@t3tools/shared/nodeSqliteClient/ReadOnly", {
56 defaultValue: () => false,
57});
58​
59/**
60 * Marks the SQL in `effect` as read-only. Wrap the whole transaction, as in
61 * `sql.withTransaction(reads).pipe(readOnly)`. Inside an open write
62 * transaction the reads keep using the writer, and a write attempted on the
63 * reader fails with "attempt to write a readonly database".
64 */
65export const readOnly = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
66 Effect.provideService(effect, ReadOnly, true);
67​
68export class UnsupportedNodeSqliteVersionError extends Schema.TaggedError<UnsupportedNodeSqliteVersionError>()(
69 "UnsupportedNodeSqliteVersionError",
70 {
71 nodeVersion: Schema.String,
72 requirement: Schema.String,
73 },
74) {
75 override get message(): string {
76 return `Node.js ${this.nodeVersion} is missing required node:sqlite APIs. Upgrade to ${this.requirement}.`;
77 }
79​
80export class UnsupportedNodeSqliteOperationError extends Schema.TaggedError<UnsupportedNodeSqliteOperationError>()(
81 "UnsupportedNodeSqliteOperationError",
82 {},
83) {
84 override get message(): string {
85 return "Node SQLite does not support executeStream.";
86 }
88​
89/**
90 * Verify that the current Node.js version includes the `node:sqlite` APIs
91 * used by `NodeSqliteClient` — specifically `StatementSync.columns()` (added
92 * in Node 22.16.0 / 23.11.0).
93 *
94 * @see https://github.com/nodejs/node/pull/57490
95 */
96const checkNodeSqliteCompat = () => {
97 const parts = process.versions.node.split(".").map(Number);
98 const major = parts[0] ?? 0;
99 const minor = parts[1] ?? 0;
100 const supported = (major === 22 && minor >= 16) || (major === 23 && minor >= 11) || major >= 24;
101​
102 if (!supported) {
103 return Effect.die(
104 new UnsupportedNodeSqliteVersionError({
105 nodeVersion: process.versions.node,
106 requirement: "Node.js >=22.16, >=23.11, or >=24",
107 }),
108 );
109 }
110 return Effect.void;
111};
112​
113/**
114 * `node:sqlite` reports the SQLite result code as `errcode`, while
115 * `classifySqliteError` reads `errno`. Copy it across so busy, locked and
116 * constraint failures get their own reasons instead of `UnknownError`.
117 */
118const classifyError = (cause: unknown, message: string, operation: string) => {
119 if (
120 Predicate.hasProperty(cause, "errcode") &&
121 typeof cause.errcode === "number" &&
122 !Predicate.hasProperty(cause, "errno")
123 ) {
124 Object.assign(cause, { errno: cause.errcode });
125 }
126 return classifySqliteError(cause, { message, operation });
127};
128​
129// Evaluated source instead of a worker file, so the reader also starts from
130// bundles and single-executable builds that have no module file on disk.
131const readerWorkerSource = `
132const { parentPort, workerData } = require("node:worker_threads");
133const { DatabaseSync } = require("node:sqlite");
134let db;
135try {
136 // A read-only open cannot be undone by SQL, unlike PRAGMA query_only.
137 const next = new DatabaseSync(workerData.filename, {
138 readOnly: true,
139 allowExtension: workerData.allowExtension,
140 });
141 next.exec("PRAGMA busy_timeout = 5000;");
142 // Without WAL a reader's shared lock blocks the writer's commits, so refuse.
143 const mode = String(next.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
144 if (mode !== "wal") throw new Error("database uses journal_mode " + mode + ", not wal");
145 db = next;
146 parentPort.postMessage({ type: "ready" });
147} catch (error) {
148 parentPort.postMessage({ type: "unavailable", message: String(error && error.message ? error.message : error) });
150const statements = new Map();
151const prepare = (sql, cached) => {
152 if (!cached) return db.prepare(sql);
153 let statement = statements.get(sql);
154 if (statement === undefined) {
155 statement = db.prepare(sql);
156 if (statements.size >= workerData.prepareCacheSize) statements.delete(statements.keys().next().value);
157 } else {
158 statements.delete(sql);
159 }
160 statements.set(sql, statement);
161 return statement;
162};
163parentPort.on("message", ({ id, sql, params, cached, values, raw, safeIntegers }) => {
164 let operation = "open";
165 try {
166 if (db === undefined) throw new Error("database reader is unavailable");
167 operation = "prepare";
168 const statement = prepare(sql, cached);
169 operation = "execute";
170 statement.setReadBigInts(safeIntegers);
171 if (statement.columns().length > 0) {
172 statement.setReturnArrays(values);
173 parentPort.postMessage({ id, rows: statement.all(...params) });
174 } else {
175 const result = statement.run(...params);
176 parentPort.postMessage({ id, rows: raw ? result : [] });
177 }
178 } catch (error) {
179 parentPort.postMessage({
180 id,
181 error: {
182 operation,
183 message: String(error && error.message ? error.message : error),
184 code: error && error.code,
185 errcode: error && error.errcode,
186 errstr: error && error.errstr,
187 },
188 });
189 }
190});
191`;
192​
193interface ReaderRequest {
194 readonly sql: string;
195 readonly params: ReadonlyArray<unknown>;
196 readonly cached: boolean;
197 readonly values: boolean;
198 readonly raw: boolean;
200​
201type ReaderStartup =
202 | { readonly type: "ready" }
203 | { readonly type: "unavailable"; readonly message: string };
204​
205type ReaderReply =
206 | { readonly id: number; readonly rows: ReadonlyArray<any> }
207 | {
208 readonly id: number;
209 readonly error: {
210 readonly operation: "open" | "prepare" | "execute";
211 readonly message: string;
212 readonly code?: unknown;
213 readonly errcode?: unknown;
214 readonly errstr?: unknown;
215 };
216 };
217​
218const readerFailureMessages = {
219 open: "Failed to open database",
220 prepare: "Failed to prepare statement",
221 execute: "Failed to execute statement",
222} as const;
223​
224const failed = (cause: unknown, message: string, operation: string) =>
225 new SqlError({ reason: classifyError(cause, message, operation) });
226​
227// COMMIT, ROLLBACK and ROLLBACK TO SAVEPOINT. On a reader they change nothing,
228// so they succeed once the worker is gone instead of failing the cleanup.
229const endsReadTransaction = (sql: string) => /^\s*ROLLBACK\b|^\s*COMMIT\b/i.test(sql);
230​
231/**
232 * Read-only connections served by one worker thread at a time. Each worker
233 * gets its own `Connection`, so a transaction stays on the worker it began on:
234 * once that worker exits, its statements fail rather than silently continuing
235 * outside the transaction on a replacement. The next acquire starts a new one.
236 * A worker that cannot open the database read-only, or finds it outside WAL
237 * mode, turns the reader off for the life of the client: reads use the writer.
238 */
239const makeReader = Effect.fnUntraced(function* (options: SqliteClientConfig) {
240 let current:
241 | {
242 readonly worker: NodeWorkerThreads.Worker;
243 readonly connection: Connection;
244 readonly started: Promise<ReaderStartup>;
245 }
246 | undefined;
247 let unavailable = false;
248 let nextRequestId = 0;
249​
250 const start = () => {
251 const worker = new NodeWorkerThreads.Worker(readerWorkerSource, {
252 eval: true,
253 workerData: {
254 filename: options.filename,
255 allowExtension: options.allowExtension ?? false,
256 prepareCacheSize: options.prepareCacheSize ?? 200,
257 },
258 });
259 let announce: (startup: ReaderStartup) => void = () => {};
260 const started = new Promise<ReaderStartup>((resolve) => {
261 announce = resolve;
262 });
263 let stoppedMessage: string | undefined;
264 const pending = new Map<
265 number,
266 { readonly endsTransaction: boolean; readonly resume: (reply: ReaderReply) => void }
267 >();
268 const stop = (message: string) => {
269 stoppedMessage = message;
270 announce({ type: "unavailable", message });
271 if (current?.worker === worker) current = undefined;
272 for (const [id, request] of pending) {
273 request.resume(
274 request.endsTransaction
275 ? { id, rows: [] }
276 : { id, error: { operation: "execute", message } },
277 );
278 }
279 pending.clear();
280 };
281 worker.on("message", (reply: ReaderReply | ReaderStartup) => {
282 if ("type" in reply) {
283 announce(reply);
284 // An idle reader must not keep the process alive.
285 if (pending.size === 0) worker.unref();
286 return;
287 }
288 const request = pending.get(reply.id);
289 if (request === undefined) return;
290 pending.delete(reply.id);
291 if (pending.size === 0) worker.unref();
292 request.resume(reply);
293 });
294 worker.on("error", (cause) => stop(`Database reader failed: ${cause.message}`));
295 worker.on("exit", (code) => stop(`Database reader exited with code ${code}`));
296​
297 const request = (input: ReaderRequest) =>
298 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
299 const endsTransaction = endsReadTransaction(input.sql);
300 if (stoppedMessage !== undefined) {
301 return endsTransaction
302 ? Effect.succeed([])
303 : Effect.fail(
304 failed(new Error(stoppedMessage), readerFailureMessages.execute, "execute"),
305 );
306 }
307 const safeIntegers = Boolean(Context.get(fiber.context, Client.SafeIntegers));
308 return Effect.callback<ReadonlyArray<any>, SqlError>((resume) => {
309 const id = nextRequestId++;
310 pending.set(id, {
311 endsTransaction,
312 resume: (reply) => {
313 if ("rows" in reply) {
314 resume(Effect.succeed(reply.rows));
315 return;
316 }
317 const { operation, message, ...codes } = reply.error;
318 resume(
319 Effect.fail(
320 failed(
321 Object.assign(new Error(message), codes),
322 readerFailureMessages[operation],
323 operation,
324 ),
325 ),
326 );
327 },
328 });
329 if (pending.size === 1) worker.ref();
330 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
331 worker.postMessage({ id, safeIntegers, ...input });
332 });
333 });
334​
335 const connection = identity<Connection>({
336 execute(sql, params, rowTransform) {
337 const effect = request({ sql, params, cached: true, values: false, raw: false });
338 return rowTransform ? Effect.map(effect, rowTransform) : effect;
339 },
340 executeRaw(sql, params) {
341 return request({ sql, params, cached: true, values: false, raw: true });
342 },
343 executeValues(sql, params) {
344 return request({ sql, params, cached: true, values: true, raw: false });
345 },
346 executeValuesUnprepared(sql, params) {
347 return request({ sql, params: params ?? [], cached: false, values: true, raw: false });
348 },
349 executeUnprepared(sql, params, rowTransform) {
350 // A read-only connection rejects BEGIN IMMEDIATE and BEGIN EXCLUSIVE,
351 // and a deferred BEGIN is all a read snapshot needs.
352 const statement = /^\s*BEGIN\b/i.test(sql) ? "BEGIN" : sql;
353 const effect = request({
354 sql: statement,
355 params: params ?? [],
356 cached: false,
357 values: false,
358 raw: false,
359 });
360 return rowTransform ? Effect.map(effect, rowTransform) : effect;
361 },
362 executeStream(_sql, _params) {
363 return Stream.die(new UnsupportedNodeSqliteOperationError());
364 },
365 });
366 current = { worker, connection, started };
367 return current;
368 };
369​
370 yield* Effect.addFinalizer(() =>
371 Effect.promise(async () => {
372 await current?.worker.terminate();
373 }),
374 );
375​
376 const startupTimeout = Duration.fromInputUnsafe(
377 options.readerStartupTimeout ?? Duration.seconds(10),
378 );
379​
380 // Runs once: concurrent first acquires share one startup and may all see it fail.
381 const turnOff = (reader: typeof current, reason: string) =>
382 Effect.suspend(() => {
383 if (reader !== undefined) {
384 if (current === reader) current = undefined;
385 void reader.worker.terminate();
386 }
387 if (unavailable) return Effect.succeed(undefined);
388 unavailable = true;
389 return Effect.logWarning("SQLite reader worker unavailable; reads use the main connection", {
390 reason,
391 }).pipe(Effect.as(undefined));
392 });
393​
394 /** The live worker's connection once it is ready, or undefined to use the writer. */
395 return Effect.suspend((): Effect.Effect<Connection | undefined> => {
396 if (unavailable) return Effect.succeed(undefined);
397 let reader: NonNullable<typeof current>;
398 try {
399 reader = current ?? start();
400 } catch (cause) {
401 return turnOff(undefined, String(cause));
402 }
403 // SqlClient acquires transaction connections uninterruptibly. Waiting for the
404 // worker happens before any lock is taken, so let a cancelled request leave.
405 return Effect.flatMap(
406 Effect.interruptible(
407 Effect.timeoutOption(
408 Effect.promise(() => reader.started),
409 startupTimeout,
410 ),
411 ),
412 (startup): Effect.Effect<Connection | undefined> =>
413 // Another acquire may have timed out and retired this worker while this one
414 // waited; a late "ready" must not hand out a worker that is being terminated.
415 unavailable || current !== reader
416 ? Effect.succeed(undefined)
417 : Option.isSome(startup) && startup.value.type === "ready"
418 ? Effect.succeed(reader.connection)
419 : turnOff(
420 reader,
421 Option.isSome(startup) && startup.value.type === "unavailable"
422 ? startup.value.message
423 : `worker did not open the database within ${Duration.toMillis(startupTimeout)} ms`,
424 ),
425 );
426 });
427});
428​
429const make = Effect.fn("makeWithDatabase")(function* (
430 options: SqliteClientConfig,
431): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
432 yield* checkNodeSqliteCompat();
433​
434 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
435 const transformRows = options.transformResultNames
436 ? Statement.defaultTransforms(options.transformResultNames).array
437 : undefined;
438​
439 const makeConnection = Effect.gen(function* () {
440 const scope = yield* Effect.scope;
441 const db = yield* Effect.try({
442 try: () =>
443 new NodeSqlite.DatabaseSync(options.filename, {
444 readOnly: options.readonly ?? false,
445 allowExtension: options.allowExtension ?? false,
446 }),
447 catch: (cause) =>
448 new SqlError({
449 reason: classifyError(cause, "Failed to open database", "open"),
450 }),
451 });
452 yield* Scope.addFinalizer(
453 scope,
454 Effect.try({
455 try: () => db.close(),
456 catch: (cause) =>
457 new SqlError({
458 reason: classifyError(cause, "Failed to close database", "close"),
459 }),
460 }).pipe(Effect.orDie),
461 );
462​
463 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
464 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
465 const cached = statementReaderCache.get(statement);
466 if (cached !== undefined) {
467 return cached;
468 }
469 const value = statement.columns().length > 0;
470 statementReaderCache.set(statement, value);
471 return value;
472 };
473​
474 const prepare = (sql: string) =>
475 Effect.try({
476 try: () => db.prepare(sql),
477 catch: (cause) =>
478 new SqlError({
479 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
480 }),
481 });
482​
483 const prepareCache = yield* Cache.makeWith(prepare, {
484 capacity: options.prepareCacheSize ?? 200,
485 // A transient prepare failure must not outlive the lock or missing schema.
486 timeToLive: (exit) =>
487 Exit.isSuccess(exit) ? (options.prepareCacheTTL ?? Duration.minutes(10)) : Duration.zero,
488 });
489​
490 const runStatement = (
491 statement: NodeSqlite.StatementSync,
492 params: ReadonlyArray<unknown>,
493 raw: boolean,
494 ) =>
495 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
496 try {
497 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
498 if (hasRows(statement)) {
499 return Effect.succeed(statement.all(...(params as any)));
500 }
501 const result = statement.run(...(params as any));
502 return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
503 } catch (cause) {
504 return Effect.fail(
505 new SqlError({
506 reason: classifyError(cause, "Failed to execute statement", "execute"),
507 }),
508 );
509 }
510 });
511​
512 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
513 Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
514​
515 const runStatementValues = (
516 statement: NodeSqlite.StatementSync,
517 params: ReadonlyArray<unknown>,
518 ) =>
519 Effect.acquireUseRelease(
520 Effect.succeed(statement),
521 (statement) =>
522 Effect.try({
523 try: () => {
524 if (hasRows(statement)) {
525 statement.setReturnArrays(true);
526 // Safe to cast to array after we've setReturnArrays(true)
527 return statement.all(...(params as any)) as unknown as ReadonlyArray<
528 ReadonlyArray<unknown>
529 >;
530 }
531 statement.run(...(params as any));
532 return [];
533 },
534 catch: (cause) =>
535 new SqlError({
536 reason: classifyError(cause, "Failed to execute statement", "execute"),
537 }),
538 }),
539 (statement) =>
540 Effect.try({
541 try: () => {
542 if (hasRows(statement)) {
543 statement.setReturnArrays(false);
544 }
545 },
546 catch: (cause) =>
547 new SqlError({
548 reason: classifyError(
549 cause,
550 "Failed to reset statement result mode",
551 "resetResultMode",
552 ),
553 }),
554 }).pipe(Effect.orDie),
555 );
556​
557 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
558 Effect.flatMap(Cache.get(prepareCache, sql), (statement) =>
559 runStatementValues(statement, params),
560 );
561​
562 return identity<Connection>({
563 execute(sql, params, rowTransform) {
564 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
565 },
566 executeRaw(sql, params) {
567 return run(sql, params, true);
568 },
569 executeValues(sql, params) {
570 return runValues(sql, params);
571 },
572 executeValuesUnprepared(sql, params) {
573 return Effect.flatMap(prepare(sql), (statement) =>
574 runStatementValues(statement, params ?? []),
575 );
576 },
577 executeUnprepared(sql, params, rowTransform) {
578 const effect = prepare(sql).pipe(
579 Effect.flatMap((statement) => runStatement(statement, params ?? [], false)),
580 );
581 return rowTransform ? Effect.map(effect, rowTransform) : effect;
582 },
583 executeStream(_sql, _params) {
584 return Stream.die(new UnsupportedNodeSqliteOperationError());
585 },
586 });
587 });
588​
589 const semaphore = yield* Semaphore.make(1);
590 const connection = yield* makeConnection;
591 const acquireReader =
592 options.readerWorker && options.filename !== ":memory:" && options.filename !== ""
593 ? yield* makeReader(options)
594 : undefined;
595 const readerSemaphore = yield* Semaphore.make(1);
596​
597 const writer = { lock: semaphore, connection };
598 // Picks the reader only for `readOnly` work, and the writer whenever the
599 // reader is turned off.
600 const route = Effect.withFiber((fiber) =>
601 acquireReader !== undefined && Context.get(fiber.context, ReadOnly)
602 ? Effect.map(acquireReader, (readerConnection) =>
603 readerConnection === undefined
604 ? writer
605 : { lock: readerSemaphore, connection: readerConnection },
606 )
607 : Effect.succeed(writer),
608 );
609​
610 const acquirer = Effect.flatMap(route, (target) =>
611 target.lock.withPermits(1)(Effect.succeed(target.connection)),
612 );
613 const transactionAcquirer = Effect.flatMap(route, (target) =>
614 Effect.uninterruptibleMask((restore) => {
615 const fiber = Fiber.getCurrent()!;
616 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
617 return Effect.as(
618 Effect.tap(restore(target.lock.take(1)), () =>
619 Scope.addFinalizer(scope, target.lock.release(1)),
620 ),
621 target.connection,
622 );
623 }),
624 );
625​
626 return yield* Client.make({
627 acquirer,
628 compiler,
629 transactionAcquirer,
630 // A deferred BEGIN only takes the write lock at the first write. If another
631 // process commits after this transaction's first read, that write fails at
632 // once with SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot wait out. Taking
633 // the lock up front makes it wait instead, at the cost of serializing
634 // read-only transactions behind other processes' writers. Read-only
635 // connections cannot write, so they keep the deferred BEGIN.
636 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
637 spanAttributes: [
638 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
639 [ATTR_DB_SYSTEM_NAME, "sqlite"],
640 ],
641 transformRows,
642 });
643});
644​
645export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
646 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));