From 5a6166d0aeef5c38f9772f3105c17a7e30ad34d5 Mon Sep 17 00:00:00 2001 From: "Brian M. Carlson" Date: Thu, 26 Dec 2019 18:36:29 +0000 Subject: [PATCH] Fire close callback when ready for next query Working on fixing some timing issues in pg-query-stream it uncovered an issue where the cursor is firing its 'close' callback before it's actually entirely ready to dispatch another query. This change makes the close callback trigger when the connection re-enters `readyForQuery` state. --- packages/pg-cursor/index.js | 4 ++-- packages/pg-cursor/test/close.js | 8 ++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/pg-cursor/index.js b/packages/pg-cursor/index.js index 405a67129..624877680 100644 --- a/packages/pg-cursor/index.js +++ b/packages/pg-cursor/index.js @@ -6,7 +6,7 @@ const util = require('util') let nextUniqueID = 1 // concept borrowed from org.postgresql.core.v3.QueryExecutorImpl -function Cursor (text, values, config) { +function Cursor(text, values, config) { EventEmitter.call(this) this._conf = config || {} @@ -192,7 +192,7 @@ Cursor.prototype.close = function (cb) { this._closePortal() this.state = 'done' if (cb) { - this.connection.once('closeComplete', function () { + this.connection.once('readyForQuery', function () { cb() }) } diff --git a/packages/pg-cursor/test/close.js b/packages/pg-cursor/test/close.js index 5497c51b2..785a71098 100644 --- a/packages/pg-cursor/test/close.js +++ b/packages/pg-cursor/test/close.js @@ -7,7 +7,10 @@ describe('close', function () { beforeEach(function (done) { const client = (this.client = new pg.Client()) client.connect(done) - client.on('drain', client.end.bind(client)) + }) + + this.afterEach(function (done) { + this.client.end(done) }) it('can close a finished cursor without a callback', function (done) { @@ -34,8 +37,9 @@ describe('close', function () { const cursor = new Cursor(text) const client = this.client client.query(cursor) - cursor.read(25, function (err) { + cursor.read(25, function (err, rows) { assert.ifError(err) + assert.strictEqual(rows.length, 25) cursor.close(function (err) { assert.ifError(err) client.query('SELECT NOW()', done)