Open History to see the last commit
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";
8
9import * as Cache from "effect/Cache";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Fiber from "effect/Fiber";
14import { identity } from "effect/Function";
15import * as Layer from "effect/Layer";
16import * as Predicate from "effect/Predicate";
17import * as Schema from "effect/Schema";
18import * as Scope from "effect/Scope";
19import * as Semaphore from "effect/Semaphore";
20import * as Context from "effect/Context";
21import * as Stream from "effect/Stream";
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
41export class UnsupportedNodeSqliteVersionError extends Schema.TaggedError<UnsupportedNodeSqliteVersionError>()(
42 "UnsupportedNodeSqliteVersionError",
43 {
44 nodeVersion: Schema.String,
45 requirement: Schema.String,
46 },
47) {
48 override get message(): string {
49 return `Node.js ${this.nodeVersion} is missing required node:sqlite APIs. Upgrade to ${this.requirement}.`;
50 }
51}
52
53export class UnsupportedNodeSqliteOperationError extends Schema.TaggedError<UnsupportedNodeSqliteOperationError>()(
54 "UnsupportedNodeSqliteOperationError",
55 {},
56) {
57 override get message(): string {
58 return "Node SQLite does not support executeStream.";
59 }
60}
61
62/**
63 * Verify that the current Node.js version includes the `node:sqlite` APIs
64 * used by `NodeSqliteClient` — specifically `StatementSync.columns()` (added
65 * in Node 22.16.0 / 23.11.0).
66 *
67 * @see https://github.com/nodejs/node/pull/57490
68 */
69const checkNodeSqliteCompat = () => {
70 const parts = process.versions.node.split(".").map(Number);
71 const major = parts[0] ?? 0;
72 const minor = parts[1] ?? 0;
73 const supported = (major === 22 && minor >= 16) || (major === 23 && minor >= 11) || major >= 24;
74
75 if (!supported) {
76 return Effect.die(
77 new UnsupportedNodeSqliteVersionError({
78 nodeVersion: process.versions.node,
79 requirement: "Node.js >=22.16, >=23.11, or >=24",
80 }),
81 );
82 }
83 return Effect.void;
84};
85
86/**
87 * `node:sqlite` reports the SQLite result code as `errcode`, while
88 * `classifySqliteError` reads `errno`. Copy it across so busy, locked and
89 * constraint failures get their own reasons instead of `UnknownError`.
90 */
91const classifyError = (cause: unknown, message: string, operation: string) => {
92 if (
93 Predicate.hasProperty(cause, "errcode") &&
94 typeof cause.errcode === "number" &&
95 !Predicate.hasProperty(cause, "errno")
96 ) {
97 Object.assign(cause, { errno: cause.errcode });
98 }
99 return classifySqliteError(cause, { message, operation });
100};
101
102const make = Effect.fn("makeWithDatabase")(function* (
103 options: SqliteClientConfig,
104): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
105 yield* checkNodeSqliteCompat();
106
107 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
108 const transformRows = options.transformResultNames
109 ? Statement.defaultTransforms(options.transformResultNames).array
110 : undefined;
111
112 const makeConnection = Effect.gen(function* () {
113 const scope = yield* Effect.scope;
114 const db = yield* Effect.try({
115 try: () =>
116 new NodeSqlite.DatabaseSync(options.filename, {
117 readOnly: options.readonly ?? false,
118 allowExtension: options.allowExtension ?? false,
119 }),
120 catch: (cause) =>
121 new SqlError({
122 reason: classifyError(cause, "Failed to open database", "open"),
123 }),
124 });
125 yield* Scope.addFinalizer(
126 scope,
127 Effect.try({
128 try: () => db.close(),
129 catch: (cause) =>
130 new SqlError({
131 reason: classifyError(cause, "Failed to close database", "close"),
132 }),
133 }).pipe(Effect.orDie),
134 );
135
136 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
137 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
138 const cached = statementReaderCache.get(statement);
139 if (cached !== undefined) {
140 return cached;
141 }
142 const value = statement.columns().length > 0;
143 statementReaderCache.set(statement, value);
144 return value;
145 };
146
147 const prepare = (sql: string) =>
148 Effect.try({
149 try: () => db.prepare(sql),
150 catch: (cause) =>
151 new SqlError({
152 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
153 }),
154 });
155
156 const prepareCache = yield* Cache.makeWith(prepare, {
157 capacity: options.prepareCacheSize ?? 200,
158 // A transient prepare failure must not outlive the lock or missing schema.
159 timeToLive: (exit) =>
160 Exit.isSuccess(exit) ? (options.prepareCacheTTL ?? Duration.minutes(10)) : Duration.zero,
161 });
162
163 const runStatement = (
164 statement: NodeSqlite.StatementSync,
165 params: ReadonlyArray<unknown>,
166 raw: boolean,
167 ) =>
168 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
169 try {
170 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
171 if (hasRows(statement)) {
172 return Effect.succeed(statement.all(...(params as any)));
173 }
174 const result = statement.run(...(params as any));
175 return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
176 } catch (cause) {
177 return Effect.fail(
178 new SqlError({
179 reason: classifyError(cause, "Failed to execute statement", "execute"),
180 }),
181 );
182 }
183 });
184
185 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
186 Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
187
188 const runStatementValues = (
189 statement: NodeSqlite.StatementSync,
190 params: ReadonlyArray<unknown>,
191 ) =>
192 Effect.acquireUseRelease(
193 Effect.succeed(statement),
194 (statement) =>
195 Effect.try({
196 try: () => {
197 if (hasRows(statement)) {
198 statement.setReturnArrays(true);
199 // Safe to cast to array after we've setReturnArrays(true)
200 return statement.all(...(params as any)) as unknown as ReadonlyArray<
201 ReadonlyArray<unknown>
202 >;
203 }
204 statement.run(...(params as any));
205 return [];
206 },
207 catch: (cause) =>
208 new SqlError({
209 reason: classifyError(cause, "Failed to execute statement", "execute"),
210 }),
211 }),
212 (statement) =>
213 Effect.try({
214 try: () => {
215 if (hasRows(statement)) {
216 statement.setReturnArrays(false);
217 }
218 },
219 catch: (cause) =>
220 new SqlError({
221 reason: classifyError(
222 cause,
223 "Failed to reset statement result mode",
224 "resetResultMode",
225 ),
226 }),
227 }).pipe(Effect.orDie),
228 );
229
230 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
231 Effect.flatMap(Cache.get(prepareCache, sql), (statement) =>
232 runStatementValues(statement, params),
233 );
234
235 return identity<Connection>({
236 execute(sql, params, rowTransform) {
237 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
238 },
239 executeRaw(sql, params) {
240 return run(sql, params, true);
241 },
242 executeValues(sql, params) {
243 return runValues(sql, params);
244 },
245 executeValuesUnprepared(sql, params) {
246 return Effect.flatMap(prepare(sql), (statement) =>
247 runStatementValues(statement, params ?? []),
248 );
249 },
250 executeUnprepared(sql, params, rowTransform) {
251 const effect = prepare(sql).pipe(
252 Effect.flatMap((statement) => runStatement(statement, params ?? [], false)),
253 );
254 return rowTransform ? Effect.map(effect, rowTransform) : effect;
255 },
256 executeStream(_sql, _params) {
257 return Stream.die(new UnsupportedNodeSqliteOperationError());
258 },
259 });
260 });
261
262 const semaphore = yield* Semaphore.make(1);
263 const connection = yield* makeConnection;
264
265 const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
266 const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
267 const fiber = Fiber.getCurrent()!;
268 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
269 return Effect.as(
270 Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))),
271 connection,
272 );
273 });
274
275 return yield* Client.make({
276 acquirer,
277 compiler,
278 transactionAcquirer,
279 // A deferred BEGIN only takes the write lock at the first write. If another
280 // process commits after this transaction's first read, that write fails at
281 // once with SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot wait out. Taking
282 // the lock up front makes it wait instead, at the cost of serializing
283 // read-only transactions behind other processes' writers. Read-only
284 // connections cannot write, so they keep the deferred BEGIN.
285 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
286 spanAttributes: [
287 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
288 [ATTR_DB_SYSTEM_NAME, "sqlite"],
289 ],
290 transformRows,
291 });
292});
293
294export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
295 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));