Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/ranges.md
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,9 @@ Good to know:
`null` range on the right, the query returns the rows memory returns: `> 0`, `>= 0` and `!= 0` hold
for every row, and `< 0`, `<= 0` and `== 0` for none. The same holds when you compare `CompareTo`
with `-1` or `1`, which EF Core also turns into operators. `CompareTo` answers only `-1`, `0` or `1`,
so `== 1` means "sorts after" in memory as in SQL.
so `== 1` means "sorts after" in memory as in SQL. A projected `CompareTo`, such as
`Select(b => b.Period.CompareTo(other))`, returns the same number in the query as in memory, also for
a `null` operand.
- **A NULL column compares as `Comparer<T>.Default` orders a null.** It is equal to a `null` range,
and before every other range. So with a `null` operand, a NULL column matches `== 0`, `>= 0` and
`<= 0`, and with a non-null operand it compares lower, so it matches `< 0`, `<= 0` and `!= 0`. In
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,36 @@ Expression Compare(Expression result)
And(And(Not(receiverNull), Not(operandNull)), comparison)));
}

/// <summary>
/// A <c>CompareTo</c> that is not compared with a number — projected, ordered by, added to —
/// answers the number itself. EF Core writes it as <c>CASE WHEN a = b THEN 0 WHEN a &gt; b THEN 1
/// WHEN a &lt; b THEN -1 END</c>, which is <c>NULL</c> for a null operand, and reading that NULL into
/// an <see cref="int"/> threw where memory answers 1 (#253). So it becomes the same split by
/// nullness as a comparison, as one conditional: EF Core writes that as one <c>CASE</c>, and the
/// branches a constant or a non-nullable column rules out fold away.
/// </summary>
protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (CompareToCall(node) is not { } call) return base.VisitMethodCall(node);

var receiver = Visit(call.Object)!;
var operand = Visit(call.Arguments[0]);
var compared = call.Update(receiver, [operand]);

var receiverNull = IsNull(receiver);
var operandNull = IsNull(operand);

// Comparer<T>.Default: (null, null) is 0, (null, x) is -1, (x, null) is 1.
return Choose(receiverNull,
Choose(operandNull, Expression.Constant(0), Expression.Constant(-1)),
Choose(operandNull, Expression.Constant(1), compared));
}

private static Expression Choose(Expression test, Expression whenTrue, Expression whenFalse)
=> test is ConstantExpression { Value: bool value }
? value ? whenTrue : whenFalse
: Expression.Condition(test, whenTrue, whenFalse);

private static bool IsComparison(ExpressionType type)
=> type is ExpressionType.Equal or ExpressionType.NotEqual
or ExpressionType.LessThan or ExpressionType.LessThanOrEqual
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,56 @@ async Task<IEnumerable<string>> Mismatch(string label, System.Linq.Expressions.E
}
}

/// <summary>
/// <c>CompareTo</c> projected, not compared: the query returns the number memory's
/// <see cref="Comparer{T}.Default"/> returns, for a null and a non-null operand over a nullable
/// range and multirange column. A null operand made the <c>CASE</c> EF Core writes yield
/// <c>NULL</c>, which threw on reading it into an <see cref="int"/> (#253).
/// </summary>
[TestMethod]
public async Task ProjectedCompareTo_ReturnsTheNumberTheDefaultComparerReturns()
{
ContainerLifecycle.RequireServer();

var connectionString = await NullableOrderContext.CreateDatabase();
Int32Range?[] seats = [null, Int32Range.Empty, Int32Range.CreateFinite(1, 5), Int32Range.CreateFinite(2, 3), Int32Range.Infinite];
var rows = seats.Select((range, index) => new NullableOrderRow
{
Id = index + 1,
Seats = range,
Blocks = range is null ? null : RangeSet<Int32Range, int>.From([range])
}).ToList();

await using (var seed = new NullableOrderContext(connectionString))
{
await seed.Database.EnsureCreatedAsync();
seed.Rows.AddRange(rows);
await seed.SaveChangesAsync();
}

await using var context = new NullableOrderContext(connectionString);

foreach (var (name, operand, setOperand) in new[]
{
("null", (Int32Range?)null, (RangeSet<Int32Range, int>?)null),
("[1,5]", Int32Range.CreateFinite(1, 5), RangeSet<Int32Range, int>.From([Int32Range.CreateFinite(1, 5)]))
})
{
var ranges = await context.Rows.OrderBy(r => r.Id).Select(r => r.Seats!.CompareTo(operand)).ToListAsync();
CollectionAssert.AreEqual(rows.Select(r => Comparer<Int32Range>.Default.Compare(r.Seats, operand)).ToList(), ranges,
$"range CompareTo({name}) projected");

var sets = await context.Rows.OrderBy(r => r.Id).Select(r => r.Blocks!.CompareTo(setOperand)).ToListAsync();
CollectionAssert.AreEqual(rows.Select(r => Comparer<RangeSet<Int32Range, int>>.Default.Compare(r.Blocks, setOperand)).ToList(), sets,
$"multirange CompareTo({name}) projected");

var ordered = await context.Rows.OrderBy(r => r.Seats!.CompareTo(operand)).ThenBy(r => r.Id).Select(r => r.Id).ToListAsync();
CollectionAssert.AreEqual(
rows.OrderBy(r => Comparer<Int32Range>.Default.Compare(r.Seats, operand)).ThenBy(r => r.Id).Select(r => r.Id).ToList(), ordered,
$"ordered by CompareTo({name})");
}
}

