| 1 | #include "duckdb/optimizer/rule/case_simplification.hpp" |
|---|---|
| 2 | |
| 3 | #include "duckdb/execution/expression_executor.hpp" |
| 4 | #include "duckdb/planner/expression/bound_case_expression.hpp" |
| 5 | |
| 6 | using namespace duckdb; |
| 7 | using namespace std; |
| 8 | |
| 9 | CaseSimplificationRule::CaseSimplificationRule(ExpressionRewriter &rewriter) : Rule(rewriter) { |
| 10 | // match on a CaseExpression that has a ConstantExpression as a check |
| 11 | auto op = make_unique<CaseExpressionMatcher>(); |
| 12 | op->check = make_unique<FoldableConstantMatcher>(); |
| 13 | root = move(op); |
| 14 | } |
| 15 | |
| 16 | unique_ptr<Expression> CaseSimplificationRule::Apply(LogicalOperator &op, vector<Expression *> &bindings, |
| 17 | bool &changes_made) { |
| 18 | auto root = (BoundCaseExpression *)bindings[0]; |
| 19 | auto constant_expr = bindings[1]; |
| 20 | // the constant_expr is a scalar expression that we have to fold |
| 21 | assert(constant_expr->IsFoldable()); |
| 22 | |
| 23 | // use an ExpressionExecutor to execute the expression |
| 24 | auto constant_value = ExpressionExecutor::EvaluateScalar(*constant_expr); |
| 25 | |
| 26 | // fold based on the constant condition |
| 27 | auto condition = constant_value.CastAs(TypeId::BOOL); |
| 28 | if (condition.is_null || !condition.value_.boolean) { |
| 29 | return move(root->result_if_false); |
| 30 | } else { |
| 31 | return move(root->result_if_true); |
| 32 | } |
| 33 | } |
| 34 |