diff --git a/homeassistant/components/recorder/migration.py b/homeassistant/components/recorder/migration.py index cf56c39a885..28952f127e2 100644 --- a/homeassistant/components/recorder/migration.py +++ b/homeassistant/components/recorder/migration.py @@ -161,7 +161,7 @@ def migrate_schema( "Database is about to correct DB schema errors: %s", ", ".join(sorted(schema_errors)), ) - statistics_correct_db_schema(engine, session_maker, schema_errors) + statistics_correct_db_schema(instance, engine, session_maker, schema_errors) def _create_index( diff --git a/homeassistant/components/recorder/statistics.py b/homeassistant/components/recorder/statistics.py index 303a925f9a0..dea454a5a33 100644 --- a/homeassistant/components/recorder/statistics.py +++ b/homeassistant/components/recorder/statistics.py @@ -2404,7 +2404,10 @@ def validate_db_schema( def correct_db_schema( - engine: Engine, session_maker: Callable[[], Session], schema_errors: set[str] + instance: Recorder, + engine: Engine, + session_maker: Callable[[], Session], + schema_errors: set[str], ) -> None: """Correct issues detected by validate_db_schema.""" from .migration import _modify_columns # pylint: disable=import-outside-toplevel @@ -2450,12 +2453,16 @@ def correct_db_schema( ) if f"{table.__tablename__}.µs precision" in schema_errors: # Attempt to convert datetime columns to µs precision + if instance.dialect_name == SupportedDialect.MYSQL: + datetime_type = "DATETIME(6)" + else: + datetime_type = "TIMESTAMP(6) WITH TIME ZONE" _modify_columns( session_maker, engine, table.__tablename__, [ - "last_reset DATETIME(6)", - "start DATETIME(6)", + f"last_reset {datetime_type}", + f"start {datetime_type}", ], ) diff --git a/tests/components/recorder/test_statistics.py b/tests/components/recorder/test_statistics.py index 376087fdb1e..d3a1c8b7fe0 100644 --- a/tests/components/recorder/test_statistics.py +++ b/tests/components/recorder/test_statistics.py @@ -1601,7 +1601,19 @@ async def test_validate_db_schema_fix_float_issue( @pytest.mark.parametrize("enable_statistics_table_validation", [True]) -@pytest.mark.parametrize("db_engine", ("mysql", "postgresql")) +@pytest.mark.parametrize( + "db_engine, modification", + ( + ("mysql", ["last_reset DATETIME(6)", "start DATETIME(6)"]), + ( + "postgresql", + [ + "last_reset TIMESTAMP(6) WITH TIME ZONE", + "start TIMESTAMP(6) WITH TIME ZONE", + ], + ), + ), +) @pytest.mark.parametrize( "table, replace_index", (("statistics", 0), ("statistics_short_term", 1)) ) @@ -1617,6 +1629,7 @@ async def test_validate_db_schema_fix_statistics_datetime_issue( hass, caplog, db_engine, + modification, table, replace_index, column, @@ -1664,7 +1677,6 @@ async def test_validate_db_schema_fix_statistics_datetime_issue( f"Database is about to correct DB schema errors: {table}.µs precision" in caplog.text ) - modification = ["last_reset DATETIME(6)", "start DATETIME(6)"] modify_columns_mock.assert_called_once_with(ANY, ANY, table, modification)