brianc/node-postgres — pull request #171 by troyk (2012-08-10 00:02:52+00:00)
Title: make Query a public api

I'd like to propose having Query available as a public API. This solves a few pain points for my use case and I hope it will for others as well. I needed better control of the connection in a multi-tenant web app and want to use the built-in connection pool. Transactions and server session state (e.g. schema, timezone, user, etc) we're causing a lot of grief until I opened up the Query API. An excerpt of the code I'm using might help explain:

```javascript
function DBSession(username,password) {
this.transaction = null;
}

DBSession.prototype.query = function(config, values, callback) {
var query = new pg.Query(config, values, callback),
self = this;
if (!this.transaction) {
pg.connect(function(err,client){
if (err) return query.handleError(err);
client.query(query);
});
} else {
query.on('error',function(){
self.rollback();
});
transaction.client.query(query);
}
return query;
};

var sql = 'SET search_path to crm1,public; SET TIME ZONE \'EST5EDT\'; select row_to_json(users) from users limit 1';
var db = new DBSession();
db.query(sql,function(e,r){
console.log(e,r);
});
```
I moved the config creation of client.query to the query class and allow an instance of Query to be passed in addition to the current string and config options. All test passed on my machine and it didn't seem like additional tests were needed, but let me know if you want a test file and if this should be tested in one of the existing tests.

Also notice how I'm able to create a DBSession and issue queries in a more synchronous manner.

Also, with this API I have something I'd like to release as a plugin that console logs the SQL in the REPL, but it depends on getting to the Query obj as well.