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

NodeSqliteClient.ts

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