diff --git a/HaDbMigration.Tests/HaDbMigration.Tests.csproj b/HaDbMigration.Tests/HaDbMigration.Tests.csproj
deleted file mode 100644
index ea88e1d..0000000
--- a/HaDbMigration.Tests/HaDbMigration.Tests.csproj
+++ /dev/null
@@ -1,34 +0,0 @@
-
-
-
- net10.0
- 14.0
- enable
- enable
- false
-
-
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/HaDbMigration.Tests/MigrationOptionsTests.cs b/HaDbMigration.Tests/MigrationOptionsTests.cs
deleted file mode 100644
index 43a8e99..0000000
--- a/HaDbMigration.Tests/MigrationOptionsTests.cs
+++ /dev/null
@@ -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()
- .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()
- .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();
- }
- 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()
- .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();
- }
-}
diff --git a/HaDbMigration.Tests/MigrationOrchestratorTests.cs b/HaDbMigration.Tests/MigrationOrchestratorTests.cs
deleted file mode 100644
index 46452b2..0000000
--- a/HaDbMigration.Tests/MigrationOrchestratorTests.cs
+++ /dev/null
@@ -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 _readerMock;
- private readonly Mock _writerMock;
- private readonly Mock _schemaMock;
- private readonly Mock _validationMock;
- private readonly Mock> _loggerMock;
-
- public MigrationOrchestratorTests()
- {
- _readerMock = new Mock();
- _writerMock = new Mock();
- _schemaMock = new Mock();
- _validationMock = new Mock();
- _loggerMock = new Mock>();
- }
-
- 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>(),
- It.IsAny()))
- .ReturnsAsync(true);
-
- _readerMock
- .Setup(x => x.ReadTableAsync(
- It.IsAny(),
- It.IsAny>>(),
- It.IsAny()))
- .Returns((TableDescriptor _, ChannelWriter> writer, CancellationToken _) =>
- {
- writer.Complete();
- return Task.CompletedTask;
- });
-
- _writerMock
- .Setup(x => x.WriteTableAsync(
- It.IsAny(),
- It.IsAny>>(),
- It.IsAny()))
- .Returns(async (TableDescriptor table, ChannelReader> reader, CancellationToken ct) =>
- {
- await foreach (var batch in reader.ReadAllAsync(ct))
- {
- }
- });
-
- _schemaMock
- .Setup(x => x.ResetSequencesAsync(
- It.IsAny>(),
- It.IsAny()))
- .Returns(Task.CompletedTask);
-
- _validationMock
- .Setup(x => x.ValidateRowCountsAsync(
- It.IsAny>(),
- It.IsAny()))
- .ReturnsAsync([]);
- }
-
- [Fact]
- public async Task RunAsync_WhenTablesDoNotExist_ShouldNotMigrateData()
- {
- // Arrange
- _schemaMock
- .Setup(x => x.ValidateTablesExistAsync(
- It.IsAny>(),
- It.IsAny()))
- .ReturnsAsync(false);
-
- var sut = CreateSut();
-
- // Act
- await sut.RunAsync(CancellationToken.None);
-
- // Assert
- _readerMock.Verify(
- x => x.ReadTableAsync(
- It.IsAny(),
- It.IsAny>>(),
- It.IsAny()),
- 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>(),
- It.IsAny()),
- 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>(),
- It.IsAny()),
- 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>(),
- It.IsAny()),
- 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>(),
- It.IsAny()),
- 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>(),
- It.IsAny()),
- 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>(),
- It.IsAny()),
- Times.Once);
- }
-
- [Fact]
- public async Task RunAsync_ShouldValidateSchemaFirst()
- {
- // Arrange
- SetupHappyPath();
- var callOrder = new List();
-
- _schemaMock
- .Setup(x => x.ValidateTablesExistAsync(
- It.IsAny>(),
- It.IsAny()))
- .Callback(() => callOrder.Add("validate"))
- .ReturnsAsync(true);
-
- _readerMock
- .Setup(x => x.ReadTableAsync(
- It.IsAny(),
- It.IsAny>>(),
- It.IsAny()))
- .Callback(() => callOrder.Add("read"))
- .Returns((TableDescriptor _, ChannelWriter> writer, CancellationToken _) =>
- {
- writer.Complete();
- return Task.CompletedTask;
- });
-
- var sut = CreateSut();
-
- // Act
- await sut.RunAsync(CancellationToken.None);
-
- // Assert
- callOrder.First().Should().Be("validate");
- }
-}
diff --git a/HaDbMigration.Tests/PostgresWriterServiceTests.cs b/HaDbMigration.Tests/PostgresWriterServiceTests.cs
deleted file mode 100644
index acb6a62..0000000
--- a/HaDbMigration.Tests/PostgresWriterServiceTests.cs
+++ /dev/null
@@ -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();
- }
-
- [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();
- }
-
- [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();
- }
-
- [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)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[])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)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();
- }
-}
diff --git a/HaDbMigration.Tests/TableDescriptorsTests.cs b/HaDbMigration.Tests/TableDescriptorsTests.cs
deleted file mode 100644
index f038744..0000000
--- a/HaDbMigration.Tests/TableDescriptorsTests.cs
+++ /dev/null
@@ -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");
- }
-}
diff --git a/HaDbMigration.Tests/ValidationServiceTests.cs b/HaDbMigration.Tests/ValidationServiceTests.cs
deleted file mode 100644
index 0ceb9ee..0000000
--- a/HaDbMigration.Tests/ValidationServiceTests.cs
+++ /dev/null
@@ -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 _sqliteReaderMock;
- private readonly Mock _postgresWriterMock;
- private readonly Mock> _loggerMock;
-
- public ValidationServiceTests()
- {
- _sqliteReaderMock = new Mock();
- _postgresWriterMock = new Mock();
- _loggerMock = new Mock>();
- }
-
- 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()))
- .ReturnsAsync(1000);
-
- _postgresWriterMock
- .Setup(x => x.GetRowCountAsync("test_table", It.IsAny()))
- .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()))
- .ReturnsAsync(1000);
-
- _postgresWriterMock
- .Setup(x => x.GetRowCountAsync("test_table", It.IsAny()))
- .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()))
- .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(), It.IsAny()))
- .ReturnsAsync(100);
-
- var sut = CreateSut(dryRun: true);
-
- // Act
- await sut.ValidateRowCountsAsync([table], CancellationToken.None);
-
- // Assert
- _postgresWriterMock.Verify(
- x => x.GetRowCountAsync(It.IsAny(), It.IsAny()),
- 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()))
- .ReturnsAsync(100);
- _sqliteReaderMock
- .Setup(x => x.GetRowCountAsync("table2", It.IsAny()))
- .ReturnsAsync(200);
-
- _postgresWriterMock
- .Setup(x => x.GetRowCountAsync("table1", It.IsAny()))
- .ReturnsAsync(100);
- _postgresWriterMock
- .Setup(x => x.GetRowCountAsync("table2", It.IsAny()))
- .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()))
- .ReturnsAsync(0);
-
- _postgresWriterMock
- .Setup(x => x.GetRowCountAsync("empty_table", It.IsAny()))
- .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);
- }
-}
diff --git a/HaDbMigration/Configuration/MigrationOptions.cs b/HaDbMigration/Configuration/MigrationOptions.cs
deleted file mode 100644
index 1817828..0000000
--- a/HaDbMigration/Configuration/MigrationOptions.cs
+++ /dev/null
@@ -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.");
- }
- }
-}
diff --git a/HaDbMigration/HaDbMigration.csproj b/HaDbMigration/HaDbMigration.csproj
deleted file mode 100644
index a396185..0000000
--- a/HaDbMigration/HaDbMigration.csproj
+++ /dev/null
@@ -1,21 +0,0 @@
-
-
-
- Exe
- net10.0
- 14.0
- enable
- enable
- HaDbMigration
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/HaDbMigration/Models/EventDataEntity.cs b/HaDbMigration/Models/EventDataEntity.cs
deleted file mode 100644
index de8d69e..0000000
--- a/HaDbMigration/Models/EventDataEntity.cs
+++ /dev/null
@@ -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; }
-}
diff --git a/HaDbMigration/Models/EventEntity.cs b/HaDbMigration/Models/EventEntity.cs
deleted file mode 100644
index 265146c..0000000
--- a/HaDbMigration/Models/EventEntity.cs
+++ /dev/null
@@ -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; }
-}
diff --git a/HaDbMigration/Models/EventTypeEntity.cs b/HaDbMigration/Models/EventTypeEntity.cs
deleted file mode 100644
index 0ab80e2..0000000
--- a/HaDbMigration/Models/EventTypeEntity.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace HaDbMigration.Models;
-
-public sealed record EventTypeEntity
-{
- public long EventTypeId { get; init; }
- public string? EventType { get; init; }
-}
diff --git a/HaDbMigration/Models/MigrationChangeEntity.cs b/HaDbMigration/Models/MigrationChangeEntity.cs
deleted file mode 100644
index e6b6450..0000000
--- a/HaDbMigration/Models/MigrationChangeEntity.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace HaDbMigration.Models;
-
-public sealed record MigrationChangeEntity
-{
- public string MigrationId { get; init; } = string.Empty;
- public short Version { get; init; }
-}
diff --git a/HaDbMigration/Models/RecorderRunEntity.cs b/HaDbMigration/Models/RecorderRunEntity.cs
deleted file mode 100644
index e293369..0000000
--- a/HaDbMigration/Models/RecorderRunEntity.cs
+++ /dev/null
@@ -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; }
-}
diff --git a/HaDbMigration/Models/SchemaChangeEntity.cs b/HaDbMigration/Models/SchemaChangeEntity.cs
deleted file mode 100644
index daefcaa..0000000
--- a/HaDbMigration/Models/SchemaChangeEntity.cs
+++ /dev/null
@@ -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; }
-}
diff --git a/HaDbMigration/Models/StateAttributeEntity.cs b/HaDbMigration/Models/StateAttributeEntity.cs
deleted file mode 100644
index f43c9a8..0000000
--- a/HaDbMigration/Models/StateAttributeEntity.cs
+++ /dev/null
@@ -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; }
-}
diff --git a/HaDbMigration/Models/StateEntity.cs b/HaDbMigration/Models/StateEntity.cs
deleted file mode 100644
index db637b6..0000000
--- a/HaDbMigration/Models/StateEntity.cs
+++ /dev/null
@@ -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; }
-}
diff --git a/HaDbMigration/Models/StatesMetaEntity.cs b/HaDbMigration/Models/StatesMetaEntity.cs
deleted file mode 100644
index d7482ce..0000000
--- a/HaDbMigration/Models/StatesMetaEntity.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace HaDbMigration.Models;
-
-public sealed record StatesMetaEntity
-{
- public long MetadataId { get; init; }
- public string? EntityId { get; init; }
-}
diff --git a/HaDbMigration/Models/StatisticsEntity.cs b/HaDbMigration/Models/StatisticsEntity.cs
deleted file mode 100644
index 182e8bc..0000000
--- a/HaDbMigration/Models/StatisticsEntity.cs
+++ /dev/null
@@ -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; }
-}
diff --git a/HaDbMigration/Models/StatisticsMetaEntity.cs b/HaDbMigration/Models/StatisticsMetaEntity.cs
deleted file mode 100644
index 3da4fd7..0000000
--- a/HaDbMigration/Models/StatisticsMetaEntity.cs
+++ /dev/null
@@ -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; }
-}
diff --git a/HaDbMigration/Models/StatisticsRunEntity.cs b/HaDbMigration/Models/StatisticsRunEntity.cs
deleted file mode 100644
index 40b1152..0000000
--- a/HaDbMigration/Models/StatisticsRunEntity.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace HaDbMigration.Models;
-
-public sealed record StatisticsRunEntity
-{
- public long RunId { get; init; }
- public DateTime Start { get; init; }
-}
diff --git a/HaDbMigration/Models/StatisticsShortTermEntity.cs b/HaDbMigration/Models/StatisticsShortTermEntity.cs
deleted file mode 100644
index 4d1a63a..0000000
--- a/HaDbMigration/Models/StatisticsShortTermEntity.cs
+++ /dev/null
@@ -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; }
-}
diff --git a/HaDbMigration/Models/TableDescriptor.cs b/HaDbMigration/Models/TableDescriptor.cs
deleted file mode 100644
index 94a117f..0000000
--- a/HaDbMigration/Models/TableDescriptor.cs
+++ /dev/null
@@ -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 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 GetMigrationOrder() =>
- [
- EventTypes,
- EventData,
- StatesMeta,
- StateAttributes,
- StatisticsMeta,
- Events,
- States,
- Statistics,
- StatisticsShortTerm,
- StatisticsRuns,
- RecorderRuns,
- SchemaChanges,
- MigrationChanges,
- ];
-}
diff --git a/HaDbMigration/Program.cs b/HaDbMigration/Program.cs
deleted file mode 100644
index b5b1e1b..0000000
--- a/HaDbMigration/Program.cs
+++ /dev/null
@@ -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("--sqlite")
-{
- Description = "Path to the Home Assistant SQLite database file (home-assistant_v2.db)",
- Required = true,
-};
-
-var pgConnectionOption = new Option("--pg-connection")
-{
- Description = "PostgreSQL connection string",
- Required = true,
-};
-
-var batchSizeOption = new Option("--batch-size")
-{
- Description = "Number of rows per batch (minimum 100)",
- DefaultValueFactory = _ => 10_000,
-};
-
-var truncateOption = new Option("--truncate")
-{
- Description = "Truncate PostgreSQL tables before migration",
- DefaultValueFactory = _ => false,
-};
-
-var dryRunOption = new Option("--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();
- services.AddSingleton();
- services.AddSingleton();
- services.AddSingleton();
- services.AddSingleton();
- })
- .Build();
-
- var orchestrator = host.Services.GetRequiredService();
- 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();
diff --git a/HaDbMigration/Services/Interfaces/IMigrationOrchestrator.cs b/HaDbMigration/Services/Interfaces/IMigrationOrchestrator.cs
deleted file mode 100644
index 527caa5..0000000
--- a/HaDbMigration/Services/Interfaces/IMigrationOrchestrator.cs
+++ /dev/null
@@ -1,6 +0,0 @@
-namespace HaDbMigration.Services.Interfaces;
-
-public interface IMigrationOrchestrator
-{
- Task RunAsync(CancellationToken cancellationToken);
-}
diff --git a/HaDbMigration/Services/Interfaces/IPostgresWriterService.cs b/HaDbMigration/Services/Interfaces/IPostgresWriterService.cs
deleted file mode 100644
index b5ee961..0000000
--- a/HaDbMigration/Services/Interfaces/IPostgresWriterService.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-using System.Threading.Channels;
-using HaDbMigration.Models;
-
-namespace HaDbMigration.Services.Interfaces;
-
-public interface IPostgresWriterService
-{
- Task WriteTableAsync(
- TableDescriptor table,
- ChannelReader> reader,
- CancellationToken cancellationToken);
-
- Task GetRowCountAsync(string tableName, CancellationToken cancellationToken);
-}
diff --git a/HaDbMigration/Services/Interfaces/ISchemaService.cs b/HaDbMigration/Services/Interfaces/ISchemaService.cs
deleted file mode 100644
index 4cb249c..0000000
--- a/HaDbMigration/Services/Interfaces/ISchemaService.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-using HaDbMigration.Models;
-
-namespace HaDbMigration.Services.Interfaces;
-
-public interface ISchemaService
-{
- Task ValidateTablesExistAsync(
- IReadOnlyList tables,
- CancellationToken cancellationToken);
-
- Task TruncateTablesAsync(
- IReadOnlyList tables,
- CancellationToken cancellationToken);
-
- Task ResetSequencesAsync(
- IReadOnlyList tables,
- CancellationToken cancellationToken);
-}
diff --git a/HaDbMigration/Services/Interfaces/ISqliteReaderService.cs b/HaDbMigration/Services/Interfaces/ISqliteReaderService.cs
deleted file mode 100644
index 0ecf123..0000000
--- a/HaDbMigration/Services/Interfaces/ISqliteReaderService.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-using System.Threading.Channels;
-using HaDbMigration.Models;
-
-namespace HaDbMigration.Services.Interfaces;
-
-public interface ISqliteReaderService
-{
- Task ReadTableAsync(
- TableDescriptor table,
- ChannelWriter> writer,
- CancellationToken cancellationToken);
-
- Task GetRowCountAsync(string tableName, CancellationToken cancellationToken);
-}
diff --git a/HaDbMigration/Services/Interfaces/IValidationService.cs b/HaDbMigration/Services/Interfaces/IValidationService.cs
deleted file mode 100644
index f1961c7..0000000
--- a/HaDbMigration/Services/Interfaces/IValidationService.cs
+++ /dev/null
@@ -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> ValidateRowCountsAsync(
- IReadOnlyList tables,
- CancellationToken cancellationToken);
-}
diff --git a/HaDbMigration/Services/MigrationOrchestrator.cs b/HaDbMigration/Services/MigrationOrchestrator.cs
deleted file mode 100644
index bdaece1..0000000
--- a/HaDbMigration/Services/MigrationOrchestrator.cs
+++ /dev/null
@@ -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 _logger;
-
- private static readonly IReadOnlyList> 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 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 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>(
- 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 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");
- }
- }
-}
diff --git a/HaDbMigration/Services/PostgresWriterService.cs b/HaDbMigration/Services/PostgresWriterService.cs
deleted file mode 100644
index 843948b..0000000
--- a/HaDbMigration/Services/PostgresWriterService.cs
+++ /dev/null
@@ -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 _logger;
-
- public PostgresWriterService(MigrationOptions options, ILogger logger)
- {
- _options = options;
- _logger = logger;
- }
-
- public async Task WriteTableAsync(
- TableDescriptor table,
- ChannelReader> 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 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