diff --git a/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreDatabaseMigrationEventHandlerBase.cs b/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreDatabaseMigrationEventHandlerBase.cs index 95b18d8221..4f0f51bd89 100644 --- a/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreDatabaseMigrationEventHandlerBase.cs +++ b/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreDatabaseMigrationEventHandlerBase.cs @@ -76,6 +76,13 @@ public abstract class EfCoreDatabaseMigrationEventHandlerBase : return; } + if (eventData.TenantId.HasValue && !await TenantExistsAsync(eventData.TenantId.Value)) + { + Logger.LogInformation( + $"Skipping the database migrations: the tenant no longer exists. TenantId = {eventData.TenantId}, Database Name = {DatabaseName}."); + return; + } + var schemaMigrated = false; try { @@ -108,6 +115,13 @@ public abstract class EfCoreDatabaseMigrationEventHandlerBase : public virtual async Task HandleEventAsync(TenantCreatedEto eventData) { + if (!await TenantExistsAsync(eventData.Id)) + { + Logger.LogInformation( + $"Skipping the tenant created event: the tenant no longer exists. TenantId = {eventData.Id}, TenantName = {eventData.Name}, Database Name = {DatabaseName}."); + return; + } + var schemaMigrated = false; try { @@ -147,6 +161,13 @@ public abstract class EfCoreDatabaseMigrationEventHandlerBase : return; } + if (!await TenantExistsAsync(eventData.Id)) + { + Logger.LogInformation( + $"Skipping the tenant connection string updated event: the tenant no longer exists. TenantId = {eventData.Id}, TenantName = {eventData.Name}, Database Name = {DatabaseName}."); + return; + } + var schemaMigrated = false; try { @@ -183,6 +204,20 @@ public abstract class EfCoreDatabaseMigrationEventHandlerBase : return Task.CompletedTask; } + /// + /// A tenant can be deleted before an event about it is handled (the events are handled asynchronously, + /// and each service handles them on its own). Such an event has nothing to migrate or seed. + /// + protected virtual async Task TenantExistsAsync(Guid tenantId) + { + using (var uow = UnitOfWorkManager.Begin(requiresNew: true, isTransactional: false)) + { + var tenantConfiguration = await TenantStore.FindAsync(tenantId); + await uow.CompleteAsync(); + return tenantConfiguration != null; + } + } + /// /// Apply pending EF Core schema migrations to the database. /// Returns true if any migration has applied. @@ -238,8 +273,14 @@ public abstract class EfCoreDatabaseMigrationEventHandlerBase : else { var tenantConfiguration = await TenantStore.FindAsync(tenantId.Value); - if (!tenantConfiguration!.ConnectionStrings!.Default.IsNullOrWhiteSpace() || - !tenantConfiguration.ConnectionStrings.GetOrDefault(DatabaseName).IsNullOrWhiteSpace()) + if (tenantConfiguration == null) + { + Logger.LogInformation( + $"The tenant no longer exists, its database is not migrated. Database Name = {DatabaseName}, TenantId = {tenantId}"); + } + else if (tenantConfiguration.ConnectionStrings != null && + (!tenantConfiguration.ConnectionStrings.Default.IsNullOrWhiteSpace() || + !tenantConfiguration.ConnectionStrings.GetOrDefault(DatabaseName).IsNullOrWhiteSpace())) { //Migrating the tenant database (only if tenant has a separate database) Logger.LogInformation( diff --git a/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreDatabaseMigrationEventHandlerBase_Tests.cs b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreDatabaseMigrationEventHandlerBase_Tests.cs new file mode 100644 index 0000000000..7644e8dbb6 --- /dev/null +++ b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreDatabaseMigrationEventHandlerBase_Tests.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Shouldly; +using Volo.Abp.Data; +using Volo.Abp.DistributedLocking; +using Volo.Abp.EventBus.Distributed; +using Volo.Abp.MultiTenancy; +using Volo.Abp.Uow; +using Xunit; + +namespace Volo.Abp.EntityFrameworkCore.Migrations; + +public class EfCoreDatabaseMigrationEventHandlerBase_Tests : EntityFrameworkCoreTestBase +{ + // A tenant can be deleted before the services handle the events about it: the tenant store then returns null. + + [Fact] + public async Task Should_Skip_The_Tenant_Created_Event_Of_A_Deleted_Tenant() + { + var handler = CreateHandler(); + + await handler.HandleEventAsync(new TenantCreatedEto { Id = Guid.NewGuid(), Name = "deleted-tenant" }); + + handler.SeededTenantIds.ShouldBeEmpty(); + handler.Errors.ShouldBeEmpty(); + } + + [Fact] + public async Task Should_Skip_The_Connection_String_Updated_Event_Of_A_Deleted_Tenant() + { + var handler = CreateHandler(); + + await handler.HandleEventAsync(new TenantConnectionStringUpdatedEto + { + Id = Guid.NewGuid(), + Name = "deleted-tenant", + ConnectionStringName = TestDatabaseMigrationEventHandler.TestDatabaseName, + NewValue = "Data Source=deleted-tenant.db" + }); + + handler.SeededTenantIds.ShouldBeEmpty(); + handler.Errors.ShouldBeEmpty(); + } + + [Fact] + public async Task Should_Skip_The_Apply_Database_Migrations_Event_Of_A_Deleted_Tenant() + { + var handler = CreateHandler(); + + await handler.HandleEventAsync(new ApplyDatabaseMigrationsEto + { + TenantId = Guid.NewGuid(), + DatabaseName = TestDatabaseMigrationEventHandler.TestDatabaseName + }); + + handler.SeededTenantIds.ShouldBeEmpty(); + handler.Errors.ShouldBeEmpty(); + } + + private TestDatabaseMigrationEventHandler CreateHandler() + { + return new TestDatabaseMigrationEventHandler( + GetRequiredService(), + GetRequiredService(), + GetRequiredService(), + GetRequiredService(), + GetRequiredService(), + GetRequiredService() + ); + } + + private class TestDatabaseMigrationEventHandler : EfCoreDatabaseMigrationEventHandlerBase + { + public const string TestDatabaseName = "TestMigrations"; + + public List SeededTenantIds { get; } = new(); + + public List Errors { get; } = new(); + + public TestDatabaseMigrationEventHandler( + ICurrentTenant currentTenant, + IUnitOfWorkManager unitOfWorkManager, + ITenantStore tenantStore, + IAbpDistributedLock abpDistributedLock, + IDistributedEventBus distributedEventBus, + ILoggerFactory loggerFactory) + : base(TestDatabaseName, currentTenant, unitOfWorkManager, tenantStore, abpDistributedLock, distributedEventBus, loggerFactory) + { + } + + protected override Task SeedAsync(Guid? tenantId) + { + SeededTenantIds.Add(tenantId); + return Task.CompletedTask; + } + + // Recorded instead of re-queued, so that a failure shows up at once. + protected override Task HandleErrorTenantCreatedAsync(TenantCreatedEto eventData, Exception exception) + { + Errors.Add(exception); + return Task.CompletedTask; + } + + protected override Task HandleErrorTenantConnectionStringUpdatedAsync(TenantConnectionStringUpdatedEto eventData, Exception exception) + { + Errors.Add(exception); + return Task.CompletedTask; + } + + protected override Task HandleErrorOnApplyDatabaseMigrationAsync(ApplyDatabaseMigrationsEto eventData, Exception exception) + { + Errors.Add(exception); + return Task.CompletedTask; + } + } +}