It turns out the built-in SQLAlchemy function for query.count() is pretty
    slow. Alternatively, use this optimized function instead.
348520
def fast_count(query):
    
    count_query = (query
                   .statement.with_only_columns([func.count()]).order_by(None))
    count = query.session.execute(count_query).scalar()
    return count
1309420
def select(*queries, **kwargs):
    
    def make_query(*args):
        def simple_query(nodes):
            if len(args) == 0:
                return nodes
            pred = args[0]
            results = []
            if isinstance(pred, list):
                funcs = [make_query(q) for q in pred]
                return __or(funcs, nodes)
            elif isinstance(pred, tuple):
                name, attrs = pred[0], pred[1:]
                name_pred = __make_name_pred(name)
                attrs_pred = __make_attrs_pred(attrs)
                for n in nodes:
                    if name_pred(n.name) and attrs_pred(n.attrs):
                        results.append(n)
            else:
                name_pred = __make_name_pred(pred)
                for n in nodes:
                    if name_pred(n.name):
                        results.append(n)
            return results
        if len(args) > 1:
            return __compose(make_query(*args[1:]), simple_query)
        return simple_query

    def deep_query(query, nodes):
        """ Slide the query down the branches. """
        def inner(children):
            results = []
            for c in children:
                if query([c]):
                    results.append(c)
                results.extend(inner(c.children))
            return results
        return inner(nodes)

    def unique(roots):
        seen = set()
        results = []
        for r in roots:
            if r not in seen:
                seen.add(r)
                results.append(r)
        return results

    def compiled_query(nodes):
        """
        This is the compiled query that can be run against a configuration.
        """
        query = make_query(*queries)

        roots = kwargs.get("roots", True)
        if kwargs.get("deep", False):
            results = deep_query(query, nodes)
            if roots:
                results = unique([r.root for r in results])
        elif roots:
            results = unique([n.root for n in query(nodes)])
        else:
            results = query(nodes)

        one = kwargs.get("one")
        if one is None:
            return SearchResult(children=results)
        return results[one] if results else None
    return compiled_query
122153
def get_count_sql(self):
        
        sql = 'SELECT COUNT(*) FROM ' + self.tables
        if len(self.where_clauses) > 0:
            sql += ' WHERE '
            sql += ' AND '.join(self.where_clauses)
        return sql
440333
def count(self) -> "CountQuery":
        
        return CountQuery(
            db=self._db,
            model=self.model,
            q_objects=self._q_objects,
            annotations=self._annotations,
            custom_filters=self._custom_filters,
        )
1371475
def dcounts(self):
        
        print("WARNING: Distinct value count for all tables can take a long time...", file=sys.stderr)
        sys.stderr.flush()

        data = []
        for t in self.tables():
            for c in t.columns():
                data.append([t.name(), c.name(), c.dcount(), t.size(), c.dcount() / float(t.size())])
        df = pd.DataFrame(data, columns=["table", "column", "distinct", "size", "fraction"])
        return df
872354
def get_relation_count_query(self, query, parent):
        
        parent_table = self._parent.get_table()

        self._set_join(query)

        query.select(QueryExpression('COUNT(*)'))

        key = self.wrap('%s.%s' % (parent_table, self._first_key))

        return query.where(self.get_has_compare_key(), '=', QueryExpression(key))
620087
public static Long count(String query, Object... params) {
        return ModelDelegate.count(modelClass(), query, params);
    }
919975
def count(self, request, filter=None):
        
        if filter is None:
            filter = create_filter(request, self.mapped_class, self.geom_attr)
        query = self.Session().query(self.mapped_class)
        if filter is not None:
            query = query.filter(filter)
        return query.count()
138936
def count_results(cube, q):
    
    q = select(columns=[func.count(True)], from_obj=q.alias())
    return cube.engine.execute(q).scalar()
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()]
952963
def count(self, model, context):
        
        SELECT_COUNT = self.statement('SELECT COUNT')

        try:
            sql, data = SELECT_COUNT(model, context)
        except orb.errors.QueryIsNull:
            return 0
        else:
            if context.dryRun:
                print sql % data
                return 0
            else:
                try:
                    rows, _ = self.execute(sql, data)
                except orb.errors.EmptyCommand:
                    rows = []

                return sum([row['count'] for row in rows])
907645
static QueryMeta buildCountSql(ActiveRecord activeRecord) {
        QueryMeta     queryMeta = new QueryMeta();
        StringBuilder sqlBuf    = new StringBuilder("SELECT COUNT(*) FROM " + activeRecord.getTableName());
        int[]         pos       = {1};
        List<Object>  list      = parseWhere(activeRecord, pos, sqlBuf);

        List<Object> temp = andWhere(activeRecord, pos, sqlBuf);
        if (null != temp) {
            list.addAll(temp);
        }

        String   sql  = sqlFilter(sqlBuf.toString());
        Object[] args = list.toArray();
        queryMeta.setSql(sql);
        queryMeta.setParams(args);
        return queryMeta;
    }
334863
async def count(query, clear_limit=False):
    
    clone = query.clone()
    if query._distinct or query._group_by or query._limit or query._offset:
        if clear_limit:
            clone._limit = clone._offset = None
        sql, params = clone.sql()
        wrapped = 'SELECT COUNT(1) FROM (%s) AS wrapped_select' % sql
        raw = query.model.raw(wrapped, *params)
        return (await scalar(raw)) or 0
    else:
        clone._returning = [peewee.fn.Count(peewee.SQL('*'))]
        clone._order_by = None
        return (await scalar(clone)) or 0
1246602
def count(cls, *criteria, **filters):
        """"""
        return cls.query.filter(*criteria).filter_by(**filters).count()
832080
def get_count(self, query=None):
        
        query = query or Query()
        return self.get_db().alerts.find(query.where).count()
564545
def count(self):
        
        if not self.query.store.autocommit:
            self.query.store.checkpoint()
        target = ', '.join([
            tableClass.storeID.getColumnName(self.query.store)
            for tableClass in self.query.tableClass ])
        sql, args = self.query._sqlAndArgs(
            'SELECT DISTINCT',
            target)
        sql = 'SELECT COUNT(*) FROM (' + sql + ')'
        result = self.query.store.querySQL(sql, args)
        assert len(result) == 1, 'more than one result: %r' % (result,)
        return result[0][0] or 0
1256708
def find_one(self, query=None):
        
        try:
            return self.find(query=query, limit=1)[0]
        except (sqlite3.OperationalError, IndexError):
            return None