brianc/node-postgres — pull request #274 by brianc (2013-02-20 14:18:20+00:00)
Title: Connection Pool refactor

Addressing #227 #224 #22 #154 and #137

This is the __start__ of the pool refactor. It is still a major work in progress. The old API will remain intact but officially deprecated. The new api is as follows:

```js
pg.connect(/*optional connection parameters*/, function(err, client, done) {
setTimeout(function() {
done(); //returns client to the pool regardless of whether or not client was used at all
}, 1000);
});
```

The api also allows you to force the pool to destroy and remove a client by passing an instance of `Error` (or anything truthy, actually) to the `done()` callback - I modeled this off of the async testing api in https://github.com/visionmedia/mocha

```js
pg.connect(function(err, client, done) {
//force the client pool to destroy the client
done(new Error("SOMETHING BAD HAPPEND"));
});
```

There are a few edge cases I tried to test more closely as well, including the following: _note: never do this IRL_

```js
pg.connect(function(err, client, done) {
done(); //return the client to the pool immediately
setTimeout(function() {
//the client will emit an error while sitting idle in the pool
client.emit('error', new Error("I GOT DISCONNECTED FROM THE DATABASE IN THE BACKGROUND!!"));
}, 1000);
});
```

When a client emits an error in the background the pool itself (or the root `pg` object) will emit the error and more importantly _the client will be destroyed and removed from the pool_. This should cover cases where postgres closes or fails in the background, all the clients will disconnect with errors and be removed from the pool. There is still work to do with failover & heartbeats and stuff however.

_____

So far I've worked in completely separate files so the pull request may not yet be clear on how I intend to integrate this with the existing API. One thing I would like is to expose the individual pool objects via `pg.pool(connectionParameters)` or something of the like. This will allow you to use the `aquire` and `release` methods directly if the `pg.connect` method doesn't suit your needs, supply a completely custom pool implementation, or do other helpful things like shutdown/destroy a particular pool. I think this will become more clear as I add more commits to this branch with the next 72 hours.

I'm looking for feedback & collaboration on this, so don't be shy!