class CountUtil {

    private static final Predicate<Action<?, ?>> PRESERVE_SIZE = action -> action.is(PRESERVE, SIZE);

    /**
     * Optimizer for count operations.
     *
     * @param <ENTITY> the entity type
     * @param info about the stream optimizer
     * @param sqlStreamTerminator that called us
     * @param pipeline the pipeline
     * @param fallbackSupplier a fallback supplier should every item be size
     * retaining
     * @return the number of rows
     */
    public static <ENTITY> long countHelper(
        final SqlStreamOptimizerInfo<ENTITY> info,
        final SqlStreamTerminator<ENTITY> sqlStreamTerminator,
        final Pipeline pipeline,
        final LongSupplier fallbackSupplier
    ) {<FILL_FUNCTION_BODY>}

    private CountUtil() {
        throw new UnsupportedOperationException();
    }

}

        requireNonNull(info);
        requireNonNull(sqlStreamTerminator);
        requireNonNull(pipeline);
        requireNonNull(fallbackSupplier);

        // Can we count it directly (with no sub-select query)?
        if (pipeline.stream().allMatch(PRESERVE_SIZE)) {
            return info.getCounter().applyAsLong(info.getSqlSelectCount(), emptyList());
        } else {

            final Pipeline optimizedPipeline = sqlStreamTerminator.optimize(pipeline);
            // Can we count using a sub-select query?
            if (optimizedPipeline.stream().allMatch(PRESERVE_SIZE)) {
                final AsynchronousQueryResult<ENTITY> asynchronousQueryResult = sqlStreamTerminator.getAsynchronousQueryResult();
                final StringBuilder sql = new StringBuilder()
                    .append("SELECT COUNT(*) FROM (")
                    .append(asynchronousQueryResult.getSql())
                    .append(")");

                if (info.getDbmsType().getSubSelectAlias() == SubSelectAlias.REQUIRED) {
                    sql.append(" AS A");
                }
                @SuppressWarnings("unchecked")
                final List<Object> values = (List<Object>) asynchronousQueryResult.getValues();
                return info.getCounter().applyAsLong(sqlStreamTerminator.attachTraceData(sql.toString()), values);
            } else {
                // Iterate over all materialized ENTITIES....
                return fallbackSupplier.getAsLong();
            }
        }
    
<no_super_class>