Loading...
Loading...
Complete guide for using drift database library in Dart applications (CLI, server-side, non-Flutter). Use when building Dart apps that need local SQLite database storage or PostgreSQL connection with type-safe queries, reactive streams, migrations, and efficient CRUD operations. Includes setup with sqlite3 package, PostgreSQL support with drift_postgres, connection pooling, and server-side patterns.
npx skill4agent add madteacher/mad-agents-skills dart-driftpubspec.yamldependencies:
drift: ^2.30.0
sqlite3: ^3.1.3
dev_dependencies:
drift_dev: ^2.30.0
build_runner: ^2.10.4(tables: [TodoItems])
class AppDatabase extends _$AppDatabase {
AppDatabase(QueryExecutor e) : super(e);
int get schemaVersion => 1;
}AppDatabase openConnection() {
final file = File('db.sqlite');
return AppDatabase(LazyDatabase(() async {
final db = sqlite3.open(file.path);
return NativeDatabase.createInBackground(db);
}));
}dart run build_runner builddependencies:
drift: ^2.30.0
postgres: ^3.5.9
drift_postgres: ^1.3.1
dev_dependencies:
drift_dev: ^2.30.0
build_runner: ^2.10.4build.yamltargets:
$default:
builders:
drift_dev:
options:
sql:
dialects:
- postgresimport 'package:drift_postgres/drift_postgres.dart';
AppDatabase openPostgresConnection() {
final endpoint = HostEndpoint(
host: 'localhost',
port: 5432,
database: 'mydb',
username: 'user',
password: 'password',
);
return AppDatabase(
PgDatabase(
endpoint: endpoint,
),
);
}void main(List<String> args) async {
final db = openConnection();
final todos = await db.select(db.todoItems).get();
print('Found ${todos.length} todos');
await db.close();
}class TodoService {
final AppDatabase db;
TodoService(this.db);
Future<List<TodoItem>> getAllTodos() async {
return await db.select(db.todoItems).get();
}
Future<int> createTodo(String title) async {
return await db.into(db.todoItems).insert(
TodoItemsCompanion.insert(title: title),
);
}
}
void main() async {
final pool = PgPool(
PgEndpoint(
host: 'localhost',
port: 5432,
database: 'mydb',
username: 'user',
password: 'password',
),
settings: PoolSettings(maxSize: 10),
);
final db = AppDatabase(PgDatabase.opened(pool));
final service = TodoService(db);
final todoId = await service.createTodo('New task');
print('Created todo with id: $todoId');
final todos = await service.getAllTodos();
print('Total todos: ${todos.length}');
}import 'package:postgres/postgres_pool.dart';
Future<AppDatabase> openPooledConnection() {
final pool = PgPool(
PgEndpoint(
host: 'localhost',
port: 5432,
database: 'mydb',
username: 'user',
password: 'password',
),
settings: PoolSettings(maxSize: 20),
);
return AppDatabase(PgDatabase.opened(pool));
}class Users extends Table {
late final id = postgresUuid().autoGenerate()();
late final name = text()();
late final settings = postgresJson()();
late final createdAt = dateTime().withDefault(
FunctionCallExpression.currentTimestamp(),
);
}AppDatabase createTestDatabase() {
return AppDatabase(NativeDatabase.memory());
}Future<void> transferTodo(int fromId, int toId) async {
await db.transaction(() async {
final fromTodo = await (db.select(db.todoItems)
..where((t) => t.id.equals(fromId))
).getSingle();
await db.update(db.todoItems).write(
TodoItemsCompanion(
id: Value(toId),
title: Value(fromTodo.title),
),
);
await db.delete(db.todoItems).go(fromId);
});
}sqlite3postgresvoid main() {
test('Insert and retrieve todo', () async {
final db = createTestDatabase();
final id = await db.into(db.todoItems).insert(
TodoItemsCompanion.insert(title: 'Test todo'),
);
final todos = await db.select(db.todoItems).get();
expect(todos.length, 1);
expect(todos.first.title, 'Test todo');
await db.close();
});
}void main() {
test('PostgreSQL connection works', () async {
final pool = PgPool(endpoint, settings: PoolSettings(maxSize: 5));
final db = AppDatabase(PgDatabase.opened(pool));
final id = await db.into(db.todoItems).insert(
TodoItemsCompanion.insert(title: 'Test'),
);
expect(id, greaterThan(0));
await db.close();
});
}dart run build_runner clean
dart run build_runner build --delete-conflicting-outputsdart run drift_dev schema validate
dart run drift_dev make-migrationsPoolSettings(
maxSize: 20,
maxLifetime: Duration(minutes: 5),
)build.yaml