| 196 | * @since 4.0.0 |
| 197 | */ |
| 198 | export const make = ( |
| 199 | options: D1ClientConfig |
| 200 | ): Effect.Effect<D1Client, never, Scope.Scope | Reactivity.Reactivity> => |
| 201 | Effect.gen(function*() { |
| 202 | const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) |
| 203 | const transformRows = options.transformResultNames ? |
| 204 | Statement.defaultTransforms(options.transformResultNames).array : |
| 205 | undefined |
| 206 | const spanAttributes: Array<readonly [string, unknown]> = [ |
| 207 | ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), |
| 208 | [ATTR_DB_SYSTEM_NAME, "sqlite"] |
| 209 | ] |
| 210 | |
| 211 | const makeConnection = Effect.gen(function*() { |
| 212 | const db = options.db |
| 213 | |
| 214 | const prepareCache = yield* Cache.make({ |
| 215 | capacity: options.prepareCacheSize ?? 200, |
| 216 | timeToLive: options.prepareCacheTTL ?? Duration.minutes(10), |
| 217 | lookup: (sql: string) => |
| 218 | Effect.try({ |
| 219 | try: () => db.prepare(sql), |
| 220 | catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to prepare statement", "prepare") }) |
| 221 | }) |
| 222 | }) |
| 223 | |
| 224 | const runStatement = ( |
| 225 | statement: D1PreparedStatement, |
| 226 | params: ReadonlyArray<unknown> = [] |
| 227 | ): Effect.Effect<ReadonlyArray<any>, SqlError, never> => |
| 228 | Effect.tryPromise({ |
| 229 | try: async () => { |
| 230 | const response = await statement.bind(...params).all() |
| 231 | if (response.error) { |
| 232 | throw response.error |
| 233 | } |
| 234 | return response.results || [] |
| 235 | }, |
| 236 | catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") }) |
| 237 | }) |
| 238 | |
| 239 | const runRaw = ( |
| 240 | sql: string, |
| 241 | params: ReadonlyArray<unknown> = [] |
| 242 | ) => runStatement(db.prepare(sql), params) |
| 243 | |
| 244 | const runCached = ( |
| 245 | sql: string, |
| 246 | params: ReadonlyArray<unknown> = [] |
| 247 | ) => Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params)) |
| 248 | |
| 249 | const runUncached = ( |
| 250 | sql: string, |
| 251 | params: ReadonlyArray<unknown> = [] |
| 252 | ) => runRaw(sql, params) |
| 253 | |
| 254 | const runValues = ( |
| 255 | sql: string, |