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

nodeSqliteClient.ts

285 lines9.6 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 Exit from "effect/Exit";
13import * as Fiber from "effect/Fiber";
14import { identity } from "effect/Function";
15import * as Layer from "effect/Layer";
16import * as Schema from "effect/Schema";
17import * as Scope from "effect/Scope";
18import * as Semaphore from "effect/Semaphore";
19import * as Context from "effect/Context";
20import * as Stream from "effect/Stream";
21import * as Reactivity from "effect/unstable/reactivity/Reactivity";
22import * as Client from "effect/unstable/sql/SqlClient";
23import type { Connection } from "effect/unstable/sql/SqlConnection";
24import { SqlError, classifySqliteError } from "effect/unstable/sql/SqlError";
25import * as Statement from "effect/unstable/sql/Statement";
26​
27const ATTR_DB_SYSTEM_NAME = "db.system.name";
28​
29export interface SqliteClientConfig {
30 readonly filename: string;
31 readonly readonly?: boolean | undefined;
32 readonly allowExtension?: boolean | undefined;
33 readonly prepareCacheSize?: number | undefined;
34 readonly prepareCacheTTL?: Duration.Input | undefined;
35 readonly spanAttributes?: Record<string, unknown> | undefined;
36 readonly transformResultNames?: ((str: string) => string) | undefined;
37 readonly transformQueryNames?: ((str: string) => string) | undefined;
39​
40export class UnsupportedNodeSqliteVersionError extends Schema.TaggedError<UnsupportedNodeSqliteVersionError>()(
41 "UnsupportedNodeSqliteVersionError",
42 {
43 nodeVersion: Schema.String,
44 requirement: Schema.String,
45 },
46) {
47 override get message(): string {
48 return `Node.js ${this.nodeVersion} is missing required node:sqlite APIs. Upgrade to ${this.requirement}.`;
49 }
51​
52export class UnsupportedNodeSqliteOperationError extends Schema.TaggedError<UnsupportedNodeSqliteOperationError>()(
53 "UnsupportedNodeSqliteOperationError",
54 {},
55) {
56 override get message(): string {
57 return "Node SQLite does not support executeStream.";
58 }
60​
61/**
62 * Verify that the current Node.js version includes the `node:sqlite` APIs
63 * used by `NodeSqliteClient` — specifically `StatementSync.columns()` (added
64 * in Node 22.16.0 / 23.11.0).
65 *
66 * @see https://github.com/nodejs/node/pull/57490
67 */
68const checkNodeSqliteCompat = () => {
69 const parts = process.versions.node.split(".").map(Number);
70 const major = parts[0] ?? 0;
71 const minor = parts[1] ?? 0;
72 const supported = (major === 22 && minor >= 16) || (major === 23 && minor >= 11) || major >= 24;
73​
74 if (!supported) {
75 return Effect.die(
76 new UnsupportedNodeSqliteVersionError({
77 nodeVersion: process.versions.node,
78 requirement: "Node.js >=22.16, >=23.11, or >=24",
79 }),
80 );
81 }
82 return Effect.void;
83};
84​
85const make = Effect.fn("makeWithDatabase")(function* (
86 options: SqliteClientConfig,
87): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
88 yield* checkNodeSqliteCompat();
89​
90 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
91 const transformRows = options.transformResultNames
92 ? Statement.defaultTransforms(options.transformResultNames).array
93 : undefined;
94​
95 const makeConnection = Effect.gen(function* () {
96 const scope = yield* Effect.scope;
97 const db = yield* Effect.try({
98 try: () =>
99 new NodeSqlite.DatabaseSync(options.filename, {
100 readOnly: options.readonly ?? false,
101 allowExtension: options.allowExtension ?? false,
102 }),
103 catch: (cause) =>
104 new SqlError({
105 reason: classifySqliteError(cause, {
106 message: "Failed to open database",
107 operation: "open",
108 }),
109 }),
110 });
111 yield* Scope.addFinalizer(
112 scope,
113 Effect.try({
114 try: () => db.close(),
115 catch: (cause) =>
116 new SqlError({
117 reason: classifySqliteError(cause, {
118 message: "Failed to close database",
119 operation: "close",
120 }),
121 }),
122 }).pipe(Effect.orDie),
123 );
124​
125 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
126 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
127 const cached = statementReaderCache.get(statement);
128 if (cached !== undefined) {
129 return cached;
130 }
131 const value = statement.columns().length > 0;
132 statementReaderCache.set(statement, value);
133 return value;
134 };
135​
136 const prepare = (sql: string) =>
137 Effect.try({
138 try: () => db.prepare(sql),
139 catch: (cause) =>
140 new SqlError({
141 reason: classifySqliteError(cause, {
142 message: "Failed to prepare statement",
143 operation: "prepare",
144 }),
145 }),
146 });
147​
148 const prepareCache = yield* Cache.makeWith(prepare, {
149 capacity: options.prepareCacheSize ?? 200,
150 // A transient prepare failure must not outlive the lock or missing schema.
151 timeToLive: (exit) =>
152 Exit.isSuccess(exit) ? (options.prepareCacheTTL ?? Duration.minutes(10)) : Duration.zero,
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​
284export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
285 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));