75 lines
1.7 KiB
Dart
75 lines
1.7 KiB
Dart
import 'package:isar/isar.dart';
|
|
import 'package:path_provider/path_provider.dart';
|
|
|
|
import '../../core/constants/app_defaults.dart';
|
|
import 'models/models.dart';
|
|
|
|
class AppDatabase {
|
|
AppDatabase._();
|
|
|
|
static final AppDatabase instance = AppDatabase._();
|
|
|
|
Isar? _isar;
|
|
|
|
Future<Isar> open() async {
|
|
final existing = _isar;
|
|
if (existing != null && existing.isOpen) {
|
|
return existing;
|
|
}
|
|
|
|
final directory = await getApplicationDocumentsDirectory();
|
|
final isar = await Isar.open(
|
|
<CollectionSchema>[
|
|
UserProfileSchema,
|
|
AppConfigSchema,
|
|
PointRecordSchema,
|
|
],
|
|
name: AppDefaults.localDatabaseName,
|
|
directory: directory.path,
|
|
inspector: false,
|
|
);
|
|
|
|
await _ensureBootstrapData(isar);
|
|
_isar = isar;
|
|
return isar;
|
|
}
|
|
|
|
Future<void> close() async {
|
|
final database = _isar;
|
|
if (database == null || !database.isOpen) {
|
|
return;
|
|
}
|
|
|
|
await database.close();
|
|
_isar = null;
|
|
}
|
|
|
|
Future<void> resetSingletonData() async {
|
|
final isar = await open();
|
|
await isar.writeTxn(() async {
|
|
await isar.userProfiles.put(UserProfile.createDefault());
|
|
await isar.appConfigs.put(AppConfig.createDefault());
|
|
});
|
|
}
|
|
|
|
Future<void> _ensureBootstrapData(Isar isar) async {
|
|
final hasProfile =
|
|
await isar.userProfiles.get(AppDefaults.singletonId) != null;
|
|
final hasConfig = await isar.appConfigs.get(AppDefaults.singletonId) != null;
|
|
|
|
if (hasProfile && hasConfig) {
|
|
return;
|
|
}
|
|
|
|
await isar.writeTxn(() async {
|
|
if (!hasProfile) {
|
|
await isar.userProfiles.put(UserProfile.createDefault());
|
|
}
|
|
|
|
if (!hasConfig) {
|
|
await isar.appConfigs.put(AppConfig.createDefault());
|
|
}
|
|
});
|
|
}
|
|
}
|