From 58b5948355545b30a2d8691cbaed282b6ae7f325 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Gro=C3=9F?= Date: Mon, 19 Oct 2026 06:49:00 +0200 Subject: [PATCH] fix: a projected CompareTo against a null range returns 1, as in memory Select(r => r.Seats.CompareTo(none)) with a null none translated to EF Core's CASE WHEN a = b ... END, which is NULL for a null operand, and reading that into an int threw "Nullable object must have a value" where memory answers 1. The interceptor's CompareTo rewriter now also rewrites a CompareTo that is not compared with a number (projected, ordered by) into the same split by nullness, as one conditional following Comparer.Default: (null, null) 0, (null, x) -1, (x, null) 1, otherwise the call. Constants and non-nullable columns fold it away: a null operand is SELECT 1, a non-null one EF Core's own CASE. RangeOrderParityTests.ProjectedCompareTo_ReturnsTheNumberTheDefaultComparerReturns projects and orders by CompareTo over a nullable range and multirange column against a null and a non-null operand, row for row against Comparer.Default; it throws with the rewrite removed (seed projected-compareto-null-reads-sql-null). The #256 seed is refreshed for the changed file. Closes #253 Found-By: CA Defect-Class: SQL Co-Authored-By: Claude Opus 5.5 --- docs/ranges.md | 4 +- .../ValueRangesQueryExpressionInterceptor.cs | 30 +++++++++++ .../RangeOrderParityTests.cs | 50 +++++++++++++++++++ .../QueryTranslationTests.cs | 15 ++++++ test/oracles/claims.json | 15 ++++++ ...eto-null-rewritten-only-against-zero.patch | 34 ++++++++++++- ...jected-compareto-null-reads-sql-null.patch | 46 +++++++++++++++++ 7 files changed, 191 insertions(+), 3 deletions(-) create mode 100644 test/oracles/seeds/projected-compareto-null-reads-sql-null.patch diff --git a/docs/ranges.md b/docs/ranges.md index d088a84a..39eef8e5 100644 --- a/docs/ranges.md +++ b/docs/ranges.md @@ -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.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 diff --git a/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs b/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs index 2e528d7c..284394fb 100644 --- a/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs +++ b/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs @@ -246,6 +246,36 @@ Expression Compare(Expression result) And(And(Not(receiverNull), Not(operandNull)), comparison))); } + /// + /// A CompareTo that is not compared with a number — projected, ordered by, added to — + /// answers the number itself. EF Core writes it as CASE WHEN a = b THEN 0 WHEN a > b THEN 1 + /// WHEN a < b THEN -1 END, which is NULL for a null operand, and reading that NULL into + /// an 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 CASE, and the + /// branches a constant or a non-nullable column rules out fold away. + /// + 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.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 diff --git a/test/CodoMetis.ValueRanges.EFCore.PostgreSQL.IntegrationTests/RangeOrderParityTests.cs b/test/CodoMetis.ValueRanges.EFCore.PostgreSQL.IntegrationTests/RangeOrderParityTests.cs index 54650fcd..97720a5a 100644 --- a/test/CodoMetis.ValueRanges.EFCore.PostgreSQL.IntegrationTests/RangeOrderParityTests.cs +++ b/test/CodoMetis.ValueRanges.EFCore.PostgreSQL.IntegrationTests/RangeOrderParityTests.cs @@ -224,6 +224,56 @@ async Task> Mismatch(string label, System.Linq.Expressions.E } } + /// + /// CompareTo projected, not compared: the query returns the number memory's + /// returns, for a null and a non-null operand over a nullable + /// range and multirange column. A null operand made the CASE EF Core writes yield + /// NULL, which threw on reading it into an (#253). + /// + [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.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?)null), + ("[1,5]", Int32Range.CreateFinite(1, 5), RangeSet.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.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>.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.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); diff --git a/test/CodoMetis.ValueRanges.EFCore.PostgreSQL.Tests/QueryTranslationTests.cs b/test/CodoMetis.ValueRanges.EFCore.PostgreSQL.Tests/QueryTranslationTests.cs index 179cc0b4..7a50a9e3 100644 --- a/test/CodoMetis.ValueRanges.EFCore.PostgreSQL.Tests/QueryTranslationTests.cs +++ b/test/CodoMetis.ValueRanges.EFCore.PostgreSQL.Tests/QueryTranslationTests.cs @@ -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() { diff --git a/test/oracles/claims.json b/test/oracles/claims.json index fe4bf90e..81c8a469 100644 --- a/test/oracles/claims.json +++ b/test/oracles/claims.json @@ -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.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", diff --git a/test/oracles/seeds/compareto-null-rewritten-only-against-zero.patch b/test/oracles/seeds/compareto-null-rewritten-only-against-zero.patch index 08aca1ea..841359fa 100644 --- a/test/oracles/seeds/compareto-null-rewritten-only-against-zero.patch +++ b/test/oracles/seeds/compareto-null-rewritten-only-against-zero.patch @@ -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; @@ -60,7 +60,7 @@ index 2e528d7..3c3b2f9 100644 /// /// 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) { @@ -113,6 +113,36 @@ index 2e528d7..3c3b2f9 100644 + : Expression.AndAlso(Expression.Not(isNull), binary); } +- /// +- /// A CompareTo that is not compared with a number — projected, ordered by, added to — +- /// answers the number itself. EF Core writes it as CASE WHEN a = b THEN 0 WHEN a > b THEN 1 +- /// WHEN a < b THEN -1 END, which is NULL for a null operand, and reading that NULL into +- /// an 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 CASE, and the +- /// branches a constant or a non-nullable column rules out fold away. +- /// +- 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.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 diff --git a/test/oracles/seeds/projected-compareto-null-reads-sql-null.patch b/test/oracles/seeds/projected-compareto-null-reads-sql-null.patch new file mode 100644 index 00000000..92418b51 --- /dev/null +++ b/test/oracles/seeds/projected-compareto-null-reads-sql-null.patch @@ -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.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))); + } + +- /// +- /// A CompareTo that is not compared with a number — projected, ordered by, added to — +- /// answers the number itself. EF Core writes it as CASE WHEN a = b THEN 0 WHEN a > b THEN 1 +- /// WHEN a < b THEN -1 END, which is NULL for a null operand, and reading that NULL into +- /// an 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 CASE, and the +- /// branches a constant or a non-nullable column rules out fold away. +- /// +- 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.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