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