brianc / node-postgres

PostgreSQL client for node.js.
https://node-postgres.com
MIT License
12.28k stars 1.22k forks source link

pooled client calls drain on dead callback #272

Closed nikravi closed 11 years ago

nikravi commented 11 years ago

Screen Shot 2013-02-19 at 9 50 19 AM Hello, I started using pooled clients, and I see that if the client was started from a pool, used and then returned, after it's reuse, on "drain" the callback of the first function that used the client will be called. Take a look at the following code. Notice that after second refresh in the browser of the "/" page, in the console you'll see the log twice. For a third refresh - you would see three more logs (in total 6 console.log's), etc.

var express = require('express');
var app = express();
var pg = require('pg');

app.get('/', function(req, res){

  pg.connect("tcp://app:appPass@localhost:5432/common", function(err, client) {
    client.query("CREATE TEMP TABLE beatles(name varchar(10), height integer, birthday timestamptz)");

    client.query("INSERT INTO beatles(name, height, birthday) values($1, $2, $3)", ['John', 68, new Date(1944, 10, 13)]);

    client.query({
      name: 'insert beatle',
      text: "INSERT INTO beatles(name, height, birthday) values($1, $2, $3)",
      values: ['John', 70, new Date(1946, 02, 14)]
    });

    var selectQuery = client.query("SELECT * FROM beatles WHERE name = $1", ['John']);

    var str = "";
    selectQuery.on('row', function(row) {
      str += JSON.stringify(row);
    });

    client.query("DROP  TABLE beatles;");

    client.on('drain', function() {

      console.log("client drained", new Date());

      res.send(str);

    });
  })

});

app.listen(9500);
console.log('Listening on port 9500');

As a workaround, I removed my usages of client.on('drain')...

booo commented 11 years ago

Consider using once instead of on.

http://nodejs.org/api/events.html

nikravi commented 11 years ago

That's nice, didn't notice this before :) Thank you! :+1:

booo commented 11 years ago

Please close the ticket if the problem is solved. Thanks.

nikravi commented 11 years ago

Thank you