Skip to content

Commit

Permalink
Cast Time/Timestamp to Rails application timezone.
Browse files Browse the repository at this point in the history
  • Loading branch information
prurph committed Mar 7, 2017
1 parent ef91d09 commit a765c3b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 15 deletions.
7 changes: 7 additions & 0 deletions lib/active_record/connection_adapters/odbc_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -113,6 +114,7 @@ def reconnect!
else
ODBC::Database.new.drvconnect(@config[:driver])
end
configure_time_options(@connection)
super
end
alias reset! reconnect!
Expand Down Expand Up @@ -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
16 changes: 1 addition & 15 deletions lib/odbc_adapter/type_caster.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit a765c3b

Please sign in to comment.