| 84 | * @since 1.0.0 |
| 85 | */ |
| 86 | export const make = ( |
| 87 | options: SqliteClientConfig |
| 88 | ): Effect.Effect<SqliteClient, never, Scope.Scope | Reactivity.Reactivity> => |
| 89 | Effect.gen(function*() { |
| 90 | const clientOptions: Parameters<typeof Sqlite.open>[0] = { |
| 91 | name: options.filename |
| 92 | } |
| 93 | if (options.location) { |
| 94 | clientOptions.location = options.location |
| 95 | } |
| 96 | if (options.encryptionKey) { |
| 97 | clientOptions.encryptionKey = options.encryptionKey |
| 98 | } |
| 99 | |
| 100 | const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) |
| 101 | const transformRows = options.transformResultNames ? |
| 102 | Statement.defaultTransforms(options.transformResultNames).array : |
| 103 | undefined |
| 104 | |
| 105 | const makeConnection = Effect.gen(function*() { |
| 106 | const db = Sqlite.open(clientOptions) |
| 107 | yield* Effect.addFinalizer(() => Effect.sync(() => db.close())) |
| 108 | |
| 109 | const run = ( |
| 110 | sql: string, |
| 111 | params: ReadonlyArray<unknown> = [] |
| 112 | ) => |
| 113 | Effect.withFiberRuntime<Array<any>, SqlError>((fiber) => { |
| 114 | if (fiber.getFiberRef(asyncQuery)) { |
| 115 | return Effect.map( |
| 116 | Effect.tryPromise({ |
| 117 | try: () => db.executeAsync(sql, params as Array<any>), |
| 118 | catch: (cause) => new SqlError({ cause, message: "Failed to execute statement (async)" }) |
| 119 | }), |
| 120 | (result) => result.rows?._array ?? [] |
| 121 | ) |
| 122 | } |
| 123 | return Effect.try({ |
| 124 | try: () => db.execute(sql, params as Array<any>).rows?._array ?? [], |
| 125 | catch: (cause) => new SqlError({ cause, message: "Failed to execute statement" }) |
| 126 | }) |
| 127 | }) |
| 128 | |
| 129 | return identity<SqliteConnection>({ |
| 130 | execute(sql, params, transformRows) { |
| 131 | return transformRows |
| 132 | ? Effect.map(run(sql, params), transformRows) |
| 133 | : run(sql, params) |
| 134 | }, |
| 135 | executeRaw(sql, params) { |
| 136 | return run(sql, params) |
| 137 | }, |
| 138 | executeValues(sql, params) { |
| 139 | return Effect.map(run(sql, params), (results) => { |
| 140 | if (results.length === 0) { |
| 141 | return [] |
| 142 | } |
| 143 | const columns = Object.keys(results[0]) |