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::FlattenDependentJoins Struct Reference
Collaboration diagram for duckdb::FlattenDependentJoins:

Public Member Functions

 FlattenDependentJoins (Binder &binder, const CorrelatedColumns &correlated, bool perform_delim=true, bool any_join=false, optional_ptr< FlattenDependentJoins > parent=nullptr)
unique_ptr< LogicalOperator > Decorrelate (unique_ptr< LogicalOperator > plan, bool parent_propagate_null_values=true, idx_t lateral_depth=0)

Static Public Member Functions

static unique_ptr< LogicalOperator > DecorrelateIndependent (Binder &binder, unique_ptr< LogicalOperator > plan)

Public Attributes

Binder & binder
ColumnBinding base_binding
idx_t delim_offset
idx_t data_offset
reference_map_t< LogicalOperator, bool > has_correlated_expressions
column_binding_map_t< idx_t > correlated_map
column_binding_map_t< idx_t > replacement_map
const CorrelatedColumns & correlated_columns
vector< LogicalType > delim_types
bool perform_delim
bool any_join
optional_ptr< FlattenDependentJoins > parent

Private Member Functions

bool DetectCorrelatedExpressions (LogicalOperator &op, bool lateral=false, idx_t lateral_depth=0, bool parent_is_dependent_join=false)
bool MarkSubtreeCorrelated (LogicalOperator &op, idx_t cte_index)
 Mark entire subtree of Logical Operators as correlated by adding them to the has_correlated_expressions map.
unique_ptr< LogicalOperator > PushDownDependentJoin (unique_ptr< LogicalOperator > plan, bool propagates_null_values=true, idx_t lateral_depth=0)
 Push the dependent join down a LogicalOperator.
unique_ptr< LogicalOperator > PushDownDependentJoinInternal (unique_ptr< LogicalOperator > plan, bool &parent_propagate_null_values, idx_t lateral_depth)

Detailed Description

The FlattenDependentJoins class is responsible for pushing the dependent join down into the plan to create a flattened subquery

Constructor & Destructor Documentation

◆ FlattenDependentJoins()

duckdb::FlattenDependentJoins::FlattenDependentJoins ( Binder & binder,
const CorrelatedColumns & correlated,
bool perform_delim = true,
bool any_join = false,
optional_ptr< FlattenDependentJoins > parent = nullptr )
384074 : binder(binder), delim_offset(DConstants::INVALID_INDEX), correlated_columns(correlated),
384075 perform_delim(perform_delim), any_join(any_join), parent(parent) {
384076 for (idx_t i = 0; i < correlated_columns.size(); i++) {
384077 auto &col = correlated_columns[i];
384078 correlated_map[col.binding] = i;
384079 delim_types.push_back(col.type);
384080 }
384081}
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

Member Function Documentation

◆ DecorrelateIndependent()

unique_ptr< LogicalOperator > duckdb::FlattenDependentJoins::DecorrelateIndependent ( Binder & binder,
unique_ptr< LogicalOperator > plan )
static
384110 {
384111 CorrelatedColumns correlated;
384112 FlattenDependentJoins flatten(binder, correlated);
384113 return flatten.Decorrelate(std::move(plan));
384114}

◆ Decorrelate()

unique_ptr< LogicalOperator > duckdb::FlattenDependentJoins::Decorrelate ( unique_ptr< LogicalOperator > plan,
bool parent_propagate_null_values = true,
idx_t lateral_depth = 0 )
384117 {
384118 switch (plan->type) {
384119 case LogicalOperatorType::LOGICAL_DEPENDENT_JOIN: {
384120 auto &delim_join = plan;
384121 auto &op = plan->Cast<LogicalDependentJoin>();
384122
384123 // If we have a parent, we unnest the left side of the DEPENDENT JOIN in the parent's context.
384124 if (parent) {
384125 // only push the dependent join to the left side, if there is correlation.
384126 auto entry = has_correlated_expressions.find(*plan);
384127 D_ASSERT(entry != has_correlated_expressions.end());
384128
384129 if (entry->second) {
384130 op.children[0] =
384131 PushDownDependentJoin(std::move(op.children[0]), parent_propagate_null_values, lateral_depth);
384132 } else {
384133 // There might be unrelated correlation, so we have to traverse the tree
384134 op.children[0] = DecorrelateIndependent(binder, std::move(op.children[0]));
384135 }
384136
384137 // we are now done with the left side, mark it as uncorrelated
384138 entry->second = false;
384139
384140 // rewrite
384141 idx_t next_lateral_depth = 0;
384142
384143 RewriteCorrelatedExpressions rewriter(base_binding, correlated_map, next_lateral_depth);
384144 rewriter.VisitOperator(*plan);
384145
384146 RewriteCorrelatedExpressions recursive_rewriter(base_binding, correlated_map, next_lateral_depth, true);
384147 recursive_rewriter.VisitOperator(*plan);
384148 } else {
384149 op.children[0] = Decorrelate(std::move(op.children[0]));
384150 }
384151
384152 if (!op.perform_delim) {
384153 // if we are not performing a delim join, we push a row_number() OVER() window operator on the LHS
384154 // and perform all duplicate elimination on that row number instead
384155 const auto &op_col = op.correlated_columns[op.correlated_columns.GetDelimIndex()];
384156 auto window = make_uniq<LogicalWindow>(op_col.binding.table_index);
384157 auto row_number = make_uniq<BoundWindowExpression>(ExpressionType::WINDOW_ROW_NUMBER, LogicalType::BIGINT,
384158 nullptr, nullptr);
384159 row_number->start = WindowBoundary::UNBOUNDED_PRECEDING;
384160 row_number->end = WindowBoundary::CURRENT_ROW_ROWS;
384161 row_number->SetAlias("delim_index");
384162 window->expressions.push_back(std::move(row_number));
384163 window->AddChild(std::move(op.children[0]));
384164 op.children[0] = std::move(window);
384165 }
384166
384167 lateral_depth = 0;
384168 bool propagate_null_values = op.propagate_null_values;
384169 FlattenDependentJoins flatten(binder, op.correlated_columns, op.perform_delim, op.any_join, this);
384170
384171 // first we check which logical operators have correlated expressions in the first place
384172 flatten.DetectCorrelatedExpressions(*delim_join->children[1], op.is_lateral_join, lateral_depth);
384173
384174 if (delim_join->children[1]->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) {
384175 auto &cte_ref = delim_join->children[1]->Cast<LogicalMaterializedCTE>();
384176 // check if the left side of the CTE has correlated expressions
384177 auto entry = flatten.has_correlated_expressions.find(*cte_ref.children[0]);
384178 if (entry != flatten.has_correlated_expressions.end()) {
384179 if (!entry->second) {
384180 // the left side of the CTE has no correlated expressions, we can push the DEPENDENT_JOIN down
384181 auto cte = std::move(delim_join->children[1]);
384182 delim_join->children[1] = std::move(cte->children[1]);
384183 cte->children[1] = Decorrelate(std::move(delim_join), parent_propagate_null_values, lateral_depth);
384184 return cte;
384185 }
384186 }
384187 }
384188
384189 // now we push the dependent join down
384190 delim_join->children[1] =
384191 flatten.PushDownDependentJoin(std::move(delim_join->children[1]), propagate_null_values, lateral_depth);
384192 data_offset = flatten.data_offset;
384193 const auto left_offset = delim_join->children[0]->GetColumnBindings().size();
384194 if (!parent) {
384195 delim_offset = left_offset + flatten.delim_offset;
384196 }
384197
384198 RewriteCorrelatedExpressions rewriter(base_binding, correlated_map, lateral_depth);
384199 rewriter.VisitOperator(*plan);
384200
384201 op.duplicate_eliminated_columns.clear();
384202 op.mark_types.clear();
384203 for (idx_t i = 0; i < op.correlated_columns.size(); i++) {
384204 auto &col = op.correlated_columns[i];
384205 op.duplicate_eliminated_columns.push_back(make_uniq<BoundColumnRefExpression>(col.type, col.binding));
384206 op.mark_types.push_back(col.type);
384207 }
384208
384209 // We are done using the operator as a DEPENDENT JOIN, it is now fully decorrelated,
384210 // and we change the type to a DELIM JOIN.
384211 delim_join->type = LogicalOperatorType::LOGICAL_DELIM_JOIN;
384212
384213 auto plan_columns = delim_join->children[1]->GetColumnBindings();
384214
384215 // Handle lateral joins
384216 if (op.is_lateral_join && op.subquery_type == SubqueryType::INVALID) {
384217 // in case of a materialized CTE, the output is defined by the second children operator
384218 if (delim_join->children[1]->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) {
384219 plan_columns = delim_join->children[1]->children[1]->GetColumnBindings();
384220 }
384221
384222 // then add the delim join conditions
384223 CreateDelimJoinConditions(op, op.correlated_columns, plan_columns, flatten.delim_offset, op.perform_delim);
384224
384225 // check if there are any arbitrary expressions left
384226 if (!op.arbitrary_expressions.empty()) {
384227 // we can only evaluate scalar arbitrary expressions for inner joins
384228 if (op.join_type != JoinType::INNER) {
384229 throw BinderException("Join condition for non-inner LATERAL JOIN must be a comparison between the "
384230 "left and right side");
384231 }
384232 auto filter = make_uniq<LogicalFilter>();
384233 filter->expressions = std::move(op.arbitrary_expressions);
384234 filter->AddChild(std::move(plan));
384235 return std::move(filter);
384236 }
384237 return plan;
384238 }
384239
384240 CreateDelimJoinConditions(op, op.correlated_columns, plan_columns, flatten.delim_offset, op.perform_delim);
384241
384242 if (op.subquery_type == SubqueryType::ANY) {
384243 // add the actual condition based on the ANY/ALL predicate
384244 for (idx_t child_idx = 0; child_idx < op.expression_children.size(); child_idx++) {
384245 JoinCondition compare_cond;
384246 compare_cond.left = std::move(op.expression_children[child_idx]);
384247 auto &child_type = op.child_types[child_idx];
384248 auto &compare_type = op.child_targets[child_idx];
384249 compare_cond.right = BoundCastExpression::AddDefaultCastToType(
384250 make_uniq<BoundColumnRefExpression>(child_type, plan_columns[child_idx]),
384251 op.child_targets[child_idx]);
384252 compare_cond.comparison = op.comparison_type;
384253
384254 // push collations
384255 ExpressionBinder::PushCollation(binder.context, compare_cond.left, compare_type);
384256 ExpressionBinder::PushCollation(binder.context, compare_cond.right, compare_type);
384257 op.conditions.push_back(std::move(compare_cond));
384258 }
384259 }
384260
384261 return plan;
384262 }
384263 default: {
384264 for (auto &child : plan->children) {
384265 child = Decorrelate(std::move(child));
384266 }
384267 }
384268 }
384269
384270 return plan;
384271}
static unique_ptr< Expression > AddDefaultCastToType(unique_ptr< Expression > expr, const LogicalType &target_type, bool try_cast=false)
Cast an expression to the specified SQL type, using only the built-in SQL casts.
Definition duckdb.cpp:375861
void filter(InputArray image, InputArray kernel, OutputArray output)
unique_ptr< LogicalOperator > PushDownDependentJoin(unique_ptr< LogicalOperator > plan, bool propagates_null_values=true, idx_t lateral_depth=0)
Push the dependent join down a LogicalOperator.
Definition duckdb.cpp:384385

