Execute RQL query
974764
function(query) {
        var q = rql2es(_.rql(query)),
            mapFn = q.fields ?
                          function(x) { return x.fields; } 
                        : function(x) { return x._source; };
        return ajax('POST', this._url + '/_search', q)
            .then(function(result) {
                return result.hits.hits.map(mapFn);
            });
    }
478168
function executeQueryCore(em, query, queryOptions, dataService) {
    try {
      var results;
      var metadataStore = em.metadataStore;

      if (metadataStore.isEmpty() && dataService.hasServerMetadata) {
        throw new Error("cannot execute _executeQueryCore until metadataStore is populated.");
      }

      if (queryOptions.fetchStrategy === FetchStrategy.FromLocalCache) {
        try {
          var qr = executeQueryLocallyCore(em, query);
          return Q.resolve({ results: qr.results, entityManager: em, inlineCount: qr.inlineCount, query: query });
        } catch (e) {
          return Q.reject(e);
        }
      }

      var mappingContext = new MappingContext({
        query: query,
        entityManager: em,
        dataService: dataService,
        mergeOptions: {
          mergeStrategy: queryOptions.mergeStrategy,
          noTracking: !!query.noTrackingEnabled,
          includeDeleted: queryOptions.includeDeleted
        }
      });

      var validateOnQuery = em.validationOptions.validateOnQuery;

      return dataService.adapterInstance.executeQuery(mappingContext).then(function (data) {
        var result = __wrapExecution(function () {
          var state = { isLoading: em.isLoading };
          em.isLoading = true;
          em._pendingPubs = [];
          return state;
        }, function (state) {
          // cleanup
          em.isLoading = state.isLoading;
          em._pendingPubs.forEach(function (fn) {
            fn();
          });
          em._pendingPubs = null;
          em._hasChangesAction && em._hasChangesAction();
          // HACK for GC
          query = null;
          mappingContext = null;
          // HACK: some errors thrown in next function do not propogate properly - this catches them.

          if (state.error) {
            Q.reject(state.error);
          }

        }, function () {
          var nodes = dataService.jsonResultsAdapter.extractResults(data);
          nodes = __toArray(nodes);

          results = mappingContext.visitAndMerge(nodes, { nodeType: "root" });
          if (validateOnQuery) {
            results.forEach(function (r) {
              // anon types and simple types will not have an entityAspect.
              r.entityAspect && r.entityAspect.validateEntity();
            });
          }
          mappingContext.processDeferred();
          // if query has expand clauses walk each of the 'results' and mark the expanded props as loaded.
          markLoadedNavProps(results, query);
          var retrievedEntities = __objectMap(mappingContext.refMap);
          return { results: results, query: query, entityManager: em, httpResponse: data.httpResponse, inlineCount: data.inlineCount, retrievedEntities: retrievedEntities };
        });
        return Q.resolve(result);
      }, function (e) {
        if (e) {
          e.query = query;
          e.entityManager = em;
        }
        return Q.reject(e);
      });

    } catch (e) {
      if (e) {
        e.query = query;
      }
      return Q.reject(e);
    }
  }
654799
function querySearch (query) {
      var results = query ? self.states.filter(createFilterFor(query)) : self.states,
          deferred;
      if (self.simulateQuery) {
        deferred = $q.defer();
        $timeout(function () { deferred.resolve(results); }, Math.random() * 1000, false);
        return deferred.promise;
      } else {
        return results;
      }
    }
1155455
function ServerQueryList(qry, limit, Resource) {
      // Allow qry to be a promise
      qry = $q
        .when(qry)
        .then(normalizeQuery)
        .then(function(_qry) {
          if (limit) {
            _qry.limit = limit;
          }
          return _qry;
        });

      var emitPromise = null;
      var results = new ArrayEmitter();
      var currentLimit = 0;
      var currentSkip = 0;
      var lastBatchSize = 0;
      var _pagingOpts = {};

      results.loading = true;

      function query(data) {
        // We only want to do one emit at a time (otherwise we could get into a bad state)
        if (angular.isFunction(data)) {
          data = data();
        }

        // Store off the query - make sure its a promise
        qry = $q.when(data);

        return qry.then(function(data) {
          // If we have an existing emitPromise then wait for it to resolve before we run
          var promise;
          if (emitPromise) {
            promise = emitPromise.then(function() {
              return sock.query(data);
            });
          } else {
            emitPromise = promise = sock.query(data);
          }

          return promise;
        });
      }

      function newData(_qryId, response, force) {
        if (!response) {
          return;
        }

        var deferred = $q.defer();
        var ids = response.ids;
        var pagingOpts = response.pagingOpts;

        // So far we've only got the ids of the qry result - go and fetch the actual objects.
        // This mechanism saves bandwidth by only getting the object data once then listening
        // for changes to it
        //
        // If we are forcing we want to get both the old and new ids to check for any changes
        // deletions etc..
        var getIds = ids;
        if (force) {
          var oldIds = pluck(results, '_id');
          getIds = union(ids, oldIds);
        }

        Resource.get(getIds, force).$promise.then(function(ress) {
          var ressmap = {};
          ress.forEach(function(res) {
            ressmap[res._id] = res;
          });

          // We don't allow repeated ids so just iterate over the results
          var tmpResults = [];
          ids.forEach(function(id) {
            tmpResults.push(ressmap[id]);
          });

          // Do we need to do a transform?
          var rprom;
          if (angular.isFunction(results.transform)) {
            rprom = $q.when(results.transform(tmpResults));
          } else {
            rprom = $q.when(tmpResults);
          }

          return rprom.then(function(transformed) {
            results.length = 0;
            transformed.forEach(function(res) {
              results.push(res);
            });

            // Since we now have data in our array store off limit data
            currentLimit = tmpResults.length;
            results.$skip = currentSkip = qry && qry.skip ? qry.skip : 0;
            lastBatchSize = lastBatchSize || tmpResults.length;
            _pagingOpts = pagingOpts;
            results.hasNext = pagingOpts.next != null;
            results.hasPrev = pagingOpts.prev != null;

            // Data has come back
            results.loading = false;

            results.$emitter.emit('update', results);

            deferred.resolve(results);
          });
        });

        return deferred.promise;
      }

      function refreshQuery(force) {
        var req = query(qry);
        var promise = req.then(function(res) {
          // If we get no response (the app could be offline) then just resolve with
          // the existing results
          if (angular.isUndefined(res)) {
            results.loading = false;
            return results;
          }

          var _qryId = res.qryId;
          var response = res.data;

          return newData(_qryId, response, force);
        });
        return promise;
      }

      function replace(_qry) {
        // Do the query but replace the existing query
        return $q
          .when(_qry)
          .then(normalizeQuery)
          .then(function(normQry) {
            // We allow a query to resolve to something falsy - in which case we just
            // drop it
            if (!normQry) {
              return;
            }

            return qry.then(function(oldqry) {
              if (JSON.stringify(oldqry) !== JSON.stringify(normQry)) {
                // query is different - continue
                var req = query(normQry);

                var promise = req.then(function(res) {
                  // If we get no response (the app could be offline) then just resolve with
                  // the existing results
                  if (angular.isUndefined(res)) {
                    results.loading = false;
                    return results;
                  }

                  // We do have a response. Continue
                  var _qryId = res.qryId;
                  var data = res.data;

                  return newData(_qryId, data);
                });

                return promise;
              }
            });
          });
      }

      function extendResults(obj, noSanitize) {
        // Sanitize the object
        if (!noSanitize) {
          if (obj._q) {
            obj = obj._q;
          } else {
            obj = { find: obj };
          }
        }

        return qry.then(function(resolved) {
          var _qry = extendQuery(resolved, obj);
          return replace(_qry);
        });
      }

      function next(num) {
        var promise;
        var extendSize;
        if (_pagingOpts.next) {
          lastBatchSize = extendSize = num || lastBatchSize;
          var extendObj = {
            limit: currentLimit + extendSize
          };
          promise = extendResults(extendObj, true);
        } else {
          var deferred = $q.defer();
          deferred.resolve();
          promise = deferred.promise;
        }

        return promise;
      }

      function prev(num) {
        var promise;
        var extendSize;
        if (_pagingOpts.prev) {
          lastBatchSize = extendSize = num || lastBatchSize;
          var extendObj = {
            skip: Math.max(currentSkip - extendSize, 0),
            limit: currentLimit + extendSize
          };
          promise = extendResults(extendObj, true);
        } else {
          var deferred = $q.defer();
          deferred.resolve();
          promise = deferred.promise;
        }

        return promise;
      }

      function get() {
        return Resource.get.apply(Resource, arguments);
      }

      function chain(Model, qryFn) {
        return Chain(results, Model, qryFn);
      }

      results.$newData = newData;
      results.$refresh = refreshQuery;
      results.extend = extendResults;
      results.replace = replace;
      results.get = get;
      results.next = next;
      results.prev = prev;
      results.$promise = refreshQuery().then(function(res) {
        results.$resolved = true;
        return res;
      });
      results.$resolved = false;
      results.chain = chain;
      results.$Model = Resource;
      results.$skip = 0;

      // Put currentSkip and currentLimit onto the results
      Object.defineProperty(results, 'currentLimit', {
        enumerable: true,
        get: () => {
          return currentLimit;
        }
      });
      Object.defineProperty(results, 'currentSkip', {
        enumerable: true,
        get: () => {
          return currentSkip;
        }
      });

      return results;
    }
