Skip to content

Commit acae15d

Browse files
committed
Emit Query Events
This change adds events to the `Cursor` object as per the [Query API](https://github.com/brianc/node-postgres/wiki/Query).
1 parent 42af014 commit acae15d

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

index.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
var Result = require('./pg').Result
22
var prepare = require('./pg').prepareValue
3+
var EventEmitter = require('events').EventEmitter;
4+
var util = require('util');
5+
6+
function Cursor (text, values) {
7+
EventEmitter.call(this);
38

4-
var Cursor = function(text, values) {
59
this.text = text
610
this.values = values ? values.map(prepare) : null
711
this.connection = null
@@ -12,6 +16,8 @@ var Cursor = function(text, values) {
1216
this._rows = null
1317
}
1418

19+
util.inherits(Cursor, EventEmitter)
20+
1521
Cursor.prototype.submit = function(connection) {
1622
this.connection = connection
1723

@@ -58,6 +64,7 @@ Cursor.prototype.handleRowDescription = function(msg) {
5864

5965
Cursor.prototype.handleDataRow = function(msg) {
6066
var row = this._result.parseRow(msg.fields)
67+
this.emit('row', row, this._result)
6168
this._rows.push(row)
6269
}
6370

@@ -87,6 +94,7 @@ Cursor.prototype.handlePortalSuspended = function() {
8794

8895
Cursor.prototype.handleReadyForQuery = function() {
8996
this._sendRows()
97+
this.emit('end', this._result)
9098
this.state = 'done'
9199
}
92100

@@ -107,6 +115,7 @@ Cursor.prototype.handleError = function(msg) {
107115
for(var i = 0; i < this._queue.length; i++) {
108116
this._queue.pop()[1](msg)
109117
}
118+
this.emit('error', msg)
110119
//call sync to keep this connection from hanging
111120
this.connection.sync()
112121
}

test/index.js

+29
Original file line numberDiff line numberDiff line change
@@ -127,4 +127,33 @@ describe('cursor', function() {
127127
done()
128128
})
129129
})
130+
131+
it('emits row events', function(done) {
132+
var cursor = this.pgCursor(text)
133+
cursor.read(10)
134+
cursor.on('row', (row, result) => result.addRow(row))
135+
cursor.on('end', (result) => {
136+
assert.equal(result.rows.length, 6)
137+
done()
138+
})
139+
})
140+
141+
it('emits row events when cursor is closed manually', function(done) {
142+
var cursor = this.pgCursor(text)
143+
cursor.on('row', (row, result) => result.addRow(row))
144+
cursor.on('end', (result) => {
145+
assert.equal(result.rows.length, 3)
146+
done()
147+
})
148+
149+
cursor.read(3, () => cursor.close())
150+
})
151+
152+
it('emits error events', function(done) {
153+
var cursor = this.pgCursor('select asdfasdf')
154+
cursor.on('error', function(err) {
155+
assert(err)
156+
done()
157+
})
158+
})
130159
})

0 commit comments

Comments
 (0)