From a765c3be4154f0b1ee41aef46ce9247bbcb92a05 Mon Sep 17 00:00:00 2001 From: Prescott Murphy Date: Tue, 7 Mar 2017 13:37:16 -0500 Subject: [PATCH] Cast Time/Timestamp to Rails application timezone. --- .../connection_adapters/odbc_adapter.rb | 7 +++++++ lib/odbc_adapter/type_caster.rb | 16 +--------------- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/lib/active_record/connection_adapters/odbc_adapter.rb b/lib/active_record/connection_adapters/odbc_adapter.rb index 8e29816b..c8faefcb 100644 --- a/lib/active_record/connection_adapters/odbc_adapter.rb +++ b/lib/active_record/connection_adapters/odbc_adapter.rb @@ -79,6 +79,7 @@ class ODBCAdapter < AbstractAdapter attr_reader :database_metadata def initialize(connection, logger, config, database_metadata) + configure_time_options(connection) super(connection, logger, config) @database_metadata = database_metadata end @@ -113,6 +114,7 @@ def reconnect! else ODBC::Database.new.drvconnect(@config[:driver]) end + configure_time_options(@connection) super end alias reset! reconnect! @@ -189,6 +191,11 @@ def alias_type(map, new_type, old_type) map.lookup(old_type, *args) end end + + # Ensure ODBC is mapping time-based fields to native ruby objects in UTC + def configure_time_options(connection) + connection.use_time = true + end end end end diff --git a/lib/odbc_adapter/type_caster.rb b/lib/odbc_adapter/type_caster.rb index 4839b51a..4da3e4c2 100644 --- a/lib/odbc_adapter/type_caster.rb +++ b/lib/odbc_adapter/type_caster.rb @@ -4,7 +4,6 @@ class TypeCaster # SQL types to an equivalent Ruby type; with the exception of # SQL_DATE, SQL_TIME and SQL_TIMESTAMP. TYPES = [ - ODBC::SQL_DATE, ODBC::SQL_TIME, ODBC::SQL_TIMESTAMP ].freeze @@ -16,20 +15,7 @@ def initialize(idx) end def cast(value) - case value - when ODBC::TimeStamp - Time.gm(value.year, value.month, value.day, value.hour, value.minute, value.second) - when ODBC::Time - now = DateTime.now - Time.gm(now.year, now.month, now.day, value.hour, value.minute, value.second) - when ODBC::Date - Date.new(value.year, value.month, value.day) - else - value - end - rescue - # Handle pre-epoch dates - DateTime.new(value.year, value.month, value.day, value.hour, value.minute, value.second) + value.in_time_zone end # Build a list of casters from a list of columns