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,31 @@
namespace HaDbMigration.Configuration;
public sealed class MigrationOptions
{
public required string SqlitePath { get; init; }
public required string PostgresConnectionString { get; init; }
public int BatchSize { get; init; } = 10_000;
public bool Truncate { get; init; }
public bool DryRun { get; init; }
public void Validate()
{
if (!File.Exists(SqlitePath))
{
throw new FileNotFoundException(
$"SQLite database file not found: {SqlitePath}");
}
if (string.IsNullOrWhiteSpace(PostgresConnectionString))
{
throw new ArgumentException(
"PostgreSQL connection string is required.", nameof(PostgresConnectionString));
}
if (BatchSize < 100)
{
throw new ArgumentOutOfRangeException(
nameof(BatchSize), "Batch size must be at least 100.");
}
}
}
+21
View File
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>HaDbMigration</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.0-preview.2.25163.8" />
<PackageReference Include="Npgsql" Version="9.0.3" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.0-preview.2.25163.2" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta5.25306.1" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
</ItemGroup>
</Project>
+8
View File
@@ -0,0 +1,8 @@
namespace HaDbMigration.Models;
public sealed record EventDataEntity
{
public long DataId { get; init; }
public long? Hash { get; init; }
public string? SharedData { get; init; }
}
+20
View File
@@ -0,0 +1,20 @@
namespace HaDbMigration.Models;
public sealed record EventEntity
{
public long EventId { get; init; }
public string? EventType { get; init; }
public string? EventData { get; init; }
public string? Origin { get; init; }
public short? OriginIdx { get; init; }
public DateTime? TimeFired { get; init; }
public double? TimeFiredTs { get; init; }
public string? ContextId { get; init; }
public string? ContextUserId { get; init; }
public string? ContextParentId { get; init; }
public long? DataId { get; init; }
public byte[]? ContextIdBin { get; init; }
public byte[]? ContextUserIdBin { get; init; }
public byte[]? ContextParentIdBin { get; init; }
public long? EventTypeId { get; init; }
}
+7
View File
@@ -0,0 +1,7 @@
namespace HaDbMigration.Models;
public sealed record EventTypeEntity
{
public long EventTypeId { get; init; }
public string? EventType { get; init; }
}
@@ -0,0 +1,7 @@
namespace HaDbMigration.Models;
public sealed record MigrationChangeEntity
{
public string MigrationId { get; init; } = string.Empty;
public short Version { get; init; }
}
+10
View File
@@ -0,0 +1,10 @@
namespace HaDbMigration.Models;
public sealed record RecorderRunEntity
{
public long RunId { get; init; }
public DateTime Start { get; init; }
public DateTime? End { get; init; }
public long ClosedIncorrect { get; init; }
public DateTime Created { get; init; }
}
@@ -0,0 +1,8 @@
namespace HaDbMigration.Models;
public sealed record SchemaChangeEntity
{
public long ChangeId { get; init; }
public int? SchemaVersion { get; init; }
public DateTime Changed { get; init; }
}
@@ -0,0 +1,8 @@
namespace HaDbMigration.Models;
public sealed record StateAttributeEntity
{
public long AttributesId { get; init; }
public long? Hash { get; init; }
public string? SharedAttrs { get; init; }
}
+25
View File
@@ -0,0 +1,25 @@
namespace HaDbMigration.Models;
public sealed record StateEntity
{
public long StateId { get; init; }
public string? EntityId { get; init; }
public string? State { get; init; }
public string? Attributes { get; init; }
public short? EventId { get; init; }
public DateTime? LastChanged { get; init; }
public double? LastChangedTs { get; init; }
public double? LastReportedTs { get; init; }
public DateTime? LastUpdated { get; init; }
public double? LastUpdatedTs { get; init; }
public long? OldStateId { get; init; }
public long? AttributesId { get; init; }
public string? ContextId { get; init; }
public string? ContextUserId { get; init; }
public string? ContextParentId { get; init; }
public short? OriginIdx { get; init; }
public byte[]? ContextIdBin { get; init; }
public byte[]? ContextUserIdBin { get; init; }
public byte[]? ContextParentIdBin { get; init; }
public long? MetadataId { get; init; }
}
+7
View File
@@ -0,0 +1,7 @@
namespace HaDbMigration.Models;
public sealed record StatesMetaEntity
{
public long MetadataId { get; init; }
public string? EntityId { get; init; }
}
+19
View File
@@ -0,0 +1,19 @@
namespace HaDbMigration.Models;
public sealed record StatisticsEntity
{
public long Id { get; init; }
public DateTime? Created { get; init; }
public double? CreatedTs { get; init; }
public long? MetadataId { get; init; }
public DateTime? Start { get; init; }
public double? StartTs { get; init; }
public double? Mean { get; init; }
public double? MeanWeight { get; init; }
public double? Min { get; init; }
public double? Max { get; init; }
public DateTime? LastReset { get; init; }
public double? LastResetTs { get; init; }
public double? State { get; init; }
public double? Sum { get; init; }
}
@@ -0,0 +1,14 @@
namespace HaDbMigration.Models;
public sealed record StatisticsMetaEntity
{
public long Id { get; init; }
public string? StatisticId { get; init; }
public string? Source { get; init; }
public string? UnitOfMeasurement { get; init; }
public string? UnitClass { get; init; }
public long? HasMean { get; init; }
public long? HasSum { get; init; }
public string? Name { get; init; }
public short MeanType { get; init; }
}
@@ -0,0 +1,7 @@
namespace HaDbMigration.Models;
public sealed record StatisticsRunEntity
{
public long RunId { get; init; }
public DateTime Start { get; init; }
}
@@ -0,0 +1,19 @@
namespace HaDbMigration.Models;
public sealed record StatisticsShortTermEntity
{
public long Id { get; init; }
public DateTime? Created { get; init; }
public double? CreatedTs { get; init; }
public long? MetadataId { get; init; }
public DateTime? Start { get; init; }
public double? StartTs { get; init; }
public double? Mean { get; init; }
public double? MeanWeight { get; init; }
public double? Min { get; init; }
public double? Max { get; init; }
public DateTime? LastReset { get; init; }
public double? LastResetTs { get; init; }
public double? State { get; init; }
public double? Sum { get; init; }
}
+206
View File
@@ -0,0 +1,206 @@
using NpgsqlTypes;
namespace HaDbMigration.Models;
public sealed record ColumnDescriptor(
string SqliteName,
string PostgresName,
NpgsqlDbType NpgsqlType,
bool IsPrimaryKey = false,
bool IsBooleanConversion = false);
public sealed record TableDescriptor(
string TableName,
IReadOnlyList<ColumnDescriptor> Columns,
string? SequenceColumn = null);
public static class TableDescriptors
{
public static readonly TableDescriptor Events = new(
"events",
[
new("event_id", "event_id", NpgsqlDbType.Bigint, IsPrimaryKey: true),
new("event_type", "event_type", NpgsqlDbType.Char),
new("event_data", "event_data", NpgsqlDbType.Char),
new("origin", "origin", NpgsqlDbType.Char),
new("origin_idx", "origin_idx", NpgsqlDbType.Smallint),
new("time_fired", "time_fired", NpgsqlDbType.TimestampTz),
new("time_fired_ts", "time_fired_ts", NpgsqlDbType.Double),
new("context_id", "context_id", NpgsqlDbType.Char),
new("context_user_id", "context_user_id", NpgsqlDbType.Char),
new("context_parent_id", "context_parent_id", NpgsqlDbType.Char),
new("data_id", "data_id", NpgsqlDbType.Bigint),
new("context_id_bin", "context_id_bin", NpgsqlDbType.Bytea),
new("context_user_id_bin", "context_user_id_bin", NpgsqlDbType.Bytea),
new("context_parent_id_bin", "context_parent_id_bin", NpgsqlDbType.Bytea),
new("event_type_id", "event_type_id", NpgsqlDbType.Bigint),
],
SequenceColumn: "event_id");
public static readonly TableDescriptor EventData = new(
"event_data",
[
new("data_id", "data_id", NpgsqlDbType.Bigint, IsPrimaryKey: true),
new("hash", "hash", NpgsqlDbType.Bigint),
new("shared_data", "shared_data", NpgsqlDbType.Text),
],
SequenceColumn: "data_id");
public static readonly TableDescriptor EventTypes = new(
"event_types",
[
new("event_type_id", "event_type_id", NpgsqlDbType.Bigint, IsPrimaryKey: true),
new("event_type", "event_type", NpgsqlDbType.Varchar),
],
SequenceColumn: "event_type_id");
public static readonly TableDescriptor States = new(
"states",
[
new("state_id", "state_id", NpgsqlDbType.Bigint, IsPrimaryKey: true),
new("entity_id", "entity_id", NpgsqlDbType.Char),
new("state", "state", NpgsqlDbType.Varchar),
new("attributes", "attributes", NpgsqlDbType.Char),
new("event_id", "event_id", NpgsqlDbType.Smallint),
new("last_changed", "last_changed", NpgsqlDbType.TimestampTz),
new("last_changed_ts", "last_changed_ts", NpgsqlDbType.Double),
new("last_reported_ts", "last_reported_ts", NpgsqlDbType.Double),
new("last_updated", "last_updated", NpgsqlDbType.TimestampTz),
new("last_updated_ts", "last_updated_ts", NpgsqlDbType.Double),
new("old_state_id", "old_state_id", NpgsqlDbType.Bigint),
new("attributes_id", "attributes_id", NpgsqlDbType.Bigint),
new("context_id", "context_id", NpgsqlDbType.Char),
new("context_user_id", "context_user_id", NpgsqlDbType.Char),
new("context_parent_id", "context_parent_id", NpgsqlDbType.Char),
new("origin_idx", "origin_idx", NpgsqlDbType.Smallint),
new("context_id_bin", "context_id_bin", NpgsqlDbType.Bytea),
new("context_user_id_bin", "context_user_id_bin", NpgsqlDbType.Bytea),
new("context_parent_id_bin", "context_parent_id_bin", NpgsqlDbType.Bytea),
new("metadata_id", "metadata_id", NpgsqlDbType.Bigint),
],
SequenceColumn: "state_id");
public static readonly TableDescriptor StateAttributes = new(
"state_attributes",
[
new("attributes_id", "attributes_id", NpgsqlDbType.Bigint, IsPrimaryKey: true),
new("hash", "hash", NpgsqlDbType.Bigint),
new("shared_attrs", "shared_attrs", NpgsqlDbType.Text),
],
SequenceColumn: "attributes_id");
public static readonly TableDescriptor StatesMeta = new(
"states_meta",
[
new("metadata_id", "metadata_id", NpgsqlDbType.Bigint, IsPrimaryKey: true),
new("entity_id", "entity_id", NpgsqlDbType.Varchar),
],
SequenceColumn: "metadata_id");
public static readonly TableDescriptor RecorderRuns = new(
"recorder_runs",
[
new("run_id", "run_id", NpgsqlDbType.Bigint, IsPrimaryKey: true),
new("start", "start", NpgsqlDbType.TimestampTz),
new("end", "end", NpgsqlDbType.TimestampTz),
new("closed_incorrect", "closed_incorrect", NpgsqlDbType.Boolean, IsBooleanConversion: true),
new("created", "created", NpgsqlDbType.TimestampTz),
],
SequenceColumn: "run_id");
public static readonly TableDescriptor SchemaChanges = new(
"schema_changes",
[
new("change_id", "change_id", NpgsqlDbType.Bigint, IsPrimaryKey: true),
new("schema_version", "schema_version", NpgsqlDbType.Integer),
new("changed", "changed", NpgsqlDbType.TimestampTz),
],
SequenceColumn: "change_id");
public static readonly TableDescriptor MigrationChanges = new(
"migration_changes",
[
new("migration_id", "migration_id", NpgsqlDbType.Varchar),
new("version", "version", NpgsqlDbType.Smallint),
]);
public static readonly TableDescriptor Statistics = new(
"statistics",
[
new("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true),
new("created", "created", NpgsqlDbType.TimestampTz),
new("created_ts", "created_ts", NpgsqlDbType.Double),
new("metadata_id", "metadata_id", NpgsqlDbType.Bigint),
new("start", "start", NpgsqlDbType.TimestampTz),
new("start_ts", "start_ts", NpgsqlDbType.Double),
new("mean", "mean", NpgsqlDbType.Double),
new("mean_weight", "mean_weight", NpgsqlDbType.Double),
new("min", "min", NpgsqlDbType.Double),
new("max", "max", NpgsqlDbType.Double),
new("last_reset", "last_reset", NpgsqlDbType.TimestampTz),
new("last_reset_ts", "last_reset_ts", NpgsqlDbType.Double),
new("state", "state", NpgsqlDbType.Double),
new("sum", "sum", NpgsqlDbType.Double),
],
SequenceColumn: "id");
public static readonly TableDescriptor StatisticsMeta = new(
"statistics_meta",
[
new("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true),
new("statistic_id", "statistic_id", NpgsqlDbType.Varchar),
new("source", "source", NpgsqlDbType.Varchar),
new("unit_of_measurement", "unit_of_measurement", NpgsqlDbType.Varchar),
new("unit_class", "unit_class", NpgsqlDbType.Varchar),
new("has_mean", "has_mean", NpgsqlDbType.Boolean, IsBooleanConversion: true),
new("has_sum", "has_sum", NpgsqlDbType.Boolean, IsBooleanConversion: true),
new("name", "name", NpgsqlDbType.Varchar),
new("mean_type", "mean_type", NpgsqlDbType.Smallint),
],
SequenceColumn: "id");
public static readonly TableDescriptor StatisticsShortTerm = new(
"statistics_short_term",
[
new("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true),
new("created", "created", NpgsqlDbType.TimestampTz),
new("created_ts", "created_ts", NpgsqlDbType.Double),
new("metadata_id", "metadata_id", NpgsqlDbType.Bigint),
new("start", "start", NpgsqlDbType.TimestampTz),
new("start_ts", "start_ts", NpgsqlDbType.Double),
new("mean", "mean", NpgsqlDbType.Double),
new("mean_weight", "mean_weight", NpgsqlDbType.Double),
new("min", "min", NpgsqlDbType.Double),
new("max", "max", NpgsqlDbType.Double),
new("last_reset", "last_reset", NpgsqlDbType.TimestampTz),
new("last_reset_ts", "last_reset_ts", NpgsqlDbType.Double),
new("state", "state", NpgsqlDbType.Double),
new("sum", "sum", NpgsqlDbType.Double),
],
SequenceColumn: "id");
public static readonly TableDescriptor StatisticsRuns = new(
"statistics_runs",
[
new("run_id", "run_id", NpgsqlDbType.Bigint, IsPrimaryKey: true),
new("start", "start", NpgsqlDbType.TimestampTz),
],
SequenceColumn: "run_id");
public static IReadOnlyList<TableDescriptor> GetMigrationOrder() =>
[
EventTypes,
EventData,
StatesMeta,
StateAttributes,
StatisticsMeta,
Events,
States,
Statistics,
StatisticsShortTerm,
StatisticsRuns,
RecorderRuns,
SchemaChanges,
MigrationChanges,
];
}
+102
View File
@@ -0,0 +1,102 @@
using System.CommandLine;
using HaDbMigration.Configuration;
using HaDbMigration.Services;
using HaDbMigration.Services.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
var sqliteOption = new Option<string>("--sqlite")
{
Description = "Path to the Home Assistant SQLite database file (home-assistant_v2.db)",
Required = true,
};
var pgConnectionOption = new Option<string>("--pg-connection")
{
Description = "PostgreSQL connection string",
Required = true,
};
var batchSizeOption = new Option<int>("--batch-size")
{
Description = "Number of rows per batch (minimum 100)",
DefaultValueFactory = _ => 10_000,
};
var truncateOption = new Option<bool>("--truncate")
{
Description = "Truncate PostgreSQL tables before migration",
DefaultValueFactory = _ => false,
};
var dryRunOption = new Option<bool>("--dry-run")
{
Description = "Validate only, do not write data",
DefaultValueFactory = _ => false,
};
var rootCommand = new RootCommand("Home Assistant SQLite to PostgreSQL migration tool");
rootCommand.Options.Add(sqliteOption);
rootCommand.Options.Add(pgConnectionOption);
rootCommand.Options.Add(batchSizeOption);
rootCommand.Options.Add(truncateOption);
rootCommand.Options.Add(dryRunOption);
rootCommand.SetAction(async (parseResult, cancellationToken) =>
{
var sqlite = parseResult.GetValue(sqliteOption)!;
var pgConnection = parseResult.GetValue(pgConnectionOption)!;
var batchSize = parseResult.GetValue(batchSizeOption);
var truncate = parseResult.GetValue(truncateOption);
var dryRun = parseResult.GetValue(dryRunOption);
var options = new MigrationOptions
{
SqlitePath = sqlite,
PostgresConnectionString = pgConnection,
BatchSize = batchSize,
Truncate = truncate,
DryRun = dryRun,
};
options.Validate();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console(
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
try
{
var host = Host.CreateDefaultBuilder()
.UseSerilog()
.ConfigureServices(services =>
{
services.AddSingleton(options);
services.AddSingleton<ISqliteReaderService, SqliteReaderService>();
services.AddSingleton<IPostgresWriterService, PostgresWriterService>();
services.AddSingleton<ISchemaService, SchemaService>();
services.AddSingleton<IValidationService, ValidationService>();
services.AddSingleton<IMigrationOrchestrator, MigrationOrchestrator>();
})
.Build();
var orchestrator = host.Services.GetRequiredService<IMigrationOrchestrator>();
await orchestrator.RunAsync(cancellationToken);
}
catch (Exception ex)
{
Log.Fatal(ex, "Migration failed with an unhandled exception");
Environment.ExitCode = 1;
}
finally
{
await Log.CloseAndFlushAsync();
}
});
var result = rootCommand.Parse(args);
return await result.InvokeAsync();
@@ -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);
}
}