Added migration tool

This commit is contained in:
Marius
2026-03-12 09:47:49 +02:00
parent 27648ae57c
commit b262d10ea4
35 changed files with 2579 additions and 2 deletions
@@ -0,0 +1,6 @@
namespace HaDbMigration.Services.Interfaces;
public interface IMigrationOrchestrator
{
Task RunAsync(CancellationToken cancellationToken);
}
@@ -0,0 +1,14 @@
using System.Threading.Channels;
using HaDbMigration.Models;
namespace HaDbMigration.Services.Interfaces;
public interface IPostgresWriterService
{
Task WriteTableAsync(
TableDescriptor table,
ChannelReader<IReadOnlyList<object?[]>> reader,
CancellationToken cancellationToken);
Task<long> GetRowCountAsync(string tableName, CancellationToken cancellationToken);
}
@@ -0,0 +1,18 @@
using HaDbMigration.Models;
namespace HaDbMigration.Services.Interfaces;
public interface ISchemaService
{
Task<bool> ValidateTablesExistAsync(
IReadOnlyList<TableDescriptor> tables,
CancellationToken cancellationToken);
Task TruncateTablesAsync(
IReadOnlyList<TableDescriptor> tables,
CancellationToken cancellationToken);
Task ResetSequencesAsync(
IReadOnlyList<TableDescriptor> tables,
CancellationToken cancellationToken);
}
@@ -0,0 +1,14 @@
using System.Threading.Channels;
using HaDbMigration.Models;
namespace HaDbMigration.Services.Interfaces;
public interface ISqliteReaderService
{
Task ReadTableAsync(
TableDescriptor table,
ChannelWriter<IReadOnlyList<object?[]>> writer,
CancellationToken cancellationToken);
Task<long> GetRowCountAsync(string tableName, CancellationToken cancellationToken);
}
@@ -0,0 +1,16 @@
using HaDbMigration.Models;
namespace HaDbMigration.Services.Interfaces;
public sealed record TableValidationResult(
string TableName,
long SourceRowCount,
long TargetRowCount,
bool IsMatch);
public interface IValidationService
{
Task<IReadOnlyList<TableValidationResult>> ValidateRowCountsAsync(
IReadOnlyList<TableDescriptor> tables,
CancellationToken cancellationToken);
}
@@ -0,0 +1,189 @@
using System.Diagnostics;
using System.Threading.Channels;
using HaDbMigration.Configuration;
using HaDbMigration.Models;
using HaDbMigration.Services.Interfaces;
using Microsoft.Extensions.Logging;
namespace HaDbMigration.Services;
public sealed class MigrationOrchestrator : IMigrationOrchestrator
{
private readonly MigrationOptions _options;
private readonly ISqliteReaderService _readerService;
private readonly IPostgresWriterService _writerService;
private readonly ISchemaService _schemaService;
private readonly IValidationService _validationService;
private readonly ILogger<MigrationOrchestrator> _logger;
private static readonly IReadOnlyList<IReadOnlyList<TableDescriptor>> MigrationGroups =
[
// Group 1: independent leaf tables (no FKs referencing other data tables)
[
TableDescriptors.EventTypes,
TableDescriptors.EventData,
TableDescriptors.StatesMeta,
TableDescriptors.StateAttributes,
TableDescriptors.StatisticsMeta,
TableDescriptors.StatisticsRuns,
TableDescriptors.SchemaChanges,
TableDescriptors.MigrationChanges,
],
// Group 2: tables with FKs to group 1
[
TableDescriptors.Events,
TableDescriptors.States,
TableDescriptors.Statistics,
TableDescriptors.StatisticsShortTerm,
TableDescriptors.RecorderRuns,
],
];
public MigrationOrchestrator(
MigrationOptions options,
ISqliteReaderService readerService,
IPostgresWriterService writerService,
ISchemaService schemaService,
IValidationService validationService,
ILogger<MigrationOrchestrator> logger)
{
_options = options;
_readerService = readerService;
_writerService = writerService;
_schemaService = schemaService;
_validationService = validationService;
_logger = logger;
}
public async Task RunAsync(CancellationToken cancellationToken)
{
var stopwatch = Stopwatch.StartNew();
_logger.LogInformation("=== Home Assistant SQLite to PostgreSQL Migration ===");
_logger.LogInformation("Source: {SqlitePath}", _options.SqlitePath);
_logger.LogInformation("Batch size: {BatchSize}", _options.BatchSize);
if (_options.DryRun)
{
_logger.LogInformation("Mode: DRY RUN (no data will be written)");
}
var allTables = TableDescriptors.GetMigrationOrder();
_logger.LogInformation("Validating PostgreSQL schema...");
var tablesExist = await _schemaService.ValidateTablesExistAsync(allTables, cancellationToken);
if (!tablesExist)
{
_logger.LogError(
"One or more required tables are missing. "
+ "Start Home Assistant pointing to the PostgreSQL database first to create the schema.");
return;
}
_logger.LogInformation("All required tables exist in PostgreSQL");
if (_options.Truncate && !_options.DryRun)
{
_logger.LogInformation("Truncating target tables...");
await _schemaService.TruncateTablesAsync(allTables, cancellationToken);
}
foreach (var group in MigrationGroups)
{
await MigrateGroupInParallelAsync(group, cancellationToken);
}
if (!_options.DryRun)
{
_logger.LogInformation("Resetting PostgreSQL sequences...");
await _schemaService.ResetSequencesAsync(allTables, cancellationToken);
}
_logger.LogInformation("Validating migration results...");
var results = await _validationService.ValidateRowCountsAsync(allTables, cancellationToken);
LogValidationResults(results);
stopwatch.Stop();
_logger.LogInformation(
"Migration completed in {Elapsed:F1} seconds",
stopwatch.Elapsed.TotalSeconds);
}
private async Task MigrateGroupInParallelAsync(
IReadOnlyList<TableDescriptor> group,
CancellationToken cancellationToken)
{
_logger.LogInformation(
"Migrating table group: {Tables}",
string.Join(", ", group.Select(t => t.TableName)));
var tasks = group.Select(table => MigrateTableAsync(table, cancellationToken)).ToArray();
await Task.WhenAll(tasks);
}
private async Task MigrateTableAsync(TableDescriptor table, CancellationToken cancellationToken)
{
var tableStopwatch = Stopwatch.StartNew();
var channel = Channel.CreateBounded<IReadOnlyList<object?[]>>(
new BoundedChannelOptions(capacity: 4)
{
FullMode = BoundedChannelFullMode.Wait,
SingleWriter = true,
SingleReader = true,
});
var readerTask = Task.Run(
() => _readerService.ReadTableAsync(table, channel.Writer, cancellationToken),
cancellationToken);
var writerTask = Task.Run(
() => _writerService.WriteTableAsync(table, channel.Reader, cancellationToken),
cancellationToken);
await Task.WhenAll(readerTask, writerTask);
tableStopwatch.Stop();
_logger.LogInformation(
"Table {Table} migrated in {Elapsed:F1}s",
table.TableName,
tableStopwatch.Elapsed.TotalSeconds);
}
private void LogValidationResults(IReadOnlyList<TableValidationResult> results)
{
_logger.LogInformation("=== Validation Results ===");
var allMatch = true;
foreach (var result in results)
{
if (result.IsMatch)
{
_logger.LogInformation(
" {Table}: {Count} rows - OK",
result.TableName,
result.SourceRowCount);
}
else
{
_logger.LogWarning(
" {Table}: Source={Source}, Target={Target} - MISMATCH",
result.TableName,
result.SourceRowCount,
result.TargetRowCount);
allMatch = false;
}
}
if (allMatch)
{
_logger.LogInformation("All tables validated successfully");
}
else
{
_logger.LogWarning("Some tables have row count mismatches - review the results above");
}
}
}
@@ -0,0 +1,163 @@
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);
}
}
+127
View File
@@ -0,0 +1,127 @@
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<SchemaService> _logger;
public SchemaService(MigrationOptions options, ILogger<SchemaService> logger)
{
_options = options;
_logger = logger;
}
public async Task<bool> ValidateTablesExistAsync(
IReadOnlyList<TableDescriptor> 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<TableDescriptor> 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<TableDescriptor> 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);
}
}
}
@@ -0,0 +1,90 @@
using System.Threading.Channels;
using HaDbMigration.Configuration;
using HaDbMigration.Models;
using HaDbMigration.Services.Interfaces;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Logging;
namespace HaDbMigration.Services;
public sealed class SqliteReaderService : ISqliteReaderService
{
private readonly MigrationOptions _options;
private readonly ILogger<SqliteReaderService> _logger;
private readonly string _connectionString;
public SqliteReaderService(MigrationOptions options, ILogger<SqliteReaderService> logger)
{
_options = options;
_logger = logger;
_connectionString = new SqliteConnectionStringBuilder
{
DataSource = _options.SqlitePath,
Mode = SqliteOpenMode.ReadOnly,
}.ToString();
}
public async Task ReadTableAsync(
TableDescriptor table,
ChannelWriter<IReadOnlyList<object?[]>> writer,
CancellationToken cancellationToken)
{
var columnNames = string.Join(", ", table.Columns.Select(c => $"\"{c.SqliteName}\""));
var sql = $"SELECT {columnNames} FROM \"{table.TableName}\"";
_logger.LogInformation("Reading table {Table} from SQLite", table.TableName);
await using var connection = new SqliteConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
await using var command = connection.CreateCommand();
command.CommandText = sql;
await using var reader = await command.ExecuteReaderAsync(cancellationToken);
var batch = new List<object?[]>(_options.BatchSize);
var totalRows = 0L;
while (await reader.ReadAsync(cancellationToken))
{
var row = new object?[table.Columns.Count];
for (var i = 0; i < table.Columns.Count; i++)
{
row[i] = reader.IsDBNull(i) ? null : reader.GetValue(i);
}
batch.Add(row);
if (batch.Count >= _options.BatchSize)
{
totalRows += batch.Count;
await writer.WriteAsync(batch, cancellationToken);
batch = new List<object?[]>(_options.BatchSize);
_logger.LogDebug("Read {Count} rows from {Table}", totalRows, table.TableName);
}
}
if (batch.Count > 0)
{
totalRows += batch.Count;
await writer.WriteAsync(batch, cancellationToken);
}
writer.Complete();
_logger.LogInformation("Finished reading {Count} rows from {Table}", totalRows, table.TableName);
}
public async Task<long> GetRowCountAsync(string tableName, CancellationToken cancellationToken)
{
await using var connection = new SqliteConnection(_connectionString);
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);
}
}
@@ -0,0 +1,67 @@
using HaDbMigration.Configuration;
using HaDbMigration.Models;
using HaDbMigration.Services.Interfaces;
using Microsoft.Extensions.Logging;
namespace HaDbMigration.Services;
public sealed class ValidationService : IValidationService
{
private readonly ISqliteReaderService _sqliteReader;
private readonly IPostgresWriterService _postgresWriter;
private readonly MigrationOptions _options;
private readonly ILogger<ValidationService> _logger;
public ValidationService(
ISqliteReaderService sqliteReader,
IPostgresWriterService postgresWriter,
MigrationOptions options,
ILogger<ValidationService> logger)
{
_sqliteReader = sqliteReader;
_postgresWriter = postgresWriter;
_options = options;
_logger = logger;
}
public async Task<IReadOnlyList<TableValidationResult>> ValidateRowCountsAsync(
IReadOnlyList<TableDescriptor> tables,
CancellationToken cancellationToken)
{
var tasks = tables.Select(table => ValidateTableAsync(table, cancellationToken));
var results = await Task.WhenAll(tasks);
return results;
}
private async Task<TableValidationResult> ValidateTableAsync(
TableDescriptor table,
CancellationToken cancellationToken)
{
var sourceCountTask = _sqliteReader.GetRowCountAsync(table.TableName, cancellationToken);
long targetCount;
if (_options.DryRun)
{
targetCount = 0;
}
else
{
targetCount = await _postgresWriter.GetRowCountAsync(table.TableName, cancellationToken);
}
var sourceCount = await sourceCountTask;
var isMatch = _options.DryRun || sourceCount == targetCount;
_logger.LogDebug(
"Validation for {Table}: source={Source}, target={Target}, match={Match}",
table.TableName,
sourceCount,
targetCount,
isMatch);
return new TableValidationResult(table.TableName, sourceCount, targetCount, isMatch);
}
}