node package manager


Create SQL queries programatically in Node.js. suport only postgresql. Loosely based on Codeigniter 'ActiveRecord'.


This is a fork of (node-db-query)[]. But my focus is on the postgres query build only.

Create SQL queries programatically in Node.js. Loosely based on Rails' ActiveRelation.

Install the module with: npm install pg-query-builder

This example uses any-db, so you'll need to npm install any-db to run it.

var Query = require('pg-query-builder');
var anyDB = require('any-db');
var database = 'postgres://user@host:5432/database_name';
var dbPool = anyDB.createPool(database, {
  min: 5,
  max: 15,
  onConnectfunction (conndone) {
    done(null, conn);
  resetfunction (conndone) {
var options = { id: [1,2,3,4] };
// or options = { id: '1,2,3,4' }; 
var q = new Query(dbPool)
  .join('JOIN posts ON posts.user_id =')
  .order('posts.updated_at DESC')
// Add some sample optional processing to the query 
var food = 'cheese';
if (food) {
  // Get people by food 
  q.join('JOIN foods ON = users.food_id')
  q.where(' = ' + q.paramNo()); // This becomes : = $1 
} else {
  // Get people by id(s) 
  // q.ids is another form of q.param, but will join arrays and wraps the result in '{ }' braces. 
  q.ids([1,2,3,4]); // q.ids('1,2,3,4'); as an alternative 
  // This is using Postgres' ANY format rather than id IN blah because it's much more efficient 
  q.where('id = ANY(' + q.paramNo() + '::int[])');
  // This becomes : id = ANY($1::int[])  
// Prepare some event handlers and execute the query 
q.on('row', function(row) { console.log(row); })
  .on('error', function(err) { console.log(err); })
  .on('end', function(data) { console.log(data); })

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.


Copyright (c) 2013 Daisuke Yamashita Licensed under the MIT license.