Returns a function that will be used to instantiate query results
481167
def _get_result_constructor(self):
        
        if not self._values_list: # we want models
            return lambda rows: self.model._construct_instance(rows)
        elif self._flat_values_list: # the user has requested flattened list (1 value per row)
            return lambda row: row.popitem()[1]
        else:
            return lambda row: self._get_row_value_list(self._only_fields, row)
1119013
def stat_smt_query(func: Callable):
    """"""
    stat_store = SolverStatistics()

    def function_wrapper(*args, **kwargs):
        if not stat_store.enabled:
            return func(*args, **kwargs)

        stat_store.query_count += 1
        begin = time()

        result = func(*args, **kwargs)

        end = time()
        stat_store.solver_time += end - begin

        return result

    return function_wrapper
777392
def compile_query(query: dict) -> PyQuery:
    

    def _pair_to_dict(pair):
        if isinstance(pair, dict):
            return pair
        return {pair[0]: pair[1]}

    def _reduce(pair):
        try:
            return {'and': (_pair_to_dict(pair[0]), _pair_to_dict(pair[1]))}
        except (KeyError, IndexError):
            return _pair_to_dict(pair)

    def _get_first_pair(d: dict):
        return list(query.items())[0]

    if len(query) < 2:
        return compile_single_item(*_get_first_pair(query))
    try:
        reduced = reduce(lambda x, y: _reduce((x, y)), query.items())
    except KeyError:
        print(query)
        reduced = query
        raise
    return compile_single_item(*_get_first_pair(reduced))
708415
private List<?> getResultList(Query query) {
        // TODO : use lazy fetch here?
        if (projection != null) {
            List<?> results = query.getResultList();
            List<Object> rv = new ArrayList<Object>(results.size());
            for (Object o : results) {
                if (o != null) {
                    Object[] arr;
                    if (!o.getClass().isArray()) {
                        arr = new Object[]{o};
                    } else {
                        arr = (Object[]) o;
                    }
                    if (projection.getArgs().size() < arr.length) {
                        Object[] shortened = new Object[projection.getArgs().size()];
                        System.arraycopy(arr, 0, shortened, 0, shortened.length);
                        arr = shortened;
                    }
                    rv.add(projection.newInstance(arr));
                } else {
                    rv.add(null);
                }
            }
            return rv;
        } else {
            return query.getResultList();
        }
    }
179110
def results_decorator(func):
    
    # Wrap function to maintian the original doc string, etc
    @wraps(func)
    def decorator(lookup_cls):
        # Construct a class decorator from the original function
        original = lookup_cls.results
        def inner(self, request):
            # Wrap lookup_cls.results by first calling func and checking the result
            result = func(request)
            if isinstance(result, HttpResponse):
                return result
            return original(self, request)
        # Replace original lookup_cls.results with wrapped version
        lookup_cls.results = inner
        return lookup_cls
    # Return the constructed decorator
    return decorator
391627
def Query(self, query, parameters=None):
    
    # TODO: catch Warning and return None.
    # Note that we cannot pass parameters as a keyword argument here.
    # A parameters value of None is not supported.
    if parameters:
      self._cursor.execute(query, parameters)
    else:
      self._cursor.execute(query)

    return self._cursor.fetchall()
23999
def extract_queries(self, args, kwargs):
        '''
        
        '''
        # Please note the function signature is NOT an error.  Neither args, nor
        # kwargs should have asterisks.  We are passing in a list and dict,
        # rather than receiving variable args.  Adding asterisks WILL BREAK the
        # function completely.

        # First, this is the query buffer.  Contains lists of [base,sql]
        qbuffer = []

        # Add on the non-keywords...
        qbuffer.extend([[None, s] for s in args])

        # And then the keywords...
        # They aren't in definition order, but they can't conflict each other.
        klist = list(kwargs.keys())
        klist.sort()
        qbuffer.extend([[k, kwargs[k]] for k in klist])

        # Filter out values that don't have queries.
        qbuffer = [x for x in qbuffer if (
                (isinstance(x[1], six.string_types) and len(x[1]))
                or
                (isinstance(x[1], (list, tuple)) and (len(x[1]) > 0) and x[1][0])
                or
                (isinstance(x[1], dict) and 'query' in x[1] and len(x[1]['query']))
            )]

        # Next, turn the whole buffer into full dicts.
        for qb in qbuffer:
            defaults = {'query': '',
                        'depth': 0,
                        'as_list': False,
                        'with_lists': None,
                        'ignore_null': False
                        }
            if isinstance(qb[1], six.string_types):
                defaults['query'] = qb[1]
            elif isinstance(qb[1], (list, tuple)):
                defaults['query'] = qb[1][0]
                if len(qb[1]) > 1:
                    defaults['depth'] = qb[1][1]
                # May set 'as_list' from qb[1][2].
            else:
                defaults.update(qb[1])
                if defaults['with_lists'] and isinstance(defaults['with_lists'], six.string_types):
                    defaults['with_lists'] = [
                        int(i) for i in defaults['with_lists'].split(',')
                    ]
            qb[1] = defaults

        return qbuffer
1278852
def get_query_builder(self, *args, **kwargs):
        
        query_builder = self.get_query_builder_class()
        return query_builder(*args, **kwargs)
1031383
def _find(api_method, query, limit, return_handler, first_page_size, **kwargs):
    ''' 
    '''
    num_results = 0

    if "limit" not in query:
        query["limit"] = first_page_size

    while True:
        resp = api_method(query, **kwargs)

        by_parent = resp.get('byParent')
        descriptions = resp.get('describe')
        def format_result(result):
            if return_handler:
                result = dxpy.get_handler(result['id'], project=result.get('project'))
            if by_parent is not None:
                return result, by_parent, descriptions
            else:
                return result

        for i in resp["results"]:
            if num_results == limit:
                return
            num_results += 1
            yield format_result(i)

        # set up next query
        if resp["next"] is not None:
            query["starting"] = resp["next"]
            query["limit"] = min(query["limit"]*2, 1000)
        else:
            return
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);
    }
835005
def _query_and_op(self, tree, table, method_name, method_kwargs):
        
        result = []
        if tree.keys_in:
            if tree.using:
                raise SyntaxError("Cannot use USING with KEYS IN")
            keys = self._iter_where_in(tree)
        else:
            visitor = Visitor(self.reserved_words)
            (action, kwargs, _) = self._build_query(table, tree, visitor)
            attrs = [visitor.get_field(table.hash_key.name)]
            if table.range_key is not None:
                attrs.append(visitor.get_field(table.range_key.name))
            kwargs["attributes"] = attrs
            kwargs["expr_values"] = visitor.expression_values
            kwargs["alias"] = visitor.attribute_names
            # If there is no 'where' on this update/delete, check with the
            # caution_callback before proceeding.
            if (
                visitor.expression_values is None
                and callable(self.caution_callback)
                and not self.caution_callback(method_name)  # pylint: disable=E1102
            ):
                return False
            method = getattr(self.connection, action + "2")
            keys = method(table.name, **kwargs)
            if self._explaining:
                try:
                    list(keys)
                except ExplainSignal:
                    keys = [{}]

        method = getattr(self.connection, method_name + "2")
        count = 0
        for key in keys:
            try:
                ret = method(table.name, key, **method_kwargs)
            except CheckFailed:
                continue
            count += 1
            if ret:
                result.append(ret)
        if result:
            return result
        else:
            return count
