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

NodeSqliteClient.ts

265 lines9.1 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 { 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 } 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;
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) => new SqlError({ cause, message: "Failed to prepare statement" }),
113 }),
114 });
115​
116 const runStatement = (
117 statement: StatementSync,
118 params: ReadonlyArray<unknown>,
119 raw: boolean,
120 ) =>
121 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
122 statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
123 try {
124 if (hasRows(statement)) {
125 return Effect.succeed(statement.all(...(params as any)));
126 }
127 const result = statement.run(...(params as any));
128 return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
129 } catch (cause) {
130 return Effect.fail(new SqlError({ cause, message: "Failed to execute statement" }));
131 }
132 });
133​
134 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
135 Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
136​
137 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
138 Effect.acquireUseRelease(
139 Cache.get(prepareCache, sql),
140 (statement) =>
141 Effect.try({
142 try: () => {
143 if (hasRows(statement)) {
144 statement.setReturnArrays(true);
145 // Safe to cast to array after we've setReturnArrays(true)
146 return statement.all(...(params as any)) as unknown as ReadonlyArray<
147 ReadonlyArray<unknown>
148 >;
149 }
150 statement.run(...(params as any));
151 return [];
152 },
153 catch: (cause) => new SqlError({ cause, message: "Failed to execute statement" }),
154 }),
155 (statement) =>
156 Effect.sync(() => {
157 if (hasRows(statement)) {
158 statement.setReturnArrays(false);
159 }
160 }),
161 );
162​
163 return identity<Connection>({
164 execute(sql, params, rowTransform) {
165 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
166 },
167 executeRaw(sql, params) {
168 return run(sql, params, true);
169 },
170 executeValues(sql, params) {
171 return runValues(sql, params);
172 },
173 executeUnprepared(sql, params, rowTransform) {
174 const effect = runStatement(db.prepare(sql), params ?? [], false);
175 return rowTransform ? Effect.map(effect, rowTransform) : effect;
176 },
177 executeStream(_sql, _params) {
178 return Stream.die("executeStream not implemented");
179 },
180 });
181 });
182​
183 const semaphore = yield* Semaphore.make(1);
184 const connection = yield* makeConnection;
185​
186 const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
187 const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
188 const fiber = Fiber.getCurrent()!;
189 const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
190 return Effect.as(
191 Effect.tap(restore(semaphore.take(1)), () =>
192 Scope.addFinalizer(scope, semaphore.release(1)),
193 ),
194 connection,
195 );
196 });
197​
198 return yield* Client.make({
199 acquirer,
200 compiler,
201 transactionAcquirer,
202 spanAttributes: [
203 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
204 [ATTR_DB_SYSTEM_NAME, "sqlite"],
205 ],
206 transformRows,
207 });
208 });
209​
210const make = (
211 options: SqliteClientConfig,
212): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
213 makeWithDatabase(
214 options,
215 () =>
216 new DatabaseSync(options.filename, {
217 readOnly: options.readonly ?? false,
218 allowExtension: options.allowExtension ?? false,
219 }),
220 );
221​
222const makeMemory = (
223 config: SqliteMemoryClientConfig = {},
224): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
225 makeWithDatabase(
226 {
227 ...config,
228 filename: ":memory:",
229 readonly: false,
230 },
231 () => {
232 const database = new DatabaseSync(":memory:", {
233 allowExtension: config.allowExtension ?? false,
234 });
235 return database;
236 },
237 );
238​
239export const layerConfig = (
240 config: Config.Wrap<SqliteClientConfig>,
241): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
242 Layer.effectServices(
243 Config.unwrap(config)
244 .asEffect()
245 .pipe(
246 Effect.flatMap(make),
247 Effect.map((client) =>
248 ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
249 ),
250 ),
251 ).pipe(Layer.provide(Reactivity.layer));
252​
253export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient> =>
254 Layer.effectServices(
255 Effect.map(make(config), (client) =>
256 ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
257 ),
258 ).pipe(Layer.provide(Reactivity.layer));
259​
260export const layerMemory = (config: SqliteMemoryClientConfig = {}): Layer.Layer<Client.SqlClient> =>
261 Layer.effectServices(
262 Effect.map(makeMemory(config), (client) =>
263 ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
264 ),
265 ).pipe(Layer.provide(Reactivity.layer));