◆ DetectCorrelatedExpressions()

bool duckdb::FlattenDependentJoins::DetectCorrelatedExpressions ( LogicalOperator & op,
bool lateral = false,
idx_t lateral_depth = 0,
bool parent_is_dependent_join = false )
private

Detects which Logical Operators have correlated expressions that they are dependent upon, filling the has_correlated_expressions map.

384274 {
384275 bool is_lateral_join = false;
384276
384277 // check if this entry has correlated expressions
384278 if (op.type == LogicalOperatorType::LOGICAL_DEPENDENT_JOIN) {
384279 is_lateral_join = true;
384280 }
384281 HasCorrelatedExpressions visitor(correlated_columns, lateral, lateral_depth);
384282 visitor.VisitOperator(op);
384283 bool has_correlation = visitor.has_correlated_expressions;
384284 int child_idx = 0;
384285 // now visit the children of this entry and check if they have correlated expressions
384286 for (auto &child : op.children) {
384287 auto new_lateral_depth = lateral_depth;
384288 if (is_lateral_join && child_idx == 1) {
384289 new_lateral_depth = lateral_depth + 1;
384290 }
384291 // we OR the property with its children such that has_correlation is true if either
384292 // (1) this node has a correlated expression or
384293 // (2) one of its children has a correlated expression
384294 bool condition = (parent_is_dependent_join || is_lateral_join) && child_idx == 0;
384295 if (DetectCorrelatedExpressions(*child, lateral, new_lateral_depth, condition)) {
384296 has_correlation = true;
384297 }
384298
384299 if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE && child_idx == 0) {
384300 auto &setop = op.Cast<LogicalCTE>();
384301 binder.recursive_ctes[setop.table_index] = &setop;
384302 has_correlated_expressions[op] = has_correlation;
384303 if (has_correlation) {
384304 setop.correlated_columns = correlated_columns;
384305 }
384306 }
384307
384308 child_idx++;
384309 }
384310
384311 // We found a CTE reference
384312 if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) {
384313 // Check, if the operator already has an entry in has_correlated_expressions.
384314 // This would only be the case, if we hit MarkSubtreeCorrelated previously.
384315 auto entry = has_correlated_expressions.find(op);
384316
384317 if (entry == has_correlated_expressions.end()) {
384318 // Try to find a recursive CTE for this operator
384319 auto &cteref = op.Cast<LogicalCTERef>();
384320 auto cte = binder.recursive_ctes.find(cteref.cte_index);
384321
384322 has_correlated_expressions[op] = false; // Default: not correlated
384323
384324 // recursive_ctes may be a misnomer at this point, as it may also contain materialized CTEs
384325 if (cte != binder.recursive_ctes.end()) {
384326 auto cte_node = cte->second;
384327
384328 if (cte_node->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) {
384329 // Found a recursive CTE, subtree is correlated
384330 return true;
384331 }
384332 // Found a materialized CTE, subtree correlation depends on the CTE node
384333 has_correlated_expressions[op] = has_correlated_expressions[*cte_node];
384334 return has_correlated_expressions[*cte_node];
384335 }
384336 // No CTE found: subtree is correlated
384337 return true;
384338 }
384339 }
384340
384341 // set the entry in the map
384342 has_correlated_expressions[op] = has_correlation;
384343
384344 // If we detect correlation in a materialized or recursive CTE, the entire right side of the operator
384345 // needs to be marked as correlated. Otherwise, function PushDownDependentJoinInternal does not do the
384346 // right thing.
384347 if (op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) {
384348 auto &setop = op.Cast<LogicalCTE>();
384349 binder.recursive_ctes[setop.table_index] = &setop;
384350 if (has_correlation) {
384351 setop.correlated_columns = correlated_columns;
384352 MarkSubtreeCorrelated(*op.children[1].get(), setop.table_index);
384353 }
384354 }
384355
384356 return has_correlation;
384357}
bool MarkSubtreeCorrelated(LogicalOperator &op, idx_t cte_index)
Mark entire subtree of Logical Operators as correlated by adding them to the has_correlated_expressio...
Definition duckdb.cpp:384359
bool DetectCorrelatedExpressions(LogicalOperator &op, bool lateral=false, idx_t lateral_depth=0, bool parent_is_dependent_join=false)
Definition duckdb.cpp:384273
Here is the call graph for this function:
Here is the caller graph for this function:

