Repository navigation
Description
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
YohDeadfall commentedon Mar 20, 2018
@roji This is a bug because of:
npgsql/src/Npgsql/TypeHandlers/DateTimeHandlers/TimestampHandler.cs
Lines 76 to 77 in 5a07635
It's a
timestamp without time zone. Therefore, the kind should beUnspecifiedand no conversions should be performed. If you agree I'll take care of this.roji commentedon Mar 20, 2018
@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?YohDeadfall commentedon Mar 20, 2018
It's a mind frapping, though that it's
DateTime.ToLocalTime(), do not mind.roji commentedon Mar 20, 2018
No problem, these date/time timezone issues are really bad. Do you want to investigate this issue?
YohDeadfall commentedon Mar 20, 2018
Npgsql transfers the first parameter value as
timestamptzwhich is converted later totimestampby PostgreSQL. It's a source of the problem:npgsql/src/Npgsql/TypeMapping/ConnectorTypeMapper.cs
Lines 137 to 149 in 5a07635
@roji I think the behavior should be changed to not take into account the date time kind at least for the
DateTimetype. TheKindproperty 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:
YohDeadfall commentedon Apr 7, 2018
@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
DateTimeas-is, but when the value has the UTC kind then the type is deduced astimestamptz. On the server side the value is converted to atimestampusing the server time zone. If the issue would be fixed, there will be another issue with storingtimestamptzvalues which specified asDateTimebecause:timestampis used to store local time,timestamptzis used to store UTC time,SQL client doesn't have that problem since it doesn't use the
Kindproperty, and SQL Server has notimestamptz-like type. It hasdatetimeoffsetbut there is no conversion between that type anddatetime.From my point of view it would be better to have more obvious behavior and do not treat an UTC
DateTimeas atimestamptzvalue. The problem also affects the Noda Time plugin./cc @divega @mj1856
roji commentedon Apr 8, 2018
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.Kindwas a mistake (I'm a big supporter of NodaTime), and yes, PostgreSQL'stimestamp with time zoneis 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
timestamportimestamptzby 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
timestamptzin 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 totimestamptzmapping 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.How so? The current implementation of the Nodatime plugin (not yet released) by default maps
InstantandLocalDateTimetotimestamp, andZonedDateTimetotimestamptz. Unlike with .NETDateTime, at least here the type separation is clean, and mapping doesn't depend on the value of aKindproperty. The discussion with @jskeet about all of this took place in #546.tmenier commentedon Apr 8, 2018
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.Utcare failing; they are always coming back as local time on SELECT. For column types, I have tried specifyingtimestamp,timestamp with time zone, andtimestamp without time zonein column definitions and the result is the same in each case.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!
YohDeadfall commentedon Apr 10, 2018
Indeed.
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
DateTimeusing theKindproperty. What do you think about that?roji commentedon Apr 11, 2018
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.Utcbehavior is the right thing, but I'm definitely open to it - more feedback from people would be helpful here.YohDeadfall commentedon Apr 24, 2018
Related:
timestamptzshould be read asDateTimeOffsetwith local timezone, not UTC timestamptz should be read as DateTimeOffset with local timezone, not UTC #1076AddColumnwithDateTimetype should generatetimestamp with timezone(Migrations AddColumn with DateTime type should generate timestamp with timezone #1179)YohDeadfall commentedon May 2, 2018
@roji I think it would be much better if that feature of Npgsql was documented and the current behavior stayed the same.
roji commentedon May 2, 2018
@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?
YohDeadfall commentedon May 2, 2018
Yes, because we have other parameter related issues too (for example #1894). I think there should be something like that.
roji commentedon May 2, 2018
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?
YohDeadfall commentedon May 2, 2018
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).
roji commentedon May 2, 2018
Sure, feel free to submit a PR with any improvements! The files are in the doc directory of this repo...
roji commentedon May 14, 2018
@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
timestamp. No conversion is done. This is a breaking change.timestampis read as aDateTimewithKind=Unspecified. Same behavior as today.DateTimeOffsettotimestampas 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
DateTimewithKind=Local. Same behavior as today.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.timestamptz, converting to UTC before sending. This is the current behavior.timestamptzby specifyingNpgsqlDbType.TimestampTz. When this is done, ifDateTime.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
timestampand nottimestamptz. 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).YohDeadfall commentedon May 14, 2018
Okay, it's fine to me.
roji commentedon May 20, 2018
Fixed via #1940 for 4.0.