Skip to content

Fix using Unspecified for pg's UTC data - #1051

Closed
cdwiegand wants to merge 1 commit into
npgsql:developfrom
cdwiegand:patch-1
Closed

cdwiegand wants to merge 1 commit into
npgsql:developfrom
cdwiegand:patch-1

Conversation

@cdwiegand

Copy link
Copy Markdown

This specifies the DateTime Kind property instead of returning Unspecified when querying a postgresql server. Now it returns UTC so a programmer can KNOW it's UTC and not maybe local time.

This specifies the DateTime Kind property instead of returning Unspecified when querying a postgresql server. Now it returns UTC so a programmer can KNOW it's UTC and not maybe local time.
@Emill

Emill commented Apr 27, 2016

Copy link
Copy Markdown
Contributor

Why would it be UTC? The "timestamp without time zone" is exactly that - no time zone specified so nobody knows (except the programmer).

@roji

roji commented Apr 28, 2016

Copy link
Copy Markdown
Member

Agree with @Emill - timestamp without time zone means exactly that we know nothing about the time zone (unlike timestamp with time zone)... If you're interested in learning more about all this you can check out the discussions in #347 (beware, it's long and painful).

Am closing this but feel free to continue the conversation here.

@roji roji closed this Apr 28, 2016
@roji

roji commented Apr 28, 2016

Copy link
Copy Markdown
Member

Note that if the programmer happens to know that a timestamp without time zone is UTC, they can (and should) perform the conversion in C# by creating a new DateTime with Kind UTC...

@cdwiegand

Copy link
Copy Markdown
Author

So my problem is the website says it returns a DateTime with Kind of UTC, and that is definitely NOT true. I based my code on what that said, and a review of the code finds something else. Very frustrating on my side. I'm also finding that if I SET TIMEZONE 'US/Denver', and update a timestamptz field with a DateTime where Kind is UTC it's still adding 6 hours, causing my times to slowly shift forward. I think it can be traced down to if a timestamptz is read, a DateTime of Kind Unspecified is returned by the code, but when that same variable is passed into an UPDATE or INSERT command, npgsql appears to be treating it as a local time and not UTC. Unspecified needs to be treated the same on both sides - either it's assumed local or it's assumed UTC, not both. I agree that this patch is ill-advised, and recall it, but I will make another patch that treats Unspecified the same as UTC instead of mixing them.

@roji

roji commented May 7, 2016

Copy link
Copy Markdown
Member

@cdwiegand, can you please post some code illustrating the issues you're seeing? The DateTime situation is indeed complicated - read the Npgsql docs carefully, and also the PostgreSQL docs.

I'd like to help you, but I can't do it without seeing any code.

@cdwiegand

Copy link
Copy Markdown
Author

Sure, here ya go:

// assumptions, rawConn is a NpgsqlConnection already setup
            // server is at UTC timezone (Amazon RDS setup, 9.4)
            // note that LOCAL on my machine is US/Denver, -07 offset, 
            // NYC is where client is located though, so -05 offset desired, set EACH time open conn!
            // testing with a date of 5/1/2016 noon @ NYC
            DateTime actualDate = new DateTime(2016, 5, 1, 12, 0, 0, DateTimeKind.Unspecified); 
            // I don't want it converted, as it's neither Local nor UTC, I'm already speaking NYC time here

            rawConn.Open();
            Npgsql.NpgsqlCommand cmd = rawConn.CreateCommand();
            cmd.CommandText = "SET TIME ZONE 'America/New_York'";
            // we promise to speak in NYC time, and to give Unspecified DateTime.Kind's
            cmd.ExecuteNonQuery();

            cmd = rawConn.CreateCommand();
            cmd.CommandText = "CREATE TABLE tmp_test (the_time timestamptz)";
            cmd.ExecuteNonQuery();

            cmd = rawConn.CreateCommand();
            cmd.CommandText = "INSERT INTO tmp_test VALUES (:one)";
            cmd.Parameters.AddWithValue("one", actualDate);
            cmd.ExecuteNonQuery();
            // copy paste from pgAdmin3: 2016-05-01 10:00:00-06, so that's working well

            cmd = rawConn.CreateCommand();
            cmd.CommandText = "SELECT * FROM tmp_test";
            Npgsql.NpgsqlDataAdapter da = new Npgsql.NpgsqlDataAdapter(cmd);
            System.Data.DataTable dt = new System.Data.DataTable();
            da.Fill(dt);
            rawConn.Close();

            // ok, now did we get back that same time? we should, we haven't changed the timezone...
            DateTime testDate = (DateTime)dt.Rows[0]["the_time"];
            if (testDate.Kind != DateTimeKind.Unspecified) throw new Exception("Pg can't know our timezone, so FAIL!"); // this passes
            if (actualDate.Subtract(testDate).TotalSeconds != 0) throw new Exception("Didn't get what we sent in!"); // this DOESNT
            // copy paste from Debug: 5/1/2016 10:00:00 AM
            // which means npgsql is giving me LOCAL time, even though it's Kind == Unspecified

