Skip to content

RangeHandler should handle all the types of its subtype's handler #3563

Closed

Description

@Arsync

I'm using NodaTime by Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime (v5.0.1) and have model:

public class A
{
    public NpgsqlRange<OffsetDateTime> VersionPeriod { get; set; }
}

When tstzrange value [2020-12-09T14:34:02.675750+03:00,) is coming from database, it throws following exception:

Unable to cast object of type 'NpgsqlTypes.NpgsqlRange`1[NodaTime.Instant]'
to type 'NpgsqlTypes.NpgsqlRange`1[NodaTime.OffsetDateTime]'.

Activity

  1. Arsync commented on Dec 16, 2020

    @Arsync
    Author

    Seems, it happens not only with NpgsqlRange, but with any properties of type OffsetDateTime.

  2. roji commented on Dec 16, 2020

    @roji
    Member

    @Arsync can you please post a runnable code sample (not just a fragment) which shows the issue? If it reproduces without NpgsqlRange, that's even better.

  3. Arsync commented on Dec 16, 2020

    @Arsync
    Author

    Can't figure out what's going on: I've created small project to reproduce this issue from scratch.
    But error message is different of my heavy solution:

    Linq request in this small sample project:

    System.InvalidCastException: 'Can't cast database type tstzrange to NpgsqlRange`1'
       at System.Runtime.CompilerServices.CastHelpers.Unbox(Void* toTypeHnd, Object obj)
       at System.Data.Common.DbDataReader.GetFieldValue[T](Int32 ordinal)
       at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
       at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
       at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
       at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
       at System.Linq.SystemCore_EnumerableDebugView`1.get_Items()
    

    Linq request in my heavy solution:

    Unable to cast object of type 'NpgsqlTypes.NpgsqlRange`1[NodaTime.Instant]' to type 'NpgsqlTypes.NpgsqlRange`1[NodaTime.OffsetDateTime]'.
       at System.Runtime.CompilerServices.CastHelpers.Unbox(Void* toTypeHnd, Object obj)
       at System.Data.Common.DbDataReader.GetFieldValue[T](Int32 ordinal)
       at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
       at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
       at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
       at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
       at System.Linq.SystemCore_EnumerableDebugView`1.get_Items()
    

    Both DbContext configuration the same:

    builder.UseNpgsql(_connectionString, opts =>
    {
        opts.UseNodaTime();
    });
    

    Version of Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime is v5.0.1, NodaTime is 3.0.3

  4. Arsync commented on Dec 17, 2020

    @Arsync
    Author

    Found why it throws different exceptions from big solution and updated sample project with another one Hosted app. It reproduces hosted runtime to add EFCoreSecondLevelCacheInterceptor, which changes exception message in following lines:

    options.AddInterceptors(
        provider.GetRequiredService<SecondLevelCacheInterceptor>());

    Test code has moved to Services/AppService.cs

    There is two actions:

    • first one is initial insert into table (produces Can't cast database type tstzrange to NpgsqlRange'1')
    • second is retrieving from db (produces Unable to cast object of type 'NpgsqlTypes.NpgsqlRange'1[NodaTime.Instant]'...)
  5. Arsync commented on Dec 17, 2020

    @Arsync
    Author

    I've thinked about possible workarounds when found this article:

    To summarize it in a few words, there are two sources of date and time data: system clocks, and the user. System generated values should be represented as Instant values. On the other hand user generated values should be represented as one of the following...

    In my case properties VersionPeriod and CreationTime are system-generated values and both can be of Instant type:

    public class SampleModel
    {
        public NpgsqlRange<Instant> VersionPeriod { get; set; }
        
        public Instant CreationTime { get; set; }
    }

    Is it safe to map Instant to timestamp with time zone?
    Goal: performing sql queries by hands will show zoned time and C# code gets UTC time.

    builder.Property(x => x.VersionPeriod)
        .HasColumnType("tstzrange")
        .HasDefaultValueSql("tstzrange(clock_timestamp(), NULL, '[)')")
        .ValueGeneratedOnAddOrUpdate()
        .IsRequired();
    
    builder.Property(x => x.CreationTime)
        .HasDefaultValueSql("clock_timestamp()")
        .HasColumnType("timestamptz")
        .ValueGeneratedOnAddOrUpdate()
        .IsRequired();

    With this approach no need to use NpgsqlRange<OffsetDateTime> while it throws can't cast to NpgsqlRange.

  6. arontsang commented on Jan 28, 2021

    @arontsang

    Shouldn't the conanical type to map to for EFcore.pg.Noda for this datebase type be NodaTime.Interval rather than NpgsqlRange?

  7. roji commented on Jan 28, 2021

    @roji
    Member

    @arontsang although there's semantic similarity between an interval and a range of timestamps, from a typing perspective NpgsqlRange corresponds to PostgreSQL ranges, which are a specific class of types with their own operations etc. You can already map NodaTime Interval (and Period) to PG interval.

  8. roji commented on Jan 28, 2021

    @roji
    Member

    Thinking about this some more, mapping NodaTime Interval to PG tsrange/tstzrange is something we could support - they do correspond very closely. The question in my mind is whether this should become the default mapping (minor breaking) or just an option.

    Opened npgsql/efcore.pg#1671 to track.

  9. Arsync commented on Jan 28, 2021

    @Arsync
    Author

    Still have LocalDate period:

    public class A
    {
        public NpgsqlRange<LocalDate> Period { get; set; } // User-controlled period in days with local date
        public NpgsqlRange<Instant> VersionPeriod { get; set; } // System field for versioning
    }

    which now exists with Interval type:

    public class A
    {
        public NpgsqlRange<LocalDate> Period { get; set; }
        public Interval VersionPeriod { get; set; }
    }

    Maybe it less elegant to use different types from two libraries to handle date ranges?

  10. roji commented on Jan 28, 2021

    @roji
    Member

    @Arsync I don't think we'd remove support for mapping NpgsqlRange<Instant> to tsrange. Mapping Interval would simply be another option for users who prefer the native NodaTime type, rather than the Npgsql type.

    However, given that NodaTime's Interval does correspond very well to PG tsrange, using Interval seems like a nice API improvement.

  11. arontsang commented on Jan 28, 2021

    @arontsang

    As an aside, I am currently putting together a PR for a ClassMapper for mapping NodaTime.DateInterval into daterange.

    https://github.com/npgsql/efcore.pg/pull/1670/files/63c1da141ac2385fd9ba65edbf9da0136256f28b..a65b026c1fa663ff4fd8b0f39f73eec8ba943c27

    I've also implemented .Start, .End .Contains etc...

    Unfortunately, I'm having some trouble with running the Unit Tests.

  12. roji commented on Jan 28, 2021

    @roji
    Member

    @arontsang I like what you're doing, but as I wrote in the PR I think we should build the mapping support at the ADO layer, so that non-EF users can benefit from it too. Let me know if you're up for doing that too - and also if you need any help, tests or otherwise.

  13. arontsang commented on Jan 28, 2021

    @arontsang
  14. roji commented on Jan 28, 2021

    @roji
    Member

    @arontsang I think it should be possible to add support there by registering a DateIntervalHandler that extends RangeHandler, but also implements INpgsqlSimpleTypeHandler<DateInterval>. That would allow both type mappings to exist, while keeping the range mapping as the default; you would still be able to set a parameter's value to a DateInterval, and read back a daterange as DateInterval via NpgsqlDataReader.GetFieldValue<DateInterval>().

    It's true we haven't yet done this with another range type, but I think it should be OK.

  15. transferred this issue fromnpgsql/efcore.pgon Feb 22, 2021
  16. roji commented on Feb 22, 2021

    @roji
    Member

    I looked into the original issue again (this got sucked into the discussion around mapping DateInterval etc).

    At the ADO level, ranges over the NodaTime only support the handler's primary type (Instant for TimestampTzHandler). At some point I fixed this issue for non-NodaTime timestamptz by having a RangelHandler with two generic parameters (see this), but NodaTime's TimestampTzHandler supports 5 types :/

    RangeHandler should support ranges over all its subtype's types via a better mechanism, instead of the current multiple generic handlers. It should be possible to just override Read<TAny> and handle things like that.

  17. changed the title [-]Can't get value from tstzrange to NpgsqlRange<OffsetDateTime>[/-] [+]RangeHandler should handle all the types of its subtype's handler[/+] on Feb 22, 2021
  18. added this to the vNext milestone on Feb 22, 2021
  19. roji commented on Sep 15, 2021

    @roji
    Member

    @arontsang FYI I did the mapping to NodaTime DateInterval in #3973, enabled by the type mapping redo in #3953.

  20. roji commented on Oct 3, 2021

    @roji
    Member

    We can do this by source-generating a RangeHandler for each base type. Do this after #3979 is resolved.

  21. roji commented on Oct 9, 2021

    @roji
    Member

    Did a quick source generation prototype (see https://github.com/roji/Npgsql/tree/archive/RangeHandlerSourceGeneration) - this approach works, but seems like a massive overkill in terms of complexity and code addition. We can simply use NpgsqlRange<T1, T2> for two elements, or simply have a custom type deriving from NpgsqlRange<T> and returned from the handler's CreateRangeHandler when needed (like NodaTime's DateHandler does).

    Am closing this - if we see any further needs we can revisit.

  22. removed this from the 6.0.0 milestone on Oct 9, 2021
  23. added theissue type on Jun 18, 2025
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

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions