Dapper icon indicating copy to clipboard operation
Dapper copied to clipboard

Npgsql 6.0.0-rc.1 DateTime issue

Open 3ldar opened this issue 5 years ago • 36 comments

We are using a library named Hangfire.PostgreSql and it uses Dapper under the hood. In that library there is a code block like below :

 using (var transaction = connection.BeginTransaction(IsolationLevel.RepeatableRead))
                {
                    int affected = -1;

                    affected = connection.Execute($@"DELETE FROM ""{options.SchemaName}"".""lock"" WHERE ""resource"" = @resource AND ""acquired"" < @timeout",
                        new
                        {
                            resource = resource,
                            timeout = DateTime.UtcNow - options.DistributedLockTimeout
                        });

                    transaction.Commit();
                }

DDL that generates the target table is like below :

create table hangfire.lock
(
	resource text not null
		constraint lock_resource_key
			unique,
	updatecount integer default 0 not null,
	acquired timestamp with time zone
);

If we change timeout = DateTime.UtcNow - options.DistributedLockTimeout into this timeout = DateTimeOffset.UtcNow - options.DistributedLockTimeout it works as expected.

In 6.0.0-rc1.0 npgsql there is a breaking change that changes the target type of DateTime into timestamp with time zone. Related info

The library uses 2.0.78 version of dapper but I've managed the reproduce the same issue with 2.0.90 version.

3ldar avatar Oct 09 '21 19:10 3ldar

I'm trying to understand what the issue is - as I understand it, it looks like if the behavior has changed, the Hangfire would need to change to match. What would Dapper do differently here?

NickCraver avatar Oct 10 '21 01:10 NickCraver

I'm trying to understand what the issue is - as I understand it, it looks like if the behavior has changed, the Hangfire would need to change to match. What would Dapper do differently here?

The issue is when I try to execute the above statement with the same parameter types and values using raw Npgsql it doesn't fail. Here is the sample that succeeds

var connection = new NpgsqlConnection("cs");
await connection.OpenAsync();
using var transaction = await connection.BeginTransactionAsync(IsolationLevel.RepeatableRead);
 var command = new NpgsqlCommand($@"DELETE FROM ""hangfire"".""lock"" WHERE ""resource"" = @resource AND ""acquired"" < @timeout")
            {
                Connection = connection,
                Transaction = transaction
            };
         
command.Parameters.Add(new NpgsqlParameter("@resource", "abuzer"));
command.Parameters.Add(new NpgsqlParameter("@timeout", DateTime.UtcNow - TimeSpan.FromMinutes(10)));

await command.ExecuteNonQueryAsync();

3ldar avatar Oct 10 '21 09:10 3ldar

It seems that Dapper does not set Kind property to DateTimeKind.Utc when dealing with DateTime. Based on the new breaking changes in npgsql, Kind must be set to DateTimeKind.Utc to use TimeStampzHandler: https://github.com/npgsql/npgsql/blob/3d2a0af5c6d994bb2efad3bf6f456603b077d607/src/Npgsql/TypeMapping/BuiltInTypeHandlerResolver.cs#L459

rezabay avatar Oct 13 '21 06:10 rezabay

Is this for inputs? Or outputs? If inputs: that seems like something consumer code should be doing, after evaluating what the data represents. If Dapper was able to just blindly convert to UTC, then I would expect Npgsql would already be doing the same internally, so it wouldn't be an issue. If outputs: we don't creat the value - the ADO.NET provider does. Or are we talking about some more specific niche case here?

mgravell avatar Oct 13 '21 17:10 mgravell

This particular example is for inputs and I know for sure that the passed value is indeed DateTime with UTC kind. Npgsql does not do any conversion anymore and instead picks the corresponding time handler based on "Kind: value: https://github.com/npgsql/npgsql/blob/3d2a0af5c6d994bb2efad3bf6f456603b077d607/src/Npgsql/TypeMapping/BuiltInTypeHandlerResolver.cs#L459. The workaround is to pass DateTimeOffset but I just want to find the root cause of issue before the release date of .Net 6 but most likely the bug is on Npgsql side.

rezabay avatar Oct 13 '21 19:10 rezabay

Well, I have located the actual issue but have no idea how can it be resolved. I had to read that dam IL code and it basically does this :

var p = command.CreateParameter();
p.ParameterName = "@timeout";
p.Direction = ParameterDirection.Input;
p.Value = DateTime.UtcNow;
p.DbType = LookupDbType() // in this case this returns DateTime because it is explicitly set in that typeMap

But if you create the parameter without specifying any DbType NpgSql sets the DbType to DateTimeOffset

Edit I have removed the code that sets the DbType explicitly and it worked. But you have some reason to set this explicitly. It would be nice where you can override the Type -> DbType mapping.

3ldar avatar Oct 13 '21 20:10 3ldar

