node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

client.end() silently exits the node process

Open mdatsev opened this issue 2 years ago • 1 comments

In some cases client.end() silently exits the node process without any error messages.

Could be related to #2691 and #2272, but in those cases, it's a query on an unconnected client. In this case, it's an end() on an unconnected client after creating another client. Here is the minimal code to reproduce the issue:

const pg = require('pg');

;(async function main() {
  try {
    // valid connection, except the database does not exist
    client = new pg.Client({
      database: 'invalid_database'
    });
    await client.connect();  
  } catch (e) {
      // valid connection, and the database exists
      const backupClient = new pg.Client({
        database: 'postgres',
      });
      await backupClient.connect();
      await backupClient.end();

      if (client) {
        const promise = client.end();
        console.log('after promise created');
        await promise;
        console.log('after await');
      }
  }
})();

The output is only

after promise created

Also if the backupClient isn't there, it works fine, which I found confusing too.

version of Node: 18.7.0 version of Postgres: 12.11

mdatsev avatar Aug 19 '22 23:08 mdatsev

Like in the other cases, this is an unfulfilled promise, not client.end() actually exiting the process. If the process has other work, it’ll continue. I would recommend not ending a client that never connected in the first place (you’re in the catch block of a connection attempt, so it’s never successfully connected on this path).

Also if the backupClient isn't there, it works fine, which I found confusing too.

That’s definitely worth looking into, though.

charmander avatar Aug 20 '22 19:08 charmander