Skip to content


yogesch edited this page May 11, 2016 · 58 revisions


The root pg object returned by require('pg') serves two purposes.
First, it has a reference to the other components of node-postgres:

  1. pg.Client
  2. pg.Query
  3. pg.defaults
  4. pg.pools
  5. pg.types

The second purpose is more important:

pg is an instance of EventEmitter which provides a somewhat native implementation of Client pooling. It has a function to retrieve Client instances from a pool of available clients. You can bypass the pg object all together and create Client objects via their constructor (new pg.Client()); however, each Client represents an open connection to your PostgreSQL server instance, and the initial connection handshake takes many times longer than a single query execution. Also, If you attempt to create and connect more Client objects than supported connections to your PostgreSQL server you will encounter errors. This becomes especially painful if you manually instantiate a new Client object per each http request to a web server. Once you receive more simultaneous requests to your web server than your PostgresSQL server can maintain you will be in a bad it's recommended unless you have a particular case, use the pg object to create pooled clients, build your own client pool implementation, or use


connect([string connectionString], function callback)

connect([object config], function callback)

connect(function callback)

The connect method retrieves a Client from the client pool, or if all pooled clients are busy and the pool is not full, the connect method will create a new client passing its first argument directly to the Client constructor. In either case, your supplied callback will only be called when the Client is ready to issue queries or an error is encountered. The callback will be called once and only once for each invocation of connect.

Calling pg.connect only creates a new pool on the first call and on subsequent calls, it does not create new pools but pulls a connection from the existing pool.

Note: The first parameter passed to connect, either a string or config object (or nothing), currently functions as the key used in pooling clients; therefore, using two different connection strings will result in two separate pools being created. The object, string, or nothing is passed to JSON.stringify for key uniqueness. If nothing is passed you are relying on connection defaults (via environment variables or pg.defaults) then JSON.stringify({}) is used as the key.

note: calling done() on a pooled client will cause it to close after idling for 30 seconds. If you do not call done() the client will never be returned to the pool and you will leak clients. This is mega-bad so always call done()


  • string connectionString
    • a connection string in the format anything://user:password@host:port/database
    • a socket path, like /var/run/postgresql
    • a socket path, with a specific database, like /var/run/postgresql a_db_name
    • a socket connection string socket:/some/path/?db=database_name&encoding=utf8
  • object config
    • an object with user, database, password, port, and host properties as described in Client.
  • 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
      • function done(): done function
        • if there is an error, this will be a NOOP function function() {}
        • a truthy value passed to done() will cause the client to be destroyed and removed from the pool (in most cases you don't want this; see the examples below).


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


Disconnects all idle clients within all active pools, and has all client pools terminate. Any currently open, checked out clients will still need to be returned to the pool before they will be shut down and disconnected.


var pg = require('pg');

pg.connect(function(err, client, done) {

//your process will not exit immediately because the pool is holding open, idle connections to the server

//the pool will dispose of all clients and your process will terminate

cancel(config, client, query)

Cancels the given query.


var pg = require('pg');

pg.connect(conString, function(err, client, done) {
  var query = client.query('SELECT pg_sleep(1)', function(err, result) {
    if(err) {
      // this should print "error: canceling statement due to user request"
      console.error("%s", err);

  setImmediate(function() {
    pg.cancel(client.connectionParameters, client, query);


The pg object has a set of defaults.


The default user to use when connecting via tcp sockets (md5 or plaintext) if a user is not provided to the individual Client instance. Default value is process.env.USER


The default database to use if a database is not provided to the individual Client instance. Default value is process.env.USER


The default password to use when connecting via tcp sockets (md5 or plaintext) if a password is not provided to the individual Client instance and PostgreSQL server requires a password. Default value is null

The default host if a host is not provided to the individual Client instance. Can be a domain name, ip address, or path to unix socket folder. Default value is localhost

Implementation note: currently (v4.4.1, August 2015) the host localhost will connect to a TCP socket instead of Unix sockets for the non-native connector. Explicitly specify a value such as /var/run/postgresql or /tmp to force use of Unix domain sockets.


The default port if a port is not provided to the individual Client instance. In the case of a unix socket, the port becomes the extension to the socket file. Default value is 5432


Whether to try SSL/TLS to connect to server. Default value is false.


Number of rows to return at a time from a prepared statement's portal. 0 will return all rows at once.


Number of unique Client objects to maintain in the pool. Default value is 10. If you want to change the pool size you must modify this value before creating a pool. Example:

var pg = require('pg');
pg.defaults.poolSize = 25;

//pool is created on first call to pg.connect
pg.connect(function(err, client, done) {

pg.defaults.poolSize = 2;
//pool still has a size of 25
pg.connect(function(err, client, done) {

//creating a new pool by using a different connection string
//will create this second pool with a size of 2
pg.connect('other-pool', function(err, client, done) {



Max milliseconds a client can go unused before it is removed from the pool and destroyed. Default value is 30000 (30 seconds)


Frequency to check for idle clients within the client pool. Default value is 1000 (1 second).


Binary result mode, defaults to false


By default fields with type int8 are returned as strings because JavaScript cannot represent 64-bit numbers. In practice this causes a problem generally because the result of a COUNT operation is an int8. Since in reality most of us aren't going to be dealing with giant numbers and it sucks having all your COUNT(*) results come out as strings, you can opt-in to parsing int8 as integers. Just be wary: you will lose data if you are dealing with actual 64bit numbers where more than 32bits are used. You can always specify your own type parsers, but this is a handy shortcut.


'error' : object error, object client

Emitted whenever a pooled client emits an error. An idle client will likely only emit an error when it loses connection to the PostgreSQL server instance, for example when your database crashes (oh no!). The pooled client which emitted the error is automatically removed from the pool and supplied to the callback.

◄ Back (Installation) Next (API - pg.Client) ►

Something went wrong with that request. Please try again.