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 = (
76 options: SqliteClientConfig,
77 openDatabase: () => DatabaseSync,
78): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
79 Effect.gen(function* () {
80 yield* checkNodeSqliteCompat();
81
82 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
83 const transformRows = options.transformResultNames
84 ? Statement.defaultTransforms(options.transformResultNames).array
85 : undefined;
86
87 const makeConnection = Effect.gen(function* () {
88 const scope = yield* Effect.scope;
89 const db = openDatabase();
90 yield* Scope.addFinalizer(
91 scope,
92 Effect.sync(() => db.close()),
93 );
94
95 const statementReaderCache = new WeakMap<StatementSync, boolean>();
96 const hasRows = (statement: StatementSync): boolean => {
97 const cached = statementReaderCache.get(statement);
98 if (cached !== undefined) {
99 return cached;
100 }
101 const value = statement.columns().length > 0;
102 statementReaderCache.set(statement, value);
103 return value;
104 };
105
106 const prepareCache = yield* Cache.make({
107 capacity: options.prepareCacheSize ?? 200,
108 timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
109 lookup: (sql: string) =>
110 Effect.try({
111 try: () => db.prepare(sql),
112 catch: (cause) =>
113 new SqlError({
114 reason: classifySqliteError(cause, {
115 message: "Failed to prepare statement",
116 operation: "prepare",
117 }),
118 }),
119 }),
120 });
121
122 const runStatement = (
123 statement: StatementSync,
124 params: ReadonlyArray<unknown>,
125 raw: boolean,
126 ) =>
127 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
128 statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
129 try {
130 if (hasRows(statement)) {
131 return Effect.succeed(statement.all(...(params as any)));
132 }
133 const result = statement.run(...(params as any));
134 return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
135 } catch (cause) {
136 return Effect.fail(
137 new SqlError({
138 reason: classifySqliteError(cause, {
139 message: "Failed to execute statement",
140 operation: "execute",
141 }),
142 }),
143 );
144 }
145 });
146
147 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
148 Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
149
150 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
151 Effect.acquireUseRelease(
152 Cache.get(prepareCache, sql),
153 (statement) =>
154 Effect.try({
155 try: () => {
156 if (hasRows(statement)) {
157 statement.setReturnArrays(true);
158 // Safe to cast to array after we've setReturnArrays(true)
159 return statement.all(...(params as any)) as unknown as ReadonlyArray<
160 ReadonlyArray<unknown>
161 >;
162 }
163 statement.run(...(params as any));
164 return [];
165 },
166 catch: (cause) =>
167 new SqlError({
168 reason: classifySqliteError(cause, {
169 message: "Failed to execute statement",
170 operation: "execute",
171 }),
172 }),
173 }),
174 (statement) =>
175 Effect.sync(() => {
176 if (hasRows(statement)) {
177 statement.setReturnArrays(false);
178 }
179 }),
180 );
181
182 return identity<Connection>({
183 execute(sql, params, rowTransform) {
184 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
185 },
186 executeRaw(sql, params) {
187 return run(sql, params, true);
188 },
189 executeValues(sql, params) {
190 return runValues(sql, params);
191 },
192 executeUnprepared(sql, params, rowTransform) {
193 const effect = runStatement(db.prepare(sql), params ?? [], false);
194 return rowTransform ? Effect.map(effect, rowTransform) : effect;
195 },
196 executeStream(_sql, _params) {
197 return Stream.die("executeStream not implemented");
198 },
199 });
200 });
201
202 const semaphore = yield* Semaphore.make(1);
203 const connection = yield* makeConnection;
204
205 const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
206 const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
207 const fiber = Fiber.getCurrent()!;
208 const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
209 return Effect.as(
210 Effect.tap(restore(semaphore.take(1)), () =>
211 Scope.addFinalizer(scope, semaphore.release(1)),
212 ),
213 connection,
214 );
215 });
216
217 return yield* Client.make({
218 acquirer,
219 compiler,
220 transactionAcquirer,
221 spanAttributes: [
222 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
223 [ATTR_DB_SYSTEM_NAME, "sqlite"],
224 ],
225 transformRows,
226 });
227 });
228
229const make = (
230 options: SqliteClientConfig,
231): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
232 makeWithDatabase(
233 options,
234 () =>
235 new DatabaseSync(options.filename, {
236 readOnly: options.readonly ?? false,
237 allowExtension: options.allowExtension ?? false,
238 }),
239 );
240
241const makeMemory = (
242 config: SqliteMemoryClientConfig = {},
243): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
244 makeWithDatabase(
245 {
246 ...config,
247 filename: ":memory:",
248 readonly: false,
249 },
250 () => {
251 const database = new DatabaseSync(":memory:", {
252 allowExtension: config.allowExtension ?? false,
253 });
254 return database;
255 },
256 );
257
258export const layerConfig = (
259 config: Config.Wrap<SqliteClientConfig>,
260): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
261 Layer.effectServices(
262 Config.unwrap(config)
263 .asEffect()
264 .pipe(
265 Effect.flatMap(make),
266 Effect.map((client) =>
267 ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
268 ),
269 ),
270 ).pipe(Layer.provide(Reactivity.layer));
271
272export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient> =>
273 Layer.effectServices(
274 Effect.map(make(config), (client) =>
275 ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
276 ),
277 ).pipe(Layer.provide(Reactivity.layer));
278
279export const layerMemory = (config: SqliteMemoryClientConfig = {}): Layer.Layer<Client.SqlClient> =>
280 Layer.effectServices(
281 Effect.map(makeMemory(config), (client) =>
282 ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
283 ),
284 ).pipe(Layer.provide(Reactivity.layer));