Sub topic 3
Describing your schema as Dart classes
This chapter assumes you have installed drift and its generator (previous chapter) and know basic relational ideas: tables, rows, primary keys, and foreign keys. You will define a schema in Dart. The next chapter runs the generator on it.
How a table class works
In drift, each SQL table is a Dart class that extends Table. Each column is a getter that returns the result of a builder chain. Drift's generator reads these classes and writes the SQL and the typed Dart code for you.
import 'package:drift/drift.dart';
class Categories extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text().withLength(min: 1, max: 50).unique()();
}Two details matter here:
- The chain ends with an extra
(). The builder (integer(),text()) configures the column, and the final call produces the column object. A missing final()is the most common beginner error. It shows up as a type mismatch, because the getter's declared type isIntColumnwhile the expression's type is a column builder. - The getter name becomes the column name. Dart
camelCaseturns into SQLsnake_case, socreatedAtis stored ascreated_at. To choose a different SQL name, callnamed('custom_name')in the chain.
The class name sets the table name the same way. TodoItems becomes the table todo_items. You can override it by adding String get tableName => 'my_table';.
Column types
Each builder maps to a SQLite storage class and a Dart type.
| Builder | SQLite type | Dart type | Notes |
|---|---|---|---|
| `integer()` | INTEGER | `int` | Also used for `autoIncrement()` keys |
| `int64()` | INTEGER | `BigInt` | For values that must be exact on web |
| `text()` | TEXT | `String` | Supports `withLength` |
| `boolean()` | BOOLEAN | `bool` | Stored as 0 or 1 |
| `dateTime()` | INTEGER | `DateTime` | Stored as a Unix timestamp in seconds by default |
| `real()` | REAL | `double` | 8-byte floating point |
| `blob()` | BLOB | `Uint8List` | Raw bytes |
SQLite itself is loosely typed. It will accept almost any value in any column. Drift's types give you the checking: the generated Dart code only lets you pass an int to an integer() column.
Because dateTime() stores whole seconds by default, a DateTime with milliseconds loses them when saved and read back. If you need sub-second precision, drift can store dates as ISO-8601 text through a build option. Choose before you ship, because switching later changes how existing values are read.
Nullability, defaults, and constraints
Every column is NOT NULL unless you say otherwise. This is the reverse of plain SQL, and it makes the generated row classes safer. You can adjust a column with these modifiers:
nullable()allowsNULL. The generated Dart field becomes nullable (String?).withDefault(const Constant(value))sets an SQLDEFAULT. SQLite applies it when an insert omits the column.clientDefault(() => value)runs a Dart function at insert time. Use it for values SQL cannot compute, such as a generated UUID. The default is not part of the SQL schema, so other code that inserts rows directly will not get it.withLength(min:, max:)adds aCHECKconstraint on text length.unique()adds a uniqueness constraint on one column.
Here is a fuller schema that uses all of them:
import 'package:drift/drift.dart';
class Categories extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text().withLength(min: 1, max: 50).unique()();
}
class TodoItems extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 1, max: 100)();
BoolColumn get isDone => boolean().withDefault(const Constant(false))();
DateTimeColumn get createdAt =>
dateTime().withDefault(currentDateAndTime)();
IntColumn get categoryId =>
integer().nullable().references(Categories, #id)();
}currentDateAndTime is an SQL expression, so SQLite fills in the timestamp when the row is inserted. The categoryId column is nullable because a to-do does not have to belong to a category. references(Categories, #id) declares a foreign key. Its second argument is a Symbol, the name of the target column.
Primary keys
autoIncrement() is the usual choice. It makes the column an integer primary key that SQLite assigns for you. It also means you do not include id when you insert.
When the key comes from your data, override primaryKey instead and drop autoIncrement(). A single natural key and a composite key both use this form:
import 'package:drift/drift.dart';
class Tags extends Table {
TextColumn get slug => text()();
TextColumn get label => text()();
@override
Set<Column> get primaryKey => {slug};
}
class TodoTags extends Table {
IntColumn get todoId => integer()();
TextColumn get tagSlug => text()();
@override
Set<Column> get primaryKey => {todoId, tagSlug};
}A table can have either an autoIncrement() column or a primaryKey override, not both. Drift reports an error at generation time if you combine them. If you need uniqueness on a combination of columns that is not the primary key, override uniqueKeys, for example List<Set<Column>> get uniqueKeys => [{todoId, tagSlug}];.
Indexes
Indexes speed up lookups on columns you filter or sort by often. You declare them with the @TableIndex annotation on the table class:
import 'package:drift/drift.dart';
@TableIndex(name: 'todo_category', columns: {#categoryId})
class Notes extends Table {
IntColumn get id => integer().autoIncrement()();
IntColumn get categoryId => integer()();
TextColumn get body => text()();
}Columns are named with Symbols again. Each index also costs disk space and slows writes slightly, so add them for real query patterns rather than for every column.
What the generator produces
You write only the table classes. When you run build_runner, drift generates, for each table:
- A row class named after the table, singular (
TodoItemsgivesTodoItem), holding one row of data. If the automatic name is wrong, add@DataClassName('Todo')above the table. - A companion class (
TodoItemsCompanion) for writing partial rows. A later chapter covers it. - A typed table object that your queries use, such as
todoItems.title.
Changing a table class does nothing until you regenerate. The generated file also describes the schema for new installs only. Phones that already have the old database need a migration, which is why schemaVersion exists.
Common errors
- Forgetting the trailing
()on a column getter. - Putting
nullable()on a column and then expecting a non-null Dart field. - Adding
withLengthto a non-text column. It only exists ontext(). - Referencing a table in
references(...)that is not listed in the@DriftDatabaseannotation. - Editing a column in a shipped app without raising
schemaVersion.
Exercise
A table class has TextColumn get note => text().nullable()();. What Dart type does the generated row class use for note, and what happens if you remove nullable() and an insert leaves note out?
Show answer
The row field is String?. Without nullable() the column is NOT NULL and has no default, so an insert that omits it fails. The generated companion's insert constructor also requires a note argument.
Exercise
You want a Projects table whose key is a text code column that you supply, such as "WEB". Which two things change compared with an autoIncrement() key?
Show answer
Define code as text() with no autoIncrement(), and override Set<Column> get primaryKey => {code};. You must also pass code on every insert, since SQLite no longer assigns it.