From 477bc46bfe1d7e1c056a4bb4aaa72d452315c160 Mon Sep 17 00:00:00 2001 From: Flavio Percoco Date: Thu, 6 Mar 2014 18:08:22 +0100 Subject: [PATCH] Set time_zone to UTC on MySQL MySQL uses UTC for all date fields but other operations like `now()` use the timezone of the server. This patch changes the timezone of the connection to UTC when the connection is first established. There's space for improvement here. For instance, we could try to avoid doing this for every new connection and let the operator configure it on the server side. We could also use `CONVERT_TZ` on every query using `now()`. Change-Id: I2e8415dbb9a6ce19d3a66f3226756094b3e0f6a4 Partial-bug: #1288820 --- marconi/queues/storage/sqlalchemy/driver.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/marconi/queues/storage/sqlalchemy/driver.py b/marconi/queues/storage/sqlalchemy/driver.py index 692583e81..afd4ac5f3 100644 --- a/marconi/queues/storage/sqlalchemy/driver.py +++ b/marconi/queues/storage/sqlalchemy/driver.py @@ -47,6 +47,12 @@ class DataDriver(storage.DataDriverBase): # to ensure FK are treated correctly by sqlite. conn.execute('pragma foreign_keys=ON') + def _mysql_on_connect(self, conn, record): + # NOTE(flaper87): This is necesary in order + # to ensure that all date operations in mysql + # happen in UTC, `now()` for example. + conn.query('SET time_zone = "+0:00"') + @decorators.lazy_property(write=False) def engine(self, *args, **kwargs): uri = self.sqlalchemy_conf.uri @@ -58,6 +64,10 @@ class DataDriver(storage.DataDriverBase): sa.event.listen(engine, 'connect', self._sqlite_on_connect) + if uri.startswith('mysql://'): + sa.event.listen(engine, 'connect', + self._mysql_on_connect) + tables.metadata.create_all(engine, checkfirst=True) return engine