aggregateQuery method

  1. @override
Future<List<Map<String, Object?>>> aggregateQuery(
  1. String table, {
  2. required List<String> groupBy,
  3. required Map<String, String> aggregations,
  4. String? where,
  5. List<Object?>? whereArgs,
  6. String? having,
  7. String? orderBy,
  8. int? limit,
  9. int? offset,
})
override

Implementation

@override
Future<List<Map<String, Object?>>> aggregateQuery(
  String table, {
  required List<String> groupBy,
  required Map<String, String> aggregations,
  String? where,
  List<Object?>? whereArgs,
  String? having,
  String? orderBy,
  int? limit,
  int? offset,
}) async {
  try {
    if (database == null) {
      throw const DatabaseBridgeException(
        error: 'Database is not initialized',
      );
    }

    // Build SELECT clause with aggregations
    final selectColumns = <String>[];

    // Add group by columns to select
    selectColumns.addAll(groupBy);

    // Add aggregation expressions
    for (final entry in aggregations.entries) {
      selectColumns.add('${entry.value} as ${entry.key}');
    }

    final selectClause = selectColumns.join(', ');

    // Build GROUP BY clause
    final groupByClause = groupBy.isNotEmpty
        ? ' GROUP BY ${groupBy.join(', ')}'
        : '';

    // Build HAVING clause
    final havingClause = having != null ? ' HAVING $having' : '';

    // Build ORDER BY clause
    final orderByClause = orderBy != null ? ' ORDER BY $orderBy' : '';

    // Build LIMIT and OFFSET clauses
    final limitClause = limit != null ? ' LIMIT $limit' : '';
    final offsetClause = offset != null ? ' OFFSET $offset' : '';

    // Build WHERE clause
    final whereClause = where != null ? ' WHERE $where' : '';

    final sql =
        'SELECT $selectClause FROM $table$whereClause$groupByClause$havingClause$orderByClause$limitClause$offsetClause';

    return await database!.rawQuery(sql, whereArgs);
  } catch (e) {
    throw DatabaseBridgeException(error: e);
  }
}