Skip to content

Revisiting NpgsqlRange<T> boundaries and support for range literals - #1939

Merged
roji merged 5 commits into
npgsql:devfrom
austindrenski:ranges-wkt
May 24, 2018
Merged

roji merged 5 commits into
npgsql:devfrom
austindrenski:ranges-wkt

Conversation

@austindrenski

Copy link
Copy Markdown
Contributor

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:

  1. Simplifying construction
  2. Preventing bad states
  3. Adding XML documentation
  4. Including a TypeConverter

Simplifying construction

Currently, the fully specified constructor takes 6 arguments:

NpgsqlRange<int> range = new NpgsqlRange<int>(0, true, false, 5, true, false);

Contrast that with the range literal format in PostgreSQL:

SELECT '[0,5]'::int4range;

I've added a static method in abbfe29 to parse the PostgreSQL range literal format:

NpgsqlRange<int> range = NpgsqlRange<int>.Parse("[0,5]");

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...

Preventing bad states

Currently, NpgsqlRange<T> uses private property setters via the constructors:

public bool LowerBoundIsInclusive
{
    get => (Flags & RangeFlags.LowerBoundInclusive) != 0;
    private set
    {
        if (value)
            Flags |= RangeFlags.LowerBoundInclusive;
       else
           Flags &= ~RangeFlags.LowerBoundInclusive;
    }
}

Given the arrival of readonly struct, I've attempted to rework the initialization logic to:

  1. Pass the initialization down to the internal constructor for consistency.
  2. Move the bitwise logic out of the setters and into a dedicated method.
  3. Add logic to guard against known bad states.
  4. Add recovery code for bad states that PostgreSQL would correct automatically (e.g. inclusive + infinite).
  5. Replaced the bitwise checks with calls to bool Enum.HasFlag(Enum).

Results:

/// <summary>
/// True if the lower bound is indefinite (i.e. infinite or unbounded); otherwise, false.
/// </summary>
public bool LowerBoundInfinite => Flags.HasFlag(RangeFlags.LowerBoundInfinite);

Adding XML documentation

I've add some basic documentation to NpgsqlRange<T> and RangeFlags.

Including a TypeConverter

I've added a TypeConverter as an internal nested class that calls up to the static Parse(string) method.

Related items

#126 (comment)
#1418 (comment)
#1493

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread src/Npgsql/NpgsqlTypes/NpgsqlRange.cs Outdated
LowerBound = lowerBound;
UpperBound = upperBound;
Flags = flags;
RangeFlags result = RangeFlags.None;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: please use var everywhere

Comment thread src/Npgsql/NpgsqlTypes/NpgsqlRange.cs Outdated
/// <returns>
/// The boundary characteristics.
/// </returns>
private static RangeFlags EvaluateBoundaryFlags(bool lowerBoundIsInclusive, bool upperBoundIsInclusive, bool lowerBoundInfinite, bool upperBoundInfinite)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: please omit private on methods as it is the default

Comment thread src/Npgsql/NpgsqlTypes/NpgsqlRange.cs Outdated
/// <summary>
/// True if the lower bound is part of the range (i.e. inclusive); otherwise, false.
/// </summary>
public bool LowerBoundIsInclusive => Flags.HasFlag(RangeFlags.LowerBoundInclusive);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]'.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See: #1943

: (LowerBoundInfinite ? 0 : LowerBound.GetHashCode()) +
(UpperBoundInfinite ? 0 : UpperBound.GetHashCode());

