Skip to content

Optimize away Coalesce over non-nullable expression #33890

@roji

Description

@roji

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:

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions