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

SqliteClient.ts

345 lines12.0 KB

1/**
2 * Node.js SQLite driver for Effect SQL, backed by `better-sqlite3`.
3 *
4 * Use this module to provide a scoped {@link SqliteClient} for file-backed or
5 * in-memory SQLite databases in Node.js. The provided layers install both the
6 * SQLite-specific service and the generic `SqlClient`, making the module useful
7 * for local applications, tests, migrations, development tools, and embedded
8 * persistence that need Effect SQL query compilation with SQLite-specific
9 * operations.
10 *
11 * ## Mental model
12 *
13 * Each client owns one scoped `better-sqlite3` database handle and serializes
14 * all SQL access through it. Because `better-sqlite3` executes statements
15 * synchronously, a long-running query or transaction holds the serialized
16 * connection until it completes. Prepared statements are cached by SQL text and
17 * result-name transforms are applied after rows are read.
18 *
19 * The service adds Node SQLite capabilities on top of the generic `SqlClient`:
20 * database export, file backup, and native extension loading.
21 *
22 * ## Common tasks
23 *
24 * - Use {@link layer} with a concrete filename and options.
25 * - Use {@link layerConfig} when the filename or flags should come from
26 * `Config`.
27 * - Use {@link make} inside a custom scoped layer when you need to manage the
28 * client lifecycle directly.
29 * - Use `client.export`, `client.backup`, or `client.loadExtension` for
30 * operations that are specific to this Node SQLite driver.
31 *
32 * ## Gotchas
33 *
34 * WAL mode is enabled by default. Set `disableWAL` for read-only databases or
35 * when the database file or directory cannot be updated with SQLite WAL side
36 * files. Separate database handles or processes can still contend for SQLite
37 * write locks even though access through one client is serialized.
38 *
39 * Safe integer handling follows the generic `SqlClient` fiber-local setting.
40 * `executeStream` is not implemented for this driver, and SQLite does not
41 * support `updateValues`.
42 *
43 * @since 4.0.0
44 */
45import Sqlite from "better-sqlite3"
46import * as Cache from "effect/Cache"
47import * as Config from "effect/Config"
48import * as Context from "effect/Context"
49import * as Duration from "effect/Duration"
50import * as Effect from "effect/Effect"
51import * as Fiber from "effect/Fiber"
52import { identity } from "effect/Function"
53import * as Layer from "effect/Layer"
54import * as Scope from "effect/Scope"
55import * as Semaphore from "effect/Semaphore"
56import * as Stream from "effect/Stream"
57import * as Reactivity from "effect/unstable/reactivity/Reactivity"
58import * as Client from "effect/unstable/sql/SqlClient"
59import type { Connection } from "effect/unstable/sql/SqlConnection"
60import { classifySqliteError, SqlError } from "effect/unstable/sql/SqlError"
61import * as Statement from "effect/unstable/sql/Statement"
62​
63const ATTR_DB_SYSTEM_NAME = "db.system.name"
64​
65const classifyError = (cause: unknown, message: string, operation: string) =>
66 classifySqliteError(cause, { message, operation })
67​
68/**
69 * Runtime type identifier used to mark Node `SqliteClient` values.
70 *
71 * @category type IDs
72 * @since 4.0.0
73 */
74export const TypeId: TypeId = "~@effect/sql-sqlite-node/SqliteClient"
75​
76/**
77 * Type-level identifier used to mark Node `SqliteClient` values.
78 *
79 * @category type IDs
80 * @since 4.0.0
81 */
82export type TypeId = "~@effect/sql-sqlite-node/SqliteClient"
83​
84/**
85 * Node SQLite client service, extending `SqlClient` with database export, backup, and extension loading helpers. `updateValues` is not supported.
86 *
87 * @category models
88 * @since 4.0.0
89 */
90export interface SqliteClient extends Client.SqlClient {
91 readonly [TypeId]: TypeId
92 readonly config: SqliteClientConfig
93 readonly export: Effect.Effect<Uint8Array, SqlError>
94 readonly backup: (destination: string) => Effect.Effect<BackupMetadata, SqlError>
95 readonly loadExtension: (path: string) => Effect.Effect<void, SqlError>
96​
97 /** Not supported in sqlite */
98 readonly updateValues: never
100​
101/**
102 * Metadata returned from a Node SQLite backup operation, reporting total and remaining page counts.
103 *
104 * @category models
105 * @since 4.0.0
106 */
107export interface BackupMetadata {
108 readonly totalPages: number
109 readonly remainingPages: number
111​
112/**
113 * Service tag for the node SQLite client implementation.
114 *
115 * @category tags
116 * @since 4.0.0
117 */
118export const SqliteClient = Context.Service<SqliteClient>("@effect/sql-sqlite-node/SqliteClient")
119​
120/**
121 * Configuration for a node SQLite client backed by `better-sqlite3`, including the database filename, read-only mode, statement cache settings, WAL behavior, span attributes, and query/result name transforms.
122 *
123 * @category models
124 * @since 4.0.0
125 */
126export interface SqliteClientConfig {
127 readonly filename: string
128 readonly readonly?: boolean | undefined
129 readonly prepareCacheSize?: number | undefined
130 readonly prepareCacheTTL?: Duration.Input | undefined
131 readonly disableWAL?: boolean | undefined
132 readonly spanAttributes?: Record<string, unknown> | undefined
133​
134 readonly transformResultNames?: ((str: string) => string) | undefined
135 readonly transformQueryNames?: ((str: string) => string) | undefined
137​
138interface SqliteConnection extends Connection {
139 readonly export: Effect.Effect<Uint8Array, SqlError>
140 readonly backup: (destination: string) => Effect.Effect<BackupMetadata, SqlError>
141 readonly loadExtension: (path: string) => Effect.Effect<void, SqlError>
143​
144/**
145 * Creates a scoped node SQLite client from the supplied configuration, using a single serialized connection with WAL enabled by default and exposing SQLite-specific `export`, `backup`, and `loadExtension` operations.
146 *
147 * @category constructors
148 * @since 4.0.0
149 */
150export const make = (
151 options: SqliteClientConfig
152): Effect.Effect<SqliteClient, never, Scope.Scope | Reactivity.Reactivity> =>
153 Effect.gen(function*() {
154 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
155 const transformRows = options.transformResultNames ?
156 Statement.defaultTransforms(
157 options.transformResultNames
158 ).array :
159 undefined
160​
161 const makeConnection = Effect.gen(function*() {
162 const scope = yield* Effect.scope
163 const db = new Sqlite(options.filename, {
164 readonly: options.readonly ?? false
165 })
166 yield* Scope.addFinalizer(scope, Effect.sync(() => db.close()))
167​
168 if (options.disableWAL !== true) {
169 db.pragma("journal_mode = WAL")
170 }
171​
172 const prepareCache = yield* Cache.make({
173 capacity: options.prepareCacheSize ?? 200,
174 timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
175 lookup: (sql: string) =>
176 Effect.try({
177 try: () => db.prepare(sql),
178 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to prepare statement", "prepare") })
179 })
180 })
181​
182 const runStatement = (
183 statement: Sqlite.Statement,
184 params: ReadonlyArray<unknown>,
185 raw: boolean
186 ) =>
187 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
188 if (Context.get(fiber.context, Client.SafeIntegers)) {
189 statement.safeIntegers(true)
190 }
191 try {
192 if (statement.reader) {
193 return Effect.succeed(statement.all(...params))
194 }
195 const result = statement.run(...params)
196 return Effect.succeed(raw ? result as unknown as ReadonlyArray<any> : [])
197 } catch (cause) {
198 return Effect.fail(new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") }))
199 }
200 })
201​
202 const run = (
203 sql: string,
204 params: ReadonlyArray<unknown>,
205 raw = false
206 ) =>
207 Effect.flatMap(
208 Cache.get(prepareCache, sql),
209 (s) => runStatement(s, params, raw)
210 )
211​
212 const runValues = (
213 sql: string,
214 params: ReadonlyArray<unknown>
215 ) =>
216 Effect.acquireUseRelease(
217 Cache.get(prepareCache, sql),
218 (statement) =>
219 Effect.try({
220 try: () => {
221 if (statement.reader) {
222 statement.raw(true)
223 return statement.all(...params) as ReadonlyArray<
224 ReadonlyArray<unknown>
225 >
226 }
227 statement.run(...params)
228 return []
229 },
230 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
231 }),
232 (statement) => Effect.sync(() => statement.reader && statement.raw(false))
233 )
234​
235 return identity<SqliteConnection>({
236 execute(sql, params, transformRows) {
237 return transformRows
238 ? Effect.map(run(sql, params), transformRows)
239 : run(sql, params)
240 },
241 executeRaw(sql, params) {
242 return run(sql, params, true)
243 },
244 executeValues(sql, params) {
245 return runValues(sql, params)
246 },
247 executeUnprepared(sql, params, transformRows) {
248 const effect = runStatement(db.prepare(sql), params ?? [], false)
249 return transformRows ? Effect.map(effect, transformRows) : effect
250 },
251 executeStream(_sql, _params) {
252 return Stream.die("executeStream not implemented")
253 },
254 export: Effect.try({
255 try: () => db.serialize(),
256 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to export database", "export") })
257 }),
258 backup(destination) {
259 return Effect.tryPromise({
260 try: () => db.backup(destination),
261 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to backup database", "backup") })
262 })
263 },
264 loadExtension(path) {
265 return Effect.try({
266 try: () => db.loadExtension(path),
267 catch: (cause) =>
268 new SqlError({ reason: classifyError(cause, "Failed to load extension", "loadExtension") })
269 })
270 }
271 })
272 })
273​
274 const semaphore = yield* Semaphore.make(1)
275 const connection = yield* makeConnection
276​
277 const acquirer = semaphore.withPermits(1)(Effect.succeed(connection))
278 const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
279 const fiber = Fiber.getCurrent()!
280 const scope = Context.getUnsafe(fiber.context, Scope.Scope)
281 return Effect.as(
282 Effect.tap(
283 restore(semaphore.take(1)),
284 () => Scope.addFinalizer(scope, semaphore.release(1))
285 ),
286 connection
287 )
288 })
289​
290 return Object.assign(
291 (yield* Client.make({
292 acquirer,
293 compiler,
294 transactionAcquirer,
295 spanAttributes: [
296 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
297 [ATTR_DB_SYSTEM_NAME, "sqlite"]
298 ],
299 transformRows
300 })) as SqliteClient,
301 {
302 [TypeId]: TypeId as TypeId,
303 config: options,
304 export: Effect.flatMap(acquirer, (_) => _.export),
305 backup: (destination: string) => Effect.flatMap(acquirer, (_) => _.backup(destination)),
306 loadExtension: (path: string) => Effect.flatMap(acquirer, (_) => _.loadExtension(path))
307 }
308 )
309 })
310​
311/**
312 * Builds a layer from an Effect `Config` value, providing both the node `SqliteClient` service and the generic `SqlClient` service.
313 *
314 * @category layers
315 * @since 4.0.0
316 */
317export const layerConfig = (
318 config: Config.Wrap<SqliteClientConfig>
319): Layer.Layer<SqliteClient | Client.SqlClient, Config.ConfigError> =>
320 Layer.effectContext(
321 Config.unwrap(config).pipe(
322 Effect.flatMap(make),
323 Effect.map((client) =>
324 Context.make(SqliteClient, client).pipe(
325 Context.add(Client.SqlClient, client)
326 )
327 )
328 )
329 ).pipe(Layer.provide(Reactivity.layer))
330​
331/**
332 * Builds a layer from a node SQLite client configuration, providing both `SqliteClient` and the generic `SqlClient` service.
333 *
334 * @category layers
335 * @since 4.0.0
336 */
337export const layer = (
338 config: SqliteClientConfig
339): Layer.Layer<SqliteClient | Client.SqlClient> =>
340 Layer.effectContext(
341 Effect.map(make(config), (client) =>
342 Context.make(SqliteClient, client).pipe(
343 Context.add(Client.SqlClient, client)
344 ))
345 ).pipe(Layer.provide(Reactivity.layer))