/// <inheritdoc />

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I'll take care of that soon.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread src/Npgsql/NpgsqlTypes/NpgsqlRange.cs Outdated
{
sb.Append(LowerBoundIsInclusive ? '[' : '(');

sb.Append(LowerBoundIsInclusive ? '[' : '(');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason for making the distinction between inclusive/exclusive when the bound is infinite? The previous code just outputted ( for infinity...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/Npgsql/NpgsqlTypes/NpgsqlRange.cs Outdated
if (value.Equals("empty", StringComparison.OrdinalIgnoreCase))
return Empty;

bool lowerInclusive = value[0] == '[';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: var everywhere please

}

/// <inheritdoc />
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: use expression-bodied method

@austindrenski

austindrenski commented May 21, 2018 •

Copy link
Copy Markdown
Contributor Author

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:

First, Span is now supposed to provide more or less the same thing as StringSegment - allocation-free slicing. See also dotnet/corefx#20378 (comment) on StringSegment vs. ReadOnlySpan - 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).

This sounds great. I hadn't considered using the new System.Memory types for this, but I agree that they are a better fit.

which by the way I think your PR omits from the csproj

I made some unrelated changes in the csproj file to get the project to build early on (before I knew this would be a PR). I'll revert and include that file if it ends up being relevant after sorting out the dependency question.

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.

EDIT:

After reviewing your comments about incorporating System.Memory, I think there's an even better argument for adding the dependency in 4.0, to allow for incremental migration to the new APIs. (Assuming that there are some places where incorporating Span<T> or ReadOnlySpan<T> would be trivial to accomplish before the 4.0 release.)

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread src/Npgsql/NpgsqlTypes/NpgsqlRange.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These curlies are redundant, please remove.

Actually if you remove the StringSegment dependency the need for a switch may go away.

Comment thread test/Npgsql.Tests/Npgsql.Tests.csproj Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As above, please revert to continue supporting net451 for now.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yikes, meant to be excluded from the commit. Removing.

Comment thread test/Npgsql.Tests/Types/RangeTests.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: please remove private

Comment thread src/Npgsql/Npgsql.csproj Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above, meant to exclude that again.

Comment thread src/Npgsql/NpgsqlTypes/NpgsqlRange.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]'.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()
austindrenski added a commit to austindrenski/npgsql-efcore.pg that referenced this pull request May 21, 2018
. Note that this commit removes subtype mapping handling.
@austindrenski
austindrenski force-pushed the ranges-wkt branch 4 times, most recently from 75d52f8 to d95f053 Compare May 21, 2018 21:25
@austindrenski

austindrenski commented May 21, 2018 •

Copy link
Copy Markdown
Contributor Author

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).

Okay, I've removed the dependency on Microsoft.Extensions.Primitives and rewritten NpgsqlRange<T>.Parse() to work without it.

Type constraints

I would like to constrain the type parameter with IComparable<T> and IEquatable<T>. This will allow for more nuanced bounds checking to prevent additional error states.

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 checks

With IComparable<T> and IEquatable<T>, it becomes possible to check for some implicitly empty ranges, such as [1, 1], though not the default valued range [0, 0].

This also allows for the detection of malformed ranges where the lower bound is greater than the upper bound, such as [2, 1], though not the range [2, 0].

Bitwise flags

Since we're sticking with bitwise flag checks, I've added a few known states to the RangeFlags enum. The goal here is to make it more obvious when we're testing for a specific condition.

/// <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.
roji pushed a commit to npgsql/efcore.pg that referenced this pull request May 22, 2018
Based on npgsql/npgsql#1939 (comment).

Note that this commit removes subtype mapping handling. (#420)
@roji

roji commented May 22, 2018

Copy link
Copy Markdown
Member

I would like to constrain the type parameter with IComparable and IEquatable. This will allow for more nuanced bounds checking to prevent additional error states.

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 inet: someone may want to have a range over inet, but .NET IPAddress happens to not be equatable or comparable. Adding the constraint would prevent users from creating the range, for little value (client-side validation/canonicalization which would be done server-side anyway).

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.

@austindrenski

austindrenski commented May 23, 2018 •

Copy link
Copy Markdown
Contributor Author

I've removed the IComparable<T> and IEquatable<T> constraints in 4c4f96735335e387d47c047523d8546aa3cf6e67.

At this point, I think the only anticipatable error state that we don't prevent is the lower > upper condition. Of all the possible error states, I think that one will be among the easiest for consuming code to get right.

Updates

I 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 hashes

I 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 fixes

I'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 tests

I've added a series of unit tests to parse various range literals. The tests use NpgsqlRange<int> and NpgsqlRange<DateTime>, but I can add others if there's any worry about subtype-specific errors.

Type converter

It 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 NpgsqlRange<T>.RangeTypeConverter:

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 RangeTypeConverter.Register() run in the static constructor, but when doing so, TypeDescriptor was unable to find the right TypeConverter. I assume this has something to do with static/generic initialization procedures, but I can't find anything definitive in the docs.

… 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 roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my last two comments about reducing allocations, after this I think we're good to go.

Comment thread src/Npgsql/NpgsqlTypes/NpgsqlRange.cs Outdated
x.UpperBoundIsInclusive == y.UpperBoundIsInclusive &&
x.LowerBoundInfinite == y.LowerBoundInfinite &&
x.UpperBoundInfinite == y.UpperBoundInfinite;
=> x.Flags == y.Flags

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread src/Npgsql/NpgsqlTypes/NpgsqlRange.cs Outdated

LowerBoundIsInclusive = lowerBoundIsInclusive;
UpperBoundIsInclusive = upperBoundIsInclusive;
if (lowerBound is T lower && !lower.Equals(default) && upperBound is T upper && !upper.Equals(default) && lower.Equals(upper))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@austindrenski

austindrenski commented May 23, 2018 •

Copy link
Copy Markdown
Contributor Author

It should be possible to check if they happen to implement IEquatable<T>, and if so, call its Equals() method, avoiding the boxing.

I moved the equality logic in 156c5e55626bde38c9bc554c01fce711098afb95 from == to IEquatable<T>.Equals(). It's a little easier (opinion) to reason about the equality logic with a clear primary entity (e.g. this).

I've added a static field HasEquatableBounds to avoid repeated type checks. At the same time, I've added another static field HasValueTypeBounds so that reference checks for null and value checks for default(T) are (hopefully) more transparent.

I've added a test that parses to NpgsqlRange<int?>, one that parses to NpgsqlRange<string>, and a third that parses to NpgsqlRange<SimpleType> which is just a test class to verify that everything works when T is neither a ValueType nor IEquatable<T>.

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).

I've never used BenchmarkDotNet, but I'll take a look now.

@austindrenski

Copy link
Copy Markdown
Contributor Author

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).

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

// * Summary *

.NET Core SDK=2.1.300-rc1-008673
  [Host]     : .NET Core 2.1.0-rc1 (CoreCLR 4.6.26426.02, CoreFX 4.6.26426.04), 64bit RyuJIT
  DefaultJob : .NET Core 2.1.0-rc1 (CoreCLR 4.6.26426.02, CoreFX 4.6.26426.04), 64bit RyuJIT


 Method |     Mean |     Error |    StdDev | Scaled | Allocated |
------- |---------:|----------:|----------:|-------:|----------:|
 Equals | 3.767 ns | 0.1154 ns | 0.2766 ns |   1.00 |       0 B |

// * Hints *
Outliers
  NpgsqlRangeEquality.Equals: Default -> 1 outlier  was  removed

// * Legends *
  Mean      : Arithmetic mean of all measurements
  Error     : Half of 99.9% confidence interval
  StdDev    : Standard deviation of all measurements
  Scaled    : Mean(CurrentBenchmark) / Mean(BaselineBenchmark)
  Allocated : Allocated memory per single operation (managed only, inclusive, 1KB = 1024B)
  1 ns      : 1 Nanosecond (0.000000001 sec)

// * Diagnostic Output - MemoryDiagnoser *


// ***** BenchmarkRunner: End *****
// * Artifacts cleanup *

Global total time: 00:01:17 (77.8 sec)

@roji
roji merged commit b3994e6 into npgsql:dev May 24, 2018
(((IEquatable<T>)UpperBound)?.Equals(other.UpperBound) ?? other.UpperBound == null);

public bool Equals(NpgsqlRange<T> other) => this == other;
return

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@roji

roji commented May 24, 2018

Copy link
Copy Markdown
Member

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 IEquatable<T> and calling equals. Can you please rerun it and post the results to confirm?

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.

@roji

roji commented May 24, 2018

Copy link
Copy Markdown
Member

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!

@austindrenski
austindrenski deleted the ranges-wkt branch May 24, 2018 13:29
mattico pushed a commit to mattico/npgsql that referenced this pull request Oct 31, 2022
Also adds a simple benchmark to test parsing allocations.

Related:
- npgsql#1939
- npgsql#1943
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants