Add client#close

Closes #6
This commit is contained in:
Brian M. Carlson 2014-09-24 23:42:51 -04:00
parent b9fd38df15
commit 19a2d26fc1
4 changed files with 52 additions and 1 deletions

View File

@ -65,6 +65,11 @@ Read `rowCount` rows from the cursor instance. The `callback` will be called wh
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.
#### cursor#close(function callback(Error err))
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.
### install
```sh

View File

@ -124,6 +124,17 @@ Cursor.prototype.end = function(cb) {
this.connection.stream.once('end', cb)
}
Cursor.prototype.close = function(cb) {
this.connection.close({type: 'P'})
this.connection.sync()
this.state = 'done'
if(cb) {
this.connection.once('closeComplete', function() {
cb()
})
}
}
Cursor.prototype.read = function(rows, cb) {
var self = this
if(this.state == 'idle') {

View File

@ -12,7 +12,7 @@
"author": "Brian M. Carlson",
"license": "MIT",
"devDependencies": {
"pg.js": "~2.8.1",
"pg.js": "~3.4.4",
"mocha": "~1.17.1"
},
"dependencies": {}

35
test/close.js Normal file
View File

@ -0,0 +1,35 @@
var assert = require('assert')
var Cursor = require('../')
var pg = require('pg.js')
var text = 'SELECT generate_series as num FROM generate_series(0, 50)'
describe('close', function() {
beforeEach(function(done) {
var client = this.client = new pg.Client()
client.connect(done)
client.on('drain', client.end.bind(client))
})
it('closes cursor early', function(done) {
var cursor = new Cursor(text)
this.client.query(cursor)
this.client.query('SELECT NOW()', done)
cursor.read(25, function(err, res) {
assert.ifError(err)
cursor.close()
})
})
it('works with callback style', function(done) {
var cursor = new Cursor(text)
var client = this.client
client.query(cursor)
cursor.read(25, function(err, res) {
assert.ifError(err)
cursor.close(function(err) {
assert.ifError(err)
client.query('SELECT NOW()', done)
})
})
})
})