Skip to content

Commit 788c819

Browse files
committed
Ensure transactions throw if connection is closed while there is no active query - fixes porsager#658
1 parent ca2754c commit 788c819

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

src/connection.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
441441
closedDate = performance.now()
442442
hadError && options.shared.retries++
443443
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
444-
onclose(connection)
444+
onclose(connection, Errors.connection('CONNECTION_CLOSED', options, socket))
445445
}
446446

447447
/* Handlers */

src/index.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,10 @@ function Postgres(a, b) {
239239

240240
try {
241241
await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
242-
return await scope(connection, fn)
242+
return await Promise.race([
243+
scope(connection, fn),
244+
new Promise((_, reject) => connection.onclose = reject)
245+
])
243246
} catch (error) {
244247
throw error
245248
}
@@ -414,9 +417,10 @@ function Postgres(a, b) {
414417
: move(c, full)
415418
}
416419

417-
function onclose(c) {
420+
function onclose(c, e) {
418421
move(c, closed)
419422
c.reserved = null
423+
c.onclose && (c.onclose(e), c.onclose = null)
420424
options.onclose && options.onclose(c.id)
421425
queries.length && connect(c, queries.shift())
422426
}

tests/index.js

+10
Original file line numberDiff line numberDiff line change
@@ -2348,6 +2348,16 @@ t('Ensure reconnect after max_lifetime with transactions', { timeout: 5 }, async
23482348
return [true, true]
23492349
})
23502350

2351+
2352+
t('Ensure transactions throw if connection is closed dwhile there is no query', async() => {
2353+
const x = await sql.begin(async() => {
2354+
setTimeout(() => sql.end({ timeout: 0 }), 10)
2355+
await new Promise(r => setTimeout(r, 200))
2356+
return sql`select 1`
2357+
}).catch(x => x)
2358+
return ['CONNECTION_CLOSED', x.code]
2359+
})
2360+
23512361
t('Custom socket', {}, async() => {
23522362
let result
23532363
const sql = postgres({

0 commit comments

Comments
 (0)