Repository navigation
Description
Versions: pg 8.23.1 (master), Node 20, PostgreSQL 18.
When a parameter of a named prepared statement fails to serialize (a toPostgres() that throws, a BigInt in a JSON value, a circular object), the client closes the statement on the server but keeps the name in its statement cache. Every later query reusing that name then fails with prepared statement "<name>" does not exist (SQLSTATE 26000), permanently, for the life of the connection.
Reproduction
const { Client } = require('pg')
async function main() {
const client = new Client()
await client.connect()
const bad = { toPostgres() { throw new Error('serialize boom') } }
// 1. named statement 'ps1' with a value that fails to serialize
try {
await client.query({ name: 'ps1', text: 'select $1::int as v', values: [bad] })
} catch (e) {
console.log('1. serialization error:', e.message)
}
// 2. reuse the SAME name with a valid value
try {
const r = await client.query({ name: 'ps1', text: 'select $1::int as v', values: [42] })
console.log('2. reuse ok:', JSON.stringify(r.rows))
} catch (e) {
console.log('2. reuse FAILED:', e.message, '| code:', e.code)
}
await client.end()
}
main()Output:
1. serialization error: serialize boom
2. reuse FAILED: prepared statement "ps1" does not exist | code: 26000
The same happens if the name is used successfully first and the serialization error comes later.
Cause
In Query.prepare (packages/pg/lib/query.js), when connection.bind() throws during value serialization, the catch sends connection.close({ type: 'S', name }) + connection.sync() to clean up — added in #3574. But the client's cache is not updated to match:
- First use of the name: the
Parsewas already written beforebind()threw, so the server answersParseComplete, and_handleParseComplete(packages/pg/lib/client.js) recordsconnection.parsedStatements[name] = text— right after theClosedestroyed it on the server. - Reuse of an already-parsed name: no new
Parseis sent, and nothing removes the existingparsedStatements[name]entry, while theClosestill destroys the statement on the server.
Either way hasBeenParsed() returns true on the next use, the client skips Parse and binds to a statement the server no longer has.
Distinct from #3820 (double-settle on the same catch path): that one is about the query settling twice, and its fix (#3835) keeps sending Close + Sync, so this cache poisoning survives it.
Fix
Have the bind-serialization catch drop the name from both statement caches and flag the query so the trailing ParseComplete is not recorded. PR coming.
Activity