From 810b12558139d0231a71b9bc81206490f2a27ef3 Mon Sep 17 00:00:00 2001 From: "Ryan B. Harvey" Date: Mon, 6 Mar 2023 12:32:13 -0600 Subject: [PATCH] Emit a 'release' event when a connection is released back to the pool (#2845) --- packages/pg-pool/index.js | 2 ++ packages/pg-pool/test/events.js | 36 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/packages/pg-pool/index.js b/packages/pg-pool/index.js index 00f55b4da..910aee6d2 100644 --- a/packages/pg-pool/index.js +++ b/packages/pg-pool/index.js @@ -330,6 +330,8 @@ class Pool extends EventEmitter { client._poolUseCount = (client._poolUseCount || 0) + 1 + this.emit('release', err, client) + // TODO(bmc): expose a proper, public interface _queryable and _ending if (err || this.ending || !client._queryable || client._ending || client._poolUseCount >= this.options.maxUses) { if (client._poolUseCount >= this.options.maxUses) { diff --git a/packages/pg-pool/test/events.js b/packages/pg-pool/test/events.js index 61979247d..751b14dbc 100644 --- a/packages/pg-pool/test/events.js +++ b/packages/pg-pool/test/events.js @@ -60,6 +60,42 @@ describe('events', function () { }, 100) }) + it('emits release every time a client is released', function (done) { + const pool = new Pool() + let releaseCount = 0 + pool.on('release', function (err, client) { + expect(err instanceof Error).not.to.be(true) + expect(client).to.be.ok() + releaseCount++ + }) + for (let i = 0; i < 10; i++) { + pool.connect(function (err, client, release) { + if (err) return done(err) + release() + }) + pool.query('SELECT now()') + } + setTimeout(function () { + expect(releaseCount).to.be(20) + pool.end(done) + }, 100) + }) + + it('emits release with an error if client is released due to an error', function (done) { + const pool = new Pool() + pool.connect(function (err, client, release) { + expect(err).to.equal(undefined) + const releaseError = new Error('problem') + pool.once('release', function (err, errClient) { + console.log(err, errClient) + expect(err).to.equal(releaseError) + expect(errClient).to.equal(client) + pool.end(done) + }) + release(releaseError) + }) + }) + it('emits error and client if an idle client in the pool hits an error', function (done) { const pool = new Pool() pool.connect(function (err, client) {