Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SqliteClient.ts

378 lines13.2 KB

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