Added migration tool

This commit is contained in:
Marius
2026-03-12 09:47:49 +02:00
parent 27648ae57c
commit b262d10ea4
35 changed files with 2579 additions and 2 deletions
@@ -0,0 +1,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<T> producer pattern
status: completed
- id: postgres-writer
content: Implement PostgresWriterService with Npgsql binary COPY and Channel<T> 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<T>` 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