private static bool Holds(int comparison, ExpressionType op, int k, bool callOnLeft)
{
var (left, right) = callOnLeft ? (comparison, k) : (k, comparison);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,21 @@ public void CompareTo_AgainstANullOperand_IsDecidedAsInMemory()
Assert.DoesNotContain("IS NULL", sql);
}

[TestMethod]
public void ProjectedCompareTo_AgainstANullOperand_IsOne_AndAgainstANonNullOneIsEFCoresCase()
{
DateRange? none = null;
var some = DateRange.CreateFinite(new DateOnly(2024, 1, 1), new DateOnly(2024, 2, 1));
using var context = new TestDbContext();

// null sorts first, so every range compares 1 against it (#253).
Assert.Contains("SELECT 1", context.Bookings.Select(b => b.Period.CompareTo(none)).ToQueryString());

var sql = context.Bookings.Select(b => b.Period.CompareTo(some)).ToQueryString();
Assert.Contains("WHEN b.\"Period\" = @some THEN 0", sql);
Assert.DoesNotContain("IS NULL", sql);
}

[TestMethod]
public void CompareTo_OnAMultirange_IsTheComparisonOperator()
{
Expand Down
15 changes: 15 additions & 0 deletions test/oracles/claims.json
Original file line number Diff line number Diff line change
Expand Up @@ -3127,6 +3127,21 @@
"RangeOrderSignContractTests"
]
},
{
"id": "R47-projected-compareto-null",
"source": "docs/ranges.md#sort-ranges",
"quote": "A projected `CompareTo`, such as `Select(b => b.Period.CompareTo(other))`, returns the same number in the query as in memory, also for a `null` operand.",
"claim": "A range or multirange CompareTo projected or ordered by in an EF Core query, over a nullable column, against a null and a non-null operand, returns for every row the number Comparer<T>.Default.Compare(column, operand) returns, and sorts as it does; a null operand translates to the constant 1 and a non-null one to EF Core's own CASE.",
"oracle": "differential",
"surfaces": [
"*Range.CompareTo",
"RangeSet.CompareTo"
],
"heldBy": [
"RangeOrderParityTests",
"QueryTranslationTests"
]
},
{
"id": "S01-canonical-set",
"source": "docs/value-sets.md#value-sets",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Fails: CompareTo(null) == 1, >= 1, > -1, != -1 and 1 == CompareTo(null) (no rows
History: found by the final pre-release analysis (#256, #261) before 10.0.0 shipped

diff --git a/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs b/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs
index 2e528d7..3c3b2f9 100644
index 284394f..3c3b2f9 100644
--- a/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs
+++ b/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs
@@ -20,8 +20,8 @@ namespace CodoMetis.ValueRanges.EntityFrameworkCore.PostgreSQL.Query;
Expand Down Expand Up @@ -60,7 +60,7 @@ index 2e528d7..3c3b2f9 100644
/// </para>
/// </remarks>
private sealed class NullOperandCompareToRewriter : ExpressionVisitor
@@ -214,87 +210,61 @@ public sealed class ValueRangesQueryExpressionInterceptor : IQueryExpressionInte
@@ -214,117 +210,61 @@ public sealed class ValueRangesQueryExpressionInterceptor : IQueryExpressionInte

protected override Expression VisitBinary(BinaryExpression node)
{
Expand Down Expand Up @@ -113,6 +113,36 @@ index 2e528d7..3c3b2f9 100644
+ : Expression.AndAlso(Expression.Not(isNull), binary);
}

- /// <summary>
- /// A <c>CompareTo</c> that is not compared with a number — projected, ordered by, added to —
- /// answers the number itself. EF Core writes it as <c>CASE WHEN a = b THEN 0 WHEN a &gt; b THEN 1
- /// WHEN a &lt; b THEN -1 END</c>, which is <c>NULL</c> for a null operand, and reading that NULL into
- /// an <see cref="int"/> threw where memory answers 1 (#253). So it becomes the same split by
- /// nullness as a comparison, as one conditional: EF Core writes that as one <c>CASE</c>, and the
- /// branches a constant or a non-nullable column rules out fold away.
- /// </summary>
- protected override Expression VisitMethodCall(MethodCallExpression node)
- {
- if (CompareToCall(node) is not { } call) return base.VisitMethodCall(node);
-
- var receiver = Visit(call.Object)!;
- var operand = Visit(call.Arguments[0]);
- var compared = call.Update(receiver, [operand]);
-
- var receiverNull = IsNull(receiver);
- var operandNull = IsNull(operand);
-
- // Comparer<T>.Default: (null, null) is 0, (null, x) is -1, (x, null) is 1.
- return Choose(receiverNull,
- Choose(operandNull, Expression.Constant(0), Expression.Constant(-1)),
- Choose(operandNull, Expression.Constant(1), compared));
- }
-
- private static Expression Choose(Expression test, Expression whenTrue, Expression whenFalse)
- => test is ConstantExpression { Value: bool value }
- ? value ? whenTrue : whenFalse
- : Expression.Condition(test, whenTrue, whenFalse);
-
- private static bool IsComparison(ExpressionType type)
- => type is ExpressionType.Equal or ExpressionType.NotEqual
- or ExpressionType.LessThan or ExpressionType.LessThanOrEqual
Expand Down
46 changes: 46 additions & 0 deletions test/oracles/seeds/projected-compareto-null-reads-sql-null.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
Seed: a CompareTo that is projected rather than compared is left to EF Core's CASE, which is NULL for a null operand
Oracles: RangeOrderParityTests
Fails: Select(r => r.Seats.CompareTo(none)) with none null throws on materialization ("Nullable object must have a value") where Comparer<T>.Default answers 1
History: found by the final pre-release analysis (#253) before 10.0.0 shipped

diff --git a/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs b/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs
index 284394f..2e528d7 100644
--- a/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs
+++ b/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs
@@ -246,36 +246,6 @@ public sealed class ValueRangesQueryExpressionInterceptor : IQueryExpressionInte
And(And(Not(receiverNull), Not(operandNull)), comparison)));
}

- /// <summary>
- /// A <c>CompareTo</c> that is not compared with a number — projected, ordered by, added to —
- /// answers the number itself. EF Core writes it as <c>CASE WHEN a = b THEN 0 WHEN a &gt; b THEN 1
- /// WHEN a &lt; b THEN -1 END</c>, which is <c>NULL</c> for a null operand, and reading that NULL into
- /// an <see cref="int"/> threw where memory answers 1 (#253). So it becomes the same split by
- /// nullness as a comparison, as one conditional: EF Core writes that as one <c>CASE</c>, and the
- /// branches a constant or a non-nullable column rules out fold away.
- /// </summary>
- protected override Expression VisitMethodCall(MethodCallExpression node)
- {
- if (CompareToCall(node) is not { } call) return base.VisitMethodCall(node);
-
- var receiver = Visit(call.Object)!;
- var operand = Visit(call.Arguments[0]);
- var compared = call.Update(receiver, [operand]);
-
- var receiverNull = IsNull(receiver);
- var operandNull = IsNull(operand);
-
- // Comparer<T>.Default: (null, null) is 0, (null, x) is -1, (x, null) is 1.
- return Choose(receiverNull,
- Choose(operandNull, Expression.Constant(0), Expression.Constant(-1)),
- Choose(operandNull, Expression.Constant(1), compared));
- }
-
- private static Expression Choose(Expression test, Expression whenTrue, Expression whenFalse)
- => test is ConstantExpression { Value: bool value }
- ? value ? whenTrue : whenFalse
- : Expression.Condition(test, whenTrue, whenFalse);
-
private static bool IsComparison(ExpressionType type)
=> type is ExpressionType.Equal or ExpressionType.NotEqual
or ExpressionType.LessThan or ExpressionType.LessThanOrEqual