Create a Count-Query for QueryByCriteria
185356
private Query getQueryByCriteriaCount(QueryByCriteria aQuery)
    {
        Class                 searchClass = aQuery.getSearchClass();
        ReportQueryByCriteria countQuery  = null;
        Criteria              countCrit   = null;
        String[]              columns     = new String[1];

        // BRJ: copied Criteria without groupby, orderby, and prefetched relationships
        if (aQuery.getCriteria() != null)
        {
            countCrit = aQuery.getCriteria().copy(false, false, false);
        }

        if (aQuery.isDistinct())
        {
            // BRJ: Count distinct is dbms dependent
            // hsql/sapdb: select count (distinct(person_id || project_id)) from person_project
            // mysql: select count (distinct person_id,project_id) from person_project
            // [tomdz]
            // Some databases have no support for multi-column count distinct (e.g. Derby)
            // Here we use a SELECT count(*) FROM (SELECT DISTINCT ...) instead 
            //
            // concatenation of pk-columns is a simple way to obtain a single column
            // but concatenation is also dbms dependent:
            //
            // SELECT count(distinct concat(row1, row2, row3)) mysql
            // SELECT count(distinct (row1 || row2 || row3)) ansi
            // SELECT count(distinct (row1 + row2 + row3)) ms sql-server

            FieldDescriptor[] pkFields   = m_broker.getClassDescriptor(searchClass).getPkFields();
            String[]          keyColumns = new String[pkFields.length];

            if (pkFields.length > 1)
            {
                // TODO: Use ColumnName. This is a temporary solution because
                // we cannot yet resolve multiple columns in the same attribute.
                for (int idx = 0; idx < pkFields.length; idx++)
                {
                    keyColumns[idx] = pkFields[idx].getColumnName();
                }
            }
            else
            {
                for (int idx = 0; idx < pkFields.length; idx++)
                {
                    keyColumns[idx] = pkFields[idx].getAttributeName();
                }
            }
            // [tomdz]
            // TODO: Add support for databases that do not support COUNT DISTINCT over multiple columns
//            if (getPlatform().supportsMultiColumnCountDistinct())
//            {
//                columns[0] = "count(distinct " + getPlatform().concatenate(keyColumns) + ")";
//            }
//            else
//            {
//                columns = keyColumns;
//            }

            columns[0] = "count(distinct " + getPlatform().concatenate(keyColumns) + ")";
        }
        else
        {
            columns[0] = "count(*)";
        }

        // BRJ: we have to preserve indirection table !
        if (aQuery instanceof MtoNQuery)
        {
            MtoNQuery                 mnQuery       = (MtoNQuery)aQuery;
            ReportQueryByMtoNCriteria mnReportQuery = new ReportQueryByMtoNCriteria(searchClass, columns, countCrit);

            mnReportQuery.setIndirectionTable(mnQuery.getIndirectionTable());
            countQuery = mnReportQuery;
        }
        else
        {
            countQuery = new ReportQueryByCriteria(searchClass, columns, countCrit);
        }

        // BRJ: we have to preserve outer-join-settings (by André Markwalder)
        for (Iterator outerJoinPath = aQuery.getOuterJoinPaths().iterator(); outerJoinPath.hasNext();)
        {
            String path = (String) outerJoinPath.next();

            if (aQuery.isPathOuterJoin(path))
            {
                countQuery.setPathOuterJoin(path);
            }
        }

        //BRJ: add orderBy Columns asJoinAttributes
        List orderBy = aQuery.getOrderBy();

        if ((orderBy != null) && !orderBy.isEmpty())
        {
            String[] joinAttributes = new String[orderBy.size()];

            for (int idx = 0; idx < orderBy.size(); idx++)
            {
                joinAttributes[idx] = ((FieldHelper)orderBy.get(idx)).name;
            }
            countQuery.setJoinAttributes(joinAttributes);
        }

        // [tomdz]
        // TODO:
        // For those databases that do not support COUNT DISTINCT over multiple columns
        // we wrap the normal SELECT DISTINCT that we just created, into a SELECT count(*)
        // For this however we need a report query that gets its data from a sub query instead
        // of a table (target class)
//        if (aQuery.isDistinct() && !getPlatform().supportsMultiColumnCountDistinct())
//        {
//        }

        return countQuery;
    }
299870
@Override
	public long dynamicQueryCount(DynamicQuery dynamicQuery,
		Projection projection) {
		return commerceUserSegmentCriterionPersistence.countWithDynamicQuery(dynamicQuery,
			projection);
	}
1016734
def CountHuntResults(self,
                       hunt_id,
                       with_tag=None,
                       with_type=None,
                       cursor=None):
    """"""
    hunt_id_int = db_utils.HuntIDToInt(hunt_id)

    query = "SELECT COUNT(*) FROM flow_results WHERE hunt_id = %s "

    args = [hunt_id_int]

    if with_tag is not None:
      query += "AND tag = %s "
      args.append(with_tag)

    if with_type is not None:
      query += "AND type = %s "
      args.append(with_type)

    cursor.execute(query, args)
    return cursor.fetchone()[0]
31273
def get_relation_count_query(self, query, parent):
        
        query.select(QueryExpression('COUNT(*)'))

        other_key = self.wrap('%s.%s' % (query.get_model().get_table(), self._other_key))

        return query.where(self.get_qualified_foreign_key(), '=', QueryExpression(other_key))
259952
public void addQueryCriterion(QueryCriterion criterion){
        if( criteria == null){
            criteria = new ArrayList<QueryCriterion>();
        }
        criteria.add(criterion);
    }
110979
public long count(String[] indices, String[] types,
            QueryBuilder filterQueryBuilder) {
        return countQuery(getSearchRequestBuilderWithMatchAll(false, indices,
                types, filterQueryBuilder));
    }
1218826
def query_target_count(self, target):
    """"""
    reply = NVCtrlQueryTargetCountReplyRequest(display=self.display,
                                               opcode=self.display.get_extension_major(extname),
                                               target_type=target.type())
    return int(reply._data.get('count'))
401041
def create_criteria(cls, query):
        
        criteria = []
        for name, value in query.items():
            if isinstance(value, list):
                for inner_value in value:
                    criteria += cls.create_criteria({name: inner_value})
            else:
                criteria.append({
                    'criteria': {
                        'field': name,
                        'value': value,
                    },
                })
        return criteria or None
927844
function count(query, callback) {
    self.emit('count', query)
    findByQuery(query, options, function (error, objects) {
      self.emit('received', objects.length)
      callback(undefined, objects.length)
    })
  }
1185775
def AQLQuery(self, query, batchSize = 100, rawResults = False, bindVars = {}, options = {}, count = False, fullCount = False,
                 json_encoder = None, **moreArgs) :
        """"""
        return AQLQuery(self, query, rawResults = rawResults, batchSize = batchSize, bindVars  = bindVars, options = options, count = count, fullCount = fullCount,
                        json_encoder = json_encoder, **moreArgs)
200763
def count(self, objectType, *args, **coolArgs) :
		""""""
		return self._makeLoadQuery(objectType, *args, **coolArgs).count()
166472
public TypedQuery<Long> count(Filter filter) {
        CriteriaQuery<Long> query = cb.createQuery(Long.class);
        Root<T> from = query.from(getEntityClass());

        if (filter != null) {
            Predicate where = new CriteriaMapper(from, cb).create(filter);
            query.where(where);
        }

        return getEntityManager().createQuery(query.select(cb.count(from)));
    }
720931
def count(self, query):
        
        if self.manual:
            return self.total
        
        if isinstance(query, Select):
            q = query.with_only_columns([func.count()]).order_by(None).limit(None).offset(None)
            return do_(q).scalar()

        return query.count()
1266688
def count(self, q='*:*', fq=None):
        """"""
        params = {'q': q, 'rows': '0'}
        if fq is not None:
            params['fq'] = fq
        res = self.search(params)
        hits = res['response']['numFound']
        return hits
52048
@Transactional(readOnly = true)
	public Collection<Response> find(SearchCriteria searchCriteria) {
		CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
		CriteriaQuery<Response> criteriaQuery = criteriaBuilder.createQuery(Response.class);
		Root<Response> root = criteriaQuery.from(Response.class);
		
		Collection<Predicate> conditions = new ArrayList<>();
		
		if (searchCriteria.getUser() != null) {
			Predicate userCondition = criteriaBuilder.equal(root.get("user").get("username"), searchCriteria.getUser().getUsername());
			conditions.add(userCondition);
		}
		
		if (searchCriteria.getDetectionSystemIds() != null) {
			Predicate detectionSystemCondition = root.get("detectionSystem").get("detectionSystemId").in(searchCriteria.getDetectionSystemIds());
			conditions.add(detectionSystemCondition);
		}

		if (conditions.size() > 0) {
			criteriaQuery.where(criteriaBuilder.and(conditions.toArray(new Predicate[0])));
		}
		
		criteriaQuery.orderBy(criteriaBuilder.asc(root.get("timestamp")));

		TypedQuery<Response> query = em.createQuery(criteriaQuery); 
		List<Response> result = query.getResultList();
		
		return result;
	}
