Fixed #26712 -- Avoided unnecessary SET TIMEZONE queries on PostgreSQL.

A change of the USE_TZ or TIME_ZONE settings doesn't necessarily require a
change to the active connections' timezones.
This commit is contained in:
Simon Charette 2016-06-05 23:46:28 -04:00
parent 6a316423df
commit b484f167be
3 changed files with 20 additions and 12 deletions

View File

@ -88,6 +88,13 @@ class BaseDatabaseWrapper(object):
# is called? # is called?
self.run_commit_hooks_on_set_autocommit_on = False 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 @cached_property
def timezone(self): def timezone(self):
""" """

View File

@ -192,17 +192,21 @@ class DatabaseWrapper(BaseDatabaseWrapper):
return connection 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): def init_connection_state(self):
self.connection.set_client_encoding('UTF8') self.connection.set_client_encoding('UTF8')
conn_timezone_name = self.connection.get_parameter_status('TimeZone') timezone_changed = self.ensure_timezone()
if timezone_changed:
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()
# Commit after setting the time zone (see #17062) # Commit after setting the time zone (see #17062)
if not self.get_autocommit(): if not self.get_autocommit():
self.connection.commit() self.connection.commit()

View File

@ -69,10 +69,7 @@ def update_connections_time_zone(**kwargs):
del conn.timezone_name del conn.timezone_name
except AttributeError: except AttributeError:
pass pass
tz_sql = conn.ops.set_time_zone_sql() conn.ensure_timezone()
if tz_sql and conn.timezone_name:
with conn.cursor() as cursor:
cursor.execute(tz_sql, [conn.timezone_name])
@receiver(setting_changed) @receiver(setting_changed)