Skip to content

Commit 19a2d26

Browse files
committed
Add client#close
Closes brianc#6
1 parent b9fd38d commit 19a2d26

File tree

4 files changed

+52
-1
lines changed

4 files changed

+52
-1
lines changed

README.md

+5
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ Read `rowCount` rows from the cursor instance. The `callback` will be called wh
6565

6666
If the cursor has read to the end of the result sets all subsequent calls to `cursor#read` will return a 0 length array of rows. I'm open to other ways to signal the end of a cursor, but this has worked out well for me so far.
6767

68+
69+
#### cursor#close(function callback(Error err))
70+
71+
Closes the backend portal before itterating through the entire result set. Useful when you want to 'abort' out of a read early but continue to use the same client for other queries after the cursor is finished.
72+
6873
### install
6974

7075
```sh

index.js

+11
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,17 @@ Cursor.prototype.end = function(cb) {
124124
this.connection.stream.once('end', cb)
125125
}
126126

127+
Cursor.prototype.close = function(cb) {
128+
this.connection.close({type: 'P'})
129+
this.connection.sync()
130+
this.state = 'done'
131+
if(cb) {
132+
this.connection.once('closeComplete', function() {
133+
cb()
134+
})
135+
}
136+
}
137+
127138
Cursor.prototype.read = function(rows, cb) {
128139
var self = this
129140
if(this.state == 'idle') {

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"author": "Brian M. Carlson",
1313
"license": "MIT",
1414
"devDependencies": {
15-
"pg.js": "~2.8.1",
15+
"pg.js": "~3.4.4",
1616
"mocha": "~1.17.1"
1717
},
1818
"dependencies": {}

test/close.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
var assert = require('assert')
2+
var Cursor = require('../')
3+
var pg = require('pg.js')
4+
5+
var text = 'SELECT generate_series as num FROM generate_series(0, 50)'
6+
describe('close', function() {
7+
beforeEach(function(done) {
8+
var client = this.client = new pg.Client()
9+
client.connect(done)
10+
client.on('drain', client.end.bind(client))
11+
})
12+
13+
it('closes cursor early', function(done) {
14+
var cursor = new Cursor(text)
15+
this.client.query(cursor)
16+
this.client.query('SELECT NOW()', done)
17+
cursor.read(25, function(err, res) {
18+
assert.ifError(err)
19+
cursor.close()
20+
})
21+
})
22+
23+
it('works with callback style', function(done) {
24+
var cursor = new Cursor(text)
25+
var client = this.client
26+
client.query(cursor)
27+
cursor.read(25, function(err, res) {
28+
assert.ifError(err)
29+
cursor.close(function(err) {
30+
assert.ifError(err)
31+
client.query('SELECT NOW()', done)
32+
})
33+
})
34+
})
35+
})

0 commit comments

Comments
 (0)