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