164 lines
5.3 KiB
C#
164 lines
5.3 KiB
C#
using System.Threading.Channels;
|
|
using HaDbMigration.Configuration;
|
|
using HaDbMigration.Models;
|
|
using HaDbMigration.Services.Interfaces;
|
|
using Microsoft.Extensions.Logging;
|
|
using Npgsql;
|
|
using NpgsqlTypes;
|
|
|
|
namespace HaDbMigration.Services;
|
|
|
|
public sealed class PostgresWriterService : IPostgresWriterService
|
|
{
|
|
private readonly MigrationOptions _options;
|
|
private readonly ILogger<PostgresWriterService> _logger;
|
|
|
|
public PostgresWriterService(MigrationOptions options, ILogger<PostgresWriterService> logger)
|
|
{
|
|
_options = options;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task WriteTableAsync(
|
|
TableDescriptor table,
|
|
ChannelReader<IReadOnlyList<object?[]>> reader,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (_options.DryRun)
|
|
{
|
|
_logger.LogInformation("[DRY RUN] Skipping write for table {Table}", table.TableName);
|
|
await DrainChannelAsync(reader, table.TableName, cancellationToken);
|
|
return;
|
|
}
|
|
|
|
await using var connection = new NpgsqlConnection(_options.PostgresConnectionString);
|
|
await connection.OpenAsync(cancellationToken);
|
|
|
|
var totalRows = 0L;
|
|
|
|
await foreach (var batch in reader.ReadAllAsync(cancellationToken))
|
|
{
|
|
await WriteBatchWithCopyAsync(connection, table, batch, cancellationToken);
|
|
totalRows += batch.Count;
|
|
|
|
_logger.LogDebug("Wrote {Count} rows to {Table}", totalRows, table.TableName);
|
|
}
|
|
|
|
_logger.LogInformation("Finished writing {Count} rows to {Table}", totalRows, table.TableName);
|
|
}
|
|
|
|
public async Task<long> GetRowCountAsync(string tableName, CancellationToken cancellationToken)
|
|
{
|
|
await using var connection = new NpgsqlConnection(_options.PostgresConnectionString);
|
|
await connection.OpenAsync(cancellationToken);
|
|
|
|
await using var command = connection.CreateCommand();
|
|
command.CommandText = $"SELECT COUNT(*) FROM \"{tableName}\"";
|
|
|
|
var result = await command.ExecuteScalarAsync(cancellationToken);
|
|
return Convert.ToInt64(result);
|
|
}
|
|
|
|
private async Task WriteBatchWithCopyAsync(
|
|
NpgsqlConnection connection,
|
|
TableDescriptor table,
|
|
IReadOnlyList<object?[]> batch,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var columnNames = string.Join(", ", table.Columns.Select(c => $"\"{c.PostgresName}\""));
|
|
var copyCommand = $"COPY \"{table.TableName}\" ({columnNames}) FROM STDIN (FORMAT BINARY)";
|
|
|
|
await using var writer = await connection.BeginBinaryImportAsync(copyCommand, cancellationToken);
|
|
|
|
foreach (var row in batch)
|
|
{
|
|
await writer.StartRowAsync(cancellationToken);
|
|
|
|
for (var i = 0; i < table.Columns.Count; i++)
|
|
{
|
|
var column = table.Columns[i];
|
|
var value = row[i];
|
|
|
|
if (value is null)
|
|
{
|
|
await writer.WriteNullAsync(cancellationToken);
|
|
continue;
|
|
}
|
|
|
|
var converted = ConvertValue(value, column);
|
|
|
|
if (converted is null)
|
|
{
|
|
await writer.WriteNullAsync(cancellationToken);
|
|
}
|
|
else
|
|
{
|
|
await writer.WriteAsync(converted, column.NpgsqlType, cancellationToken);
|
|
}
|
|
}
|
|
}
|
|
|
|
await writer.CompleteAsync(cancellationToken);
|
|
}
|
|
|
|
private static object? ConvertValue(object value, ColumnDescriptor column)
|
|
{
|
|
if (column.IsBooleanConversion)
|
|
{
|
|
return Convert.ToInt64(value) != 0;
|
|
}
|
|
|
|
return column.NpgsqlType switch
|
|
{
|
|
NpgsqlDbType.Bigint => Convert.ToInt64(value),
|
|
NpgsqlDbType.Integer => Convert.ToInt32(value),
|
|
NpgsqlDbType.Smallint => Convert.ToInt16(value),
|
|
NpgsqlDbType.Double => Convert.ToDouble(value),
|
|
NpgsqlDbType.Boolean => Convert.ToBoolean(value),
|
|
NpgsqlDbType.Text or NpgsqlDbType.Varchar => value.ToString(),
|
|
NpgsqlDbType.Char => ConvertCharValue(value),
|
|
NpgsqlDbType.Bytea => value as byte[],
|
|
NpgsqlDbType.TimestampTz => ConvertToTimestampTz(value),
|
|
_ => value,
|
|
};
|
|
}
|
|
|
|
private static string? ConvertCharValue(object value)
|
|
{
|
|
var str = value.ToString();
|
|
return string.IsNullOrEmpty(str) ? null : str;
|
|
}
|
|
|
|
private static DateTime? ConvertToTimestampTz(object value)
|
|
{
|
|
if (value is string str)
|
|
{
|
|
return DateTime.TryParse(str, out var parsed)
|
|
? DateTime.SpecifyKind(parsed, DateTimeKind.Utc)
|
|
: null;
|
|
}
|
|
|
|
if (value is DateTime dt)
|
|
{
|
|
return DateTime.SpecifyKind(dt, DateTimeKind.Utc);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private async Task DrainChannelAsync(
|
|
ChannelReader<IReadOnlyList<object?[]>> reader,
|
|
string tableName,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var totalRows = 0L;
|
|
|
|
await foreach (var batch in reader.ReadAllAsync(cancellationToken))
|
|
{
|
|
totalRows += batch.Count;
|
|
}
|
|
|
|
_logger.LogInformation("[DRY RUN] Would write {Count} rows to {Table}", totalRows, tableName);
|
|
}
|
|
}
|