From db503c0daa647eda342f75f1648dfa54b045eb04 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 9 Feb 2023 11:39:45 -0600 Subject: [PATCH] Always use UTC time for the MariaDB/MySQL session (#87583) --- homeassistant/components/recorder/migration.py | 6 +++--- homeassistant/components/recorder/util.py | 3 +++ tests/components/recorder/test_util.py | 3 ++- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/recorder/migration.py b/homeassistant/components/recorder/migration.py index b7df00175e9..ee319aaf38b 100644 --- a/homeassistant/components/recorder/migration.py +++ b/homeassistant/components/recorder/migration.py @@ -996,7 +996,7 @@ def _migrate_columns_to_timestamp( text( "UPDATE events set time_fired_ts=" "IF(time_fired is NULL,0," - "UNIX_TIMESTAMP(CONVERT_TZ(time_fired,'+00:00',@@global.time_zone))" + "UNIX_TIMESTAMP(time_fired)" ") " "where time_fired_ts is NULL " "LIMIT 250000;" @@ -1009,10 +1009,10 @@ def _migrate_columns_to_timestamp( text( "UPDATE states set last_updated_ts=" "IF(last_updated is NULL,0," - "UNIX_TIMESTAMP(CONVERT_TZ(last_updated,'+00:00',@@global.time_zone)) " + "UNIX_TIMESTAMP(last_updated) " "), " "last_changed_ts=" - "UNIX_TIMESTAMP(CONVERT_TZ(last_changed,'+00:00',@@global.time_zone)) " + "UNIX_TIMESTAMP(last_changed) " "where last_updated_ts is NULL " "LIMIT 250000;" ) diff --git a/homeassistant/components/recorder/util.py b/homeassistant/components/recorder/util.py index bd5bcf5f20f..3fc41fe22e5 100644 --- a/homeassistant/components/recorder/util.py +++ b/homeassistant/components/recorder/util.py @@ -543,6 +543,9 @@ def setup_connection_for_dialect( or MARIA_DB_107 <= version < MARIADB_WITH_FIXED_IN_QUERIES_107 or MARIA_DB_108 <= version < MARIADB_WITH_FIXED_IN_QUERIES_108 ) + + # Ensure all times are using UTC to avoid issues with daylight savings + execute_on_connection(dbapi_connection, "SET time_zone = '+00:00'") elif dialect_name == SupportedDialect.POSTGRESQL: # Historically we have marked PostgreSQL as having slow range in select # but this may not be true for all versions. We should investigate diff --git a/tests/components/recorder/test_util.py b/tests/components/recorder/test_util.py index c9e91df4187..ba1ec5bb84b 100644 --- a/tests/components/recorder/test_util.py +++ b/tests/components/recorder/test_util.py @@ -203,9 +203,10 @@ def test_setup_connection_for_dialect_mysql(mysql_version): util.setup_connection_for_dialect(instance_mock, "mysql", dbapi_connection, True) - assert len(execute_args) == 2 + assert len(execute_args) == 3 assert execute_args[0] == "SET session wait_timeout=28800" assert execute_args[1] == "SELECT VERSION()" + assert execute_args[2] == "SET time_zone = '+00:00'" @pytest.mark.parametrize(