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

Prefer equality in boolean comparisons #34166

Open
wants to merge 2 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
89 changes: 49 additions & 40 deletions src/EFCore.Relational/Query/SqlNullabilityProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1289,6 +1289,7 @@ protected virtual SqlExpression VisitSqlBinary(
right,
leftNullable,
rightNullable,
optimize,
out nullable);

if (optimized is SqlUnaryExpression { Operand: ColumnExpression optimizedUnaryColumnOperand } optimizedUnary)
Expand Down Expand Up @@ -1623,6 +1624,7 @@ private SqlExpression ProcessJoinPredicate(SqlExpression predicate)
right,
leftNullable,
rightNullable,
optimize: true,
out _);

return result;
Expand All @@ -1649,6 +1651,7 @@ private SqlExpression OptimizeComparison(
SqlExpression right,
bool leftNullable,
bool rightNullable,
bool optimize,
out bool nullable)
{
var leftNullValue = leftNullable && left is SqlConstantExpression or SqlParameterExpression;
Expand Down Expand Up @@ -1729,47 +1732,20 @@ private SqlExpression OptimizeComparison(
&& !rightNullable
&& sqlBinaryExpression.OperatorType is ExpressionType.Equal or ExpressionType.NotEqual)
{
var leftUnary = left as SqlUnaryExpression;
var rightUnary = right as SqlUnaryExpression;

var leftNegated = IsLogicalNot(leftUnary);
var rightNegated = IsLogicalNot(rightUnary);

if (leftNegated)
{
left = leftUnary!.Operand;
}

if (rightNegated)
{
right = rightUnary!.Operand;
}

// a == b <=> !a == !b -> a == b
// !a == b <=> a == !b -> a != b
// a != b <=> !a != !b -> a != b
// !a != b <=> a != !b -> a == b

nullable = false;

return sqlBinaryExpression.OperatorType == ExpressionType.Equal ^ leftNegated == rightNegated
? _sqlExpressionFactory.NotEqual(left, right)
: _sqlExpressionFactory.Equal(left, right);
return OptimizeBooleanComparison(sqlBinaryExpression, left, right, optimize);
}

nullable = false;

return sqlBinaryExpression.Update(left, right);
}

private SqlExpression RewriteNullSemantics(
private SqlExpression OptimizeBooleanComparison(
SqlBinaryExpression sqlBinaryExpression,
SqlExpression left,
SqlExpression right,
bool leftNullable,
bool rightNullable,
bool optimize,
out bool nullable)
bool optimize)
{
var leftUnary = left as SqlUnaryExpression;
var rightUnary = right as SqlUnaryExpression;
Expand All @@ -1787,22 +1763,49 @@ private SqlExpression RewriteNullSemantics(
right = rightUnary!.Operand;
}

var notEqual = sqlBinaryExpression.OperatorType == ExpressionType.Equal ^ leftNegated == rightNegated;

// prefer equality in predicates
if (optimize && notEqual && left.Type == typeof(bool))
{
if (right is ColumnExpression && (left is not ColumnExpression || leftNegated))
{
left = _sqlExpressionFactory.Not(left);
}
else
{
right = _sqlExpressionFactory.Not(right);
}

return _sqlExpressionFactory.Equal(left, right);
}

// a == b <=> !a == !b -> a == b
// !a == b <=> a == !b -> a != b
// a != b <=> !a != !b -> a != b
// !a != b <=> a != !b -> a == b

return notEqual
? _sqlExpressionFactory.NotEqual(left, right)
: _sqlExpressionFactory.Equal(left, right);
}

private SqlExpression RewriteNullSemantics(
SqlBinaryExpression sqlBinaryExpression,
SqlExpression left,
SqlExpression right,
bool leftNullable,
bool rightNullable,
bool optimize,
out bool nullable)
{
var leftIsNull = ProcessNullNotNull(_sqlExpressionFactory.IsNull(left), leftNullable);
var leftIsNotNull = _sqlExpressionFactory.Not(leftIsNull);

var rightIsNull = ProcessNullNotNull(_sqlExpressionFactory.IsNull(right), rightNullable);
var rightIsNotNull = _sqlExpressionFactory.Not(rightIsNull);

SqlExpression body;
if (leftNegated == rightNegated)
{
body = _sqlExpressionFactory.Equal(left, right);
}
else
{
// a == !b and !a == b in SQL evaluate the same as a != b
body = _sqlExpressionFactory.NotEqual(left, right);
}
var body = OptimizeBooleanComparison(sqlBinaryExpression, left, right, optimize);

// optimized expansion which doesn't distinguish between null and false
if (optimize && sqlBinaryExpression.OperatorType == ExpressionType.Equal)
Expand All @@ -1815,6 +1818,12 @@ private SqlExpression RewriteNullSemantics(
// doing a full null semantics rewrite - removing all nulls from truth table
nullable = false;

if (sqlBinaryExpression.OperatorType == ExpressionType.NotEqual)
{
// the factory takes care of simplifying equal <-> not-equal
body = _sqlExpressionFactory.Not(body);
}

// (a == b && (a != null && b != null)) || (a == null && b == null)
body = _sqlExpressionFactory.OrElse(
_sqlExpressionFactory.AndAlso(body, _sqlExpressionFactory.AndAlso(leftIsNotNull, rightIsNotNull)),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -562,9 +562,9 @@ public override async Task String_ends_with_not_equals_nullable_column(bool asyn
FROM [FunkyCustomers] AS [f]
CROSS JOIN [FunkyCustomers] AS [f0]
WHERE CASE
WHEN [f].[FirstName] IS NOT NULL AND [f0].[LastName] IS NOT NULL AND RIGHT([f].[FirstName], LEN([f0].[LastName])) = [f0].[LastName] THEN CAST(1 AS bit)
WHEN [f].[FirstName] IS NULL OR [f0].[LastName] IS NULL OR RIGHT([f].[FirstName], LEN([f0].[LastName])) <> [f0].[LastName] THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END <> [f].[NullableBool] OR [f].[NullableBool] IS NULL
END = [f].[NullableBool] OR [f].[NullableBool] IS NULL
""");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6831,7 +6831,7 @@ FROM [Gears] AS [g]
LEFT JOIN (
SELECT [w].[Id], [w].[OwnerFullName]
FROM [Weapons] AS [w]
WHERE [w].[IsAutomatic] <> @__isAutomatic_0
WHERE [w].[IsAutomatic] = ~@__isAutomatic_0
) AS [w0] ON [g].[FullName] = [w0].[OwnerFullName]
""");
}
Expand Down Expand Up @@ -7555,15 +7555,15 @@ public override async Task Logical_operation_with_non_null_parameter_optimizes_n

SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank]
FROM [Gears] AS [g]
WHERE [g].[HasSoulPatch] <> @__prm_0
WHERE [g].[HasSoulPatch] = ~@__prm_0
""",
//
"""
@__prm_0='False'

SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank]
FROM [Gears] AS [g]
WHERE [g].[HasSoulPatch] <> @__prm_0
WHERE [g].[HasSoulPatch] = ~@__prm_0
""");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1347,7 +1347,7 @@ public override async Task Where_not_bool_member_compared_to_binary_expression(b
"""
SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock]
FROM [Products] AS [p]
WHERE [p].[Discontinued] <> CASE
WHERE [p].[Discontinued] = ~CASE
WHEN [p].[ProductID] > 50 THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END
Expand Down Expand Up @@ -1381,7 +1381,7 @@ FROM [Products] AS [p]
WHERE CASE
WHEN [p].[ProductID] > 50 THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END <> @__prm_0
END = ~@__prm_0
""");
}

Expand Down
Loading