Skip to content

Instantly share code, notes, and snippets.

@hoegaarden
Last active November 19, 2015 14:17
Show Gist options
  • Save hoegaarden/47f38c9b65844d78dba7 to your computer and use it in GitHub Desktop.
Save hoegaarden/47f38c9b65844d78dba7 to your computer and use it in GitHub Desktop.
node-postgres initial query for clients
var pg = require('pg');
var pgStart = require('./pg-start');
function printRes(type, err, res) {
console.log(
'from', type, 'we got', err ? 'an ERROR' : 'a response: ',
err || res
)
}
pgStart(pg, 'select 666', printRes.bind(null, 'init'));
pg.connect(function(err, client, done){
client.query('select 1', function(err, res){
printRes('normal query', err, res);
done();
pg.end();
});
});
$ node index.js
from init we got a response: { command: 'SELECT',
rowCount: 1,
oid: NaN,
rows: [ { '?column?': 666 } ],
fields:
[ { name: '?column?',
tableID: 0,
columnID: 0,
dataTypeID: 23,
dataTypeSize: 4,
dataTypeModifier: -1,
format: 'text' } ],
_parsers: [ [Function] ],
RowCtor: [Function] }
from normal query we got a response: { command: 'SELECT',
rowCount: 1,
oid: NaN,
rows: [ { '?column?': 1 } ],
fields:
[ { name: '?column?',
tableID: 0,
columnID: 0,
dataTypeID: 23,
dataTypeSize: 4,
dataTypeModifier: -1,
format: 'text' } ],
_parsers: [ [Function] ],
RowCtor: [Function] }
$
var util = require('util');
module.exports = function inject(pg) {
var queryArgs = Array.prototype.slice.call(arguments).slice(1);
var orgClient = pg.Client;
var newClient = function(){
orgClient.apply(this, arguments);
this.query.apply(this, queryArgs);
return this;
};
util.inherits(newClient, orgClient);
pg.Client = pg.pools.Client = newClient;
}
@jabclab
Copy link

jabclab commented Nov 19, 2015

Nice, thanks 😄 (Used this pattern for setting search_path).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment