Optimize away Coalesce over non-nullable expression
- Dominant language
- C#
- Stars
- 14.8k
- Forks
- 3.4k
- PR merge metrics
- PR metrics pending
Description
We should introduce a check into SqlExpressionFactory.Coalesce(), which doesn't actually add a Coalesce node if the left side is known to be non-nullable:
```c#
public virtual SqlExpression Coalesce(SqlExpression left, SqlExpression right, RelationalTypeMapping? typeMapping = null)
{
switch (left)
{
case SqlConstantExpression { Value: not null }:
case ColumnExpression { IsNullable: false }:
return left;
case SqlConstantExpression { Value: null }:
return right;
}
```
This would allow calling SqlExpressionFactory.Coalesce() without first checking if it's needed, simplying call sites.
Similarly, we should also perform this optimization in SqlNullabilityProcessor, which can take care of more cases.
The main difficulty here is that we have various tests exercising Coalesce functionality, which are implemented over non-nullable columns; the Coalesce node would be stripped away there, and the tests would become useless. These need to be updated.
Note: do this for Cosmos as well, but remember that the Cosmos coalesce operator (??) is for `undefined` rather than `null`.
Contributor guide
Assessment
This issue has not been assessed yet.