Skip to content

Determining if NpgsqlRange<T> is implicitly empty #1943

Description

@austindrenski

Moved from: #1939 (comment)

// TODO: We need to check if the bounds are implicitly empty. E.g. '(1,1)' or '(0,0]'.

@roji:

Very true. We could implement this for some of the commonly-used range types (i.e. the ones that come built-in in PostgreSQL), although this can be left for later.

@austindrenski:

I'm planning to handle this more thoroughly in a separate PR down the road.

Basically, I think we need to incorporate the concept of range types being continuous/discrete in order to handle this properly.

I'm still thinking through the design, but one approach would be to follow PostgreSQL and have the user provide canonical functions, which would then allow us to increment/decrement for checks like this. I think the trick here would be to provide these hooks while guarding against obvious performance pitfalls.

@roji:

OK, please open a separate issue for discussing this (you can copy-paste my comments below there).

Unless I'm mistaken, it's possible to identify discrete vs. continuous ranges in PostgreSQL by checking for the existence of a cannonicalization function (pg_range.rngcanonical), as described in the docs.

The problem is that NpgsqlRange<T> isn't actually attached to any actual PostgreSQL database, and I think it's good to keep it that way. I think that a complex mechanism for loading discreteness from PostgreSQL would be a big overkill and of very little value (in theory two databases could also have the same range type defined but with different discreteness; but we really shouldn't go this far).

So it seems to me this is best handled by hardcoding the discreteness in code, which would probably cover at least 99% of the use cases.

Activity

  1. austindrenski commented on May 21, 2018

    @austindrenski
    ContributorAuthor

    @roji I think hardcoding discreteness makes sense for the built in range types. But to clarify, I wasn't suggesting a database lookup for the canonical functions.

    Initially, I was playing around with the idea of an interface based approach, whereby user-defined range types are implemented as structs with some INpgsqlRange interface....but that gets complicated quickly. (This is where canonical functions could come into play, as actual functions...but it introduces concerns of consistency.)

    Instead, what if we add IEquatable<T> and IComparable<T> constraint to NpgsqlRange<T>?

    public readonly struct NpgsqlRange<T> : IEquatable<NpgsqlRange<T>> 
        where T : IComparable<T>, IEquatable<T>
    {
        // ommitted
    }

    Then, we could add a discrete parameter to the fully-specified constructor:

    public NpgsqlRange(T lowerBound, bool lowerBoundIsInclusive, bool lowerBoundInfinite,
                       T upperBound, bool upperBoundIsInclusive, bool upperBoundInfinite,
                       bool discrete)
    {
        // use discrete + equatable/comparable to check for implicit emptiness
    }

    Continuous ranges would be the default, so alternative constructors would gain an optional parameter for discrete (set to false). The discrete parameter would be overridden for built in types, to prevent the construction of a continuous NpgsqlRange<int>.

    Then the new parser would change from:

    // currently in #1939
    Npgsql<T>.Parse(string rangeLiteral);
    
    // proposed
    NpgsqlRange<T>.Parse(string rangeLiteral, bool discrete);
  2. roji commented on May 22, 2018

    @roji
    Member

    Initially, I was playing around with the idea of an interface based approach, whereby user-defined range types are implemented as structs with some INpgsqlRange interface....but that gets complicated quickly. (This is where canonical functions could come into play, as actual functions...but it introduces concerns of consistency.)

    This goes back to questions of replicating the PostgreSQL range behavior in the client, which as you know seems like a risk proposition to me, especially in light of the relatively limited value it brings to the table.

    Instead, what if we add IEquatable and IComparable constraint to NpgsqlRange?
    [...]
    Then, we could add a discrete parameter to the fully-specified constructor:

    Shifting the discrete/continuous decision to the user could work. If we go down this route, I think there would still be a constructor without the discrete parameter, and which would also apply the hard-coded logic (int is discrete, float isn't).

    But to be honest, I'm simply not sure I see the value in going this far. Ranges are a pretty rarely-used feature in PostgreSQL, and user-defined range - well, let's just say I've never received a single question on them, and I doubt there's more than a handful people out there actually doing this. So while I appreciate doing this kind of thing for completeness, it may be better to simply wait until someone complains before jumping to implement. This is especially true here because we're only talking about the discrete/continuous distinction, which is really non-critical: user-defined ranges can be function perfectly well without this.

    But I'm open to considering this if you really think it's important (maybe someone else has an opinion as well).

    One last note: at "The Future of C#" session of Build, a new language range was shown that will probably make it into C# 8. The main goal is to allow you to slice arrays and strings, and do similar operations, but who knows - we may be able to do something there.

  3. changed the title [-]Determining if NpgsqlRange<T> is implicitly emptying[/-] [+]Determining if NpgsqlRange<T> is implicitly empty[/+] on May 22, 2018
  4. Brar commented on Jun 3, 2018

    @Brar
    Member

    @austindrenski wrote:

    Initially, I was playing around with the idea of an interface based approach, whereby user-defined range types are implemented as structs with some INpgsqlRange interface....but that gets complicated quickly.

    Is this really the case?
    What makes it complicated?

    @roji wrote:

    But to be honest, I'm simply not sure I see the value in going this far. Ranges are a pretty rarely-used feature in PostgreSQL, and user-defined range - well, let's just say I've never received a single question on them, and I doubt there's more than a handful people out there actually doing this.

    With this in mind I was thinking about an Interface too.
    We could provide a very efficient implementation for the six built-in range types and leave the (possibly complicated) implementation of special types (that are unpredictable for us) to users who think they really need it.

    I was thinking of something like the following:

    // No type contraints. Users may do whatever they want
    public interface INpgsqlRange<T> : IEquatable<INpgsqlRange<T>>
    {
        T LowerBound { get; }
        T UpperBound { get; }
        bool LowerBoundIsInclusive { get; }
        bool UpperBoundIsInclusive { get; }
        bool LowerBoundInfinite { get; }
        bool UpperBoundInfinite { get; }
        bool IsEmpty { get; }
    }
    
    // Strict type constraints for efficiency and predictability
    readonly struct NpgsqlBuiltInTypeRange<T> : INpgsqlRange<T> where T : struct, IEquatable<T>
    {
        // Move most of NpgsqlRange<T> here but simplify it and make it more efficient due
         // to the stricter type constraints
    }
    
    // User-visible classes for the six built-in range types
    public readonly struct NpgsqlInt4Range : INpgsqlRange<int>
    {
        readonly NpgsqlBuiltInTypeRange<int> _npgsqlRangeImplementation;
    
        public NpgsqlInt4Range(int lowerBound, int upperBound)
            : this(lowerBound, true, false, upperBound, true, false) { }
    
        public NpgsqlInt4Range(int lowerBound, bool lowerBoundIsInclusive, int upperBound,
            bool upperBoundIsInclusive)
            : this(lowerBound, lowerBoundIsInclusive, false, upperBound, upperBoundIsInclusive, false) { }
    
        public NpgsqlInt4Range(int lowerBound, bool lowerBoundIsInclusive, bool lowerBoundInfinite,
            int upperBound, bool upperBoundIsInclusive, bool upperBoundInfinite)
            : this(lowerBound, upperBound, NpgsqlRangeHelper.EvaluateBoundaryFlags(
                lowerBoundIsInclusive,
                upperBoundIsInclusive,
                lowerBoundInfinite,
                upperBoundInfinite)) { }
    
        internal NpgsqlInt4Range(int lowerBound, int upperBound, RangeFlags flags)
        {
            _npgsqlRangeImplementation = new NpgsqlBuiltInTypeRange<int>(lowerBound, upperBound, flags);
        }
    
        public bool Equals(INpgsqlRange<int> other) => _npgsqlRangeImplementation.Equals(other);
    
        public int LowerBound => _npgsqlRangeImplementation.LowerBound;
    
        public int UpperBound => _npgsqlRangeImplementation.UpperBound;
    
        public bool LowerBoundIsInclusive => _npgsqlRangeImplementation.LowerBoundIsInclusive;
    
        public bool UpperBoundIsInclusive => _npgsqlRangeImplementation.UpperBoundIsInclusive;
    
        public bool LowerBoundInfinite => _npgsqlRangeImplementation.LowerBoundInfinite;
    
        public bool UpperBoundInfinite => _npgsqlRangeImplementation.UpperBoundInfinite;
    
        public bool IsEmpty => _npgsqlRangeImplementation.IsEmpty;
    }
    
    // Do the same for NpgsqlInt8Range, NpgsqlNumRange, ...
    
    // We'll need this for the TypeHandler and for NpgsqlBuiltInTypeRange<T> so it
    // better lives on its own
    static class NpgsqlRangeHelper
    {
        public static RangeFlags EvaluateBoundaryFlags(bool lowerBoundIsInclusive, bool upperBoundIsInclusive, bool lowerBoundInfinite, bool upperBoundInfinite)
        {
            // Existing implementation from NpgsqlRange<T>
        }
    
        public static RangeFlags EvaluateBoundaryFlags<T>(INpgsqlRange<T> range)
            => EvaluateBoundaryFlags(range.LowerBoundIsInclusive, range.UpperBoundIsInclusive, range.LowerBoundInfinite, range.LowerBoundInfinite);
    }
  5. roji commented on Jun 3, 2018

    @roji
    Member

    Regarding the interface idea, it works well for writing ranges to PostgreSQL, but what do you for reading, i.e. how does Npgsql know which concrete type to instantiate and return?

    One option is to allow users to specify the concrete type simply by calling reader.GetFieldValue<MyRangeType>(index), and assuming that MyRangeType implements the interface it will work (but the interface is read-only, so how does it get constructed/populated...). In addition you have to think of what is returned from reader.GetValue() (i.e. no user-specified type) - it could be a generic implementation similar to today.

  6. Brar commented on Jun 3, 2018

    @Brar
    Member

    One option is to allow users to specify the concrete type simply by calling reader.GetFieldValue(index), and assuming that MyRangeType implements the interface it will work (but the interface is read-only, so how does it get constructed/populated...).

    We could require it to implement an additional interface for setting values like

    public interface INpgsqlReadableRange<T> : INpgsqlRange<T>
    {
        void SetEmpty();
        void SetValues(T lowerBound, T upperBound,
                                bool lowerBoundIsInclusive, bool UpperBoundIsInclusive,
                                bool lowerBoundInfinite, bool upperBoundInfinite);
    }

    If users don't like to make those methods public they could still implement the interface explicitly.

    In addition you have to think of what is returned from reader.GetValue() (i.e. no user-specified type) - it could be a generic implementation similar to today.

    This is what I was thinking of too.
    But in this case it would just be a bare minimum implementation of the interface without any whistles and bells.

  7. Brar commented on Jun 3, 2018

    @Brar
    Member

    ...and if this isn't enough for some user we still have the type handler hooks where it should be possible to do whatever you want.

  8. roji commented on Jun 3, 2018

    @roji
    Member

    Considering that a concrete range implementation would typically be a struct, having mutators on the interface would make the struct mutable, which is a pretty bad idea IMHO.

    Another consequence of the interface is that writing will almost surely involve boxing...

    Guys, don't forget that nobody has ever actually complained about the range support, and that the main advantage of the user-defined type is the ability to define discreteness, which seems even more of an exotic requirement... I'd rather avoid a problematic solution (mutable struct, boxing, requirement to define a type handler, which is a really advanced thing) to a problem which I'm not sure people actually have...

    Don't forget that if someone really wants to, they can define their own struct (or class) and define implicit casts between that and the current NpgsqlRange<T>. I think that would solve the issue without requiring anything complicated on the Npgsql side...

  9. Brar commented on Jun 3, 2018

    @Brar
    Member

    Considering that a concrete range implementation would typically be a struct, having mutators on the interface would make the struct mutable, which is a pretty bad idea IMHO.

    Another consequence of the interface is that writing will almost surely involve boxing.

    Both of this would only be true for the user defined range types where we expect close to zero usage.
    I'm pretty sure that we can avoid boxing for the six built-in range types, make them immutable and even make them more efficient due to the stricter type constraints on our own implementation.

    Guys, don't forget that nobody has ever actually complained about the range support.

    The reason I'm engaging here is that I just found out that the following simple test fails.
    While this is a problem we inherit from the PostgreSQL backend, it could certainly be overcome by overriding Equals in a class like NpgsqlInt4Range.

    [Test]
    public void SimpleRoundTripProblem()
    {
        var testValue = new NpgsqlRange<int>(0,1);
        using (var conn = OpenConnection(ConnectionString))
        {
            using (var cmd = new NpgsqlCommand("SELECT @p", conn))
            {
                cmd.Parameters.AddWithValue("p", NpgsqlDbType.Range | NpgsqlDbType.Integer, testValue);
                using (var reader = cmd.ExecuteReader())
                {
                    reader.Read();
                    Assert.That(reader.GetValue(0), Is.EqualTo(testValue));
                }
            }
        }
    }
  10. austindrenski commented on Jun 3, 2018

    @austindrenski
    ContributorAuthor

    @roji wrote:

    Considering that a concrete range implementation would typically be a struct, having mutators on the interface would make the struct mutable, which is a pretty bad idea IMHO.

    Very much agree. But what prevents us from using a reflection-based invocation of a matching constructor?


    @roji wrote:

    Guys, don't forget that nobody has ever actually complained about the range support.

    To be fair, I think of this as a chicken and egg problem. I have a few real world projects that could creatively use user-defined ranges, but avoid them because the ORM support is limited.


    @Brar wrote:

    The reason I'm engaging here is that I just found out that the following simple test fails.
    While this is a problem we inherit from the PostgreSQL backend, it could certainly be overcome by overriding Equals in a class like NpgsqlInt4Range.

    I had this in mind while reworking on the NpgsqlRange<T>. It's a difficult problem to address without an awareness of continuous and discrete data types.

    It's worsened by the PostgreSQL canonicalization of [a, b] to [a, b + ε).

    For those following along without the test suite, here's the output of the unit test:

    Assert.Equal() Failure
    Expected: [0,1]
    Actual:   [0,2)
    

    @Brar wrote:

    @austindrenski wrote:

    Initially, I was playing around with the idea of an interface based approach, whereby user-defined range types are implemented as structs with some INpgsqlRange interface....but that gets complicated quickly.

    Is this really the case?
    What makes it complicated?

    I found it complicated due to the problem you demonstrated above.

    In my early drafts of the interface, I found myself wanting to require a add an epsilon delegate. Some Func<T, T> that would increment or decrement a bound by some type-appropriate value. This would allow the client to construct the canonicalized form used by PostgreSQL.

    I don't think this is out of the realm of possibilities, since user-defined ranges will likely be the domain of advanced scenarios. But it does add a layer of complexity.

    We punted the canonicalization altogether for 4.0.0 to move forward with the obvious improvements, but this is still a critical limitation of the range types.


    Addressing canonicalization

    One option would be to address the canonicalization of builtin types, before expanding support for user-defined ranges.

    This could take the form of private non-generic methods on NpgsqlRange<T> to handle of bound comparisons for the standard mappings. It's possible this could be done without boxing, and it could remove the canonicalization discrepancy that currently exists.

  11. Brar commented on Jun 3, 2018

    @Brar
    Member

    But what prevents us from using a reflection-based invocation of a matching constructor?

    This is another option. Yet we don't have a way to enforce the presence of a certain constructor at compile time and reflection tends to be slow.

    Anyways this would only be a problem for user defined range types which probably are a 0.01% case and most certainly not worth any headache.

    To be fair, I think of this as a chicken and egg problem. I have a few real world projects that could creatively use user-defined ranges, but avoid them because the ORM support is limited.

    I very much agree. I tend to use daterange and tsrange all the time but until now I've never let them map to anything outside the database (I usually split them into two dates or timestamps from/to).

    One option would be to address the canonicalization of builtin types, before expanding support for user-defined ranges.

    👍

  12. austindrenski commented on Jun 3, 2018

    @austindrenski
    ContributorAuthor

    I've opened #1974 to update NpgsqlRange<T> to use ReadOnlySpan<char> per some pre-4.0.0 discussion.

    @Brar I've included your unit test as Roundtrip_canonicalization_causes_issues. The condition is flipped such that passing means the issue exists.

  13. Brar commented on Jun 3, 2018

    @Brar
    Member

    @austindrenski nice!

    BTW I just found out that we also can't roundtrip an empty tstzrange with the current dev branch.
    My guess is that it's due to #1940

  14. austindrenski commented on Jun 3, 2018

    @austindrenski
    ContributorAuthor

    @Brar Can you post a test?

  15. 10 remaining items

  16. added this to the 4.1 milestone on Jun 24, 2018
  17. modified the milestones: 4.1, 5.0 on Sep 8, 2019
  18. modified the milestones: 5.0, 6.0.0 on Sep 17, 2020
  19. modified the milestones: 6.0.0, 7.0.0 on Oct 3, 2021
  20. modified the milestones: 7.0.0, Backlog on Oct 5, 2021
  21. added theissue type on Jun 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions