Skip to content

DateTime(Kind=UTC) being converted to local when inserting to TIMESTAMP WITHOUT TIME ZONE #1803

Closed

Description

@bharrison44

As per the documentation, a DateTime(Kind=UTC) should be sent as-is. I am seeing the opposite behaviour with Npgsql 3.2.6 and PostgreSQL 10.1.

With my Postgres servers default timezone of 'Australia/Brisbane', DateTime values with a kind of UTC are being converted to local time.

My test table:

CREATE TABLE public.ts_test (ts_type text NOT NULL, ts timestamp without time zone NOT NULL)

My insert code:

using (var command = connection.CreateCommand())
{
    command.CommandText = "INSERT INTO ts_test (ts_type, ts) VALUES (@type1, @ts1),  (@type2, @ts2), (@type3, @ts3)";
    command.Parameters.AddWithValue("type1", "UTC");
    command.Parameters.AddWithValue("ts1", new DateTime(2020, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
    command.Parameters.AddWithValue("type2", "Unspecified");
    command.Parameters.AddWithValue("ts2", new DateTime(2020, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
    command.Parameters.AddWithValue("type3", "Local");
    command.Parameters.AddWithValue("ts3", new DateTime(2020, 1, 1, 0, 0, 0, 0, DateTimeKind.Local));
    command.ExecuteNonQuery();
}

The results of this is:

SELECT * FROM ts_test;
   ts_type   |         ts
-------------+---------------------
 UTC         | 2020-01-01 10:00:00
 Unspecified | 2020-01-01 00:00:00
 Local       | 2020-01-01 00:00:00
(3 rows)

If however I run SET TIME ZONE 'utc'; before insert all DateTimes are inserted correctly.

SELECT * FROM ts_test;
   ts_type   |         ts
-------------+---------------------
 UTC         | 2020-01-01 00:00:00
 Unspecified | 2020-01-01 00:00:00
 Local       | 2020-01-01 00:00:00
(3 rows)

Setting the connection time zone to any other value also behaves consistently ie SET TIME ZONE '+4'; before insert results in:

SELECT * FROM ts_test;
   ts_type   |         ts
-------------+---------------------
 UTC         | 2020-01-01 04:00:00
 Unspecified | 2020-01-01 00:00:00
 Local       | 2020-01-01 00:00:00
(3 rows)

Specifying a NpgsqlDbType as Timestamp is also a way I found that results in correct behaviour, however if I am interpreting the documentation correctly the default value TimestampTZ should not perform any conversion, either.

command.Parameters.AddWithValue("ChangeTime1", NpgsqlDbType.Timestamp, new DateTime(2020, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));

The work around of setting the connections time zone before inserts will work for us, but it would be great to get some clarification on the intended behaviour and whether that is what is being observed here or what I believe is being described by the documentation.

Activity

  1. YohDeadfall commented on Mar 20, 2018

    @YohDeadfall
    Contributor

    @roji This is a bug because of:

    if (ts.IsFinite)
    return ts.ToDateTime();

    It's a timestamp without time zone. Therefore, the kind should beUnspecified and no conversions should be performed. If you agree I'll take care of this.

  2. roji commented on Mar 20, 2018

    @roji
    Member

    @YohDeadfall can you explain exactly what you mean? The code you show indeed takes an NpgsqlDateTime with Kind=Unspecified and calls ToDateTime() on it, where do you see any conversions being performed?

  3. YohDeadfall commented on Mar 20, 2018

    @YohDeadfall
    Contributor

    It's a mind frapping, though that it's DateTime.ToLocalTime(), do not mind.

  4. roji commented on Mar 20, 2018

    @roji
    Member

    It's a mind frapping, though that it's DateTime.ToLocalTime(), do not mind.

    No problem, these date/time timezone issues are really bad. Do you want to investigate this issue?

  5. YohDeadfall commented on Mar 20, 2018

    @YohDeadfall
    Contributor

    Npgsql transfers the first parameter value as timestamptz which is converted later to timestamp by PostgreSQL. It's a source of the problem:

    if (value is DateTime)
    {
    return ((DateTime)value).Kind == DateTimeKind.Utc
    ? GetByNpgsqlDbType(NpgsqlDbType.TimestampTz)
    : GetByNpgsqlDbType(NpgsqlDbType.Timestamp);
    }
    if (value is NpgsqlDateTime)
    {
    return ((NpgsqlDateTime)value).Kind == DateTimeKind.Utc
    ? GetByNpgsqlDbType(NpgsqlDbType.TimestampTz)
    : GetByNpgsqlDbType(NpgsqlDbType.Timestamp);
    }

    @roji I think the behavior should be changed to not take into account the date time kind at least for the DateTime type. The Kind property was a big mistake by Microsoft, but they do not have a time machine to change the design. dotnet/corefxlab#1901 (comment)

    @bharrison44 You can specify the parameter type directly like in the code below as a temporary workaround:

    command.Parameters.AddWithValue("ts1", NpgsqlDbType.Timestamp, new DateTime(2020, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
    
  6. YohDeadfall commented on Apr 7, 2018

    @YohDeadfall
    Contributor

    @roji It's a breaking change and a bug. I would like to hear your opinion on that problem and others too.

    Npgsql sends a DateTime as-is, but when the value has the UTC kind then the type is deduced as timestamptz. On the server side the value is converted to a timestamp using the server time zone. If the issue would be fixed, there will be another issue with storing timestamptz values which specified as DateTime because:

    • timestamp is used to store local time,
    • timestamptz is used to store UTC time,
    • there is an automatic conversion between them.

    SQL client doesn't have that problem since it doesn't use the Kind property, and SQL Server has no timestamptz-like type. It has datetimeoffset but there is no conversion between that type and datetime.

    From my point of view it would be better to have more obvious behavior and do not treat an UTC DateTime as a timestamptz value. The problem also affects the Noda Time plugin.

    /cc @divega @mj1856

  7. roji commented on Apr 8, 2018

    @roji
    Member

    For anyone interested in the history of all this behavior, see #347.

    First, I agree that the situation is messy - but I'm not sure that changing anything would make it better. Yes, DateTime.Kind was a mistake (I'm a big supporter of NodaTime), and yes, PostgreSQL's timestamp with time zone is problematic (although AFAIK it's mandated by the SQL standard which PG tries to conform to).

    Second, it's important to reiterate that the discussion is only about the default mapping, i.e. when NpgsqlDbType isn't specified. As mentioned above, it's always possible to explicitly send a timestamp or timestamptz by specifying the correct NpgsqlDbType.

    More to the point, the idea is that a DateTime with Kind=UTC is actually the only DateTime with a clear, unambiguous meaning which doesn't depend on the system time or anything else. The same is true for PostgreSQL's timestamptz, and this is why the mappings were set up this way.

    I admit that since the behavior was defined, we've seen many users stumbling with timestamptz in general, and that as time goes along I think there it should really be recommended against. However, I'm not sure that removing the DateTime.Utc to timestamptz mapping would really make things much better, so as to justify the breaking change. I'm open to thinking about this for 4.0.0 though.

    The problem also affects the Noda Time plugin.

    How so? The current implementation of the Nodatime plugin (not yet released) by default maps Instant and LocalDateTime to timestamp, and ZonedDateTime to timestamptz. Unlike with .NET DateTime, at least here the type separation is clean, and mapping doesn't depend on the value of a Kind property. The discussion with @jskeet about all of this took place in #546.

  8. added this to the 4.0 milestone on Apr 8, 2018
  9. tmenier commented on Apr 8, 2018

    @tmenier

    I'm not a PostgreSQL expert by any means, but I can confirm this is problematic with my AsyncPoco tests. I upgraded Npgsql from 2.x to 3.x (yes, long overdue), and now tests that insert a date with DateTimeKind.Utc are failing; they are always coming back as local time on SELECT. For column types, I have tried specifying timestamp, timestamp with time zone, and timestamp without time zone in column definitions and the result is the same in each case.

    Second, it's important to reiterate that the discussion is only about the default mapping, i.e. when NpgsqlDbType isn't specified.

    As you can imagine, in a micro-ORM library that supports many db platforms, you want to have as little platform-specific code as possible. As of now these tests are passing for MySql, SQL Server, SQLite, and Oracle, with no platform-specific date handling for any of them.

    Can you suggest a work-around? Otherwise, I'll probably just downgrade to 2.x. Thanks!

  10. YohDeadfall commented on Apr 10, 2018

    @YohDeadfall
    Contributor

    The current implementation of the Nodatime plugin (not yet released) by default maps Instant and LocalDateTime to timestamp, and ZonedDateTime to timestamptz. Unlike with .NET DateTime, at least here the type separation is clean, and mapping doesn't depend on the value of a Kind property.

    Indeed.

    The discussion with @jskeet about all of this took plaace in #546.

    Okay, it also makes sense, but it causes problems to other users. Therefore, I think keep the current behavior, but make it optional. This will allow all users to have the logic they want and migrate without drastic changes. We can add a new flag to the connection string which turns mapping DateTime using the Kind property. What do you think about that?

  11. roji commented on Apr 11, 2018

    @roji
    Member

    The discussion with @jskeet about all of this took plaace in #546.

    Okay, it also makes sense, but it causes problems to other users. Therefore, I think keep the current behavior, but make it optional. This will allow all users to have the logic they want and migrate without drastic changes. We can add a new flag to the connection string which turns mapping DateTime using the Kind property. What do you think about that?

    Does that mean that you find the current NodaTime plugin mapping strategy good? Because it still hasn't been released yet, and so it's easy to make any changes.

    I really hate connections string flags. Every time there's a question about how Npgsql should behave, there's the temptation of having another flag allowing both behaviors. This complicates the driver, makes it a bit unpredictable (since there are several different behaviors), creates more paths that need to be tested...

    Especially since 4.0 is coming up, I'd much rather define a single, good behavior, even if it breaks the behavior for some people (I know this is a little contradictory to what I wrote above). I'm still not really convinced that dropping the DateTimeKind.Utc behavior is the right thing, but I'm definitely open to it - more feedback from people would be helpful here.

  12. YohDeadfall commented on Apr 24, 2018

    @YohDeadfall
    Contributor

    Related:

    1. timestamptz should be read as DateTimeOffset with local timezone, not UTC timestamptz should be read as DateTimeOffset with local timezone, not UTC #1076
    2. Migrations AddColumn with DateTime type should generate timestamp with timezone (Migrations AddColumn with DateTime type should generate timestamp with timezone #1179)
  13. YohDeadfall commented on May 2, 2018

    @YohDeadfall
    Contributor

    @roji I think it would be much better if that feature of Npgsql was documented and the current behavior stayed the same.

  14. roji commented on May 2, 2018

    @roji
    Member

    @YohDeadfall I was thinking to sit down tomorrow and take a look at all the date/time stuff with a fresh mind, are you saying that you think we shouldn't change anything, just document?

  15. YohDeadfall commented on May 2, 2018

    @YohDeadfall
    Contributor

    Yes, because we have other parameter related issues too (for example #1894). I think there should be something like that.

  16. roji commented on May 2, 2018

    @roji
    Member

    Well, we do have this page and this one specifically for date/time. They do contain some inaccuracies (which we should fix) but do you think we need something else entirely?

  17. YohDeadfall commented on May 2, 2018

    @YohDeadfall
    Contributor

    Could we add a link into Parameters and rename Types to Type Mappings? I think the problem here is that everyone thinks that Types is about Npgsql classes and not about parameters (me too).

  18. roji commented on May 2, 2018

    @roji
    Member

    Sure, feel free to submit a PR with any improvements! The files are in the doc directory of this repo...

  19. self-assigned this
    on May 5, 2018
  20. roji commented on May 14, 2018

    @roji
    Member

    @YohDeadfall, I've done some more thinking about this and I think it may be a good idea to break the current behavior and simplify things. Based on the discussion, here's a proposal:

    Timestamp without time zone

    • By default DateTime is always sent as timestamp. No conversion is done. This is a breaking change.
    • timestamp is read as a DateTime with Kind=Unspecified. Same behavior as today.
    • It will no longer be possible to write DateTimeOffset to timestamp as it is in 3.x (trying to read currently throws an exception), I'm not sure why this was allowed in the first place. This is a breaking change.

    Timestamp with time zone

    • By default timestamptz reads as DateTime with Kind=Local. Same behavior as today.
    • timestamptz is also readable as DateTimeOffset, but as @YohDeadfall mentioned it should have the local timezone, not UTC. Note that this isn't exactly the PostgreSQL behavior - PostgreSQL converts timestamptz according to the PG session timezone, which isn't the same as the machine's local timezone.
    • By default DateTimeOffset is always sent as timestamptz, converting to UTC before sending. This is the current behavior.
    • It's possible to send DateTime as timestamptz by specifying NpgsqlDbType.TimestampTz. When this is done, if DateTime.Kind=Local, we convert to UTC before sending. This is the current behavior, which we're retaining.

    Note that the 3.x DateTimeKind.Utc special behavior is the only current case where mapping depends on a value's content, as opposed to its type. This would remove that, making the driver more consistent and understandable.

    @YohDeadfall I'd like to have your opinion - and quickly if possible, if we do this we must do it very soon (ideally I'd like to do an rc2 very soon including this new behavior).

    One specific comment: above you wrote "Migrations AddColumn with DateTime type should generate timestamp with timezone (#1179)", but I can't picture any scenario where that really makes sense. First, we can't look at the Kind when making EF mapping decisions (we only have the type, no instance), which is why it selects timestamp and not timestamptz. And the vast majority of use cases just want DateTime to be a database timestamp. I can't see any reason to change this (not to mention the EF breakage that would ensue).

  21. YohDeadfall commented on May 14, 2018

    @YohDeadfall
    Contributor

    Okay, it's fine to me.

  22. roji commented on May 20, 2018

    @roji
    Member

    Fixed via #1940 for 4.0.

  23. removed this from the 4.0 milestone on May 20, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions