From 99093b34c899f348c5618f8d8bdb8e5d29e18820 Mon Sep 17 00:00:00 2001 From: brianc Date: Fri, 4 Feb 2011 19:15:57 -0600 Subject: [PATCH] query events handled by client in simple query scenario --- lib/client.js | 13 +++++++++++-- lib/query.js | 48 ++++++++++++++++++------------------------------ 2 files changed, 29 insertions(+), 32 deletions(-) diff --git a/lib/client.js b/lib/client.js index 58efb31e..ccbc0eb3 100644 --- a/lib/client.js +++ b/lib/client.js @@ -70,6 +70,9 @@ p.connect = function() { //hook up query handling events to connection //after the connection initially becomes ready for queries var ready = function() { + if(self.activeQuery) { + self.activeQuery.handleReadyForQuery(); + } self.readyForQuery = true; this.activeQuery = null; self.pulseQueryQueue(); @@ -85,9 +88,12 @@ p.connect = function() { con.on('commandComplete', function(msg) { self.activeQuery.handleCommandComplete(msg); - }) + }); + + con.on('readyForQuery', function() { + ready(); + }); - con.on('readyForQuery', ready); ready(); }); @@ -95,6 +101,9 @@ p.connect = function() { con.on('error', function(error) { if(!self.activeQuery) { self.emit('error', error); + } else { + self.activeQuery.handleError(error); + self.activeQuery = null; } }); }; diff --git a/lib/query.js b/lib/query.js index 6a02e66b..80a34730 100644 --- a/lib/query.js +++ b/lib/query.js @@ -94,6 +94,24 @@ p.handleCommandComplete = function(msg) { this._result.addCommandComplete(msg); }; +p.handleReadyForQuery = function() { + if(this.callback) { + this.callback(null, this._result); + } + this.emit('end', this._result); +}; + +p.handleError = function(err) { + //if callback supplied do not emit error event as uncaught error + //events will bubble up to node process + if(this.callback) { + this.callback(err) + } else { + this.emit('error', err); + } + this.emit('end'); +}; + p.submit = function(connection) { var self = this; if(this.requiresPreparation()) { @@ -101,36 +119,6 @@ p.submit = function(connection) { } else { connection.query(this.text); } - - var onReadyForQuery = function() { - removeListeners(); - if(self.callback) { - self.callback(null, self._result); - } - self.emit('end', self._result); - }; - - var onError = function(err) { - //remove all listeners - removeListeners(); - if(self.callback) { - self.callback(err); - } else { - self.emit('error', err); - } - self.emit('end'); - }; - - var onDataRow = this.handleDataRow.bind(this); - - var removeListeners = function() { - //remove all listeners - connection.removeListener('readyForQuery', onReadyForQuery); - connection.removeListener('error', onError); - }; - - connection.on('readyForQuery', onReadyForQuery); - connection.on('error', onError); }; p.hasBeenParsed = function(connection) {