From 6e067a28d8527726a2a17045bef0f0e3d3430ed5 Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 23 Apr 2021 17:28:18 +0800 Subject: refactor: Refactor a lot. --- .../DatabaseManagement/DatabaseCustomMigrator.cs | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 BackEnd/Timeline/Services/DatabaseManagement/DatabaseCustomMigrator.cs (limited to 'BackEnd/Timeline/Services/DatabaseManagement/DatabaseCustomMigrator.cs') 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 _migrations; + private DatabaseContext _database; + + private ILogger _logger; + + public DatabaseCustomMigrator(IEnumerable migrations, DatabaseContext database, ILogger 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); + } + } + } + } +} -- cgit v1.2.3