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

NodeSqliteClient.ts

241 lines8.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 { 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​
53const makeWithDatabase = (
54 options: SqliteClientConfig,
55 openDatabase: () => DatabaseSync,
56): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
57 Effect.gen(function* () {
58 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
59 const transformRows = options.transformResultNames
60 ? Statement.defaultTransforms(options.transformResultNames).array
61 : undefined;
62​
63 const makeConnection = Effect.gen(function* () {
64 const scope = yield* Effect.scope;
65 const db = openDatabase();
66 yield* Scope.addFinalizer(
67 scope,
68 Effect.sync(() => db.close()),
69 );
70​
71 const statementReaderCache = new WeakMap<StatementSync, boolean>();
72 const hasRows = (statement: StatementSync): boolean => {
73 const cached = statementReaderCache.get(statement);
74 if (cached !== undefined) {
75 return cached;
76 }
77 const value = statement.columns().length > 0;
78 statementReaderCache.set(statement, value);
79 return value;
80 };
81​
82 const prepareCache = yield* Cache.make({
83 capacity: options.prepareCacheSize ?? 200,
84 timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
85 lookup: (sql: string) =>
86 Effect.try({
87 try: () => db.prepare(sql),
88 catch: (cause) => new SqlError({ cause, message: "Failed to prepare statement" }),
89 }),
90 });
91​
92 const runStatement = (
93 statement: StatementSync,
94 params: ReadonlyArray<unknown>,
95 raw: boolean,
96 ) =>
97 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
98 statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
99 try {
100 if (hasRows(statement)) {
101 return Effect.succeed(statement.all(...(params as any)));
102 }
103 const result = statement.run(...(params as any));
104 return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
105 } catch (cause) {
106 return Effect.fail(new SqlError({ cause, message: "Failed to execute statement" }));
107 }
108 });
109​
110 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
111 Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
112​
113 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
114 Effect.acquireUseRelease(
115 Cache.get(prepareCache, sql),
116 (statement) =>
117 Effect.try({
118 try: () => {
119 if (hasRows(statement)) {
120 statement.setReturnArrays(true);
121 // Safe to cast to array after we've setReturnArrays(true)
122 return statement.all(...(params as any)) as unknown as ReadonlyArray<
123 ReadonlyArray<unknown>
124 >;
125 }
126 statement.run(...(params as any));
127 return [];
128 },
129 catch: (cause) => new SqlError({ cause, message: "Failed to execute statement" }),
130 }),
131 (statement) =>
132 Effect.sync(() => {
133 if (hasRows(statement)) {
134 statement.setReturnArrays(false);
135 }
136 }),
137 );
138​
139 return identity<Connection>({
140 execute(sql, params, rowTransform) {
141 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
142 },
143 executeRaw(sql, params) {
144 return run(sql, params, true);
145 },
146 executeValues(sql, params) {
147 return runValues(sql, params);
148 },
149 executeUnprepared(sql, params, rowTransform) {
150 const effect = runStatement(db.prepare(sql), params ?? [], false);
151 return rowTransform ? Effect.map(effect, rowTransform) : effect;
152 },
153 executeStream(_sql, _params) {
154 return Stream.die("executeStream not implemented");
155 },
156 });
157 });
158​
159 const semaphore = yield* Semaphore.make(1);
160 const connection = yield* makeConnection;
161​
162 const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
163 const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
164 const fiber = Fiber.getCurrent()!;
165 const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
166 return Effect.as(
167 Effect.tap(restore(semaphore.take(1)), () =>
168 Scope.addFinalizer(scope, semaphore.release(1)),
169 ),
170 connection,
171 );
172 });
173​
174 return yield* Client.make({
175 acquirer,
176 compiler,
177 transactionAcquirer,
178 spanAttributes: [
179 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
180 [ATTR_DB_SYSTEM_NAME, "sqlite"],
181 ],
182 transformRows,
183 });
184 });
185​
186const make = (
187 options: SqliteClientConfig,
188): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
189 makeWithDatabase(
190 options,
191 () =>
192 new DatabaseSync(options.filename, {
193 readOnly: options.readonly ?? false,
194 allowExtension: options.allowExtension ?? false,
195 }),
196 );
197​
198const makeMemory = (
199 config: SqliteMemoryClientConfig = {},
200): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
201 makeWithDatabase(
202 {
203 ...config,
204 filename: ":memory:",
205 readonly: false,
206 },
207 () => {
208 const database = new DatabaseSync(":memory:", {
209 allowExtension: config.allowExtension ?? false,
210 });
211 return database;
212 },
213 );
214​
215export const layerConfig = (
216 config: Config.Wrap<SqliteClientConfig>,
217): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
218 Layer.effectServices(
219 Config.unwrap(config)
220 .asEffect()
221 .pipe(
222 Effect.flatMap(make),
223 Effect.map((client) =>
224 ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
225 ),
226 ),
227 ).pipe(Layer.provide(Reactivity.layer));
228​
229export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient> =>
230 Layer.effectServices(
231 Effect.map(make(config), (client) =>
232 ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
233 ),
234 ).pipe(Layer.provide(Reactivity.layer));
235​
236export const layerMemory = (config: SqliteMemoryClientConfig = {}): Layer.Layer<Client.SqlClient> =>
237 Layer.effectServices(
238 Effect.map(makeMemory(config), (client) =>
239 ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
240 ),
241 ).pipe(Layer.provide(Reactivity.layer));