| 1 | #include "duckdb/optimizer/filter_pushdown.hpp" |
|---|---|
| 2 | #include "duckdb/planner/expression/bound_columnref_expression.hpp" |
| 3 | #include "duckdb/planner/expression_iterator.hpp" |
| 4 | #include "duckdb/planner/operator/logical_empty_result.hpp" |
| 5 | #include "duckdb/planner/operator/logical_projection.hpp" |
| 6 | |
| 7 | namespace duckdb { |
| 8 | |
| 9 | static unique_ptr<Expression> ReplaceProjectionBindings(LogicalProjection &proj, unique_ptr<Expression> expr) { |
| 10 | if (expr->type == ExpressionType::BOUND_COLUMN_REF) { |
| 11 | auto &colref = expr->Cast<BoundColumnRefExpression>(); |
| 12 | D_ASSERT(colref.binding.table_index == proj.table_index); |
| 13 | D_ASSERT(colref.binding.column_index < proj.expressions.size()); |
| 14 | D_ASSERT(colref.depth == 0); |
| 15 | // replace the binding with a copy to the expression at the referenced index |
| 16 | return proj.expressions[colref.binding.column_index]->Copy(); |
| 17 | } |
| 18 | ExpressionIterator::EnumerateChildren( |
| 19 | expression&: *expr, callback: [&](unique_ptr<Expression> &child) { child = ReplaceProjectionBindings(proj, expr: std::move(child)); }); |
| 20 | return expr; |
| 21 | } |
| 22 | |
| 23 | unique_ptr<LogicalOperator> FilterPushdown::PushdownProjection(unique_ptr<LogicalOperator> op) { |
| 24 | D_ASSERT(op->type == LogicalOperatorType::LOGICAL_PROJECTION); |
| 25 | auto &proj = op->Cast<LogicalProjection>(); |
| 26 | // push filter through logical projection |
| 27 | // all the BoundColumnRefExpressions in the filter should refer to the LogicalProjection |
| 28 | // we can rewrite them by replacing those references with the expression of the LogicalProjection node |
| 29 | FilterPushdown child_pushdown(optimizer); |
| 30 | for (auto &filter : filters) { |
| 31 | auto &f = *filter; |
| 32 | D_ASSERT(f.bindings.size() <= 1); |
| 33 | // rewrite the bindings within this subquery |
| 34 | f.filter = ReplaceProjectionBindings(proj, expr: std::move(f.filter)); |
| 35 | // add the filter to the child pushdown |
| 36 | if (child_pushdown.AddFilter(expr: std::move(f.filter)) == FilterResult::UNSATISFIABLE) { |
| 37 | // filter statically evaluates to false, strip tree |
| 38 | return make_uniq<LogicalEmptyResult>(args: std::move(op)); |
| 39 | } |
| 40 | } |
| 41 | child_pushdown.GenerateFilters(); |
| 42 | // now push into children |
| 43 | op->children[0] = child_pushdown.Rewrite(op: std::move(op->children[0])); |
| 44 | if (op->children[0]->type == LogicalOperatorType::LOGICAL_EMPTY_RESULT) { |
| 45 | // child returns an empty result: generate an empty result here too |
| 46 | return make_uniq<LogicalEmptyResult>(args: std::move(op)); |
| 47 | } |
| 48 | return op; |
| 49 | } |
| 50 | |
| 51 | } // namespace duckdb |
| 52 |