public void UpdateModel(string prefix = null) { try { //Find all unapplied migrations and apply using up operations //Update model with all unapplied migrations var appliedMigrations = _rabbitMqHistory.GetAppliedMigrations(prefix); var allMigrations = GetAllRabbitMqMigrations(prefix); using (new RabbitMqMigratorLock(_connectionFactory)) { using var connection = _connectionFactory.CreateConnection(); foreach (var migrationInfo in allMigrations.OrderBy(x => x.Key)) { var applied = appliedMigrations.GetMigration(migrationInfo.Key); if (applied == null) { // Apply migration operations ApplyOperations(connection, prefix, migrationInfo.Value.UpOperations); appliedMigrations.AddMigration(migrationInfo); } else if (!string.IsNullOrEmpty(applied.Hash) && applied.Hash != migrationInfo.Value.CalculateHash()) { // Rollback old version of migration ApplyOperations(connection, prefix, applied.DownOperations); // Apply new version of migration ApplyOperations(connection, prefix, migrationInfo.Value.UpOperations); applied.UpdateMigration(migrationInfo.Value); } else if (string.IsNullOrEmpty(applied.Hash)) { applied.UpdateMigration(migrationInfo.Value); } } foreach (var applied in appliedMigrations.AppliedMigrations.Where(x => allMigrations.All(y => y.Key != x.Name)).ToList()) { // Rollback migration because not present in current application ApplyOperations(connection, prefix, applied.DownOperations); appliedMigrations.RemoveMigration(applied.Name); } _rabbitMqHistory.UpdateAppliedMigrations(appliedMigrations); } } catch (FileLoadException ex) { throw new RabbitMqMigrationException($"Could not update RabbitMQ model: could not load file {ex.FileName}", ex); } catch (Exception ex) { throw new RabbitMqMigrationException("Could not update RabbitMQ model", ex); } }
public void TestGetAppliedMigrations() { _rabbitMqHistory.Init(); SetupDefaultExchange(); PushDummyMigrationHistoryMessage(); var result = _rabbitMqHistory.GetAppliedMigrations("test"); Assert.IsNotNull(result); Assert.AreEqual("test", result.Prefix); Assert.AreEqual(1, result.AppliedMigrations.Count); Assert.AreEqual("001_TestMigration", result.AppliedMigrations.First().Name); }