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::RelationManager Class Reference
Collaboration diagram for duckdb::RelationManager:

Public Member Functions

 RelationManager (ClientContext &context)
idx_t NumRelations ()
bool ExtractJoinRelations (JoinOrderOptimizer &optimizer, LogicalOperator &input_op, vector< reference< LogicalOperator > > &filter_operators, optional_ptr< LogicalOperator > parent=nullptr)
vector< unique_ptr< FilterInfo > > ExtractEdges (LogicalOperator &op, vector< reference< LogicalOperator > > &filter_operators, JoinRelationSetManager &set_manager)
bool ExtractBindings (Expression &expression, unordered_set< idx_t > &bindings)
 Extract the set of relations referred to inside an expression.
void AddRelation (LogicalOperator &op, optional_ptr< LogicalOperator > parent, const RelationStats &stats)
void AddRelationWithChildren (JoinOrderOptimizer &optimizer, LogicalOperator &op, LogicalOperator &input_op, optional_ptr< LogicalOperator > parent, RelationStats &child_stats, optional_ptr< LogicalOperator > limit_op, vector< reference< LogicalOperator > > &datasource_filters)
 Add an unnest relation which can come from a logical unnest or a logical get which has an unnest function.
void AddAggregateOrWindowRelation (LogicalOperator &op, optional_ptr< LogicalOperator > parent, const RelationStats &stats, LogicalOperatorType op_type)
vector< unique_ptr< SingleJoinRelation > > GetRelations ()
const vector< RelationStats > GetRelationStats ()
bool CrossProductWithRelationAllowed (idx_t relation_id)
void PrintRelationStats ()

Public Attributes

unordered_map< idx_t, idx_t > relation_mapping
 A mapping of base table index -> index into relations array (relation number).

Private Attributes

ClientContext & context
vector< unique_ptr< SingleJoinRelation > > relations
 Set of all relations considered in the join optimizer.
unordered_set< idx_t > no_cross_product_relations

Constructor & Destructor Documentation

◆ RelationManager()

duckdb::RelationManager::RelationManager ( ClientContext & context)
inlineexplicit
21616 : context(context) {
21617 }

Member Function Documentation

◆ NumRelations()

idx_t duckdb::RelationManager::NumRelations ( )
313294 {
313295 return relations.size();
313296}
vector< unique_ptr< SingleJoinRelation > > relations
Set of all relations considered in the join optimizer.
Definition duckdb.hpp:21654

◆ ExtractJoinRelations()

