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

nodeSqliteClient.ts

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