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 { DatabaseSync, type StatementSync } from "node:sqlite";
8
9import * as Cache from "effect/Cache";
10import * as Config from "effect/Config";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Fiber from "effect/Fiber";
14import { identity } from "effect/Function";
15import * as Layer from "effect/Layer";
16import * as Scope from "effect/Scope";
17import * as Semaphore from "effect/Semaphore";
18import * as ServiceMap from "effect/ServiceMap";
19import * as Stream from "effect/Stream";
20import * as Reactivity from "effect/unstable/reactivity/Reactivity";
21import * as Client from "effect/unstable/sql/SqlClient";
22import type { Connection } from "effect/unstable/sql/SqlConnection";
23import { SqlError, classifySqliteError } from "effect/unstable/sql/SqlError";
24import * as Statement from "effect/unstable/sql/Statement";
25
26const ATTR_DB_SYSTEM_NAME = "db.system.name";
27
28export const TypeId: TypeId = "~local/sqlite-node/SqliteClient";
29
30export type TypeId = "~local/sqlite-node/SqliteClient";
31
32/**
33 * SqliteClient - Effect service tag for the sqlite SQL client.
34 */
35export const SqliteClient = ServiceMap.Service<Client.SqlClient>("t3/persistence/NodeSqliteClient");
36
37export interface SqliteClientConfig {
38 readonly filename: string;
39 readonly readonly?: boolean | undefined;
40 readonly allowExtension?: boolean | undefined;
41 readonly prepareCacheSize?: number | undefined;
42 readonly prepareCacheTTL?: Duration.Input | undefined;
43 readonly spanAttributes?: Record<string, unknown> | undefined;
44 readonly transformResultNames?: ((str: string) => string) | undefined;
45 readonly transformQueryNames?: ((str: string) => string) | undefined;
46}
47
48export interface SqliteMemoryClientConfig extends Omit<
49 SqliteClientConfig,
50 "filename" | "readonly"
51> {}
52
53/**
54 * Verify that the current Node.js version includes the `node:sqlite` APIs
55 * used by `NodeSqliteClient` — specifically `StatementSync.columns()` (added
56 * in Node 22.16.0 / 23.11.0).
57 *
58 * @see https://github.com/nodejs/node/pull/57490
59 */
60const checkNodeSqliteCompat = () => {
61 const parts = process.versions.node.split(".").map(Number);
62 const major = parts[0] ?? 0;
63 const minor = parts[1] ?? 0;
64 const supported = (major === 22 && minor >= 16) || (major === 23 && minor >= 11) || major >= 24;
65
66 if (!supported) {
67 return Effect.die(
68 `Node.js ${process.versions.node} is missing required node:sqlite APIs ` +
69 `(StatementSync.columns). Upgrade to Node.js >=22.16, >=23.11, or >=24.`,
70 );
71 }
72 return Effect.void;
73};
74
75const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
76 options: SqliteClientConfig,
77 openDatabase: () => DatabaseSync,
78): Effect.fn.Return<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> {
79 yield* checkNodeSqliteCompat();
80
81 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
82 const transformRows = options.transformResultNames
83 ? Statement.defaultTransforms(options.transformResultNames).array
84 : undefined;
85
86 const makeConnection = Effect.gen(function* () {
87 const scope = yield* Effect.scope;
88 const db = openDatabase();
89 yield* Scope.addFinalizer(
90 scope,
91 Effect.sync(() => db.close()),
92 );
93
94 const statementReaderCache = new WeakMap<StatementSync, boolean>();
95 const hasRows = (statement: StatementSync): boolean => {
96 const cached = statementReaderCache.get(statement);
97 if (cached !== undefined) {
98 return cached;
99 }
100 const value = statement.columns().length > 0;
101 statementReaderCache.set(statement, value);
102 return value;
103 };
104
105 const prepareCache = yield* Cache.make({
106 capacity: options.prepareCacheSize ?? 200,
107 timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
108 lookup: (sql: string) =>
109 Effect.try({
110 try: () => db.prepare(sql),
111 catch: (cause) =>
112 new SqlError({
113 reason: classifySqliteError(cause, {
114 message: "Failed to prepare statement",
115 operation: "prepare",
116 }),
117 }),
118 }),
119 });
120
121 const runStatement = (statement: StatementSync, params: ReadonlyArray<unknown>, raw: boolean) =>
122 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
123 statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
124 try {
125 if (hasRows(statement)) {
126 return Effect.succeed(statement.all(...(params as any)));
127 }
128 const result = statement.run(...(params as any));
129 return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
130 } catch (cause) {
131 return Effect.fail(
132 new SqlError({
133 reason: classifySqliteError(cause, {
134 message: "Failed to execute statement",
135 operation: "execute",
136 }),
137 }),
138 );
139 }
140 });
141
142 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
143 Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
144
145 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
146 Effect.acquireUseRelease(
147 Cache.get(prepareCache, sql),
148 (statement) =>
149 Effect.try({
150 try: () => {
151 if (hasRows(statement)) {
152 statement.setReturnArrays(true);
153 // Safe to cast to array after we've setReturnArrays(true)
154 return statement.all(...(params as any)) as unknown as ReadonlyArray<
155 ReadonlyArray<unknown>
156 >;
157 }
158 statement.run(...(params as any));
159 return [];
160 },
161 catch: (cause) =>
162 new SqlError({
163 reason: classifySqliteError(cause, {
164 message: "Failed to execute statement",
165 operation: "execute",
166 }),
167 }),
168 }),
169 (statement) =>
170 Effect.sync(() => {
171 if (hasRows(statement)) {
172 statement.setReturnArrays(false);
173 }
174 }),
175 );
176
177 return identity<Connection>({
178 execute(sql, params, rowTransform) {
179 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
180 },
181 executeRaw(sql, params) {
182 return run(sql, params, true);
183 },
184 executeValues(sql, params) {
185 return runValues(sql, params);
186 },
187 executeUnprepared(sql, params, rowTransform) {
188 const effect = runStatement(db.prepare(sql), params ?? [], false);
189 return rowTransform ? Effect.map(effect, rowTransform) : effect;
190 },
191 executeStream(_sql, _params) {
192 return Stream.die("executeStream not implemented");
193 },
194 });
195 });
196
197 const semaphore = yield* Semaphore.make(1);
198 const connection = yield* makeConnection;
199
200 const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
201 const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
202 const fiber = Fiber.getCurrent()!;
203 const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
204 return Effect.as(
205 Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))),
206 connection,
207 );
208 });
209
210 return yield* Client.make({
211 acquirer,
212 compiler,
213 transactionAcquirer,
214 spanAttributes: [
215 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
216 [ATTR_DB_SYSTEM_NAME, "sqlite"],
217 ],
218 transformRows,
219 });
220});
221
222const make = (
223 options: SqliteClientConfig,
224): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
225 makeWithDatabase(
226 options,
227 () =>
228 new DatabaseSync(options.filename, {
229 readOnly: options.readonly ?? false,
230 allowExtension: options.allowExtension ?? false,
231 }),
232 );
233
234const makeMemory = (
235 config: SqliteMemoryClientConfig = {},
236): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
237 makeWithDatabase(
238 {
239 ...config,
240 filename: ":memory:",
241 readonly: false,
242 },
243 () => {
244 const database = new DatabaseSync(":memory:", {
245 allowExtension: config.allowExtension ?? false,
246 });
247 return database;
248 },
249 );
250
251export const layerConfig = (
252 config: Config.Wrap<SqliteClientConfig>,
253): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
254 Layer.effectServices(
255 Config.unwrap(config)
256 .asEffect()
257 .pipe(
258 Effect.flatMap(make),
259 Effect.map((client) =>
260 ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
261 ),
262 ),
263 ).pipe(Layer.provide(Reactivity.layer));
264
265export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient> =>
266 Layer.effectServices(
267 Effect.map(make(config), (client) =>
268 ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
269 ),
270 ).pipe(Layer.provide(Reactivity.layer));
271
272export const layerMemory = (config: SqliteMemoryClientConfig = {}): Layer.Layer<Client.SqlClient> =>
273 Layer.effectServices(
274 Effect.map(makeMemory(config), (client) =>
275 ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
276 ),
277 ).pipe(Layer.provide(Reactivity.layer));