Skip to content

Allow per-connection, non-global plugin usage #747

Closed

Description

@lust4life

through this #568 (comment) and #648 (comment) , seems right now, the BCL date/time types are not supported when the NodaTime plugin is configured., and from this Long story short, when you set up the ADO NodaTime plugin, it "hijacks" NpgsqlDbType.Timestamp and routes it to the NodaTime type handler, instead of the built-in DateTime type handler.

and http://www.npgsql.org/doc/types/nodatime.html#setup shows :

// Place this at the beginning of your program to use NodaTime everywhere (recommended)
NpgsqlConnection.GlobalTypeMapper.UseNodaTime();

// Or to temporarily use NodaTime on a single connection only:
conn.TypeMapper.UseNodaTime();

seems that, npgsql supports using plugins in connection level, while the extension method UseNodaTime shows :

// TODO: Global-only setup at the ADO.NET level for now, optionally allow per-connection?
NpgsqlConnection.GlobalTypeMapper.UseNodaTime();

I am wondering that if this can be implemented in per-connection way or is there any workaround here for now?

My situation here is , we have not the whole control with code we use, e.g: use aspnet.identity, hangfire.postgresql , these libs may use ef.core, may use dapper or raw npgsql. While our own dbcontext use the nodatime plugin style, if some dbcontext config using nodatime plugin, it will break all BCL ways to use datetime, even in raw npgsql.

Does the way check plugins and add corresponding type-mappers in NpgsqlRelationalConnection solve the problem ?

right now, this works for me, does this a reasonable way to fix situation here, do you have any suggestion ?

// ensure conn in di is request scoped
services.AddScoped<DbConnection>(provider =>
    {
        var conn = new NpgsqlConnection("conn str");
        conn.Open();
        // register typp mapper on connection level, not global level
        conn.TypeMapper.UseNodaTime();
        return conn;
    })
    .AddHangfire(o =>
    {
        // since nodatime type mapper region on connection level, it will not affect BCL datetime on hangfire use dapper with raw npgsql
        o.UsePostgreSqlStorage("conn str");
    })
    .AddEntityFrameworkNpgsql()
    .AddDbContext<XXXDbContext>((p, options) =>
    {
        // since conn is registered with nodatime type mapper on connection level before, ef.core will work correctly
        var conn = p.GetRequiredService<DbConnection>();
        
        options.UseNpgsql(conn,b =>
        {
            // DON'T USE `UseNodaTime()` extension method, since it will register nodatime on global type mapper, and it will affect BCL datetime on the application level
            // UsePlugin here to register plugin on ef.core plugin model
            b.UsePlugin(new NodaTimePlugin());
        });
    });

