From 19a2d26fc189cab1676a7a20b22f5085512e63e1 Mon Sep 17 00:00:00 2001 From: "Brian M. Carlson" Date: Wed, 24 Sep 2014 23:42:51 -0400 Subject: [PATCH] Add client#close Closes #6 --- README.md | 5 +++++ index.js | 11 +++++++++++ package.json | 2 +- test/close.js | 35 +++++++++++++++++++++++++++++++++++ 4 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 test/close.js diff --git a/README.md b/README.md index 5263d989..16adc25f 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/index.js b/index.js index 2d8e088b..457d7f6c 100644 --- a/index.js +++ b/index.js @@ -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') { diff --git a/package.json b/package.json index e3c41869..c8c71d4b 100644 --- a/package.json +++ b/package.json @@ -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": {} diff --git a/test/close.js b/test/close.js new file mode 100644 index 00000000..5f4f5bd9 --- /dev/null +++ b/test/close.js @@ -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) + }) + }) + }) +})