Skip to content

Commit

Permalink
Ensure transactions throw if connection is closed while there is no a…
Browse files Browse the repository at this point in the history
…ctive query - fixes #658
  • Loading branch information
porsager committed Oct 27, 2023
1 parent ca2754c commit 788c819
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
closedDate = performance.now()
hadError && options.shared.retries++
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
onclose(connection)
onclose(connection, Errors.connection('CONNECTION_CLOSED', options, socket))
}

/* Handlers */
Expand Down
8 changes: 6 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,10 @@ function Postgres(a, b) {

try {
await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
return await scope(connection, fn)
return await Promise.race([
scope(connection, fn),
new Promise((_, reject) => connection.onclose = reject)
])
} catch (error) {
throw error
}
Expand Down Expand Up @@ -414,9 +417,10 @@ function Postgres(a, b) {
: move(c, full)
}

function onclose(c) {
function onclose(c, e) {
move(c, closed)
c.reserved = null
c.onclose && (c.onclose(e), c.onclose = null)
options.onclose && options.onclose(c.id)
queries.length && connect(c, queries.shift())
}
Expand Down
10 changes: 10 additions & 0 deletions tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2348,6 +2348,16 @@ t('Ensure reconnect after max_lifetime with transactions', { timeout: 5 }, async
return [true, true]
})


t('Ensure transactions throw if connection is closed dwhile there is no query', async() => {
const x = await sql.begin(async() => {
setTimeout(() => sql.end({ timeout: 0 }), 10)
await new Promise(r => setTimeout(r, 200))
return sql`select 1`
}).catch(x => x)
return ['CONNECTION_CLOSED', x.code]
})

t('Custom socket', {}, async() => {
let result
const sql = postgres({
Expand Down

0 comments on commit 788c819

Please sign in to comment.