sequelize/sequelize — pull request #1137 by peaches (2013-12-17 19:27:48+00:00)
Title: Closing postgres client properly

This fixes a couple issues:

* Multiple decrements of `pendingQueries` for the same query. Since we
have a `complete` handler in addition to `success` and `error`,
`endQuery` gets called twice if it's a success or an error. This
means that we will end up with `pendingQueries < 0` so the
disconnect condition is never satisfied.
* We were hooking into pg's `drain` event during the disconnect step,
this is already too late since most of the time, the drain event is
already fired. We need to hook into the `drain` event on client
creation. Sadly, we cannot close the connection on the `drain`
event as it will break with the error,
`Error: Stream unexpectedly ended during query execution`

Repro of the second issue with `sequelize` and `node-postgres`. This script because `client.end` is never called.

```
var Sequelize = require('sequelize');
var sequelize = new Sequelize('some_db', 'user', 'password', {
dialect: 'postgres',
port: 5432
});

sequelize.query('SELECT 1').success(function(row) {
console.log(row);
});
```