Preprocess collection queries.
764820
def _build_cache():
    """"""
    query = current_app.config['COLLECTIONS_DELETED_RECORDS']
    for collection in Collection.query.filter(
            Collection.dbquery.isnot(None)).all():
        yield collection.name, dict(
            query=query.format(dbquery=collection.dbquery),
            ancestors=set(_ancestors(collection)),
        )
    raise StopIteration
486656
def collections(record, key, value):
    """"""
    return {
        'primary': value.get('a'),
        'secondary': value.get('b'),
        'deleted': value.get('c'),
    }
53213
protected Query buildPrefetchQuery(Collection ids)
    {
        CollectionDescriptor cds = getCollectionDescriptor();
        QueryByCriteria query = buildPrefetchQuery(ids, cds.getForeignKeyFieldDescriptors(getItemClassDescriptor()));

        // check if collection must be ordered
        if (!cds.getOrderBy().isEmpty())
        {
            Iterator iter = cds.getOrderBy().iterator();
            while (iter.hasNext())
            {
                query.addOrderBy((FieldHelper) iter.next());
            }
        }

        return query;
    }
694398
def apply(query, collection=None):
    
    if not collection:
        return query
    result_tree = create_collection_query(collection)
    return AndOp(query, result_tree)
872066
def collections(self, values):
        """"""
        # if cache server is configured, save collection list
        if self.cache:
            self.cache.set(
                self.app.config['COLLECTIONS_CACHE_KEY'], values)
1224420
private static function addQueries() {
        self::$debugbar->addCollector(new MessagesCollector('queries'));
        self::$queries = ORM::get_query_log();
        if (self::$queries) {
            foreach (self::$queries as $query) {
                self::$debugbar['queries']->info($query);
            }
        }
    }
589173
def _fetch_objects(self, key, value):
        """"""
        return self.to_cls.query.filter(**{key: value})
655763
def query(options, collection_name,
          num_to_skip, num_to_return, query, field_selector=None):
    
    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)
    data += bson.BSON.encode(query)
    if field_selector is not None:
        data += bson.BSON.encode(field_selector)
    return __pack_message(2004, data)
1079045
def many(cls, filter=None, **kwargs):
        """"""
        from mongoframes.queries import Condition, Group, to_refs

        # Flatten the projection
        kwargs['projection'], references, subs = \
                cls._flatten_projection(
                    kwargs.get('projection', cls._default_projection)
                    )

        # Find the documents
        if isinstance(filter, (Condition, Group)):
            filter = filter.to_dict()

        documents = list(cls.get_collection().find(to_refs(filter), **kwargs))

        # Dereference the documents (if required)
        if references:
            cls._dereference(documents, references)

        # Add sub-frames to the documents (if required)
        if subs:
            cls._apply_sub_frames(documents, subs)

        return [cls(d) for d in documents]
843228
def _process_query(self, query):
        """"""
        key, val = query
        field_name, field_action = split_field_action(key)

        # Boost by name__action overrides boost by name.
        boost = self.field_boosts.get(key)
        if boost is None:
            boost = self.field_boosts.get(field_name)

        handler_name = 'process_query_{0}'.format(field_action)

        if field_action and hasattr(self, handler_name):
            return getattr(self, handler_name)(field_name, val, field_action)

        elif field_action in QUERY_ACTION_MAP:
            return {
                QUERY_ACTION_MAP[field_action]: _boosted_value(
                    field_name, field_action, key, val, boost)
            }

        elif field_action == 'query_string':
            # query_string has different syntax, so it's handled
            # differently.
            #
            # Note: query_string queries are not boosted with
            # .boost()---they're boosted in the query text itself.
            return {
                'query_string': {'default_field': field_name, 'query': val}
            }

        elif field_action in RANGE_ACTIONS:
            # Ranges are special and have a different syntax, so
            # we handle them separately.
            return {
                'range': {field_name: _boosted_value(
                        field_action, field_action, key, val, boost)}
           }

        elif field_action == 'range':
            lower, upper = val
            value = {
                'gte': lower,
                'lte': upper,
            }
            if boost:
                value['boost'] = boost

            return {'range': {field_name: value}}

        raise InvalidFieldActionError(
            '%s is not a valid field action' % field_action)
761032
def _annotate_query(query, generate_dict):
    """"""
    annotate_key_list = []
    for field_name, annotate_dict in generate_dict.items():
        for annotate_name, annotate_func in annotate_dict["annotate_dict"].items():
            query = annotate_func(query)
            annotate_key_list.append(annotate_name)
    return query, annotate_key_list
1182251
protected function _prepareCollection()
    {
        parent::_prepareCollection();
        $collection = $this->getCollection();
        $turpentineEnabled = false;
        $fullPageEnabled = false;
        foreach ($collection as $key=>$item) {
            if ($item->getStatus() == 1 && ($item->getId() == 'turpentine_pages' || $item->getId() == 'turpentine_esi_blocks')) {
                $turpentineEnabled = true;
            }
            if ($item->getStatus() == 1 && $item->getId() == 'full_page') {
                $fullPageEnabled = true;
            }
        }
        if ($turpentineEnabled  && !$fullPageEnabled) {
            $collection->removeItemByKey('full_page');
        }
        if ($fullPageEnabled && !$turpentineEnabled) {
            $collection->removeItemByKey('turpentine_pages');
            $collection->removeItemByKey('turpentine_esi_blocks');
        }
        $this->setCollection($collection);
        return $this;
    }
387954
def each_indexed_object(collection, index_name, **where):
    """"""
    index = _db[collection].indexes[index_name]
    for id in index.value_map.get(indexed_value(index, where), []):
        yield get_object(collection, id)
1291815
protected function prepare_query() 
	{
		$this->query->where( $this->foreign_key, $this->local_model->{$this->local_key} )
			->limit( 1 );
	}
981050
def run(self):
        """"""
        query = self.query

        # count before filtering
        self.cardinality = query.add_columns(self.columns[0].sqla_expr).count()

        self._set_column_filter_expressions()
        self._set_global_filter_expression()
        self._set_sort_expressions()
        self._set_yadcf_data(query)

        # apply filters
        query = query.filter(
            *[e for e in self.filter_expressions if e is not None])

        self.cardinality_filtered = query.add_columns(
            self.columns[0].sqla_expr).count()

        # apply sorts
        query = query.order_by(
            *[e for e in self.sort_expressions if e is not None])

        # add paging options
        length = int(self.params.get('length'))
        if length >= 0:
            query = query.limit(length)
        elif length == -1:
            pass
        else:
            raise (ValueError(
                'Length should be a positive integer or -1 to disable'))
        query = query.offset(int(self.params.get('start')))

        # add columns to query
        query = query.add_columns(*[c.sqla_expr for c in self.columns])

        # fetch the result of the queries
        column_names = [
            col.mData if col.mData else str(i)
            for i, col in enumerate(self.columns)
        ]
        self.results = [{k: v
                         for k, v in zip(column_names, row)}
                        for row in query.all()]
283197
protected function _prepare_filter() {
		$term = \get_queried_object();

		if ( ! empty( $term->slug ) && ! empty( $term->taxonomy ) ) {
			$this->term     = $term->slug;
			$this->taxonomy = $term->taxonomy;
		}
	}
631278
def _ancestors(collection):
    """"""
    for index, c in enumerate(collection.path_to_root()):
        if index > 0 and c.dbquery is not None:
            raise StopIteration
        yield c.name
    raise StopIteration