◆ MarkSubtreeCorrelated()

bool duckdb::FlattenDependentJoins::MarkSubtreeCorrelated ( LogicalOperator & op,
idx_t cte_index )
private

Mark entire subtree of Logical Operators as correlated by adding them to the has_correlated_expressions map.

384359 {
384360 // Do not mark base table scans as correlated
384361 auto entry = has_correlated_expressions.find(op);
384362 D_ASSERT(entry != has_correlated_expressions.end());
384363 bool has_correlation = entry->second;
384364 for (auto &child : op.children) {
384365 has_correlation |= MarkSubtreeCorrelated(*child.get(), cte_index);
384366 }
384367 if (op.type != LogicalOperatorType::LOGICAL_GET || op.children.size() == 1) {
384368 if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) {
384369 // There may be multiple recursive CTEs. Only mark CTE_REFs as correlated,
384370 // IFF the CTE that we are reading from is correlated.
384371 auto &cteref = op.Cast<LogicalCTERef>();
384372 if (cteref.cte_index != cte_index) {
384373 has_correlated_expressions[op] = has_correlation;
384374 return has_correlation;
384375 }
384376 has_correlated_expressions[op] = true;
384377 return true;
384378 } else {
384379 has_correlated_expressions[op] = has_correlation;
384380 }
384381 }
384382 return has_correlation;
384383}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PushDownDependentJoin()

unique_ptr< LogicalOperator > duckdb::FlattenDependentJoins::PushDownDependentJoin ( unique_ptr< LogicalOperator > plan,
bool propagates_null_values = true,
idx_t lateral_depth = 0 )
private

Push the dependent join down a LogicalOperator.

384387 {
384388 auto result = PushDownDependentJoinInternal(std::move(plan), propagate_null_values, lateral_depth);
384389 if (!replacement_map.empty()) {
384390 // check if we have to replace any COUNT aggregates into "CASE WHEN X IS NULL THEN 0 ELSE COUNT END"
384391 RewriteCountAggregates aggr(replacement_map);
384392 aggr.VisitOperator(*result);
384393 }
384394 return result;
384395}

◆ PushDownDependentJoinInternal()

