LiteDbMigrations.cs
1 using GUNRPG.Application.Sessions; 2 using LiteDB; 3 using LiteDB.Migration; 4 5 namespace GUNRPG.Infrastructure.Persistence; 6 7 /// <summary> 8 /// Manages database schema migrations for LiteDB. 9 /// Handles versioning and upgrading of combat session snapshots. 10 /// </summary> 11 public static class LiteDbMigrations 12 { 13 /// <summary> 14 /// Current schema version of the combat session snapshot. 15 /// Increment this when making breaking changes to the snapshot structure. 16 /// </summary> 17 public const int CurrentSchemaVersion = 1; 18 19 /// <summary> 20 /// Applies all necessary migrations to the database. 21 /// Should be called during application startup before any data access. 22 /// </summary> 23 /// <param name="database">The LiteDB database instance</param> 24 public static void ApplyMigrations(LiteDatabase database) 25 { 26 if (database == null) 27 throw new ArgumentNullException(nameof(database)); 28 29 // Currently on version 1 with no migrations needed 30 // When schema changes are needed, add migrations here using LiteDB.Migration 31 32 // Example migration setup for future use: 33 // var migrations = new MigrationContainer(config => 34 // { 35 // config.Collection<CombatSessionSnapshot>("combat_sessions", collectionConfig => 36 // { 37 // collectionConfig 38 // .StartWithModel<OldCombatSessionSnapshot>() 39 // .WithMigration(old => new CurrentCombatSessionSnapshot 40 // { 41 // Id = old.Id, 42 // // ... map properties 43 // NewProperty = "default" 44 // }) 45 // .UseLatestVersion(); 46 // }); 47 // }); 48 // migrations.Apply(database); 49 50 // No migrations to apply yet - we're on the initial schema version 51 } 52 53 /// <summary> 54 /// Gets the current schema version stored in the database metadata. 55 /// Returns 0 if no version is set (new database). 56 /// </summary> 57 public static int GetDatabaseSchemaVersion(LiteDatabase database) 58 { 59 if (database == null) 60 throw new ArgumentNullException(nameof(database)); 61 62 var metadata = database.GetCollection("_metadata"); 63 var versionDoc = metadata.FindById("schema_version"); 64 65 if (versionDoc == null) 66 { 67 return 0; 68 } 69 70 return versionDoc["version"].AsInt32; 71 } 72 73 /// <summary> 74 /// Sets the schema version in the database metadata. 75 /// Used to track which migrations have been applied. 76 /// </summary> 77 public static void SetDatabaseSchemaVersion(LiteDatabase database, int version) 78 { 79 if (database == null) 80 throw new ArgumentNullException(nameof(database)); 81 82 var metadata = database.GetCollection("_metadata"); 83 var versionDoc = new BsonDocument 84 { 85 ["_id"] = "schema_version", 86 ["version"] = version, 87 ["updated_at"] = DateTimeOffset.UtcNow.ToString("O") 88 }; 89 metadata.Upsert(versionDoc); 90 } 91 }