Open History to see the last commit
1/**
2 * Connects Effect SQL to SQLite on Node.js using `node:sqlite`.
3 *
4 * This module opens a SQLite database and exposes it as both `SqliteClient` and
5 * the generic Effect SQL client. It serializes access through one connection,
6 * caches prepared statements, enables WAL mode unless disabled, and waits up
7 * to five seconds for busy databases by default. Explicit transactions on
8 * writable connections use `BEGIN IMMEDIATE` to avoid read-to-write lock
9 * upgrades, which serializes them behind other writers even when they only
10 * read. Clients opened with `readonly: true` are unaffected. Busy waits block
11 * the Node.js event loop because `node:sqlite` is synchronous. Database backup
12 * and extension loading are supported; streaming queries and `updateValues`
13 * are not.
14 *
15 * @since 4.0.0
16 */
17import * as Cache from "effect/Cache"
18import * as Config from "effect/Config"
19import * as Context from "effect/Context"
20import * as Duration from "effect/Duration"
21import * as Effect from "effect/Effect"
22import * as Fiber from "effect/Fiber"
23import { identity } from "effect/Function"
24import * as Layer from "effect/Layer"
25import * as Scope from "effect/Scope"
26import * as Semaphore from "effect/Semaphore"
27import * as Stream from "effect/Stream"
28import * as Reactivity from "effect/unstable/reactivity/Reactivity"
29import * as Client from "effect/unstable/sql/SqlClient"
30import type { Connection } from "effect/unstable/sql/SqlConnection"
31import { classifySqliteError, SqlError } from "effect/unstable/sql/SqlError"
32import * as Statement from "effect/unstable/sql/Statement"
33import { backup as backupDatabase, DatabaseSync } from "node:sqlite"
34import type { StatementSync } from "node:sqlite"
35
36const ATTR_DB_SYSTEM_NAME = "db.system.name"
37const MAX_BUSY_TIMEOUT = 2_147_483_647
38
39/**
40 * Runtime type identifier used to mark Node `SqliteClient` values.
41 *
42 * @category type IDs
43 * @since 4.0.0
44 */
45export const TypeId: TypeId = "~@effect/sql-sqlite-node/SqliteClient"
46
47/**
48 * Type-level identifier used to mark Node `SqliteClient` values.
49 *
50 * @category type IDs
51 * @since 4.0.0
52 */
53export type TypeId = "~@effect/sql-sqlite-node/SqliteClient"
54
55/**
56 * Node SQLite client service, extending `SqlClient` with database export, backup, and extension loading helpers. `updateValues` is not supported.
57 *
58 * @category services
59 * @since 4.0.0
60 */
61export interface SqliteClient extends Client.SqlClient {
62 readonly [TypeId]: TypeId
63 readonly config: SqliteClientConfig
64 readonly backup: (destination: string) => Effect.Effect<BackupMetadata, SqlError>
65 readonly loadExtension: (path: string) => Effect.Effect<void, SqlError>
66
67 /** Not supported in sqlite */
68 readonly updateValues: never
69}
70
71/**
72 * Metadata returned from a Node SQLite backup operation, reporting total and remaining page counts.
73 *
74 * @category models
75 * @since 4.0.0
76 */
77export interface BackupMetadata {
78 readonly totalPages: number
79 readonly remainingPages: number
80}
81
82/**
83 * Service tag for the node SQLite client implementation.
84 *
85 * @category services
86 * @since 4.0.0
87 */
88export const SqliteClient = Context.Service<SqliteClient>("@effect/sql-sqlite-node/SqliteClient")
89
90/**
91 * Configuration for a node SQLite client backed by `node:sqlite`, including the database filename, read-only mode, statement cache settings, WAL and busy timeout behavior, span attributes, and query/result name transforms.
92 *
93 * @category models
94 * @since 4.0.0
95 */
96export interface SqliteClientConfig {
97 readonly filename: string
98 readonly readonly?: boolean | undefined
99 readonly prepareCacheSize?: number | undefined
100 readonly prepareCacheTTL?: Duration.Input | undefined
101 readonly disableWAL?: boolean | undefined
102 /**
103 * How long SQLite waits when the database is busy. Defaults to 5 seconds.
104 * `Duration.infinity` is clamped to SQLite's maximum timeout.
105 * Waiting blocks the Node.js event loop because `node:sqlite` is synchronous.
106 */
107 readonly busyTimeout?: Duration.Input | undefined
108 readonly spanAttributes?: Record<string, unknown> | undefined
109
110 readonly transformResultNames?: ((str: string) => string) | undefined
111 readonly transformQueryNames?: ((str: string) => string) | undefined
112}
113
114interface SqliteConnection extends Connection {
115 readonly backup: (destination: string) => Effect.Effect<BackupMetadata, SqlError>
116 readonly loadExtension: (path: string) => Effect.Effect<void, SqlError>
117}
118
119/**
120 * Creates a scoped node SQLite client from the supplied configuration, using a single serialized connection with WAL and a 5-second busy timeout enabled by default. Explicit transactions on writable connections take the write lock for their duration, even when they only read; clients opened with `readonly: true` are unaffected.
121 *
122 * @category constructors
123 * @since 4.0.0
124 */
125export const make = (
126 options: SqliteClientConfig
127): Effect.Effect<SqliteClient, never, Scope.Scope | Reactivity.Reactivity> =>
128 Effect.gen(function*() {
129 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
130 const transformRows = options.transformResultNames ?
131 Statement.defaultTransforms(
132 options.transformResultNames
133 ).array :
134 undefined
135
136 const makeConnection = Effect.gen(function*() {
137 const scope = yield* Effect.scope
138 const db = new DatabaseSync(options.filename, {
139 readOnly: options.readonly ?? false,
140 allowExtension: true
141 })
142 yield* Scope.addFinalizer(scope, Effect.sync(() => db.close()))
143 db.enableLoadExtension(false)
144 const busyTimeout = Math.min(
145 MAX_BUSY_TIMEOUT,
146 Math.max(0, Math.round(Duration.toMillis(options.busyTimeout ?? Duration.seconds(5))))
147 )
148 db.exec(`PRAGMA busy_timeout = ${busyTimeout}`)
149
150 if (options.disableWAL !== true) {
151 db.exec("PRAGMA journal_mode = WAL")
152 }
153
154 const prepareCache = yield* Cache.make({
155 capacity: options.prepareCacheSize ?? 200,
156 timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
157 lookup: (sql: string) =>
158 Effect.try({
159 try: () => db.prepare(sql),
160 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to prepare statement", "prepare") })
161 })
162 })
163
164 const runStatement = (
165 statement: StatementSync,
166 params: ReadonlyArray<unknown>,
167 raw: boolean
168 ) =>
169 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
170 const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
171 return Effect.try({
172 try: () => {
173 statement.setReadBigInts(useSafeIntegers)
174 if (statement.columns().length > 0) {
175 return statement.all(...(params as Array<any>)) as ReadonlyArray<any>
176 }
177 const result = statement.run(...(params as Array<any>))
178 return raw ? { changes: result.changes, lastInsertRowid: result.lastInsertRowid } as any : []
179 },
180 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
181 })
182 })
183
184 const runStatementValues = (
185 statement: StatementSync,
186 params: ReadonlyArray<unknown>
187 ) =>
188 Effect.withFiber<ReadonlyArray<ReadonlyArray<unknown>>, SqlError>((fiber) => {
189 const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
190 return Effect.try({
191 try: () => {
192 statement.setReadBigInts(useSafeIntegers)
193 if (statement.columns().length > 0) {
194 return statement.all(...(params as Array<any>)) as unknown as ReadonlyArray<ReadonlyArray<unknown>>
195 }
196 statement.run(...(params as Array<any>))
197 return []
198 },
199 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
200 })
201 })
202
203 const runStatementValuesUnprepared = (
204 statement: StatementSync,
205 params: ReadonlyArray<unknown>
206 ) =>
207 Effect.withFiber<ReadonlyArray<ReadonlyArray<unknown>>, SqlError>((fiber) => {
208 const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
209 return Effect.try({
210 try: () => {
211 statement.setReadBigInts(useSafeIntegers)
212 statement.setReturnArrays(true)
213 if (statement.columns().length > 0) {
214 return statement.all(...(params as Array<any>)) as unknown as ReadonlyArray<ReadonlyArray<unknown>>
215 }
216 statement.run(...(params as Array<any>))
217 return []
218 },
219 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
220 })
221 })
222
223 const run = (
224 sql: string,
225 params: ReadonlyArray<unknown>,
226 raw = false
227 ) =>
228 Effect.flatMap(
229 Cache.get(prepareCache, sql),
230 (s) => runStatement(s, params, raw)
231 )
232
233 const runValues = (
234 sql: string,
235 params: ReadonlyArray<unknown>
236 ) =>
237 Effect.acquireUseRelease(
238 Cache.get(prepareCache, sql),
239 (statement) => {
240 statement.setReturnArrays(true)
241 return runStatementValues(statement, params)
242 },
243 (statement) => Effect.sync(() => statement.setReturnArrays(false))
244 )
245
246 const runValuesUnprepared = (
247 sql: string,
248 params: ReadonlyArray<unknown>
249 ) => runStatementValuesUnprepared(db.prepare(sql), params)
250
251 return identity<SqliteConnection>({
252 execute(sql, params, transformRows) {
253 return transformRows
254 ? Effect.map(run(sql, params), transformRows)
255 : run(sql, params)
256 },
257 executeRaw(sql, params) {
258 return run(sql, params, true)
259 },
260 executeValues(sql, params) {
261 return runValues(sql, params)
262 },
263 executeValuesUnprepared(sql, params) {
264 return runValuesUnprepared(sql, params)
265 },
266 executeUnprepared(sql, params, transformRows) {
267 const effect = runStatement(db.prepare(sql), params ?? [], false)
268 return transformRows ? Effect.map(effect, transformRows) : effect
269 },
270 executeStream(_sql, _params) {
271 return Stream.die("executeStream not implemented")
272 },
273 backup(destination) {
274 return Effect.suspend(() => {
275 let totalPages = 0
276 return Effect.tryPromise({
277 try: () =>
278 backupDatabase(db, destination, {
279 progress: (progress) => {
280 totalPages = progress.totalPages
281 }
282 }).then((pages): BackupMetadata => ({ totalPages: totalPages || pages, remainingPages: 0 })),
283 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to backup database", "backup") })
284 })
285 })
286 },
287 loadExtension(path) {
288 return Effect.acquireUseRelease(
289 Effect.sync(() => db.enableLoadExtension(true)),
290 () =>
291 Effect.try({
292 try: () => db.loadExtension(path),
293 catch: (cause) =>
294 new SqlError({ reason: classifyError(cause, "Failed to load extension", "loadExtension") })
295 }),
296 () => Effect.sync(() => db.enableLoadExtension(false))
297 )
298 }
299 })
300 })
301
302 const semaphore = yield* Semaphore.make(1)
303 const connection = yield* makeConnection
304
305 const acquirer = semaphore.withPermits(1)(Effect.succeed(connection))
306 const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
307 const fiber = Fiber.getCurrent()!
308 const scope = Context.getUnsafe(fiber.context, Scope.Scope)
309 return Effect.as(
310 Effect.tap(
311 restore(semaphore.take(1)),
312 () => Scope.addFinalizer(scope, semaphore.release(1))
313 ),
314 connection
315 )
316 })
317
318 return Object.assign(
319 (yield* Client.make({
320 acquirer,
321 compiler,
322 transactionAcquirer,
323 beginTransaction: "BEGIN IMMEDIATE",
324 spanAttributes: [
325 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
326 [ATTR_DB_SYSTEM_NAME, "sqlite"]
327 ],
328 transformRows
329 })) as SqliteClient,
330 {
331 [TypeId]: TypeId as TypeId,
332 config: options,
333 backup: (destination: string) => Effect.flatMap(acquirer, (_) => _.backup(destination)),
334 loadExtension: (path: string) => Effect.flatMap(acquirer, (_) => _.loadExtension(path))
335 }
336 )
337 })
338
339/**
340 * Builds a layer from an Effect `Config` value, providing both the node `SqliteClient` service and the generic `SqlClient` service.
341 *
342 * @category layers
343 * @since 4.0.0
344 */
345export const layerConfig = (
346 config: Config.Wrap<SqliteClientConfig>
347): Layer.Layer<SqliteClient | Client.SqlClient, Config.ConfigError> =>
348 Layer.effectContext(
349 Config.unwrap(config).pipe(
350 Effect.flatMap(make),
351 Effect.map((client) =>
352 Context.make(SqliteClient, client).pipe(
353 Context.add(Client.SqlClient, client)
354 )
355 )
356 )
357 ).pipe(Layer.provide(Reactivity.layer))
358
359/**
360 * Builds a layer from a node SQLite client configuration, providing both `SqliteClient` and the generic `SqlClient` service.
361 *
362 * @category layers
363 * @since 4.0.0
364 */
365export const layer = (
366 config: SqliteClientConfig
367): Layer.Layer<SqliteClient | Client.SqlClient> =>
368 Layer.effectContext(
369 Effect.map(make(config), (client) =>
370 Context.make(SqliteClient, client).pipe(
371 Context.add(Client.SqlClient, client)
372 ))
373 ).pipe(Layer.provide(Reactivity.layer))
374
375// internal
376
377const classifyError = (cause: unknown, message: string, operation: string) =>
378 classifySqliteError(sqliteCauseWithErrno(cause), { message, operation })
379
380const sqliteCauseWithErrno = (cause: unknown): unknown => {
381 if (typeof cause !== "object" || cause === null || !("errcode" in cause) || "errno" in cause) {
382 return cause
383 }
384 const errcode = (cause as { readonly errcode: unknown }).errcode
385 if (typeof errcode !== "number") {
386 return cause
387 }
388 return Object.assign(cause, { errno: errcode })
389}