Skip to content

Client Initialization

Ricky Ng-Adam edited this page Apr 25, 2014 · 1 revision

You may want to take actions on a connection basis, such as setting Global User Context (GUC) variables or You can test to see if the client is a "new" connection and take action on a per connection basis by using the Client.poolCount variable. This member variable is incremented every time the client is reused from the pool. The first time a Client is connected, poolCount is set to 1.

For example, the plv8 initialization function (called for each new GUC) is set on a per connection basis (before any calls to any plv8 functions) as follows:

SET plv8.start_proc = "docstore"

The client can create an init function:

    function clientInitFunction(client, cb) {
      console.log('calling client init');
      client.query('SET plv8.start_proc = "docstore"', cb);
    }

which is then called on our promise generating connect closure:

  function connect(dsn) {
    DEBUG_ENABLED && console.log('connect called with ' + dsn);
    var deferred = Q.defer();

    pg.connect(dsn, function(err, client, done) {
      if(err) {
        deferred.reject(new Error('error fetching client from pool ' + err));
        return;
      }
      if(client.poolCount === 1 && clientInitFunction) {
        clientInitFunction(client, function(err) {
          if(err) {
            deferred.reject(new Error('error initing client ' + err));
            return;
          } else {
            deferred.resolve(new Connection(client, done));
            return;
          }
        })
      }
      deferred.resolve(new Connection(client, done));
    });
    return deferred.promise;
  }
Clone this wiki locally