Skip to content

Commit

Permalink
Remove SQL parentheses for most outer ANDs
Browse files Browse the repository at this point in the history
To maintain SQL compatibility for providers who haven't implemented an
operator precedence table.
  • Loading branch information
roji committed Mar 19, 2023
1 parent e5b8fb4 commit 5d4d63a
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/EFCore.Relational/Query/QuerySqlGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1396,6 +1396,23 @@ protected virtual bool RequiresParentheses(SqlExpression outerExpression, SqlExp
};
}

// Even if the provider doesn't define precedence, assume that AND has less precedence than any other binary operator
// except for OR. This is universal, was our behavior before introducing provider precedence and removes the need for many
// parentheses. Do the same for OR (though here we add parentheses around inner AND just for readability).
if (outerExpression is SqlBinaryExpression outerBinary2)
{
if (outerBinary2.OperatorType == ExpressionType.AndAlso)
{
return innerBinaryExpression.OperatorType == ExpressionType.OrElse;
}

if (outerBinary2.OperatorType == ExpressionType.OrElse)
{
// Precedence-wise AND is above OR but we still add parentheses for ease of understanding
return innerBinaryExpression.OperatorType == ExpressionType.AndAlso;
}
}

// Otherwise always parenthesize for safety
return true;
}
Expand Down

0 comments on commit 5d4d63a

Please sign in to comment.