Sub topic 5
Creating the database class and opening it
This chapter assumes you have already added drift and drift_flutter, defined the TodoItems table, and run build_runner once. You should also be comfortable with Future, async/await, and constructors with optional positional parameters. Here you write the class that ties the tables to a SQLite file and learn how and when the file is opened.
What the database class does
In drift, the database class is the single entry point to your data. It does three jobs:
- It lists the tables that belong to the schema.
- It declares the schema version.
- It holds the connection to SQLite and exposes the query builders (
select,into,update,delete).
You write a small class and let the generator write the rest:
import 'package:drift/drift.dart';
import 'package:drift_flutter/drift_flutter.dart';
part 'database.g.dart';
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)();
}
@DriftDatabase(tables: [TodoItems])
class AppDatabase extends _$AppDatabase {
AppDatabase([QueryExecutor? executor])
: super(executor ?? driftDatabase(name: 'app'));
@override
int get schemaVersion => 1;
}Each piece has a purpose.
The pieces, one at a time
The part directive
part 'database.g.dart'; tells Dart that the generated file is part of this library. Without it, the name _$AppDatabase does not exist and the analyzer reports an error. The generated file shares the library's private names, which is why the superclass can start with _$. Its name must match your file name, plus .g.dart.
The @DriftDatabase annotation
@DriftDatabase(tables: [TodoItems]) is what build_runner looks for. Any table you forget to list here gets no generated code. You cannot query it, and it is not created in the file. If you add a table class and the app fails with "no such table" or the accessor is missing, check this list first.
The generated superclass
_$AppDatabase is generated. It provides:
- A typed accessor for each table, such as
todoItems. You pass these toselect(todoItems)andinto(todoItems). - The row class (
TodoItem) and the companion class (TodoItemsCompanion). allTables, which the default migration uses to create the schema.
Because the class extends the generated one, run dart run build_runner build again whenever you change table definitions or the annotation. Until then, the editor shows errors about missing members.
The schema version
schemaVersion is an integer you raise by hand each time the schema changes. Drift stores it inside the SQLite file, in the user_version pragma. On open, drift compares the stored number to yours and decides whether to create the schema or migrate it. For a brand-new app it is 1. A later chapter covers what to do when you raise it.
The constructor and the QueryExecutor
The constructor takes an optional QueryExecutor. A QueryExecutor is the object that actually sends SQL to a database engine. The default, driftDatabase(name: 'app') from drift_flutter, builds an executor that opens a SQLite file named app in the app's documents directory on mobile and desktop. On the web it uses WebAssembly SQLite with browser storage.
Making the executor optional is a deliberate design choice. Production code calls AppDatabase() and gets the real file. Tests call AppDatabase(NativeDatabase.memory()) and get a throwaway database. You do not need a mock or an interface, and the database class stays unchanged.
If you need the file in a different place, pass options to driftDatabase. This example uses the application support directory and requires the path_provider package:
import 'package:drift_flutter/drift_flutter.dart';
import 'package:path_provider/path_provider.dart';
QueryExecutor openConnection() {
return driftDatabase(
name: 'app',
native: const DriftNativeOptions(
databaseDirectory: getApplicationSupportDirectory,
),
);
}When the file is actually opened
Creating the object does not open the file. Drift opens the connection lazily, on the first query. At that moment it:
- Opens or creates the file.
- Reads
user_version. - Runs
onCreate(fresh file) oronUpgrade(older version), thenbeforeOpen. - Runs your query.
Two consequences follow. Constructing the database in main() is cheap and does not slow startup. And errors from opening, such as a failed migration, appear as exceptions from the first query, not from the constructor.
The default driftDatabase runs the SQLite work on a background isolate on native platforms, so queries do not block your UI thread. You do not need to configure this. A later chapter covers the details.
Running code before the database is used
Sometimes you must run setup SQL on every open. The most common case is enabling foreign keys, which SQLite leaves off by default. Override migration and use beforeOpen:
@override
MigrationStrategy get migration => MigrationStrategy(
onCreate: (m) => m.createAll(),
beforeOpen: (details) async {
await customStatement('PRAGMA foreign_keys = ON');
if (details.wasCreated) {
// Runs only on a freshly created file.
}
},
);details.wasCreated is true only when this open created the schema. details.hadUpgrade tells you a migration just ran. Overriding migration replaces the default, so include onCreate: (m) => m.createAll() yourself. If you leave it out, a new install ends up with no tables.
One instance, closed once
Open one AppDatabase per file for the whole app, and share it. Two instances pointing at the same file each hold their own connection. Drift cannot coordinate them, so streams from one do not see writes from the other, and drift prints a warning about duplicate databases. A common mistake is calling AppDatabase() inside build, which creates a new database on every rebuild.
A simple way to get a single instance is to create it in a State object and pass it down:
import 'package:flutter/material.dart';
import 'database.dart';
void main() => runApp(const App());
class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
late final AppDatabase db = AppDatabase();
@override
void dispose() {
db.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: FutureBuilder<List<TodoItem>>(
future: db.select(db.todoItems).get(),
builder: (context, snapshot) {
if (!snapshot.hasData) return const CircularProgressIndicator();
return Text('${snapshot.data!.length} items stored');
},
),
),
),
);
}
}Note that late final delays creation until first use, and dispose calls close(). The FutureBuilder here recreates its future on each rebuild. That is acceptable for a demo, but the streams chapter shows the proper pattern.
For larger apps you can hand the instance to a dependency injection package or an InheritedWidget. The rule stays the same: one instance, created once, closed once.
Common errors
| Symptom | Likely cause |
|---|---|
| `_$AppDatabase` is undefined | `build_runner` has not run, or the `part` file name is wrong |
| A table accessor is missing | The table is not in the `tables:` list, or the generator was not re-run |
| "no such table" at runtime | You overrode `migration` without `onCreate: (m) => m.createAll()` |
| Data disappears after an update | The database name or directory changed between releases |
| Warning about multiple database instances | `AppDatabase()` is called repeatedly, for example inside `build` |
| Foreign key constraints are ignored | `PRAGMA foreign_keys = ON` is not set in `beforeOpen` |
Exercise
Your teammate calls AppDatabase() inside a widget's build method and says it works. Name two problems this causes and describe a fix.
Show answer
Each rebuild creates a new database object with its own connection to the same file, so streams on one instance do not see writes made through another, and drift warns about duplicate instances. The old instances are also never closed, which leaks connections. Fix it by creating one instance in a long-lived place, such as a late final field in a State object (or a dependency injection container), passing it to the widgets that need it, and calling close() in dispose.
Exercise
Why does the AppDatabase constructor accept an optional QueryExecutor, and what do you pass in a unit test?
Show answer
The optional parameter lets production code use the default on-device file from driftDatabase(name: 'app'), while tests supply a different executor without changing the class. In a test, pass NativeDatabase.memory() so each test gets a fresh database that is never written to disk.