Sub topic 2
Rows and companions: reading versus writing
Prerequisites
This chapter assumes you have the TodoItems table and AppDatabase class from the earlier chapters, and that you have run build_runner. You should be comfortable with async/await and with Futures and Streams in Dart.
Rows and companions
drift generates two classes for each table. The row class (TodoItem) holds one stored record with every column filled in. Queries return row objects. The companion class (TodoItemsCompanion) holds the values you want to write. Its fields are wrapped in Value, so drift can tell a field you set from one you left out. Omitted fields use column defaults, such as isDone and createdAt.
Use a companion to insert or partially update. Use a row to read data or to replace a whole record.
Create, read, update, and delete
// Inside AppDatabase
Future<int> addItem(String title) =>
into(todoItems).insert(TodoItemsCompanion.insert(title: title));
Future<List<TodoItem>> allItems() => select(todoItems).get();
Future<bool> updateItem(TodoItem item) =>
update(todoItems).replace(item);
Future<int> deleteDone() =>
(delete(todoItems)..where((t) => t.isDone.equals(true))).go();insert returns the new row id. replace matches on the primary key and rewrites every column, so pass it a row from a fresh read. delete with a where clause removes only matching rows and returns the number removed.
Filtering, sorting, and limiting results
Future<List<TodoItem>> recentOpenItems() {
return (select(todoItems)
..where((t) => t.isDone.equals(false))
..orderBy([(t) => OrderingTerm.desc(t.createdAt)])
..limit(10))
.get();
}where filters rows, orderBy sorts them, and limit caps the count. SQLite runs all three, so the database returns only the rows you need.
Watching queries as streams
Replace get() with watch() to receive a Stream that emits a new list whenever the table changes.
Stream<List<TodoItem>> watchOpenItems() {
return (select(todoItems)
..where((t) => t.isDone.equals(false))
..orderBy([(t) => OrderingTerm.desc(t.createdAt)]))
.watch();
}Exercise
How do you mark one item as done without loading it first?
Show answer
Use a partial update with a companion, filtered by id: (update(todoItems)..where((t) => t.id.equals(id))).write(TodoItemsCompanion(isDone: Value(true))).