seed_dump icon indicating copy to clipboard operation
seed_dump copied to clipboard

DateTime is not set to UTC on seed's create command

Open andrewchen5678 opened this issue 8 years ago • 3 comments

Hi, when I export data with DateTime in postgresql, and import again, the resulting timestamp gets shifted by the timezone offset. For example, I have an object in the database with last_accessed set to "2016-08-12 02:20:20" in the database, which is UTC timezone, when I run puts SeedDump.dump(SessionUser.order(id: :desc)), it becomes this:

SessionUser.create!([
  {last_accessed: "2016-08-12 02:20:20", visitor_tag: "57aa76e706715e3bc6f3d2c3", using_promo_code: nil}
])

If I run this to seed data, it becomes last_accessed "2016-08-12 09:20:20" instead in the database when I run it on a machine with pacific timezone.

andrewchen5678 avatar Aug 19 '16 23:08 andrewchen5678

Hi @andrewchen5678 . If your datetime does not store timezone, should seed_dump know about it ?

kofronpi avatar May 04 '17 13:05 kofronpi

How did you solve this bug? When I do the SeedDump.dump it writes the file with the UTC time, without timezone!

So when loading it back to the database my app believes they are in app's timezone instead of utc

Example:

my timezone is America/Santiago (UTC-4)

if it is 1 PM in santiago, it is 5 pm in UTC

When I Dump it, the date will become 5pm on the file. (which is UTC, but no timezone explicitly set on the file)

When importing it, will be inserted as 5pm America santiago which will be 9pm UTC

I think the export to the file should include the timezone

Like this:

2018-07-11T13:00:00.000-04:00

silva96 avatar Jul 11 '18 20:07 silva96

I've experienced the same issue and managed to fix it:

You dump records, load seeds, dump again - ALL dates shifted by time zone. Here is the monkey-patch you can use if you have the same issue:

    class SeedDump
      module DumpMethods
        def value_to_s(value)
          value = case value
          when BigDecimal, IPAddr
            value.to_s
          when Date, Time, DateTime
            value.to_s(:iso8601)
          when Range
            range_to_string(value)
          when ->(v) { v.class.ancestors.map(&:to_s).include?('RGeo::Feature::Instance') }
            value.to_s
          else
            value
          end

          value.inspect
        end
      end
    end

Note key part is: value.to_s(:iso8601) This way it includes time zone information in a dump

Just place it into config/initializers/seeds_dump.rb

I would've submitted PR but it looks like the project is abandoned (but still works), so no use in doing that

dimitrypo avatar Oct 06 '21 14:10 dimitrypo