unique_ptr< LogicalOperator > duckdb::FlattenDependentJoins::PushDownDependentJoinInternal ( unique_ptr< LogicalOperator > plan,
bool & parent_propagate_null_values,
idx_t lateral_depth )
private
384415 {
384416 // first check if the logical operator has correlated expressions
384417 auto entry = has_correlated_expressions.find(*plan);
384418 bool exit_projection = false;
384419 unique_ptr<LogicalDelimGet> delim_scan;
384420 D_ASSERT(entry != has_correlated_expressions.end());
384421 if (!entry->second) {
384422 // we reached a node without correlated expressions
384423 // we can eliminate the dependent join now and create a simple cross product
384424 // now create the duplicate eliminated scan for this node
384425 if (plan->type == LogicalOperatorType::LOGICAL_CTE_REF) {
384426 auto &op = plan->Cast<LogicalCTERef>();
384427
384428 auto rec_cte = binder.recursive_ctes.find(op.cte_index);
384429 if (rec_cte != binder.recursive_ctes.end()) {
384430 D_ASSERT(rec_cte->second->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE ||
384431 rec_cte->second->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE);
384432
384433 auto &rec_cte_op = rec_cte->second->Cast<LogicalCTE>();
384434 if (op.correlated_columns == 0) {
384435 RewriteCTEScan cte_rewriter(op.cte_index, rec_cte_op.correlated_columns,
384437 cte_rewriter.VisitOperator(*plan);
384438 }
384439 }
384440 }
384441
384442 // create cross product with Delim Join
384443 auto delim_index = binder.GenerateTableIndex();
384444 base_binding = ColumnBinding(delim_index, 0);
384445
384446 auto left_columns = plan->GetColumnBindings().size();
384447 delim_offset = left_columns;
384448 data_offset = 0;
384449 delim_scan = make_uniq<LogicalDelimGet>(delim_index, delim_types);
384450 if (plan->type == LogicalOperatorType::LOGICAL_PROJECTION) {
384451 // we want to keep the logical projection for positionality.
384452 exit_projection = true;
384453 } else if (plan->type == LogicalOperatorType::LOGICAL_CTE_REF) {
384454 // Should a reference to a CTE be the final non-recursive operator,
384455 // we have to add a filter predicate to ensure column equality between
384456 // the left and right side of the join. A simple cross product does not
384457 // suffice in this case.
384458 auto &cteref = plan->Cast<LogicalCTERef>();
384459 auto join = make_uniq<LogicalComparisonJoin>(JoinType::INNER);
384460 auto left_binding =
384461 ColumnBinding(cteref.table_index, cteref.chunk_types.size() - cteref.correlated_columns);
384462 // add the correlated columns to the join conditions
384463 for (idx_t i = 0; i < cteref.correlated_columns; i++) {
384464 JoinCondition cond;
384465 cond.left = make_uniq<BoundColumnRefExpression>(
384466 correlated_columns[i].type, ColumnBinding(left_binding.table_index, left_binding.column_index + i));
384467 cond.right = make_uniq<BoundColumnRefExpression>(
384468 correlated_columns[i].type, ColumnBinding(base_binding.table_index, base_binding.column_index + i));
384469 cond.comparison = ExpressionType::COMPARE_NOT_DISTINCT_FROM;
384470 join->conditions.push_back(std::move(cond));
384471 }
384472 join->children.push_back(std::move(plan));
384473 join->children.push_back(std::move(delim_scan));
384474
384475 return std::move(join);
384476 } else {
384477 auto cross_product = LogicalCrossProduct::Create(Decorrelate(std::move(plan)), std::move(delim_scan));
384478 return cross_product;
384479 }
384480 }
384481 switch (plan->type) {
384482 case LogicalOperatorType::LOGICAL_UNNEST:
384483 case LogicalOperatorType::LOGICAL_FILTER: {
384484 // filter
384485 // first we flatten the dependent join in the child of the filter
384486 for (auto &expr : plan->expressions) {
384487 any_join |= SubqueryDependentFilter(*expr);
384488 }
384489 plan->children[0] =
384490 PushDownDependentJoinInternal(std::move(plan->children[0]), parent_propagate_null_values, lateral_depth);
384491
384492 // then we replace any correlated expressions with the corresponding entry in the correlated_map
384493 RewriteCorrelatedExpressions rewriter(base_binding, correlated_map, lateral_depth);
384494 rewriter.VisitOperator(*plan);
384495 return plan;
384496 }
384497 case LogicalOperatorType::LOGICAL_PROJECTION: {
384498 // projection
384499 // first we flatten the dependent join in the child of the projection
384500 for (auto &expr : plan->expressions) {
384501 parent_propagate_null_values &= expr->PropagatesNullValues();
384502 }
384503
384504 // If our immediate children is a DEPENDENT JOIN, the projection expressions did contain
384505 // a subquery expression previously—Which does not propagate null values.
384506 // We have to account for that.
384507 bool child_is_dependent_join = plan->children[0]->type == LogicalOperatorType::LOGICAL_DEPENDENT_JOIN;
384508 parent_propagate_null_values &= !child_is_dependent_join;
384509
384510 // if the node has no correlated expressions,
384511 // push the cross product with the delim get only below the projection.
384512 // This will preserve positionality of the columns and prevent errors when reordering of
384513 // delim gets is enabled.
384514 if (exit_projection) {
384515 auto cross_product =
384516 LogicalCrossProduct::Create(Decorrelate(std::move(plan->children[0])), std::move(delim_scan));
384517 plan->children[0] = std::move(cross_product);
384518 } else {
384519 plan->children[0] = PushDownDependentJoinInternal(std::move(plan->children[0]),
384520 parent_propagate_null_values, lateral_depth);
384521 }
384522
384523 // then we replace any correlated expressions with the corresponding entry in the correlated_map
384524 RewriteCorrelatedExpressions rewriter(base_binding, correlated_map, lateral_depth);
384525 rewriter.VisitOperator(*plan);
384526 // now we add all the columns of the delim_scan to the projection list
384527 auto &proj = plan->Cast<LogicalProjection>();
384528 for (idx_t i = 0; i < correlated_columns.size(); i++) {
384529 auto &col = correlated_columns[i];
384530 auto colref = make_uniq<BoundColumnRefExpression>(
384531 col.name, col.type, ColumnBinding(base_binding.table_index, base_binding.column_index + i));
384532 plan->expressions.push_back(std::move(colref));
384533 }
384534
384535 base_binding.table_index = proj.table_index;
384536 base_binding.column_index = plan->expressions.size() - correlated_columns.size();
384537 this->delim_offset = base_binding.column_index;
384538 this->data_offset = 0;
384539 return plan;
384540 }
384541 case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: {
384542 auto &aggr = plan->Cast<LogicalAggregate>();
384543 // aggregate and group by
384544 // first we flatten the dependent join in the child of the projection
384545 for (auto &expr : plan->expressions) {
384546 parent_propagate_null_values &= expr->PropagatesNullValues();
384547 }
384548 plan->children[0] =
384549 PushDownDependentJoinInternal(std::move(plan->children[0]), parent_propagate_null_values, lateral_depth);
384550 // then we replace any correlated expressions with the corresponding entry in the correlated_map
384551 RewriteCorrelatedExpressions rewriter(base_binding, correlated_map, lateral_depth);
384552 rewriter.VisitOperator(*plan);
384553 // now we add all the columns of the delim_scan to the grouping operators AND the projection list
384554 idx_t delim_table_index;
384555 idx_t delim_column_offset;
384556 idx_t delim_data_offset;
384557 auto new_group_count = perform_delim ? correlated_columns.size() : 1;
384558 for (idx_t i = 0; i < new_group_count; i++) {
384559 auto &col = correlated_columns[i];
384560 auto colref = make_uniq<BoundColumnRefExpression>(
384561 col.name, col.type, ColumnBinding(base_binding.table_index, base_binding.column_index + i));
384562 for (auto &set : aggr.grouping_sets) {
384563 set.insert(aggr.groups.size());
384564 }
384565 aggr.groups.push_back(std::move(colref));
384566 }
384567 if (!perform_delim) {
384568 // if we are not performing the duplicate elimination, we have only added the row_id column to the grouping
384569 // operators in this case, we push a FIRST aggregate for each of the remaining expressions
384570 delim_table_index = aggr.aggregate_index;
384571 delim_column_offset = aggr.expressions.size();
384572 delim_data_offset = aggr.groups.size();
384573 for (idx_t i = 0; i < correlated_columns.size(); i++) {
384574 auto &col = correlated_columns[i];
384575 auto first_aggregate = FirstFunctionGetter::GetFunction(col.type);
384576 auto colref = make_uniq<BoundColumnRefExpression>(
384577 col.name, col.type, ColumnBinding(base_binding.table_index, base_binding.column_index + i));
384578 vector<unique_ptr<Expression>> aggr_children;
384579 aggr_children.push_back(std::move(colref));
384580 auto first_fun =
384581 make_uniq<BoundAggregateExpression>(std::move(first_aggregate), std::move(aggr_children), nullptr,
384582 nullptr, AggregateType::NON_DISTINCT);
384583 aggr.expressions.push_back(std::move(first_fun));
384584 }
384585 } else {
384586 delim_table_index = aggr.group_index;
384587 delim_column_offset = aggr.groups.size() - correlated_columns.size();
384588 delim_data_offset = aggr.groups.size();
384589 }
384590 bool ungrouped_join = false;
384591 if (aggr.grouping_sets.empty()) {
384592 ungrouped_join = aggr.groups.size() == new_group_count;
384593 } else {
384594 for (auto &grouping_set : aggr.grouping_sets) {
384595 if (grouping_set.size() == new_group_count) {
384596 ungrouped_join = true;
384597 }
384598 }
384599 }
384600 if (ungrouped_join) {
384601 // we have to perform an INNER or LEFT OUTER JOIN between the result of this aggregate and the delim scan
384602 // this does not always have to be a LEFT OUTER JOIN, depending on whether aggr.expressions return
384603 // NULL or a value
384604 JoinType join_type = JoinType::INNER;
384605 if (any_join || !parent_propagate_null_values) {
384606 join_type = JoinType::LEFT;
384607 }
384608 for (auto &aggr_exp : aggr.expressions) {
384609 auto &b_aggr_exp = aggr_exp->Cast<BoundAggregateExpression>();
384610 if (!b_aggr_exp.PropagatesNullValues()) {
384611 join_type = JoinType::LEFT;
384612 break;
384613 }
384614 }
384615 unique_ptr<LogicalComparisonJoin> join = make_uniq<LogicalComparisonJoin>(join_type);
384616 auto left_index = binder.GenerateTableIndex();
384617 delim_scan = make_uniq<LogicalDelimGet>(left_index, delim_types);
384618 join->children.push_back(std::move(delim_scan));
384619 join->children.push_back(std::move(plan));
384620 for (idx_t i = 0; i < new_group_count; i++) {
384621 auto &col = correlated_columns[i];
384622 JoinCondition cond;
384623 cond.left = make_uniq<BoundColumnRefExpression>(col.name, col.type, ColumnBinding(left_index, i));
384624 cond.right = make_uniq<BoundColumnRefExpression>(
384625 correlated_columns[i].type, ColumnBinding(delim_table_index, delim_column_offset + i));
384626 cond.comparison = ExpressionType::COMPARE_NOT_DISTINCT_FROM;
384627 join->conditions.push_back(std::move(cond));
384628 }
384629 // for any COUNT aggregate we replace references to the column with: CASE WHEN COUNT(*) IS NULL THEN 0
384630 // ELSE COUNT(*) END
384631 for (idx_t i = 0; i < aggr.expressions.size(); i++) {
384632 D_ASSERT(aggr.expressions[i]->GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE);
384633 auto &bound = aggr.expressions[i]->Cast<BoundAggregateExpression>();
384634 vector<LogicalType> arguments;
384635 if (bound.function == CountFunctionBase::GetFunction() ||
384636 bound.function == CountStarFun::GetFunction()) {
384637 // have to replace this ColumnBinding with the CASE expression
384638 replacement_map[ColumnBinding(aggr.aggregate_index, i)] = i;
384639 }
384640 }
384641 // now we update the delim_index
384642 base_binding.table_index = left_index;
384643 this->delim_offset = base_binding.column_index = 0;
384644 this->data_offset = 0;
384645 return std::move(join);
384646 } else {
384647 // update the delim_index
384648 base_binding.table_index = delim_table_index;
384649 this->delim_offset = base_binding.column_index = delim_column_offset;
384650 this->data_offset = delim_data_offset;
384651 return plan;
384652 }
384653 }
384654 case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: {
384655 // cross product
384656 // push into both sides of the plan
384657 bool left_has_correlation = has_correlated_expressions.find(*plan->children[0])->second;
384658 bool right_has_correlation = has_correlated_expressions.find(*plan->children[1])->second;
384659 if (!right_has_correlation) {
384660 // only left has correlation: push into left
384661 plan->children[0] = PushDownDependentJoinInternal(std::move(plan->children[0]),
384662 parent_propagate_null_values, lateral_depth);
384663
384664 // recurse into right children, there may be more local correlations
384665 plan->children[1] = DecorrelateIndependent(binder, std::move(plan->children[1]));
384666 return plan;
384667 }
384668 if (!left_has_correlation) {
384669 // only right has correlation: push into right
384670 plan->children[1] = PushDownDependentJoinInternal(std::move(plan->children[1]),
384671 parent_propagate_null_values, lateral_depth);
384672
384673 // recurse into left children
384674 plan->children[0] = DecorrelateIndependent(binder, std::move(plan->children[0]));
384675 // Similar to the LOGICAL_COMPARISON_JOIN
384676 delim_offset += plan->children[0]->GetColumnBindings().size();
384677 return plan;
384678 }
384679 // both sides have correlation
384680 // turn into an inner join
384681 // correctly use left child's delim_offset so execute left child as the last one
384682 auto join = make_uniq<LogicalComparisonJoin>(JoinType::INNER);
384683 plan->children[1] =
384684 PushDownDependentJoinInternal(std::move(plan->children[1]), parent_propagate_null_values, lateral_depth);
384685 auto right_binding = this->base_binding;
384686 plan->children[0] =
384687 PushDownDependentJoinInternal(std::move(plan->children[0]), parent_propagate_null_values, lateral_depth);
384688 // add the correlated columns to the join conditions
384689 for (idx_t i = 0; i < correlated_columns.size(); i++) {
384690 JoinCondition cond;
384691 cond.left = make_uniq<BoundColumnRefExpression>(
384692 correlated_columns[i].type, ColumnBinding(base_binding.table_index, base_binding.column_index + i));
384693 cond.right = make_uniq<BoundColumnRefExpression>(
384694 correlated_columns[i].type, ColumnBinding(right_binding.table_index, right_binding.column_index + i));
384695 cond.comparison = ExpressionType::COMPARE_NOT_DISTINCT_FROM;
384696 join->conditions.push_back(std::move(cond));
384697 }
384698 join->children.push_back(std::move(plan->children[0]));
384699 join->children.push_back(std::move(plan->children[1]));
384700 return std::move(join);
384701 }
384702 case LogicalOperatorType::LOGICAL_DEPENDENT_JOIN: {
384703 D_ASSERT(plan->children.size() == 2);
384704 return Decorrelate(std::move(plan), parent_propagate_null_values, lateral_depth);
384705 }
384706 case LogicalOperatorType::LOGICAL_ANY_JOIN:
384707 case LogicalOperatorType::LOGICAL_ASOF_JOIN:
384708 case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: {
384709 auto &join = plan->Cast<LogicalJoin>();
384710 D_ASSERT(plan->children.size() == 2);
384711 // check the correlated expressions in the children of the join
384712 bool left_has_correlation = has_correlated_expressions.find(*plan->children[0])->second;
384713 bool right_has_correlation = has_correlated_expressions.find(*plan->children[1])->second;
384714
384715 if (join.join_type == JoinType::INNER) {
384716 // inner join
384717 if (!right_has_correlation) {
384718 // only left has correlation: push into left
384719 plan->children[0] = PushDownDependentJoinInternal(std::move(plan->children[0]),
384720 parent_propagate_null_values, lateral_depth);
384721 plan->children[1] = DecorrelateIndependent(binder, std::move(plan->children[1]));
384722 // Remove the correlated columns coming from outside for current join node
384723 return plan;
384724 }
384725 if (!left_has_correlation) {
384726 // only right has correlation: push into right
384727 plan->children[1] = PushDownDependentJoinInternal(std::move(plan->children[1]),
384728 parent_propagate_null_values, lateral_depth);
384729 plan->children[0] = DecorrelateIndependent(binder, std::move(plan->children[0]));
384730 delim_offset += plan->children[0]->GetColumnBindings().size();
384731 // Remove the correlated columns coming from outside for current join node
384732 return plan;
384733 }
384734 } else if (join.join_type == JoinType::LEFT) {
384735 // left outer join
384736 if (!right_has_correlation) {
384737 // only left has correlation: push into left
384738 plan->children[0] = PushDownDependentJoinInternal(std::move(plan->children[0]),
384739 parent_propagate_null_values, lateral_depth);
384740 plan->children[1] = DecorrelateIndependent(binder, std::move(plan->children[1]));
384741 // Remove the correlated columns coming from outside for current join node
384742 return plan;
384743 }
384744 } else if (join.join_type == JoinType::RIGHT) {
384745 // right outer join
384746 if (!left_has_correlation) {
384747 // only right has correlation: push into right
384748 plan->children[1] = PushDownDependentJoinInternal(std::move(plan->children[1]),
384749 parent_propagate_null_values, lateral_depth);
384750 plan->children[0] = DecorrelateIndependent(binder, std::move(plan->children[0]));
384751 delim_offset += plan->children[0]->GetColumnBindings().size();
384752 return plan;
384753 }
384754 } else if (join.join_type == JoinType::MARK) {
384755 if (!left_has_correlation && right_has_correlation) {
384756 // found a MARK join where the left side has no correlation
384757
384758 ColumnBinding right_binding;
384759
384760 // there may still be correlation on the right side that we have to deal with
384761 // push into the right side if necessary or decorrelate it independently otherwise
384762 plan->children[1] = PushDownDependentJoinInternal(std::move(plan->children[1]),
384763 parent_propagate_null_values, lateral_depth);
384764 right_binding = this->base_binding;
384765
384766 // now push into the left side of the MARK join even though it has no correlation
384767 // this is necessary to add the correlated columns to the column bindings and allow
384768 // the join condition to be rewritten correctly
384769 plan->children[0] = PushDownDependentJoinInternal(std::move(plan->children[0]),
384770 parent_propagate_null_values, lateral_depth);
384771
384772 auto left_binding = this->base_binding;
384773
384774 // add the correlated columns to the join conditions
384775 for (idx_t i = 0; i < correlated_columns.size(); i++) {
384776 JoinCondition cond;
384777 cond.left = make_uniq<BoundColumnRefExpression>(
384778 correlated_columns[i].type,
384779 ColumnBinding(left_binding.table_index, left_binding.column_index + i));
384780 cond.right = make_uniq<BoundColumnRefExpression>(
384781 correlated_columns[i].type,
384782 ColumnBinding(right_binding.table_index, right_binding.column_index + i));
384783 cond.comparison = ExpressionType::COMPARE_NOT_DISTINCT_FROM;
384784
384785 auto &comparison_join = join.Cast<LogicalComparisonJoin>();
384786 comparison_join.conditions.push_back(std::move(cond));
384787 }
384788 return plan;
384789 }
384790
384791 // push the child into the LHS
384792 plan->children[0] = PushDownDependentJoinInternal(std::move(plan->children[0]),
384793 parent_propagate_null_values, lateral_depth);
384794 plan->children[1] = DecorrelateIndependent(binder, std::move(plan->children[1]));
384795 // rewrite expressions in the join conditions
384796 RewriteCorrelatedExpressions rewriter(base_binding, correlated_map, lateral_depth);
384797 rewriter.VisitOperator(*plan);
384798 return plan;
384799 } else {
384800 throw NotImplementedException("Unsupported join type for flattening correlated subquery");
384801 }
384802 // both sides have correlation
384803 // push into both sides
384804 plan->children[0] =
384805 PushDownDependentJoinInternal(std::move(plan->children[0]), parent_propagate_null_values, lateral_depth);
384806 auto left_delim_offset = delim_offset;
384807 auto left_binding = this->base_binding;
384808 plan->children[1] =
384809 PushDownDependentJoinInternal(std::move(plan->children[1]), parent_propagate_null_values, lateral_depth);
384810 auto right_binding = this->base_binding;
384811 // NOTE: for OUTER JOINS it matters what the BASE BINDING is after the join
384812 // for the LEFT OUTER JOIN, we want the LEFT side to be the base binding after we push
384813 // because the RIGHT binding might contain NULL values
384814 if (join.join_type == JoinType::LEFT) {
384815 this->base_binding = left_binding;
384816 delim_offset = left_delim_offset;
384817 } else if (join.join_type == JoinType::RIGHT) {
384818 this->base_binding = right_binding;
384819 delim_offset += plan->children[0]->GetColumnBindings().size();
384820 }
384821 // add the correlated columns to the join conditions
384822 for (idx_t i = 0; i < correlated_columns.size(); i++) {
384823 auto left = make_uniq<BoundColumnRefExpression>(
384824 correlated_columns[i].type, ColumnBinding(left_binding.table_index, left_binding.column_index + i));
384825 auto right = make_uniq<BoundColumnRefExpression>(
384826 correlated_columns[i].type, ColumnBinding(right_binding.table_index, right_binding.column_index + i));
384827
384828 if (join.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN ||
384829 join.type == LogicalOperatorType::LOGICAL_ASOF_JOIN) {
384830 JoinCondition cond;
384831 cond.left = std::move(left);
384832 cond.right = std::move(right);
384833 cond.comparison = ExpressionType::COMPARE_NOT_DISTINCT_FROM;
384834
384835 auto &comparison_join = join.Cast<LogicalComparisonJoin>();
384836 comparison_join.conditions.push_back(std::move(cond));
384837 } else {
384838 auto &logical_any_join = join.Cast<LogicalAnyJoin>();
384839 auto comparison = make_uniq<BoundComparisonExpression>(ExpressionType::COMPARE_NOT_DISTINCT_FROM,
384840 std::move(left), std::move(right));
384841 auto conjunction = make_uniq<BoundConjunctionExpression>(
384842 ExpressionType::CONJUNCTION_AND, std::move(comparison), std::move(logical_any_join.condition));
384843 logical_any_join.condition = std::move(conjunction);
384844 }
384845 }
384846 // then we replace any correlated expressions with the corresponding entry in the correlated_map
384847 RewriteCorrelatedExpressions rewriter(right_binding, correlated_map, lateral_depth);
384848 rewriter.VisitOperator(*plan);
384849 return plan;
384850 }
384851 case LogicalOperatorType::LOGICAL_LIMIT: {
384852 auto &limit = plan->Cast<LogicalLimit>();
384853 switch (limit.limit_val.Type()) {
384854 case LimitNodeType::CONSTANT_PERCENTAGE:
384855 case LimitNodeType::EXPRESSION_PERCENTAGE:
384856 // NOTE: limit percent could be supported in a manner similar to the LIMIT above
384857 // but instead of filtering by an exact number of rows, the limit should be expressed as
384858 // COUNT computed over the partition multiplied by the percentage
384859 throw ParserException("Limit percent operator not supported in correlated subquery");
384860 case LimitNodeType::EXPRESSION_VALUE:
384861 throw ParserException("Non-constant limit not supported in correlated subquery");
384862 default:
384863 break;
384864 }
384865 switch (limit.offset_val.Type()) {
384866 case LimitNodeType::EXPRESSION_VALUE:
384867 throw ParserException("Non-constant offset not supported in correlated subquery");
384868 case LimitNodeType::CONSTANT_PERCENTAGE:
384869 case LimitNodeType::EXPRESSION_PERCENTAGE:
384870 throw InternalException("Percentage offset in FlattenDependentJoin");
384871 default:
384872 break;
384873 }
384874 auto rownum_alias = "limit_rownum";
384875 unique_ptr<LogicalOperator> child;
384876 unique_ptr<LogicalOrder> order_by;
384877
384878 // check if the direct child of this LIMIT node is an ORDER BY node, if so, keep it separate
384879 // this is done for an optimization to avoid having to compute the total order
384880 if (plan->children[0]->type == LogicalOperatorType::LOGICAL_ORDER_BY) {
384881 order_by = unique_ptr_cast<LogicalOperator, LogicalOrder>(std::move(plan->children[0]));
384882 child = PushDownDependentJoinInternal(std::move(order_by->children[0]), parent_propagate_null_values,
384883 lateral_depth);
384884 } else {
384885 child = PushDownDependentJoinInternal(std::move(plan->children[0]), parent_propagate_null_values,
384886 lateral_depth);
384887 }
384888 auto child_column_count = child->GetColumnBindings().size();
384889 // we push a row_number() OVER (PARTITION BY [correlated columns])
384890 auto window_index = binder.GenerateTableIndex();
384891 auto window = make_uniq<LogicalWindow>(window_index);
384892 auto row_number =
384893 make_uniq<BoundWindowExpression>(ExpressionType::WINDOW_ROW_NUMBER, LogicalType::BIGINT, nullptr, nullptr);
384894 auto partition_count = perform_delim ? correlated_columns.size() : 1;
384895 for (idx_t i = 0; i < partition_count; i++) {
384896 auto &col = correlated_columns[i];
384897 auto colref = make_uniq<BoundColumnRefExpression>(
384898 col.name, col.type, ColumnBinding(base_binding.table_index, base_binding.column_index + i));
384899 row_number->partitions.push_back(std::move(colref));
384900 }
384901 if (order_by) {
384902 // optimization: if there is an ORDER BY node followed by a LIMIT
384903 // rather than computing the entire order, we push the ORDER BY expressions into the row_num computation
384904 // this way, the order only needs to be computed per partition
384905 row_number->orders = std::move(order_by->orders);
384906 }
384907 row_number->start = WindowBoundary::UNBOUNDED_PRECEDING;
384908 row_number->end = WindowBoundary::CURRENT_ROW_ROWS;
384909 window->expressions.push_back(std::move(row_number));
384910 window->children.push_back(std::move(child));
384911
384912 // add a filter based on the row_number
384913 // the filter we add is "row_number > offset AND row_number <= offset + limit"
384914 auto filter = make_uniq<LogicalFilter>();
384915 unique_ptr<Expression> condition;
384916 auto row_num_ref =
384917 make_uniq<BoundColumnRefExpression>(rownum_alias, LogicalType::BIGINT, ColumnBinding(window_index, 0));
384918
384919 if (limit.limit_val.Type() == LimitNodeType::CONSTANT_VALUE) {
384920 auto upper_bound_limit = NumericLimits<int64_t>::Maximum();
384921 auto limit_val = int64_t(limit.limit_val.GetConstantValue());
384922 if (limit.offset_val.Type() == LimitNodeType::CONSTANT_VALUE) {
384923 // both offset and limit specified - upper bound is offset + limit
384924 auto offset_val = int64_t(limit.offset_val.GetConstantValue());
384925 TryAddOperator::Operation(limit_val, offset_val, upper_bound_limit);
384926 } else {
384927 // no offset - upper bound is only the limit
384928 upper_bound_limit = limit_val;
384929 }
384930 auto upper_bound = make_uniq<BoundConstantExpression>(Value::BIGINT(upper_bound_limit));
384931 condition = make_uniq<BoundComparisonExpression>(ExpressionType::COMPARE_LESSTHANOREQUALTO,
384932 row_num_ref->Copy(), std::move(upper_bound));
384933 }
384934 // we only need to add "row_number >= offset + 1" if offset is bigger than 0
384935 if (limit.offset_val.Type() == LimitNodeType::CONSTANT_VALUE) {
384936 auto offset_val = int64_t(limit.offset_val.GetConstantValue());
384937 auto lower_bound = make_uniq<BoundConstantExpression>(Value::BIGINT(offset_val));
384938 auto lower_comp = make_uniq<BoundComparisonExpression>(ExpressionType::COMPARE_GREATERTHAN,
384939 row_num_ref->Copy(), std::move(lower_bound));
384940 if (condition) {
384941 auto conj = make_uniq<BoundConjunctionExpression>(ExpressionType::CONJUNCTION_AND,
384942 std::move(lower_comp), std::move(condition));
384943 condition = std::move(conj);
384944 } else {
384945 condition = std::move(lower_comp);
384946 }
384947 }
384948 filter->expressions.push_back(std::move(condition));
384949 filter->children.push_back(std::move(window));
384950 // we prune away the row_number after the filter clause using the projection map
384951 for (idx_t i = 0; i < child_column_count; i++) {
384952 filter->projection_map.push_back(i);
384953 }
384954 return std::move(filter);
384955 }
384956 case LogicalOperatorType::LOGICAL_WINDOW: {
384957 auto &window = plan->Cast<LogicalWindow>();
384958 // push into children
384959 plan->children[0] =
384960 PushDownDependentJoinInternal(std::move(plan->children[0]), parent_propagate_null_values, lateral_depth);
384961
384962 // we replace any correlated expressions with the corresponding entry in the correlated_map
384963 RewriteCorrelatedExpressions rewriter(base_binding, correlated_map, lateral_depth);
384964 rewriter.VisitOperator(*plan);
384965
384966 // add the correlated columns to the PARTITION BY clauses in the Window
384967 for (auto &expr : window.expressions) {
384968 D_ASSERT(expr->GetExpressionClass() == ExpressionClass::BOUND_WINDOW);
384969 auto &w = expr->Cast<BoundWindowExpression>();
384970 for (idx_t i = 0; i < correlated_columns.size(); i++) {
384971 w.partitions.push_back(make_uniq<BoundColumnRefExpression>(
384972 correlated_columns[i].type,
384973 ColumnBinding(base_binding.table_index, base_binding.column_index + i)));
384974 }
384975 }
384976 return plan;
384977 }
384978 case LogicalOperatorType::LOGICAL_EXCEPT:
384979 case LogicalOperatorType::LOGICAL_INTERSECT:
384980 case LogicalOperatorType::LOGICAL_UNION: {
384981 auto &setop = plan->Cast<LogicalSetOperation>();
384982 // set operator, push into both children
384983#ifdef DEBUG
384984 for (auto &child : plan->children) {
384985 child->ResolveOperatorTypes();
384986 }
384987 for (idx_t i = 1; i < plan->children.size(); i++) {
384988 D_ASSERT(plan->children[0]->types.size() == plan->children[i]->types.size());
384989 }
384990#endif
384991 for (auto &child : plan->children) {
384992 child = PushDownDependentJoin(std::move(child));
384993 }
384994 for (idx_t i = 0; i < plan->children.size(); i++) {
384995 if (plan->children[i]->type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) {
384996 auto proj_index = binder.GenerateTableIndex();
384997 auto bindings = plan->children[i]->GetColumnBindings();
384998 plan->children[i]->ResolveOperatorTypes();
384999 auto types = plan->children[i]->types;
385000 vector<unique_ptr<Expression>> expressions;
385001 expressions.reserve(bindings.size());
385002 D_ASSERT(bindings.size() == types.size());
385003
385004 // No column binding replaceent is needed because the parent operator is
385005 // a setop which will immediately assign new bindings.
385006 for (idx_t col_idx = 0; col_idx < bindings.size(); col_idx++) {
385007 expressions.push_back(make_uniq<BoundColumnRefExpression>(types[col_idx], bindings[col_idx]));
385008 }
385009 auto proj = make_uniq<LogicalProjection>(proj_index, std::move(expressions));
385010 proj->children.push_back(std::move(plan->children[i]));
385011 plan->children[i] = std::move(proj);
385012 }
385013 }
385014
385015 // here we need to check the children. If they have reorderable bindings, you need to plan a projection
385016 // on top that will guarantee the order of the bindings.
385017#ifdef DEBUG
385018 for (idx_t i = 1; i < plan->children.size(); i++) {
385019 D_ASSERT(plan->children[0]->GetColumnBindings().size() == plan->children[i]->GetColumnBindings().size());
385020 }
385021 for (auto &child : plan->children) {
385022 child->ResolveOperatorTypes();
385023 }
385024 for (idx_t i = 1; i < plan->children.size(); i++) {
385025 D_ASSERT(plan->children[0]->types.size() == plan->children[i]->types.size());
385026 }
385027#endif
385028 // we have to refer to the setop index now
385029 base_binding.table_index = setop.table_index;
385030 base_binding.column_index = setop.column_count;
385031 setop.column_count += correlated_columns.size();
385032 return plan;
385033 }
385034 case LogicalOperatorType::LOGICAL_DISTINCT: {
385035 auto &distinct = plan->Cast<LogicalDistinct>();
385036 // push down into child
385037 distinct.children[0] = PushDownDependentJoin(std::move(distinct.children[0]));
385038 // add all correlated columns to the distinct targets
385039 for (idx_t i = 0; i < correlated_columns.size(); i++) {
385040 distinct.distinct_targets.push_back(make_uniq<BoundColumnRefExpression>(
385041 correlated_columns[i].type, ColumnBinding(base_binding.table_index, base_binding.column_index + i)));
385042 }
385043 return plan;
385044 }
385045 case LogicalOperatorType::LOGICAL_EXPRESSION_GET: {
385046 // expression get
385047 // first we flatten the dependent join in the child
385048 plan->children[0] =
385049 PushDownDependentJoinInternal(std::move(plan->children[0]), parent_propagate_null_values, lateral_depth);
385050 // then we replace any correlated expressions with the corresponding entry in the correlated_map
385051 RewriteCorrelatedExpressions rewriter(base_binding, correlated_map, lateral_depth);
385052 rewriter.VisitOperator(*plan);
385053 // now we add all the correlated columns to each of the expressions of the expression scan
385054 auto &expr_get = plan->Cast<LogicalExpressionGet>();
385055 for (idx_t i = 0; i < correlated_columns.size(); i++) {
385056 for (auto &expr_list : expr_get.expressions) {
385057 auto colref = make_uniq<BoundColumnRefExpression>(
385058 correlated_columns[i].type, ColumnBinding(base_binding.table_index, base_binding.column_index + i));
385059 expr_list.push_back(std::move(colref));
385060 }
385061 expr_get.expr_types.push_back(correlated_columns[i].type);
385062 }
385063
385064 base_binding.table_index = expr_get.table_index;
385065 this->delim_offset = base_binding.column_index = expr_get.expr_types.size() - correlated_columns.size();
385066 this->data_offset = 0;
385067 return plan;
385068 }
385069 case LogicalOperatorType::LOGICAL_PIVOT:
385070 throw BinderException("PIVOT is not supported in correlated subqueries yet");
385071 case LogicalOperatorType::LOGICAL_ORDER_BY:
385072 plan->children[0] = PushDownDependentJoin(std::move(plan->children[0]));
385073 return plan;
385074 case LogicalOperatorType::LOGICAL_GET: {
385075 auto &get = plan->Cast<LogicalGet>();
385076 if (get.children.size() != 1) {
385077 throw InternalException("Flatten dependent joins - logical get encountered without children");
385078 }
385079 plan->children[0] = PushDownDependentJoin(std::move(plan->children[0]));
385080 for (idx_t i = 0; i < correlated_columns.size(); i++) {
385081 get.projected_input.push_back(this->delim_offset + i);
385082 }
385083 this->delim_offset = get.GetColumnIds().size();
385084 this->data_offset = 0;
385085
385086 RewriteCorrelatedExpressions rewriter(base_binding, correlated_map, lateral_depth);
385087 rewriter.VisitOperator(*plan);
385088 return plan;
385089 }
385090 case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE:
385091 case LogicalOperatorType::LOGICAL_RECURSIVE_CTE: {
385092#ifdef DEBUG
385093 plan->children[0]->ResolveOperatorTypes();
385094 plan->children[1]->ResolveOperatorTypes();
385095#endif
385096 if (plan->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) {
385097 // check the correlated expressions in the children of the join
385098 bool left_has_correlation = has_correlated_expressions.find(*plan->children[0])->second;
385099 bool right_has_correlation = has_correlated_expressions.find(*plan->children[1])->second;
385100
385101 if (!left_has_correlation && right_has_correlation) {
385102 // only right has correlation: push into right
385103 plan->children[1] = PushDownDependentJoinInternal(std::move(plan->children[1]),
385104 parent_propagate_null_values, lateral_depth);
385105 plan->children[0] = DecorrelateIndependent(binder, std::move(plan->children[0]));
385106 return plan;
385107 }
385108 }
385109
385110 idx_t table_index = 0;
385111 plan->children[0] =
385112 PushDownDependentJoinInternal(std::move(plan->children[0]), parent_propagate_null_values, lateral_depth);
385113
385114 auto &setop = plan->Cast<LogicalCTE>();
385115 base_binding.table_index = setop.table_index;
385116 base_binding.column_index = setop.column_count;
385117 table_index = setop.table_index;
385118 setop.correlated_columns = correlated_columns;
385119 binder.recursive_ctes[setop.table_index] = &setop;
385120
385121 if (plan->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) {
385122 auto &setop = plan->Cast<LogicalRecursiveCTE>();
385123
385124 if (!setop.key_targets.empty()) {
385125 for (idx_t i = 0; i < correlated_columns.size(); i++) {
385126 auto corr = correlated_columns[i];
385127 auto colref = make_uniq<BoundColumnRefExpression>(
385128 correlated_columns[i].type,
385129 ColumnBinding(base_binding.table_index, base_binding.column_index + i));
385130 setop.key_targets.push_back(std::move(colref));
385131 }
385132 }
385133 }
385134
385135 CTEScanRewriteMode rewrite_mode;
385136 if (plan->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) {
385138 } else if (plan->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) {
385140 } else {
385141 throw InternalException("Unsupported CTE operator type for CTEScanRewriteMode selection");
385142 }
385143 RewriteCTEScan cte_rewriter(table_index, correlated_columns, rewrite_mode);
385144 cte_rewriter.VisitOperator(*plan->children[1]);
385145
385146 parent_propagate_null_values = false;
385147 plan->children[1] =
385148 PushDownDependentJoinInternal(std::move(plan->children[1]), parent_propagate_null_values, lateral_depth);
385149
385150 RewriteCorrelatedExpressions rewriter(this->base_binding, correlated_map, lateral_depth);
385151 rewriter.VisitOperator(*plan);
385152
385153 RewriteCorrelatedExpressions recursive_rewriter(this->base_binding, correlated_map, lateral_depth + 1, true);
385154 recursive_rewriter.VisitOperator(*plan->children[0]);
385155 recursive_rewriter.VisitOperator(*plan->children[1]);
385156
385157#ifdef DEBUG
385158 plan->children[0]->ResolveOperatorTypes();
385159 plan->children[1]->ResolveOperatorTypes();
385160#endif
385161
385162 if (plan->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) {
385163 // we have to refer to the recursive CTE index now
385164 base_binding.table_index = setop.table_index;
385165 base_binding.column_index = setop.column_count;
385166 }
385167
385168 setop.column_count += correlated_columns.size();
385169
385170 return plan;
385171 }
385172 case LogicalOperatorType::LOGICAL_CTE_REF: {
385173 auto &cteref = plan->Cast<LogicalCTERef>();
385174 // Read correlated columns from CTE_SCAN instead of from DELIM_SCAN
385175 base_binding.table_index = cteref.table_index;
385176 base_binding.column_index = cteref.chunk_types.size() - cteref.correlated_columns;
385177 return plan;
385178 }
385179 case LogicalOperatorType::LOGICAL_DELIM_JOIN: {
385180 throw BinderException("Nested lateral joins or lateral joins in correlated subqueries are not (yet) supported");
385181 }
385182 case LogicalOperatorType::LOGICAL_SAMPLE:
385183 throw BinderException("Sampling in correlated subqueries is not (yet) supported");
385184 case LogicalOperatorType::LOGICAL_POSITIONAL_JOIN:
385185 throw BinderException("Positional join in correlated subqueries is not (yet) supported");
385186 default:
385187 throw InternalException("Logical operator type \"%s\" for dependent join", LogicalOperatorToString(plan->type));
385188 }
385189}
static DUCKDB_API Value BIGINT(int64_t value)
Create a bigint Value from a specified value.
Definition duckdb.cpp:132146
__host__ cudaTextureObject_t get() const noexcept
float corr
cv::String join(const cv::String &base, const cv::String &path)
::int64_t int64_t
CTEScanRewriteMode
Controls whether RewriteCTEScan rewrites only CTE_REF nodes or also dependent joins.
Definition duckdb.cpp:384041
@ WITH_NON_RECURSIVE_DEPENDENT_JOINS
Rewrite LOGICAL_CTE_REF nodes and non-recursive dependent joins that reference the target CTE.
Definition duckdb.cpp:384045
@ WITH_RECURSIVE_DEPENDENT_JOINS
Rewrite LOGICAL_CTE_REF nodes and dependent joins for recursive CTE rewrites (preserving recursive or...
Definition duckdb.cpp:384047

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