Skip to content

tstzrange[] and daterange[] aren't mapped to NodaTime Interval[] and DateInterval[] by default #4234

Closed

Description

@madmox

Npgsql.NodaTime 6.0 fixed the tstzrange to NodaTime.Interval mapping, but it does not map tstzrange[] to Interval[] as it should (it is still mapped as NpgsqlRange<Instant>[]).

Note that it correctly maps tstzmultirange to Interval[], but there are some scenarios where it is not possible to use tstzmultirange instead of tstzrange[], like if you don't have access to PostgreSQL 14+ (it is not yet available on all managed hosting providers), or if you want to store non-contiguous ranges in the field (overlapping ranges).

Originally reported here.

Activity

  1. roji commented on Dec 22, 2021

    @roji
    Member

    @madmox I ran a small test, and Npgsql can in fact read PG tstzrange[] as NodaTime Interval[]:

    await using var cmd = new NpgsqlCommand(
        @"SELECT '{""[\""1998-04-12 15:26:38+02\"",\""1998-04-12 17:26:38+02\"")"",""[\""1998-04-13 15:26:38+02\"",\""1998-04-13 17:26:38+02\"")""}'::tstzrange[]",
        conn);
    await using var reader = await cmd.ExecuteReaderAsync();
    reader.Read();
    
    var intervalArray = reader.GetFieldValue<Interval[]>(0);
    Console.WriteLine(intervalArray[1]);

    It can also write NodaTime Interval[] to PG tstzrange[], although since tstzmultirange is the default option, you need to explicitly specify tstzrange[] as follows:

    var intervalArray = new Interval[]
    {
        new(
            new LocalDateTime(1998, 4, 12, 13, 26, 38).InUtc().ToInstant(),
            new LocalDateTime(1998, 4, 12, 15, 26, 38).InUtc().ToInstant()),
        new(
            new LocalDateTime(1998, 4, 13, 13, 26, 38).InUtc().ToInstant(),
            new LocalDateTime(1998, 4, 13, 15, 26, 38).InUtc().ToInstant()),
    };
    
    await using var cmd = new NpgsqlCommand(@"SELECT pg_typeof($1)::text, pg_typeof($2)::text", conn)
    {
        Parameters =
        {
            new() { Value = intervalArray },
            new() { Value = intervalArray, NpgsqlDbType = NpgsqlDbType.TimestampTzRange | NpgsqlDbType.Array }
        }
    };
    await using var reader = await cmd.ExecuteReaderAsync();
    reader.Read();
    
    Console.WriteLine(reader.GetString(0));
    Console.WriteLine(reader.GetString(1));

    This seems to be the right behavior: the multirange types should generally be preferred as the default, while giving users the option to use the array instead.

    Have I missed something?

  2. madmox commented on Dec 22, 2021

    @madmox
    Author

    I'm using Dapper on top of Npgsql, so I'm not sure how it uses Npgsl internally to perform the query and read the results. What I do is :

    My code:

    using Dapper;
    using NodaTime;
    using Npgsql;
    using System;
    using System.Data;
    
    NpgsqlConnection.GlobalTypeMapper.UseNodaTime();
    SqlMapper.AddTypeHandler(new IntervaArrayHandler());
    
    using var connection = new NpgsqlConnection("xxx");
    var p = new { Id = 1 };
    string sql = $@"SELECT * FROM foo WHERE id = @Id;";
    Foo result = await connection.QuerySingleAsync<Foo>(sql, p);
    
    Console.WriteLine(result.Ranges.Length);
    
    public class Foo
    {
        public int Id { get; set; }
        public Interval[] Ranges { get; set; }
    }
    
    public class IntervaArrayHandler : SqlMapper.TypeHandler<Interval[]>
    {
        public override Interval[] Parse(object value)
        {
            return (Interval[])value;
        }
        public override void SetValue(IDbDataParameter parameter, Interval[] value)
        {
            parameter.Value = value;
        }
    }

    The code fails in the handler, in the IntervaArrayHandler.Parse(), because value is of type NpgsqlRange<Instant>[]:

    System.Data.DataException
      HResult=0x80131501
      Message=Error parsing column 1 (ranges=NpgsqlTypes.NpgsqlRange`1[NodaTime.Instant][] - Object)
      Source=Dapper
      StackTrace:
       at Dapper.SqlMapper.ThrowDataException(Exception ex, Int32 index, IDataReader reader, Object value) in /_/Dapper/SqlMapper.cs:line 3706
       at Dapper.SqlMapper.ReadRow[T](CacheInfo info, Identity identity, CommandDefinition& command, Type effectiveType, IDataReader reader) in /_/Dapper/SqlMapper.cs:line 1248
       at Dapper.SqlMapper.<QueryRowAsync>d__34`1.MoveNext() in /_/Dapper/SqlMapper.Async.cs:line 480
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at <Program>$.<<Main>$>d__0.MoveNext() in [...]\Program.cs:line 12
    
      This exception was originally thrown at this call stack:
        IntervaArrayHandler.Parse(object) in Program.cs
        [External Code]
    
    Inner Exception 1:
    InvalidCastException: Unable to cast object of type 'NpgsqlTypes.NpgsqlRange`1[NodaTime.Instant][]' to type 'NodaTime.Interval[]'.
    
  3. added a commit that references this issue on Dec 29, 2021
    6321d93
  4. self-assigned this
    on Dec 29, 2021
  5. added this to the 6.0.3 milestone on Dec 29, 2021
  6. roji commented on Dec 29, 2021

    @roji
    Member

    Right, so this is about the default being read for tstzrange[] - it's currently NpgsqlRange<Instant>[] whereas it should be Interval[]. I'll make that change for 6.0.3.

    The same is also true for daterange[] which should be mapped to DateInterval[] by default.

  7. changed the title [-]tstzrange[] is not mapped to NodaTime.Interval[][/-] [+]tstzrange[] and daterange[] aren't mapped to NodaTime Interval[] and DateInterval[] by default[/+] on Dec 29, 2021
  8. added 2 commits that reference this issue on Dec 29, 2021
    39cc38b
    b617faf
  9. alitas commented on Apr 21, 2022

    @alitas
    Contributor

    PostgreSQL supports inclusive and exclusive bounds on range types. However, Interval doesn't seem to have such a concept and is always inclusive on the lower bound and always exclusive on the upper bound.

    Documentation: https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-INCLUSIVITY

  10. roji commented on Apr 21, 2022

    @roji
    Member

    @alitas yep, that's right. You always still have the option of mapping tstzrange to NpgsqlRange instead of Interval if you need that kind of control.

  11. 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

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions