sozsoft-platform/api/src/Sozsoft.Platform.Domain/Data/PlatformDbMigrationService.cs

262 lines
10 KiB
C#
Raw Normal View History

2026-02-24 20:44:16 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
2026-10-05 12:58:59 +00:00
using Sozsoft.Languages.Caching;
2026-09-04 09:05:26 +00:00
using Sozsoft.Platform.Data.Seeds;
2026-02-24 20:44:16 +00:00
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.TenantManagement;
namespace Sozsoft.Platform.Data;
public class PlatformDbMigrationService : ITransientDependency
{
public ILogger<PlatformDbMigrationService> Logger { get; set; }
private readonly IDataSeeder _dataSeeder;
private readonly IEnumerable<IPlatformDbSchemaMigrator> _dbSchemaMigrators;
private readonly ITenantRepository _tenantRepository;
private readonly ICurrentTenant _currentTenant;
private readonly IConfiguration _configuration;
private readonly IEnumerable<IFinalSeeder> _finalSeeders;
2026-09-04 09:05:26 +00:00
private readonly IListFormSeedDataApplier _listFormSeedDataApplier;
2026-10-05 12:58:59 +00:00
private readonly DistributedCacheCleaner _cacheCleaner;
2026-02-24 20:44:16 +00:00
public PlatformDbMigrationService(
IDataSeeder dataSeeder,
IEnumerable<IPlatformDbSchemaMigrator> dbSchemaMigrators,
ITenantRepository tenantRepository,
ICurrentTenant currentTenant,
IConfiguration configuration,
IEnumerable<IFinalSeeder> finalSeeders,
2026-10-05 12:58:59 +00:00
IListFormSeedDataApplier listFormSeedDataApplier,
DistributedCacheCleaner cacheCleaner)
2026-02-24 20:44:16 +00:00
{
_dataSeeder = dataSeeder;
_dbSchemaMigrators = dbSchemaMigrators;
_tenantRepository = tenantRepository;
_currentTenant = currentTenant;
_configuration = configuration;
_finalSeeders = finalSeeders;
2026-09-04 09:05:26 +00:00
_listFormSeedDataApplier = listFormSeedDataApplier;
2026-10-05 12:58:59 +00:00
_cacheCleaner = cacheCleaner;
2026-02-24 20:44:16 +00:00
Logger = NullLogger<PlatformDbMigrationService>.Instance;
}
public async Task MigrateAsync()
{
var seed = _configuration.GetValue("Seed", false);
Logger.LogInformation($"Migrating database. Seed: {seed}. Env: {Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")}");
2026-10-05 12:58:59 +00:00
await ClearCacheAsync();
2026-02-24 20:44:16 +00:00
2026-10-05 12:58:59 +00:00
var tenantSeedId = _configuration.GetValue<Guid?>(TenantSeedOptions.TenantIdKey);
if (tenantSeedId.HasValue)
2026-02-24 20:44:16 +00:00
{
2026-10-05 12:58:59 +00:00
await SeedSingleTenantAsync(tenantSeedId.Value);
2026-02-24 20:44:16 +00:00
return;
}
Logger.LogInformation("Started database migrations...");
await MigrateDatabaseSchemaAsync();
2026-10-05 12:58:59 +00:00
var tenants = await _tenantRepository.GetListAsync(includeDetails: true);
// Bekleyen wizard kurulumu dosyaları uygulayan son veritabanında kapanır; host'ta kapansaydı
// ekranın eski sürümü kurulu olan ayrı veritabanlı tenant onu "kurulu" sayıp güncellemezdi.
var lastSeedFileTenant = tenants.LastOrDefault(SeedFileScope.AppliesTo);
2026-02-24 20:44:16 +00:00
if (seed)
{
2026-10-05 12:58:59 +00:00
await SeedDataAsync(completesPending: lastSeedFileTenant == null);
2026-02-24 20:44:16 +00:00
}
Logger.LogInformation($"Successfully completed host database migrations.");
var migratedDatabaseSchemas = new HashSet<string>();
foreach (var tenant in tenants)
{
using (_currentTenant.Change(tenant.Id))
{
if (tenant.ConnectionStrings.Any())
{
var tenantConnectionStrings = tenant.ConnectionStrings
.Select(x => x.Value)
.ToList();
if (!migratedDatabaseSchemas.IsSupersetOf(tenantConnectionStrings))
{
await MigrateDatabaseSchemaAsync(tenant);
migratedDatabaseSchemas.AddIfNotContains(tenantConnectionStrings);
}
}
if (seed)
{
2026-10-05 12:58:59 +00:00
await SeedDataAsync(tenant, completesPending: tenant == lastSeedFileTenant);
2026-02-24 20:44:16 +00:00
}
}
Logger.LogInformation($"Successfully completed {tenant.Name} tenant database migrations.");
}
Logger.LogInformation("Successfully completed all database migrations.");
2026-10-05 12:58:59 +00:00
await ExecuteFinalSeedersAsync(tenants, includeHost: true);
// Seed; menu, yetki ve dil metni ekler. Calisan uygulama bu arada eski halleri onbellege
// almis olabilir (ornegin wizard'in yeni menusu); migrate sonrasinda da temizlenir.
if (seed)
2026-10-05 12:58:59 +00:00
await ClearCacheAsync();
Logger.LogInformation("You can safely end this process...");
}
/// <summary>
/// Tenants ekranının "Seed" sekmesi: yalnızca verilen tenant'ın şemasını ve seed'ini
/// tam migrate'le aynı adımlarla çalıştırır. Yönetici bilgisi bu tenant için ekrandan gelir;
/// tam migrate'teki varsayılan yönetici kullanılmaz.
/// </summary>
private async Task SeedSingleTenantAsync(Guid tenantId)
{
var tenant = await _tenantRepository.FindAsync(tenantId, includeDetails: true)
?? throw new InvalidOperationException($"Tenant not found: {tenantId}");
var adminEmail = _configuration[TenantSeedOptions.AdminEmailKey];
var adminPassword = _configuration[TenantSeedOptions.AdminPasswordKey];
if (string.IsNullOrWhiteSpace(adminEmail) || string.IsNullOrWhiteSpace(adminPassword))
{
throw new InvalidOperationException("Admin email and password are required for tenant seed.");
}
Logger.LogInformation("Started {TenantName} tenant migration and seed...", tenant.Name);
using (_currentTenant.Change(tenant.Id))
{
if (tenant.ConnectionStrings.Any())
{
await MigrateDatabaseSchemaAsync(tenant);
}
// Host ve diğer tenant'lar bu çalışmada kurulmadığı için bekleyen wizard kurulumu açık kalır.
await SeedDataAsync(tenant, completesPending: false, adminEmail, adminPassword);
}
Logger.LogInformation("Successfully completed {TenantName} tenant database migrations.", tenant.Name);
await ExecuteFinalSeedersAsync([tenant], includeHost: false);
await ClearCacheAsync();
2026-02-24 20:44:16 +00:00
Logger.LogInformation("You can safely end this process...");
}
2026-10-05 12:58:59 +00:00
private async Task ClearCacheAsync()
{
2026-10-05 12:58:59 +00:00
var removed = await _cacheCleaner.ClearAsync();
Logger.LogInformation("Distributed cache cleared. {Count} key(s) removed.", removed);
}
/// <summary>
2026-08-17 09:23:47 +00:00
/// Tüm host ve tenant migration/seed adımları bittikten sonra,
2026-10-05 12:58:59 +00:00
/// {sql|postgres}/execute klasöründeki script'lerin dosya adından türeyen procedure'lerini
/// host'ta ve kendi veritabanı olan her tenant'ta çalıştırır. Host veritabanını paylaşan tenant
/// atlanır; procedure o veritabanında host adımında zaten çalışmıştır.
/// </summary>
2026-10-05 12:58:59 +00:00
private async Task ExecuteFinalSeedersAsync(List<Tenant> tenants, bool includeHost)
{
if (!_finalSeeders.Any())
{
2026-08-17 09:23:47 +00:00
Logger.LogInformation("No SQL executor registered, skipping execute scripts.");
return;
}
Logger.LogInformation(
2026-10-05 12:58:59 +00:00
"Executing SQL scripts for {Host}{TenantCount} tenant(s)...",
includeHost ? "host and " : string.Empty,
tenants.Count);
2026-10-05 12:58:59 +00:00
if (includeHost)
{
2026-10-05 12:58:59 +00:00
using (_currentTenant.Change(null))
{
2026-10-05 12:58:59 +00:00
foreach (var executor in _finalSeeders)
{
Logger.LogInformation("Running SQL scripts for host...");
await executor.ExecuteAsync();
Logger.LogInformation("Completed SQL scripts for host.");
}
}
}
2026-10-05 12:58:59 +00:00
foreach (var tenant in tenants.Where(SeedFileScope.AppliesTo))
{
using (_currentTenant.Change(tenant.Id))
{
foreach (var executor in _finalSeeders)
{
Logger.LogInformation(
2026-08-12 12:20:00 +00:00
"Running SQL scripts for {TenantName} tenant...",
tenant.Name);
2026-10-05 12:58:59 +00:00
await executor.ExecuteAsync();
Logger.LogInformation(
2026-08-12 12:20:00 +00:00
"Completed SQL scripts for {TenantName} tenant.",
tenant.Name);
}
}
}
2026-08-12 12:20:00 +00:00
Logger.LogInformation("Successfully completed all SQL scripts.");
}
2026-02-24 20:44:16 +00:00
private async Task MigrateDatabaseSchemaAsync(Tenant? tenant = null)
{
Logger.LogInformation(
$"Migrating schema for {(tenant == null ? "host" : tenant.Name + " tenant")} database...");
foreach (var migrator in _dbSchemaMigrators)
{
await migrator.MigrateAsync();
}
}
2026-10-05 12:58:59 +00:00
private async Task SeedDataAsync(
Tenant? tenant = null,
bool completesPending = true,
string adminEmail = PlatformConsts.AbpIdentity.User.AdminEmailDefaultValue,
string adminPassword = PlatformConsts.AbpIdentity.User.AdminPasswordDefaultValue)
2026-02-24 20:44:16 +00:00
{
Logger.LogInformation($"Executing {(tenant == null ? "host" : tenant.Name + " tenant")} database seed...");
2026-10-05 12:58:59 +00:00
var applySeedFiles = SeedFileScope.AppliesTo(tenant);
if (!applySeedFiles)
2026-02-24 20:44:16 +00:00
{
2026-10-05 12:58:59 +00:00
Logger.LogInformation("{TenantName} tenant shares the host database; seed files are already applied there.", tenant!.Name);
2026-02-24 20:44:16 +00:00
}
2026-10-05 12:58:59 +00:00
await _dataSeeder.SeedAsync(new DataSeedContext(tenant?.Id)
.WithProperty(IdentityDataSeedContributor.AdminEmailPropertyName, adminEmail)
.WithProperty(IdentityDataSeedContributor.AdminPasswordPropertyName, adminPassword)
.WithProperty(IdentityDataSeedContributor.AdminUserNamePropertyName, adminEmail)
.WithProperty(SeedFileScope.PropertyName, applySeedFiles)
.WithProperty(SeedFileScope.CompletesPendingPropertyName, completesPending)
2026-02-24 20:44:16 +00:00
);
2026-10-05 12:58:59 +00:00
// Veri seed dosyalari ListForm tanimlarina ve tablolara dayandigi icin butun
// contributor'lar bittikten sonra uygulanir; ABP contributor sirasi garanti degildir.
if (applySeedFiles)
2026-02-24 20:44:16 +00:00
{
2026-10-05 12:58:59 +00:00
await _listFormSeedDataApplier.ApplyAsync(tenant?.Id);
2026-02-24 20:44:16 +00:00
}
}
}