Skip to content

Commit

Permalink
feat: add database migration
Browse files Browse the repository at this point in the history
  • Loading branch information
maelchiotti committed Feb 15, 2025
1 parent 37129b9 commit 9fb6d5a
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions lib/services/migration/migration_service.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:developer';

import 'package:isar/isar.dart';

import '../../common/constants/constants.dart';
Expand All @@ -19,6 +21,8 @@ class MigrationService {
switch (databaseVersion) {
case 1:
await _migrateToV2();
case 2:
await _migrateToV3();
}
}

Expand Down Expand Up @@ -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<void> _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);
}
}

0 comments on commit 9fb6d5a

Please sign in to comment.