fix(sql-d1): return typed SqlError when prepare throws on raw and unprepared queries (#10867)

Co-authored-by: Satoru Mikawa <6104306+hyponex@users.noreply.github.com>
This commit is contained in:
effect-bot
2026-11-24 12:19:59 +13:00
committed by GitHub
co-authored by Satoru Mikawa
parent 310a81b391
commit 49d3c99bd8
3 changed files with 36 additions and 7 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"@effect/sql-d1": patch
---
Return a typed `SqlError` instead of dying when `D1Database.prepare()` throws synchronously on `.raw` and `.unprepared` queries.
+9 -7
View File
@@ -228,14 +228,16 @@ export const make = (
const makeConnection = Effect.gen(function*() {
const db = options.db
const prepare = (sql: string) =>
Effect.try({
try: () => db.prepare(sql),
catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to prepare statement", "prepare") })
})
const prepareCache = yield* Cache.make({
capacity: options.prepareCacheSize ?? 200,
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
lookup: (sql: string) =>
Effect.try({
try: () => db.prepare(sql),
catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to prepare statement", "prepare") })
})
lookup: prepare
})
const runStatementRaw = (
@@ -262,7 +264,7 @@ export const make = (
const runRaw = (
sql: string,
params: ReadonlyArray<unknown> = []
) => runStatementRaw(db.prepare(sql), params)
) => Effect.flatMap(prepare(sql), (s) => runStatementRaw(s, params))
const runCached = (
sql: string,
@@ -272,7 +274,7 @@ export const make = (
const runUncached = (
sql: string,
params: ReadonlyArray<unknown> = []
) => runStatement(db.prepare(sql), params)
) => Effect.flatMap(prepare(sql), (s) => runStatement(s, params))
const runValues = (
sql: string,
+22
View File
@@ -40,6 +40,28 @@ describe("Client", { concurrent: false, timeout: 30_000 }, () => {
Effect.provide(Reactivity.layer)
))
it.effect("fails with SqlError when prepare throws on raw and unprepared queries", () =>
Effect.gen(function*() {
const cause = new Error("prepare failed")
const failingDb = {
prepare: () => {
throw cause
}
} as any
const client = yield* D1Client.make({ db: failingDb })
for (const query of [client`SELECT 1`.raw, client`SELECT 1`.unprepared]) {
const error = yield* Effect.flip(query)
assert.strictEqual(error.reason._tag, "UnknownError")
assert.strictEqual(error.reason.operation, "prepare")
assert.strictEqual(error.reason.cause, cause)
}
}).pipe(
Effect.scoped,
Effect.provide(Reactivity.layer)
))
it.effect("should handle queries without transactions", () =>
Effect.gen(function*() {
const sql = yield* D1Client.D1Client