diff --git a/lib/services/migration/migration_service.dart b/lib/services/migration/migration_service.dart index 7a1e9c7a..2aabcef5 100644 --- a/lib/services/migration/migration_service.dart +++ b/lib/services/migration/migration_service.dart @@ -1,3 +1,5 @@ +import 'dart:developer'; + import 'package:isar/isar.dart'; import '../../common/constants/constants.dart'; @@ -19,6 +21,8 @@ class MigrationService { switch (databaseVersion) { case 1: await _migrateToV2(); + case 2: + await _migrateToV3(); } } @@ -63,4 +67,34 @@ class MigrationService { // Update the database version await PreferenceKey.databaseVersion.set(2); } + + /// Migrates the database to version 3. + /// + /// Sets the new `id` and `archived` fields of each rich text note. + Future _migrateToV3() async { + logger.i('Migrating the database from version 2 to version 3'); + + // Get the rich text notes + final richTextNotes = await _databaseService.database.richTextNotes.where().findAll(); + log(richTextNotes.map((n) => n.toJson()).toString()); + + // Set the rich text notes 'id' and 'archived' fields + for (final note in richTextNotes) { + note.id = uuid.v4(); + note.archived = false; + await _notesService.put(note); + } + + // Check that the migration succeeded + final richTextNotesCount = await _databaseService.database.richTextNotes.count(); + final richTextNotesNotArchivedCount = + await _databaseService.database.richTextNotes.where().archivedEqualTo(false).count(); + assert( + richTextNotesCount == richTextNotesNotArchivedCount, + 'The count of rich text notes ($richTextNotesCount) is different from the count of not archived rich text notes ($richTextNotesNotArchivedCount) after the migration to v3', + ); + + // Update the database version + await PreferenceKey.databaseVersion.set(3); + } }