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
7using namespace duckdb;
8using namespace std;
9
10static unique_ptr<Expression> ReplaceProjectionBindings(LogicalProjection &proj, unique_ptr<Expression> expr) {
11 if (expr->type == ExpressionType::BOUND_COLUMN_REF) {
12 auto &colref = (BoundColumnRefExpression &)*expr;
13 assert(colref.binding.table_index == proj.table_index);
14 assert(colref.binding.column_index < proj.expressions.size());
15 assert(colref.depth == 0);
16 // replace the binding with a copy to the expression at the referenced index
17 return proj.expressions[colref.binding.column_index]->Copy();
18 }
19 ExpressionIterator::EnumerateChildren(*expr, [&](unique_ptr<Expression> child) -> unique_ptr<Expression> {
20 return ReplaceProjectionBindings(proj, move(child));
21 });
22 return expr;
23}
24
25unique_ptr<LogicalOperator> FilterPushdown::PushdownProjection(unique_ptr<LogicalOperator> op) {
26 assert(op->type == LogicalOperatorType::PROJECTION);
27 auto &proj = (LogicalProjection &)*op;
28 // push filter through logical projection
29 // all the BoundColumnRefExpressions in the filter should refer to the LogicalProjection
30 // we can rewrite them by replacing those references with the expression of the LogicalProjection node
31 FilterPushdown child_pushdown(optimizer);
32 for (idx_t i = 0; i < filters.size(); i++) {
33 auto &f = *filters[i];
34 assert(f.bindings.size() <= 1);
35 // rewrite the bindings within this subquery
36 f.filter = ReplaceProjectionBindings(proj, move(f.filter));
37 // add the filter to the child pushdown
38 if (child_pushdown.AddFilter(move(f.filter)) == FilterResult::UNSATISFIABLE) {
39 // filter statically evaluates to false, strip tree
40 return make_unique<LogicalEmptyResult>(move(op));
41 }
42 }
43 child_pushdown.GenerateFilters();
44 // now push into children
45 op->children[0] = child_pushdown.Rewrite(move(op->children[0]));
46 return op;
47}
48