Line data Source code
1 : import 'package:injectable/injectable.dart';
2 : import 'package:network_tools/src/database/database_service.dart';
3 : import 'package:network_tools/src/database/drift_database.dart';
4 : import 'package:network_tools/src/network_tools_utils.dart';
5 :
6 : @Injectable(as: DatabaseService<AppDatabase>)
7 : class DriftDatabaseService extends DatabaseService<AppDatabase> {
8 : static AppDatabase? appDatabase;
9 : static Future<AppDatabase?>? _openFuture;
10 :
11 6 : @override
12 6 : Future<AppDatabase?> open() => _openFuture ??= _open();
13 :
14 : /// Forgets the cached connection so the next [open] builds a fresh database.
15 : ///
16 : /// A drift connection cannot be reopened once closed, so without this the
17 : /// package stays broken for the rest of the process after a shutdown.
18 1 : static void reset() {
19 : _openFuture = null;
20 : appDatabase = null;
21 : }
22 :
23 6 : static Future<AppDatabase?> _open() async {
24 4 : final AppDatabase database = appDatabase ??= AppDatabase();
25 : try {
26 6 : await database.ensureIndexes();
27 : } catch (error, stackTrace) {
28 : // Indexes only speed up lookups, so a failure here must not block the
29 : // repositories from starting.
30 2 : logger.warning(
31 1 : 'Failed to create database indexes: $error',
32 : error,
33 : stackTrace,
34 : );
35 : }
36 : return database;
37 : }
38 : }
|