diff --git a/django/db/backends/base/base.py b/django/db/backends/base/base.py index f186e3b10b..fcafa5f71a 100644 --- a/django/db/backends/base/base.py +++ b/django/db/backends/base/base.py @@ -88,6 +88,13 @@ class BaseDatabaseWrapper(object): # is called? self.run_commit_hooks_on_set_autocommit_on = False + def ensure_timezone(self): + """ + Ensure the connection's timezone is set to `self.timezone_name` and + return whether it changed or not. + """ + return False + @cached_property def timezone(self): """ diff --git a/django/db/backends/postgresql/base.py b/django/db/backends/postgresql/base.py index 8819c39d31..90f28703af 100644 --- a/django/db/backends/postgresql/base.py +++ b/django/db/backends/postgresql/base.py @@ -192,17 +192,21 @@ class DatabaseWrapper(BaseDatabaseWrapper): return connection + def ensure_timezone(self): + self.ensure_connection() + conn_timezone_name = self.connection.get_parameter_status('TimeZone') + timezone_name = self.timezone_name + if timezone_name and conn_timezone_name != timezone_name: + with self.connection.cursor() as cursor: + cursor.execute(self.ops.set_time_zone_sql(), [timezone_name]) + return True + return False + def init_connection_state(self): self.connection.set_client_encoding('UTF8') - conn_timezone_name = self.connection.get_parameter_status('TimeZone') - - if self.timezone_name and conn_timezone_name != self.timezone_name: - cursor = self.connection.cursor() - try: - cursor.execute(self.ops.set_time_zone_sql(), [self.timezone_name]) - finally: - cursor.close() + timezone_changed = self.ensure_timezone() + if timezone_changed: # Commit after setting the time zone (see #17062) if not self.get_autocommit(): self.connection.commit() diff --git a/django/test/signals.py b/django/test/signals.py index 62b386268c..70b20625ff 100644 --- a/django/test/signals.py +++ b/django/test/signals.py @@ -69,10 +69,7 @@ def update_connections_time_zone(**kwargs): del conn.timezone_name except AttributeError: pass - tz_sql = conn.ops.set_time_zone_sql() - if tz_sql and conn.timezone_name: - with conn.cursor() as cursor: - cursor.execute(tz_sql, [conn.timezone_name]) + conn.ensure_timezone() @receiver(setting_changed)