bool duckdb::RelationManager::ExtractJoinRelations ( JoinOrderOptimizer & optimizer,
LogicalOperator & input_op,
vector< reference< LogicalOperator > > & filter_operators,
optional_ptr< LogicalOperator > parent = nullptr )
313474 {
313475 optional_ptr<LogicalOperator> op = &input_op;
313476 vector<reference<LogicalOperator>> datasource_filters;
313477 optional_ptr<LogicalOperator> limit_op = nullptr;
313478 // pass through single child operators
313479 while (op->children.size() == 1 && !OperatorNeedsRelation(op->type)) {
313480 if (op->type == LogicalOperatorType::LOGICAL_FILTER) {
313481 if (HasNonReorderableChild(*op)) {
313482 datasource_filters.push_back(*op);
313483 }
313484 filter_operators.push_back(*op);
313485 }
313486 if (op->type == LogicalOperatorType::LOGICAL_LIMIT) {
313487 limit_op = op;
313488 }
313489 op = op->children[0].get();
313490 }
313491 bool non_reorderable_operation = false;
313492 if (OperatorIsNonReorderable(op->type)) {
313493 // set operation, optimize separately in children
313494 non_reorderable_operation = true;
313495 }
313496
313497 if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) {
313498 if (JoinIsReorderable(*op)) {
313499 // extract join conditions from inner join
313500 filter_operators.push_back(*op);
313501 } else {
313502 non_reorderable_operation = true;
313503 }
313504 }
313505 if (non_reorderable_operation) {
313506 // we encountered a non-reordable operation (setop or non-inner join)
313507 // we do not reorder non-inner joins yet, however we do want to expand the potential join graph around them
313508 // non-inner joins are also tricky because we can't freely make conditions through them
313509 // e.g. suppose we have (left LEFT OUTER JOIN right WHERE right IS NOT NULL), the join can generate
313510 // new NULL values in the right side, so pushing this condition through the join leads to incorrect results
313511 // for this reason, we just start a new JoinOptimizer pass in each of the children of the join
313512 // stats.cardinality will be initiated to highest cardinality of the children.
313513 vector<RelationStats> children_stats;
313514 for (auto &child : op->children) {
313515 auto stats = RelationStats();
313516 auto child_optimizer = optimizer.CreateChildOptimizer();
313517 child = child_optimizer.Optimize(std::move(child), &stats);
313518 children_stats.push_back(stats);
313519 }
313520
313521 auto combined_stats = RelationStatisticsHelper::CombineStatsOfNonReorderableOperator(*op, children_stats);
313522 op->SetEstimatedCardinality(combined_stats.cardinality);
313523 if (!datasource_filters.empty()) {
313524 combined_stats.cardinality = (idx_t)MaxValue(
313525 double(combined_stats.cardinality) * RelationStatisticsHelper::DEFAULT_SELECTIVITY, (double)1);
313526 }
313527 AddRelation(input_op, parent, combined_stats);
313528 return true;
313529 }
313530
313531 switch (op->type) {
313532 case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: {
313533 // optimize children
313534 RelationStats child_stats;
313535 auto child_optimizer = optimizer.CreateChildOptimizer();
313536 op->children[0] = child_optimizer.Optimize(std::move(op->children[0]), &child_stats);
313537 auto &aggr = op->Cast<LogicalAggregate>();
313538 auto operator_stats = RelationStatisticsHelper::ExtractAggregationStats(aggr, child_stats);
313539 // the extracted cardinality should be set for aggregate
313540 aggr.SetEstimatedCardinality(operator_stats.cardinality);
313541 if (!datasource_filters.empty()) {
313542 operator_stats.cardinality = LossyNumericCast<idx_t>(static_cast<double>(operator_stats.cardinality) *
313543 RelationStatisticsHelper::DEFAULT_SELECTIVITY);
313544 }
313545 ModifyStatsIfLimit(limit_op.get(), child_stats);
313546 AddAggregateOrWindowRelation(input_op, parent, operator_stats, op->type);
313547 return true;
313548 }
313549 case LogicalOperatorType::LOGICAL_WINDOW: {
313550 // optimize children
313551 RelationStats child_stats;
313552 auto child_optimizer = optimizer.CreateChildOptimizer();
313553 op->children[0] = child_optimizer.Optimize(std::move(op->children[0]), &child_stats);
313554 auto &window = op->Cast<LogicalWindow>();
313555 auto operator_stats = RelationStatisticsHelper::ExtractWindowStats(window, child_stats);
313556 // the extracted cardinality should be set for window
313557 window.SetEstimatedCardinality(operator_stats.cardinality);
313558 if (!datasource_filters.empty()) {
313559 operator_stats.cardinality = LossyNumericCast<idx_t>(static_cast<double>(operator_stats.cardinality) *
313560 RelationStatisticsHelper::DEFAULT_SELECTIVITY);
313561 }
313562 ModifyStatsIfLimit(limit_op.get(), child_stats);
313563 AddAggregateOrWindowRelation(input_op, parent, operator_stats, op->type);
313564 return true;
313565 }
313566 case LogicalOperatorType::LOGICAL_UNNEST: {
313567 // optimize children of unnest
313568 RelationStats child_stats;
313569 AddRelationWithChildren(optimizer, *op, input_op, parent, child_stats, limit_op, datasource_filters);
313570 return true;
313571 }
313572 case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: {
313573 auto &join = op->Cast<LogicalComparisonJoin>();
313574 // Adding relations of the left side to the current join order optimizer
313575 bool can_reorder_left = ExtractJoinRelations(optimizer, *op->children[0], filter_operators, op);
313576 bool can_reorder_right = true;
313577 // For semi & anti joins, you only reorder relations in the left side of the join.
313578 // We do not want to reorder a relation A into the right side because then all column bindings A from A will be
313579 // lost after the semi or anti join
313580
313581 // We cannot reorder a relation B out of the right side because any filter/join in the right side
313582 // between a relation B and another RHS relation will be invalid. The semi join will remove
313583 // all right column bindings,
313584
313585 // So we treat the right side of left join as its own relation so no relations
313586 // are pushed into the right side, or taken out of the right side.
313587 if (join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI) {
313588 RelationStats child_stats;
313589 // optimize the child and copy the stats
313590 auto child_optimizer = optimizer.CreateChildOptimizer();
313591 op->children[1] = child_optimizer.Optimize(std::move(op->children[1]), &child_stats);
313592 AddRelation(*op->children[1], op, child_stats);
313593 // remember that if a cross product needs to be forced, it cannot be forced
313594 // across the children of a semi or anti join
313595 no_cross_product_relations.insert(relations.size() - 1);
313596 auto right_child_bindings = op->children[1]->GetColumnBindings();
313597 for (auto &bindings : right_child_bindings) {
313598 relation_mapping[bindings.table_index] = relations.size() - 1;
313599 }
313600 } else {
313601 can_reorder_right = ExtractJoinRelations(optimizer, *op->children[1], filter_operators, op);
313602 }
313603 return can_reorder_left && can_reorder_right;
313604 }
313605 case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: {
313606 bool can_reorder_left = ExtractJoinRelations(optimizer, *op->children[0], filter_operators, op);
313607 bool can_reorder_right = ExtractJoinRelations(optimizer, *op->children[1], filter_operators, op);
313608 return can_reorder_left && can_reorder_right;
313609 }
313610 case LogicalOperatorType::LOGICAL_DUMMY_SCAN: {
313611 auto &dummy_scan = op->Cast<LogicalDummyScan>();
313612 auto stats = RelationStatisticsHelper::ExtractDummyScanStats(dummy_scan, context);
313613 AddRelation(input_op, parent, stats);
313614 return true;
313615 }
313616 case LogicalOperatorType::LOGICAL_EXPRESSION_GET: {
313617 // base table scan, add to set of relations.
313618 // create empty stats for dummy scan or logical expression get
313619 auto &expression_get = op->Cast<LogicalExpressionGet>();
313620 auto stats = RelationStatisticsHelper::ExtractExpressionGetStats(expression_get, context);
313621 AddRelation(input_op, parent, stats);
313622 return true;
313623 }
313624 case LogicalOperatorType::LOGICAL_GET: {
313625 // TODO: Get stats from a logical GET
313626 auto &get = op->Cast<LogicalGet>();
313627 // this is a get that *most likely* has a function (like unnest or json_each).
313628 // there are new bindings for output of the function, but child bindings also exist, and can
313629 // be used in joins
313630 if (!op->children.empty()) {
313631 RelationStats child_stats;
313632 AddRelationWithChildren(optimizer, *op, input_op, parent, child_stats, limit_op, datasource_filters);
313633 return true;
313634 }
313635 auto stats = RelationStatisticsHelper::ExtractGetStats(get, context);
313636 // if there is another logical filter that could not be pushed down into the
313637 // table scan, apply another selectivity.
313638 get.SetEstimatedCardinality(stats.cardinality);
313639 if (!datasource_filters.empty()) {
313640 stats.cardinality =
313641 (idx_t)MaxValue(double(stats.cardinality) * RelationStatisticsHelper::DEFAULT_SELECTIVITY, (double)1);
313642 }
313643 ModifyStatsIfLimit(limit_op.get(), stats);
313644 AddRelation(input_op, parent, stats);
313645 return true;
313646 }
313647 case LogicalOperatorType::LOGICAL_PROJECTION: {
313648 RelationStats child_stats;
313649 // optimize the child and copy the stats
313650 auto child_optimizer = optimizer.CreateChildOptimizer();
313651 op->children[0] = child_optimizer.Optimize(std::move(op->children[0]), &child_stats);
313652 auto &proj = op->Cast<LogicalProjection>();
313653 // Projection can create columns so we need to add them here
313654 auto proj_stats = RelationStatisticsHelper::ExtractProjectionStats(proj, child_stats);
313655 proj.SetEstimatedCardinality(proj_stats.cardinality);
313656 ModifyStatsIfLimit(limit_op.get(), proj_stats);
313657 AddRelation(input_op, parent, proj_stats);
313658 return true;
313659 }
313660 case LogicalOperatorType::LOGICAL_EMPTY_RESULT: {
313661 // optimize the child and copy the stats
313662 auto &empty_result = op->Cast<LogicalEmptyResult>();
313663 // Projection can create columns so we need to add them here
313664 auto stats = RelationStatisticsHelper::ExtractEmptyResultStats(empty_result);
313665 empty_result.SetEstimatedCardinality(stats.cardinality);
313666 AddRelation(input_op, parent, stats);
313667 return true;
313668 }
313669 case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE:
313670 case LogicalOperatorType::LOGICAL_RECURSIVE_CTE: {
313671 RelationStats lhs_stats;
313672 // optimize the lhs child and copy the stats
313673 auto lhs_optimizer = optimizer.CreateChildOptimizer();
313674 op->children[0] = lhs_optimizer.Optimize(std::move(op->children[0]), &lhs_stats);
313675 // optimize the rhs child
313676 auto rhs_optimizer = optimizer.CreateChildOptimizer();
313677 auto table_index = op->Cast<LogicalCTE>().table_index;
313678
313679 auto child_1_card = lhs_stats.stats_initialized ? lhs_stats.cardinality : 0;
313680 rhs_optimizer.AddMaterializedCTEStats(table_index, std::move(lhs_stats));
313681 if (op->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) {
313682 rhs_optimizer.recursive_cte_indexes.insert(op->Cast<LogicalCTE>().table_index);
313683 }
313684 RelationStats rhs_stats;
313685 op->children[1] = rhs_optimizer.Optimize(std::move(op->children[1]), &rhs_stats);
313686
313687 // create the stats for the CTE
313688 auto child_2_card = rhs_stats.stats_initialized ? rhs_stats.cardinality : 0;
313689
313690 if (op->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) {
313691 // we cannot really estimate the cardinality of a recursive CTE
313692 // because we don't know how many times it will be executed
313693 // we just assume it will be executed 1000 times
313694 op->SetEstimatedCardinality(child_1_card + child_2_card * 1000);
313695 } else if (op->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) {
313696 // for a materialized CTE, we just take the cardinality of the right children
313697 op->SetEstimatedCardinality(child_2_card);
313698 }
313699
313700 return false;
313701 }
313702 case LogicalOperatorType::LOGICAL_CTE_REF: {
313703 auto &cte_ref = op->Cast<LogicalCTERef>();
313704 auto cte_stats = optimizer.GetMaterializedCTEStats(cte_ref.cte_index);
313705 cte_ref.SetEstimatedCardinality(cte_stats.cardinality);
313706 AddRelation(input_op, parent, cte_stats);
313707
313708 auto is_recursive = optimizer.recursive_cte_indexes.find(cte_ref.cte_index);
313709 if (is_recursive != optimizer.recursive_cte_indexes.end()) {
313710 return false;
313711 }
313712 return true;
313713 }
313714 case LogicalOperatorType::LOGICAL_DELIM_JOIN: {
313715 auto &delim_join = op->Cast<LogicalComparisonJoin>();
313716
313717 // optimize LHS (duplicate-eliminated) child
313718 RelationStats lhs_stats;
313719 auto lhs_optimizer = optimizer.CreateChildOptimizer();
313720 op->children[0] = lhs_optimizer.Optimize(std::move(op->children[0]), &lhs_stats);
313721
313722 // create dummy aggregation for the duplicate elimination
313723 auto dummy_aggr = make_uniq<LogicalAggregate>(DConstants::INVALID_INDEX - 1, DConstants::INVALID_INDEX,
313724 vector<unique_ptr<Expression>>());
313725 dummy_aggr->grouping_sets.emplace_back();
313726 for (auto &delim_col : delim_join.duplicate_eliminated_columns) {
313727 dummy_aggr->grouping_sets.back().insert(dummy_aggr->groups.size());
313728 dummy_aggr->groups.push_back(delim_col->Copy());
313729 }
313730 auto lhs_delim_stats = RelationStatisticsHelper::ExtractAggregationStats(*dummy_aggr, lhs_stats);
313731
313732 // optimize the other child, which will now have access to the stats
313733 RelationStats rhs_stats;
313734 auto rhs_optimizer = optimizer.CreateChildOptimizer();
313735 rhs_optimizer.AddDelimScanStats(lhs_delim_stats);
313736 op->children[1] = rhs_optimizer.Optimize(std::move(op->children[1]), rhs_stats);
313737
313738 RelationStats dj_stats;
313739 switch (delim_join.join_type) {
313740 case JoinType::LEFT:
313741 case JoinType::INNER:
313742 case JoinType::OUTER:
313743 case JoinType::SINGLE:
313744 case JoinType::MARK:
313745 case JoinType::SEMI:
313746 case JoinType::ANTI:
313747 dj_stats = lhs_stats;
313748 break;
313749 case JoinType::RIGHT:
313750 case JoinType::RIGHT_SEMI:
313751 case JoinType::RIGHT_ANTI:
313752 dj_stats = rhs_stats;
313753 break;
313754 default:
313755 throw NotImplementedException("Unsupported join type");
313756 }
313757
313758 if (delim_join.join_type == JoinType::SEMI || delim_join.join_type == JoinType::ANTI ||
313759 delim_join.join_type == JoinType::RIGHT_SEMI || delim_join.join_type == JoinType::RIGHT_ANTI) {
313760 dj_stats.cardinality =
313761 MaxValue<idx_t>(LossyNumericCast<idx_t>(static_cast<double>(dj_stats.cardinality) /
313762 CardinalityEstimator::DEFAULT_SEMI_ANTI_SELECTIVITY),
313763 1);
313764 }
313765
313766 AddAggregateOrWindowRelation(input_op, parent, dj_stats, op->type);
313767
313768 return false;
313769 }
313770 case LogicalOperatorType::LOGICAL_DELIM_GET: {
313771 // Used to not be possible to reorder these. We added reordering (without stats) before,
313772 // but ran into terrible join orders (see internal issue #596), so we removed it again
313773 // We now have proper statistics for DelimGets, and get an even better query plan for #596
313774 auto delim_scan_stats = optimizer.GetDelimScanStats();
313775 op->SetEstimatedCardinality(delim_scan_stats.cardinality);
313776 AddAggregateOrWindowRelation(input_op, parent, delim_scan_stats, op->type);
313777 return true;
313778 }
313779 default:
313780 return false;
313781 }
313782}
unordered_map< idx_t, idx_t > relation_mapping
A mapping of base table index -> index into relations array (relation number).
Definition duckdb.hpp:21645
void AddRelationWithChildren(JoinOrderOptimizer &optimizer, LogicalOperator &op, LogicalOperator &input_op, optional_ptr< LogicalOperator > parent, RelationStats &child_stats, optional_ptr< LogicalOperator > limit_op, vector< reference< LogicalOperator > > &datasource_filters)
Add an unnest relation which can come from a logical unnest or a logical get which has an unnest func...
Definition duckdb.cpp:313457
static RelationStats CombineStatsOfNonReorderableOperator(LogicalOperator &op, const vector< RelationStats > &child_stats)
Called after reordering a query plan with potentially 2+ relations.
Definition duckdb.cpp:314200
static RelationStats ExtractGetStats(LogicalGet &get, ClientContext &context)
Extract Statistics from a LogicalGet.
Definition duckdb.cpp:314035
static RelationStats ExtractDummyScanStats(LogicalDummyScan &dummy_scan, ClientContext &context)
Definition duckdb.cpp:314162
static RelationStats ExtractProjectionStats(LogicalProjection &proj, RelationStats &child_stats)
All relation extractors for blocking relations.
Definition duckdb.cpp:314132
__host__ cudaTextureObject_t get() const noexcept
cv::String join(const cv::String &base, const cv::String &path)
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
static constexpr const idx_t INVALID_INDEX
The value used to signify an invalid index entry.
Definition duckdb.hpp:1117

◆ ExtractEdges()

vector< unique_ptr< FilterInfo > > duckdb::RelationManager::ExtractEdges ( LogicalOperator & op,
vector< reference< LogicalOperator > > & filter_operators,
JoinRelationSetManager & set_manager )

for each join filter in the logical plan op, extract the relations that are referred to on both sides of the join filter, along with the tables & indexes.

313820 {
313821 // now that we know we are going to perform join ordering we actually extract the filters, eliminating duplicate
313822 // filters in the process
313823 vector<unique_ptr<FilterInfo>> filters_and_bindings;
313824 expression_set_t filter_set;
313825 for (auto &filter_op : filter_operators) {
313826 auto &f_op = filter_op.get();
313827 if (f_op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN ||
313828 f_op.type == LogicalOperatorType::LOGICAL_ASOF_JOIN) {
313829 auto &join = f_op.Cast<LogicalComparisonJoin>();
313830 D_ASSERT(join.expressions.empty());
313831 if (join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI) {
313832 auto conjunction_expression = make_uniq<BoundConjunctionExpression>(ExpressionType::CONJUNCTION_AND);
313833 // create a conjunction expression for the semi join.
313834 // It's possible multiple LHS relations have a condition in
313835 // this semi join. Suppose we have ((A ⨝ B) ⋉ C). (example in test_4950.test)
313836 // If the semi join condition has A.x = C.y AND B.x = C.z then we need to prevent a reordering
313837 // that looks like ((A ⋉ C) ⨝ B)), since all columns from C will be lost after it joins with A,
313838 // and the condition B.x = C.z will no longer be possible.
313839 // if we make a conjunction expressions and populate the left set and right set with all
313840 // the relations from the conditions in the conjunction expression, we can prevent invalid
313841 // reordering.
313842 for (auto &cond : join.conditions) {
313843 auto comparison = make_uniq<BoundComparisonExpression>(cond.comparison, std::move(cond.left),
313844 std::move(cond.right));
313845 conjunction_expression->children.push_back(std::move(comparison));
313846 }
313847
313848 // create the filter info so all required LHS relations are present when reconstructing the
313849 // join
313850 optional_ptr<JoinRelationSet> left_set;
313851 optional_ptr<JoinRelationSet> right_set;
313852 optional_ptr<JoinRelationSet> full_set;
313853 // here we create a left_set that unions all relations from the left side of
313854 // every expression and a right_set that unions all relations frmo the right side of a
313855 // every expression (although this should always be 1).
313856 for (auto &bound_expr : conjunction_expression->children) {
313857 D_ASSERT(bound_expr->GetExpressionClass() == ExpressionClass::BOUND_COMPARISON);
313858 auto &comp = bound_expr->Cast<BoundComparisonExpression>();
313859 unordered_set<idx_t> right_bindings, left_bindings;
313860 ExtractBindings(*comp.right, right_bindings);
313861 ExtractBindings(*comp.left, left_bindings);
313862
313863 if (!left_set) {
313864 left_set = set_manager.GetJoinRelation(left_bindings);
313865 } else {
313866 left_set = set_manager.Union(set_manager.GetJoinRelation(left_bindings), *left_set);
313867 }
313868 if (!right_set) {
313869 right_set = set_manager.GetJoinRelation(right_bindings);
313870 } else {
313871 right_set = set_manager.Union(set_manager.GetJoinRelation(right_bindings), *right_set);
313872 }
313873 }
313874 full_set = set_manager.Union(*left_set, *right_set);
313875 D_ASSERT(left_set && left_set->count > 0);
313876 D_ASSERT(right_set && right_set->count == 1);
313877 D_ASSERT(full_set && full_set->count > 0);
313878
313879 // now we push the conjunction expressions
313880 // In QueryGraphManager::GenerateJoins we extract each condition again and create a standalone join
313881 // condition.
313882 auto filter_info = make_uniq<FilterInfo>(std::move(conjunction_expression), *full_set,
313883 filters_and_bindings.size(), join.join_type);
313884 filter_info->SetLeftSet(left_set);
313885 filter_info->SetRightSet(right_set);
313886
313887 filters_and_bindings.push_back(std::move(filter_info));
313888 } else {
313889 // can extract every inner join condition individually.
313890 for (auto &cond : join.conditions) {
313891 auto comparison = make_uniq<BoundComparisonExpression>(cond.comparison, std::move(cond.left),
313892 std::move(cond.right));
313893 if (filter_set.find(*comparison) == filter_set.end()) {
313894 filter_set.insert(*comparison);
313895 unordered_set<idx_t> bindings;
313896 ExtractBindings(*comparison, bindings);
313897 auto &set = set_manager.GetJoinRelation(bindings);
313898 auto filter_info = make_uniq<FilterInfo>(std::move(comparison), set,
313899 filters_and_bindings.size(), join.join_type);
313900 filters_and_bindings.push_back(std::move(filter_info));
313901 }
313902 }
313903 }
313904 join.conditions.clear();
313905 } else {
313906 vector<unique_ptr<Expression>> leftover_expressions;
313907 for (auto &expression : f_op.expressions) {
313908 if (filter_set.find(*expression) == filter_set.end()) {
313909 filter_set.insert(*expression);
313910 unordered_set<idx_t> bindings;
313911 ExtractBindings(*expression, bindings);
313912 if (bindings.empty()) {
313913 // the filter is on a column that is not in our relational map. (example: limit_rownum)
313914 // in this case we do not create a FilterInfo for it. (duckdb-internal/#1493)s
313915 leftover_expressions.push_back(std::move(expression));
313916 continue;
313917 }
313918 auto &set = set_manager.GetJoinRelation(bindings);
313919 auto filter_info = make_uniq<FilterInfo>(std::move(expression), set, filters_and_bindings.size());
313920 filters_and_bindings.push_back(std::move(filter_info));
313921 }
313922 }
313923 f_op.expressions = std::move(leftover_expressions);
313924 }
313925 }
313926
313927 return filters_and_bindings;
313928}
bool ExtractBindings(Expression &expression, unordered_set< idx_t > &bindings)
Extract the set of relations referred to inside an expression.
Definition duckdb.cpp:313784
Here is the call graph for this function:

