sozsoft-platform/api/src/Sozsoft.Platform.DbMigrator/Seeds/HangfireDbSchemaMigrator.cs
2026-05-15 22:42:33 +03:00

65 lines
2.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Threading.Tasks;
using Hangfire.SqlServer;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Sozsoft.Platform.Data;
using Volo.Abp.DependencyInjection;
using static Sozsoft.Settings.SettingsConsts;
namespace Sozsoft.Platform.DbMigrator;
/// <summary>
/// DbMigrator çalışırken HangFire şemasını oluşturur.
/// EF Core migration'larından sonra (EntityFrameworkCorePlatformDbSchemaMigrator),
/// SqlDataSeeder'dan önce çalışarak HangFire tablolarının (HangFire.Job vb.) mevcut
/// olmasını sağlar. Bu sayede SqlData klasöründeki HangFire view'ları ilk çalışmada oluşturulabilir.
/// [ExposeServices] ABP'nin naming convention'ından bağımsız olarak IPlatformDbSchemaMigrator
/// listesine dahil edilmesini sağlar.
/// </summary>
[ExposeServices(typeof(IPlatformDbSchemaMigrator))]
public class HangfireDbSchemaMigrator : IPlatformDbSchemaMigrator, ITransientDependency
{
private readonly IConfiguration _configuration;
private readonly ILogger<HangfireDbSchemaMigrator> _logger;
public HangfireDbSchemaMigrator(
IConfiguration configuration,
ILogger<HangfireDbSchemaMigrator> logger)
{
_configuration = configuration;
_logger = logger;
}
public async Task MigrateAsync()
{
var connectionString = _configuration.GetConnectionString(DefaultDatabaseProvider);
if (string.IsNullOrWhiteSpace(connectionString))
{
_logger.LogWarning("HangFire schema migration skipped: connection string '{Key}' not found.", DefaultDatabaseProvider);
return;
}
try
{
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
// HangFire tablolarını oluştur (idempotent — mevcutsa atlar).
SqlServerObjectsInstaller.Install(connection, "HangFire", enableHeavyMigrations: true);
_logger.LogInformation("HangFire schema initialized successfully.");
}
catch (SqlException sqlEx) when (sqlEx.Number == 4060)
{
// Veritabanı henüz oluşturulmamış (ilk migration dışında tenant DB senaryosu)
_logger.LogWarning("HangFire schema skipped: database does not exist yet (error 4060).");
}
catch (Exception ex)
{
_logger.LogError(ex, "HangFire schema initialization FAILED.");
throw;
}
}
}