Sub topic 6
Rows and companions: reading versus writing
This chapter assumes you have a working AppDatabase with the TodoItems table from the earlier chapters, and that build_runner has generated database.g.dart. You should also know what Future<int> and nullable types mean in Dart.
For every table, drift generates two classes. A row class (also called a data class) represents a row you read. A companion represents values you want to write. The split exists because a row you read always has every column filled in, while a row you write often leaves some columns for the database to fill in, such as an auto-incrementing id.
What drift generates for TodoItems
For the TodoItems table, the generator produces two classes:
TodoItem, the row class. The name is the table name with the trailing "s" removed.TodoItemsCompanion, the companion. The name is the table name plusCompanion.
The following table summarizes the differences.
| Row | Row class (`TodoItem`) | Companion (`TodoItemsCompanion`) |
|---|---|---|
| Used for | Results of `select` queries | Arguments to insert and update |
| Field types | Plain Dart types: `int`, `String`, `bool`, `DateTime` | `Value<int>`, `Value<String>`, and so on |
| Can a field be missing? | No. Non-nullable columns always have a value | Yes. A field can be `Value.absent()` |
| Immutable? | Yes, with `copyWith` | Yes, with `copyWith` |
Both classes implement the Insertable interface, so most drift write methods accept either one.
Row classes: what you read
A row class is an immutable value object. You never construct one yourself during normal use, because queries return them. The class for TodoItems looks roughly like this (simplified):
class TodoItem extends DataClass implements Insertable<TodoItem> {
final int id;
final String title;
final bool isDone;
final DateTime createdAt;
const TodoItem({
required this.id,
required this.title,
required this.isDone,
required this.createdAt,
});
// Also generated: copyWith, toCompanion, toJson, fromJson,
// ==, hashCode, and toString.
}Because it implements == and hashCode by value, two TodoItem objects with equal fields compare as equal. This matters for streams and for widget rebuilds in the UI chapters.
Rows are immutable, so you "change" one by copying it:
final done = item.copyWith(isDone: true);copyWith is the usual way to prepare an edited row for update(todoItems).replace(...).
Renaming the row class
The default name can be awkward. TodoItems becomes TodoItem, but a table named Categories becomes Categorie. Override the name with @DataClassName:
@DataClassName('Category')
class Categories extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text()();
}Run dart run build_runner build again after changing it. The companion keeps the table-based name, so this one is still CategoriesCompanion.
Companions: what you write
Each companion field is wrapped in a Value<T>. The wrapper lets drift tell three situations apart:
Value(x): writexto this column.Value.absent(): leave this column out. On insert the column's default applies. On update the stored value stays as it is.Value(null): write SQLNULL. This is only valid for nullable columns.
A plain null cannot express "don't touch this column" and "set this column to NULL" at the same time. That is why Value exists.
Two ways to build a companion
The generated companion has two constructors.
The default constructor takes every field as an optional Value. Each field defaults to Value.absent():
const update = TodoItemsCompanion(isDone: Value(true));The .insert constructor takes raw values. It marks as required only the columns that have no default and are not auto-increment:
final newItem = TodoItemsCompanion.insert(title: 'Write tests');Here title is required because it has no default. id is auto-increment, isDone has a default of false, and createdAt defaults to the current time. All three can be omitted.
For inserts, prefer .insert. It turns a missing required column into a compile error. The default constructor accepts anything, so a forgotten title only fails at runtime with a NOT NULL constraint error.
Values that depend on a nullable variable
If you have a nullable Dart value and want "absent if null" behavior, use Value.absentIfNull:
TodoItemsCompanion.insert(
title: 'Ship it',
isDone: Value.absentIfNull(maybeDone), // maybeDone is bool?
);Check that your drift version includes this constructor. It was added in recent releases. If it's missing, write maybeDone == null ? const Value.absent() : Value(maybeDone).
Putting both to work
The following test uses the AppDatabase from earlier chapters with an in-memory database. It inserts with a companion, reads a row back, and makes a partial update. Save it as test/rows_test.dart and adjust the import path to match your project:
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/database.dart';
void main() {
late AppDatabase db;
setUp(() => db = AppDatabase(NativeDatabase.memory()));
tearDown(() => db.close());
test('companions write, rows read', () async {
// Write: only the title is supplied.
final id = await db
.into(db.todoItems)
.insert(TodoItemsCompanion.insert(title: 'Read chapter'));
// Read: every column has a value, including defaults.
final item = await (db.select(db.todoItems)
..where((t) => t.id.equals(id)))
.getSingle();
expect(item.isDone, false);
expect(item.title, 'Read chapter');
// Partial update: only isDone is written.
final changed = await (db.update(db.todoItems)
..where((t) => t.id.equals(id)))
.write(const TodoItemsCompanion(isDone: Value(true)));
expect(changed, 1);
final after = await db.select(db.todoItems).getSingle();
expect(after.isDone, true);
expect(after.title, 'Read chapter');
});
}Three things to notice:
insertreturns the new row'sid. It does not return the row itself.- The
writecall touched onlyisDone.titlekept its stored value because the companion'stitlewas absent. writereturns the number of affected rows.
If you want the full inserted row, including defaults the database computed, use insertReturning:
final row = await db
.into(db.todoItems)
.insertReturning(TodoItemsCompanion.insert(title: 'Call back'));
print(row.createdAt);replace versus write
Drift gives you two update styles, and they differ in how they treat missing fields.
update(table).replace(row)takes a wholeInsertableand writes every column, using the row'sidto find the target. It fails if the row doesn't exist. Use it with a row class you read earlier and changed withcopyWith.(update(table)..where(...)).write(companion)writes only the fields that are present, for every row matching thewhere. Use it for targeted changes.
If you call write without a where, the update applies to every row in the table.
Nullable columns and copyWith
When a table has a nullable column, copyWith handles it differently from non-null ones. Assume the note column from the migrations example, text().nullable()():
final withNote = item.copyWith(note: const Value('Remember this'));
final cleared = item.copyWith(note: const Value(null));
final unchanged = item.copyWith(isDone: true); // note stays as it wasFor nullable columns, copyWith takes a Value<String?>. A bare null can't tell "keep" from "clear", so the wrapper is required. Non-nullable columns take plain values.
Common mistakes
- Missing
Valuewrappers.TodoItemsCompanion(isDone: true)fails to compile. WriteValue(true), or use.insert, which takes raw values. - Importing the wrong name. The companion exists only after code generation. If
TodoItemsCompanionis undefined, rundart run build_runner build, and check thepart 'database.g.dart';line. - Expecting a row from
insert. It returns anint. UseinsertReturningwhen you need the row. - Using the row class to insert a new item. A
TodoItemneeds anid, which a new item doesn't have yet. Create a companion instead.
Exercise
You want to mark every item with a given id as done without touching its other columns. Which write style and which class do you use, and what happens to title if you pass TodoItemsCompanion(isDone: Value(true))?
Show answer
Use (update(todoItems)..where((t) => t.id.equals(id))).write(...) with a TodoItemsCompanion. The title field of the companion is Value.absent(), so the stored title is left unchanged. Only isDone is written.
Exercise
Why does TodoItemsCompanion.insert(title: 'x') need no id, isDone, or createdAt, while TodoItemsCompanion.insert() with no arguments does not compile?
Show answer
The .insert constructor requires only columns that have no default and are not auto-increment. id is auto-increment, and isDone and createdAt have defaults, so they are optional. title has neither, so it is required, and omitting it is a compile error.