Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
duckdb::RemoveUnusedColumns Class Reference

The RemoveUnusedColumns optimizer traverses the logical operator tree and removes any columns that are not required. More...

Inheritance diagram for duckdb::RemoveUnusedColumns:
Collaboration diagram for duckdb::RemoveUnusedColumns:

Public Member Functions

 RemoveUnusedColumns (Optimizer &optimizer)
 RemoveUnusedColumns (RemoveUnusedColumns &parent, bool is_root)
void VisitOperator (LogicalOperator &op) override

Private Member Functions

template<class T>
void ClearUnusedExpressions (vector< T > &list, idx_t table_idx, bool replace=true)
void RemoveColumnsFromLogicalGet (LogicalGet &get)
void CheckPushdownExtract (LogicalOperator &op)
void RewriteExpressions (LogicalProjection &proj, idx_t expression_count)
void WritePushdownExtractColumns (const ColumnBinding &binding, ReferencedColumn &col, idx_t original_idx, const LogicalType &column_type, const std::function< idx_t(const ColumnIndex &new_index, optional_ptr< const LogicalType > cast_type)> &callback)
unordered_map< idx_t, MaterializedCTEInfo > & GetCTEMap ()
optional_ptr< unordered_map< idx_t, MaterializedCTEInfo > > TryGetCTEMap ()

Private Attributes

Optimizer & optimizer
Binder & binder
ClientContext & context
bool everything_referenced
RemoveUnusedColumns & root
unique_ptr< unordered_map< idx_t, MaterializedCTEInfo > > root_cte_map

Additional Inherited Members

Static Public Member Functions inherited from duckdb::LogicalOperatorVisitor
static void EnumerateExpressions (LogicalOperator &op, const std::function< void(unique_ptr< Expression > *child)> &callback)
Protected Member Functions inherited from duckdb::BaseColumnPruner
void VisitExpression (unique_ptr< Expression > *expression) override
unique_ptr< Expression > VisitReplace (BoundColumnRefExpression &expr, unique_ptr< Expression > *expr_ptr) override
unique_ptr< Expression > VisitReplace (BoundReferenceExpression &expr, unique_ptr< Expression > *expr_ptr) override
void AddBinding (BoundColumnRefExpression &col)
 Add a reference to the column in its entirey.
void AddBinding (BoundColumnRefExpression &col, ColumnIndex child_column)
 Add a reference to a sub-section of the column.
void AddBinding (BoundColumnRefExpression &col, ColumnIndex child_column, const vector< ReferencedExtractComponent > &parent)
 Add a reference to a sub-section of the column used in a struct extract, with the parent expression.
idx_t ReplaceBinding (ColumnBinding current_binding, ColumnBinding new_binding)
bool HandleExtractExpression (unique_ptr< Expression > *expression, optional_ptr< unique_ptr< Expression > > cast_expression=nullptr)
bool HandleStructExtract (unique_ptr< Expression > &expr, optional_ptr< BoundColumnRefExpression > &colref, reference< ColumnIndex > &path_ref, vector< ReferencedExtractComponent > &expressions)
bool HandleVariantExtract (unique_ptr< Expression > &expr, optional_ptr< BoundColumnRefExpression > &colref, reference< ColumnIndex > &path_ref, vector< ReferencedExtractComponent > &expressions)
bool HandleExtractRecursive (unique_ptr< Expression > &expr, optional_ptr< BoundColumnRefExpression > &colref, reference< ColumnIndex > &path_ref, vector< ReferencedExtractComponent > &expressions)
void SetMode (BaseColumnPrunerMode mode)
BaseColumnPrunerMode GetMode () const
Protected Member Functions inherited from duckdb::LogicalOperatorVisitor
void VisitOperatorChildren (LogicalOperator &op)
void VisitOperatorExpressions (LogicalOperator &op)
void VisitOperatorWithProjectionMapChildren (LogicalOperator &op)
 Alternatives for VisitOperatorChildren for operators that have a projection map.
void VisitChildOfOperatorWithProjectionMap (LogicalOperator &child, vector< idx_t > &projection_map)
virtual void VisitExpressionChildren (Expression &expression)
virtual unique_ptr< Expression > VisitReplace (BoundAggregateExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundBetweenExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundCaseExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundCastExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundComparisonExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundConjunctionExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundConstantExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundDefaultExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundFunctionExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundOperatorExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundSubqueryExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundParameterExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundWindowExpression &expr, unique_ptr< Expression > *expr_ptr)
virtual unique_ptr< Expression > VisitReplace (BoundUnnestExpression &expr, unique_ptr< Expression > *expr_ptr)
Protected Attributes inherited from duckdb::BaseColumnPruner
column_binding_map_t< ReferencedColumn > column_references
 The map of column references.

Detailed Description

The RemoveUnusedColumns optimizer traverses the logical operator tree and removes any columns that are not required.

Constructor & Destructor Documentation

◆ RemoveUnusedColumns() [1/2]

