dotnet / dotnet/efcore

Optimize away Coalesce over non-nullable expression

Open
#33,890 10 comments 0 reactions 0 assignees View on GitHub
area-query
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.