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