Skip to content

Commit c5a1e33

Browse files
Ensure client is defined when catching error (#5943)
Co-authored-by: Tim <[email protected]>
1 parent e88f289 commit c5a1e33

File tree

2 files changed

+31
-14
lines changed

2 files changed

+31
-14
lines changed

.changeset/crazy-walls-wait.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@effect/sql-pg": patch
3+
---
4+
5+
Fix crash when pool.connect fails by ensuring client exists before attaching error handler

packages/sql-pg/src/PgClient.ts

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -315,25 +315,37 @@ export const make = (
315315
const fiber = Option.getOrThrow(Fiber.getCurrentFiber())
316316
const scope = Context.unsafeGet(fiber.currentContext, Scope.Scope)
317317
let cause: Error | undefined = undefined
318+
function onError(cause_: Error) {
319+
cause = cause_
320+
}
318321
pool.connect((err, client, release) => {
319322
if (err) {
320323
resume(Effect.fail(new SqlError({ cause: err, message: "Failed to acquire connection for transaction" })))
321-
} else {
322-
resume(Effect.as(
323-
Scope.addFinalizer(
324-
scope,
325-
Effect.sync(() => {
326-
client!.off("error", onError)
327-
release(cause)
324+
return
325+
} else if (!client) {
326+
resume(
327+
Effect.fail(
328+
new SqlError({
329+
message: "Failed to acquire connection for transaction",
330+
cause: new Error("No client returned")
328331
})
329-
),
330-
client!
331-
))
332-
}
333-
function onError(cause_: Error) {
334-
cause = cause_
332+
)
333+
)
334+
return
335335
}
336-
client!.on("error", onError)
336+
337+
// Else we know we have client defined, so we can proceed with the connection
338+
client.on("error", onError)
339+
resume(Effect.as(
340+
Scope.addFinalizer(
341+
scope,
342+
Effect.sync(() => {
343+
client.off("error", onError)
344+
release(cause)
345+
})
346+
),
347+
client
348+
))
337349
})
338350
})
339351
const reserve = Effect.map(reserveRaw, (client) => new ConnectionImpl(client))

0 commit comments

Comments
 (0)