Skip to content

Commit

Permalink
fix: add missing connection error handler in pool, resolving process …
Browse files Browse the repository at this point in the history
…crash

pg-pool requires attaching an error handler to each item checked out off the pool, which will
handle connection-level errors. Without it, the application straight-up crashes whenever the
connection is interrupted (e.g. database failover).

See brianc/node-postgres#1324

Signed-off-by: Quentin Machu <[email protected]>
  • Loading branch information
Quentin-M authored and dhmlau committed Jan 9, 2024
1 parent cf21bd3 commit 86ebae8
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions lib/postgresql.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,16 +80,7 @@ function PostgreSQL(postgresql, settings) {
}
this.clientConfig.Promise = Promise;
this.pg = new postgresql.Pool(this.clientConfig);

if (settings.onError) {
if (settings.onError === 'ignore') {
this.pg.on('error', function(err) {
debug(err);
});
} else {
this.pg.on('error', settings.onError);
}
}
attachErrorHandler(settings, this.pg);

this.settings = settings;
debug('Settings %j', {
Expand All @@ -109,6 +100,18 @@ function PostgreSQL(postgresql, settings) {
});
}

function attachErrorHandler(settings, pg) {
if (settings.onError) {
if (settings.onError === 'ignore') {
pg.on('error', function(err) {
debug(err);
});
} else {
pg.on('error', settings.onError);
}
}
}

// Inherit from loopback-datasource-juggler BaseSQL
util.inherits(PostgreSQL, SqlConnector);

Expand All @@ -125,6 +128,10 @@ PostgreSQL.prototype.multiInsertSupported = true;
PostgreSQL.prototype.connect = function(callback) {
const self = this;
self.pg.connect(function(err, client, releaseCb) {
// pg-pool requires attaching an error handler to each item checked out off the pool,
// which will handle connection-level errors.
// See https://github.com/brianc/node-postgres/issues/1324
attachErrorHandler(self.settings, client);
self.client = client;
process.nextTick(releaseCb);
callback && callback(err, client);
Expand Down Expand Up @@ -194,6 +201,10 @@ PostgreSQL.prototype.executeSQL = function(sql, params, options, callback) {
} else {
self.pg.connect(function(err, connection, releaseCb) {
if (err) return callback(err);
// pg-pool requires attaching an error handler to each item checked out off the pool,
// which will handle connection-level errors.
// See https://github.com/brianc/node-postgres/issues/1324
attachErrorHandler(self.settings, connection);
executeWithConnection(connection, releaseCb);
});
}
Expand Down

0 comments on commit 86ebae8

Please sign in to comment.