1223573
function FormatQRY(query) { 
						var R = '', Q = query; switch(true) {
							case THS.QisFunction: return CleanQRY(Q.toString());
							case THS.QisArray: return Q.join("\n").replace("\t","");
							default: return R;
						};
					}
486671
function(query) {
        var self = this;
        return Q.ninvoke(fs, 'readdir', path.join(this.backend.options.path, this.name))
            .then(function(files) {
                return Q.all(files.map(function(f) {
                    return self.get(f);
                }));
            })
            .then(function(vals) {
                return _.query(vals, query);
            });
    }
828025
function query(q) {
  var filter = Object.keys(q);
  var isValid;
  var valid;
  var val;

  return this.reduce((list, ps) => {
    isValid = filter.every(key => {
      val = q[key];
      valid = true;

      if (typeof val === 'string') {
        if (val.indexOf('<') > -1) {
          valid = ps[key] < cleanValue(val, '<');
        }

        if (valid && val.indexOf('>') > -1) {
          valid = ps[key] > cleanValue(val, '>');
        }

        if (valid && val.indexOf('~') > -1) {
          valid = ps[key].indexOf(q[key].replace('~', '')) > -1;
        }
      } else {
        valid = ps[key] === val;
      }

      return valid;
    });

    if (isValid) list.push(ps);

    return list;
  }, []);
}
141521
def query(self, query, inplace=True):
        
        # TODO: add to queue
        result = self.data.query(query, inplace=inplace)
        return result
432323
function runQuery(client, queryString, args, callback) {
  if (activeBackend === 'mysql') {
    queryString = queryString.replace(/\$\d+/, '?');
  }

  client.query(queryString, args, function (err, result) {
    if (err) {
      callback(err, null);
      return;
    }
    if (activeBackend === 'mysql') {
      callback(err, result);
    }
    else if (activeBackend === 'pgsql') {
      var rows = [];
      if (result.rows) {
        rows = result.rows;
      }
      callback(err, rows);
    }
  });
}
150240
def execute(self, query_string, params=None):
    
    cr = self.connection.cursor()
    logger.info("SQL: %s (%s)", query_string, params)
    self.last_query = (query_string, params)
    t0 = time.time()
    cr.execute(query_string, params or self.core.empty_params)
    ms = (time.time() - t0) * 1000
    logger.info("RUNTIME: %.2f ms", ms)
    self._update_cursor_stats(cr)
    return cr
238385
function query(base, q, callback) {
    // Added unescape to fix URI errors resulting from hexadecimal escape sequences
    var url = util.format("%s?%s", base, querystring.unescape(querystring.stringify(q)));
    request(url, function (err, response) {
        if (err) return callback(err);
        callback(null, response.body);
    });
}
339587
def execute(self):
        
        self.response = SolrResponse.load_http_response(
            self.session.get(self.HTTP_ENDPOINT, params=self.query)
        )

        # ADS will apply a ceiling to 'rows' and re-write the query
        # This code checks if that happened by comparing the reponse
        # "rows" with what we sent in our query
        # references https://github.com/andycasey/ads/issues/45
        recv_rows = int(self.response.responseHeader.get("params", {}).get("rows"))
        if recv_rows != self.query.get("rows"):
            self._query['rows'] = recv_rows
            warnings.warn("Response rows did not match input rows. "
                          "Setting this query's rows to {}".format(self.query['rows']))

        self._articles.extend(self.response.articles)
        if self._query.get('start') is not None:
            self._query['start'] += self._query['rows']
        elif self._query.get('cursorMark') is not None:
            self._query['cursorMark'] = self.response.json.get("nextCursorMark")

        self._highlights.update(self.response.json.get("highlighting", {}))
1005054
public SolrDocumentList runQuery(String q, List<String> fieldList,
			int results) throws SolrServerException {
		SolrQuery query = new SolrQuery();
		query.setQuery(escapeQuery(q));
		query.setRows(results);
		query.setFields(fieldList.toArray(new String[1]));
		QueryResponse rsp = server.query(query, METHOD.POST);
		return rsp.getResults();
	}
106892
def __execute_queries(self):
        """"""

        def func(item):
            or_check = False
            for queries in self._queries:
                and_check = True
                for query in queries:
                    and_check &= self._matcher._match(
                        item.get(query.get('key'), None),
                        query.get('operator'),
                        query.get('value')
                    )
                or_check |= and_check
            return or_check

        self._json_data = list(filter(lambda item: func(item), self._json_data))
