Builds the query object from the options property
422193
protected function getParams()
    {
        $params = ["key=".$this->apiKey];
        if (@count($this->options[0]) > 0 && is_array($this->options[0])) {
            foreach ($this->options[0] as $k => $v) {
                if ($k != "response_type" && $k != "apiKey") {
                    array_push($params, "$k=$v");
                }
            }
        }
        return $params;
    }
889917
function strictQueryParams(options) {

    var opts = options || {};
    assert.optionalObject(opts, 'options');
    assert.optionalString(opts.message, 'options.message');

    function _strictQueryParams(req, res, next) {

        var keyValQParams = !/(\&(?!(\w+=\w+)))/.test(req.url);

        if (!keyValQParams) {
            var msg = opts.message ? opts.message :
                'Url query params does not meet strict format';
            return next(new BadRequestError(msg));
        }

        return next();
    }

    return (_strictQueryParams);
}
816585
private Status runQuery(QueryOptions options, QueryRowBlock block) {
        if (options == null)
            options = new QueryOptions();

        // OPT: It would be faster to use separate tables for raw-or ascii-collated views so that
        // they could be indexed with the right collation, instead of having to specify it here.
        String collationStr = "";
        if (collation == View.TDViewCollation.TDViewCollationASCII)
            collationStr += " COLLATE JSON_ASCII";
        else if (collation == View.TDViewCollation.TDViewCollationRaw)
            collationStr += " COLLATE JSON_RAW";


        StringBuilder sql = new StringBuilder("SELECT key, value, docid, revs.sequence");
        if (options.isIncludeDocs()) {
            sql.append(", revid, json");
        }
        sql.append(String.format(Locale.ENGLISH, " FROM 'maps_%s', revs, docs", mapTableName()));
        sql.append(" WHERE 1");

        List<String> argsList = new ArrayList<String>();

        if (options.getKeys() != null && options.getKeys().size() > 0) {
            sql.append(" AND key in (");
            String item = "?";
            for (Object key : options.getKeys()) {
                // null key should be ignored
                if (key != null) {
                    sql.append(item);
                    item = ", ?";
                    argsList.add(toJSONString(key));
                }
            }
            sql.append(')');
        }

        Object minKey = options.getStartKey();
        Object maxKey = options.getEndKey();
        String minKeyDocId = options.getStartKeyDocId();
        String maxKeyDocId = options.getEndKeyDocId();

        boolean inclusiveMin = options.isInclusiveStart();
        boolean inclusiveMax = options.isInclusiveEnd();
        if (options.isDescending()) {
            Object min = minKey;
            minKey = maxKey;
            maxKey = min;
            inclusiveMin = inclusiveMax;
            inclusiveMax = true;
            minKeyDocId = options.getEndKeyDocId();
            maxKeyDocId = options.getStartKeyDocId();
        }

        if (minKey != null) {
            String minKeyJSON = toJSONString(minKey);
            sql.append(inclusiveMin ? " AND key >= ?" : " AND key > ?");
            sql.append(collationStr);
            argsList.add(minKeyJSON);
            if (minKeyDocId != null && inclusiveMin) {
                //OPT: This calls the JSON collator a 2nd time unnecessarily.
                sql.append(String.format(Locale.ENGLISH, " AND (key > ? %s OR docid >= ?)", collationStr));
                argsList.add(minKeyJSON);
                argsList.add(minKeyDocId);
            }
        }

        if (maxKey != null) {
            maxKey = View.keyForPrefixMatch(maxKey, options.getPrefixMatchLevel());
            String maxKeyJSON = toJSONString(maxKey);
            sql.append(inclusiveMax ? " AND key <= ?" : " AND key < ?");
            sql.append(collationStr);
            argsList.add(maxKeyJSON);
            if (maxKeyDocId != null && inclusiveMax) {
                sql.append(String.format(Locale.ENGLISH, " AND (key < ? %s OR docid <= ?)", collationStr));
                argsList.add(maxKeyJSON);
                argsList.add(maxKeyDocId);
            }
        }

        sql.append(String.format(Locale.ENGLISH,
                " AND revs.sequence = 'maps_%s'.sequence AND docs.doc_id = revs.doc_id ORDER BY key",
                mapTableName()));
        sql.append(collationStr);
        if (options.isDescending()) {
            sql.append(" DESC");
        }
        sql.append(options.isDescending() ? ", docid DESC" : ", docid");

        sql.append(" LIMIT ? OFFSET ?");
        argsList.add(Integer.toString(options.getLimit()));
        argsList.add(Integer.toString(options.getSkip()));

        Log.v(Log.TAG_VIEW, "Query %s: %s | args: %s", name, sql.toString(), argsList);

        Status status = new Status(Status.OK);
        Cursor cursor = null;
        try {
            cursor = store.getStorageEngine().rawQuery(sql.toString(),
                    argsList.toArray(new String[argsList.size()]));
            // regular query
            cursor.moveToNext();
            while (!cursor.isAfterLast()) {
                // Call the block!
                byte[] keyData = cursor.getBlob(0);
                byte[] valueData = cursor.getBlob(1);
                String docID = cursor.getString(2);
                status = block.onRow(keyData, valueData, docID, cursor);
                if (status.isError())
                    break;
                else if (status.getCode() <= 0) {
                    status = new Status(Status.OK);
                    break;
                }
                cursor.moveToNext();
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return status;
    }
5418
def parse_query(query=nil, options={})
      valid_options = [:models, :lazy, :core, :results_format, :sql_options,
        :alternate_query, :boost_functions, :filter_queries, :facets, :sort,
        :scores, :operator, :latitude, :longitude, :radius, :relevance, :highlight,
        :offset, :per_page, :limit, :page,]
      query_options = {}

      return if query.nil?
      raise "Query should be a string" unless query.is_a?(String)
      raise "Invalid parameters: #{(options.keys - valid_options).join(',')}" unless (options.keys - valid_options).empty?
      begin
        Deprecation.validate_query(options)

        query_options[:filter_queries] = []
        query.strip!

        # using *:* disable index boosts, so use the type filter
        if query.blank?
          query = solr_type_condition(options)
        else
          query = sanitize_query(query)
          query_options[:filter_queries] << solr_type_condition(options)

          # put types on filtered fields
          query = replace_types([*query], ':').first
        end

        query_options[:filter_queries] += replace_types([*options[:filter_queries]], '') if options[:filter_queries]

        options[:alternate_query] ||= ''
        options[:alternate_query].strip!
        query = "#{options[:alternate_query]} #{query}" unless options[:alternate_query].blank?

        query = add_relevance query, options[:relevance]

        query_options[:query] = query

        field_list = options[:models].nil? ? solr_configuration[:primary_key_field] : "id"
        query_options[:field_list] = [field_list, 'score']

        per_page = options[:per_page] || options[:limit] || 30
        offset = options[:offset] || (((options[:page] || 1).to_i - 1) * per_page)
        query_options[:rows] = per_page
        query_options[:start] = offset

        query_options[:operator] = options[:operator]

        query_options[:boost_functions] = replace_types([*options[:boost_functions]], '').join(' ') if options[:boost_functions]

        # first steps on the facet parameter processing
        if options[:facets]
          query_options[:facets] = {}
          query_options[:facets][:limit] = -1  # TODO: make this configurable
          query_options[:facets][:sort] = :count if options[:facets][:sort]
          query_options[:facets][:mincount] = 0
          query_options[:facets][:mincount] = 1 if options[:facets][:zeros] == false
          # override the :zeros (it's deprecated anyway) if :mincount exists
          query_options[:facets][:mincount] = options[:facets][:mincount] if options[:facets][:mincount]
          query_options[:facets][:fields] = options[:facets][:fields].map{ |k| "#{k}_facet" } if options[:facets][:fields]
          query_options[:filter_queries] += replace_types([*options[:facets][:browse]]) if options[:facets][:browse]
          query_options[:facets][:queries] = replace_types([*options[:facets][:query]]) if options[:facets][:query]

          if options[:facets][:dates]
            query_options[:date_facets] = {}
            # if options[:facets][:dates][:fields] exists then :start, :end, and :gap must be there
            if options[:facets][:dates][:fields]
              [:start, :end, :gap].each { |k| raise "#{k} must be present in faceted date query" unless options[:facets][:dates].include?(k) }
              query_options[:date_facets][:fields] = []
              options[:facets][:dates][:fields].each { |f|
                if f.kind_of? Hash
                  key = f.keys[0]
                  query_options[:date_facets][:fields] << {"#{key}_d" => f[key]}
                  validate_date_facet_other_options(f[key][:other]) if f[key][:other]
                else
                  query_options[:date_facets][:fields] << "#{f}_d"
                end
              }
            end

            query_options[:date_facets][:start]   = options[:facets][:dates][:start] if options[:facets][:dates][:start]
            query_options[:date_facets][:end]     = options[:facets][:dates][:end] if options[:facets][:dates][:end]
            query_options[:date_facets][:gap]     = options[:facets][:dates][:gap] if options[:facets][:dates][:gap]
            query_options[:date_facets][:hardend] = options[:facets][:dates][:hardend] if options[:facets][:dates][:hardend]
            query_options[:date_facets][:filter]  = replace_types([*options[:facets][:dates][:filter]].collect{|k| "#{k.dup.sub!(/ *:(?!\d) */,"_d:")}"}) if options[:facets][:dates][:filter]

            if options[:facets][:dates][:other]
              validate_date_facet_other_options(options[:facets][:dates][:other])
              query_options[:date_facets][:other] = options[:facets][:dates][:other]
            end

          end
        end

        if options[:highlight]
          query_options[:highlighting] = {}
          query_options[:highlighting][:field_list] = replace_types([*options[:highlight][:fields]], '') if options[:highlight][:fields]
          query_options[:highlighting][:require_field_match] =  options[:highlight][:require_field_match] if options[:highlight][:require_field_match]
          query_options[:highlighting][:max_snippets] = options[:highlight][:max_snippets] if options[:highlight][:max_snippets]
          query_options[:highlighting][:prefix] = options[:highlight][:prefix] if options[:highlight][:prefix]
          query_options[:highlighting][:suffix] = options[:highlight][:suffix] if options[:highlight][:suffix]
        end

        query_options[:sort] = replace_types([*options[:sort]], '')[0] if options[:sort]

        if options[:radius]
          query_options[:radius] = options[:radius]
          query_options[:filter_queries] << '{!geofilt}'
        end
        query_options[:latitude] = options[:latitude]
        query_options[:longitude] = options[:longitude]

        not_dismax = query_options[:operator] == :or
        request = not_dismax ? Solr::Request::Standard.new(query_options) : Solr::Request::Dismax.new(query_options)
        ActsAsSolr::Post.execute(request, options[:core])
      rescue
        raise "#{$query} There was a problem executing your search\n#{query_options.inspect}\n: #{$!} in #{$!.backtrace.first}"
      end
    end
1211577
def _gql(query_string, query_class=Query):
  
  from .google_imports import gql  # Late import, to avoid name conflict.
  gql_qry = gql.GQL(query_string)
  kind = gql_qry.kind()
  if kind is None:
    # The query must be lacking a "FROM <kind>" class.  Let Expando
    # stand in for the model class (it won't actually be used to
    # construct the results).
    modelclass = model.Expando
  else:
    modelclass = model.Model._lookup_model(
        kind,
        tasklets.get_context()._conn.adapter.default_model)
    # Adjust kind to the kind of the model class.
    kind = modelclass._get_kind()
  ancestor = None
  flt = gql_qry.filters()
  filters = list(modelclass._default_filters())
  for name_op in sorted(flt):
    name, op = name_op
    values = flt[name_op]
    op = op.lower()
    if op == 'is' and name == gql.GQL._GQL__ANCESTOR:
      if len(values) != 1:
        raise ValueError('"is" requires exactly one value')
      [(func, args)] = values
      ancestor = _args_to_val(func, args)
      continue
    if op not in _OPS:
      raise NotImplementedError('Operation %r is not supported.' % op)
    for (func, args) in values:
      val = _args_to_val(func, args)
      prop = _get_prop_from_modelclass(modelclass, name)
      if prop._name != name:
        raise RuntimeError('Whoa! _get_prop_from_modelclass(%s, %r) '
                           'returned a property whose name is %r?!' %
                           (modelclass.__name__, name, prop._name))
      if isinstance(val, ParameterizedThing):
        node = ParameterNode(prop, op, val)
      elif op == 'in':
        node = prop._IN(val)
      else:
        node = prop._comparison(op, val)
      filters.append(node)
  if filters:
    filters = ConjunctionNode(*filters)
  else:
    filters = None
  orders = _orderings_to_orders(gql_qry.orderings(), modelclass)
  offset = gql_qry.offset()
  limit = gql_qry.limit()
  if limit < 0:
    limit = None
  keys_only = gql_qry._keys_only
  if not keys_only:
    keys_only = None
  options = QueryOptions(offset=offset, limit=limit, keys_only=keys_only)
  projection = gql_qry.projection()
  if gql_qry.is_distinct():
    group_by = projection
  else:
    group_by = None
  qry = query_class(kind=kind,
                    ancestor=ancestor,
                    filters=filters,
                    orders=orders,
                    default_options=options,
                    projection=projection,
                    group_by=group_by)
  return qry
92053
function(query, options) {
            var nresults = 0, content;

            // Define options
            options = _.defaults(options || {}, {
                silent: false,
                caseSensitive: false
            });

            query = options.caseSensitive ? query : query.toLowerCase();

            nresults = this.filter(function(model, item) {
                content = this.options.searchAttribute != null ? model.get(this.searchAttribute, "") : item.$el.text();
                content = options.caseSensitive ? content : content.toLowerCase();
                return content.search(query) >= 0;
            }, this);

            if (!options.silent) this.trigger("search", {
                query: query,
                n: nresults
            });

            return this;
        }
86333
def _get_build_kwargs(self, obj, pk_set=None, action=None, update_fields=None, reverse=None, **kwargs):
        """"""
        if action is None:
            # Check filter before rebuilding index.
            if not self._filter([obj], update_fields=update_fields):
                return

            queryset = getattr(obj, self.accessor).all()

            # Special handling for relations to self.
            if self.field.rel.model == self.field.rel.related_model:
                queryset = queryset.union(getattr(obj, self.field.rel.get_accessor_name()).all())

            return {'queryset': queryset}
        else:
            # Update to relation itself, only update the object in question.
            if self.field.rel.model == self.field.rel.related_model:
                # Special case, self-reference, update both ends of the relation.
                pks = set()
                if self._filter(self.model.objects.filter(pk__in=pk_set)):
                    pks.add(obj.pk)

                if self._filter(self.model.objects.filter(pk__in=[obj.pk])):
                    pks.update(pk_set)

                return {'queryset': self.index.object_type.objects.filter(pk__in=pks)}
            elif isinstance(obj, self.model):
                # Need to switch the role of object and pk_set.
                result = {'queryset': self.index.object_type.objects.filter(pk__in=pk_set)}
                pk_set = {obj.pk}
            else:
                result = {'obj': obj}

            if action != 'post_clear':
                # Check filter before rebuilding index.
                if not self._filter(self.model.objects.filter(pk__in=pk_set)):
                    return

            return result
1100471
function(model, settings, options, cb) {
      var baseQuery, defaultSelect, k, query, v;
      if (settings == null) {
        settings = {};
      }
      if (options == null) {
        options = {};
      }
      if (cb == null) {
        cb = function() {};
      }
      Hoek.assert(model, i18n.assertModuleRequired);
      defaultSelect = settings.defaultSelect || null;
      baseQuery = settings.baseQuery || {};
      if (_.isFunction(options)) {
        cb = options;
        options = {};
      }
      options.where || (options.where = {});
      options.select || (options.select = defaultSelect);
      for (k in baseQuery) {
        v = baseQuery[k];
        options.where[k] = v;
      }
      query = model.findOne(options.where);
      if (options.select && options.select.length > 0) {
        query = query.select(options.select);
      }
      return query.exec(cb);
    }
1071064
function genQueryString (options) {

    if ( !options.queryParams ) {
        return "";
    }

    log(options.verbose,"Now generating query string value ...");

    var queryStringParams = [];

    Object.keys(options.queryParams).forEach(function (key) {
        queryStringParams.push(createEncodedParam(key,options.queryParams[key]));
    });

    var queryString = "?";

    log(options.verbose,"Query string key/value pairs are:");

    for ( var i=0; i<queryStringParams.length; i++ ) {
        log(options.verbose,"  "+queryStringParams[i].key+"="+queryStringParams[i].value);
        queryString += queryStringParams[i].key+"="+queryStringParams[i].value;
        if ( queryStringParams[i+1] ) {
            queryString += "&";
        }
    }

    log(options.verbose,"Query string value is: "+queryString);

    return queryString;
}
752335
private String buildQuery() {
        fetchKeys();

        List<String> columns = getSelectColumns();
        String selectColumnList = columns.size() == 0 ? "*" : makeColumnList(columns);
        String partitionKeyList = makeColumnList(partitionKeys);

        return String.format("SELECT %s FROM %s.%s WHERE token(%s)>? AND token(%s)<=?" + getAdditionalWhereClauses(),
                selectColumnList, quote(keyspace), quote(cfName), partitionKeyList, partitionKeyList);
    }
805244
function queryOptionsToMongo(query, options) {
    var hash = {},
        fields = fieldsToMongo(query[options.keywords.fields]),
        omitFields = omitFieldsToMongo(query[options.keywords.omit]),
        sort = sortToMongo(query[options.keywords.sort]),
        maxLimit = options.maxLimit || 9007199254740992,
        limit = options.maxLimit || 0

    if (fields) hash.fields = fields
    // omit intentionally overwrites fields if both have been specified in the query
    // mongo does not accept mixed true/fals field specifiers for projections
    if (omitFields) hash.fields = omitFields
    if (sort) hash.sort = sort

    if (query[options.keywords.offset]) hash.skip = Number(query[options.keywords.offset])
    if (query[options.keywords.limit]) limit = Math.min(Number(query[options.keywords.limit]), maxLimit)
    if (limit) {
        hash.limit = limit
    } else if (options.maxLimit) {
        hash.limit = maxLimit
    }

    return hash
}
679368
function convertAndMergeHiddenQueryProps(model, json, omitProps, builder) {
  const queryProps = model[QUERY_PROPS_PROPERTY];

  if (!queryProps) {
    // The model has no query properties.
    return json;
  }

  const modelClass = model.constructor;
  const keys = Object.keys(queryProps);

  for (let i = 0, l = keys.length; i < l; ++i) {
    const key = keys[i];

    if (!omitProps || !omitProps.includes(key)) {
      const queryProp = queryPropToKnexRaw(queryProps[key], builder);
      json[modelClass.propertyNameToColumnName(key)] = queryProp;
    }
  }

  return json;
}
516164
function getQueryObj(query='') {
  const qObj = {};
  const pairs = (query[0] === '?' ? query.substr(1) : query).split('&');
  for (let i = 0, j = pairs.length; i < j; i++) {
    let pair = pairs[i].split('=');
    qObj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
  }
  return qObj;
}
651491
function(url, options) {
            url = this.make_url(url);
            if (options) url = url + '?' + this.propToQueryString(options);
            return url;
        }
380941
function () {
  OptionsProcessor.apply(this, arguments)

  this._single = false
  this._cached = false
  this._resolved = true

  this._query = undefined
  this._fields = undefined
  this._options = {
    limit: 500
  }
}
156565
function modelQuery(options) {
            return models.Post.findPage(options)
                .then(({data, meta}) => {
                    return {
                        posts: data.map(model => urlsForPost(model.id, model.toJSON(options), options)),
                        meta: meta
                    };
                });
        }
645476
public function buildQuery()
    {
        $model = $this->model;
        $query = $model::query();

        // perform joins
        if (is_array($this->join)) {
            foreach ($this->join as $condition) {
                list($joinModel, $column, $foreignKey) = $condition;
                $query->join($joinModel, $column, $foreignKey);
            }
        }

        // sanitze and set the filter
        $filter = $this->parseFilterInput($this->filter);
        $query->where($filter);

        // performs a search using LIKE queries
        // WARNING use sparingly, these queries are expensive
        if (!empty($this->search) && is_string($this->search) && property_exists($model, 'searchableProperties')) {
            $w = [];
            $search = addslashes($this->search);
            foreach ($model::$searchableProperties as $name) {
                $w[] = "`$name` LIKE '%$search%'";
            }

            if (count($w) > 0) {
                $query->where('('.implode(' OR ', $w).')');
            }
        }

        // eager loading
        foreach ($this->expand as $k) {
            $property = $model::getProperty($k);
            if ($property && isset($property['relation'])) {
                if (isset($property['id_property'])) {
                    $query->with($property['id_property']);
                } else {
                    $query->with($k);
                }
            }
        }

        if (isset($this->sort)) {
            $query->sort($this->sort);
        }

        // calculate limit and offset
        $start = ($this->page - 1) * $this->perPage;
        $query->start($start)->limit($this->perPage);

        return $query;
    }