◆ ExtractBindings()

bool duckdb::RelationManager::ExtractBindings ( Expression & expression,
unordered_set< idx_t > & bindings )

Extract the set of relations referred to inside an expression.

313784 {
313785 if (expression.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) {
313786 auto &colref = expression.Cast<BoundColumnRefExpression>();
313787 D_ASSERT(colref.depth == 0);
313788 D_ASSERT(colref.binding.table_index != DConstants::INVALID_INDEX);
313789 // map the base table index to the relation index used by the JoinOrderOptimizer
313790 if (expression.GetAlias() == "SUBQUERY" &&
313791 relation_mapping.find(colref.binding.table_index) == relation_mapping.end()) {
313792 // most likely a BoundSubqueryExpression that was created from an uncorrelated subquery
313793 // Here we return true and don't fill the bindings, the expression can be reordered.
313794 // A filter will be created using this expression, and pushed back on top of the parent
313795 // operator during plan reconstruction
313796 return true;
313797 }
313798 if (relation_mapping.find(colref.binding.table_index) != relation_mapping.end()) {
313799 bindings.insert(relation_mapping[colref.binding.table_index]);
313800 }
313801 }
313802 if (expression.GetExpressionType() == ExpressionType::BOUND_REF) {
313803 // bound expression
313804 bindings.clear();
313805 return false;
313806 }
313807 D_ASSERT(expression.GetExpressionType() != ExpressionType::SUBQUERY);
313808 bool can_reorder = true;
313809 ExpressionIterator::EnumerateChildren(expression, [&](Expression &expr) {
313810 if (!ExtractBindings(expr, bindings)) {
313811 can_reorder = false;
313812 return;
313813 }
313814 });
313815 return can_reorder;
313816}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AddRelation()

void duckdb::RelationManager::AddRelation ( LogicalOperator & op,
optional_ptr< LogicalOperator > parent,
const RelationStats & stats )
313315 {
313316 // if parent is null, then this is a root relation
313317 // if parent is not null, it should have multiple children
313318 D_ASSERT(!parent || parent->children.size() >= 2);
313319 auto relation = make_uniq<SingleJoinRelation>(op, parent, stats);
313320 auto relation_id = relations.size();
313321
313322 auto table_indexes = op.GetTableIndex();
313323 bool is_mark = op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN &&
313324 op.Cast<LogicalComparisonJoin>().join_type == JoinType::MARK;
313325 bool get_all_child_bindings = op.type == LogicalOperatorType::LOGICAL_UNNEST;
313326 if (op.type == LogicalOperatorType::LOGICAL_GET) {
313327 get_all_child_bindings = !op.children.empty();
313328 }
313329 if (table_indexes.empty() || is_mark) {
313330 // relation represents a non-reorderable relation, most likely a join relation
313331 // Get the tables referenced in the non-reorderable relation and add them to the relation mapping
313332 // This should all table references, even if there are nested non-reorderable joins.
313333 unordered_set<idx_t> table_references;
313334 LogicalJoin::GetTableReferences(op, table_references);
313335 D_ASSERT(table_references.size() > 0);
313336 for (auto &reference : table_references) {
313337 D_ASSERT(relation_mapping.find(reference) == relation_mapping.end());
313338 relation_mapping[reference] = relation_id;
313339 }
313340 } else if (get_all_child_bindings) {
313341 // logical get has a logical_get index, but if a function is present other bindings can refer to
313342 // columns that are not unnested, and from the child of the logical get.
313343 auto bindings = op.GetColumnBindings();
313344 for (auto &binding : bindings) {
313345 relation_mapping[binding.table_index] = relation_id;
313346 }
313347 } else {
313348 // Relations should never return more than 1 table index
313349 D_ASSERT(table_indexes.size() == 1);
313350 idx_t table_index = table_indexes.at(0);
313351 D_ASSERT(relation_mapping.find(table_index) == relation_mapping.end());
313352 relation_mapping[table_index] = relation_id;
313353 }
313354 relations.push_back(std::move(relation));
313355 op.estimated_cardinality = stats.cardinality;
313356 op.has_estimated_cardinality = true;
313357}
static void GetTableReferences(LogicalOperator &op, unordered_set< idx_t > &bindings)
Gets the set of table references that are reachable from this node.
Definition duckdb.cpp:382702

