You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Determining if NpgsqlRange<T> is implicitly empty #1943
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.
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.
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.
@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>?
Then, we could add a discrete parameter to the fully-specified constructor:
publicNpgsqlRange(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 #1939Npgsql<T>.Parse(stringrangeLiteral);// proposedNpgsqlRange<T>.Parse(stringrangeLiteral,booldiscrete);
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.
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?
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 wantpublicinterfaceINpgsqlRange<T>:IEquatable<INpgsqlRange<T>>{TLowerBound{get;}TUpperBound{get;}boolLowerBoundIsInclusive{get;}boolUpperBoundIsInclusive{get;}boolLowerBoundInfinite{get;}boolUpperBoundInfinite{get;}boolIsEmpty{get;}}// Strict type constraints for efficiency and predictabilityreadonlystructNpgsqlBuiltInTypeRange<T>:INpgsqlRange<T>whereT: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 typespublicreadonlystructNpgsqlInt4Range:INpgsqlRange<int>{readonlyNpgsqlBuiltInTypeRange<int>_npgsqlRangeImplementation;publicNpgsqlInt4Range(intlowerBound,intupperBound):this(lowerBound,true,false,upperBound,true,false){}publicNpgsqlInt4Range(intlowerBound,boollowerBoundIsInclusive,intupperBound,boolupperBoundIsInclusive):this(lowerBound,lowerBoundIsInclusive,false,upperBound,upperBoundIsInclusive,false){}publicNpgsqlInt4Range(intlowerBound,boollowerBoundIsInclusive,boollowerBoundInfinite,intupperBound,boolupperBoundIsInclusive,boolupperBoundInfinite):this(lowerBound,upperBound,NpgsqlRangeHelper.EvaluateBoundaryFlags(lowerBoundIsInclusive,upperBoundIsInclusive,lowerBoundInfinite,upperBoundInfinite)){}internalNpgsqlInt4Range(intlowerBound,intupperBound,RangeFlagsflags){_npgsqlRangeImplementation=newNpgsqlBuiltInTypeRange<int>(lowerBound,upperBound,flags);}publicboolEquals(INpgsqlRange<int>other)=>_npgsqlRangeImplementation.Equals(other);publicintLowerBound=>_npgsqlRangeImplementation.LowerBound;publicintUpperBound=>_npgsqlRangeImplementation.UpperBound;publicboolLowerBoundIsInclusive=>_npgsqlRangeImplementation.LowerBoundIsInclusive;publicboolUpperBoundIsInclusive=>_npgsqlRangeImplementation.UpperBoundIsInclusive;publicboolLowerBoundInfinite=>_npgsqlRangeImplementation.LowerBoundInfinite;publicboolUpperBoundInfinite=>_npgsqlRangeImplementation.UpperBoundInfinite;publicboolIsEmpty=>_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 ownstaticclassNpgsqlRangeHelper{publicstaticRangeFlagsEvaluateBoundaryFlags(boollowerBoundIsInclusive,boolupperBoundIsInclusive,boollowerBoundInfinite,boolupperBoundInfinite){// Existing implementation from NpgsqlRange<T>}publicstaticRangeFlagsEvaluateBoundaryFlags<T>(INpgsqlRange<T>range)=>EvaluateBoundaryFlags(range.LowerBoundIsInclusive,range.UpperBoundIsInclusive,range.LowerBoundInfinite,range.LowerBoundInfinite);}
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.
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
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.
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...
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.
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?
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.
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:
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?
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.
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.
Activity
austindrenski commentedon May 21, 2018
@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
INpgsqlRangeinterface....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>andIComparable<T>constraint toNpgsqlRange<T>?Then, we could add a
discreteparameter to the fully-specified constructor:Continuous ranges would be the default, so alternative constructors would gain an optional parameter for
discrete(set tofalse). The discrete parameter would be overridden for built in types, to prevent the construction of a continuousNpgsqlRange<int>.Then the new parser would change from:
roji commentedon May 22, 2018
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.
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.
[-]Determining if NpgsqlRange<T> is implicitly emptying[/-][+]Determining if NpgsqlRange<T> is implicitly empty[/+]Brar commentedon Jun 3, 2018
@austindrenski wrote:
Is this really the case?
What makes it complicated?
@roji wrote:
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:
roji commentedon Jun 3, 2018
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 fromreader.GetValue()(i.e. no user-specified type) - it could be a generic implementation similar to today.Brar commentedon Jun 3, 2018
We could require it to implement an additional interface for setting values like
If users don't like to make those methods public they could still implement the interface explicitly.
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.
Brar commentedon Jun 3, 2018
...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.
roji commentedon Jun 3, 2018
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...Brar commentedon Jun 3, 2018
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.
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.austindrenski commentedon Jun 3, 2018
@roji wrote:
Very much agree. But what prevents us from using a reflection-based invocation of a matching constructor?
@roji wrote:
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:
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:
@Brar wrote:
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 epsilondelegate. SomeFunc<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.0to 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.Brar commentedon Jun 3, 2018
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.
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).
👍
austindrenski commentedon Jun 3, 2018
I've opened #1974 to update
NpgsqlRange<T>to useReadOnlySpan<char>per some pre-4.0.0discussion.@Brar I've included your unit test as
Roundtrip_canonicalization_causes_issues. The condition is flipped such that passing means the issue exists.Brar commentedon Jun 3, 2018
@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
austindrenski commentedon Jun 3, 2018
@Brar Can you post a test?
10 remaining items
Updates NpgsqlRange<T> to use ReadOnlySpan<char>