Permalink
Browse files

extracted query

  • Loading branch information...
Karl Seguin
Karl Seguin committed May 6, 2012
1 parent 3160aad commit acf1b08d4325b2b46ca0b6ac432b76441000a0ea
Showing with 167 additions and 272 deletions.
  1. +5 −102 lib/mysql.js
  2. +9 −168 lib/postgres.js
  3. +153 −0 lib/query.js
  4. +0 −2 test/pg_query_spec.coffee
View
@@ -2,6 +2,7 @@ var events =require('events');
var util = require('util');
var _ = require('underscore')._;
var mysql = require("mysql");
+var Query = require('./query')
var parseWhere = function(conditions) {
@@ -39,104 +40,6 @@ var parseWhere = function(conditions) {
return where;
};
-var Query = function(sql, params, table) {
- events.EventEmitter.call(this);
- var self = this;
- self.sql = sql;
- self.params = params || [];
- self.table = table;
- self.db = table.db;
- self.columns = ""
- self.where = {};
- self.limit = "";
- self.order = "";
-
- self.on('newListener', function(eventName){
- if(eventName === 'row'){
- //fire the query
- self.each();
- }
- });
-
- self.order = function(){
- self.sql += util.format(" \nORDER BY %s", arguments[0]);
- return self;
- }
-
- self.limit = function() {
- if(arguments.length > 1){
- self.sql += util.format(" \nLIMIT(%d,%d)", arguments[0], arguments[1]);
- }else{
- self.sql += " \nLIMIT " + arguments[0];
- }
- return self;
- };
- self.raiseError = function(err){
- self.error = err;
- return self;
- };
- self.parseArgs = function(args) {
- if(_.isFunction(args[0])) return;
- var columns = " * ";
- var where = {};
- //if the first argument is an array, columns are specified
- if(args.length > 0 && _.isArray(args[0])){
- columns = args[0].join(",");
- self.sql = self.sql.replace("*", columns);
- }else if(args.length > 1 && args[1].columns) {
- self.sql = self.sql.replace("*", args[1].columns);
-
- }else if (args.length > 0 && _.isNumber(args[0])){
- var criteria = {};
- criteria[self.table.pk] = args[0];
- where = parseWhere(criteria);
- self.sql += where.sql;
- self.params = where.params;
-
- }else if (args.length > 0 && _.isObject(args[0])){
- where = parseWhere(args[0]);
- self.sql += where.sql;
- self.params = where.params;
- }
- return self;
- }
- self.execute = function(callback) {
- self.db.execute(self.sql, self.params, function(err,result){
- if(callback) callback(err,result);
- self.emit("executed");
- })
- }
-
- self.each = function(callback) {
- self.db.execute(self.sql,self.params, function(err,results){
- if(err && callback) callback(err,self.raiseError(err));
- else {
- _.each(results, function(r){
- self.emit("row", r);
- if(callback) callback(null,r);
- });
- self.emit("end");
- }
- });
- };
-
- self.first = function(callback) {
- self.sql += " LIMIT(1) ";
- self.db.execute(self.sql,self.params, function(err,results){
- if(err) callback(err,self.raiseError(err));
- else callback(null,results[0]);
- });
- };
- self.last = function(callback) {
- self.sql += util.format(" ORDER BY %s DESC LIMIT(1) ", this.table.pk);
- self.db.execute(self.sql,self.params, function(err,results){
- if(err) callback(err,self.raiseError(err));
- else callback(null,results[0]);
- });
- };
-}
-util.inherits(Query, events.EventEmitter);
-
var Table = function(tableName, pk, _db) {
var self = this;
this.name = tableName;
@@ -207,13 +110,13 @@ var Table = function(tableName, pk, _db) {
sql+= util.format(" \nWHERE \"%s\" = %d", this.pk, where);
}else if (_.isString(where)){
sql+= util.format(" \nWHERE \"%s\" = ?", this.pk);
- parameters.push(where);
+ parameters.push(where);
}else{
where = parseWhere(where);
sql += where.sql;
if(where.params.length > 0) parameters.push(where.params);
}
-
+
}
var query = new Query(sql, parameters, this);
return query;
@@ -245,12 +148,12 @@ var MySQL = function(credentials){
this.execute = function(sql, params, callback) {
var client = mysql.createClient(credentials);
-
+
self.emit("beforeExecute", self);
client.query(sql, params, function(err, results){
if(err && callback) {
- callback(err,null)
+ callback(err,null)
self.emit("error", err);
}else {
if(callback)callback(null,results);
View
@@ -2,148 +2,11 @@ var events =require('events');
var util = require('util');
var _ = require('underscore')._;
var pg = require("pg");
+var Query = require('./query')
//This function examines the passed-in object anc creates a WHERE statement for Postgres. This is pg client-specific.
-//The type of object passed-in is important. If the value is a boolean or number, it will be appended as opposed to
+//The type of object passed-in is important. If the value is a boolean or number, it will be appended as opposed to
//using parameters.
-var parseWhere = function(conditions) {
-
- var where = {};
- var params = [];
-
- if(_.isObject(conditions) &! _.isArray(conditions)) {
-
- var operations = {'=': '=', '!': '!=', '>': '>', '<': '<', '>=': '>=', '<=': '<=', '!=' : '<>', '<>': '<>'};
- var _conditions = [];
- var seed = params.length;
-
- _.each(conditions, function(value, key) {
- var parts = key.trim().split(/ +/);
- var property = parts[0];
- var operation = operations[parts[1]] || '=';
-
- if (_.isBoolean(value) || _.isNumber(value)) {
- _conditions.push(util.format('"%s" %s %d', property, operation, value));
- } else if (_.isArray(value)) {
- var arrayConditions = [];
- _.each(value, function(v) {
- arrayConditions.push('$' + ++seed);
- params.push(v);
- });
- _conditions.push(util.format('"%s" %s (%s)', property, operation == '!=' || operation == '<>' ? 'NOT IN' : 'IN', arrayConditions.join(', ')));
- } else {
- _conditions.push(util.format('"%s" %s %s', property, operation, '$' + ++seed));
- params.push(value);
- }
- });
- where.sql = ' \nWHERE ' + _conditions.join(' \nAND ');
- where.params = params;
- };
- return where;
-};
-
-var Query = function(sql, params, table) {
- events.EventEmitter.call(this);
- var self = this;
- self.sql = sql;
- self.params = params || [];
- self.table = table;
- self.db = table.db;
- self.columns = ""
- self.where = {};
- self.limit = "";
- self.order = "";
-
- self.on('newListener', function(eventName){
- if(eventName === 'row'){
- //fire the query
- self.each();
- }
- });
-
- self.order = function(){
- self.sql += util.format(" \nORDER BY %s", arguments[0]);
- return self;
- }
-
- self.limit = function() {
- if(arguments.length > 1){
- self.sql += util.format(" \nLIMIT(%d,%d)", arguments[0], arguments[1]);
- }else{
- self.sql += " \nLIMIT " + arguments[0];
- }
- return self;
- };
- self.raiseError = function(err){
- self.error = err;
- return self;
- };
- self.parseArgs = function(args) {
- if(_.isFunction(args[0])) return;
- var columns = " * ";
- var where = {};
- //if the first argument is an array, columns are specified
- if(args.length > 0 && _.isArray(args[0])){
- columns = args[0].join(",");
- self.sql = self.sql.replace("*", columns);
- //if the second arg has {columns : "..."} then columns are also specified
- }else if(args.length > 1 && args[1].columns) {
- self.sql = self.sql.replace("*", args[1].columns);
- //if the argument is numeric (instead of an object) - default it to a PK lookup
- }else if (args.length > 0 && _.isNumber(args[0])){
- var criteria = {};
- criteria[self.table.pk] = args[0];
- where = parseWhere(criteria);
- self.sql += where.sql;
- self.params = where.params;
- //if the argument is an object, parse a where statement
- }else if (args.length > 0 && _.isObject(args[0])){
- where = parseWhere(args[0]);
- self.sql += where.sql;
- self.params = where.params;
- }
- return self;
- }
-
- //execution uses the Client
- self.execute = function(callback) {
- self.db.execute(self.sql, self.params, function(err,result,client){
- if(callback) callback(err,result,client);
- self.emit("executed",client);
- })
- }
-
- //built-in iteration. This fetches the results using a callback
- //TODO: use the PG client's built in streamer for this
- self.each = function(callback) {
- self.db.execute(self.sql,self.params, function(err,results){
- if(err && callback) callback(err,self.raiseError(err));
- else {
- _.each(results, function(r){
- self.emit("row", r);
- if(callback) callback(null,r);
- });
- self.emit("end");
- }
- });
- };
-
- self.first = function(callback) {
- self.sql += " LIMIT(1) ";
- self.db.execute(self.sql,self.params, function(err,results){
- if(err) callback(err,self.raiseError(err));
- else callback(null,results[0]);
- });
- };
- self.last = function(callback) {
- self.sql += util.format(" ORDER BY %s DESC LIMIT(1) ", this.table.pk);
- self.db.execute(self.sql,self.params, function(err,results){
- if(err) callback(err,self.raiseError(err));
- else callback(null,results[0]);
- });
- };
-}
-util.inherits(Query, events.EventEmitter);
var Table = function(tableName, pk, _db) {
var self = this;
@@ -163,23 +26,15 @@ var Table = function(tableName, pk, _db) {
};
this.find = function() {
- var query = new Query("SELECT * FROM " + this.name, [], this);
- query.parseArgs(arguments);
- return query;
+ return new Query("SELECT * FROM " + this.name, [], this).parseArgs(arguments)
};
+
this.count = function(where) {
- var query = new Query("SELECT COUNT(1) FROM " + this.name, [] ,this);
- if(where) {
- var criteria = parseWhere(where);
- query.sql += criteria.sql;
- query.params.push(criteria.params);
- }
- return query;
- }
+ return new Query("SELECT COUNT(1) FROM " + this.name, [] ,this).where(where);
+ };
+
this.destroy = function() {
- var query = new Query("DELETE FROM " + this.name, [], this);
- query.parseArgs(arguments);
- return query;
+ return new Query("DELETE FROM " + this.name, [], this).parseArgs(arguments)
};
this.insert = function(data) {
@@ -209,21 +64,7 @@ var Table = function(tableName, pk, _db) {
parameters.push(value);
});
var sql = util.format("UPDATE %s SET %s", this.name, f.join(', '));
- if(where){
- if(_.isNumber(where)){
- sql+= util.format(" \nWHERE \"%s\" = %d", this.pk, where);
- }else if (_.isString(where)){
- sql+= util.format(" \nWHERE \"%s\" = $%d", this.pk, parameters.length+1);
- parameters.push(where);
- }else{
- where = parseWhere(where);
- sql += where.sql;
- if(where.params.length > 0) parameters.push(where.params);
- }
-
- }
- var query = new Query(sql, parameters, this);
- return query;
+ return new Query(sql, parameters, this).where(where);
};
}
Oops, something went wrong.

0 comments on commit acf1b08

Please sign in to comment.