Skip to content

Query settles twice when a parameter fails to serialize (callback gets error, then success with no rows) #3820

Open

Description

@YOGESH256

Versions: pg 8.22.0 and 8.23.1 (master), Node 20.18.0, PostgreSQL 17.5

Since 8.22.0, when a query parameter fails to serialize (a toPostgres() that throws, a BigInt inside a JSON value, a circular object), the query settles twice: once with the error, then again as a success with zero rows.

const { Client } = require('pg')
const client = new Client()
await client.connect()

const bad = { toPostgres() { throw new Error('boom') } }
client.query('select $1::text as v', [bad], (err, res) => {
  console.log(err ? 'err: ' + err.message : 'ok: ' + JSON.stringify(res.rows))
})

Output:

err: boom
ok: []

Same with a named statement, and with pipeline: true. With a Query object the error event is followed by end. The promise API hides it because a promise can only settle once.

Expected: the callback runs once, with the error; no end after error (that is the documented contract, see #590).

Cause: #3574 (shipped in 8.22.0) added connection.close() + connection.sync() in the catch block of Query.prepare so the connection no longer wedges, and then calls this.handleError(err) right away. The query is still the client's active query, so when the server answers the Sync with ReadyForQuery, _handleReadyForQuery calls handleReadyForQuery on it and that is the success callback. The unit test added with #3574 stubs con.sync, so no ReadyForQuery ever arrives there and the second call is not seen.

One side effect in pipeline mode: with a Query object that has no error listener, the emit('error') throws out of _pulsePipelinedQueryQueue after Parse/Close/Sync were written but before the query was pushed to _sentQueryQueue, so the replies have no owner and the client errors with "Received unexpected rowDescription message from backend".

Fix I have working locally: in that catch block, set this._canceledDueToError = err instead of calling handleError immediately. The query then settles once on ReadyForQuery, through the path a failing type parser already uses. The existing throw-in-bind-tests.js needs to emit readyForQuery after the query for the callback to fire. PR coming.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions