/*
Checks for the existence of an operator in a query clause list
163055
protected static boolean isOperatorFoundInClause(String operator, List<Object> clause) {
        boolean found = false;

        // first check for the existence of $not so that we can find negated operators:
        // if we find $not then recurse with the value associated with it in the query map
        for (Object rawTerm : clause){
            if (rawTerm instanceof Map) {
                Map term = (Map) rawTerm;
                if (term.size() == 1 && term.values().toArray()[0] instanceof Map) {
                    Map predicate = (Map) term.values().toArray()[0];
                    if (predicate.get(NOT) != null && predicate.get(NOT) instanceof Map) {
                        return isOperatorFoundInClause(operator, Collections
                                .<Object>singletonList(predicate));
                    }
                }
            }
        }

        // if we didn't find $not then look directly for the operator
        for (Object rawTerm : clause){
            if (rawTerm instanceof Map) {
                Map term = (Map) rawTerm;
                if (term.size() == 1 && term.values().toArray()[0] instanceof Map) {
                    Map predicate = (Map) term.values().toArray()[0];
                    if (predicate.get(operator) != null) {
                        found = true;
                        break;
                    }
                }
            }
        }

        return found;
    }
224853
function where(column, operator, value) {

    // Support "where true || where false"
    if (column === false || column === true) {
      return this.where(1, '=', column ? 1 : 0);
    }

    // Check if the column is a function, in which case it's
    // a where statement wrapped in parens.
    if (typeof column === 'function') {
      return this.whereWrapped(column);
    }

    // Allow a raw statement to be passed along to the query.
    if (column instanceof Raw && arguments.length === 1) {
      return this.whereRaw(column);
    }

    // Allows `where({id: 2})` syntax.
    if (typeof column === 'object' && !(column instanceof Raw)) {
      return this._objectWhere(column);
    }

    // Enable the where('key', value) syntax, only when there
    // are explicitly two arguments passed, so it's not possible to
    // do where('key', '!=') and have that turn into where key != null
    if (arguments.length === 2) {
      value = operator;
      operator = '=';

      // If the value is null, and it's a two argument query,
      // we assume we're going for a `whereNull`.
      if (value === null) {
        return this.whereNull(column);
      }
    }

    // lower case the operator for comparison purposes
    var checkOperator = ('' + operator).toLowerCase().trim();

    // If there are 3 arguments, check whether 'in' is one of them.
    if (arguments.length === 3) {
      if (checkOperator === 'in' || checkOperator === 'not in') {
        return this._not(checkOperator === 'not in').whereIn(arguments[0], arguments[2]);
      }
      if (checkOperator === 'between' || checkOperator === 'not between') {
        return this._not(checkOperator === 'not between').whereBetween(arguments[0], arguments[2]);
      }
    }

    // If the value is still null, check whether they're meaning
    // where value is null
    if (value === null) {

      // Check for .where(key, 'is', null) or .where(key, 'is not', 'null');
      if (checkOperator === 'is' || checkOperator === 'is not') {
        return this._not(checkOperator === 'is not').whereNull(column);
      }
    }

    // Push onto the where statement stack.
    this._statements.push({
      grouping: 'where',
      type: 'whereBasic',
      column: column,
      operator: operator,
      value: value,
      not: this._not(),
      bool: this._bool()
    });
    return this;
  }
1240929
function (operator, field) {
            if (!this.query.where) {
                return null;
            }

            function findExpression(expressions) {
                var expression,
                    ret = null;
                for (var i = 0; i < expressions.length; i++) {
                    expression = expressions[i];
                    if (expression instanceof Where) {
                        ret = findExpression(expression.expressions);
                    } else if (expression instanceof Comparator) {
                        if (expression.operator == operator && expression.field == field) {
                            ret = expression;
                        }
                    }
                    if (ret) {
                        return ret;
                    }

                }
                return ret;
            }

            return findExpression(this.query.where.expressions);
        }
658128
function(query) {
    //  summary:
    //    state machine for query tokenization
    //  description:
    //    instead of using a brittle and slow regex-based CSS parser,
    //    dojo.query implements an AST-style query representation. This
    //    representation is only generated once per query. For example,
    //    the same query run multiple times or under different root nodes
    //    does not re-parse the selector expression but instead uses the
    //    cached data structure. The state machine implemented here
    //    terminates on the last " " (space) character and returns an
    //    ordered array of query component structures (or "parts"). Each
    //    part represents an operator or a simple CSS filtering
    //    expression. The structure for parts is documented in the code
    //    below.


    // NOTE:
    //    this code is designed to run fast and compress well. Sacrifices
    //    to readability and maintainability have been made.
    if (specials.indexOf(query.slice(-1)) >= 0) {
      // If we end with a ">", "+", or "~", that means we're implicitly
      // searching all children, so make it explicit.
      query += ' * '
    } else {
      // if you have not provided a terminator, one will be provided for
      // you...
      query += ' ';
    }

    var ts = function(/*Integer*/ s, /*Integer*/ e) {
      // trim and slice.

      // take an index to start a string slice from and an end position
      // and return a trimmed copy of that sub-string
      return goog.string.trim(query.slice(s, e));
    };

    // The overall data graph of the full query, as represented by queryPart
    // objects.
    var queryParts = [];


    // state keeping vars
    var inBrackets = -1,
        inParens = -1,
        inMatchFor = -1,
        inPseudo = -1,
        inClass = -1,
        inId = -1,
        inTag = -1,
        lc = '',
        cc = '',
        pStart;

    // iteration vars
    var x = 0, // index in the query
        ql = query.length,
        currentPart = null, // data structure representing the entire clause
        cp = null; // the current pseudo or attr matcher

    // several temporary variables are assigned to this structure during a
    // potential sub-expression match:
    //    attr:
    //      a string representing the current full attribute match in a
    //      bracket expression
    //    type:
    //      if there's an operator in a bracket expression, this is
    //      used to keep track of it
    //    value:
    //      the internals of parenthetical expression for a pseudo. for
    //      :nth-child(2n+1), value might be '2n+1'

    var endTag = function() {
      // called when the tokenizer hits the end of a particular tag name.
      // Re-sets state variables for tag matching and sets up the matcher
      // to handle the next type of token (tag or operator).
      if (inTag >= 0) {
        var tv = (inTag == x) ? null : ts(inTag, x);
        if (specials.indexOf(tv) < 0) {
          currentPart.tag = tv;
        } else {
          currentPart.oper = tv;
        }
        inTag = -1;
      }
    };

    var endId = function() {
      // Called when the tokenizer might be at the end of an ID portion of a
      // match.
      if (inId >= 0) {
        currentPart.id = ts(inId, x).replace(/\\/g, '');
        inId = -1;
      }
    };

    var endClass = function() {
      // Called when the tokenizer might be at the end of a class name
      // match. CSS allows for multiple classes, so we augment the
      // current item with another class in its list.
      if (inClass >= 0) {
        currentPart.classes.push(ts(inClass + 1, x).replace(/\\/g, ''));
        inClass = -1;
      }
    };

    var endAll = function() {
      // at the end of a simple fragment, so wall off the matches
      endId(); endTag(); endClass();
    };

    var endPart = function() {
      endAll();
      if (inPseudo >= 0) {
        currentPart.pseudos.push({ name: ts(inPseudo + 1, x) });
      }
      // Hint to the selector engine to tell it whether or not it
      // needs to do any iteration. Many simple selectors don't, and
      // we can avoid significant construction-time work by advising
      // the system to skip them.
      currentPart.loops = currentPart.pseudos.length ||
                          currentPart.attrs.length ||
                          currentPart.classes.length;

      // save the full expression as a string
      currentPart.oquery = currentPart.query = ts(pStart, x);


      // otag/tag are hints to suggest to the system whether or not
      // it's an operator or a tag. We save a copy of otag since the
      // tag name is cast to upper-case in regular HTML matches. The
      // system has a global switch to figure out if the current
      // expression needs to be case sensitive or not and it will use
      // otag or tag accordingly
      currentPart.otag = currentPart.tag = (currentPart.oper) ?
                                                     null :
                                                     (currentPart.tag || '*');

      if (currentPart.tag) {
        // if we're in a case-insensitive HTML doc, we likely want
        // the toUpperCase when matching on element.tagName. If we
        // do it here, we can skip the string op per node
        // comparison
        currentPart.tag = currentPart.tag.toUpperCase();
      }

      // add the part to the list
      if (queryParts.length && (queryParts[queryParts.length - 1].oper)) {
        // operators are always infix, so we remove them from the
        // list and attach them to the next match. The evaluator is
        // responsible for sorting out how to handle them.
        currentPart.infixOper = queryParts.pop();
        currentPart.query = currentPart.infixOper.query + ' ' +
            currentPart.query;
      }
      queryParts.push(currentPart);

      currentPart = null;
    }

    // iterate over the query, character by character, building up a
    // list of query part objects
    for (; lc = cc, cc = query.charAt(x), x < ql; x++) {
      //    cc: the current character in the match
      //    lc: the last character (if any)

      // someone is trying to escape something, so don't try to match any
      // fragments. We assume we're inside a literal.
      if (lc == '\\') {
        continue;
      }
      if (!currentPart) { // a part was just ended or none has yet been created
        // NOTE: I hate all this alloc, but it's shorter than writing tons of
        // if's
        pStart = x;
        //  rules describe full CSS sub-expressions, like:
        //    #someId
        //    .className:first-child
        //  but not:
        //    thinger > div.howdy[type=thinger]
        //  the individual components of the previous query would be
        //  split into 3 parts that would be represented a structure
        //  like:
        //    [
        //      {
        //        query: 'thinger',
        //        tag: 'thinger',
        //      },
        //      {
        //        query: 'div.howdy[type=thinger]',
        //        classes: ['howdy'],
        //        infixOper: {
        //          query: '>',
        //          oper: '>',
        //        }
        //      },
        //    ]
        currentPart = {
          query: null, // the full text of the part's rule
          pseudos: [], // CSS supports multiple pseudo-class matches in a single
              // rule
          attrs: [],  // CSS supports multi-attribute match, so we need an array
          classes: [], // class matches may be additive,
              // e.g.: .thinger.blah.howdy
          tag: null,  // only one tag...
          oper: null, // ...or operator per component. Note that these wind up
              // being exclusive.
          id: null,   // the id component of a rule
          getTag: function() {
            return (caseSensitive) ? this.otag : this.tag;
          }
        };

        // if we don't have a part, we assume we're going to start at
        // the beginning of a match, which should be a tag name. This
        // might fault a little later on, but we detect that and this
        // iteration will still be fine.
        inTag = x;
      }

      if (inBrackets >= 0) {
        // look for a the close first
        if (cc == ']') { // if we're in a [...] clause and we end, do assignment
          if (!cp.attr) {
            // no attribute match was previously begun, so we
            // assume this is an attribute existence match in the
            // form of [someAttributeName]
            cp.attr = ts(inBrackets + 1, x);
          } else {
            // we had an attribute already, so we know that we're
            // matching some sort of value, as in [attrName=howdy]
            cp.matchFor = ts((inMatchFor || inBrackets + 1), x);
          }
          var cmf = cp.matchFor;
          if (cmf) {
            // try to strip quotes from the matchFor value. We want
            // [attrName=howdy] to match the same
            //  as [attrName = 'howdy' ]
            if ((cmf.charAt(0) == '"') || (cmf.charAt(0) == "'")) {
              cp.matchFor = cmf.slice(1, -1);
            }
          }
          // end the attribute by adding it to the list of attributes.
          currentPart.attrs.push(cp);
          cp = null; // necessary?
          inBrackets = inMatchFor = -1;
        } else if (cc == '=') {
          // if the last char was an operator prefix, make sure we
          // record it along with the '=' operator.
          var addToCc = ('|~^$*'.indexOf(lc) >= 0) ? lc : '';
          cp.type = addToCc + cc;
          cp.attr = ts(inBrackets + 1, x - addToCc.length);
          inMatchFor = x + 1;
        }
        // now look for other clause parts
      } else if (inParens >= 0) {
        // if we're in a parenthetical expression, we need to figure
        // out if it's attached to a pseudo-selector rule like
        // :nth-child(1)
        if (cc == ')') {
          if (inPseudo >= 0) {
            cp.value = ts(inParens + 1, x);
          }
          inPseudo = inParens = -1;
        }
      } else if (cc == '#') {
        // start of an ID match
        endAll();
        inId = x + 1;
      } else if (cc == '.') {
        // start of a class match
        endAll();
        inClass = x;
      } else if (cc == ':') {
        // start of a pseudo-selector match
        endAll();
        inPseudo = x;
      } else if (cc == '[') {
        // start of an attribute match.
        endAll();
        inBrackets = x;
        // provide a new structure for the attribute match to fill-in
        cp = {
          /*=====
          attr: null, type: null, matchFor: null
          =====*/
        };
      } else if (cc == '(') {
        // we really only care if we've entered a parenthetical
        // expression if we're already inside a pseudo-selector match
        if (inPseudo >= 0) {
          // provide a new structure for the pseudo match to fill-in
          cp = {
            name: ts(inPseudo + 1, x),
            value: null
          }
          currentPart.pseudos.push(cp);
        }
        inParens = x;
      } else if (
        (cc == ' ') &&
        // if it's a space char and the last char is too, consume the
        // current one without doing more work
        (lc != cc)
      ) {
        endPart();
      }
    }
    return queryParts;
  }
409215
@Override
    public void _search(String fieldName, String searchTerms, SearchOperator operator) {
        List<QueryToken> tokens = getCurrentWhereTokens();
        appendOperatorIfNeeded(tokens);

        fieldName = ensureValidFieldName(fieldName, false);
        negateIfNeeded(tokens, fieldName);

        WhereToken whereToken = WhereToken.create(WhereOperator.SEARCH, fieldName, addQueryParameter(searchTerms), new WhereToken.WhereOptions(operator));
        tokens.add(whereToken);
    }
521411
private String toSQLClause(ExistsCriteria c, ClassDescriptor cld)
    {
        StringBuffer buf = new StringBuffer();
        Query subQuery = (Query) c.getValue();

        buf.append(c.getClause());
        buf.append(" (");

        // If it's a proper call
        if (cld != null)
        {
            buf.append(
                getPreparedSelectStatement(
                    subQuery,
                    cld.getRepository().getDescriptorFor(subQuery.getSearchClass())));

            // Otherwise it's most likely a call to toString()
        }
        else
        {
            buf.append(subQuery);
        }

        buf.append(")");
        return buf.toString();
    }
805582
def comparison_operator_query(comparison_operator):
    """"""
    def _comparison_operator_query(expression):
        """Apply binary operator to expression."""
        def _apply_comparison_operator(index, expression=expression):
            """Return store key for documents that satisfy expression."""
            ev = expression() if callable(expression) else expression
            return [
                store_key
                for value, store_keys
                in index.get_index().items()
                if comparison_operator(value, ev)
                for store_key in store_keys
            ]
        return _apply_comparison_operator
    return _comparison_operator_query
707926
@SuppressWarnings("unchecked")
    public static Map<String, Object> normaliseAndValidateQuery(Map<String, Object> query) throws QueryException{
        boolean isWildCard = false;
        if (query.isEmpty()) {
            isWildCard = true;
        }

        // First expand the query to include a leading compound predicate
        // if there isn't one already.
        query = addImplicitAnd(query);

        // At this point we will have a single entry map, key AND or OR,
        // forming the compound predicate.
        String compoundOperator = (String) query.keySet().toArray()[0];
        List<Object> predicates = new ArrayList<Object>();
        if (query.get(compoundOperator) instanceof List) {
            // Next make sure all the predicates have an operator -- the EQ
            // operator is implicit and we need to add it if there isn't one.
            // Take
            //     [ {"field1": "mike"}, ... ]
            // and make
            //     [ {"field1": { "$eq": "mike"} }, ... ]
            predicates = addImplicitEq((List<Object>) query.get(compoundOperator));

            // Then all shorthand operators like $ne, if present, need to be converted
            // to their logical longhand equivalent.
            // Take
            //     [ { "field1": { "$ne": "mike"} }, ... ]
            // and make
            //     [ { "field1": { "$not" : { "$eq": "mike"} } }, ... ]
            predicates = handleShortHandOperators(predicates);

            // Now in the event that extraneous $not operators exist in the query,
            // these operators must be compressed down to the their logical equivalent.
            // Take
            //     [ { "field1": { "$not" : { $"not" : { "$eq": "mike"} } } }, ... ]
            // and make
            //     [ { "field1": { "$eq": "mike"} }, ... ]
            predicates = compressMultipleNotOperators(predicates);

            // Here we ensure that all non-whole number arguments included in a $mod
            // clause are truncated.  This provides for consistent behavior between
            // the SQL engine and the unindexed matcher.
            // Take
            //     [ { "field1": { "$mod" : [ 2.6, 1.7] } }, ... ]
            // and make
            //     [ { "field1": { "$mod" : [ 2, 1 ] } }, ... ]
            predicates = truncateModArguments(predicates);
        }

        Map<String, Object> selector = new HashMap<String, Object>();
        selector.put(compoundOperator, predicates);
        if (!isWildCard) {
            validateSelector(selector);
        }

        return selector;
    }
