| 141 | * @since 4.0.0 |
| 142 | */ |
| 143 | export 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 | ) |