716243
function Query(model, action, conditions) {
    var self = this;
    self.model = model;
    self.action = action || 'all';
    self.q = {
        conditions: {},
        params: {},
        pkey: false,
        fields: false
    };
    if (typeof conditions === 'object') {
        self.q.conditions = helpers.merge(self.q.conditions, conditions);
    }

    ['all', 'run', 'exec'].forEach(function(method) {
        self[method] = function(params, callback) {
            if (arguments.length === 1) {
                callback = params;
                params = {};
            }
            params = buildQuery(params, this);
            var action = self.action ? self.action : 'all';
            self.model[action](params, callback);
        };
    });

    ['find', 'findOne'].forEach(function(method) {
        self[method] = function(params, callback) {
            if (arguments.length === 1) {
                callback = params;
                params = {};
            }
            params = buildQuery(params, this);
            self.model[method](params, callback);
        };
    });

    ['skip', 'limit', 'order', 'sort', 'group'].forEach(function(method) {
        self[method] = function(key, value) {
            this.q.pkey = false;
            if (method === 'sort') {
                method = 'order';
            }
            if (typeof value === 'undefined') {
                if (/^-/.test(key)) {
                    this.q.params[method] = key.replace(/^-/, '') + ' DESC';
                } else {
                    this.q.params[method] = key;
                }
            } else {
                this.q.params[method] = key + ' ' + value;
            }
            return this;
        };
    });

    self.asc = function(value) {
        this.q.pkey = false;
        this.q.params['order'] = value + ' ASC';
        return this;
    };

    self.desc = function(value) {
        this.q.pkey = false;
        this.q.params['order'] = value + ' DESC';
        return this;
    };

    self.where = function(key, value) {
        if (typeof value === 'undefined') {
            this.q.pkey = key;
        } else {
            this.q.pkey = false;
            this.q.conditions[key] = value;
        }
        return this;
    };

    self.or = function(values) {
        if (Array.isArray(values)) {
            this.q.conditions['or'] = values;
        }
        return this;
    };

    self.range = function(key, from, to) {
        if (typeof to === 'undefined') {
            if (this.q.pkey) {
                to = from;
                from = key;
                if (typeof this.q.conditions[this.q.pkey] === 'undefined') {
                    this.q.conditions[this.q.pkey] = {};
                }
                this.q.conditions[this.q.pkey].gt = from;
                this.q.conditions[this.q.pkey].lt = to;
            }
        } else {
            this.q.pkey = false;
            if (typeof this.q.conditions[key] === 'undefined') {
                this.q.conditions[key] = {};
            }
            this.q.conditions[key].gt = from;
            this.q.conditions[key].lt = to;
        }
        return this;
    };

    ['gt', 'gte', 'lt', 'lte', 'in', 'inq', 'ne', 'neq', 'nin', 'regex', 'like', 'nlike', 'between'].forEach(function(method) {
        self[method] = function(key, value) {
            if (typeof value === 'undefined') {
                if (this.q.pkey) {
                    if (typeof this.q.conditions[this.q.pkey] === 'undefined') {
                        this.q.conditions[this.q.pkey] = {};
                    }
                    this.q.conditions[this.q.pkey][method] = key;
                }
            } else {
                this.q.pkey = false;
                if (typeof this.q.conditions[key] === 'undefined') {
                    this.q.conditions[key] = {};
                }
                this.q.conditions[key][method] = value;
            }
            return this;
        };
    });

    self.slice = function(values) {
        if (Array.isArray(values)) {
            if (typeof values[1] === 'undefined') {
                this.q.params['limit'] = values[0];
            } else {
                this.q.params['skip'] = values[0];
                this.q.params['limit'] = values[1];
            }
        }
        return this;
    };

    /**
     * Destroy records
     * @param {Object} params
     * @param {Function} callback
     */
    self.remove = function(params, callback) {
        if (arguments.length === 1) {
            callback = params;
            params = {};
        }
        params = buildQuery(params, this);
        self.model.remove(params, callback);
    };

    function buildQuery(opts, query) {
        if (typeof opts.where === 'undefined') {
            opts.where = {};
        }
        opts.where = helpers.merge(opts.where, query.q.conditions);
        query.q.conditions = {};

        for (var pkey in query.q.params) {
            if (typeof opts[pkey] === 'undefined') {
                opts[pkey] = {};
            }
            opts[pkey] = query.q.params[pkey];
        }

        query.q.params = {};
        query.q.pkey = false;
        return opts;
    }
}
122791
def get_query(self, q, request):
        
        return Project.objects.filter(
            Q(pid__icontains=q)
            | Q(name__icontains=q)
        )
685918
def execute_cql_query(self, query, compression):
    
    self._seqid += 1
    d = self._reqs[self._seqid] = defer.Deferred()
    self.send_execute_cql_query(query, compression)
    return d