354766
function(query) {
        var queryObj = {q: ''};
        if(!query) {
            return queryObj;
        }

        var qArray = query.split('&');
        var qObj = qs.parse(query);
        for(var i = 0, len = qArray.length; i < len; i++) {
            var queryItem = decodeURIComponent(qArray[i]).replace('=', '');
            if(/^\?/g.test(queryItem)) {
                debug('matched query: %s', queryItem) ;
                queryObj.q = queryItem;
                break;
            }
        }

        queryObj.m = qObj._mcss == 'true' || qObj._mcss == 'y';
        return queryObj;
    }
192048
function (item, expression) {
            var ret = 1,
                operator = expression.operator;

            if (expression instanceof Query.Where) {
                if (operator === "or") {
                    ret = 0;
                }
                var tmp;
                for (var i = 0; i < expression.expressions.length; i++) {
                    tmp = this._filterItem(item, expression.expressions[i]);
                    if (operator === "and") {
                        ret = ret * tmp;
                    } else if (operator === "or" && tmp) {
                        return 1;
                    } else if (operator === "not") {
                        return tmp ? 0 : 1;
                    }
                }
            } else if (expression instanceof Query.Comparator) {
                // TODO: add type check
                var value = expression.value,
                    field = expression.field,
                    itemValue = this._getValueForItemField(item, field);

                if (typeof(itemValue) === "undefined") {
                    return 0;
                }

                switch (operator) {
                    case "eql":
                        return itemValue == value;
                    case "gt":
                        return itemValue > value;
                    case "lt":
                        return itemValue < value;
                    case "gte":
                        return itemValue >= value;
                    case "lte":
                        return itemValue <= value;
                    case "in":
                        if (!(itemValue instanceof Array)) {
                            itemValue = [itemValue];
                        }
                        for (var j = 0; j < itemValue.length; j++) {
                            for (var k in value) {
                                if (value.hasOwnProperty(k)) {
                                    if (itemValue[j] == value[k]) {
                                        return 1;
                                    }
                                }
                            }
                        }
                        return 0;
                    case "between":
                        return itemValue >= value[0] && itemValue <= value[1];
                    case "like":
                        return new RegExp(value, "i").test(itemValue);
                    case "ne":
                        return itemValue != value;
                    default :
                        return 1;
                }

            }

            return ret;
        }
