Repository navigation
Revisiting NpgsqlRange<T> boundaries and support for range literals - #1939
Conversation
…g well-known text.
roji
left a comment
There was a problem hiding this comment.
Thanks for this @austindrenski, I've been wanting to clean up the Npgsql built-in types for a while but never found the time. This definitely looks much better than before, and much more well-documented!
Apart from my review comments:
Currently, the fully specified constructor takes 6 arguments:
That's true, but that's only the fully-specified constructor. Initializing from a string has the perf disadvantage of having the user allocating a string - which isn't to say that string initialization isn't a good feature to have.
I initially wrote Parse for a project that included Microsoft.Extensions.Primitives.StringSegment. I would prefer to keep using StringSegment here (nice API, reduce allocations), but it could be rewritten with low level string/char[] methods, if the added dependency is untenable...
The intention to keep the parsing zero-allocation is great. But a few caveats...
First, Span<char> is now supposed to provide more or less the same thing as StringSegment - allocation-free slicing. See also https://github.com/dotnet/corefx/issues/20378#issuecomment-329902618 on StringSegment vs. ReadOnlySpan<char> - the latter is preferable, especially for our case where it really is a stack-only operation (no need to ever keep it in the heap).
Second, there are several places where Npgsql internally could benefit from Span - see mainly #1900 but also #1712. So I think it makes much more sense to add a dependency on System.Memory (which we'll be using anyway) rather than on Microsoft.Extensions.Primitives (which by the way I think your PR omits from the csproj).
However, in 4.0.0 itself we don't use Span yet, so I'm leaning towards adding Span only for 4.1 - it would be weird to add a dependency just for NpgsqlRange<T>.Parse(), if you know what I mean. So I'm thinking it may make sense to implement it inefficiently for 4.0 and then do it with Span for 4.1.
What do you think?
| LowerBound = lowerBound; | ||
| UpperBound = upperBound; | ||
| Flags = flags; | ||
| RangeFlags result = RangeFlags.None; |
| /// <returns> | ||
| /// The boundary characteristics. | ||
| /// </returns> | ||
| private static RangeFlags EvaluateBoundaryFlags(bool lowerBoundIsInclusive, bool upperBoundIsInclusive, bool lowerBoundInfinite, bool upperBoundInfinite) |
There was a problem hiding this comment.
nit: please omit private on methods as it is the default
| /// <summary> | ||
| /// True if the lower bound is part of the range (i.e. inclusive); otherwise, false. | ||
| /// </summary> | ||
| public bool LowerBoundIsInclusive => Flags.HasFlag(RangeFlags.LowerBoundInclusive); |
There was a problem hiding this comment.
Note that Flags.HasFlag() used to be very inefficient compared to simply doing the bit operation - this is why I've always avoided it. .NET Core 2.1 adds JIT intrinstics for this, making Enum.HasFlag() fast, but I honestly don't see the value over just doing a bitwise and operation, which would also be fast under .NET Core 2.0 and .NET Framework. So I'd revert that specific change (although do leave your change to a getter-only expression property).
There was a problem hiding this comment.
Ah, I wasn't thinking about the perf implications for the full framework. I'll revert the Enum.HasFlag() checks throughout the file.
Though, if those intrinsics are ever backported, it would be a nice readability improvement to use Enum.HasFlag(). I'll add a code comment citing this thread for posterity.
|
|
||
| LowerBoundIsInclusive = lowerBoundIsInclusive; | ||
| UpperBoundIsInclusive = upperBoundIsInclusive; | ||
| // TODO: We need to check if the bounds are implicitly empty. E.g. '(1,1)' or '(0,0]'. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| : (LowerBoundInfinite ? 0 : LowerBound.GetHashCode()) + | ||
| (UpperBoundInfinite ? 0 : UpperBound.GetHashCode()); | ||
|
|
||
| /// <inheritdoc /> |
There was a problem hiding this comment.
Unrelated, but I just realized I replicated this logic in the EF Core provider's NpgsqlRangeTypeMapping.GenerateNonNullSqlLiteral(). Do you want to compare the two and submit a PR which makes EF Core simply call ToString()?
There was a problem hiding this comment.
Sure, I'll take care of that soon.
| { | ||
| sb.Append(LowerBoundIsInclusive ? '[' : '('); | ||
|
|
||
| sb.Append(LowerBoundIsInclusive ? '[' : '('); |
There was a problem hiding this comment.
Any reason for making the distinction between inclusive/exclusive when the bound is infinite? The previous code just outputted ( for infinity...
There was a problem hiding this comment.
This change was motivated by the PostgreSQL docs:
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.
Since the constructor rewrite converts inclusive-infinity to exclusive-infinity, the distinction here is no longer needed. The string representation of the lower bound for any initialized NpgsqlRange<T> will only depend on the inclusivity test, because all infinite bounds will be constructed as exclusive.
| if (value.Equals("empty", StringComparison.OrdinalIgnoreCase)) | ||
| return Empty; | ||
|
|
||
| bool lowerInclusive = value[0] == '['; |
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) |
|
Thanks for the review @roji , I pushed a commit that addresses the line-by-line comments and responded to those directly where you had specific questions. I'll address the general comments here:
This sounds great. I hadn't considered using the new
I made some unrelated changes in the
I'm inclined to introduce the new dependency with the major version increment, given that there are plans to make extensive use of it throughout this major version. That said, I think this falls squarely into the project/package management domain. If you find it sensible to hold back the dependency until its providing more value, I'm on board with that too. EDIT: After reviewing your comments about incorporating |
roji
left a comment
There was a problem hiding this comment.
Thanks for the changes. See below for the string parsing discussion (and a few comments in the code as well).
However, in 4.0.0 itself we don't use Span yet, so I'm leaning towards adding Span only for 4.1 - it would be weird to add a dependency just for NpgsqlRange.Parse(), if you know what I mean. So I'm thinking it may make sense to implement it inefficiently for 4.0 and then do it with Span for 4.1.
I'm inclined to introduce the new dependency with the major version increment, given that there are plans to make extensive use of it throughout this major version.
That said, I think this falls squarely into the project/package management domain. If you find it sensible to hold back the dependency until its providing more value, I'm on board with that too.
I understand, and to be honest I'm a bit torn on this. Note that Npgsql minor versions also introduce breakage and new dependencies; in that sense it follows the old PostgreSQL versioning scheme (where 9.6 was a "major" version compared to 9.5), rather than semver. So there's nothing blocking us from adding System.Memory in 4.1.
Let's leave this dependency out for now - I'd rather see everything out and stabilized before starting to adopt Span in the Npgsql codebase (which we'll definitely do).
There was a problem hiding this comment.
These curlies are redundant, please remove.
Actually if you remove the StringSegment dependency the need for a switch may go away.
There was a problem hiding this comment.
As above, please revert to continue supporting net451 for now.
There was a problem hiding this comment.
Yikes, meant to be excluded from the commit. Removing.
There was a problem hiding this comment.
I only now noticed that Microsoft.Extensions.Primitives doesn't support pre-netstandard2.0, which is another point against it in the context of Npgsql.
It's not that I care so much about supporting net45/net451 specifically, but continuing to support these platforms doesn't really cost us anything at the moment, so I wouldn't want to drop support for them just because of range string parsing...
There was a problem hiding this comment.
Same as above, meant to exclude that again.
There was a problem hiding this comment.
I personally don't see huge value in having these strings as constants, but I don't have much against it either :) OK to leave like this if you prefer.
There was a problem hiding this comment.
I think there could be some value in documenting that these literals are based on PostgreSQL, rather than Npgsql. But I can use inline comments for the same effect. Let me know if you change your mind on keep/remove.
|
|
||
| LowerBoundIsInclusive = lowerBoundIsInclusive; | ||
| UpperBoundIsInclusive = upperBoundIsInclusive; | ||
| // TODO: We need to check if the bounds are implicitly empty. E.g. '(1,1)' or '(0,0]'. |
There was a problem hiding this comment.
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.
…by PostgreSQL. Added comment about the decision to keep bitwise operators. The following commit addresses comments about the implementation of NpgsqlRange<T>.Parse()
75d52f8 to
d95f053
Compare
Okay, I've removed the dependency on Type constraintsI would like to constrain the type parameter with It seems reasonable to constrain the type parameter in this way as ranges are inherently modeling a comparable/equatable idea. Further, the PostgreSQL's built in range types are mapped to CLR types that implement these interfaces. // before
public readonly struct NpgsqlRange<T> : IEquatable<NpgsqlRange<T>>
{
}
// after
public readonly struct NpgsqlRange<T> : IEquatable<NpgsqlRange<T>>
where T : IComparable<T>, IEquatable<T>
{
}Additional bounds checksWith This also allows for the detection of malformed ranges where the lower bound is greater than the upper bound, such as Bitwise flagsSince we're sticking with bitwise flag checks, I've added a few known states to the /// <summary>
/// Represents characteristics of range type boundaries.
/// </summary>
/// <remarks>
/// See: https://www.postgresql.org/docs/current/static/rangetypes.html
/// </remarks>
[Flags]
enum RangeFlags : byte
{
... // omitted
/// <summary>
/// Both the lower and upper bounds are inclusive.
/// </summary>
Inclusive = LowerBoundInclusive & UpperBoundInclusive,
/// <summary>
/// One of the bounds is inclusive and the other is exclusive.
/// </summary>
Mixed = LowerBoundInclusive ^ UpperBoundInclusive,
/// <summary>
/// The lower bound is both inclusive and infinite. This represents an error condition.
/// </summary>
LowerInclusiveInfinite = LowerBoundInclusive & LowerBoundInfinite,
/// <summary>
/// The upper bound is both inclusive and infinite. This represents an error condition.
/// </summary>
UpperInclusiveInfinite = UpperBoundInclusive & UpperBoundInfinite
} |
…NpgsqlRange<T>.Parse(string). Added type constraints to make range checks possible. Editing exception messages to align with what PostgreSQL would throw given the same conditions. Also reworking the RangeFlags enum to explicitly define combination states (since we're sticking with bitwise operations). This commit also incorporates checks for implicit emptiness where conditions allow.
Based on npgsql/npgsql#1939 (comment). Note that this commit removes subtype mapping handling. (#420)
Don't forget that in the end, PostgreSQL is the one responsible for making interpreting the range and raising errors. We can check for some simple error states client-side, but at the end of the day we send a range to PostgreSQL, which raises an error back if there's an issue. I'd like to avoid a complicated client-side validation which would add very little value (since validation already occurs server-side). Another note is that at least theoretically, there may be a PostgreSQL range (possibly user-defined) over a type, whose C# analogue happens to not be equatable and/or comparable with itself. A good example may be Let me know what you think. For the rest I'm OK for merging, except that the PR doesn't currently build and imposes the equatable/comparable constraints. |
|
I've removed the At this point, I think the only anticipatable error state that we don't prevent is the UpdatesI think this commit completes the feature scope for this PR. Along with removing those type constraints, 4c4f96735335e387d47c047523d8546aa3cf6e67 also includes some housekeeping fixes and unit tests. Equality and hashesI reworked the equality and hashcode methods to reflect the updated constructors. The unit tests all pass, but I would appreciate another set of eyes on the rewrite. Parser fixesI've fixed a few bugs that were introduced in b55ed19. I've also removed some of the bound-correction logic from the parser, so that bound-correction only ever occurs via the constructors. Unit testsI've added a series of unit tests to parse various range literals. The tests use Type converterIt turns out that this doesn't work: [TypeConverter(typeof(NpgsqlRange<>.RangeTypeConverter))]
public readonly struct NpgsqlRange<T> : IEquatable<NpgsqlRange<T>>
{
// omitted
}Instead, I added this to public static void Register() =>
TypeDescriptor.AddAttributes(
typeof(NpgsqlRange<T>),
new TypeConverterAttribute(typeof(RangeTypeConverter)));Consuming code will need to call this method to register the converter: NpgsqlRange<int>.RangeTypeConverter.Register();
var converter = TypeDescriptor.GetConverter(typeof(NpgsqlRange<int>));I tried to have |
… hashcode functions to reflect new constructor logic. Adding some comments throughout. Bug fixes in the parser introduced in b55ed19 while removing StringSegment. And clarifying some of the bitwise checks. Added unit tests.
roji
left a comment
There was a problem hiding this comment.
See my last two comments about reducing allocations, after this I think we're good to go.
| x.UpperBoundIsInclusive == y.UpperBoundIsInclusive && | ||
| x.LowerBoundInfinite == y.LowerBoundInfinite && | ||
| x.UpperBoundInfinite == y.UpperBoundInfinite; | ||
| => x.Flags == y.Flags |
There was a problem hiding this comment.
Thanks for this simplification, it does looks better. But one last thing - this causes boxing as y.{Lower,Upper}Bound are passed as parameters to Equals.
It should be possible to check if they happen to implement IEquatable<T>, and if so, call its Equals() method, avoiding the boxing. Unless I'm mistaken this check when even be elided by the JIT in runtime. If possible please run a BenchmarkDotNet to ensure there are zero allocations in this operation (the benchmark doesn't need to be checked in, just post its code and results).
|
|
||
| LowerBoundIsInclusive = lowerBoundIsInclusive; | ||
| UpperBoundIsInclusive = upperBoundIsInclusive; | ||
| if (lowerBound is T lower && !lower.Equals(default) && upperBound is T upper && !upper.Equals(default) && lower.Equals(upper)) |
There was a problem hiding this comment.
This check seems unnecessary: lowerBound is T lower, as lowerBound is T, no?
Also, for the Equals() call, see my comment in the comparison equality for checking IEquatable<T> and using it if possible to prevent the boxing allocation.
There was a problem hiding this comment.
lowerBound is T lower returns false when lowerBound is null (even when T is nullable).
It's a nice shorthand around null checks. However, that line is removed in 156c5e55626bde38c9bc554c01fce711098afb95 as a result of addressing the boxing comment.
…so using type checks to simplify equality for value types.
I moved the equality logic in 156c5e55626bde38c9bc554c01fce711098afb95 from I've added a static field I've added a test that parses to
I've never used BenchmarkDotNet, but I'll take a look now. |
This is my first time using this library...so let me know if I've misconfigured something. Benchmark[MemoryDiagnoser]
public class NpgsqlRangeEquality
{
static readonly NpgsqlRange<int> A = NpgsqlRange<int>.Parse("(0,0)");
static readonly NpgsqlRange<int> B = NpgsqlRange<int>.Empty;
[Benchmark(Baseline = true)]
public bool Equals() => A == B;
}Results |
| (((IEquatable<T>)UpperBound)?.Equals(other.UpperBound) ?? other.UpperBound == null); | ||
|
|
||
| public bool Equals(NpgsqlRange<T> other) => this == other; | ||
| return |
There was a problem hiding this comment.
Distinguishing between value types and references types isn't really necessary here. You can keep the code that checks for null, and it should get elided by the JIT.
|
Thanks @austindrenski, merged! For the benchmarks, the most important part for us here is the fact that there are zero allocations. A few nanos here or there make very little difference - especially in a code-path which can be considered non-hot - but allocations quickly add up and have a perf impact on the application as a whole by creating more GC pressure. One issue with your benchmark is that it compares an empty range, which means that the Equals method returns false immediately (at the flag comparison point), and does not actually check the important bit, which is casting to See also my comment about distinguishing between value and references types in the equality check. I merged this in the meantime since 4.0 is right around the corner, you can still submit another PR on the above though. |
|
One last comment - I try to follow this guideline for commit messages, especially the 50-char and 72-char line limits, try to keep it in mind for future work. And thanks for all the contributions! |
Also adds a simple benchmark to test parsing allocations. Related: - npgsql#1939 - npgsql#1943
Overview
Range types in PostgreSQL are a breeze, but
NpgsqlRange<T>can be complicated to work with.This PR is focused on improving
NpgsqlRange<T>by:TypeConverterSimplifying construction
Currently, the fully specified constructor takes 6 arguments:
Contrast that with the range literal format in PostgreSQL:
I've added a static method in abbfe29 to parse the PostgreSQL range literal format:
I initially wrote
Parsefor a project that includedMicrosoft.Extensions.Primitives.StringSegment. I would prefer to keep usingStringSegmenthere (nice API, reduce allocations), but it could be rewritten with low levelstring/char[]methods, if the added dependency is untenable...Preventing bad states
Currently,
NpgsqlRange<T>uses private property setters via the constructors:Given the arrival of
readonly struct, I've attempted to rework the initialization logic to:internalconstructor for consistency.bool Enum.HasFlag(Enum).Results:
Adding XML documentation
I've add some basic documentation to
NpgsqlRange<T>andRangeFlags.Including a
TypeConverterI've added a
TypeConverteras an internal nested class that calls up to the staticParse(string)method.Related items
#126 (comment)
#1418 (comment)
#1493