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

SqliteClient.ts

383 lines13.0 KB

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