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

SqliteClient.ts

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