◆ AddRelationWithChildren()

void duckdb::RelationManager::AddRelationWithChildren ( JoinOrderOptimizer & optimizer,
LogicalOperator & op,
LogicalOperator & input_op,
optional_ptr< LogicalOperator > parent,
RelationStats & child_stats,
optional_ptr< LogicalOperator > limit_op,
vector< reference< LogicalOperator > > & datasource_filters )

Add an unnest relation which can come from a logical unnest or a logical get which has an unnest function.

313460 {
313461 D_ASSERT(!op.children.empty());
313462 auto child_optimizer = optimizer.CreateChildOptimizer();
313463 op.children[0] = child_optimizer.Optimize(std::move(op.children[0]), &child_stats);
313464 if (!datasource_filters.empty()) {
313465 child_stats.cardinality = LossyNumericCast<idx_t>(static_cast<double>(child_stats.cardinality) *
313466 RelationStatisticsHelper::DEFAULT_SELECTIVITY);
313467 }
313468 ModifyStatsIfLimit(limit_op.get(), child_stats);
313469 AddRelation(input_op, parent, child_stats);
313470}

◆ AddAggregateOrWindowRelation()

void duckdb::RelationManager::AddAggregateOrWindowRelation ( LogicalOperator & op,
optional_ptr< LogicalOperator > parent,
const RelationStats & stats,
LogicalOperatorType op_type )
313299 {
313300 auto relation = make_uniq<SingleJoinRelation>(op, parent, stats);
313301 auto relation_id = relations.size();
313302
313303 auto op_bindings = op.GetColumnBindings();
313304 for (auto &binding : op_bindings) {
313305 if (relation_mapping.find(binding.table_index) == relation_mapping.end()) {
313306 relation_mapping[binding.table_index] = relation_id;
313307 }
313308 }
313309 relations.push_back(std::move(relation));
313310 op.estimated_cardinality = stats.cardinality;
313311 op.has_estimated_cardinality = true;
313312}

