Skip to content

Instantly share code, notes, and snippets.

@chilts
Created August 23, 2012 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chilts/3441701 to your computer and use it in GitHub Desktop.
Save chilts/3441701 to your computer and use it in GitHub Desktop.
Example Node.js + Postgres tests
var fmt = require('fmt');
var pg = require('pg');
var conString = "pg://scroober@localhost/scroober";
pg.connect(conString, function(err, cl) {
if (err) {
console.log(err);
return;
}
// disconnect client when all queries are finished
cl.on('drain', cl.end.bind(cl));
cl.query("SELECT NOW() as when", function(err, result) {
fmt.title('SELECT NOW()');
console.log("Row count: %d",result.rows.length); // 1
console.log("Current year: %d", result.rows[0].when.getYear());
fmt.line();
});
cl.query("SELECT * FROM property", function(err, result) {
fmt.title('Property Table');
console.log("Row count: %d", result.rows.length); // 1
fmt.line();
});
});
var fmt = require('fmt');
var pg = require('pg');
var client = new pg.Client({
user : 'scroober',
database : 'scroober',
});
// disconnect client when all queries are finished
client.on('drain', client.end.bind(client));
client.connect(function(err) {
fmt.line();
fmt.title('Inside client.connect()');
if (err) {
console.log(err);
return;
}
console.log('Connected');
client.query("SELECT * FROM property", function(err, result) {
fmt.line();
console.log("Row count : %d", result.rows.length); // 1
fmt.dump(result, 'result');
fmt.line();
});
// create a parameterized query
var query = client.query({
text : 'SELECT key, value FROM property WHERE key = $1 OR key = $2',
values : ['Greeting', 'Theme']
});
query.on('row', function(row) {
fmt.title('New Row');
fmt.dump(row, 'row');
fmt.line();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment