diff --git a/.cursor/plans/ha_sqlite_to_postgresql_migration_tool_e53c18ee.plan.md b/.cursor/plans/ha_sqlite_to_postgresql_migration_tool_e53c18ee.plan.md new file mode 100644 index 0000000..7fc95d6 --- /dev/null +++ b/.cursor/plans/ha_sqlite_to_postgresql_migration_tool_e53c18ee.plan.md @@ -0,0 +1,199 @@ +--- +name: HA SQLite to PostgreSQL Migration Tool +overview: Build a .NET 10.0 console application that reads a Home Assistant SQLite database file (home-assistant_v2.db) and migrates all data into a PostgreSQL database, handling schema differences, boolean type conversions, batch processing, and sequence resets. +todos: + - id: create-project + content: Create HaDbMigration console project (.csproj, add to solution, install NuGet packages) + status: completed + - id: entity-models + content: Create C# entity models for all 12+1 HA recorder tables matching schema v53 + status: completed + - id: configuration + content: Implement MigrationOptions and CLI argument parsing with System.CommandLine + status: completed + - id: program-host + content: Build Program.cs with Generic Host, DI registration, Serilog logging + status: completed + - id: sqlite-reader + content: Implement SqliteReaderService with batch reading and Channel producer pattern + status: completed + - id: postgres-writer + content: Implement PostgresWriterService with Npgsql binary COPY and Channel consumer + status: completed + - id: schema-service + content: Implement SchemaService for table validation, truncation, and sequence resets + status: completed + - id: orchestrator + content: Implement MigrationOrchestrator to coordinate table-order, parallelism, and progress + status: completed + - id: validation-service + content: Implement ValidationService for row-count comparison and integrity checks + status: completed + - id: type-conversions + content: Handle SQLite-to-PostgreSQL type conversions (bool, BLOB/BYTEA, legacy columns) + status: completed + - id: unit-tests + content: Add HaDbMigration.Tests project with unit tests for services + status: completed +isProject: false +--- + +# HA SQLite to PostgreSQL Migration Tool + +## Context + +Home Assistant stores its recorder data in a SQLite file (`home-assistant_v2.db`) with schema version 53. The HA recorder schema contains 12 tables tracking events, states, statistics, and metadata. This tool will be a .NET 10.0 console app added to the existing solution that reads the SQLite file and writes all data to a PostgreSQL database. + +## HA Recorder Tables (Schema v53) + +The following 12 tables need to be migrated: + +- **events** -- event history (PK: `event_id`, FKs to `event_data`, `event_types`) +- **event_data** -- shared event data blobs (PK: `data_id`) +- **event_types** -- event type lookup (PK: `event_type_id`) +- **states** -- state change history (PK: `state_id`, FKs to `state_attributes`, `states_meta`, self-ref `old_state_id`) +- **state_attributes** -- shared attribute blobs (PK: `attributes_id`) +- **states_meta** -- entity_id metadata (PK: `metadata_id`) +- **recorder_runs** -- recorder run tracking (PK: `run_id`, has `closed_incorrect` boolean) +- **schema_changes** -- schema version log (PK: `change_id`) +- **migration_changes** -- migration tracking (PK: `migration_id`) +- **statistics** -- long-term hourly statistics (PK: `id`, FK to `statistics_meta`) +- **statistics_meta** -- statistics metadata (PK: `id`, has `has_mean`/`has_sum` booleans) +- **statistics_short_term** -- 5-minute statistics (PK: `id`, FK to `statistics_meta`) +- **statistics_runs** -- statistics run tracking (PK: `run_id`) + +## Key Schema Compatibility Issues + +1. **Boolean columns**: SQLite stores booleans as integers (0/1). PostgreSQL uses native `boolean`. Affected columns: + - `statistics_meta.has_sum` + - `statistics_meta.has_mean` + - `recorder_runs.closed_incorrect` +2. **ID types**: SQLite uses INTEGER for identity PKs; PostgreSQL uses BIGINT with IDENTITY sequences. +3. **Unused/Legacy columns**: Many columns are typed as `CHAR(0)` in SQLite but `CHAR(1)` in PostgreSQL (legacy columns kept for backward compat). +4. **Sequences**: After bulk insert, PostgreSQL sequences must be reset to `MAX(pk) + 1`. +5. **BLOB columns**: Context ID binary columns (`context_id_bin`, etc.) are `BLOB` in SQLite, `BYTEA` in PostgreSQL. + +## Architecture + +```mermaid +flowchart TB + subgraph cli [CLI Layer] + Program["Program.cs -- Argument parsing, DI setup"] + end + + subgraph services [Service Layer] + Orchestrator["MigrationOrchestrator -- Coordinates full migration"] + SchemaCreator["SchemaService -- Creates PG tables via HA startup or SQL"] + Reader["SqliteReaderService -- Reads from SQLite"] + Writer["PostgresWriterService -- Bulk writes to PostgreSQL"] + Validator["ValidationService -- Row counts, integrity checks"] + end + + subgraph data [Data Layer] + Entities["Entity models matching HA schema"] + end + + Program --> Orchestrator + Orchestrator --> SchemaCreator + Orchestrator --> Reader + Orchestrator --> Writer + Orchestrator --> Validator + Reader --> Entities + Writer --> Entities +``` + + + +## Project Structure + +New console project: `HaDbMigration/` + +``` +HaDbMigration/ + HaDbMigration.csproj + Program.cs + Configuration/ + MigrationOptions.cs + Models/ + EventEntity.cs + EventDataEntity.cs + EventTypeEntity.cs + StateEntity.cs + StateAttributeEntity.cs + StatesMetaEntity.cs + RecorderRunEntity.cs + SchemaChangeEntity.cs + MigrationChangeEntity.cs + StatisticsEntity.cs + StatisticsMetaEntity.cs + StatisticsShortTermEntity.cs + StatisticsRunEntity.cs + Services/ + Interfaces/ + IMigrationOrchestrator.cs + ISqliteReaderService.cs + IPostgresWriterService.cs + ISchemaService.cs + IValidationService.cs + MigrationOrchestrator.cs + SqliteReaderService.cs + PostgresWriterService.cs + SchemaService.cs + ValidationService.cs +``` + +## NuGet Packages + +- `Microsoft.Data.Sqlite` -- read SQLite database +- `Npgsql` -- write to PostgreSQL (raw ADO.NET for bulk performance) +- `Microsoft.Extensions.Hosting` -- generic host, DI, configuration, logging +- `Microsoft.Extensions.Configuration.CommandLine` -- CLI argument binding +- `Serilog.Extensions.Hosting` + sinks -- consistent logging with the rest of the solution +- `System.CommandLine` -- CLI argument parsing + +## Migration Strategy + +The recommended approach (matching community best practice) is: + +1. **Let HA create the PostgreSQL schema first** by pointing HA at the empty PG database and starting it briefly. This ensures the schema is exactly correct for the HA version in use. +2. **This tool then migrates data only** -- it reads from the SQLite file and bulk-inserts into the existing PG tables. + +The tool will: + +1. **Validate inputs** -- check SQLite file exists, PostgreSQL is reachable, target tables exist +2. **Truncate target tables** (with user confirmation) -- clear any data HA auto-created during schema setup +3. **Migrate data table-by-table** in dependency order (leaf tables first): + - `event_types` -> `event_data` -> `events` + - `states_meta` -> `state_attributes` -> `states` + - `statistics_meta` -> `statistics` -> `statistics_short_term` + - `statistics_runs`, `recorder_runs`, `schema_changes`, `migration_changes` +4. **Batch processing** -- read/write in configurable batches (default 10,000 rows) using `Channel` producer-consumer with parallel read/write +5. **Handle type conversions** -- integer-to-boolean for `has_sum`, `has_mean`, `closed_incorrect` +6. **Reset PostgreSQL sequences** -- `setval(pg_get_serial_sequence(...), MAX(pk))` for all identity columns +7. **Validate migration** -- compare row counts between source and target for each table +8. **Report results** -- log per-table row counts, elapsed time, and any errors + +## CLI Interface + +``` +HaDbMigration.exe --sqlite "C:\path\to\home-assistant_v2.db" --pg-connection "Host=...;Database=...;Username=...;Password=..." [--batch-size 10000] [--truncate] [--dry-run] +``` + + +| Argument | Required | Description | +| ----------------- | -------- | ----------------------------------- | +| `--sqlite` | Yes | Path to the SQLite database file | +| `--pg-connection` | Yes | PostgreSQL connection string | +| `--batch-size` | No | Rows per batch (default: 10,000) | +| `--truncate` | No | Truncate PG tables before migration | +| `--dry-run` | No | Validate only, do not write | + + +## Multi-Threading Approach + +- Producer-consumer pattern using `System.Threading.Channels` +- SQLite reader produces batches on a dedicated thread +- PostgreSQL writer consumes batches on its own thread(s) +- Multiple tables can be migrated concurrently (respecting FK ordering via topological sort into independent groups) +- `Npgsql` binary COPY for maximum PostgreSQL write throughput + diff --git a/HaDbMigration.Tests/HaDbMigration.Tests.csproj b/HaDbMigration.Tests/HaDbMigration.Tests.csproj new file mode 100644 index 0000000..ea88e1d --- /dev/null +++ b/HaDbMigration.Tests/HaDbMigration.Tests.csproj @@ -0,0 +1,34 @@ + + + + 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 new file mode 100644 index 0000000..43a8e99 --- /dev/null +++ b/HaDbMigration.Tests/MigrationOptionsTests.cs @@ -0,0 +1,200 @@ +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 new file mode 100644 index 0000000..46452b2 --- /dev/null +++ b/HaDbMigration.Tests/MigrationOrchestratorTests.cs @@ -0,0 +1,260 @@ +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 new file mode 100644 index 0000000..acb6a62 --- /dev/null +++ b/HaDbMigration.Tests/PostgresWriterServiceTests.cs @@ -0,0 +1,189 @@ +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 new file mode 100644 index 0000000..f038744 --- /dev/null +++ b/HaDbMigration.Tests/TableDescriptorsTests.cs @@ -0,0 +1,171 @@ +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 new file mode 100644 index 0000000..0ceb9ee --- /dev/null +++ b/HaDbMigration.Tests/ValidationServiceTests.cs @@ -0,0 +1,212 @@ +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 new file mode 100644 index 0000000..1817828 --- /dev/null +++ b/HaDbMigration/Configuration/MigrationOptions.cs @@ -0,0 +1,31 @@ +namespace HaDbMigration.Configuration; + +public sealed class MigrationOptions +{ + public required string SqlitePath { get; init; } + public required string PostgresConnectionString { get; init; } + public int BatchSize { get; init; } = 10_000; + public bool Truncate { get; init; } + public bool DryRun { get; init; } + + public void Validate() + { + if (!File.Exists(SqlitePath)) + { + throw new FileNotFoundException( + $"SQLite database file not found: {SqlitePath}"); + } + + if (string.IsNullOrWhiteSpace(PostgresConnectionString)) + { + throw new ArgumentException( + "PostgreSQL connection string is required.", nameof(PostgresConnectionString)); + } + + if (BatchSize < 100) + { + throw new ArgumentOutOfRangeException( + nameof(BatchSize), "Batch size must be at least 100."); + } + } +} diff --git a/HaDbMigration/HaDbMigration.csproj b/HaDbMigration/HaDbMigration.csproj new file mode 100644 index 0000000..a396185 --- /dev/null +++ b/HaDbMigration/HaDbMigration.csproj @@ -0,0 +1,21 @@ + + + + Exe + net10.0 + 14.0 + enable + enable + HaDbMigration + + + + + + + + + + + + diff --git a/HaDbMigration/Models/EventDataEntity.cs b/HaDbMigration/Models/EventDataEntity.cs new file mode 100644 index 0000000..de8d69e --- /dev/null +++ b/HaDbMigration/Models/EventDataEntity.cs @@ -0,0 +1,8 @@ +namespace HaDbMigration.Models; + +public sealed record EventDataEntity +{ + public long DataId { get; init; } + public long? Hash { get; init; } + public string? SharedData { get; init; } +} diff --git a/HaDbMigration/Models/EventEntity.cs b/HaDbMigration/Models/EventEntity.cs new file mode 100644 index 0000000..265146c --- /dev/null +++ b/HaDbMigration/Models/EventEntity.cs @@ -0,0 +1,20 @@ +namespace HaDbMigration.Models; + +public sealed record EventEntity +{ + public long EventId { get; init; } + public string? EventType { get; init; } + public string? EventData { get; init; } + public string? Origin { get; init; } + public short? OriginIdx { get; init; } + public DateTime? TimeFired { get; init; } + public double? TimeFiredTs { get; init; } + public string? ContextId { get; init; } + public string? ContextUserId { get; init; } + public string? ContextParentId { get; init; } + public long? DataId { get; init; } + public byte[]? ContextIdBin { get; init; } + public byte[]? ContextUserIdBin { get; init; } + public byte[]? ContextParentIdBin { get; init; } + public long? EventTypeId { get; init; } +} diff --git a/HaDbMigration/Models/EventTypeEntity.cs b/HaDbMigration/Models/EventTypeEntity.cs new file mode 100644 index 0000000..0ab80e2 --- /dev/null +++ b/HaDbMigration/Models/EventTypeEntity.cs @@ -0,0 +1,7 @@ +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 new file mode 100644 index 0000000..e6b6450 --- /dev/null +++ b/HaDbMigration/Models/MigrationChangeEntity.cs @@ -0,0 +1,7 @@ +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 new file mode 100644 index 0000000..e293369 --- /dev/null +++ b/HaDbMigration/Models/RecorderRunEntity.cs @@ -0,0 +1,10 @@ +namespace HaDbMigration.Models; + +public sealed record RecorderRunEntity +{ + public long RunId { get; init; } + public DateTime Start { get; init; } + public DateTime? End { get; init; } + public long ClosedIncorrect { get; init; } + public DateTime Created { get; init; } +} diff --git a/HaDbMigration/Models/SchemaChangeEntity.cs b/HaDbMigration/Models/SchemaChangeEntity.cs new file mode 100644 index 0000000..daefcaa --- /dev/null +++ b/HaDbMigration/Models/SchemaChangeEntity.cs @@ -0,0 +1,8 @@ +namespace HaDbMigration.Models; + +public sealed record SchemaChangeEntity +{ + public long ChangeId { get; init; } + public int? SchemaVersion { get; init; } + public DateTime Changed { get; init; } +} diff --git a/HaDbMigration/Models/StateAttributeEntity.cs b/HaDbMigration/Models/StateAttributeEntity.cs new file mode 100644 index 0000000..f43c9a8 --- /dev/null +++ b/HaDbMigration/Models/StateAttributeEntity.cs @@ -0,0 +1,8 @@ +namespace HaDbMigration.Models; + +public sealed record StateAttributeEntity +{ + public long AttributesId { get; init; } + public long? Hash { get; init; } + public string? SharedAttrs { get; init; } +} diff --git a/HaDbMigration/Models/StateEntity.cs b/HaDbMigration/Models/StateEntity.cs new file mode 100644 index 0000000..db637b6 --- /dev/null +++ b/HaDbMigration/Models/StateEntity.cs @@ -0,0 +1,25 @@ +namespace HaDbMigration.Models; + +public sealed record StateEntity +{ + public long StateId { get; init; } + public string? EntityId { get; init; } + public string? State { get; init; } + public string? Attributes { get; init; } + public short? EventId { get; init; } + public DateTime? LastChanged { get; init; } + public double? LastChangedTs { get; init; } + public double? LastReportedTs { get; init; } + public DateTime? LastUpdated { get; init; } + public double? LastUpdatedTs { get; init; } + public long? OldStateId { get; init; } + public long? AttributesId { get; init; } + public string? ContextId { get; init; } + public string? ContextUserId { get; init; } + public string? ContextParentId { get; init; } + public short? OriginIdx { get; init; } + public byte[]? ContextIdBin { get; init; } + public byte[]? ContextUserIdBin { get; init; } + public byte[]? ContextParentIdBin { get; init; } + public long? MetadataId { get; init; } +} diff --git a/HaDbMigration/Models/StatesMetaEntity.cs b/HaDbMigration/Models/StatesMetaEntity.cs new file mode 100644 index 0000000..d7482ce --- /dev/null +++ b/HaDbMigration/Models/StatesMetaEntity.cs @@ -0,0 +1,7 @@ +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 new file mode 100644 index 0000000..182e8bc --- /dev/null +++ b/HaDbMigration/Models/StatisticsEntity.cs @@ -0,0 +1,19 @@ +namespace HaDbMigration.Models; + +public sealed record StatisticsEntity +{ + public long Id { get; init; } + public DateTime? Created { get; init; } + public double? CreatedTs { get; init; } + public long? MetadataId { get; init; } + public DateTime? Start { get; init; } + public double? StartTs { get; init; } + public double? Mean { get; init; } + public double? MeanWeight { get; init; } + public double? Min { get; init; } + public double? Max { get; init; } + public DateTime? LastReset { get; init; } + public double? LastResetTs { get; init; } + public double? State { get; init; } + public double? Sum { get; init; } +} diff --git a/HaDbMigration/Models/StatisticsMetaEntity.cs b/HaDbMigration/Models/StatisticsMetaEntity.cs new file mode 100644 index 0000000..3da4fd7 --- /dev/null +++ b/HaDbMigration/Models/StatisticsMetaEntity.cs @@ -0,0 +1,14 @@ +namespace HaDbMigration.Models; + +public sealed record StatisticsMetaEntity +{ + public long Id { get; init; } + public string? StatisticId { get; init; } + public string? Source { get; init; } + public string? UnitOfMeasurement { get; init; } + public string? UnitClass { get; init; } + public long? HasMean { get; init; } + public long? HasSum { get; init; } + public string? Name { get; init; } + public short MeanType { get; init; } +} diff --git a/HaDbMigration/Models/StatisticsRunEntity.cs b/HaDbMigration/Models/StatisticsRunEntity.cs new file mode 100644 index 0000000..40b1152 --- /dev/null +++ b/HaDbMigration/Models/StatisticsRunEntity.cs @@ -0,0 +1,7 @@ +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 new file mode 100644 index 0000000..4d1a63a --- /dev/null +++ b/HaDbMigration/Models/StatisticsShortTermEntity.cs @@ -0,0 +1,19 @@ +namespace HaDbMigration.Models; + +public sealed record StatisticsShortTermEntity +{ + public long Id { get; init; } + public DateTime? Created { get; init; } + public double? CreatedTs { get; init; } + public long? MetadataId { get; init; } + public DateTime? Start { get; init; } + public double? StartTs { get; init; } + public double? Mean { get; init; } + public double? MeanWeight { get; init; } + public double? Min { get; init; } + public double? Max { get; init; } + public DateTime? LastReset { get; init; } + public double? LastResetTs { get; init; } + public double? State { get; init; } + public double? Sum { get; init; } +} diff --git a/HaDbMigration/Models/TableDescriptor.cs b/HaDbMigration/Models/TableDescriptor.cs new file mode 100644 index 0000000..94a117f --- /dev/null +++ b/HaDbMigration/Models/TableDescriptor.cs @@ -0,0 +1,206 @@ +using NpgsqlTypes; + +namespace HaDbMigration.Models; + +public sealed record ColumnDescriptor( + string SqliteName, + string PostgresName, + NpgsqlDbType NpgsqlType, + bool IsPrimaryKey = false, + bool IsBooleanConversion = false); + +public sealed record TableDescriptor( + string TableName, + IReadOnlyList 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 new file mode 100644 index 0000000..b5b1e1b --- /dev/null +++ b/HaDbMigration/Program.cs @@ -0,0 +1,102 @@ +using System.CommandLine; +using HaDbMigration.Configuration; +using HaDbMigration.Services; +using HaDbMigration.Services.Interfaces; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Serilog; + +var sqliteOption = new Option("--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 new file mode 100644 index 0000000..527caa5 --- /dev/null +++ b/HaDbMigration/Services/Interfaces/IMigrationOrchestrator.cs @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000..b5ee961 --- /dev/null +++ b/HaDbMigration/Services/Interfaces/IPostgresWriterService.cs @@ -0,0 +1,14 @@ +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 new file mode 100644 index 0000000..4cb249c --- /dev/null +++ b/HaDbMigration/Services/Interfaces/ISchemaService.cs @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000..0ecf123 --- /dev/null +++ b/HaDbMigration/Services/Interfaces/ISqliteReaderService.cs @@ -0,0 +1,14 @@ +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 new file mode 100644 index 0000000..f1961c7 --- /dev/null +++ b/HaDbMigration/Services/Interfaces/IValidationService.cs @@ -0,0 +1,16 @@ +using HaDbMigration.Models; + +namespace HaDbMigration.Services.Interfaces; + +public sealed record TableValidationResult( + string TableName, + long SourceRowCount, + long TargetRowCount, + bool IsMatch); + +public interface IValidationService +{ + Task> ValidateRowCountsAsync( + IReadOnlyList tables, + CancellationToken cancellationToken); +} diff --git a/HaDbMigration/Services/MigrationOrchestrator.cs b/HaDbMigration/Services/MigrationOrchestrator.cs new file mode 100644 index 0000000..bdaece1 --- /dev/null +++ b/HaDbMigration/Services/MigrationOrchestrator.cs @@ -0,0 +1,189 @@ +using System.Diagnostics; +using System.Threading.Channels; +using HaDbMigration.Configuration; +using HaDbMigration.Models; +using HaDbMigration.Services.Interfaces; +using Microsoft.Extensions.Logging; + +namespace HaDbMigration.Services; + +public sealed class MigrationOrchestrator : IMigrationOrchestrator +{ + private readonly MigrationOptions _options; + private readonly ISqliteReaderService _readerService; + private readonly IPostgresWriterService _writerService; + private readonly ISchemaService _schemaService; + private readonly IValidationService _validationService; + private readonly ILogger _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 new file mode 100644 index 0000000..843948b --- /dev/null +++ b/HaDbMigration/Services/PostgresWriterService.cs @@ -0,0 +1,163 @@ +using System.Threading.Channels; +using HaDbMigration.Configuration; +using HaDbMigration.Models; +using HaDbMigration.Services.Interfaces; +using Microsoft.Extensions.Logging; +using Npgsql; +using NpgsqlTypes; + +namespace HaDbMigration.Services; + +public sealed class PostgresWriterService : IPostgresWriterService +{ + private readonly MigrationOptions _options; + private readonly ILogger _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 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> 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); + } +} diff --git a/HaDbMigration/Services/SchemaService.cs b/HaDbMigration/Services/SchemaService.cs new file mode 100644 index 0000000..71a595e --- /dev/null +++ b/HaDbMigration/Services/SchemaService.cs @@ -0,0 +1,127 @@ +using HaDbMigration.Configuration; +using HaDbMigration.Models; +using HaDbMigration.Services.Interfaces; +using Microsoft.Extensions.Logging; +using Npgsql; + +namespace HaDbMigration.Services; + +public sealed class SchemaService : ISchemaService +{ + private readonly MigrationOptions _options; + private readonly ILogger _logger; + + public SchemaService(MigrationOptions options, ILogger logger) + { + _options = options; + _logger = logger; + } + + public async Task ValidateTablesExistAsync( + IReadOnlyList 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 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 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); + } + } +} diff --git a/HaDbMigration/Services/SqliteReaderService.cs b/HaDbMigration/Services/SqliteReaderService.cs new file mode 100644 index 0000000..16596e4 --- /dev/null +++ b/HaDbMigration/Services/SqliteReaderService.cs @@ -0,0 +1,90 @@ +using System.Threading.Channels; +using HaDbMigration.Configuration; +using HaDbMigration.Models; +using HaDbMigration.Services.Interfaces; +using Microsoft.Data.Sqlite; +using Microsoft.Extensions.Logging; + +namespace HaDbMigration.Services; + +public sealed class SqliteReaderService : ISqliteReaderService +{ + private readonly MigrationOptions _options; + private readonly ILogger _logger; + private readonly string _connectionString; + + public SqliteReaderService(MigrationOptions options, ILogger logger) + { + _options = options; + _logger = logger; + _connectionString = new SqliteConnectionStringBuilder + { + DataSource = _options.SqlitePath, + Mode = SqliteOpenMode.ReadOnly, + }.ToString(); + } + + public async Task ReadTableAsync( + TableDescriptor table, + ChannelWriter> 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(_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(_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 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); + } +} diff --git a/HaDbMigration/Services/ValidationService.cs b/HaDbMigration/Services/ValidationService.cs new file mode 100644 index 0000000..80ad26a --- /dev/null +++ b/HaDbMigration/Services/ValidationService.cs @@ -0,0 +1,67 @@ +using HaDbMigration.Configuration; +using HaDbMigration.Models; +using HaDbMigration.Services.Interfaces; +using Microsoft.Extensions.Logging; + +namespace HaDbMigration.Services; + +public sealed class ValidationService : IValidationService +{ + private readonly ISqliteReaderService _sqliteReader; + private readonly IPostgresWriterService _postgresWriter; + private readonly MigrationOptions _options; + private readonly ILogger _logger; + + public ValidationService( + ISqliteReaderService sqliteReader, + IPostgresWriterService postgresWriter, + MigrationOptions options, + ILogger logger) + { + _sqliteReader = sqliteReader; + _postgresWriter = postgresWriter; + _options = options; + _logger = logger; + } + + public async Task> ValidateRowCountsAsync( + IReadOnlyList tables, + CancellationToken cancellationToken) + { + var tasks = tables.Select(table => ValidateTableAsync(table, cancellationToken)); + var results = await Task.WhenAll(tasks); + + return results; + } + + private async Task 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); + } +} diff --git a/HomeAssistantSDK.sln b/HomeAssistantSDK.sln index dc2e35c..4d6ef12 100644 --- a/HomeAssistantSDK.sln +++ b/HomeAssistantSDK.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeAssistant.Server", "HomeAssistant.Server\HomeAssistant.Server.csproj", "{D51DF7CC-5779-4E6F-9D02-10E8D083F468}" EndProject @@ -14,41 +14,130 @@ 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 + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {D51DF7CC-5779-4E6F-9D02-10E8D083F468}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D51DF7CC-5779-4E6F-9D02-10E8D083F468}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D51DF7CC-5779-4E6F-9D02-10E8D083F468}.Debug|x64.ActiveCfg = Debug|Any CPU + {D51DF7CC-5779-4E6F-9D02-10E8D083F468}.Debug|x64.Build.0 = Debug|Any CPU + {D51DF7CC-5779-4E6F-9D02-10E8D083F468}.Debug|x86.ActiveCfg = Debug|Any CPU + {D51DF7CC-5779-4E6F-9D02-10E8D083F468}.Debug|x86.Build.0 = Debug|Any CPU {D51DF7CC-5779-4E6F-9D02-10E8D083F468}.Release|Any CPU.ActiveCfg = Release|Any CPU {D51DF7CC-5779-4E6F-9D02-10E8D083F468}.Release|Any CPU.Build.0 = Release|Any CPU + {D51DF7CC-5779-4E6F-9D02-10E8D083F468}.Release|x64.ActiveCfg = Release|Any CPU + {D51DF7CC-5779-4E6F-9D02-10E8D083F468}.Release|x64.Build.0 = Release|Any CPU + {D51DF7CC-5779-4E6F-9D02-10E8D083F468}.Release|x86.ActiveCfg = Release|Any CPU + {D51DF7CC-5779-4E6F-9D02-10E8D083F468}.Release|x86.Build.0 = Release|Any CPU {DF115433-AE84-4C00-A0E7-08840E633CB2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DF115433-AE84-4C00-A0E7-08840E633CB2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DF115433-AE84-4C00-A0E7-08840E633CB2}.Debug|x64.ActiveCfg = Debug|Any CPU + {DF115433-AE84-4C00-A0E7-08840E633CB2}.Debug|x64.Build.0 = Debug|Any CPU + {DF115433-AE84-4C00-A0E7-08840E633CB2}.Debug|x86.ActiveCfg = Debug|Any CPU + {DF115433-AE84-4C00-A0E7-08840E633CB2}.Debug|x86.Build.0 = Debug|Any CPU {DF115433-AE84-4C00-A0E7-08840E633CB2}.Release|Any CPU.ActiveCfg = Release|Any CPU {DF115433-AE84-4C00-A0E7-08840E633CB2}.Release|Any CPU.Build.0 = Release|Any CPU + {DF115433-AE84-4C00-A0E7-08840E633CB2}.Release|x64.ActiveCfg = Release|Any CPU + {DF115433-AE84-4C00-A0E7-08840E633CB2}.Release|x64.Build.0 = Release|Any CPU + {DF115433-AE84-4C00-A0E7-08840E633CB2}.Release|x86.ActiveCfg = Release|Any CPU + {DF115433-AE84-4C00-A0E7-08840E633CB2}.Release|x86.Build.0 = Release|Any CPU {C7470849-2B14-4E4E-AE96-5A509CACA5AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C7470849-2B14-4E4E-AE96-5A509CACA5AA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C7470849-2B14-4E4E-AE96-5A509CACA5AA}.Debug|x64.ActiveCfg = Debug|Any CPU + {C7470849-2B14-4E4E-AE96-5A509CACA5AA}.Debug|x64.Build.0 = Debug|Any CPU + {C7470849-2B14-4E4E-AE96-5A509CACA5AA}.Debug|x86.ActiveCfg = Debug|Any CPU + {C7470849-2B14-4E4E-AE96-5A509CACA5AA}.Debug|x86.Build.0 = Debug|Any CPU {C7470849-2B14-4E4E-AE96-5A509CACA5AA}.Release|Any CPU.ActiveCfg = Release|Any CPU {C7470849-2B14-4E4E-AE96-5A509CACA5AA}.Release|Any CPU.Build.0 = Release|Any CPU + {C7470849-2B14-4E4E-AE96-5A509CACA5AA}.Release|x64.ActiveCfg = Release|Any CPU + {C7470849-2B14-4E4E-AE96-5A509CACA5AA}.Release|x64.Build.0 = Release|Any CPU + {C7470849-2B14-4E4E-AE96-5A509CACA5AA}.Release|x86.ActiveCfg = Release|Any CPU + {C7470849-2B14-4E4E-AE96-5A509CACA5AA}.Release|x86.Build.0 = Release|Any CPU {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E}.Debug|x64.ActiveCfg = Debug|Any CPU + {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E}.Debug|x64.Build.0 = Debug|Any CPU + {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E}.Debug|x86.ActiveCfg = Debug|Any CPU + {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E}.Debug|x86.Build.0 = Debug|Any CPU {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E}.Release|Any CPU.ActiveCfg = Release|Any CPU {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E}.Release|Any CPU.Build.0 = Release|Any CPU + {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E}.Release|x64.ActiveCfg = Release|Any CPU + {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E}.Release|x64.Build.0 = Release|Any CPU + {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E}.Release|x86.ActiveCfg = Release|Any CPU + {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E}.Release|x86.Build.0 = Release|Any CPU {4DB472EC-910B-4612-9457-E41709BB2F0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4DB472EC-910B-4612-9457-E41709BB2F0C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4DB472EC-910B-4612-9457-E41709BB2F0C}.Debug|x64.ActiveCfg = Debug|Any CPU + {4DB472EC-910B-4612-9457-E41709BB2F0C}.Debug|x64.Build.0 = Debug|Any CPU + {4DB472EC-910B-4612-9457-E41709BB2F0C}.Debug|x86.ActiveCfg = Debug|Any CPU + {4DB472EC-910B-4612-9457-E41709BB2F0C}.Debug|x86.Build.0 = Debug|Any CPU {4DB472EC-910B-4612-9457-E41709BB2F0C}.Release|Any CPU.ActiveCfg = Release|Any CPU {4DB472EC-910B-4612-9457-E41709BB2F0C}.Release|Any CPU.Build.0 = Release|Any CPU + {4DB472EC-910B-4612-9457-E41709BB2F0C}.Release|x64.ActiveCfg = Release|Any CPU + {4DB472EC-910B-4612-9457-E41709BB2F0C}.Release|x64.Build.0 = Release|Any CPU + {4DB472EC-910B-4612-9457-E41709BB2F0C}.Release|x86.ActiveCfg = Release|Any CPU + {4DB472EC-910B-4612-9457-E41709BB2F0C}.Release|x86.Build.0 = Release|Any CPU {D1FDF2F0-E8D2-4F00-95CA-1759047EA205}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D1FDF2F0-E8D2-4F00-95CA-1759047EA205}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D1FDF2F0-E8D2-4F00-95CA-1759047EA205}.Debug|x64.ActiveCfg = Debug|Any CPU + {D1FDF2F0-E8D2-4F00-95CA-1759047EA205}.Debug|x64.Build.0 = Debug|Any CPU + {D1FDF2F0-E8D2-4F00-95CA-1759047EA205}.Debug|x86.ActiveCfg = Debug|Any CPU + {D1FDF2F0-E8D2-4F00-95CA-1759047EA205}.Debug|x86.Build.0 = Debug|Any CPU {D1FDF2F0-E8D2-4F00-95CA-1759047EA205}.Release|Any CPU.ActiveCfg = Release|Any CPU {D1FDF2F0-E8D2-4F00-95CA-1759047EA205}.Release|Any CPU.Build.0 = Release|Any CPU + {D1FDF2F0-E8D2-4F00-95CA-1759047EA205}.Release|x64.ActiveCfg = Release|Any CPU + {D1FDF2F0-E8D2-4F00-95CA-1759047EA205}.Release|x64.Build.0 = Release|Any CPU + {D1FDF2F0-E8D2-4F00-95CA-1759047EA205}.Release|x86.ActiveCfg = Release|Any CPU + {D1FDF2F0-E8D2-4F00-95CA-1759047EA205}.Release|x86.Build.0 = Release|Any CPU {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Debug|x64.ActiveCfg = Debug|Any CPU + {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Debug|x64.Build.0 = Debug|Any CPU + {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Debug|x86.ActiveCfg = Debug|Any CPU + {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Debug|x86.Build.0 = Debug|Any CPU {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Release|Any CPU.ActiveCfg = Release|Any CPU {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Release|Any CPU.Build.0 = Release|Any CPU + {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Release|x64.ActiveCfg = Release|Any CPU + {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(NestedProjects) = preSolution + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection EndGlobal