458531
function(cb) {
      // For a basic match
      usableQueryKeys = [];
      Object.keys(query).forEach(function(k) {
        if (
          typeof query[k] === 'string' ||
          typeof query[k] === 'number' ||
          typeof query[k] === 'boolean' ||
          util.isDate(query[k]) ||
          query[k] === null
        ) {
          usableQueryKeys.push(k);
        }
      });
      usableQueryKeys = _.intersection(usableQueryKeys, indexNames);
      if (usableQueryKeys.length > 0) {
        return cb(null, self.indexes[usableQueryKeys[0]].getMatching(query[usableQueryKeys[0]]));
      }

      // For a $in match
      usableQueryKeys = [];
      Object.keys(query).forEach(function(k) {
        if (query[k] && query[k].hasOwnProperty('$in')) {
          usableQueryKeys.push(k);
        }
      });
      usableQueryKeys = _.intersection(usableQueryKeys, indexNames);
      if (usableQueryKeys.length > 0) {
        return cb(
          null,
          self.indexes[usableQueryKeys[0]].getMatching(query[usableQueryKeys[0]].$in),
        );
      }

      // For a comparison match
      usableQueryKeys = [];
      Object.keys(query).forEach(function(k) {
        if (
          query[k] &&
          (query[k].hasOwnProperty('$lt') ||
            query[k].hasOwnProperty('$lte') ||
            query[k].hasOwnProperty('$gt') ||
            query[k].hasOwnProperty('$gte'))
        ) {
          usableQueryKeys.push(k);
        }
      });
      usableQueryKeys = _.intersection(usableQueryKeys, indexNames);
      if (usableQueryKeys.length > 0) {
        return cb(
          null,
          self.indexes[usableQueryKeys[0]].getBetweenBounds(query[usableQueryKeys[0]]),
        );
      }

      // By default, return all the DB data
      return cb(null, self.getAllData());
    }
857244
def refine(query, description):
    

    for attribute, arguments in description.items():
        if hasattr(query, attribute):
            attribute = getattr(query, attribute)
        else:
            raise ValueError("Unknown query method: " + attribute)

        # query descriptions are often automatically generated, and
        # may include empty calls, which we skip
        if utils.isempty(arguments):
            continue

        if callable(attribute):
            method = attribute
            if isinstance(arguments, dict):
                query = method(**arguments)
            elif isinstance(arguments, list):
                query = method(*arguments)
            else:
                query = method(arguments)
        else:
            setattr(attribute, arguments)

    return query
811000
def as_cql_query(self, formatted=False):
        
        sep = '\n    ' if formatted else ' '
        keyspace = protect_name(self.keyspace)
        name = protect_name(self.name)
        arg_list = ', '.join(["%s %s" % (protect_name(n), t)
                             for n, t in zip(self.argument_names, self.argument_types)])
        typ = self.return_type
        lang = self.language
        body = self.body
        on_null = "CALLED" if self.called_on_null_input else "RETURNS NULL"

        return "CREATE FUNCTION %(keyspace)s.%(name)s(%(arg_list)s)%(sep)s" \
               "%(on_null)s ON NULL INPUT%(sep)s" \
               "RETURNS %(typ)s%(sep)s" \
               "LANGUAGE %(lang)s%(sep)s" \
               "AS $$%(body)s$$" % locals()
503216
function query (query, params) {
        let rows = [];
        let stmt = sql.prepare(query);
        params = normalizeParams(params);
        stmt.bind(params);
        while(stmt.step()) {
            rows.push(stmt.getAsObject());
        }
        stmt.free();
        return rows;
    }
709886
function wrapQueryMethod(fn, ctx) {
    return function() {
        // Obtain function arguments
        var args = [].slice.call(arguments);
        
        // Return a thunkified function that receives a done callback
        return function(done) {
            // Add a custom callback to provided args
            args.push(function(err, result) {
                // Query failed?
                if (err) {
                    return done(err);
                }

                // Query succeeded
                done(null, result);
            });

            // Execute the query
            fn.apply(ctx, args);
        };
    };
}
691898
def query(self, *args, **kwargs):
        
        clone = self._clone()
        queries = []
        from pyes.query import Query

        if args:
            for f in args:
                if isinstance(f, Query):
                    queries.append(f)
                else:
                    raise TypeError('Only Query objects can be passed as argument')

        for field, value in kwargs.items():
            if value == [None]:
                value = ["$$$$"]
            queries.append(self._build_inner_query(field, value))

        clone._queries.extend(queries)
        return clone