Ok, I think I kind of know what is going on. When DbType is set to DbType.DateTime, Npgsql maps it to NpgsqlDbType.Timestamp (https://github.com/npgsql/npgsql/blob/dba60fb5a87bc6d661bbdcd2a31be687edfc10e9/src/Npgsql/TypeMapping/GlobalTypeMapper.cs#L435) and later in NpgsqlParameter class (https://github.com/npgsql/npgsql/blob/dba60fb5a87bc6d661bbdcd2a31be687edfc10e9/src/Npgsql/NpgsqlParameter.cs#L505), TimestampHanler is selected instead of TimestampZHanlder resulting the issue above. I don't know if this is the expected behaviour or a bug after DateTime breaking changes.

rezabay avatar Oct 13 '21 20:10 rezabay

Hey everyone, I want to do my best to help - Npgsql 6.0 indeed does some pretty serious breaking changes. In case you're not aware, you can set an AppContext compatibility switch to revert to the pre-6.0 behavior.

I can see the issue which @3ldar is describing; Dapper sets the DbType on the parameter to the result of LookupDbType, which returns DbType.DateTime. PostgreSQL has two timestamp types: timestamp without time zone (for local/unspecified) and timestamp with time zone(for UTC); Npgsql uses DbType.DateTime to refer to the former and DbType.DateTimeOffset to refer to the latter (since there's no datetimeoffset DB type). Maybe DbType.DateTime2 would be a better choice (or in addition), but that's beside the point.

The thing is, in 6.0, we no longer allow UTC timestamps to be written to timestamp without time zone, since that's mixing timestamp types (UTC goes to UTC, non-UTC to non-UTC). If DbType were to be unset, Npgsql would simply infer automatically what to do by looking at the DateTime's Kind, but since Dapper sets it explicitly, it just does what it's told...

@mgravell @NickCraver is there a particular reason to set DbType rather than let the driver decide? I'm open to making a change on the Npgsql if absolutely necessary, but would like to understand if Dapper is doing the right thing etc.

roji avatar Oct 13 '21 21:10 roji

Hi @roji - I'm pretty open to changing it to not specify anything, if that is going to work better. Date time is kinda unique among the primitives in that we keep inventing new ways of handling it. If omitting a type entirely is going to work better for dates/times: that's fine! I can probably try that tomorrow if you like.

mgravell avatar Oct 13 '21 21:10 mgravell

For Npgsql it's definitely better - just hoping there's not some reason it was done this way etc. Basically the ADO.NET driver is in a better position to know what to write based on the CLR type than Dapper is...

roji avatar Oct 13 '21 21:10 roji

BTW another possibly problematic one is TimeSpan -> DbType.Time... PostgreSQL has an interval type (which can be over 1 day), and a time type (which is really for time of day). Npgsql maps TimeSpan to interval (since TimeSpan can be more than a day), but DbType.Time maps to time... so you're effectively overriding the "natural" provider mapping. BTW luckily .NET now has TimeOnly, which can be cleanly mapped to time...

Type mapping is hard... especially date/times...

roji avatar Oct 13 '21 21:10 roji

spike started, @roji - should be on MyGet soon, assuming no explosions; what would we need to repro the failure here, to prove the fix?

mgravell avatar Oct 14 '21 12:10 mgravell

huh; tell a lie - looks like we only build MyGet for merges, but: it built and tested cleanly, at least

mgravell avatar Oct 14 '21 12:10 mgravell

The following fails with Npgsql 6.0.0-rc.1:

_ = conn.ExecuteScalar("SELECT @Now", new { Now = DateTime.UtcNow });

If you avoid setting DbType, Npgsql should internally infer the right PostgreSQL type and all should be well.

... and thanks for spending time on this!!

roji avatar Oct 14 '21 13:10 roji

building with that now: https://ci.appveyor.com/project/StackExchange/dapper/builds/41146676

mgravell avatar Oct 14 '21 13:10 mgravell

well, the good news is that the new TestPostgresqlDateTimeUsage passes; the less good news is that .TestPostgresqlArrayParameters now fails:

        [FactPostgresql]
        public void TestPostgresqlArrayParameters()
        {
            using (var conn = GetOpenNpgsqlConnection())
            {
                IDbTransaction transaction = conn.BeginTransaction();
                conn.Execute("create table tcat ( id serial not null, breed character varying(20) not null, name character varying (20) not null);");
                conn.Execute("insert into tcat(breed, name) values(:breed, :name) ", Cats);

                var r = conn.Query<Cat>("select * from tcat where id=any(:catids)", new { catids = new[] { 1, 3, 5 } });
                Assert.Equal(3, r.Count());
                Assert.Equal(1, r.Count(c => c.Id == 1));
                Assert.Equal(1, r.Count(c => c.Id == 3));
                Assert.Equal(1, r.Count(c => c.Id == 5));
                transaction.Rollback();
            }
        }

mgravell avatar Oct 14 '21 13:10 mgravell

Uhh... I don't know enough about what's going on internally to know... I'm assuming this change does just remove the setting of DbType, right? FWIW for arrays there's no correct DbType anyway...

roji avatar Oct 14 '21 13:10 roji

should be; checking to see whether I borked anything; never underestimate my ability to bork things - it is unrivaled

(FWIW, the same code worked on npgsql v5)

mgravell avatar Oct 14 '21 13:10 mgravell

@mgravell can you try it with a List<T>.

3ldar avatar Oct 14 '21 13:10 3ldar

I don't have npgsql locally, so I'm a little dependent on CI, but: List<int> failed too; not sure what is up without being able to debug: https://ci.appveyor.com/project/StackExchange/dapper/builds/41147028/tests

mgravell avatar Oct 14 '21 13:10 mgravell