Open History to see the last commit
1/**
2 * Connects Effect SQL to SQLite when running on Bun, using `bun: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 to the database, enables
6 * WAL mode unless disabled, and waits up to five seconds for busy databases by
7 * default. Explicit transactions on writable connections use `BEGIN IMMEDIATE`
8 * to avoid read-to-write lock upgrades, which serializes them behind other
9 * writers even when they only read. Clients opened with `readonly: true` are
10 * unaffected. Busy waits block the event loop because `bun:sqlite` is
11 * synchronous. Database export and extension loading are supported; streaming
12 * queries and `updateValues` are not.
13 *
14 * @stability unstable
15 * @since 4.0.0
16 */
17import { constants, Database } from "bun:sqlite"
18import * as Clock from "effect/Clock"
19import * as Config from "effect/Config"
20import * as Context from "effect/Context"
21import * as Duration from "effect/Duration"
22import * as Effect from "effect/Effect"
23import { identity } from "effect/Function"
24import * as Layer from "effect/Layer"
25import * as Reactivity from "effect/reactivity/Reactivity"
26import * as Schedule from "effect/Schedule"
27import type * as Scope from "effect/Scope"
28import * as Semaphore from "effect/Semaphore"
29import * as Client from "effect/sql/SqlClient"
30import type { Connection } from "effect/sql/SqlConnection"
31import { classifySqliteError, SqlError } from "effect/sql/SqlError"
32import * as Statement from "effect/sql/Statement"
33import * as Stream from "effect/Stream"
34
35const ATTR_DB_SYSTEM_NAME = "db.system.name"
36const MAX_BUSY_TIMEOUT = 2_147_483_647
37const NANOS_PER_MILLI = BigInt(1_000_000)
38
39const classifyError = (cause: unknown, message: string, operation: string) =>
40 classifySqliteError(cause, { message, operation })
41
42/**
43 * Runtime type identifier used to mark Bun `SqliteClient` values.
44 *
45 * @stability unstable
46 * @category type IDs
47 * @since 4.0.0
48 */
49export const TypeId: TypeId = "~@effect/sql-sqlite-bun/SqliteClient"
50
51/**
52 * Type-level identifier used to mark Bun `SqliteClient` values.
53 *
54 * @stability unstable
55 * @category type IDs
56 * @since 4.0.0
57 */
58export type TypeId = "~@effect/sql-sqlite-bun/SqliteClient"
59
60/**
61 * Bun SQLite client service, extending `SqlClient` with database export and extension loading helpers. `updateValues` is not supported.
62 *
63 * @stability unstable
64 * @category services
65 * @since 4.0.0
66 */
67export interface SqliteClient extends Client.Base {
68 readonly [TypeId]: TypeId
69 readonly config: SqliteClientConfig
70 readonly export: Effect.Effect<Uint8Array, SqlError>
71 readonly loadExtension: (path: string) => Effect.Effect<void, SqlError>
72
73 /** Not supported in sqlite */
74 readonly updateValues: never
75}
76
77/**
78 * Service tag for the Bun SQLite client service.
79 *
80 * **When to use**
81 *
82 * Use to access or provide a Bun SQLite client through the Effect context.
83 *
84 * @stability unstable
85 * @category services
86 * @since 4.0.0
87 */
88export const SqliteClient = Context.Service<SqliteClient, SqliteClient & Client.SqlClient>(
89 "@effect/sql-sqlite-bun/Client"
90)
91
92/**
93 * Configuration for a Bun SQLite client, including filename, open mode flags, WAL and busy timeout behavior, span attributes, and query/result name transforms.
94 *
95 * @stability unstable
96 * @category models
97 * @since 4.0.0
98 */
99export interface SqliteClientConfig {
100 readonly filename: string
101 readonly readonly?: boolean | undefined
102 readonly create?: boolean | undefined
103 readonly readwrite?: boolean | undefined
104 readonly disableWAL?: boolean | undefined
105 /**
106 * How long SQLite waits when the database is busy. Defaults to 5 seconds.
107 * `Duration.infinity` is clamped to SQLite's maximum timeout.
108 * Waiting blocks the event loop because `bun:sqlite` is synchronous.
109 */
110 readonly busyTimeout?: Duration.Input | undefined
111
112 readonly spanAttributes?: Record<string, unknown> | undefined
113
114 readonly transformResultNames?: ((str: string) => string) | undefined
115 readonly transformQueryNames?: ((str: string) => string) | undefined
116}
117
118interface SqliteConnection extends Connection {
119 readonly isTransaction: () => boolean
120 readonly export: Effect.Effect<Uint8Array, SqlError>
121 readonly loadExtension: (path: string) => Effect.Effect<void, SqlError>
122}
123
124/**
125 * Creates a scoped Bun SQLite client for a database file, enabling WAL and a 5-second busy timeout 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. Streaming queries are not implemented.
126 *
127 * @stability unstable
128 * @category constructors
129 * @since 4.0.0
130 */
131export const make = (
132 options: SqliteClientConfig
133): Effect.Effect<SqliteClient & Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
134 Effect.gen(function*() {
135 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
136 const transformRows = options.transformResultNames ?
137 Statement.defaultTransforms(
138 options.transformResultNames
139 ).array :
140 undefined
141
142 const makeConnection = Effect.gen(function*() {
143 const readonly = options.readonly === true
144 const openOptions = {
145 readonly,
146 readwrite: readonly ? false : options.readwrite ?? true,
147 create: readonly ? false : options.create ?? true
148 }
149 const db = yield* Effect.acquireRelease(
150 Effect.try({
151 try: () =>
152 new Database(
153 options.filename,
154 options.filename.startsWith("file:")
155 ? constants.SQLITE_OPEN_URI |
156 (openOptions.readonly ? constants.SQLITE_OPEN_READONLY : 0) |
157 (openOptions.readwrite || openOptions.create ? constants.SQLITE_OPEN_READWRITE : 0) |
158 (openOptions.create ? constants.SQLITE_OPEN_CREATE : 0)
159 : openOptions
160 ),
161 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to open database", "connect") })
162 }),
163 (db) => Effect.sync(() => db.close())
164 )
165 const busyTimeout = Math.min(
166 MAX_BUSY_TIMEOUT,
167 Math.max(0, Math.round(Duration.toMillis(options.busyTimeout ?? Duration.seconds(5))))
168 )
169 const exec = (sql: string) =>
170 Effect.try({
171 try: () => db.run(sql),
172 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to configure database", "connect") })
173 })
174 yield* exec(`PRAGMA busy_timeout = ${busyTimeout};`)
175
176 if (options.disableWAL !== true && !readonly) {
177 // Switching to WAL can fail with SQLITE_BUSY without invoking the busy
178 // handler, so retry it until busyTimeout has elapsed. Each attempt's
179 // native busy wait is limited to the remaining time.
180 const deadline = (yield* Clock.monotonicTimeNanos) + BigInt(busyTimeout) * NANOS_PER_MILLI
181 const remainingMillis = Effect.map(
182 Clock.monotonicTimeNanos,
183 (now) => Math.max(0, Number((deadline - now) / NANOS_PER_MILLI))
184 )
185 yield* remainingMillis.pipe(
186 Effect.flatMap((remaining) => exec(`PRAGMA busy_timeout = ${remaining}`)),
187 Effect.andThen(exec("PRAGMA journal_mode = WAL;")),
188 Effect.retry({
189 while: (error) =>
190 error.reason._tag === "LockTimeoutError" && Effect.map(remainingMillis, (remaining) => remaining > 0),
191 schedule: Schedule.spaced("10 millis")
192 })
193 )
194 yield* exec(`PRAGMA busy_timeout = ${busyTimeout}`)
195 }
196
197 const prepare = (sql: string, useSafeIntegers: boolean) => {
198 const statement = db.query(sql)
199 // @ts-ignore bun-types missing safeIntegers method, fixed in https://github.com/oven-sh/bun/pull/26627
200 statement.safeIntegers(useSafeIntegers)
201 return statement
202 }
203
204 const run = (
205 sql: string,
206 params: ReadonlyArray<unknown> = []
207 ) =>
208 Effect.withFiber<Array<any>, SqlError>((fiber) => {
209 const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
210 try {
211 return Effect.succeed((prepare(sql, useSafeIntegers).all(...(params as any)) ?? []) as Array<any>)
212 } catch (cause) {
213 return Effect.fail(new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") }))
214 }
215 })
216
217 const runValues = (
218 sql: string,
219 params: ReadonlyArray<unknown> = []
220 ) =>
221 Effect.withFiber<Array<any>, SqlError>((fiber) => {
222 const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
223 try {
224 return Effect.succeed((prepare(sql, useSafeIntegers).values(...(params as any)) ?? []) as Array<any>)
225 } catch (cause) {
226 return Effect.fail(
227 new SqlError({ reason: classifyError(cause, "Failed to execute statement", "executeValues") })
228 )
229 }
230 })
231
232 return identity<SqliteConnection>({
233 isTransaction: () => db.inTransaction,
234 execute(sql, params, transformRows) {
235 return transformRows
236 ? Effect.map(run(sql, params), transformRows)
237 : run(sql, params)
238 },
239 executeRaw(sql, params) {
240 return run(sql, params)
241 },
242 executeValues(sql, params) {
243 return runValues(sql, params)
244 },
245 executeValuesUnprepared(sql, params) {
246 return runValues(sql, params)
247 },
248 executeUnprepared(sql, params, transformRows) {
249 return this.execute(sql, params, transformRows)
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 loadExtension: (path) =>
259 Effect.try({
260 try: () => db.loadExtension(path),
261 catch: (cause) =>
262 new SqlError({ reason: classifyError(cause, "Failed to load extension", "loadExtension") })
263 })
264 })
265 })
266
267 const connection = yield* makeConnection
268 const { acquirer, borrower, isTransaction, onCommitFailure, transactionAcquirer } = Client.makeSqliteAcquirers({
269 connection: Effect.succeed(connection),
270 semaphore: yield* Semaphore.make(1),
271 isTransaction: (conn) => conn.isTransaction()
272 })
273
274 const client: SqliteClient & Client.SqlClient = Object.assign(
275 (yield* Client.make({
276 driver: "sqlite-bun",
277 acquirer,
278 borrower,
279 compiler,
280 transactionAcquirer,
281 onCommitFailure,
282 isTransaction,
283 releaseSavepoint: (name) => `RELEASE SAVEPOINT ${name}`,
284 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
285 spanAttributes: [
286 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
287 [ATTR_DB_SYSTEM_NAME, "sqlite"]
288 ],
289 transformRows
290 })) as SqliteClient & Client.SqlClient,
291 {
292 [TypeId]: TypeId as TypeId,
293 config: options,
294 export: Effect.withFiber((fiber) => {
295 const transaction = Context.getOrUndefined(fiber.context, client.transactionService)
296 return transaction !== undefined
297 ? Effect.andThen(Client.activeTransactionConnection(transaction), connection.export)
298 : Effect.scoped(Effect.flatMap(acquirer, (_) => _.export))
299 }),
300 loadExtension: (path: string) => Effect.scoped(Effect.flatMap(acquirer, (_) => _.loadExtension(path)))
301 }
302 )
303 return client
304 })
305
306/**
307 * Creates a layer from a `Config`-wrapped Bun SQLite client configuration, providing both `SqliteClient` and `SqlClient`.
308 *
309 * @stability unstable
310 * @category layers
311 * @since 4.0.0
312 */
313export const layerConfig = (
314 config: Config.Wrap<SqliteClientConfig>
315): Layer.Layer<SqliteClient | Client.SqlClient, Config.ConfigError | SqlError> =>
316 Layer.effectContext(
317 Config.unwrap(config).pipe(
318 Effect.flatMap(make),
319 Effect.map((client) =>
320 Context.make(SqliteClient, client).pipe(
321 Context.add(Client.SqlClient, client)
322 )
323 )
324 )
325 ).pipe(Layer.provide(Reactivity.layer))
326
327/**
328 * Creates a layer from a concrete Bun SQLite client configuration, providing both `SqliteClient` and `SqlClient`.
329 *
330 * @stability unstable
331 * @category layers
332 * @since 4.0.0
333 */
334export const layer = (
335 config: SqliteClientConfig
336): Layer.Layer<SqliteClient | Client.SqlClient, SqlError> =>
337 Layer.effectContext(
338 Effect.map(make(config), (client) =>
339 Context.make(SqliteClient, client).pipe(
340 Context.add(Client.SqlClient, client)
341 ))
342 ).pipe(Layer.provide(Reactivity.layer))