duckdb::RemoveUnusedColumns::RemoveUnusedColumns ( Optimizer & optimizer)
explicit
318338 : optimizer(optimizer), binder(optimizer.binder), context(optimizer.context), everything_referenced(true),
318339 root(*this) {
318340}
bool everything_referenced
Definition duckdb.cpp:60581

◆ RemoveUnusedColumns() [2/2]

duckdb::RemoveUnusedColumns::RemoveUnusedColumns ( RemoveUnusedColumns & parent,
bool is_root )
318343 : optimizer(parent.optimizer), binder(parent.binder), context(parent.context), everything_referenced(is_root),
318344 root(parent.root) {
318345}

Member Function Documentation

◆ VisitOperator()

void duckdb::RemoveUnusedColumns::VisitOperator ( LogicalOperator & op)
overridevirtual

When RETURNING is used, a PROJECTION is the top level operator for INSERTS, UPDATES, and DELETES We still need to project all values from these operators so the projection on top of them can select from only the table values being inserted. TODO: Push down the projections from the returning statement TODO: Be careful because you might be adding expressions when a user returns *

Reimplemented from duckdb::LogicalOperatorVisitor.

318419 {
318420 switch (op.type) {
318421 case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: {
318422 // aggregate
318423 auto &aggr = op.Cast<LogicalAggregate>();
318424 if (!everything_referenced) {
318425 // FIXME: groups that are not referenced need to stay -> but they don't need to be scanned and output!
318426 ClearUnusedExpressions(aggr.expressions, aggr.aggregate_index);
318427 if (aggr.expressions.empty() && aggr.groups.empty()) {
318428 // removed all expressions from the aggregate: push a COUNT(*)
318429 auto count_star_fun = CountStarFun::GetFunction();
318430 FunctionBinder function_binder(context);
318431 aggr.expressions.push_back(
318432 function_binder.BindAggregateFunction(count_star_fun, {}, nullptr, AggregateType::NON_DISTINCT));
318433 }
318434 }
318435
318436 // then recurse into the children of the aggregate
318437 // Note: We allow all optimizations (join column replacement, column pruning) to run below ROLLUP
318438 // The duplicate groups optimizer will be responsible for not breaking ROLLUP by skipping when
318439 // multiple grouping sets are present
318440 RemoveUnusedColumns remove(*this, everything_referenced);
318441 remove.VisitOperatorExpressions(op);
318442 remove.VisitOperator(*op.children[0]);
318443 return;
318444 }
318445 case LogicalOperatorType::LOGICAL_ASOF_JOIN:
318446 case LogicalOperatorType::LOGICAL_DELIM_JOIN:
318447 case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: {
318448 if (everything_referenced) {
318449 break;
318450 }
318451 auto &comp_join = op.Cast<LogicalComparisonJoin>();
318452
318453 if (comp_join.join_type != JoinType::INNER) {
318454 break;
318455 }
318456 // for inner joins with equality predicates in the form of (X=Y)
318457 // we can replace any references to the RHS (Y) to references to the LHS (X)
318458 // this reduces the amount of columns we need to extract from the join hash table
318459 // (except in the case of floating point numbers which have +0 and -0, equal but different).
318460 for (auto &cond : comp_join.conditions) {
318461 if (cond.comparison != ExpressionType::COMPARE_EQUAL) {
318462 continue;
318463 }
318464 if (cond.left->GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) {
318465 continue;
318466 }
318467 if (cond.right->GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) {
318468 continue;
318469 }
318470 if (cond.left->Cast<BoundColumnRefExpression>().return_type.IsFloating()) {
318471 continue;
318472 }
318473 if (cond.right->Cast<BoundColumnRefExpression>().return_type.IsFloating()) {
318474 continue;
318475 }
318476 // comparison join between two bound column refs
318477 // we can replace any reference to the RHS (build-side) with a reference to the LHS (probe-side)
318478 auto &lhs_col = cond.left->Cast<BoundColumnRefExpression>();
318479 auto &rhs_col = cond.right->Cast<BoundColumnRefExpression>();
318480 // if there are any columns that refer to the RHS,
318481 auto colrefs = column_references.find(rhs_col.binding);
318482 if (colrefs == column_references.end()) {
318483 continue;
318484 }
318485 for (auto &entry : colrefs->second.bindings) {
318486 auto &colref = entry.get();
318487 colref.binding = lhs_col.binding;
318488 AddBinding(colref);
318489 }
318490 column_references.erase(rhs_col.binding);
318491 }
318492 break;
318493 }
318494 case LogicalOperatorType::LOGICAL_ANY_JOIN:
318495 break;
318496 case LogicalOperatorType::LOGICAL_UNION: {
318497 auto &setop = op.Cast<LogicalSetOperation>();
318498 if (setop.setop_all && !everything_referenced) {
318499 // for UNION we can remove unreferenced columns if union all is used
318500 // it's possible not all columns are referenced, but unreferenced columns in the union can
318501 // still have an affect on the result of the union
318502 vector<idx_t> entries;
318503 for (idx_t i = 0; i < setop.column_count; i++) {
318504 entries.push_back(i);
318505 }
318506 ClearUnusedExpressions(entries, setop.table_index);
318507 if (entries.size() >= setop.column_count) {
318508 // We still need to recurse into the children to populate CTE info, etc.
318509 for (auto &child : op.children) {
318510 RemoveUnusedColumns remove(*this, true);
318511 remove.VisitOperator(*child);
318512 }
318513
318514 return;
318515 }
318516 if (entries.empty()) {
318517 // no columns referenced: this happens in the case of a COUNT(*)
318518 // extract the first column
318519 entries.push_back(0);
318520 }
318521 // columns were cleared
318522 setop.column_count = entries.size();
318523
318524 for (idx_t child_idx = 0; child_idx < op.children.size(); child_idx++) {
318525 RemoveUnusedColumns remove(*this, true);
318526 auto &child = op.children[child_idx];
318527
318528 // we push a projection under this child that references the required columns of the union
318529 child->ResolveOperatorTypes();
318530 auto bindings = child->GetColumnBindings();
318531 vector<unique_ptr<Expression>> expressions;
318532 expressions.reserve(entries.size());
318533 for (auto &column_idx : entries) {
318534 expressions.push_back(
318535 make_uniq<BoundColumnRefExpression>(child->types[column_idx], bindings[column_idx]));
318536 }
318537
318538 auto new_projection = make_uniq<LogicalProjection>(binder.GenerateTableIndex(), std::move(expressions));
318539 if (child->has_estimated_cardinality) {
318540 new_projection->SetEstimatedCardinality(child->estimated_cardinality);
318541 }
318542 new_projection->children.push_back(std::move(child));
318543 op.children[child_idx] = std::move(new_projection);
318544
318545 remove.VisitOperator(*op.children[child_idx]);
318546 }
318547 return;
318548 }
318549 for (auto &child : op.children) {
318550 RemoveUnusedColumns remove(*this, true);
318551 remove.VisitOperator(*child);
318552 }
318553 return;
318554 }
318555 case LogicalOperatorType::LOGICAL_EXCEPT:
318556 case LogicalOperatorType::LOGICAL_INTERSECT: {
318557 // for INTERSECT/EXCEPT operations we can't remove anything, just recursively visit the children
318558 for (auto &child : op.children) {
318559 RemoveUnusedColumns remove(*this, true);
318560 remove.VisitOperator(*child);
318561 }
318562 return;
318563 }
318564 case LogicalOperatorType::LOGICAL_PROJECTION: {
318565 if (!everything_referenced) {
318566 auto &proj = op.Cast<LogicalProjection>();
318568 auto old_expression_count = proj.expressions.size();
318569 ClearUnusedExpressions(proj.expressions, proj.table_index);
318570 RewriteExpressions(proj, old_expression_count);
318571
318572 if (proj.expressions.empty()) {
318573 // nothing references the projected expressions
318574 // this happens in the case of e.g. EXISTS(SELECT * FROM ...)
318575 // in this case we only need to project a single constant
318576 proj.expressions.push_back(make_uniq<BoundConstantExpression>(Value::INTEGER(42)));
318577 }
318578 }
318579 // then recurse into the children of this projection
318580 RemoveUnusedColumns remove(*this, false);
318581 remove.VisitOperatorExpressions(op);
318582 remove.VisitOperator(*op.children[0]);
318583 return;
318584 }
318585 case LogicalOperatorType::LOGICAL_INSERT:
318586 case LogicalOperatorType::LOGICAL_UPDATE:
318587 case LogicalOperatorType::LOGICAL_DELETE:
318588 case LogicalOperatorType::LOGICAL_MERGE_INTO: {
318594 RemoveUnusedColumns remove(*this, true);
318595 remove.VisitOperatorExpressions(op);
318596 remove.VisitOperator(*op.children[0]);
318597 return;
318598 }
318599 case LogicalOperatorType::LOGICAL_GET: {
318601 auto &get = op.Cast<LogicalGet>();
318603 if (!op.children.empty()) {
318604 // Some LOGICAL_GET operators (e.g., table in out functions) may have a
318605 // child operator. So we recurse into it if it exists.
318606 RemoveUnusedColumns remove(*this, true);
318607 remove.VisitOperator(*op.children[0]);
318608 }
318609 return;
318610 }
318611 case LogicalOperatorType::LOGICAL_DISTINCT: {
318612 auto &distinct = op.Cast<LogicalDistinct>();
318613 if (distinct.distinct_type == DistinctType::DISTINCT_ON) {
318614 // distinct type references columns that need to be distinct on, so no
318615 // need to implicity reference everything.
318616 break;
318617 }
318618 // distinct, all projected columns are used for the DISTINCT computation
318619 // mark all columns as used and continue to the children
318620 // FIXME: DISTINCT with expression list does not implicitly reference everything
318621 everything_referenced = true;
318622 break;
318623 }
318624 case LogicalOperatorType::LOGICAL_RECURSIVE_CTE: {
318625 // We do not (yet) support pruning columns in recursive CTEs, so we mark everything as referenced and continue
318626 // to the children. However, we still need to create the cte_info_map for the recursive CTE so that column
318627 // references in the CTE body can find the correct CTE entry and mark columns as referenced.
318628 auto &rec = op.Cast<LogicalCTE>();
318629 auto &cte_info_map = GetCTEMap();
318630 cte_info_map.insert({rec.table_index, MaterializedCTEInfo()});
318631 everything_referenced = true;
318632 break;
318633 }
318634 case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: {
318635 auto &cte_map_ref = GetCTEMap();
318636 auto &cte = op.Cast<LogicalCTE>();
318637 auto &cte_map_entry = cte_map_ref[cte.table_index];
318638
318639 // Gather all scans of this CTE in the query and mark them as expected readers of this CTE
318640 GatherCTEScans(cte.table_index, *cte.children[1], cte_map_entry.expected_readers);
318641 cte_map_entry.everything_referenced = false;
318642 RemoveUnusedColumns rhs_child_optimizer(*this, true);
318643 rhs_child_optimizer.VisitOperator(*cte.children[1]);
318644
318645 unordered_set<idx_t> referenced_columns_in_rhs;
318646 for (auto &entry : cte_map_entry.column_references) {
318647 referenced_columns_in_rhs.insert(entry.first.column_index);
318648 }
318649
318650 // If we have seen all readers of this CTE, and not all columns are referenced, we can prune the left-hand side
318651 // of the CTE. However, if we have not seen all readers, we opt to not prune, because we might miss column
318652 // references, resulting in incorrect query results.
318653 auto have_seen_all_readers = cte_map_entry.expected_readers == cte_map_entry.seen_readers;
318654
318655 if (!have_seen_all_readers) {
318656 // We did not traverse the entire plan. Something is wrong.
318657 throw InternalException("CTE pruning did not traverse the entire plan. This is a bug in the optimizer.");
318658 }
318659
318660 if (!cte_map_entry.everything_referenced && have_seen_all_readers) {
318661 RemoveUnusedColumns lhs_child_optimizer(*this, true);
318662 // Construct a projection on top of the left-hand side of the CTE
318663 // that only projects the columns that are referenced in the right-hand side of the CTE
318664 cte.children[0]->ResolveOperatorTypes();
318665 auto bindings = cte.children[0]->GetColumnBindings();
318666 vector<unique_ptr<Expression>> expressions;
318667 if (referenced_columns_in_rhs.empty()) {
318668 // if we have no columns selected just select the first column
318669 referenced_columns_in_rhs.insert(0);
318670 }
318671 for (idx_t i = 0; i < bindings.size(); i++) {
318672 if (referenced_columns_in_rhs.find(i) != referenced_columns_in_rhs.end()) {
318673 expressions.push_back(make_uniq<BoundColumnRefExpression>(cte.children[0]->types[i], bindings[i]));
318674 }
318675 }
318676
318677 auto projection = make_uniq<LogicalProjection>(binder.GenerateTableIndex(), std::move(expressions));
318678 projection->children.push_back(std::move(cte.children[0]));
318679 cte.children[0] = std::move(projection);
318680
318681 lhs_child_optimizer.VisitOperator(*cte.children[0]);
318682
318683 // After pruning the left-hand side of the CTE, we need to rewrite the CTE references to account for the
318684 // removed columns.
318685 CTERefPruner cte_ref_pruner(cte.table_index, referenced_columns_in_rhs);
318686 cte_ref_pruner.VisitOperator(*cte.children[1]);
318687
318688 // We also need to rewrite the column bindings in the right-hand side of the CTE to account for the removed
318689 // columns on the left-hand side. Conveniently, the CTERefPruner already has the information about which
318690 // columns were removed, so we can reuse it for the column binding replacement.
318691 ColumnBindingReplacer column_binding_replacer;
318692 column_binding_replacer.replacement_bindings = cte_ref_pruner.binding_replacements;
318693 column_binding_replacer.VisitOperator(*cte.children[1]);
318694 return;
318695 }
318696 everything_referenced = true;
318697 // We may opt out here, but we still need to traverse the left-hand side of the CTE
318698 RemoveUnusedColumns remove(*this, true);
318699 remove.VisitOperator(*cte.children[0]);
318700 return;
318701 }
318702 case LogicalOperatorType::LOGICAL_CTE_REF: {
318703 auto &cte_ref = op.Cast<LogicalCTERef>();
318704
318705 auto cte_info_map = TryGetCTEMap();
318706 if (!cte_info_map) {
318707 everything_referenced = true;
318708 break;
318709 }
318710 auto &cte_map_ref = *cte_info_map;
318711 auto it = cte_map_ref.find(cte_ref.cte_index);
318712 if (it == cte_map_ref.end()) {
318713 throw InternalException("Could not find CTE definition for CTE reference");
318714 }
318715 auto &cte_entry = it->second;
318716 auto &referenced_columns = cte_entry.column_references;
318717
318718 // Mark this CTE reference as a seen reader of the CTE
318719 it->second.seen_readers.insert(cte_ref.table_index);
318720
318721 for (auto &entry : column_references) {
318722 if (entry.first.table_index == cte_ref.table_index) {
318723 referenced_columns.insert(entry);
318724 }
318725 }
318726
318727 cte_map_ref[cte_ref.cte_index].everything_referenced |=
318728 cte_ref.chunk_types.size() == cte_map_ref[cte_ref.cte_index].column_references.size();
318729
318730 break;
318731 }
318732 case LogicalOperatorType::LOGICAL_COPY_TO_FILE:
318733 case LogicalOperatorType::LOGICAL_PIVOT: {
318734 everything_referenced = true;
318735 break;
318736 }
318737 default:
318738 break;
318739 }
318742
318743 if (op.type == LogicalOperatorType::LOGICAL_ASOF_JOIN || op.type == LogicalOperatorType::LOGICAL_DELIM_JOIN ||
318744 op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) {
318745 auto &comp_join = op.Cast<LogicalComparisonJoin>();
318746 // after removing duplicate columns we may have duplicate join conditions (if the join graph is cyclical)
318747 vector<JoinCondition> unique_conditions;
318748 for (auto &cond : comp_join.conditions) {
318749 bool found = false;
318750 for (auto &unique_cond : unique_conditions) {
318751 if (cond.comparison == unique_cond.comparison && cond.left->Equals(*unique_cond.left) &&
318752 cond.right->Equals(*unique_cond.right)) {
318753 found = true;
318754 break;
318755 }
318756 }
318757 if (!found) {
318758 unique_conditions.push_back(std::move(cond));
318759 }
318760 }
318761 comp_join.conditions = std::move(unique_conditions);
318762 }
318763}
void AddBinding(BoundColumnRefExpression &col)
Add a reference to the column in its entirey.
Definition duckdb.cpp:319428
column_binding_map_t< ReferencedColumn > column_references
The map of column references.
Definition duckdb.cpp:60560
void VisitOperatorExpressions(LogicalOperator &op)
Definition duckdb.cpp:381188
void VisitOperatorChildren(LogicalOperator &op)
Definition duckdb.cpp:380983
void CheckPushdownExtract(LogicalOperator &op)
Definition duckdb.cpp:318932
void RewriteExpressions(LogicalProjection &proj, idx_t expression_count)
Definition duckdb.cpp:318883
void ClearUnusedExpressions(vector< T > &list, idx_t table_idx, bool replace=true)
Definition duckdb.cpp:318384
void RemoveColumnsFromLogicalGet(LogicalGet &get)
Definition duckdb.cpp:319005
static DUCKDB_API Value INTEGER(int32_t value)
Create an integer Value from a specified value.
Definition duckdb.cpp:132139
__host__ cudaTextureObject_t get() const noexcept
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ClearUnusedExpressions()

template<class T>
void duckdb::RemoveUnusedColumns::ClearUnusedExpressions ( vector< T > & list,
idx_t table_idx,
bool replace = true )
private

One or more children of this column are referenced, and pushdown-extract is enabled

318384 {
318385 idx_t offset = 0;
318386 idx_t new_col_idx = 0;
318387 for (idx_t col_idx = 0; col_idx < list.size(); col_idx++) {
318388 auto current_binding = ColumnBinding(table_idx, col_idx + offset);
318389 auto entry = column_references.find(current_binding);
318390 if (entry == column_references.end()) {
318391 // this entry is not referred to, erase it from the set of expressions
318392 list.erase_at(col_idx);
318393 offset++;
318394 col_idx--;
318395 continue;
318396 }
318397 if (!replace) {
318398 continue;
318399 }
318400 bool should_replace = false;
318401 if (col_idx + offset != new_col_idx) {
318402 should_replace = true;
318403 }
318404 if (!entry->second.child_columns.empty() &&
318405 entry->second.supports_pushdown_extract == PushdownExtractSupport::ENABLED) {
318407 should_replace = true;
318408 }
318409 if (should_replace) {
318410 // column is used but the ColumnBinding has changed because of removed columns
318411 auto created_bindings = ReplaceBinding(current_binding, ColumnBinding(table_idx, new_col_idx));
318412 new_col_idx += created_bindings;
318413 } else {
318414 new_col_idx++;
318415 }
318416 }
318417}
idx_t ReplaceBinding(ColumnBinding current_binding, ColumnBinding new_binding)
Definition duckdb.cpp:318358
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RemoveColumnsFromLogicalGet()

void duckdb::RemoveUnusedColumns::RemoveColumnsFromLogicalGet ( LogicalGet & get)
private

The existing column ids

The newly written column ids (same size as 'original_ids')

The old index that the new one is based on (same size as 'new_column_ids')

Map of column index to binding, for pushed down struct extracts

Created bindings per original_column (for pushdown extract verification)

i.e: This contains all the columns of the table

  1. The set of filtered ids containing only the columns referenced by the projection expressions (proj_sel)
  2. The set of filtered ids containing columns referenced by either the projection or the filter expressions (col_sel)

FIXME: pushdown extract is disabled when a struct field is referenced by a filter, because that would involve rewriting the existing TableFilterSet

NOTE: This vector is required to keep the referenced Expressions alive

Convert the filter to an expression, so we can visit it

Now visit the filter to add to the 'column_references'

Check with the LogicalGet whether pushdown-extract is supported

RemoveUnusedColumns is also used by other optimizers, so we have to deal with this case and preserve the PushdownExtract we created earlier

Pushdown Extract is supported, emit a column for every field

Adds the binding for the child only if it doesn't exist yet

Find matching indices between the proj_sel and the col_sel

319005 {
319006 if (everything_referenced) {
319007 return;
319008 }
319009 if (!get.function.projection_pushdown) {
319010 return;
319011 }
319012
319014 auto old_column_ids = get.GetColumnIds();
319016 vector<ColumnIndex> new_column_ids;
319018 vector<idx_t> original_ids;
319020 column_index_map<idx_t> child_map;
319022 unordered_map<idx_t, idx_t> created_bindings;
319023
319024 // Create "selection vector" that contains all indices of the old 'column_ids' of the LogicalGet
319026 vector<idx_t> proj_sel;
319027 for (idx_t col_idx = 0; col_idx < old_column_ids.size(); col_idx++) {
319028 proj_sel.push_back(col_idx);
319029 }
319030 // Create a copy so we can later check the difference between these two:
319034 auto col_sel = proj_sel;
319035 // Clear unused ids, exclude filter columns that are projected out immediately
319036 ClearUnusedExpressions(proj_sel, get.table_index, false);
319037
319041
319042 // for every table filter, push a column binding into the column references map to prevent the column from
319043 // being projected out
319044
319046 vector<unique_ptr<Expression>> filter_expressions;
319047 for (auto &filter : get.table_filters.filters) {
319048 auto index = GetColumnIdsIndexForFilter(old_column_ids, filter.first);
319049 auto column_type = get.GetColumnType(ColumnIndex(filter.first));
319050
319051 ColumnBinding filter_binding(get.table_index, index);
319052 auto column_ref = make_uniq<BoundColumnRefExpression>(std::move(column_type), filter_binding);
319054 auto filter_expr = filter.second->ToExpression(*column_ref);
319055 if (filter_expr->IsScalar()) {
319056 filter_expr = std::move(column_ref);
319057 }
319058 filter_expressions.push_back(std::move(filter_expr));
319060 VisitExpression(&filter_expressions.back());
319061 }
319062
319065
319066 // Clear unused ids, include filter columns that are projected out immediately
319067 ClearUnusedExpressions(col_sel, get.table_index);
319068
319069 // Now set the column ids in the LogicalGet using the "selection vector"
319070 for (auto &col_sel_idx : col_sel) {
319071 auto &column_type = get.GetColumnType(old_column_ids[col_sel_idx]);
319072 auto entry = column_references.find(ColumnBinding(get.table_index, col_sel_idx));
319073 if (entry == column_references.end()) {
319074 throw InternalException("RemoveUnusedColumns - could not find referenced column");
319075 }
319076 if (entry->second.child_columns.empty() ||
319077 entry->second.supports_pushdown_extract != PushdownExtractSupport::ENABLED) {
319078 auto &logical_column_id = old_column_ids[col_sel_idx];
319079
319080 original_ids.emplace_back(col_sel_idx);
319081 if (logical_column_id.IsPushdownExtract()) {
319084 D_ASSERT(entry->second.child_columns.empty());
319085 new_column_ids.emplace_back(logical_column_id);
319086 } else {
319087 ColumnIndex new_index(logical_column_id.GetPrimaryIndex(), entry->second.child_columns);
319088 new_column_ids.emplace_back(std::move(new_index));
319089 }
319090 continue;
319091 }
319092 auto struct_column_index = old_column_ids[col_sel_idx].GetPrimaryIndex();
319093
319096 entry->first, entry->second, col_sel_idx, column_type,
319097 [&](const ColumnIndex &extract_path, optional_ptr<const LogicalType> cast_type) -> idx_t {
319098 ColumnIndex new_index(struct_column_index, {extract_path});
319099 new_index.SetPushdownExtractType(column_type, cast_type);
319100
319101 auto column_binding_index = new_column_ids.size();
319102 auto entry = child_map.find(new_index);
319103 if (entry == child_map.end()) {
319105 entry = child_map.emplace(new_index, column_binding_index).first;
319106 created_bindings[new_index.GetPrimaryIndex()]++;
319107
319108 new_column_ids.emplace_back(std::move(new_index));
319109 original_ids.emplace_back(col_sel_idx);
319110 }
319111 return entry->second;
319112 });
319113 }
319114 if (new_column_ids.empty()) {
319115 // this generally means we are only interested in whether or not anything exists in the table (e.g.
319116 // EXISTS(SELECT * FROM tbl)) in this case, we just scan the row identifier column as it means we do not
319117 // need to read any of the columns
319118 auto any_column = get.GetAnyColumn();
319119 original_ids.emplace_back(any_column);
319120 new_column_ids.emplace_back(any_column);
319121 }
319122 get.SetColumnIds(std::move(new_column_ids));
319123
319124 if (!get.function.filter_prune) {
319125 return;
319126 }
319127 // Now set the projection cols by matching the "selection vector" that excludes filter columns
319128 // with the "selection vector" that includes filter columns
319129 idx_t col_idx = 0;
319130 get.projection_ids.clear();
319131 vector<idx_t> filtered_original_ids;
319133 for (auto to_keep : proj_sel) {
319134 for (; col_idx < col_sel.size(); col_idx++) {
319135 if (to_keep == col_sel[col_idx]) {
319136 filtered_original_ids.push_back(to_keep);
319137 break;
319138 }
319139 }
319140 }
319141 col_idx = 0;
319142 for (auto col : filtered_original_ids) {
319143 for (; col_idx < original_ids.size(); col_idx++) {
319144 if (original_ids[col_idx] == col) {
319145 get.projection_ids.push_back(col_idx);
319146 } else if (original_ids[col_idx] > col) {
319147 break;
319148 }
319149 }
319150 }
319151}
void VisitExpression(unique_ptr< Expression > *expression) override
Definition duckdb.cpp:319455
void WritePushdownExtractColumns(const ColumnBinding &binding, ReferencedColumn &col, idx_t original_idx, const LogicalType &column_type, const std::function< idx_t(const ColumnIndex &new_index, optional_ptr< const LogicalType > cast_type)> &callback)
Definition duckdb.cpp:318819
index
void filter(InputArray image, InputArray kernel, OutputArray output)
@ DISABLE_PUSHDOWN_EXTRACT
Any child reference disables PUSHDOWN_EXTRACT for the parent column.
Definition duckdb.cpp:60512
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CheckPushdownExtract()

void duckdb::RemoveUnusedColumns::CheckPushdownExtract ( LogicalOperator & op)
private

For all referenced struct fields, check if the scan supports pushing down the extract

Binding is not referenced, skip

Either not a struct, or we're not using struct field projection pushdown - skip it

We're already not using pushdown extract for this column, no need to check with the scan

Either 'statistics_extended' needs to be set or 'statistics' needs to be NULL

Not referenced, skip

No children of this column are referenced, skip

Not a column reference, can't pull up the extract

Extract pull up only supported for STRUCT currently

Already explicitly disabled, don't need to check

318932 {
318933 switch (op.type) {
318934 case LogicalOperatorType::LOGICAL_GET: {
318935 auto &get = op.Cast<LogicalGet>();
318937 auto &column_ids = get.GetColumnIds();
318938 for (idx_t i = 0; i < column_ids.size(); i++) {
318939 auto entry = column_references.find(ColumnBinding(get.table_index, i));
318940 if (entry == column_references.end()) {
318942 continue;
318943 }
318944 auto &col = entry->second;
318945 if (col.struct_extracts.empty()) {
318947 continue;
318948 }
318949 if (col.supports_pushdown_extract == PushdownExtractSupport::DISABLED) {
318951 continue;
318952 }
318953 auto logical_column_index = LogicalIndex(column_ids[i].GetPrimaryIndex());
318954 if (!get.function.supports_pushdown_extract || get.function.statistics) {
318956 col.supports_pushdown_extract = PushdownExtractSupport::DISABLED;
318957 continue;
318958 }
318959 D_ASSERT(get.bind_data);
318960 if (get.function.supports_pushdown_extract(*get.bind_data, logical_column_index)) {
318961 col.supports_pushdown_extract = PushdownExtractSupport::ENABLED;
318962 } else {
318963 col.supports_pushdown_extract = PushdownExtractSupport::DISABLED;
318964 }
318965 }
318966 return;
318967 }
318968 case LogicalOperatorType::LOGICAL_PROJECTION: {
318969 auto &proj = op.Cast<LogicalProjection>();
318970 for (idx_t idx = 0; idx < proj.expressions.size(); idx++) {
318971 auto &expr = *proj.expressions[idx];
318972 auto record = column_references.find(ColumnBinding(proj.table_index, idx));
318973 if (record == column_references.end()) {
318975 continue;
318976 }
318977 auto &col = record->second;
318978 auto &child_columns = col.child_columns;
318979 if (child_columns.empty()) {
318981 continue;
318982 }
318983 if (expr.type != ExpressionType::BOUND_COLUMN_REF) {
318985 continue;
318986 }
318987 if (expr.return_type.id() != LogicalTypeId::STRUCT) {
318989 continue;
318990 }
318991 if (col.supports_pushdown_extract == PushdownExtractSupport::DISABLED) {
318993 continue;
318994 }
318995 col.supports_pushdown_extract = PushdownExtractSupport::ENABLED;
318996 }
318997 return;
318998 }
318999 default:
319000 throw InternalException("CheckPushdownExtract not supported for LogicalOperatorType::%s",
319001 EnumUtil::ToString(op.type));
319002 }
319003}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RewriteExpressions()

void duckdb::RemoveUnusedColumns::RewriteExpressions ( LogicalProjection & proj,
idx_t expression_count )
private

Already removed by the call to ClearUnusedExpressions

Pushdown Extract is supported, emit a column for every field

318883 {
318884 vector<unique_ptr<Expression>> expressions;
318885 auto &context = this->context;
318886
318887 column_index_map<idx_t> new_bindings;
318888 idx_t expression_idx = 0;
318889 for (idx_t i = 0; i < expression_count; i++) {
318890 auto binding = ColumnBinding(proj.table_index, i);
318891 auto entry = column_references.find(binding);
318892 if (entry == column_references.end()) {
318894 continue;
318895 }
318896 if (entry->second.child_columns.empty() ||
318897 entry->second.supports_pushdown_extract != PushdownExtractSupport::ENABLED) {
318898 expressions.push_back(std::move(proj.expressions[expression_idx++]));
318899 continue;
318900 }
318901 auto &expr = *proj.expressions[expression_idx++];
318902 auto &colref = expr.Cast<BoundColumnRefExpression>();
318903 auto original_binding = colref.binding;
318904 auto &column_type = expr.return_type;
318905 idx_t start = expressions.size();
318908 entry->first, entry->second, i, column_type,
318909 [&](const ColumnIndex &extract_path, optional_ptr<const LogicalType> cast_type) -> idx_t {
318910 auto target = make_uniq<BoundColumnRefExpression>(column_type, original_binding);
318911 target->SetAlias(expr.GetAlias());
318912 auto new_extract = ConstructStructExtractFromPath(context, std::move(target), extract_path);
318913 if (cast_type) {
318914 auto cast = BoundCastExpression::AddCastToType(context, std::move(new_extract), *cast_type);
318915 new_extract = std::move(cast);
318916 }
318917 ColumnIndex full_path(i);
318918 full_path.AddChildIndex(extract_path);
318919 auto it = new_bindings.emplace(full_path, expressions.size()).first;
318920 if (it->second == expressions.size()) {
318921 expressions.push_back(std::move(new_extract));
318922 }
318923 return it->second;
318924 });
318925 for (; start < expressions.size(); start++) {
318926 VisitExpression(&expressions[start]);
318927 }
318928 }
318929 proj.expressions = std::move(expressions);
318930}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WritePushdownExtractColumns()

void duckdb::RemoveUnusedColumns::WritePushdownExtractColumns ( const ColumnBinding & binding,
ReferencedColumn & col,
idx_t original_idx,
const LogicalType & column_type,
const std::function< idx_t(const ColumnIndex &new_index, optional_ptr< const LogicalType > cast_type)> & callback )
private

For each struct extract, replace the expression with a BoundColumnRefExpression The expression references a binding created for the extracted path, 1 per unique path

Replace the struct extract expression at the right depth with a BoundColumnRefExpression

318821 {
318824 for (auto &struct_extract : col.struct_extracts) {
318826 auto &full_path = struct_extract.extract_path;
318827
318828 auto res = FindShortestMatchingPath(col.unique_paths, full_path);
318829 auto entry = res.first;
318830 auto depth = res.second;
318831 if (entry == col.unique_paths.end()) {
318832 throw InternalException("This path wasn't found in the registered paths for this expression at all!?");
318833 }
318834 D_ASSERT(struct_extract.components.size() > depth);
318835 auto &component = struct_extract.components[depth];
318836 auto &expr = component.cast ? *component.cast : component.extract;
318837
318838 auto return_type = expr->return_type;
318839
318840 auto &colref = col.bindings[struct_extract.bindings_idx];
318841 auto colref_copy = colref.get().Copy();
318842 expr = std::move(colref_copy);
318843 auto &new_expr = expr->Cast<BoundColumnRefExpression>();
318844 new_expr.return_type = return_type;
318845
318846 auto column_index = callback(*entry, component.cast ? &(*component.cast)->return_type : nullptr);
318847 new_expr.binding.column_index = column_index;
318848 }
318849}
double depth(InputArray R, InputArray t, InputArray X)
std::pair< column_index_set::iterator, idx_t > FindShortestMatchingPath(column_index_set &all_paths, const ColumnIndex &full_path)
returns: found_path, depth of the found path
Definition duckdb.cpp:318777
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetCTEMap()

unordered_map< idx_t, MaterializedCTEInfo > & duckdb::RemoveUnusedColumns::GetCTEMap ( )
private
318347 {
318348 if (!root.root_cte_map) {
318349 root.root_cte_map = make_uniq<unordered_map<idx_t, MaterializedCTEInfo>>();
318350 }
318351 return *root.root_cte_map;
318352}

◆ TryGetCTEMap()

optional_ptr< unordered_map< idx_t, MaterializedCTEInfo > > duckdb::RemoveUnusedColumns::TryGetCTEMap ( )
private
318354 {
318355 return root.root_cte_map.get();
318356}

Member Data Documentation

◆ everything_referenced

bool duckdb::RemoveUnusedColumns::everything_referenced
private

Whether or not all the columns are referenced. This happens in the case of the root expression (because the output implicitly refers all the columns below it)


The documentation for this class was generated from the following file: