using HaDbMigration.Configuration; using HaDbMigration.Models; using HaDbMigration.Services.Interfaces; using Microsoft.Extensions.Logging; using Npgsql; namespace HaDbMigration.Services; public sealed class SchemaService : ISchemaService { private readonly MigrationOptions _options; private readonly ILogger _logger; public SchemaService(MigrationOptions options, ILogger logger) { _options = options; _logger = logger; } public async Task ValidateTablesExistAsync( IReadOnlyList tables, CancellationToken cancellationToken) { await using var connection = new NpgsqlConnection(_options.PostgresConnectionString); await connection.OpenAsync(cancellationToken); var allExist = true; foreach (var table in tables) { await using var command = connection.CreateCommand(); command.CommandText = """ SELECT EXISTS ( SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = @tableName ) """; command.Parameters.AddWithValue("@tableName", table.TableName); var exists = (bool)(await command.ExecuteScalarAsync(cancellationToken))!; if (!exists) { _logger.LogError("Table {Table} does not exist in PostgreSQL", table.TableName); allExist = false; } else { _logger.LogDebug("Table {Table} validated", table.TableName); } } return allExist; } public async Task TruncateTablesAsync( IReadOnlyList tables, CancellationToken cancellationToken) { await using var connection = new NpgsqlConnection(_options.PostgresConnectionString); await connection.OpenAsync(cancellationToken); var tableNames = string.Join(", ", tables.Select(t => $"\"{t.TableName}\"")); var sql = $"TRUNCATE TABLE {tableNames} CASCADE"; _logger.LogInformation("Truncating tables: {Tables}", tableNames); await using var command = connection.CreateCommand(); command.CommandText = sql; await command.ExecuteNonQueryAsync(cancellationToken); _logger.LogInformation("Tables truncated successfully"); } public async Task ResetSequencesAsync( IReadOnlyList tables, CancellationToken cancellationToken) { await using var connection = new NpgsqlConnection(_options.PostgresConnectionString); await connection.OpenAsync(cancellationToken); foreach (var table in tables) { if (table.SequenceColumn is null) { continue; } await ResetSequenceForTableAsync(connection, table, cancellationToken); } _logger.LogInformation("All sequences reset successfully"); } private async Task ResetSequenceForTableAsync( NpgsqlConnection connection, TableDescriptor table, CancellationToken cancellationToken) { var sql = $""" SELECT setval( pg_get_serial_sequence('"{table.TableName}"', '{table.SequenceColumn}'), COALESCE(MAX("{table.SequenceColumn}"), 1) ) FROM "{table.TableName}" """; await using var command = connection.CreateCommand(); command.CommandText = sql; try { await command.ExecuteScalarAsync(cancellationToken); _logger.LogDebug( "Reset sequence for {Table}.{Column}", table.TableName, table.SequenceColumn); } catch (PostgresException ex) when (ex.SqlState == "42P01") { _logger.LogWarning( "No sequence found for {Table}.{Column}, skipping", table.TableName, table.SequenceColumn); } } }