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

Public Member Functions

 BaseSelectBinder (Binder &binder, ClientContext &context, BoundSelectNode &node, BoundGroupInformation &info)
bool BoundAggregates ()
void ResetBindings ()
Public Member Functions inherited from duckdb::ExpressionBinder
 ExpressionBinder (Binder &binder, ClientContext &context, bool replace_binder=false)
virtual bool TryResolveAliasReference (ColumnRefExpression &colref, idx_t depth, bool root_expression, BindResult &result, unique_ptr< ParsedExpression > &expr_ptr)
virtual bool DoesColumnAliasExist (const ColumnRefExpression &colref)
unique_ptr< Expression > Bind (unique_ptr< ParsedExpression > &expr, optional_ptr< LogicalType > result_type=nullptr, bool root_expression=true)
bool HasBoundColumns ()
 Returns whether or not any columns have been bound by the expression binder.
const vector< BoundColumnReferenceInfo > & GetBoundColumns ()
void SetCatalogLookupCallback (catalog_entry_callback_t callback)
ErrorData Bind (unique_ptr< ParsedExpression > &expr, idx_t depth, bool root_expression=false)
unique_ptr< ParsedExpression > CreateStructExtract (unique_ptr< ParsedExpression > base, const string &field_name)
 Returns the STRUCT_EXTRACT operator expression.
unique_ptr< ParsedExpression > CreateStructPack (ColumnRefExpression &col_ref)
 Returns a STRUCT_PACK function expression.
BindResult BindQualifiedColumnName (ColumnRefExpression &colref, const string &table_name)
unique_ptr< ParsedExpression > QualifyColumnName (const ParsedExpression &expr, const string &column_name, ErrorData &error)
 Returns a qualified column reference from a column name.
unique_ptr< ParsedExpression > QualifyColumnNameWithManyDots (ColumnRefExpression &col_ref, ErrorData &error)
 Returns a qualified column reference from a column reference with column_names.size() > 2.
virtual unique_ptr< ParsedExpression > QualifyColumnName (ColumnRefExpression &col_ref, ErrorData &error)
 Returns a qualified column reference from a column reference.
void QualifyColumnNamesInLambda (FunctionExpression &function, vector< unordered_set< string > > &lambda_params)
 Enables special-handling of lambda parameters by tracking them in the lambda_params vector.
void QualifyColumnNames (unique_ptr< ParsedExpression > &expr, vector< unordered_set< string > > &lambda_params, const bool within_function_expression=false)
BindResult BindCorrelatedColumns (unique_ptr< ParsedExpression > &expr, ErrorData error_message)
void BindChild (unique_ptr< ParsedExpression > &expr, idx_t depth, ErrorData &error)
void ReplaceMacroParameters (unique_ptr< ParsedExpression > &expr, vector< unordered_set< string > > &lambda_params)
void ReplaceMacroParametersInLambda (FunctionExpression &function, vector< unordered_set< string > > &lambda_params)

Protected Member Functions

BindResult BindExpression (unique_ptr< ParsedExpression > &expr_ptr, idx_t depth, bool root_expression=false) override
BindResult BindAggregate (FunctionExpression &expr, AggregateFunctionCatalogEntry &function, idx_t depth) override
BindResult BindGroupingFunction (OperatorExpression &op, idx_t depth) override
virtual BindResult BindWindow (WindowExpression &expr, idx_t depth)
 Binds a WINDOW expression and returns the result.
virtual BindResult BindColumnRef (unique_ptr< ParsedExpression > &expr_ptr, idx_t depth, bool root_expression)
idx_t TryBindGroup (ParsedExpression &expr)
BindResult BindGroup (ParsedExpression &expr, idx_t depth, idx_t group_index)
Protected Member Functions inherited from duckdb::ExpressionBinder
BindResult BindExpression (BetweenExpression &expr, idx_t depth)
BindResult BindExpression (CaseExpression &expr, idx_t depth)
BindResult BindExpression (CollateExpression &expr, idx_t depth)
BindResult BindExpression (CastExpression &expr, idx_t depth)
BindResult BindExpression (ColumnRefExpression &expr, idx_t depth, bool root_expression, unique_ptr< ParsedExpression > &expr_ptr)
BindResult BindExpression (LambdaRefExpression &expr, idx_t depth)
BindResult BindExpression (ComparisonExpression &expr, idx_t depth)
BindResult BindExpression (ConjunctionExpression &expr, idx_t depth)
BindResult BindExpression (ConstantExpression &expr, idx_t depth)
BindResult BindExpression (FunctionExpression &expr, idx_t depth, unique_ptr< ParsedExpression > &expr_ptr)
BindResult BindExpression (TypeExpression &expr, idx_t depth)
BindResult BindExpression (LambdaExpression &expr, idx_t depth, const vector< LogicalType > &function_child_types, optional_ptr< bind_lambda_function_t > bind_lambda_function)
BindResult BindExpression (OperatorExpression &expr, idx_t depth)
BindResult BindExpression (ParameterExpression &expr, idx_t depth)
BindResult BindExpression (SubqueryExpression &expr, idx_t depth)
BindResult BindPositionalReference (unique_ptr< ParsedExpression > &expr, idx_t depth, bool root_expression)
void TransformCapturedLambdaColumn (unique_ptr< Expression > &original, unique_ptr< Expression > &replacement, BoundLambdaExpression &bound_lambda_expr, const optional_ptr< bind_lambda_function_t > bind_lambda_function, const vector< LogicalType > &function_child_types)
void CaptureLambdaColumns (BoundLambdaExpression &bound_lambda_expr, unique_ptr< Expression > &expr, const optional_ptr< bind_lambda_function_t > bind_lambda_function, const vector< LogicalType > &function_child_types)
virtual unique_ptr< ParsedExpression > GetSQLValueFunction (const string &column_name)
LogicalType ResolveOperatorType (OperatorExpression &op, vector< unique_ptr< Expression > > &children)
LogicalType ResolveCoalesceType (OperatorExpression &op, vector< unique_ptr< Expression > > &children)
LogicalType ResolveNotType (OperatorExpression &op, vector< unique_ptr< Expression > > &children)
BindResult BindUnsupportedExpression (ParsedExpression &expr, idx_t depth, const string &message)
optional_ptr< CatalogEntry > BindAndQualifyFunction (FunctionExpression &function, bool allow_throw)
virtual BindResult BindFunction (FunctionExpression &expr, ScalarFunctionCatalogEntry &function, idx_t depth)
virtual BindResult BindLambdaFunction (FunctionExpression &expr, ScalarFunctionCatalogEntry &function, idx_t depth)
virtual BindResult BindUnnest (FunctionExpression &expr, idx_t depth, bool root_expression)
virtual BindResult BindMacro (FunctionExpression &expr, ScalarMacroCatalogEntry &macro, idx_t depth, unique_ptr< ParsedExpression > &expr_ptr)
void UnfoldMacroExpression (FunctionExpression &function, ScalarMacroCatalogEntry &macro_func, unique_ptr< ParsedExpression > &expr, idx_t depth)
virtual string UnsupportedAggregateMessage ()
virtual string UnsupportedUnnestMessage ()
optional_ptr< CatalogEntry > GetCatalogEntry (const string &catalog, const string &schema, const EntryLookupInfo &lookup_info, OnEntryNotFound on_entry_not_found)
BindResult TryBindLambdaOrJson (FunctionExpression &function, idx_t depth, CatalogEntry &func, const LambdaSyntaxType syntax_type)
unique_ptr< ParsedExpression > QualifyColumnNameWithManyDotsInternal (ColumnRefExpression &col_ref, ErrorData &error, idx_t &struct_extract_start)
virtual void ThrowIfUnnestInLambda (const ColumnBinding &column_binding)

Protected Attributes

bool inside_window
bool bound_aggregate = false
BoundSelectNode & node
BoundGroupInformation & info
Protected Attributes inherited from duckdb::ExpressionBinder
Binder & binder
ClientContext & context
optional_ptr< ExpressionBinder > stored_binder
vector< BoundColumnReferenceInfo > bound_columns

Additional Inherited Members

Static Public Member Functions inherited from duckdb::ExpressionBinder
static bool IsPotentialAlias (const ColumnRefExpression &colref)
static void QualifyColumnNames (Binder &binder, unique_ptr< ParsedExpression > &expr)
 Entry point for qualifying the column references of the expression.
static void QualifyColumnNames (ExpressionBinder &binder, unique_ptr< ParsedExpression > &expr)
static bool PushCollation (ClientContext &context, unique_ptr< Expression > &source, const LogicalType &sql_type, CollationType type=CollationType::ALL_COLLATIONS)
static void TestCollation (ClientContext &context, const string &collation)
static void ExtractCorrelatedExpressions (Binder &binder, Expression &expr)
static bool ContainsNullType (const LogicalType &type)
static LogicalType ExchangeNullType (const LogicalType &type)
static bool ContainsType (const LogicalType &type, LogicalTypeId target)
static LogicalType ExchangeType (const LogicalType &type, LogicalTypeId target, LogicalType new_type)
static LogicalType GetExpressionReturnType (const Expression &expr)
static bool IsUnnestFunction (const string &function_name)
 Returns true if the function name is an alias for the UNNEST function.
Public Attributes inherited from duckdb::ExpressionBinder
LogicalType target_type
optional_ptr< DummyBinding > macro_binding
optional_ptr< vector< DummyBinding > > lambda_bindings

Detailed Description

The BaseSelectBinder is the base binder of the SELECT, HAVING and QUALIFY binders. It can bind aggregates and window functions.

Constructor & Destructor Documentation

◆ BaseSelectBinder()

duckdb::BaseSelectBinder::BaseSelectBinder ( Binder & binder,
ClientContext & context,
BoundSelectNode & node,
BoundGroupInformation & info )
377333 : ExpressionBinder(binder, context), inside_window(false), node(node), info(info) {
377334}

Member Function Documentation

◆ BoundAggregates()

bool duckdb::BaseSelectBinder::BoundAggregates ( )
inline
359442 {
359443 return bound_aggregate;
359444 }

◆ ResetBindings()

void duckdb::BaseSelectBinder::ResetBindings ( )
inline
359445 {
359446 this->bound_aggregate = false;
359447 this->bound_columns.clear();
359448 }

◆ BindExpression()

BindResult duckdb::BaseSelectBinder::BindExpression ( unique_ptr< ParsedExpression > & expr_ptr,
idx_t depth,
bool root_expression = false )
overrideprotectedvirtual

Bind the given expression. Unlike Bind(), this does not mute the given ParsedExpression. Exposed to be used from sub-binders that aren't subclasses of ExpressionBinder.

Reimplemented from duckdb::ExpressionBinder.

377336 {
377337 auto &expr = *expr_ptr;
377338 // check if the expression binds to one of the groups
377339 auto group_index = TryBindGroup(expr);
377340 if (group_index != DConstants::INVALID_INDEX) {
377341 return BindGroup(expr, depth, group_index);
377342 }
377343 switch (expr.GetExpressionClass()) {
377344 case ExpressionClass::COLUMN_REF:
377345 return BindColumnRef(expr_ptr, depth, root_expression);
377346 case ExpressionClass::DEFAULT:
377347 return BindResult(BinderException::Unsupported(expr, "SELECT clause cannot contain DEFAULT clause"));
377348 case ExpressionClass::WINDOW:
377349 return BindWindow(expr.Cast<WindowExpression>(), depth);
377350 default:
377351 return ExpressionBinder::BindExpression(expr_ptr, depth, root_expression);
377352 }
377353}
virtual BindResult BindWindow(WindowExpression &expr, idx_t depth)
Binds a WINDOW expression and returns the result.
Definition duckdb.cpp:363321
virtual BindResult BindExpression(unique_ptr< ParsedExpression > &expr_ptr, idx_t depth, bool root_expression=false)
Definition duckdb.cpp:378842
static constexpr const idx_t INVALID_INDEX
The value used to signify an invalid index entry.
Definition duckdb.hpp:1117
Here is the call graph for this function:

◆ BindAggregate()

BindResult duckdb::BaseSelectBinder::BindAggregate ( FunctionExpression & expr,
AggregateFunctionCatalogEntry & function,
idx_t depth )
overrideprotectedvirtual

Reimplemented from duckdb::ExpressionBinder.

359572 {
359573 // first bind the child of the aggregate expression (if any)
359574 this->bound_aggregate = true;
359575 unique_ptr<Expression> bound_filter;
359576 AggregateBinder aggregate_binder(binder, context);
359577 ErrorData error;
359578
359579 // Now we bind the filter (if any)
359580 if (aggr.filter) {
359581 aggregate_binder.BindChild(aggr.filter, 0, error);
359582 }
359583
359584 // Handle ordered-set aggregates by moving the single ORDER BY expression to the front of the children.
359585 // https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-ORDEREDSET-TABLE
359586 // We also have to handle ORDER BY in the argument list, so note how many arguments we should have
359587 // and only inject the ordering expression if there are too few.
359588 idx_t ordered_set_agg = 0;
359589 bool negate_fractions = false;
359590 if (aggr.order_bys && aggr.order_bys->orders.size() == 1) {
359591 const auto &func_name = aggr.function_name;
359592 if (func_name == "mode") {
359593 ordered_set_agg = 1;
359594 } else if (func_name == "quantile_cont" || func_name == "quantile_disc") {
359595 ordered_set_agg = 2;
359596
359597 auto &config = DBConfig::GetConfig(context);
359598 const auto &order = aggr.order_bys->orders[0];
359599 const auto sense = config.ResolveOrder(context, order.type);
359600 negate_fractions = (sense == OrderType::DESCENDING);
359601 }
359602 }
359603
359604 for (idx_t i = 0; i < aggr.children.size(); ++i) {
359605 auto &child = aggr.children[i];
359606 aggregate_binder.BindChild(child, 0, error);
359607 // We have to negate the fractions for PERCENTILE_XXXX DESC
359608 if (!error.HasError() && ordered_set_agg && i == aggr.children.size() - 1) {
359609 NegatePercentileFractions(context, child, negate_fractions);
359610 }
359611 }
359612
359613 // Bind the ORDER BYs, if any
359614 if (aggr.order_bys && !aggr.order_bys->orders.empty()) {
359615 for (auto &order : aggr.order_bys->orders) {
359616 if (order.expression->GetExpressionType() == ExpressionType::VALUE_CONSTANT) {
359617 auto &const_expr = order.expression->Cast<ConstantExpression>();
359618 if (!const_expr.value.type().IsIntegral()) {
359619 auto order_by_non_integer_literal = Settings::Get<OrderByNonIntegerLiteralSetting>(context);
359620 if (!order_by_non_integer_literal) {
359621 throw BinderException(
359622 *order.expression,
359623 "ORDER BY non-integer literal has no effect.\n* SET order_by_non_integer_literal=true to "
359624 "allow this behavior.\n\nPerhaps you misplaced ORDER BY; ORDER BY must appear "
359625 "after all regular arguments of the aggregate.");
359626 }
359627 }
359628 }
359629 aggregate_binder.BindChild(order.expression, 0, error);
359630 }
359631 }
359632
359633 if (error.HasError()) {
359634 // failed to bind child
359635 if (aggregate_binder.HasBoundColumns()) {
359636 for (idx_t i = 0; i < aggr.children.size(); i++) {
359637 // however, we bound columns!
359638 // that means this aggregation belongs to this node
359639 // check if we have to resolve any errors by binding with parent binders
359640 auto result = aggregate_binder.BindCorrelatedColumns(aggr.children[i], error);
359641 // if there is still an error after this, we could not successfully bind the aggregate
359642 if (result.HasError()) {
359643 result.error.Throw();
359644 }
359645 auto &bound_expr = BoundExpression::GetExpression(*aggr.children[i]);
359646 ExtractCorrelatedExpressions(binder, *bound_expr);
359647 }
359648 if (aggr.filter) {
359649 auto result = aggregate_binder.BindCorrelatedColumns(aggr.filter, error);
359650 // if there is still an error after this, we could not successfully bind the aggregate
359651 if (result.HasError()) {
359652 result.error.Throw();
359653 }
359654 auto &bound_expr = BoundExpression::GetExpression(*aggr.filter);
359655 ExtractCorrelatedExpressions(binder, *bound_expr);
359656 }
359657 if (aggr.order_bys && !aggr.order_bys->orders.empty()) {
359658 for (auto &order : aggr.order_bys->orders) {
359659 auto result = aggregate_binder.BindCorrelatedColumns(order.expression, error);
359660 if (result.HasError()) {
359661 result.error.Throw();
359662 }
359663 auto &bound_expr = BoundExpression::GetExpression(*order.expression);
359664 ExtractCorrelatedExpressions(binder, *bound_expr);
359665 }
359666 }
359667 } else {
359668 // we didn't bind columns, try again in children
359669 return BindResult(std::move(error));
359670 }
359671 } else if (depth > 0 && !aggregate_binder.HasBoundColumns()) {
359672 return BindResult("Aggregate with only constant parameters has to be bound in the root subquery");
359673 }
359674
359675 if (aggr.filter) {
359676 auto &child = BoundExpression::GetExpression(*aggr.filter);
359677 bound_filter = BoundCastExpression::AddCastToType(context, std::move(child), LogicalType::BOOLEAN);
359678 }
359679
359680 // all children bound successfully
359681 // extract the children and types
359682 vector<LogicalType> types;
359683 vector<LogicalType> arguments;
359684 vector<unique_ptr<Expression>> children;
359685
359686 if (ordered_set_agg) {
359687 const bool order_sensitive = (aggr.function_name == "mode");
359688 // Inject missing ordering arguments
359689 if (aggr.children.size() < ordered_set_agg) {
359690 for (auto &order : aggr.order_bys->orders) {
359691 auto &child = BoundExpression::GetExpression(*order.expression);
359692 types.push_back(child->return_type);
359693 arguments.push_back(child->return_type);
359694 if (order_sensitive) {
359695 children.push_back(child->Copy());
359696 } else {
359697 children.push_back(std::move(child));
359698 }
359699 }
359700 }
359701 if (!order_sensitive) {
359702 aggr.order_bys->orders.clear();
359703 }
359704 }
359705
359706 for (idx_t i = 0; i < aggr.children.size(); i++) {
359707 auto &child = BoundExpression::GetExpression(*aggr.children[i]);
359708 types.push_back(child->return_type);
359709 arguments.push_back(child->return_type);
359710 children.push_back(std::move(child));
359711 }
359712
359713 // bind the aggregate
359714 FunctionBinder function_binder(binder);
359715 auto best_function = function_binder.BindFunction(func.name, func.functions, types, error);
359716 if (!best_function.IsValid()) {
359717 error.AddQueryLocation(aggr);
359718 error.Throw();
359719 }
359720 // found a matching function!
359721 auto bound_function = func.functions.GetFunctionByOffset(best_function.GetIndex());
359722
359723 if (!bound_function.CanAggregate() && bound_function.CanWindow()) {
359724 auto msg = StringUtil::Format("Function '%s' can only be used as a window function", bound_function.name);
359725 error = BinderException(msg);
359726 error.AddQueryLocation(aggr);
359727 error.Throw();
359728 }
359729
359730 // Bind any sort columns, unless the aggregate is order-insensitive
359731 unique_ptr<BoundOrderModifier> order_bys;
359732 if (!aggr.order_bys->orders.empty()) {
359733 order_bys = make_uniq<BoundOrderModifier>();
359734 auto &config = DBConfig::GetConfig(context);
359735 for (auto &order : aggr.order_bys->orders) {
359736 auto &order_expr = BoundExpression::GetExpression(*order.expression);
359737 PushCollation(context, order_expr, order_expr->return_type);
359738 const auto sense = config.ResolveOrder(context, order.type);
359739 const auto null_order = config.ResolveNullOrder(context, sense, order.null_order);
359740 order_bys->orders.emplace_back(sense, null_order, std::move(order_expr));
359741 }
359742 }
359743
359744 // If the aggregate is DISTINCT then the ORDER BYs need to be functional dependencies of the arguments.
359745 if (aggr.distinct && order_bys) {
359746 bool in_args = true;
359747 for (const auto &order_by : order_bys->orders) {
359748 in_args &= IsFunctionallyDependent(order_by.expression, children);
359749 }
359750
359751 if (!in_args) {
359752 throw BinderException("In a DISTINCT aggregate, ORDER BY expressions must appear in the argument list");
359753 }
359754 }
359755
359756 auto aggregate =
359757 function_binder.BindAggregateFunction(bound_function, std::move(children), std::move(bound_filter),
359758 aggr.distinct ? AggregateType::DISTINCT : AggregateType::NON_DISTINCT);
359759 if (aggr.export_state) {
359760 aggregate = ExportAggregateFunction::Bind(std::move(aggregate));
359761 }
359762 aggregate->order_bys = std::move(order_bys);
359763
359764 // check for all the aggregates if this aggregate already exists
359765 idx_t aggr_index;
359766 auto entry = node.aggregate_map.find(*aggregate);
359767 if (entry == node.aggregate_map.end()) {
359768 // new aggregate: insert into aggregate list
359769 aggr_index = node.aggregates.size();
359770 node.aggregate_map[*aggregate] = aggr_index;
359771 node.aggregates.push_back(std::move(aggregate));
359772 } else {
359773 // duplicate aggregate: simplify refer to this aggregate
359774 aggr_index = entry->second;
359775 }
359776
359777 // now create a column reference referring to the aggregate
359778 auto colref = make_uniq<BoundColumnRefExpression>(
359779 aggr.GetAlias().empty() ? node.aggregates[aggr_index]->ToString() : aggr.GetAlias(),
359780 node.aggregates[aggr_index]->return_type, ColumnBinding(node.aggregate_index, aggr_index), depth);
359781 // move the aggregate expression into the set of bound aggregates
359782 return BindResult(std::move(colref));
359783}
static DUCKDB_API unique_ptr< Expression > AddCastToType(ClientContext &context, unique_ptr< Expression > expr, const LogicalType &target_type, bool try_cast=false)
Cast an expression to the specified SQL type if required.
Definition duckdb.cpp:375869
static string Format(const string fmt_str, ARGS... params)
Format a string using printf semantics.
Definition duckdb.hpp:4002
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ BindGroupingFunction()

BindResult duckdb::BaseSelectBinder::BindGroupingFunction ( OperatorExpression & op,
idx_t depth )
overrideprotectedvirtual

Reimplemented from duckdb::ExpressionBinder.

377386 {
377387 if (op.children.empty()) {
377388 throw InternalException("GROUPING requires at least one child");
377389 }
377390 if (node.groups.group_expressions.empty()) {
377391 return BindResult(BinderException(op, "GROUPING statement cannot be used without groups"));
377392 }
377393 if (op.children.size() >= 64) {
377394 return BindResult(BinderException(op, "GROUPING statement cannot have more than 64 groups"));
377395 }
377396 vector<idx_t> group_indexes;
377397 group_indexes.reserve(op.children.size());
377398 for (auto &child : op.children) {
377400 auto idx = TryBindGroup(*child);
377401 if (idx == DConstants::INVALID_INDEX) {
377402 return BindResult(BinderException(op, "GROUPING child \"%s\" must be a grouping column", child->GetName()));
377403 }
377404 group_indexes.push_back(idx);
377405 }
377406 auto col_idx = node.grouping_functions.size();
377407 node.grouping_functions.push_back(std::move(group_indexes));
377408 return BindResult(make_uniq<BoundColumnRefExpression>(op.GetName(), LogicalType::BIGINT,
377409 ColumnBinding(node.groupings_index, col_idx), depth));
377410}
void QualifyColumnNames(unique_ptr< ParsedExpression > &expr, vector< unordered_set< string > > &lambda_params, const bool within_function_expression=false)
Definition duckdb.cpp:360116

◆ BindWindow()

BindResult duckdb::BaseSelectBinder::BindWindow ( WindowExpression & expr,
idx_t depth )
protectedvirtual

Binds a WINDOW expression and returns the result.

Reimplemented in duckdb::HavingBinder.

363321 {
363322 QueryErrorContext error_context(window.GetQueryLocation());
363323 // Check for macros pretending to be aggregates
363324
363325 EntryLookupInfo function_lookup(CatalogType::SCALAR_FUNCTION_ENTRY, window.function_name, error_context);
363326 auto entry = GetCatalogEntry(window.catalog, window.schema, function_lookup, OnEntryNotFound::RETURN_NULL);
363327 if (window.GetExpressionType() == ExpressionType::WINDOW_AGGREGATE && entry &&
363328 entry->type == CatalogType::MACRO_ENTRY) {
363329 auto macro = make_uniq<FunctionExpression>(window.catalog, window.schema, window.function_name,
363330 std::move(window.children), std::move(window.filter_expr), nullptr,
363331 window.distinct);
363332 auto macro_expr = window.Copy();
363333 return BindMacro(*macro, entry->Cast<ScalarMacroCatalogEntry>(), depth, macro_expr);
363334 }
363335
363336 auto name = window.alias;
363337
363338 if (inside_window) {
363339 throw BinderException(error_context, "window function calls cannot be nested");
363340 }
363341 if (depth > 0) {
363342 throw BinderException(error_context, "correlated columns in window functions not supported");
363343 }
363344
363345 // If we have range expressions, then only one order by clause is allowed.
363346 const auto is_range =
363347 (window.start == WindowBoundary::EXPR_PRECEDING_RANGE || window.start == WindowBoundary::EXPR_FOLLOWING_RANGE ||
363348 window.end == WindowBoundary::EXPR_PRECEDING_RANGE || window.end == WindowBoundary::EXPR_FOLLOWING_RANGE);
363349 if (is_range && window.orders.size() != 1) {
363350 throw BinderException(error_context, "RANGE frames must have only one ORDER BY expression");
363351 } else if (window.GetExpressionType() == ExpressionType::WINDOW_FILL &&
363352 (window.arg_orders.size() > 1 || (window.arg_orders.empty() && window.orders.size() != 1))) {
363353 throw BinderException(error_context, "FILL functions must have only one ORDER BY expression");
363354 }
363355 // bind inside the children of the window function
363356 // we set the inside_window flag to true to prevent binding nested window functions
363357 inside_window = true;
363358 ErrorData error;
363359 for (auto &child : window.children) {
363360 BindChild(child, depth, error);
363361 }
363362 for (auto &child : window.partitions) {
363363 BindChild(child, depth, error);
363364 }
363365 for (auto &order : window.orders) {
363366 BindChild(order.expression, depth, error);
363367
363368 // If the frame is a RANGE frame and the type is a time,
363369 // then we have to convert the time to a timestamp to avoid wrapping.
363370 if (!is_range || error.HasError()) {
363371 continue;
363372 }
363373 auto &order_expr = order.expression;
363374 auto &bound_order = BoundExpression::GetExpression(*order_expr);
363375 const auto type_id = bound_order->return_type.id();
363376 if (type_id == LogicalTypeId::TIME || type_id == LogicalTypeId::TIME_TZ) {
363377 // Convert to time + epoch and rebind
363378 unique_ptr<ParsedExpression> epoch = make_uniq<ConstantExpression>(Value::DATE(date_t::epoch()));
363379 BindChild(epoch, depth, error);
363380 BindRangeExpression(context, "+", order.expression, epoch);
363381 }
363382 }
363383 BindChild(window.filter_expr, depth, error);
363384 BindChild(window.start_expr, depth, error);
363385 BindChild(window.end_expr, depth, error);
363386 BindChild(window.offset_expr, depth, error);
363387 BindChild(window.default_expr, depth, error);
363388
363389 for (auto &order : window.arg_orders) {
363390 BindChild(order.expression, depth, error);
363391 }
363392
363393 inside_window = false;
363394 if (error.HasError()) {
363395 // failed to bind children of window function
363396 return BindResult(std::move(error));
363397 }
363398
363399 // Restore any collation expressions
363400 for (auto &order : window.arg_orders) {
363401 auto &order_expr = order.expression;
363402 auto &bound_order = BoundExpression::GetExpression(*order_expr);
363403 ExpressionBinder::PushCollation(context, bound_order, bound_order->return_type);
363404 }
363405 for (auto &part_expr : window.partitions) {
363406 auto &bound_partition = BoundExpression::GetExpression(*part_expr);
363407 ExpressionBinder::PushCollation(context, bound_partition, bound_partition->return_type);
363408 }
363409 for (auto &order : window.orders) {
363410 auto &order_expr = order.expression;
363411 auto &bound_order = BoundExpression::GetExpression(*order_expr);
363412 ExpressionBinder::PushCollation(context, bound_order, bound_order->return_type);
363413 }
363414 // successfully bound all children: create bound window function
363415 vector<LogicalType> types;
363416 vector<unique_ptr<Expression>> children;
363417 for (auto &child : window.children) {
363418 D_ASSERT(child.get());
363419 D_ASSERT(child->GetExpressionClass() == ExpressionClass::BOUND_EXPRESSION);
363420 auto &bound = BoundExpression::GetExpression(*child);
363421 // Add casts for positional arguments
363422 const auto argno = children.size();
363423 switch (window.GetExpressionType()) {
363424 case ExpressionType::WINDOW_NTILE:
363425 // ntile(bigint)
363426 if (argno == 0) {
363427 bound = BoundCastExpression::AddCastToType(context, std::move(bound), LogicalType::BIGINT);
363428 }
363429 break;
363430 case ExpressionType::WINDOW_NTH_VALUE:
363431 // nth_value(<expr>, index)
363432 if (argno == 1) {
363433 bound = BoundCastExpression::AddCastToType(context, std::move(bound), LogicalType::BIGINT);
363434 }
363435 break;
363436 default:
363437 break;
363438 }
363439 types.push_back(bound->return_type);
363440 children.push_back(std::move(bound));
363441 }
363442 // Determine the function type.
363443 LogicalType sql_type;
363444 unique_ptr<AggregateFunction> aggregate;
363445 unique_ptr<FunctionData> bind_info;
363446 if (window.GetExpressionType() == ExpressionType::WINDOW_AGGREGATE) {
363447 // Look up the aggregate function in the catalog
363448 if (!entry || entry->type != CatalogType::AGGREGATE_FUNCTION_ENTRY) {
363449 // Not an aggregate: Look it up to generate error
363450 Catalog::GetEntry<AggregateFunctionCatalogEntry>(context, window.catalog, window.schema,
363451 window.function_name, error_context);
363452 }
363453 auto &func = entry->Cast<AggregateFunctionCatalogEntry>();
363454 D_ASSERT(func.type == CatalogType::AGGREGATE_FUNCTION_ENTRY);
363455
363456 // bind the aggregate
363457 ErrorData error_aggr;
363458 FunctionBinder function_binder(context);
363459 auto best_function = function_binder.BindFunction(func.name, func.functions, types, error_aggr);
363460 if (!best_function.IsValid()) {
363461 error_aggr.AddQueryLocation(window);
363462 error_aggr.Throw();
363463 }
363464
363465 // found a matching function! bind it as an aggregate
363466 auto bound_function = func.functions.GetFunctionByOffset(best_function.GetIndex());
363467
363468 if (!bound_function.CanAggregate() && bound_function.CanWindow() && !window.arg_orders.empty()) {
363469 // ORDER BY in non-aggregate window functions not supported
363470 // (The WindowCustomAggregator does not support it for now)
363471 ErrorData err(BinderException("Function '%s' cannot be used as a window with ORDER BY arguments",
363472 bound_function.name));
363473 err.AddQueryLocation(window);
363474 err.Throw();
363475 }
363476
363477 auto window_bound_aggregate = function_binder.BindAggregateFunction(bound_function, std::move(children));
363478 // create the aggregate
363479 aggregate = make_uniq<AggregateFunction>(window_bound_aggregate->function);
363480 bind_info = std::move(window_bound_aggregate->bind_info);
363481 children = std::move(window_bound_aggregate->children);
363482 sql_type = window_bound_aggregate->return_type;
363483
363484 } else {
363485 // fetch the child of the non-aggregate window function (if any)
363486 sql_type = ResolveWindowExpressionType(window.GetExpressionType(), types);
363487 }
363488 auto result = make_uniq<BoundWindowExpression>(window.GetExpressionType(), sql_type, std::move(aggregate),
363489 std::move(bind_info));
363490 result->children = std::move(children);
363491 for (auto &child : window.partitions) {
363492 result->partitions.push_back(GetExpression(child));
363493 }
363494 result->ignore_nulls = window.ignore_nulls;
363495 result->distinct = window.distinct;
363496
363497 // Convert RANGE boundary expressions to ORDER +/- expressions.
363498 // Note that PRECEEDING and FOLLOWING refer to the sequential order in the frame,
363499 // not the natural ordering of the type. This means that the offset arithmetic must be reversed
363500 // for ORDER BY DESC.
363501 auto &config = DBConfig::GetConfig(context);
363502 auto range_sense = OrderType::INVALID;
363503 LogicalType start_type = LogicalType::BIGINT;
363504 if (window.start == WindowBoundary::EXPR_PRECEDING_RANGE) {
363505 D_ASSERT(window.orders.size() == 1);
363506 range_sense = config.ResolveOrder(context, window.orders[0].type);
363507 const auto range_name = (range_sense == OrderType::ASCENDING) ? "-" : "+";
363508 start_type = BindRangeExpression(context, range_name, window.start_expr, window.orders[0].expression);
363509
363510 } else if (window.start == WindowBoundary::EXPR_FOLLOWING_RANGE) {
363511 D_ASSERT(window.orders.size() == 1);
363512 range_sense = config.ResolveOrder(context, window.orders[0].type);
363513 const auto range_name = (range_sense == OrderType::ASCENDING) ? "+" : "-";
363514 start_type = BindRangeExpression(context, range_name, window.start_expr, window.orders[0].expression);
363515 }
363516
363517 LogicalType end_type = LogicalType::BIGINT;
363518 if (window.end == WindowBoundary::EXPR_PRECEDING_RANGE) {
363519 D_ASSERT(window.orders.size() == 1);
363520 range_sense = config.ResolveOrder(context, window.orders[0].type);
363521 const auto range_name = (range_sense == OrderType::ASCENDING) ? "-" : "+";
363522 end_type = BindRangeExpression(context, range_name, window.end_expr, window.orders[0].expression);
363523
363524 } else if (window.end == WindowBoundary::EXPR_FOLLOWING_RANGE) {
363525 D_ASSERT(window.orders.size() == 1);
363526 range_sense = config.ResolveOrder(context, window.orders[0].type);
363527 const auto range_name = (range_sense == OrderType::ASCENDING) ? "+" : "-";
363528 end_type = BindRangeExpression(context, range_name, window.end_expr, window.orders[0].expression);
363529 }
363530
363531 // Cast ORDER and boundary expressions to the same type
363532 if (range_sense != OrderType::INVALID) {
363533 D_ASSERT(window.orders.size() == 1);
363534
363535 auto &order_expr = window.orders[0].expression;
363536 D_ASSERT(order_expr.get());
363537 D_ASSERT(order_expr->GetExpressionClass() == ExpressionClass::BOUND_EXPRESSION);
363538 auto &bound_order = BoundExpression::GetExpression(*order_expr);
363539 auto order_type = bound_order->return_type;
363540 if (window.start_expr) {
363541 order_type = LogicalType::MaxLogicalType(context, order_type, start_type);
363542 }
363543 if (window.end_expr) {
363544 order_type = LogicalType::MaxLogicalType(context, order_type, end_type);
363545 }
363546
363547 // Cast all three to match
363548 bound_order = BoundCastExpression::AddCastToType(context, std::move(bound_order), order_type);
363549 start_type = end_type = order_type;
363550 }
363551
363552 for (auto &order : window.orders) {
363553 auto type = config.ResolveOrder(context, order.type);
363554 auto null_order = config.ResolveNullOrder(context, type, order.null_order);
363555 auto expression = GetExpression(order.expression);
363556 result->orders.emplace_back(type, null_order, std::move(expression));
363557 }
363558
363559 // Argument orders are just like arguments, not frames
363560 for (auto &order : window.arg_orders) {
363561 auto type = config.ResolveOrder(context, order.type);
363562 auto null_order = config.ResolveNullOrder(context, type, order.null_order);
363563 auto expression = GetExpression(order.expression);
363564 result->arg_orders.emplace_back(type, null_order, std::move(expression));
363565 }
363566
363567 // Check FILL arguments support subtraction
363568 if (window.GetExpressionType() == ExpressionType::WINDOW_FILL) {
363569 D_ASSERT(!result->children.empty());
363570 if (!IsFillType(result->children[0]->return_type)) {
363571 throw BinderException(error_context, "FILL argument must support subtraction");
363572 }
363573 LogicalType order_type;
363574 if (window.arg_orders.empty()) {
363575 D_ASSERT(!result->orders.empty());
363576 order_type = result->orders[0].expression->return_type;
363577 } else {
363578 order_type = result->arg_orders[0].expression->return_type;
363579 }
363580 if (!IsFillType(order_type)) {
363581 throw BinderException(error_context, "FILL ordering must support subtraction");
363582 }
363583 }
363584
363585 result->filter_expr = CastWindowExpression(window.filter_expr, LogicalType::BOOLEAN);
363586 result->start_expr = CastWindowExpression(window.start_expr, start_type);
363587 result->end_expr = CastWindowExpression(window.end_expr, end_type);
363588 result->offset_expr = CastWindowExpression(window.offset_expr, LogicalType::BIGINT);
363589 result->default_expr = CastWindowExpression(window.default_expr, result->return_type);
363590 result->start = window.start;
363591 result->end = window.end;
363592 result->exclude_clause = window.exclude_clause;
363593
363594 // create a BoundColumnRef that references this entry
363595 auto colref = make_uniq<BoundColumnRefExpression>(std::move(name), result->return_type,
363596 ColumnBinding(node.window_index, node.windows.size()), depth);
363597 // move the WINDOW expression into the set of bound windows
363598 node.windows.push_back(std::move(result));
363599 return BindResult(std::move(colref));
363600}
DUCKDB_API optional_ptr< CatalogEntry > GetEntry(ClientContext &context, const string &schema, const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found)
Gets the "schema.name" entry of the specified type, if entry does not exist behavior depends on OnEnt...
Definition duckdb.cpp:8156
DUCKDB_API void Throw(const string &prepended_message="") const
Throw the error.
Definition duckdb.cpp:70200
static DUCKDB_API Value DATE(date_t date)
Create a date Value from a specified date.
Definition duckdb.cpp:132338
static DUCKDB_API LogicalType MaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right)
Returns the maximum logical type when combining the two types - or throws an exception if combining i...
Definition duckdb.cpp:140334
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BindColumnRef()

BindResult duckdb::BaseSelectBinder::BindColumnRef ( unique_ptr< ParsedExpression > & expr_ptr,
idx_t depth,
bool root_expression )
protectedvirtual
377382 {
377383 return ExpressionBinder::BindExpression(expr_ptr, depth);
377384}

◆ TryBindGroup()

idx_t duckdb::BaseSelectBinder::TryBindGroup ( ParsedExpression & expr)
protected
377355 {
377356 // first check the group alias map, if expr is a ColumnRefExpression
377357 if (expr.GetExpressionType() == ExpressionType::COLUMN_REF) {
377358 auto &colref = expr.Cast<ColumnRefExpression>();
377359 if (!colref.IsQualified()) {
377360 auto alias_entry = info.alias_map.find(colref.column_names[0]);
377361 if (alias_entry != info.alias_map.end()) {
377362 // found entry!
377363 return alias_entry->second;
377364 }
377365 }
377366 }
377367 // no alias reference found
377368 // check the list of group columns for a match
377369 auto entry = info.map.find(expr);
377370 if (entry != info.map.end()) {
377371 return entry->second;
377372 }
377373#ifdef DEBUG
377374 for (auto map_entry : info.map) {
377375 D_ASSERT(!map_entry.first.get().Equals(expr));
377376 D_ASSERT(!expr.Equals(map_entry.first.get()));
377377 }
377378#endif
377380}

◆ BindGroup()

BindResult duckdb::BaseSelectBinder::BindGroup ( ParsedExpression & expr,
idx_t depth,
idx_t group_index )
protected
377412 {
377413 auto it = info.collated_groups.find(group_index);
377414 if (it != info.collated_groups.end()) {
377415 // This is an implicitly collated group, so we need to refer to the first() aggregate
377416 const auto &aggr_index = it->second;
377417 const auto return_type = node.aggregates[aggr_index]->return_type;
377418 auto uncollated_first_expression = make_uniq<BoundColumnRefExpression>(
377419 expr.GetName(), return_type, ColumnBinding(node.aggregate_index, aggr_index), depth);
377420
377421 if (node.groups.grouping_sets.size() <= 1) {
377422 // if there are no more than two grouping sets, you can return the uncollated first expression.
377423 // "first" meaning the aggreagte function.
377424 return BindResult(std::move(uncollated_first_expression));
377425 }
377426
377427 // otherwise we insert a case statement to return NULL when the collated group expression is NULL
377428 // otherwise you can return the "first" of the uncollated expression.
377429 auto &group = node.groups.group_expressions[group_index];
377430 auto collated_group_expression = make_uniq<BoundColumnRefExpression>(
377431 expr.GetName(), group->return_type, ColumnBinding(node.group_index, group_index), depth);
377432
377433 auto sql_null = make_uniq<BoundConstantExpression>(Value(return_type));
377434 auto when_expr = make_uniq<BoundOperatorExpression>(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN);
377435 when_expr->children.push_back(std::move(collated_group_expression));
377436 auto then_expr = make_uniq<BoundConstantExpression>(Value(return_type));
377437 auto else_expr = std::move(uncollated_first_expression);
377438 auto case_expr =
377439 make_uniq<BoundCaseExpression>(std::move(when_expr), std::move(then_expr), std::move(else_expr));
377440 return BindResult(std::move(case_expr));
377441 } else {
377442 auto &group = node.groups.group_expressions[group_index];
377443 return BindResult(make_uniq<BoundColumnRefExpression>(expr.GetName(), group->return_type,
377444 ColumnBinding(node.group_index, group_index), depth));
377445 }
377446}

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