brianc/node-postgres — pull request #556 by rngadam (2014-04-01 06:18:30+00:00)
Title: add count for reuse of each connection and track connection 'freshness'

add an internal variable to each client to track how many times the client was reused from the pool.

This has the side-benefit that we can now test to see if the client is a "new" connection and take action on a per connection basis.

For example, 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.__pool_count === 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;
}
```

Alternatively, I've thought of adding a new event created that would be propagated from pool -> pg but that doesn't really fit with having to wait for the custom initialization to execute before continuing. Adding hooks to add initialization functions to pg would also unnecessarily complicate the code IMO.