Open History to see the last commit
1/**
2 * Connects Effect SQL to SQLite compiled to WebAssembly with
3 * `@effect/wa-sqlite`.
4 *
5 * This module can create an in-memory SQLite database in the current runtime or
6 * connect to a worker-backed database, such as the OPFS worker from
7 * `OpfsWorker`. Both clients are exposed as `SqliteClient` and the generic
8 * Effect SQL client, serialize access, support database import and export, and
9 * can install reactivity hooks from SQLite update notifications. In-memory
10 * clients can stream query rows; worker-backed clients cannot. `updateValues`
11 * is not supported by this driver.
12 *
13 * @since 4.0.0
14 */
15// oxlint-disable-next-line effect/no-import-from-barrel-package
16import * as WaSqlite from "@effect/wa-sqlite"
17import SQLiteESMFactory from "@effect/wa-sqlite/dist/wa-sqlite.mjs"
18import { MemoryVFS } from "@effect/wa-sqlite/src/examples/MemoryVFS.js"
19import * as Config from "effect/Config"
20import * as Context from "effect/Context"
21import * as Deferred from "effect/Deferred"
22import * as Effect from "effect/Effect"
23import * as Exit from "effect/Exit"
24import * as Fiber from "effect/Fiber"
25import { identity } from "effect/Function"
26import * as Layer from "effect/Layer"
27import * as Rec from "effect/Record"
28import * as Scope from "effect/Scope"
29import * as ScopedRef from "effect/ScopedRef"
30import * as Semaphore from "effect/Semaphore"
31import * as Stream from "effect/Stream"
32import * as Reactivity from "effect/unstable/reactivity/Reactivity"
33import * as Client from "effect/unstable/sql/SqlClient"
34import type { Connection } from "effect/unstable/sql/SqlConnection"
35import { classifySqliteError, SqlError } from "effect/unstable/sql/SqlError"
36import * as Statement from "effect/unstable/sql/Statement"
37import type { OpfsWorkerMessage } from "./internal/opfsWorker.ts"
38
39const ATTR_DB_SYSTEM_NAME = "db.system.name"
40
41const classifyError = (cause: unknown, message: string, operation: string) =>
42 classifySqliteError(cause, { message, operation })
43
44/**
45 * Runtime identifier attached to SQLite WASM client values.
46 *
47 * @category type IDs
48 * @since 4.0.0
49 */
50export const TypeId: TypeId = "~@effect/sql-sqlite-wasm/SqliteClient"
51
52/**
53 * Type-level identifier for SQLite WASM client values.
54 *
55 * @category type IDs
56 * @since 4.0.0
57 */
58export type TypeId = "~@effect/sql-sqlite-wasm/SqliteClient"
59
60/**
61 * SQLite WASM client service interface, extending `SqlClient` with database `export` and `import` operations and marking `updateValues` as unsupported for SQLite.
62 *
63 * @category models
64 * @since 4.0.0
65 */
66export interface SqliteClient extends Client.SqlClient {
67 readonly [TypeId]: TypeId
68 readonly config: SqliteClientMemoryConfig
69 readonly export: Effect.Effect<Uint8Array, SqlError>
70 readonly import: (data: Uint8Array) => Effect.Effect<void, SqlError>
71
72 /** Not supported in sqlite */
73 readonly updateValues: never
74}
75
76/**
77 * Service tag for the SQLite WASM client.
78 *
79 * @category services
80 * @since 4.0.0
81 */
82export const SqliteClient = Context.Service<SqliteClient>("@effect/sql-sqlite-wasm/SqliteClient")
83
84/**
85 * Configuration for an in-memory SQLite WASM client, including optional reactivity hooks, span attributes, and query/result name transforms.
86 *
87 * @category models
88 * @since 4.0.0
89 */
90export interface SqliteClientMemoryConfig {
91 readonly installReactivityHooks?: boolean
92 readonly spanAttributes?: Record<string, unknown>
93 readonly transformResultNames?: (str: string) => string
94 readonly transformQueryNames?: (str: string) => string
95}
96
97/**
98 * Configuration for a worker-backed SQLite WASM client, including the scoped worker or message port, optional reactivity hooks, span attributes, and query/result name transforms.
99 *
100 * @category models
101 * @since 4.0.0
102 */
103export interface SqliteClientConfig {
104 readonly worker: Effect.Effect<Worker | SharedWorker | MessagePort, never, Scope.Scope>
105 readonly installReactivityHooks?: boolean
106 readonly spanAttributes?: Record<string, unknown>
107 readonly transformResultNames?: (str: string) => string
108 readonly transformQueryNames?: (str: string) => string
109}
110
111interface SqliteConnection extends Connection {
112 readonly export: Effect.Effect<Uint8Array, SqlError>
113 readonly import: (data: Uint8Array) => Effect.Effect<void, SqlError>
114}
115
116const initModule = Effect.runSync(
117 Effect.cached(Effect.promise(() => SQLiteESMFactory()))
118)
119
120const initEffect = Effect.runSync(
121 Effect.cached(initModule.pipe(Effect.map((module) => WaSqlite.Factory(module))))
122)
123
124const registered = new Set<string>()
125
126/**
127 * Creates a scoped in-memory SQLite WASM client using the memory VFS, serializing access through a semaphore and exposing database `export` and `import` operations.
128 *
129 * @category constructors
130 * @since 4.0.0
131 */
132export const makeMemory = (
133 options: SqliteClientMemoryConfig
134): Effect.Effect<SqliteClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
135 Effect.gen(function*() {
136 const reactivity = yield* Reactivity.Reactivity
137 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
138 const transformRows = options.transformResultNames ?
139 Statement.defaultTransforms(
140 options.transformResultNames
141 ).array :
142 undefined
143
144 const makeConnection = Effect.gen(function*() {
145 const sqlite3 = yield* initEffect
146
147 if (registered.has("memory-vfs") === false) {
148 registered.add("memory-vfs")
149 const module = yield* initModule
150 // @ts-expect-error
151 const vfs = new MemoryVFS("memory-vfs", module)
152 sqlite3.vfs_register(vfs as any, false)
153 }
154 const db = yield* Effect.acquireRelease(
155 Effect.try({
156 try: () => sqlite3.open_v2(":memory:", undefined, "memory-vfs"),
157 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to open database", "openDatabase") })
158 }),
159 (db) => Effect.sync(() => sqlite3.close(db))
160 )
161
162 if (options.installReactivityHooks) {
163 sqlite3.update_hook(db, (_op, _db, table, rowid) => {
164 if (!table) return
165 const id = String(Number(rowid))
166 reactivity.invalidateUnsafe({ [table]: [id] })
167 })
168 }
169
170 const run = (
171 sql: string,
172 params: ReadonlyArray<unknown> = [],
173 rowMode: "object" | "array" = "object"
174 ) =>
175 Effect.try({
176 try: () => {
177 const results: Array<any> = []
178 for (const stmt of sqlite3.statements(db, sql)) {
179 let columns: Array<string> | undefined
180 sqlite3.bind_collection(stmt, params as any)
181 while (sqlite3.step(stmt) === WaSqlite.SQLITE_ROW) {
182 columns = columns ?? sqlite3.column_names(stmt)
183 const row = sqlite3.row(stmt)
184 if (rowMode === "object") {
185 const obj: Record<string, any> = {}
186 for (let i = 0; i < columns.length; i++) {
187 Rec.assignProperty(obj, columns[i], row[i])
188 }
189 results.push(obj)
190 } else {
191 results.push(row)
192 }
193 }
194 }
195 return results
196 },
197 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
198 })
199
200 return identity<SqliteConnection>({
201 execute(sql, params, transformRows) {
202 return transformRows
203 ? Effect.map(run(sql, params), transformRows)
204 : run(sql, params)
205 },
206 executeRaw(sql, params) {
207 return run(sql, params)
208 },
209 executeValues(sql, params) {
210 return run(sql, params, "array")
211 },
212 executeValuesUnprepared(sql, params) {
213 return run(sql, params, "array")
214 },
215 executeUnprepared(sql, params, transformRows) {
216 return this.execute(sql, params, transformRows)
217 },
218 executeStream(sql, params, transformRows) {
219 function* stream() {
220 for (const stmt of sqlite3.statements(db, sql)) {
221 let columns: Array<string> | undefined
222 sqlite3.bind_collection(stmt, params as any)
223 while (sqlite3.step(stmt) === WaSqlite.SQLITE_ROW) {
224 columns = columns ?? sqlite3.column_names(stmt)
225 const row = sqlite3.row(stmt)
226 const obj: Record<string, any> = {}
227 for (let i = 0; i < columns.length; i++) {
228 Rec.assignProperty(obj, columns[i], row[i])
229 }
230 yield obj
231 }
232 }
233 }
234 return Stream.suspend(() => Stream.fromIteratorSucceed(stream()[Symbol.iterator]())).pipe(
235 transformRows
236 ? Stream.mapArray((chunk) => transformRows(chunk) as any)
237 : identity,
238 Stream.mapError((cause) =>
239 new SqlError({ reason: classifyError(cause, "Failed to execute statement", "stream") })
240 )
241 )
242 },
243 export: Effect.try({
244 try: () => sqlite3.serialize(db, "main"),
245 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to export database", "export") })
246 }),
247 import(data) {
248 return Effect.try({
249 try: () => sqlite3.deserialize(db, "main", data, data.length, data.length, 1 | 2),
250 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to import database", "import") })
251 })
252 }
253 })
254 })
255
256 const semaphore = yield* Semaphore.make(1)
257 const connection = yield* makeConnection
258
259 const acquirer = semaphore.withPermits(1)(Effect.succeed(connection))
260 const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
261 const fiber = Fiber.getCurrent()!
262 const scope = Context.getUnsafe(fiber.context, Scope.Scope)
263 return Effect.as(
264 Effect.tap(
265 restore(semaphore.take(1)),
266 () => Scope.addFinalizer(scope, semaphore.release(1))
267 ),
268 connection
269 )
270 })
271
272 return Object.assign(
273 (yield* Client.make({
274 acquirer,
275 compiler,
276 transactionAcquirer,
277 spanAttributes: [
278 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
279 [ATTR_DB_SYSTEM_NAME, "sqlite"]
280 ],
281 transformRows
282 })) as SqliteClient,
283 {
284 [TypeId]: TypeId as TypeId,
285 config: options,
286 export: semaphore.withPermits(1)(connection.export),
287 import(data: Uint8Array) {
288 return semaphore.withPermits(1)(connection.import(data))
289 }
290 }
291 )
292 })
293
294/**
295 * Creates a scoped worker-backed SQLite WASM client, communicating with the configured worker or message port, restarting the scoped connection on worker errors, and exposing database `export` and `import` operations.
296 *
297 * @category constructors
298 * @since 4.0.0
299 */
300export const make = (
301 options: SqliteClientConfig
302): Effect.Effect<SqliteClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
303 Effect.gen(function*() {
304 const reactivity = yield* Reactivity.Reactivity
305 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
306 const transformRows = options.transformResultNames ?
307 Statement.defaultTransforms(options.transformResultNames).array :
308 undefined
309 const pending = new Map<number, (effect: Exit.Exit<any, SqlError>) => void>()
310
311 const makeConnection = Effect.gen(function*() {
312 let currentId = 0
313 const scope = yield* Effect.scope
314 const readyDeferred = yield* Deferred.make<void>()
315
316 const worker = yield* options.worker
317 const port = "port" in worker ? worker.port : worker
318 const postMessage = (message: OpfsWorkerMessage, transferables?: ReadonlyArray<any>) =>
319 port.postMessage(message, transferables as any)
320
321 yield* Scope.addFinalizer(scope, Effect.sync(() => postMessage(["close"])))
322
323 const onMessage = (event: any) => {
324 const [id, error, results] = event.data
325 if (id === "ready") {
326 Deferred.doneUnsafe(readyDeferred, Exit.void)
327 return
328 } else if (id === "update_hook") {
329 reactivity.invalidateUnsafe({ [error]: [results] })
330 return
331 } else {
332 const resume = pending.get(id)
333 if (!resume) return
334 pending.delete(id)
335 if (error) {
336 resume(
337 Exit.fail(
338 new SqlError({ reason: classifyError(error as string, "Failed to execute statement", "execute") })
339 )
340 )
341 } else {
342 resume(Exit.succeed(results))
343 }
344 }
345 }
346 port.addEventListener("message", onMessage)
347
348 function onError() {
349 Effect.runFork(ScopedRef.set(connectionRef, makeConnection))
350 }
351 if ("onerror" in worker) {
352 worker.addEventListener("error", onError)
353 }
354
355 yield* Scope.addFinalizer(
356 scope,
357 Effect.sync(() => {
358 worker.removeEventListener("message", onMessage)
359 worker.removeEventListener("error", onError)
360 })
361 )
362
363 yield* Deferred.await(readyDeferred)
364
365 if (options.installReactivityHooks) {
366 postMessage(["update_hook"])
367 }
368
369 const send = (id: number, message: OpfsWorkerMessage, transferables?: ReadonlyArray<any>) =>
370 Effect.callback<any, SqlError>((resume) => {
371 pending.set(id, resume)
372 postMessage(message, transferables)
373 })
374
375 const run = (
376 sql: string,
377 params: ReadonlyArray<unknown> = [],
378 rowMode: "object" | "array" = "object"
379 ): Effect.Effect<Array<any>, SqlError, never> => {
380 const rows = Effect.withFiber<[Array<string>, Array<any>], SqlError>((fiber) => {
381 const id = currentId++
382 return send(id, [id, sql, params], fiber.getRef(Transferables))
383 })
384 return rowMode === "object"
385 ? Effect.map(rows, extractObject)
386 : Effect.map(rows, extractRows)
387 }
388
389 return identity<SqliteConnection>({
390 execute(sql, params, transformRows) {
391 return transformRows
392 ? Effect.map(run(sql, params), transformRows)
393 : run(sql, params)
394 },
395 executeRaw(sql, params) {
396 return run(sql, params)
397 },
398 executeValues(sql, params) {
399 return run(sql, params, "array")
400 },
401 executeValuesUnprepared(sql, params) {
402 return run(sql, params, "array")
403 },
404 executeUnprepared(sql, params, transformRows) {
405 return this.execute(sql, params, transformRows)
406 },
407 executeStream() {
408 return Stream.die("executeStream not implemented")
409 },
410 export: Effect.suspend(() => {
411 const id = currentId++
412 return send(id, ["export", id])
413 }),
414 import(data) {
415 return Effect.suspend(() => {
416 const id = currentId++
417 return send(id, ["import", id, data], [data.buffer])
418 })
419 }
420 })
421 })
422
423 const connectionRef = yield* ScopedRef.fromAcquire(makeConnection)
424
425 const semaphore = yield* Semaphore.make(1)
426 const acquirer = semaphore.withPermits(1)(ScopedRef.get(connectionRef))
427 const transactionAcquirer = Effect.uninterruptibleMask(Effect.fnUntraced(function*(restore) {
428 const fiber = Fiber.getCurrent()!
429 const scope = Context.getUnsafe(fiber.context, Scope.Scope)
430 yield* restore(semaphore.take(1))
431 yield* Scope.addFinalizer(scope, semaphore.release(1))
432 return yield* ScopedRef.get(connectionRef)
433 }))
434
435 return Object.assign(
436 (yield* Client.make({
437 acquirer,
438 compiler,
439 transactionAcquirer,
440 spanAttributes: [
441 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
442 [ATTR_DB_SYSTEM_NAME, "sqlite"]
443 ],
444 transformRows
445 })) as SqliteClient,
446 {
447 [TypeId]: TypeId as TypeId,
448 config: options,
449 export: Effect.flatMap(acquirer, (connection) => connection.export),
450 import(data: Uint8Array) {
451 return Effect.flatMap(acquirer, (connection) => connection.import(data))
452 }
453 }
454 )
455 })
456
457function rowToObject(columns: Array<string>, row: Array<any>) {
458 const obj: Record<string, any> = {}
459 for (let i = 0; i < columns.length; i++) {
460 Rec.assignProperty(obj, columns[i], row[i])
461 }
462 return obj
463}
464const extractObject = (rows: [Array<string>, Array<any>]) => rows[1].map((row) => rowToObject(rows[0], row))
465const extractRows = (rows: [Array<string>, Array<any>]) => rows[1]
466
467/**
468 * Fiber reference that stores transferables to include with worker-backed SQLite WASM query messages.
469 *
470 * @category transferables
471 * @since 4.0.0
472 */
473export const Transferables = Context.Reference<ReadonlyArray<Transferable>>(
474 "@effect/sql-sqlite-wasm/currentTransferables",
475 { defaultValue: () => [] }
476)
477
478/**
479 * Runs an effect with the supplied transferables attached to worker-backed SQLite WASM query messages.
480 *
481 * @category transferables
482 * @since 4.0.0
483 */
484export const withTransferables =
485 (transferables: ReadonlyArray<Transferable>) => <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
486 Effect.provideService(effect, Transferables, transferables)
487
488/**
489 * Builds a layer from an Effect `Config` value, providing both the in-memory SQLite WASM `SqliteClient` service and the generic `SqlClient` service.
490 *
491 * @category layers
492 * @since 4.0.0
493 */
494export const layerMemoryConfig = (
495 config: Config.Wrap<SqliteClientMemoryConfig>
496): Layer.Layer<SqliteClient | Client.SqlClient, Config.ConfigError | SqlError> =>
497 Layer.effectContext(
498 Config.unwrap(config).pipe(
499 Effect.flatMap(makeMemory),
500 Effect.map((client) =>
501 Context.make(SqliteClient, client).pipe(
502 Context.add(Client.SqlClient, client)
503 )
504 )
505 )
506 ).pipe(Layer.provide(Reactivity.layer))
507
508/**
509 * Builds a layer from an in-memory SQLite WASM client configuration, providing both `SqliteClient` and the generic `SqlClient` service.
510 *
511 * @category layers
512 * @since 4.0.0
513 */
514export const layerMemory = (
515 config: SqliteClientMemoryConfig
516): Layer.Layer<SqliteClient | Client.SqlClient, SqlError> =>
517 Layer.effectContext(
518 Effect.map(makeMemory(config), (client) =>
519 Context.make(SqliteClient, client).pipe(
520 Context.add(Client.SqlClient, client)
521 ))
522 ).pipe(Layer.provide(Reactivity.layer))
523
524/**
525 * Builds a layer from a worker-backed SQLite WASM client configuration, providing both `SqliteClient` and the generic `SqlClient` service.
526 *
527 * @category layers
528 * @since 4.0.0
529 */
530export const layer = (
531 config: SqliteClientConfig
532): Layer.Layer<SqliteClient | Client.SqlClient, SqlError> =>
533 Layer.effectContext(
534 Effect.map(make(config), (client) =>
535 Context.make(SqliteClient, client).pipe(
536 Context.add(Client.SqlClient, client)
537 ))
538 ).pipe(Layer.provide(Reactivity.layer))
539
540/**
541 * Builds a layer from an Effect `Config` value, providing both the worker-backed SQLite WASM `SqliteClient` service and the generic `SqlClient` service.
542 *
543 * @category layers
544 * @since 4.0.0
545 */
546export const layerConfig = (
547 config: Config.Wrap<SqliteClientConfig>
548): Layer.Layer<SqliteClient | Client.SqlClient, Config.ConfigError | SqlError> =>
549 Layer.effectContext(
550 Config.unwrap(config).pipe(
551 Effect.flatMap(make),
552 Effect.map((client) =>
553 Context.make(SqliteClient, client).pipe(
554 Context.add(Client.SqlClient, client)
555 )
556 )
557 )
558 ).pipe(Layer.provide(Reactivity.layer))