From 2836c8b64d3162a9a3c3f883dd52d5e3efb993ee Mon Sep 17 00:00:00 2001 From: Brian Carlson Date: Thu, 14 Apr 2011 22:38:55 -0500 Subject: [PATCH] native connection failures gracefully emit error from libpq --- src/binding.cc | 35 +++++++++++++++++++++++---------- test/native/connection-tests.js | 3 ++- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/src/binding.cc b/src/binding.cc index 9bd018f..d840384 100644 --- a/src/binding.cc +++ b/src/binding.cc @@ -103,7 +103,10 @@ public: } String::Utf8Value conninfo(args[0]->ToString()); - self->Connect(*conninfo); + bool success = self->Connect(*conninfo); + if(!success) { + self -> AbortConnection(); + } return Undefined(); } @@ -182,8 +185,8 @@ public: Local jsParams = Local::Cast(args[1]); int len = jsParams->Length(); - - + + char** paramValues = ArgToCStringArray(jsParams); if(!paramValues) { THROW("Unable to allocate char **paramValues from Local of v8 params"); @@ -279,6 +282,22 @@ protected: } } + //aborts connection and returns connection error message + char* AbortConnection() + { + EmitLastError(); + DestroyConnection(); + } + + //safely destroys the connection at most 1 time + void DestroyConnection() + { + if(connection_ != NULL) { + PQfinish(connection_); + connection_ = NULL; + } + } + //initializes initial async connection to postgres via libpq //and hands off control to libev bool Connect(const char* conninfo) @@ -287,22 +306,18 @@ protected: if (!connection_) { LOG("Connection couldn't be created"); - } else { - TRACE("Native connection created"); } if (PQsetnonblocking(connection_, 1) == -1) { LOG("Unable to set connection to non-blocking"); - PQfinish(connection_); - connection_ = NULL; + return false; } ConnStatusType status = PQstatus(connection_); if(CONNECTION_BAD == status) { - PQfinish(connection_); LOG("Bad connection status"); - connection_ = NULL; + return false; } int fd = PQsocket(connection_); @@ -477,7 +492,7 @@ protected: { StopRead(); StopWrite(); - PQfinish(connection_); + DestroyConnection(); } private: diff --git a/test/native/connection-tests.js b/test/native/connection-tests.js index 64a5e37..d418b87 100644 --- a/test/native/connection-tests.js +++ b/test/native/connection-tests.js @@ -3,11 +3,12 @@ var Client = require(__dirname + "/../../lib/native").Client; test('connecting with wrong parameters', function() { var con = new Client("user=asldfkj hostaddr=127.0.0.1 port=5432 dbname=asldkfj"); - con.connect(); assert.emits(con, 'error', function(error) { assert.ok(error != null, "error should not be null"); con.end(); }); + + con.connect(); }); test('connects', function() {