◆ GetRelations()

vector< unique_ptr< SingleJoinRelation > > duckdb::RelationManager::GetRelations ( )
313290 {
313291 return std::move(relations);
313292}

◆ GetRelationStats()

const vector< RelationStats > duckdb::RelationManager::GetRelationStats ( )
313282 {
313283 vector<RelationStats> ret;
313284 for (idx_t i = 0; i < relations.size(); i++) {
313285 ret.push_back(relations[i]->stats);
313286 }
313287 return ret;
313288}

◆ CrossProductWithRelationAllowed()

bool duckdb::RelationManager::CrossProductWithRelationAllowed ( idx_t relation_id)
313359 {
313360 return no_cross_product_relations.find(relation_id) == no_cross_product_relations.end();
313361}

◆ PrintRelationStats()

void duckdb::RelationManager::PrintRelationStats ( )
313932 {
313933#ifdef DEBUG
313934 string to_print;
313935 for (idx_t i = 0; i < relations.size(); i++) {
313936 auto &relation = relations.at(i);
313937 auto &stats = relation->stats;
313938 D_ASSERT(stats.column_names.size() == stats.column_distinct_count.size());
313939 for (idx_t i = 0; i < stats.column_names.size(); i++) {
313940 to_print = stats.column_names.at(i) + " has estimated distinct count " +
313941 to_string(stats.column_distinct_count.at(i).distinct_count);
313942 Printer::Print(to_print);
313943 }
313944 to_print = stats.table_name + " has estimated cardinality " + to_string(stats.cardinality);
313945 to_print += " and relation id " + to_string(i) + "\n";
313946 Printer::Print(to_print);
313947 }
313948#endif
313949}
static DUCKDB_API void Print(OutputStream stream, const string &str)
Print the object to the stream.
Definition duckdb.cpp:92556
std::string to_string(const T &value)
Definition duckdb.cpp:19425

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