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

SqliteClient.ts

390 lines13.1 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.map(
184 Effect.tryPromise({
185 try: () => db.executeRaw(sql, params as Array<any>),
186 catch: (cause) =>
187 new SqlError({ reason: classifyError(cause, "Failed to execute statement (async)", "execute") })
188 }),
189 (result) => result.rawRows
190 )
191 }
192 return Effect.try({
193 try: () => db.executeRawSync(sql, params as Array<any>).rawRows,
194 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
195 })
196 })
197​
198 return identity<SqliteConnection>({
199 execute(sql, params, transformRows) {
200 return transformRows
201 ? Effect.map(run(sql, params), transformRows)
202 : run(sql, params)
203 },
204 executeRaw(sql, params) {
205 return run(sql, params)
206 },
207 executeValues(sql, params) {
208 return runValues(sql, params)
209 },
210 executeValuesUnprepared(sql, params) {
211 return runValues(sql, params)
212 },
213 executeUnprepared(sql, params, transformRows) {
214 return this.execute(sql, params, transformRows)
215 },
216 executeStream() {
217 return Stream.die("executeStream not implemented")
218 }
219 })
220 })
221​
222 const semaphore = yield* Semaphore.make(1)
223 const connection = yield* makeConnection
224​
225 const acquirer = semaphore.withPermits(1)(Effect.succeed(connection))
226 const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
227 const fiber = Fiber.getCurrent()!
228 const scope = Context.getUnsafe(fiber.context, Scope.Scope)
229 return Effect.as(
230 Effect.tap(
231 restore(semaphore.take(1)),
232 () => Scope.addFinalizer(scope, semaphore.release(1))
233 ),
234 connection
235 )
236 })
237​
238 return Object.assign(
239 (yield* Client.make({
240 acquirer,
241 compiler,
242 transactionAcquirer,
243 spanAttributes: [
244 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
245 [ATTR_DB_SYSTEM_NAME, "sqlite"]
246 ],
247 transformRows
248 })) as SqliteClient,
249 {
250 [TypeId]: TypeId,
251 config: options
252 }
253 )
254 })
255​
256/**
257 * Builds a layer from an Effect `Config` value, providing both the React Native `SqliteClient` service and the generic `SqlClient` service.
258 *
259 * @category layers
260 * @since 4.0.0
261 */
262export const layerConfig = (
263 config: Config.Wrap<SqliteClientConfig>
264): Layer.Layer<SqliteClient | Client.SqlClient, Config.ConfigError> =>
265 Layer.effectContext(
266 Config.unwrap(config).pipe(
267 Effect.flatMap(make),
268 Effect.map((client) =>
269 Context.make(SqliteClient, client).pipe(
270 Context.add(Client.SqlClient, client)
271 )
272 )
273 )
274 ).pipe(Layer.provide(Reactivity.layer))
275​
276/**
277 * Builds a layer from a React Native SQLite client configuration, providing both `SqliteClient` and the generic `SqlClient` service.
278 *
279 * @category layers
280 * @since 4.0.0
281 */
282export const layer = (
283 config: SqliteClientConfig
284): Layer.Layer<SqliteClient | Client.SqlClient> =>
285 Layer.effectContext(
286 Effect.map(make(config), (client) =>
287 Context.make(SqliteClient, client).pipe(
288 Context.add(Client.SqlClient, client)
289 ))
290 ).pipe(Layer.provide(Reactivity.layer))
291​
292interface DB {
293 close: () => void
294 delete: (location?: string) => void
295 attach: (params: {
296 secondaryDbFileName: string
297 alias: string
298 location?: string
299 }) => void
300 detach: (alias: string) => void
301 /**
302 * Sync version of the execute function
303 * It will block the JS thread and therefore your UI and should be used with caution
304 *
305 * When writing your queries, you can use the ? character as a placeholder for parameters
306 * The parameters will be automatically escaped and sanitized
307 *
308 * Example:
309 * db.executeSync('SELECT * FROM table WHERE id = ?', [1]);
310 *
311 * If you are writing a query that doesn't require parameters, you can omit the second argument
312 *
313 * If you are writing to the database YOU SHOULD BE USING TRANSACTIONS!
314 * Transactions protect you from partial writes and ensure that your data is always in a consistent state
315 */
316 executeSync: (query: string, params?: Array<any>) => QueryResult
317 /**
318 * Basic query execution function, it is async don't forget to await it
319 *
320 * When writing your queries, you can use the ? character as a placeholder for parameters
321 * The parameters will be automatically escaped and sanitized
322 *
323 * Example:
324 * await db.execute('SELECT * FROM table WHERE id = ?', [1]);
325 *
326 * If you are writing a query that doesn't require parameters, you can omit the second argument
327 *
328 * If you are writing to the database YOU SHOULD BE USING TRANSACTIONS!
329 * Transactions protect you from partial writes and ensure that your data is always in a consistent state
330 *
331 * If you need a large amount of queries ran as fast as possible you should be using `executeBatch`, `executeRaw`, `loadFile` or `executeWithHostObjects`
332 */
333 execute: (query: string, params?: Array<any>) => Promise<QueryResult>
334 /**
335 * Loads a runtime loadable sqlite extension. Libsql and iOS embedded version do not support loading extensions
336 */
337 loadExtension: (path: string, entryPoint?: string) => void
338 /**
339 * Same as `execute` except the results are not returned in objects but rather in arrays with just the values and not the keys
340 * It will be faster since a lot of repeated work is skipped and only the values you care about are returned
341 */
342 executeRaw: (query: string, params?: Array<any>) => Promise<RawQueryResult>
343 /**
344 * Same as `executeRaw` but it will block the JS thread and therefore your UI and should be used with caution
345 * It will return an array of arrays with just the values and not the keys
346 */
347 executeRawSync: (query: string, params?: Array<any>) => RawQueryResult
348 /**
349 * Get's the absolute path to the db file. Useful for debugging on local builds and for attaching the DB from users devices
350 */
351 getDbPath: (location?: string) => string
352 /**
353 * Reactive execution of queries when data is written to the database. Check the docs for how to use them.
354 */
355 reactiveExecute: (params: {
356 query: string
357 arguments: Array<any>
358 fireOn: Array<{
359 table: string
360 ids?: Array<number>
361 }>
362 callback: (response: any) => void
363 }) => () => void
364 /** This function is only available for libsql.
365 * Allows to trigger a sync the database with it's remote replica
366 * In order for this function to work you need to use openSync or openRemote functions
367 * with libsql: true in the package.json
368 *
369 * The database is hosted in turso
370 */
371 sync: () => void
373​
374interface RawQueryResult {
375 rawRows: Array<Array<any>>
377​
378interface QueryResult {
379 insertId?: number
380 rowsAffected: number
381 res?: Array<any>
382 rows: Array<Record<string, any>>
383 // An array of intermediate results, just values without column names
384 rawRows?: Array<Array<any>>
385 columnNames?: Array<string>
386 /**
387 * Query metadata, available only for select query results
388 */
389 metadata?: Array<any>