Skip to content

Commit fe6d5ae

Browse files
author
Christophe Macabiau
committed
query cancellation (libpq native binding)
1 parent 947b53a commit fe6d5ae

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

lib/native/index.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,15 @@ p.query = function(config, values, callback) {
5656
return q;
5757
}
5858

59+
var nativeCancel = p.cancel;
60+
61+
p.cancel = function(client, query) {
62+
if (client._activeQuery == query)
63+
this.connect(nativeCancel.bind(client));
64+
else if (client._queryQueue.indexOf(query) != -1)
65+
client._queryQueue.splice(client._queryQueue.indexOf(query), 1);
66+
};
67+
5968
p._pulseQueryQueue = function(initialConnection) {
6069
if(!this._connected) {
6170
return;
@@ -94,8 +103,8 @@ p.pauseDrain = function() {
94103
};
95104

96105
p.resumeDrain = function() {
97-
if(this._drainPaused > 1) {
98-
this.emit('drain')
106+
if(this._drainPaused > 1) {
107+
this.emit('drain')
99108
};
100109
this._drainPaused = 0;
101110
};

src/binding.cc

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ class Connection : public ObjectWrap {
6969
NODE_SET_PROTOTYPE_METHOD(t, "_sendQueryWithParams", SendQueryWithParams);
7070
NODE_SET_PROTOTYPE_METHOD(t, "_sendPrepare", SendPrepare);
7171
NODE_SET_PROTOTYPE_METHOD(t, "_sendQueryPrepared", SendQueryPrepared);
72+
NODE_SET_PROTOTYPE_METHOD(t, "cancel", Cancel);
7273
NODE_SET_PROTOTYPE_METHOD(t, "end", End);
7374

7475
target->Set(String::NewSymbol("Connection"), t->GetFunction());
@@ -104,6 +105,22 @@ class Connection : public ObjectWrap {
104105
return Undefined();
105106
}
106107

108+
//v8 entry point into Connection#cancel
109+
static Handle<Value>
110+
Cancel(const Arguments& args)
111+
{
112+
HandleScope scope;
113+
Connection *self = ObjectWrap::Unwrap<Connection>(args.This());
114+
115+
bool success = self->Cancel();
116+
if(!success) {
117+
self -> EmitLastError();
118+
self -> DestroyConnection();
119+
}
120+
121+
return Undefined();
122+
}
123+
107124
//v8 entry point into Connection#_sendQuery
108125
static Handle<Value>
109126
SendQuery(const Arguments& args)
@@ -267,6 +284,15 @@ class Connection : public ObjectWrap {
267284
return PQsendQueryPrepared(connection_, name, nParams, paramValues, NULL, NULL, 0);
268285
}
269286

287+
int Cancel()
288+
{
289+
PGcancel* pgCancel = PQgetCancel(connection_);
290+
char errbuf[256];
291+
int result = PQcancel(pgCancel, errbuf, 256);
292+
PQfreeCancel(pgCancel);
293+
return result;
294+
}
295+
270296
//flushes socket
271297
void Flush()
272298
{

0 commit comments

Comments
 (0)