Activity

  1. austindrenski commented on Dec 11, 2018

    @austindrenski
    Contributor

    @lust4life I'm a bit confused by the snippet you've provided.

    I cleaned up the formatting to be sure, but it still looks like you register the NodaTime plugin on each connection before yielding it back and then also configure that plugin on each context.

    Have I misread (or worse mis-reformatted) your snippet?

    I am wondering that if this can be implemented in per-connection way or is there any workaround here for now?

    In general terms, we don't currently have much in the way of guidance for users interested in using these plugins on a per-connection basis, so it's difficult to say what the best workaround would be.

    I'll take a closer look at our plugin model and see if I can put together some concrete guidance.

    Related

    #654

  2. added this to the 3.0.0 milestone on Dec 11, 2018
  3. lust4life commented on Dec 12, 2018

    @lust4life
    Author

    @austindrenski reformat the code snippet and add some comments . the idea here is to avoid register type mapper on global level.

  4. changed the title [-]workaround in nodatime plugin live with DateTime [/-] [+]Allow per-connection, non-global plugin usage[/+] on Dec 13, 2018
  5. roji commented on Dec 13, 2018

    @roji
    Member

    There have been enough complaints about this kind of thing that we probably need to address this.

    It's probably pretty easy to change from doing global type mapping at the ADO level to simply setting up the plugin on each connection. This would involve changing NpgsqlRelationalConnection to be aware of the plugins and applying them at each open.

    However, we should make sure the per-connection type mapping changes don't have a prohibitive perf cost - I've opened npgsql/npgsql#2263 to optimize this.

  6. roji commented on Apr 17, 2019

    @roji
    Member

    @Jacquers this is indeed what this issue is about. I'm hoping we can get per-connection plugins working in EF Core soon. In the meantime you can check out the workaround snippet provided by @lust4life above.

  7. roji commented on May 3, 2019

    @roji
    Member

    For anyone doing this, please be aware that there's a potentially substantial performance degradation currently associated with using plugins at the connection level (rather than at the global level). npgsql/npgsql#2263 will hopefully fix this soon.

  8. modified the milestones: 3.0.0, 3.1.0 on Aug 28, 2019
  9. sandcastle commented on Sep 30, 2019

    @sandcastle

    @roji - are you aware of anything else that can be done at the ADO NodaTime plugin level to stop the hijacking from occurring that would enable both DateTime and NodaTime types to be used at the same time?

  10. 14 remaining items

  11. davidroth commented on Sep 8, 2020

    @davidroth

    Good news for everybody waiting for a solution to this issue: The npgsql noda time plugin has recently been modified to support BCL types besides nodatime types. See MR npgsql/npgsql#3124 for details. This should resolve the specific pain points described in this thread as now BCL datetime types can co-exist with Nodatime types, without any workarounds or performance issues.

    Fix has been merged and is targeted for https://github.com/npgsql/npgsql/milestone/70

  12. roji commented on Oct 3, 2020

    @roji
    Member

    Moving this to backlog - it's no longer necessary since @davidroth implemented npgsql/npgsql#3124.

  13. modified the milestones: 5.0.0, Backlog on Oct 3, 2020
  14. ProfDoof commented on Nov 21, 2020

    @ProfDoof

    Ok, I may be posting this in the wrong thread but I seem to be running into problems caused by using NodaTime and Hangfire together. This appears to be related to the way that types are mapped but maybe I'm on the wrong path. If this is still related to my problem, is there a workaround? I'm on Npgsql version 5.0.0.

    System.Data.DataException: Error parsing column 3 (FetchedAt=2020-11-21T06:16:54Z - Object)
     ---> System.InvalidCastException: Unable to cast object of type 'NodaTime.Instant' to type 'System.Nullable`1[System.DateTime]'.
       at Deserialize6023f57c-30b5-4885-bf3a-28a14f99d3e3(IDataReader )
       --- End of inner exception stack trace ---
       at Dapper.SqlMapper.ThrowDataException(Exception ex, Int32 index, IDataReader reader, Object value) in C:\projects\dapper\Dapper\SqlMapper.cs:line 3633
       at Deserialize6023f57c-30b5-4885-bf3a-28a14f99d3e3(IDataReader )
       at Dapper.SqlMapper.QueryImpl[T](IDbConnection cnn, CommandDefinition command, Type effectiveType)+MoveNext() in C:\projects\dapper\Dapper\SqlMapper.cs:line 1098
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in C:\projects\dapper\Dapper\SqlMapper.cs:line 721
       at Hangfire.PostgreSql.PostgreSqlJobQueue.<>c__DisplayClass5_1.<Dequeue_Transaction>b__0()
       at Hangfire.PostgreSql.Utils.Utils.TryExecute[T](Func`1 func, T& result, Func`2 smoothExValidator, Nullable`1 tryCount)
       at Hangfire.PostgreSql.PostgreSqlJobQueue.Dequeue_Transaction(String[] queues, CancellationToken cancellationToken)
       at Hangfire.PostgreSql.PostgreSqlJobQueue.Dequeue(String[] queues, CancellationToken cancellationToken)
       at Hangfire.PostgreSql.PostgreSqlConnection.FetchNextJob(String[] queues, CancellationToken cancellationToken)
       at Hangfire.Server.Worker.Execute(BackgroundProcessContext context)
       at Hangfire.Server.BackgroundProcessDispatcherBuilder.ExecuteProcess(Guid executionId, Object state)
       at Hangfire.Processing.BackgroundExecution.Run(Action`2 callback, Object state)
    

    This is currently the way that I'm using Hangfire

    .AddHangfire(configuration => configuration
                        .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                        .UseSimpleAssemblyNameTypeSerializer()
                        .UseRecommendedSerializerSettings()
                        .UsePostgreSqlStorage(connectionStringBuilder.ConnectionString, new PostgreSqlStorageOptions { DistributedLockTimeout = TimeSpan.FromMinutes(1), }))

    and this is the way I'm turning on the NodaTime mapping

    optionsBuilder
            .UseLoggerFactory(this._loggerFactory)
            .UseNpgsql(this.DbConnectionString, 
                        o => o.UseNodaTime());
  15. YohDeadfall commented on Nov 21, 2020

    @YohDeadfall
    Contributor

    Was fixed by npgsql/npgsql#3124 and available since Npgsql 4.1.5.

  16. removed this from the Backlog milestone on Nov 21, 2020
  17. davidroth commented on Nov 21, 2020

    @davidroth

    @fireflamemm

    Yes there is a workaround 😊
    Let me first explain why you are seeing the exception, although the NodaTime plugin now supports BCL types.

    Dapper maps properties by using the non-generic IDataRecord indexer. You can check that if you look at dappers SqlMapper code on line 3492 and line 2962.

    The NodaTime plugin overrides the default type mapping and therefore it will try to read Instant instead of DateTime.
    If dapper would use the explicit IDataRecord.GetDateTime(int i) method, the exception wouldn't occur because in that case, the plugin would correctly return the expected DateTime value.

    Fortunately, dapper supports registering custom TypeHandler instances which will solve this issue.
    So to fix this issue you need to:

    1. Copy the following class in your project:
    // Needed because NodaTime Plugin overrides the default mappings and Dapper uses non-generic IDataReader.GetValue functions which return Instant instead of DateTime.
    public class DapperDateTimeTypeHandler : SqlMapper.TypeHandler<DateTime>
    {
        public override DateTime Parse(object value)
        {
            if (value is DateTime dateTime)
            {
                return dateTime;
            }
            else if (value is NodaTime.Instant i)
            {
                return i.ToDateTimeUtc();
            }
            throw new ArgumentException($"Invalid value of type '{value?.GetType().FullName}' given. DateTime or NodaTime.Instant values are supported.", nameof(value));
        }
    
        public void SetValue(IDbDataParameter parameter, object value)
            => parameter.Value = value;
    
        public override void SetValue(IDbDataParameter parameter, DateTime value)
            => parameter.Value = value;
    }
    1. Add the following line somewhere in Startup.cs. I prefer adding it directly in the services.AddHangfire call:
    services.AddHangfire(config =>
    {
        config.UsePostgreSqlStorage(appSettings.ConnectionString);
        Dapper.SqlMapper.AddTypeHandler(new DapperDateTimeTypeHandler()); // <--- register the type handler
    });
  18. davidroth commented on Nov 21, 2020

    @davidroth

    @YohDeadfall

    Was fixed by npgsql/npgsql#3124 and available since Npgsql 4.1.5.

    Unfortunately not in the case of dapper. See my previous explanation. The generic apis now work all nicely and without workarounds. But as soon as a library uses the non-generic object based IDataReader methods, and implicitly assumes BCL types being returned, a workaround is necessary.

  19. ProfDoof commented on Nov 21, 2020

    @ProfDoof

    @davidroth
    Thank you so much for the quick response! That seems to have cleared everything right up. Now on to the next bug! Good luck with all of this!

  20. YohDeadfall commented on Nov 21, 2020

    @YohDeadfall
    Contributor

    @davidroth, am aware of it, but this repository for EF Core (:

  21. artschekoff commented on Sep 3, 2022

    @artschekoff

    @fireflamemm

    Yes there is a workaround 😊 Let me first explain why you are seeing the exception, although the NodaTime plugin now supports BCL types.

    Dapper maps properties by using the non-generic IDataRecord indexer. You can check that if you look at dappers SqlMapper code on line 3492 and line 2962.

    The NodaTime plugin overrides the default type mapping and therefore it will try to read Instant instead of DateTime. If dapper would use the explicit IDataRecord.GetDateTime(int i) method, the exception wouldn't occur because in that case, the plugin would correctly return the expected DateTime value.

    Fortunately, dapper supports registering custom TypeHandler instances which will solve this issue. So to fix this issue you need to:

    1. Copy the following class in your project:
    // Needed because NodaTime Plugin overrides the default mappings and Dapper uses non-generic IDataReader.GetValue functions which return Instant instead of DateTime.
    public class DapperDateTimeTypeHandler : SqlMapper.TypeHandler<DateTime>
    {
        public override DateTime Parse(object value)
        {
            if (value is DateTime dateTime)
            {
                return dateTime;
            }
            else if (value is NodaTime.Instant i)
            {
                return i.ToDateTimeUtc();
            }
            throw new ArgumentException($"Invalid value of type '{value?.GetType().FullName}' given. DateTime or NodaTime.Instant values are supported.", nameof(value));
        }
    
        public void SetValue(IDbDataParameter parameter, object value)
            => parameter.Value = value;
    
        public override void SetValue(IDbDataParameter parameter, DateTime value)
            => parameter.Value = value;
    }
    1. Add the following line somewhere in Startup.cs. I prefer adding it directly in the services.AddHangfire call:
    services.AddHangfire(config =>
    {
        config.UsePostgreSqlStorage(appSettings.ConnectionString);
        Dapper.SqlMapper.AddTypeHandler(new DapperDateTimeTypeHandler()); // <--- register the type handler
    });

    Thx, you saved me <3

    I've only added one more type check and cast, because LocalDateTime is used in my models:

            if (value is NodaTime.Instant i)
            {
                return i.ToDateTimeUtc();
            }
    
            if (value is NodaTime.LocalDateTime lt)
            {
                return lt.ToDateTimeUnspecified();
            }
  22. bessgeor commented on Aug 12, 2026

    @bessgeor

    The TypeHandler workaround got broken with Hangfire.PostgreSql release 1.21: the lib migrated to Dapper.AOT which shortcuts to Convert.ToDateTime(IDataReader.GetValue(i)), thus yielding System.InvalidCastException: Unable to cast object of type 'NodaTime.Instant' to type 'System.IConvertible'..

    As I need to share a datasource between the app own logic (which uses Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime) and Hangfire (which migrated to Dapper.AOT), so I could enqueue a job in the same non-distributed transaction as I make changes in the business logic, and I don't want to migrate from NodaTime, I had to research a new workaround.

    The workaround is to change what non-generic GetValue returns to something implementing IConvertible, and that is possible using Npgsql experimental API AddTypeInfoResolverFactory.

    Npgsql* 10.0.3, Hangfire.PostgreSql 1.21.1

    So, we need an adapter

    public readonly struct ConvertibleInstant(Instant value) : IConvertible, IEquatable<ConvertibleInstant>
    {
      public Instant Value { get; } = value;
    
      public TypeCode GetTypeCode() => TypeCode.Object;
    
      public DateTime ToDateTime(IFormatProvider? provider) => Value.ToDateTimeUtc();
    
      public string ToString(IFormatProvider? provider) => Value.ToString();
    
      public object ToType(Type conversionType, IFormatProvider? provider)
      {
        if (conversionType == typeof(DateTime))
        {
          return ToDateTime(provider);
        }
    
        if (conversionType == typeof(Instant))
        {
          return Value;
        }
    
        if (conversionType == typeof(string))
        {
          return ToString(provider);
        }
    
        throw new InvalidCastException($"Cannot convert {nameof(ConvertibleInstant)} to {conversionType}.");
      }
    
      // IConvertible other methods implementation, just throwing InvalidCastException
      // IEquatable implementation
    }

    Make a binary converter that would be able to handle (de)serialization into timestamp binary representation:

    internal sealed class ConvertibleInstantConverter : PgBufferedConverter<ConvertibleInstant>
    {
      private static readonly Instant PgEpoch = Instant.FromUtc(2000, 1, 1, 0, 0, 0);
    
      protected override ConvertibleInstant ReadCore(PgReader reader)
      {
        var micros = reader.ReadInt64();
        return new ConvertibleInstant(PgEpoch.PlusTicks(micros * 10));
      }
    
      protected override void WriteCore(PgWriter writer, ConvertibleInstant value)
      {
        var ticks = (value.Value - PgEpoch).BclCompatibleTicks;
        writer.WriteInt64(ticks / 10);
      }
    
    #pragma warning disable CS0618 // legacy CanConvert override: required by PgBufferedConverter; no other way to set bufferRequirements
      public override bool CanConvert(DataFormat format, out BufferRequirements bufferRequirements)
      {
        bufferRequirements = BufferRequirements.CreateFixedSize(sizeof(long));
        return format is DataFormat.Binary;
      }
    #pragma warning restore CS0618
    }

    And add a factory that would register the adapter as default type for timestamp/timestamptz:

    public sealed class DefaultInstantAsConvertibleResolverFactory : PgTypeInfoResolverFactory
    {
      public override IPgTypeInfoResolver CreateResolver() => new Resolver();
    
      public override IPgTypeInfoResolver? CreateArrayResolver() => null;
    
      private sealed class Resolver : IPgTypeInfoResolver
      {
        private TypeInfoMappingCollection? _mappings;
        private TypeInfoMappingCollection Mappings => _mappings ??= Build();
    
        public PgTypeInfo? GetTypeInfo(Type? type, DataTypeName? dataTypeName, PgSerializerOptions options)
        {
          if (type is not null && type != typeof(object))
          {
            return null;
          }
    
          return Mappings.Find(type, dataTypeName, options);
        }
    
        private static TypeInfoMappingCollection Build()
        {
          var mappings = new TypeInfoMappingCollection();
          mappings.AddStructType<ConvertibleInstant>("pg_catalog.timestamptz",
            static (options, mapping, _) => mapping.CreateInfo(options, new ConvertibleInstantConverter()),
            isDefault: true);
          mappings.AddStructType<ConvertibleInstant>("pg_catalog.timestamp",
            static (options, mapping, _) => mapping.CreateInfo(options, new ConvertibleInstantConverter()),
            isDefault: true);
          return mappings;
        }
      }
    }

    And the last part is to register the factory in the shared data source.

    var builder = new NpgsqlDataSourceBuilder(connectionString);
    builder.UseNodaTime();
    #pragma warning disable NPG9001 // AddTypeInfoResolverFactory is an experimental API that is subject to change
    builder.AddTypeInfoResolverFactory(new DefaultInstantAsConvertibleResolverFactory());
    #pragma warning restore NPG9001
    // whatever configuration you might need

    Keep optionsBuilder.UseNpgsql(b => b.UseNodaTime()) in your DbContext, use shared DataSource between EF and Hangfire (you probably are already doing it with Hangfire.PostgreSql.IConnectionFactory implementation and wiring the same DataSource into DbContextOptionsBuilder.UseNpgsql) and you are good to go until the experimental API changes. It has been experimental for almost 3Y, so it seems pretty solid now (npgsql/npgsql@e8f20a0).

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions