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

Public Member Functions

 TopNWindowElimination (ClientContext &context, Optimizer &optimizer, optional_ptr< column_binding_map_t< unique_ptr< BaseStatistics > > > stats_p)
unique_ptr< LogicalOperator > Optimize (unique_ptr< LogicalOperator > op)
Public Member Functions inherited from duckdb::LogicalOperatorVisitor
virtual void VisitOperator (LogicalOperator &op)

Private Member Functions

bool CanOptimize (LogicalOperator &op)
unique_ptr< LogicalOperator > OptimizeInternal (unique_ptr< LogicalOperator > op, ColumnBindingReplacer &replacer)
unique_ptr< LogicalOperator > CreateAggregateOperator (LogicalWindow &window, vector< unique_ptr< Expression > > args, const TopNWindowEliminationParameters &params) const
unique_ptr< LogicalOperator > TryCreateUnnestOperator (unique_ptr< LogicalOperator > op, const TopNWindowEliminationParameters &params) const
unique_ptr< LogicalOperator > CreateProjectionOperator (unique_ptr< LogicalOperator > op, const TopNWindowEliminationParameters &params, const map< idx_t, idx_t > &group_idxs) const
vector< unique_ptr< Expression > > GenerateAggregatePayload (const vector< ColumnBinding > &bindings, const LogicalWindow &window, map< idx_t, idx_t > &group_idxs)
bool TraverseProjectionBindings (const vector< ColumnBinding > &old_bindings, reference< LogicalOperator > &op, vector< ColumnBinding > &new_bindings)
unique_ptr< Expression > CreateAggregateExpression (vector< unique_ptr< Expression > > aggregate_params, bool requires_arg, const TopNWindowEliminationParameters &params) const
unique_ptr< Expression > CreateRowNumberGenerator (unique_ptr< Expression > aggregate_column_ref) const
void AddStructExtractExprs (vector< unique_ptr< Expression > > &exprs, const LogicalType &struct_type, const unique_ptr< BoundColumnRefExpression > &aggregate_column_ref) const
unique_ptr< LogicalOperator > UpdateTopmostBindings (idx_t window_idx, unique_ptr< LogicalOperator > op, const vector< LogicalType > &types, const map< idx_t, idx_t > &group_idxs, const vector< ColumnBinding > &topmost_bindings, vector< ColumnBinding > &new_bindings, ColumnBindingReplacer &replacer)
TopNWindowEliminationParameters ExtractOptimizerParameters (const LogicalWindow &window, const LogicalFilter &filter, const vector< ColumnBinding > &bindings, vector< unique_ptr< Expression > > &aggregate_payload)
unique_ptr< LogicalOperator > TryPrepareLateMaterialization (const LogicalWindow &window, vector< unique_ptr< Expression > > &args)
unique_ptr< LogicalOperator > ConstructLHS (LogicalGet &rhs, vector< idx_t > &projections) const
bool CanUseLateMaterialization (const LogicalWindow &window, vector< unique_ptr< Expression > > &args, vector< idx_t > &projections, vector< reference< LogicalOperator > > &stack)
bool ExtractSingleBinding (unique_ptr< Expression > *expr, ColumnBinding &binding, bool require_direct_column_ref=false)

Static Private Member Functions

static unique_ptr< LogicalOperator > ConstructJoin (unique_ptr< LogicalOperator > lhs, unique_ptr< LogicalOperator > rhs, idx_t rhs_rowid_idx, const TopNWindowEliminationParameters &params)

Private Attributes

ClientContext & context
Optimizer & optimizer
optional_ptr< column_binding_map_t< unique_ptr< BaseStatistics > > > stats

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.

Constructor & Destructor Documentation

◆ TopNWindowElimination()

duckdb::TopNWindowElimination::TopNWindowElimination ( ClientContext & context,
Optimizer & optimizer,
optional_ptr< column_binding_map_t< unique_ptr< BaseStatistics > > > stats_p )
explicit
326027 : context(context_p), optimizer(optimizer), stats(stats_p) {
326028 D_ASSERT(stats);
326029}

Member Function Documentation

◆ Optimize()

unique_ptr< LogicalOperator > duckdb::TopNWindowElimination::Optimize ( unique_ptr< LogicalOperator > op)
326031 {
326032 auto &extension_manager = context.db->GetExtensionManager();
326033 if (!extension_manager.ExtensionIsLoaded("core_functions")) {
326034 return op;
326035 }
326036
326037 ColumnBindingReplacer replacer;
326038 op = OptimizeInternal(std::move(op), replacer);
326039 if (!replacer.replacement_bindings.empty()) {
326040 replacer.VisitOperator(*op);
326041 }
326042 return op;
326043}

◆ CanOptimize()

bool duckdb::TopNWindowElimination::CanOptimize ( LogicalOperator & op)
private
326357 {
326358 if (op.type != LogicalOperatorType::LOGICAL_FILTER) {
326359 return false;
326360 }
326361
326362 const auto &filter = op.Cast<LogicalFilter>();
326363 if (filter.expressions.size() != 1) {
326364 return false;
326365 }
326366
326367 const auto comparison = filter.expressions[0]->type;
326368 switch (comparison) {
326369 case ExpressionType::COMPARE_LESSTHANOREQUALTO:
326370 case ExpressionType::COMPARE_LESSTHAN:
326371 case ExpressionType::COMPARE_EQUAL:
326372 break;
326373 default:
326374 return false;
326375 }
326376
326377 auto &filter_comparison = filter.expressions[0]->Cast<BoundComparisonExpression>();
326378 if (filter_comparison.right->type != ExpressionType::VALUE_CONSTANT) {
326379 return false;
326380 }
326381 auto &filter_value = filter_comparison.right->Cast<BoundConstantExpression>();
326382 if (filter_value.value.type() != LogicalType::BIGINT) {
326383 return false;
326384 }
326385 if (filter_value.value.IsNull()) {
326386 return false;
326387 }
326388
326389 const auto bigint_value = filter_value.value.GetValue<int64_t>();
326390 switch (comparison) {
326391 case ExpressionType::COMPARE_LESSTHANOREQUALTO:
326392 if (bigint_value < 1) {
326393 return false;
326394 }
326395 break;
326396 case ExpressionType::COMPARE_LESSTHAN:
326397 if (bigint_value < 2) {
326398 return false;
326399 }
326400 break;
326401 case ExpressionType::COMPARE_EQUAL:
326402 // TODO: Handle other values
326403 if (bigint_value != 1) {
326404 return false;
326405 }
326406 break;
326407 default:
326408 return false;
326409 }
326410
326411 if (filter_comparison.left->type != ExpressionType::BOUND_COLUMN_REF) {
326412 return false;
326413 }
326414 VisitExpression(&filter_comparison.left);
326415
326416 reference<LogicalOperator> child = *filter.children[0];
326417 while (child.get().type == LogicalOperatorType::LOGICAL_PROJECTION) {
326418 auto &projection = child.get().Cast<LogicalProjection>();
326419 if (column_references.size() != 1) {
326420 column_references.clear();
326421 return false;
326422 }
326423
326424 const auto current_column_ref = column_references.begin()->first;
326425 column_references.clear();
326426 D_ASSERT(current_column_ref.table_index == projection.table_index);
326427 VisitExpression(&projection.expressions[current_column_ref.column_index]);
326428
326429 child = *child.get().children[0];
326430 }
326431
326432 if (column_references.size() != 1) {
326433 column_references.clear();
326434 return false;
326435 }
326436 const auto filter_col_idx = column_references.begin()->first.table_index;
326437 column_references.clear();
326438
326439 if (child.get().type != LogicalOperatorType::LOGICAL_WINDOW) {
326440 return false;
326441 }
326442 const auto &window = child.get().Cast<LogicalWindow>();
326443 if (window.window_index != filter_col_idx) {
326444 return false;
326445 }
326446 const auto &first_window_expr = window.expressions[0]->Cast<BoundWindowExpression>();
326447 for (auto &partition : first_window_expr.partitions) {
326448 if (partition->GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) {
326449 return false;
326450 }
326451 }
326452 if (window.expressions.size() != 1) {
326453 for (idx_t i = 1; i < window.expressions.size(); ++i) {
326454 if (!window.expressions[i]->Equals(first_window_expr)) {
326455 return false;
326456 }
326457 }
326458 }
326459 if (window.expressions[0]->type != ExpressionType::WINDOW_ROW_NUMBER) {
326460 return false;
326461 }
326462 auto &window_expr = window.expressions[0]->Cast<BoundWindowExpression>();
326463
326464 if (window_expr.orders.size() != 1) {
326465 return false;
326466 }
326467 if (window_expr.orders[0].type != OrderType::DESCENDING && window_expr.orders[0].type != OrderType::ASCENDING) {
326468 return false;
326469 }
326470 if (window_expr.orders[0].null_order != OrderByNullType::NULLS_LAST) {
326471 return false;
326472 }
326473
326474 // We have found a grouped top-n window construct!
326475 return true;
326476}
void VisitExpression(unique_ptr< Expression > *expression) override
Definition duckdb.cpp:319455
column_binding_map_t< ReferencedColumn > column_references
The map of column references.
Definition duckdb.cpp:60560
int partition(const std::vector< _Tp > &_vec, std::vector< int > &labels, _EqPredicate predicate=_EqPredicate())
void filter(InputArray image, InputArray kernel, OutputArray output)
::int64_t int64_t
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ OptimizeInternal()

unique_ptr< LogicalOperator > duckdb::TopNWindowElimination::OptimizeInternal ( unique_ptr< LogicalOperator > op,
ColumnBindingReplacer & replacer )
private
326046 {
326047 if (!CanOptimize(*op)) {
326048 // Traverse through query plan to find grouped top-n pattern
326049 if (op->children.size() > 1) {
326050 // If an operator has multiple children, we do not want them to overwrite each other's stop operator.
326051 // Thus, first update only the column binding in op, then set op as the new stop operator.
326052 for (auto &child : op->children) {
326053 ColumnBindingReplacer r2;
326054 child = OptimizeInternal(std::move(child), r2);
326055
326056 if (!r2.replacement_bindings.empty()) {
326057 r2.VisitOperator(*op);
326058 replacer.replacement_bindings.insert(replacer.replacement_bindings.end(),
326059 r2.replacement_bindings.begin(),
326060 r2.replacement_bindings.end());
326061 replacer.stop_operator = op;
326062 }
326063 }
326064 } else if (!op->children.empty()) {
326065 op->children[0] = OptimizeInternal(std::move(op->children[0]), replacer);
326066 }
326067
326068 return op;
326069 }
326070 // We have made sure that this is an operator sequence of filter -> N optional projections -> window
326071 auto &filter = op->Cast<LogicalFilter>();
326072 reference<LogicalOperator> child = *filter.children[0];
326073
326074 // Get bindings and types from filter to use in top-most operator later
326075 const auto topmost_bindings = filter.GetColumnBindings();
326076 const auto topmost_types = filter.types;
326077 vector<ColumnBinding> new_bindings;
326078 if (!TraverseProjectionBindings(topmost_bindings, child, new_bindings)) {
326079 return op;
326080 }
326081
326082 D_ASSERT(child.get().type == LogicalOperatorType::LOGICAL_WINDOW);
326083 auto &window = child.get().Cast<LogicalWindow>();
326084 const idx_t window_idx = window.window_index;
326085
326086 // Map the input column offsets of the group columns to the output offset if there are projections on the group
326087 // We use an ordered map here because we need to iterate over them in order later
326088 map<idx_t, idx_t> group_projection_idxs;
326089 auto aggregate_payload = GenerateAggregatePayload(new_bindings, window, group_projection_idxs);
326090 auto params = ExtractOptimizerParameters(window, filter, new_bindings, aggregate_payload);
326091
326092 unique_ptr<LogicalOperator> late_mat_lhs = nullptr;
326093 if (params.payload_type == TopNPayloadType::STRUCT_PACK) {
326094 // Try circumventing struct-packing with late materialization
326095 late_mat_lhs = TryPrepareLateMaterialization(window, aggregate_payload);
326096 if (late_mat_lhs && aggregate_payload.size() == 1) {
326097 params.payload_type = TopNPayloadType::SINGLE_COLUMN;
326098 }
326099 }
326100
326101 // Optimize window children
326102 window.children[0] = Optimize(std::move(window.children[0]));
326103
326104 op = CreateAggregateOperator(window, std::move(aggregate_payload), params);
326105 op = TryCreateUnnestOperator(std::move(op), params);
326106 op = CreateProjectionOperator(std::move(op), params, group_projection_idxs);
326107
326108 D_ASSERT(op->type != LogicalOperatorType::LOGICAL_UNNEST);
326109
326110 if (late_mat_lhs) {
326111 op = ConstructJoin(std::move(late_mat_lhs), std::move(op), group_projection_idxs.size(), params);
326112 }
326113
326114 op = UpdateTopmostBindings(window_idx, std::move(op), topmost_types, group_projection_idxs, topmost_bindings,
326115 new_bindings, replacer);
326116
326117 replacer.stop_operator = op.get();
326118
326119 if (!HasExternalCTEReferences(*op)) {
326120 RemoveUnusedColumns unused_optimizer(optimizer);
326121 unused_optimizer.VisitOperator(*op);
326122 }
326123
326124 return unique_ptr<LogicalOperator>(std::move(op));
326125}
PyParams params(const std::string &tag, const std::string &model, const std::string &weights, const std::string &device)

◆ CreateAggregateOperator()

unique_ptr< LogicalOperator > duckdb::TopNWindowElimination::CreateAggregateOperator ( LogicalWindow & window,
vector< unique_ptr< Expression > > args,
const TopNWindowEliminationParameters & params ) const
private
326153 {
326154 auto &window_expr = window.expressions[0]->Cast<BoundWindowExpression>();
326155 D_ASSERT(window_expr.orders.size() == 1);
326156
326157 vector<unique_ptr<Expression>> aggregate_params;
326158 aggregate_params.reserve(3);
326159
326160 const bool use_arg = !args.empty();
326161 if (args.size() == 1) {
326162 aggregate_params.push_back(std::move(args[0]));
326163 } else if (args.size() > 1) {
326164 // For more than one arg, we must use struct pack
326165 auto &catalog = Catalog::GetSystemCatalog(context);
326166 FunctionBinder function_binder(context);
326167 auto &struct_pack_entry = catalog.GetEntry<ScalarFunctionCatalogEntry>(context, DEFAULT_SCHEMA, "struct_pack");
326168 const auto struct_pack_fun =
326169 struct_pack_entry.functions.GetFunctionByArguments(context, ExtractReturnTypes(args));
326170 auto struct_pack_expr = function_binder.BindScalarFunction(struct_pack_fun, std::move(args));
326171 aggregate_params.push_back(std::move(struct_pack_expr));
326172 }
326173
326174 aggregate_params.push_back(std::move(window_expr.orders[0].expression));
326175 if (params.limit > 1) {
326176 aggregate_params.push_back(std::move(make_uniq<BoundConstantExpression>(Value::BIGINT(params.limit))));
326177 }
326178
326179 auto aggregate_expr = CreateAggregateExpression(std::move(aggregate_params), use_arg, params);
326180
326181 vector<unique_ptr<Expression>> select_list;
326182 select_list.push_back(std::move(aggregate_expr));
326183
326184 auto aggregate = make_uniq<LogicalAggregate>(optimizer.binder.GenerateTableIndex(),
326185 optimizer.binder.GenerateTableIndex(), std::move(select_list));
326186 aggregate->groupings_index = optimizer.binder.GenerateTableIndex();
326187 aggregate->groups = std::move(window_expr.partitions);
326188 aggregate->children.push_back(std::move(window.children[0]));
326189 aggregate->ResolveOperatorTypes();
326190
326191 // Add group statistics to allow for perfect hash aggregation if applicable
326192 aggregate->group_stats.resize(aggregate->groups.size());
326193 for (idx_t i = 0; i < aggregate->groups.size(); i++) {
326194 auto &group = aggregate->groups[i];
326195 if (group->type == ExpressionType::BOUND_COLUMN_REF) {
326196 auto &column_ref = group->Cast<BoundColumnRefExpression>();
326197 auto group_stats = stats->find(column_ref.binding);
326198 if (group_stats == stats->end()) {
326199 continue;
326200 }
326201 aggregate->group_stats[i] = group_stats->second->ToUnique();
326202 }
326203 }
326204
326205 return unique_ptr<LogicalOperator>(std::move(aggregate));
326206}
static DUCKDB_API Catalog & GetSystemCatalog(ClientContext &context)
Get the SystemCatalog from the ClientContext.
Definition duckdb.cpp:7173
static DUCKDB_API Value BIGINT(int64_t value)
Create a bigint Value from a specified value.
Definition duckdb.cpp:132146

◆ TryCreateUnnestOperator()

unique_ptr< LogicalOperator > duckdb::TopNWindowElimination::TryCreateUnnestOperator ( unique_ptr< LogicalOperator > op,
const TopNWindowEliminationParameters & params ) const
private
326247 {
326248 D_ASSERT(op->type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY);
326249
326250 auto &logical_aggregate = op->Cast<LogicalAggregate>();
326251 const idx_t aggregate_column_idx = logical_aggregate.groups.size();
326252 LogicalType aggregate_type = logical_aggregate.types[aggregate_column_idx];
326253
326254 if (params.limit <= 1) {
326255 // LIMIT 1 -> we do not need to unnest
326256 return op;
326257 }
326258
326259 // Create unnest expression for aggregate args
326260 const auto aggregate_bindings = logical_aggregate.GetColumnBindings();
326261 auto aggregate_column_ref =
326262 make_uniq<BoundColumnRefExpression>(aggregate_type, aggregate_bindings[aggregate_column_idx]);
326263
326264 vector<unique_ptr<Expression>> unnest_exprs;
326265
326266 auto unnest_aggregate = make_uniq<BoundUnnestExpression>(ListType::GetChildType(aggregate_type));
326267 unnest_aggregate->child = aggregate_column_ref->Copy();
326268 unnest_exprs.push_back(std::move(unnest_aggregate));
326269
326270 if (params.include_row_number) {
326271 // Create row number expression
326272 unnest_exprs.push_back(CreateRowNumberGenerator(std::move(aggregate_column_ref)));
326273 }
326274
326275 auto unnest = make_uniq<LogicalUnnest>(optimizer.binder.GenerateTableIndex());
326276 unnest->expressions = std::move(unnest_exprs);
326277 unnest->children.push_back(std::move(op));
326278 unnest->ResolveOperatorTypes();
326279
326280 return unique_ptr<LogicalOperator>(std::move(unnest));
326281}

◆ CreateProjectionOperator()

unique_ptr< LogicalOperator > duckdb::TopNWindowElimination::CreateProjectionOperator ( unique_ptr< LogicalOperator > op,
const TopNWindowEliminationParameters & params,
const map< idx_t, idx_t > & group_idxs ) const
private
326310 {
326311 const auto aggregate_type = GetAggregateType(op);
326312 const idx_t aggregate_table_idx = GetAggregateIdx(op);
326313 const auto op_column_bindings = op->GetColumnBindings();
326314
326315 vector<unique_ptr<Expression>> proj_exprs;
326316 // Only project necessary group columns, but in the same order as they appear in the aggregate operator.
326317 // For that, we need the group_idxs ordered by value.
326318 std::set<idx_t> ordered_group_projection_idxs;
326319 for (const auto &group_idx : group_idxs) {
326320 ordered_group_projection_idxs.insert(group_idx.second);
326321 }
326322
326323 for (const idx_t group_projection_idx : ordered_group_projection_idxs) {
326324 proj_exprs.push_back(make_uniq<BoundColumnRefExpression>(op->types[group_projection_idx],
326325 op_column_bindings[group_projection_idx]));
326326 }
326327
326328 auto aggregate_column_ref =
326329 make_uniq<BoundColumnRefExpression>(aggregate_type, ColumnBinding(aggregate_table_idx, 0));
326330
326331 if (params.payload_type == TopNPayloadType::STRUCT_PACK) {
326332 AddStructExtractExprs(proj_exprs, aggregate_type, aggregate_column_ref);
326333 } else {
326334 // No need for struct_unpack! Just reference the aggregate column
326335 proj_exprs.push_back(std::move(aggregate_column_ref));
326336 }
326337
326338 if (params.include_row_number) {
326339 // If aggregate (i.e., limit 1): constant, if unnest: expect there to be a second column
326340 if (op->type == LogicalOperatorType::LOGICAL_UNNEST) {
326341 auto row_number_column_binding = GetRowNumberColumnBinding(op);
326342 proj_exprs.push_back(
326343 make_uniq<BoundColumnRefExpression>("row_number", LogicalType::BIGINT, row_number_column_binding));
326344 } else {
326345 proj_exprs.push_back(make_uniq<BoundConstantExpression>(Value::BIGINT(1)));
326346 }
326347 }
326348
326349 auto logical_projection =
326350 make_uniq<LogicalProjection>(optimizer.binder.GenerateTableIndex(), std::move(proj_exprs));
326351 logical_projection->children.push_back(std::move(op));
326352 logical_projection->ResolveOperatorTypes();
326353
326354 return unique_ptr<LogicalOperator>(std::move(logical_projection));
326355}

◆ GenerateAggregatePayload()

vector< unique_ptr< Expression > > duckdb::TopNWindowElimination::GenerateAggregatePayload ( const vector< ColumnBinding > & bindings,
const LogicalWindow & window,
map< idx_t, idx_t > & group_idxs )
private
326480 {
326481 vector<unique_ptr<Expression>> aggregate_args;
326482 aggregate_args.reserve(bindings.size());
326483
326484 window.children[0]->ResolveOperatorTypes();
326485 const auto &window_child_types = window.children[0]->types;
326486 const auto window_child_bindings = window.children[0]->GetColumnBindings();
326487 auto &window_expr = window.expressions[0]->Cast<BoundWindowExpression>();
326488
326489 // Remember order of group columns to recreate that order in new bindings later
326490 column_binding_map_t<idx_t> group_bindings;
326491 for (idx_t i = 0; i < window_expr.partitions.size(); i++) {
326492 auto &expr = window_expr.partitions[i];
326493 VisitExpression(&expr);
326494 group_bindings[column_references.begin()->first] = i;
326495 column_references.clear();
326496 }
326497
326498 for (idx_t i = 0; i < bindings.size(); i++) {
326499 const auto &binding = bindings[i];
326500 const auto group_binding = group_bindings.find(binding);
326501 if (group_binding != group_bindings.end()) {
326502 group_idxs[i] = group_binding->second;
326503 continue;
326504 }
326505 if (binding.table_index == window.window_index) {
326506 continue;
326507 }
326508
326509 auto column_id = binding.ToString();
326510 if (window.children[0]->type == LogicalOperatorType::LOGICAL_PROJECTION) {
326511 // The column index points to the correct column binding
326512 aggregate_args.push_back(
326513 make_uniq<BoundColumnRefExpression>(column_id, window_child_types[binding.column_index], binding));
326514 } else {
326515 // The child operator could have multiple or no table indexes. Therefore, we must find the right type first
326516 const auto child_column_idx =
326517 static_cast<idx_t>(std::find(window_child_bindings.begin(), window_child_bindings.end(), binding) -
326518 window_child_bindings.begin());
326519 aggregate_args.push_back(
326520 make_uniq<BoundColumnRefExpression>(column_id, window_child_types[child_column_idx], binding));
326521 }
326522 }
326523
326524 if (aggregate_args.size() == 1) {
326525 // If we only project the aggregate value itself, we do not need it as an arg
326526 VisitExpression(&window_expr.orders[0].expression);
326527 if (column_references.size() != 1) {
326528 column_references.clear();
326529 return aggregate_args;
326530 }
326531 const auto aggregate_value_binding = column_references.begin()->first;
326532 column_references.clear();
326533
326534 if (window_expr.orders[0].expression->type == ExpressionType::BOUND_COLUMN_REF &&
326535 aggregate_args[0]->Cast<BoundColumnRefExpression>().binding == aggregate_value_binding) {
326536 return {};
326537 }
326538 }
326539
326540 return aggregate_args;
326541}

◆ TraverseProjectionBindings()

bool duckdb::TopNWindowElimination::TraverseProjectionBindings ( const vector< ColumnBinding > & old_bindings,
reference< LogicalOperator > & op,
vector< ColumnBinding > & new_bindings )
private
326545 {
326546 new_bindings = old_bindings;
326547
326548 // Traverse child projections to retrieve projections on window output
326549 while (op.get().type == LogicalOperatorType::LOGICAL_PROJECTION) {
326550 auto &projection = op.get().Cast<LogicalProjection>();
326551
326552 for (idx_t i = 0; i < new_bindings.size(); i++) {
326553 auto &new_binding = new_bindings[i];
326554 D_ASSERT(new_binding.table_index == projection.table_index);
326555 VisitExpression(&projection.expressions[new_binding.column_index]);
326556 if (column_references.size() != 1) {
326557 column_references.clear();
326558 return false;
326559 }
326560 new_binding = column_references.begin()->first;
326561 column_references.clear();
326562 }
326563 op = *op.get().children[0];
326564 }
326565
326566 return true;
326567}

◆ CreateAggregateExpression()

unique_ptr< Expression > duckdb::TopNWindowElimination::CreateAggregateExpression ( vector< unique_ptr< Expression > > aggregate_params,
bool requires_arg,
const TopNWindowEliminationParameters & params ) const
private
326130 {
326131 auto &catalog = Catalog::GetSystemCatalog(context);
326132 FunctionBinder function_binder(context);
326133
326134 // If the value column can be null, we must use the nulls_last function to follow null ordering semantics
326135 const bool change_to_arg = !requires_arg && params.can_be_null && params.limit > 1;
326136 if (change_to_arg) {
326137 // Copy value as argument
326138 aggregate_params.insert(aggregate_params.begin() + 1, aggregate_params[0]->Copy());
326139 }
326140
326141 D_ASSERT(params.order_type == OrderType::ASCENDING || params.order_type == OrderType::DESCENDING);
326142 string fun_name = requires_arg || change_to_arg ? "arg_" : "";
326143 fun_name += params.order_type == OrderType::ASCENDING ? "min" : "max";
326144 fun_name += params.can_be_null && (requires_arg || change_to_arg) ? "_nulls_last" : "";
326145
326146 auto &fun_entry = catalog.GetEntry<AggregateFunctionCatalogEntry>(context, DEFAULT_SCHEMA, fun_name);
326147 const auto fun = fun_entry.functions.GetFunctionByArguments(context, ExtractReturnTypes(aggregate_params));
326148 return function_binder.BindAggregateFunction(fun, std::move(aggregate_params));
326149}

◆ CreateRowNumberGenerator()

unique_ptr< Expression > duckdb::TopNWindowElimination::CreateRowNumberGenerator ( unique_ptr< Expression > aggregate_column_ref) const
private
326209 {
326210 // Create unnest(generate_series(1, array_length(column_ref, 1))) function to generate row ids
326211 FunctionBinder function_binder(context);
326212 auto &catalog = Catalog::GetSystemCatalog(context);
326213
326214 // array_length
326215 auto &array_length_entry = catalog.GetEntry<ScalarFunctionCatalogEntry>(context, DEFAULT_SCHEMA, "array_length");
326216 vector<unique_ptr<Expression>> array_length_exprs;
326217 array_length_exprs.push_back(std::move(aggregate_column_ref));
326218 array_length_exprs.push_back(make_uniq<BoundConstantExpression>(1));
326219
326220 const auto array_length_fun = array_length_entry.functions.GetFunctionByArguments(
326221 context, {array_length_exprs[0]->return_type, array_length_exprs[1]->return_type});
326222 auto bound_array_length_fun = function_binder.BindScalarFunction(array_length_fun, std::move(array_length_exprs));
326223
326224 // generate_series
326225 auto &generate_series_entry =
326226 catalog.GetEntry<ScalarFunctionCatalogEntry>(context, DEFAULT_SCHEMA, "generate_series");
326227
326228 vector<unique_ptr<Expression>> generate_series_exprs;
326229 generate_series_exprs.push_back(make_uniq<BoundConstantExpression>(1));
326230 generate_series_exprs.push_back(std::move(bound_array_length_fun));
326231
326232 const auto generate_series_fun = generate_series_entry.functions.GetFunctionByArguments(
326233 context, {generate_series_exprs[0]->return_type, generate_series_exprs[1]->return_type});
326234 auto bound_generate_series_fun =
326235 function_binder.BindScalarFunction(generate_series_fun, std::move(generate_series_exprs));
326236
326237 // unnest
326238 auto unnest_row_number_expr = make_uniq<BoundUnnestExpression>(LogicalType::BIGINT);
326239 unnest_row_number_expr->alias = "row_number";
326240 unnest_row_number_expr->child = std::move(bound_generate_series_fun);
326241
326242 return unique_ptr<Expression>(std::move(unnest_row_number_expr));
326243}

◆ AddStructExtractExprs()

void duckdb::TopNWindowElimination::AddStructExtractExprs ( vector< unique_ptr< Expression > > & exprs,
const LogicalType & struct_type,
const unique_ptr< BoundColumnRefExpression > & aggregate_column_ref ) const
private
326285 {
326286 FunctionBinder function_binder(context);
326287 auto &catalog = Catalog::GetSystemCatalog(context);
326288 auto &struct_extract_entry =
326289 catalog.GetEntry<ScalarFunctionCatalogEntry>(context, DEFAULT_SCHEMA, "struct_extract");
326290 const auto struct_extract_fun =
326291 struct_extract_entry.functions.GetFunctionByArguments(context, {struct_type, LogicalType::VARCHAR});
326292
326293 const auto &child_types = StructType::GetChildTypes(struct_type);
326294 for (idx_t i = 0; i < child_types.size(); i++) {
326295 const auto &alias = child_types[i].first;
326296
326297 vector<unique_ptr<Expression>> fun_args(2);
326298 fun_args[0] = aggregate_column_ref->Copy();
326299 fun_args[1] = make_uniq<BoundConstantExpression>(alias);
326300
326301 auto bound_function = function_binder.BindScalarFunction(struct_extract_fun, std::move(fun_args));
326302 bound_function->alias = alias;
326303 exprs.push_back(std::move(bound_function));
326304 }
326305}

◆ UpdateTopmostBindings()

unique_ptr< LogicalOperator > duckdb::TopNWindowElimination::UpdateTopmostBindings ( idx_t window_idx,
unique_ptr< LogicalOperator > op,
const vector< LogicalType > & types,
const map< idx_t, idx_t > & group_idxs,
const vector< ColumnBinding > & topmost_bindings,
vector< ColumnBinding > & new_bindings,
ColumnBindingReplacer & replacer )
private
326573 {
326574 // The top-most operator's column order is:
326575 // [projected groups][aggregate args/value][row number]
326576 // Now set the new bindings according to this order and remember replacements in replacer
326577 D_ASSERT(topmost_bindings.size() == new_bindings.size());
326578 set<idx_t> row_id_binding_idxs;
326579
326580 const idx_t group_table_idx = GetGroupIdx(op);
326581 const idx_t aggregate_table_idx = GetAggregateIdx(op);
326582
326583 // Project the group columns
326584 const auto compact_group_columns = group_table_idx == aggregate_table_idx;
326585 map<idx_t, idx_t> compact_group_projection_idxs;
326586 if (compact_group_columns) {
326587 set<idx_t> ordered_group_projection_idxs;
326588 for (const auto &group_idx : group_idxs) {
326589 ordered_group_projection_idxs.insert(group_idx.second);
326590 }
326591 idx_t compact_idx = 0;
326592 for (const auto group_projection_idx : ordered_group_projection_idxs) {
326593 compact_group_projection_idxs[group_projection_idx] = compact_idx++;
326594 }
326595 }
326596 idx_t current_column_idx = 0;
326597 for (auto group_idx : group_idxs) {
326598 const auto group_referencing_idx = group_idx.first;
326599 const auto column_idx = (compact_group_columns && op->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN)
326600 ? compact_group_projection_idxs[group_idx.second]
326601 : group_idx.second;
326602 new_bindings[group_referencing_idx].table_index = group_table_idx;
326603 new_bindings[group_referencing_idx].column_index = column_idx;
326604
326605 current_column_idx++;
326606 }
326607
326608 if (!compact_group_columns) {
326609 // If the topmost operator is an aggregate, the table indexes are different, and we start back from 0
326610 current_column_idx = 0;
326611 }
326612 if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) {
326613 // We do not have an aggregate index, so we need to set an offset to hit the correct columns
326614 current_column_idx = TraverseAndFindAggregateOffset(op->children[1]);
326615 }
326616
326617 // Project the args/value
326618 for (idx_t i = 0; i < new_bindings.size(); i++) {
326619 auto &binding = new_bindings[i];
326620 if (group_idxs.find(i) != group_idxs.end()) {
326621 continue;
326622 }
326623 if (binding.table_index == window_idx) {
326624 row_id_binding_idxs.insert(i);
326625 continue;
326626 }
326627 binding.column_index = current_column_idx++;
326628 binding.table_index = aggregate_table_idx;
326629 }
326630
326631 // Project the row number
326632 for (const auto row_id_binding_idx : row_id_binding_idxs) {
326633 // Let all projections on row id point to the last output column
326634 auto &binding = new_bindings[row_id_binding_idx];
326635 binding = GetRowNumberColumnBinding(op);
326636 }
326637
326638 // If we are inside a SET operator, then replacing bindings is insufficient
326639 // because the set operators assume that all the inputs have the same schema.
326640 // To fix this, we have to inject another projection using the new bindings.
326641 replacer.replacement_bindings.reserve(new_bindings.size());
326642 const auto proj_table = optimizer.binder.GenerateTableIndex();
326643 vector<unique_ptr<Expression>> proj_exprs;
326644 for (idx_t i = 0; i < topmost_bindings.size(); ++i) {
326645 auto &new_binding = new_bindings[i];
326646 proj_exprs.push_back(make_uniq<BoundColumnRefExpression>(types[i], new_binding));
326647 new_binding.table_index = proj_table;
326648 new_binding.column_index = i;
326649 replacer.replacement_bindings.emplace_back(topmost_bindings[i], new_binding);
326650 }
326651
326652 auto set_projection = make_uniq<LogicalProjection>(proj_table, std::move(proj_exprs));
326653 set_projection->children.push_back(std::move(op));
326654 set_projection->ResolveOperatorTypes();
326655
326656 return unique_ptr<LogicalOperator>(std::move(set_projection));
326657}

◆ ExtractOptimizerParameters()

TopNWindowEliminationParameters duckdb::TopNWindowElimination::ExtractOptimizerParameters ( const LogicalWindow & window,
const LogicalFilter & filter,
const vector< ColumnBinding > & bindings,
vector< unique_ptr< Expression > > & aggregate_payload )
private
326662 {
326663 TopNWindowEliminationParameters params;
326664
326665 auto &filter_expr = filter.expressions[0]->Cast<BoundComparisonExpression>();
326666 auto &limit_expr = filter_expr.right;
326667 params.limit = limit_expr->Cast<BoundConstantExpression>().value.GetValue<int64_t>();
326668 if (filter_expr.GetExpressionType() == ExpressionType::COMPARE_LESSTHAN) {
326669 --params.limit;
326670 }
326671 params.include_row_number = BindingsReferenceRowNumber(bindings, window);
326672 params.payload_type = aggregate_payload.size() > 1 ? TopNPayloadType::STRUCT_PACK : TopNPayloadType::SINGLE_COLUMN;
326673 auto &window_expr = window.expressions[0]->Cast<BoundWindowExpression>();
326674 params.order_type = window_expr.orders[0].type;
326675
326676 VisitExpression(&window_expr.orders[0].expression);
326677 if (params.payload_type == TopNPayloadType::SINGLE_COLUMN && !aggregate_payload.empty()) {
326678 VisitExpression(&aggregate_payload[0]);
326679 }
326680 for (const auto &column_ref : column_references) {
326681 const auto &column_stats = stats->find(column_ref.first);
326682 if (column_stats == stats->end() || column_stats->second->CanHaveNull()) {
326683 params.can_be_null = true;
326684 break;
326685 }
326686 }
326687 column_references.clear();
326688
326689 return params;
326690}

◆ TryPrepareLateMaterialization()

unique_ptr< LogicalOperator > duckdb::TopNWindowElimination::TryPrepareLateMaterialization ( const LogicalWindow & window,
vector< unique_ptr< Expression > > & args )
private
326887 {
326888 vector<idx_t> lhs_projections;
326889 vector<reference<LogicalOperator>> stack;
326890 bool use_late_materialization = CanUseLateMaterialization(window, args, lhs_projections, stack);
326891 if (!use_late_materialization) {
326892 return nullptr;
326893 }
326894
326895 D_ASSERT(stack.back().get().type == LogicalOperatorType::LOGICAL_GET);
326896 auto &rhs_get = stack.back().get().Cast<LogicalGet>();
326897 auto lhs = ConstructLHS(rhs_get, lhs_projections);
326898
326899 const auto rhs_rowid_column_idxs = rhs_get.function.get_row_id_columns(context, rhs_get.bind_data.get());
326900 if (rhs_rowid_column_idxs.size() >= args.size()) {
326901 // Only use late materializtion if we can reduce the number of args
326902 return nullptr;
326903 }
326904
326905 vector<TableColumn> rhs_rowid_columns;
326906 for (const auto &col_idx : rhs_rowid_column_idxs) {
326907 rhs_rowid_columns.push_back(rhs_get.virtual_columns[col_idx]);
326908 }
326909 auto rhs_rowid_idxs =
326910 LateMaterializationHelper::GetOrInsertRowIds(rhs_get, rhs_rowid_column_idxs, rhs_rowid_columns);
326911
326912 // Add rowid column to the operators on the right-hand side
326913 idx_t last_table_idx = rhs_get.table_index;
326914
326915 // Add rowid projections to the query tree on the right-hand side
326916 for (auto stack_it = std::next(stack.rbegin()); stack_it != stack.rend(); ++stack_it) {
326917 auto &op = stack_it->get();
326918
326919 switch (op.type) {
326920 case LogicalOperatorType::LOGICAL_PROJECTION: {
326921 for (idx_t i = 0; i < rhs_rowid_columns.size(); i++) {
326922 auto &rowid_column = rhs_rowid_columns[i];
326923 op.expressions.push_back(make_uniq<BoundColumnRefExpression>(
326924 rowid_column.name, rowid_column.type, ColumnBinding {last_table_idx, rhs_rowid_idxs[i]}));
326925 rhs_rowid_idxs[i] = op.expressions.size() - 1;
326926 }
326927 last_table_idx = op.GetTableIndex()[0];
326928 break;
326929 }
326930 case LogicalOperatorType::LOGICAL_FILTER: {
326931 if (op.HasProjectionMap()) {
326932 auto &filter = op.Cast<LogicalFilter>();
326933 for (const auto rowid_idx : rhs_rowid_idxs) {
326934 // The rowid_idx is the index into the rhs_get.column_ids,
326935 // not the index of the rhs_get schema.
326936 auto schema_idx = rowid_idx;
326937 if (last_table_idx == rhs_get.table_index && !rhs_get.projection_ids.empty()) {
326938 for (schema_idx = 0; schema_idx < rhs_get.projection_ids.size(); ++schema_idx) {
326939 if (rhs_get.projection_ids[schema_idx] == rowid_idx) {
326940 break;
326941 }
326942 }
326943 }
326944 filter.projection_map.push_back(schema_idx);
326945 }
326946 }
326947 break;
326948 }
326949 case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: {
326950 if (op.HasProjectionMap()) {
326951 auto &join = op.Cast<LogicalComparisonJoin>();
326952 auto &op_child = std::prev(stack_it)->get();
326953
326954 auto &projection_map = RefersToSameObject(op_child, *join.children[0]) ? join.left_projection_map
326955 : join.right_projection_map;
326956 for (const auto rowid_idx : rhs_rowid_idxs) {
326957 projection_map.push_back(rowid_idx);
326958 }
326959 }
326960 break;
326961 }
326962 default:
326963 throw InternalException("Unsupported operator in late materialization right-hand side.");
326964 }
326965 }
326966
326967 // Change args to project rowid
326968 args.clear();
326969 for (idx_t i = 0; i < rhs_rowid_columns.size(); i++) {
326970 args.push_back(make_uniq<BoundColumnRefExpression>(rhs_rowid_columns[i].name, rhs_rowid_columns[i].type,
326971 ColumnBinding {last_table_idx, rhs_rowid_idxs[i]}));
326972 }
326973
326974 return lhs;
326975}
cv::String join(const cv::String &base, const cv::String &path)
bool RefersToSameObject(const reference< T > &a, const reference< T > &b)
Returns whether or not two reference wrappers refer to the same object.
Definition duckdb.hpp:2191

◆ ConstructLHS()

unique_ptr< LogicalOperator > duckdb::TopNWindowElimination::ConstructLHS ( LogicalGet & rhs,
vector< idx_t > & projections ) const
private
326977 {
326978 auto lhs_get = LateMaterializationHelper::CreateLHSGet(rhs, optimizer.binder);
326979 const auto lhs_rowid_column_idxs = lhs_get->function.get_row_id_columns(context, lhs_get->bind_data.get());
326980 vector<TableColumn> lhs_rowid_columns;
326981 for (const auto &col_idx : lhs_rowid_column_idxs) {
326982 lhs_rowid_columns.push_back(rhs.virtual_columns[col_idx]);
326983 }
326984
326985 const auto lhs_rowid_idxs =
326986 LateMaterializationHelper::GetOrInsertRowIds(*lhs_get, lhs_rowid_column_idxs, lhs_rowid_columns);
326987
326988 if (!projections.empty()) {
326989 for (auto rowid_idx : lhs_rowid_idxs) {
326990 projections.push_back(rowid_idx);
326991 }
326992 lhs_get->ResolveOperatorTypes();
326993
326994 vector<unique_ptr<Expression>> projs;
326995 projs.reserve(projections.size());
326996 const auto &column_ids = lhs_get->GetColumnIds();
326997 for (auto column_idx : projections) {
326998 D_ASSERT(column_idx < column_ids.size());
326999 const auto &column_type = lhs_get->GetColumnType(column_ids[column_idx]);
327000 projs.push_back(
327001 make_uniq<BoundColumnRefExpression>(column_type, ColumnBinding {lhs_get->table_index, column_idx}));
327002 }
327003 auto projection = make_uniq<LogicalProjection>(optimizer.binder.GenerateTableIndex(), std::move(projs));
327004 projection->children.push_back(std::move(lhs_get));
327005 return unique_ptr<LogicalOperator>(std::move(projection));
327006 }
327007 return unique_ptr<LogicalOperator>(std::move(lhs_get));
327008}

◆ ConstructJoin()

unique_ptr< LogicalOperator > duckdb::TopNWindowElimination::ConstructJoin ( unique_ptr< LogicalOperator > lhs,
unique_ptr< LogicalOperator > rhs,
idx_t rhs_rowid_idx,
const TopNWindowEliminationParameters & params )
staticprivate
327013 {
327014 lhs->ResolveOperatorTypes();
327015
327016 const idx_t rowid_column_count =
327017 params.include_row_number ? rhs->types.size() - (aggregate_offset + 1) : rhs->types.size() - aggregate_offset;
327018 const idx_t rhs_binding_offset =
327019 rhs->type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY ? 0 : aggregate_offset;
327020
327021 auto join = make_uniq<LogicalComparisonJoin>(JoinType::SEMI);
327022 for (idx_t i = 0; i < rowid_column_count; i++) {
327023 const idx_t lhs_rowid_idx = lhs->types.size() - (rowid_column_count - i);
327024 const idx_t rhs_rowid_idx = rhs_binding_offset + i;
327025 const auto &alias = GetLHSRowIdColumnName(lhs, lhs_rowid_idx);
327026
327027 JoinCondition condition;
327028 condition.comparison = ExpressionType::COMPARE_EQUAL;
327029 condition.left = make_uniq<BoundColumnRefExpression>(alias, lhs->types[lhs_rowid_idx],
327030 ColumnBinding {lhs->GetTableIndex()[0], lhs_rowid_idx});
327031 condition.right = make_uniq<BoundColumnRefExpression>(alias, rhs->types[aggregate_offset + i],
327032 ColumnBinding {GetAggregateIdx(rhs), rhs_rowid_idx});
327033 join->conditions.push_back(std::move(condition));
327034 }
327035
327036 if (params.include_row_number) {
327037 // Add row_number to join result
327038 join->join_type = JoinType::INNER;
327039 join->right_projection_map.push_back(rhs->types.size() - 1);
327040 }
327041
327042 // Remove the row_numbers from the LHS projection map
327043 for (idx_t i = 0; i < lhs->types.size() - rowid_column_count; ++i) {
327044 join->left_projection_map.emplace_back(i);
327045 }
327046
327047 join->children.push_back(std::move(lhs));
327048 join->children.push_back(std::move(rhs));
327049
327050 return unique_ptr<LogicalOperator>(std::move(join));
327051}
GOpaque< Size > size(const GMat &src)

◆ CanUseLateMaterialization()

bool duckdb::TopNWindowElimination::CanUseLateMaterialization ( const LogicalWindow & window,
vector< unique_ptr< Expression > > & args,
vector< idx_t > & projections,
vector< reference< LogicalOperator > > & stack )
private
326709 {
326710 auto &window_expr = window.expressions[0]->Cast<BoundWindowExpression>();
326711 vector<ColumnBinding> projections(window_expr.partitions.size() + args.size());
326712
326713 // Build a projection list for an LHS table scan to recreate the column order of an aggregate with struct packing
326714 for (idx_t i = 0; i < window_expr.partitions.size(); i++) {
326715 auto &partition = window_expr.partitions[i];
326716 if (!ExtractSingleBinding(&partition, projections[i])) {
326717 return false;
326718 }
326719 }
326720 for (idx_t i = 0; i < args.size(); i++) {
326721 auto &arg = args[i];
326722 if (!ExtractSingleBinding(&arg, projections[window_expr.partitions.size() + i])) {
326723 return false;
326724 }
326725 }
326726
326727 reference<LogicalOperator> op = *window.children[0];
326728
326729 // Traverse projections to a single table scan
326730 while (!op.get().children.empty()) {
326731 stack.push_back(op);
326732 switch (op.get().type) {
326733 case LogicalOperatorType::LOGICAL_PROJECTION: {
326734 auto &projection = op.get().Cast<LogicalProjection>();
326735 for (idx_t i = 0; i < projections.size(); i++) {
326736 if (projection.table_index != projections[i].table_index) {
326737 return false;
326738 }
326739 const idx_t projection_idx = projections[i].column_index;
326740 if (projection_idx >= projection.expressions.size()) {
326741 return false;
326742 }
326743 if (!ExtractSingleBinding(&projection.expressions[projection_idx], projections[i])) {
326744 return false;
326745 }
326746 }
326747 op = *op.get().children[0];
326748 break;
326749 }
326750 case LogicalOperatorType::LOGICAL_FILTER: {
326751 op = *op.get().children[0];
326752 break;
326753 }
326754 case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: {
326755 auto &join = op.get().Cast<LogicalComparisonJoin>();
326756 if (join.join_type != JoinType::INNER && join.join_type != JoinType::SEMI &&
326757 join.join_type != JoinType::ANTI) {
326758 return false;
326759 }
326760
326761 // If there is a join, we only allow late materialization if the projected output stems from a single table.
326762 // However, we allow replacing references to join columns as they are equal to the other side by condition.
326763 column_binding_map_t<ColumnBinding> replaceable_bindings;
326764 for (auto &condition : join.conditions) {
326765 if (condition.comparison != ExpressionType::COMPARE_EQUAL) {
326766 return false;
326767 }
326768 ColumnBinding left_binding;
326769 if (!ExtractSingleBinding(&condition.left, left_binding, true)) {
326770 return false;
326771 }
326772 ColumnBinding right_binding;
326773 if (!ExtractSingleBinding(&condition.right, right_binding, true)) {
326774 return false;
326775 }
326776
326777 replaceable_bindings[left_binding] = right_binding;
326778 replaceable_bindings[right_binding] = left_binding;
326779 }
326780
326781 auto left_column_bindings = join.children[0]->GetColumnBindings();
326782 auto right_column_bindings = join.children[1]->GetColumnBindings();
326783 auto lidxs = join.children[0]->GetTableIndex();
326784 auto ridxs = join.children[1]->GetTableIndex();
326785 if (lidxs.size() != 1 || ridxs.size() != 1) {
326786 return false;
326787 }
326788 auto left_idx = lidxs[0];
326789 auto right_idx = ridxs[0];
326790
326791 bool all_left_replaceable = true;
326792 bool all_right_replaceable = true;
326793 for (idx_t i = 0; i < projections.size(); i++) {
326794 const auto &projection = projections[i];
326795 if (projection.table_index != left_idx && projection.table_index != right_idx) {
326796 return false;
326797 }
326798 if (projection.table_index == left_idx && projection.column_index >= left_column_bindings.size()) {
326799 return false;
326800 }
326801 if (projection.table_index == right_idx && projection.column_index >= right_column_bindings.size()) {
326802 return false;
326803 }
326804 auto &column_binding = projection.table_index == left_idx
326805 ? left_column_bindings[projection.column_index]
326806 : right_column_bindings[projection.column_index];
326807 if (replaceable_bindings.find(column_binding) == replaceable_bindings.end()) {
326808 if (column_binding.table_index == left_idx) {
326809 all_left_replaceable = false;
326810 } else {
326811 all_right_replaceable = false;
326812 }
326813 }
326814 }
326815
326816 if (!all_left_replaceable && !all_right_replaceable) {
326817 // We cannot use late materialization by scanning a single table.
326818 return false;
326819 }
326820
326821 idx_t replace_table_idx = all_right_replaceable ? right_idx : left_idx;
326822 for (idx_t i = 0; i < projections.size(); i++) {
326823 const auto projection_idx = projections[i];
326824 if (projection_idx.table_index != left_idx && projection_idx.table_index != right_idx) {
326825 return false;
326826 }
326827 if (projection_idx.table_index == left_idx &&
326828 projection_idx.column_index >= left_column_bindings.size()) {
326829 return false;
326830 }
326831 if (projection_idx.table_index == right_idx &&
326832 projection_idx.column_index >= right_column_bindings.size()) {
326833 return false;
326834 }
326835 auto &column_binding = projection_idx.table_index == left_idx
326836 ? left_column_bindings[projection_idx.column_index]
326837 : right_column_bindings[projection_idx.column_index];
326838 if (column_binding.table_index == replace_table_idx) {
326839 projections[i] = replaceable_bindings[column_binding];
326840 }
326841 }
326842
326843 if (all_right_replaceable) {
326844 op = *op.get().children[0];
326845 } else {
326846 op = *op.get().children[1];
326847 }
326848 break;
326849 }
326850 default: {
326851 return false;
326852 }
326853 }
326854 }
326855 stack.push_back(op);
326856
326857 if (op.get().type != LogicalOperatorType::LOGICAL_GET) {
326858 // Alternative verification can produce leaf operators without children that are not logical gets.
326859 // In that case, late materialization is not applicable and we should gracefully fall back.
326860 return false;
326861 }
326862 auto &logical_get = op.get().Cast<LogicalGet>();
326863 if (!logical_get.function.late_materialization || !logical_get.function.get_row_id_columns) {
326864 return false;
326865 }
326866
326867 const auto rowid_column_idxs = logical_get.function.get_row_id_columns(context, logical_get.bind_data.get());
326868 for (const auto &col_idx : rowid_column_idxs) {
326869 auto entry = logical_get.virtual_columns.find(col_idx);
326870 if (entry == logical_get.virtual_columns.end()) {
326871 return false;
326872 }
326873 }
326874 // Check if we need the projection map
326875 for (idx_t i = 0; i < projections.size(); i++) {
326876 if (projections[i].column_index != i) {
326877 for (auto &proj : projections) {
326878 lhs_projections.push_back(proj.column_index);
326879 }
326880 break;
326881 }
326882 }
326883 return true;
326884}
internal::named_arg< T, Char > arg(const S &name, const T &arg)
Definition duckdb.cpp:16242

◆ ExtractSingleBinding()

bool duckdb::TopNWindowElimination::ExtractSingleBinding ( unique_ptr< Expression > * expr,
ColumnBinding & binding,
bool require_direct_column_ref = false )
private
326693 {
326694 if (require_direct_column_ref && expr->get()->type != ExpressionType::BOUND_COLUMN_REF) {
326695 return false;
326696 }
326697 VisitExpression(expr);
326698 if (column_references.size() != 1) {
326699 column_references.clear();
326700 return false;
326701 }
326702 binding = column_references.begin()->first;
326703 column_references.clear();
326704 return true;
326705}

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