From 72a012ebf09a9eda5b93d27ca6d2a83dd2ed3998 Mon Sep 17 00:00:00 2001 From: Samuel Reed Date: Tue, 3 Dec 2019 13:27:20 -0500 Subject: [PATCH] fix(pool): synchronously release pool connection Rapidly-fired queries can exhaust the pool capability and lead to odd results. In test, we've witnessed "Connection Terminated" flakiness with many fast test suites. This, combined with setting `lazyConnect: true` and `idleTimeoutMillis: 0`, alleviates the issue. --- lib/postgresql.js | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/lib/postgresql.js b/lib/postgresql.js index 0a538d8f..71b9368b 100644 --- a/lib/postgresql.js +++ b/lib/postgresql.js @@ -40,9 +40,7 @@ exports.initialize = function initializeDataSource(dataSource, callback) { if (callback) { if (dbSettings.lazyConnect) { - process.nextTick(function() { - callback(); - }); + process.nextTick(callback); } else { dataSource.connecting = true; dataSource.connector.connect(callback); @@ -97,9 +95,9 @@ PostgreSQL.prototype.getDefaultSchemaName = function() { */ PostgreSQL.prototype.connect = function(callback) { const self = this; - self.pg.connect(function(err, client, done) { + self.pg.connect(function(err, client, releaseCb) { self.client = client; - process.nextTick(done); + process.nextTick(releaseCb); callback && callback(err, client); }); }; @@ -123,17 +121,13 @@ PostgreSQL.prototype.executeSQL = function(sql, params, options, callback) { debug('SQL: %s', sql); } - function executeWithConnection(connection, done) { + function executeWithConnection(connection, releaseCb) { connection.query(sql, params, function(err, data) { // if(err) console.error(err); if (err) debug(err); if (data) debugData('%j', data); - if (done) { - process.nextTick(function() { - // Release the connection in next tick - done(err); - }); - } + // Release the connection back to the pool. + if (releaseCb) releaseCb(err); let result = null; if (data) { switch (data.command) { @@ -169,9 +163,9 @@ PostgreSQL.prototype.executeSQL = function(sql, params, options, callback) { // Do not release the connection executeWithConnection(transaction.connection, null); } else { - self.pg.connect(function(err, connection, done) { + self.pg.connect(function(err, connection, releaseCb) { if (err) return callback(err); - executeWithConnection(connection, done); + executeWithConnection(connection, releaseCb); }); } };