Repository navigation
Description
The problem
Working with NpgsqlRange I've found that the following use cases are a big cumbersome to work with:
- Modifying an existing range
- Infinite values
- Nullable values
Modifying an existing range
Often times I've found that you need to reduce or extend an existing range and I've solved it with:
var oldRange = ...;
var newRange = new NpgsqlRange<T>(
oldRange.LowerBound, oldRange.LowerBoundIsInclusive, oldRange.LowerBoundIsInfinite,
newUpperBound, ..., ...);
This copies three values (the actual bound value, whether it's inclusive, whether it's infinite).
In general any operation when you really need to have one of the bounds in a single variable is difficult to work with due to the fact that you have to carry over the extra 2 satellite values.
Infinite values
Postgres documentation specifies that:
The lower bound of a range can be omitted, meaning that all points less than the upper bound are included in the range. Likewise, if the upper bound of the range is omitted, then all points greater than the lower bound are included in the range. If both lower and upper bounds are omitted, all values of the element type are considered to be in the range.
This is equivalent to considering that the lower bound is "minus infinity", or the upper bound is "plus infinity", respectively. But note that these infinite values are never values of the range's element type, and can never be part of the range. (So there is no such thing as an inclusive infinite bound — if you try to write one, it will automatically be converted to an exclusive bound.)
(emphasis mine)
This implies that, for example, new NpgsqlRange<T>(default(T), true, true, ...) and new NpgsqlRange<T>(default(T), false, true) is exactly the same thing and represents a range with an open left bound.
The main problem with the current interface is that in order for you to specify an infinite bound on either side of the range you need to also specify two extra values (the value and the inclusiveness) which don't make much sense.
Nullable types
I think that in the context of a NpgsqlRange<T>, T should always be non nullable and null should always be allowed as a value for either side of the range. This greatly helps when you have to assemble a range based on two different nullable values.
For example:
T? from = ...;
T? to = ...;
Currently in order to construct a range I would need to write:
new NpgsqlRange<T>(
from.GetValueOrDefault(), ..., !from.HasValue,
to.GetValueOrDefault(), ..., !to.HasValue);
which, as mentioned above, is rather redundant.
Proposed solution
Considering the above issues I propose that we store bounds in appropriate data structures so that their shape can be easily constructed and passed around.
Example implementation
public class Bound<T>
where T : struct // see below (*1)
{
public T Value { get; set; }
public bool IsInclusive { get; set; }
public bool IsInfinite { get; set; }
public static Bound<T> Include(T? bound)
{
return new Bound<T>
{
Value = bound.GetValueOrDefault(),
IsInclusive = bound.HasValue,
IsInfinite = !bound.HasValue,
};
}
public static Bound<T> Exclude(T? bound)
{
return new Bound<T>
{
Value = bound.GetValueOrDefault(),
IsInclusive = false,
IsInfinite = !bound.HasValue,
};
}
public static Bound<T> Open()
{
return new Bound<T>
{
Value = default(T),
IsInclusive = false,
IsInfinite = true,
};
}
}
In addition to this we would need to extend NpgsqlRange with:
- A constructor that accepts two
Bound<T>s - Two getters that return the corresponding
LowerandUpperbounds asBound<T>s
*(1) I'm relatively new to C# and I'd like to support reference types, but I can't seem to find a way to define that while also allowing T?. I believe in C# 8 (with a specific enabled extension) this is a non-issue given that they "fixed" default nullability for reference types.
public class Bound<T>
where T : struct // see below (*1)
{
public static Bound<T> Open()
{
return new Bound<T>
{
Value = bound.GetValueOrDefault(),
IsInclusive = false,
IsInfinite = !bound.HasValue,
};
}
...
}
Usage examples:
In order to modify an existing range you could have:
var oldRange = ...;
var newRange = new NpgsqlRange<T>(oldRange.Lower, Bound<T>.Include(newUpperBound));
For open bounds:
new NpgsqlRange<T>(Bound<T>.Open(), Bound<T>.Exclude(upperBound));
For nullable types:
T? from = ...;
T? to = ...;
new NpgsqlRange<T>(Bound<T>.Include(from), Bound<T>.Exclude(to));
Activity
roji commentedon Jan 5, 2019
See previous issue #570.
I have some detailed responses below, but I'd like to emphasize that we're discussing what seems to me to be a pretty minor API usability issue - the only proposed improvement is not to force the user to use a 6-parameter constructor, in some cases. We haven't heard any complaints about this from other users, and I'm not necessarily inclined to spend too much time (much less introduce any backwards compatibility issues). In any case, I'm pretty sure that C# language restrictions won't make it possible to improve this, as I try to show below. @austindrenski, I think you already looked into this in #570, you may have thoughts on this too.
First, it's important to use accurate terminology. From your examples, it doesn't seem like you're proposing to allow modifying an existing range, but to make the construction of a new one from an existing range easier - by providing a new constructor with less parameters. Actually modifying an existing range is impossible, since NpgsqlRange is a readonly struct and it's good for it to stay that way.
Regarding infinitive bounds, you write:
That's not true for value types. For example,
default(int)is 0, which is very different from an open bound. This is the main reason why a separate bool flag is needed, and "defaultness" cannot be used. We could think about different behavior for reference and value types, but that doesn't seem like a good idea and in any case all frequently-used ranges seem to be over value types (numbers, dates...).Then how does one construct a range over, say, an IPAddress (which is a class)? This is technically possible and even makes sense, and Npgsql is supposed to fully support user-defined range types, so in theory T really can be anything.
That's indeed impossible. C# 8.0 indeed introduces non-nullable references, but at least for now I don't think C# 8.0 allows writing T? in a generic class without a
structconstraint, which restricts the generic type to be over value types only. In C#, nullable value types and nullable reference types are very different things. If you have any other information about this, please share it.Having a class Bound is a definite non-starter for me, as it would imply two heap allocations per range instance. It's possible to define Bound as a struct instead, but I simply can't see any benefit that gives over managing the value, inclusiveness and openness directly without an encapsulating bound structure.
If you really feel strongly about this, then I'd suggest trying to work on a full solution that actually works in C# - for now the ideas above don't seem applicable to me.
austindrenski commentedon Jan 5, 2019
Yes, the ideas here overlap with some previous exploratory work to improve ranges. I'm very sympathetic to the proposals described above, but at this time, I agree with @roji on the intractability of the current challenges and proposed solutions.
There are ways that we could further improve the current
NpgsqlRange<T>, but I think our current plan for major usability improvements is to wait and see what we can do with the range support that will ship with C# 8.0.For immediate relief from constructor-related headaches, I would recommend a static factory class, perhaps with some extension methods for constructing new ranges based on existing ones (e.g.
someRange.WithUpper(newUpperBound)).shoooe commentedon Jan 6, 2019
In all cases. The introduction of
Boundis semantically equivalent to that of the 6 parameters constructor.I'm sorry but this doesn't mean anything unless you know how many people actually use
NpgsqlRange. It also depends on how many people actually kept using it after their first interaction, how many of those are willing to drop by to let you know it's not pleasant to work with, etc...You can consider this your first formal complain.
I'm not sure what you've read there but I was just pointing out that if the third parameter (infinity) is
truethen for Postgres the fact that infinity is included or not (second parameter) makes no difference because it will convert it always to excluded.default(T)is needed only because in case of infinity you are still required to fill out the other two parameters, which is, at the very least, confusing.I'm open to changes. With
Bound<T>.Openyou can define an open bound so if you want you can skip theBound<T>.Exclude(T?)(with nullable) without losing any functionality. I just proposed it because (as you say) "all frequently-used ranges seem to be over value types (numbers, dates...)".I'm not experienced with the nuances of performance tuning in C#, so for me it can also be a
structor whatever equivalent interface you'd like to change it in.I thought I mentioned them above. The interface is really difficult to work with. This simplified things and reduces confusing interfaces like having to define a value
Tand an unnecessary flag (include/exclude) for open bounds.An alternative solution which would solve the "T can only be a value type" problem and the performance issues of a
class:YohDeadfall commentedon Jan 6, 2019
@Jefffrey I like the idea with bounds. It's really simplifies the interface. The perf can be tuned later in a PR.
@roji as I know the range support is limited as it's designed for indexers only.
shoooe commentedon Jan 6, 2019
@austindrenski
Hmm, interesting. I've read a little about C# 8.0 ranges, but I didn't see anything applicable to
NpgsqlRangesince it seems to only support integral ranges.What new features are you referring to exactly?
austindrenski commentedon Jan 6, 2019
Early on there was discussion of various range types (e.g.
Range,LongRange, a futureRange<T>), though recently the LDM notes have only touched onRange.It seems likely that we will only see basic indexer-related integral range support in 8.0, but I would expect the final release notes to give us some indication of possible future extensions (hopefully
Range<T>).On the topic of the
Boundtype mentioned above, I think we've discussed that in the course of a PR a while back (defined as a struct). It's not impossible, but once you start working with that syntax, the benefits become less clear.I'm still with @roji on this one, in that I think we need to see a more detailed specification and example usage here. Your proposal is implementable, but it involves more than just the driver, as it would require additional translation work in the EF Core provider. I'm happy to take on that translation work if the specification is sufficient, but I'm not yet convinced.
Let me look for the previous design discussions, those might help clarify what the inhibiting factors were last time this came up.
roji commentedon Jan 6, 2019
That's partially true, but what other option do we have when prioritizing issues to work on? Note also that there are definitely lots of issues where several people participate in the conversation and vote, when something is painful or limiting. We tend to work on those more than on other issues.
Sorry, that was just me misreading your comment above. You're right.
I'm not sure I understand... A Bound would have exactly the same restriction as NpgsqlRange in terms of nullability. Specifically, writing T? simply isn't possible without constraining the generic type to be a value type, and doing that would mean that NpgsqlRange simply isn't possible anymore. For me that's a non-starter, but if you have other ideas please let us know what they are.
I think this is a non-essential point of the discussion - I'm just saying that if we introduced something like Bound, it would definitely be a struct rather than a class. Class allocation has a significant perf cost since it's done on the heap (rather than the stack), and the garbage collector has to spend time later to collect these instances. This has been shown to be decisive in .NET performance, and a lot of work in .NET infrastructure has gone into eliminating unneeded heap allocations (including in Npgsql). But I don't think your proposal depends on this in any way.
So again, I'm not trying to say the current API is great - it isn't. To make sure there are no misunderstandings, you've raised two different and separate directions:
In any case, as @austindrenski said the best way forward seems to do a proper proposal here, with an API etc. (you started to give some usage examples above, but it needs to be developed into a proposal).
Finally, I'm personally interested in seeing a code sample with the current API that shows that it's really so bad. I've occasionally worked with ranges and with the 6-param constructor, and while it's not ideal I can't say it was that problematic or terrible an experience (considering the time we're spending discussing this :)).
bad enough to warrant such a change? I'm looking for something that's bad enough as to be convincing that something like Bound really is necessary.
shoooe commentedon Jan 7, 2019
Oh yeah sure, it's nitpicking and I'm sure there are other more important issues out there that are definitely more prioritized.
It's just that this is a fairly trivial change (once an API is decided) and can improve the range interface quite a bit.
I didn't know about upcoming ranges (probably after C# 8.0+) so it might be wise to wait for that and see if we can maybe reuse some standard constructs.
If everybody is ok with it, we can close this issue and maybe reopen it when the time comes.
austindrenski commentedon Jan 7, 2019
@Jefffrey Thanks for your understanding on this. We certainly appreciate the feedback and discussion on API improvements, especially when it comes to the types found in the
NpgsqlTypesnamespace.On a personal note, I make heavy use of
NpgsqlRange<T>in a few professional projects, so its usability and performance are always on my radar. If you would like, I can try to CC you on future API and perf discussions related toNpgsqlRange<T>.I'll close this for now, but feel free to keep posting. We can always reopen this when the landscape changes.
shoooe commentedon Jan 7, 2019
@austindrenski I'd appreciate it, thanks. 😄
roji commentedon Jan 7, 2019
I'm sorry if I came across as overly negative on this... Part of the discussion above was complicated with nullability questions and C# 8.0, struct vs. class, etc.
Again, I don't think C# 8 introduces any changes that affect this (namely, the possibility to have a non-constrained generic type and to use T? within it). Regarding introducing something like Bound, even if I personally don't see a big need, I think if a full API proposal is submitted we'd definitely consider it - I really do mean that. This doesn't mean we'd necessarily accept it - it could be argued that instantiating two Bound instances to construct an NpgsqlRange would in fact be more verbose/complicated than the current 6-param constructor, which is why we need a full proposal with a comparison to the current API, etc.