Skip to content
This repository has been archived by the owner on Mar 4, 2019. It is now read-only.

Commit

Permalink
cleaned up query.parseArgs and made it more flexible in terms of how …
Browse files Browse the repository at this point in the history
…it can be used
  • Loading branch information
Karl Seguin committed May 6, 2012
1 parent 85a6bfd commit c9721a0
Showing 1 changed file with 20 additions and 18 deletions.
38 changes: 20 additions & 18 deletions lib/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,28 +30,30 @@ var Query = function(sql, params, table) {
};

self.parseArgs = function(args) {
if(_.isFunction(args[0])) { return self; }

var where = {};

if(args.length > 0 && _.isArray(args[0])) { //if the first argument is an array, columns are specified
self.sql = self.sql.replace("*", args[0].join(","));
} else if(args.length > 1 && args[1].columns) { //if the second arg has {columns : "..."} then columns are also specified
self.sql = self.sql.replace("*", args[1].columns);
} else if (args.length > 0 && _.isNumber(args[0])) { //if the argument is numeric (instead of an object) - default it to a PK lookup
var criteria = {};
criteria[self.table.pk] = args[0];
self.where(criteria);
} else if (args.length > 0 && _.isObject(args[0])){ //if the argument is an object, parse a where statement
self.where(args[0]);
}
if(args.length == 0 || _.isFunction(args[0])) { return self; }

_.each(args, function(arg) {
if (_.isNumber(arg) || _.isString(arg)) {
var criteria = {};
criteria[self.table.pk] = args[0];
return self.where(criteria);
}

var columns = arg.columns || arg;
if (_.isArray(columns)) { self.sql = self.sql.replace("*", columns.join(",")); }
if (_.isString(columns)) { self.sql = self.sql.replace("*", columns); }
delete arg.columns;

var where = arg.where || arg;
if (!_.isArray(where) && _.isObject(where) && _.size(where) > 0) { self.where(where); }

});
return self;
};

self.where = function(conditions) {
if (_.isUndefined(conditions)) {
return self;
}
if (_.isUndefined(conditions)) { return self; }

if(_.isNumber(conditions)) {
return self._append(" \nWHERE \"%s\" = %d", self.table.pk, conditions);
}
Expand Down

0 comments on commit c9721a0

Please sign in to comment.