Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am using node-postgres in my application. I would like to know the best practices that I want to follow to ensure the stable connection.

following is the code I'm using right now,

exports.getAll = function (args, callback) {
helper.client = new pg.Client('tcp://postgres:system6:[email protected]/abc_dev');
helper.client.connect();
helper.client.query('select count(1) as total_records from facilities', function(err,response){
    helper.client.query('select * ,'+response.rows[0].total_records+' as total_records  from facilities', 
        function(err,response){
            callback(response);
            helper.client.end.bind(helper.client);
        });
    });
};

As you can see in the code I'm connecting the DB for every request and disconnect once the query has executed. I have one more idea where I can connect the DB globally only once and execute the query using the opened connection. The code look like

helper.client = new pg.Client('tcp://postgres:system6:[email protected]/abc_dev');
helper.client.connect();

exports.getAll = function (args, callback) {
helper.client.query('select count(1) as total_records from facilities', function(err,response){
    helper.client.query('select * ,'+response.rows[0].total_records+' as total_records  from facilities', 
        function(err,response){
            callback(response);
        });
    });
};

Here the connection never ends. As of my knowledge I am unable to decide which one is best. Please suggest.

Thanks..

share|improve this question
    
Very interesting question. As far as I know a connection on request scope is popular in most languages. However, I'm not sure if it is the same with Node. –  SebastianG Apr 13 '13 at 15:02
add comment

1 Answer

There is an example in the node-postgres wiki. It connects whenever a request is handled:

var server = http.createServer(function(req, res, next) {
  pg.connect(function(err, client, done) {

This is what I think is right, too: Your connection should be in request scope.

share|improve this answer
2  
Since node-postgres uses connection pooling (default pool size is 10 connections), this is a good solution. For modules which don't provide pooling, and actually have to reconnect to the database server each time, it seems a waste of resources and a global connection might work just as well (and faster). –  robertklep Apr 13 '13 at 17:40
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.