I think this is caused by line 47 of src/Npgsql/TypeHandlers/DateTimeHandlers/TimeStampTzHandler.cs:

                if (ts.IsFinite)
                    return ts.DateTime.ToLocalTime();

Npgsql is converting to my box's local time, but Kind == Unspecified. Additionally I'm already specifying a time zone I want all of my dates in..

@roji

roji commented May 9, 2016

Copy link
Copy Markdown
Member

I've looked at your example, and there's some problematic stuff going on indeed, but not exactly where you'd think. Date/time is really confusing in Npgsql/PostgreSQL because .NET date/time concepts don't map well to PostgreSQL, and there's also some poor naming involved. I'll explain.

First off, you're using a timestamptz column. In PostgreSQL, timestamptz means something like "we're going to assume this timestamp is UTC, please perform a conversion to my local timezone when I fetch it". Now, usually "my local timezone" is the TIME ZONE variable you set - this is why your pgAdmin returned 2016-05-01 10:00:00-06 (notice the -06 at the end, which corresponds to Denver).

Now, Npgsql uses binary encoding to talk to PostgreSQL, not text (which is what pgAdmin uses). When returning data in binary, PostgreSQL does not apply timezone conversions - it simply sends whatever it has in its table. So, to make things look and feel like standard "text mode" PostgreSQL, when retrieving a timestamptz Npgsql converts it to local time. However, it doesn't know anything about the SET TIME ZONE command you sent earlier, all it does is use the system time zone (this is what DateTime.ToLocal does).

Up to now everything is the expected behavior. I've confirmed and when using NpgsqlDataReader directly you indeed get a local time (with Kind=Local). However, for some obscure reason, when DataAdapter is used the Kind changes to Unspecified (there's probably some bad copying going on in there). I've opened #1075 and will try to investigate.

Another lesson from this is that when Npgsql converts timestamptz to local, it should be sensitive to what PostgreSQL considers to be your local timezone, not what your system timezone is - sending SET TIME ZONE should have an effect. I've updated #646 to track this, although it might be a bit tricky to implement.

Finally, for your specific case... If what you want is to put a timestamp in your database and not have any conversions performed, I really suggest you use timestamp. timestamptz is confusing (as you can see) and not very useful, timestamp ensures that you always get out what you put in, and it's up to you to do any conversions later. If you really want to use timestamptz, I suggest dropping NpgsqlDataAdapter (which is considered somewhat obsolete and will not exist in CoreCLR).

Hope this clarifies things... Don't hesitate to post back questions and comments.

@roji

roji commented May 9, 2016

Copy link
Copy Markdown
Member

I've also fixed the documentation to specify that timestamptz is returned as a DateTime with Kind=Local, not UTC.

@roji

roji commented May 9, 2016

Copy link
Copy Markdown
Member

@Emill

Emill commented May 10, 2016 •

Copy link
Copy Markdown
Contributor

If you read that document, it is timetz they don't recommend as I can see.

@roji

roji commented May 10, 2016

Copy link
Copy Markdown
Member

Oops you're right. Although with all the confusion timestamptz creates I'd recommend against using it as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants