Beispiel #1
0
        public override ExpressionNode VisitCaseExpression(CaseExpression expression)
        {
            base.VisitCaseExpression(expression);

            // NOTE: It must be a searched CASE. The normalizer should have normalized it already.
            //
            // Remove all WHEN expressions that are allays FALSE or NULL.
            // AND
            // Cut off all WHENs trailing an expression that is always true.

            List <ExpressionNode> whenExpressions = new List <ExpressionNode>();
            List <ExpressionNode> thenExpressions = new List <ExpressionNode>();

            for (int i = 0; i < expression.WhenExpressions.Length; i++)
            {
                if (AstUtil.IsNull(expression.WhenExpressions[i]))
                {
                    // A WHEN expression is always null.
                    continue;
                }

                ConstantExpression whenAsBooleanConstant = expression.WhenExpressions[i] as ConstantExpression;

                if (whenAsBooleanConstant != null)
                {
                    if (!whenAsBooleanConstant.AsBoolean)
                    {
                        // A WHEN expression is always false.
                        //
                        // We remove this part from the case expression by not adding to
                        // whenExpressions and thenExpressions.
                        continue;
                    }
                    else
                    {
                        // A WHEN expression is always true.
                        //
                        // We replace the ELSE expression by the THEN expression and
                        // cut off the rest.

                        expression.ElseExpression = expression.ThenExpressions[i];
                        break;
                    }
                }

                whenExpressions.Add(expression.WhenExpressions[i]);
                thenExpressions.Add(expression.ThenExpressions[i]);
            }

            if (whenExpressions.Count == 0)
            {
                // This means the first WHEN expression was always false
                // or all WHEN expressions are either FALSE or NULL.
                //
                // We replace the case expression by the else expression
                // or by NULL.

                if (expression.ElseExpression != null)
                {
                    return(expression.ElseExpression);
                }

                return(LiteralExpression.FromTypedNull(expression.ExpressionType));
            }

            expression.WhenExpressions = whenExpressions.ToArray();
            expression.ThenExpressions = thenExpressions.ToArray();

            return(expression);
        }