680491
@SuppressWarnings({ "unchecked", "rawtypes" })
    protected <T> void applySearchCriteriaToQuery(SearchCriteriaBean criteria, CriteriaBuilder builder,
            CriteriaQuery<?> query, Root<T> from, boolean countOnly) {

        List<SearchCriteriaFilterBean> filters = criteria.getFilters();
        if (filters != null && !filters.isEmpty()) {
            List<Predicate> predicates = new ArrayList<>();
            for (SearchCriteriaFilterBean filter : filters) {
                if (filter.getOperator() == SearchCriteriaFilterOperator.eq) {
                    Path<Object> path = from.get(filter.getName());
                    Class<?> pathc = path.getJavaType();
                    if (pathc.isAssignableFrom(String.class)) {
                        predicates.add(builder.equal(path, filter.getValue()));
                    } else if (pathc.isEnum()) {
                        predicates.add(builder.equal(path, Enum.valueOf((Class)pathc, filter.getValue())));
                    }
                } else if (filter.getOperator() == SearchCriteriaFilterOperator.bool_eq) {
                    predicates.add(builder.equal(from.<Boolean>get(filter.getName()), Boolean.valueOf(filter.getValue())));
                } else if (filter.getOperator() == SearchCriteriaFilterOperator.gt) {
                    predicates.add(builder.greaterThan(from.<Long>get(filter.getName()), new Long(filter.getValue())));
                } else if (filter.getOperator() == SearchCriteriaFilterOperator.gte) {
                    predicates.add(builder.greaterThanOrEqualTo(from.<Long>get(filter.getName()), new Long(filter.getValue())));
                } else if (filter.getOperator() == SearchCriteriaFilterOperator.lt) {
                    predicates.add(builder.lessThan(from.<Long>get(filter.getName()), new Long(filter.getValue())));
                } else if (filter.getOperator() == SearchCriteriaFilterOperator.lte) {
                    predicates.add(builder.lessThanOrEqualTo(from.<Long>get(filter.getName()), new Long(filter.getValue())));
                } else if (filter.getOperator() == SearchCriteriaFilterOperator.neq) {
                    predicates.add(builder.notEqual(from.get(filter.getName()), filter.getValue()));
                } else if (filter.getOperator() == SearchCriteriaFilterOperator.like) {
                    predicates.add(builder.like(builder.upper(from.<String>get(filter.getName())), filter.getValue().toUpperCase().replace('*', '%')));
                }
            }
            query.where(predicates.toArray(new Predicate[predicates.size()]));
        }
        OrderByBean orderBy = criteria.getOrderBy();
        if (orderBy != null && !countOnly) {
            if (orderBy.isAscending()) {
                query.orderBy(builder.asc(from.get(orderBy.getName())));
            } else {
                query.orderBy(builder.desc(from.get(orderBy.getName())));
            }
        }
    }
134503
public <R> Predicate createPredicate(QueryCriteria criteria, CriteriaQuery<R> query, CriteriaBuilder builder) {
        // subquery and root
        Root<TaskImpl> taskRoot = getRoot(query, TaskImpl.class);
        Subquery<Long> subQuery = query.subquery(Long.class);
        Root<TaskVariableImpl> taskVarRoot = subQuery.from(TaskVariableImpl.class);
        subQuery.select(taskVarRoot.get(TaskVariableImpl_.taskId));

        // task variable predicate (in subquery)
        Predicate taskVariablePredicate = null;
        String listId = criteria.getListId();
        if( TASK_VARIABLE_COMBINED_ID.equals(listId) ) {
            List<QueryCriteria> taskVarSubCriteriaList = criteria.getCriteria();
            int size = taskVarSubCriteriaList.size();
            Predicate[] taskVarSubPredicates = new Predicate[size];
            for( int i = 0; i < size; ++i ) {
                taskVarSubPredicates[i] = createSingleTaskVariableCriteriaPredicate(
                        builder, taskVarRoot, taskVarSubCriteriaList.get(i));
            }
            taskVariablePredicate = builder.and(taskVarSubPredicates);
        } else {
            taskVariablePredicate = createSingleTaskVariableCriteriaPredicate(builder, taskVarRoot, criteria);
        }

        // add predicate to subquery
        subQuery.where(taskVariablePredicate);

        // create predicate for actual query that references subquery
        return taskRoot.get(TaskImpl_.id).in(subQuery);
    }