Open History to see the last commit
1/**
2 * Connects Effect SQL to SQLite in React Native using
3 * `@op-engineering/op-sqlite`.
4 *
5 * This module opens an on-device SQLite database and exposes it as both
6 * `SqliteClient` and the generic Effect SQL client. It serializes access,
7 * supports normal and value-based queries, and uses the driver's synchronous
8 * query API by default. `AsyncQuery` and `withAsyncQuery` switch a scoped effect
9 * to the driver's asynchronous query API. Streaming queries and `updateValues`
10 * are not supported by this driver.
11 *
12 * @since 4.0.0
13 */
14import * as Sqlite from "@op-engineering/op-sqlite"
15import * as Config from "effect/Config"
16import * as Context from "effect/Context"
17import * as Effect from "effect/Effect"
18import * as Fiber from "effect/Fiber"
19import { constFalse, identity } from "effect/Function"
20import * as Layer from "effect/Layer"
21import * as Scope from "effect/Scope"
22import * as Semaphore from "effect/Semaphore"
23import * as Stream from "effect/Stream"
24import * as Reactivity from "effect/unstable/reactivity/Reactivity"
25import * as Client from "effect/unstable/sql/SqlClient"
26import type { Connection } from "effect/unstable/sql/SqlConnection"
27import { classifySqliteError, SqlError } from "effect/unstable/sql/SqlError"
28import * as Statement from "effect/unstable/sql/Statement"
29
30const ATTR_DB_SYSTEM_NAME = "db.system.name"
31
32const classifyError = (cause: unknown, message: string, operation: string) =>
33 classifySqliteError(cause, { message, operation })
34
35/**
36 * Runtime identifier attached to SQLite React Native client values.
37 *
38 * @category type IDs
39 * @since 4.0.0
40 */
41export const TypeId: TypeId = "~@effect/sql-sqlite-react-native/SqliteClient"
42
43/**
44 * Type-level identifier for SQLite React Native client values.
45 *
46 * @category type IDs
47 * @since 4.0.0
48 */
49export type TypeId = "~@effect/sql-sqlite-react-native/SqliteClient"
50
51/**
52 * React Native SQLite client service interface, extending `SqlClient` with its configuration and marking `updateValues` as unsupported for SQLite.
53 *
54 * @category models
55 * @since 4.0.0
56 */
57export interface SqliteClient extends Client.SqlClient {
58 readonly [TypeId]: TypeId
59 readonly config: SqliteClientConfig
60
61 /** Not supported in sqlite */
62 readonly updateValues: never
63}
64
65/**
66 * Service tag for the React Native SQLite client.
67 *
68 * @category services
69 * @since 4.0.0
70 */
71export const SqliteClient = Context.Service<SqliteClient>("@effect/sql-sqlite-react-native/SqliteClient")
72
73/**
74 * Configuration for a React Native SQLite client, including the database filename, optional location and encryption key, span attributes, and query/result name transforms.
75 *
76 * @category models
77 * @since 4.0.0
78 */
79export interface SqliteClientConfig {
80 readonly filename: string
81 readonly location?: string | undefined
82 readonly encryptionKey?: string | undefined
83 readonly spanAttributes?: Record<string, unknown> | undefined
84 readonly transformResultNames?: ((str: string) => string) | undefined
85 readonly transformQueryNames?: ((str: string) => string) | undefined
86}
87
88/**
89 * Fiber reference that makes the React Native SQLite client run queries through the asynchronous `execute` API instead of `executeSync`.
90 *
91 * **When to use**
92 *
93 * Use to switch React Native SQLite query execution to the asynchronous driver
94 * API for a scoped effect.
95 *
96 * @category fiber refs
97 * @since 4.0.0
98 */
99export const AsyncQuery = Context.Reference<boolean>(
100 "@effect/sql-sqlite-react-native/Client/asyncQuery",
101 { defaultValue: constFalse }
102)
103
104/**
105 * Runs an effect with `AsyncQuery` enabled, causing React Native SQLite queries in that effect to use the asynchronous driver API.
106 *
107 * @category fiber refs
108 * @since 4.0.0
109 */
110export const withAsyncQuery = <R, E, A>(effect: Effect.Effect<A, E, R>) =>
111 Effect.provideService(effect, AsyncQuery, true)
112
113interface SqliteConnection extends Connection {}
114
115/**
116 * Creates a scoped React Native SQLite client from the supplied configuration, using a single serialized connection and honoring `AsyncQuery` for query execution.
117 *
118 * @category constructors
119 * @since 4.0.0
120 */
121export const make = (
122 options: SqliteClientConfig
123): Effect.Effect<SqliteClient, never, Scope.Scope | Reactivity.Reactivity> =>
124 Effect.gen(function*() {
125 const clientOptions: Parameters<typeof Sqlite.open>[0] = {
126 name: options.filename
127 }
128 if (options.location) {
129 clientOptions.location = options.location
130 }
131 if (options.encryptionKey) {
132 clientOptions.encryptionKey = options.encryptionKey
133 }
134
135 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
136 const transformRows = options.transformResultNames ?
137 Statement.defaultTransforms(options.transformResultNames).array :
138 undefined
139
140 const makeConnection = Effect.gen(function*() {
141 const db = Sqlite.open(clientOptions) as DB
142 yield* Effect.addFinalizer(() => Effect.sync(() => db.close()))
143
144 const run = (
145 sql: string,
146 params: ReadonlyArray<unknown> = [],
147 values = false
148 ) =>
149 Effect.withFiber<Array<any>, SqlError>((fiber) => {
150 if (fiber.getRef(AsyncQuery)) {
151 return Effect.map(
152 Effect.tryPromise({
153 try: () => db.execute(sql, params as Array<any>),
154 catch: (cause) =>
155 new SqlError({ reason: classifyError(cause, "Failed to execute statement (async)", "execute") })
156 }),
157 (result) => values ? result.rawRows ?? [] : result.rows
158 )
159 }
160 return Effect.try({
161 try: () => {
162 const result = db.executeSync(sql, params as Array<any>)
163 return values ? result.rawRows ?? [] : result.rows
164 },
165 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
166 })
167 })
168
169 return identity<SqliteConnection>({
170 execute(sql, params, transformRows) {
171 return transformRows
172 ? Effect.map(run(sql, params), transformRows)
173 : run(sql, params)
174 },
175 executeRaw(sql, params) {
176 return run(sql, params)
177 },
178 executeValues(sql, params) {
179 return run(sql, params, true)
180 },
181 executeValuesUnprepared(sql, params) {
182 return run(sql, params, true)
183 },
184 executeUnprepared(sql, params, transformRows) {
185 return this.execute(sql, params, transformRows)
186 },
187 executeStream() {
188 return Stream.die("executeStream not implemented")
189 }
190 })
191 })
192
193 const semaphore = yield* Semaphore.make(1)
194 const connection = yield* makeConnection
195
196 const acquirer = semaphore.withPermits(1)(Effect.succeed(connection))
197 const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
198 const fiber = Fiber.getCurrent()!
199 const scope = Context.getUnsafe(fiber.context, Scope.Scope)
200 return Effect.as(
201 Effect.tap(
202 restore(semaphore.take(1)),
203 () => Scope.addFinalizer(scope, semaphore.release(1))
204 ),
205 connection
206 )
207 })
208
209 return Object.assign(
210 (yield* Client.make({
211 acquirer,
212 compiler,
213 transactionAcquirer,
214 spanAttributes: [
215 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
216 [ATTR_DB_SYSTEM_NAME, "sqlite"]
217 ],
218 transformRows
219 })) as SqliteClient,
220 {
221 [TypeId]: TypeId,
222 config: options
223 }
224 )
225 })
226
227/**
228 * Builds a layer from an Effect `Config` value, providing both the React Native `SqliteClient` service and the generic `SqlClient` service.
229 *
230 * @category layers
231 * @since 4.0.0
232 */
233export const layerConfig = (
234 config: Config.Wrap<SqliteClientConfig>
235): Layer.Layer<SqliteClient | Client.SqlClient, Config.ConfigError> =>
236 Layer.effectContext(
237 Config.unwrap(config).pipe(
238 Effect.flatMap(make),
239 Effect.map((client) =>
240 Context.make(SqliteClient, client).pipe(
241 Context.add(Client.SqlClient, client)
242 )
243 )
244 )
245 ).pipe(Layer.provide(Reactivity.layer))
246
247/**
248 * Builds a layer from a React Native SQLite client configuration, providing both `SqliteClient` and the generic `SqlClient` service.
249 *
250 * @category layers
251 * @since 4.0.0
252 */
253export const layer = (
254 config: SqliteClientConfig
255): Layer.Layer<SqliteClient | Client.SqlClient> =>
256 Layer.effectContext(
257 Effect.map(make(config), (client) =>
258 Context.make(SqliteClient, client).pipe(
259 Context.add(Client.SqlClient, client)
260 ))
261 ).pipe(Layer.provide(Reactivity.layer))
262
263interface DB {
264 close: () => void
265 delete: (location?: string) => void
266 attach: (params: {
267 secondaryDbFileName: string
268 alias: string
269 location?: string
270 }) => void
271 detach: (alias: string) => void
272 /**
273 * Sync version of the execute function
274 * It will block the JS thread and therefore your UI and should be used with caution
275 *
276 * When writing your queries, you can use the ? character as a placeholder for parameters
277 * The parameters will be automatically escaped and sanitized
278 *
279 * Example:
280 * db.executeSync('SELECT * FROM table WHERE id = ?', [1]);
281 *
282 * If you are writing a query that doesn't require parameters, you can omit the second argument
283 *
284 * If you are writing to the database YOU SHOULD BE USING TRANSACTIONS!
285 * Transactions protect you from partial writes and ensure that your data is always in a consistent state
286 */
287 executeSync: (query: string, params?: Array<any>) => QueryResult
288 /**
289 * Basic query execution function, it is async don't forget to await it
290 *
291 * When writing your queries, you can use the ? character as a placeholder for parameters
292 * The parameters will be automatically escaped and sanitized
293 *
294 * Example:
295 * await db.execute('SELECT * FROM table WHERE id = ?', [1]);
296 *
297 * If you are writing a query that doesn't require parameters, you can omit the second argument
298 *
299 * If you are writing to the database YOU SHOULD BE USING TRANSACTIONS!
300 * Transactions protect you from partial writes and ensure that your data is always in a consistent state
301 *
302 * If you need a large amount of queries ran as fast as possible you should be using `executeBatch`, `executeRaw`, `loadFile` or `executeWithHostObjects`
303 */
304 execute: (query: string, params?: Array<any>) => Promise<QueryResult>
305 /**
306 * Loads a runtime loadable sqlite extension. Libsql and iOS embedded version do not support loading extensions
307 */
308 loadExtension: (path: string, entryPoint?: string) => void
309 /**
310 * Same as `execute` except the results are not returned in objects but rather in arrays with just the values and not the keys
311 * It will be faster since a lot of repeated work is skipped and only the values you care about are returned
312 */
313 executeRaw: (query: string, params?: Array<any>) => Promise<Array<any>>
314 /**
315 * Same as `executeRaw` but it will block the JS thread and therefore your UI and should be used with caution
316 * It will return an array of arrays with just the values and not the keys
317 */
318 executeRawSync: (query: string, params?: Array<any>) => Array<any>
319 /**
320 * Get's the absolute path to the db file. Useful for debugging on local builds and for attaching the DB from users devices
321 */
322 getDbPath: (location?: string) => string
323 /**
324 * Reactive execution of queries when data is written to the database. Check the docs for how to use them.
325 */
326 reactiveExecute: (params: {
327 query: string
328 arguments: Array<any>
329 fireOn: Array<{
330 table: string
331 ids?: Array<number>
332 }>
333 callback: (response: any) => void
334 }) => () => void
335 /** This function is only available for libsql.
336 * Allows to trigger a sync the database with it's remote replica
337 * In order for this function to work you need to use openSync or openRemote functions
338 * with libsql: true in the package.json
339 *
340 * The database is hosted in turso
341 */
342 sync: () => void
343}
344
345interface QueryResult {
346 insertId?: number
347 rowsAffected: number
348 res?: Array<any>
349 rows: Array<Record<string, any>>
350 // An array of intermediate results, just values without column names
351 rawRows?: Array<Array<any>>
352 columnNames?: Array<string>
353 /**
354 * Query metadata, available only for select query results
355 */
356 metadata?: Array<any>
357}