Add `count()` as a utility extension

This commit is contained in:
Simon Binder 2023-11-10 21:12:02 +01:00
parent e79124e5af
commit f9012fc05c
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
3 changed files with 47 additions and 0 deletions

View File

@ -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

View File

@ -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].

View File

@ -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]));
});
});
}