Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid duplicating complex expression in comparisons #34172

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
31 changes: 27 additions & 4 deletions src/EFCore.Relational/Query/SqlNullabilityProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1815,10 +1815,33 @@ private SqlExpression RewriteNullSemantics(
// doing a full null semantics rewrite - removing all nulls from truth table
nullable = false;

// (a == b && (a != null && b != null)) || (a == null && b == null)
body = _sqlExpressionFactory.OrElse(
_sqlExpressionFactory.AndAlso(body, _sqlExpressionFactory.AndAlso(leftIsNotNull, rightIsNotNull)),
_sqlExpressionFactory.AndAlso(leftIsNull, rightIsNull));
var originallyNotEqual = sqlBinaryExpression.OperatorType == ExpressionType.NotEqual;
var bodyNotEqual = body is SqlBinaryExpression { OperatorType: ExpressionType.NotEqual };

// When both operands are nullable, the CASE transformation is invalid.
// We also use the generic transformation when it simplifies to one of:
// - a == b && (a != null)
// - a == b && (b != null)
// - a == b || (a == null)
// - a == b || (b == null)
// as these expressions can use indexes on a and/or on b.
if (leftNullable && rightNullable || (optimize && originallyNotEqual == bodyNotEqual))
{
// (a == b && (a != null && b != null)) || (a == null && b == null)
body = _sqlExpressionFactory.OrElse(
_sqlExpressionFactory.AndAlso(body, _sqlExpressionFactory.AndAlso(leftIsNotNull, rightIsNotNull)),
_sqlExpressionFactory.AndAlso(leftIsNull, rightIsNull));
}
else
{
// When only one of the operands is nullable, we avoid duplicating
// complex expressions by performing the following transformation:
// a == b -> CASE WHEN a == b THEN TRUE ELSE FALSE END
body = _sqlExpressionFactory.Case(
[new(body, _sqlExpressionFactory.Constant(true, body.Type, body.TypeMapping))],
_sqlExpressionFactory.Constant(false, body.Type, body.TypeMapping));
}


if (sqlBinaryExpression.OperatorType == ExpressionType.NotEqual)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,26 @@ await AssertQueryScalar(
assertEmpty: true);
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task Compare_simple_expression(bool async)
=> AssertQueryScalar(
async,
ss => ss.Set<NullSemanticsEntity1>()
.Where(e => e.NullableIntA + e.IntB != e.IntC)
.Select(e => e.Id),
assertOrder: true);

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task Compare_complex_expression_not_duplicated(bool async)
=> AssertQueryScalar(
async,
ss => ss.Set<NullSemanticsEntity1>()
.Where(e => e.NullableIntA + e.NullableIntB != e.IntC)
.Select(e => e.Id),
assertOrder: true);

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task Compare_nullable_with_null_parameter_equal(bool async)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2246,7 +2246,10 @@ SELECT MIN([o0].[HourlyRate])
FROM [Order] AS [o0]
WHERE [o0].[CustomerId] = [o].[CustomerId]) AS [CustomerMinHourlyRate], MIN([o].[HourlyRate]) AS [HourlyRate], COUNT(*) AS [Count]
FROM [Order] AS [o]
WHERE [o].[Number] <> N'A1' OR [o].[Number] IS NULL
WHERE CASE
WHEN [o].[Number] = N'A1' THEN CAST(0 AS bit)
ELSE CAST(1 AS bit)
END = CAST(1 AS bit)
GROUP BY [o].[CustomerId], [o].[Number]
""");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,10 @@ FROM [Employees] AS [e]
LEFT JOIN (
SELECT [d].[Id], [d].[Device], [d].[EmployeeId]
FROM [Devices] AS [d]
WHERE [d].[Device] <> N'foo' OR [d].[Device] IS NULL
WHERE CASE
WHEN [d].[Device] = N'foo' THEN CAST(0 AS bit)
ELSE CAST(1 AS bit)
END = CAST(1 AS bit)
) AS [d0] ON [e].[Id] = [d0].[EmployeeId]
ORDER BY [e].[Id]
""");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,10 @@ public override async Task Self_reference_in_query_filter_works()
FROM [EntitiesWithQueryFilterSelfReference] AS [e]
WHERE EXISTS (
SELECT 1
FROM [EntitiesWithQueryFilterSelfReference] AS [e0]) AND ([e].[Name] <> N'Foo' OR [e].[Name] IS NULL)
FROM [EntitiesWithQueryFilterSelfReference] AS [e0]) AND CASE
WHEN [e].[Name] = N'Foo' THEN CAST(0 AS bit)
ELSE CAST(1 AS bit)
END = CAST(1 AS bit)
""",
//
"""
Expand All @@ -225,7 +228,10 @@ SELECT 1
FROM [EntitiesWithQueryFilterSelfReference] AS [e0]
WHERE EXISTS (
SELECT 1
FROM [EntitiesWithQueryFilterSelfReference] AS [e1])) AND ([e].[Name] <> N'Foo' OR [e].[Name] IS NULL)
FROM [EntitiesWithQueryFilterSelfReference] AS [e1])) AND CASE
WHEN [e].[Name] = N'Foo' THEN CAST(0 AS bit)
ELSE CAST(1 AS bit)
END = CAST(1 AS bit)
""");
}

Expand All @@ -239,15 +245,21 @@ public override async Task Invoke_inside_query_filter_gets_correctly_evaluated_d

SELECT [e].[Id], [e].[Name], [e].[TenantId]
FROM [Entities] AS [e]
WHERE ([e].[Name] <> N'Foo' OR [e].[Name] IS NULL) AND [e].[TenantId] = @__ef_filter__p_0
WHERE CASE
WHEN [e].[Name] = N'Foo' THEN CAST(0 AS bit)
ELSE CAST(1 AS bit)
END = CAST(1 AS bit) AND [e].[TenantId] = @__ef_filter__p_0
""",
//
"""
@__ef_filter__p_0='2'

SELECT [e].[Id], [e].[Name], [e].[TenantId]
FROM [Entities] AS [e]
WHERE ([e].[Name] <> N'Foo' OR [e].[Name] IS NULL) AND [e].[TenantId] = @__ef_filter__p_0
WHERE CASE
WHEN [e].[Name] = N'Foo' THEN CAST(0 AS bit)
ELSE CAST(1 AS bit)
END = CAST(1 AS bit) AND [e].[TenantId] = @__ef_filter__p_0
""");
}

Expand Down
Loading