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 prepare = (sql: string) =>
155 Effect.try({
156 try: () => db.prepare(sql),
157 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to prepare statement", "prepare") })
158 })
159
160 const prepareCache = yield* Cache.make({
161 capacity: options.prepareCacheSize ?? 200,
162 timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
163 lookup: prepare
164 })
165
166 const runStatement = (
167 statement: StatementSync,
168 params: ReadonlyArray<unknown>,
169 raw: boolean
170 ) =>
171 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
172 const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
173 return Effect.try({
174 try: () => {
175 statement.setReadBigInts(useSafeIntegers)
176 if (statement.columns().length > 0) {
177 return statement.all(...(params as Array<any>)) as ReadonlyArray<any>
178 }
179 const result = statement.run(...(params as Array<any>))
180 return raw ? { changes: result.changes, lastInsertRowid: result.lastInsertRowid } as any : []
181 },
182 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
183 })
184 })
185
186 const runStatementValues = (
187 statement: StatementSync,
188 params: ReadonlyArray<unknown>
189 ) =>
190 Effect.withFiber<ReadonlyArray<ReadonlyArray<unknown>>, SqlError>((fiber) => {
191 const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
192 return Effect.try({
193 try: () => {
194 statement.setReadBigInts(useSafeIntegers)
195 if (statement.columns().length > 0) {
196 return statement.all(...(params as Array<any>)) as unknown as ReadonlyArray<ReadonlyArray<unknown>>
197 }
198 statement.run(...(params as Array<any>))
199 return []
200 },
201 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
202 })
203 })
204
205 const runStatementValuesUnprepared = (
206 statement: StatementSync,
207 params: ReadonlyArray<unknown>
208 ) =>
209 Effect.withFiber<ReadonlyArray<ReadonlyArray<unknown>>, SqlError>((fiber) => {
210 const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
211 return Effect.try({
212 try: () => {
213 statement.setReadBigInts(useSafeIntegers)
214 statement.setReturnArrays(true)
215 if (statement.columns().length > 0) {
216 return statement.all(...(params as Array<any>)) as unknown as ReadonlyArray<ReadonlyArray<unknown>>
217 }
218 statement.run(...(params as Array<any>))
219 return []
220 },
221 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
222 })
223 })
224
225 const run = (
226 sql: string,
227 params: ReadonlyArray<unknown>,
228 raw = false
229 ) =>
230 Effect.flatMap(
231 Cache.get(prepareCache, sql),
232 (s) => runStatement(s, params, raw)
233 )
234
235 const runValues = (
236 sql: string,
237 params: ReadonlyArray<unknown>
238 ) =>
239 Effect.acquireUseRelease(
240 Cache.get(prepareCache, sql),
241 (statement) => {
242 statement.setReturnArrays(true)
243 return runStatementValues(statement, params)
244 },
245 (statement) => Effect.sync(() => statement.setReturnArrays(false))
246 )
247
248 const runValuesUnprepared = (
249 sql: string,
250 params: ReadonlyArray<unknown>
251 ) => Effect.flatMap(prepare(sql), (statement) => runStatementValuesUnprepared(statement, params))
252
253 return identity<SqliteConnection>({
254 execute(sql, params, transformRows) {
255 return transformRows
256 ? Effect.map(run(sql, params), transformRows)
257 : run(sql, params)
258 },
259 executeRaw(sql, params) {
260 return run(sql, params, true)
261 },
262 executeValues(sql, params) {
263 return runValues(sql, params)
264 },
265 executeValuesUnprepared(sql, params) {
266 return runValuesUnprepared(sql, params)
267 },
268 executeUnprepared(sql, params, transformRows) {
269 const effect = Effect.flatMap(prepare(sql), (statement) => runStatement(statement, params ?? [], false))
270 return transformRows ? Effect.map(effect, transformRows) : effect
271 },
272 executeStream(_sql, _params) {
273 return Stream.die("executeStream not implemented")
274 },
275 backup(destination) {
276 return Effect.suspend(() => {
277 let totalPages = 0
278 return Effect.tryPromise({
279 try: () =>
280 backupDatabase(db, destination, {
281 progress: (progress) => {
282 totalPages = progress.totalPages
283 }
284 }).then((pages): BackupMetadata => ({ totalPages: totalPages || pages, remainingPages: 0 })),
285 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to backup database", "backup") })
286 })
287 })
288 },
289 loadExtension(path) {
290 return Effect.acquireUseRelease(
291 Effect.sync(() => db.enableLoadExtension(true)),
292 () =>
293 Effect.try({
294 try: () => db.loadExtension(path),
295 catch: (cause) =>
296 new SqlError({ reason: classifyError(cause, "Failed to load extension", "loadExtension") })
297 }),
298 () => Effect.sync(() => db.enableLoadExtension(false))
299 )
300 }
301 })
302 })
303
304 const semaphore = yield* Semaphore.make(1)
305 const connection = yield* makeConnection
306
307 const acquirer = semaphore.withPermits(1)(Effect.succeed(connection))
308 const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
309 const fiber = Fiber.getCurrent()!
310 const scope = Context.getUnsafe(fiber.context, Scope.Scope)
311 return Effect.as(
312 Effect.tap(
313 restore(semaphore.take(1)),
314 () => Scope.addFinalizer(scope, semaphore.release(1))
315 ),
316 connection
317 )
318 })
319
320 return Object.assign(
321 (yield* Client.make({
322 acquirer,
323 compiler,
324 transactionAcquirer,
325 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
326 spanAttributes: [
327 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
328 [ATTR_DB_SYSTEM_NAME, "sqlite"]
329 ],
330 transformRows
331 })) as SqliteClient,
332 {
333 [TypeId]: TypeId as TypeId,
334 config: options,
335 backup: (destination: string) => Effect.flatMap(acquirer, (_) => _.backup(destination)),
336 loadExtension: (path: string) => Effect.flatMap(acquirer, (_) => _.loadExtension(path))
337 }
338 )
339 })
340
341/**
342 * Builds a layer from an Effect `Config` value, providing both the node `SqliteClient` service and the generic `SqlClient` service.
343 *
344 * @category layers
345 * @since 4.0.0
346 */
347export const layerConfig = (
348 config: Config.Wrap<SqliteClientConfig>
349): Layer.Layer<SqliteClient | Client.SqlClient, Config.ConfigError> =>
350 Layer.effectContext(
351 Config.unwrap(config).pipe(
352 Effect.flatMap(make),
353 Effect.map((client) =>
354 Context.make(SqliteClient, client).pipe(
355 Context.add(Client.SqlClient, client)
356 )
357 )
358 )
359 ).pipe(Layer.provide(Reactivity.layer))
360
361/**
362 * Builds a layer from a node SQLite client configuration, providing both `SqliteClient` and the generic `SqlClient` service.
363 *
364 * @category layers
365 * @since 4.0.0
366 */
367export const layer = (
368 config: SqliteClientConfig
369): Layer.Layer<SqliteClient | Client.SqlClient> =>
370 Layer.effectContext(
371 Effect.map(make(config), (client) =>
372 Context.make(SqliteClient, client).pipe(
373 Context.add(Client.SqlClient, client)
374 ))
375 ).pipe(Layer.provide(Reactivity.layer))
376
377// internal
378
379const classifyError = (cause: unknown, message: string, operation: string) =>
380 classifySqliteError(sqliteCauseWithErrno(cause), { message, operation })
381
382const sqliteCauseWithErrno = (cause: unknown): unknown => {
383 if (typeof cause !== "object" || cause === null || !("errcode" in cause) || "errno" in cause) {
384 return cause
385 }
386 const errcode = (cause as { readonly errcode: unknown }).errcode
387 if (typeof errcode !== "number") {
388 return cause
389 }
390 return Object.assign(cause, { errno: errcode })
391}