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

nodeSqliteClient.ts

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