Forcing times in the database to UTC?


#1

Howdy All,

I’d like to make sure that every timestamp that is stored in the
database is in UTC. I set ActiveRecord::Base.default_timezone to :utc
and that takes care of the automatically-managed updated_at and
created_at fields, but the rest are still at the mercy of the code
remembering to make sure that times are converted to UTC before calling
save on the model.

At first glance, it seems that forcing the developer to manually
convert ensure that all times are in UTC before saving is error prone.
Wouldn’t it be simpler to force all times to UTC on their way to being
stored in the database if default_timezone == :utc?

I’ve patched
activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
to have the quote() method covert Time and DateTime objects to UTC
before producting the quoted value for use with the database:

      ....
      when Time, DateTime
        if ActiveRecord::Base.default_timezone == :utc
          # Make sure we've got UTC going into the database
          "'#{quoted_date(value.dup.utc)}'"
        else
          "'#{quoted_date(value)}'"
        end
      ....

The dup is because the utc method is side-effecting and I prefer not to
catch the caller by surprise with a changed value.

This works for me and passes the ActiveRecord unit tests with the MySQL
adaptor.

My question is: is this a reasonable approach to solving this problem?
It’s a simple change, so I’m wondering why it hasn’t been done in the
past… Some unintended consequence I’m not thinking of?

Any insight would be appreciated.

Thanks,
Greg