Skip to content

Commit

Permalink
Changes sql SELECT to support special objects in condition values (fixes
Browse files Browse the repository at this point in the history
 #19)

Example:

```js
Person.find({ age: orm.between(20, 30) }, cb);
```

Other special objects:

- orm.eq(val): equal to val
- orm.ne(val): not equal to val
- orm.gt(val): greater than val
- orm.gte(val): greater or equal to val
- orm.lt(val): lesser than val
- orm.lte(val): lesser or equal to val
  • Loading branch information
dresende committed Jan 10, 2013
1 parent 6ab45c3 commit 1ed3dc5
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
44 changes: 40 additions & 4 deletions lib/sql/Select.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,11 @@ Builder.prototype.table = function (table) {
};

Builder.prototype.where = function (field, value, comparison) {
if (!Array.isArray(value) && typeof(value) === 'object') {
comparison = value.op || value.operator || value.comp || value.comparison;
value = value.value;
}
// stand by for now..
// if (!Array.isArray(value) && typeof(value) === 'object') {
// comparison = value.op || value.operator || value.comp || value.comparison;
// value = value.value;
// }
this.opts.where.push({
field : field,
value : value,
Expand Down Expand Up @@ -118,6 +119,41 @@ Builder.prototype.build = function () {
// where
lst = [];
for (i = 0; i < this.opts.where.length; i++) {
if (typeof this.opts.where[i].value.orm_special_object == "function") {
var op = this.opts.where[i].value.orm_special_object();
switch (op) {
case "between":
lst.push([
this.escapeId(this.opts.where[i].field),
"BETWEEN",
this.escape(this.opts.where[i].value.from),
"AND",
this.escape(this.opts.where[i].value.to)
].join(" "));
break;
case "eq":
case "ne":
case "gt":
case "gte":
case "lt":
case "lte":
switch (op) {
case "eq" : op = "="; break;
case "ne" : op = "<>"; break;
case "gt" : op = ">"; break;
case "gte" : op = ">="; break;
case "lt" : op = "<"; break;
case "lte" : op = "<="; break;
}
lst.push([
this.escapeId(this.opts.where[i].field),
op,
this.escape(this.opts.where[i].value.val)
].join(" "));
break;
}
continue;
}
lst.push([
this.escapeId(this.opts.where[i].field),
this.opts.where[i].comp,
Expand Down
2 changes: 1 addition & 1 deletion test/integration/test-find-where.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ common.createConnection(function (err, db) {

var TestModel = db.define(tableName, common.getModelProperties());

TestModel.find({ id: { value: 1, comparison: '<>' }}, function (err, Instances) {
TestModel.find({ id: common.ORM.ne(1) }, function (err, Instances) {
assert.equal(err, null);
assert.equal(Array.isArray(Instances), true);
assert.equal(Instances[0].id, 2);
Expand Down

0 comments on commit 1ed3dc5

Please sign in to comment.