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::Binder Class Reference

Bind the parsed query tree to the actual columns present in the catalog. More...

Inheritance diagram for duckdb::Binder:
Collaboration diagram for duckdb::Binder:

Public Member Functions

DUCKDB_API BoundStatement Bind (SQLStatement &statement)
DUCKDB_API BoundStatement Bind (QueryNode &node)
unique_ptr< BoundCreateTableInfo > BindCreateTableInfo (unique_ptr< CreateInfo > info)
unique_ptr< BoundCreateTableInfo > BindCreateTableInfo (unique_ptr< CreateInfo > info, SchemaCatalogEntry &schema)
unique_ptr< BoundCreateTableInfo > BindCreateTableInfo (unique_ptr< CreateInfo > info, SchemaCatalogEntry &schema, vector< unique_ptr< Expression > > &bound_defaults)
vector< unique_ptr< BoundConstraint > > BindConstraints (const vector< unique_ptr< Constraint > > &constraints, const string &table_name, const ColumnList &columns)
vector< unique_ptr< BoundConstraint > > BindConstraints (const TableCatalogEntry &table)
vector< unique_ptr< BoundConstraint > > BindNewConstraints (vector< unique_ptr< Constraint > > &constraints, const string &table_name, const ColumnList &columns)
unique_ptr< BoundConstraint > BindConstraint (const Constraint &constraint, const string &table, const ColumnList &columns)
unique_ptr< BoundConstraint > BindUniqueConstraint (const Constraint &constraint, const string &table, const ColumnList &columns)
BoundStatement BindAlterAddIndex (BoundStatement &result, CatalogEntry &entry, unique_ptr< AlterInfo > alter_info)
void SetCatalogLookupCallback (catalog_entry_callback_t callback)
void BindCreateViewInfo (CreateViewInfo &base)
void SearchSchema (CreateInfo &info)
SchemaCatalogEntry & BindSchema (CreateInfo &info)
SchemaCatalogEntry & BindCreateFunctionInfo (CreateInfo &info)
unique_ptr< BoundPragmaInfo > BindPragma (PragmaInfo &info, QueryErrorContext error_context)
BoundStatement Bind (TableRef &ref)
idx_t GenerateTableIndex ()
 Generates an unused index for a table.
optional_ptr< CatalogEntry > GetCatalogEntry (const string &catalog, const string &schema, const EntryLookupInfo &lookup_info, OnEntryNotFound on_entry_not_found)
optional_ptr< CTEBinding > GetCTEBinding (const BindingAlias &name)
 Find all candidate common table expression by name; returns empty vector if none exists.
void AddBoundView (ViewCatalogEntry &view)
 Add the view to the set of currently bound views - used for detecting recursive view definitions.
void PushExpressionBinder (ExpressionBinder &binder)
void PopExpressionBinder ()
void SetActiveBinder (ExpressionBinder &binder)
ExpressionBinder & GetActiveBinder ()
bool HasActiveBinder ()
vector< reference< ExpressionBinder > > & GetActiveBinders ()
void MergeCorrelatedColumns (CorrelatedColumns &other)
void AddCorrelatedColumn (const CorrelatedColumnInfo &info)
 Add a correlated column to this binder (if it does not exist).
unique_ptr< LogicalOperator > BindUpdateSet (LogicalOperator &op, unique_ptr< LogicalOperator > root, UpdateSetInfo &set_info, TableCatalogEntry &table, vector< PhysicalIndex > &columns, bool prioritize_table_when_binding=false)
void BindUpdateSet (idx_t proj_index, unique_ptr< LogicalOperator > &root, UpdateSetInfo &set_info, TableCatalogEntry &table, vector< PhysicalIndex > &columns, vector< unique_ptr< Expression > > &update_expressions, vector< unique_ptr< Expression > > &projection_expressions, bool prioritize_table_when_binding=false)
void BindVacuumTable (LogicalVacuum &vacuum, unique_ptr< LogicalOperator > &root)
void BindLogicalType (LogicalType &type)
optional_ptr< Binding > GetMatchingBinding (const string &table_name, const string &column_name, ErrorData &error)
optional_ptr< Binding > GetMatchingBinding (const string &schema_name, const string &table_name, const string &column_name, ErrorData &error)
optional_ptr< Binding > GetMatchingBinding (const string &catalog_name, const string &schema_name, const string &table_name, const string &column_name, ErrorData &error)
void SetBindingMode (BindingMode mode)
BindingMode GetBindingMode ()
void AddTableName (string table_name)
void AddReplacementScan (const string &table_name, unique_ptr< TableRef > replacement)
const unordered_set< string > & GetTableNames ()
case_insensitive_map_t< unique_ptr< TableRef > > & GetReplacementScans ()
CatalogEntryRetriever & EntryRetriever ()
optional_ptr< BoundParameterMap > GetParameters ()
void SetParameters (BoundParameterMap &parameters)
void SetCanContainNulls (bool can_contain_nulls)
void SetAlwaysRequireRebind ()
StatementProperties & GetStatementProperties ()
unique_ptr< LogicalOperator > UnionOperators (vector< unique_ptr< LogicalOperator > > nodes)
void SetSearchPath (Catalog &catalog, const string &schema)
Public Member Functions inherited from duckdb::enable_shared_from_this< Binder >
shared_ptr< Binder > shared_from_this ()

Static Public Member Functions

static DUCKDB_API shared_ptr< Binder > CreateBinder (ClientContext &context, optional_ptr< Binder > parent=nullptr, BinderType binder_type=BinderType::REGULAR_BINDER)
static unique_ptr< BoundCreateTableInfo > BindCreateTableCheckpoint (unique_ptr< CreateInfo > info, SchemaCatalogEntry &schema)
static vector< unique_ptr< BoundConstraint > > BindConstraints (ClientContext &context, const vector< unique_ptr< Constraint > > &constraints, const string &table_name, const ColumnList &columns)
static void BindView (ClientContext &context, const SelectStatement &stmt, const string &catalog_name, const string &schema_name, optional_ptr< LogicalDependencyList > dependencies, const vector< string > &aliases, vector< LogicalType > &result_types, vector< string > &result_names)
static void BindNamedParameters (named_parameter_type_map_t &types, named_parameter_map_t &values, QueryErrorContext &error_context, string &func_name)
 Check usage, and cast named parameters to their types.
static void BindSchemaOrCatalog (ClientContext &context, string &catalog, string &schema)
static optional_ptr< ParsedExpression > GetResolvedColumnExpression (ParsedExpression &root_expr)
 Returns a ColumnRefExpression after it was resolved (i.e. past the STAR expression/USING clauses).
static void ReplaceStarExpression (unique_ptr< ParsedExpression > &expr, unique_ptr< ParsedExpression > &replacement)
static string ReplaceColumnsAlias (const string &alias, const string &column_name, optional_ptr< duckdb_re2::RE2 > regex)

Public Attributes

ClientContext & context
 The client context.
BindContext bind_context
 The bind context.
CorrelatedColumns correlated_columns
string alias
 The alias for the currently processing subquery, if it exists.
optional_ptr< DummyBinding > macro_binding
 Macro parameter bindings (if any).
optional_ptr< vector< DummyBinding > > lambda_bindings
 The intermediate lambda bindings to bind nested lambdas (if any).
unordered_map< idx_t, LogicalOperator * > recursive_ctes

Private Member Functions

idx_t GetBinderDepth () const
 Determine the depth of the binder.
void IncreaseDepth ()
 Increase the depth of the binder.
void BindGeneratedColumns (BoundCreateTableInfo &info)
 Bind the expressions of generated columns to check for errors.
void BindDefaultValues (const ColumnList &columns, vector< unique_ptr< Expression > > &bound_defaults, const string &catalog="", const string &schema="")
 Bind the default values of the columns of a table.
BoundLimitNode BindLimitValue (OrderBinder &order_binder, unique_ptr< ParsedExpression > limit_val, bool is_percentage, bool is_offset)
 Bind a limit value (LIMIT or OFFSET).
void MoveCorrelatedExpressions (Binder &other)
 Move correlated expressions from the child binder to this binder.
BoundStatement BindWithReplacementScan (ClientContext &context, BaseTableRef &ref)
 Tries to bind the table name with replacement scans.
template<class T>
BoundStatement BindWithCTE (T &statement)
BoundStatement Bind (SelectStatement &stmt)
BoundStatement Bind (InsertStatement &stmt)
BoundStatement Bind (CopyStatement &stmt, CopyToType copy_to_type)
BoundStatement Bind (DeleteStatement &stmt)
BoundStatement Bind (UpdateStatement &stmt)
BoundStatement Bind (CreateStatement &stmt)
BoundStatement Bind (DropStatement &stmt)
BoundStatement Bind (AlterStatement &stmt)
BoundStatement Bind (PrepareStatement &stmt)
BoundStatement Bind (ExecuteStatement &stmt)
BoundStatement Bind (TransactionStatement &stmt)
BoundStatement Bind (PragmaStatement &stmt)
BoundStatement Bind (ExplainStatement &stmt)
BoundStatement Bind (VacuumStatement &stmt)
BoundStatement Bind (RelationStatement &stmt)
BoundStatement Bind (CallStatement &stmt)
BoundStatement Bind (ExportStatement &stmt)
BoundStatement Bind (ExtensionStatement &stmt)
BoundStatement Bind (SetStatement &stmt)
BoundStatement Bind (SetVariableStatement &stmt)
BoundStatement Bind (ResetVariableStatement &stmt)
BoundStatement Bind (LoadStatement &stmt)
BoundStatement Bind (LogicalPlanStatement &stmt)
BoundStatement Bind (AttachStatement &stmt)
BoundStatement Bind (DetachStatement &stmt)
BoundStatement Bind (CopyDatabaseStatement &stmt)
BoundStatement Bind (UpdateExtensionsStatement &stmt)
BoundStatement Bind (MergeIntoStatement &stmt)
void BindRowIdColumns (TableCatalogEntry &table, LogicalGet &get, vector< unique_ptr< Expression > > &expressions)
BoundStatement BindReturning (vector< unique_ptr< ParsedExpression > > returning_list, TableCatalogEntry &table, const string &alias, idx_t update_table_index, unique_ptr< LogicalOperator > child_operator, virtual_column_map_t virtual_columns=virtual_column_map_t())
unique_ptr< QueryNode > BindTableMacro (FunctionExpression &function, TableMacroCatalogEntry &macro_func, idx_t depth)
BoundStatement BindCTE (const string &ctename, CommonTableExpressionInfo &info)
BoundStatement BindNode (SelectNode &node)
BoundStatement BindNode (SetOperationNode &node)
BoundStatement BindNode (RecursiveCTENode &node)
BoundStatement BindNode (QueryNode &node)
BoundStatement BindNode (StatementNode &node)
unique_ptr< LogicalOperator > VisitQueryNode (BoundQueryNode &node, unique_ptr< LogicalOperator > root)
unique_ptr< LogicalOperator > CreatePlan (BoundSelectNode &statement)
unique_ptr< LogicalOperator > CreatePlan (BoundSetOperationNode &node)
unique_ptr< LogicalOperator > CreatePlan (BoundQueryNode &node)
void BuildUnionByNameInfo (BoundSetOperationNode &result)
BoundStatement BindJoin (Binder &parent, TableRef &ref)
BoundStatement Bind (BaseTableRef &ref)
BoundStatement Bind (BoundRefWrapper &ref)
BoundStatement Bind (JoinRef &ref)
BoundStatement Bind (SubqueryRef &ref)
BoundStatement Bind (TableFunctionRef &ref)
BoundStatement Bind (EmptyTableRef &ref)
BoundStatement Bind (DelimGetRef &ref)
BoundStatement Bind (ExpressionListRef &ref)
BoundStatement Bind (ColumnDataRef &ref)
BoundStatement Bind (PivotRef &expr)
BoundStatement Bind (ShowRef &ref)
unique_ptr< SelectNode > BindPivot (PivotRef &expr, vector< unique_ptr< ParsedExpression > > all_columns)
unique_ptr< SelectNode > BindUnpivot (Binder &child_binder, PivotRef &expr, vector< unique_ptr< ParsedExpression > > all_columns, unique_ptr< ParsedExpression > &where_clause)
BoundStatement BindBoundPivot (PivotRef &expr)
void ExtractUnpivotEntries (Binder &child_binder, PivotColumnEntry &entry, vector< UnpivotEntry > &unpivot_entries)
void ExtractUnpivotColumnName (ParsedExpression &expr, vector< string > &result)
unique_ptr< BoundAtClause > BindAtClause (optional_ptr< AtClause > at_clause)
bool BindTableFunctionParameters (TableFunctionCatalogEntry &table_function, vector< unique_ptr< ParsedExpression > > &expressions, vector< LogicalType > &arguments, vector< Value > &parameters, named_parameter_map_t &named_parameters, BoundStatement &subquery, ErrorData &error)
void BindTableInTableOutFunction (vector< unique_ptr< ParsedExpression > > &expressions, BoundStatement &subquery)
BoundStatement BindTableFunction (TableFunction &function, vector< Value > parameters)
BoundStatement BindTableFunctionInternal (TableFunction &table_function, const TableFunctionRef &ref, vector< Value > parameters, named_parameter_map_t named_parameters, vector< LogicalType > input_table_types, vector< string > input_table_names)
unique_ptr< LogicalOperator > CreatePlan (BoundJoinRef &ref)
BoundStatement BindCopyTo (CopyStatement &stmt, const CopyFunction &function, CopyToType copy_to_type)
BoundStatement BindCopyFrom (CopyStatement &stmt, const CopyFunction &function)
void BindCopyOptions (CopyInfo &info)
case_insensitive_map_t< CopyOption > GetFullCopyOptionsList (const CopyFunction &function, CopyOptionMode mode)
void PrepareModifiers (OrderBinder &order_binder, QueryNode &statement, BoundQueryNode &result)
void BindModifiers (BoundQueryNode &result, idx_t table_index, const vector< string > &names, const vector< LogicalType > &sql_types, const SelectBindState &bind_state)
unique_ptr< BoundResultModifier > BindLimit (OrderBinder &order_binder, LimitModifier &limit_mod)
unique_ptr< BoundResultModifier > BindLimitPercent (OrderBinder &order_binder, LimitPercentModifier &limit_mod)
unique_ptr< Expression > BindOrderExpression (OrderBinder &order_binder, unique_ptr< ParsedExpression > expr)
unique_ptr< LogicalOperator > PlanFilter (unique_ptr< Expression > condition, unique_ptr< LogicalOperator > root)
void PlanSubqueries (unique_ptr< Expression > &expr, unique_ptr< LogicalOperator > &root)
unique_ptr< Expression > PlanSubquery (BoundSubqueryExpression &expr, unique_ptr< LogicalOperator > &root)
unique_ptr< LogicalOperator > PlanLateralJoin (unique_ptr< LogicalOperator > left, unique_ptr< LogicalOperator > right, CorrelatedColumns &correlated_columns, JoinType join_type=JoinType::INNER, unique_ptr< Expression > condition=nullptr)
unique_ptr< LogicalOperator > CastLogicalOperatorToTypes (const vector< LogicalType > &source_types, const vector< LogicalType > &target_types, unique_ptr< LogicalOperator > op)
BindingAlias FindBinding (const string &using_column, const string &join_side)
bool TryFindBinding (const string &using_column, const string &join_side, BindingAlias &result)
void AddUsingBindingSet (unique_ptr< UsingColumnSet > set)
BindingAlias RetrieveUsingBinding (Binder &current_binder, optional_ptr< UsingColumnSet > current_set, const string &column_name, const string &join_side)
void ExpandStarExpressions (vector< unique_ptr< ParsedExpression > > &select_list, vector< unique_ptr< ParsedExpression > > &new_select_list)
void ExpandStarExpression (unique_ptr< ParsedExpression > expr, vector< unique_ptr< ParsedExpression > > &new_select_list)
StarExpressionType FindStarExpression (unique_ptr< ParsedExpression > &expr, StarExpression **star, bool is_root, bool in_columns)
void ReplaceUnpackedStarExpression (unique_ptr< ParsedExpression > &expr, vector< unique_ptr< ParsedExpression > > &replacements, StarExpression &star, optional_ptr< duckdb_re2::RE2 > regex)
void BindWhereStarExpression (unique_ptr< ParsedExpression > &expr)
void BindSchemaOrCatalog (string &catalog_name, string &schema_name)
 If only a schema name is provided (e.g. "a.b") then figure out if "a" is a schema or a catalog name.
const string BindCatalog (string &catalog_name)
SchemaCatalogEntry & BindCreateSchema (CreateInfo &info)
vector< CatalogSearchEntry > GetSearchPath (Catalog &catalog, const string &schema_name)
LogicalType BindLogicalTypeInternal (const unique_ptr< ParsedExpression > &type_expr)
BoundStatement BindSelectNode (SelectNode &statement, BoundStatement from_table)
unique_ptr< LogicalOperator > BindCopyDatabaseSchema (Catalog &source_catalog, const string &target_database_name)
unique_ptr< LogicalOperator > BindCopyDatabaseData (Catalog &source_catalog, const string &target_database_name)
BoundStatement BindShowQuery (ShowRef &ref)
BoundStatement BindShowTable (ShowRef &ref)
BoundStatement BindSummarize (ShowRef &ref)
void BindInsertColumnList (TableCatalogEntry &table, vector< string > &columns, bool default_values, vector< LogicalIndex > &named_column_map, vector< LogicalType > &expected_types, IndexVector< idx_t, PhysicalIndex > &column_index_map)
void TryReplaceDefaultExpression (unique_ptr< ParsedExpression > &expr, const ColumnDefinition &column)
void ExpandDefaultInValuesList (InsertStatement &stmt, TableCatalogEntry &table, optional_ptr< ExpressionListRef > values_list, const vector< LogicalIndex > &named_column_map)
unique_ptr< BoundMergeIntoAction > BindMergeAction (LogicalMergeInto &merge_into, TableCatalogEntry &table, LogicalGet &get, idx_t proj_index, vector< unique_ptr< Expression > > &expressions, unique_ptr< LogicalOperator > &root, MergeIntoAction &action, const vector< BindingAlias > &source_aliases, const vector< string > &source_names)
unique_ptr< MergeIntoStatement > GenerateMergeInto (InsertStatement &stmt, TableCatalogEntry &table)
BoundCTEData PrepareCTE (const string &ctename, CommonTableExpressionInfo &statement)
BoundStatement FinishCTE (BoundCTEData &bound_cte, BoundStatement child_data)
shared_ptr< Binder > CreateBinderWithSearchPath (const string &catalog_name, const string &schema_name)
 Create a binder whose catalog search path is anchored to the table's catalog+schema.
 Binder (ClientContext &context, shared_ptr< Binder > parent, BinderType binder_type)

Static Private Member Functions

static void BindSchemaOrCatalog (CatalogEntryRetriever &retriever, string &catalog, string &schema)
static void CheckInsertColumnCountMismatch (idx_t expected_columns, idx_t result_columns, bool columns_provided, const string &tname)

Private Attributes

shared_ptr< Binder > parent
 The parent binder (if any).
BinderType binder_type = BinderType::REGULAR_BINDER
 What kind of node we are binding using this binder.
shared_ptr< GlobalBinderState > global_binder_state
 Global binder state.
shared_ptr< QueryBinderState > query_binder_state
 Query binder state.
bool has_unplanned_dependent_joins = false
 Whether or not the binder has any unplanned dependent joins that still need to be planned/flattened.
bool is_outside_flattened = true
 Whether or not outside dependent joins have been planned and flattened.
bool can_contain_nulls = false
 Whether or not the binder can contain NULLs as the root of expressions.
reference_set_t< ViewCatalogEntry > bound_views
 The set of bound views.
CatalogEntryRetriever entry_retriever
 Used to retrieve CatalogEntry's.
idx_t unnamed_subquery_index = 1
 Unnamed subquery index.
idx_t depth
 Binder depth.

Friends

class ExpressionBinder
class RecursiveDependentJoinPlanner

Additional Inherited Members

Protected Member Functions inherited from duckdb::enable_shared_from_this< Binder >
enable_shared_from_this & operator= (enable_shared_from_this const &) noexcept

Detailed Description

Bind the parsed query tree to the actual columns present in the catalog.

The binder is responsible for binding tables and columns to actual physical tables and columns in the catalog. In the process, it also resolves types of all expressions.

Constructor & Destructor Documentation

◆ Binder()

duckdb::Binder::Binder ( ClientContext & context,
shared_ptr< Binder > parent,
BinderType binder_type )
private
374442 : context(context), bind_context(*this), parent(std::move(parent_p)), binder_type(binder_type),
374443 global_binder_state(parent ? parent->global_binder_state : make_shared_ptr<GlobalBinderState>()),
374444 query_binder_state(parent && binder_type == BinderType::REGULAR_BINDER ? parent->query_binder_state
374445 : make_shared_ptr<QueryBinderState>()),
374446 entry_retriever(context), depth(parent ? parent->GetBinderDepth() : 1) {
374447 IncreaseDepth();
374448 if (parent) {
374449 entry_retriever.Inherit(parent->entry_retriever);
374450
374451 // We have to inherit macro and lambda parameter bindings and from the parent binder, if there is a parent.
374452 macro_binding = parent->macro_binding;
374453 lambda_bindings = parent->lambda_bindings;
374454 }
374455}
CatalogEntryRetriever entry_retriever
Used to retrieve CatalogEntry's.
Definition duckdb.cpp:2117
void IncreaseDepth()
Increase the depth of the binder.
Definition duckdb.cpp:374427
BinderType binder_type
What kind of node we are binding using this binder.
Definition duckdb.cpp:2103
shared_ptr< Binder > parent
The parent binder (if any).
Definition duckdb.cpp:2101
ClientContext & context
The client context.
Definition duckdb.cpp:1968
idx_t depth
Binder depth.
Definition duckdb.cpp:2121
BindContext bind_context
The bind context.
Definition duckdb.cpp:1970
optional_ptr< DummyBinding > macro_binding
Macro parameter bindings (if any).
Definition duckdb.cpp:1977
optional_ptr< vector< DummyBinding > > lambda_bindings
The intermediate lambda bindings to bind nested lambdas (if any).
Definition duckdb.cpp:1979
shared_ptr< GlobalBinderState > global_binder_state
Global binder state.
Definition duckdb.cpp:2105
shared_ptr< QueryBinderState > query_binder_state
Query binder state.
Definition duckdb.cpp:2107

Member Function Documentation

◆ CreateBinder()

shared_ptr< Binder > duckdb::Binder::CreateBinder ( ClientContext & context,
optional_ptr< Binder > parent = nullptr,
BinderType binder_type = BinderType::REGULAR_BINDER )
static
374437 {
374438 return shared_ptr<Binder>(new Binder(context, parent ? parent->shared_from_this() : nullptr, binder_type));
374439}

◆ Bind() [1/42]

BoundStatement duckdb::Binder::Bind ( SQLStatement & statement)
374469 {
374470 switch (statement.type) {
374471 case StatementType::SELECT_STATEMENT:
374472 return Bind(statement.Cast<SelectStatement>());
374473 case StatementType::INSERT_STATEMENT:
374474 return BindWithCTE(statement.Cast<InsertStatement>());
374475 case StatementType::COPY_STATEMENT:
374476 return Bind(statement.Cast<CopyStatement>(), CopyToType::COPY_TO_FILE);
374477 case StatementType::DELETE_STATEMENT:
374478 return BindWithCTE(statement.Cast<DeleteStatement>());
374479 case StatementType::UPDATE_STATEMENT:
374480 return BindWithCTE(statement.Cast<UpdateStatement>());
374481 case StatementType::RELATION_STATEMENT:
374482 return Bind(statement.Cast<RelationStatement>());
374483 case StatementType::CREATE_STATEMENT:
374484 return Bind(statement.Cast<CreateStatement>());
374485 case StatementType::DROP_STATEMENT:
374486 return Bind(statement.Cast<DropStatement>());
374487 case StatementType::ALTER_STATEMENT:
374488 return Bind(statement.Cast<AlterStatement>());
374489 case StatementType::TRANSACTION_STATEMENT:
374490 return Bind(statement.Cast<TransactionStatement>());
374491 case StatementType::PRAGMA_STATEMENT:
374492 return Bind(statement.Cast<PragmaStatement>());
374493 case StatementType::EXPLAIN_STATEMENT:
374494 return Bind(statement.Cast<ExplainStatement>());
374495 case StatementType::VACUUM_STATEMENT:
374496 return Bind(statement.Cast<VacuumStatement>());
374497 case StatementType::CALL_STATEMENT:
374498 return Bind(statement.Cast<CallStatement>());
374499 case StatementType::EXPORT_STATEMENT:
374500 return Bind(statement.Cast<ExportStatement>());
374501 case StatementType::SET_STATEMENT:
374502 return Bind(statement.Cast<SetStatement>());
374503 case StatementType::LOAD_STATEMENT:
374504 return Bind(statement.Cast<LoadStatement>());
374505 case StatementType::EXTENSION_STATEMENT:
374506 return Bind(statement.Cast<ExtensionStatement>());
374507 case StatementType::PREPARE_STATEMENT:
374508 return Bind(statement.Cast<PrepareStatement>());
374509 case StatementType::EXECUTE_STATEMENT:
374510 return Bind(statement.Cast<ExecuteStatement>());
374511 case StatementType::LOGICAL_PLAN_STATEMENT:
374512 return Bind(statement.Cast<LogicalPlanStatement>());
374513 case StatementType::ATTACH_STATEMENT:
374514 return Bind(statement.Cast<AttachStatement>());
374515 case StatementType::DETACH_STATEMENT:
374516 return Bind(statement.Cast<DetachStatement>());
374517 case StatementType::COPY_DATABASE_STATEMENT:
374518 return Bind(statement.Cast<CopyDatabaseStatement>());
374519 case StatementType::UPDATE_EXTENSIONS_STATEMENT:
374520 return Bind(statement.Cast<UpdateExtensionsStatement>());
374521 case StatementType::MERGE_INTO_STATEMENT:
374522 return BindWithCTE(statement.Cast<MergeIntoStatement>());
374523 default: // LCOV_EXCL_START
374524 throw NotImplementedException("Unimplemented statement type \"%s\" for Bind",
374525 StatementTypeToString(statement.type));
374526 } // LCOV_EXCL_STOP
374527}

◆ Bind() [2/42]

BoundStatement duckdb::Binder::Bind ( QueryNode & node)
374529 {
374530 return BindNode(node);
374531}

◆ BindCreateTableInfo() [1/3]

unique_ptr< BoundCreateTableInfo > duckdb::Binder::BindCreateTableInfo ( unique_ptr< CreateInfo > info)
368372 {
368373 auto &base = info->Cast<CreateTableInfo>();
368374 auto &schema = BindCreateSchema(base);
368375 return BindCreateTableInfo(std::move(info), schema);
368376}

◆ BindCreateTableInfo() [2/3]

unique_ptr< BoundCreateTableInfo > duckdb::Binder::BindCreateTableInfo ( unique_ptr< CreateInfo > info,
SchemaCatalogEntry & schema )
368008 {
368009 vector<unique_ptr<Expression>> bound_defaults;
368010 return BindCreateTableInfo(std::move(info), schema, bound_defaults);
368011}

◆ BindCreateTableInfo() [3/3]

unique_ptr< BoundCreateTableInfo > duckdb::Binder::BindCreateTableInfo ( unique_ptr< CreateInfo > info,
SchemaCatalogEntry & schema,
vector< unique_ptr< Expression > > & bound_defaults )
368255 {
368256 auto &base = info->Cast<CreateTableInfo>();
368257 auto result = make_uniq<BoundCreateTableInfo>(schema, std::move(info));
368258 auto &dependencies = result->dependencies;
368259 auto &catalog = schema.ParentCatalog();
368260 optional_ptr<StorageManager> storage_manager;
368261 if (catalog.IsDuckCatalog() && !catalog.InMemory()) {
368262 storage_manager = StorageManager::Get(catalog);
368263 }
368264
368265 // Bind all types by first looking into the same catalog/schema as the table
368266 auto type_binder = Binder::CreateBinder(context, *this);
368267 type_binder->SetSearchPath(result->schema.catalog, result->schema.name);
368268
368269 vector<unique_ptr<BoundConstraint>> bound_constraints;
368270 if (base.query) {
368271 // construct the result object
368272 auto query_obj = Bind(*base.query);
368273 base.query.reset();
368274 result->query = std::move(query_obj.plan);
368275
368276 // construct the set of columns based on the names and types of the query
368277 auto &names = query_obj.names;
368278 auto &sql_types = query_obj.types;
368279 // e.g. create table (col1 ,col2) as QUERY
368280 // col1 and col2 are the target_col_names
368281 auto target_col_names = base.columns.GetColumnNames();
368282 // TODO check types and target_col_names are mismatch in size
368283 D_ASSERT(names.size() == sql_types.size());
368284 base.columns.SetAllowDuplicates(true);
368285 if (!target_col_names.empty()) {
368286 if (target_col_names.size() > sql_types.size()) {
368287 throw BinderException("Target table has more colum names than query result.");
368288 } else if (target_col_names.size() < sql_types.size()) {
368289 // filled the target_col_names with the name of query names
368290 for (idx_t i = target_col_names.size(); i < sql_types.size(); i++) {
368291 target_col_names.push_back(names[i]);
368292 }
368293 }
368294 ColumnList new_colums;
368295 for (idx_t i = 0; i < target_col_names.size(); i++) {
368296 new_colums.AddColumn(ColumnDefinition(target_col_names[i], sql_types[i]));
368297 }
368298 base.columns = std::move(new_colums);
368299 } else {
368300 for (idx_t i = 0; i < names.size(); i++) {
368301 base.columns.AddColumn(ColumnDefinition(names[i], sql_types[i]));
368302 }
368303 }
368304
368305 // Bind all types
368306 for (idx_t i = 0; i < base.columns.PhysicalColumnCount(); i++) {
368307 auto &column = base.columns.GetColumnMutable(PhysicalIndex(i));
368308 type_binder->BindLogicalType(column.TypeMutable());
368309 }
368310
368311 } else {
368312 SetCatalogLookupCallback([&dependencies, &schema](CatalogEntry &entry) {
368313 if (&schema.ParentCatalog() != &entry.ParentCatalog()) {
368314 // Don't register dependencies between catalogs
368315 return;
368316 }
368317
368318 if (entry.type == CatalogType::TYPE_ENTRY && entry.internal) {
368319 // Don't register dependencies on internal types
368320 return;
368321 }
368322
368323 dependencies.AddDependency(entry);
368324 });
368325
368326 // Bind all physical column types
368327 for (idx_t i = 0; i < base.columns.PhysicalColumnCount(); i++) {
368328 auto &column = base.columns.GetColumnMutable(PhysicalIndex(i));
368329 type_binder->BindLogicalType(column.TypeMutable());
368330 }
368331
368332 auto &config = DBConfig::Get(catalog.GetAttached());
368333 VerifyCompressionType(context, storage_manager, config, *result);
368334 CreateColumnDependencyManager(*result);
368335 // bind the generated column expressions
368336 BindGeneratedColumns(*result);
368337 // bind any constraints
368338
368339 BindCreateTableConstraints(base, entry_retriever, schema);
368340
368341 if (AnyConstraintReferencesGeneratedColumn(base)) {
368342 throw BinderException("Constraints on generated columns are not supported yet");
368343 }
368344 bound_constraints = BindNewConstraints(base.constraints, base.table, base.columns);
368345 // bind the default values
368346 auto &catalog_name = schema.ParentCatalog().GetName();
368347 auto &schema_name = schema.name;
368348 BindDefaultValues(base.columns, bound_defaults, catalog_name, schema_name);
368349 }
368350
368351 if (base.columns.PhysicalColumnCount() == 0) {
368352 throw BinderException("Creating a table without physical (non-generated) columns is not supported");
368353 }
368354
368355 result->dependencies.VerifyDependencies(schema.catalog, result->Base().table);
368356
368357#ifdef DEBUG
368358 // Ensure all types are bound
368359 for (idx_t i = 0; i < base.columns.LogicalColumnCount(); i++) {
368360 auto &column = base.columns.GetColumn(LogicalIndex(i));
368361 if (TypeVisitor::Contains(column.Type(), LogicalTypeId::UNBOUND)) {
368362 throw InternalException("Unbound type remaining in column \"%s\" during Create Table bind", column.Name());
368363 }
368364 }
368365#endif
368366
368367 auto &properties = GetStatementProperties();
368368 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
368369 return result;
368370}
void BindDefaultValues(const ColumnList &columns, vector< unique_ptr< Expression > > &bound_defaults, const string &catalog="", const string &schema="")
Bind the default values of the columns of a table.
Definition duckdb.cpp:367979
void BindGeneratedColumns(BoundCreateTableInfo &info)
Bind the expressions of generated columns to check for errors.
Definition duckdb.cpp:367915
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ BindCreateTableCheckpoint()

unique_ptr< BoundCreateTableInfo > duckdb::Binder::BindCreateTableCheckpoint ( unique_ptr< CreateInfo > info,
SchemaCatalogEntry & schema )
static
368014 {
368015 auto result = make_uniq<BoundCreateTableInfo>(schema, std::move(info));
368016 CreateColumnDependencyManager(*result);
368017 return result;
368018}

◆ BindConstraints() [1/3]

vector< unique_ptr< BoundConstraint > > duckdb::Binder::BindConstraints ( ClientContext & context,
const vector< unique_ptr< Constraint > > & constraints,
const string & table_name,
const ColumnList & columns )
static
367747 {
367748 auto binder = Binder::CreateBinder(context);
367749 return binder->BindConstraints(constraints, table_name, columns);
367750}

◆ BindConstraints() [2/3]

vector< unique_ptr< BoundConstraint > > duckdb::Binder::BindConstraints ( const vector< unique_ptr< Constraint > > & constraints,
const string & table_name,
const ColumnList & columns )
367757 {
367758 vector<unique_ptr<BoundConstraint>> bound_constraints;
367759 for (const auto &constr : constraints) {
367760 bound_constraints.push_back(BindConstraint(*constr, table_name, columns));
367761 }
367762 return bound_constraints;
367763}

◆ BindConstraints() [3/3]

vector< unique_ptr< BoundConstraint > > duckdb::Binder::BindConstraints ( const TableCatalogEntry & table)
367752 {
367753 return BindConstraints(table.GetConstraints(), table.name, table.GetColumns());
367754}

◆ BindNewConstraints()

vector< unique_ptr< BoundConstraint > > duckdb::Binder::BindNewConstraints ( vector< unique_ptr< Constraint > > & constraints,
const string & table_name,
const ColumnList & columns )
367766 {
367767 auto bound_constraints = BindConstraints(constraints, table_name, columns);
367768
367769 // Handle PK and NOT NULL constraints.
367770 bool has_primary_key = false;
367771 physical_index_set_t not_null_columns;
367772 vector<PhysicalIndex> primary_keys;
367773
367774 for (const auto &bound_constr : bound_constraints) {
367775 switch (bound_constr->type) {
367776 case ConstraintType::NOT_NULL: {
367777 auto &not_null = bound_constr->Cast<BoundNotNullConstraint>();
367778 not_null_columns.insert(not_null.index);
367779 break;
367780 }
367781 case ConstraintType::UNIQUE: {
367782 const auto &unique = bound_constr->Cast<BoundUniqueConstraint>();
367783 if (unique.is_primary_key) {
367784 if (has_primary_key) {
367785 throw ParserException("table \"%s\" has more than one primary key", table_name);
367786 }
367787 has_primary_key = true;
367788 primary_keys = unique.keys;
367789 }
367790 break;
367791 }
367792 default:
367793 break;
367794 }
367795 }
367796
367797 if (has_primary_key) {
367798 // Create a PK constraint, and a NOT NULL constraint for each indexed column.
367799 for (auto &column_index : primary_keys) {
367800 if (not_null_columns.count(column_index) != 0) {
367801 continue;
367802 }
367803
367804 auto logical_index = columns.PhysicalToLogical(column_index);
367805 constraints.push_back(make_uniq<NotNullConstraint>(logical_index));
367806 bound_constraints.push_back(make_uniq<BoundNotNullConstraint>(column_index));
367807 }
367808 }
367809
367810 return bound_constraints;
367811}

◆ BindConstraint()

unique_ptr< BoundConstraint > duckdb::Binder::BindConstraint ( const Constraint & constraint,
const string & table,
const ColumnList & columns )
367894 {
367895 switch (constraint.type) {
367896 case ConstraintType::CHECK: {
367897 return BindCheckConstraint(*this, constraint, table, columns);
367898 }
367899 case ConstraintType::NOT_NULL: {
367900 auto &not_null = constraint.Cast<NotNullConstraint>();
367901 auto &col = columns.GetColumn(not_null.index);
367902 return make_uniq<BoundNotNullConstraint>(col.Physical());
367903 }
367904 case ConstraintType::UNIQUE: {
367905 return BindUniqueConstraint(constraint, table, columns);
367906 }
367907 case ConstraintType::FOREIGN_KEY: {
367908 return BindForeignKey(constraint);
367909 }
367910 default:
367911 throw NotImplementedException("unrecognized constraint type in bind");
367912 }
367913}

◆ BindUniqueConstraint()

unique_ptr< BoundConstraint > duckdb::Binder::BindUniqueConstraint ( const Constraint & constraint,
const string & table,
const ColumnList & columns )
367831 {
367832 auto &unique = constraint.Cast<UniqueConstraint>();
367833
367834 // Resolve the columns.
367835 vector<PhysicalIndex> indexes;
367836 physical_index_set_t index_set;
367837
367838 // HasIndex refers to a column index, not an index(-structure).
367839 // If set, then the UNIQUE constraint is defined on a single column.
367840 if (unique.HasIndex()) {
367841 auto &col = columns.GetColumn(unique.GetIndex());
367842 indexes.push_back(col.Physical());
367843 index_set.insert(col.Physical());
367844 return make_uniq<BoundUniqueConstraint>(std::move(indexes), std::move(index_set), unique.IsPrimaryKey());
367845 }
367846
367847 // The UNIQUE constraint is defined on a list of columns.
367848 for (auto &col_name : unique.GetColumnNames()) {
367849 if (!columns.ColumnExists(col_name)) {
367850 throw CatalogException("table \"%s\" does not have a column named \"%s\"", table, col_name);
367851 }
367852 auto &col = columns.GetColumn(col_name);
367853 if (col.Generated()) {
367854 throw BinderException("cannot create a PRIMARY KEY on a generated column: %s", col.GetName());
367855 }
367856
367857 auto physical_index = col.Physical();
367858 if (index_set.find(physical_index) != index_set.end()) {
367859 throw ParserException("column \"%s\" appears twice in primary key constraint", col_name);
367860 }
367861 indexes.push_back(physical_index);
367862 index_set.insert(physical_index);
367863 }
367864
367865 return make_uniq<BoundUniqueConstraint>(std::move(indexes), std::move(index_set), unique.IsPrimaryKey());
367866}

◆ BindAlterAddIndex()

BoundStatement duckdb::Binder::BindAlterAddIndex ( BoundStatement & result,
CatalogEntry & entry,
unique_ptr< AlterInfo > alter_info )
370549 {
370550 if (entry.type != CatalogType::TABLE_ENTRY) {
370551 throw BinderException("Cannot execute the `ALTER TABLE` statement on `%s`, only `Table` entries are accepted.",
370552 CatalogTypeToString(entry.type));
370553 }
370554 auto &table_info = alter_info->Cast<AlterTableInfo>();
370555 auto &constraint_info = table_info.Cast<AddConstraintInfo>();
370556 auto &table = entry.Cast<TableCatalogEntry>();
370557 auto &column_list = table.GetColumns();
370558
370559 auto bound_constraint = BindUniqueConstraint(*constraint_info.constraint, table_info.name, column_list);
370560 auto &bound_unique = bound_constraint->Cast<BoundUniqueConstraint>();
370561
370562 // Create the CreateIndexInfo.
370563 auto create_index_info = make_uniq<CreateIndexInfo>();
370564 create_index_info->table = table_info.name;
370565 create_index_info->index_type = ART::TYPE_NAME;
370566 create_index_info->constraint_type = IndexConstraintType::PRIMARY;
370567
370568 for (const auto &physical_index : bound_unique.keys) {
370569 auto &col = column_list.GetColumn(physical_index);
370570 unique_ptr<ParsedExpression> parsed = make_uniq<ColumnRefExpression>(col.GetName(), table_info.name);
370571 create_index_info->expressions.push_back(parsed->Copy());
370572 create_index_info->parsed_expressions.push_back(parsed->Copy());
370573 }
370574
370575 auto unique_constraint = constraint_info.constraint->Cast<UniqueConstraint>();
370576 auto index_name = unique_constraint.GetName(table_info.name);
370577 create_index_info->index_name = index_name;
370578 D_ASSERT(!create_index_info->index_name.empty());
370579
370580 // Plan the table scan.
370581 TableDescription table_description(table_info.catalog, table_info.schema, table_info.name);
370582 auto table_ref = make_uniq<BaseTableRef>(table_description);
370583 auto bound_table = Bind(*table_ref);
370584 if (bound_table.plan->type != LogicalOperatorType::LOGICAL_GET) {
370585 throw BinderException("can only add an index to a base table");
370586 }
370587 auto &get = bound_table.plan->Cast<LogicalGet>();
370588 get.names = column_list.GetColumnNames();
370589
370590 auto alter_table_info = unique_ptr_cast<AlterInfo, AlterTableInfo>(std::move(alter_info));
370591 result.plan = table.catalog.BindAlterAddIndex(*this, table, std::move(bound_table.plan),
370592 std::move(create_index_info), std::move(alter_table_info));
370593 return std::move(result);
370594}
static constexpr const char * TYPE_NAME
Index type name for the ART.
Definition duckdb.cpp:12136
__host__ cudaTextureObject_t get() const noexcept

◆ SetCatalogLookupCallback()

void duckdb::Binder::SetCatalogLookupCallback ( catalog_entry_callback_t callback)
367125 {
367126 entry_retriever.SetCallback(std::move(callback));
367127}

◆ BindCreateViewInfo()

void duckdb::Binder::BindCreateViewInfo ( CreateViewInfo & base)
367158 {
367159 optional_ptr<LogicalDependencyList> dependencies;
367160 if (Settings::Get<EnableViewDependenciesSetting>(context)) {
367161 dependencies = base.dependencies;
367162 }
367163 BindView(context, *base.query, base.catalog, base.schema, dependencies, base.aliases, base.types, base.names);
367164}

◆ BindView()

void duckdb::Binder::BindView ( ClientContext & context,
const SelectStatement & stmt,
const string & catalog_name,
const string & schema_name,
optional_ptr< LogicalDependencyList > dependencies,
const vector< string > & aliases,
vector< LogicalType > & result_types,
vector< string > & result_names )
static
367131 {
367132 auto view_binder = Binder::CreateBinder(context);
367133 auto &catalog = Catalog::GetCatalog(context, catalog_name);
367134
367135 if (dependencies) {
367136 view_binder->SetCatalogLookupCallback([&dependencies, &catalog](CatalogEntry &entry) {
367137 if (&catalog != &entry.ParentCatalog()) {
367138 // Don't register dependencies between catalogs
367139 return;
367140 }
367141 dependencies->AddDependency(entry);
367142 });
367143 }
367144 view_binder->can_contain_nulls = true;
367145
367146 auto view_search_path = view_binder->GetSearchPath(catalog, schema_name);
367147 view_binder->entry_retriever.SetSearchPath(std::move(view_search_path));
367148
367149 auto copy = stmt.Copy();
367150 auto query_node = view_binder->Bind(*copy);
367151 if (aliases.size() > query_node.names.size()) {
367152 throw BinderException("More VIEW aliases than columns in query result");
367153 }
367154 result_types = query_node.types;
367155 result_names = query_node.names;
367156}
static DUCKDB_API Catalog & GetCatalog(ClientContext &context, const string &catalog_name)
Get the specified Catalog from the ClientContext.
Definition duckdb.cpp:7211

◆ SearchSchema()

void duckdb::Binder::SearchSchema ( CreateInfo & info)
367074 {
367075 BindSchemaOrCatalog(info.catalog, info.schema);
367076 if (IsInvalidCatalog(info.catalog) && info.temporary) {
367077 info.catalog = TEMP_CATALOG;
367078 }
367079 auto &search_path = ClientData::Get(context).catalog_search_path;
367080 if (IsInvalidCatalog(info.catalog) && IsInvalidSchema(info.schema)) {
367081 auto &default_entry = search_path->GetDefault();
367082 info.catalog = default_entry.catalog;
367083 info.schema = default_entry.schema;
367084 } else if (IsInvalidSchema(info.schema)) {
367085 info.schema = search_path->GetDefaultSchema(context, info.catalog);
367086 } else if (IsInvalidCatalog(info.catalog)) {
367087 info.catalog = search_path->GetDefaultCatalog(info.schema);
367088 }
367089 if (IsInvalidCatalog(info.catalog)) {
367090 info.catalog = DatabaseManager::GetDefaultDatabase(context);
367091 }
367092 if (!info.temporary) {
367093 // non-temporary create: not read only
367094 if (info.catalog == TEMP_CATALOG) {
367095 throw ParserException("Only TEMPORARY table names can use the \"%s\" catalog", std::string(TEMP_CATALOG));
367096 }
367097 } else {
367098 if (info.catalog != TEMP_CATALOG) {
367099 throw ParserException("TEMPORARY table names can *only* use the \"%s\" catalog", std::string(TEMP_CATALOG));
367100 }
367101 }
367102}

◆ BindSchema()

SchemaCatalogEntry & duckdb::Binder::BindSchema ( CreateInfo & info)
367104 {
367105 SearchSchema(info);
367106 // fetch the schema in which we want to create the object
367107 auto &schema_obj = Catalog::GetSchema(context, info.catalog, info.schema);
367108 D_ASSERT(schema_obj.type == CatalogType::SCHEMA_ENTRY);
367109 info.schema = schema_obj.name;
367110 if (!info.temporary) {
367111 auto &properties = GetStatementProperties();
367112 properties.RegisterDBModify(schema_obj.catalog, context, DatabaseModificationType::CREATE_CATALOG_ENTRY);
367113 }
367114 return schema_obj;
367115}
DUCKDB_API SchemaCatalogEntry & GetSchema(ClientContext &context, const EntryLookupInfo &schema_lookup)
Returns the schema object with the specified name, or throws an exception if it does not exist.
Definition duckdb.cpp:7493

◆ BindCreateFunctionInfo()

SchemaCatalogEntry & duckdb::Binder::BindCreateFunctionInfo ( CreateInfo & info)

Set to identify exact matches in macro overloads

367166 {
367168 struct VectorOfLogicalTypeHash {
367169 std::size_t operator()(const vector<LogicalType> &k) const {
367170 auto hash = std::hash<size_t>()(k.size());
367171 for (auto &type : k) {
367172 hash = CombineHash(hash, type.Hash());
367173 }
367174 return hash;
367175 }
367176 };
367177
367178 struct VectorOfLogicalTypeEquality {
367179 bool operator()(const vector<LogicalType> &a, const vector<LogicalType> &b) const {
367180 if (a.size() != b.size()) {
367181 return false;
367182 }
367183 for (idx_t i = 0; i < a.size(); i++) {
367184 if (a[i] != b[i]) {
367185 return false;
367186 }
367187 }
367188 return true;
367189 }
367190 };
367191
367192 using vector_of_logical_type_set_t =
367193 unordered_set<vector<LogicalType>, VectorOfLogicalTypeHash, VectorOfLogicalTypeEquality>;
367194
367195 // Bind the catalog/schema
367196 SearchSchema(info);
367197 auto &catalog = Catalog::GetCatalog(context, info.catalog);
367198
367199 // Figure out if we can store typed macro parameters
367200 auto &attached = catalog.GetAttached();
367201 auto store_types = true;
367202 if (attached.HasStorageManager()) {
367203 // If DuckDB is used as a storage, we must check the version.
367204 auto &storage_manager = attached.GetStorageManager();
367205 const auto since = SerializationCompatibility::FromString("v1.4.0").serialization_version;
367206 store_types = info.temporary || attached.IsTemporary() || storage_manager.InMemory() ||
367207 storage_manager.GetStorageVersion() >= since;
367208 }
367209 // try to bind each of the included functions
367210 vector_of_logical_type_set_t type_overloads;
367211 auto &base = info.Cast<CreateMacroInfo>();
367212 for (auto &function : base.macros) {
367213 if (!store_types) {
367214 for (const auto &type : function->types) {
367215 if (type.id() != LogicalTypeId::UNKNOWN) {
367216 string msg = "Typed macro parameters are only supported for storage versions v1.4.0 and higher.\n";
367217 msg += "Use an in-memory database, ATTACH with (STORAGE_VERSION v1.4.0), or create a TEMP macro";
367218 throw BinderException(msg);
367219 }
367220 }
367221 }
367222
367223 if (info.type == CatalogType::MACRO_ENTRY) {
367224 auto &scalar_function = function->Cast<ScalarMacroFunction>();
367225 if (scalar_function.expression->HasParameter()) {
367226 throw BinderException("Parameter expressions within macro's are not supported!");
367227 }
367228 } else {
367229 D_ASSERT(info.type == CatalogType::TABLE_MACRO_ENTRY);
367230 auto &table_function = function->Cast<TableMacroFunction>();
367231 ParsedExpressionIterator::EnumerateQueryNodeChildren(
367232 *table_function.query_node, [](unique_ptr<ParsedExpression> &child) {
367233 if (child->HasParameter()) {
367234 throw BinderException("Parameter expressions within macro's are not supported!");
367235 }
367236 });
367237 }
367238
367239 // Constant-fold all default parameter expressions
367240 for (auto &it : function->default_parameters) {
367241 auto &param_name = it.first;
367242 auto &param_expr = it.second;
367243
367244 if (param_expr->type == ExpressionType::VALUE_CONSTANT) {
367245 continue;
367246 }
367247
367248 ConstantBinder binder(*this, context, StringUtil::Format("Default value for parameter '%s'", param_name));
367249 auto default_expr = param_expr->Copy();
367250 auto bound_default = binder.Bind(default_expr);
367251 if (!bound_default->IsFoldable()) {
367252 auto msg = StringUtil::Format("Default value '%s' for parameter '%s' is not a constant expression.",
367253 param_expr->ToString(), param_name);
367254 throw BinderException(msg);
367255 }
367256
367257 auto default_val = ExpressionExecutor::EvaluateScalar(context, *bound_default);
367258
367259 // Save this back as a constant expression
367260 auto const_expr = make_uniq<ConstantExpression>(default_val);
367261 const_expr->alias = param_name;
367262 it.second = std::move(const_expr);
367263 }
367264
367265 // Resolve any user type arguments
367266 for (idx_t param_idx = 0; param_idx < function->types.size(); param_idx++) {
367267 auto &type = function->types[param_idx];
367268 if (type.id() == LogicalTypeId::UNKNOWN) {
367269 continue;
367270 }
367271 if (type.id() == LogicalTypeId::UNBOUND) {
367272 BindLogicalType(type);
367273 }
367274 const auto &param_name = function->parameters[param_idx]->Cast<ColumnRefExpression>().GetColumnName();
367275 auto it = function->default_parameters.find(param_name);
367276 if (it != function->default_parameters.end()) {
367277 const auto &val_type = it->second->Cast<ConstantExpression>().value.type();
367278 if (CastFunctionSet::ImplicitCastCost(context, val_type, type) < 0) {
367279 auto msg =
367280 StringUtil::Format("Default value '%s' for parameter '%s' cannot be implicitly cast to '%s'.",
367281 it->second->ToString(), param_name, type.ToString());
367282 throw BinderException(msg + " Please add an explicit type cast.");
367283 }
367284 }
367285 }
367286
367287 vector<LogicalType> dummy_types;
367288 vector<string> dummy_names;
367289 // positional parameters
367290 for (idx_t param_idx = 0; param_idx < function->parameters.size(); param_idx++) {
367291 dummy_types.emplace_back(function->types.empty() ? LogicalType::UNKNOWN : function->types[param_idx]);
367292 dummy_names.push_back(function->parameters[param_idx]->Cast<ColumnRefExpression>().GetColumnName());
367293 }
367294
367295 if (!type_overloads.insert(dummy_types).second) {
367296 throw BinderException(
367297 "Ambiguity in macro overloads - macro %s() has multiple definitions with the same parameters",
367298 base.name);
367299 }
367300
367301 auto this_macro_binding = make_uniq<DummyBinding>(dummy_types, dummy_names, base.name);
367302 macro_binding = this_macro_binding.get();
367303
367304 auto &dependencies = base.dependencies;
367305 const auto should_create_dependencies = Settings::Get<EnableMacroDependenciesSetting>(context);
367306 const auto binder_callback = [&dependencies, &catalog](CatalogEntry &entry) {
367307 if (&catalog != &entry.ParentCatalog()) {
367308 // Don't register any cross-catalog dependencies
367309 return;
367310 }
367311 // Register any catalog entry required to bind the macro function
367312 dependencies.AddDependency(entry);
367313 };
367314
367315 // bind it to verify the function was defined correctly
367316 ErrorData error;
367317 if (info.type == CatalogType::MACRO_ENTRY) {
367318 BoundSelectNode sel_node;
367319 BoundGroupInformation group_info;
367320 SelectBinder binder(*this, context, sel_node, group_info);
367321 if (should_create_dependencies) {
367322 binder.SetCatalogLookupCallback(binder_callback);
367323 }
367324
367325 // create a copy of the expression because we do not want to alter the original
367326 auto expression = function->Cast<ScalarMacroFunction>().expression->Copy();
367327 ExpressionBinder::QualifyColumnNames(*this, expression);
367328 try {
367329 error = binder.Bind(expression, 0, false);
367330 if (error.HasError()) {
367331 error.Throw();
367332 }
367333 } catch (const std::exception &ex) {
367334 error = ErrorData(ex);
367335 }
367336 } else {
367337 D_ASSERT(info.type == CatalogType::TABLE_MACRO_ENTRY);
367338 auto dummy_binder = CreateBinder(context, this);
367339 if (should_create_dependencies) {
367340 dummy_binder->SetCatalogLookupCallback(binder_callback);
367341 }
367342
367343 // create a copy of the query node because we do not want to alter the original
367344 auto query_node = function->Cast<TableMacroFunction>().query_node->Copy();
367345 ParsedExpressionIterator::EnumerateQueryNodeChildren(
367346 *query_node, [&dummy_binder](unique_ptr<ParsedExpression> &child) {
367347 ExpressionBinder::QualifyColumnNames(*dummy_binder, child);
367348 });
367349 try {
367350 dummy_binder->Bind(*query_node);
367351 } catch (const std::exception &ex) {
367352 error = ErrorData(ex);
367353 }
367354 }
367355
367356 // if we cannot resolve parameters we postpone binding until the macro function is used
367357 if (error.HasError() && error.Type() != ExceptionType::PARAMETER_NOT_RESOLVED) {
367358 error.Throw();
367359 }
367360 }
367361
367362 return BindCreateSchema(info);
367363}
DUCKDB_API int64_t ImplicitCastCost(optional_ptr< ClientContext > context, const LogicalType &source, const LogicalType &target)
Returns the implicit cast cost of casting from source -> target -1 means an implicit cast is not poss...
Definition duckdb.cpp:213249
void QualifyColumnNames(unique_ptr< ParsedExpression > &expr, vector< unordered_set< string > > &lambda_params, const bool within_function_expression=false)
Definition duckdb.cpp:360116
static DUCKDB_API Value EvaluateScalar(ClientContext &context, const Expression &expr, bool allow_unfoldable=false)
Evaluate a scalar expression and fold it into a single value.
Definition duckdb.cpp:149993
static string Format(const string fmt_str, ARGS... params)
Format a string using printf semantics.
Definition duckdb.hpp:4002
__device__ __forceinline__ R operator()(index_type y, index_type x) const
hash_t CombineHash(hash_t left, hash_t right)
Combine two hashes by XORing them.
Definition duckdb.hpp:4635
Here is the call graph for this function:

◆ BindNamedParameters()

void duckdb::Binder::BindNamedParameters ( named_parameter_type_map_t & types,
named_parameter_map_t & values,
QueryErrorContext & error_context,
string & func_name )
static

Check usage, and cast named parameters to their types.

372112 {
372113 for (auto &kv : values) {
372114 auto entry = types.find(kv.first);
372115 if (entry == types.end()) {
372116 auto ordered_params = order_case_insensitive_map(types);
372117 // create a list of named parameters for the error
372118 string named_params;
372119 for (auto &kv_ordered_params : ordered_params) {
372120 named_params += " ";
372121 named_params += kv_ordered_params.first;
372122 named_params += " ";
372123 named_params += kv_ordered_params.second.ToString();
372124 named_params += "\n";
372125 }
372126 string error_msg;
372127 if (named_params.empty()) {
372128 error_msg = "Function does not accept any named parameters.";
372129 } else {
372130 error_msg = "Candidates:\n" + named_params;
372131 }
372132 throw BinderException(error_context, "Invalid named parameter \"%s\" for function %s\n%s", kv.first,
372133 func_name, error_msg);
372134 }
372135 if (entry->second.id() != LogicalTypeId::ANY) {
372136 kv.second = kv.second.DefaultCastAs(entry->second);
372137 }
372138 }
372139}

◆ BindPragma()

unique_ptr< BoundPragmaInfo > duckdb::Binder::BindPragma ( PragmaInfo & info,
QueryErrorContext error_context )
370313 {
370314 vector<Value> params;
370315 named_parameter_map_t named_parameters;
370316
370317 // resolve the parameters
370318 ConstantBinder pragma_binder(*this, context, "PRAGMA value");
370319 for (auto &param : info.parameters) {
370320 auto bound_value = pragma_binder.Bind(param);
370321 auto value = ExpressionExecutor::EvaluateScalar(context, *bound_value, true);
370322 params.push_back(std::move(value));
370323 }
370324
370325 for (auto &entry : info.named_parameters) {
370326 auto bound_value = pragma_binder.Bind(entry.second);
370327 auto value = ExpressionExecutor::EvaluateScalar(context, *bound_value, true);
370328 named_parameters.insert(make_pair(entry.first, std::move(value)));
370329 }
370330
370331 // bind the pragma function
370332 auto entry = Catalog::GetEntry<PragmaFunctionCatalogEntry>(context, INVALID_CATALOG, DEFAULT_SCHEMA, info.name,
370333 OnEntryNotFound::RETURN_NULL);
370334 if (!entry) {
370335 // try to find whether a table extry might exist
370336 auto table_entry = Catalog::GetEntry<TableFunctionCatalogEntry>(context, INVALID_CATALOG, DEFAULT_SCHEMA,
370337 info.name, OnEntryNotFound::RETURN_NULL);
370338 if (table_entry) {
370339 // there is a table entry with the same name, now throw more explicit error message
370340 throw CatalogException("Pragma Function with name %s does not exist, but a table function with the same "
370341 "name exists, try `CALL %s(...)`",
370342 info.name, info.name);
370343 }
370344 // rebind to throw exception
370345 entry = Catalog::GetEntry<PragmaFunctionCatalogEntry>(context, INVALID_CATALOG, DEFAULT_SCHEMA, info.name,
370346 OnEntryNotFound::THROW_EXCEPTION);
370347 }
370348
370349 FunctionBinder function_binder(*this);
370350 ErrorData error;
370351 auto bound_idx = function_binder.BindFunction(entry->name, entry->functions, params, error);
370352 if (!bound_idx.IsValid()) {
370353 D_ASSERT(error.HasError());
370354 error.AddQueryLocation(error_context);
370355 error.Throw();
370356 }
370357 auto bound_function = entry->functions.GetFunctionByOffset(bound_idx.GetIndex());
370358 // bind and check named params
370359 BindNamedParameters(bound_function.named_parameters, named_parameters, error_context, bound_function.name);
370360 return make_uniq<BoundPragmaInfo>(std::move(bound_function), std::move(params), std::move(named_parameters));
370361}
static void BindNamedParameters(named_parameter_type_map_t &types, named_parameter_map_t &values, QueryErrorContext &error_context, string &func_name)
Check usage, and cast named parameters to their types.
Definition duckdb.cpp:372111
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
PyParams params(const std::string &tag, const std::string &model, const std::string &weights, const std::string &device)

◆ Bind() [3/42]

BoundStatement duckdb::Binder::Bind ( TableRef & ref)
374533 {
374534 BoundStatement result;
374535 switch (ref.type) {
374536 case TableReferenceType::BASE_TABLE:
374537 result = Bind(ref.Cast<BaseTableRef>());
374538 break;
374539 case TableReferenceType::JOIN:
374540 result = Bind(ref.Cast<JoinRef>());
374541 break;
374542 case TableReferenceType::SUBQUERY:
374543 result = Bind(ref.Cast<SubqueryRef>());
374544 break;
374545 case TableReferenceType::EMPTY_FROM:
374546 result = Bind(ref.Cast<EmptyTableRef>());
374547 break;
374548 case TableReferenceType::TABLE_FUNCTION:
374549 result = Bind(ref.Cast<TableFunctionRef>());
374550 break;
374551 case TableReferenceType::EXPRESSION_LIST:
374552 result = Bind(ref.Cast<ExpressionListRef>());
374553 break;
374554 case TableReferenceType::COLUMN_DATA:
374555 result = Bind(ref.Cast<ColumnDataRef>());
374556 break;
374557 case TableReferenceType::PIVOT:
374558 result = Bind(ref.Cast<PivotRef>());
374559 break;
374560 case TableReferenceType::SHOW_REF:
374561 result = Bind(ref.Cast<ShowRef>());
374562 break;
374563 case TableReferenceType::DELIM_GET:
374564 result = Bind(ref.Cast<DelimGetRef>());
374565 break;
374566 case TableReferenceType::BOUND_TABLE_REF:
374567 result = Bind(ref.Cast<BoundRefWrapper>());
374568 break;
374569 case TableReferenceType::CTE:
374570 case TableReferenceType::INVALID:
374571 default:
374572 throw InternalException("Unknown table ref type (%s)", EnumUtil::ToString(ref.type));
374573 }
374574 if (ref.sample) {
374575 result.plan = make_uniq<LogicalSample>(std::move(ref.sample), std::move(result.plan));
374576 }
374577 return result;
374578}

◆ GenerateTableIndex()

idx_t duckdb::Binder::GenerateTableIndex ( )

Generates an unused index for a table.

374615 {
374616 return global_binder_state->bound_tables++;
374617}
Here is the caller graph for this function:

◆ GetCatalogEntry()

optional_ptr< CatalogEntry > duckdb::Binder::GetCatalogEntry ( const string & catalog,
const string & schema,
const EntryLookupInfo & lookup_info,
OnEntryNotFound on_entry_not_found )
374813 {
374814 return entry_retriever.GetEntry(catalog, schema, lookup_info, on_entry_not_found);
374815}

◆ GetCTEBinding()

optional_ptr< CTEBinding > duckdb::Binder::GetCTEBinding ( const BindingAlias & name)

Find all candidate common table expression by name; returns empty vector if none exists.

374580 {
374581 reference<Binder> current_binder(*this);
374582 optional_ptr<CTEBinding> result;
374583 while (true) {
374584 auto &current = current_binder.get();
374585 auto entry = current.bind_context.GetCTEBinding(name);
374586 if (entry) {
374587 // we only directly return the CTE if it can be referenced
374588 // if it cannot be referenced (circular reference) we keep going up the stack
374589 // to look for a CTE that can be referenced
374590 if (entry->CanBeReferenced()) {
374591 return entry;
374592 }
374593 result = entry;
374594 }
374595 if (!current.parent || current.binder_type != BinderType::REGULAR_BINDER) {
374596 break;
374597 }
374598 current_binder = *current.parent;
374599 }
374600 return result;
374601}

◆ AddBoundView()

void duckdb::Binder::AddBoundView ( ViewCatalogEntry & view)

Add the view to the set of currently bound views - used for detecting recursive view definitions.

374603 {
374604 // check if the view is already bound
374605 auto current = this;
374606 while (current) {
374607 if (current->bound_views.find(view) != current->bound_views.end()) {
374608 throw BinderException("infinite recursion detected: attempting to recursively bind view \"%s\"", view.name);
374609 }
374610 current = current->parent.get();
374611 }
374612 bound_views.insert(view);
374613}
reference_set_t< ViewCatalogEntry > bound_views
The set of bound views.
Definition duckdb.cpp:2115

◆ PushExpressionBinder()

void duckdb::Binder::PushExpressionBinder ( ExpressionBinder & binder)
374631 {
374632 GetActiveBinders().push_back(binder);
374633}

◆ PopExpressionBinder()

void duckdb::Binder::PopExpressionBinder ( )
374635 {
374636 D_ASSERT(HasActiveBinder());
374637 GetActiveBinders().pop_back();
374638}

◆ SetActiveBinder()

void duckdb::Binder::SetActiveBinder ( ExpressionBinder & binder)
374640 {
374641 D_ASSERT(HasActiveBinder());
374642 GetActiveBinders().back() = binder;
374643}

◆ GetActiveBinder()

ExpressionBinder & duckdb::Binder::GetActiveBinder ( )
374645 {
374646 return GetActiveBinders().back();
374647}

◆ HasActiveBinder()

bool duckdb::Binder::HasActiveBinder ( )
374649 {
374650 return !GetActiveBinders().empty();
374651}

◆ GetActiveBinders()

vector< reference< ExpressionBinder > > & duckdb::Binder::GetActiveBinders ( )
374653 {
374654 return query_binder_state->active_binders;
374655}

◆ MergeCorrelatedColumns()

void duckdb::Binder::MergeCorrelatedColumns ( CorrelatedColumns & other)
374666 {
374667 for (idx_t i = 0; i < other.size(); i++) {
374668 AddCorrelatedColumn(other[i]);
374669 }
374670}
void AddCorrelatedColumn(const CorrelatedColumnInfo &info)
Add a correlated column to this binder (if it does not exist).
Definition duckdb.cpp:374672

◆ AddCorrelatedColumn()

void duckdb::Binder::AddCorrelatedColumn ( const CorrelatedColumnInfo & info)

Add a correlated column to this binder (if it does not exist).

374672 {
374673 // we only add correlated columns to the list if they are not already there
374674 if (std::find(correlated_columns.begin(), correlated_columns.end(), info) == correlated_columns.end()) {
374675 correlated_columns.AddColumn(info);
374676 }
374677}
CorrelatedColumns correlated_columns
Definition duckdb.cpp:1973

◆ BindUpdateSet() [1/2]

unique_ptr< LogicalOperator > duckdb::Binder::BindUpdateSet ( LogicalOperator & op,
unique_ptr< LogicalOperator > root,
UpdateSetInfo & set_info,
TableCatalogEntry & table,
vector< PhysicalIndex > & columns,
bool prioritize_table_when_binding = false )
370943 {
370944 auto proj_index = GenerateTableIndex();
370945
370946 vector<unique_ptr<Expression>> projection_expressions;
370947 BindUpdateSet(proj_index, root, set_info, table, columns, op.expressions, projection_expressions,
370948 prioritize_table_when_binding);
370949 if (op.type != LogicalOperatorType::LOGICAL_UPDATE && projection_expressions.empty()) {
370950 return root;
370951 }
370952 // now create the projection
370953 auto proj = make_uniq<LogicalProjection>(proj_index, std::move(projection_expressions));
370954 proj->AddChild(std::move(root));
370955 return unique_ptr_cast<LogicalProjection, LogicalOperator>(std::move(proj));
370956}
idx_t GenerateTableIndex()
Generates an unused index for a table.
Definition duckdb.cpp:374615

◆ BindUpdateSet() [2/2]

void duckdb::Binder::BindUpdateSet ( idx_t proj_index,
unique_ptr< LogicalOperator > & root,
UpdateSetInfo & set_info,
TableCatalogEntry & table,
vector< PhysicalIndex > & columns,
vector< unique_ptr< Expression > > & update_expressions,
vector< unique_ptr< Expression > > & projection_expressions,
bool prioritize_table_when_binding = false )
370893 {
370894 D_ASSERT(set_info.columns.size() == set_info.expressions.size());
370895
370896 Binder *expr_binder_ptr = this;
370897 shared_ptr<Binder> binder_with_search_path;
370898
370899 if (prioritize_table_when_binding) {
370900 binder_with_search_path =
370901 CreateBinderWithSearchPath(table.ParentCatalog().GetName(), table.ParentSchema().name);
370902 expr_binder_ptr = binder_with_search_path.get();
370903 }
370904
370905 for (idx_t i = 0; i < set_info.columns.size(); i++) {
370906 auto &colname = set_info.columns[i];
370907 auto &expr = set_info.expressions[i];
370908 if (!table.ColumnExists(colname)) {
370909 vector<string> column_names;
370910 for (auto &col : table.GetColumns().Physical()) {
370911 column_names.push_back(col.Name());
370912 }
370913 auto candidates = StringUtil::CandidatesErrorMessage(column_names, colname, "Did you mean");
370914 throw BinderException("Referenced update column %s not found in table!\n%s", colname, candidates);
370915 }
370916 auto &column = table.GetColumn(colname);
370917 if (column.Generated()) {
370918 throw BinderException("Cant update column \"%s\" because it is a generated column!", column.Name());
370919 }
370920 if (std::find(columns.begin(), columns.end(), column.Physical()) != columns.end()) {
370921 throw BinderException("Multiple assignments to same column \"%s\"", colname);
370922 }
370923 columns.push_back(column.Physical());
370924 if (expr->GetExpressionType() == ExpressionType::VALUE_DEFAULT) {
370925 update_expressions.push_back(make_uniq<BoundDefaultExpression>(column.Type()));
370926 } else {
370927 UpdateBinder binder(*expr_binder_ptr, context);
370928 binder.target_type = column.Type();
370929 auto bound_expr = binder.Bind(expr);
370930 PlanSubqueries(bound_expr, root);
370931
370932 update_expressions.push_back(make_uniq<BoundColumnRefExpression>(
370933 bound_expr->return_type, ColumnBinding(proj_index, projection_expressions.size())));
370934 projection_expressions.push_back(std::move(bound_expr));
370935 }
370936 }
370937}
shared_ptr< Binder > CreateBinderWithSearchPath(const string &catalog_name, const string &schema_name)
Create a binder whose catalog search path is anchored to the table's catalog+schema.
Definition duckdb.cpp:374818
static DUCKDB_API string CandidatesErrorMessage(const vector< string > &strings, const string &target, const string &message_prefix, idx_t n=5)
Definition duckdb.cpp:109926

◆ BindVacuumTable()

void duckdb::Binder::BindVacuumTable ( LogicalVacuum & vacuum,
unique_ptr< LogicalOperator > & root )
371119 {
371120 auto &info = vacuum.GetInfo();
371121 if (!info.has_table) {
371122 return;
371123 }
371124
371125 D_ASSERT(vacuum.column_id_map.empty());
371126
371127 auto bound_table = Bind(*info.ref);
371128 if (bound_table.plan->type != LogicalOperatorType::LOGICAL_GET) {
371129 throw BinderException("Can only vacuum or analyze base tables");
371130 }
371131 auto table_scan = std::move(bound_table.plan);
371132 auto &get = table_scan->Cast<LogicalGet>();
371133 auto table_ptr = get.GetTable();
371134 if (!table_ptr) {
371135 throw BinderException("Can only vacuum or analyze base tables");
371136 }
371137 auto &table = *table_ptr;
371138 vacuum.SetTable(table);
371139
371140 vector<unique_ptr<Expression>> select_list;
371141 auto &columns = info.columns;
371142 if (columns.empty()) {
371143 // Empty means ALL columns should be vacuumed/analyzed
371144 for (auto &col : table.GetColumns().Physical()) {
371145 columns.push_back(col.GetName());
371146 }
371147 }
371148
371149 case_insensitive_set_t column_name_set;
371150 vector<string> non_generated_column_names;
371151 for (auto &col_name : columns) {
371152 if (column_name_set.count(col_name) > 0) {
371153 throw BinderException("cannot vacuum or analyze the same column twice, i.e., there is a duplicate entry in "
371154 "the list of column names");
371155 }
371156 column_name_set.insert(col_name);
371157 if (!table.ColumnExists(col_name)) {
371158 throw BinderException("Column with name \"%s\" does not exist", col_name);
371159 }
371160 auto &col = table.GetColumn(col_name);
371161 // ignore generated column
371162 if (col.Generated()) {
371163 throw BinderException(
371164 "cannot vacuum or analyze generated column \"%s\" - specify non-generated columns to vacuum or analyze",
371165 col.GetName());
371166 }
371167 non_generated_column_names.push_back(col_name);
371168 ColumnRefExpression colref(col_name, table.name);
371169 auto result = bind_context.BindColumn(colref, 0);
371170 if (result.HasError()) {
371171 result.error.Throw();
371172 }
371173 select_list.push_back(std::move(result.expression));
371174 }
371175 info.columns = std::move(non_generated_column_names);
371176
371177 auto &column_ids = get.GetColumnIds();
371178 D_ASSERT(select_list.size() == column_ids.size());
371179 D_ASSERT(info.columns.size() == column_ids.size());
371180 for (idx_t i = 0; i < column_ids.size(); i++) {
371181 vacuum.column_id_map[i] = table.GetColumns().LogicalToPhysical(column_ids[i].ToLogical()).index;
371182 }
371183
371184 auto projection = make_uniq<LogicalProjection>(GenerateTableIndex(), std::move(select_list));
371185 projection->children.push_back(std::move(table_scan));
371186
371187 root = std::move(projection);
371188}

◆ BindSchemaOrCatalog() [1/3]

void duckdb::Binder::BindSchemaOrCatalog ( ClientContext & context,
string & catalog,
string & schema )
static
367055 {
367056 CatalogEntryRetriever retriever(context);
367057 BindSchemaOrCatalog(retriever, catalog, schema);
367058}

◆ BindLogicalType()

void duckdb::Binder::BindLogicalType ( LogicalType & type)
367391 {
367392 // Check if we need to bind this type at all
367393 if (!TypeVisitor::Contains(type, LogicalTypeId::UNBOUND)) {
367394 return;
367395 }
367396
367397 // Replace all unbound types within the type
367398 // Normally, the unbound type is the root type, but it can also be nested within other types if we e.g.
367399 // alter-table and change a struct field.
367400 type = TypeVisitor::VisitReplace(type, [&](const LogicalType &ty) {
367401 if (ty.id() == LogicalTypeId::UNBOUND) {
367402 auto &type_expr = UnboundType::GetTypeExpression(ty);
367403 return BindLogicalTypeInternal(type_expr);
367404 }
367405
367406 return ty;
367407 });
367408}

◆ GetMatchingBinding() [1/3]

optional_ptr< Binding > duckdb::Binder::GetMatchingBinding ( const string & table_name,
const string & column_name,
ErrorData & error )
374680 {
374681 string empty_schema;
374682 return GetMatchingBinding(empty_schema, table_name, column_name, error);
374683}

◆ GetMatchingBinding() [2/3]

optional_ptr< Binding > duckdb::Binder::GetMatchingBinding ( const string & schema_name,
const string & table_name,
const string & column_name,
ErrorData & error )
374686 {
374687 string empty_catalog;
374688 return GetMatchingBinding(empty_catalog, schema_name, table_name, column_name, error);
374689}

◆ GetMatchingBinding() [3/3]

optional_ptr< Binding > duckdb::Binder::GetMatchingBinding ( const string & catalog_name,
const string & schema_name,
const string & table_name,
const string & column_name,
ErrorData & error )
374693 {
374694 optional_ptr<Binding> binding;
374695 if (macro_binding && table_name == macro_binding->GetAlias()) {
374696 binding = optional_ptr<Binding>(macro_binding.get());
374697 } else {
374698 BindingAlias alias(catalog_name, schema_name, table_name);
374699 binding = bind_context.GetBinding(alias, column_name, error);
374700 }
374701 return binding;
374702}
string alias
The alias for the currently processing subquery, if it exists.
Definition duckdb.cpp:1975

◆ SetBindingMode()

void duckdb::Binder::SetBindingMode ( BindingMode mode)
374704 {
374705 global_binder_state->mode = mode;
374706}

◆ GetBindingMode()

BindingMode duckdb::Binder::GetBindingMode ( )
374708 {
374709 return global_binder_state->mode;
374710}

◆ AddTableName()

void duckdb::Binder::AddTableName ( string table_name)
374721 {
374722 global_binder_state->table_names.insert(std::move(table_name));
374723}

◆ AddReplacementScan()

void duckdb::Binder::AddReplacementScan ( const string & table_name,
unique_ptr< TableRef > replacement )
374725 {
374726 auto it = global_binder_state->replacement_scans.find(table_name);
374727 replacement->column_name_alias.clear();
374728 replacement->alias.clear();
374729 if (it == global_binder_state->replacement_scans.end()) {
374730 global_binder_state->replacement_scans[table_name] = std::move(replacement);
374731 } else {
374732 // A replacement scan by this name was previously registered, we can just use it
374733 }
374734}

◆ GetTableNames()

const unordered_set< string > & duckdb::Binder::GetTableNames ( )
374736 {
374737 return global_binder_state->table_names;
374738}

◆ GetReplacementScans()

case_insensitive_map_t< unique_ptr< TableRef > > & duckdb::Binder::GetReplacementScans ( )
374740 {
374741 return global_binder_state->replacement_scans;
374742}

◆ EntryRetriever()

CatalogEntryRetriever & duckdb::Binder::EntryRetriever ( )
inline
2079 {
2080 return entry_retriever;
2081 }

◆ GetParameters()

optional_ptr< BoundParameterMap > duckdb::Binder::GetParameters ( )
374623 {
374624 return global_binder_state->parameters;
374625}

◆ SetParameters()

void duckdb::Binder::SetParameters ( BoundParameterMap & parameters)
374627 {
374628 global_binder_state->parameters = parameters;
374629}

◆ GetResolvedColumnExpression()

optional_ptr< ParsedExpression > duckdb::Binder::GetResolvedColumnExpression ( ParsedExpression & root_expr)
static

Returns a ColumnRefExpression after it was resolved (i.e. past the STAR expression/USING clauses).

362211 {
362212 optional_ptr<ParsedExpression> expr = &root_expr;
362213 while (expr) {
362214 if (expr->GetExpressionType() == ExpressionType::COLUMN_REF) {
362215 break;
362216 }
362217 if (expr->GetExpressionType() == ExpressionType::OPERATOR_COALESCE) {
362218 expr = expr->Cast<OperatorExpression>().children[0].get();
362219 } else {
362220 // unknown expression
362221 return nullptr;
362222 }
362223 }
362224 return expr;
362225}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetCanContainNulls()

void duckdb::Binder::SetCanContainNulls ( bool can_contain_nulls)
374712 {
374713 can_contain_nulls = can_contain_nulls_p;
374714}
bool can_contain_nulls
Whether or not the binder can contain NULLs as the root of expressions.
Definition duckdb.cpp:2113

◆ SetAlwaysRequireRebind()

void duckdb::Binder::SetAlwaysRequireRebind ( )
374716 {
374717 auto &properties = GetStatementProperties();
374718 properties.always_require_rebind = true;
374719}

◆ GetStatementProperties()

StatementProperties & duckdb::Binder::GetStatementProperties ( )
374619 {
374620 return global_binder_state->prop;
374621}

◆ ReplaceStarExpression()

void duckdb::Binder::ReplaceStarExpression ( unique_ptr< ParsedExpression > & expr,
unique_ptr< ParsedExpression > & replacement )
static
362073 {
362074 D_ASSERT(expr);
362075 if (StarExpression::IsColumns(*expr) || StarExpression::IsStar(*expr)) {
362076 D_ASSERT(replacement);
362077 auto alias = expr->GetAlias();
362078 expr = replacement->Copy();
362079 if (!alias.empty()) {
362080 expr->SetAlias(std::move(alias));
362081 }
362082 return;
362083 }
362084 ParsedExpressionIterator::EnumerateChildren(
362085 *expr, [&](unique_ptr<ParsedExpression> &child_expr) { ReplaceStarExpression(child_expr, replacement); });
362086}

◆ ReplaceColumnsAlias()

string duckdb::Binder::ReplaceColumnsAlias ( const string & alias,
const string & column_name,
optional_ptr< duckdb_re2::RE2 > regex )
static
362089 {
362090 string result;
362091 result.reserve(alias.size());
362092 for (idx_t c = 0; c < alias.size(); c++) {
362093 if (alias[c] == '\\') {
362094 c++;
362095 if (c >= alias.size()) {
362096 throw BinderException("Unterminated backslash in COLUMNS(*) \"%s\" alias. Backslashes must either be "
362097 "escaped or followed by a number",
362098 alias);
362099 }
362100 if (alias[c] == '\\') {
362101 result += "\\";
362102 continue;
362103 }
362104 if (alias[c] < '0' || alias[c] > '9') {
362105 throw BinderException("Invalid backslash code in COLUMNS(*) \"%s\" alias. Backslashes must either be "
362106 "escaped or followed by a number",
362107 alias);
362108 }
362109 if (alias[c] == '0') {
362110 result += column_name;
362111 } else if (!regex) {
362112 throw BinderException(
362113 "Only the backslash escape code \\0 can be used when no regex is supplied to COLUMNS(*)");
362114 } else {
362115 string extracted;
362116 RE2::Extract(column_name, *regex, "\\" + alias.substr(c, 1), &extracted);
362117 result += extracted;
362118 }
362119 } else {
362120 result += alias[c];
362121 }
362122 }
362123 return result;
362124}

◆ UnionOperators()

unique_ptr< LogicalOperator > duckdb::Binder::UnionOperators ( vector< unique_ptr< LogicalOperator > > nodes)
368887 {
368888 if (nodes.empty()) {
368889 return nullptr;
368890 }
368891 if (nodes.size() == 1) {
368892 return std::move(nodes[0]);
368893 }
368894 return make_uniq<LogicalSetOperation>(GenerateTableIndex(), 1U, std::move(nodes),
368895 LogicalOperatorType::LOGICAL_UNION, true, false);
368896}

◆ SetSearchPath()

void duckdb::Binder::SetSearchPath ( Catalog & catalog,
const string & schema )
371324 {
371325 auto search_path = GetSearchPath(catalog, schema);
371326 entry_retriever.SetSearchPath(std::move(search_path));
371327}
vector< CatalogSearchEntry > GetSearchPath(Catalog &catalog, const string &schema_name)
Definition duckdb.cpp:371309

◆ GetBinderDepth()

idx_t duckdb::Binder::GetBinderDepth ( ) const
private

Determine the depth of the binder.

374423 {
374424 return depth;
374425}

◆ IncreaseDepth()

void duckdb::Binder::IncreaseDepth ( )
private

Increase the depth of the binder.

374427 {
374428 depth++;
374429 auto max_expression_depth = Settings::Get<MaxExpressionDepthSetting>(context);
374430 if (depth > max_expression_depth) {
374431 throw BinderException("Max expression depth limit of %lld exceeded. Use \"SET max_expression_depth TO x\" to "
374432 "increase the maximum expression depth.",
374433 max_expression_depth);
374434 }
374435}

◆ BindGeneratedColumns()

void duckdb::Binder::BindGeneratedColumns ( BoundCreateTableInfo & info)
private

Bind the expressions of generated columns to check for errors.

Already bound this previously This can not be optimized out of the GetBindOrder function These occurrences happen because we need to make sure that ALL dependencies of a column are resolved before it gets resolved

367915 {
367916 auto &base = info.base->Cast<CreateTableInfo>();
367917
367918 vector<string> names;
367919 vector<LogicalType> types;
367920
367921 D_ASSERT(base.type == CatalogType::TABLE_ENTRY);
367922 for (auto &col : base.columns.Logical()) {
367923 names.push_back(col.Name());
367924 types.push_back(col.Type());
367925 }
367926 auto table_index = GenerateTableIndex();
367927
367928 // Create a new binder because we dont need (or want) these bindings in this scope
367929 auto binder = Binder::CreateBinder(context);
367930 binder->SetCatalogLookupCallback(entry_retriever.GetCallback());
367931 binder->bind_context.AddGenericBinding(table_index, base.table, names, types);
367932 auto expr_binder = ExpressionBinder(*binder, context);
367933 ErrorData ignore;
367934 auto table_binding = binder->bind_context.GetBinding(base.table, ignore);
367935 D_ASSERT(table_binding && !ignore.HasError());
367936
367937 auto bind_order = info.column_dependency_manager.GetBindOrder(base.columns);
367938 logical_index_set_t bound_indices;
367939
367940 while (!bind_order.empty()) {
367941 auto i = bind_order.top();
367942 bind_order.pop();
367943 auto &col = base.columns.GetColumnMutable(i);
367944
367949 if (bound_indices.count(i)) {
367950 continue;
367951 }
367952 D_ASSERT(col.Generated());
367953
367954 auto expression = col.GeneratedExpression().Copy();
367955
367956 auto bound_expression = expr_binder.Bind(expression);
367957 D_ASSERT(bound_expression);
367958 if (bound_expression->HasSubquery()) {
367959 throw BinderException("Failed to bind generated column '%s' because the expression contains a subquery",
367960 col.Name());
367961 }
367962 if (col.Type().id() == LogicalTypeId::ANY) {
367963 // Do this before changing the type, so we know it's the first time the type is set
367964 col.ChangeGeneratedExpressionType(bound_expression->return_type);
367965 col.SetType(bound_expression->return_type);
367966
367967 // Update the type in the binding, for future expansions
367968 table_binding->SetColumnType(i.index, col.Type());
367969 } else if (col.Type().id() == LogicalTypeId::UNBOUND) {
367970 // Bind column type
367971 BindLogicalType(col.TypeMutable());
367972 table_binding->SetColumnType(i.index, col.Type());
367973 }
367974
367975 bound_indices.insert(i);
367976 }
367977}
bool HasError() const
Returns true, if this error data contains an exception, else false.
Definition duckdb.hpp:6527
Here is the call graph for this function:

◆ BindDefaultValues()

void duckdb::Binder::BindDefaultValues ( const ColumnList & columns,
vector< unique_ptr< Expression > > & bound_defaults,
const string & catalog = "",
const string & schema = "" )
private

Bind the default values of the columns of a table.

367980 {
367981 string schema_name = schema_p;
367982 if (schema_p.empty()) {
367983 schema_name = DEFAULT_SCHEMA;
367984 }
367985
367986 auto default_binder = CreateBinderWithSearchPath(catalog_name, schema_name);
367987
367988 for (auto &column : columns.Physical()) {
367989 unique_ptr<Expression> bound_default;
367990 if (column.HasDefaultValue()) {
367991 // we bind a copy of the DEFAULT value because binding is destructive
367992 // and we want to keep the original expression around for serialization
367993 auto default_copy = column.DefaultValue().Copy();
367994 if (default_copy->HasParameter()) {
367995 throw BinderException("DEFAULT values cannot contain parameters");
367996 }
367997 ConstantBinder default_value_binder(*default_binder, context, "DEFAULT value");
367998 default_value_binder.target_type = column.Type();
367999 bound_default = default_value_binder.Bind(default_copy);
368000 } else {
368001 // no default value specified: push a default value of constant null
368002 bound_default = make_uniq<BoundConstantExpression>(Value(column.Type()));
368003 }
368004 bound_defaults.push_back(std::move(bound_default));
368005 }
368006}
Here is the call graph for this function:

◆ BindLimitValue()

BoundLimitNode duckdb::Binder::BindLimitValue ( OrderBinder & order_binder,
unique_ptr< ParsedExpression > limit_val,
bool is_percentage,
bool is_offset )
private

Bind a limit value (LIMIT or OFFSET).

this is a constant

364162 {
364163 auto new_binder = Binder::CreateBinder(context, this);
364164 ExpressionBinder expr_binder(*new_binder, context);
364165 auto target_type = is_percentage ? LogicalType::DOUBLE : LogicalType::BIGINT;
364166 expr_binder.target_type = target_type;
364167 auto original_limit = limit_val->Copy();
364168 auto expr = expr_binder.Bind(limit_val);
364169 if (expr->HasSubquery()) {
364170 if (!order_binder.HasExtraList()) {
364171 throw BinderException("Subquery in LIMIT/OFFSET not supported in set operation");
364172 }
364173 auto bound_limit = order_binder.CreateExtraReference(std::move(original_limit));
364174 if (is_percentage) {
364175 return BoundLimitNode::ExpressionPercentage(std::move(bound_limit));
364176 } else {
364177 return BoundLimitNode::ExpressionValue(std::move(bound_limit));
364178 }
364179 }
364180 if (expr->IsFoldable()) {
364182 auto val = ExpressionExecutor::EvaluateScalar(context, *expr).CastAs(context, target_type);
364183 if (is_percentage) {
364184 D_ASSERT(!is_offset);
364185 double percentage_val;
364186 if (val.IsNull()) {
364187 percentage_val = 100.0;
364188 } else {
364189 percentage_val = val.GetValue<double>();
364190 }
364191 if (Value::IsNan(percentage_val) || percentage_val < 0 || percentage_val > 100) {
364192 throw OutOfRangeException("Limit percent out of range, should be between 0% and 100%");
364193 }
364194 return BoundLimitNode::ConstantPercentage(percentage_val);
364195 } else {
364196 int64_t constant_val;
364197 if (val.IsNull()) {
364198 constant_val = is_offset ? 0 : NumericLimits<int64_t>::Maximum();
364199 } else {
364200 constant_val = val.GetValue<int64_t>();
364201 }
364202 if (constant_val < 0) {
364203 throw BinderException(expr->GetQueryLocation(), "LIMIT/OFFSET cannot be negative");
364204 }
364205 return BoundLimitNode::ConstantValue(constant_val);
364206 }
364207 }
364208 if (!new_binder->correlated_columns.empty()) {
364209 throw BinderException("Correlated columns not supported in LIMIT/OFFSET");
364210 }
364211 // move any correlated columns to this binder
364212 MoveCorrelatedExpressions(*new_binder);
364213 if (is_percentage) {
364214 return BoundLimitNode::ExpressionPercentage(std::move(expr));
364215 } else {
364216 return BoundLimitNode::ExpressionValue(std::move(expr));
364217 }
364218}
void MoveCorrelatedExpressions(Binder &other)
Move correlated expressions from the child binder to this binder.
Definition duckdb.cpp:374661
DUCKDB_API Value CastAs(CastFunctionSet &set, GetCastFunctionInput &get_input, const LogicalType &target_type, bool strict=false) const
Cast this value to another type, throws exception if its not possible.
Definition duckdb.cpp:133710
::int64_t int64_t
Here is the call graph for this function:

◆ MoveCorrelatedExpressions()

void duckdb::Binder::MoveCorrelatedExpressions ( Binder & other)
private

Move correlated expressions from the child binder to this binder.

374661 {
374662 MergeCorrelatedColumns(other.correlated_columns);
374663 other.correlated_columns.clear();
374664}
Here is the caller graph for this function:

◆ BindWithReplacementScan()

BoundStatement duckdb::Binder::BindWithReplacementScan ( ClientContext & context,
BaseTableRef & ref )
private

Tries to bind the table name with replacement scans.

371257 {
371258 auto &config = DBConfig::GetConfig(context);
371259 if (!context.config.use_replacement_scans) {
371260 return BoundStatement();
371261 }
371262 for (auto &scan : config.replacement_scans) {
371263 ReplacementScanInput input(ref.catalog_name, ref.schema_name, ref.table_name);
371264 auto replacement_function = scan.function(context, input, scan.data.get());
371265 if (!replacement_function) {
371266 continue;
371267 }
371268 if (!ref.alias.empty()) {
371269 // user-provided alias overrides the default alias
371270 replacement_function->alias = ref.alias;
371271 } else if (replacement_function->alias.empty()) {
371272 // if the replacement scan itself did not provide an alias we use the table name
371273 replacement_function->alias = ref.table_name;
371274 }
371275 if (replacement_function->type == TableReferenceType::TABLE_FUNCTION) {
371276 auto &table_function = replacement_function->Cast<TableFunctionRef>();
371277 table_function.column_name_alias = ref.column_name_alias;
371278 } else if (replacement_function->type == TableReferenceType::SUBQUERY) {
371279 auto &subquery = replacement_function->Cast<SubqueryRef>();
371280 subquery.column_name_alias = ref.column_name_alias;
371281 } else {
371282 auto select_node = make_uniq<SelectNode>();
371283 select_node->select_list.push_back(make_uniq<StarExpression>());
371284 select_node->from_table = std::move(replacement_function);
371285 auto select_stmt = make_uniq<SelectStatement>();
371286 select_stmt->node = std::move(select_node);
371287 auto subquery = make_uniq<SubqueryRef>(std::move(select_stmt));
371288 subquery->column_name_alias = ref.column_name_alias;
371289 replacement_function = std::move(subquery);
371290 }
371291 if (GetBindingMode() == BindingMode::EXTRACT_REPLACEMENT_SCANS) {
371292 AddReplacementScan(ref.table_name, replacement_function->Copy());
371293 }
371294 return Bind(*replacement_function);
371295 }
371296 return BoundStatement();
371297}

◆ BindWithCTE()

template<class T>
BoundStatement duckdb::Binder::BindWithCTE ( T & statement)
private
374458 {
374459 auto &cte_map = statement.cte_map;
374460 if (cte_map.map.empty()) {
374461 return Bind(statement);
374462 }
374463
374464 auto stmt_node = make_uniq<StatementNode>(statement);
374465 stmt_node->cte_map = cte_map.Copy();
374466 return Bind(*stmt_node);
374467}

◆ Bind() [4/42]

BoundStatement duckdb::Binder::Bind ( SelectStatement & stmt)
private
370437 {
370438 auto &properties = GetStatementProperties();
370439 properties.output_type = QueryResultOutputType::ALLOW_STREAMING;
370440 properties.return_type = StatementReturnType::QUERY_RESULT;
370441 return Bind(*stmt.node);
370442}

◆ Bind() [5/42]

BoundStatement duckdb::Binder::Bind ( InsertStatement & stmt)
private
369653 {
369654 BoundStatement result;
369655 result.names = {"Count"};
369656 result.types = {LogicalType::BIGINT};
369657
369658 BindSchemaOrCatalog(stmt.catalog, stmt.schema);
369659 auto &table = Catalog::GetEntry<TableCatalogEntry>(context, stmt.catalog, stmt.schema, stmt.table);
369660 if (stmt.on_conflict_info) {
369661 // generate a MERGE INTO statement and bind it instead
369662 auto merge_into = GenerateMergeInto(stmt, table);
369663 return Bind(*merge_into);
369664 }
369665 if (table.temporary) {
369666 // Temporary inserts still need a catalog dependency so prepared statements are rebound if the table is dropped.
369667 GetStatementProperties().RegisterDBRead(table.catalog, context);
369668 } else {
369669 // inserting into a non-temporary table: alters underlying database
369670 DatabaseModificationType modification_type = DatabaseModificationType::INSERT_DATA;
369671 GetStatementProperties().RegisterDBModify(table.catalog, context, modification_type);
369672 }
369673
369674 auto insert = make_uniq<LogicalInsert>(table, GenerateTableIndex());
369675
369676 auto values_list = stmt.GetValuesList();
369677
369678 // bind the root select node (if any)
369679 BoundStatement root_select;
369680 if (stmt.column_order == InsertColumnOrder::INSERT_BY_NAME) {
369681 if (values_list) {
369682 throw BinderException("INSERT BY NAME can only be used when inserting from a SELECT statement");
369683 }
369684 if (stmt.default_values) {
369685 throw BinderException("INSERT BY NAME cannot be combined with with DEFAULT VALUES");
369686 }
369687 if (!stmt.columns.empty()) {
369688 throw BinderException("INSERT BY NAME cannot be combined with an explicit column list");
369689 }
369690 D_ASSERT(stmt.select_statement);
369691 // INSERT BY NAME - generate the columns from the names of the SELECT statement
369692 auto select_binder = Binder::CreateBinder(context, this);
369693 root_select = select_binder->Bind(*stmt.select_statement);
369694 MoveCorrelatedExpressions(*select_binder);
369695
369696 stmt.columns = root_select.names;
369697 }
369698
369699 vector<LogicalIndex> named_column_map;
369700 BindInsertColumnList(table, stmt.columns, stmt.default_values, named_column_map, insert->expected_types,
369701 insert->column_index_map);
369702
369703 // bind the default values
369704 auto &catalog_name = table.ParentCatalog().GetName();
369705 auto &schema_name = table.ParentSchema().name;
369706 BindDefaultValues(table.GetColumns(), insert->bound_defaults, catalog_name, schema_name);
369707 insert->bound_constraints = BindConstraints(table);
369708 if (!stmt.select_statement && !stmt.default_values) {
369709 result.plan = std::move(insert);
369710 return result;
369711 }
369712 // Exclude the generated columns from this amount
369713 idx_t expected_columns = stmt.columns.empty() ? table.GetColumns().PhysicalColumnCount() : stmt.columns.size();
369714 ExpandDefaultInValuesList(stmt, table, values_list, named_column_map);
369715
369716 // parse select statement and add to logical plan
369717 unique_ptr<LogicalOperator> root;
369718 if (stmt.select_statement) {
369719 if (stmt.column_order == InsertColumnOrder::INSERT_BY_POSITION) {
369720 auto select_binder = Binder::CreateBinder(context, this);
369721 root_select = select_binder->Bind(*stmt.select_statement);
369722 MoveCorrelatedExpressions(*select_binder);
369723 }
369724 // inserting from a select - check if the column count matches
369725 CheckInsertColumnCountMismatch(expected_columns, root_select.types.size(), !stmt.columns.empty(), table.name);
369726
369727 root = CastLogicalOperatorToTypes(root_select.types, insert->expected_types, std::move(root_select.plan));
369728 } else {
369729 root = make_uniq<LogicalDummyScan>(GenerateTableIndex());
369730 }
369731
369732 insert->AddChild(std::move(root));
369733 if (!stmt.returning_list.empty()) {
369734 insert->return_chunk = true;
369735 auto insert_table_index = GenerateTableIndex();
369736 insert->table_index = insert_table_index;
369737 unique_ptr<LogicalOperator> index_as_logicaloperator = std::move(insert);
369738
369739 return BindReturning(std::move(stmt.returning_list), table, stmt.table_ref ? stmt.table_ref->alias : string(),
369740 insert_table_index, std::move(index_as_logicaloperator));
369741 }
369742
369743 D_ASSERT(result.types.size() == result.names.size());
369744 result.plan = std::move(insert);
369745
369746 auto &properties = GetStatementProperties();
369747 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
369748 properties.return_type = StatementReturnType::CHANGED_ROWS;
369749 return result;
369750}

◆ Bind() [6/42]

BoundStatement duckdb::Binder::Bind ( CopyStatement & stmt,
CopyToType copy_to_type )
private
366706 {
366707 // bind the copy options
366708 BindCopyOptions(*stmt.info);
366709
366710 if (!stmt.info->is_from && !stmt.info->select_statement) {
366711 // copy table into file without a query
366712 // generate SELECT * FROM table;
366713 auto ref = make_uniq<BaseTableRef>();
366714 ref->catalog_name = stmt.info->catalog;
366715 ref->schema_name = stmt.info->schema;
366716 ref->table_name = stmt.info->table;
366717
366718 auto statement = make_uniq<SelectNode>();
366719 statement->from_table = std::move(ref);
366720 if (!stmt.info->select_list.empty()) {
366721 for (auto &name : stmt.info->select_list) {
366722 statement->select_list.push_back(make_uniq<ColumnRefExpression>(name));
366723 }
366724 } else {
366725 statement->select_list.push_back(make_uniq<StarExpression>());
366726 }
366727 stmt.info->select_statement = std::move(statement);
366728 }
366729
366730 // Let's first bind our format
366731 // lookup the format in the catalog
366732 auto on_entry_do =
366733 stmt.info->is_format_auto_detected ? OnEntryNotFound::RETURN_NULL : OnEntryNotFound::THROW_EXCEPTION;
366734 CatalogEntryRetriever entry_retriever {context};
366735 auto &catalog = Catalog::GetSystemCatalog(context);
366736 auto entry = catalog.GetEntry(entry_retriever, DEFAULT_SCHEMA,
366737 {CatalogType::COPY_FUNCTION_ENTRY, stmt.info->format}, on_entry_do);
366738
366739 if (!entry) {
366740 IsFormatExtensionKnown(stmt.info->format);
366741 // If we did not find an entry, we default to a CSV
366742 entry = catalog.GetEntry(entry_retriever, DEFAULT_SCHEMA, {CatalogType::COPY_FUNCTION_ENTRY, "csv"},
366743 OnEntryNotFound::THROW_EXCEPTION);
366744 }
366745 auto &copy_function = entry->Cast<CopyFunctionCatalogEntry>();
366746 auto &function = copy_function.function;
366747
366748 if (function.copy_options) {
366749 // list all copy options - then bind them and offer alternatives
366750 auto copy_mode = stmt.info->is_from ? CopyOptionMode::READ_ONLY : CopyOptionMode::WRITE_ONLY;
366751 auto copy_options = GetFullCopyOptionsList(function, CopyOptionMode::READ_WRITE);
366752 for (auto &provided_entry : stmt.info->options) {
366753 auto &provided_option = provided_entry.first;
366754 auto option_entry = copy_options.find(provided_option);
366755 if (option_entry == copy_options.end()) {
366756 // option not found - offer an alternative suggestion
366757 vector<string> candidates;
366758 for (auto &copy_entry : copy_options) {
366759 candidates.push_back(copy_entry.first);
366760 }
366761 string candidate_str = StringUtil::CandidatesMessage(
366762 StringUtil::TopNJaroWinkler(candidates, provided_option), "Candidate options");
366763
366764 throw NotImplementedException("Unrecognized option \"%s\" for %s\n%s", provided_option,
366765 stmt.info->format, candidate_str);
366766 }
366767 auto &copy_option = option_entry->second;
366768 // check if this matches the mode
366769 if (copy_option.mode != CopyOptionMode::READ_WRITE && copy_option.mode != copy_mode) {
366770 throw InvalidInputException("Option \"%s\" is not supported for %s - only for %s", provided_option,
366771 std::string(stmt.info->is_from ? "reading" : "writing"),
366772 std::string(stmt.info->is_from ? "writing" : "reading"));
366773 }
366774 if (copy_option.type.id() != LogicalTypeId::ANY) {
366775 if (provided_entry.second.empty()) {
366776 if (copy_option.type.id() == LogicalTypeId::BOOLEAN) {
366777 // boolean can be empty (e.g. "HEADER")
366778 continue;
366779 }
366780 throw InvalidInputException("Copy option \"%s\" requires an argument of type %s", provided_option,
366781 copy_option.type.ToString());
366782 }
366783 if (provided_entry.second.size() > 1) {
366784 throw InvalidInputException("Copy option \"%s\" did not expect a list as argument",
366785 provided_option);
366786 }
366787 auto &original_value = provided_entry.second[0];
366788 if (copy_option.type == original_value.type()) {
366789 // types match
366790 continue;
366791 }
366792 bool can_cast =
366793 CastFunctionSet::ImplicitCastCost(context, original_value.type(), copy_option.type) >= 0;
366794 if (!can_cast) {
366795 // for backwards compatibility - we are more lax on casting rules for copy options
366796 if (copy_option.type.IsNumeric()) {
366797 can_cast = original_value.type().IsNumeric();
366798 } else if (copy_option.type.id() == LogicalTypeId::BOOLEAN) {
366799 can_cast = original_value.type().IsIntegral();
366800 }
366801 if (original_value.type().id() == LogicalTypeId::VARCHAR) {
366802 can_cast = true;
366803 }
366804 }
366805
366806 Value new_value;
366807 if (!can_cast || !original_value.TryCastAs(context, copy_option.type, new_value, nullptr)) {
366808 throw InvalidInputException("Copy option \"%s\" expected an argument of type %s - the argument "
366809 "\"%s\" of type %s could not be cast as this type",
366810 provided_option, copy_option.type, original_value.ToString(),
366811 original_value.type());
366812 }
366813 original_value = std::move(new_value);
366814 }
366815 }
366816 }
366817
366818 auto &properties = GetStatementProperties();
366819 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
366820 properties.return_type = StatementReturnType::CHANGED_ROWS;
366821 if (stmt.info->is_from) {
366822 return BindCopyFrom(stmt, function);
366823 } else {
366824 return BindCopyTo(stmt, function, copy_to_type);
366825 }
366826}
static DUCKDB_API Catalog & GetSystemCatalog(ClientContext &context)
Get the SystemCatalog from the ClientContext.
Definition duckdb.cpp:7173
static DUCKDB_API vector< string > TopNJaroWinkler(const vector< string > &strings, const string &target, idx_t n=5, double threshold=0.5)
Definition duckdb.cpp:109902

◆ Bind() [7/42]

BoundStatement duckdb::Binder::Bind ( DeleteStatement & stmt)
private
368416 {
368417 // visit the table reference
368418 auto bound_table = Bind(*stmt.table);
368419 auto root = std::move(bound_table.plan);
368420 if (root->type != LogicalOperatorType::LOGICAL_GET) {
368421 throw BinderException("Can only delete from base table");
368422 }
368423 auto &get = root->Cast<LogicalGet>();
368424 auto table_ptr = get.GetTable();
368425 if (!table_ptr) {
368426 throw BinderException("Can only delete from base table");
368427 }
368428 auto &table = *table_ptr;
368429 if (!table.temporary) {
368430 // delete from persistent table: not read only!
368431 auto &properties = GetStatementProperties();
368432 properties.RegisterDBModify(table.catalog, context, DatabaseModificationType::DELETE_DATA);
368433 }
368434
368435 // plan any tables from the various using clauses
368436 if (!stmt.using_clauses.empty()) {
368437 unique_ptr<LogicalOperator> child_operator;
368438 for (auto &using_clause : stmt.using_clauses) {
368439 // bind the using clause
368440 auto using_binder = Binder::CreateBinder(context, this);
368441 auto op = using_binder->Bind(*using_clause);
368442 if (child_operator) {
368443 // already bound a child: create a cross product to unify the two
368444 child_operator = LogicalCrossProduct::Create(std::move(child_operator), std::move(op.plan));
368445 } else {
368446 child_operator = std::move(op.plan);
368447 }
368448 bind_context.AddContext(std::move(using_binder->bind_context));
368449 }
368450 if (child_operator) {
368451 root = LogicalCrossProduct::Create(std::move(root), std::move(child_operator));
368452 }
368453 }
368454
368455 // project any additional columns required for the condition
368456 unique_ptr<Expression> condition;
368457 if (stmt.condition) {
368458 WhereBinder binder(*this, context);
368459 condition = binder.Bind(stmt.condition);
368460
368461 PlanSubqueries(condition, root);
368462 auto filter = make_uniq<LogicalFilter>(std::move(condition));
368463 filter->AddChild(std::move(root));
368464 root = std::move(filter);
368465 }
368466 // create the delete node
368467 auto del = make_uniq<LogicalDelete>(table, GenerateTableIndex());
368468 del->bound_constraints = BindConstraints(table);
368469 del->AddChild(std::move(root));
368470
368471 // bind the row id columns and add them to the projection list
368472 BindRowIdColumns(table, get, del->expressions);
368473
368474 if (!stmt.returning_list.empty()) {
368475 del->return_chunk = true;
368476
368477 auto update_table_index = GenerateTableIndex();
368478 del->table_index = update_table_index;
368479
368480 unique_ptr<LogicalOperator> del_as_logicaloperator = std::move(del);
368481 return BindReturning(std::move(stmt.returning_list), table, stmt.table->alias, update_table_index,
368482 std::move(del_as_logicaloperator));
368483 }
368484 BoundStatement result;
368485 result.plan = std::move(del);
368486 result.names = {"Count"};
368487 result.types = {LogicalType::BIGINT};
368488
368489 auto &properties = GetStatementProperties();
368490 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
368491 properties.return_type = StatementReturnType::CHANGED_ROWS;
368492
368493 return result;
368494}
void filter(InputArray image, InputArray kernel, OutputArray output)

◆ Bind() [8/42]

BoundStatement duckdb::Binder::Bind ( UpdateStatement & stmt)
private
370986 {
370987 unique_ptr<LogicalOperator> root;
370988
370989 // visit the table reference
370990 auto bound_table = Bind(*stmt.table);
370991 if (bound_table.plan->type != LogicalOperatorType::LOGICAL_GET) {
370992 throw BinderException("Can only update base table");
370993 }
370994 auto &bound_table_get = bound_table.plan->Cast<LogicalGet>();
370995 auto table_ptr = bound_table_get.GetTable();
370996 if (!table_ptr) {
370997 throw BinderException("Can only update base table");
370998 }
370999 auto &table = *table_ptr;
371000
371001 optional_ptr<LogicalGet> get;
371002 if (stmt.from_table) {
371003 auto from_binder = Binder::CreateBinder(context, this);
371004 BoundJoinRef bound_crossproduct(JoinRefType::CROSS);
371005 bound_crossproduct.left = std::move(bound_table);
371006 bound_crossproduct.right = from_binder->Bind(*stmt.from_table);
371007 root = CreatePlan(bound_crossproduct);
371008 get = &root->children[0]->Cast<LogicalGet>();
371009 bind_context.AddContext(std::move(from_binder->bind_context));
371010 } else {
371011 root = std::move(bound_table.plan);
371012 get = &root->Cast<LogicalGet>();
371013 }
371014
371015 if (!table.temporary) {
371016 // update of persistent table: not read only!
371017 auto &properties = GetStatementProperties();
371018 properties.RegisterDBModify(table.catalog, context, DatabaseModificationType::UPDATE_DATA);
371019 }
371020 auto update = make_uniq<LogicalUpdate>(table);
371021
371022 // set return_chunk boolean early because it needs uses update_is_del_and_insert logic
371023 if (!stmt.returning_list.empty()) {
371024 update->return_chunk = true;
371025 }
371026 // bind the default values
371027 auto &catalog_name = table.ParentCatalog().GetName();
371028 auto &schema_name = table.ParentSchema().name;
371029 BindDefaultValues(table.GetColumns(), update->bound_defaults, catalog_name, schema_name);
371030 update->bound_constraints = BindConstraints(table);
371031
371032 // project any additional columns required for the condition/expressions
371033 if (stmt.set_info->condition) {
371034 WhereBinder binder(*this, context);
371035 auto condition = binder.Bind(stmt.set_info->condition);
371036
371037 PlanSubqueries(condition, root);
371038 auto filter = make_uniq<LogicalFilter>(std::move(condition));
371039 filter->AddChild(std::move(root));
371040 root = std::move(filter);
371041 }
371042
371043 D_ASSERT(stmt.set_info);
371044 D_ASSERT(stmt.set_info->columns.size() == stmt.set_info->expressions.size());
371045
371046 auto proj_tmp = BindUpdateSet(*update, std::move(root), *stmt.set_info, table, update->columns,
371047 stmt.prioritize_table_when_binding);
371048 D_ASSERT(proj_tmp->type == LogicalOperatorType::LOGICAL_PROJECTION);
371049 auto proj = unique_ptr_cast<LogicalOperator, LogicalProjection>(std::move(proj_tmp));
371050
371051 // bind any extra columns necessary for CHECK constraints or indexes
371052 table.BindUpdateConstraints(*this, *get, *proj, *update, context);
371053
371054 // finally bind the row id column and add them to the projection list
371055 BindRowIdColumns(table, *get, proj->expressions);
371056
371057 // set the projection as child of the update node and finalize the result
371058 update->AddChild(std::move(proj));
371059
371060 auto update_table_index = GenerateTableIndex();
371061 update->table_index = update_table_index;
371062 if (!stmt.returning_list.empty()) {
371063 unique_ptr<LogicalOperator> update_as_logicaloperator = std::move(update);
371064
371065 return BindReturning(std::move(stmt.returning_list), table, stmt.table->alias, update_table_index,
371066 std::move(update_as_logicaloperator));
371067 }
371068
371069 BoundStatement result;
371070 result.names = {"Count"};
371071 result.types = {LogicalType::BIGINT};
371072 result.plan = std::move(update);
371073
371074 auto &properties = GetStatementProperties();
371075 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
371076 properties.return_type = StatementReturnType::CHANGED_ROWS;
371077 return result;
371078}

◆ Bind() [9/42]

BoundStatement duckdb::Binder::Bind ( CreateStatement & stmt)
private
367418 {
367419 BoundStatement result;
367420 result.names = {"Count"};
367421 result.types = {LogicalType::BIGINT};
367422
367423 auto catalog_type = stmt.info->type;
367424 auto &properties = GetStatementProperties();
367425 switch (catalog_type) {
367426 case CatalogType::SCHEMA_ENTRY: {
367427 auto &base = stmt.info->Cast<CreateInfo>();
367428 auto catalog = BindCatalog(base.catalog);
367429 properties.RegisterDBModify(Catalog::GetCatalog(context, catalog), context,
367430 DatabaseModificationType::CREATE_CATALOG_ENTRY);
367431 result.plan = make_uniq<LogicalCreate>(LogicalOperatorType::LOGICAL_CREATE_SCHEMA, std::move(stmt.info));
367432 break;
367433 }
367434 case CatalogType::VIEW_ENTRY: {
367435 auto &base = stmt.info->Cast<CreateViewInfo>();
367436 // bind the schema
367437 auto &schema = BindCreateSchema(*stmt.info);
367438 BindCreateViewInfo(base);
367439 result.plan = make_uniq<LogicalCreate>(LogicalOperatorType::LOGICAL_CREATE_VIEW, std::move(stmt.info), &schema);
367440 break;
367441 }
367442 case CatalogType::SEQUENCE_ENTRY: {
367443 auto &schema = BindCreateSchema(*stmt.info);
367444 result.plan =
367445 make_uniq<LogicalCreate>(LogicalOperatorType::LOGICAL_CREATE_SEQUENCE, std::move(stmt.info), &schema);
367446 break;
367447 }
367448 case CatalogType::TABLE_MACRO_ENTRY: {
367449 auto &schema = BindCreateFunctionInfo(*stmt.info);
367450 result.plan =
367451 make_uniq<LogicalCreate>(LogicalOperatorType::LOGICAL_CREATE_MACRO, std::move(stmt.info), &schema);
367452 break;
367453 }
367454 case CatalogType::MACRO_ENTRY: {
367455 auto &schema = BindCreateFunctionInfo(*stmt.info);
367456 auto logical_create =
367457 make_uniq<LogicalCreate>(LogicalOperatorType::LOGICAL_CREATE_MACRO, std::move(stmt.info), &schema);
367458 result.plan = std::move(logical_create);
367459 break;
367460 }
367461 case CatalogType::INDEX_ENTRY: {
367462 auto &create_index_info = stmt.info->Cast<CreateIndexInfo>();
367463
367464 // Plan the table scan.
367465 TableDescription table_description(create_index_info.catalog, create_index_info.schema,
367466 create_index_info.table);
367467 auto table_ref = make_uniq<BaseTableRef>(table_description);
367468 auto bound_table = Bind(*table_ref);
367469 auto plan = std::move(bound_table.plan);
367470 if (plan->type != LogicalOperatorType::LOGICAL_GET) {
367471 throw BinderException("can only create an index on a base table");
367472 }
367473 auto &get = plan->Cast<LogicalGet>();
367474 auto table_ptr = get.GetTable();
367475 if (!table_ptr) {
367476 throw BinderException("can only create an index on a base table");
367477 }
367478
367479 auto &table = *table_ptr;
367480 if (table.temporary) {
367481 stmt.info->temporary = true;
367482 }
367483 properties.RegisterDBModify(table.catalog, context, DatabaseModificationType::CREATE_INDEX);
367484 result.plan = table.catalog.BindCreateIndex(*this, stmt, table, std::move(plan));
367485 break;
367486 }
367487 case CatalogType::TABLE_ENTRY: {
367488 auto bound_info = BindCreateTableInfo(std::move(stmt.info));
367489 auto root = std::move(bound_info->query);
367490
367491 // create the logical operator
367492 auto &schema = bound_info->schema;
367493 auto create_table = make_uniq<LogicalCreateTable>(schema, std::move(bound_info));
367494 if (root) {
367495 // CREATE TABLE AS
367496 properties.return_type = StatementReturnType::CHANGED_ROWS;
367497 create_table->children.push_back(std::move(root));
367498 }
367499 result.plan = std::move(create_table);
367500 break;
367501 }
367502 case CatalogType::TYPE_ENTRY: {
367503 auto &schema = BindCreateSchema(*stmt.info);
367504 auto &create_type_info = stmt.info->Cast<CreateTypeInfo>();
367505 result.plan = make_uniq<LogicalCreate>(LogicalOperatorType::LOGICAL_CREATE_TYPE, std::move(stmt.info), &schema);
367506
367507 auto &catalog = Catalog::GetCatalog(context, create_type_info.catalog);
367508 auto &dependencies = create_type_info.dependencies;
367509 auto dependency_callback = [&dependencies, &catalog](CatalogEntry &entry) {
367510 if (&catalog != &entry.ParentCatalog()) {
367511 // Don't register any cross-catalog dependencies
367512 return;
367513 }
367514 dependencies.AddDependency(entry);
367515 };
367516 if (create_type_info.query) {
367517 // CREATE TYPE mood AS ENUM (SELECT 'happy')
367518 auto query_obj = Bind(*create_type_info.query);
367519 auto query = std::move(query_obj.plan);
367520 create_type_info.query.reset();
367521
367522 auto &sql_types = query_obj.types;
367523 if (sql_types.size() != 1) {
367524 // add cast expression?
367525 throw BinderException("The query must return a single column");
367526 }
367527 if (sql_types[0].id() != LogicalType::VARCHAR) {
367528 // push a projection casting to varchar
367529 vector<unique_ptr<Expression>> select_list;
367530 auto ref = make_uniq<BoundColumnRefExpression>(sql_types[0], query->GetColumnBindings()[0]);
367531 auto cast_expr = BoundCastExpression::AddCastToType(context, std::move(ref), LogicalType::VARCHAR);
367532 select_list.push_back(std::move(cast_expr));
367533 auto proj = make_uniq<LogicalProjection>(GenerateTableIndex(), std::move(select_list));
367534 proj->AddChild(std::move(query));
367535 query = std::move(proj);
367536 }
367537
367538 result.plan->AddChild(std::move(query));
367539 } else {
367540 SetCatalogLookupCallback(dependency_callback);
367541 // Bind the underlying type
367542 BindLogicalType(create_type_info.type);
367543 }
367544 break;
367545 }
367546 case CatalogType::SECRET_ENTRY: {
367547 CatalogTransaction transaction = CatalogTransaction(Catalog::GetSystemCatalog(context), context);
367548 properties.return_type = StatementReturnType::QUERY_RESULT;
367549
367550 auto &info = stmt.info->Cast<CreateSecretInfo>();
367551
367552 // We need to execute all expressions in the CreateSecretInfo to construct a CreateSecretInput
367553 ConstantBinder default_binder(*this, context, "Secret Parameter");
367554
367555 string provider_string, type_string;
367556 vector<string> scope_strings;
367557
367558 if (info.provider) {
367559 auto bound_provider = default_binder.Bind(info.provider);
367560 if (bound_provider->HasParameter()) {
367561 throw InvalidInputException("Create Secret expressions can not have parameters!");
367562 }
367563 provider_string =
367564 StringUtil::Lower(ExpressionExecutor::EvaluateScalar(context, *bound_provider, true).ToString());
367565 }
367566 if (info.type) {
367567 auto bound_type = default_binder.Bind(info.type);
367568 if (bound_type->HasParameter()) {
367569 throw InvalidInputException("Create Secret expressions can not have parameters!");
367570 }
367571 type_string = StringUtil::Lower(ExpressionExecutor::EvaluateScalar(context, *bound_type, true).ToString());
367572 }
367573 if (info.scope) {
367574 auto bound_scope = default_binder.Bind(info.scope);
367575 if (bound_scope->HasParameter()) {
367576 throw InvalidInputException("Create Secret expressions can not have parameters!");
367577 }
367578 // Execute all scope expressions
367579 Value scope = ExpressionExecutor::EvaluateScalar(context, *bound_scope, true);
367580 if (scope.type() == LogicalType::VARCHAR) {
367581 scope_strings.push_back(scope.ToString());
367582 } else if (scope.type() == LogicalType::LIST(LogicalType::VARCHAR)) {
367583 for (const auto &item : ListValue::GetChildren(scope)) {
367584 scope_strings.push_back(item.GetValue<string>());
367585 }
367586 } else if (scope.type().InternalType() == PhysicalType::STRUCT) {
367587 // struct expression with empty keys is also allowed for backwards compatibility to when the create
367588 // secret statement would be parsed differently: this allows CREATE SECRET (TYPE x, SCOPE ('bla',
367589 // 'bloe'))
367590 for (const auto &child : StructValue::GetChildren(scope)) {
367591 if (child.type() != LogicalType::VARCHAR) {
367592 throw InvalidInputException(
367593 "Invalid input to scope parameter of create secret: only struct of VARCHARs is allowed");
367594 }
367595 scope_strings.push_back(child.GetValue<string>());
367596 }
367597 } else {
367598 throw InvalidInputException("Create Secret scope must be of type VARCHAR or LIST(VARCHAR)");
367599 }
367600 }
367601
367602 // Execute all options expressions
367603 case_insensitive_map_t<Value> bound_options;
367604 for (auto &option : info.options) {
367605 auto bound_value = default_binder.Bind(option.second);
367606 if (bound_value->HasParameter()) {
367607 throw InvalidInputException("Create Secret expressions can not have parameters!");
367608 }
367609 bound_options.insert({option.first, ExpressionExecutor::EvaluateScalar(context, *bound_value, true)});
367610 }
367611
367612 CreateSecretInput create_secret_input {type_string, provider_string, info.storage_type, info.name,
367613 scope_strings, bound_options, info.on_conflict, info.persist_type};
367614
367615 return SecretManager::Get(context).BindCreateSecret(transaction, create_secret_input);
367616 }
367617 default:
367618 throw InternalException("Unrecognized type!");
367619 }
367620 properties.return_type = StatementReturnType::NOTHING;
367621 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
367622 return result;
367623}
SchemaCatalogEntry & BindCreateFunctionInfo(CreateInfo &info)
Definition duckdb.cpp:367166
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
DUCKDB_API BoundStatement BindCreateSecret(CatalogTransaction transaction, CreateSecretInput &info)
The Bind for create secret is done by the secret manager.
Definition duckdb.cpp:300401
static DUCKDB_API SecretManager & Get(ClientContext &context)
Static Helper Functions.
Definition duckdb.cpp:300872
static DUCKDB_API string Lower(const string &str)
Convert a string to lowercase.
Definition duckdb.cpp:109630
DUCKDB_API string ToString() const
Convert this value to a string.
Definition duckdb.cpp:133318
@ STRUCT
Struct of logical types.
Definition duckdb.hpp:2816

◆ Bind() [10/42]

BoundStatement duckdb::Binder::Bind ( DropStatement & stmt)
private

Secrets are stored in the secret manager; they can always be dropped

368530 {
368531 BoundStatement result;
368532
368533 auto &properties = GetStatementProperties();
368534 switch (stmt.info->type) {
368535 case CatalogType::PREPARED_STATEMENT:
368536 // dropping prepared statements is always possible
368537 // it also does not require a valid transaction
368538 properties.requires_valid_transaction = false;
368539 break;
368540 case CatalogType::SCHEMA_ENTRY: {
368541 // dropping a schema is never read-only because there are no temporary schemas
368542 auto &catalog = Catalog::GetCatalog(context, stmt.info->catalog);
368543 properties.RegisterDBModify(catalog, context, DatabaseModificationType::DROP_CATALOG_ENTRY);
368544 break;
368545 }
368546 case CatalogType::VIEW_ENTRY:
368547 case CatalogType::SEQUENCE_ENTRY:
368548 case CatalogType::MACRO_ENTRY:
368549 case CatalogType::TABLE_MACRO_ENTRY:
368550 case CatalogType::INDEX_ENTRY:
368551 case CatalogType::TABLE_ENTRY:
368552 case CatalogType::TYPE_ENTRY: {
368553 BindSchemaOrCatalog(stmt.info->catalog, stmt.info->schema);
368554 auto catalog = Catalog::GetCatalogEntry(context, stmt.info->catalog);
368555 if (catalog) {
368556 // mark catalog as accessed
368557 properties.RegisterDBRead(*catalog, context);
368558 }
368559 optional_ptr<CatalogEntry> entry;
368560 if (stmt.info->type == CatalogType::MACRO_ENTRY) {
368561 // We also support "DROP MACRO" (instead of "DROP MACRO TABLE") for table macros
368562 // First try to drop a scalar macro
368563 EntryLookupInfo macro_entry_lookup(stmt.info->type, stmt.info->name);
368564 entry = Catalog::GetEntry(context, stmt.info->catalog, stmt.info->schema, macro_entry_lookup,
368565 OnEntryNotFound::RETURN_NULL);
368566 if (!entry) {
368567 // Unable to find a scalar macro, try to drop a table macro
368568 EntryLookupInfo table_macro_entry_lookup(CatalogType::TABLE_MACRO_ENTRY, stmt.info->name);
368569 entry = Catalog::GetEntry(context, stmt.info->catalog, stmt.info->schema, table_macro_entry_lookup,
368570 OnEntryNotFound::RETURN_NULL);
368571 if (entry) {
368572 // Change type to table macro so future lookups get the correct one
368573 stmt.info->type = CatalogType::TABLE_MACRO_ENTRY;
368574 }
368575 }
368576
368577 if (!entry) {
368578 // Unable to find table macro, try again with original OnEntryNotFound to ensure we throw if necessary
368579 entry = Catalog::GetEntry(context, stmt.info->catalog, stmt.info->schema, macro_entry_lookup,
368580 stmt.info->if_not_found);
368581 }
368582 } else {
368583 EntryLookupInfo entry_lookup(stmt.info->type, stmt.info->name);
368584 entry = Catalog::GetEntry(context, stmt.info->catalog, stmt.info->schema, entry_lookup,
368585 stmt.info->if_not_found);
368586 }
368587 if (!entry) {
368588 break;
368589 }
368590 if (entry->internal) {
368591 throw CatalogException("Cannot drop internal catalog entry \"%s\"!", entry->name);
368592 }
368593 stmt.info->catalog = entry->ParentCatalog().GetName();
368594 if (!entry->temporary) {
368595 // we can only drop temporary schema entries in read-only mode
368596 properties.RegisterDBModify(entry->ParentCatalog(), context, DatabaseModificationType::DROP_CATALOG_ENTRY);
368597 }
368598 stmt.info->schema = entry->ParentSchema().name;
368599 break;
368600 }
368601 case CatalogType::SECRET_ENTRY: {
368603 properties.requires_valid_transaction = false;
368604 break;
368605 }
368606 default:
368607 throw BinderException("Unknown catalog type for drop statement: '%s'", CatalogTypeToString(stmt.info->type));
368608 }
368609 result.plan = make_uniq<LogicalSimple>(LogicalOperatorType::LOGICAL_DROP, std::move(stmt.info));
368610 result.names = {"Success"};
368611 result.types = {LogicalType::BOOLEAN};
368612
368613 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
368614 properties.return_type = StatementReturnType::NOTHING;
368615 return result;
368616}
static DUCKDB_API optional_ptr< Catalog > GetCatalogEntry(ClientContext &context, const string &catalog_name)
Gets the specified Catalog from the database if it exists.
Definition duckdb.cpp:7198
Here is the call graph for this function:

◆ Bind() [11/42]

BoundStatement duckdb::Binder::Bind ( AlterStatement & stmt)
private
370618 {
370619 BoundStatement result;
370620 result.names = {"Success"};
370621 result.types = {LogicalType::BOOLEAN};
370622
370623 // Special handling for ALTER DATABASE - doesn't use schema binding
370624 if (stmt.info->type == AlterType::ALTER_DATABASE) {
370625 auto &properties = GetStatementProperties();
370626 properties.return_type = StatementReturnType::NOTHING;
370627 properties.RegisterDBModify(Catalog::GetSystemCatalog(context), context, DatabaseModificationType::ALTER_TABLE);
370628 result.plan = make_uniq<LogicalSimple>(LogicalOperatorType::LOGICAL_ALTER, std::move(stmt.info));
370629 return result;
370630 }
370631
370632 BindSchemaOrCatalog(stmt.info->catalog, stmt.info->schema);
370633
370634 optional_ptr<CatalogEntry> entry;
370635 if (stmt.info->type == AlterType::SET_COLUMN_COMMENT) {
370636 // Extra step for column comments: They can alter a table or a view, and we resolve that here.
370637 auto &info = stmt.info->Cast<SetColumnCommentInfo>();
370638 entry = info.TryResolveCatalogEntry(entry_retriever);
370639 if (entry && info.catalog_entry_type == CatalogType::VIEW_ENTRY) {
370640 // when running SET COLUMN on a VIEW - ensure the view is bound
370641 auto &view = entry->Cast<ViewCatalogEntry>();
370642 view.BindView(context);
370643 }
370644 } else {
370645 // For any other ALTER, we retrieve the catalog entry directly.
370646 EntryLookupInfo lookup_info(stmt.info->GetCatalogType(), stmt.info->name);
370647 entry = entry_retriever.GetEntry(stmt.info->catalog, stmt.info->schema, lookup_info, stmt.info->if_not_found);
370648 }
370649
370650 auto &properties = GetStatementProperties();
370651 properties.return_type = StatementReturnType::NOTHING;
370652 if (!entry) {
370653 // Bind types in this binder
370654 BindAlterTypes(*this, stmt);
370655
370656 result.plan = make_uniq<LogicalSimple>(LogicalOperatorType::LOGICAL_ALTER, std::move(stmt.info));
370657 return result;
370658 }
370659
370660 D_ASSERT(!entry->deleted);
370661 auto &catalog = entry->ParentCatalog();
370662
370663 // Bind types in the same catalog as the entry
370664 auto type_binder = Binder::CreateBinder(context, *this);
370665 type_binder->SetSearchPath(catalog, stmt.info->schema);
370666
370667 BindAlterTypes(*type_binder, stmt);
370668
370669 if (catalog.IsSystemCatalog()) {
370670 throw BinderException("Can not comment on System Catalog entries");
370671 }
370672 if (!entry->temporary) {
370673 // We can only alter temporary tables and views in read-only mode.
370674 properties.RegisterDBModify(catalog, context, DatabaseModificationType::ALTER_TABLE);
370675 }
370676 stmt.info->catalog = catalog.GetName();
370677 stmt.info->schema = entry->ParentSchema().name;
370678
370679 if (!stmt.info->IsAddPrimaryKey()) {
370680 result.plan = make_uniq<LogicalSimple>(LogicalOperatorType::LOGICAL_ALTER, std::move(stmt.info));
370681 return result;
370682 }
370683
370684 return BindAlterAddIndex(result, *entry, std::move(stmt.info));
370685}

◆ Bind() [12/42]

BoundStatement duckdb::Binder::Bind ( PrepareStatement & stmt)
private
370389 {
370390 Planner prepared_planner(context);
370391 auto prepared_data = prepared_planner.PrepareSQLStatement(std::move(stmt.statement));
370392 global_binder_state->bound_tables = prepared_planner.binder->global_binder_state->bound_tables;
370393
370394 if (prepared_planner.properties.always_require_rebind) {
370395 // we always need to rebind - don't keep the plan around
370396 prepared_planner.plan.reset();
370397 }
370398
370399 auto prepare = make_uniq<LogicalPrepare>(stmt.name, std::move(prepared_data), std::move(prepared_planner.plan));
370400 // we can always prepare, even if the transaction has been invalidated
370401 // this is required because most clients ALWAYS invoke prepared statements
370402 auto &properties = GetStatementProperties();
370403 properties.requires_valid_transaction = false;
370404 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
370405 properties.bound_all_parameters = true;
370406 properties.parameter_count = 0;
370407 properties.return_type = StatementReturnType::NOTHING;
370408
370409 BoundStatement result;
370410 result.names = {"Success"};
370411 result.types = {LogicalType::BOOLEAN};
370412 result.plan = std::move(prepare);
370413 return result;
370414}

◆ Bind() [13/42]

BoundStatement duckdb::Binder::Bind ( ExecuteStatement & stmt)
private
368632 {
368633 auto parameter_count = stmt.named_param_map.size();
368634
368635 // bind the prepared statement
368636 auto &client_data = ClientData::Get(context);
368637
368638 auto entry = client_data.prepared_statements.find(stmt.name);
368639 if (entry == client_data.prepared_statements.end()) {
368640 throw BinderException("Prepared statement \"%s\" does not exist", stmt.name);
368641 }
368642
368643 // check if we need to rebind the prepared statement
368644 // this happens if the catalog changes, since in this case e.g. tables we relied on may have been deleted
368645 auto prepared = entry->second;
368646 auto &named_param_map = prepared->unbound_statement->named_param_map;
368647
368648 PreparedStatement::VerifyParameters(stmt.named_values, named_param_map);
368649
368650 auto &mapped_named_values = stmt.named_values;
368651 // bind any supplied parameters
368652 case_insensitive_map_t<BoundParameterData> bind_values;
368653 auto constant_binder = Binder::CreateBinder(context);
368654 constant_binder->SetCanContainNulls(true);
368655 for (auto &pair : mapped_named_values) {
368656 bool is_literal = pair.second->GetExpressionType() == ExpressionType::VALUE_CONSTANT;
368657
368658 ConstantBinder cbinder(*constant_binder, context, "EXECUTE statement");
368659 auto bound_expr = cbinder.Bind(pair.second);
368660 BoundParameterData parameter_data;
368661 if (is_literal) {
368662 auto &constant = bound_expr->Cast<BoundConstantExpression>();
368663 LogicalType return_type;
368664 if (constant.return_type == LogicalTypeId::VARCHAR &&
368665 StringType::GetCollation(constant.return_type).empty()) {
368666 return_type = LogicalTypeId::STRING_LITERAL;
368667 } else if (constant.return_type.IsIntegral()) {
368668 return_type = LogicalType::INTEGER_LITERAL(constant.value);
368669 } else {
368670 return_type = constant.value.type();
368671 }
368672 parameter_data = BoundParameterData(std::move(constant.value), std::move(return_type));
368673 } else {
368674 auto value = ExpressionExecutor::EvaluateScalar(context, *bound_expr, true);
368675 auto value_type = value.type();
368676 parameter_data = BoundParameterData(std::move(value), std::move(value_type));
368677 }
368678 bind_values[pair.first] = std::move(parameter_data);
368679 }
368680 unique_ptr<LogicalOperator> rebound_plan;
368681
368682 RebindQueryInfo rebind = RebindQueryInfo::DO_NOT_REBIND;
368683 if (prepared->RequireRebind(context, bind_values)) {
368684 rebind = RebindQueryInfo::ATTEMPT_TO_REBIND;
368685 }
368686 for (auto &state : context.registered_state->States()) {
368687 BindPreparedStatementCallbackInfo info {*prepared, bind_values};
368688 auto new_rebind = state->OnRebindPreparedStatement(context, info, rebind);
368689 if (new_rebind == RebindQueryInfo::ATTEMPT_TO_REBIND) {
368690 rebind = RebindQueryInfo::ATTEMPT_TO_REBIND;
368691 }
368692 }
368693 if (rebind == RebindQueryInfo::ATTEMPT_TO_REBIND) {
368694 // catalog was modified or statement does not have clear types: rebind the statement before running the execute
368695 Planner prepared_planner(context);
368696 prepared_planner.parameter_data = bind_values;
368697 prepared = prepared_planner.PrepareSQLStatement(entry->second->unbound_statement->Copy());
368698 rebound_plan = std::move(prepared_planner.plan);
368699 D_ASSERT(prepared->properties.bound_all_parameters);
368700 global_binder_state->bound_tables = prepared_planner.binder->global_binder_state->bound_tables;
368701 }
368702 // copy the properties of the prepared statement into the planner
368703 auto &properties = GetStatementProperties();
368704 properties = prepared->properties;
368705 properties.parameter_count = parameter_count;
368706
368707 BoundStatement result;
368708 result.names = prepared->names;
368709 result.types = prepared->types;
368710
368711 prepared->Bind(std::move(bind_values));
368712 if (rebound_plan) {
368713 auto execute_plan = make_uniq<LogicalExecute>(std::move(prepared));
368714 execute_plan->children.push_back(std::move(rebound_plan));
368715 result.plan = std::move(execute_plan);
368716 } else {
368717 result.plan = make_uniq<LogicalExecute>(std::move(prepared));
368718 }
368719 return result;
368720}
R value_type
static DUCKDB_API LogicalType INTEGER_LITERAL(const Value &constant)
Integer literal of the specified value.
Definition duckdb.cpp:140922

◆ Bind() [14/42]

BoundStatement duckdb::Binder::Bind ( TransactionStatement & stmt)
private
370687 {
370688 auto &properties = GetStatementProperties();
370689
370690 // Transaction statements do not require a valid transaction.
370691 properties.requires_valid_transaction = stmt.info->type == TransactionType::BEGIN_TRANSACTION;
370692
370693 BoundStatement result;
370694 result.names = {"Success"};
370695 result.types = {LogicalType::BOOLEAN};
370696 result.plan = make_uniq<LogicalSimple>(LogicalOperatorType::LOGICAL_TRANSACTION, std::move(stmt.info));
370697 properties.return_type = StatementReturnType::NOTHING;
370698 return result;
370699}

◆ Bind() [15/42]

BoundStatement duckdb::Binder::Bind ( PragmaStatement & stmt)
private
370363 {
370364 // bind the pragma function
370365 QueryErrorContext error_context(stmt.stmt_location);
370366 auto bound_info = BindPragma(*stmt.info, error_context);
370367 if (!bound_info->function.function) {
370368 throw BinderException("PRAGMA function does not have a function specified");
370369 }
370370
370371 BoundStatement result;
370372 result.names = {"Success"};
370373 result.types = {LogicalType::BOOLEAN};
370374 result.plan = make_uniq<LogicalPragma>(std::move(bound_info));
370375
370376 auto &properties = GetStatementProperties();
370377 properties.return_type = StatementReturnType::QUERY_RESULT;
370378 return result;
370379}

◆ Bind() [16/42]

BoundStatement duckdb::Binder::Bind ( ExplainStatement & stmt)
private
368729 {
368730 BoundStatement result;
368731
368732 // bind the underlying statement
368733 auto plan = Bind(*stmt.stmt);
368734 // get the unoptimized logical plan, and create the explain statement
368735 auto logical_plan_unopt = plan.plan->ToString(stmt.explain_format);
368736 auto explain = make_uniq<LogicalExplain>(std::move(plan.plan), stmt.explain_type, stmt.explain_format);
368737 explain->logical_plan_unopt = logical_plan_unopt;
368738
368739 result.plan = std::move(explain);
368740 result.names = {"explain_key", "explain_value"};
368741 result.types = {LogicalType::VARCHAR, LogicalType::VARCHAR};
368742
368743 auto &properties = GetStatementProperties();
368744 properties.return_type = StatementReturnType::QUERY_RESULT;
368745 return result;
368746}

◆ Bind() [17/42]

BoundStatement duckdb::Binder::Bind ( VacuumStatement & stmt)
private
371190 {
371191 BoundStatement result;
371192
371193 unique_ptr<LogicalOperator> root;
371194
371195 auto vacuum = make_uniq<LogicalVacuum>(std::move(stmt.info));
371196 BindVacuumTable(*vacuum, root);
371197 if (root) {
371198 vacuum->children.push_back(std::move(root));
371199 }
371200
371201 result.names = {"Success"};
371202 result.types = {LogicalType::BOOLEAN};
371203 result.plan = std::move(vacuum);
371204
371205 auto &properties = GetStatementProperties();
371206 properties.return_type = StatementReturnType::NOTHING;
371207 return result;
371208}

◆ Bind() [18/42]

BoundStatement duckdb::Binder::Bind ( RelationStatement & stmt)
private
370426 {
370427 return stmt.relation->Bind(*this);
370428}

◆ Bind() [19/42]

BoundStatement duckdb::Binder::Bind ( CallStatement & stmt)
private
366188 {
366189 SelectStatement select_statement;
366190 auto select_node = make_uniq<SelectNode>();
366191 auto table_function = make_uniq<TableFunctionRef>();
366192 table_function->function = std::move(stmt.function);
366193 select_node->select_list.push_back(make_uniq<StarExpression>());
366194 select_node->from_table = std::move(table_function);
366195 select_statement.node = std::move(select_node);
366196
366197 auto result = Bind(select_statement);
366198 auto &properties = GetStatementProperties();
366199 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
366200 return result;
366201}

◆ Bind() [20/42]

BoundStatement duckdb::Binder::Bind ( ExportStatement & stmt)
private
368898 {
368899 // COPY TO a file
368900 BoundStatement result;
368901 result.types = {LogicalType::BOOLEAN};
368902 result.names = {"Success"};
368903
368904 // bind copy options
368905 BindCopyOptions(*stmt.info);
368906
368907 // lookup the format in the catalog
368908 auto &copy_function =
368909 Catalog::GetEntry<CopyFunctionCatalogEntry>(context, INVALID_CATALOG, DEFAULT_SCHEMA, stmt.info->format);
368910 if (!copy_function.function.copy_to_bind && !copy_function.function.plan) {
368911 throw NotImplementedException("COPY TO is not supported for FORMAT \"%s\"", stmt.info->format);
368912 }
368913
368914 // gather a list of all the tables
368915 string catalog = stmt.database.empty() ? INVALID_CATALOG : stmt.database;
368916 catalog_entry_vector_t tables;
368917 auto schemas = Catalog::GetSchemas(context, catalog);
368918 for (auto &schema : schemas) {
368919 schema.get().Scan(context, CatalogType::TABLE_ENTRY, [&](CatalogEntry &entry) {
368920 if (entry.type == CatalogType::TABLE_ENTRY) {
368921 tables.push_back(entry.Cast<TableCatalogEntry>());
368922 }
368923 });
368924 }
368925
368926 // reorder tables because of foreign key constraint
368927 ReorderTableEntries(tables);
368928
368929 // now generate the COPY statements for each of the tables
368930 auto &fs = FileSystem::GetFileSystem(context);
368931
368932 auto exported_tables = make_uniq<BoundExportData>();
368933
368934 unordered_set<string> table_name_index;
368935 vector<unique_ptr<LogicalOperator>> export_nodes;
368936 for (auto &t : tables) {
368937 auto &table = t.get().Cast<TableCatalogEntry>();
368938 auto info = make_uniq<CopyInfo>();
368939 // we copy the options supplied to the EXPORT
368940 info->format = stmt.info->format;
368941 info->options = stmt.info->options;
368942 // set up the file name for the COPY TO
368943
368944 idx_t id = 0;
368945 while (true) {
368946 string id_suffix = id == 0 ? string() : "_" + to_string(id);
368947 auto name = CreateFileName(id_suffix, table, copy_function.function.extension);
368948 auto directory = stmt.info->file_path;
368949 auto full_path = fs.JoinPath(directory, name);
368950 info->file_path = full_path;
368951 auto insert_result = table_name_index.insert(info->file_path);
368952 if (insert_result.second) {
368953 // this name was not yet taken: take it
368954 break;
368955 }
368956 id++;
368957 }
368958 info->is_from = false;
368959 info->catalog = catalog;
368960 info->schema = table.schema.name;
368961 info->table = table.name;
368962
368963 // We can not export generated columns
368964 child_list_t<LogicalType> select_list;
368965 // Let's verify if any on these columns have not null constraints
368966 vector<string> not_null_columns;
368967 for (auto &constaint : table.GetConstraints()) {
368968 if (constaint->type == ConstraintType::NOT_NULL) {
368969 auto &not_null_constraint = constaint->Cast<NotNullConstraint>();
368970 not_null_columns.push_back(table.GetColumn(not_null_constraint.index).GetName());
368971 }
368972 }
368973 for (auto &col : table.GetColumns().Physical()) {
368974 select_list.push_back(std::make_pair(col.Name(), col.Type()));
368975 }
368976
368977 ExportedTableData exported_data;
368978 exported_data.database_name = catalog;
368979 exported_data.table_name = info->table;
368980 exported_data.schema_name = info->schema;
368981
368982 exported_data.file_path = info->file_path;
368983
368984 ExportedTableInfo table_info(table, std::move(exported_data), not_null_columns);
368985 exported_tables->data.push_back(table_info);
368986 id++;
368987
368988 // generate the copy statement and bind it
368989 CopyStatement copy_stmt;
368990 copy_stmt.info = std::move(info);
368991 copy_stmt.info->select_statement = CreateSelectStatement(copy_stmt, select_list);
368992
368993 auto copy_binder = Binder::CreateBinder(context, this);
368994 auto bound_statement = copy_binder->Bind(copy_stmt, CopyToType::EXPORT_DATABASE);
368995
368996 auto plan = std::move(bound_statement.plan);
368997
368998 export_nodes.push_back(std::move(plan));
368999 }
369000 auto child_operator = UnionOperators(std::move(export_nodes));
369001
369002 // try to create the directory, if it doesn't exist yet
369003 // a bit hacky to do it here, but we need to create the directory BEFORE the copy statements run
369004 if (!fs.DirectoryExists(stmt.info->file_path)) {
369005 fs.CreateDirectory(stmt.info->file_path);
369006 }
369007
369008 stmt.info->catalog = catalog;
369009 // prepare the options for export
369010 auto &format = stmt.info->format;
369011 auto &options = stmt.info->options;
369012 if (format == "csv") {
369013 // insert default csv options, if not specified
369014 if (options.find("header") == options.end()) {
369015 options["header"].push_back(Value::INTEGER(1));
369016 }
369017 if (options.find("delimiter") == options.end() && options.find("sep") == options.end() &&
369018 options.find("delim") == options.end()) {
369019 options["delimiter"].push_back(Value(","));
369020 }
369021 if (options.find("quote") == options.end()) {
369022 options["quote"].push_back(Value("\""));
369023 }
369024 options.erase("force_quote");
369025 }
369026 // for any options that are write-only, use them for writing but don't put them in the COPY statements we generate
369027 // for reading
369028 auto &function = copy_function.function;
369029 if (function.copy_options) {
369030 auto copy_options = GetFullCopyOptionsList(function, CopyOptionMode::READ_ONLY);
369031 vector<string> erased_options;
369032 for (auto &entry : options) {
369033 if (copy_options.find(entry.first) == copy_options.end()) {
369034 erased_options.push_back(entry.first);
369035 }
369036 }
369037 for (auto &erased : erased_options) {
369038 options.erase(erased);
369039 }
369040 }
369041
369042 // create the export node
369043 auto export_node =
369044 make_uniq<LogicalExport>(copy_function.function, std::move(stmt.info), std::move(exported_tables));
369045
369046 if (child_operator) {
369047 export_node->children.push_back(std::move(child_operator));
369048 }
369049
369050 result.plan = std::move(export_node);
369051
369052 auto &properties = GetStatementProperties();
369053 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
369054 properties.return_type = StatementReturnType::NOTHING;
369055 return result;
369056}
static DUCKDB_API Value INTEGER(int32_t value)
Create an integer Value from a specified value.
Definition duckdb.cpp:132139
std::basic_string< Char > format(const S &format_str, Args &&... args)
Definition duckdb.cpp:16295
std::string to_string(const T &value)
Definition duckdb.cpp:19425

◆ Bind() [21/42]

BoundStatement duckdb::Binder::Bind ( ExtensionStatement & stmt)
private
369065 {
369066 // perform the planning of the function
369067 D_ASSERT(stmt.extension.plan_function);
369068 auto parse_result =
369069 stmt.extension.plan_function(stmt.extension.parser_info.get(), context, std::move(stmt.parse_data));
369070
369071 auto &properties = GetStatementProperties();
369072 properties.modified_databases = parse_result.modified_databases;
369073 properties.requires_valid_transaction = parse_result.requires_valid_transaction;
369074 properties.return_type = parse_result.return_type;
369075
369076 // create the plan as a scan of the given table function
369077 auto result = BindTableFunction(parse_result.function, std::move(parse_result.parameters));
369078 D_ASSERT(result.plan->type == LogicalOperatorType::LOGICAL_GET);
369079 auto &get = result.plan->Cast<LogicalGet>();
369080 get.ClearColumnIds();
369081 for (idx_t i = 0; i < get.returned_types.size(); i++) {
369082 get.AddColumnId(i);
369083 }
369084 return result;
369085}

◆ Bind() [22/42]

BoundStatement duckdb::Binder::Bind ( SetStatement & stmt)
private
370502 {
370503 switch (stmt.set_type) {
370504 case SetType::SET: {
370505 auto &set_stmt = stmt.Cast<SetVariableStatement>();
370506 return Bind(set_stmt);
370507 }
370508 case SetType::RESET: {
370509 auto &set_stmt = stmt.Cast<ResetVariableStatement>();
370510 return Bind(set_stmt);
370511 }
370512 default:
370513 throw NotImplementedException("Type not implemented for SetType");
370514 }
370515}

◆ Bind() [23/42]

BoundStatement duckdb::Binder::Bind ( SetVariableStatement & stmt)
private
370456 {
370457 BoundStatement result;
370458 result.types = {LogicalType::BOOLEAN};
370459 result.names = {"Success"};
370460
370461 // evaluate the scalar value
370462 Value value;
370463 unique_ptr<LogicalOperator> op;
370464 if (stmt.scope != SetScope::VARIABLE) {
370465 ConstantBinder default_binder(*this, context, "SET value");
370466 auto bound_value = default_binder.Bind(stmt.value);
370467 if (bound_value->HasParameter()) {
370468 throw NotImplementedException("SET statements cannot have parameters");
370469 }
370470 value = ExpressionExecutor::EvaluateScalar(context, *bound_value, true);
370471 } else {
370472 auto select_node = make_uniq<SelectNode>();
370473 select_node->select_list.push_back(std::move(stmt.value));
370474 select_node->from_table = make_uniq<EmptyTableRef>();
370475 auto bound_select = Bind(*select_node);
370476 if (bound_select.types.size() > 1) {
370477 throw BinderException("SET variable expected a single input");
370478 }
370479 op = std::move(bound_select.plan);
370480 }
370481 result.plan = make_uniq<LogicalSet>(stmt.name, std::move(value), stmt.scope);
370482 if (op) {
370483 result.plan->children.push_back(std::move(op));
370484 }
370485 auto &properties = GetStatementProperties();
370486 properties.return_type = StatementReturnType::NOTHING;
370487 return result;
370488}

◆ Bind() [24/42]

BoundStatement duckdb::Binder::Bind ( ResetVariableStatement & stmt)
private
370490 {
370491 BoundStatement result;
370492 result.types = {LogicalType::BOOLEAN};
370493 result.names = {"Success"};
370494
370495 result.plan = make_uniq<LogicalReset>(stmt.name, stmt.scope);
370496
370497 auto &properties = GetStatementProperties();
370498 properties.return_type = StatementReturnType::NOTHING;
370499 return result;
370500}

◆ Bind() [25/42]

BoundStatement duckdb::Binder::Bind ( LoadStatement & stmt)
private
369761 {
369762 BoundStatement result;
369763 result.types = {LogicalType::BOOLEAN};
369764 result.names = {"Success"};
369765
369766 // Ensure the repository exists if it's an alias
369767 if (!stmt.info->repository.empty() && stmt.info->repo_is_alias) {
369768 auto repository_url = ExtensionRepository::TryGetRepositoryUrl(stmt.info->repository);
369769 if (repository_url.empty()) {
369770 throw BinderException("'%s' is not a known repository name. Are you trying to query from a repository by "
369771 "path? Use single quotes: `FROM '%s'`",
369772 stmt.info->repository, stmt.info->repository);
369773 }
369774 }
369775
369776 result.plan = make_uniq<LogicalSimple>(LogicalOperatorType::LOGICAL_LOAD, std::move(stmt.info));
369777
369778 auto &properties = GetStatementProperties();
369779 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
369780 properties.return_type = StatementReturnType::NOTHING;
369781 return result;
369782}
static string TryGetRepositoryUrl(const string &repository)
Try to convert a repository to a url, will return empty string if the repository is unknown.
Definition duckdb.cpp:281242

◆ Bind() [26/42]

BoundStatement duckdb::Binder::Bind ( LogicalPlanStatement & stmt)
private
369804 {
369805 BoundStatement result;
369806 result.types = stmt.plan->types;
369807 for (idx_t i = 0; i < result.types.size(); i++) {
369808 result.names.push_back(StringUtil::Format("col%d", i));
369809 }
369810 result.plan = std::move(stmt.plan);
369811
369812 auto &properties = GetStatementProperties();
369813 properties.output_type = QueryResultOutputType::ALLOW_STREAMING;
369814 properties.return_type = StatementReturnType::QUERY_RESULT; // TODO could also be something else
369815
369816 if (parent) {
369817 throw InternalException("LogicalPlanStatement should be bound in root binder");
369818 }
369819 global_binder_state->bound_tables = GetMaxTableIndex(*result.plan) + 1;
369820 return result;
369821}

◆ Bind() [27/42]

BoundStatement duckdb::Binder::Bind ( AttachStatement & stmt)
private
366153 {
366154 BoundStatement result;
366155 result.types = {LogicalType::BOOLEAN};
366156 result.names = {"Success"};
366157
366158 // bind the options
366159 TableFunctionBinder option_binder(*this, context, "Attach", "Attach parameter");
366160 unordered_map<string, Value> kv_options;
366161 for (auto &entry : stmt.info->parsed_options) {
366162 auto bound_expr = option_binder.Bind(entry.second);
366163 auto val = ExpressionExecutor::EvaluateScalar(context, *bound_expr);
366164 if (val.IsNull()) {
366165 throw BinderException("NULL is not supported as a valid option for ATTACH option \"" + entry.first + "\"");
366166 }
366167 stmt.info->options[entry.first] = std::move(val);
366168 }
366169 stmt.info->parsed_options.clear();
366170
366171 result.plan = make_uniq<LogicalSimple>(LogicalOperatorType::LOGICAL_ATTACH, std::move(stmt.info));
366172
366173 auto &properties = GetStatementProperties();
366174 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
366175 properties.return_type = StatementReturnType::NOTHING;
366176 return result;
366177}

◆ Bind() [28/42]

BoundStatement duckdb::Binder::Bind ( DetachStatement & stmt)
private
368504 {
368505 BoundStatement result;
368506
368507 result.plan = make_uniq<LogicalSimple>(LogicalOperatorType::LOGICAL_DETACH, std::move(stmt.info));
368508 result.names = {"Success"};
368509 result.types = {LogicalType::BOOLEAN};
368510
368511 auto &properties = GetStatementProperties();
368512 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
368513 properties.return_type = StatementReturnType::NOTHING;
368514 return result;
368515}

◆ Bind() [29/42]

BoundStatement duckdb::Binder::Bind ( CopyDatabaseStatement & stmt)
private
366930 {
366931 BoundStatement result;
366932
366933 unique_ptr<LogicalOperator> plan;
366934 auto &source_catalog = Catalog::GetCatalog(context, stmt.from_database);
366935 auto &target_catalog = Catalog::GetCatalog(context, stmt.to_database);
366936 if (&source_catalog == &target_catalog) {
366937 throw BinderException("Cannot copy from \"%s\" to \"%s\" - FROM and TO databases are the same",
366938 stmt.from_database, stmt.to_database);
366939 }
366940 if (stmt.copy_type == CopyDatabaseType::COPY_SCHEMA) {
366941 result.types = {LogicalType::BOOLEAN};
366942 result.names = {"Success"};
366943
366944 plan = BindCopyDatabaseSchema(source_catalog, target_catalog.GetName());
366945 } else {
366946 result.types = {LogicalType::BIGINT};
366947 result.names = {"Count"};
366948
366949 plan = BindCopyDatabaseData(source_catalog, target_catalog.GetName());
366950 }
366951
366952 result.plan = std::move(plan);
366953
366954 auto &properties = GetStatementProperties();
366955 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
366956 properties.return_type = StatementReturnType::NOTHING;
366957
366958 DatabaseModificationType modification;
366959 modification |= DatabaseModificationType::INSERT_DATA;
366960 modification |= DatabaseModificationType::CREATE_CATALOG_ENTRY;
366961 properties.RegisterDBModify(target_catalog, context, modification);
366962 return result;
366963}

◆ Bind() [30/42]

BoundStatement duckdb::Binder::Bind ( UpdateExtensionsStatement & stmt)
private
371089 {
371090 BoundStatement result;
371091
371092 result.names.emplace_back("extension_name");
371093 result.types.emplace_back(LogicalType::VARCHAR);
371094 result.names.emplace_back("repository");
371095 result.types.emplace_back(LogicalType::VARCHAR);
371096 result.names.emplace_back("update_result");
371097 result.types.emplace_back(LogicalType::VARCHAR);
371098 result.names.emplace_back("previous_version");
371099 result.types.emplace_back(LogicalType::VARCHAR);
371100 result.names.emplace_back("current_version");
371101 result.types.emplace_back(LogicalType::VARCHAR);
371102
371103 result.plan = make_uniq<LogicalSimple>(LogicalOperatorType::LOGICAL_UPDATE_EXTENSIONS, std::move(stmt.info));
371104
371105 return result;
371106}

◆ Bind() [31/42]

BoundStatement duckdb::Binder::Bind ( MergeIntoStatement & stmt)
private
370108 {
370109 // bind the target table
370110 auto target_binder = Binder::CreateBinder(context, this);
370111 string table_alias = stmt.target->alias;
370112 auto bound_table = target_binder->Bind(*stmt.target);
370113 if (bound_table.plan->type != LogicalOperatorType::LOGICAL_GET) {
370114 throw BinderException("Can only merge into base tables!");
370115 }
370116 auto table_ptr = bound_table.plan->Cast<LogicalGet>().GetTable();
370117 if (!table_ptr) {
370118 throw BinderException("Can only merge into base tables!");
370119 }
370120 auto &table = *table_ptr;
370121 if (!table.temporary) {
370122 // update of persistent table: not read only!
370123 auto &properties = GetStatementProperties();
370124 // modification type depends on actions
370125 DatabaseModificationType modification;
370126 for (auto &action_condition : stmt.actions) {
370127 for (auto &action : action_condition.second) {
370128 switch (action->action_type) {
370129 case MergeActionType::MERGE_UPDATE:
370130 modification |= DatabaseModificationType::UPDATE_DATA;
370131 break;
370132 case MergeActionType::MERGE_DELETE:
370133 modification |= DatabaseModificationType::DELETE_DATA;
370134 break;
370135 case MergeActionType::MERGE_INSERT:
370136 modification |= DatabaseModificationType::INSERT_DATA;
370137 break;
370138 default:
370139 break;
370140 }
370141 }
370142 }
370143 properties.RegisterDBModify(table.catalog, context, modification);
370144 }
370145
370146 // bind the source
370147 auto source_binder = Binder::CreateBinder(context, this);
370148 auto source_binding = source_binder->Bind(*stmt.source);
370149
370150 // get the source names/types
370151 vector<BindingAlias> source_aliases;
370152 vector<string> source_names;
370153 for (auto &binding_entry : source_binder->bind_context.GetBindingsList()) {
370154 auto &binding = *binding_entry;
370155 auto &column_names = binding.GetColumnNames();
370156 for (idx_t c = 0; c < column_names.size(); c++) {
370157 source_aliases.push_back(binding.GetBindingAlias());
370158 source_names.push_back(column_names[c]);
370159 }
370160 }
370161
370162 // bind the join between the source and target
370163 // our conditions determine the join type we need
370164 // if we have WHEN NOT MATCHED BY SOURCE we need all source rows -> RIGHT join
370165 // if we have WHEN NOT MATCHED BY TARGET we need all target rows -> LEFT join
370166 // if we have both -> FULL join
370167 // if we only have WHEN MATCHED we only need matches -> INNER join
370168 JoinRef join;
370169 auto has_not_matched_by_source = stmt.actions.count(MergeActionCondition::WHEN_NOT_MATCHED_BY_SOURCE) > 0;
370170 auto has_not_matched_by_target = stmt.actions.count(MergeActionCondition::WHEN_NOT_MATCHED_BY_TARGET) > 0;
370171 if (has_not_matched_by_source && has_not_matched_by_target) {
370172 join.type = JoinType::OUTER;
370173 } else if (has_not_matched_by_source) {
370174 join.type = JoinType::RIGHT;
370175 } else if (has_not_matched_by_target) {
370176 join.type = JoinType::LEFT;
370177 } else {
370178 join.type = JoinType::INNER;
370179 }
370180 auto &get = bound_table.plan->Cast<LogicalGet>();
370181 join.left = make_uniq<BoundRefWrapper>(std::move(source_binding), std::move(source_binder));
370182 join.right = make_uniq<BoundRefWrapper>(std::move(bound_table), std::move(target_binder));
370183 if (stmt.join_condition) {
370184 join.condition = std::move(stmt.join_condition);
370185 } else {
370186 join.using_columns = std::move(stmt.using_columns);
370187 }
370188 auto bound_join_node = Bind(join);
370189
370190 auto root = std::move(bound_join_node.plan);
370191 auto join_ref = reference<LogicalOperator>(*root);
370192 while (join_ref.get().children.size() == 1) {
370193 join_ref = *join_ref.get().children[0];
370194 }
370195 if (join_ref.get().children.size() != 2) {
370196 throw NotImplementedException("Expected a join after binding a join operator - but got a %s",
370197 join_ref.get().type);
370198 }
370199 // kind of hacky, CreatePlan turns a RIGHT join into a LEFT join so the children get reversed from what we need
370200 bool inverted = join.type == JoinType::RIGHT;
370201 auto &source = join_ref.get().children[inverted ? 1 : 0];
370202
370203 auto merge_into = make_uniq<LogicalMergeInto>(table);
370204 merge_into->table_index = GenerateTableIndex();
370205 if (!stmt.returning_list.empty()) {
370206 merge_into->return_chunk = true;
370207 }
370208
370209 // bind table constraints/default values in case these are referenced
370210 auto &catalog_name = table.ParentCatalog().GetName();
370211 auto &schema_name = table.ParentSchema().name;
370212 BindDefaultValues(table.GetColumns(), merge_into->bound_defaults, catalog_name, schema_name);
370213
370214 merge_into->bound_constraints = BindConstraints(table);
370215
370216 // bind the merge actions
370217 auto proj_index = GenerateTableIndex();
370218 vector<unique_ptr<Expression>> projection_expressions;
370219
370220 for (auto &entry : stmt.actions) {
370221 vector<unique_ptr<BoundMergeIntoAction>> bound_actions;
370222 for (auto &action : entry.second) {
370223 CheckMergeAction(entry.first, action->action_type);
370224 bound_actions.push_back(BindMergeAction(*merge_into, table, get, proj_index, projection_expressions, root,
370225 *action, source_aliases, source_names));
370226 }
370227 merge_into->actions.emplace(entry.first, std::move(bound_actions));
370228 }
370229
370230 if (has_not_matched_by_source) {
370231 // if we have "has_not_matched_by_source" we need to push an extra marker into the source
370232 // this marker tells us if we have found a source match or not
370233 auto new_proj_index = GenerateTableIndex();
370234
370235 source->ResolveOperatorTypes();
370236 auto source_bindings = source->GetColumnBindings();
370237 vector<unique_ptr<Expression>> select_list;
370238 for (idx_t c = 0; c < source_bindings.size(); c++) {
370239 select_list.push_back(make_uniq<BoundColumnRefExpression>(source->types[c], source_bindings[c]));
370240 }
370241
370242 // insert the source marker
370243 auto marker = make_uniq<BoundConstantExpression>(Value::INTEGER(42));
370244 marker->alias = "source_marker";
370245 ColumnBinding source_marker;
370246 source_marker = ColumnBinding(new_proj_index, select_list.size());
370247 select_list.push_back(std::move(marker));
370248
370249 // construct the new projection
370250 auto proj = make_uniq<LogicalProjection>(new_proj_index, std::move(select_list));
370251 proj->children.push_back(std::move(source));
370252 source = std::move(proj);
370253
370254 // rewrite "column_bindings" in the join to refer to the new projection we have just pushed
370255 for (auto &expr : projection_expressions) {
370256 RewriteMergeBindings(expr, source_bindings, new_proj_index);
370257 }
370258 RewriteMergeBindings(*root, source_bindings, new_proj_index);
370259 RewriteMergeBindings(join_ref, source_bindings, new_proj_index);
370260 RewriteMergeBindings(*merge_into, source_bindings, new_proj_index);
370261
370262 // push a reference
370263 merge_into->source_marker = projection_expressions.size();
370264 auto marker_ref = make_uniq<BoundColumnRefExpression>(LogicalType::INTEGER, source_marker);
370265 marker_ref->alias = "source_marker";
370266 projection_expressions.push_back(std::move(marker_ref));
370267 }
370268
370269 merge_into->row_id_start = projection_expressions.size();
370270 // finally bind the row id column and add them to the projection list
370271 BindRowIdColumns(table, get, projection_expressions);
370272
370273 auto proj = make_uniq<LogicalProjection>(proj_index, std::move(projection_expressions));
370274 proj->AddChild(std::move(root));
370275
370276 merge_into->AddChild(std::move(proj));
370277
370278 if (!stmt.returning_list.empty()) {
370279 auto merge_table_index = merge_into->table_index;
370280 unique_ptr<LogicalOperator> index_as_logicaloperator = std::move(merge_into);
370281
370282 // add the merge_action virtual column
370283 virtual_column_map_t virtual_columns;
370284 virtual_columns.insert(make_pair(VIRTUAL_COLUMN_START, TableColumn("merge_action", LogicalType::VARCHAR)));
370285 return BindReturning(std::move(stmt.returning_list), table, table_alias, merge_table_index,
370286 std::move(index_as_logicaloperator), std::move(virtual_columns));
370287 }
370288
370289 BoundStatement result;
370290 result.plan = std::move(merge_into);
370291 result.names = {"Count"};
370292 result.types = {LogicalType::BIGINT};
370293
370294 auto &properties = GetStatementProperties();
370295 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
370296 properties.return_type = StatementReturnType::CHANGED_ROWS;
370297 return result;
370298}
cv::String join(const cv::String &base, const cv::String &path)

◆ BindRowIdColumns()

void duckdb::Binder::BindRowIdColumns ( TableCatalogEntry & table,
LogicalGet & get,
vector< unique_ptr< Expression > > & expressions )
private
370958 {
370959 auto row_id_columns = table.GetRowIdColumns();
370960 auto virtual_columns = table.GetVirtualColumns();
370961 auto &column_ids = get.GetColumnIds();
370962 for (auto &row_id_column : row_id_columns) {
370963 auto row_id_entry = virtual_columns.find(row_id_column);
370964 if (row_id_entry == virtual_columns.end()) {
370965 throw InternalException(
370966 "BindRowIdColumns could not find the row id column in the virtual columns list of the table");
370967 }
370968 // check if this column has alraedy been projected
370969 idx_t column_idx;
370970 for (column_idx = 0; column_idx < column_ids.size(); ++column_idx) {
370971 if (column_ids[column_idx].GetPrimaryIndex() == row_id_column) {
370972 // it has! avoid projecting it again
370973 break;
370974 }
370975 }
370976 auto row_id_expr =
370977 make_uniq<BoundColumnRefExpression>(row_id_entry->second.type, ColumnBinding(get.table_index, column_idx));
370978 row_id_expr->alias = row_id_entry->second.name;
370979 expressions.push_back(std::move(row_id_expr));
370980 if (column_idx == column_ids.size()) {
370981 get.AddColumnId(row_id_column);
370982 }
370983 }
370984}

◆ BindReturning()

BoundStatement duckdb::Binder::BindReturning ( vector< unique_ptr< ParsedExpression > > returning_list,
TableCatalogEntry & table,
const string & alias,
idx_t update_table_index,
unique_ptr< LogicalOperator > child_operator,
virtual_column_map_t virtual_columns = virtual_column_map_t() )
private
374761 {
374762 vector<LogicalType> types;
374763 vector<string> names;
374764
374765 auto binder = Binder::CreateBinder(context);
374766
374767 vector<ColumnIndex> bound_columns;
374768 idx_t column_count = 0;
374769 for (auto &col : table.GetColumns().Logical()) {
374770 names.push_back(col.Name());
374771 types.push_back(col.Type());
374772 if (!col.Generated()) {
374773 bound_columns.emplace_back(column_count);
374774 }
374775 column_count++;
374776 }
374777
374778 binder->bind_context.AddBaseTable(update_table_index, alias, names, types, bound_columns, table,
374779 std::move(virtual_columns));
374780 ReturningBinder returning_binder(*binder, context);
374781
374782 vector<unique_ptr<Expression>> projection_expressions;
374783 LogicalType result_type;
374784 vector<unique_ptr<ParsedExpression>> new_returning_list;
374785 BoundStatement result;
374786 binder->ExpandStarExpressions(returning_list, new_returning_list);
374787 for (auto &returning_expr : new_returning_list) {
374788 VerifyNotExcluded(*returning_expr);
374789 auto expr = returning_binder.Bind(returning_expr, &result_type);
374790 result.names.push_back(expr->GetName());
374791 result.types.push_back(result_type);
374792 projection_expressions.push_back(std::move(expr));
374793 }
374794 if (new_returning_list.empty()) {
374795 throw BinderException("RETURNING list is empty!");
374796 }
374797 auto projection = make_uniq<LogicalProjection>(GenerateTableIndex(), std::move(projection_expressions));
374798 projection->AddChild(std::move(child_operator));
374799 D_ASSERT(result.types.size() == result.names.size());
374800 result.plan = std::move(projection);
374801 // If an insert/delete/update statement returns data, there are sometimes issues with streaming results
374802 // where the data modification doesn't take place until the streamed result is exhausted. Once a row is
374803 // returned, it should be guaranteed that the row has been inserted.
374804 // see https://github.com/duckdb/duckdb/issues/8310
374805 auto &properties = GetStatementProperties();
374806 properties.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
374807 properties.return_type = StatementReturnType::QUERY_RESULT;
374808 return result;
374809}

◆ BindTableMacro()

unique_ptr< QueryNode > duckdb::Binder::BindTableMacro ( FunctionExpression & function,
TableMacroCatalogEntry & macro_func,
idx_t depth )
private
365228 {
365229 // validate the arguments and separate positional and default arguments
365230 vector<unique_ptr<ParsedExpression>> positional_arguments;
365231 InsertionOrderPreservingMap<unique_ptr<ParsedExpression>> named_arguments;
365232
365233 auto bind_result = MacroFunction::BindMacroFunction(*this, macro_func.macros, macro_func.name, function,
365234 positional_arguments, named_arguments, depth);
365235 if (!bind_result.error.empty()) {
365236 throw BinderException(function, bind_result.error);
365237 }
365238 auto &macro_def = *macro_func.macros[bind_result.function_idx.GetIndex()];
365239
365240 auto new_macro_binding =
365241 MacroFunction::CreateDummyBinding(macro_def, macro_func.name, positional_arguments, named_arguments);
365242 new_macro_binding->arguments = &positional_arguments;
365243
365244 // We need an ExpressionBinder so that we can call ExpressionBinder::ReplaceMacroParametersRecursive()
365245 auto eb = ExpressionBinder(*this, this->context);
365246
365247 eb.macro_binding = new_macro_binding.get();
365248 vector<unordered_set<string>> lambda_params;
365249
365250 auto node = macro_def.Cast<TableMacroFunction>().query_node->Copy();
365251 ParsedExpressionIterator::EnumerateQueryNodeChildren(
365252 *node, [&](unique_ptr<ParsedExpression> &child) { eb.ReplaceMacroParameters(child, lambda_params); });
365253
365254 return node;
365255}

◆ BindNode() [1/5]

BoundStatement duckdb::Binder::BindNode ( SelectNode & node)
private
364494 {
364495 D_ASSERT(statement.from_table);
364496
364497 // first bind the FROM table statement
364498 auto from = std::move(statement.from_table);
364499 auto from_table = Bind(*from);
364500 return BindSelectNode(statement, std::move(from_table));
364501}

◆ BindNode() [2/5]

BoundStatement duckdb::Binder::BindNode ( SetOperationNode & node)
private
365098 {
365099 BoundSetOperationNode result;
365100 result.setop_type = statement.setop_type;
365101 result.setop_all = statement.setop_all;
365102
365103 // first recursively visit the set operations
365104 // all children have an independent BindContext and Binder
365105 result.setop_index = GenerateTableIndex();
365106 if (statement.children.size() < 2) {
365107 throw InternalException("Set Operations must have at least 2 children");
365108 }
365109 if (statement.children.size() != 2 && statement.setop_type != SetOperationType::UNION &&
365110 statement.setop_type != SetOperationType::UNION_BY_NAME) {
365111 throw InternalException("Set Operation type must have exactly 2 children - except for UNION/UNION_BY_NAME");
365112 }
365113 for (auto &child : statement.children) {
365114 auto child_binder = Binder::CreateBinder(context, this);
365115 child_binder->can_contain_nulls = true;
365116 auto child_node = child_binder->BindNode(*child);
365117 MoveCorrelatedExpressions(*child_binder);
365118 result.bound_children.push_back(std::move(child_node));
365119 result.child_binders.push_back(std::move(child_binder));
365120 }
365121
365122 if (result.setop_type == SetOperationType::UNION_BY_NAME) {
365123 // UNION BY NAME - merge the columns from all sides
365124 BuildUnionByNameInfo(result);
365125 } else {
365126 // UNION ALL BY POSITION - the columns of both sides must match exactly
365127 result.names = result.bound_children[0].names;
365128 auto result_columns = result.bound_children[0].types.size();
365129 for (idx_t i = 1; i < result.bound_children.size(); ++i) {
365130 if (result.bound_children[i].types.size() != result_columns) {
365131 throw BinderException("Set operations can only apply to expressions with the "
365132 "same number of result columns");
365133 }
365134 }
365135
365136 // figure out the types of the setop result by picking the max of both
365137 for (idx_t i = 0; i < result_columns; i++) {
365138 auto result_type = result.bound_children[0].types[i];
365139 for (idx_t child_idx = 1; child_idx < result.bound_children.size(); ++child_idx) {
365140 auto &child_types = result.bound_children[child_idx].types;
365141 result_type = LogicalType::ForceMaxLogicalType(result_type, child_types[i]);
365142 }
365143 if (!can_contain_nulls) {
365144 if (ExpressionBinder::ContainsNullType(result_type)) {
365145 result_type = ExpressionBinder::ExchangeNullType(result_type);
365146 }
365147 }
365148 result.types.push_back(result_type);
365149 }
365150 }
365151
365152 if (!statement.setop_all) {
365153 statement.modifiers.insert(statement.modifiers.begin(), make_uniq<DistinctModifier>());
365154 statement.setop_all = false; // Already handled
365155 }
365156
365157 SelectBindState bind_state;
365158 if (!statement.modifiers.empty()) {
365159 // handle the ORDER BY/DISTINCT clauses
365160 vector<reference<Binder>> binders;
365161 GatherSetOpBinders(result.bound_children, result.child_binders, binders);
365162 GatherAliases(result, result.bound_children, bind_state);
365163
365164 // now we perform the actual resolution of the ORDER BY/DISTINCT expressions
365165 OrderBinder order_binder(binders, bind_state);
365166 PrepareModifiers(order_binder, statement, result);
365167 }
365168
365169 // finally bind the types of the ORDER/DISTINCT clause expressions
365170 BindModifiers(result, result.setop_index, result.names, result.types, bind_state);
365171
365172 BoundStatement result_statement;
365173 result_statement.types = result.types;
365174 result_statement.names = result.names;
365175 result_statement.plan = CreatePlan(result);
365176 result_statement.extra_info.setop_type = statement.setop_type;
365177 result_statement.extra_info.bound_children = std::move(result.bound_children);
365178 result_statement.extra_info.child_binders = std::move(result.child_binders);
365179 return result_statement;
365180}
static DUCKDB_API LogicalType ForceMaxLogicalType(const LogicalType &left, const LogicalType &right)
Forcibly returns a maximum logical type - similar to MaxLogicalType but never throws....
Definition duckdb.cpp:140319

◆ BindNode() [3/5]

BoundStatement duckdb::Binder::BindNode ( RecursiveCTENode & node)
private
363782 {
363783 // first recursively visit the recursive CTE operations
363784 // the left side is visited first and is added to the BindContext of the right side
363785 D_ASSERT(statement.left);
363786 D_ASSERT(statement.right);
363787
363788 auto is_using_key = !statement.key_targets.empty();
363789
363790 if (is_using_key) {
363791 auto setting = Settings::Get<DeprecatedUsingKeySyntaxSetting>(context);
363792
363793 // The USING KEY currently implement is actually the UNION ALL variant,
363794 // but we use UNION syntax. This stands in the way of a possible addition of
363795 // the UNION variant, so we will deprecate the UNION syntax for now (with
363796 // the ability to still use it via a setting). Once enough time has elapsed
363797 // and users have migrated relevant code to using UNION ALL syntax, we can
363798 // declare the UNION syntax either as illegal syntax or implement the UNION
363799 // variant proper (again with the ability to override the UNION syntax to
363800 // use the "old" UNION ALL variant).
363801
363802 bool warn_deprecated_syntax = setting == DeprecatedUsingKeySyntax::DEFAULT && !statement.union_all;
363803 const string msg =
363804 "Deprecated UNION in USING KEY CTE detected."
363805 "Please transition to using UNION ALL, before DuckDB's next release. \n"
363806 "Use SET deprecated_using_key_syntax='UNION_AS_UNION_ALL' to enable the deprecated behavior. \n"
363807 "For more information, see "
363808 "https://duckdb.org/docs/stable/sql/query_syntax/with#recursive-ctes-with-using-key.";
363809
363810 if (warn_deprecated_syntax) {
363811 DUCKDB_LOG_WARNING(context, msg);
363812 }
363813 }
363814
363815 auto ctename = statement.ctename;
363816 auto union_all = statement.union_all;
363817 auto setop_index = GenerateTableIndex();
363818
363819 auto left_binder = Binder::CreateBinder(context, this);
363820 auto left = left_binder->BindNode(*statement.left);
363821
363822 BoundStatement result;
363823 // the result types of the CTE are the types of the LHS
363824 result.types = left.types;
363825 // names are picked from the LHS, unless aliases are explicitly specified
363826 result.names = left.names;
363827 for (idx_t i = 0; i < statement.aliases.size() && i < result.names.size(); i++) {
363828 result.names[i] = statement.aliases[i];
363829 }
363830
363831 // This allows the right side to reference the CTE recursively
363832 bind_context.AddGenericBinding(setop_index, statement.ctename, result.names, result.types);
363833
363834 auto right_binder = Binder::CreateBinder(context, this);
363835
363836 // Add bindings of left side to temporary CTE bindings context
363837 BindingAlias cte_alias(statement.ctename);
363838 right_binder->bind_context.AddCTEBinding(setop_index, std::move(cte_alias), result.names, result.types);
363839
363840 BindingAlias recurring_alias("recurring", statement.ctename);
363841 right_binder->bind_context.AddCTEBinding(setop_index, std::move(recurring_alias), result.names, result.types);
363842
363843 auto right = right_binder->BindNode(*statement.right);
363844 for (auto &c : left_binder->correlated_columns) {
363845 right_binder->AddCorrelatedColumn(c);
363846 }
363847
363848 // move the correlated expressions from the child binders to this binder
363849 MoveCorrelatedExpressions(*left_binder);
363850 MoveCorrelatedExpressions(*right_binder);
363851
363852 vector<unique_ptr<Expression>> key_targets;
363853 // bind specified keys to the referenced column
363854 auto expression_binder = ExpressionBinder(*this, context);
363855 for (auto &expr : statement.key_targets) {
363856 auto bound_expr = expression_binder.Bind(expr);
363857 D_ASSERT(bound_expr->type == ExpressionType::BOUND_COLUMN_REF);
363858 key_targets.push_back(std::move(bound_expr));
363859 }
363860
363861 // now both sides have been bound we can resolve types
363862 if (left.types.size() != right.types.size()) {
363863 throw BinderException("Set operations can only apply to expressions with the "
363864 "same number of result columns");
363865 }
363866
363867 if (!statement.modifiers.empty()) {
363868 throw NotImplementedException("FIXME: bind modifiers in recursive CTE");
363869 }
363870
363871 // Generate the logical plan for the left and right sides of the set operation
363872 left_binder->is_outside_flattened = is_outside_flattened;
363873 right_binder->is_outside_flattened = is_outside_flattened;
363874
363875 auto left_node = std::move(left.plan);
363876 auto right_node = std::move(right.plan);
363877
363878 // check if there are any unplanned subqueries left in either child
363879 has_unplanned_dependent_joins = has_unplanned_dependent_joins || left_binder->has_unplanned_dependent_joins ||
363880 right_binder->has_unplanned_dependent_joins;
363881
363882 // for both the left and right sides, cast them to the same types
363883 left_node = CastLogicalOperatorToTypes(left.types, result.types, std::move(left_node));
363884 right_node = CastLogicalOperatorToTypes(right.types, result.types, std::move(right_node));
363885
363886 auto recurring_binding = right_binder->GetCTEBinding(BindingAlias("recurring", ctename));
363887 bool ref_recurring = recurring_binding && recurring_binding->IsReferenced();
363888
363889 // Check if there is a reference to the recursive or recurring table, if not create a set operator.
363890 auto cte_binding = right_binder->GetCTEBinding(BindingAlias(ctename));
363891 bool ref_cte = cte_binding && cte_binding->IsReferenced();
363892 if (!ref_cte && !ref_recurring) {
363893 auto root =
363894 make_uniq<LogicalSetOperation>(setop_index, result.types.size(), std::move(left_node),
363895 std::move(right_node), LogicalOperatorType::LOGICAL_UNION, union_all);
363896 result.plan = std::move(root);
363897 } else {
363898 auto root = make_uniq<LogicalRecursiveCTE>(ctename, setop_index, result.types.size(), union_all,
363899 std::move(key_targets), std::move(left_node), std::move(right_node));
363900 root->ref_recurring = ref_recurring;
363901 result.plan = std::move(root);
363902 }
363903 return result;
363904}
bool is_outside_flattened
Whether or not outside dependent joins have been planned and flattened.
Definition duckdb.cpp:2111
bool has_unplanned_dependent_joins
Whether or not the binder has any unplanned dependent joins that still need to be planned/flattened.
Definition duckdb.cpp:2109

◆ BindNode() [4/5]

BoundStatement duckdb::Binder::BindNode ( QueryNode & node)
private
363625 {
363626 reference<Binder> current_binder(*this);
363627 vector<BoundCTEData> bound_ctes;
363628 for (auto &cte : node.cte_map.map) {
363629 bound_ctes.push_back(current_binder.get().PrepareCTE(cte.first, *cte.second));
363630 current_binder = *bound_ctes.back().child_binder;
363631 }
363632 BoundStatement result;
363633 // now we bind the node
363634 switch (node.type) {
363635 case QueryNodeType::SELECT_NODE:
363636 result = current_binder.get().BindNode(node.Cast<SelectNode>());
363637 break;
363638 case QueryNodeType::RECURSIVE_CTE_NODE:
363639 result = current_binder.get().BindNode(node.Cast<RecursiveCTENode>());
363640 break;
363641 case QueryNodeType::SET_OPERATION_NODE:
363642 result = current_binder.get().BindNode(node.Cast<SetOperationNode>());
363643 break;
363644 case QueryNodeType::STATEMENT_NODE:
363645 result = current_binder.get().BindNode(node.Cast<StatementNode>());
363646 break;
363647 default:
363648 throw InternalException("Unsupported query node type");
363649 }
363650 for (idx_t i = bound_ctes.size(); i > 0; i--) {
363651 auto &finish_binder = i == 1 ? *this : *bound_ctes[i - 2].child_binder;
363652 result = finish_binder.FinishCTE(bound_ctes[i - 1], std::move(result));
363653 }
363654 return result;
363655}

◆ BindNode() [5/5]

BoundStatement duckdb::Binder::BindNode ( StatementNode & node)
private
365192 {
365193 // switch on type here to ensure we bind WITHOUT ctes to prevent infinite recursion
365194 switch (statement.stmt.type) {
365195 case StatementType::INSERT_STATEMENT:
365196 return Bind(statement.stmt.Cast<InsertStatement>());
365197 case StatementType::DELETE_STATEMENT:
365198 return Bind(statement.stmt.Cast<DeleteStatement>());
365199 case StatementType::UPDATE_STATEMENT:
365200 return Bind(statement.stmt.Cast<UpdateStatement>());
365201 case StatementType::MERGE_INTO_STATEMENT:
365202 return Bind(statement.stmt.Cast<MergeIntoStatement>());
365203 default:
365204 return Bind(statement.stmt);
365205 }
365206}

◆ VisitQueryNode()

unique_ptr< LogicalOperator > duckdb::Binder::VisitQueryNode ( BoundQueryNode & node,
unique_ptr< LogicalOperator > root )
private
365267 {
365268 D_ASSERT(root);
365269 for (auto &mod : node.modifiers) {
365270 switch (mod->type) {
365271 case ResultModifierType::DISTINCT_MODIFIER: {
365272 auto &bound = mod->Cast<BoundDistinctModifier>();
365273 if (bound.target_distincts.empty()) {
365274 break;
365275 }
365276 auto distinct = make_uniq<LogicalDistinct>(std::move(bound.target_distincts), bound.distinct_type);
365277 distinct->AddChild(std::move(root));
365278 root = std::move(distinct);
365279 break;
365280 }
365281 case ResultModifierType::ORDER_MODIFIER: {
365282 auto &bound = mod->Cast<BoundOrderModifier>();
365283 if (root->type == LogicalOperatorType::LOGICAL_DISTINCT) {
365284 auto &distinct = root->Cast<LogicalDistinct>();
365285 if (distinct.distinct_type == DistinctType::DISTINCT_ON) {
365286 auto order_by = make_uniq<BoundOrderModifier>();
365287 for (auto &order_node : bound.orders) {
365288 order_by->orders.push_back(order_node.Copy());
365289 }
365290 distinct.order_by = std::move(order_by);
365291 }
365292 }
365293 auto order = make_uniq<LogicalOrder>(std::move(bound.orders));
365294 order->AddChild(std::move(root));
365295 root = std::move(order);
365296 break;
365297 }
365298 case ResultModifierType::LIMIT_MODIFIER: {
365299 auto &bound = mod->Cast<BoundLimitModifier>();
365300 auto limit = make_uniq<LogicalLimit>(std::move(bound.limit_val), std::move(bound.offset_val));
365301 limit->AddChild(std::move(root));
365302 root = std::move(limit);
365303 break;
365304 }
365305 default:
365306 throw BinderException("Unimplemented modifier type!");
365307 }
365308 }
365309 return root;
365310}

◆ CreatePlan() [1/3]

unique_ptr< LogicalOperator > duckdb::Binder::CreatePlan ( BoundSelectNode & statement)
private
365330 {
365331 D_ASSERT(statement.from_table.plan);
365332 auto root = std::move(statement.from_table.plan);
365333
365334 // plan the sample clause
365335 if (statement.sample_options) {
365336 root = make_uniq<LogicalSample>(std::move(statement.sample_options), std::move(root));
365337 }
365338
365339 if (statement.where_clause) {
365340 root = PlanFilter(std::move(statement.where_clause), std::move(root));
365341 }
365342
365343 if (!statement.aggregates.empty() || !statement.groups.group_expressions.empty() || statement.having) {
365344 if (!statement.groups.group_expressions.empty()) {
365345 // visit the groups
365346 for (auto &group : statement.groups.group_expressions) {
365347 PlanSubqueries(group, root);
365348 }
365349 }
365350 // now visit all aggregate expressions
365351 for (auto &expr : statement.aggregates) {
365352 PlanSubqueries(expr, root);
365353 }
365354 // finally create the aggregate node with the group_index and aggregate_index as obtained from the binder
365355 auto aggregate = make_uniq<LogicalAggregate>(statement.group_index, statement.aggregate_index,
365356 std::move(statement.aggregates));
365357 aggregate->groups = std::move(statement.groups.group_expressions);
365358 aggregate->groupings_index = statement.groupings_index;
365359 aggregate->grouping_sets = std::move(statement.groups.grouping_sets);
365360 aggregate->grouping_functions = std::move(statement.grouping_functions);
365361
365362 aggregate->AddChild(std::move(root));
365363 root = std::move(aggregate);
365364 } else if (!statement.groups.grouping_sets.empty()) {
365365 // edge case: we have grouping sets but no groups or aggregates
365366 // this can only happen if we have e.g. select 1 from tbl group by ();
365367 // just output a dummy scan
365368 root = make_uniq_base<LogicalOperator, LogicalDummyScan>(statement.group_index);
365369 }
365370
365371 if (statement.having) {
365372 PlanSubqueries(statement.having, root);
365373 auto having = make_uniq<LogicalFilter>(std::move(statement.having));
365374
365375 having->AddChild(std::move(root));
365376 root = std::move(having);
365377 }
365378
365379 if (!statement.windows.empty()) {
365380 auto win = make_uniq<LogicalWindow>(statement.window_index);
365381 win->expressions = std::move(statement.windows);
365382 // visit the window expressions
365383 for (auto &expr : win->expressions) {
365384 PlanSubqueries(expr, root);
365385 }
365386 D_ASSERT(!win->expressions.empty());
365387 win->AddChild(std::move(root));
365388 root = std::move(win);
365389 }
365390
365391 if (statement.qualify) {
365392 PlanSubqueries(statement.qualify, root);
365393 auto qualify = make_uniq<LogicalFilter>(std::move(statement.qualify));
365394
365395 qualify->AddChild(std::move(root));
365396 root = std::move(qualify);
365397 }
365398
365399 for (idx_t i = statement.unnests.size(); i > 0; i--) {
365400 auto unnest_level = i - 1;
365401 auto entry = statement.unnests.find(unnest_level);
365402 if (entry == statement.unnests.end()) {
365403 throw InternalException("unnests specified at level %d but none were found", unnest_level);
365404 }
365405 auto &unnest_node = entry->second;
365406 auto unnest = make_uniq<LogicalUnnest>(unnest_node.index);
365407 unnest->expressions = std::move(unnest_node.expressions);
365408 // visit the unnest expressions
365409 for (auto &expr : unnest->expressions) {
365410 PlanSubqueries(expr, root);
365411 }
365412 D_ASSERT(!unnest->expressions.empty());
365413 unnest->AddChild(std::move(root));
365414 root = std::move(unnest);
365415 }
365416
365417 for (auto &expr : statement.select_list) {
365418 PlanSubqueries(expr, root);
365419 }
365420
365421 auto proj = make_uniq<LogicalProjection>(statement.projection_index, std::move(statement.select_list));
365422 auto &projection = *proj;
365423 proj->AddChild(std::move(root));
365424 root = std::move(proj);
365425
365426 // finish the plan by handling the elements of the QueryNode
365427 root = VisitQueryNode(statement, std::move(root));
365428
365429 // add a prune node if necessary
365430 if (statement.need_prune) {
365431 D_ASSERT(root);
365432 vector<unique_ptr<Expression>> prune_expressions;
365433 for (idx_t i = 0; i < statement.column_count; i++) {
365434 prune_expressions.push_back(make_uniq<BoundColumnRefExpression>(
365435 projection.expressions[i]->return_type, ColumnBinding(statement.projection_index, i)));
365436 }
365437 auto prune = make_uniq<LogicalProjection>(statement.prune_index, std::move(prune_expressions));
365438 prune->AddChild(std::move(root));
365439 root = std::move(prune);
365440 }
365441 return root;
365442}

◆ CreatePlan() [2/3]

unique_ptr< LogicalOperator > duckdb::Binder::CreatePlan ( BoundSetOperationNode & node)
private
365539 {
365540 // create actual logical ops for setops
365541 LogicalOperatorType logical_type = LogicalOperatorType::LOGICAL_INVALID;
365542 switch (node.setop_type) {
365543 case SetOperationType::UNION:
365544 case SetOperationType::UNION_BY_NAME:
365545 logical_type = LogicalOperatorType::LOGICAL_UNION;
365546 break;
365547 case SetOperationType::EXCEPT:
365548 logical_type = LogicalOperatorType::LOGICAL_EXCEPT;
365549 break;
365550 case SetOperationType::INTERSECT:
365551 logical_type = LogicalOperatorType::LOGICAL_INTERSECT;
365552 break;
365553 default:
365554 throw InternalException("Unsupported logical operator type for set-operation");
365555 }
365556 // Generate the logical plan for the children of the set operation
365557
365558 D_ASSERT(node.bound_children.size() >= 2);
365559 vector<unique_ptr<LogicalOperator>> children;
365560 for (idx_t child_idx = 0; child_idx < node.bound_children.size(); child_idx++) {
365561 auto &child = node.bound_children[child_idx];
365562 auto &child_binder = *node.child_binders[child_idx];
365563
365564 // construct the logical plan for the child node
365565 auto child_node = std::move(child.plan);
365566 // push casts for the target types
365567 child_node = CastLogicalOperatorToTypes(child.types, node.types, std::move(child_node));
365568 // check if there are any unplanned subqueries left in any child
365569 if (child_binder.has_unplanned_dependent_joins) {
365571 }
365572 children.push_back(std::move(child_node));
365573 }
365574 auto root = make_uniq<LogicalSetOperation>(node.setop_index, node.types.size(), std::move(children), logical_type,
365575 node.setop_all);
365576 return VisitQueryNode(node, std::move(root));
365577}

◆ BuildUnionByNameInfo()

void duckdb::Binder::BuildUnionByNameInfo ( BoundSetOperationNode & result)
private
364975 {
364976 D_ASSERT(result.setop_type == SetOperationType::UNION_BY_NAME);
364977 vector<case_insensitive_map_t<idx_t>> node_name_maps;
364978 case_insensitive_set_t global_name_set;
364979
364980 // Build a name_map to use to check if a name exists
364981 // We throw a binder exception if two same name in the SELECT list
364982 D_ASSERT(result.names.empty());
364983 for (auto &child : result.bound_children) {
364984 auto &child_names = child.names;
364985 case_insensitive_map_t<idx_t> node_name_map;
364986 for (idx_t i = 0; i < child_names.size(); ++i) {
364987 auto &col_name = child_names[i];
364988 if (node_name_map.find(col_name) != node_name_map.end()) {
364989 throw BinderException(
364990 "UNION (ALL) BY NAME operation doesn't support duplicate names in the SELECT list - "
364991 "the name \"%s\" occurs multiple times",
364992 col_name);
364993 }
364994 if (global_name_set.find(col_name) == global_name_set.end()) {
364995 // column is not yet present in the result
364996 result.names.push_back(col_name);
364997 global_name_set.insert(col_name);
364998 }
364999 node_name_map[col_name] = i;
365000 }
365001 node_name_maps.push_back(std::move(node_name_map));
365002 }
365003
365004 idx_t new_size = result.names.size();
365005 bool need_reorder = false;
365006
365007 // construct the return type of each of the columns
365008 for (idx_t i = 0; i < new_size; ++i) {
365009 auto &col_name = result.names[i];
365010 LogicalType result_type(LogicalTypeId::INVALID);
365011 for (idx_t child_idx = 0; child_idx < result.bound_children.size(); ++child_idx) {
365012 auto &child_types = result.bound_children[child_idx].types;
365013 auto &child_name_map = node_name_maps[child_idx];
365014 // check if the column exists in this child node
365015 auto entry = child_name_map.find(col_name);
365016 if (entry == child_name_map.end()) {
365017 need_reorder = true;
365018 } else {
365019 auto col_idx_in_child = entry->second;
365020 auto &child_col_type = child_types[col_idx_in_child];
365021 // the child exists in this node - compute the type
365022 if (result_type.id() == LogicalTypeId::INVALID) {
365023 result_type = child_col_type;
365024 } else {
365025 result_type = LogicalType::ForceMaxLogicalType(result_type, child_col_type);
365026 }
365027 if (i != col_idx_in_child) {
365028 // the column exists - but the children are out-of-order, so we need to re-order anyway
365029 need_reorder = true;
365030 }
365031 }
365032 }
365033 // compute the final type for each column
365034 if (!can_contain_nulls) {
365035 if (ExpressionBinder::ContainsNullType(result_type)) {
365036 result_type = ExpressionBinder::ExchangeNullType(result_type);
365037 }
365038 }
365039 result.types.push_back(result_type);
365040 }
365041
365042 if (!need_reorder) {
365043 // if all columns in the children of the set-operations are identical we don't need to re-order at all
365044 // skip adding expressions entirely
365045 return;
365046 }
365047 // If reorder is required, generate the expressions for each node
365048 vector<vector<unique_ptr<Expression>>> reorder_expressions;
365049 reorder_expressions.resize(result.bound_children.size());
365050 for (idx_t i = 0; i < new_size; ++i) {
365051 auto &col_name = result.names[i];
365052 for (idx_t child_idx = 0; child_idx < result.bound_children.size(); ++child_idx) {
365053 auto &child = result.bound_children[child_idx];
365054 auto &child_name_map = node_name_maps[child_idx];
365055 // check if the column exists in this child node
365056 auto entry = child_name_map.find(col_name);
365057 unique_ptr<Expression> expr;
365058 if (entry == child_name_map.end()) {
365059 // the column does not exist - push a `NULL`
365060 expr = make_uniq<BoundConstantExpression>(Value(result.types[i]));
365061 } else {
365062 // the column exists - reference it
365063 auto col_idx_in_child = entry->second;
365064 auto &child_col_type = child.types[col_idx_in_child];
365065 auto root_idx = child.plan->GetRootIndex();
365066 expr = make_uniq<BoundColumnRefExpression>(child_col_type, ColumnBinding(root_idx, col_idx_in_child));
365067 }
365068 reorder_expressions[child_idx].push_back(std::move(expr));
365069 }
365070 }
365071 // now push projections for each node
365072 for (idx_t child_idx = 0; child_idx < result.bound_children.size(); ++child_idx) {
365073 auto &child = result.bound_children[child_idx];
365074 auto &child_reorder_expressions = reorder_expressions[child_idx];
365075 // if we have re-order expressions push a projection
365076 vector<LogicalType> child_types;
365077 for (auto &expr : child_reorder_expressions) {
365078 child_types.push_back(expr->return_type);
365079 }
365080 auto child_projection =
365081 make_uniq<LogicalProjection>(GenerateTableIndex(), std::move(child_reorder_expressions));
365082 child_projection->children.push_back(std::move(child.plan));
365083 child.plan = std::move(child_projection);
365084 child.types = std::move(child_types);
365085 }
365086}

◆ BindJoin()

BoundStatement duckdb::Binder::BindJoin ( Binder & parent,
TableRef & ref )
private
371863 {
371864 unnamed_subquery_index = parent_binder.unnamed_subquery_index;
371865 auto result = Bind(ref);
371866 parent_binder.unnamed_subquery_index = unnamed_subquery_index;
371867 return result;
371868}
idx_t unnamed_subquery_index
Unnamed subquery index.
Definition duckdb.cpp:2119

◆ Bind() [32/42]

BoundStatement duckdb::Binder::Bind ( BaseTableRef & ref)
private
371329 {
371330 QueryErrorContext error_context(ref.query_location);
371331 // CTEs and views are also referred to using BaseTableRefs, hence need to distinguish here
371332 // check if the table name refers to a CTE
371333
371334 // CTE name should never be qualified (i.e. schema_name should be empty)
371335 // unless we want to refer to the recurring table of "using key".
371336 BindingAlias binding_alias(ref.schema_name, ref.table_name);
371337 auto ctebinding = GetCTEBinding(binding_alias);
371338 if (ctebinding && ctebinding->CanBeReferenced()) {
371339 ctebinding->Reference();
371340
371341 // There is a CTE binding in the BindContext.
371342 // This can only be the case if there is a recursive CTE,
371343 // or a materialized CTE present.
371344 auto index = GenerateTableIndex();
371345
371346 auto alias = ref.alias.empty() ? ref.table_name : ref.alias;
371347 auto names = BindContext::AliasColumnNames(alias, ctebinding->GetColumnNames(), ref.column_name_alias);
371348
371349 bind_context.AddGenericBinding(index, alias, names, ctebinding->GetColumnTypes());
371350
371351 bool is_recurring = ref.schema_name == "recurring";
371352
371353 BoundStatement result;
371354 result.types = ctebinding->GetColumnTypes();
371355 result.names = names;
371356 result.plan =
371357 make_uniq<LogicalCTERef>(index, ctebinding->GetIndex(), result.types, std::move(names), is_recurring);
371358 return result;
371359 }
371360
371361 // not a CTE
371362 // extract a table or view from the catalog
371363 auto at_clause = BindAtClause(ref.at_clause);
371364 auto entry_at_clause = at_clause ? at_clause.get() : entry_retriever.GetAtClause();
371365 EntryLookupInfo table_lookup(CatalogType::TABLE_ENTRY, ref.table_name, entry_at_clause, error_context);
371366 BindSchemaOrCatalog(entry_retriever, ref.catalog_name, ref.schema_name);
371367 auto table_or_view =
371368 entry_retriever.GetEntry(ref.catalog_name, ref.schema_name, table_lookup, OnEntryNotFound::RETURN_NULL);
371369 // we still didn't find the table
371370 if (GetBindingMode() == BindingMode::EXTRACT_NAMES || GetBindingMode() == BindingMode::EXTRACT_QUALIFIED_NAMES) {
371371 if (!table_or_view || table_or_view->type == CatalogType::TABLE_ENTRY) {
371372 // if we are in EXTRACT_NAMES or EXTRACT_QUALIFIED_NAMES, we create a dummy table ref
371373 if (GetBindingMode() == BindingMode::EXTRACT_QUALIFIED_NAMES) {
371374 AddTableName(ref.ToString());
371375 } else {
371376 AddTableName(ref.table_name);
371377 }
371378
371379 // add a bind context entry
371380 auto table_index = GenerateTableIndex();
371381 auto ref_alias = ref.alias.empty() ? ref.table_name : ref.alias;
371382 vector<LogicalType> types {LogicalType::INTEGER};
371383 vector<string> names {"__dummy_col" + to_string(table_index)};
371384 bind_context.AddGenericBinding(table_index, ref_alias, names, types);
371385
371386 BoundStatement result;
371387 result.types = std::move(types);
371388 result.names = std::move(names);
371389 result.plan = make_uniq<LogicalDummyScan>(table_index);
371390 return result;
371391 }
371392 }
371393 if (!table_or_view) {
371394 // table could not be found: try to bind a replacement scan
371395 // Try replacement scan bind
371396 auto replacement_scan_bind_result = BindWithReplacementScan(context, ref);
371397 if (replacement_scan_bind_result.plan) {
371398 return replacement_scan_bind_result;
371399 }
371400
371401 // Try autoloading an extension, then retry the replacement scan bind
371402 auto full_path = ReplacementScan::GetFullPath(ref.catalog_name, ref.schema_name, ref.table_name);
371403 auto extension_loaded = TryLoadExtensionForReplacementScan(context, full_path);
371404 if (extension_loaded) {
371405 replacement_scan_bind_result = BindWithReplacementScan(context, ref);
371406 if (replacement_scan_bind_result.plan) {
371407 return replacement_scan_bind_result;
371408 }
371409 }
371410 auto &config = DBConfig::GetConfig(context);
371411 if (context.config.use_replacement_scans && Settings::Get<EnableExternalAccessSetting>(config) &&
371412 ExtensionHelper::IsFullPath(full_path)) {
371413 auto &fs = FileSystem::GetFileSystem(context);
371414 if (!fs.IsDisabledForPath(full_path) && fs.FileExists(full_path)) {
371415 throw BinderException(
371416 "No extension found that is capable of reading the file \"%s\"\n* If this file is a supported file "
371417 "format you can explicitly use the reader functions, such as read_csv, read_json or read_parquet",
371418 full_path);
371419 }
371420 }
371421
371422 // if we found a CTE that cannot be referenced that means that there is a circular reference
371423 if (ctebinding) {
371424 D_ASSERT(!ctebinding->CanBeReferenced());
371425 throw BinderException(error_context,
371426 "Circular reference to CTE \"%s\", use WITH RECURSIVE to "
371427 "use recursive CTEs.",
371428 ref.table_name);
371429 }
371430 // could not find an alternative: bind again to get the error
371431 // note: this will always throw when using DuckDB as a catalog, but a second look-up might succeed
371432 // in catalogs that do not have transactional DDL
371433 table_or_view =
371434 entry_retriever.GetEntry(ref.catalog_name, ref.schema_name, table_lookup, OnEntryNotFound::THROW_EXCEPTION);
371435 }
371436 switch (table_or_view->type) {
371437 case CatalogType::TABLE_ENTRY: {
371438 // base table
371439 auto table_index = GenerateTableIndex();
371440 auto &table = table_or_view->Cast<TableCatalogEntry>();
371441
371442 auto &properties = GetStatementProperties();
371443 properties.RegisterDBRead(table.ParentCatalog(), context);
371444
371445 unique_ptr<FunctionData> bind_data;
371446 auto scan_function = table.GetScanFunction(context, bind_data, table_lookup);
371447 if (bind_data && !bind_data->SupportStatementCache()) {
371448 SetAlwaysRequireRebind();
371449 }
371450 // TODO: bundle the type and name vector in a struct (e.g PackedColumnMetadata)
371451 vector<LogicalType> table_types;
371452 vector<string> table_names;
371453 vector<TableColumnType> table_categories;
371454
371455 vector<LogicalType> return_types;
371456 vector<string> return_names;
371457 for (auto &col : table.GetColumns().Logical()) {
371458 table_types.push_back(col.Type());
371459 table_names.push_back(col.Name());
371460 return_types.push_back(col.Type());
371461 return_names.push_back(col.Name());
371462 }
371463 table_names = BindContext::AliasColumnNames(ref.table_name, table_names, ref.column_name_alias);
371464
371465 virtual_column_map_t virtual_columns;
371466 if (scan_function.get_virtual_columns) {
371467 virtual_columns = scan_function.get_virtual_columns(context, bind_data.get());
371468 } else {
371469 virtual_columns = table.GetVirtualColumns();
371470 }
371471 auto logical_get =
371472 make_uniq<LogicalGet>(table_index, scan_function, std::move(bind_data), std::move(return_types),
371473 std::move(return_names), std::move(virtual_columns));
371474 auto table_entry = logical_get->GetTable();
371475 auto &col_ids = logical_get->GetMutableColumnIds();
371476 if (!table_entry) {
371477 bind_context.AddBaseTable(table_index, ref.alias, table_names, table_types, col_ids, ref.table_name);
371478 } else {
371479 bind_context.AddBaseTable(table_index, ref.alias, table_names, table_types, col_ids, *table_entry);
371480 }
371481 BoundStatement result;
371482 result.types = table_types;
371483 result.names = table_names;
371484 result.plan = std::move(logical_get);
371485 return result;
371486 }
371487 case CatalogType::VIEW_ENTRY: {
371488 // the node is a view: get the query that the view represents
371489 auto &view_catalog_entry = table_or_view->Cast<ViewCatalogEntry>();
371490 // We need to use a new binder for the view that doesn't reference any CTEs
371491 // defined for this binder so there are no collisions between the CTEs defined
371492 // for the view and for the current query
371493 auto view_binder = Binder::CreateBinder(context, this, BinderType::VIEW_BINDER);
371494 view_binder->can_contain_nulls = true;
371495
371496 // The view may contain CTEs, but maybe only in the cte_map, so we need create CTE nodes for them
371497 auto query = view_catalog_entry.GetQuery().Copy();
371498 SubqueryRef subquery(unique_ptr_cast<SQLStatement, SelectStatement>(std::move(query)));
371499
371500 subquery.alias = ref.alias;
371501 // construct view names by taking the view aliases
371502 subquery.column_name_alias = view_catalog_entry.aliases;
371503 // now apply the subquery column aliases
371504 for (idx_t i = 0; i < ref.column_name_alias.size(); i++) {
371505 if (i < subquery.column_name_alias.size()) {
371506 // override alias
371507 subquery.column_name_alias[i] = ref.column_name_alias[i];
371508 } else {
371509 subquery.column_name_alias.push_back(ref.column_name_alias[i]);
371510 }
371511 }
371512
371513 // when binding a view, we always look into the catalog/schema where the view is stored first
371514 auto view_search_path =
371515 GetSearchPath(view_catalog_entry.ParentCatalog(), view_catalog_entry.ParentSchema().name);
371516 view_binder->entry_retriever.SetSearchPath(std::move(view_search_path));
371517 // propagate the AT clause through the view
371518 view_binder->entry_retriever.SetAtClause(entry_at_clause);
371519
371520 // bind the child subquery
371521 view_binder->AddBoundView(view_catalog_entry);
371522 auto bound_child = view_binder->Bind(subquery);
371523 if (!view_binder->correlated_columns.empty()) {
371524 throw BinderException("Contents of view were altered - view bound correlated columns");
371525 }
371526 // update the view binding with the bound view information
371527 view_catalog_entry.UpdateBinding(bound_child.types, bound_child.names);
371528 bind_context.AddView(bound_child.plan->GetRootIndex(), subquery.alias, subquery, bound_child,
371529 view_catalog_entry);
371530 return bound_child;
371531 }
371532 default:
371533 throw InternalException("Catalog entry type");
371534 }
371535}
static vector< string > AliasColumnNames(const string &table_name, const vector< string > &names, const vector< string > &column_aliases)
Definition duckdb.cpp:359247
BoundStatement BindWithReplacementScan(ClientContext &context, BaseTableRef &ref)
Tries to bind the table name with replacement scans.
Definition duckdb.cpp:371257
optional_ptr< CTEBinding > GetCTEBinding(const BindingAlias &name)
Find all candidate common table expression by name; returns empty vector if none exists.
Definition duckdb.cpp:374580
index

◆ Bind() [33/42]

BoundStatement duckdb::Binder::Bind ( BoundRefWrapper & ref)
private
371541 {
371542 if (!ref.binder || !ref.bound_ref.plan) {
371543 throw InternalException("Rebinding bound ref that was already bound");
371544 }
371545 bind_context.AddContext(std::move(ref.binder->bind_context));
371546 return std::move(ref.bound_ref);
371547}

◆ Bind() [34/42]

BoundStatement duckdb::Binder::Bind ( JoinRef & ref)
private
371870 {
371871 auto result = make_uniq<BoundJoinRef>(ref.ref_type);
371872 result->left_binder = Binder::CreateBinder(context, this);
371873 result->right_binder = Binder::CreateBinder(context, this);
371874 auto &left_binder = *result->left_binder;
371875 auto &right_binder = *result->right_binder;
371876
371877 result->type = ref.type;
371878 result->left = left_binder.BindJoin(*this, *ref.left);
371879 result->delim_flipped = ref.delim_flipped;
371880
371881 {
371882 LateralBinder binder(left_binder, context);
371883 result->right = right_binder.BindJoin(*this, *ref.right);
371884 if (!ref.duplicate_eliminated_columns.empty()) {
371885 if (ref.delim_flipped) {
371886 // We gotta use the expression binder of the right side
371887 ExpressionBinder expr_binder(right_binder, context);
371888 for (auto &col : ref.duplicate_eliminated_columns) {
371889 result->duplicate_eliminated_columns.emplace_back(expr_binder.Bind(col));
371890 }
371891 } else {
371892 // We use the left side
371893 ExpressionBinder expr_binder(left_binder, context);
371894 for (auto &col : ref.duplicate_eliminated_columns) {
371895 result->duplicate_eliminated_columns.emplace_back(expr_binder.Bind(col));
371896 }
371897 }
371898 }
371899 bool is_lateral = false;
371900 // Store the correlated columns in the right binder in bound ref for planning of LATERALs
371901 // Ignore the correlated columns in the left binder, flattening handles those correlations
371902 result->correlated_columns = right_binder.correlated_columns;
371903 // Find correlations for the current join
371904 for (auto &cor_col : result->correlated_columns) {
371905 if (cor_col.depth == 1) {
371906 // Depth 1 indicates columns binding from the left indicating a lateral join
371907 is_lateral = true;
371908 break;
371909 }
371910 }
371911 result->lateral = is_lateral;
371912 if (result->lateral) {
371913 // lateral join: can only be an INNER or LEFT join
371914 if (ref.type != JoinType::INNER && ref.type != JoinType::LEFT) {
371915 throw BinderException("The combining JOIN type must be INNER or LEFT for a LATERAL reference");
371916 }
371917 }
371918 }
371919
371920 vector<unique_ptr<ParsedExpression>> extra_conditions;
371921 vector<string> extra_using_columns;
371922 switch (ref.ref_type) {
371923 case JoinRefType::NATURAL: {
371924 // natural join, figure out which column names are present in both sides of the join
371925 // first bind the left hand side and get a list of all the tables and column names
371926 case_insensitive_set_t lhs_columns;
371927 auto &lhs_binding_list = left_binder.bind_context.GetBindingsList();
371928 for (auto &binding : lhs_binding_list) {
371929 for (auto &column_name : binding->GetColumnNames()) {
371930 lhs_columns.insert(column_name);
371931 }
371932 }
371933 // now bind the rhs
371934 for (auto &column_name : lhs_columns) {
371935 auto right_using_binding = right_binder.bind_context.GetUsingBinding(column_name);
371936
371937 BindingAlias right_binding;
371938 // loop over the set of lhs columns, and figure out if there is a table in the rhs with the same name
371939 if (!right_using_binding) {
371940 if (!right_binder.TryFindBinding(column_name, "right", right_binding)) {
371941 // no match found for this column on the rhs: skip
371942 continue;
371943 }
371944 }
371945 extra_using_columns.push_back(column_name);
371946 }
371947 if (extra_using_columns.empty()) {
371948 // no matching bindings found in natural join: throw an exception
371949 string error_msg = "No columns found to join on in NATURAL JOIN.\n";
371950 error_msg += "Use CROSS JOIN if you intended for this to be a cross-product.";
371951 // gather all left/right candidates
371952 string left_candidates, right_candidates;
371953 auto &rhs_binding_list = right_binder.bind_context.GetBindingsList();
371954 for (auto &binding_ref : lhs_binding_list) {
371955 auto &binding = *binding_ref;
371956 for (auto &column_name : binding.GetColumnNames()) {
371957 if (!left_candidates.empty()) {
371958 left_candidates += ", ";
371959 }
371960 left_candidates += binding.GetAlias() + "." + column_name;
371961 }
371962 }
371963 for (auto &binding_ref : rhs_binding_list) {
371964 auto &binding = *binding_ref;
371965 for (auto &column_name : binding.GetColumnNames()) {
371966 if (!right_candidates.empty()) {
371967 right_candidates += ", ";
371968 }
371969 right_candidates += binding.GetAlias() + "." + column_name;
371970 }
371971 }
371972 error_msg += "\n Left candidates: " + left_candidates;
371973 error_msg += "\n Right candidates: " + right_candidates;
371974 throw BinderException(ref, error_msg);
371975 }
371976 break;
371977 }
371978 case JoinRefType::REGULAR:
371979 case JoinRefType::ASOF:
371980 if (!ref.using_columns.empty()) {
371981 // USING columns
371982 D_ASSERT(!result->condition);
371983 extra_using_columns = ref.using_columns;
371984 }
371985 break;
371986
371987 case JoinRefType::CROSS:
371988 case JoinRefType::POSITIONAL:
371989 case JoinRefType::DEPENDENT:
371990 break;
371991 }
371992 extra_using_columns = RemoveDuplicateUsingColumns(extra_using_columns);
371993
371994 if (!extra_using_columns.empty()) {
371995 vector<optional_ptr<UsingColumnSet>> left_using_bindings;
371996 vector<optional_ptr<UsingColumnSet>> right_using_bindings;
371997 for (idx_t i = 0; i < extra_using_columns.size(); i++) {
371998 auto &using_column = extra_using_columns[i];
371999 // we check if there is ALREADY a using column of the same name in the left and right set
372000 // this can happen if we chain USING clauses
372001 // e.g. x JOIN y USING (c) JOIN z USING (c)
372002 auto left_using_binding = left_binder.bind_context.GetUsingBinding(using_column);
372003 auto right_using_binding = right_binder.bind_context.GetUsingBinding(using_column);
372004 if (!left_using_binding) {
372005 left_binder.bind_context.GetMatchingBinding(using_column);
372006 }
372007 if (!right_using_binding) {
372008 right_binder.bind_context.GetMatchingBinding(using_column);
372009 }
372010 left_using_bindings.push_back(left_using_binding);
372011 right_using_bindings.push_back(right_using_binding);
372012 }
372013
372014 for (idx_t i = 0; i < extra_using_columns.size(); i++) {
372015 auto &using_column = extra_using_columns[i];
372016 BindingAlias left_binding;
372017 BindingAlias right_binding;
372018
372019 auto set = make_uniq<UsingColumnSet>();
372020 auto &left_using_binding = left_using_bindings[i];
372021 auto &right_using_binding = right_using_bindings[i];
372022 left_binding = RetrieveUsingBinding(left_binder, left_using_binding, using_column, "left");
372023 right_binding = RetrieveUsingBinding(right_binder, right_using_binding, using_column, "right");
372024
372025 // Last column of ASOF JOIN ... USING is >=
372026 const auto type = (ref.ref_type == JoinRefType::ASOF && i == extra_using_columns.size() - 1)
372027 ? ExpressionType::COMPARE_GREATERTHANOREQUALTO
372028 : ExpressionType::COMPARE_EQUAL;
372029
372030 extra_conditions.push_back(
372031 AddCondition(context, left_binder, right_binder, left_binding, right_binding, using_column, type));
372032
372033 AddUsingBindings(*set, left_using_binding, left_binding);
372034 AddUsingBindings(*set, right_using_binding, right_binding);
372035 SetPrimaryBinding(*set, ref.type, left_binding, right_binding);
372036 bind_context.TransferUsingBinding(left_binder.bind_context, left_using_binding, *set, using_column);
372037 bind_context.TransferUsingBinding(right_binder.bind_context, right_using_binding, *set, using_column);
372038 AddUsingBindingSet(std::move(set));
372039 }
372040 }
372041
372042 auto right_bindings = right_binder.bind_context.GetBindingAliases();
372043 auto left_bindings = left_binder.bind_context.GetBindingAliases();
372044
372045 bind_context.AddContext(std::move(left_binder.bind_context));
372046 bind_context.AddContext(std::move(right_binder.bind_context));
372047
372048 // Update the correlated columns for the parent binder
372049 // For the left binder, depth >= 1 indicates correlations from the parent binder
372050 for (const auto &col : left_binder.correlated_columns) {
372051 if (col.depth >= 1) {
372052 AddCorrelatedColumn(col);
372053 }
372054 }
372055 // For the right binder, depth > 1 indicates correlations from the parent binder
372056 // (depth = 1 indicates correlations from the left side of the join)
372057 for (auto col : right_binder.correlated_columns) {
372058 if (col.depth > 1) {
372059 // Decrement the depth to account for the effect of the lateral binder
372060 col.depth--;
372061 AddCorrelatedColumn(col);
372062 }
372063 }
372064
372065 for (auto &condition : extra_conditions) {
372066 if (ref.condition) {
372067 ref.condition = make_uniq<ConjunctionExpression>(ExpressionType::CONJUNCTION_AND, std::move(ref.condition),
372068 std::move(condition));
372069 } else {
372070 ref.condition = std::move(condition);
372071 }
372072 }
372073 if (ref.condition) {
372074 WhereBinder binder(*this, context);
372075 result->condition = binder.Bind(ref.condition);
372076 }
372077
372078 if (result->type == JoinType::SEMI || result->type == JoinType::ANTI || result->type == JoinType::MARK) {
372079 bind_context.RemoveContext(right_bindings);
372080 if (result->type == JoinType::MARK) {
372081 auto mark_join_idx = GenerateTableIndex();
372082 string mark_join_alias = "__internal_mark_join_ref" + to_string(mark_join_idx);
372083 bind_context.AddGenericBinding(mark_join_idx, mark_join_alias, {"__mark_index_column"},
372084 {LogicalType::BOOLEAN});
372085 result->mark_index = mark_join_idx;
372086 }
372087 }
372088 if (result->type == JoinType::RIGHT_SEMI || result->type == JoinType::RIGHT_ANTI) {
372089 bind_context.RemoveContext(left_bindings);
372090 }
372091
372092 BoundStatement result_stmt;
372093 result_stmt.types.insert(result_stmt.types.end(), result->left.types.begin(), result->left.types.end());
372094 result_stmt.types.insert(result_stmt.types.end(), result->right.types.begin(), result->right.types.end());
372095 result_stmt.names.insert(result_stmt.names.end(), result->left.names.begin(), result->left.names.end());
372096 result_stmt.names.insert(result_stmt.names.end(), result->right.names.begin(), result->right.names.end());
372097 result_stmt.plan = CreatePlan(*result);
372098 return result_stmt;
372099}

◆ Bind() [35/42]

BoundStatement duckdb::Binder::Bind ( SubqueryRef & ref)
private
373357 {
373358 auto binder = Binder::CreateBinder(context, this);
373359 binder->can_contain_nulls = true;
373360 auto subquery = binder->BindNode(*ref.subquery->node);
373361 binder->alias = ref.alias.empty() ? "unnamed_subquery" : ref.alias;
373362 idx_t bind_index = subquery.plan->GetRootIndex();
373363 string subquery_alias;
373364 if (ref.alias.empty()) {
373365 auto index = unnamed_subquery_index++;
373366 subquery_alias = "unnamed_subquery";
373367 ;
373368 if (index > 1) {
373369 subquery_alias += to_string(index);
373370 }
373371 } else {
373372 subquery_alias = ref.alias;
373373 }
373374 binder->is_outside_flattened = is_outside_flattened;
373375 if (binder->has_unplanned_dependent_joins) {
373377 }
373378 bind_context.AddSubquery(bind_index, subquery_alias, ref, subquery);
373379 MoveCorrelatedExpressions(*binder);
373380
373381 return subquery;
373382}

◆ Bind() [36/42]

BoundStatement duckdb::Binder::Bind ( TableFunctionRef & ref)
private
373740 {
373741 QueryErrorContext error_context(ref.query_location);
373742
373743 D_ASSERT(ref.function->GetExpressionType() == ExpressionType::FUNCTION);
373744 auto &fexpr = ref.function->Cast<FunctionExpression>();
373745
373746 string catalog = fexpr.catalog;
373747 string schema = fexpr.schema;
373748 Binder::BindSchemaOrCatalog(context, catalog, schema);
373749
373750 // fetch the function from the catalog
373751
373752 EntryLookupInfo table_function_lookup(CatalogType::TABLE_FUNCTION_ENTRY, fexpr.function_name, error_context);
373753 auto &func_catalog = *GetCatalogEntry(catalog, schema, table_function_lookup, OnEntryNotFound::THROW_EXCEPTION);
373754
373755 if (func_catalog.type == CatalogType::TABLE_MACRO_ENTRY) {
373756 auto &macro_func = func_catalog.Cast<TableMacroCatalogEntry>();
373757 auto query_node = BindTableMacro(fexpr, macro_func, 0);
373758 D_ASSERT(query_node);
373759
373760 auto binder = Binder::CreateBinder(context, this);
373761 binder->can_contain_nulls = true;
373762
373763 binder->alias = ref.alias.empty() ? "unnamed_query" : ref.alias;
373764 BoundStatement query;
373765 try {
373766 query = binder->BindNode(*query_node);
373767 } catch (std::exception &ex) {
373768 ErrorData error(ex);
373769 error.AddQueryLocation(ref);
373770 error.Throw();
373771 }
373772
373773 idx_t bind_index = query.plan->GetRootIndex();
373774 // string alias;
373775 string alias = (ref.alias.empty() ? "unnamed_query" + to_string(bind_index) : ref.alias);
373776
373777 // remember ref here is TableFunctionRef and NOT base class
373778 bind_context.AddSubquery(bind_index, alias, ref, query);
373779 MoveCorrelatedExpressions(*binder);
373780 return query;
373781 }
373782 D_ASSERT(func_catalog.type == CatalogType::TABLE_FUNCTION_ENTRY);
373783 auto &function = func_catalog.Cast<TableFunctionCatalogEntry>();
373784
373785 // evaluate the input parameters to the function
373786 vector<LogicalType> arguments;
373787 vector<Value> parameters;
373788 named_parameter_map_t named_parameters;
373789 BoundStatement subquery;
373790 ErrorData error;
373791 if (!BindTableFunctionParameters(function, fexpr.children, arguments, parameters, named_parameters, subquery,
373792 error)) {
373793 error.AddQueryLocation(ref);
373794 error.Throw();
373795 }
373796
373797 // select the function based on the input parameters
373798 FunctionBinder function_binder(*this);
373799 auto best_function_idx = function_binder.BindFunction(function.name, function.functions, arguments, error);
373800 if (!best_function_idx.IsValid()) {
373801 error.AddQueryLocation(ref);
373802 error.Throw();
373803 }
373804 auto table_function = function.functions.GetFunctionByOffset(best_function_idx.GetIndex());
373805
373806 // now check the named parameters
373807 BindNamedParameters(table_function.named_parameters, named_parameters, error_context, table_function.name);
373808
373809 vector<LogicalType> input_table_types;
373810 vector<string> input_table_names;
373811
373812 if (subquery.plan) {
373813 input_table_types = subquery.types;
373814 input_table_names = subquery.names;
373815 } else if (table_function.in_out_function) {
373816 for (auto &param : parameters) {
373817 input_table_types.push_back(param.type());
373818 input_table_names.push_back(string());
373819 }
373820 }
373821 if (!parameters.empty()) {
373822 // cast the parameters to the type of the function
373823 for (idx_t i = 0; i < arguments.size(); i++) {
373824 auto target_type =
373825 i < table_function.arguments.size() ? table_function.arguments[i] : table_function.varargs;
373826
373827 if (target_type != LogicalType::ANY && target_type != LogicalType::POINTER &&
373828 target_type.id() != LogicalTypeId::LIST && target_type != LogicalType::TABLE) {
373829 parameters[i] = parameters[i].CastAs(context, target_type);
373830 }
373831 }
373832 } else if (subquery.plan) {
373833 for (idx_t i = 0; i < arguments.size(); i++) {
373834 auto target_type =
373835 i < table_function.arguments.size() ? table_function.arguments[i] : table_function.varargs;
373836
373837 if (target_type != LogicalType::ANY && target_type != LogicalType::POINTER &&
373838 target_type.id() != LogicalTypeId::LIST) {
373839 input_table_types[i] = target_type;
373840 }
373841 }
373842 }
373843
373844 BoundStatement get;
373845 try {
373846 get = BindTableFunctionInternal(table_function, ref, std::move(parameters), std::move(named_parameters),
373847 std::move(input_table_types), std::move(input_table_names));
373848 } catch (std::exception &ex) {
373849 error = ErrorData(ex);
373850 error.AddQueryLocation(ref);
373851 error.Throw();
373852 }
373853
373854 if (subquery.plan) {
373855 auto child_node = std::move(subquery.plan);
373856
373857 reference<LogicalOperator> node = *get.plan;
373858
373859 while (!node.get().children.empty()) {
373860 D_ASSERT(node.get().children.size() == 1);
373861 if (node.get().children.size() != 1) {
373862 throw InternalException(
373863 "Binder::CreatePlan<BoundTableFunction>: linear path expected, but found node with %d children",
373864 node.get().children.size());
373865 }
373866 node = *node.get().children[0];
373867 }
373868
373869 D_ASSERT(node.get().type == LogicalOperatorType::LOGICAL_GET);
373870 node.get().children.push_back(std::move(child_node));
373871 }
373872 BoundStatement result_statement;
373873 result_statement.names = get.names;
373874 result_statement.types = get.types;
373875 result_statement.plan = std::move(get.plan);
373876 return result_statement;
373877}

◆ Bind() [37/42]

BoundStatement duckdb::Binder::Bind ( EmptyTableRef & ref)
private
371602 {
371603 BoundStatement result;
371604 result.plan = make_uniq<LogicalDummyScan>(GenerateTableIndex());
371605 return result;
371606}

◆ Bind() [38/42]

BoundStatement duckdb::Binder::Bind ( DelimGetRef & ref)
private
371581 {
371582 // Have to add bindings
371583 idx_t tbl_idx = GenerateTableIndex();
371584 string internal_name = "__internal_delim_get_ref_" + std::to_string(tbl_idx);
371585
371586 BoundStatement result;
371587 result.types = std::move(ref.types);
371588 result.names = std::move(ref.internal_aliases);
371589 result.plan = make_uniq<LogicalDelimGet>(tbl_idx, result.types);
371590
371591 bind_context.AddGenericBinding(tbl_idx, internal_name, result.names, result.types);
371592 return result;
371593}

◆ Bind() [39/42]

BoundStatement duckdb::Binder::Bind ( ExpressionListRef & ref)
private
371619 {
371620 BoundStatement result;
371621 result.types = expr.expected_types;
371622 result.names = expr.expected_names;
371623
371624 vector<vector<unique_ptr<Expression>>> values;
371625 auto prev_can_contain_nulls = this->can_contain_nulls;
371626 // bind value list
371627 InsertBinder binder(*this, context);
371628 binder.target_type = LogicalType(LogicalTypeId::INVALID);
371629 for (idx_t list_idx = 0; list_idx < expr.values.size(); list_idx++) {
371630 auto &expression_list = expr.values[list_idx];
371631 if (result.names.empty()) {
371632 // no names provided, generate them
371633 for (idx_t val_idx = 0; val_idx < expression_list.size(); val_idx++) {
371634 result.names.push_back("col" + to_string(val_idx));
371635 }
371636 }
371637
371638 this->can_contain_nulls = true;
371639 vector<unique_ptr<Expression>> list;
371640 for (idx_t val_idx = 0; val_idx < expression_list.size(); val_idx++) {
371641 if (!result.types.empty()) {
371642 D_ASSERT(result.types.size() == expression_list.size());
371643 binder.target_type = result.types[val_idx];
371644 }
371645 auto bound_expr = binder.Bind(expression_list[val_idx]);
371646 list.push_back(std::move(bound_expr));
371647 }
371648 values.push_back(std::move(list));
371649 this->can_contain_nulls = prev_can_contain_nulls;
371650 }
371651 if (result.types.empty() && !expr.values.empty()) {
371652 // there are no types specified
371653 // we have to figure out the result types
371654 // for each column, we iterate over all of the expressions and select the max logical type
371655 // we initialize all types to SQLNULL
371656 result.types.resize(expr.values[0].size(), LogicalType::SQLNULL);
371657 // now loop over the lists and select the max logical type
371658 for (idx_t list_idx = 0; list_idx < values.size(); list_idx++) {
371659 auto &list = values[list_idx];
371660 for (idx_t val_idx = 0; val_idx < list.size(); val_idx++) {
371661 auto &current_type = result.types[val_idx];
371662 auto next_type = ExpressionBinder::GetExpressionReturnType(*list[val_idx]);
371663 result.types[val_idx] = LogicalType::MaxLogicalType(context, current_type, next_type);
371664 }
371665 }
371666 for (auto &type : result.types) {
371667 type = LogicalType::NormalizeType(type);
371668 }
371669 // finally do another loop over the expressions and add casts where required
371670 for (idx_t list_idx = 0; list_idx < values.size(); list_idx++) {
371671 auto &list = values[list_idx];
371672 for (idx_t val_idx = 0; val_idx < list.size(); val_idx++) {
371673 list[val_idx] =
371674 BoundCastExpression::AddCastToType(context, std::move(list[val_idx]), result.types[val_idx]);
371675 }
371676 }
371677 }
371678 auto bind_index = GenerateTableIndex();
371679 bind_context.AddGenericBinding(bind_index, expr.alias, result.names, result.types);
371680
371681 // values list, first plan any subqueries in the list
371682 auto root = make_uniq_base<LogicalOperator, LogicalDummyScan>(GenerateTableIndex());
371683 for (auto &expr_list : values) {
371684 for (auto &expr : expr_list) {
371685 PlanSubqueries(expr, root);
371686 }
371687 }
371688
371689 auto expr_get = make_uniq<LogicalExpressionGet>(bind_index, result.types, std::move(values));
371690 expr_get->AddChild(std::move(root));
371691 result.plan = std::move(expr_get);
371692 return result;
371693}
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
static DUCKDB_API LogicalType NormalizeType(const LogicalType &type)
Normalize a type - removing literals.
Definition duckdb.cpp:139907

◆ Bind() [40/42]

BoundStatement duckdb::Binder::Bind ( ColumnDataRef & ref)
private
371556 {
371557 auto &collection = *ref.collection;
371558 auto types = collection.Types();
371559
371560 BoundStatement result;
371561 result.names = std::move(ref.expected_names);
371562 for (idx_t i = result.names.size(); i < types.size(); i++) {
371563 result.names.push_back("col" + to_string(i + 1));
371564 }
371565 result.types = types;
371566 auto bind_index = GenerateTableIndex();
371567 bind_context.AddGenericBinding(bind_index, ref.alias, result.names, types);
371568
371569 result.plan =
371570 make_uniq_base<LogicalOperator, LogicalColumnDataGet>(bind_index, std::move(types), std::move(ref.collection));
371571 return result;
371572}

◆ Bind() [41/42]

BoundStatement duckdb::Binder::Bind ( PivotRef & expr)
private
373078 {
373079 if (!ref.source) {
373080 throw InternalException("Pivot without a source!?");
373081 }
373082 if (!ref.bound_pivot_values.empty() || !ref.bound_group_names.empty() || !ref.bound_aggregate_names.empty()) {
373083 // bound pivot
373084 return BindBoundPivot(ref);
373085 }
373086
373087 // bind the source of the pivot
373088 // we need to do this to be able to expand star expressions
373089 if (ref.source->type == TableReferenceType::SUBQUERY && ref.source->alias.empty()) {
373090 ref.source->alias = "__internal_pivot_alias_" + to_string(GenerateTableIndex());
373091 }
373092 auto copied_source = ref.source->Copy();
373093 auto star_binder = Binder::CreateBinder(context, this);
373094 star_binder->Bind(*copied_source);
373095
373096 // figure out the set of column names that are in the source of the pivot
373097 vector<unique_ptr<ParsedExpression>> all_columns;
373098 star_binder->ExpandStarExpression(make_uniq<StarExpression>(), all_columns);
373099
373100 unique_ptr<SelectNode> select_node;
373101 unique_ptr<ParsedExpression> where_clause;
373102 if (!ref.aggregates.empty()) {
373103 select_node = BindPivot(ref, std::move(all_columns));
373104 } else {
373105 select_node = BindUnpivot(*star_binder, ref, std::move(all_columns), where_clause);
373106 }
373107 // bind the generated select node
373108 auto child_binder = Binder::CreateBinder(context, this);
373109 auto result = child_binder->BindNode(*select_node);
373110 auto root_index = result.plan->GetRootIndex();
373111
373112 MoveCorrelatedExpressions(*child_binder);
373113 auto subquery_alias = ref.alias.empty() ? "__unnamed_pivot" : ref.alias;
373114 SubqueryRef subquery_ref(nullptr, subquery_alias);
373115 subquery_ref.column_name_alias = std::move(ref.column_name_alias);
373116 if (where_clause) {
373117 // if a WHERE clause was provided - bind a subquery holding the WHERE clause
373118 // we need to bind a new subquery here because the WHERE clause has to be applied AFTER the unnest
373119 child_binder = Binder::CreateBinder(context, this);
373120 child_binder->bind_context.AddSubquery(root_index, subquery_ref.alias, subquery_ref, result);
373121 auto where_query = make_uniq<SelectNode>();
373122 where_query->select_list.push_back(make_uniq<StarExpression>());
373123 where_query->where_clause = std::move(where_clause);
373124 result = child_binder->BindSelectNode(*where_query, std::move(result));
373125 root_index = result.plan->GetRootIndex();
373126 }
373127 bind_context.AddSubquery(root_index, subquery_ref.alias, subquery_ref, result);
373128 return result;
373129}

◆ Bind() [42/42]

BoundStatement duckdb::Binder::Bind ( ShowRef & ref)
private
373340 {
373341 if (ref.show_type == ShowType::SUMMARY) {
373342 return BindSummarize(ref);
373343 }
373344 if (ref.query) {
373345 return BindShowQuery(ref);
373346 } else {
373347 return BindShowTable(ref);
373348 }
373349}

◆ BindPivot()

unique_ptr< SelectNode > duckdb::Binder::BindPivot ( PivotRef & expr,
vector< unique_ptr< ParsedExpression > > all_columns )
private
372683 {
372684 // keep track of the columns by which we pivot/aggregate
372685 // any columns which are not pivoted/aggregated on are added to the GROUP BY clause
372686 case_insensitive_set_t handled_columns;
372687
372688 vector<reference<FunctionExpression>> pivot_aggregates;
372689 // parse the aggregate, and extract the referenced columns from the aggregate
372690 for (auto &aggr : ref.aggregates) {
372691 if (aggr->HasSubquery()) {
372692 throw BinderException(*aggr, "Pivot expression cannot contain subqueries");
372693 }
372694 if (aggr->IsWindow()) {
372695 throw BinderException(*aggr, "Pivot expression cannot contain window functions");
372696 }
372697 idx_t aggregate_count = pivot_aggregates.size();
372698 ExtractPivotAggregateExpression(context, aggr, pivot_aggregates);
372699 if (pivot_aggregates.size() != aggregate_count + 1) {
372700 string error_str = pivot_aggregates.size() == aggregate_count
372701 ? "but no aggregates were found"
372702 : "but " + to_string(pivot_aggregates.size() - aggregate_count) + " were found";
372703 throw BinderException(*aggr, "Pivot expression must contain exactly one aggregate, %s", error_str);
372704 }
372705 }
372706 for (auto &aggr : pivot_aggregates) {
372707 ExtractPivotExpressions(aggr.get(), handled_columns, macro_binding);
372708 }
372709
372710 // process the in-lists
372711 for (auto &pivot_column : ref.pivots) {
372712 D_ASSERT(pivot_column.unpivot_names.empty());
372713
372714 for (auto &pivot_entry : pivot_column.entries) {
372715 // bind the expressions in the IN list
372716 if (!pivot_entry.values.empty()) {
372717 continue;
372718 }
372719
372720 BindPivotInList(pivot_entry.expr, pivot_entry.values, *this);
372721
372722 // check that we have the expected number of values
372723 const auto expected_size = pivot_column.pivot_expressions.size();
372724 const auto values_size = pivot_entry.values.size();
372725
372726 if (values_size != expected_size) {
372727 throw BinderException("PIVOT IN list - inconsistent amount of rows - expected %d but got %d",
372728 expected_size, values_size);
372729 }
372730
372731 // clear the expression after binding, we only need the values from now
372732 pivot_entry.expr = nullptr;
372733 }
372734 }
372735
372736 // first add all pivots to the set of handled columns, and check for duplicates
372737 idx_t total_pivots = 1;
372738 for (auto &pivot : ref.pivots) {
372739 if (!pivot.pivot_enum.empty()) {
372740 auto &type_entry =
372741 Catalog::GetEntry<TypeCatalogEntry>(context, INVALID_CATALOG, INVALID_SCHEMA, pivot.pivot_enum);
372742 auto type = type_entry.user_type;
372743 if (type.id() != LogicalTypeId::ENUM) {
372744 throw BinderException(ref, "Pivot must reference an ENUM type: \"%s\" is of type \"%s\"",
372745 pivot.pivot_enum, type.ToString());
372746 }
372747 if (!type.IsComplete()) {
372748 throw BinderException("ENUM type is incomplete");
372749 }
372750 auto enum_size = EnumType::GetSize(type);
372751 for (idx_t i = 0; i < enum_size; i++) {
372752 auto enum_value = EnumType::GetValue(Value::ENUM(i, type));
372753 PivotColumnEntry entry;
372754 entry.values.emplace_back(enum_value);
372755 entry.alias = std::move(enum_value);
372756 pivot.entries.push_back(std::move(entry));
372757 }
372758 }
372759 total_pivots *= pivot.entries.size();
372760 // add the pivoted column to the columns that have been handled
372761 for (auto &pivot_name : pivot.pivot_expressions) {
372762 ExtractPivotExpressions(*pivot_name, handled_columns, macro_binding);
372763 }
372764 value_set_t pivots;
372765 for (auto &entry : pivot.entries) {
372766 D_ASSERT(!entry.expr);
372767 Value val;
372768 if (entry.values.size() == 1) {
372769 val = entry.values[0];
372770 } else {
372771 val = Value::LIST(LogicalType::VARCHAR, entry.values);
372772 }
372773 if (pivots.find(val) != pivots.end()) {
372774 throw BinderException(ref, "The value \"%s\" was specified multiple times in the IN clause",
372775 val.ToString());
372776 }
372777 if (entry.values.size() != pivot.pivot_expressions.size()) {
372778 throw BinderException(ref, "PIVOT IN list - inconsistent amount of rows - expected %d but got %d",
372779 pivot.pivot_expressions.size(), entry.values.size());
372780 }
372781 pivots.insert(val);
372782 }
372783 }
372784 auto pivot_limit = Settings::Get<PivotLimitSetting>(context);
372785 if (total_pivots >= pivot_limit) {
372786 throw BinderException(ref, "Pivot column limit of %llu exceeded. Use SET pivot_limit=X to increase the limit.",
372787 pivot_limit);
372788 }
372789
372790 // construct the required pivot values recursively
372791 vector<PivotValueElement> pivot_values;
372792 ConstructPivots(ref, pivot_values);
372793
372794 unique_ptr<SelectNode> pivot_node;
372795 // pivots have three components
372796 // - the pivots (i.e. future column names)
372797 // - the groups (i.e. the future row names
372798 // - the aggregates (i.e. the values of the pivot columns)
372799
372800 // we have two ways of executing a pivot statement
372801 // (1) the straightforward manner of filtered aggregates SUM(..) FILTER (pivot_value=X)
372802 // (2) computing the aggregates once, then using LIST to group the aggregates together with the PIVOT operator
372803 // -> filtered aggregates are faster when there are FEW pivot values
372804 // -> LIST is faster when there are MANY pivot values
372805 // we switch dynamically based on the number of pivots to compute
372806 auto pivot_filter_threshold = Settings::Get<PivotFilterThresholdSetting>(context);
372807 if (pivot_values.size() <= pivot_filter_threshold) {
372808 // use a set of filtered aggregates
372809 pivot_node =
372810 PivotFilteredAggregate(context, ref, std::move(all_columns), handled_columns, std::move(pivot_values));
372811 } else {
372812 // executing a pivot statement happens in three stages
372813 // 1) execute the query "SELECT {groups}, {pivots}, {aggregates} FROM {from_clause} GROUP BY {groups}, {pivots}
372814 // this computes all values that are required in the final result, but not yet in the correct orientation
372815 // 2) execute the query "SELECT {groups}, LIST({pivots}), LIST({aggregates}) FROM [Q1] GROUP BY {groups}
372816 // this pushes all pivots and aggregates that belong to a specific group together in an aligned manner
372817 // 3) push a PIVOT operator, that performs the actual pivoting of the values into the different columns
372818
372819 PivotBindState bind_state;
372820 // Pivot Stage 1
372821 // SELECT {groups}, {pivots}, {aggregates} FROM {from_clause} GROUP BY {groups}, {pivots}
372822 auto subquery_stage1 = PivotInitialAggregate(context, bind_state, ref, std::move(all_columns), handled_columns);
372823
372824 // Pivot stage 2
372825 // SELECT {groups}, LIST({pivots}), LIST({aggregates}) FROM [Q1] GROUP BY {groups}
372826 auto subquery_stage2 = PivotListAggregate(bind_state, ref, std::move(subquery_stage1));
372827
372828 // Pivot stage 3
372829 // construct the final pivot operator
372830 pivot_node = PivotFinalOperator(bind_state, ref, std::move(subquery_stage2), std::move(pivot_values));
372831 }
372832 return pivot_node;
372833}
static DUCKDB_API Value LIST(const LogicalType &child_type, vector< Value > values)
Create a list value with the given entries.
Definition duckdb.cpp:132555

◆ BindUnpivot()

unique_ptr< SelectNode > duckdb::Binder::BindUnpivot ( Binder & child_binder,
PivotRef & expr,
vector< unique_ptr< ParsedExpression > > all_columns,
unique_ptr< ParsedExpression > & where_clause )
private
372899 {
372900 D_ASSERT(ref.groups.empty());
372901 D_ASSERT(ref.pivots.size() == 1);
372902
372903 auto select_node = make_uniq<SelectNode>();
372904 select_node->from_table = std::move(ref.source);
372905
372906 // handle the pivot
372907 auto &unpivot = ref.pivots[0];
372908
372909 // handle star expressions in any entries
372910 vector<UnpivotEntry> unpivot_entries;
372911 for (auto &entry : unpivot.entries) {
372912 ExtractUnpivotEntries(child_binder, entry, unpivot_entries);
372913 }
372914 if (unpivot_entries.empty()) {
372915 throw BinderException(ref, "UNPIVOT clause must unpivot on at least one column - zero were provided");
372916 }
372917
372918 case_insensitive_set_t handled_columns;
372919 case_insensitive_map_t<string> name_map;
372920 for (auto &entry : unpivot_entries) {
372921 for (auto &unpivot_expr : entry.expressions) {
372922 vector<string> result;
372923 ExtractUnpivotColumnName(*unpivot_expr, result);
372924 if (result.empty()) {
372925 throw BinderException(
372926 *unpivot_expr,
372927 "UNPIVOT clause must contain exactly one column - expression \"%s\" does not contain any",
372928 unpivot_expr->ToString());
372929 }
372930 if (result.size() > 1) {
372931 throw BinderException(
372932 *unpivot_expr,
372933 "UNPIVOT clause must contain exactly one column - expression \"%s\" contains multiple (%s)",
372934 unpivot_expr->ToString(), StringUtil::Join(result, ", "));
372935 }
372936 handled_columns.insert(result[0]);
372937 entry.column_names.push_back(std::move(result[0]));
372938 }
372939 }
372940
372941 vector<string> select_names;
372942 for (auto &col_expr : all_columns) {
372943 if (col_expr->GetExpressionType() != ExpressionType::COLUMN_REF) {
372944 throw InternalException("Unexpected child of pivot source - not a ColumnRef");
372945 }
372946 auto &columnref = col_expr->Cast<ColumnRefExpression>();
372947 auto &column_name = columnref.GetColumnName();
372948 auto entry = handled_columns.find(column_name);
372949 if (entry == handled_columns.end()) {
372950 // not handled - add to the set of regularly selected columns
372951 select_names.push_back(col_expr->GetName());
372952 select_node->select_list.push_back(std::move(col_expr));
372953 } else {
372954 name_map[column_name] = column_name;
372955 handled_columns.erase(entry);
372956 }
372957 }
372958 if (!handled_columns.empty()) {
372959 for (auto &entry : handled_columns) {
372960 throw BinderException(
372961 ref, "Column \"%s\" referenced in UNPIVOT but no matching entry was found in the table", entry);
372962 }
372963 }
372964 vector<Value> unpivot_names;
372965 for (auto &entry : unpivot_entries) {
372966 string generated_name;
372967 D_ASSERT(entry.expressions.size() == entry.column_names.size());
372968 for (idx_t c = 0; c < entry.expressions.size(); c++) {
372969 auto name_entry = name_map.find(entry.column_names[c]);
372970 if (name_entry == name_map.end()) {
372971 throw InternalException("Unpivot - could not find column name in name map");
372972 }
372973 if (!generated_name.empty()) {
372974 generated_name += "_";
372975 }
372976 generated_name += name_entry->second;
372977 }
372978 unpivot_names.emplace_back(!entry.alias.empty() ? entry.alias : generated_name);
372979 }
372980 vector<vector<unique_ptr<ParsedExpression>>> unpivot_expressions;
372981 for (idx_t v_idx = 1; v_idx < unpivot_entries.size(); v_idx++) {
372982 if (unpivot_entries[v_idx].expressions.size() != unpivot_entries[0].expressions.size()) {
372983 throw BinderException(
372984 ref,
372985 "UNPIVOT value count mismatch - entry has %llu values, but expected all entries to have %llu values",
372986 unpivot_entries[v_idx].expressions.size(), unpivot_entries[0].expressions.size());
372987 }
372988 }
372989
372990 for (idx_t v_idx = 0; v_idx < unpivot_entries[0].expressions.size(); v_idx++) {
372991 vector<unique_ptr<ParsedExpression>> expressions;
372992 expressions.reserve(unpivot_entries.size());
372993 for (auto &entry : unpivot_entries) {
372994 expressions.push_back(std::move(entry.expressions[v_idx]));
372995 }
372996 unpivot_expressions.push_back(std::move(expressions));
372997 }
372998
372999 idx_t column_count = select_names.size();
373000 idx_t unnest_count = unpivot_expressions.size();
373001 // add the names for the generated unpivot lists
373002 select_names.push_back("unpivot_names");
373003 for (idx_t i = 0; i < unpivot_expressions.size(); i++) {
373004 if (i > 0) {
373005 select_names.push_back("unpivot_list_" + std::to_string(i + 1));
373006 } else {
373007 select_names.push_back("unpivot_list");
373008 }
373009 }
373010
373011 // now de-duplicate the names
373012 QueryResult::DeduplicateColumns(select_names);
373013
373014 // construct the UNNEST expression for the set of names (constant)
373015 auto unpivot_list = Value::LIST(LogicalType::VARCHAR, std::move(unpivot_names));
373016 auto unpivot_name_expr = make_uniq<ConstantExpression>(std::move(unpivot_list));
373017 unpivot_name_expr->alias = select_names[column_count];
373018 select_node->select_list.push_back(std::move(unpivot_name_expr));
373019
373020 // construct the unpivot lists for the set of unpivoted columns
373021 if (ref.unpivot_names.size() != unpivot_expressions.size()) {
373022 throw BinderException(ref, "UNPIVOT name count mismatch - got %d names but %d expressions",
373023 ref.unpivot_names.size(), unpivot_expressions.size());
373024 }
373025 for (idx_t i = 0; i < unpivot_expressions.size(); i++) {
373026 auto list_expr = make_uniq<FunctionExpression>("unpivot_list", std::move(unpivot_expressions[i]));
373027 list_expr->alias = select_names[column_count + 1 + i];
373028 select_node->select_list.push_back(std::move(list_expr));
373029 }
373030
373031 // move the unpivot lists into a subquery
373032 auto result_node = make_uniq<SelectNode>();
373033 auto sub_select = make_uniq<SelectStatement>();
373034 sub_select->node = std::move(select_node);
373035 auto subquery = make_uniq<SubqueryRef>(std::move(sub_select));
373036 subquery->alias = "unpivot";
373037
373038 result_node->from_table = std::move(subquery);
373039
373040 // construct the final UNNEST calls which generate the final unpivot result
373041 for (idx_t i = 0; i < column_count; i++) {
373042 auto select_col = make_uniq<ColumnRefExpression>(std::move(select_names[i]));
373043 result_node->select_list.push_back(std::move(select_col));
373044 }
373045
373046 auto unpivot_name_list = make_uniq<ColumnRefExpression>(std::move(select_names[column_count]));
373047 vector<unique_ptr<ParsedExpression>> unnest_name_children;
373048 unnest_name_children.push_back(std::move(unpivot_name_list));
373049 auto unnest_name_expr = make_uniq<FunctionExpression>("unnest", std::move(unnest_name_children));
373050 unnest_name_expr->SetAlias(unpivot.unpivot_names[0]);
373051 result_node->select_list.push_back(std::move(unnest_name_expr));
373052
373053 for (idx_t i = 0; i < unnest_count; i++) {
373054 auto unpivot_internal_name = std::move(select_names[column_count + 1 + i]);
373055
373056 auto unpivot_list_ref = make_uniq<ColumnRefExpression>(std::move(unpivot_internal_name));
373057 vector<unique_ptr<ParsedExpression>> unnest_val_children;
373058 unnest_val_children.push_back(std::move(unpivot_list_ref));
373059 auto unnest_val_expr = make_uniq<FunctionExpression>("unnest", std::move(unnest_val_children));
373060 auto unnest_name = i < ref.column_name_alias.size() ? ref.column_name_alias[i] : ref.unpivot_names[i];
373061 unnest_val_expr->SetAlias(unnest_name);
373062 result_node->select_list.push_back(std::move(unnest_val_expr));
373063 if (!ref.include_nulls) {
373064 // if we are running with EXCLUDE NULLS we need to add an IS NOT NULL filter
373065 auto colref = make_uniq<ColumnRefExpression>(unnest_name);
373066 auto filter = make_uniq<OperatorExpression>(ExpressionType::OPERATOR_IS_NOT_NULL, std::move(colref));
373067 if (where_clause) {
373068 where_clause = make_uniq<ConjunctionExpression>(ExpressionType::CONJUNCTION_AND,
373069 std::move(where_clause), std::move(filter));
373070 } else {
373071 where_clause = std::move(filter);
373072 }
373073 }
373074 }
373075 return result_node;
373076}
static void DeduplicateColumns(vector< string > &names)
Deduplicate column names for interop with external libraries.
Definition duckdb.cpp:296062
static DUCKDB_API string Join(const vector< string > &input, const string &separator)
Join multiple strings into one string. Components are concatenated by the given separator.
Definition duckdb.cpp:109497

◆ BindBoundPivot()

BoundStatement duckdb::Binder::BindBoundPivot ( PivotRef & expr)
private
372562 {
372563 // bind the child table in a child binder
372564 BoundPivotRef result;
372565 result.bind_index = GenerateTableIndex();
372566 result.child_binder = Binder::CreateBinder(context, this);
372567 result.child = result.child_binder->Bind(*ref.source);
372568
372569 auto &aggregates = result.bound_pivot.aggregates;
372570 ExtractPivotAggregates(result.child, aggregates);
372571
372572 if (aggregates.size() < ref.bound_aggregate_names.size()) {
372573 vector<string> unique_names;
372574 unordered_set<string> seen;
372575 for (auto &name : ref.bound_aggregate_names) {
372576 if (seen.find(name) == seen.end()) {
372577 unique_names.push_back(name);
372578 seen.insert(name);
372579 }
372580 }
372581
372582 if (unique_names.size() != aggregates.size()) {
372583 throw InternalException("Pivot aggregate mismatch: %llu unique names, %llu aggregates", unique_names.size(),
372584 aggregates.size());
372585 }
372586
372587 unordered_map<string, idx_t> name_to_position;
372588 for (idx_t i = 0; i < unique_names.size(); i++) {
372589 name_to_position[unique_names[i]] = i;
372590 }
372591
372592 vector<unique_ptr<Expression>> expanded_aggs;
372593 for (auto &expected_name : ref.bound_aggregate_names) {
372594 idx_t position = name_to_position[expected_name];
372595 expanded_aggs.push_back(aggregates[position]->Copy());
372596 }
372597
372598 result.bound_pivot.aggregates = std::move(expanded_aggs);
372599 }
372600
372601 if (aggregates.size() != ref.bound_aggregate_names.size()) {
372602 throw InternalException("Pivot aggregate count mismatch (expected %llu, found %llu)",
372603 ref.bound_aggregate_names.size(), aggregates.size());
372604 }
372605
372606 vector<string> child_names;
372607 vector<LogicalType> child_types;
372608 result.child_binder->bind_context.GetTypesAndNames(child_names, child_types);
372609
372610 vector<string> names;
372611 vector<LogicalType> types;
372612 // emit the groups
372613 for (idx_t i = 0; i < ref.bound_group_names.size(); i++) {
372614 names.push_back(ref.bound_group_names[i]);
372615 types.push_back(child_types[i]);
372616 }
372617 // emit the pivot columns
372618 for (auto &pivot_value : ref.bound_pivot_values) {
372619 for (idx_t aggr_idx = 0; aggr_idx < ref.bound_aggregate_names.size(); aggr_idx++) {
372620 auto &aggr = aggregates[aggr_idx];
372621 auto &aggr_name = ref.bound_aggregate_names[aggr_idx];
372622 auto name = pivot_value.name + aggr_name;
372623
372624 string pivot_str;
372625 for (auto &value : pivot_value.values) {
372626 auto str = value.ToString();
372627 if (pivot_str.empty()) {
372628 pivot_str = std::move(str);
372629 } else {
372630 pivot_str += "_" + str;
372631 }
372632 }
372633 result.bound_pivot.pivot_values.push_back(std::move(pivot_str));
372634 names.push_back(std::move(name));
372635 types.push_back(aggr->return_type);
372636 }
372637 }
372638 result.bound_pivot.group_count = ref.bound_group_names.size();
372639 result.bound_pivot.types = types;
372640 auto subquery_alias = ref.alias.empty() ? "__unnamed_pivot" : ref.alias;
372642 bind_context.AddGenericBinding(result.bind_index, subquery_alias, names, types);
372643
372644 MoveCorrelatedExpressions(*result.child_binder);
372645
372646 BoundStatement result_statement;
372647 result_statement.plan =
372648 make_uniq<LogicalPivot>(result.bind_index, std::move(result.child.plan), std::move(result.bound_pivot));
372649 return result_statement;
372650}

◆ ExtractUnpivotEntries()

void duckdb::Binder::ExtractUnpivotEntries ( Binder & child_binder,
PivotColumnEntry & entry,
vector< UnpivotEntry > & unpivot_entries )
private
372842 {
372843 // Try to bind the entry expression as values
372844 try {
372845 auto expr_copy = entry.expr->Copy();
372846 BindPivotInList(expr_copy, entry.values, child_binder);
372847 // successfully bound as values - clear the expression
372848 entry.expr = nullptr;
372849 } catch (...) {
372850 // ignore binder exceptions here - we fall back to expression mode
372851 entry.values.clear();
372852 }
372853
372854 if (!entry.expr) {
372855 // pivot entry without an expression - generate one
372856 UnpivotEntry unpivot_entry;
372857 unpivot_entry.alias = entry.alias;
372858 for (auto &val : entry.values) {
372859 auto column_name = val.ToString();
372860 if (column_name.empty()) {
372861 throw BinderException("UNPIVOT - empty column name not supported");
372862 }
372863 unpivot_entry.expressions.push_back(make_uniq<ColumnRefExpression>(column_name));
372864 }
372865 unpivot_entries.push_back(std::move(unpivot_entry));
372866 return;
372867 }
372868 D_ASSERT(entry.values.empty());
372869 // expand star expressions (if any)
372870 vector<unique_ptr<ParsedExpression>> star_columns;
372871 child_binder.ExpandStarExpression(std::move(entry.expr), star_columns);
372872
372873 for (auto &expr : star_columns) {
372874 // create one pivot entry per result column
372875 UnpivotEntry unpivot_entry;
372876 if (!expr->GetAlias().empty()) {
372877 unpivot_entry.alias = expr->GetAlias();
372878 }
372879 unpivot_entry.expressions.push_back(std::move(expr));
372880 unpivot_entries.push_back(std::move(unpivot_entry));
372881 }
372882}

◆ ExtractUnpivotColumnName()

void duckdb::Binder::ExtractUnpivotColumnName ( ParsedExpression & expr,
vector< string > & result )
private
372884 {
372885 if (expr.GetExpressionType() == ExpressionType::COLUMN_REF) {
372886 auto &colref = expr.Cast<ColumnRefExpression>();
372887 result.push_back(colref.GetColumnName());
372888 return;
372889 }
372890 if (expr.GetExpressionType() == ExpressionType::SUBQUERY) {
372891 throw BinderException(expr, "UNPIVOT list cannot contain subqueries");
372892 }
372893 ParsedExpressionIterator::EnumerateChildren(
372894 expr, [&](ParsedExpression &child) { ExtractUnpivotColumnName(child, result); });
372895}

◆ BindAtClause()

unique_ptr< BoundAtClause > duckdb::Binder::BindAtClause ( optional_ptr< AtClause > at_clause)
private
371299 {
371300 if (!at_clause) {
371301 return nullptr;
371302 }
371303 ConstantBinder binder(*this, context, "AT clause");
371304 auto expr = binder.Bind(at_clause->ExpressionMutable());
371305 auto val = ExpressionExecutor::EvaluateScalar(context, *expr);
371306 return make_uniq<BoundAtClause>(at_clause->Unit(), std::move(val));
371307}

◆ BindTableFunctionParameters()

bool duckdb::Binder::BindTableFunctionParameters ( TableFunctionCatalogEntry & table_function,
vector< unique_ptr< ParsedExpression > > & expressions,
vector< LogicalType > & arguments,
vector< Value > & parameters,
named_parameter_map_t & named_parameters,
BoundStatement & subquery,
ErrorData & error )
private
373478 {
373479 auto bind_type = GetTableFunctionBindType(table_function, expressions);
373480 if (bind_type == TableFunctionBindType::TABLE_IN_OUT_FUNCTION) {
373481 // bind table in-out function
373482 BindTableInTableOutFunction(expressions, subquery);
373483 // fetch the arguments from the subquery
373484 arguments = subquery.types;
373485 return true;
373486 }
373487 bool seen_subquery = false;
373488 for (auto &child : expressions) {
373489 string parameter_name;
373490
373491 // hack to make named parameters work
373492 if (child->GetExpressionType() == ExpressionType::COMPARE_EQUAL) {
373493 // comparison, check if the LHS is a columnref
373494 auto &comp = child->Cast<ComparisonExpression>();
373495 if (comp.left->GetExpressionType() == ExpressionType::COLUMN_REF) {
373496 auto &colref = comp.left->Cast<ColumnRefExpression>();
373497 if (!colref.IsQualified()) {
373498 parameter_name = colref.GetColumnName();
373499 child = std::move(comp.right);
373500 }
373501 }
373502 } else if (!child->GetAlias().empty()) {
373503 // <name> => <expression> will set the alias of <expression> to <name>
373504 parameter_name = child->GetAlias();
373505 }
373506 if (bind_type == TableFunctionBindType::TABLE_PARAMETER_FUNCTION &&
373507 child->GetExpressionType() == ExpressionType::SUBQUERY) {
373508 D_ASSERT(table_function.functions.Size() == 1);
373509 auto fun = table_function.functions.GetFunctionByOffset(0);
373510 if (table_function.functions.Size() != 1 || fun.arguments.empty()) {
373511 throw BinderException(
373512 "Only table-in-out functions can have subquery parameters - %s only accepts constant parameters",
373513 fun.name);
373514 }
373515 if (seen_subquery) {
373516 error = ErrorData("Table function can have at most one subquery parameter");
373517 return false;
373518 }
373519 auto binder = Binder::CreateBinder(this->context, this);
373520 binder->can_contain_nulls = true;
373521 auto &se = child->Cast<SubqueryExpression>();
373522 subquery = binder->BindNode(*se.subquery->node);
373523 MoveCorrelatedExpressions(*binder);
373524 seen_subquery = true;
373525 arguments.emplace_back(LogicalTypeId::TABLE);
373526 parameters.emplace_back();
373527 continue;
373528 }
373529
373530 TableFunctionBinder binder(*this, context, table_function.name);
373531 LogicalType sql_type;
373532 auto expr = binder.Bind(child, &sql_type);
373533 if (expr->HasParameter()) {
373534 throw ParameterNotResolvedException();
373535 }
373536 if (!expr->IsScalar()) {
373537 // should have been eliminated before
373538 throw InternalException("Table function requires a constant parameter");
373539 }
373540 auto constant = ExpressionExecutor::EvaluateScalar(context, *expr, true);
373541 if (parameter_name.empty()) {
373542 // unnamed parameter
373543 if (!named_parameters.empty()) {
373544 error = ErrorData("Unnamed parameters cannot come after named parameters");
373545 return false;
373546 }
373547 arguments.emplace_back(constant.IsNull() ? LogicalType::SQLNULL : sql_type);
373548 parameters.emplace_back(std::move(constant));
373549 } else {
373550 named_parameters[parameter_name] = std::move(constant);
373551 }
373552 }
373553 return true;
373554}

◆ BindTableInTableOutFunction()

void duckdb::Binder::BindTableInTableOutFunction ( vector< unique_ptr< ParsedExpression > > & expressions,
BoundStatement & subquery )
private
373463 {
373464 auto binder = Binder::CreateBinder(this->context, this);
373465 // generate a subquery and bind that (i.e. UNNEST([1,2,3]) becomes UNNEST((SELECT [1,2,3]))
373466 auto select_node = make_uniq<SelectNode>();
373467 select_node->select_list = std::move(expressions);
373468 select_node->from_table = make_uniq<EmptyTableRef>();
373469 binder->can_contain_nulls = true;
373470 subquery = binder->BindNode(*select_node);
373471 MoveCorrelatedExpressions(*binder);
373472}

◆ BindTableFunction()

BoundStatement duckdb::Binder::BindTableFunction ( TableFunction & function,
vector< Value > parameters )
private
373728 {
373729 named_parameter_map_t named_parameters;
373730 vector<LogicalType> input_table_types;
373731 vector<string> input_table_names;
373732
373733 TableFunctionRef ref;
373734 ref.alias = function.name;
373735 D_ASSERT(!ref.alias.empty());
373736 return BindTableFunctionInternal(function, ref, std::move(parameters), std::move(named_parameters),
373737 std::move(input_table_types), std::move(input_table_names));
373738}

◆ BindTableFunctionInternal()

BoundStatement duckdb::Binder::BindTableFunctionInternal ( TableFunction & table_function,
const TableFunctionRef & ref,
vector< Value > parameters,
named_parameter_map_t named_parameters,
vector< LogicalType > input_table_types,
vector< string > input_table_names )
private
373570 {
373571 auto function_name = GetAlias(ref);
373572 auto &column_name_alias = ref.column_name_alias;
373573 auto bind_index = GenerateTableIndex();
373574 // perform the binding
373575 unique_ptr<FunctionData> bind_data;
373576 vector<LogicalType> return_types;
373577 vector<string> return_names;
373578 auto constexpr ordinality_name = "ordinality";
373579 string ordinality_column_name = ordinality_name;
373580 optional_idx ordinality_column_id;
373581 if (table_function.bind || table_function.bind_replace || table_function.bind_operator) {
373582 TableFunctionBindInput bind_input(parameters, named_parameters, input_table_types, input_table_names,
373583 table_function.function_info.get(), this, table_function, ref);
373584 if (table_function.bind_operator) {
373585 auto new_plan = table_function.bind_operator(context, bind_input, bind_index, return_names);
373586 if (new_plan) {
373587 new_plan->ResolveOperatorTypes();
373588 if (new_plan->types.size() != return_names.size()) {
373589 throw InternalException("Failed to bind \"%s\": return_types/names must have same size",
373590 table_function.name);
373591 }
373592 for (auto &binding : new_plan->GetColumnBindings()) {
373593 if (binding.table_index != bind_index) {
373594 throw InternalException(
373595 "Failed to bind \"%s\": root bind index must be the passed in bind index",
373596 table_function.name);
373597 }
373598 }
373599 BoundStatement result;
373600 bind_context.AddGenericBinding(bind_index, function_name, return_names, new_plan->types);
373601 result.names = return_names;
373602 result.types = new_plan->types;
373603 result.plan = std::move(new_plan);
373604 return result;
373605 }
373606 }
373607 if (table_function.bind_replace) {
373608 auto new_plan = table_function.bind_replace(context, bind_input);
373609 if (new_plan) {
373610 if (!ref.alias.empty()) {
373611 new_plan->alias = ref.alias;
373612 }
373613 if (!ref.column_name_alias.empty()) {
373614 new_plan->column_name_alias = ref.column_name_alias;
373615 }
373616 return Bind(*new_plan);
373617 }
373618 }
373619 if (!table_function.bind) {
373620 throw BinderException("Failed to bind \"%s\": nullptr returned from bind_replace without bind function",
373621 table_function.name);
373622 }
373623 bind_data = table_function.bind(context, bind_input, return_types, return_names);
373624 if (ref.with_ordinality == OrdinalityType::WITH_ORDINALITY) {
373625 // check if column name 'ordinality' already exists and if so, replace it iteratively until free name is
373626 // found
373627 case_insensitive_set_t ci_return_names;
373628 idx_t ordinality_name_suffix = 0;
373629 for (auto &n : return_names) {
373630 ci_return_names.insert(n);
373631 }
373632 for (auto &n : column_name_alias) {
373633 ci_return_names.insert(n);
373634 }
373635 while (ci_return_names.find(ordinality_column_name) != ci_return_names.end()) {
373636 ordinality_column_name = ordinality_name + to_string(ordinality_name_suffix++);
373637 }
373638 if (!correlated_columns.empty()) {
373639 return_types.emplace_back(LogicalType::BIGINT);
373640 return_names.emplace_back(ordinality_column_name);
373641 D_ASSERT(return_names.size() == return_types.size());
373642 ordinality_column_id = return_types.size() - 1;
373643 }
373644 }
373645 } else {
373646 throw InvalidInputException("Cannot call function \"%s\" directly - it has no bind function",
373647 table_function.name);
373648 }
373649 if (bind_data && !bind_data->SupportStatementCache()) {
373650 SetAlwaysRequireRebind();
373651 }
373652 if (return_types.size() != return_names.size()) {
373653 throw InternalException("Failed to bind \"%s\": return_types/names must have same size", table_function.name);
373654 }
373655 if (return_types.empty()) {
373656 throw InternalException("Failed to bind \"%s\": Table function must return at least one column",
373657 table_function.name);
373658 }
373659 // overwrite the names with any supplied aliases
373660 for (idx_t i = 0; i < column_name_alias.size() && i < return_names.size(); i++) {
373661 return_names[i] = column_name_alias[i];
373662 }
373663 for (idx_t i = 0; i < return_names.size(); i++) {
373664 if (return_names[i].empty()) {
373665 return_names[i] = "C" + to_string(i);
373666 }
373667 }
373668 virtual_column_map_t virtual_columns;
373669 if (table_function.get_virtual_columns) {
373670 virtual_columns = table_function.get_virtual_columns(context, bind_data.get());
373671 }
373672
373673 auto get = make_uniq<LogicalGet>(bind_index, table_function, std::move(bind_data), return_types, return_names,
373674 virtual_columns);
373675 get->parameters = parameters;
373676 get->named_parameters = named_parameters;
373677 get->input_table_types = input_table_types;
373678 get->input_table_names = input_table_names;
373679 if (ref.with_ordinality == OrdinalityType::WITH_ORDINALITY && !correlated_columns.empty()) {
373680 get->ordinality_idx = ordinality_column_id;
373681 }
373682 if (table_function.in_out_function) {
373683 for (idx_t i = 0; i < return_types.size(); i++) {
373684 get->AddColumnId(i);
373685 }
373686 }
373687
373688 if (ref.with_ordinality == OrdinalityType::WITH_ORDINALITY && correlated_columns.empty()) {
373689 bind_context.AddTableFunction(bind_index, function_name, return_names, return_types, get->GetMutableColumnIds(),
373690 get->GetTable().get(), std::move(virtual_columns));
373691
373692 auto window_index = GenerateTableIndex();
373693 auto window = make_uniq<duckdb::LogicalWindow>(window_index);
373694 auto row_number =
373695 make_uniq<BoundWindowExpression>(ExpressionType::WINDOW_ROW_NUMBER, LogicalType::BIGINT, nullptr, nullptr);
373696 row_number->start = WindowBoundary::UNBOUNDED_PRECEDING;
373697 row_number->end = WindowBoundary::CURRENT_ROW_ROWS;
373698 string ordinality_alias = ordinality_column_name;
373699 if (return_names.size() < column_name_alias.size()) {
373700 row_number->alias = column_name_alias[return_names.size()];
373701 ordinality_alias = column_name_alias[return_names.size()];
373702 } else {
373703 row_number->alias = ordinality_column_name;
373704 }
373705 return_names.push_back(ordinality_alias);
373706 return_types.push_back(LogicalType::BIGINT);
373707 window->expressions.push_back(std::move(row_number));
373708 window->types.push_back(LogicalType::BIGINT);
373709 window->children.push_back(std::move(get));
373710 bind_context.AddGenericBinding(window_index, function_name, {ordinality_alias}, {LogicalType::BIGINT});
373711
373712 BoundStatement result;
373713 result.names = std::move(return_names);
373714 result.types = std::move(return_types);
373715 result.plan = std::move(window);
373716 return result;
373717 }
373718 // now add the table function to the bind context so its columns can be bound
373719 BoundStatement result;
373720 bind_context.AddTableFunction(bind_index, function_name, return_names, return_types, get->GetMutableColumnIds(),
373721 get->GetTable().get(), std::move(virtual_columns));
373722 result.names = std::move(return_names);
373723 result.types = std::move(return_types);
373724 result.plan = std::move(get);
373725 return result;
373726}

◆ CreatePlan() [3/3]

unique_ptr< LogicalOperator > duckdb::Binder::CreatePlan ( BoundJoinRef & ref)
private
374271 {
374272 auto old_is_outside_flattened = is_outside_flattened;
374273 // Plan laterals from outermost to innermost
374274 if (ref.lateral) {
374275 // Set the flag to ensure that children do not flatten before the root
374276 is_outside_flattened = false;
374277 }
374278 auto left = std::move(ref.left.plan);
374279 auto right = std::move(ref.right.plan);
374280 is_outside_flattened = old_is_outside_flattened;
374281
374282 // For joins, depth of the bindings will be one higher on the right because of the lateral binder
374283 // If the current join does not have correlations between left and right, then the right bindings
374284 // have depth 1 too high and can be reduced by 1 throughout
374285 if (!ref.lateral && !ref.correlated_columns.empty()) {
374286 LateralBinder::ReduceExpressionDepth(*right, ref.correlated_columns);
374287 }
374288
374289 if (ref.type == JoinType::RIGHT && ref.ref_type != JoinRefType::ASOF &&
374290 ClientConfig::GetConfig(context).enable_optimizer &&
374291 !Optimizer::OptimizerDisabled(context, OptimizerType::BUILD_SIDE_PROBE_SIDE)) {
374292 // we turn any right outer joins into left outer joins for optimization purposes
374293 // they are the same but with sides flipped, so treating them the same simplifies life
374294 ref.type = JoinType::LEFT;
374295 std::swap(left, right);
374296 }
374297 if (ref.lateral) {
374298 auto new_plan = PlanLateralJoin(std::move(left), std::move(right), ref.correlated_columns, ref.type,
374299 std::move(ref.condition));
374301 RecursiveDependentJoinPlanner plan(*this);
374302 plan.VisitOperator(*new_plan);
374303 }
374304 return new_plan;
374305 }
374306 switch (ref.ref_type) {
374307 case JoinRefType::CROSS:
374308 return LogicalCrossProduct::Create(std::move(left), std::move(right));
374309 case JoinRefType::POSITIONAL:
374310 return LogicalPositionalJoin::Create(std::move(left), std::move(right));
374311 default:
374312 break;
374313 }
374314 if (ref.type == JoinType::INNER && (ref.condition->HasSubquery() || HasCorrelatedColumns(*ref.condition)) &&
374315 ref.ref_type == JoinRefType::REGULAR) {
374316 // inner join, generate a cross product + filter
374317 // this will be later turned into a proper join by the join order optimizer
374318 auto root = LogicalCrossProduct::Create(std::move(left), std::move(right));
374319
374320 auto filter = make_uniq<LogicalFilter>(std::move(ref.condition));
374321 // visit the expressions in the filter
374322 for (auto &expression : filter->expressions) {
374323 PlanSubqueries(expression, root);
374324 }
374325 filter->AddChild(std::move(root));
374326 return std::move(filter);
374327 }
374328
374329 // now create the join operator from the join condition
374330 auto result = LogicalComparisonJoin::CreateJoin(context, ref.type, ref.ref_type, std::move(left), std::move(right),
374331 std::move(ref.condition));
374332 optional_ptr<LogicalOperator> join;
374333 if (result->type == LogicalOperatorType::LOGICAL_FILTER) {
374334 join = result->children[0].get();
374335 } else {
374336 join = result.get();
374337 }
374338
374339 if (ref.type == JoinType::MARK) {
374340 join->Cast<LogicalJoin>().mark_index = ref.mark_index;
374341 }
374342 for (auto &child : join->children) {
374343 if (child->type == LogicalOperatorType::LOGICAL_FILTER) {
374344 auto &filter = child->Cast<LogicalFilter>();
374345 for (auto &expr : filter.expressions) {
374346 PlanSubqueries(expr, filter.children[0]);
374347 }
374348 }
374349 }
374350
374351 // we visit the expressions depending on the type of join
374352 switch (join->type) {
374353 case LogicalOperatorType::LOGICAL_ASOF_JOIN:
374354 case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: {
374355 // comparison join
374356 // in this join we visit the expressions on the LHS with the LHS as root node
374357 // and the expressions on the RHS with the RHS as root node
374358 auto &comp_join = join->Cast<LogicalComparisonJoin>();
374359 for (idx_t i = 0; i < comp_join.conditions.size(); i++) {
374360 PlanSubqueries(comp_join.conditions[i].left, comp_join.children[0]);
374361 PlanSubqueries(comp_join.conditions[i].right, comp_join.children[1]);
374362 }
374363 break;
374364 }
374365 case LogicalOperatorType::LOGICAL_ANY_JOIN: {
374366 auto &any_join = join->Cast<LogicalAnyJoin>();
374367 // for the any join we just visit the condition
374368 if (any_join.condition->HasSubquery()) {
374369 throw NotImplementedException("Cannot perform non-inner join on subquery!");
374370 }
374371 break;
374372 }
374373 default:
374374 break;
374375 }
374376 if (!ref.duplicate_eliminated_columns.empty()) {
374377 auto &comp_join = join->Cast<LogicalComparisonJoin>();
374378 comp_join.type = LogicalOperatorType::LOGICAL_DELIM_JOIN;
374379 comp_join.delim_flipped = ref.delim_flipped;
374380 for (auto &col : ref.duplicate_eliminated_columns) {
374381 comp_join.duplicate_eliminated_columns.emplace_back(col->Copy());
374382 }
374383 }
374384 return result;
374385}
bool OptimizerDisabled(OptimizerType type)
Whether the specific optimizer is disabled.
Definition duckdb.cpp:316303

◆ BindCopyTo()

BoundStatement duckdb::Binder::BindCopyTo ( CopyStatement & stmt,
const CopyFunction & function,
CopyToType copy_to_type )
private
366292 {
366293 if (function.plan) {
366294 // plan rewrite COPY TO
366295 return function.plan(*this, stmt);
366296 }
366297
366298 auto &copy_info = *stmt.info;
366299 // bind the select statement
366300 auto node_copy = copy_info.select_statement->Copy();
366301 auto select_node = Bind(*node_copy);
366302
366303 if (!function.copy_to_bind) {
366304 throw NotImplementedException("COPY TO is not supported for FORMAT \"%s\"", stmt.info->format);
366305 }
366306
366307 bool use_tmp_file = true;
366308 CopyOverwriteMode overwrite_mode = CopyOverwriteMode::COPY_ERROR_ON_CONFLICT;
366309 FilenamePattern filename_pattern;
366310 bool user_set_use_tmp_file = false;
366311 bool per_thread_output = false;
366312 optional_idx file_size_bytes;
366313 vector<idx_t> partition_cols;
366314 bool seen_overwrite_mode = false;
366315 bool seen_filepattern = false;
366316 bool write_partition_columns = false;
366317 bool write_empty_file = true;
366318 bool hive_file_pattern = true;
366319 PreserveOrderType preserve_order = PreserveOrderType::AUTOMATIC;
366320 CopyFunctionReturnType return_type = CopyFunctionReturnType::CHANGED_ROWS;
366321
366322 CopyFunctionBindInput bind_input(*stmt.info, function.function_info);
366323
366324 bind_input.file_extension = function.extension;
366325
366326 auto original_options = stmt.info->options;
366327 stmt.info->options.clear();
366328 for (auto &option : original_options) {
366329 auto loption = StringUtil::Lower(option.first);
366330 if (loption == "use_tmp_file") {
366331 use_tmp_file = GetBooleanArg(context, option.second);
366332 user_set_use_tmp_file = true;
366333 } else if (loption == "overwrite_or_ignore" || loption == "overwrite" || loption == "append") {
366334 if (seen_overwrite_mode) {
366335 throw BinderException("Can only set one of OVERWRITE_OR_IGNORE, OVERWRITE or APPEND");
366336 }
366337 seen_overwrite_mode = true;
366338
366339 auto boolean = GetBooleanArg(context, option.second);
366340 if (boolean) {
366341 if (loption == "overwrite_or_ignore") {
366342 overwrite_mode = CopyOverwriteMode::COPY_OVERWRITE_OR_IGNORE;
366343 } else if (loption == "overwrite") {
366344 overwrite_mode = CopyOverwriteMode::COPY_OVERWRITE;
366345 } else if (loption == "append") {
366346 if (!seen_filepattern) {
366347 filename_pattern.SetFilenamePattern("{uuid}");
366348 }
366349 overwrite_mode = CopyOverwriteMode::COPY_APPEND;
366350 }
366351 }
366352 } else if (loption == "filename_pattern") {
366353 if (option.second.empty()) {
366354 throw IOException("FILENAME_PATTERN cannot be empty");
366355 }
366356 filename_pattern.SetFilenamePattern(
366357 option.second[0].CastAs(context, LogicalType::VARCHAR).GetValue<string>());
366358 seen_filepattern = true;
366359 } else if (loption == "file_extension") {
366360 if (option.second.empty()) {
366361 throw IOException("FILE_EXTENSION cannot be empty");
366362 }
366363 bind_input.file_extension = option.second[0].CastAs(context, LogicalType::VARCHAR).GetValue<string>();
366364 } else if (loption == "per_thread_output") {
366365 per_thread_output = GetBooleanArg(context, option.second);
366366 } else if (loption == "file_size_bytes") {
366367 if (option.second.empty()) {
366368 throw BinderException("FILE_SIZE_BYTES cannot be empty");
366369 }
366370 if (!function.rotate_files) {
366371 throw NotImplementedException("FILE_SIZE_BYTES not implemented for FORMAT \"%s\"", stmt.info->format);
366372 }
366373 if (option.second[0].GetTypeMutable().id() == LogicalTypeId::VARCHAR) {
366374 file_size_bytes = DBConfig::ParseMemoryLimit(option.second[0].ToString());
366375 } else {
366376 file_size_bytes = option.second[0].GetValue<uint64_t>();
366377 }
366378 } else if (loption == "partition_by") {
366379 auto converted = ConvertVectorToValue(std::move(option.second));
366380 partition_cols = ParseColumnsOrdered(converted, select_node.names, loption);
366381 } else if (loption == "return_files") {
366382 if (GetBooleanArg(context, option.second)) {
366383 return_type = CopyFunctionReturnType::CHANGED_ROWS_AND_FILE_LIST;
366384 }
366385 } else if (loption == "preserve_order") {
366386 if (GetBooleanArg(context, option.second)) {
366387 preserve_order = PreserveOrderType::PRESERVE_ORDER;
366388 } else {
366389 preserve_order = PreserveOrderType::DONT_PRESERVE_ORDER;
366390 }
366391 } else if (loption == "return_stats") {
366392 if (GetBooleanArg(context, option.second)) {
366393 return_type = CopyFunctionReturnType::WRITTEN_FILE_STATISTICS;
366394 }
366395 } else if (loption == "write_partition_columns") {
366396 write_partition_columns = GetBooleanArg(context, option.second);
366397 } else if (loption == "write_empty_file") {
366398 write_empty_file = GetBooleanArg(context, option.second);
366399 } else if (loption == "hive_file_pattern") {
366400 hive_file_pattern = GetBooleanArg(context, option.second);
366401 } else {
366402 stmt.info->options[option.first] = option.second;
366403 }
366404 }
366405 if (overwrite_mode == CopyOverwriteMode::COPY_APPEND && !filename_pattern.HasUUID()) {
366406 throw BinderException("APPEND mode requires a {uuid} label in filename_pattern");
366407 }
366408 if (user_set_use_tmp_file && per_thread_output) {
366409 throw NotImplementedException("Can't combine USE_TMP_FILE and PER_THREAD_OUTPUT for COPY");
366410 }
366411 if (user_set_use_tmp_file && file_size_bytes.IsValid()) {
366412 throw NotImplementedException("Can't combine USE_TMP_FILE and FILE_SIZE_BYTES for COPY");
366413 }
366414 if (user_set_use_tmp_file && !partition_cols.empty()) {
366415 throw NotImplementedException("Can't combine USE_TMP_FILE and PARTITION_BY for COPY");
366416 }
366417 if (per_thread_output && !partition_cols.empty()) {
366418 throw NotImplementedException("Can't combine PER_THREAD_OUTPUT and PARTITION_BY for COPY");
366419 }
366420 if (file_size_bytes.IsValid() && !partition_cols.empty()) {
366421 throw NotImplementedException("Can't combine FILE_SIZE_BYTES and PARTITION_BY for COPY");
366422 }
366423 if (!write_partition_columns) {
366424 if (partition_cols.size() == select_node.names.size()) {
366425 throw NotImplementedException("No column to write as all columns are specified as partition columns. "
366426 "WRITE_PARTITION_COLUMNS option can be used to write partition columns.");
366427 }
366428 }
366429 bool is_remote_file = FileSystem::IsRemoteFile(stmt.info->file_path);
366430 if (is_remote_file) {
366431 use_tmp_file = false;
366432 } else {
366433 auto &fs = FileSystem::GetFileSystem(context);
366434 bool is_file_and_exists = fs.FileExists(stmt.info->file_path);
366435 bool is_stdout = stmt.info->file_path == "/dev/stdout";
366436 if (!user_set_use_tmp_file) {
366437 use_tmp_file = is_file_and_exists && !per_thread_output && partition_cols.empty() && !is_stdout;
366438 }
366439 }
366440
366441 // Allow the copy function to intercept the select list and types and push a new projection on top of the plan
366442 if (function.copy_to_select) {
366443 auto bindings = select_node.plan->GetColumnBindings();
366444
366445 CopyToSelectInput input = {context, stmt.info->options, {}, copy_to_type};
366446 input.select_list.reserve(bindings.size());
366447
366448 // Create column references for the select list
366449 for (idx_t i = 0; i < bindings.size(); i++) {
366450 auto &binding = bindings[i];
366451 auto &name = select_node.names[i];
366452 auto &type = select_node.types[i];
366453 input.select_list.push_back(make_uniq<BoundColumnRefExpression>(name, type, binding));
366454 }
366455
366456 auto new_select_list = function.copy_to_select(input);
366457 if (!new_select_list.empty()) {
366458 // We have a new select list, create a projection on top of the current plan
366459 auto projection = make_uniq<LogicalProjection>(GenerateTableIndex(), std::move(new_select_list));
366460 projection->children.push_back(std::move(select_node.plan));
366461 projection->ResolveOperatorTypes();
366462
366463 // Update the names and types of the select node
366464 select_node.names.clear();
366465 select_node.types.clear();
366466 for (auto &expr : projection->expressions) {
366467 select_node.names.push_back(expr->GetName());
366468 select_node.types.push_back(expr->return_type);
366469 }
366470 select_node.plan = std::move(projection);
366471 }
366472 }
366473
366474 auto unique_column_names = select_node.names;
366475 QueryResult::DeduplicateColumns(unique_column_names);
366476 auto file_path = stmt.info->file_path;
366477
366478 auto names_to_write =
366479 LogicalCopyToFile::GetNamesWithoutPartitions(unique_column_names, partition_cols, write_partition_columns);
366480 auto types_to_write =
366481 LogicalCopyToFile::GetTypesWithoutPartitions(select_node.types, partition_cols, write_partition_columns);
366482 auto function_data = function.copy_to_bind(context, bind_input, names_to_write, types_to_write);
366483
366484 const auto rotate = function.rotate_files && function.rotate_files(*function_data, file_size_bytes);
366485 if (rotate) {
366486 if (!function.rotate_next_file) {
366487 throw InternalException("rotate_next_file not implemented for \"%s\"", function.extension);
366488 }
366489 if (user_set_use_tmp_file) {
366490 throw NotImplementedException(
366491 "Can't combine USE_TMP_FILE and file rotation (e.g., ROW_GROUPS_PER_FILE) for COPY");
366492 }
366493 if (!partition_cols.empty()) {
366494 throw NotImplementedException(
366495 "Can't combine file rotation (e.g., ROW_GROUPS_PER_FILE) and PARTITION_BY for COPY");
366496 }
366497 }
366498 if (!write_empty_file) {
366499 if (per_thread_output) {
366500 throw NotImplementedException("Can't combine WRITE_EMPTY_FILE false with PER_THREAD_OUTPUT");
366501 }
366502 if (!partition_cols.empty()) {
366503 throw NotImplementedException("Can't combine WRITE_EMPTY_FILE false with PARTITION_BY");
366504 }
366505 }
366506 if (return_type == CopyFunctionReturnType::WRITTEN_FILE_STATISTICS && !function.copy_to_get_written_statistics) {
366507 throw NotImplementedException("RETURN_STATS is not supported for the \"%s\" copy format", stmt.info->format);
366508 }
366509
366510 // now create the copy information
366511 auto copy = make_uniq<LogicalCopyToFile>(function, std::move(function_data), std::move(stmt.info));
366512 copy->file_path = file_path;
366513 copy->use_tmp_file = use_tmp_file;
366514 copy->overwrite_mode = overwrite_mode;
366515 copy->filename_pattern = filename_pattern;
366516 copy->file_extension = bind_input.file_extension;
366517 copy->per_thread_output = per_thread_output;
366518 if (file_size_bytes.IsValid()) {
366519 copy->file_size_bytes = file_size_bytes;
366520 }
366521 copy->rotate = rotate;
366522 copy->partition_output = !partition_cols.empty();
366523 copy->write_partition_columns = write_partition_columns;
366524 copy->partition_columns = std::move(partition_cols);
366525 copy->write_empty_file = write_empty_file;
366526 copy->return_type = return_type;
366527 copy->preserve_order = preserve_order;
366528 copy->hive_file_pattern = hive_file_pattern;
366529
366530 copy->names = unique_column_names;
366531 copy->expected_types = select_node.types;
366532
366533 copy->AddChild(std::move(select_node.plan));
366534
366535 auto &properties = GetStatementProperties();
366536 switch (copy->return_type) {
366537 case CopyFunctionReturnType::CHANGED_ROWS:
366538 properties.return_type = StatementReturnType::CHANGED_ROWS;
366539 break;
366540 case CopyFunctionReturnType::CHANGED_ROWS_AND_FILE_LIST:
366541 case CopyFunctionReturnType::WRITTEN_FILE_STATISTICS:
366542 properties.return_type = StatementReturnType::QUERY_RESULT;
366543 break;
366544 default:
366545 throw NotImplementedException("Unknown CopyFunctionReturnType");
366546 }
366547
366548 BoundStatement result;
366549 result.names = GetCopyFunctionReturnNames(copy->return_type);
366550 result.types = GetCopyFunctionReturnLogicalTypes(copy->return_type);
366551 result.plan = std::move(copy);
366552
366553 return result;
366554}
static DUCKDB_API bool IsRemoteFile(const string &path)
Whether or not a file is remote or local, based only on file path.
Definition duckdb.cpp:74413
void rotate(InputArray src, OutputArray dst, int rotateCode)
::uint64_t uint64_t
vector< LogicalType > GetCopyFunctionReturnLogicalTypes(CopyFunctionReturnType return_type)
Definition duckdb.cpp:220611

◆ BindCopyFrom()

BoundStatement duckdb::Binder::BindCopyFrom ( CopyStatement & stmt,
const CopyFunction & function )
private
366556 {
366557 BoundStatement result;
366558 result.types = {LogicalType::BIGINT};
366559 result.names = {"Count"};
366560
366561 if (stmt.info->table.empty()) {
366562 throw ParserException("COPY FROM requires a table name to be specified");
366563 }
366564 if (!function.copy_from_bind) {
366565 throw NotImplementedException("COPY FROM is not supported for FORMAT \"%s\"", stmt.info->format);
366566 }
366567 // COPY FROM a file
366568 // generate an insert statement for the to-be-inserted table
366569 InsertStatement insert;
366570 insert.table = stmt.info->table;
366571 insert.schema = stmt.info->schema;
366572 insert.catalog = stmt.info->catalog;
366573 insert.columns = stmt.info->select_list;
366574
366575 // bind the insert statement to the base table
366576 auto insert_statement = Bind(insert);
366577 D_ASSERT(insert_statement.plan->type == LogicalOperatorType::LOGICAL_INSERT);
366578
366579 auto &bound_insert = insert_statement.plan->Cast<LogicalInsert>();
366580
366581 // lookup the table to copy into
366582 BindSchemaOrCatalog(stmt.info->catalog, stmt.info->schema);
366583 auto &table =
366584 Catalog::GetEntry<TableCatalogEntry>(context, stmt.info->catalog, stmt.info->schema, stmt.info->table);
366585 vector<string> expected_names;
366586 if (!bound_insert.column_index_map.empty()) {
366587 expected_names.resize(bound_insert.expected_types.size());
366588 for (auto &col : table.GetColumns().Physical()) {
366589 auto i = col.Physical();
366590 if (bound_insert.column_index_map[i] != DConstants::INVALID_INDEX) {
366591 expected_names[bound_insert.column_index_map[i]] = col.Name();
366592 }
366593 }
366594 } else {
366595 expected_names.reserve(bound_insert.expected_types.size());
366596 for (auto &col : table.GetColumns().Physical()) {
366597 expected_names.push_back(col.Name());
366598 }
366599 }
366600 auto copy_from_function = function.copy_from_function;
366601 CopyFromFunctionBindInput input(*stmt.info, copy_from_function);
366602 auto function_data = function.copy_from_bind(context, input, expected_names, bound_insert.expected_types);
366603 auto get = make_uniq<LogicalGet>(GenerateTableIndex(), std::move(copy_from_function), std::move(function_data),
366604 bound_insert.expected_types, expected_names);
366605 for (idx_t i = 0; i < bound_insert.expected_types.size(); i++) {
366606 get->AddColumnId(i);
366607 }
366608 insert_statement.plan->children.push_back(std::move(get));
366609 result.plan = std::move(insert_statement.plan);
366610 return result;
366611}
static constexpr const idx_t INVALID_INDEX
The value used to signify an invalid index entry.
Definition duckdb.hpp:1117

◆ BindCopyOptions()

void duckdb::Binder::BindCopyOptions ( CopyInfo & info)
private
366673 {
366674 TableFunctionBinder option_binder(*this, context, "Copy", "Copy options");
366675 if (info.file_path_expression) {
366676 auto inputs = BindCopyOption(context, option_binder, "filename", info.file_path_expression);
366677 if (inputs.size() != 1 || inputs[0].type().id() != LogicalTypeId::VARCHAR) {
366678 throw InternalException("Unsupported parameter type for filename: expected e.g. TARGET 'file.parquet'");
366679 }
366680 if (!info.file_path.empty()) {
366681 throw InternalException("Both a file path and a file path expression were provided for COPY - only one of "
366682 "the two can be provided");
366683 }
366684 info.file_path = inputs[0].ToString();
366685 info.file_path_expression.reset();
366686 }
366687 for (auto &entry : info.parsed_options) {
366688 auto inputs = BindCopyOption(context, option_binder, entry.first, entry.second);
366689 if (StringUtil::CIEquals(entry.first, "format")) {
366690 // format specifier: interpret this option
366691 if (inputs.size() != 1 || inputs[0].type().id() != LogicalTypeId::VARCHAR) {
366692 throw ParserException("Unsupported parameter type for FORMAT: expected e.g. FORMAT 'csv', 'parquet'");
366693 }
366694 info.format = StringUtil::Lower(inputs[0].ToString());
366695 info.is_format_auto_detected = false;
366696 continue;
366697 }
366698 info.options[entry.first] = std::move(inputs);
366699 }
366700 if (info.is_format_auto_detected && info.format.empty()) {
366701 info.format = ExtractFormat(info.file_path);
366702 }
366703 info.parsed_options.clear();
366704}
static DUCKDB_API bool CIEquals(const string &l1, const string &l2)
Case insensitive equals.
Definition duckdb.cpp:109696
vector< Value > BindCopyOption(ClientContext &context, TableFunctionBinder &option_binder, const string &name, unique_ptr< ParsedExpression > &expr)
Definition duckdb.cpp:366613

◆ GetFullCopyOptionsList()

case_insensitive_map_t< CopyOption > duckdb::Binder::GetFullCopyOptionsList ( const CopyFunction & function,
CopyOptionMode mode )
private
366248 {
366249 case_insensitive_map_t<CopyOption> copy_options;
366250 CopyOptionsInput input(copy_options);
366251 function.copy_options(context, input);
366252
366253 // first erase all options that don't match this type
366254 if (mode != CopyOptionMode::READ_WRITE) {
366255 vector<string> erased_options;
366256 for (auto &entry : copy_options) {
366257 if (entry.second.mode == CopyOptionMode::READ_WRITE) {
366258 // used for both
366259 continue;
366260 }
366261 if (entry.second.mode != mode) {
366262 erased_options.push_back(entry.first);
366263 }
366264 }
366265 for (auto &erased : erased_options) {
366266 copy_options.erase(erased);
366267 }
366268 }
366269
366270 // now we have a list of all options for this copy type
366271 // add generic options
366272 if (mode != CopyOptionMode::READ_ONLY) {
366273 copy_options["use_tmp_file"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY);
366274 copy_options["overwrite_or_ignore"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY);
366275 copy_options["overwrite"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY);
366276 copy_options["append"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY);
366277 copy_options["filename_pattern"] = CopyOption(LogicalType::VARCHAR, CopyOptionMode::WRITE_ONLY);
366278 copy_options["file_extension"] = CopyOption(LogicalType::VARCHAR, CopyOptionMode::WRITE_ONLY);
366279 copy_options["per_thread_output"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY);
366280 copy_options["file_size_bytes"] = CopyOption(LogicalType::ANY, CopyOptionMode::WRITE_ONLY);
366281 copy_options["partition_by"] = CopyOption(LogicalType::ANY, CopyOptionMode::WRITE_ONLY);
366282 copy_options["return_files"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY);
366283 copy_options["preserve_order"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY);
366284 copy_options["return_stats"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY);
366285 copy_options["write_partition_columns"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY);
366286 copy_options["write_empty_file"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY);
366287 copy_options["hive_file_pattern"] = CopyOption(LogicalType::BOOLEAN, CopyOptionMode::WRITE_ONLY);
366288 }
366289 return copy_options;
366290}

◆ PrepareModifiers()

void duckdb::Binder::PrepareModifiers ( OrderBinder & order_binder,
QueryNode & statement,
BoundQueryNode & result )
private
364242 {
364243 for (auto &mod : statement.modifiers) {
364244 unique_ptr<BoundResultModifier> bound_modifier;
364245 switch (mod->type) {
364246 case ResultModifierType::DISTINCT_MODIFIER: {
364247 auto &distinct = mod->Cast<DistinctModifier>();
364248 auto bound_distinct = make_uniq<BoundDistinctModifier>();
364249 bound_distinct->distinct_type =
364250 distinct.distinct_on_targets.empty() ? DistinctType::DISTINCT : DistinctType::DISTINCT_ON;
364251 if (distinct.distinct_on_targets.empty()) {
364252 for (idx_t i = 0; i < result.names.size(); i++) {
364253 distinct.distinct_on_targets.push_back(
364254 make_uniq<ConstantExpression>(Value::INTEGER(UnsafeNumericCast<int32_t>(1 + i))));
364255 }
364256 }
364257 order_binder.SetQueryComponent("DISTINCT ON");
364258 auto &order_binders = order_binder.GetBinders();
364259 for (auto &distinct_on_target : distinct.distinct_on_targets) {
364260 vector<unique_ptr<ParsedExpression>> target_list;
364261 order_binders[0].get().ExpandStarExpression(std::move(distinct_on_target), target_list);
364262 for (auto &target : target_list) {
364263 auto expr = BindOrderExpression(order_binder, std::move(target));
364264 if (!expr) {
364265 continue;
364266 }
364267 // Skip duplicates
364268 bool duplicate = false;
364269 for (auto &existing : bound_distinct->target_distincts) {
364270 if (expr->Equals(*existing)) {
364271 duplicate = true;
364272 break;
364273 }
364274 }
364275 if (!duplicate) {
364276 bound_distinct->target_distincts.push_back(std::move(expr));
364277 }
364278 }
364279 }
364280 order_binder.SetQueryComponent();
364281
364282 bound_modifier = std::move(bound_distinct);
364283 break;
364284 }
364285 case ResultModifierType::ORDER_MODIFIER: {
364286 auto &order = mod->Cast<OrderModifier>();
364287 auto bound_order = make_uniq<BoundOrderModifier>();
364288 auto &config = DBConfig::GetConfig(context);
364289 D_ASSERT(!order.orders.empty());
364290 auto &order_binders = order_binder.GetBinders();
364291 if (order.orders.size() == 1 && order.orders[0].expression->GetExpressionType() == ExpressionType::STAR) {
364292 auto &star = order.orders[0].expression->Cast<StarExpression>();
364293 if (star.exclude_list.empty() && star.replace_list.empty() && !star.expr) {
364294 // ORDER BY ALL
364295 // replace the order list with the all elements in the SELECT list
364296 auto order_type = config.ResolveOrder(context, order.orders[0].type);
364297 auto null_order = config.ResolveNullOrder(context, order_type, order.orders[0].null_order);
364298 auto constant_expr = make_uniq<BoundConstantExpression>(Value("ALL"));
364299 bound_order->orders.emplace_back(order_type, null_order, std::move(constant_expr));
364300 bound_modifier = std::move(bound_order);
364301 break;
364302 }
364303 }
364304#if 0
364305 // When this verification is enabled, replace ORDER BY x, y with ORDER BY create_sort_key(x, y)
364306 // note that we don't enable this during actual verification since it doesn't always work
364307 // e.g. it breaks EXPLAIN output on queries
364308 bool can_replace = true;
364309 for (auto &order_node : order.orders) {
364310 if (order_node.expression->GetExpressionType() == ExpressionType::VALUE_CONSTANT) {
364311 // we cannot replace the sort key when we order by literals (e.g. ORDER BY 1, 2`
364312 can_replace = false;
364313 break;
364314 }
364315 }
364316 if (!order_binder.HasExtraList()) {
364317 // we can only do the replacement when we can order by elements that are not in the selection list
364318 can_replace = false;
364319 }
364320 if (can_replace) {
364321 vector<unique_ptr<ParsedExpression>> sort_key_parameters;
364322 for (auto &order_node : order.orders) {
364323 sort_key_parameters.push_back(std::move(order_node.expression));
364324 auto type = config.ResolveOrder(context, order_node.type);
364325 auto null_order = config.ResolveNullOrder(context, type, order_node.null_order);
364326 string sort_param = EnumUtil::ToString(type) + " " + EnumUtil::ToString(null_order);
364327 sort_key_parameters.push_back(make_uniq<ConstantExpression>(Value(sort_param)));
364328 }
364329 order.orders.clear();
364330 auto create_sort_key = make_uniq<FunctionExpression>("create_sort_key", std::move(sort_key_parameters));
364331 order.orders.emplace_back(OrderType::ASCENDING, OrderByNullType::NULLS_LAST, std::move(create_sort_key));
364332 }
364333#endif
364334 for (auto &order_node : order.orders) {
364335 vector<unique_ptr<ParsedExpression>> order_list;
364336 order_binders[0].get().ExpandStarExpression(std::move(order_node.expression), order_list);
364337
364338 auto type = config.ResolveOrder(context, order_node.type);
364339 auto null_order = config.ResolveNullOrder(context, type, order_node.null_order);
364340 for (auto &order_expr : order_list) {
364341 auto bound_expr = BindOrderExpression(order_binder, std::move(order_expr));
364342 if (!bound_expr) {
364343 continue;
364344 }
364345 bound_order->orders.emplace_back(type, null_order, std::move(bound_expr));
364346 }
364347 }
364348 if (!bound_order->orders.empty()) {
364349 bound_modifier = std::move(bound_order);
364350 }
364351 break;
364352 }
364353 case ResultModifierType::LIMIT_MODIFIER:
364354 bound_modifier = BindLimit(order_binder, mod->Cast<LimitModifier>());
364355 break;
364356 case ResultModifierType::LIMIT_PERCENT_MODIFIER:
364357 bound_modifier = BindLimitPercent(order_binder, mod->Cast<LimitPercentModifier>());
364358 break;
364359 default:
364360 throw InternalException("Unsupported result modifier");
364361 }
364362 if (bound_modifier) {
364363 result.modifiers.push_back(std::move(bound_modifier));
364364 }
364365 }
364366}

◆ BindModifiers()

void duckdb::Binder::BindModifiers ( BoundQueryNode & result,
idx_t table_index,
const vector< string > & names,
const vector< LogicalType > & sql_types,
const SelectBindState & bind_state )
private
364436 {
364437 for (auto &bound_mod : result.modifiers) {
364438 switch (bound_mod->type) {
364439 case ResultModifierType::DISTINCT_MODIFIER: {
364440 auto &distinct = bound_mod->Cast<BoundDistinctModifier>();
364441 // set types of distinct targets
364442 for (auto &expr : distinct.target_distincts) {
364443 expr = FinalizeBindOrderExpression(std::move(expr), table_index, names, sql_types, bind_state);
364444 if (!expr) {
364445 throw InternalException("DISTINCT ON ORDER BY ALL not supported");
364446 }
364447 }
364448 for (auto &expr : distinct.target_distincts) {
364449 ExpressionBinder::PushCollation(context, expr, expr->return_type);
364450 }
364451 break;
364452 }
364453 case ResultModifierType::LIMIT_MODIFIER: {
364454 auto &limit = bound_mod->Cast<BoundLimitModifier>();
364455 AssignReturnType(limit.limit_val.GetExpression(), table_index, names, sql_types, bind_state);
364456 AssignReturnType(limit.offset_val.GetExpression(), table_index, names, sql_types, bind_state);
364457 break;
364458 }
364459 case ResultModifierType::ORDER_MODIFIER: {
364460 auto &order = bound_mod->Cast<BoundOrderModifier>();
364461 bool order_by_all = false;
364462 for (auto &order_node : order.orders) {
364463 auto &expr = order_node.expression;
364464 expr = FinalizeBindOrderExpression(std::move(expr), table_index, names, sql_types, bind_state);
364465 if (!expr) {
364466 order_by_all = true;
364467 }
364468 }
364469 if (order_by_all) {
364470 D_ASSERT(order.orders.size() == 1);
364471 auto order_type = order.orders[0].type;
364472 auto null_order = order.orders[0].null_order;
364473 order.orders.clear();
364474 for (idx_t i = 0; i < sql_types.size(); i++) {
364475 auto expr = make_uniq<BoundColumnRefExpression>(sql_types[i], ColumnBinding(table_index, i));
364476 if (i < names.size()) {
364477 expr->SetAlias(names[i]);
364478 }
364479 order.orders.emplace_back(order_type, null_order, std::move(expr));
364480 }
364481 }
364482 for (auto &order_node : order.orders) {
364483 auto &expr = order_node.expression;
364484 ExpressionBinder::PushCollation(context, order_node.expression, expr->return_type);
364485 }
364486 break;
364487 }
364488 default:
364489 break;
364490 }
364491 }
364492}

◆ BindLimit()

duckdb::unique_ptr< BoundResultModifier > duckdb::Binder::BindLimit ( OrderBinder & order_binder,
LimitModifier & limit_mod )
private
364220 {
364221 auto result = make_uniq<BoundLimitModifier>();
364222 if (limit_mod.limit) {
364223 result->limit_val = BindLimitValue(order_binder, std::move(limit_mod.limit), false, false);
364224 }
364225 if (limit_mod.offset) {
364226 result->offset_val = BindLimitValue(order_binder, std::move(limit_mod.offset), false, true);
364227 }
364228 return std::move(result);
364229}
BoundLimitNode BindLimitValue(OrderBinder &order_binder, unique_ptr< ParsedExpression > limit_val, bool is_percentage, bool is_offset)
Bind a limit value (LIMIT or OFFSET).
Definition duckdb.cpp:364161

◆ BindLimitPercent()

unique_ptr< BoundResultModifier > duckdb::Binder::BindLimitPercent ( OrderBinder & order_binder,
LimitPercentModifier & limit_mod )
private
364231 {
364232 auto result = make_uniq<BoundLimitModifier>();
364233 if (limit_mod.limit) {
364234 result->limit_val = BindLimitValue(order_binder, std::move(limit_mod.limit), true, false);
364235 }
364236 if (limit_mod.offset) {
364237 result->offset_val = BindLimitValue(order_binder, std::move(limit_mod.offset), false, true);
364238 }
364239 return std::move(result);
364240}

◆ BindOrderExpression()

unique_ptr< Expression > duckdb::Binder::BindOrderExpression ( OrderBinder & order_binder,
unique_ptr< ParsedExpression > expr )
private
364149 {
364150 // we treat the distinct list as an ORDER BY
364151 auto bound_expr = order_binder.Bind(std::move(expr));
364152 if (!bound_expr) {
364153 // DISTINCT ON non-integer constant
364154 // remove the expression from the DISTINCT ON list
364155 return nullptr;
364156 }
364157 D_ASSERT(bound_expr->GetExpressionType() == ExpressionType::VALUE_CONSTANT);
364158 return bound_expr;
364159}

◆ PlanFilter()

unique_ptr< LogicalOperator > duckdb::Binder::PlanFilter ( unique_ptr< Expression > condition,
unique_ptr< LogicalOperator > root )
private
365323 {
365324 PlanSubqueries(condition, root);
365325 auto filter = make_uniq<LogicalFilter>(std::move(condition));
365326 filter->AddChild(std::move(root));
365327 return std::move(filter);
365328}

◆ PlanSubqueries()

void duckdb::Binder::PlanSubqueries ( unique_ptr< Expression > & expr,
unique_ptr< LogicalOperator > & root )
private
366097 {
366098 if (!expr_ptr) {
366099 return;
366100 }
366101 auto &expr = *expr_ptr;
366102 // first visit the children of the node, if any
366103 ExpressionIterator::EnumerateChildren(expr, [&](unique_ptr<Expression> &expr) { PlanSubqueries(expr, root); });
366104
366105 // check if this is a subquery node
366106 if (expr.GetExpressionClass() == ExpressionClass::BOUND_SUBQUERY) {
366107 auto &subquery = expr.Cast<BoundSubqueryExpression>();
366108 // subquery node! plan it
366109 expr_ptr = PlanSubquery(subquery, root);
366110 }
366111}

◆ PlanSubquery()

unique_ptr< Expression > duckdb::Binder::PlanSubquery ( BoundSubqueryExpression & expr,
unique_ptr< LogicalOperator > & root )
private
366071 {
366072 D_ASSERT(root);
366073 // first we translate the QueryNode of the subquery into a logical plan
366074 auto sub_binder = Binder::CreateBinder(context, this);
366075 sub_binder->is_outside_flattened = false;
366076 auto subquery_root = std::move(expr.subquery.plan);
366077 D_ASSERT(subquery_root);
366078
366079 // now we actually flatten the subquery
366080 auto plan = std::move(subquery_root);
366081
366082 unique_ptr<Expression> result_expression;
366083 if (!expr.IsCorrelated()) {
366084 result_expression = PlanUncorrelatedSubquery(*this, expr, root, std::move(plan));
366085 } else {
366086 result_expression = PlanCorrelatedSubquery(*this, expr, root, std::move(plan));
366087 }
366088 IncreaseDepth();
366089 // finally, we recursively plan the nested subqueries (if there are any)
366090 if (sub_binder->has_unplanned_dependent_joins) {
366091 RecursiveDependentJoinPlanner plan(*this);
366092 plan.VisitOperator(*root);
366093 }
366094 return result_expression;
366095}

◆ PlanLateralJoin()

unique_ptr< LogicalOperator > duckdb::Binder::PlanLateralJoin ( unique_ptr< LogicalOperator > left,
unique_ptr< LogicalOperator > right,
CorrelatedColumns & correlated_columns,
JoinType join_type = JoinType::INNER,
unique_ptr< Expression > condition = nullptr )
private
366115 {
366116 // scan the right operator for correlated columns
366117 // correlated LATERAL JOIN
366118 vector<JoinCondition> conditions;
366119 vector<unique_ptr<Expression>> arbitrary_expressions;
366120 if (condition) {
366121 if (condition->HasSubquery()) {
366122 throw BinderException(*condition, "Subqueries are not supported in LATERAL join conditions");
366123 }
366124 // extract join conditions, if there are any
366125 LogicalComparisonJoin::ExtractJoinConditions(context, join_type, JoinRefType::REGULAR, left, right,
366126 std::move(condition), conditions, arbitrary_expressions);
366127 }
366128
366129 auto perform_delim = PerformDuplicateElimination(*this, correlated);
366130 auto delim_join = CreateDuplicateEliminatedJoin(correlated, join_type, std::move(left), perform_delim);
366131
366132 // Store all information required to perform UNNESTING later.
366133 delim_join->perform_delim = perform_delim;
366134 delim_join->any_join = false;
366135 delim_join->propagate_null_values = join_type != JoinType::INNER;
366136 delim_join->is_lateral_join = true;
366137 delim_join->arbitrary_expressions = std::move(arbitrary_expressions);
366138 delim_join->conditions = std::move(conditions);
366139 delim_join->AddChild(std::move(right));
366140 return std::move(delim_join);
366141}

◆ CastLogicalOperatorToTypes()

unique_ptr< LogicalOperator > duckdb::Binder::CastLogicalOperatorToTypes ( const vector< LogicalType > & source_types,
const vector< LogicalType > & target_types,
unique_ptr< LogicalOperator > op )
private
365459 {
365460 D_ASSERT(op);
365461 // first check if we even need to cast
365462 D_ASSERT(source_types.size() == target_types.size());
365463 if (source_types == target_types) {
365464 // source and target types are equal: don't need to cast
365465 return op;
365466 }
365467 // otherwise add casts
365468 auto node = op.get();
365469 if (node->type == LogicalOperatorType::LOGICAL_PROJECTION) {
365470 // "node" is a projection; we can just do the casts in there
365471 D_ASSERT(node->expressions.size() == source_types.size());
365472 if (node->children.size() == 1 && node->children[0]->type == LogicalOperatorType::LOGICAL_GET) {
365473 // If this projection only has one child and that child is a logical get we can try to pushdown types
365474 auto &logical_get = node->children[0]->Cast<LogicalGet>();
365475 auto &column_ids = logical_get.GetColumnIds();
365476 if (logical_get.function.type_pushdown) {
365477 unordered_map<idx_t, LogicalType> new_column_types;
365478 bool do_pushdown = true;
365479 for (idx_t i = 0; i < op->expressions.size(); i++) {
365480 if (op->expressions[i]->GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) {
365481 auto &col_ref = op->expressions[i]->Cast<BoundColumnRefExpression>();
365482 auto column_id = column_ids[col_ref.binding.column_index].GetPrimaryIndex();
365483 if (new_column_types.find(column_id) != new_column_types.end()) {
365484 // Only one reference per column is accepted
365485 do_pushdown = false;
365486 break;
365487 }
365488 new_column_types[column_id] = target_types[i];
365489 } else {
365490 do_pushdown = false;
365491 break;
365492 }
365493 }
365494 if (do_pushdown) {
365495 logical_get.function.type_pushdown(context, logical_get.bind_data, new_column_types);
365496 // We also have to modify the types to the logical_get.returned_types
365497 for (auto &type : new_column_types) {
365498 logical_get.returned_types[type.first] = type.second;
365499 }
365500 return std::move(op->children[0]);
365501 }
365502 }
365503 }
365504 // add the casts to the selection list
365505 for (idx_t i = 0; i < target_types.size(); i++) {
365506 if (source_types[i] != target_types[i]) {
365507 // differing types, have to add a cast
365508 string cur_alias = node->expressions[i]->GetAlias();
365509 node->expressions[i] =
365510 BoundCastExpression::AddCastToType(context, std::move(node->expressions[i]), target_types[i]);
365511 node->expressions[i]->SetAlias(cur_alias);
365512 }
365513 }
365514 return op;
365515 } else {
365516 // found a non-projection operator
365517 // push a new projection containing the casts
365518
365519 // fetch the set of column bindings
365520 auto setop_columns = op->GetColumnBindings();
365521 D_ASSERT(setop_columns.size() == source_types.size());
365522
365523 // now generate the expression list
365524 vector<unique_ptr<Expression>> select_list;
365525 for (idx_t i = 0; i < target_types.size(); i++) {
365526 unique_ptr<Expression> result = make_uniq<BoundColumnRefExpression>(source_types[i], setop_columns[i]);
365527 if (source_types[i] != target_types[i]) {
365528 // add a cast only if the source and target types are not equivalent
365529 result = BoundCastExpression::AddCastToType(context, std::move(result), target_types[i]);
365530 }
365531 select_list.push_back(std::move(result));
365532 }
365533 auto projection = make_uniq<LogicalProjection>(GenerateTableIndex(), std::move(select_list));
365534 projection->children.push_back(std::move(op));
365535 return std::move(projection);
365536 }
365537}

◆ FindBinding()

BindingAlias duckdb::Binder::FindBinding ( const string & using_column,
const string & join_side )
private
371802 {
371803 BindingAlias result;
371804 if (!TryFindBinding(using_column, join_side, result)) {
371805 throw BinderException("Column \"%s\" does not exist on %s side of join!", using_column, join_side);
371806 }
371807 return result;
371808}

◆ TryFindBinding()

bool duckdb::Binder::TryFindBinding ( const string & using_column,
const string & join_side,
BindingAlias & result )
private
371773 {
371774 // for each using column, get the matching binding
371775 auto bindings = bind_context.GetMatchingBindings(using_column);
371776 if (bindings.empty()) {
371777 return false;
371778 }
371779 // find the join binding
371780 for (auto &binding : bindings) {
371781 if (result.IsSet()) {
371782 string error = "Column name \"";
371783 error += using_column;
371784 error += "\" is ambiguous: it exists more than once on ";
371785 error += join_side;
371786 error += " side of join.\nCandidates:";
371787 for (auto &binding_ref : bindings) {
371788 auto &other_binding = binding_ref.get();
371789 error += "\n\t";
371790 error += other_binding.GetAlias();
371791 error += ".";
371792 error += bind_context.GetActualColumnName(other_binding, using_column);
371793 }
371794 throw BinderException(error);
371795 } else {
371796 result = binding.get().GetBindingAlias();
371797 }
371798 }
371799 return true;
371800}

◆ AddUsingBindingSet()

void duckdb::Binder::AddUsingBindingSet ( unique_ptr< UsingColumnSet > set)
private
374657 {
374658 global_binder_state->using_column_sets.push_back(std::move(set));
374659}

◆ RetrieveUsingBinding()

BindingAlias duckdb::Binder::RetrieveUsingBinding ( Binder & current_binder,
optional_ptr< UsingColumnSet > current_set,
const string & column_name,
const string & join_side )
private
371841 {
371842 BindingAlias binding;
371843 if (!current_set) {
371844 binding = current_binder.FindBinding(using_column, join_side);
371845 } else {
371846 binding = current_set->primary_binding;
371847 }
371848 return binding;
371849}

◆ ExpandStarExpressions()

void duckdb::Binder::ExpandStarExpressions ( vector< unique_ptr< ParsedExpression > > & select_list,
vector< unique_ptr< ParsedExpression > > & new_select_list )
private
362381 {
362382 for (auto &select_element : select_list) {
362383 ExpandStarExpression(std::move(select_element), new_select_list);
362384 }
362385}
void ExpandStarExpression(unique_ptr< ParsedExpression > expr, vector< unique_ptr< ParsedExpression > > &new_select_list)
Definition duckdb.cpp:362227

◆ ExpandStarExpression()

void duckdb::Binder::ExpandStarExpression ( unique_ptr< ParsedExpression > expr,
vector< unique_ptr< ParsedExpression > > & new_select_list )
private

Check the current 'expr' to find out if it contains a star-expression that needs to be expanded

Expand the star that we found into a new list of expressions

We make a copy because we will be replacing the original star If we have identical stars that also need to be replaced This causes a heap-use-after-free or other corruption if we don't make a copy to reference instead.

362228 {
362229 TryTransformStarLike(expr);
362230
362231 StarExpression *star = nullptr;
362232
362235 auto star_type = FindStarExpression(expr, &star, true, false);
362236 if (star_type == StarExpressionType::NONE) {
362237 // no star expression: add it as-is
362238 D_ASSERT(!star);
362239 new_select_list.push_back(std::move(expr));
362240 return;
362241 }
362242 D_ASSERT(star);
362243 vector<unique_ptr<ParsedExpression>> star_list;
362245 bind_context.GenerateAllColumnExpressions(*star, star_list);
362246
362247 unique_ptr<duckdb_re2::RE2> regex;
362248 if (star->expr) {
362249 // COLUMNS with an expression
362250 // two options:
362251 // VARCHAR parameter <- this is a regular expression
362252 // LIST of VARCHAR parameters <- this is a set of columns
362253 TableFunctionBinder binder(*this, context);
362254 auto child = star->expr->Copy();
362255 auto result = binder.Bind(child);
362256 if (!result->IsFoldable()) {
362257 // cannot resolve parameters here
362258 if (star->expr->HasParameter()) {
362259 throw ParameterNotResolvedException();
362260 } else {
362261 throw BinderException("Unsupported expression in COLUMNS");
362262 }
362263 }
362264 auto val = ExpressionExecutor::EvaluateScalar(context, *result);
362265 if (val.type().id() == LogicalTypeId::VARCHAR) {
362266 // regex
362267 if (val.IsNull()) {
362268 throw BinderException("COLUMNS does not support NULL as regex argument");
362269 }
362270 auto &regex_str = StringValue::Get(val);
362271 regex = make_uniq<duckdb_re2::RE2>(regex_str);
362272 if (!regex->error().empty()) {
362273 auto err = StringUtil::Format("Failed to compile regex \"%s\": %s", regex_str, regex->error());
362274 throw BinderException(*star, err);
362275 }
362276 vector<unique_ptr<ParsedExpression>> new_list;
362277 for (auto &expanded_expr : star_list) {
362278 auto child_expr = GetResolvedColumnExpression(*expanded_expr);
362279 if (!child_expr) {
362280 continue;
362281 }
362282 auto &colref = child_expr->Cast<ColumnRefExpression>();
362283 if (!RE2::PartialMatch(colref.GetColumnName(), *regex)) {
362284 continue;
362285 }
362286 new_list.push_back(std::move(expanded_expr));
362287 }
362288 if (new_list.empty()) {
362289 vector<string> candidates;
362290 for (auto &expanded_expr : star_list) {
362291 auto child_expr = GetResolvedColumnExpression(*expanded_expr);
362292 if (!child_expr) {
362293 continue;
362294 }
362295 auto &colref = child_expr->Cast<ColumnRefExpression>();
362296 candidates.push_back(colref.GetColumnName());
362297 }
362298 string candidate_str;
362299 if (!candidates.empty()) {
362300 candidate_str = "\n" + StringUtil::CandidatesErrorMessage(candidates, regex_str, "Did you mean");
362301 }
362302 auto err =
362303 StringUtil::Format("No matching columns found that match regex \"%s\"%s", regex_str, candidate_str);
362304 throw BinderException(*star, err);
362305 }
362306 star_list = std::move(new_list);
362307 } else if (val.type().id() == LogicalTypeId::LIST &&
362308 ListType::GetChildType(val.type()).id() == LogicalTypeId::VARCHAR) {
362309 // list of varchar columns
362310 if (val.IsNull() || ListValue::GetChildren(val).empty()) {
362311 auto err =
362312 StringUtil::Format("Star expression \"%s\" resulted in an empty set of columns", star->ToString());
362313 throw BinderException(*star, err);
362314 }
362315 auto &children = ListValue::GetChildren(val);
362316 vector<unique_ptr<ParsedExpression>> new_list;
362317 // scan the list for all selected columns and construct a lookup table
362318 case_insensitive_map_t<bool> selected_set;
362319 for (auto &child : children) {
362320 if (child.IsNull()) {
362321 throw BinderException(*star, "Columns expression does not support NULL input parameters");
362322 }
362323 selected_set.insert(make_pair(StringValue::Get(child), false));
362324 }
362325 // now check the list of all possible expressions and select which ones make it in
362326 for (auto &expr : star_list) {
362327 auto str = GetColumnsStringValue(*expr);
362328 auto entry = selected_set.find(str);
362329 if (entry != selected_set.end()) {
362330 new_list.push_back(std::move(expr));
362331 entry->second = true;
362332 }
362333 }
362334 // check if all expressions found a match
362335 for (auto &entry : selected_set) {
362336 if (!entry.second) {
362337 throw BinderException("Column \"%s\" was selected but was not found in the FROM clause",
362338 entry.first);
362339 }
362340 }
362341 star_list = std::move(new_list);
362342 } else {
362343 throw BinderException(
362344 *star, "COLUMNS expects either a VARCHAR argument (regex) or a LIST of VARCHAR (list of columns)");
362345 }
362346 }
362350 auto copied_star_p = star->Copy();
362351 auto &copied_star = copied_star_p->Cast<StarExpression>();
362352
362353 // now perform the replacement
362354 if (star_type == StarExpressionType::UNPACKED) {
362355 if (StarExpression::IsColumnsUnpacked(*expr)) {
362356 throw BinderException("*COLUMNS not allowed at the root level, use COLUMNS instead");
362357 }
362358 ReplaceUnpackedStarExpression(expr, star_list, copied_star, regex.get());
362359 new_select_list.push_back(std::move(expr));
362360 return;
362361 }
362362 for (idx_t i = 0; i < star_list.size(); i++) {
362363 auto new_expr = expr->Copy();
362364 ReplaceStarExpression(new_expr, star_list[i]);
362365 if (StarExpression::IsColumns(copied_star)) {
362366 auto expr = GetResolvedColumnExpression(*star_list[i]);
362367 if (expr) {
362368 auto &colref = expr->Cast<ColumnRefExpression>();
362369 if (new_expr->GetAlias().empty()) {
362370 new_expr->SetAlias(colref.GetColumnName());
362371 } else {
362372 new_expr->SetAlias(ReplaceColumnsAlias(new_expr->GetAlias(), colref.GetColumnName(), regex.get()));
362373 }
362374 }
362375 }
362376 new_select_list.push_back(std::move(new_expr));
362377 }
362378}
static optional_ptr< ParsedExpression > GetResolvedColumnExpression(ParsedExpression &root_expr)
Returns a ColumnRefExpression after it was resolved (i.e. past the STAR expression/USING clauses).
Definition duckdb.cpp:362211
Here is the call graph for this function:

◆ FindStarExpression()

StarExpressionType duckdb::Binder::FindStarExpression ( unique_ptr< ParsedExpression > & expr,
StarExpression ** star,
bool is_root,
bool in_columns )
private
361997 {
361998 StarExpressionType has_star = StarExpressionType::NONE;
361999 if (expr->GetExpressionType() == ExpressionType::OPERATOR_UNPACK) {
362000 auto &operator_expr = expr->Cast<OperatorExpression>();
362001 auto res = FindStarExpression(operator_expr.children[0], star, is_root, in_columns);
362002 if (res != StarExpressionType::STAR && res != StarExpressionType::COLUMNS) {
362003 throw BinderException(
362004 "UNPACK can only be used in combination with a STAR (*) expression or COLUMNS expression");
362005 }
362006 return StarExpressionType::UNPACKED;
362007 }
362008 if (expr->GetExpressionClass() == ExpressionClass::STAR) {
362009 auto &current_star = expr->Cast<StarExpression>();
362010 if (StarExpression::IsStar(*expr)) {
362011 if (is_root) {
362012 D_ASSERT(!in_columns);
362013 // At the root level
362014 *star = &current_star;
362015 return StarExpressionType::STAR;
362016 }
362017
362018 if (!in_columns) {
362019 // '*' can only appear inside COLUMNS or at the root level
362020 throw BinderException(
362021 "STAR expression is only allowed as the root element of an expression. Use COLUMNS(*) instead.");
362022 }
362023
362024 if (!current_star.replace_list.empty()) {
362025 // '*' inside COLUMNS can not have a REPLACE list
362026 throw BinderException(
362027 "STAR expression with REPLACE list is only allowed as the root element of COLUMNS");
362028 }
362029 if (!current_star.rename_list.empty()) {
362030 // '*' inside COLUMNS can not have a REPLACE list
362031 throw BinderException(
362032 "STAR expression with RENAME list is only allowed as the root element of COLUMNS");
362033 }
362034
362035 // '*' expression inside a COLUMNS - convert to a constant list of strings (column names)
362036 vector<unique_ptr<ParsedExpression>> star_list;
362037 bind_context.GenerateAllColumnExpressions(current_star, star_list);
362038
362039 vector<Value> values;
362040 values.reserve(star_list.size());
362041 for (auto &element : star_list) {
362042 values.emplace_back(GetColumnsStringValue(*element));
362043 }
362044 D_ASSERT(!values.empty());
362045 expr = make_uniq<ConstantExpression>(Value::LIST(LogicalType::VARCHAR, values));
362046 return StarExpressionType::STAR;
362047 }
362048 if (in_columns) {
362049 throw BinderException("COLUMNS expression is not allowed inside another COLUMNS expression");
362050 }
362051 in_columns = true;
362052
362053 if (*star) {
362054 // we can have multiple
362055 if (!(*star)->Equals(current_star)) {
362056 throw BinderException(*expr,
362057 "Multiple different STAR/COLUMNS in the same expression are not supported");
362058 }
362059 return StarExpressionType::STAR;
362060 }
362061 *star = &current_star;
362062 has_star = StarExpressionType::STAR;
362063 }
362064 ParsedExpressionIterator::EnumerateChildren(*expr, [&](unique_ptr<ParsedExpression> &child_expr) {
362065 auto res = FindStarExpression(child_expr, star, false, in_columns);
362066 if (res != StarExpressionType::NONE) {
362067 has_star = res;
362068 }
362069 });
362070 return has_star;
362071}

◆ ReplaceUnpackedStarExpression()

void duckdb::Binder::ReplaceUnpackedStarExpression ( unique_ptr< ParsedExpression > & expr,
vector< unique_ptr< ParsedExpression > > & replacements,
StarExpression & star,
optional_ptr< duckdb_re2::RE2 > regex )
private
363141 {
363142 D_ASSERT(expr);
363143 auto expression_class = expr->GetExpressionClass();
363144 // Replace *COLUMNS(...) in the supported places
363145 switch (expression_class) {
363146 case ExpressionClass::FUNCTION: {
363147 ReplaceInFunction(expr, star_list, star, regex);
363148 break;
363149 }
363150 case ExpressionClass::OPERATOR: {
363151 if (StarExpression::IsColumnsUnpacked(*expr)) {
363152 throw BinderException("*COLUMNS() can not be used in this place");
363153 }
363154 ReplaceInOperator(expr, star_list, star, regex);
363155 break;
363156 }
363157 default: {
363158 break;
363159 }
363160 }
363161
363162 // Visit the children of this expression, collecting the unpacked expressions
363163 ParsedExpressionIterator::EnumerateChildren(*expr, [&](unique_ptr<ParsedExpression> &child_expr) {
363164 ReplaceUnpackedStarExpression(child_expr, star_list, star, regex);
363165 });
363166}

◆ BindWhereStarExpression()

void duckdb::Binder::BindWhereStarExpression ( unique_ptr< ParsedExpression > & expr)
private
364503 {
364504 // expand any expressions in the upper AND recursively
364505 if (expr->GetExpressionType() == ExpressionType::CONJUNCTION_AND) {
364506 auto &conj = expr->Cast<ConjunctionExpression>();
364507 for (auto &child : conj.children) {
364508 BindWhereStarExpression(child);
364509 }
364510 return;
364511 }
364512 if (expr->GetExpressionType() == ExpressionType::STAR) {
364513 auto &star = expr->Cast<StarExpression>();
364514 if (!star.columns) {
364515 throw ParserException("STAR expression is not allowed in the WHERE clause. Use COLUMNS(*) instead.");
364516 }
364517 }
364518 // expand the stars for this expression
364519 vector<unique_ptr<ParsedExpression>> new_conditions;
364520 ExpandStarExpression(std::move(expr), new_conditions);
364521 if (new_conditions.empty()) {
364522 throw ParserException("COLUMNS expansion resulted in empty set of columns");
364523 }
364524
364525 // set up an AND conjunction between the expanded conditions
364526 expr = std::move(new_conditions[0]);
364527 for (idx_t i = 1; i < new_conditions.size(); i++) {
364528 auto and_conj = make_uniq<ConjunctionExpression>(ExpressionType::CONJUNCTION_AND, std::move(expr),
364529 std::move(new_conditions[i]));
364530 expr = std::move(and_conj);
364531 }
364532}

◆ BindSchemaOrCatalog() [2/3]

void duckdb::Binder::BindSchemaOrCatalog ( string & catalog_name,
string & schema_name )
private

If only a schema name is provided (e.g. "a.b") then figure out if "a" is a schema or a catalog name.

367060 {
367061 BindSchemaOrCatalog(context, catalog, schema);
367062}

◆ BindSchemaOrCatalog() [3/3]

void duckdb::Binder::BindSchemaOrCatalog ( CatalogEntryRetriever & retriever,
string & catalog,
string & schema )
staticprivate

No database by that name was found

367017 {
367018 auto &context = retriever.GetContext();
367019 if (schema.empty()) {
367020 return;
367021 }
367022 if (!catalog.empty()) {
367023 return;
367024 }
367025 // schema is specified - but catalog is not
367026 // try searching for the catalog instead
367027 auto &db_manager = DatabaseManager::Get(context);
367028 auto database = db_manager.GetDatabase(context, schema);
367029 if (!database) {
367031 return;
367032 }
367033 // we have a database with this name
367034 // check if there is a schema
367035 auto &search_path = retriever.GetSearchPath();
367036 auto catalog_names = search_path.GetCatalogsForSchema(schema);
367037 if (catalog_names.empty()) {
367038 catalog_names.push_back(DatabaseManager::GetDefaultDatabase(context));
367039 }
367040 for (auto &catalog_name : catalog_names) {
367041 auto catalog_ptr = Catalog::GetCatalogEntry(retriever, catalog_name);
367042 if (!catalog_ptr) {
367043 continue;
367044 }
367045 if (catalog_ptr->CheckAmbiguousCatalogOrSchema(context, schema)) {
367046 throw BinderException(
367047 "Ambiguous reference to catalog or schema \"%s\" - use a fully qualified path like \"%s.%s\"", schema,
367048 catalog_name, schema);
367049 }
367050 }
367051 catalog = schema;
367052 schema = string();
367053}
Here is the call graph for this function:

◆ BindCatalog()

const string duckdb::Binder::BindCatalog ( string & catalog_name)
private
367064 {
367065 auto &db_manager = DatabaseManager::Get(context);
367066 optional_ptr<AttachedDatabase> database = db_manager.GetDatabase(context, catalog);
367067 if (database) {
367068 return db_manager.GetDatabase(context, catalog).get()->GetName();
367069 } else {
367070 return db_manager.GetDefaultDatabase(context);
367071 }
367072}

◆ BindCreateSchema()

SchemaCatalogEntry & duckdb::Binder::BindCreateSchema ( CreateInfo & info)
private
367117 {
367118 auto &schema = BindSchema(info);
367119 if (schema.catalog.IsSystemCatalog()) {
367120 throw BinderException("Cannot create entry in system catalog");
367121 }
367122 return schema;
367123}

◆ GetSearchPath()

vector< CatalogSearchEntry > duckdb::Binder::GetSearchPath ( Catalog & catalog,
const string & schema_name )
private

Signal that this catalog should be checked, regardless of the schema in the reference

371309 {
371310 vector<CatalogSearchEntry> view_search_path;
371311 auto &catalog_name = catalog.GetName();
371312 if (!schema_name.empty()) {
371313 view_search_path.emplace_back(catalog_name, schema_name);
371314 }
371315 auto default_schema = catalog.GetDefaultSchema();
371316 if (schema_name.empty() && schema_name != default_schema) {
371317 view_search_path.emplace_back(catalog_name, default_schema);
371318 }
371320 view_search_path.emplace_back(catalog_name, INVALID_SCHEMA);
371321 return view_search_path;
371322}
Here is the call graph for this function:

◆ BindLogicalTypeInternal()

LogicalType duckdb::Binder::BindLogicalTypeInternal ( const unique_ptr< ParsedExpression > & type_expr)
private
367365 {
367366 ConstantBinder binder(*this, context, "Type binding");
367367 auto copy = type_expr->Copy();
367368 auto expr = binder.Bind(copy);
367369
367370 if (!expr->IsFoldable()) {
367371 throw BinderException(*type_expr, "Type expression is not constant");
367372 }
367373
367374 if (expr->return_type != LogicalTypeId::TYPE) {
367375 throw BinderException(*type_expr, "Expected a type returning expression, but got expression of type '%s'",
367376 expr->return_type.ToString());
367377 }
367378
367379 // Shortcut for constant expressions
367380 if (expr->GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) {
367381 auto &const_expr = expr->Cast<BoundConstantExpression>();
367382 return TypeValue::GetType(const_expr.value);
367383 }
367384
367385 // Else, evaluate the type expression
367386 auto type_value = ExpressionExecutor::EvaluateScalar(context, *expr);
367387 D_ASSERT(type_value.type().id() == LogicalTypeId::TYPE);
367388 return TypeValue::GetType(type_value);
367389}

◆ BindSelectNode()

BoundStatement duckdb::Binder::BindSelectNode ( SelectNode & statement,
BoundStatement from_table )
private
364534 {
364535 D_ASSERT(from_table.plan);
364536 D_ASSERT(!statement.from_table);
364537 auto result_ptr = make_uniq<BoundSelectNode>();
364538 auto &result = *result_ptr;
364539 result.projection_index = GenerateTableIndex();
364540 result.group_index = GenerateTableIndex();
364541 result.aggregate_index = GenerateTableIndex();
364542 result.groupings_index = GenerateTableIndex();
364543 result.window_index = GenerateTableIndex();
364544 result.prune_index = GenerateTableIndex();
364545
364546 result.from_table = std::move(from_table);
364547 // bind the sample clause
364548 if (statement.sample) {
364549 result.sample_options = std::move(statement.sample);
364550 }
364551
364552 // visit the select list and expand any "*" statements
364553 vector<unique_ptr<ParsedExpression>> new_select_list;
364554 ExpandStarExpressions(statement.select_list, new_select_list);
364555
364556 if (new_select_list.empty()) {
364557 throw BinderException("SELECT list is empty after resolving * expressions!");
364558 }
364559 statement.select_list = std::move(new_select_list);
364560
364561 auto &bind_state = result.bind_state;
364562 for (idx_t i = 0; i < statement.select_list.size(); i++) {
364563 auto &expr = statement.select_list[i];
364564 result.names.push_back(expr->GetName());
364566 if (!expr->GetAlias().empty()) {
364567 bind_state.alias_map[expr->GetAlias()] = i;
364568 result.names[i] = expr->GetAlias();
364569 }
364570 bind_state.projection_map[*expr] = i;
364571 bind_state.original_expressions.push_back(expr->Copy());
364572 }
364573 result.column_count = statement.select_list.size();
364574
364575 // first visit the WHERE clause
364576 // the WHERE clause happens before the GROUP BY, PROJECTION or HAVING clauses
364577 if (statement.where_clause) {
364578 // bind any star expressions in the WHERE clause
364579 BindWhereStarExpression(statement.where_clause);
364580
364581 ColumnAliasBinder alias_binder(bind_state);
364582 WhereBinder where_binder(*this, context, &alias_binder);
364583 unique_ptr<ParsedExpression> condition = std::move(statement.where_clause);
364584 result.where_clause = where_binder.Bind(condition);
364585 }
364586
364587 // now bind all the result modifiers; including DISTINCT and ORDER BY targets
364588 OrderBinder order_binder({*this}, statement, bind_state);
364589 PrepareModifiers(order_binder, statement, result);
364590
364591 vector<unique_ptr<ParsedExpression>> unbound_groups;
364592 BoundGroupInformation info;
364593 auto &group_expressions = statement.groups.group_expressions;
364594 if (!group_expressions.empty()) {
364595 // the statement has a GROUP BY clause, bind it
364596 unbound_groups.resize(group_expressions.size());
364597 GroupBinder group_binder(*this, context, statement, result.group_index, bind_state, info.alias_map);
364598 // Allow NULL constants in GROUP BY to maintain their SQLNULL type
364599 auto prev_can_contain_nulls = this->can_contain_nulls;
364600 this->can_contain_nulls = true;
364601 for (idx_t i = 0; i < group_expressions.size(); i++) {
364602 // we keep a copy of the unbound expression;
364603 // we keep the unbound copy around to check for group references in the SELECT and HAVING clause
364604 // the reason we want the unbound copy is because we want to figure out whether an expression
364605 // is a group reference BEFORE binding in the SELECT/HAVING binder
364606 group_binder.unbound_expression = group_expressions[i]->Copy();
364607 group_binder.bind_index = i;
364608
364609 // bind the groups
364610 LogicalType group_type;
364611 auto bound_expr = group_binder.Bind(group_expressions[i], &group_type);
364612 D_ASSERT(bound_expr->return_type.id() != LogicalTypeId::INVALID);
364613
364614 // find out whether the expression contains a subquery, it can't be copied if so
364615 auto &bound_expr_ref = *bound_expr;
364616 bool contains_subquery = bound_expr_ref.HasSubquery();
364617
364618 // push a potential collation, if necessary
364619 bool requires_collation = ExpressionBinder::PushCollation(context, bound_expr, group_type);
364620 if (!contains_subquery && requires_collation) {
364621 // if there is a collation on a group x, we should group by the collated expr,
364622 // but also push a first(x) aggregate in case x is selected (uncollated)
364623 info.collated_groups[i] = result.aggregates.size();
364624
364625 auto first_fun = FirstFunctionGetter::GetFunction(bound_expr_ref.return_type);
364626 vector<unique_ptr<Expression>> first_children;
364627 // FIXME: would be better to just refer to this expression, but for now we copy
364628 first_children.push_back(bound_expr_ref.Copy());
364629
364630 FunctionBinder function_binder(*this);
364631 auto function = function_binder.BindAggregateFunction(first_fun, std::move(first_children));
364632 function->SetAlias("__collated_group");
364633 result.aggregates.push_back(std::move(function));
364634 }
364635 result.groups.group_expressions.push_back(std::move(bound_expr));
364636
364637 // in the unbound expression we DO bind the table names of any ColumnRefs
364638 // we do this to make sure that "table.a" and "a" are treated the same
364639 // if we wouldn't do this then (SELECT test.a FROM test GROUP BY a) would not work because "test.a" <> "a"
364640 // hence we convert "a" -> "test.a" in the unbound expression
364641 unbound_groups[i] = std::move(group_binder.unbound_expression);
364642 ExpressionBinder::QualifyColumnNames(*this, unbound_groups[i]);
364643 info.map[*unbound_groups[i]] = i;
364644 }
364645 this->can_contain_nulls = prev_can_contain_nulls;
364646 }
364647 result.groups.grouping_sets = std::move(statement.groups.grouping_sets);
364648
364649 // bind the HAVING clause, if any
364650 if (statement.having) {
364651 HavingBinder having_binder(*this, context, result, info, statement.aggregate_handling);
364652 ExpressionBinder::QualifyColumnNames(having_binder, statement.having);
364653 result.having = having_binder.Bind(statement.having);
364654 }
364655
364656 // bind the QUALIFY clause, if any
364657 vector<BoundColumnReferenceInfo> bound_qualify_columns;
364658 if (statement.qualify) {
364659 if (statement.aggregate_handling == AggregateHandling::FORCE_AGGREGATES) {
364660 throw BinderException("Combining QUALIFY with GROUP BY ALL is not supported yet");
364661 }
364662 QualifyBinder qualify_binder(*this, context, result, info);
364663 ExpressionBinder::QualifyColumnNames(*this, statement.qualify);
364664 result.qualify = qualify_binder.Bind(statement.qualify);
364665 if (qualify_binder.HasBoundColumns()) {
364666 if (qualify_binder.BoundAggregates()) {
364667 throw BinderException("Cannot mix aggregates with non-aggregated columns!");
364668 }
364669 bound_qualify_columns = qualify_binder.GetBoundColumns();
364670 }
364671 }
364672
364673 // after that, we bind to the SELECT list
364674 SelectBinder select_binder(*this, context, result, info);
364675
364676 // if we expand select-list expressions, e.g., via UNNEST, then we need to possibly
364677 // adjust the column index of the already bound ORDER BY modifiers, and not only set their types
364678 vector<idx_t> group_by_all_indexes;
364679 vector<string> new_names;
364680 vector<LogicalType> internal_sql_types;
364681
364682 for (idx_t i = 0; i < statement.select_list.size(); i++) {
364683 bool is_window = statement.select_list[i]->IsWindow();
364684 idx_t unnest_count = result.unnests.size();
364685 LogicalType result_type;
364686 auto expr = select_binder.Bind(statement.select_list[i], &result_type, true);
364687 bool is_original_column = i < result.column_count;
364688 bool can_group_by_all =
364689 statement.aggregate_handling == AggregateHandling::FORCE_AGGREGATES && is_original_column;
364690 result.bound_column_count++;
364691
364692 if (expr->GetExpressionType() == ExpressionType::BOUND_EXPANDED) {
364693 if (!is_original_column) {
364694 throw BinderException("UNNEST of struct cannot be used in ORDER BY/DISTINCT ON clause");
364695 }
364696 if (statement.aggregate_handling == AggregateHandling::FORCE_AGGREGATES) {
364697 throw BinderException("UNNEST of struct cannot be combined with GROUP BY ALL");
364698 }
364699
364700 auto &expanded = expr->Cast<BoundExpandedExpression>();
364701 auto &struct_expressions = expanded.expanded_expressions;
364702 D_ASSERT(!struct_expressions.empty());
364703
364704 for (auto &struct_expr : struct_expressions) {
364705 new_names.push_back(struct_expr->GetName());
364706 result.types.push_back(struct_expr->return_type);
364707 internal_sql_types.push_back(struct_expr->return_type);
364708 result.select_list.push_back(std::move(struct_expr));
364709 }
364710 bind_state.AddExpandedColumn(struct_expressions.size());
364711 continue;
364712 }
364713
364714 if (expr->IsVolatile()) {
364715 bind_state.SetExpressionIsVolatile(i);
364716 }
364717 if (expr->HasSubquery()) {
364718 bind_state.SetExpressionHasSubquery(i);
364719 }
364720 bind_state.AddRegularColumn();
364721
364722 if (can_group_by_all && select_binder.HasBoundColumns()) {
364723 if (select_binder.BoundAggregates()) {
364724 throw BinderException("Cannot mix aggregates with non-aggregated columns!");
364725 }
364726 if (is_window) {
364727 throw BinderException("Cannot group on a window clause");
364728 }
364729 if (result.unnests.size() > unnest_count) {
364730 throw BinderException("Cannot group on an UNNEST or UNLIST clause");
364731 }
364732 // we are forcing aggregates, and the node has columns bound
364733 // this entry becomes a group
364734 group_by_all_indexes.push_back(i);
364735 }
364736
364737 result.select_list.push_back(std::move(expr));
364738 if (is_original_column) {
364739 new_names.push_back(std::move(result.names[i]));
364740 result.types.push_back(result_type);
364741 }
364742 internal_sql_types.push_back(result_type);
364743
364744 if (can_group_by_all) {
364745 select_binder.ResetBindings();
364746 }
364747 }
364748
364749 // push the GROUP BY ALL expressions into the group set
364750
364751 for (auto &group_by_all_index : group_by_all_indexes) {
364752 auto &expr = result.select_list[group_by_all_index];
364753 auto group_ref = make_uniq<BoundColumnRefExpression>(
364754 expr->return_type, ColumnBinding(result.group_index, result.groups.group_expressions.size()));
364755 result.groups.group_expressions.push_back(std::move(expr));
364756 expr = std::move(group_ref);
364757 }
364758 set<idx_t> group_by_all_indexes_set;
364759 if (!group_by_all_indexes.empty()) {
364760 idx_t num_set_indexes = result.groups.group_expressions.size();
364761 for (idx_t i = 0; i < num_set_indexes; i++) {
364762 group_by_all_indexes_set.insert(i);
364763 }
364764 D_ASSERT(result.groups.grouping_sets.empty());
364765 result.groups.grouping_sets.push_back(group_by_all_indexes_set);
364766 }
364767 result.column_count = new_names.size();
364768 result.names = std::move(new_names);
364769 result.need_prune = result.select_list.size() > result.column_count;
364770
364771 // in the normal select binder, we bind columns as if there is no aggregation
364772 // i.e. in the query [SELECT i, SUM(i) FROM integers;] the "i" will be bound as a normal column
364773 // since we have an aggregation, we need to either (1) throw an error, or (2) wrap the column in a FIRST() aggregate
364774 // we choose the former one [CONTROVERSIAL: this is the PostgreSQL behavior]
364775 if (!result.groups.group_expressions.empty() || !result.aggregates.empty() || statement.having ||
364776 !result.groups.grouping_sets.empty()) {
364777 if (statement.aggregate_handling == AggregateHandling::NO_AGGREGATES_ALLOWED) {
364778 throw BinderException("Aggregates cannot be present in a Project relation!");
364779 } else {
364780 vector<BoundColumnReferenceInfo> bound_columns;
364781 if (select_binder.HasBoundColumns()) {
364782 bound_columns = select_binder.GetBoundColumns();
364783 }
364784 for (auto &bound_qualify_col : bound_qualify_columns) {
364785 bound_columns.push_back(bound_qualify_col);
364786 }
364787 if (!bound_columns.empty()) {
364788 string error;
364789 error = "column \"%s\" must appear in the GROUP BY clause or must be part of an aggregate function.";
364790 if (statement.aggregate_handling == AggregateHandling::FORCE_AGGREGATES) {
364791 error += "\nGROUP BY ALL will only group entries in the SELECT list. Add it to the SELECT list or "
364792 "GROUP BY this entry explicitly.";
364793 throw BinderException(bound_columns[0].query_location, error, bound_columns[0].name);
364794 } else {
364795 error +=
364796 "\nEither add it to the GROUP BY list, or use \"ANY_VALUE(%s)\" if the exact value of \"%s\" "
364797 "is not important.";
364798 throw BinderException(bound_columns[0].query_location, error, bound_columns[0].name,
364799 bound_columns[0].name, bound_columns[0].name);
364800 }
364801 }
364802 }
364803 }
364804
364805 // QUALIFY clause requires at least one window function to be specified in at least one of the SELECT column list or
364806 // the filter predicate of the QUALIFY clause
364807 if (statement.qualify && result.windows.empty()) {
364808 throw BinderException("at least one window function must appear in the SELECT column or QUALIFY clause");
364809 }
364810
364811 // now that the SELECT list is bound, we set the types of DISTINCT/ORDER BY expressions
364812 BindModifiers(result, result.projection_index, result.names, internal_sql_types, bind_state);
364813
364814 BoundStatement result_statement;
364815 result_statement.types = result.types;
364816 result_statement.names = result.names;
364817 result_statement.plan = CreatePlan(result);
364818 result_statement.extra_info.original_expressions = std::move(result.bind_state.original_expressions);
364819 return result_statement;
364820}

◆ BindCopyDatabaseSchema()

unique_ptr< LogicalOperator > duckdb::Binder::BindCopyDatabaseSchema ( Catalog & source_catalog,
const string & target_database_name )
private
366851 {
366852 catalog_entry_vector_t catalog_entries;
366853 catalog_entries = PhysicalExport::GetNaiveExportOrder(context, from_database);
366854
366855 auto info = make_uniq<CopyDatabaseInfo>(target_database_name);
366856 for (auto &entry : catalog_entries) {
366857 auto create_info = entry.get().GetInfo();
366858 create_info->catalog = target_database_name;
366859 auto on_conflict = create_info->type == CatalogType::SCHEMA_ENTRY ? OnCreateConflict::IGNORE_ON_CONFLICT
366860 : OnCreateConflict::ERROR_ON_CONFLICT;
366861 // Update all the dependencies of the entry to point to the newly created entries on the target database
366862 LogicalDependencyList altered_dependencies;
366863 for (auto &dep : create_info->dependencies.Set()) {
366864 auto altered_dep = dep;
366865 altered_dep.catalog = target_database_name;
366866 altered_dependencies.AddDependency(altered_dep);
366867 }
366868 create_info->dependencies = altered_dependencies;
366869 create_info->on_conflict = on_conflict;
366870 info->entries.push_back(std::move(create_info));
366871 }
366872
366873 return make_uniq<LogicalCopyDatabase>(std::move(info));
366874}

◆ BindCopyDatabaseData()

unique_ptr< LogicalOperator > duckdb::Binder::BindCopyDatabaseData ( Catalog & source_catalog,
const string & target_database_name )
private
366876 {
366877 auto source_schemas = source_catalog.GetSchemas(context);
366878
366879 // We can just use ExtractEntries here because the order doesn't matter
366880 ExportEntries entries;
366881 PhysicalExport::ExtractEntries(context, source_schemas, entries);
366882
366883 vector<unique_ptr<LogicalOperator>> insert_nodes;
366884 for (auto &table_ref : entries.tables) {
366885 auto &table = table_ref.get().Cast<TableCatalogEntry>();
366886 // generate the insert statement
366887 InsertStatement insert_stmt;
366888 insert_stmt.catalog = target_database_name;
366889 insert_stmt.schema = table.ParentSchema().name;
366890 insert_stmt.table = table.name;
366891
366892 auto from_tbl = make_uniq<BaseTableRef>();
366893 from_tbl->catalog_name = source_catalog.GetName();
366894 from_tbl->schema_name = table.ParentSchema().name;
366895 from_tbl->table_name = table.name;
366896
366897 auto select_node = make_uniq<SelectNode>();
366898 auto &select_list = select_node->select_list;
366899 for (auto &col : table.GetColumns().Physical()) {
366900 select_list.push_back(make_uniq<ColumnRefExpression>(col.Name(), table.name));
366901 }
366902
366903 select_node->from_table = std::move(from_tbl);
366904
366905 auto select_stmt = make_uniq<SelectStatement>();
366906 select_stmt->node = std::move(select_node);
366907
366908 insert_stmt.select_statement = std::move(select_stmt);
366909 auto bound_insert = Bind(insert_stmt);
366910 auto insert_plan = std::move(bound_insert.plan);
366911 insert_nodes.push_back(std::move(insert_plan));
366912 }
366913 unique_ptr<LogicalOperator> result;
366914 if (insert_nodes.empty()) {
366915 vector<LogicalType> result_types;
366916 result_types.push_back(LogicalType::BIGINT);
366917 vector<unique_ptr<Expression>> expression_list;
366918 expression_list.push_back(make_uniq<BoundConstantExpression>(Value::BIGINT(0)));
366919 vector<vector<unique_ptr<Expression>>> expressions;
366920 expressions.push_back(std::move(expression_list));
366921 result = make_uniq<LogicalExpressionGet>(GenerateTableIndex(), std::move(result_types), std::move(expressions));
366922 result->children.push_back(make_uniq<LogicalDummyScan>(GenerateTableIndex()));
366923 } else {
366924 // use UNION ALL to combine the individual copy statements into a single node
366925 result = UnionOperators(std::move(insert_nodes));
366926 }
366927 return result;
366928}
static DUCKDB_API Value BIGINT(int64_t value)
Create a bigint Value from a specified value.
Definition duckdb.cpp:132146

◆ BindShowQuery()

BoundStatement duckdb::Binder::BindShowQuery ( ShowRef & ref)
private
373221 {
373222 // bind the child plan of the DESCRIBE statement
373223 auto child_binder = Binder::CreateBinder(context, this);
373224 auto plan = child_binder->Bind(*ref.query);
373225
373226 // construct a column data collection with the result
373227 vector<string> return_names = {"column_name", "column_type", "null", "key", "default", "extra"};
373228 vector<LogicalType> return_types = {LogicalType::VARCHAR, LogicalType::VARCHAR, LogicalType::VARCHAR,
373229 LogicalType::VARCHAR, LogicalType::VARCHAR, LogicalType::VARCHAR};
373230 DataChunk output;
373231 output.Initialize(Allocator::Get(context), return_types);
373232
373233 auto collection = make_uniq<ColumnDataCollection>(context, return_types);
373234 ColumnDataAppendState append_state;
373235 collection->InitializeAppend(append_state);
373236 for (idx_t column_idx = 0; column_idx < plan.types.size(); column_idx++) {
373237 // check if we can trace the column to a base table so that we can figure out constraint information
373238 auto result = FindBaseTableColumn(*plan.plan, column_idx);
373239 idx_t row_index = output.size();
373240 auto &alias = plan.names[column_idx];
373241 if (result.table) {
373242 // we can! emit the information from the base table directly
373243 PragmaTableInfo::GetColumnInfo(*result.table, *result.column, output, row_index);
373244 // Override the base column name with the alias if one is specified.
373245 if (alias != result.column->Name()) {
373246 output.SetValue(0, row_index, Value(alias));
373247 }
373248 } else {
373249 // we cannot - read the type/name from the plan instead
373250 auto type = plan.types[column_idx];
373251
373252 // "name", TypeId::VARCHAR
373253 output.SetValue(0, row_index, Value(alias));
373254 // "type", TypeId::VARCHAR
373255 output.SetValue(1, row_index, Value(type.ToString()));
373256 // "null", TypeId::VARCHAR
373257 output.SetValue(2, row_index, Value("YES"));
373258 // "pk", TypeId::BOOL
373259 output.SetValue(3, row_index, Value());
373260 // "dflt_value", TypeId::VARCHAR
373261 output.SetValue(4, row_index, Value());
373262 // "extra", TypeId::VARCHAR
373263 output.SetValue(5, row_index, Value());
373264 }
373265
373266 output.SetCardinality(output.size() + 1);
373267 if (output.size() == STANDARD_VECTOR_SIZE) {
373268 collection->Append(append_state, output);
373269 output.Reset();
373270 }
373271 }
373272 collection->Append(append_state, output);
373273
373274 auto table_index = GenerateTableIndex();
373275
373276 BoundStatement result;
373277 result.names = return_names;
373278 result.types = return_types;
373279 result.plan = make_uniq<LogicalColumnDataGet>(table_index, return_types, std::move(collection));
373280 bind_context.AddGenericBinding(table_index, "__show_select", return_names, return_types);
373281 return result;
373282}
BaseTableColumnInfo FindBaseTableColumn(LogicalOperator &op, ColumnBinding binding)
Definition duckdb.cpp:373153

◆ BindShowTable()

BoundStatement duckdb::Binder::BindShowTable ( ShowRef & ref)
private
373284 {
373285 auto lname = StringUtil::Lower(ref.table_name);
373286
373287 string sql;
373288 if (lname == "\"databases\"") {
373289 sql = PragmaShowDatabases();
373290 } else if (lname == "\"schemas\"") {
373291 sql = "SELECT "
373292 " schema.database_name, "
373293 " schema.schema_name, "
373294 " ((select current_schema() = schema.schema_name) "
373295 " and (select current_database() = schema.database_name)) \"current\" "
373296 "FROM duckdb_schemas() schema "
373297 "JOIN duckdb_databases dbs USING (database_oid) "
373298 "WHERE dbs.internal = false "
373299 "ORDER BY all;";
373300 } else if (lname == "\"tables\"") {
373301 sql = PragmaShowTables();
373302 } else if (ref.show_type == ShowType::SHOW_FROM) {
373303 auto catalog_name = ref.catalog_name;
373304 auto schema_name = ref.schema_name;
373305
373306 // Check for unqualified name, promote schema to catalog if unambiguous, and set schema_name to empty if so
373307 Binder::BindSchemaOrCatalog(catalog_name, schema_name);
373308
373309 // If fully qualified, check if the schema exists
373310 if (!catalog_name.empty() && !schema_name.empty()) {
373311 auto schema_entry = Catalog::GetSchema(context, catalog_name, schema_name, OnEntryNotFound::RETURN_NULL);
373312 if (!schema_entry) {
373313 throw CatalogException("SHOW TABLES FROM: No catalog + schema named \"%s.%s\" found.", catalog_name,
373314 schema_name);
373315 }
373316 } else if (catalog_name.empty() && !schema_name.empty()) {
373317 // We have a schema name, use default catalog
373318 auto &client_data = ClientData::Get(context);
373319 auto &default_entry = client_data.catalog_search_path->GetDefault();
373320 catalog_name = default_entry.catalog;
373321 auto schema_entry = Catalog::GetSchema(context, catalog_name, schema_name, OnEntryNotFound::RETURN_NULL);
373322 if (!schema_entry) {
373323 throw CatalogException("SHOW TABLES FROM: No catalog + schema named \"%s.%s\" found.", catalog_name,
373324 schema_name);
373325 }
373326 }
373327 sql = PragmaShowTables(catalog_name, schema_name);
373328 } else if (lname == "\"variables\"") {
373329 sql = PragmaShowVariables();
373330 } else if (lname == "__show_tables_expanded") {
373331 sql = PragmaShowTablesExpanded();
373332 } else {
373333 sql = PragmaShow(ref.table_name);
373334 }
373336 auto subquery = make_uniq<SubqueryRef>(std::move(select));
373337 return Bind(*subquery);
373338}
GMat select(const GMat &src1, const GMat &src2, const GMat &mask)
static DUCKDB_API unique_ptr< SelectStatement > ParseSelect(const string &sql)
Parse a SELECT statement from a SQL string.
Definition duckdb.cpp:339903

◆ BindSummarize()

BoundStatement duckdb::Binder::BindSummarize ( ShowRef & ref)
private
370781 {
370782 unique_ptr<QueryNode> query;
370783 if (ref.query) {
370784 query = std::move(ref.query);
370785 } else {
370786 auto table_name = QualifiedName::Parse(ref.table_name);
370787 auto node = make_uniq<SelectNode>();
370788 node->select_list.push_back(make_uniq<StarExpression>());
370789 auto basetableref = make_uniq<BaseTableRef>();
370790 basetableref->catalog_name = table_name.catalog;
370791 basetableref->schema_name = table_name.schema;
370792 basetableref->table_name = table_name.name;
370793 node->from_table = std::move(basetableref);
370794 query = std::move(node);
370795 }
370796 auto query_copy = query->Copy();
370797
370798 // we bind the plan once in a child-node to figure out the column names and column types
370799 auto child_binder = Binder::CreateBinder(context, this);
370800 auto plan = child_binder->Bind(*query);
370801 D_ASSERT(plan.types.size() == plan.names.size());
370802 vector<unique_ptr<ParsedExpression>> name_children;
370803 vector<unique_ptr<ParsedExpression>> type_children;
370804 vector<unique_ptr<ParsedExpression>> min_children;
370805 vector<unique_ptr<ParsedExpression>> max_children;
370806 vector<unique_ptr<ParsedExpression>> unique_children;
370807 vector<unique_ptr<ParsedExpression>> avg_children;
370808 vector<unique_ptr<ParsedExpression>> std_children;
370809 vector<unique_ptr<ParsedExpression>> q25_children;
370810 vector<unique_ptr<ParsedExpression>> q50_children;
370811 vector<unique_ptr<ParsedExpression>> q75_children;
370812 vector<unique_ptr<ParsedExpression>> count_children;
370813 vector<unique_ptr<ParsedExpression>> null_percentage_children;
370814 auto select = make_uniq<SelectStatement>();
370815 select->node = std::move(query_copy);
370816 for (idx_t i = 0; i < plan.names.size(); i++) {
370817 name_children.push_back(make_uniq<ConstantExpression>(Value(plan.names[i])));
370818 type_children.push_back(make_uniq<ConstantExpression>(Value(plan.types[i].ToString())));
370819 min_children.push_back(SummarizeCreateAggregate("min", plan.names[i]));
370820 max_children.push_back(SummarizeCreateAggregate("max", plan.names[i]));
370821 unique_children.push_back(make_uniq<CastExpression>(
370822 LogicalType::BIGINT, SummarizeCreateAggregate("approx_count_distinct", plan.names[i])));
370823 if (plan.types[i].IsNumeric() || plan.types[i].IsTemporal()) {
370824 avg_children.push_back(SummarizeCreateAggregate("avg", plan.names[i]));
370825 } else {
370826 avg_children.push_back(make_uniq<ConstantExpression>(Value()));
370827 }
370828 if (plan.types[i].IsNumeric()) {
370829 std_children.push_back(SummarizeCreateAggregate("stddev", plan.names[i]));
370830 } else {
370831 std_children.push_back(make_uniq<ConstantExpression>(Value()));
370832 }
370833 if (plan.types[i].IsNumeric() || plan.types[i].IsTemporal()) {
370834 q25_children.push_back(SummarizeCreateAggregate("approx_quantile", plan.names[i], Value::FLOAT(0.25)));
370835 q50_children.push_back(SummarizeCreateAggregate("approx_quantile", plan.names[i], Value::FLOAT(0.50)));
370836 q75_children.push_back(SummarizeCreateAggregate("approx_quantile", plan.names[i], Value::FLOAT(0.75)));
370837 } else {
370838 q25_children.push_back(make_uniq<ConstantExpression>(Value()));
370839 q50_children.push_back(make_uniq<ConstantExpression>(Value()));
370840 q75_children.push_back(make_uniq<ConstantExpression>(Value()));
370841 }
370842 count_children.push_back(SummarizeCreateCountStar());
370843 null_percentage_children.push_back(SummarizeCreateNullPercentage(plan.names[i]));
370844 }
370845 auto subquery_ref = make_uniq<SubqueryRef>(std::move(select), "summarize_tbl");
370846 subquery_ref->column_name_alias = plan.names;
370847
370848 auto select_node = make_uniq<SelectNode>();
370849 select_node->select_list.push_back(SummarizeWrapUnnest(name_children, "column_name"));
370850 select_node->select_list.push_back(SummarizeWrapUnnest(type_children, "column_type"));
370851 select_node->select_list.push_back(SummarizeWrapUnnest(min_children, "min"));
370852 select_node->select_list.push_back(SummarizeWrapUnnest(max_children, "max"));
370853 select_node->select_list.push_back(SummarizeWrapUnnest(unique_children, "approx_unique"));
370854 select_node->select_list.push_back(SummarizeWrapUnnest(avg_children, "avg"));
370855 select_node->select_list.push_back(SummarizeWrapUnnest(std_children, "std"));
370856 select_node->select_list.push_back(SummarizeWrapUnnest(q25_children, "q25"));
370857 select_node->select_list.push_back(SummarizeWrapUnnest(q50_children, "q50"));
370858 select_node->select_list.push_back(SummarizeWrapUnnest(q75_children, "q75"));
370859 select_node->select_list.push_back(SummarizeWrapUnnest(count_children, "count"));
370860 select_node->select_list.push_back(SummarizeWrapUnnest(null_percentage_children, "null_percentage"));
370861 select_node->from_table = std::move(subquery_ref);
370862
370863 auto select_stmt = make_uniq<SelectStatement>();
370864 select_stmt->node = std::move(select_node);
370865 auto subquery = make_uniq<SubqueryRef>(std::move(select_stmt));
370866 return Bind(*subquery);
370867}
static DUCKDB_API Value FLOAT(float value)
Create a float Value from a specified value.
Definition duckdb.cpp:132310
static QualifiedName Parse(const string &input)
Definition duckdb.cpp:347714

◆ BindInsertColumnList()

void duckdb::Binder::BindInsertColumnList ( TableCatalogEntry & table,
vector< string > & columns,
bool default_values,
vector< LogicalIndex > & named_column_map,
vector< LogicalType > & expected_types,
IndexVector< idx_t, PhysicalIndex > & column_index_map )
private
369364 {
369365 if (!columns.empty() || default_values) {
369366 // insertion statement specifies column list
369367
369368 // create a mapping of (list index) -> (column index)
369369 case_insensitive_map_t<idx_t> column_name_map;
369370 for (idx_t i = 0; i < columns.size(); i++) {
369371 auto entry = column_name_map.insert(make_pair(columns[i], i));
369372 if (!entry.second) {
369373 throw BinderException("Duplicate column name \"%s\" in INSERT", columns[i]);
369374 }
369375 auto column_index = table.GetColumnIndex(columns[i]);
369376 if (column_index.index == COLUMN_IDENTIFIER_ROW_ID) {
369377 throw BinderException("Cannot explicitly insert values into rowid column");
369378 }
369379 auto &col = table.GetColumn(column_index);
369380 if (col.Generated()) {
369381 throw BinderException("Cannot insert into a generated column");
369382 }
369383 expected_types.push_back(col.Type());
369384 named_column_map.push_back(column_index);
369385 }
369386 for (auto &col : table.GetColumns().Physical()) {
369387 auto entry = column_name_map.find(col.Name());
369388 if (entry == column_name_map.end()) {
369389 // column not specified, set index to DConstants::INVALID_INDEX
369390 column_index_map.push_back(DConstants::INVALID_INDEX);
369391 } else {
369392 // column was specified, set to the index
369393 column_index_map.push_back(entry->second);
369394 }
369395 }
369396 } else {
369397 // insert by position and no columns specified - insertion into all columns of the table
369398 // intentionally don't populate 'column_index_map' as an indication of this
369399 for (auto &col : table.GetColumns().Physical()) {
369400 named_column_map.push_back(col.Logical());
369401 expected_types.push_back(col.Type());
369402 }
369403 }
369404}
const column_t COLUMN_IDENTIFIER_ROW_ID
Special value used to signify the ROW ID of a table.
Definition duckdb.cpp:50303

◆ TryReplaceDefaultExpression()

void duckdb::Binder::TryReplaceDefaultExpression ( unique_ptr< ParsedExpression > & expr,
const ColumnDefinition & column )
private
369193 {
369194 if (expr->GetExpressionType() != ExpressionType::VALUE_DEFAULT) {
369195 return;
369196 }
369197 expr = ExpandDefaultExpression(column);
369198}

◆ ExpandDefaultInValuesList()

void duckdb::Binder::ExpandDefaultInValuesList ( InsertStatement & stmt,
TableCatalogEntry & table,
optional_ptr< ExpressionListRef > values_list,
const vector< LogicalIndex > & named_column_map )
private
369202 {
369203 if (!values_list) {
369204 return;
369205 }
369206 idx_t expected_columns = stmt.columns.empty() ? table.GetColumns().PhysicalColumnCount() : stmt.columns.size();
369207
369208 // special case: check if we are inserting from a VALUES statement
369209 if (values_list) {
369210 auto &expr_list = values_list->Cast<ExpressionListRef>();
369211 expr_list.expected_types.resize(expected_columns);
369212 expr_list.expected_names.resize(expected_columns);
369213
369214 D_ASSERT(!expr_list.values.empty());
369215 CheckInsertColumnCountMismatch(expected_columns, expr_list.values[0].size(), !stmt.columns.empty(), table.name);
369216
369217 // VALUES list!
369218 for (idx_t col_idx = 0; col_idx < expected_columns; col_idx++) {
369219 D_ASSERT(named_column_map.size() >= col_idx);
369220 auto &table_col_idx = named_column_map[col_idx];
369221
369222 // set the expected types as the types for the INSERT statement
369223 auto &column = table.GetColumn(table_col_idx);
369224 expr_list.expected_types[col_idx] = column.Type();
369225 expr_list.expected_names[col_idx] = column.Name();
369226
369227 // now replace any DEFAULT values with the corresponding default expression
369228 for (idx_t list_idx = 0; list_idx < expr_list.values.size(); list_idx++) {
369229 TryReplaceDefaultExpression(expr_list.values[list_idx][col_idx], column);
369230 }
369231 }
369232 }
369233}

◆ BindMergeAction()

unique_ptr< BoundMergeIntoAction > duckdb::Binder::BindMergeAction ( LogicalMergeInto & merge_into,
TableCatalogEntry & table,
LogicalGet & get,
idx_t proj_index,
vector< unique_ptr< Expression > > & expressions,
unique_ptr< LogicalOperator > & root,
MergeIntoAction & action,
const vector< BindingAlias > & source_aliases,
const vector< string > & source_names )
private
369948 {
369949 auto result = make_uniq<BoundMergeIntoAction>();
369950 result->action_type = action.action_type;
369951 if (action.condition) {
369952 if (action.condition->HasSubquery()) {
369953 // if we have a subquery we need to execute the condition outside of the MERGE INTO statement
369954 WhereBinder where_binder(*this, context);
369955 auto cond = where_binder.Bind(action.condition);
369956 PlanSubqueries(cond, root);
369957 result->condition =
369958 make_uniq<BoundColumnRefExpression>(cond->return_type, ColumnBinding(proj_index, expressions.size()));
369959 expressions.push_back(std::move(cond));
369960 } else {
369961 ProjectionBinder proj_binder(*this, context, proj_index, expressions, "WHERE clause");
369962 proj_binder.target_type = LogicalType::BOOLEAN;
369963 auto cond = proj_binder.Bind(action.condition);
369964 result->condition = std::move(cond);
369965 }
369966 }
369967 switch (action.action_type) {
369968 case MergeActionType::MERGE_UPDATE: {
369969 if (!action.update_info) {
369970 // empty update list - generate it
369971 action.update_info = make_uniq<UpdateSetInfo>();
369972 if (action.column_order == InsertColumnOrder::INSERT_BY_NAME) {
369973 // UPDATE BY NAME - get the name list from the source binder
369974 action.update_info->columns = source_names;
369975 } else {
369976 // UPDATE BY POSITION - get the name list from the table
369977 for (auto &col : table.GetColumns().Physical()) {
369978 action.update_info->columns.push_back(col.Name());
369979 }
369980 }
369981 if (source_names.size() != action.update_info->columns.size()) {
369982 throw BinderException(
369983 "Data provided for UPDATE did not match column count in table - expected %d columns but got %d",
369984 action.update_info->columns.size(), source_names.size());
369985 }
369986 action.update_info->expressions = GenerateColumnReferences(*this, source_aliases, source_names);
369987 }
369988 BindUpdateSet(proj_index, root, *action.update_info, table, result->columns, result->expressions, expressions);
369989
369990 // bind any additional columns that need to be bound for update constraints
369991 // FIXME: this is pretty hacky
369992 // construct a dummy projection and update
369993 LogicalProjection proj(proj_index, std::move(expressions));
369994 LogicalUpdate update(table);
369995 update.return_chunk = merge_into.return_chunk;
369996 update.columns = std::move(result->columns);
369997 update.expressions = std::move(result->expressions);
369998 update.bound_defaults = std::move(merge_into.bound_defaults);
369999 update.bound_constraints = std::move(merge_into.bound_constraints);
370000 update.update_is_del_and_insert = false;
370001
370002 // call BindUpdateConstraints
370003 table.BindUpdateConstraints(*this, get, proj, update, context);
370004
370005 // move all moved values back
370006 merge_into.bound_defaults = std::move(update.bound_defaults);
370007 merge_into.bound_constraints = std::move(update.bound_constraints);
370008 expressions = std::move(proj.expressions);
370009 result->columns = std::move(update.columns);
370010 result->expressions = std::move(update.expressions);
370011 result->update_is_del_and_insert = update.update_is_del_and_insert;
370012 break;
370013 }
370014 case MergeActionType::MERGE_INSERT: {
370015 if (action.column_order == InsertColumnOrder::INSERT_BY_NAME) {
370016 // INSERT BY NAME - get the name list from the source binder and push it into the table
370017 if (!action.insert_columns.empty()) {
370018 throw InternalException("INSERT BY NAME cannot be combined with a column list");
370019 }
370020 action.insert_columns = source_names;
370021 }
370022 vector<LogicalIndex> named_column_map;
370023 vector<LogicalType> expected_types;
370024 BindInsertColumnList(table, action.insert_columns, action.default_values, named_column_map, expected_types,
370025 result->column_index_map);
370026
370027 vector<unique_ptr<Expression>> insert_expressions;
370028 if (!action.default_values && action.expressions.empty()) {
370029 // no expressions: *
370030 // expand source bindings
370031 action.expressions = GenerateColumnReferences(*this, source_aliases, source_names);
370032 }
370033 CheckInsertColumnCountMismatch(expected_types.size(), action.expressions.size(), !action.insert_columns.empty(),
370034 table.name);
370035 // explicit expressions - plan them
370036 for (idx_t i = 0; i < action.expressions.size(); i++) {
370037 auto &column = table.GetColumns().GetColumn(named_column_map[i]);
370038
370039 InsertBinder insert_binder(*this, context);
370040 insert_binder.target_type = column.Type();
370041
370042 TryReplaceDefaultExpression(action.expressions[i], column);
370043 auto insert_expr = insert_binder.Bind(action.expressions[i]);
370044
370045 PlanSubqueries(insert_expr, root);
370046 insert_expressions.push_back(std::move(insert_expr));
370047 }
370048
370049 for (auto &insert_expr : insert_expressions) {
370050 result->expressions.push_back(make_uniq<BoundColumnRefExpression>(
370051 insert_expr->return_type, ColumnBinding(proj_index, expressions.size())));
370052 expressions.push_back(std::move(insert_expr));
370053 }
370054 break;
370055 }
370056 case MergeActionType::MERGE_ERROR: {
370057 // bind the error message (if any)
370058 for (auto &expr : action.expressions) {
370059 ProjectionBinder proj_binder(*this, context, proj_index, expressions, "Error Message");
370060 proj_binder.target_type = LogicalType::VARCHAR;
370061 auto error_msg = proj_binder.Bind(expr);
370062 result->expressions.push_back(std::move(error_msg));
370063 }
370064 break;
370065 }
370066 case MergeActionType::MERGE_DELETE:
370067 case MergeActionType::MERGE_DO_NOTHING:
370068 // DELETE / DO NOTHING have nothing extra to bind
370069 break;
370070 default:
370071 throw InternalException("Unsupported merge action type");
370072 }
370073 return result;
370074}

◆ GenerateMergeInto()

unique_ptr< MergeIntoStatement > duckdb::Binder::GenerateMergeInto ( InsertStatement & stmt,
TableCatalogEntry & table )
private
369406 {
369407 D_ASSERT(stmt.on_conflict_info);
369408
369409 auto &on_conflict_info = *stmt.on_conflict_info;
369410 auto merge_into = make_uniq<MergeIntoStatement>();
369411 // set up the target table
369412 string table_name = !stmt.table_ref->alias.empty() ? stmt.table_ref->alias : stmt.table;
369413 merge_into->target = std::move(stmt.table_ref);
369414
369415 auto storage_info = table.GetStorageInfo(context);
369416 auto &columns = table.GetColumns();
369417 // set up the columns on which to join
369418 vector<vector<string>> all_distinct_on_columns;
369419 if (on_conflict_info.indexed_columns.empty()) {
369420 // When omitting the conflict target, we derive the join columns from the primary key/unique constraints
369421 // traverse the primary key/unique constraints
369422
369423 vector<unique_ptr<ParsedExpression>> join_conditions;
369424 // We check if there are any constraints on the table, if there aren't we throw an error.
369425 idx_t found_matching_indexes = 0;
369426 for (auto &index : storage_info.index_info) {
369427 if (!index.is_unique) {
369428 continue;
369429 }
369430
369431 vector<unique_ptr<ParsedExpression>> and_children;
369432 auto &indexed_columns = index.column_set;
369433 vector<string> distinct_on_columns;
369434 for (auto &column : columns.Physical()) {
369435 if (!indexed_columns.count(column.Physical().index)) {
369436 continue;
369437 }
369438 auto lhs = make_uniq<ColumnRefExpression>(column.Name(), table_name);
369439 auto rhs = make_uniq<ColumnRefExpression>(column.Name(), "excluded");
369440 auto new_condition =
369441 make_uniq<ComparisonExpression>(ExpressionType::COMPARE_EQUAL, std::move(lhs), std::move(rhs));
369442 and_children.push_back(std::move(new_condition));
369443 distinct_on_columns.push_back(column.Name());
369444 }
369445 all_distinct_on_columns.push_back(std::move(distinct_on_columns));
369446 if (and_children.empty()) {
369447 continue;
369448 }
369449 unique_ptr<ParsedExpression> condition;
369450 if (and_children.size() == 1) {
369451 condition = std::move(and_children[0]);
369452 } else {
369453 // AND together
369454 condition = make_uniq<ConjunctionExpression>(ExpressionType::CONJUNCTION_AND, std::move(and_children));
369455 }
369456 join_conditions.push_back(std::move(condition));
369457 found_matching_indexes++;
369458 }
369459 unique_ptr<ParsedExpression> join_condition;
369460 if (join_conditions.size() == 1) {
369461 join_condition = std::move(join_conditions[0]);
369462 } else {
369463 // OR together
369464 join_condition =
369465 make_uniq<ConjunctionExpression>(ExpressionType::CONJUNCTION_OR, std::move(join_conditions));
369466 }
369467 merge_into->join_condition = std::move(join_condition);
369468
369469 if (!found_matching_indexes) {
369470 throw BinderException("There are no UNIQUE/PRIMARY KEY constraints that refer to this table, specify ON "
369471 "CONFLICT columns manually");
369472 } else if (found_matching_indexes != 1) {
369473 if (on_conflict_info.action_type != OnConflictAction::NOTHING) {
369474 // When no conflict target is provided, and the action type is UPDATE,
369475 // we only allow the operation when only a single Index exists
369476 throw BinderException("Conflict target has to be provided for a DO UPDATE operation when the table has "
369477 "multiple UNIQUE/PRIMARY KEY constraints");
369478 }
369479 }
369480 } else {
369481 // when on conflict columns are explicitly provided - use them directly
369482 // first figure out if there is an index on the columns or not
369483 case_insensitive_map_t<idx_t> specified_columns;
369484 for (idx_t i = 0; i < on_conflict_info.indexed_columns.size(); i++) {
369485 specified_columns[on_conflict_info.indexed_columns[i]] = i;
369486 auto column_index = table.GetColumnIndex(on_conflict_info.indexed_columns[i]);
369487 if (column_index.index == COLUMN_IDENTIFIER_ROW_ID) {
369488 throw BinderException("Cannot specify ROWID as ON CONFLICT target");
369489 }
369490 auto &col = columns.GetColumn(column_index);
369491 if (col.Generated()) {
369492 throw BinderException("Cannot specify a generated column as ON CONFLICT target");
369493 }
369494 }
369495 unordered_set<column_t> on_conflict_filter;
369496 for (auto &col : columns.Physical()) {
369497 auto entry = specified_columns.find(col.Name());
369498 if (entry != specified_columns.end()) {
369499 // column was specified, set to the index
369500 on_conflict_filter.insert(col.Physical().index);
369501 }
369502 }
369503 bool index_references_columns = false;
369504 for (auto &index : storage_info.index_info) {
369505 if (!index.is_unique) {
369506 continue;
369507 }
369508 bool index_matches = on_conflict_filter == index.column_set;
369509 if (index_matches) {
369510 index_references_columns = true;
369511 break;
369512 }
369513 }
369514 if (!index_references_columns) {
369515 // Same as before, this is essentially a no-op, turning this into a DO THROW instead
369516 // But since this makes no logical sense, it's probably better to throw an error
369517 throw BinderException("The specified columns as conflict target are not referenced by a UNIQUE/PRIMARY KEY "
369518 "CONSTRAINT or INDEX");
369519 }
369520 all_distinct_on_columns.push_back(on_conflict_info.indexed_columns);
369521 merge_into->using_columns = std::move(on_conflict_info.indexed_columns);
369522 }
369523
369524 // expand any default values
369525 auto values_list = stmt.GetValuesList();
369526 if (values_list) {
369527 vector<LogicalIndex> named_column_map;
369528 if (stmt.columns.empty()) {
369529 for (auto &col : table.GetColumns().Physical()) {
369530 named_column_map.push_back(col.Logical());
369531 }
369532 } else {
369533 // Ensure that the columns are valid.
369534 for (auto &col_name : stmt.columns) {
369535 auto col_idx = table.GetColumnIndex(col_name);
369536 named_column_map.push_back(col_idx);
369537 }
369538 }
369539 ExpandDefaultInValuesList(stmt, table, values_list, named_column_map);
369540 }
369541 // set up the data source
369542 unique_ptr<TableRef> source;
369543 if (stmt.select_statement) {
369544 source = make_uniq<SubqueryRef>(std::move(stmt.select_statement), "excluded");
369545 } else {
369546 source = make_uniq<EmptyTableRef>();
369547 }
369548 if (stmt.column_order == InsertColumnOrder::INSERT_BY_POSITION) {
369549 // if we are inserting by position add the columns of the target table as an alias to the source
369550 if (!stmt.columns.empty() || stmt.default_values) {
369551 // we are not emitting all columns - set the column set as the set of aliases
369552 source->column_name_alias = stmt.columns;
369553
369554 // now push another subquery that adds the default columns
369555 auto select_stmt = make_uniq<SelectStatement>();
369556 auto select_node = make_uniq<SelectNode>();
369557 unordered_set<string> set_columns;
369558 for (auto &set_col : stmt.columns) {
369559 set_columns.insert(set_col);
369560 }
369561
369562 for (auto &column : columns.Physical()) {
369563 auto &name = column.Name();
369564 unique_ptr<ParsedExpression> expr;
369565 if (set_columns.find(name) == set_columns.end()) {
369566 // column is not specified - at the default value
369567 if (column.HasDefaultValue()) {
369568 expr = column.DefaultValue().Copy();
369569 } else {
369570 expr = make_uniq<ConstantExpression>(Value(column.Type()));
369571 }
369572 } else {
369573 // column is specified - add a reference to it
369574 expr = make_uniq<ColumnRefExpression>(name);
369575 }
369576 select_node->select_list.push_back(std::move(expr));
369577 }
369578 select_node->from_table = std::move(source);
369579 select_stmt->node = std::move(select_node);
369580
369581 source = make_uniq<SubqueryRef>(std::move(select_stmt), "excluded");
369582 }
369583 // push all columns of the table as an alias
369584 for (auto &column : columns.Physical()) {
369585 source->column_name_alias.push_back(column.Name());
369586 }
369587 }
369588 // push DISTINCT ON(unique_columns)
369589 for (auto &distinct_on_columns : all_distinct_on_columns) {
369590 auto distinct_stmt = make_uniq<SelectStatement>();
369591 auto select_node = make_uniq<SelectNode>();
369592 auto distinct = make_uniq<DistinctModifier>();
369593 for (auto &col : distinct_on_columns) {
369594 distinct->distinct_on_targets.push_back(make_uniq<ColumnRefExpression>(col));
369595 }
369596 select_node->modifiers.push_back(std::move(distinct));
369597 select_node->select_list.push_back(make_uniq<StarExpression>());
369598 select_node->from_table = std::move(source);
369599 distinct_stmt->node = std::move(select_node);
369600 source = make_uniq<SubqueryRef>(std::move(distinct_stmt), "excluded");
369601 }
369602
369603 merge_into->source = std::move(source);
369604
369605 if (on_conflict_info.action_type == OnConflictAction::REPLACE) {
369606 D_ASSERT(!on_conflict_info.set_info);
369607 // For BY POSITION, create explicit SET information
369608 // For BY NAME, leave it empty and let bind_merge_into handle it automatically
369609 if (stmt.column_order != InsertColumnOrder::INSERT_BY_NAME) {
369610 on_conflict_info.set_info = CreateSetInfoForReplace(table, stmt, storage_info);
369611 }
369612 on_conflict_info.action_type = OnConflictAction::UPDATE;
369613 }
369614 // now set up the merge actions
369615 // first set up the base (insert) action when not matched
369616 auto insert_action = make_uniq<MergeIntoAction>();
369617 insert_action->action_type = MergeActionType::MERGE_INSERT;
369618 insert_action->column_order = stmt.column_order;
369619
369620 merge_into->actions[MergeActionCondition::WHEN_NOT_MATCHED_BY_TARGET].push_back(std::move(insert_action));
369621
369622 if (on_conflict_info.condition) {
369623 throw BinderException("ON CONFLICT WHERE clause is only supported in DO UPDATE SET ... WHERE ...\nThe WHERE "
369624 "clause after the conflict columns is used for partial indexes which are not supported.");
369625 }
369626 if (on_conflict_info.action_type == OnConflictAction::UPDATE) {
369627 // when doing UPDATE set up the when matched action
369628 auto update_action = make_uniq<MergeIntoAction>();
369629 update_action->action_type = MergeActionType::MERGE_UPDATE;
369630 update_action->column_order = stmt.column_order;
369631 if (on_conflict_info.set_info) {
369632 for (auto &col : on_conflict_info.set_info->expressions) {
369633 vector<unordered_set<string>> lambda_params;
369634 DoUpdateSetQualify(col, table_name, lambda_params);
369635 }
369636 if (on_conflict_info.set_info->condition) {
369637 vector<unordered_set<string>> lambda_params;
369638 DoUpdateSetQualify(on_conflict_info.set_info->condition, table_name, lambda_params);
369639 update_action->condition = std::move(on_conflict_info.set_info->condition);
369640 }
369641 update_action->update_info = std::move(on_conflict_info.set_info);
369642 }
369643
369644 merge_into->actions[MergeActionCondition::WHEN_MATCHED].push_back(std::move(update_action));
369645 }
369646
369647 // move over extra properties
369648 merge_into->cte_map = std::move(stmt.cte_map);
369649 merge_into->returning_list = std::move(stmt.returning_list);
369650 return merge_into;
369651}

◆ CheckInsertColumnCountMismatch()

void duckdb::Binder::CheckInsertColumnCountMismatch ( idx_t expected_columns,
idx_t result_columns,
bool columns_provided,
const string & tname )
staticprivate
369175 {
369176 if (result_columns != expected_columns) {
369177 string msg = StringUtil::Format(!columns_provided ? "table %s has %lld columns but %lld values were supplied"
369178 : "Column name/value mismatch for insert on %s: "
369179 "expected %lld columns but %lld values were supplied",
369180 tname, expected_columns, result_columns);
369181 throw BinderException(msg);
369182 }
369183}

◆ PrepareCTE()

BoundCTEData duckdb::Binder::PrepareCTE ( const string & ctename,
CommonTableExpressionInfo & statement )
private
363710 {
363711 BoundCTEData result;
363712
363713 // first recursively visit the materialized CTE operations
363714 // the left side is visited first and is added to the BindContext of the right side
363715 D_ASSERT(statement.query);
363716
363717 result.ctename = ctename;
363718 result.materialized = statement.materialized;
363719 result.setop_index = GenerateTableIndex();
363720
363721 // instead of eagerly binding the CTE here we add the CTE bind state to the list of CTE bindings
363722 // the CTE is bound lazily - when referenced for the first time we perform the binding
363723 result.cte_bind_state = make_shared_ptr<CTEBindState>(*this, *statement.query->node, statement.aliases);
363724
363725 result.child_binder = Binder::CreateBinder(context, this);
363726
363727 // Add bindings of left side to temporary CTE bindings context
363728 // as we are binding a CTE currently, we take precendence over the existing binding.
363729 // This implements the CTE shadowing behavior.
363730 auto cte_binding = make_uniq<CTEBinding>(BindingAlias(ctename), result.cte_bind_state, result.setop_index);
363731 result.child_binder->bind_context.AddCTEBinding(std::move(cte_binding));
363732 return result;
363733}

◆ FinishCTE()

BoundStatement duckdb::Binder::FinishCTE ( BoundCTEData & bound_cte,
BoundStatement child_data )
private
363735 {
363736 if (!bound_cte.cte_bind_state->IsBound()) {
363737 // CTE was not bound - just ignore it
363738 MoveCorrelatedExpressions(*bound_cte.child_binder);
363739 return child;
363740 }
363741 auto &bind_state = *bound_cte.cte_bind_state;
363742 for (auto &c : bind_state.query_binder->correlated_columns) {
363743 bound_cte.child_binder->AddCorrelatedColumn(c);
363744 }
363745
363746 BoundStatement result;
363747 // the result types of the CTE are the types of the LHS
363748 result.types = child.types;
363749 result.names = child.names;
363750
363751 MoveCorrelatedExpressions(*bound_cte.child_binder);
363752 MoveCorrelatedExpressions(*bind_state.query_binder);
363753
363754 auto cte_query = std::move(bind_state.query.plan);
363755 auto cte_child = std::move(child.plan);
363756
363757 auto root = make_uniq<LogicalMaterializedCTE>(bound_cte.ctename, bound_cte.setop_index, result.types.size(),
363758 std::move(cte_query), std::move(cte_child), bound_cte.materialized);
363759
363760 // check if there are any unplanned subqueries left in either child
363762 bound_cte.child_binder->has_unplanned_dependent_joins ||
363763 bind_state.query_binder->has_unplanned_dependent_joins;
363764 result.plan = std::move(root);
363765 return result;
363766}

◆ CreateBinderWithSearchPath()

shared_ptr< Binder > duckdb::Binder::CreateBinderWithSearchPath ( const string & catalog_name,
const string & schema_name )
private

Create a binder whose catalog search path is anchored to the table's catalog+schema.

374818 {
374819 shared_ptr<Binder> new_binder = Binder::CreateBinder(context, this);
374820
374821 vector<CatalogSearchEntry> search_path;
374822
374823 search_path.emplace_back(catalog_name, schema_name);
374824 if (schema_name != DEFAULT_SCHEMA) {
374825 search_path.emplace_back(catalog_name, DEFAULT_SCHEMA);
374826 }
374827 new_binder->entry_retriever.SetSearchPath(std::move(search_path));
374828 return new_binder;
374829}
Here is the caller graph for this function:

Member Data Documentation

◆ correlated_columns

CorrelatedColumns duckdb::Binder::correlated_columns

The set of correlated columns bound by this binder (FIXME: this should probably be an unordered_set and not a vector)


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