Rails/Postgresql SQL differences w/ Dates

后端 未结 1 602
轮回少年
轮回少年 2020-12-20 21:37

When running the following query in psql I get back 7 results:

SELECT generate_series(\'2012-10-14\', CURRENT_DATE, interval \'1 day\'); # 7
<
相关标签:
1条回答
  • 2020-12-20 22:03

    The version of generate_series that you're using is working with timestamps, not dates. So your '2012-10-14' and current_date are getting converted to timestamp with time zones and generate_series is producing a set of timestamp with time zones; compare these:

    => select generate_series('2012-10-14', current_date, '1 day');
        generate_series     
    ------------------------
     2012-10-14 00:00:00-07
     2012-10-15 00:00:00-07
     2012-10-16 00:00:00-07
     2012-10-17 00:00:00-07
     2012-10-18 00:00:00-07
     2012-10-19 00:00:00-07
     2012-10-20 00:00:00-07
    (7 rows)
    
    => select generate_series('2012-10-14', current_date::timestamp, '1 day');
       generate_series   
    ---------------------
     2012-10-14 00:00:00
     2012-10-15 00:00:00
     2012-10-16 00:00:00
     2012-10-17 00:00:00
     2012-10-18 00:00:00
     2012-10-19 00:00:00
     2012-10-20 00:00:00
    (7 rows)
    

    The first one has time zones, the second one doesn't.

    But, the current_date always gets converted to a timestamp with the database session's time zone adjustment applied. The Rails session will talk to the database in UTC, your psql session is probably using ET.

    If you manually specify the current date and explicitly work with timestamps:

    select generate_series('2012-10-14'::timestamp, '2012-10-20'::timestamp, '1 day')
    

    then you'll get the same seven results in both because there's no time zone in sight to make a mess of things.

    The easiest way to ignore time zones is to use the integer version of generate_series and the fact that adding an integer to a date treats the integer as a number of days:

    select '2012-10-14'::date + generate_series(0, 6)
    

    That will give you the same seven days without time zone interference. You can still use the current_date (which has no time zone since SQL dates don't have time zones) by noting that the difference between two dates is the number of days between them (an integer):

    => select '2012-10-14'::date + generate_series(0, current_date - '2012-10-14');
      ?column?  
    ------------
     2012-10-14
     2012-10-15
     2012-10-16
     2012-10-17
     2012-10-18
     2012-10-19
     2012-10-20
    (7 rows)
    

    and from Rails:

    > pp ActiveRecord::Base.connection.execute("select '2012-10-14'::date + generate_series(0, 6)").to_a
    [{"?column?"=>"2012-10-14"},
     {"?column?"=>"2012-10-15"},
     {"?column?"=>"2012-10-16"},
     {"?column?"=>"2012-10-17"},
     {"?column?"=>"2012-10-18"},
     {"?column?"=>"2012-10-19"},
     {"?column?"=>"2012-10-20"}]
    

    BTW, I hate time zones, hate and despise them.

    0 讨论(0)
提交回复
热议问题