How do I count all rows in a table and get number of rows as a result using the moor_flutter package?
I have seen moor_flutter official documentation here but I can't find what I'm looking for.
I was hoping it would be like the function below according to the similarities in crud functions when using the moor_flutter package but it is not working either.
Future<int<Person>> countPersons() => count(persons).get();
In SQLite the Count(*) function will return total number of rows available in a table, including the rows which contain NULL values. The Count(*) will not take any parameters other than the asterisk symbol (*).
If you are using SQLite, you can use PRAGMA functions to find this info. See here for documentation. To find the number of columns for a table (let's call this table tracks ) you would use this query: SELECT COUNT(*) FROM pragma_table_info('tracks');
I figured out a way to find count of table rows. Here is a complete solution with basic comments,
//Create expression of count
var countExp = persons.id.count();
//Moor creates query from Expression so, they don't have value unless you execute it as query.
//Following query will execute experssion on Table.
final query = selectOnly(persons)..addColumns([countExp]);
var result = await query.map((row) => row.read(countExp)).getSingle();
Please note that I have used selectOnly
instead of select
because I am not interested in any column except Count.
If you need a filter condition on your count, then you can put call the top level function countAll
with the named parameter filter
as you can see below.
var count = countAll(filter: persons.id.isSmallerThanValue(100));
var res = await (selectOnly(persons)..addColumns([count]))
.map((row) => row.read(count))
.getSingle();
It is now documented in the official documentation
EDIT
Now, count expression is supported by moor, see this link or this answer.
This answer is not a way to go anymore, because of obvious performance issues.
There is no such statement in moor_flutter
(only select
, into
, update
and delete
).
This should work :
Future<int> countPersons() async {
return (await select(persons).get()).length;
}
or (exactly the same but one line)
Future<int> countPersons() async => (await select(persons).get()).length;
Or you could try to write custom SQL queries.
The canonical Moor way seems a trifle confusing to me. If you feel the same, you might go old school and try:
@UseDao(
tables: [Instruments],
queries: {
'instrumentsCount': 'SELECT COUNT(*) FROM instruments;'
},
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With