Special decorator encapsulating query method.
163119
def run(wrapped):
    

    @wraps(wrapped)
    def _run(self, query, bindings=None, *args, **kwargs):
        self._reconnect_if_missing_connection()

        start = time.time()
        try:
            result = wrapped(self, query, bindings, *args, **kwargs)
        except Exception as e:
            result = self._try_again_if_caused_by_lost_connection(
                e, query, bindings, wrapped
            )

        t = self._get_elapsed_time(start)
        self.log_query(query, bindings, t)

        return result

    return _run
950502
def decorator(f):
    """"""
    @functools.wraps(f)
    def decoratored_function(*args, **kwargs):
        if args and len(args) == 1:
            return f(*args, **kwargs)

        if args:
            raise TypeError(
                "This decorator only accepts extra keyword arguments.")

        return lambda g: f(g, **kwargs)

    return decoratored_function
531952
def filter_query(key, expression):
    """"""
    if (isinstance(expression, dict)
            and len(expression) == 1
            and list(expression.keys())[0].startswith('$')):
        compiled_expression = compile_query(expression)
    elif callable(expression):
        def _filter(index, expression=expression):
            result = [store_key
                      for value, store_keys in index.get_index().items()
                      if expression(value)
                      for store_key in store_keys]
            return result
        compiled_expression = _filter
    else:
        compiled_expression = expression

    def _get(query_function, key=key, expression=compiled_expression):
        """Get document key and check against expression."""
        return query_function(key, expression)

    return _get
275091
def _one_to_many_query(cls, query_obj, search4, model_attrib):
        
        model = model_attrib.parent.class_

        if isinstance(search4, str):
            query_obj = query_obj.join(model).filter(model_attrib.like(search4))

        elif isinstance(search4, int):
            query_obj = query_obj.join(model).filter(model_attrib == search4)

        elif isinstance(search4, Iterable):
            query_obj = query_obj.join(model).filter(model_attrib.in_(search4))

        return query_obj
1015699
def filter_query(self, query):
        

        for filter_class in list(self.filter_classes):
            query = filter_class().filter_query(self.request, query, self)

        return query
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
560622
def query(self, model, **kwargs):
        ''''''
        sm = self.model(model)
        query_class = sm.manager.query_class or Query
        return query_class(sm._meta, self, **kwargs)
1278852
def get_query_builder(self, *args, **kwargs):
        
        query_builder = self.get_query_builder_class()
        return query_builder(*args, **kwargs)
1017787
def invenio_query_factory(parser=None, walkers=None):
    """"""
    parser = parser or Main
    walkers = walkers or [PypegConverter()]
    walkers.append(ElasticSearchDSL())

    def invenio_query(pattern):
        query = pypeg2.parse(pattern, parser, whitespace="")
        for walker in walkers:
            query = query.accept(walker)
        return query
    return invenio_query
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))
765311
def _query(options, collection_name, num_to_skip,
           num_to_return, query, field_selector, opts, check_keys):
    """"""
    encoded = _dict_to_bson(query, check_keys, opts)
    if field_selector:
        efs = _dict_to_bson(field_selector, False, opts)
    else:
        efs = b""
    max_bson_size = max(len(encoded), len(efs))
    return b"".join([
        _pack_int(options),
        _make_c_string(collection_name),
        _pack_int(num_to_skip),
        _pack_int(num_to_return),
        encoded,
        efs]), max_bson_size
1086624
def _query_wrap(fun, *args, **kwargs):
    
    with _query_lock:
        global _last_query_time
        since_last_query = time.time() - _last_query_time
        if since_last_query < QUERY_WAIT_TIME:
            time.sleep(QUERY_WAIT_TIME - since_last_query)
        _last_query_time = time.time()
        return fun(*args, **kwargs)
360316
def query_all(self):
        
        if DJANGO_20_PLUS:
            obj = self._clone()
        else:
            obj = self._clone(klass=SalesforceQuerySet)  # pylint: disable=unexpected-keyword-arg
        obj.query.set_query_all()
        return obj
1136364
def query(options, collection_name, num_to_skip,
          num_to_return, query, field_selector, opts, check_keys=False):
    
    data = struct.pack("<I", options)
    data += bson._make_c_string(collection_name)
    data += struct.pack("<i", num_to_skip)
    data += struct.pack("<i", num_to_return)
    encoded = bson.BSON.encode(query, check_keys, opts)
    data += encoded
    max_bson_size = len(encoded)
    if field_selector is not None:
        encoded = bson.BSON.encode(field_selector, False, opts)
        data += encoded
        max_bson_size = max(len(encoded), max_bson_size)
    (request_id, query_message) = __pack_message(2004, data)
    return (request_id, query_message, max_bson_size)
784026
def filter(self, **kwargs):
        """"""
        assert not self._primary_keys
        self.queryset = self.queryset.filter(**kwargs)
        return self
830757
def paginated_retrieval(methodname, itemtype):
    """"""
    return compose(
        reusable,
        basic_interaction,
        map_yield(partial(_params_as_get, methodname)),
    )
1373055
def query_decl(self, **kwargs):
        """"""
        return self.session.query(Decl).filter_by(**kwargs).all()