From 5bc48f4c374314e1eda1839fd9753a1ee77c0ebe Mon Sep 17 00:00:00 2001 From: mde Date: Thu, 16 Aug 2012 11:25:56 -0700 Subject: [PATCH] Handle array values when creating operations --- lib/query/query.js | 46 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/lib/query/query.js b/lib/query/query.js index d0dfbc22..b0c10a17 100644 --- a/lib/query/query.js +++ b/lib/query/query.js @@ -47,25 +47,55 @@ query.Query.prototype = new (function () { }; } - , _createConditions = function (conditions, key) { - var type = key || 'and' + , _createOperation = function (conditions, key) { + var self = this + , type = key || 'and' + , cond + , item , op = operation.create(type) + , notOperand , operand; // TODO: Handle associations for (var k in conditions) { + cond = conditions[k]; + + // Operation type, can contain other operations/conditions if (_operationTypes[k]) { - if (k == 'not') { - operand = operation.create(k); - operand.add(_createConditions.apply(this, [conditions[k], 'and'])); + // Base operation-type to create: if the type is a 'not', + // create a single 'and' with the same conditions to wrap + // in a 'not' + type = k == 'not' ? 'and' : k; + + // If the conditions are an array, create a single 'and' + // op that wraps each set of conditions in each item, and + // add to the wrapper + if (Array.isArray(cond)) { + // Create empty wrapper + operand = operation.create(type); + cond.forEach(function (c) { + operand.add(_createOperation.apply(self, [c, 'and'])); + }); } + // Simple object-literal, just create an operation else { - operand = _createConditions.apply(this, [conditions[k], k]); + operand = _createOperation.apply(this, [cond, type]); + } + + // If this was a 'not' operation, create a wrapping 'not' + // to contain the single operation created + if (k == 'not') { + notOperand = operation.create(k); + notOperand.add(operand); + operand = notOperand; } } + + // Simple condition (leaf-node) else { - operand = _createComparison.apply(this, [conditions[k], k]); + operand = _createComparison.apply(this, [cond, k]); } + op.add(operand); } return op; @@ -178,7 +208,7 @@ query.Query.prototype = new (function () { this.model = model; this.isValidField = _createIsValidField.apply(this); this.opts = _parseOpts.apply(this, [opts || {}]); - this.conditions = _createConditions.apply(this, [conditions]); + this.conditions = _createOperation.apply(this, [conditions]); };