Skip to content

Range API improvement #2314

Open

Description

@YohDeadfall

Originally proposed by @shoooe in npgsql/efcore.pg#785


Motivation

As @shoooe already pointed out, the current API isn't friendly. This proposal is trying to solve it and investigate more natural way to create ranges.

Proposal

public readonly struct NpgsqlRange<T> : IEquatable<NpgsqlRange<T>>
    where T : IEquatable<T>, IComparable<T>
{
    // Creates a range with an exclusive upper bound
    public NpgsqlRange(T lowerBound, T upperBound);
    // Inclusivity is specified by bounds
    public NpgsqlRange(NpgsqlRangeBound<T> lowerBound, NpgsqlRangeBound<T> upperBound);

    public NpgsqlRangeBound<T> LowerBound { get; }
    public NpgsqlRangeBound<T> UpperBound { get; }

    public bool IsEmpty { get; }

    public bool IsCanonical { get; }
    public NpgsqlRange<T> Canonicalize();

    public bool Equals(object other);
    public bool Equals(NpgsqlRange<T> other);
    public int GetHashCode();
}

public readonly struct NpgsqlRangeBound<T> : IEquatable<NpgsqlRangeBound<T>>, IComparable<NpgsqlRangeBound<T>>
    where T : IEquatable<T>, IComparable<T>
{
    public NpgsqlRangeBound(T value);
    public NpgsqlRangeBound(T value, bool isInclusive);

    public bool IsInclusive { get; }
    public bool IsInfinite { get; }
    public T Value { get; }

    public bool Equals(object other);
    public bool Equals(NpgsqlRangeBound<T> other);
    public int CompareTo(NpgsqlRangeBound<T> other);
    public int GetHashCode();

    public static bool operator ==(NpgsqlRangeBound<T> left, NpgsqlRangeBound<T> right);
    public static bool operator !=(NpgsqlRangeBound<T> left, NpgsqlRangeBound<T> right);

    public static bool operator <(NpgsqlRangeBound<T> left, NpgsqlRangeBound<T> right);
    public static bool operator >(NpgsqlRangeBound<T> left, NpgsqlRangeBound<T> right);

    public static implicit operator T?(NpgsqlRangeBound<T value);
}

public static class NpgsqlRangeBound
{
    public static NpgsqlRangeBound<T> Exclusive(T value)
        where T : IEquatable<T>, IComparable<T>;

    public static NpgsqlRangeBound<T> Inclusive(T value)
        where T : IEquatable<T>, IComparable<T>;

    public static NpgsqlRangeBound<T> Infinite()
        where T : IEquatable<T>, IComparable<T>;
}

Activity

  1. austindrenski commented on Feb 5, 2019

    @austindrenski
    Contributor

    IIRC we can't constrain T in this way, since the subtypes of some known ranges lack the IComparable<T>.

  2. austindrenski commented on Feb 5, 2019

    @austindrenski
    Contributor

    Some more thoughts:

    • Why not have those factory methods on the bound itself?
    • It might be trivially small, but how does this impact the overall footprint of a range?
  3. khellang commented on Feb 5, 2019

    @khellang
    Contributor

    Why not make the bounds themselves nullable? Why force lower and upper bounds only to store a field to tell whether it's infinite or not?

    A missing bound means it's infinite. Example:

    public readonly struct NpgsqlRange<T> : IEquatable<NpgsqlRange<T>>
    {
        public NpgsqlRange(NpgsqlRangeBound<T>? lowerBound, NpgsqlRangeBound<T>? upperBound)
        {
            LowerBound = lowerBound;
            UpperBound = upperBound;
        }
    
        public NpgsqlRangeBound<T>? LowerBound { get; }
    
        public NpgsqlRangeBound<T>? UpperBound { get; }
    }

    By modeling the type like this, you'll prevent error conditions like the following:

    /// <summary>
    /// The lower bound is both inclusive and indefinite. This represents an error condition.
    /// </summary>
    LowerInclusiveInfinite = LowerBoundInclusive | LowerBoundInfinite,
    /// <summary>
    /// The upper bound is both inclusive and indefinite. This represents an error condition.
    /// </summary>
    UpperInclusiveInfinite = UpperBoundInclusive | UpperBoundInfinite

    • Why not have those factory methods on the bound itself?

    It's common to have non-generic static classes with generic factory methods to allow C# type inference, i.e.

    var lower = NpgsqlRangeBound<int>.Inclusive(42);
    
    // vs
    
    var upper = NpgsqlRangeBound.Exclusive(1337);
  4. khellang commented on Feb 5, 2019

    @khellang
    Contributor

    There's no need to constrain T on IEquatable<T> either, as you can implement equality and hash code using EqualityComparer<T>.Default, which is now a JIT intrinsic (https://github.com/dotnet/coreclr/issues/6688) 😄

  5. austindrenski commented on Feb 5, 2019

    @austindrenski
    Contributor

    It's common to have non-generic static classes with generic factory methods to allow C# type inference, i.e.

    Oops, that's right. Wasn't thinking about the associated noise of static methods on a generic class!

  6. austindrenski commented on Feb 6, 2019

    @austindrenski
    Contributor

    Why not make the bounds themselves nullable?

    Sigh, that would be the silver bullet.... but some range subtypes are reference types, and IIRC there's a compilation error associated with mixing nullables/generics.

    (I did some work on this last time we updated these types, and ran into the above problem. I'll link the relevant issues/PRs when I'm off mobile.)

  7. khellang commented on Feb 6, 2019

    @khellang
    Contributor

    but some range subtypes are reference types, and IIRC there's a compilation error associated with mixing nullables/generics.

    NpgsqlRangeBound<T> is a struct, structs can be wrapped in Nullable<T>. I'm not saying we should make T nullable (which would force us to constrain it to struct and thus excluding reference types). Whether T is a reference type or not, doesn't really matter 😄

    There's nothing stopping you from doing

    var range = new NpgsqlRange<string>("foo", "bar"); // assuming implicit operator for NpgsqlRangeBound<T>
    
    var hasLower = range.LowerBound.HasValue; // true
    var lowerValue = range.LowerBound.Value; // "foo";
    
    var hasUpper = range.UpperBound.HasValue; // true;
    var upperValue = range.UpperBound.Value; // "bar";
  8. austindrenski commented on Feb 6, 2019

    @austindrenski
    Contributor

    NpgsqlRangeBound<T> is a struct, structs can be wrapped in Nullable<T>. I'm not saying we should make T nullable (which would force us to constrain it to struct and thus excluding reference types).

    Oh, that's a great point (and possibly the best argument in favor of this proposal so far).

  9. YohDeadfall commented on Feb 6, 2019

    @YohDeadfall
    ContributorAuthor

    @austindrenski @khellang What types do lack of comparison interfaces?

    Why not have those factory methods on the bound itself?

    As @khellang said, it is for type inference, but it's not the only reason for that. Another reason is using static directive which accepts only non-generic types or closed generics. So you can do something like in the example below:

    using static NpgsqlTypes.NpgsqlRangeBound;
    
    namespace Samples
    {
        public void UsingDirective()
        {
            var range = new NpgsqlRange(Exclusive(20), Inclusive(30));
        }
    }

    Why not make the bounds themselves nullable? Why force lower and upper bounds only to store a field to tell whether it's infinite or not?

    Memory footprint (triple size of IntPtr instead of two) and an unusable way to check that the bound is inclusive or exclusive, but the last one is minor. It could be fixed by extension methods on NpgsqlRangeBound<T>.

    public static bool IsInclusive<T>(this NpgsqlRangeBound2<T>? bound)
        where T : IEquatable<T>, IComparable<T>
        => bound.HasValue && bound.Value.IsInclusive;
    var range = new NpgsqlRange<int>(10, 20);
    var isInclusive = range.LowerBound.IsInclusive();

    But making bounds nullable will provide a PostgeSQL like way to create ranges. It's a pro of nullability.

  10. khellang commented on Feb 6, 2019

    @khellang
    Contributor

    an unusable way to check that the bound is inclusive or exclusive

    Unusual, maybe. But it reflects the problem you're trying to model perfectly. If it doesn't have a lower bound, there's no point in checking if it's inclusive or not.

  11. roji commented on Feb 6, 2019

    @roji
    Member

    Take a look at dotnet/csharplang#2194. Now that nullable references are coming, it makes sense for C# to allow you do do T? without constraining to value types or references types. However, the discussion is ongoing and it's very unclear whether this will make it in. It might be a good idea to postpone this discussion a little bit until that's clarified.

  12. roji commented on Feb 6, 2019

    @roji
    Member

    Some other notes...

    an unusable way to check that the bound is inclusive or exclusive, but the last one is minor

    At least as far as the check is concerned, that makes a lot of sense to me - you can't check if a bound is inclusive or exclusive if there's no bound (i.e. it's infinity). So it seems OK to ask users to do bound?.IsInclusive and handle the null case. However, I'm still hoping we'll be able to make T itself nullable, rather than the bound (see previous comment).

    How do you propose to handle inclusivity? It seems like we should default to lower bounds being inclusive and upper ones being exclusive (seems pretty standard). Since we don't want to force the user to specify inclusivity all the time, this may mean that the bound's inclusivity should be nullable; if it's unspecified, the range will automatically treat it as inclusive for lower, and exclusive for upper. This does complicate the idea of having IsInclusive (or IsInclusive()), because there's no good answer for the null case - but that seems OK to me. What do you guys think?

    Also, I think we should definitely keep some simpler constructor on the range itself, which don't involve NpgsqlRangeBound. We want the user to just be able to specify values, and I really don't think we should go into implicit cast operators - those can be quite dangerous.

  13. YohDeadfall commented on Feb 6, 2019

    @YohDeadfall
    ContributorAuthor

    Good point, @khellang, but it's possible to incapsulate nullability check logic into the NpgsqlRangeBound<T>, so it will throw an exception if there's no value in it. Otherwise, it will return it. Even more if Microsofties implement the proposal @roji mentioned, we could ad an implicit cast to T?.

    By the way, PostgreSQL allows you to specify inclusive null bounds even if it means the same as exclusive.

  14. khellang commented on Feb 6, 2019

    @khellang
    Contributor

    it's possible to incapsulate nullability check logic into the NpgsqlRangeBound<T>, so it will throw an exception if there's no value in it.

    @YohDeadfall Yeah, that's essentially what Nullable<T> does. I guess that could be baked into the NpgsqlRangeBound<T> type, but if you want to prevent an exception being thrown, instead of writing

    var isInclusive = range.Lower.HasValue && range.Lower.Value.IsInclusive;
    
    // or
    
    var isInclusive = (range.Lower ?? default).IsInclusive;
    
    // or
    
    var isInclusive = range.Lower?.IsInclusive ?? false;

    You'd have to write

    var isInclusive = !range.Lower.IsInfinite && range.Lower.IsInclusive;

    I'm not seeing the gain. Nullable<T> is a tried and true concept, well understood by .NET developers. It even has language support 😄

    How do you propose to handle inclusivity?

    @roji I'm not a big fan of making IsInclusive nullable, because the HasValue and default value propagation everywhere.

    I'm thinking you could work around the verboseness of forcing the user to consider inclusivity by adding a value ctor to NpgsqlRange<T> with the default (inclusive/exclusive) behavior:

    public readonly struct NpgsqlRange<T>
    {
    	public static readonly NpgsqlRange<T> All = new NpgsqlRange<T>(null, null);
    
        public NpgsqlRange(T lowerBound, T upperBound)
    	    : this(NpgsqlRangeBound.Inclusive(lowerBound), NpgsqlRangeBound.Exclusive(upperBound))
    	{
    	}
    
        public NpgsqlRange(NpgsqlRangeBound<T>? lowerBound, NpgsqlRangeBound<T>? upperBound)
        {
        	LowerBound = lowerBound;
            UpperBound = upperBound;
        }
        
        public NpgsqlRangeBound<T>? LowerBound { get; }
        
        public NpgsqlRangeBound<T>? UpperBound { get; }
    }

    You could also add factory methods for ranges with other characteristics:

    public static class NpgsqlRangeBound
    {
        public static NpgsqlRangeBound<T> Inclusive<T>(T value) => new NpgsqlRangeBound<T>(value, isInclusive: true);
    	
    	public static NpgsqlRangeBound<T> Exclusive<T>(T value) => new NpgsqlRangeBound<T>(value, isInclusive: false);
    }
    
    public static class NpgsqlRange
    {
        public static NpgsqlRange<T> Inclusive<T>(T lowerBound, T upperBound) =>
            new NpgsqlRange<T>(NpgsqlRangeBound.Inclusive(lowerBound), NpgsqlRangeBound.Inclusive(upperBound));
    	
    	public static NpgsqlRange<T> Exclusive<T>(T lowerBound, T upperBound) =>
            new NpgsqlRange<T>(NpgsqlRangeBound.Exclusive(lowerBound), NpgsqlRangeBound.Exclusive(upperBound));
    	
    	public static NpgsqlRange<T> InclusiveExclusive<T>(T lowerBound, T upperBound) =>
            new NpgsqlRange<T>(NpgsqlRangeBound.Inclusive(lowerBound), NpgsqlRangeBound.Exclusive(upperBound));
    	
    	public static NpgsqlRange<T> ExclusiveInclusive<T>(T lowerBound, T upperBound) =>
            new NpgsqlRange<T>(NpgsqlRangeBound.Exclusive(lowerBound), NpgsqlRangeBound.Inclusive(upperBound));
    	
    	public static NpgsqlRange<T> GreaterThan<T>(T lowerBound) => DownTo(NpgsqlRangeBound.Exclusive(lowerBound));
    
    	public static NpgsqlRange<T> AtLeast<T>(T lowerBound) => DownTo(NpgsqlRangeBound.Inclusive(lowerBound));
    	
    	public static NpgsqlRange<T> LessThan<T>(T upperBound) => UpTo(NpgsqlRangeBound.Exclusive(upperBound));
    	
    	public static NpgsqlRange<T> AtMost<T>(T upperBound) => UpTo(NpgsqlRangeBound.Inclusive(upperBound));
    	
    	public static NpgsqlRange<T> DownTo<T>(NpgsqlRangeBound<T> lowerBound) => new NpgsqlRange<T>(lowerBound, null);
    	
    	public static NpgsqlRange<T> UpTo<T>(NpgsqlRangeBound<T> upperBound) => new NpgsqlRange<T>(null, upperBound);
    	
    	public static NpgsqlRange<T> All<T>() => NpgsqlRange<T>.All;
    }

    (You could even add a using static for NpgsqlRangeBound to shorten the code even more)

  15. 8 remaining items

  16. shoooe commented on Feb 7, 2019

    @shoooe

    Oh dear, I'm having a deja-vù.

    I just want to crosspost that one problem with the following:

    public NpgsqlRange(T lowerBound, bool lowerBoundIsInclusive, T upperBound, bool upperBoundIsInclusive)
    

    is that of constructing a range from one of the bounds of another range.

    Comparing:

    var range = new NpgsqlRange<T>(otherRange.LowerBound, ...);
    

    with:

    var range = new NpgsqlRange<T>(otherRange.LowerBound, otherRange.LowerBoundIsInclusive, ...);
    

    To be fair, with 3 values it was way worse. The latter is not as readable as the one above, but acceptable, I guess.

  17. YohDeadfall commented on Feb 24, 2019

    @YohDeadfall
    ContributorAuthor

    Opened dotnet/corefx#35420 to add the range type to the base class library.

  18. added this to the Backlog milestone on May 13, 2020
  19. modified the milestones: Backlog, 6.0.0 on Sep 20, 2020
  20. modified the milestones: 6.0.0, Backlog on Oct 5, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions