feat: Implement migration for hive schema versions

This commit is contained in:
Christian Pauly 2021-06-20 10:31:17 +02:00
parent 16f1cb7456
commit 96d28a1b76
1 changed files with 12 additions and 0 deletions

View File

@ -18,6 +18,7 @@ import 'package:hive/hive.dart';
/// ///
/// This database does not support file caching! /// This database does not support file caching!
class FamedlySdkHiveDatabase extends DatabaseApi { class FamedlySdkHiveDatabase extends DatabaseApi {
static const int version = 2;
final String name; final String name;
Box _clientBox; Box _clientBox;
Box _accountDataBox; Box _accountDataBox;
@ -163,9 +164,18 @@ class FamedlySdkHiveDatabase extends DatabaseApi {
_eventsBoxName, _eventsBoxName,
encryptionCipher: encryptionCipher, encryptionCipher: encryptionCipher,
); );
final currentVersion = (await _clientBox.get('version') as int) ?? 0;
if (currentVersion != version) await _migrateFromVersion(currentVersion);
return; return;
} }
Future<void> _migrateFromVersion(int currentVersion) async {
Logs().i('Migrate Hive database from version $currentVersion to $version');
await clearCache(0);
await _clientBox.put('version', version);
}
@override @override
Future<void> clear(int clientId) async { Future<void> clear(int clientId) async {
Logs().i('Clear and close hive database...'); Logs().i('Clear and close hive database...');
@ -185,6 +195,7 @@ class FamedlySdkHiveDatabase extends DatabaseApi {
await _timelineFragmentsBox.deleteAll(_timelineFragmentsBox.keys); await _timelineFragmentsBox.deleteAll(_timelineFragmentsBox.keys);
await _outboundGroupSessionsBox.deleteAll(_outboundGroupSessionsBox.keys); await _outboundGroupSessionsBox.deleteAll(_outboundGroupSessionsBox.keys);
await _presencesBox.deleteAll(_presencesBox.keys); await _presencesBox.deleteAll(_presencesBox.keys);
await _clientBox.delete('prev_batch');
} }
@override @override
@ -244,6 +255,7 @@ class FamedlySdkHiveDatabase extends DatabaseApi {
Future<Map<String, dynamic>> getClient(String name) async { Future<Map<String, dynamic>> getClient(String name) async {
final map = <String, dynamic>{}; final map = <String, dynamic>{};
for (final key in _clientBox.keys) { for (final key in _clientBox.keys) {
if (key == 'version') continue;
map[key] = await _clientBox.get(key); map[key] = await _clientBox.get(key);
} }
if (map.isEmpty) return null; if (map.isEmpty) return null;