| 216 | * @since 4.0.0 |
| 217 | */ |
| 218 | export const make = ( |
| 219 | options: D1ClientConfig |
| 220 | ): Effect.Effect<D1Client & Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> => |
| 221 | Effect.gen(function*() { |
| 222 | const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) |
| 223 | const transformRows = options.transformResultNames ? |
| 224 | Statement.defaultTransforms(options.transformResultNames).array : |
| 225 | undefined |
| 226 | const spanAttributes = Object.entries({ |
| 227 | [ATTR_DB_SYSTEM_NAME]: "sqlite", |
| 228 | ...options.spanAttributes |
| 229 | }) |
| 230 | |
| 231 | const makeConnection = Effect.gen(function*() { |
| 232 | const db = options.db |
| 233 | |
| 234 | const prepare = (sql: string) => |
| 235 | Effect.try({ |
| 236 | try: () => db.prepare(sql), |
| 237 | catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to prepare statement", "prepare") }) |
| 238 | }) |
| 239 | |
| 240 | const prepareCache = yield* Cache.make({ |
| 241 | capacity: options.prepareCacheSize ?? 200, |
| 242 | timeToLive: options.prepareCacheTTL ?? Duration.minutes(10), |
| 243 | lookup: prepare |
| 244 | }) |
| 245 | |
| 246 | const runStatementRaw = ( |
| 247 | statement: D1PreparedStatement, |
| 248 | params: ReadonlyArray<unknown> = [] |
| 249 | ): Effect.Effect<D1Result, SqlError, never> => |
| 250 | Effect.tryPromise({ |
| 251 | try: async () => { |
| 252 | const response = await statement.bind(...params).all() |
| 253 | if (response.error) { |
| 254 | throw response.error |
| 255 | } |
| 256 | return response |
| 257 | }, |
| 258 | catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") }) |
| 259 | }) |
| 260 | |
| 261 | const runStatement = ( |
| 262 | statement: D1PreparedStatement, |
| 263 | params: ReadonlyArray<unknown> = [] |
| 264 | ): Effect.Effect<ReadonlyArray<any>, SqlError, never> => |
| 265 | Effect.map(runStatementRaw(statement, params), (response) => response.results || []) |
| 266 | |
| 267 | const runRaw = ( |
| 268 | sql: string, |
| 269 | params: ReadonlyArray<unknown> = [] |
| 270 | ) => Effect.flatMap(prepare(sql), (s) => runStatementRaw(s, params)) |
| 271 | |
| 272 | const runCached = ( |
| 273 | sql: string, |
| 274 | params: ReadonlyArray<unknown> = [] |
| 275 | ) => Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params)) |