-
Notifications
You must be signed in to change notification settings - Fork 3
Database
Database is one of the (local) data sources of our application. It is responsible for persisting data on the device. This is important if you plan to support offline functionality in your application.
The project is using drift as the database.
The database file is saved in the application's cache directory. DatabaseFactory is responsible for opening the database when we are going read or write data.
A DataObject is a class that represents a table in the database.
See Data Objects for more details.
LocalDataSource is an interface that defines the operations that can be done in the database. We use this interface to hide the implementation details of the database to the consumers of the data source.
abstract interface class LocalDataSource<TTable extends DataTable, TDataObject extends Insertable<TDataObject>> {
Future<TDataObject?> get(int id);
Future<Iterable<TDataObject>> getAll();
Future<void> addOrUpdate(TDataObject object);
Future<void> addOrUpdateAll(Iterable<TDataObject> objects);
Future<void> remove(TDataObject object);
Future<void> removeAll(Iterable<int> ids);
}💡 IMPORTANT
- By default, we expose
getAllanddeleteAlldatabase operations with filters. This is to avoid loading all the data in the database at once. This is important if you have a large amount of data in the database. Loading all the data without any filters may be applicable for tables that have a small or fixed amount of data. - Update the implementing interfaces of
LocalDataSourceif you wish to add additional filters. See the next sections below for more details.
Once you have created your data object, you can now create your local data source by extending BaseLocalDataSource.
@lazySingleton
class PostLocalDataSource extends BaseLocalDataSource<AppDatabase, PostDataTable, PostDataObject> {
PostLocalDataSource(super.attachedDatabase);
Future<PostDataObject?> getPost(int postId) async {
final SimpleSelectStatement<PostDataTable, PostDataObject> query = select(table)
..where((PostDataTable t) => t.postId.equals(postId));
final PostDataObject? post = await query.getSingleOrNull();
return post;
}
}-
@lazySingletonis used to register the data source as a lazy singleton. -
BaseLocalDataSourceis a base class that implementsLocalDataSource. It is responsible for opening the database and executing transactions. -
PostDataTableis the schema of the table in the database. -
PostDataObjectis generated after running thebuild_runner. This is the class that represents the table in the database. - It is important that we only implement
LocalDataSource<PostDataObject>toPostLocalDataSource. This will hide the unecessary implementation details ofIsarLocalDataSourceto the consumers ofPostLocalDataSource.