| 92 | * @since 1.0.0 |
| 93 | */ |
| 94 | export const make = ( |
| 95 | options: SqliteClientConfig |
| 96 | ): Effect.Effect<SqliteClient, never, Scope.Scope | Reactivity.Reactivity> => |
| 97 | Effect.gen(function*() { |
| 98 | const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) |
| 99 | const transformRows = options.transformResultNames ? |
| 100 | Statement.defaultTransforms( |
| 101 | options.transformResultNames |
| 102 | ).array : |
| 103 | undefined |
| 104 | |
| 105 | const makeConnection = Effect.gen(function*() { |
| 106 | const scope = yield* Effect.scope |
| 107 | const db = new Sqlite(options.filename, { |
| 108 | readonly: options.readonly ?? false |
| 109 | }) |
| 110 | yield* Scope.addFinalizer(scope, Effect.sync(() => db.close())) |
| 111 | |
| 112 | if (options.disableWAL !== true) { |
| 113 | db.pragma("journal_mode = WAL") |
| 114 | } |
| 115 | |
| 116 | const prepareCache = yield* Cache.make({ |
| 117 | capacity: options.prepareCacheSize ?? 200, |
| 118 | timeToLive: options.prepareCacheTTL ?? Duration.minutes(10), |
| 119 | lookup: (sql: string) => |
| 120 | Effect.try({ |
| 121 | try: () => db.prepare(sql), |
| 122 | catch: (cause) => new SqlError({ cause, message: "Failed to prepare statement " }) |
| 123 | }) |
| 124 | }) |
| 125 | |
| 126 | const runStatement = ( |
| 127 | statement: Sqlite.Statement, |
| 128 | params: ReadonlyArray<unknown>, |
| 129 | raw: boolean |
| 130 | ) => |
| 131 | Effect.withFiberRuntime<ReadonlyArray<any>, SqlError>((fiber) => { |
| 132 | if (Context.get(fiber.currentContext, Client.SafeIntegers)) { |
| 133 | statement.safeIntegers(true) |
| 134 | } |
| 135 | try { |
| 136 | if (statement.reader) { |
| 137 | return Effect.succeed(statement.all(...params)) |
| 138 | } |
| 139 | const result = statement.run(...params) |
| 140 | return Effect.succeed(raw ? result as unknown as ReadonlyArray<any> : []) |
| 141 | } catch (cause) { |
| 142 | return Effect.fail(new SqlError({ cause, message: "Failed to execute statement" })) |
| 143 | } |
| 144 | }) |
| 145 | |
| 146 | const run = ( |
| 147 | sql: string, |
| 148 | params: ReadonlyArray<unknown>, |
| 149 | raw = false |
| 150 | ) => |
| 151 | Effect.flatMap( |