Skip to content
brianc edited this page Dec 20, 2010 · 35 revisions

pg

pg is an small object which provides transparent Client life-cycle management and client pooling.

You're absolutely free to bypass the pg class completely in favor of your own client pool implementation; however, it is very, very not recommended to create an individual, new Client instance for each request to a web server. It will work fine in development but once your web server receives more simultaneous requests than your PostgreSQL server can support, your new Client instances will all emit the error event when they attempt to connect and you will be in...how you say...a world of hurt.

example

    require('pg');
    
    var connectionString = "pg://brian:1234@localhost/postgres"
    pg.connect(connectionString, function(err, client) {
      client.query('SELECT name FROM users WHERE email = $1', ['brian@example.com'], function(err, result) {
        assert.equal('brianc', result.rows[0].name);
      });
    });

Methods

Connect(string connectionString, function callback)

Connect(object config, function callback)

The connect method retrieves a Client from the client pool. If all clients are busy and the pool has available slots, it will create a new client passing the first argument to connect directly to the Client constructor. In either case, the callback will only fire when the Client is ready to issue queries or an error is encountered. The callback will fire once and only once for each invocation of connect. The first parameter passed to connect currently functions as the key used in pooling clients; therefore, using two different connection strings will result in two separate pools being created. this might change in the future if it causes problems. I'm considering creating pools based on a host/database combo from the connection information instead of the entire string or config object

parameters

  • string connectionString
    • a connection string in the format anything://user:password@host:port/database
  • function callback
    • called exactly once for one of the following reasons
      • new client is created and connected to PostgreSQL
      • an existing client is returned to the internal client pool
      • an error is encountered during connection
    • callback parameters
      • object _error: error object
        • if there is no error, this will be null
      • object Client : postgres-node client object ready for queries
        • if there is an error, this object will be null

end(optional string poolKey)

Disconnects all clients within a pool if poolKey is provided, or disconnects all clients in all pools. Not very clean and can potentially interrupt query executions. Primarily used during testing to allow the node process to shutdown after all the tests are executed. I'm currently evaluating routes for cleaning up and shutting down client pools as gracefully as possible.

Clone this wiki locally