The best way to control Claude Code, Codex and more from any computer or phone

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