1064818
function checkQuery(expected, actual){
    if(!expected){
        return;
    }

    //Ignore trailing ampersands
    var actualObj = actual ? queryString.parse(actual.replace(/\&$/, '')) : {};
    var expectedObj = queryString.parse(expected);

    if(! _.isEqual(actualObj, expectedObj)){
        return {
            error: "Query parameters do not match",
            expected: expectedObj,
            actual: actualObj
        };
    }
}
645282
@Override
    public boolean checkCondition(IValue test) throws FilterException {
        Iterator iter = values.iterator();
        while (iter.hasNext()) {
            IValue value = (IValue) iter.next();
            if (value.containedBy(test)) {
                return true;
            }
        }
        return false;
    }
364923
def check_query(query):
    
    q = query.lower()
    if "select " not in q:
        raise InvalidQuery("SELECT word not found in the query: {0}".format(query))
    if " from " not in q:
        raise InvalidQuery("FROM word not found in the query: {0}".format(query))
513661
function (query, params, stringifier) {
    if (!query || !query.length || !params) {
      return query;
    }
    if (!stringifier) {
      stringifier = function (a) {return a.toString()};
    }
    var parts = [];
    var isLiteral = false;
    var lastIndex = 0;
    var paramsCounter = 0;
    for (var i = 0; i < query.length; i++) {
      var char = query.charAt(i);
      if (char === "'" && query.charAt(i-1) !== '\\') {
        //opening or closing quotes in a literal value of the query
        isLiteral = !isLiteral;
      }
      if (!isLiteral && char === '?') {
        //is a placeholder
        parts.push(query.substring(lastIndex, i));
        parts.push(stringifier(params[paramsCounter++]));
        lastIndex = i+1;
      }
    }
    parts.push(query.substring(lastIndex));
    return parts.join('');
  }
270475
@VisibleForTesting
    public static boolean checkInBloomFilter(BloomFilter bloomFilter, Object predicateValue, Type sqlType)
    {
        if (sqlType == TINYINT || sqlType == SMALLINT || sqlType == INTEGER || sqlType == BIGINT) {
            return bloomFilter.testLong(((Number) predicateValue).longValue());
        }

        if (sqlType == DOUBLE) {
            return bloomFilter.testDouble((Double) predicateValue);
        }

        if (sqlType instanceof VarcharType || sqlType instanceof VarbinaryType) {
            return bloomFilter.test(((Slice) predicateValue).getBytes());
        }

        // todo support DECIMAL, FLOAT, DATE, TIMESTAMP, and CHAR
        return true;
    }
215383
def matches_conditions?(object, query)
        query[:guard] == false ||
        Array(if_condition).all? {|condition| evaluate_method(object, condition)} &&
        !Array(unless_condition).any? {|condition| evaluate_method(object, condition)}
      end
1164793
def or_where(self, key, operator, value):
        
        if len(self._queries) > 0:
            self._current_query_index += 1
        self.__store_query({"key": key, "operator": operator, "value": value})
        return self