From c9a7c94d8ff9f20d751591de68814f887e44ab6e Mon Sep 17 00:00:00 2001 From: Karen Tracey Date: Wed, 25 Nov 2020 12:26:09 -0500 Subject: [PATCH 1/2] When writing to MS SQL, use special DATETIME2... ...type for datetime objects. This avoids problems with the restricted year range of default datetime type for MS SQL (1753 is oldest year allowed for that type). --- commcare_export/writers.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/commcare_export/writers.py b/commcare_export/writers.py index fd104755..d46016e1 100644 --- a/commcare_export/writers.py +++ b/commcare_export/writers.py @@ -357,7 +357,10 @@ def best_type_for(self, val): if isinstance(val, bool): return sqlalchemy.Boolean() elif isinstance(val, datetime.datetime): - return sqlalchemy.DateTime() + if self.is_mssql: + return sqlalchemy.dialects.mssql.DATETIME2() + else: + return sqlalchemy.DateTime() elif isinstance(val, datetime.date): return sqlalchemy.Date() From 6361d301875843bab2c48e5e151476209d09bb91 Mon Sep 17 00:00:00 2001 From: Karen Tracey Date: Wed, 25 Nov 2020 15:38:19 -0500 Subject: [PATCH 2/2] Adjust a test to acocunt for different way... ...datetime2 is formatted to text than datetime by MS SQL Server. --- tests/test_writers.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/test_writers.py b/tests/test_writers.py index b770af3d..befbd84a 100644 --- a/tests/test_writers.py +++ b/tests/test_writers.py @@ -281,9 +281,8 @@ def test_change_type(self, writer): expected['bazzle']['c'] = '0' if 'pyodbc' in writer.connection.engine.driver: expected['bazzle']['c'] = '0' - # couldn't figure out how to make SQL Server convert date to ISO8601 - # see https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017#date-and-time-styles - expected['bazzle']['e'] = 'May 1 2014 11:16AM' + # MSSQL includes fractional seconds in returned value. + expected['bazzle']['e'] = '2014-05-01 11:16:45.0000000' for id, row in result.items(): assert id in expected