Remove HaDbMigration project and all related files

This commit is contained in:
Marius
2026-03-12 13:08:53 +02:00
parent b262d10ea4
commit 7dcdac6933
34 changed files with 0 additions and 2317 deletions
@@ -1,34 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HaDbMigration\HaDbMigration.csproj" />
</ItemGroup>
</Project>
@@ -1,200 +0,0 @@
using FluentAssertions;
using HaDbMigration.Configuration;
namespace HaDbMigration.Tests;
public sealed class MigrationOptionsTests
{
[Fact]
public void Validate_WithValidOptions_ShouldNotThrow()
{
// Arrange
var tempFile = Path.GetTempFileName();
try
{
var options = new MigrationOptions
{
SqlitePath = tempFile,
PostgresConnectionString = "Host=localhost;Database=test",
BatchSize = 10_000,
};
// Act
var act = () => options.Validate();
// Assert
act.Should().NotThrow();
}
finally
{
File.Delete(tempFile);
}
}
[Fact]
public void Validate_WithMissingSqliteFile_ShouldThrowFileNotFoundException()
{
// Arrange
var options = new MigrationOptions
{
SqlitePath = @"C:\nonexistent\path\db.sqlite",
PostgresConnectionString = "Host=localhost;Database=test",
};
// Act
var act = () => options.Validate();
// Assert
act.Should().Throw<FileNotFoundException>()
.WithMessage("*nonexistent*");
}
[Fact]
public void Validate_WithEmptyPostgresConnectionString_ShouldThrowArgumentException()
{
// Arrange
var tempFile = Path.GetTempFileName();
try
{
var options = new MigrationOptions
{
SqlitePath = tempFile,
PostgresConnectionString = "",
};
// Act
var act = () => options.Validate();
// Assert
act.Should().Throw<ArgumentException>()
.WithMessage("*connection string*");
}
finally
{
File.Delete(tempFile);
}
}
[Fact]
public void Validate_WithWhitespacePostgresConnectionString_ShouldThrowArgumentException()
{
// Arrange
var tempFile = Path.GetTempFileName();
try
{
var options = new MigrationOptions
{
SqlitePath = tempFile,
PostgresConnectionString = " ",
};
// Act
var act = () => options.Validate();
// Assert
act.Should().Throw<ArgumentException>();
}
finally
{
File.Delete(tempFile);
}
}
[Theory]
[InlineData(0)] // below minimum
[InlineData(50)] // below minimum
[InlineData(99)] // just below threshold
public void Validate_WithBatchSizeBelowMinimum_ShouldThrowArgumentOutOfRangeException(int batchSize)
{
// Arrange
var tempFile = Path.GetTempFileName();
try
{
var options = new MigrationOptions
{
SqlitePath = tempFile,
PostgresConnectionString = "Host=localhost;Database=test",
BatchSize = batchSize,
};
// Act
var act = () => options.Validate();
// Assert
act.Should().Throw<ArgumentOutOfRangeException>()
.WithMessage("*at least 100*");
}
finally
{
File.Delete(tempFile);
}
}
[Fact]
public void Validate_WithBatchSizeAtMinimum_ShouldNotThrow()
{
// Arrange
var tempFile = Path.GetTempFileName();
try
{
var options = new MigrationOptions
{
SqlitePath = tempFile,
PostgresConnectionString = "Host=localhost;Database=test",
BatchSize = 100,
};
// Act
var act = () => options.Validate();
// Assert
act.Should().NotThrow();
}
finally
{
File.Delete(tempFile);
}
}
[Fact]
public void DefaultBatchSize_ShouldBe10000()
{
// Arrange & Act
var options = new MigrationOptions
{
SqlitePath = "test.db",
PostgresConnectionString = "Host=localhost",
};
// Assert
options.BatchSize.Should().Be(10_000);
}
[Fact]
public void DefaultDryRun_ShouldBeFalse()
{
// Arrange & Act
var options = new MigrationOptions
{
SqlitePath = "test.db",
PostgresConnectionString = "Host=localhost",
};
// Assert
options.DryRun.Should().BeFalse();
}
[Fact]
public void DefaultTruncate_ShouldBeFalse()
{
// Arrange & Act
var options = new MigrationOptions
{
SqlitePath = "test.db",
PostgresConnectionString = "Host=localhost",
};
// Assert
options.Truncate.Should().BeFalse();
}
}
@@ -1,260 +0,0 @@
using System.Threading.Channels;
using FluentAssertions;
using HaDbMigration.Configuration;
using HaDbMigration.Models;
using HaDbMigration.Services;
using HaDbMigration.Services.Interfaces;
using Microsoft.Extensions.Logging;
using Moq;
namespace HaDbMigration.Tests;
public sealed class MigrationOrchestratorTests
{
private readonly Mock<ISqliteReaderService> _readerMock;
private readonly Mock<IPostgresWriterService> _writerMock;
private readonly Mock<ISchemaService> _schemaMock;
private readonly Mock<IValidationService> _validationMock;
private readonly Mock<ILogger<MigrationOrchestrator>> _loggerMock;
public MigrationOrchestratorTests()
{
_readerMock = new Mock<ISqliteReaderService>();
_writerMock = new Mock<IPostgresWriterService>();
_schemaMock = new Mock<ISchemaService>();
_validationMock = new Mock<IValidationService>();
_loggerMock = new Mock<ILogger<MigrationOrchestrator>>();
}
private MigrationOrchestrator CreateSut(
bool truncate = false,
bool dryRun = false)
{
var options = new MigrationOptions
{
SqlitePath = "test.db",
PostgresConnectionString = "Host=localhost",
Truncate = truncate,
DryRun = dryRun,
};
return new MigrationOrchestrator(
options,
_readerMock.Object,
_writerMock.Object,
_schemaMock.Object,
_validationMock.Object,
_loggerMock.Object);
}
private void SetupHappyPath()
{
_schemaMock
.Setup(x => x.ValidateTablesExistAsync(
It.IsAny<IReadOnlyList<TableDescriptor>>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
_readerMock
.Setup(x => x.ReadTableAsync(
It.IsAny<TableDescriptor>(),
It.IsAny<ChannelWriter<IReadOnlyList<object?[]>>>(),
It.IsAny<CancellationToken>()))
.Returns((TableDescriptor _, ChannelWriter<IReadOnlyList<object?[]>> writer, CancellationToken _) =>
{
writer.Complete();
return Task.CompletedTask;
});
_writerMock
.Setup(x => x.WriteTableAsync(
It.IsAny<TableDescriptor>(),
It.IsAny<ChannelReader<IReadOnlyList<object?[]>>>(),
It.IsAny<CancellationToken>()))
.Returns(async (TableDescriptor table, ChannelReader<IReadOnlyList<object?[]>> reader, CancellationToken ct) =>
{
await foreach (var batch in reader.ReadAllAsync(ct))
{
}
});
_schemaMock
.Setup(x => x.ResetSequencesAsync(
It.IsAny<IReadOnlyList<TableDescriptor>>(),
It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
_validationMock
.Setup(x => x.ValidateRowCountsAsync(
It.IsAny<IReadOnlyList<TableDescriptor>>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync([]);
}
[Fact]
public async Task RunAsync_WhenTablesDoNotExist_ShouldNotMigrateData()
{
// Arrange
_schemaMock
.Setup(x => x.ValidateTablesExistAsync(
It.IsAny<IReadOnlyList<TableDescriptor>>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(false);
var sut = CreateSut();
// Act
await sut.RunAsync(CancellationToken.None);
// Assert
_readerMock.Verify(
x => x.ReadTableAsync(
It.IsAny<TableDescriptor>(),
It.IsAny<ChannelWriter<IReadOnlyList<object?[]>>>(),
It.IsAny<CancellationToken>()),
Times.Never);
}
[Fact]
public async Task RunAsync_WithTruncateEnabled_ShouldTruncateTables()
{
// Arrange
SetupHappyPath();
var sut = CreateSut(truncate: true);
// Act
await sut.RunAsync(CancellationToken.None);
// Assert
_schemaMock.Verify(
x => x.TruncateTablesAsync(
It.IsAny<IReadOnlyList<TableDescriptor>>(),
It.IsAny<CancellationToken>()),
Times.Once);
}
[Fact]
public async Task RunAsync_WithTruncateDisabled_ShouldNotTruncateTables()
{
// Arrange
SetupHappyPath();
var sut = CreateSut(truncate: false);
// Act
await sut.RunAsync(CancellationToken.None);
// Assert
_schemaMock.Verify(
x => x.TruncateTablesAsync(
It.IsAny<IReadOnlyList<TableDescriptor>>(),
It.IsAny<CancellationToken>()),
Times.Never);
}
[Fact]
public async Task RunAsync_InDryRunMode_ShouldNotResetSequences()
{
// Arrange
SetupHappyPath();
var sut = CreateSut(dryRun: true);
// Act
await sut.RunAsync(CancellationToken.None);
// Assert
_schemaMock.Verify(
x => x.ResetSequencesAsync(
It.IsAny<IReadOnlyList<TableDescriptor>>(),
It.IsAny<CancellationToken>()),
Times.Never);
}
[Fact]
public async Task RunAsync_InDryRunMode_ShouldNotTruncateEvenIfFlagSet()
{
// Arrange
SetupHappyPath();
var sut = CreateSut(truncate: true, dryRun: true);
// Act
await sut.RunAsync(CancellationToken.None);
// Assert
_schemaMock.Verify(
x => x.TruncateTablesAsync(
It.IsAny<IReadOnlyList<TableDescriptor>>(),
It.IsAny<CancellationToken>()),
Times.Never);
}
[Fact]
public async Task RunAsync_AfterSuccessfulMigration_ShouldValidateRowCounts()
{
// Arrange
SetupHappyPath();
var sut = CreateSut();
// Act
await sut.RunAsync(CancellationToken.None);
// Assert
_validationMock.Verify(
x => x.ValidateRowCountsAsync(
It.IsAny<IReadOnlyList<TableDescriptor>>(),
It.IsAny<CancellationToken>()),
Times.Once);
}
[Fact]
public async Task RunAsync_AfterSuccessfulMigration_ShouldResetSequences()
{
// Arrange
SetupHappyPath();
var sut = CreateSut();
// Act
await sut.RunAsync(CancellationToken.None);
// Assert
_schemaMock.Verify(
x => x.ResetSequencesAsync(
It.IsAny<IReadOnlyList<TableDescriptor>>(),
It.IsAny<CancellationToken>()),
Times.Once);
}
[Fact]
public async Task RunAsync_ShouldValidateSchemaFirst()
{
// Arrange
SetupHappyPath();
var callOrder = new List<string>();
_schemaMock
.Setup(x => x.ValidateTablesExistAsync(
It.IsAny<IReadOnlyList<TableDescriptor>>(),
It.IsAny<CancellationToken>()))
.Callback(() => callOrder.Add("validate"))
.ReturnsAsync(true);
_readerMock
.Setup(x => x.ReadTableAsync(
It.IsAny<TableDescriptor>(),
It.IsAny<ChannelWriter<IReadOnlyList<object?[]>>>(),
It.IsAny<CancellationToken>()))
.Callback(() => callOrder.Add("read"))
.Returns((TableDescriptor _, ChannelWriter<IReadOnlyList<object?[]>> writer, CancellationToken _) =>
{
writer.Complete();
return Task.CompletedTask;
});
var sut = CreateSut();
// Act
await sut.RunAsync(CancellationToken.None);
// Assert
callOrder.First().Should().Be("validate");
}
}
@@ -1,189 +0,0 @@
using System.Reflection;
using FluentAssertions;
using HaDbMigration.Models;
using HaDbMigration.Services;
using NpgsqlTypes;
namespace HaDbMigration.Tests;
public sealed class PostgresWriterServiceTests
{
private const BindingFlags PrivateStatic = BindingFlags.NonPublic | BindingFlags.Static;
private static object? InvokeConvertValue(object value, ColumnDescriptor column)
{
return typeof(PostgresWriterService)
.GetMethod("ConvertValue", PrivateStatic)!
.Invoke(null, [value, column]);
}
[Theory]
[InlineData(0L, false)] // SQLite integer 0 -> PostgreSQL false
[InlineData(1L, true)] // SQLite integer 1 -> PostgreSQL true
[InlineData(42L, true)] // any non-zero -> true
public void ConvertValue_WithBooleanConversion_ShouldConvertIntToBool(
long input, bool expected)
{
// Arrange
var column = new ColumnDescriptor("test", "test", NpgsqlDbType.Boolean, IsBooleanConversion: true);
// Act
var result = InvokeConvertValue(input, column);
// Assert
result.Should().Be(expected);
}
[Fact]
public void ConvertValue_WithBigintColumn_ShouldConvertToLong()
{
// Arrange
var column = new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint);
// Act
var result = InvokeConvertValue(42, column);
// Assert
result.Should().Be(42L);
result.Should().BeOfType<long>();
}
[Fact]
public void ConvertValue_WithIntegerColumn_ShouldConvertToInt()
{
// Arrange
var column = new ColumnDescriptor("ver", "ver", NpgsqlDbType.Integer);
// Act
var result = InvokeConvertValue(42L, column);
// Assert
result.Should().Be(42);
result.Should().BeOfType<int>();
}
[Fact]
public void ConvertValue_WithSmallintColumn_ShouldConvertToShort()
{
// Arrange
var column = new ColumnDescriptor("idx", "idx", NpgsqlDbType.Smallint);
// Act
var result = InvokeConvertValue(5, column);
// Assert
result.Should().Be((short)5);
result.Should().BeOfType<short>();
}
[Fact]
public void ConvertValue_WithDoubleColumn_ShouldConvertToDouble()
{
// Arrange
var column = new ColumnDescriptor("ts", "ts", NpgsqlDbType.Double);
// Act
var result = InvokeConvertValue(1234567890.123, column);
// Assert
result.Should().BeOfType<double>();
((double)result!).Should().BeApproximately(1234567890.123, 0.001);
}
[Fact]
public void ConvertValue_WithTextColumn_ShouldConvertToString()
{
// Arrange
var column = new ColumnDescriptor("data", "data", NpgsqlDbType.Text);
// Act
var result = InvokeConvertValue("{\"key\": \"value\"}", column);
// Assert
result.Should().Be("{\"key\": \"value\"}");
}
[Fact]
public void ConvertValue_WithVarcharColumn_ShouldConvertToString()
{
// Arrange
var column = new ColumnDescriptor("name", "name", NpgsqlDbType.Varchar);
// Act
var result = InvokeConvertValue("test_entity", column);
// Assert
result.Should().Be("test_entity");
}
[Fact]
public void ConvertValue_WithCharColumnAndEmptyString_ShouldReturnNull()
{
// Arrange
var column = new ColumnDescriptor("legacy", "legacy", NpgsqlDbType.Char);
// Act
var result = InvokeConvertValue("", column);
// Assert
result.Should().BeNull();
}
[Fact]
public void ConvertValue_WithByteaColumn_ShouldReturnByteArray()
{
// Arrange
var column = new ColumnDescriptor("bin", "bin", NpgsqlDbType.Bytea);
var bytes = new byte[] { 0x01, 0x02, 0x03 };
// Act
var result = InvokeConvertValue(bytes, column);
// Assert
result.Should().BeOfType<byte[]>();
((byte[])result!).Should().Equal(0x01, 0x02, 0x03);
}
[Fact]
public void ConvertValue_WithTimestampTzAndStringDate_ShouldConvertToUtcDateTime()
{
// Arrange
var column = new ColumnDescriptor("ts", "ts", NpgsqlDbType.TimestampTz);
// Act
var result = InvokeConvertValue("2024-01-15 10:30:00", column);
// Assert
result.Should().NotBeNull();
result.Should().BeOfType<DateTime>();
((DateTime)result!).Kind.Should().Be(DateTimeKind.Utc);
}
[Fact]
public void ConvertValue_WithTimestampTzAndDateTime_ShouldEnsureUtcKind()
{
// Arrange
var column = new ColumnDescriptor("ts", "ts", NpgsqlDbType.TimestampTz);
var unspecified = new DateTime(2024, 1, 15, 10, 30, 0, DateTimeKind.Unspecified);
// Act
var result = InvokeConvertValue(unspecified, column);
// Assert
result.Should().NotBeNull();
((DateTime)result!).Kind.Should().Be(DateTimeKind.Utc);
}
[Fact]
public void ConvertValue_WithTimestampTzAndInvalidString_ShouldReturnNull()
{
// Arrange
var column = new ColumnDescriptor("ts", "ts", NpgsqlDbType.TimestampTz);
// Act
var result = InvokeConvertValue("not-a-date", column);
// Assert
result.Should().BeNull();
}
}
@@ -1,171 +0,0 @@
using FluentAssertions;
using HaDbMigration.Models;
using NpgsqlTypes;
namespace HaDbMigration.Tests;
public sealed class TableDescriptorsTests
{
[Fact]
public void GetMigrationOrder_ShouldReturn13Tables()
{
// Act
var tables = TableDescriptors.GetMigrationOrder();
// Assert
tables.Should().HaveCount(13);
}
[Fact]
public void GetMigrationOrder_ShouldHaveLeafTablesBeforeDependentTables()
{
// Arrange
var tables = TableDescriptors.GetMigrationOrder();
var tableNames = tables.Select(t => t.TableName).ToList();
// Assert - event_types before events
tableNames.IndexOf("event_types").Should().BeLessThan(tableNames.IndexOf("events"));
// Assert - event_data before events
tableNames.IndexOf("event_data").Should().BeLessThan(tableNames.IndexOf("events"));
// Assert - states_meta before states
tableNames.IndexOf("states_meta").Should().BeLessThan(tableNames.IndexOf("states"));
// Assert - state_attributes before states
tableNames.IndexOf("state_attributes").Should().BeLessThan(tableNames.IndexOf("states"));
// Assert - statistics_meta before statistics
tableNames.IndexOf("statistics_meta").Should().BeLessThan(tableNames.IndexOf("statistics"));
// Assert - statistics_meta before statistics_short_term
tableNames.IndexOf("statistics_meta").Should().BeLessThan(tableNames.IndexOf("statistics_short_term"));
}
[Fact]
public void Events_ShouldHaveCorrectColumns()
{
// Act
var table = TableDescriptors.Events;
// Assert
table.TableName.Should().Be("events");
table.SequenceColumn.Should().Be("event_id");
table.Columns.Should().HaveCount(15);
table.Columns[0].IsPrimaryKey.Should().BeTrue();
table.Columns[0].SqliteName.Should().Be("event_id");
}
[Fact]
public void StatisticsMeta_ShouldHaveBooleanConversionColumns()
{
// Act
var table = TableDescriptors.StatisticsMeta;
var hasMeanColumn = table.Columns.First(c => c.SqliteName == "has_mean");
var hasSumColumn = table.Columns.First(c => c.SqliteName == "has_sum");
// Assert
hasMeanColumn.IsBooleanConversion.Should().BeTrue();
hasMeanColumn.NpgsqlType.Should().Be(NpgsqlDbType.Boolean);
hasSumColumn.IsBooleanConversion.Should().BeTrue();
hasSumColumn.NpgsqlType.Should().Be(NpgsqlDbType.Boolean);
}
[Fact]
public void RecorderRuns_ShouldHaveBooleanConversionForClosedIncorrect()
{
// Act
var table = TableDescriptors.RecorderRuns;
var closedIncorrectColumn = table.Columns.First(c => c.SqliteName == "closed_incorrect");
// Assert
closedIncorrectColumn.IsBooleanConversion.Should().BeTrue();
closedIncorrectColumn.NpgsqlType.Should().Be(NpgsqlDbType.Boolean);
}
[Fact]
public void MigrationChanges_ShouldHaveNoSequenceColumn()
{
// Act
var table = TableDescriptors.MigrationChanges;
// Assert
table.SequenceColumn.Should().BeNull();
}
[Theory]
[InlineData("events", "event_id")]
[InlineData("event_data", "data_id")]
[InlineData("event_types", "event_type_id")]
[InlineData("states", "state_id")]
[InlineData("state_attributes", "attributes_id")]
[InlineData("states_meta", "metadata_id")]
[InlineData("recorder_runs", "run_id")]
[InlineData("schema_changes", "change_id")]
[InlineData("statistics", "id")]
[InlineData("statistics_meta", "id")]
[InlineData("statistics_short_term", "id")]
[InlineData("statistics_runs", "run_id")]
public void TablesWithSequences_ShouldHaveCorrectSequenceColumn(
string tableName, string expectedSequenceColumn)
{
// Act
var table = TableDescriptors.GetMigrationOrder().First(t => t.TableName == tableName);
// Assert
table.SequenceColumn.Should().Be(expectedSequenceColumn);
}
[Fact]
public void AllTables_ShouldHaveAtLeastOneColumn()
{
// Act
var tables = TableDescriptors.GetMigrationOrder();
// Assert
tables.Should().AllSatisfy(t => t.Columns.Should().NotBeEmpty());
}
[Fact]
public void AllTables_ShouldHaveUniqueNames()
{
// Act
var tables = TableDescriptors.GetMigrationOrder();
var names = tables.Select(t => t.TableName).ToList();
// Assert
names.Should().OnlyHaveUniqueItems();
}
[Fact]
public void States_ShouldHaveByteaColumnsForContextBinaries()
{
// Act
var table = TableDescriptors.States;
var byteaColumns = table.Columns
.Where(c => c.NpgsqlType == NpgsqlDbType.Bytea)
.Select(c => c.SqliteName)
.ToList();
// Assert
byteaColumns.Should().Contain("context_id_bin");
byteaColumns.Should().Contain("context_user_id_bin");
byteaColumns.Should().Contain("context_parent_id_bin");
}
[Fact]
public void Events_ShouldHaveByteaColumnsForContextBinaries()
{
// Act
var table = TableDescriptors.Events;
var byteaColumns = table.Columns
.Where(c => c.NpgsqlType == NpgsqlDbType.Bytea)
.Select(c => c.SqliteName)
.ToList();
// Assert
byteaColumns.Should().Contain("context_id_bin");
byteaColumns.Should().Contain("context_user_id_bin");
byteaColumns.Should().Contain("context_parent_id_bin");
}
}
@@ -1,212 +0,0 @@
using FluentAssertions;
using HaDbMigration.Configuration;
using HaDbMigration.Models;
using HaDbMigration.Services;
using HaDbMigration.Services.Interfaces;
using Microsoft.Extensions.Logging;
using Moq;
using NpgsqlTypes;
namespace HaDbMigration.Tests;
public sealed class ValidationServiceTests
{
private readonly Mock<ISqliteReaderService> _sqliteReaderMock;
private readonly Mock<IPostgresWriterService> _postgresWriterMock;
private readonly Mock<ILogger<ValidationService>> _loggerMock;
public ValidationServiceTests()
{
_sqliteReaderMock = new Mock<ISqliteReaderService>();
_postgresWriterMock = new Mock<IPostgresWriterService>();
_loggerMock = new Mock<ILogger<ValidationService>>();
}
private ValidationService CreateSut(bool dryRun = false)
{
var options = new MigrationOptions
{
SqlitePath = "test.db",
PostgresConnectionString = "Host=localhost",
DryRun = dryRun,
};
return new ValidationService(
_sqliteReaderMock.Object,
_postgresWriterMock.Object,
options,
_loggerMock.Object);
}
[Fact]
public async Task ValidateRowCountsAsync_WhenCountsMatch_ShouldReturnAllMatched()
{
// Arrange
var table = new TableDescriptor(
"test_table",
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
"id");
_sqliteReaderMock
.Setup(x => x.GetRowCountAsync("test_table", It.IsAny<CancellationToken>()))
.ReturnsAsync(1000);
_postgresWriterMock
.Setup(x => x.GetRowCountAsync("test_table", It.IsAny<CancellationToken>()))
.ReturnsAsync(1000);
var sut = CreateSut();
// Act
var results = await sut.ValidateRowCountsAsync([table], CancellationToken.None);
// Assert
results.Should().HaveCount(1);
results[0].IsMatch.Should().BeTrue();
results[0].SourceRowCount.Should().Be(1000);
results[0].TargetRowCount.Should().Be(1000);
}
[Fact]
public async Task ValidateRowCountsAsync_WhenCountsMismatch_ShouldReturnMismatch()
{
// Arrange
var table = new TableDescriptor(
"test_table",
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
"id");
_sqliteReaderMock
.Setup(x => x.GetRowCountAsync("test_table", It.IsAny<CancellationToken>()))
.ReturnsAsync(1000);
_postgresWriterMock
.Setup(x => x.GetRowCountAsync("test_table", It.IsAny<CancellationToken>()))
.ReturnsAsync(500);
var sut = CreateSut();
// Act
var results = await sut.ValidateRowCountsAsync([table], CancellationToken.None);
// Assert
results.Should().HaveCount(1);
results[0].IsMatch.Should().BeFalse();
results[0].SourceRowCount.Should().Be(1000);
results[0].TargetRowCount.Should().Be(500);
}
[Fact]
public async Task ValidateRowCountsAsync_InDryRunMode_ShouldAlwaysReturnMatch()
{
// Arrange
var table = new TableDescriptor(
"test_table",
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
"id");
_sqliteReaderMock
.Setup(x => x.GetRowCountAsync("test_table", It.IsAny<CancellationToken>()))
.ReturnsAsync(1000);
var sut = CreateSut(dryRun: true);
// Act
var results = await sut.ValidateRowCountsAsync([table], CancellationToken.None);
// Assert
results.Should().HaveCount(1);
results[0].IsMatch.Should().BeTrue();
results[0].TargetRowCount.Should().Be(0);
}
[Fact]
public async Task ValidateRowCountsAsync_InDryRunMode_ShouldNotQueryPostgres()
{
// Arrange
var table = new TableDescriptor(
"test_table",
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
"id");
_sqliteReaderMock
.Setup(x => x.GetRowCountAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(100);
var sut = CreateSut(dryRun: true);
// Act
await sut.ValidateRowCountsAsync([table], CancellationToken.None);
// Assert
_postgresWriterMock.Verify(
x => x.GetRowCountAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()),
Times.Never);
}
[Fact]
public async Task ValidateRowCountsAsync_WithMultipleTables_ShouldReturnResultForEach()
{
// Arrange
var table1 = new TableDescriptor(
"table1",
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
"id");
var table2 = new TableDescriptor(
"table2",
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
"id");
_sqliteReaderMock
.Setup(x => x.GetRowCountAsync("table1", It.IsAny<CancellationToken>()))
.ReturnsAsync(100);
_sqliteReaderMock
.Setup(x => x.GetRowCountAsync("table2", It.IsAny<CancellationToken>()))
.ReturnsAsync(200);
_postgresWriterMock
.Setup(x => x.GetRowCountAsync("table1", It.IsAny<CancellationToken>()))
.ReturnsAsync(100);
_postgresWriterMock
.Setup(x => x.GetRowCountAsync("table2", It.IsAny<CancellationToken>()))
.ReturnsAsync(200);
var sut = CreateSut();
// Act
var results = await sut.ValidateRowCountsAsync([table1, table2], CancellationToken.None);
// Assert
results.Should().HaveCount(2);
results.Should().AllSatisfy(r => r.IsMatch.Should().BeTrue());
}
[Fact]
public async Task ValidateRowCountsAsync_WithEmptyTable_ShouldHandleZeroCounts()
{
// Arrange
var table = new TableDescriptor(
"empty_table",
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
"id");
_sqliteReaderMock
.Setup(x => x.GetRowCountAsync("empty_table", It.IsAny<CancellationToken>()))
.ReturnsAsync(0);
_postgresWriterMock
.Setup(x => x.GetRowCountAsync("empty_table", It.IsAny<CancellationToken>()))
.ReturnsAsync(0);
var sut = CreateSut();
// Act
var results = await sut.ValidateRowCountsAsync([table], CancellationToken.None);
// Assert
results.Should().HaveCount(1);
results[0].IsMatch.Should().BeTrue();
results[0].SourceRowCount.Should().Be(0);
results[0].TargetRowCount.Should().Be(0);
}
}
@@ -1,31 +0,0 @@
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
@@ -1,21 +0,0 @@
<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
@@ -1,8 +0,0 @@
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
@@ -1,20 +0,0 @@
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
@@ -1,7 +0,0 @@
namespace HaDbMigration.Models;
public sealed record EventTypeEntity
{
public long EventTypeId { get; init; }
public string? EventType { get; init; }
}
@@ -1,7 +0,0 @@
namespace HaDbMigration.Models;
public sealed record MigrationChangeEntity
{
public string MigrationId { get; init; } = string.Empty;
public short Version { get; init; }
}
-10
View File
@@ -1,10 +0,0 @@
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; }
}
@@ -1,8 +0,0 @@
namespace HaDbMigration.Models;
public sealed record SchemaChangeEntity
{
public long ChangeId { get; init; }
public int? SchemaVersion { get; init; }
public DateTime Changed { get; init; }
}
@@ -1,8 +0,0 @@
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
@@ -1,25 +0,0 @@
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
@@ -1,7 +0,0 @@
namespace HaDbMigration.Models;
public sealed record StatesMetaEntity
{
public long MetadataId { get; init; }
public string? EntityId { get; init; }
}
-19
View File
@@ -1,19 +0,0 @@
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; }
}
@@ -1,14 +0,0 @@
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; }
}
@@ -1,7 +0,0 @@
namespace HaDbMigration.Models;
public sealed record StatisticsRunEntity
{
public long RunId { get; init; }
public DateTime Start { get; init; }
}
@@ -1,19 +0,0 @@
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
@@ -1,206 +0,0 @@
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
@@ -1,102 +0,0 @@
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();
@@ -1,6 +0,0 @@
namespace HaDbMigration.Services.Interfaces;
public interface IMigrationOrchestrator
{
Task RunAsync(CancellationToken cancellationToken);
}
@@ -1,14 +0,0 @@
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);
}
@@ -1,18 +0,0 @@
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);
}
@@ -1,14 +0,0 @@
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);
}
@@ -1,16 +0,0 @@
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);
}
@@ -1,189 +0,0 @@
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");
}
}
}
@@ -1,163 +0,0 @@
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
@@ -1,127 +0,0 @@
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);
}
}
}
@@ -1,90 +0,0 @@
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);
}
}
@@ -1,67 +0,0 @@
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);
}
}
-28
View File
@@ -14,10 +14,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeAssistant.Models", "Hom
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NordPool.Manager.Tests", "NordPool.Manager.Tests\NordPool.Manager.Tests.csproj", "{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HaDbMigration", "HaDbMigration\HaDbMigration.csproj", "{B759A963-6844-4029-97C4-FC954D0AF9DD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HaDbMigration.Tests", "HaDbMigration.Tests\HaDbMigration.Tests.csproj", "{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -112,30 +108,6 @@ Global
{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Release|x64.Build.0 = Release|Any CPU
{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Release|x86.ActiveCfg = Release|Any CPU
{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Release|x86.Build.0 = Release|Any CPU
{B759A963-6844-4029-97C4-FC954D0AF9DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B759A963-6844-4029-97C4-FC954D0AF9DD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B759A963-6844-4029-97C4-FC954D0AF9DD}.Debug|x64.ActiveCfg = Debug|Any CPU
{B759A963-6844-4029-97C4-FC954D0AF9DD}.Debug|x64.Build.0 = Debug|Any CPU
{B759A963-6844-4029-97C4-FC954D0AF9DD}.Debug|x86.ActiveCfg = Debug|Any CPU
{B759A963-6844-4029-97C4-FC954D0AF9DD}.Debug|x86.Build.0 = Debug|Any CPU
{B759A963-6844-4029-97C4-FC954D0AF9DD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B759A963-6844-4029-97C4-FC954D0AF9DD}.Release|Any CPU.Build.0 = Release|Any CPU
{B759A963-6844-4029-97C4-FC954D0AF9DD}.Release|x64.ActiveCfg = Release|Any CPU
{B759A963-6844-4029-97C4-FC954D0AF9DD}.Release|x64.Build.0 = Release|Any CPU
{B759A963-6844-4029-97C4-FC954D0AF9DD}.Release|x86.ActiveCfg = Release|Any CPU
{B759A963-6844-4029-97C4-FC954D0AF9DD}.Release|x86.Build.0 = Release|Any CPU
{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}.Debug|x64.ActiveCfg = Debug|Any CPU
{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}.Debug|x64.Build.0 = Debug|Any CPU
{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}.Debug|x86.ActiveCfg = Debug|Any CPU
{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}.Debug|x86.Build.0 = Debug|Any CPU
{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}.Release|Any CPU.Build.0 = Release|Any CPU
{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}.Release|x64.ActiveCfg = Release|Any CPU
{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}.Release|x64.Build.0 = Release|Any CPU
{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}.Release|x86.ActiveCfg = Release|Any CPU
{8FF77CB2-8006-428D-8FFC-0E3501BE9C94}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE