aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline/Services/DatabaseManagement/DatabaseCustomMigrator.cs
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2021-04-23 17:28:18 +0800
committercrupest <crupest@outlook.com>2021-04-23 17:37:37 +0800
commit6e067a28d8527726a2a17045bef0f0e3d3430ed5 (patch)
tree967ed4c84981d6b626a3370c726d35d1c3e2c2b4 /BackEnd/Timeline/Services/DatabaseManagement/DatabaseCustomMigrator.cs
parent6acef36dc717834605eda2af9e1738dac8fa2f6d (diff)
downloadtimeline-6e067a28d8527726a2a17045bef0f0e3d3430ed5.tar.gz
timeline-6e067a28d8527726a2a17045bef0f0e3d3430ed5.tar.bz2
timeline-6e067a28d8527726a2a17045bef0f0e3d3430ed5.zip
refactor: Refactor a lot.
Diffstat (limited to 'BackEnd/Timeline/Services/DatabaseManagement/DatabaseCustomMigrator.cs')
-rw-r--r--BackEnd/Timeline/Services/DatabaseManagement/DatabaseCustomMigrator.cs56
1 files changed, 56 insertions, 0 deletions
diff --git a/BackEnd/Timeline/Services/DatabaseManagement/DatabaseCustomMigrator.cs b/BackEnd/Timeline/Services/DatabaseManagement/DatabaseCustomMigrator.cs
new file mode 100644
index 00000000..2180ad40
--- /dev/null
+++ b/BackEnd/Timeline/Services/DatabaseManagement/DatabaseCustomMigrator.cs
@@ -0,0 +1,56 @@
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using Timeline.Entities;
+
+namespace Timeline.Services.DatabaseManagement
+{
+ public interface IDatabaseCustomMigrator
+ {
+ Task MigrateAsync(CancellationToken cancellationToken = default);
+ }
+
+ public class DatabaseCustomMigrator : IDatabaseCustomMigrator
+ {
+ private IEnumerable<IDatabaseCustomMigration> _migrations;
+ private DatabaseContext _database;
+
+ private ILogger<DatabaseCustomMigrator> _logger;
+
+ public DatabaseCustomMigrator(IEnumerable<IDatabaseCustomMigration> migrations, DatabaseContext database, ILogger<DatabaseCustomMigrator> logger)
+ {
+ _migrations = migrations;
+ _database = database;
+ _logger = logger;
+ }
+
+ public async Task MigrateAsync(CancellationToken cancellationToken = default)
+ {
+ foreach (var migration in _migrations)
+ {
+ var name = migration.GetName();
+ var isApplied = await _database.Migrations.AnyAsync(m => m.Name == name, cancellationToken);
+
+ _logger.LogInformation("Found custom migration '{0}'. Applied: {1}.", name, isApplied);
+
+ if (!isApplied)
+ {
+ _logger.LogWarning("Begin custom migration '{0}'.", name);
+
+ await using var transaction = await _database.Database.BeginTransactionAsync(cancellationToken);
+
+ await migration.ExecuteAsync(_database, cancellationToken);
+
+ _database.Migrations.Add(new MigrationEntity { Name = name });
+ await _database.SaveChangesAsync(cancellationToken);
+
+ await transaction.CommitAsync(cancellationToken);
+
+ _logger.LogWarning("End custom migration '{0}'.", name);
+ }
+ }
+ }
+ }
+}