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 * @stability unstable
16 * @since 4.0.0
17 */
18import * as Cache from "effect/Cache"
19import * as Clock from "effect/Clock"
20import * as Config from "effect/Config"
21import * as Context from "effect/Context"
22import * as Duration from "effect/Duration"
23import * as Effect from "effect/Effect"
24import * as Exit from "effect/Exit"
25import { identity } from "effect/Function"
26import * as Layer from "effect/Layer"
27import * as Reactivity from "effect/reactivity/Reactivity"
28import * as Schedule from "effect/Schedule"
29import type * as Scope from "effect/Scope"
30import * as Semaphore from "effect/Semaphore"
31import * as Client from "effect/sql/SqlClient"
32import type { Connection } from "effect/sql/SqlConnection"
33import { classifySqliteError, SqlError } from "effect/sql/SqlError"
34import * as Statement from "effect/sql/Statement"
35import * as Stream from "effect/Stream"
36import { backup as backupDatabase, DatabaseSync } from "node:sqlite"
37import type { StatementSync } from "node:sqlite"
38
39const ATTR_DB_SYSTEM_NAME = "db.system.name"
40const MAX_BUSY_TIMEOUT = 2_147_483_647
41const NANOS_PER_MILLI = BigInt(1_000_000)
42
43/**
44 * Runtime type identifier used to mark Node `SqliteClient` values.
45 *
46 * @stability unstable
47 * @category type IDs
48 * @since 4.0.0
49 */
50export const TypeId: TypeId = "~@effect/sql-sqlite-node/SqliteClient"
51
52/**
53 * Type-level identifier used to mark Node `SqliteClient` values.
54 *
55 * @stability unstable
56 * @category type IDs
57 * @since 4.0.0
58 */
59export type TypeId = "~@effect/sql-sqlite-node/SqliteClient"
60
61/**
62 * Node SQLite client service, extending `SqlClient` with database export, backup, and extension loading helpers. `updateValues` is not supported.
63 *
64 * @stability unstable
65 * @category services
66 * @since 4.0.0
67 */
68export interface SqliteClient extends Client.Base {
69 readonly [TypeId]: TypeId
70 readonly config: SqliteClientConfig
71 readonly backup: (destination: string) => Effect.Effect<BackupMetadata, SqlError>
72 readonly loadExtension: (path: string) => Effect.Effect<void, SqlError>
73
74 /** Not supported in sqlite */
75 readonly updateValues: never
76}
77
78/**
79 * Metadata returned from a Node SQLite backup operation, reporting total and remaining page counts.
80 *
81 * @stability unstable
82 * @category models
83 * @since 4.0.0
84 */
85export interface BackupMetadata {
86 readonly totalPages: number
87 readonly remainingPages: number
88}
89
90/**
91 * Service tag for the node SQLite client implementation.
92 *
93 * @stability unstable
94 * @category services
95 * @since 4.0.0
96 */
97export const SqliteClient = Context.Service<SqliteClient, SqliteClient & Client.SqlClient>(
98 "@effect/sql-sqlite-node/SqliteClient"
99)
100
101/**
102 * 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.
103 *
104 * @stability unstable
105 * @category models
106 * @since 4.0.0
107 */
108export interface SqliteClientConfig {
109 readonly filename: string
110 readonly readonly?: boolean | undefined
111 readonly prepareCacheSize?: number | undefined
112 readonly prepareCacheTTL?: Duration.Input | undefined
113 readonly disableWAL?: boolean | undefined
114 /**
115 * How long SQLite waits when the database is busy. Defaults to 5 seconds.
116 * `Duration.infinity` is clamped to SQLite's maximum timeout.
117 * Waiting blocks the Node.js event loop because `node:sqlite` is synchronous.
118 */
119 readonly busyTimeout?: Duration.Input | undefined
120 readonly spanAttributes?: Record<string, unknown> | undefined
121
122 readonly transformResultNames?: ((str: string) => string) | undefined
123 readonly transformQueryNames?: ((str: string) => string) | undefined
124}
125
126interface SqliteConnection extends Connection {
127 readonly isTransaction: () => boolean
128 readonly backup: (destination: string) => Effect.Effect<BackupMetadata, SqlError>
129 readonly loadExtension: (path: string) => Effect.Effect<void, SqlError>
130}
131
132/**
133 * 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.
134 *
135 * @stability unstable
136 * @category constructors
137 * @since 4.0.0
138 */
139export const make = (
140 options: SqliteClientConfig
141): Effect.Effect<SqliteClient & Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
142 Effect.gen(function*() {
143 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
144 const transformRows = options.transformResultNames ?
145 Statement.defaultTransforms(
146 options.transformResultNames
147 ).array :
148 undefined
149
150 const makeConnection = Effect.gen(function*() {
151 const db = yield* Effect.acquireRelease(
152 Effect.try({
153 try: () =>
154 new DatabaseSync(options.filename, {
155 readOnly: options.readonly ?? false,
156 allowExtension: true
157 }),
158 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to open database", "connect") })
159 }),
160 (db) => Effect.sync(() => db.close())
161 )
162 setLoadExtensionEnabled(db, false)
163 const busyTimeout = Math.min(
164 MAX_BUSY_TIMEOUT,
165 Math.max(0, Math.round(Duration.toMillis(options.busyTimeout ?? Duration.seconds(5))))
166 )
167 const exec = (sql: string) =>
168 Effect.try({
169 try: () => db.exec(sql),
170 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to configure database", "connect") })
171 })
172 yield* exec(`PRAGMA busy_timeout = ${busyTimeout}`)
173
174 if (options.disableWAL !== true && !options.readonly) {
175 // Switching to WAL can fail with SQLITE_BUSY without invoking the busy
176 // handler, so retry it until busyTimeout has elapsed. Each attempt's
177 // native busy wait is limited to the remaining time.
178 // Deno's `exec` errors omit `errcode`, so run the pragma as a prepared
179 // statement to keep SQLITE_BUSY retryable.
180 const enableWAL = Effect.try({
181 try: () => db.prepare("PRAGMA journal_mode = WAL").get(),
182 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to configure database", "connect") })
183 })
184 const deadline = (yield* Clock.monotonicTimeNanos) + BigInt(busyTimeout) * NANOS_PER_MILLI
185 const remainingMillis = Effect.map(
186 Clock.monotonicTimeNanos,
187 (now) => Math.max(0, Number((deadline - now) / NANOS_PER_MILLI))
188 )
189 yield* remainingMillis.pipe(
190 Effect.flatMap((remaining) => exec(`PRAGMA busy_timeout = ${remaining}`)),
191 Effect.andThen(enableWAL),
192 Effect.retry({
193 while: (error) =>
194 error.reason._tag === "LockTimeoutError" && Effect.map(remainingMillis, (remaining) => remaining > 0),
195 schedule: Schedule.spaced("10 millis")
196 })
197 )
198 yield* exec(`PRAGMA busy_timeout = ${busyTimeout}`)
199 }
200
201 const prepare = (sql: string) =>
202 Effect.try({
203 try: () => db.prepare(sql),
204 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to prepare statement", "prepare") })
205 })
206
207 const prepareCacheTTL = options.prepareCacheTTL ?? Duration.minutes(10)
208 const prepareCache = yield* Cache.makeWith(prepare, {
209 capacity: options.prepareCacheSize ?? 200,
210 timeToLive: (exit) => Exit.isSuccess(exit) ? prepareCacheTTL : Duration.zero
211 })
212
213 const runStatement = (
214 statement: StatementSync,
215 params: ReadonlyArray<unknown>,
216 raw: boolean
217 ) =>
218 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
219 const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
220 return Effect.try({
221 try: () => {
222 statement.setReadBigInts(useSafeIntegers)
223 if (!raw || statement.columns().length > 0) {
224 return statement.all(...(params as Array<any>)) as ReadonlyArray<any>
225 }
226 const result = statement.run(...(params as Array<any>))
227 return { changes: result.changes, lastInsertRowid: result.lastInsertRowid } as any
228 },
229 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
230 })
231 })
232
233 const runStatementValues = (
234 statement: StatementSync,
235 params: ReadonlyArray<unknown>
236 ) =>
237 Effect.withFiber<ReadonlyArray<ReadonlyArray<unknown>>, SqlError>((fiber) => {
238 const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
239 return Effect.try({
240 try: () => {
241 statement.setReadBigInts(useSafeIntegers)
242 return statement.all(...(params as Array<any>)) as unknown as ReadonlyArray<ReadonlyArray<unknown>>
243 },
244 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
245 })
246 })
247
248 const runStatementValuesUnprepared = (
249 statement: StatementSync,
250 params: ReadonlyArray<unknown>
251 ) =>
252 Effect.withFiber<ReadonlyArray<ReadonlyArray<unknown>>, SqlError>((fiber) => {
253 const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
254 return Effect.try({
255 try: () => {
256 statement.setReadBigInts(useSafeIntegers)
257 statement.setReturnArrays(true)
258 return statement.all(...(params as Array<any>)) as unknown as ReadonlyArray<ReadonlyArray<unknown>>
259 },
260 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
261 })
262 })
263
264 const run = (
265 sql: string,
266 params: ReadonlyArray<unknown>,
267 raw = false
268 ) =>
269 Effect.flatMap(
270 Cache.get(prepareCache, sql),
271 (s) => runStatement(s, params, raw)
272 )
273
274 const runValues = (
275 sql: string,
276 params: ReadonlyArray<unknown>
277 ) =>
278 Effect.acquireUseRelease(
279 Cache.get(prepareCache, sql),
280 (statement) => {
281 statement.setReturnArrays(true)
282 return runStatementValues(statement, params)
283 },
284 (statement) => Effect.sync(() => statement.setReturnArrays(false))
285 )
286
287 const runValuesUnprepared = (
288 sql: string,
289 params: ReadonlyArray<unknown>
290 ) => Effect.flatMap(prepare(sql), (statement) => runStatementValuesUnprepared(statement, params))
291
292 return identity<SqliteConnection>({
293 isTransaction: () => db.isTransaction,
294 execute(sql, params, transformRows) {
295 return transformRows
296 ? Effect.map(run(sql, params), transformRows)
297 : run(sql, params)
298 },
299 executeRaw(sql, params) {
300 return run(sql, params, true)
301 },
302 executeValues(sql, params) {
303 return runValues(sql, params)
304 },
305 executeValuesUnprepared(sql, params) {
306 return runValuesUnprepared(sql, params)
307 },
308 executeUnprepared(sql, params, transformRows) {
309 const effect = Effect.flatMap(prepare(sql), (statement) => runStatement(statement, params ?? [], false))
310 return transformRows ? Effect.map(effect, transformRows) : effect
311 },
312 executeStream(_sql, _params) {
313 return Stream.die("executeStream not implemented")
314 },
315 backup(destination) {
316 return Effect.suspend(() => {
317 let totalPages = 0
318 return Effect.tryPromise({
319 try: () =>
320 backupDatabase(db, destination, {
321 progress: (progress) => {
322 totalPages = progress.totalPages
323 }
324 }).then((pages): BackupMetadata => ({ totalPages: totalPages || pages, remainingPages: 0 })),
325 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to backup database", "backup") })
326 })
327 })
328 },
329 loadExtension(path) {
330 return Effect.acquireUseRelease(
331 Effect.sync(() => setLoadExtensionEnabled(db, true)),
332 () =>
333 Effect.try({
334 try: () => db.loadExtension(path),
335 catch: (cause) =>
336 new SqlError({ reason: classifyError(cause, "Failed to load extension", "loadExtension") })
337 }),
338 () => Effect.sync(() => setLoadExtensionEnabled(db, false))
339 )
340 }
341 })
342 })
343
344 const connection = yield* makeConnection
345 const { acquirer, borrower, isTransaction, onCommitFailure, transactionAcquirer } = Client.makeSqliteAcquirers({
346 connection: Effect.succeed(connection),
347 semaphore: yield* Semaphore.make(1),
348 isTransaction: (conn) => conn.isTransaction()
349 })
350
351 return Object.assign(
352 (yield* Client.make({
353 driver: "sqlite-node",
354 acquirer,
355 borrower,
356 compiler,
357 transactionAcquirer,
358 onCommitFailure,
359 isTransaction,
360 releaseSavepoint: (name) => `RELEASE SAVEPOINT ${name}`,
361 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
362 spanAttributes: [
363 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
364 [ATTR_DB_SYSTEM_NAME, "sqlite"]
365 ],
366 transformRows
367 })) as SqliteClient & Client.SqlClient,
368 {
369 [TypeId]: TypeId as TypeId,
370 config: options,
371 backup: (destination: string) => Effect.scoped(Effect.flatMap(acquirer, (_) => _.backup(destination))),
372 loadExtension: (path: string) => Effect.scoped(Effect.flatMap(acquirer, (_) => _.loadExtension(path)))
373 }
374 )
375 })
376
377/**
378 * Builds a layer from an Effect `Config` value, providing both the node `SqliteClient` service and the generic `SqlClient` service.
379 *
380 * @stability unstable
381 * @category layers
382 * @since 4.0.0
383 */
384export const layerConfig = (
385 config: Config.Wrap<SqliteClientConfig>
386): Layer.Layer<SqliteClient | Client.SqlClient, Config.ConfigError | SqlError> =>
387 Layer.effectContext(
388 Config.unwrap(config).pipe(
389 Effect.flatMap(make),
390 Effect.map((client) =>
391 Context.make(SqliteClient, client).pipe(
392 Context.add(Client.SqlClient, client)
393 )
394 )
395 )
396 ).pipe(Layer.provide(Reactivity.layer))
397
398/**
399 * Builds a layer from a node SQLite client configuration, providing both `SqliteClient` and the generic `SqlClient` service.
400 *
401 * @stability unstable
402 * @category layers
403 * @since 4.0.0
404 */
405export const layer = (
406 config: SqliteClientConfig
407): Layer.Layer<SqliteClient | Client.SqlClient, SqlError> =>
408 Layer.effectContext(
409 Effect.map(make(config), (client) =>
410 Context.make(SqliteClient, client).pipe(
411 Context.add(Client.SqlClient, client)
412 ))
413 ).pipe(Layer.provide(Reactivity.layer))
414
415// internal
416
417const classifyError = (cause: unknown, message: string, operation: string) =>
418 classifySqliteError(sqliteCauseWithErrno(cause), { message, operation })
419
420const sqliteCauseWithErrno = (cause: unknown): unknown => {
421 if (typeof cause !== "object" || cause === null || !("errcode" in cause) || "errno" in cause) {
422 return cause
423 }
424 const errcode = (cause as { readonly errcode: unknown }).errcode
425 if (typeof errcode !== "number") {
426 return cause
427 }
428 return Object.assign(cause, { errno: errcode })
429}
430
431// Deno's node:sqlite has no `enableLoadExtension`, so `allowExtension` alone
432// controls extension loading there.
433const setLoadExtensionEnabled = (db: DatabaseSync, enabled: boolean): void => {
434 if (typeof db.enableLoadExtension === "function") {
435 db.enableLoadExtension(enabled)
436 }
437}