Skip to content

Commit

Permalink
Add count() as a utility extension
Browse files Browse the repository at this point in the history
  • Loading branch information
simolus3 committed Nov 10, 2023
1 parent e79124e commit f9012fc
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions drift/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
## 2.14.0-dev

- Add the `QueryInterceptor` to easily monitor all database calls made by drift.
- Add the `count()` extension on tables to easily count rows in tables or views.

## 2.13.1

Expand Down
17 changes: 17 additions & 0 deletions drift/lib/src/runtime/query_builder/on_table.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,23 @@ extension TableOrViewStatements<Tbl extends HasResultSet, Row>
return select();
}

/// Counts the rows in this table.
///
/// The optional [where] clause can be used to only count rows matching the
/// condition, similar to [SimpleSelectStatement.where].
///
/// The returned [Selectable] can be run once with [Selectable.getSingle] to
/// get the count once, or be watched as a stream with [Selectable.watchSingle].
Selectable<int> count({Expression<bool> Function(Tbl row)? where}) {
final count = countAll();
final stmt = selectOnly()..addColumns([count]);
if (where != null) {
stmt.where(where(asDslTable));
}

return stmt.map((row) => row.read(count)!);
}

/// Composes a `SELECT` statement on the captured table or view.
///
/// This is equivalent to calling [DatabaseConnectionUser.select].
Expand Down
29 changes: 29 additions & 0 deletions drift/test/database/statements/select_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -256,4 +256,33 @@ void main() {
[r'$.foo'],
));
});

group('count', () {
test('all', () async {
when(executor.runSelect(any, any)).thenAnswer((_) async => [
{'c0': 3}
]);

final result = await db.todosTable.count().getSingle();
expect(result, 3);

verify(executor.runSelect(
'SELECT COUNT(*) AS "c0" FROM "todos";', argThat(isEmpty)));
});

test('with filter', () async {
when(executor.runSelect(any, any)).thenAnswer((_) async => [
{'c0': 2}
]);

final result = await db.todosTable
.count(where: (row) => row.id.isBiggerThanValue(12))
.getSingle();
expect(result, 2);

verify(executor.runSelect(
'SELECT COUNT(*) AS "c0" FROM "todos" WHERE "todos"."id" > ?;',
[12]));
});
});
}

0 comments on commit f9012fc

Please sign in to comment.