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

The physical plan generator generates a physical execution plan from a logical query plan. More...

#include <duckdb.hpp>

Collaboration diagram for duckdb::PhysicalPlanGenerator:

Public Member Functions

 PhysicalPlanGenerator (ClientContext &context)
unique_ptr< PhysicalPlan > Plan (unique_ptr< LogicalOperator > logical)
 Creates and returns the physical plan from the logical operator. Performs a verification pass.
PhysicalOperator & CreatePlan (LogicalOperator &op)
template<class T, class... ARGS>
PhysicalOperator & Make (ARGS &&... args)
 Make a physical operator in the physical plan.
ArenaAllocator & ArenaRef ()
 Get a reference to the ArenaAllocator of the underlying physical plan. Creates a new (empty) physical plan if none exists yet.
PhysicalOperator & ResolveDefaultsProjection (LogicalInsert &op, PhysicalOperator &child)

Static Public Member Functions

static bool UseBatchIndex (ClientContext &context, PhysicalOperator &plan)
 Whether or not we can (or should) use a batch-index based operator for executing the given sink.
static bool PreserveInsertionOrder (ClientContext &context, PhysicalOperator &plan)
 Whether or not we should preserve insertion order for executing the given sink.
static OrderPreservationType OrderPreservationRecursive (PhysicalOperator &op)
 The order preservation type of the given operator decided by recursively looking at its children.

Public Attributes

LogicalDependencyList dependencies
unordered_map< idx_t, shared_ptr< ColumnDataCollection > > recursive_cte_tables
 Recursive CTEs require at least one ChunkScan, referencing the working_table. This data structure is used to establish it.
unordered_map< idx_t, shared_ptr< ColumnDataCollection > > recurring_cte_tables
 Used to reference the recurring tables.
unordered_map< idx_t, vector< const_reference< PhysicalOperator > > > materialized_ctes
 Materialized CTE ids must be collected.
idx_t delim_index = 0
 The index for duplicate eliminated joins.

Protected Member Functions

PhysicalOperator & CreatePlan (LogicalAggregate &op)
PhysicalOperator & CreatePlan (LogicalAnyJoin &op)
PhysicalOperator & CreatePlan (LogicalColumnDataGet &op)
PhysicalOperator & CreatePlan (LogicalComparisonJoin &op)
PhysicalOperator & CreatePlan (LogicalCopyDatabase &op)
PhysicalOperator & CreatePlan (LogicalCreate &op)
PhysicalOperator & CreatePlan (LogicalCreateTable &op)
PhysicalOperator & CreatePlan (LogicalCreateIndex &op)
PhysicalOperator & CreatePlan (LogicalCreateSecret &op)
PhysicalOperator & CreatePlan (LogicalCrossProduct &op)
PhysicalOperator & CreatePlan (LogicalDelete &op)
PhysicalOperator & CreatePlan (LogicalDelimGet &op)
PhysicalOperator & CreatePlan (LogicalDistinct &op)
PhysicalOperator & CreatePlan (LogicalDummyScan &expr)
PhysicalOperator & CreatePlan (LogicalEmptyResult &op)
PhysicalOperator & CreatePlan (LogicalExpressionGet &op)
PhysicalOperator & CreatePlan (LogicalExport &op)
PhysicalOperator & CreatePlan (LogicalFilter &op)
PhysicalOperator & CreatePlan (LogicalGet &op)
PhysicalOperator & CreatePlan (LogicalLimit &op)
PhysicalOperator & CreatePlan (LogicalMergeInto &op)
PhysicalOperator & CreatePlan (LogicalOrder &op)
PhysicalOperator & CreatePlan (LogicalTopN &op)
PhysicalOperator & CreatePlan (LogicalPositionalJoin &op)
PhysicalOperator & CreatePlan (LogicalProjection &op)
PhysicalOperator & CreatePlan (LogicalInsert &op)
PhysicalOperator & CreatePlan (LogicalCopyToFile &op)
PhysicalOperator & CreatePlan (LogicalExplain &op)
PhysicalOperator & CreatePlan (LogicalSetOperation &op)
PhysicalOperator & CreatePlan (LogicalUpdate &op)
PhysicalOperator & CreatePlan (LogicalPrepare &expr)
PhysicalOperator & CreatePlan (LogicalWindow &expr)
PhysicalOperator & CreatePlan (LogicalExecute &op)
PhysicalOperator & CreatePlan (LogicalPragma &op)
PhysicalOperator & CreatePlan (LogicalSample &op)
PhysicalOperator & CreatePlan (LogicalSet &op)
PhysicalOperator & CreatePlan (LogicalReset &op)
PhysicalOperator & CreatePlan (LogicalSimple &op)
PhysicalOperator & CreatePlan (LogicalVacuum &op)
PhysicalOperator & CreatePlan (LogicalUnnest &op)
PhysicalOperator & CreatePlan (LogicalRecursiveCTE &op)
PhysicalOperator & CreatePlan (LogicalMaterializedCTE &op)
PhysicalOperator & CreatePlan (LogicalCTERef &op)
PhysicalOperator & CreatePlan (LogicalPivot &op)
PhysicalOperator & PlanAsOfJoin (LogicalComparisonJoin &op)
PhysicalOperator & PlanComparisonJoin (LogicalComparisonJoin &op)
PhysicalOperator & PlanDelimJoin (LogicalComparisonJoin &op)
PhysicalOperator & ExtractAggregateExpressions (PhysicalOperator &child, vector< unique_ptr< Expression > > &expressions, vector< unique_ptr< Expression > > &groups, optional_ptr< vector< GroupingSet > > grouping_sets)

Private Member Functions

PhysicalOperator & ResolveAndPlan (unique_ptr< LogicalOperator > logical)
unique_ptr< PhysicalPlan > PlanInternal (LogicalOperator &logical)
bool PreserveInsertionOrder (PhysicalOperator &plan)
bool UseBatchIndex (PhysicalOperator &plan)
optional_ptr< PhysicalOperator > PlanAsOfLoopJoin (LogicalComparisonJoin &op, PhysicalOperator &probe, PhysicalOperator &build)

Private Attributes

ClientContext & context
unique_ptr< PhysicalPlan > physical_plan

Detailed Description

The physical plan generator generates a physical execution plan from a logical query plan.

Constructor & Destructor Documentation

◆ PhysicalPlanGenerator()

duckdb::PhysicalPlanGenerator::PhysicalPlanGenerator ( ClientContext & context)
explicit
206789 : context(context) {
206790}

◆ ~PhysicalPlanGenerator()

duckdb::PhysicalPlanGenerator::~PhysicalPlanGenerator ( )
206792 {
206793}

Member Function Documentation

◆ Plan()

unique_ptr< PhysicalPlan > duckdb::PhysicalPlanGenerator::Plan ( unique_ptr< LogicalOperator > logical)

Creates and returns the physical plan from the logical operator. Performs a verification pass.

206795 {
206796 auto &plan = ResolveAndPlan(std::move(op));
206797 plan.Verify();
206798 return std::move(physical_plan);
206799}

◆ CreatePlan() [1/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalOperator & op)
206842 {
206843 switch (op.type) {
206844 case LogicalOperatorType::LOGICAL_GET:
206845 return CreatePlan(op.Cast<LogicalGet>());
206846 case LogicalOperatorType::LOGICAL_PROJECTION:
206847 return CreatePlan(op.Cast<LogicalProjection>());
206848 case LogicalOperatorType::LOGICAL_EMPTY_RESULT:
206849 return CreatePlan(op.Cast<LogicalEmptyResult>());
206850 case LogicalOperatorType::LOGICAL_FILTER:
206851 return CreatePlan(op.Cast<LogicalFilter>());
206852 case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY:
206853 return CreatePlan(op.Cast<LogicalAggregate>());
206854 case LogicalOperatorType::LOGICAL_WINDOW:
206855 return CreatePlan(op.Cast<LogicalWindow>());
206856 case LogicalOperatorType::LOGICAL_UNNEST:
206857 return CreatePlan(op.Cast<LogicalUnnest>());
206858 case LogicalOperatorType::LOGICAL_LIMIT:
206859 return CreatePlan(op.Cast<LogicalLimit>());
206860 case LogicalOperatorType::LOGICAL_SAMPLE:
206861 return CreatePlan(op.Cast<LogicalSample>());
206862 case LogicalOperatorType::LOGICAL_ORDER_BY:
206863 return CreatePlan(op.Cast<LogicalOrder>());
206864 case LogicalOperatorType::LOGICAL_TOP_N:
206865 return CreatePlan(op.Cast<LogicalTopN>());
206866 case LogicalOperatorType::LOGICAL_COPY_TO_FILE:
206867 return CreatePlan(op.Cast<LogicalCopyToFile>());
206868 case LogicalOperatorType::LOGICAL_DUMMY_SCAN:
206869 return CreatePlan(op.Cast<LogicalDummyScan>());
206870 case LogicalOperatorType::LOGICAL_ANY_JOIN:
206871 return CreatePlan(op.Cast<LogicalAnyJoin>());
206872 case LogicalOperatorType::LOGICAL_ASOF_JOIN:
206873 case LogicalOperatorType::LOGICAL_DELIM_JOIN:
206874 case LogicalOperatorType::LOGICAL_COMPARISON_JOIN:
206875 return CreatePlan(op.Cast<LogicalComparisonJoin>());
206876 case LogicalOperatorType::LOGICAL_CROSS_PRODUCT:
206877 return CreatePlan(op.Cast<LogicalCrossProduct>());
206878 case LogicalOperatorType::LOGICAL_POSITIONAL_JOIN:
206879 return CreatePlan(op.Cast<LogicalPositionalJoin>());
206880 case LogicalOperatorType::LOGICAL_UNION:
206881 case LogicalOperatorType::LOGICAL_EXCEPT:
206882 case LogicalOperatorType::LOGICAL_INTERSECT:
206883 return CreatePlan(op.Cast<LogicalSetOperation>());
206884 case LogicalOperatorType::LOGICAL_INSERT:
206885 return CreatePlan(op.Cast<LogicalInsert>());
206886 case LogicalOperatorType::LOGICAL_DELETE:
206887 return CreatePlan(op.Cast<LogicalDelete>());
206888 case LogicalOperatorType::LOGICAL_CHUNK_GET:
206889 return CreatePlan(op.Cast<LogicalColumnDataGet>());
206890 case LogicalOperatorType::LOGICAL_DELIM_GET:
206891 return CreatePlan(op.Cast<LogicalDelimGet>());
206892 case LogicalOperatorType::LOGICAL_EXPRESSION_GET:
206893 return CreatePlan(op.Cast<LogicalExpressionGet>());
206894 case LogicalOperatorType::LOGICAL_UPDATE:
206895 return CreatePlan(op.Cast<LogicalUpdate>());
206896 case LogicalOperatorType::LOGICAL_MERGE_INTO:
206897 return CreatePlan(op.Cast<LogicalMergeInto>());
206898 case LogicalOperatorType::LOGICAL_CREATE_TABLE:
206899 return CreatePlan(op.Cast<LogicalCreateTable>());
206900 case LogicalOperatorType::LOGICAL_CREATE_INDEX:
206901 return CreatePlan(op.Cast<LogicalCreateIndex>());
206902 case LogicalOperatorType::LOGICAL_CREATE_SECRET:
206903 return CreatePlan(op.Cast<LogicalCreateSecret>());
206904 case LogicalOperatorType::LOGICAL_EXPLAIN:
206905 return CreatePlan(op.Cast<LogicalExplain>());
206906 case LogicalOperatorType::LOGICAL_DISTINCT:
206907 return CreatePlan(op.Cast<LogicalDistinct>());
206908 case LogicalOperatorType::LOGICAL_PREPARE:
206909 return CreatePlan(op.Cast<LogicalPrepare>());
206910 case LogicalOperatorType::LOGICAL_EXECUTE:
206911 return CreatePlan(op.Cast<LogicalExecute>());
206912 case LogicalOperatorType::LOGICAL_CREATE_VIEW:
206913 case LogicalOperatorType::LOGICAL_CREATE_SEQUENCE:
206914 case LogicalOperatorType::LOGICAL_CREATE_SCHEMA:
206915 case LogicalOperatorType::LOGICAL_CREATE_MACRO:
206916 case LogicalOperatorType::LOGICAL_CREATE_TYPE:
206917 return CreatePlan(op.Cast<LogicalCreate>());
206918 case LogicalOperatorType::LOGICAL_PRAGMA:
206919 return CreatePlan(op.Cast<LogicalPragma>());
206920 case LogicalOperatorType::LOGICAL_VACUUM:
206921 return CreatePlan(op.Cast<LogicalVacuum>());
206922 case LogicalOperatorType::LOGICAL_TRANSACTION:
206923 case LogicalOperatorType::LOGICAL_ALTER:
206924 case LogicalOperatorType::LOGICAL_DROP:
206925 case LogicalOperatorType::LOGICAL_LOAD:
206926 case LogicalOperatorType::LOGICAL_ATTACH:
206927 case LogicalOperatorType::LOGICAL_DETACH:
206928 return CreatePlan(op.Cast<LogicalSimple>());
206929 case LogicalOperatorType::LOGICAL_RECURSIVE_CTE:
206930 return CreatePlan(op.Cast<LogicalRecursiveCTE>());
206931 case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE:
206932 return CreatePlan(op.Cast<LogicalMaterializedCTE>());
206933 case LogicalOperatorType::LOGICAL_CTE_REF:
206934 return CreatePlan(op.Cast<LogicalCTERef>());
206935 case LogicalOperatorType::LOGICAL_EXPORT:
206936 return CreatePlan(op.Cast<LogicalExport>());
206937 case LogicalOperatorType::LOGICAL_SET:
206938 return CreatePlan(op.Cast<LogicalSet>());
206939 case LogicalOperatorType::LOGICAL_RESET:
206940 return CreatePlan(op.Cast<LogicalReset>());
206941 case LogicalOperatorType::LOGICAL_PIVOT:
206942 return CreatePlan(op.Cast<LogicalPivot>());
206943 case LogicalOperatorType::LOGICAL_COPY_DATABASE:
206944 return CreatePlan(op.Cast<LogicalCopyDatabase>());
206945 case LogicalOperatorType::LOGICAL_UPDATE_EXTENSIONS:
206946 return CreatePlan(op.Cast<LogicalSimple>());
206947 case LogicalOperatorType::LOGICAL_EXTENSION_OPERATOR: {
206948 auto &extension_op = op.Cast<LogicalExtensionOperator>();
206949 return extension_op.CreatePlan(context, *this);
206950 }
206951 case LogicalOperatorType::LOGICAL_JOIN:
206952 case LogicalOperatorType::LOGICAL_DEPENDENT_JOIN:
206953 case LogicalOperatorType::LOGICAL_INVALID: {
206954 throw NotImplementedException("Unimplemented logical operator type!");
206955 }
206956 }
206957 throw InternalException("Physical plan generator - no plan generated");
206958}

◆ UseBatchIndex() [1/2]

bool duckdb::PhysicalPlanGenerator::UseBatchIndex ( ClientContext & context,
PhysicalOperator & plan )
static

Whether or not we can (or should) use a batch-index based operator for executing the given sink.

204851 {
204852 auto &scheduler = TaskScheduler::GetScheduler(context);
204853 if (scheduler.NumberOfThreads() == 1) {
204854 // batch index usage only makes sense if we are using multiple threads
204855 return false;
204856 }
204857 if (!plan.AllSourcesSupportBatchIndex()) {
204858 // batch index is not supported
204859 return false;
204860 }
204861 return true;
204862}

◆ PreserveInsertionOrder() [1/2]

bool duckdb::PhysicalPlanGenerator::PreserveInsertionOrder ( ClientContext & context,
PhysicalOperator & plan )
static

Whether or not we should preserve insertion order for executing the given sink.

204829 {
204830 auto preservation_type = OrderPreservationRecursive(plan);
204831 if (preservation_type == OrderPreservationType::FIXED_ORDER) {
204832 // always need to maintain preservation order
204833 return true;
204834 }
204835 if (preservation_type == OrderPreservationType::NO_ORDER) {
204836 // never need to preserve order
204837 return false;
204838 }
204839 // preserve insertion order - check flags
204840 if (!Settings::Get<PreserveInsertionOrderSetting>(context)) {
204841 // preserving insertion order is disabled by config
204842 return false;
204843 }
204844 return true;
204845}
static OrderPreservationType OrderPreservationRecursive(PhysicalOperator &op)
The order preservation type of the given operator decided by recursively looking at its children.
Definition duckdb.cpp:204808
Here is the call graph for this function:

◆ OrderPreservationRecursive()

OrderPreservationType duckdb::PhysicalPlanGenerator::OrderPreservationRecursive ( PhysicalOperator & op)
static

The order preservation type of the given operator decided by recursively looking at its children.

204808 {
204809 if (op.IsSource()) {
204810 return op.SourceOrder();
204811 }
204812
204813 idx_t child_idx = 0;
204814 for (auto &child : op.children) {
204815 // Do not take the materialization phase of physical CTEs into account
204816 if (op.type == PhysicalOperatorType::CTE && child_idx == 0) {
204817 child_idx++;
204818 continue;
204819 }
204820 auto child_preservation = OrderPreservationRecursive(child);
204821 if (child_preservation != OrderPreservationType::INSERTION_ORDER) {
204822 return child_preservation;
204823 }
204824 child_idx++;
204825 }
204826 return OrderPreservationType::INSERTION_ORDER;
204827}
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Make()

template<class T, class... ARGS>
PhysicalOperator & duckdb::PhysicalPlanGenerator::Make ( ARGS &&... args)
inline

Make a physical operator in the physical plan.

38182 {
38183 return physical_plan->Make<T>(std::forward<ARGS>(args)...);
38184 }

◆ ArenaRef()

ArenaAllocator & duckdb::PhysicalPlanGenerator::ArenaRef ( )

Get a reference to the ArenaAllocator of the underlying physical plan. Creates a new (empty) physical plan if none exists yet.

206960 {
206961 if (!physical_plan) {
206962 physical_plan = make_uniq<PhysicalPlan>(Allocator::Get(context));
206963 }
206964 return physical_plan->ArenaRef();
206965}

◆ ResolveDefaultsProjection()

PhysicalOperator & duckdb::PhysicalPlanGenerator::ResolveDefaultsProjection ( LogicalInsert & op,
PhysicalOperator & child )
204868 {
204869 if (op.column_index_map.empty()) {
204870 throw InternalException("No defaults to push");
204871 }
204872 // columns specified by the user, push a projection
204873 vector<LogicalType> types;
204874 vector<unique_ptr<Expression>> select_list;
204875 for (auto &col : op.table.GetColumns().Physical()) {
204876 auto storage_idx = col.StorageOid();
204877 auto mapped_index = op.column_index_map[col.Physical()];
204878 if (mapped_index == DConstants::INVALID_INDEX) {
204879 // push default value
204880 select_list.push_back(std::move(op.bound_defaults[storage_idx]));
204881 } else {
204882 // push reference
204883 select_list.push_back(make_uniq<BoundReferenceExpression>(col.Type(), mapped_index));
204884 }
204885 types.push_back(col.Type());
204886 }
204887 auto &proj = Make<PhysicalProjection>(std::move(types), std::move(select_list), child.estimated_cardinality);
204888 proj.children.push_back(child);
204889 return proj;
204890}
PhysicalOperator & Make(ARGS &&... args)
Make a physical operator in the physical plan.
Definition duckdb.hpp:38182
static constexpr const idx_t INVALID_INDEX
The value used to signify an invalid index entry.
Definition duckdb.hpp:1117

◆ CreatePlan() [2/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalAggregate & op)
protected
202246 {
202247 D_ASSERT(op.children.size() == 1);
202248
202249 reference<PhysicalOperator> plan = CreatePlan(*op.children[0]);
202250 plan = ExtractAggregateExpressions(plan, op.expressions, op.groups, op.grouping_sets);
202251
202252 bool can_use_simple_aggregation = true;
202253 for (auto &expression : op.expressions) {
202254 auto &aggregate = expression->Cast<BoundAggregateExpression>();
202255 if (!aggregate.function.HasStateSimpleUpdateCallback()) {
202256 // unsupported aggregate for simple aggregation: use hash aggregation
202257 can_use_simple_aggregation = false;
202258 break;
202259 }
202260 }
202261
202262 // Check if all groups are valid
202263 if (op.group_stats.empty()) {
202264 op.group_stats.resize(op.groups.size());
202265 }
202266 auto group_validity = TupleDataValidityType::CANNOT_HAVE_NULL_VALUES;
202267 for (const auto &stats : op.group_stats) {
202268 if (stats && !stats->CanHaveNull()) {
202269 continue;
202270 }
202271 group_validity = TupleDataValidityType::CAN_HAVE_NULL_VALUES;
202272 break;
202273 }
202274
202275 if (op.groups.empty() && op.grouping_sets.size() <= 1) {
202276 // no groups, check if we can use a simple aggregation
202277 // special case: aggregate entire columns together
202278 if (can_use_simple_aggregation) {
202279 auto &group_by = Make<PhysicalUngroupedAggregate>(op.types, std::move(op.expressions),
202280 op.estimated_cardinality, op.distinct_validity);
202281 group_by.children.push_back(plan);
202282 return group_by;
202283 }
202284 auto &group_by =
202285 Make<PhysicalHashAggregate>(context, op.types, std::move(op.expressions), op.estimated_cardinality);
202286 group_by.children.push_back(plan);
202287 return group_by;
202288 }
202289
202290 // groups! create a GROUP BY aggregator
202291 // use a partitioned or perfect hash aggregate if possible
202292 vector<column_t> partition_columns;
202293 vector<idx_t> required_bits;
202294 if (can_use_simple_aggregation && CanUsePartitionedAggregate(context, op, plan, partition_columns)) {
202295 auto &group_by =
202296 Make<PhysicalPartitionedAggregate>(context, op.types, std::move(op.expressions), std::move(op.groups),
202297 std::move(partition_columns), op.estimated_cardinality);
202298 group_by.children.push_back(plan);
202299 return group_by;
202300 }
202301
202302 if (CanUsePerfectHashAggregate(context, op, required_bits)) {
202303 auto &group_by = Make<PhysicalPerfectHashAggregate>(context, op.types, std::move(op.expressions),
202304 std::move(op.groups), std::move(op.group_stats),
202305 std::move(required_bits), op.estimated_cardinality);
202306 group_by.children.push_back(plan);
202307 return group_by;
202308 }
202309
202310 auto &group_by = Make<PhysicalHashAggregate>(context, op.types, std::move(op.expressions), std::move(op.groups),
202311 std::move(op.grouping_sets), std::move(op.grouping_functions),
202312 op.estimated_cardinality, group_validity, op.distinct_validity);
202313 group_by.children.push_back(plan);
202314 return group_by;
202315}

◆ CreatePlan() [3/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalAnyJoin & op)
protected
202369 {
202370 // Visit the child nodes.
202371 D_ASSERT(op.children.size() == 2);
202372 D_ASSERT(op.condition);
202373 auto &left = CreatePlan(*op.children[0]);
202374 auto &right = CreatePlan(*op.children[1]);
202375
202376 // Create the blockwise NL join.
202377 return Make<PhysicalBlockwiseNLJoin>(op, left, right, std::move(op.condition), op.join_type,
202378 op.estimated_cardinality);
202379}

◆ CreatePlan() [4/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalColumnDataGet & op)
protected
202821 {
202822 D_ASSERT(op.children.empty());
202823 D_ASSERT(op.collection);
202824 return Make<PhysicalColumnDataScan>(op.types, PhysicalOperatorType::COLUMN_DATA_SCAN, op.estimated_cardinality,
202825 std::move(op.collection));
202826}

◆ CreatePlan() [5/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalComparisonJoin & op)
protected
202930 {
202931 switch (op.type) {
202932 case LogicalOperatorType::LOGICAL_ASOF_JOIN:
202933 return PlanAsOfJoin(op);
202934 case LogicalOperatorType::LOGICAL_COMPARISON_JOIN:
202935 return PlanComparisonJoin(op);
202936 case LogicalOperatorType::LOGICAL_DELIM_JOIN:
202937 return PlanDelimJoin(op);
202938 default:
202939 throw InternalException("Unrecognized operator type for LogicalComparisonJoin");
202940 }
202941}

◆ CreatePlan() [6/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalCopyDatabase & op)
protected
202950 {
202951 return Make<PhysicalCopyDatabase>(op.types, op.estimated_cardinality, std::move(op.info));
202952}

◆ CreatePlan() [7/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalCreate & op)
protected
203094 {
203095 switch (op.type) {
203096 case LogicalOperatorType::LOGICAL_CREATE_SEQUENCE:
203097 return Make<PhysicalCreateSequence>(unique_ptr_cast<CreateInfo, CreateSequenceInfo>(std::move(op.info)),
203098 op.estimated_cardinality);
203099 case LogicalOperatorType::LOGICAL_CREATE_VIEW:
203100 return Make<PhysicalCreateView>(unique_ptr_cast<CreateInfo, CreateViewInfo>(std::move(op.info)),
203101 op.estimated_cardinality);
203102 case LogicalOperatorType::LOGICAL_CREATE_SCHEMA:
203103 return Make<PhysicalCreateSchema>(unique_ptr_cast<CreateInfo, CreateSchemaInfo>(std::move(op.info)),
203104 op.estimated_cardinality);
203105 case LogicalOperatorType::LOGICAL_CREATE_MACRO:
203106 return Make<PhysicalCreateFunction>(unique_ptr_cast<CreateInfo, CreateMacroInfo>(std::move(op.info)),
203107 op.estimated_cardinality);
203108 case LogicalOperatorType::LOGICAL_CREATE_TYPE: {
203109 auto &create = Make<PhysicalCreateType>(unique_ptr_cast<CreateInfo, CreateTypeInfo>(std::move(op.info)),
203110 op.estimated_cardinality);
203111 if (!op.children.empty()) {
203112 D_ASSERT(op.children.size() == 1);
203113 auto &plan = CreatePlan(*op.children[0]);
203114 create.children.push_back(plan);
203115 }
203116 return create;
203117 }
203118 default:
203119 throw NotImplementedException("Unimplemented type for logical simple create");
203120 }
203121}
static cv::Ptr< QuasiDenseStereo > create(cv::Size monoImgSize, cv::String paramFilepath=cv::String())

◆ CreatePlan() [8/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalCreateTable & op)
protected
203426 {
203427 const auto &create_info = op.info->base->Cast<CreateTableInfo>();
203428 auto &catalog = op.info->schema.catalog;
203429 auto existing_entry = catalog.GetEntry(context, CatalogType::TABLE_ENTRY, create_info.schema, create_info.table,
203430 OnEntryNotFound::RETURN_NULL);
203431 bool replace = op.info->Base().on_conflict == OnCreateConflict::REPLACE_ON_CONFLICT;
203432 if ((!existing_entry || replace) && !op.children.empty()) {
203433 auto &plan = CreatePlan(*op.children[0]);
203434 return op.schema.catalog.PlanCreateTableAs(context, *this, op, plan);
203435 }
203436 return Make<PhysicalCreateTable>(op, op.schema, std::move(op.info), op.estimated_cardinality);
203437}

◆ CreatePlan() [9/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalCreateIndex & op)
protected
203219 {
203220 // Early-out, if the index already exists.
203221 auto &schema = op.table.schema;
203222 auto entry = schema.GetEntry(schema.GetCatalogTransaction(context), CatalogType::INDEX_ENTRY, op.info->index_name);
203223 if (entry) {
203224 if (op.info->on_conflict != OnCreateConflict::IGNORE_ON_CONFLICT) {
203225 throw CatalogException("Index with name \"%s\" already exists!", op.info->index_name);
203226 }
203227 return Make<PhysicalDummyScan>(op.types, op.estimated_cardinality);
203228 }
203229
203230 if (!op.table.IsDuckTable()) {
203231 throw BinderException("Indexes can only be created on DuckDB tables.");
203232 }
203233
203234 // Ensure that all expressions contain valid scalar functions.
203235 // E.g., get_current_timestamp(), random(), and sequence values cannot be index keys.
203236 for (idx_t i = 0; i < op.unbound_expressions.size(); i++) {
203237 auto &expr = op.unbound_expressions[i];
203238 if (!expr->IsConsistent()) {
203239 throw BinderException("Index keys cannot contain expressions with side effects.");
203240 }
203241 }
203242
203243 // If we get here and the index type is not valid index type, we throw an exception.
203244 const auto index_type = context.db->config.GetIndexTypes().FindByName(op.info->index_type);
203245 if (!index_type) {
203246 throw BinderException("Unknown index type: " + op.info->index_type);
203247 }
203248
203249 // Add a dependency for the entire table on which we create the index.
203250 dependencies.AddDependency(op.table);
203251 D_ASSERT(op.info->scan_types.size() - 1 <= op.info->names.size());
203252 D_ASSERT(op.info->scan_types.size() - 1 <= op.info->column_ids.size());
203253
203254 D_ASSERT(op.children.size() == 1);
203255 auto &scan = CreatePlan(*op.children[0]);
203256
203257 // Index has a plan replacement function
203258 if (index_type->create_plan) {
203259 PlanIndexInput input(context, op, *this, scan, index_type->index_info);
203260 return index_type->create_plan(input);
203261 }
203262
203263 // Fall back to generic index creation plan
203264 // SCAN -> PROJECTION -> [FILTER] -> [SORT] -> CREATE INDEX
203265
203266 // "Bind" the index and determine if we need a sort.
203267 auto &duck_table = op.table.Cast<DuckTableEntry>();
203268 IndexBuildBindInput bind_input {context, duck_table, *op.info, op.unbound_expressions};
203269 auto bind_data = index_type->build_bind(bind_input);
203270
203271 auto need_sort = false;
203272 if (index_type->build_sort) {
203273 IndexBuildSortInput sort_input {bind_data.get()};
203274 need_sort = index_type->build_sort(sort_input);
203275 }
203276
203277 // Determine if this is a fresh index creation or an ALTER TABLE ADD INDEX
203278 auto need_filter = op.alter_table_info == nullptr;
203279
203280 // Construct the plan
203281 auto plan = &scan;
203282 plan = &AddProjection(*this, op, *plan);
203283
203284 if (need_filter) {
203285 plan = &AddFilter(*this, op, *plan);
203286 }
203287 if (need_sort) {
203288 plan = &AddSort(*this, op, *plan);
203289 }
203290 plan = &AddCreateIndex(*this, op, *plan, *index_type, std::move(bind_data));
203291
203292 return *plan;
203293}
float index_type

◆ CreatePlan() [10/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalCreateSecret & op)
protected
203345 {
203346 return Make<PhysicalCreateSecret>(op.secret_input, op.estimated_cardinality);
203347}

◆ CreatePlan() [11/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalCrossProduct & op)
protected
203511 {
203512 D_ASSERT(op.children.size() == 2);
203513 auto &left = CreatePlan(*op.children[0]);
203514 auto &right = CreatePlan(*op.children[1]);
203515 return Make<PhysicalCrossProduct>(op.types, left, right, op.estimated_cardinality);
203516}

◆ CreatePlan() [12/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalDelete & op)
protected
203728 {
203729 D_ASSERT(op.children.size() == 1);
203730
203731 dependencies.AddDependency(op.table);
203732 return op.table.catalog.PlanDelete(context, *this, op);
203733}

◆ CreatePlan() [13/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalDelimGet & op)
protected
203790 {
203791 // Create a PhysicalChunkScan without an owned_collection.
203792 // We'll add the collection later.
203793 D_ASSERT(op.children.empty());
203794 return Make<PhysicalColumnDataScan>(op.types, PhysicalOperatorType::DELIM_SCAN, op.estimated_cardinality, nullptr);
203795}

◆ CreatePlan() [14/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalDistinct & op)
protected
203948 {
203949 D_ASSERT(op.children.size() == 1);
203950 reference<PhysicalOperator> child = CreatePlan(*op.children[0]);
203951 auto &distinct_targets = op.distinct_targets;
203952 D_ASSERT(!distinct_targets.empty());
203953
203954 auto &types = child.get().GetTypes();
203955 vector<unique_ptr<Expression>> groups, aggregates, projections;
203956 idx_t group_count = distinct_targets.size();
203957 unordered_map<idx_t, idx_t> group_by_references;
203958 vector<LogicalType> aggregate_types;
203959 // creates one group per distinct_target
203960 for (idx_t i = 0; i < distinct_targets.size(); i++) {
203961 auto &target = distinct_targets[i];
203962 if (target->GetExpressionType() == ExpressionType::BOUND_REF) {
203963 auto &bound_ref = target->Cast<BoundReferenceExpression>();
203964 group_by_references[bound_ref.index] = i;
203965 }
203966 aggregate_types.push_back(target->return_type);
203967 groups.push_back(std::move(target));
203968 }
203969 bool requires_projection = false;
203970 if (types.size() != group_count) {
203971 requires_projection = true;
203972 }
203973 // we need to create one aggregate per column in the select_list
203974 for (idx_t i = 0; i < types.size(); ++i) {
203975 auto logical_type = types[i];
203976 // check if we can directly refer to a group, or if we need to push an aggregate with FIRST
203977 auto entry = group_by_references.find(i);
203978 if (entry != group_by_references.end()) {
203979 auto group_index = entry->second;
203980 // entry is found: can directly refer to a group
203981 projections.push_back(make_uniq<BoundReferenceExpression>(logical_type, group_index));
203982 if (group_index != i) {
203983 // we require a projection only if this group element is out of order
203984 requires_projection = true;
203985 }
203986 } else {
203987 if (op.distinct_type == DistinctType::DISTINCT && op.order_by) {
203988 throw InternalException("Entry that is not a group, but not a DISTINCT ON aggregate");
203989 }
203990 // entry is not one of the groups: need to push a FIRST aggregate
203991 auto bound = make_uniq<BoundReferenceExpression>(logical_type, i);
203992 vector<unique_ptr<Expression>> first_children;
203993 first_children.push_back(std::move(bound));
203994
203995 FunctionBinder function_binder(context);
203996 auto first_aggregate =
203997 function_binder.BindAggregateFunction(FirstFunctionGetter::GetFunction(logical_type),
203998 std::move(first_children), nullptr, AggregateType::NON_DISTINCT);
203999 first_aggregate->order_bys = op.order_by ? op.order_by->Copy() : nullptr;
204000
204001 if (ClientConfig::GetConfig(context).enable_optimizer) {
204002 bool changes_made = false;
204003 auto new_expr =
204004 OrderedAggregateOptimizer::Apply(context, *first_aggregate, groups, nullptr, changes_made);
204005 if (new_expr) {
204006 D_ASSERT(new_expr->return_type == first_aggregate->return_type);
204007 D_ASSERT(new_expr->GetExpressionType() == ExpressionType::BOUND_AGGREGATE);
204008 first_aggregate = unique_ptr_cast<Expression, BoundAggregateExpression>(std::move(new_expr));
204009 }
204010 }
204011 // add the projection
204012 projections.push_back(make_uniq<BoundReferenceExpression>(logical_type, group_count + aggregates.size()));
204013 // push it to the list of aggregates
204014 aggregate_types.push_back(logical_type);
204015 aggregates.push_back(std::move(first_aggregate));
204016 requires_projection = true;
204017 }
204018 }
204019
204020 child = ExtractAggregateExpressions(child, aggregates, groups, nullptr);
204021
204022 // we add a physical hash aggregation in the plan to select the distinct groups
204023 auto &group_by = Make<PhysicalHashAggregate>(context, aggregate_types, std::move(aggregates), std::move(groups),
204024 child.get().estimated_cardinality);
204025 group_by.children.push_back(child);
204026 if (!requires_projection) {
204027 return group_by;
204028 }
204029
204030 // we add a physical projection on top of the aggregation to project all members in the select list
204031 auto &proj = Make<PhysicalProjection>(types, std::move(projections), group_by.estimated_cardinality);
204032 proj.children.push_back(group_by);
204033 return proj;
204034}

◆ CreatePlan() [15/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalDummyScan & expr)
protected
204090 {
204091 D_ASSERT(op.children.empty());
204092 return Make<PhysicalDummyScan>(op.types, op.estimated_cardinality);
204093}

◆ CreatePlan() [16/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalEmptyResult & op)
protected
204149 {
204150 D_ASSERT(op.children.size() == 0);
204151 return Make<PhysicalEmptyResult>(op.types, op.estimated_cardinality);
204152}

◆ CreatePlan() [17/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalExpressionGet & op)
protected
204459 {
204460 D_ASSERT(op.children.size() == 1);
204461 auto &plan = CreatePlan(*op.children[0]);
204462
204463 auto &expr_scan = Make<PhysicalExpressionScan>(op.types, std::move(op.expressions), op.estimated_cardinality);
204464 expr_scan.children.push_back(plan);
204465
204466 auto &cast_expr_scan = expr_scan.Cast<PhysicalExpressionScan>();
204467 if (!cast_expr_scan.IsFoldable()) {
204468 return expr_scan;
204469 }
204470
204471 auto &allocator = Allocator::Get(context);
204472 // simple expression scan (i.e. no subqueries to evaluate and no prepared statement parameters)
204473 // we can evaluate all the expressions right now and turn this into a chunk collection scan
204474 auto &chunk_scan = Make<PhysicalColumnDataScan>(op.types, PhysicalOperatorType::COLUMN_DATA_SCAN,
204475 cast_expr_scan.expressions.size(),
204476 make_uniq<ColumnDataCollection>(context, op.types));
204477 auto &cast_chunk_scan = chunk_scan.Cast<PhysicalColumnDataScan>();
204478
204479 DataChunk chunk;
204480 chunk.Initialize(allocator, op.types);
204481
204482 ColumnDataAppendState append_state;
204483 cast_chunk_scan.collection->InitializeAppend(append_state);
204484 for (idx_t expression_idx = 0; expression_idx < cast_expr_scan.expressions.size(); expression_idx++) {
204485 chunk.Reset();
204486 cast_expr_scan.EvaluateExpression(context, expression_idx, nullptr, chunk);
204487 cast_chunk_scan.collection->Append(append_state, chunk);
204488 }
204489 return chunk_scan;
204490}

◆ CreatePlan() [18/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalExport & op)
protected
204386 {
204387 auto &export_op = Make<PhysicalExport>(op.types, op.function, std::move(op.copy_info), op.estimated_cardinality,
204388 std::move(op.exported_tables));
204389 // Plan the underlying copy statements, if any.
204390 if (!op.children.empty()) {
204391 auto &plan = CreatePlan(*op.children[0]);
204392 export_op.children.push_back(plan);
204393 }
204394 return export_op;
204395}

◆ CreatePlan() [19/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalFilter & op)
protected
204552 {
204553 D_ASSERT(op.children.size() == 1);
204554 reference<PhysicalOperator> plan = CreatePlan(*op.children[0]);
204555 if (!op.expressions.empty()) {
204556 // create a filter if there is anything to filter
204557 auto &filter = Make<PhysicalFilter>(plan.get().GetTypes(), std::move(op.expressions), op.estimated_cardinality);
204558 filter.children.push_back(plan);
204559 plan = filter;
204560 }
204561 if (op.HasProjectionMap()) {
204562 // there is a projection map, generate a physical projection
204563 vector<unique_ptr<Expression>> select_list;
204564 for (idx_t i = 0; i < op.projection_map.size(); i++) {
204565 select_list.push_back(make_uniq<BoundReferenceExpression>(op.types[i], op.projection_map[i]));
204566 }
204567 auto &proj = Make<PhysicalProjection>(op.types, std::move(select_list), op.estimated_cardinality);
204568 proj.children.push_back(plan);
204569 plan = proj;
204570 }
204571 return plan;
204572}
void filter(InputArray image, InputArray kernel, OutputArray output)

◆ CreatePlan() [20/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalGet & op)
protected
204611 {
204612 auto column_ids = op.GetColumnIds();
204613 if (!op.children.empty()) {
204614 reference<PhysicalOperator> child = ResolveAndPlan(std::move(op.children[0]));
204615 auto &child_types = child.get().types;
204616
204617 // this is for table producing functions that consume subquery results
204618 // push a projection node with casts if required
204619 if (child_types.size() < op.input_table_types.size()) {
204620 throw InternalException(
204621 "Mismatch between input table types and child node types - expected %llu but got %llu",
204622 op.input_table_types.size(), child_types.size());
204623 }
204624
204625 vector<LogicalType> return_types;
204626 vector<unique_ptr<Expression>> expressions;
204627 bool any_cast_required = false;
204628 for (idx_t proj_idx = 0; proj_idx < child_types.size(); proj_idx++) {
204629 auto ref = make_uniq<BoundReferenceExpression>(child_types[proj_idx], proj_idx);
204630 auto &target_type =
204631 proj_idx < op.input_table_types.size() ? op.input_table_types[proj_idx] : child_types[proj_idx];
204632 if (child_types[proj_idx] != target_type) {
204633 // cast is required - push a cast
204634 any_cast_required = true;
204635 auto cast = BoundCastExpression::AddCastToType(context, std::move(ref), target_type);
204636 expressions.push_back(std::move(cast));
204637 } else {
204638 expressions.push_back(std::move(ref));
204639 }
204640 return_types.push_back(target_type);
204641 }
204642
204643 if (any_cast_required) {
204644 auto &proj = Make<PhysicalProjection>(std::move(return_types), std::move(expressions),
204645 child.get().estimated_cardinality);
204646 proj.children.push_back(child);
204647 child = proj;
204648 }
204649
204650 auto &table_in_out =
204651 Make<PhysicalTableInOutFunction>(op.types, op.function, std::move(op.bind_data), column_ids,
204652 op.estimated_cardinality, std::move(op.projected_input));
204653 table_in_out.children.push_back(child);
204654 auto &cast_table_in_out = table_in_out.Cast<PhysicalTableInOutFunction>();
204655 cast_table_in_out.ordinality_idx = op.ordinality_idx;
204656 return table_in_out;
204657 }
204658
204659 if (!op.projected_input.empty()) {
204660 throw InternalException("LogicalGet::project_input can only be set for table-in-out functions");
204661 }
204662
204663 unique_ptr<TableFilterSet> table_filters;
204664 if (!op.table_filters.filters.empty()) {
204665 table_filters = CreateTableFilterSet(op.table_filters, column_ids);
204666 }
204667
204668 if (op.function.dependency) {
204669 op.function.dependency(dependencies, op.bind_data.get());
204670 }
204671
204672 optional_ptr<PhysicalOperator> filter;
204673 auto &projection_ids = op.projection_ids;
204674
204675 if (table_filters && op.function.supports_pushdown_type) {
204676 vector<unique_ptr<Expression>> select_list;
204677 unique_ptr<Expression> unsupported_filter;
204678 unordered_set<idx_t> to_remove;
204679
204680 virtual_column_map_t virtual_columns;
204681 if (op.function.get_virtual_columns) {
204682 virtual_columns = op.function.get_virtual_columns(context, op.bind_data.get());
204683 }
204684 for (auto &entry : table_filters->filters) {
204685 auto column_id = column_ids[entry.first].GetPrimaryIndex();
204686 if (!op.function.supports_pushdown_type(*op.bind_data, column_id)) {
204687 LogicalType column_type;
204688 if (IsVirtualColumn(column_id)) {
204689 auto &column = virtual_columns.at(column_id);
204690 column_type = column.type;
204691 } else {
204692 column_type = op.returned_types[column_id];
204693 }
204694 idx_t column_id_filter = entry.first;
204695 bool found_projection = false;
204696 for (idx_t i = 0; i < projection_ids.size(); i++) {
204697 if (column_ids[projection_ids[i]] == column_ids[entry.first]) {
204698 column_id_filter = i;
204699 found_projection = true;
204700 break;
204701 }
204702 }
204703 if (!found_projection) {
204704 projection_ids.push_back(entry.first);
204705 column_id_filter = projection_ids.size() - 1;
204706 }
204707 auto column = make_uniq<BoundReferenceExpression>(column_type, column_id_filter);
204708 select_list.push_back(entry.second->ToExpression(*column));
204709 to_remove.insert(entry.first);
204710 }
204711 }
204712 for (auto &col : to_remove) {
204713 table_filters->filters.erase(col);
204714 }
204715
204716 if (!select_list.empty()) {
204717 vector<LogicalType> filter_types;
204718 for (auto &c : projection_ids) {
204719 auto column_id = column_ids[c].GetPrimaryIndex();
204720 if (IsVirtualColumn(column_id)) {
204721 auto &column = virtual_columns.at(column_id);
204722 filter_types.push_back(column.type);
204723 } else {
204724 filter_types.push_back(op.returned_types[column_id]);
204725 }
204726 }
204727 filter = Make<PhysicalFilter>(filter_types, std::move(select_list), op.estimated_cardinality);
204728 }
204729 }
204730 op.ResolveOperatorTypes();
204731 // create the table scan node
204732 if (!op.function.projection_pushdown) {
204733 // function does not support projection pushdown
204734 auto &table_scan = Make<PhysicalTableScan>(
204735 op.returned_types, op.function, std::move(op.bind_data), op.returned_types, column_ids, vector<column_t>(),
204736 op.names, std::move(table_filters), op.estimated_cardinality, std::move(op.extra_info),
204737 std::move(op.parameters), std::move(op.virtual_columns));
204738 // first check if an additional projection is necessary
204739 if (column_ids.size() == op.returned_types.size()) {
204740 bool projection_necessary = false;
204741 for (idx_t i = 0; i < column_ids.size(); i++) {
204742 if (column_ids[i].GetPrimaryIndex() != i) {
204743 projection_necessary = true;
204744 break;
204745 }
204746 }
204747 if (!projection_necessary) {
204748 // a projection is not necessary if all columns have been requested in-order
204749 // in that case we just return the node
204750 if (filter) {
204751 filter->children.push_back(table_scan);
204752 return *filter;
204753 }
204754 return table_scan;
204755 }
204756 }
204757 // push a projection on top that does the projection
204758 vector<LogicalType> types;
204759 vector<unique_ptr<Expression>> expressions;
204760 for (auto &column_id : column_ids) {
204761 if (column_id.IsVirtualColumn()) {
204762 throw NotImplementedException("Virtual columns require projection pushdown");
204763 } else {
204764 auto col_id = column_id.GetPrimaryIndex();
204765 auto type = op.returned_types[col_id];
204766 types.push_back(type);
204767 expressions.push_back(make_uniq<BoundReferenceExpression>(type, col_id));
204768 }
204769 }
204770 auto &proj = Make<PhysicalProjection>(std::move(types), std::move(expressions), op.estimated_cardinality);
204771 if (filter) {
204772 filter->children.push_back(table_scan);
204773 proj.children.push_back(*filter);
204774 return proj;
204775 }
204776 proj.children.push_back(table_scan);
204777 return proj;
204778 }
204779
204780 auto &table_scan =
204781 Make<PhysicalTableScan>(op.types, op.function, std::move(op.bind_data), op.returned_types, column_ids,
204782 op.projection_ids, op.names, std::move(table_filters), op.estimated_cardinality,
204783 std::move(op.extra_info), std::move(op.parameters), std::move(op.virtual_columns));
204784 auto &cast_table_scan = table_scan.Cast<PhysicalTableScan>();
204785 cast_table_scan.dynamic_filters = op.dynamic_filters;
204786 if (filter) {
204787 filter->children.push_back(table_scan);
204788 return *filter;
204789 }
204790 return table_scan;
204791}
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
Widget2D cast() const

◆ CreatePlan() [21/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalLimit & op)
protected
205029 {
205030 D_ASSERT(op.children.size() == 1);
205031 auto &plan = CreatePlan(*op.children[0]);
205032
205033 switch (op.limit_val.Type()) {
205034 case LimitNodeType::EXPRESSION_PERCENTAGE:
205035 case LimitNodeType::CONSTANT_PERCENTAGE: {
205036 auto &limit = Make<PhysicalLimitPercent>(op.types, std::move(op.limit_val), std::move(op.offset_val),
205037 op.estimated_cardinality);
205038 limit.children.push_back(plan);
205039 return limit;
205040 }
205041 default: {
205042 if (!PreserveInsertionOrder(plan)) {
205043 // use parallel streaming limit if insertion order is not important
205044 auto &limit = Make<PhysicalStreamingLimit>(op.types, std::move(op.limit_val), std::move(op.offset_val),
205045 op.estimated_cardinality, true);
205046 limit.children.push_back(plan);
205047 return limit;
205048 }
205049
205050 // maintaining insertion order is important
205051 if (UseBatchIndex(plan) && UseBatchLimit(plan, op.limit_val, op.offset_val)) {
205052 // source supports batch index: use parallel batch limit
205053 auto &limit = Make<PhysicalLimit>(op.types, std::move(op.limit_val), std::move(op.offset_val),
205054 op.estimated_cardinality);
205055 limit.children.push_back(plan);
205056 return limit;
205057 }
205058
205059 // source does not support batch index: use a non-parallel streaming limit
205060 auto &limit = Make<PhysicalStreamingLimit>(op.types, std::move(op.limit_val), std::move(op.offset_val),
205061 op.estimated_cardinality, false);
205062 limit.children.push_back(plan);
205063 return limit;
205064 }
205065 }
205066}
static bool PreserveInsertionOrder(ClientContext &context, PhysicalOperator &plan)
Whether or not we should preserve insertion order for executing the given sink.
Definition duckdb.cpp:204829
static bool UseBatchIndex(ClientContext &context, PhysicalOperator &plan)
Whether or not we can (or should) use a batch-index based operator for executing the given sink.
Definition duckdb.cpp:204851

◆ CreatePlan() [22/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalMergeInto & op)
protected
205268 {
205269 auto &plan = CreatePlan(*op.children[0]);
205270 D_ASSERT(op.children.size() == 1);
205271 dependencies.AddDependency(op.table);
205272 return op.table.catalog.PlanMergeInto(context, *this, op, plan);
205273}

◆ CreatePlan() [23/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalOrder & op)
protected
205326 {
205327 D_ASSERT(op.children.size() == 1);
205328
205329 auto &plan = CreatePlan(*op.children[0]);
205330 if (op.orders.empty()) {
205331 return plan;
205332 }
205333
205334 vector<idx_t> projection_map;
205335 if (op.HasProjectionMap()) {
205336 projection_map = std::move(op.projection_map);
205337 } else {
205338 for (idx_t i = 0; i < plan.types.size(); i++) {
205339 projection_map.push_back(i);
205340 }
205341 }
205342 auto &order =
205343 Make<PhysicalOrder>(op.types, std::move(op.orders), std::move(projection_map), op.estimated_cardinality);
205344 order.children.push_back(plan);
205345 return order;
205346}

◆ CreatePlan() [24/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalTopN & op)
protected
206312 {
206313 D_ASSERT(op.children.size() == 1);
206314 auto &plan = CreatePlan(*op.children[0]);
206315 auto &top_n =
206316 Make<PhysicalTopN>(op.types, std::move(op.orders), NumericCast<idx_t>(op.limit), NumericCast<idx_t>(op.offset),
206317 std::move(op.dynamic_filter), op.estimated_cardinality);
206318 top_n.children.push_back(plan);
206319 return top_n;
206320}

◆ CreatePlan() [25/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalPositionalJoin & op)
protected
205444 {
205445 D_ASSERT(op.children.size() == 2);
205446
205447 auto &left = CreatePlan(*op.children[0]);
205448 auto &right = CreatePlan(*op.children[1]);
205449 switch (left.type) {
205450 case PhysicalOperatorType::TABLE_SCAN:
205451 case PhysicalOperatorType::POSITIONAL_SCAN:
205452 switch (right.type) {
205453 case PhysicalOperatorType::TABLE_SCAN:
205454 case PhysicalOperatorType::POSITIONAL_SCAN:
205455 return Make<PhysicalPositionalScan>(op.types, left, right);
205456 default:
205457 break;
205458 }
205459 break;
205460 default:
205461 break;
205462 }
205463 return Make<PhysicalPositionalJoin>(op.types, left, right, op.estimated_cardinality);
205464}

◆ CreatePlan() [26/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalProjection & op)
protected
205600 {
205601 D_ASSERT(op.children.size() == 1);
205602 auto &plan = CreatePlan(*op.children[0]);
205603
205604#ifdef DEBUG
205605 for (auto &expr : op.expressions) {
205606 D_ASSERT(!expr->IsWindow());
205607 D_ASSERT(!expr->IsAggregate());
205608 }
205609#endif
205610 if (plan.GetTypes().size() == op.types.size()) {
205611 // check if this projection can be omitted entirely
205612 // this happens if a projection simply emits the columns in the same order
205613 // e.g. PROJECTION(#0, #1, #2, #3, ...)
205614 bool omit_projection = true;
205615 for (idx_t i = 0; i < op.types.size(); i++) {
205616 if (op.expressions[i]->GetExpressionType() == ExpressionType::BOUND_REF) {
205617 auto &bound_ref = op.expressions[i]->Cast<BoundReferenceExpression>();
205618 if (bound_ref.index == i) {
205619 continue;
205620 }
205621 }
205622 omit_projection = false;
205623 break;
205624 }
205625 if (omit_projection) {
205626 // the projection only directly projects the child' columns: omit it entirely
205627 return plan;
205628 }
205629 }
205630
205631 auto &proj = Make<PhysicalProjection>(op.types, std::move(op.expressions), op.estimated_cardinality);
205632 proj.children.push_back(plan);
205633 return proj;
205634}

◆ CreatePlan() [27/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalInsert & op)
protected
204933 {
204934 optional_ptr<PhysicalOperator> plan;
204935 if (!op.children.empty()) {
204936 D_ASSERT(op.children.size() == 1);
204937 plan = CreatePlan(*op.children[0]);
204938 }
204939 dependencies.AddDependency(op.table);
204940 return op.table.catalog.PlanInsert(context, *this, op, plan);
204941}

◆ CreatePlan() [28/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalCopyToFile & op)
protected
202962 {
202963 auto &plan = CreatePlan(*op.children[0]);
202964 bool preserve_insertion_order = PhysicalPlanGenerator::PreserveInsertionOrder(context, plan);
202965 bool supports_batch_index = PhysicalPlanGenerator::UseBatchIndex(context, plan);
202966
202967 if (op.preserve_order == PreserveOrderType::PRESERVE_ORDER) {
202968 preserve_insertion_order = true;
202969 } else if (op.preserve_order == PreserveOrderType::DONT_PRESERVE_ORDER) {
202970 preserve_insertion_order = false;
202971 }
202972
202973 auto &fs = FileSystem::GetFileSystem(context);
202974 op.file_path = fs.ExpandPath(op.file_path);
202975
202976 if (op.use_tmp_file) {
202977 auto path = StringUtil::GetFilePath(op.file_path);
202978 auto base = StringUtil::GetFileName(op.file_path);
202979 op.file_path = fs.JoinPath(path, "tmp_" + base);
202980 }
202981 if (op.per_thread_output || op.file_size_bytes.IsValid() || op.rotate || op.partition_output ||
202982 !op.partition_columns.empty()) {
202983 if (op.preserve_order == PreserveOrderType::PRESERVE_ORDER) {
202984 throw InvalidInputException("PRESERVE_ORDER is not supported with these parameters");
202985 }
202986 // hive-partitioning/per-thread output does not care about insertion order, and does not support batch indexes
202987 preserve_insertion_order = false;
202988 supports_batch_index = false;
202989 }
202990 auto mode = CopyFunctionExecutionMode::REGULAR_COPY_TO_FILE;
202991 if (op.function.execution_mode) {
202992 mode = op.function.execution_mode(preserve_insertion_order, supports_batch_index);
202993 }
202994 if (mode == CopyFunctionExecutionMode::BATCH_COPY_TO_FILE) {
202995 if (!supports_batch_index) {
202996 throw InternalException("BATCH_COPY_TO_FILE can only be used if batch indexes are supported");
202997 }
202998 // batched copy to file
202999 auto &copy =
203000 Make<PhysicalBatchCopyToFile>(op.types, op.function, std::move(op.bind_data), op.estimated_cardinality);
203001
203002 auto &cast_copy = copy.Cast<PhysicalBatchCopyToFile>();
203003 cast_copy.file_path = op.file_path;
203004 cast_copy.use_tmp_file = op.use_tmp_file;
203005 cast_copy.children.push_back(plan);
203006 cast_copy.return_type = op.return_type;
203007 cast_copy.write_empty_file = op.write_empty_file;
203008 return copy;
203009 }
203010
203011 // COPY from select statement to file
203012 auto &copy = Make<PhysicalCopyToFile>(op.types, op.function, std::move(op.bind_data), op.estimated_cardinality);
203013
203014 auto &cast_copy = copy.Cast<PhysicalCopyToFile>();
203015 cast_copy.file_path = op.file_path;
203016 cast_copy.use_tmp_file = op.use_tmp_file;
203017 cast_copy.overwrite_mode = op.overwrite_mode;
203018 cast_copy.filename_pattern = op.filename_pattern;
203019 cast_copy.file_extension = op.file_extension;
203020 cast_copy.per_thread_output = op.per_thread_output;
203021
203022 if (op.file_size_bytes.IsValid()) {
203023 cast_copy.file_size_bytes = op.file_size_bytes;
203024 }
203025
203026 cast_copy.rotate = op.rotate;
203027 cast_copy.return_type = op.return_type;
203028 cast_copy.partition_output = op.partition_output;
203029 cast_copy.partition_columns = op.partition_columns;
203030 cast_copy.write_partition_columns = op.write_partition_columns;
203031 cast_copy.names = op.names;
203032 cast_copy.expected_types = op.expected_types;
203033 cast_copy.parallel = mode == CopyFunctionExecutionMode::PARALLEL_COPY_TO_FILE;
203034 cast_copy.write_empty_file = op.write_empty_file;
203035 cast_copy.hive_file_pattern = op.hive_file_pattern;
203036
203037 cast_copy.children.push_back(plan);
203038 return copy;
203039}

◆ CreatePlan() [29/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalExplain & op)
protected
204285 {
204286 D_ASSERT(op.children.size() == 1);
204287 auto logical_plan_opt = op.children[0]->ToString(op.explain_format);
204288 auto &plan = CreatePlan(*op.children[0]);
204289 if (op.explain_type == ExplainType::EXPLAIN_ANALYZE) {
204290 auto &explain = Make<PhysicalExplainAnalyze>(op.types, op.explain_format);
204291 explain.children.push_back(plan);
204292 return explain;
204293 }
204294
204295 // Format the plan and set the output of the EXPLAIN.
204296 op.physical_plan = plan.ToString(op.explain_format);
204297 vector<string> keys, values;
204298 switch (Settings::Get<ExplainOutputSetting>(context)) {
204299 case ExplainOutputType::OPTIMIZED_ONLY:
204300 keys = {"logical_opt"};
204301 values = {logical_plan_opt};
204302 break;
204303 case ExplainOutputType::PHYSICAL_ONLY:
204304 keys = {"physical_plan"};
204305 values = {op.physical_plan};
204306 break;
204307 default:
204308 keys = {"logical_plan", "logical_opt", "physical_plan"};
204309 values = {op.logical_plan_unopt, logical_plan_opt, op.physical_plan};
204310 }
204311
204312 // Create a ColumnDataCollection from the output.
204313 auto &allocator = Allocator::Get(context);
204314 vector<LogicalType> plan_types {LogicalType::VARCHAR, LogicalType::VARCHAR};
204315 auto collection =
204316 make_uniq<ColumnDataCollection>(context, plan_types, ColumnDataAllocatorType::IN_MEMORY_ALLOCATOR);
204317
204318 DataChunk chunk;
204319 chunk.Initialize(allocator, op.types);
204320 for (idx_t i = 0; i < keys.size(); i++) {
204321 chunk.SetValue(0, chunk.size(), Value(keys[i]));
204322 chunk.SetValue(1, chunk.size(), Value(values[i]));
204323 chunk.SetCardinality(chunk.size() + 1);
204324 if (chunk.size() == STANDARD_VECTOR_SIZE) {
204325 collection->Append(chunk);
204326 chunk.Reset();
204327 }
204328 }
204329 collection->Append(chunk);
204330
204331 // Output the result via a chunk scan.
204332 return Make<PhysicalColumnDataScan>(op.types, PhysicalOperatorType::COLUMN_DATA_SCAN, op.estimated_cardinality,
204333 std::move(collection));
204334}
DUCKDB_API void Reset()
Definition duckdb.cpp:116840
DUCKDB_API void Initialize(ClientContext &context, const vector< LogicalType > &types, idx_t capacity=STANDARD_VECTOR_SIZE)
Definition duckdb.cpp:116791
@ IN_MEMORY_ALLOCATOR
Definition duckdb.hpp:18802

◆ CreatePlan() [30/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalSetOperation & op)
protected
206083 {
206084 ArenaLinkedList<reference<PhysicalOperator>> children(physical_plan->ArenaRef());
206085 for (auto &child : op.children) {
206086 children.push_back(CreatePlan(*child));
206087 }
206088 for (idx_t i = 1; i < children.size(); i++) {
206089 if (children[i].get().GetTypes() != children[0].get().GetTypes()) {
206090 throw InvalidInputException("Type mismatch for SET OPERATION");
206091 }
206092 }
206093
206094 optional_ptr<PhysicalOperator> result;
206095 switch (op.type) {
206096 case LogicalOperatorType::LOGICAL_UNION:
206097 // UNION
206098 result = Make<PhysicalUnion>(op.types, std::move(children), op.estimated_cardinality, op.allow_out_of_order);
206099 break;
206100 case LogicalOperatorType::LOGICAL_EXCEPT:
206101 case LogicalOperatorType::LOGICAL_INTERSECT: {
206102 if (children.size() != 2) {
206103 throw InternalException("EXCEPT / INTERSECT must have exactly two children");
206104 }
206105 auto &left = children[0];
206106 auto &right = children[1];
206107 auto &types = left.get().GetTypes();
206108 vector<JoinCondition> conditions;
206109 // create equality condition for all columns
206110 for (idx_t i = 0; i < types.size(); i++) {
206111 conditions.push_back(CreateNotDistinctComparison(context, types[i], i));
206112 }
206113 // For EXCEPT ALL / INTERSECT ALL we push a window operator with a ROW_NUMBER into the scans and join to get bag
206114 // semantics.
206115 if (op.setop_all) {
206116 vector<LogicalType> window_types = types;
206117 window_types.push_back(LogicalType::BIGINT);
206118
206119 auto select_list = CreatePartitionedRowNumExpression(context, types);
206120 auto &left_window =
206121 Make<PhysicalWindow>(window_types, std::move(select_list), left.get().estimated_cardinality);
206122 left_window.children.push_back(left);
206123 left = left_window;
206124
206125 select_list = CreatePartitionedRowNumExpression(context, types);
206126 auto &right_window =
206127 Make<PhysicalWindow>(window_types, std::move(select_list), right.get().estimated_cardinality);
206128 right_window.children.push_back(right);
206129 right = right_window;
206130
206131 // add window expression result to join condition
206132 conditions.push_back(CreateNotDistinctComparison(context, LogicalType::BIGINT, types.size()));
206133 // join (created below) now includes the row number result column
206134 op.types.push_back(LogicalType::BIGINT);
206135 }
206136
206137 // EXCEPT is ANTI join
206138 // INTERSECT is SEMI join
206139
206140 JoinType join_type = op.type == LogicalOperatorType::LOGICAL_EXCEPT ? JoinType::ANTI : JoinType::SEMI;
206141 result = Make<PhysicalHashJoin>(op, left, right, std::move(conditions), join_type, op.estimated_cardinality);
206142
206143 // For EXCEPT ALL / INTERSECT ALL we need to remove the row number column again
206144 if (op.setop_all) {
206145 vector<unique_ptr<Expression>> select_list;
206146 for (idx_t i = 0; i < types.size(); i++) {
206147 select_list.push_back(make_uniq<BoundReferenceExpression>(types[i], i));
206148 }
206149 auto &proj = Make<PhysicalProjection>(types, std::move(select_list), op.estimated_cardinality);
206150 proj.children.push_back(*result);
206151 result = proj;
206152 }
206153 break;
206154 }
206155 default:
206156 throw InternalException("Unexpected operator type for set operation");
206157 }
206158
206159 // if the ALL specifier is not given, we have to ensure distinct results. Hence, push a GROUP BY ALL
206160 if (!op.setop_all) { // no ALL, use distinct semantics
206161 auto &types = result->GetTypes();
206162 vector<unique_ptr<Expression>> groups, aggregates /* left empty */;
206163 for (idx_t i = 0; i < types.size(); i++) {
206164 groups.push_back(make_uniq<BoundReferenceExpression>(types[i], i));
206165 }
206166 auto &group_by = Make<PhysicalHashAggregate>(context, op.types, std::move(aggregates), std::move(groups),
206167 result->estimated_cardinality);
206168 group_by.children.push_back(*result);
206169 result = group_by;
206170 }
206171
206172 D_ASSERT(result);
206173 return *result;
206174}
__host__ cudaTextureObject_t get() const noexcept

◆ CreatePlan() [31/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalUpdate & op)
protected
206399 {
206400 D_ASSERT(op.children.size() == 1);
206401 dependencies.AddDependency(op.table);
206402 return op.table.catalog.PlanUpdate(context, *this, op);
206403}

◆ CreatePlan() [32/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalPrepare & expr)
protected
205580 {
205581 // Generate the physical plan only if all parameters are bound.
205582 // Otherwise, the physical plan is never used.
205583 D_ASSERT(op.children.size() <= 1);
205584 if (op.prepared->properties.bound_all_parameters && !op.children.empty()) {
205585 PhysicalPlanGenerator inner_planner(context);
205586 op.prepared->physical_plan = inner_planner.PlanInternal(*op.children[0]);
205587 op.prepared->types = op.prepared->physical_plan->Root().types;
205588 }
205589 return Make<PhysicalPrepare>(op.name, std::move(op.prepared), op.estimated_cardinality);
205590}

◆ CreatePlan() [33/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalWindow & expr)
protected
206526 {
206527 D_ASSERT(op.children.size() == 1);
206528
206529 op.estimated_cardinality = op.EstimateCardinality(context);
206530 reference<PhysicalOperator> plan = CreatePlan(*op.children[0]);
206531#ifdef DEBUG
206532 for (auto &expr : op.expressions) {
206533 D_ASSERT(expr->IsWindow());
206534 }
206535#endif
206536
206537 op.estimated_cardinality = op.EstimateCardinality(context);
206538
206539 // Slice types
206540 auto types = op.types;
206541 const auto input_width = types.size() - op.expressions.size();
206542 types.resize(input_width);
206543
206544 // Identify streaming windows
206545 const bool enable_optimizer = ClientConfig::GetConfig(context).enable_optimizer;
206546 vector<idx_t> blocking_windows;
206547 vector<idx_t> streaming_windows;
206548 for (idx_t expr_idx = 0; expr_idx < op.expressions.size(); expr_idx++) {
206549 if (enable_optimizer && PhysicalStreamingWindow::IsStreamingFunction(context, op.expressions[expr_idx])) {
206550 streaming_windows.push_back(expr_idx);
206551 } else {
206552 blocking_windows.push_back(expr_idx);
206553 }
206554 }
206555
206556 // Process the window functions by sharing the partition/order definitions
206557 unordered_map<idx_t, idx_t> projection_map;
206558 vector<vector<idx_t>> window_expressions;
206559 idx_t streaming_count = 0;
206560 auto output_pos = input_width;
206561 while (!blocking_windows.empty() || !streaming_windows.empty()) {
206562 const bool process_blocking = streaming_windows.empty();
206563 auto &remaining = process_blocking ? blocking_windows : streaming_windows;
206564 streaming_count += process_blocking ? 0 : 1;
206565
206566 // Find all functions that share the partitioning of the first remaining expression
206567 auto over_idx = remaining[0];
206568
206569 vector<idx_t> matching;
206570 vector<idx_t> unprocessed;
206571 for (const auto &expr_idx : remaining) {
206572 D_ASSERT(op.expressions[expr_idx]->GetExpressionClass() == ExpressionClass::BOUND_WINDOW);
206573 auto &wexpr = op.expressions[expr_idx]->Cast<BoundWindowExpression>();
206574
206575 // Just record the first one (it defines the partition)
206576 if (over_idx == expr_idx) {
206577 matching.emplace_back(expr_idx);
206578 continue;
206579 }
206580
206581 // If it is in a different partition, skip it
206582 const auto &over_expr = op.expressions[over_idx]->Cast<BoundWindowExpression>();
206583 if (!over_expr.PartitionsAreEquivalent(wexpr)) {
206584 unprocessed.emplace_back(expr_idx);
206585 continue;
206586 }
206587
206588 // CSE Elimination: Search for a previous match
206589 bool cse = false;
206590 for (idx_t i = 0; i < matching.size(); ++i) {
206591 const auto match_idx = matching[i];
206592 auto &match_expr = op.expressions[match_idx]->Cast<BoundWindowExpression>();
206593 if (wexpr.Equals(match_expr)) {
206594 projection_map[input_width + expr_idx] = output_pos + i;
206595 cse = true;
206596 break;
206597 }
206598 }
206599 if (cse) {
206600 continue;
206601 }
206602
206603 // Is there a common sort prefix?
206604 const auto prefix = over_expr.GetSharedOrders(wexpr);
206605 if (prefix != MinValue<idx_t>(over_expr.orders.size(), wexpr.orders.size())) {
206606 unprocessed.emplace_back(expr_idx);
206607 continue;
206608 }
206609 matching.emplace_back(expr_idx);
206610
206611 // Switch to the longer prefix
206612 if (prefix < wexpr.orders.size()) {
206613 over_idx = expr_idx;
206614 }
206615 }
206616 remaining.swap(unprocessed);
206617
206618 // Remember the projection order
206619 for (const auto &expr_idx : matching) {
206620 projection_map[input_width + expr_idx] = output_pos++;
206621 }
206622
206623 window_expressions.emplace_back(std::move(matching));
206624 }
206625
206626 // Build the window operators
206627 for (idx_t i = 0; i < window_expressions.size(); ++i) {
206628 // Extract the matching expressions
206629 const auto &matching = window_expressions[i];
206630 vector<unique_ptr<Expression>> select_list;
206631 for (const auto &expr_idx : matching) {
206632 select_list.emplace_back(std::move(op.expressions[expr_idx]));
206633 types.emplace_back(op.types[input_width + expr_idx]);
206634 }
206635
206636 // Chain the new window operator on top of the plan
206637 if (i >= streaming_count) {
206638 auto &window = Make<PhysicalWindow>(types, std::move(select_list), op.estimated_cardinality);
206639 window.children.push_back(plan);
206640 plan = window;
206641 } else {
206642 auto &window = Make<PhysicalStreamingWindow>(types, std::move(select_list), op.estimated_cardinality);
206643 window.children.push_back(plan);
206644 plan = window;
206645 }
206646 }
206647
206648 // Put everything back into place if it moved
206649 if (!projection_map.empty()) {
206650 vector<unique_ptr<Expression>> select_list(op.types.size());
206651 // The inputs don't move
206652 for (idx_t i = 0; i < input_width; ++i) {
206653 select_list[i] = make_uniq<BoundReferenceExpression>(op.types[i], i);
206654 }
206655 // The outputs have been rearranged
206656 for (const auto &p : projection_map) {
206657 select_list[p.first] = make_uniq<BoundReferenceExpression>(op.types[p.first], p.second);
206658 }
206659 auto &proj = Make<PhysicalProjection>(op.types, std::move(select_list), op.estimated_cardinality);
206660 proj.children.push_back(plan);
206661 plan = proj;
206662 }
206663
206664 return plan;
206665}

◆ CreatePlan() [34/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalExecute & op)
protected
204204 {
204205 if (op.prepared->physical_plan) {
204206 D_ASSERT(op.children.empty());
204207 return Make<PhysicalExecute>(op.prepared->physical_plan->Root());
204208 }
204209
204210 D_ASSERT(op.children.size() == 1);
204211 auto &plan = CreatePlan(*op.children[0]);
204212 auto &execute = Make<PhysicalExecute>(plan);
204213 auto &cast_execute = execute.Cast<PhysicalExecute>();
204214 cast_execute.prepared = op.prepared;
204215 return execute;
204216}

◆ CreatePlan() [35/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalPragma & op)
protected
205513 {
205514 return Make<PhysicalPragma>(std::move(op.info), op.estimated_cardinality);
205515}

◆ CreatePlan() [36/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalSample & op)
protected
205894 {
205895 D_ASSERT(op.children.size() == 1);
205896
205897 auto &plan = CreatePlan(*op.children[0]);
205898 if (!op.sample_options->seed.IsValid()) {
205899 auto &random_engine = RandomEngine::Get(context);
205900 op.sample_options->SetSeed(random_engine.NextRandomInteger());
205901 }
205902
205903 switch (op.sample_options->method) {
205904 case SampleMethod::RESERVOIR_SAMPLE: {
205905 auto &sample = Make<PhysicalReservoirSample>(op.types, std::move(op.sample_options), op.estimated_cardinality);
205906 sample.children.push_back(plan);
205907 return sample;
205908 }
205909 case SampleMethod::SYSTEM_SAMPLE:
205910 case SampleMethod::BERNOULLI_SAMPLE: {
205911 if (!op.sample_options->is_percentage) {
205912 throw ParserException("Sample method %s cannot be used with a discrete sample count, either switch to "
205913 "reservoir sampling or use a sample_size",
205914 EnumUtil::ToString(op.sample_options->method));
205915 }
205916 auto &sample = Make<PhysicalStreamingSample>(op.types, std::move(op.sample_options), op.estimated_cardinality);
205917 sample.children.push_back(plan);
205918 return sample;
205919 }
205920 default:
205921 throw InternalException("Unimplemented sample method");
205922 }
205923}

◆ CreatePlan() [37/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalSet & op)
protected
205977 {
205978 // Set a config setting.
205979 if (op.children.empty()) {
205980 return Make<PhysicalSet>(op.name, op.value, op.scope, op.estimated_cardinality);
205981 }
205982
205983 // Set a variable.
205984 auto &plan = CreatePlan(*op.children[0]);
205985 auto &set_variable = Make<PhysicalSetVariable>(std::move(op.name), op.estimated_cardinality);
205986 set_variable.children.push_back(plan);
205987 return set_variable;
205988}

◆ CreatePlan() [38/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalReset & op)
protected
205838 {
205839 return Make<PhysicalReset>(op.name, op.scope, op.estimated_cardinality);
205840}

◆ CreatePlan() [39/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalSimple & op)
protected
206231 {
206232 switch (op.type) {
206233 case LogicalOperatorType::LOGICAL_ALTER:
206234 return Make<PhysicalAlter>(unique_ptr_cast<ParseInfo, AlterInfo>(std::move(op.info)), op.estimated_cardinality);
206235 case LogicalOperatorType::LOGICAL_DROP:
206236 return Make<PhysicalDrop>(unique_ptr_cast<ParseInfo, DropInfo>(std::move(op.info)), op.estimated_cardinality);
206237 case LogicalOperatorType::LOGICAL_TRANSACTION:
206238 return Make<PhysicalTransaction>(unique_ptr_cast<ParseInfo, TransactionInfo>(std::move(op.info)),
206239 op.estimated_cardinality);
206240 case LogicalOperatorType::LOGICAL_LOAD:
206241 return Make<PhysicalLoad>(unique_ptr_cast<ParseInfo, LoadInfo>(std::move(op.info)), op.estimated_cardinality);
206242 case LogicalOperatorType::LOGICAL_ATTACH:
206243 return Make<PhysicalAttach>(unique_ptr_cast<ParseInfo, AttachInfo>(std::move(op.info)),
206244 op.estimated_cardinality);
206245 case LogicalOperatorType::LOGICAL_DETACH:
206246 return Make<PhysicalDetach>(unique_ptr_cast<ParseInfo, DetachInfo>(std::move(op.info)),
206247 op.estimated_cardinality);
206248 case LogicalOperatorType::LOGICAL_UPDATE_EXTENSIONS:
206249 return Make<PhysicalUpdateExtensions>(unique_ptr_cast<ParseInfo, UpdateExtensionsInfo>(std::move(op.info)),
206250 op.estimated_cardinality);
206251 default:
206252 throw NotImplementedException("Unimplemented type for logical simple operator");
206253 }
206254}

◆ CreatePlan() [40/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalVacuum & op)
protected
206465 {
206466 auto &vacuum = Make<PhysicalVacuum>(unique_ptr_cast<ParseInfo, VacuumInfo>(std::move(op.info)), op.table,
206467 std::move(op.column_id_map), op.estimated_cardinality);
206468 if (!op.children.empty()) {
206469 auto &plan = CreatePlan(*op.children[0]);
206470 vacuum.children.push_back(plan);
206471 }
206472 return vacuum;
206473}

◆ CreatePlan() [41/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalUnnest & op)
protected
206366 {
206367 D_ASSERT(op.children.size() == 1);
206368 auto &plan = CreatePlan(*op.children[0]);
206369 auto &unnest = Make<PhysicalUnnest>(op.types, std::move(op.expressions), op.estimated_cardinality);
206370 unnest.children.push_back(plan);
206371 return unnest;
206372}

◆ CreatePlan() [42/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalRecursiveCTE & op)
protected
205651 {
205652 D_ASSERT(op.children.size() == 2);
205653
205654 // Create the working_table that the PhysicalRecursiveCTE will use for evaluation.
205655 auto working_table = make_shared_ptr<ColumnDataCollection>(context, op.types);
205656
205657 // Add the ColumnDataCollection to the context of this PhysicalPlanGenerator
205658 recursive_cte_tables[op.table_index] = working_table;
205659
205660 auto &left = CreatePlan(*op.children[0]);
205661
205662 // If the logical operator has no key targets or all columns are referenced,
205663 // then we create a normal recursive CTE operator.
205664 if (op.key_targets.empty()) {
205665 auto recurring_table = make_shared_ptr<ColumnDataCollection>(context, op.types);
205666 recurring_cte_tables[op.table_index] = recurring_table;
205667 auto &right = CreatePlan(*op.children[1]);
205668 auto &cte = Make<PhysicalRecursiveCTE>(op.ctename, op.table_index, op.types, op.union_all, left, right,
205669 op.estimated_cardinality);
205670 auto &cast_cte = cte.Cast<PhysicalRecursiveCTE>();
205671 cast_cte.ref_recurring = op.ref_recurring;
205672 cast_cte.recurring_table = recurring_table;
205673 cast_cte.distinct_types = op.types;
205674 cast_cte.working_table = working_table;
205675 return cte;
205676 }
205677
205678 vector<LogicalType> payload_types, distinct_types;
205679 vector<idx_t> payload_idx, distinct_idx;
205680 vector<unique_ptr<BoundAggregateExpression>> payload_aggregates;
205681
205682 // create a group for each target, these are the columns that should be grouped
205683 unordered_map<idx_t, idx_t> group_by_references;
205684 for (idx_t i = 0; i < op.key_targets.size(); i++) {
205685 auto &target = op.key_targets[i];
205686 D_ASSERT(target->type == ExpressionType::BOUND_REF);
205687 auto &bound_ref = target->Cast<BoundReferenceExpression>();
205688 group_by_references[bound_ref.index] = i;
205689 }
205690
205691 /*
205692 * iterate over all types
205693 * Differentiate the occurrence of the column in the key clause.
205694 */
205695 auto &types = left.GetTypes();
205696 for (idx_t i = 0; i < types.size(); ++i) {
205697 auto logical_type = types[i];
205698 // Check if we can directly refer to a group, or if we need to push an aggregate with LAST
205699 auto entry = group_by_references.find(i);
205700 if (entry != group_by_references.end()) {
205701 // Column has a key, note the column index to make a distinction on it
205702 distinct_idx.emplace_back(i);
205703 distinct_types.push_back(logical_type);
205704 } else {
205705 // Column is not in the key clause, so we need to create an aggregate
205706 auto bound = make_uniq<BoundReferenceExpression>(logical_type, 0U);
205707
205708 vector<unique_ptr<Expression>> first_children;
205709 first_children.push_back(std::move(bound));
205710
205711 FunctionBinder function_binder(context);
205712 auto first_aggregate =
205713 function_binder.BindAggregateFunction(LastFunctionGetter::GetFunction(logical_type),
205714 std::move(first_children), nullptr, AggregateType::NON_DISTINCT);
205715 first_aggregate->order_bys = nullptr;
205716
205717 payload_types.push_back(logical_type);
205718 payload_idx.emplace_back(i);
205719 payload_aggregates.push_back(std::move(first_aggregate));
205720 }
205721 }
205722
205723 // If the key variant has been used, a recurring table will be created.
205724 auto recurring_table = make_shared_ptr<ColumnDataCollection>(context, op.types);
205725 recurring_cte_tables[op.table_index] = recurring_table;
205726
205727 auto &right = CreatePlan(*op.children[1]);
205728 auto &cte = Make<PhysicalRecursiveCTE>(op.ctename, op.table_index, op.types, op.union_all, left, right,
205729 op.estimated_cardinality);
205730 auto &cast_cte = cte.Cast<PhysicalRecursiveCTE>();
205731 cast_cte.using_key = true;
205732 cast_cte.payload_aggregates = std::move(payload_aggregates);
205733 cast_cte.distinct_idx = distinct_idx;
205734 cast_cte.distinct_types = distinct_types;
205735 cast_cte.payload_idx = payload_idx;
205736 cast_cte.payload_types = payload_types;
205737 cast_cte.ref_recurring = op.ref_recurring;
205738 cast_cte.working_table = working_table;
205739 cast_cte.recurring_table = recurring_table;
205740 return cte;
205741}
unordered_map< idx_t, shared_ptr< ColumnDataCollection > > recurring_cte_tables
Used to reference the recurring tables.
Definition duckdb.hpp:38161
unordered_map< idx_t, shared_ptr< ColumnDataCollection > > recursive_cte_tables
Recursive CTEs require at least one ChunkScan, referencing the working_table. This data structure is ...
Definition duckdb.hpp:38159

◆ CreatePlan() [43/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalMaterializedCTE & op)
protected
203637 {
203638 D_ASSERT(op.children.size() == 2);
203639
203640 // Create the working_table that the PhysicalCTE will use for evaluation.
203641 auto working_table = make_shared_ptr<ColumnDataCollection>(context, op.children[0]->types);
203642
203643 // Add the ColumnDataCollection to the context of this PhysicalPlanGenerator
203644 recursive_cte_tables[op.table_index] = working_table;
203645 materialized_ctes[op.table_index] = vector<const_reference<PhysicalOperator>>();
203646
203647 // Create the plan for the left side. This is the materialization.
203648 auto &left = CreatePlan(*op.children[0]);
203649 // Initialize an empty vector to collect the scan operators.
203650 auto &right = CreatePlan(*op.children[1]);
203651
203652 auto &cte = Make<PhysicalCTE>(op.ctename, op.table_index, right.types, left, right, op.estimated_cardinality);
203653 auto &cast_cte = cte.Cast<PhysicalCTE>();
203654 cast_cte.working_table = working_table;
203655 cast_cte.cte_scans = materialized_ctes[op.table_index];
203656 return cte;
203657}
unordered_map< idx_t, vector< const_reference< PhysicalOperator > > > materialized_ctes
Materialized CTE ids must be collected.
Definition duckdb.hpp:38163

◆ CreatePlan() [44/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalCTERef & op)
protected
205743 {
205744 D_ASSERT(op.children.empty());
205745
205746 // Check if this LogicalCTERef is supposed to scan a materialized CTE.
205747 // Lookup if there is a materialized CTE for the cte_index.
205748 auto materialized_cte = materialized_ctes.find(op.cte_index);
205749
205750 // If this check fails, this is a reference to a materialized recursive CTE.
205751 if (materialized_cte != materialized_ctes.end()) {
205752 auto &chunk_scan = Make<PhysicalColumnDataScan>(op.chunk_types, PhysicalOperatorType::CTE_SCAN,
205753 op.estimated_cardinality, op.cte_index);
205754
205755 auto cte = recursive_cte_tables.find(op.cte_index);
205756 if (cte == recursive_cte_tables.end()) {
205757 throw InvalidInputException("Referenced materialized CTE does not exist.");
205758 }
205759
205760 auto &cast_chunk_scan = chunk_scan.Cast<PhysicalColumnDataScan>();
205761 cast_chunk_scan.collection = cte->second.get();
205762 materialized_cte->second.push_back(cast_chunk_scan);
205763 return chunk_scan;
205764 }
205765
205766 // CreatePlan of a LogicalRecursiveCTE must have happened before.
205767 auto cte = recursive_cte_tables.find(op.cte_index);
205768 if (cte == recursive_cte_tables.end()) {
205769 throw InvalidInputException("Referenced recursive CTE does not exist.");
205770 }
205771
205772 // If we found a recursive CTE and we want to scan the recurring table, we search for it,
205773 if (op.is_recurring) {
205774 cte = recurring_cte_tables.find(op.cte_index);
205775 if (cte == recurring_cte_tables.end()) {
205776 throw InvalidInputException("RECURRING can only be used with USING KEY in recursive CTE.");
205777 }
205778 }
205779
205780 auto &types = cte->second.get()->Types();
205781 auto op_type =
205782 op.is_recurring ? PhysicalOperatorType::RECURSIVE_RECURRING_CTE_SCAN : PhysicalOperatorType::RECURSIVE_CTE_SCAN;
205783 auto &chunk_scan = Make<PhysicalColumnDataScan>(types, op_type, op.estimated_cardinality, op.cte_index);
205784 auto &cast_chunk_scan = chunk_scan.Cast<PhysicalColumnDataScan>();
205785 cast_chunk_scan.collection = cte->second.get();
205786 return chunk_scan;
205787}

◆ CreatePlan() [45/45]

PhysicalOperator & duckdb::PhysicalPlanGenerator::CreatePlan ( LogicalPivot & op)
protected
205399 {
205400 D_ASSERT(op.children.size() == 1);
205401 auto &plan = CreatePlan(*op.children[0]);
205402 return Make<PhysicalPivot>(std::move(op.types), plan, std::move(op.bound_pivot));
205403}

◆ PlanAsOfJoin()

PhysicalOperator & duckdb::PhysicalPlanGenerator::PlanAsOfJoin ( LogicalComparisonJoin & op)
protected
202643 {
202644 // now visit the children
202645 D_ASSERT(op.children.size() == 2);
202646 idx_t lhs_cardinality = op.children[0]->EstimateCardinality(context);
202647 idx_t rhs_cardinality = op.children[1]->EstimateCardinality(context);
202648 auto &left = CreatePlan(*op.children[0]);
202649 auto &right = CreatePlan(*op.children[1]);
202650
202651 // Validate
202652 vector<idx_t> equi_indexes;
202653 auto asof_idx = op.conditions.size();
202654 for (size_t c = 0; c < op.conditions.size(); ++c) {
202655 auto &cond = op.conditions[c];
202656 switch (cond.comparison) {
202657 case ExpressionType::COMPARE_EQUAL:
202658 case ExpressionType::COMPARE_NOT_DISTINCT_FROM:
202659 equi_indexes.emplace_back(c);
202660 break;
202661 case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
202662 case ExpressionType::COMPARE_GREATERTHAN:
202663 case ExpressionType::COMPARE_LESSTHANOREQUALTO:
202664 case ExpressionType::COMPARE_LESSTHAN:
202665 D_ASSERT(asof_idx == op.conditions.size());
202666 asof_idx = c;
202667 break;
202668 default:
202669 throw InternalException("Invalid ASOF JOIN comparison");
202670 }
202671 }
202672 D_ASSERT(asof_idx < op.conditions.size());
202673
202674 // If there is a non-comparison predicate, we have to use NLJ.
202675 const bool has_predicate = op.predicate.get();
202676 const bool force_asof_join = Settings::Get<DebugAsofIejoinSetting>(context);
202677 if (!force_asof_join || has_predicate) {
202678 const idx_t asof_join_threshold = Settings::Get<AsofLoopJoinThresholdSetting>(context);
202679 if (has_predicate || (op.children[0]->has_estimated_cardinality && lhs_cardinality < asof_join_threshold)) {
202680 auto result = PlanAsOfLoopJoin(op, left, right);
202681 if (result) {
202682 return *result;
202683 }
202684 }
202685 return Make<PhysicalAsOfJoin>(op, left, right);
202686 }
202687
202688 // Strip extra column from rhs projections
202689 auto &right_projection_map = op.right_projection_map;
202690 if (right_projection_map.empty()) {
202691 const auto right_count = right.GetTypes().size();
202692 right_projection_map.reserve(right_count);
202693 for (column_t i = 0; i < right_count; ++i) {
202694 right_projection_map.emplace_back(i);
202695 }
202696 }
202697
202698 // Debug implementation: IEJoin of Window
202699 // LEAD(asof_column, 1, infinity) OVER (PARTITION BY equi_column... ORDER BY asof_column) AS asof_end
202700 auto &asof_comp = op.conditions[asof_idx];
202701 auto &asof_column = asof_comp.right;
202702 auto asof_type = asof_column->return_type;
202703 auto asof_end = make_uniq<BoundWindowExpression>(ExpressionType::WINDOW_LEAD, asof_type, nullptr, nullptr);
202704 asof_end->children.emplace_back(asof_column->Copy());
202705 // TODO: If infinities are not supported for a type, fake them by looking at LHS statistics?
202706 asof_end->offset_expr = make_uniq<BoundConstantExpression>(Value::BIGINT(1));
202707 for (auto equi_idx : equi_indexes) {
202708 asof_end->partitions.emplace_back(op.conditions[equi_idx].right->Copy());
202709 }
202710 switch (asof_comp.comparison) {
202711 case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
202712 case ExpressionType::COMPARE_GREATERTHAN:
202713 asof_end->orders.emplace_back(OrderType::ASCENDING, OrderByNullType::NULLS_FIRST, asof_column->Copy());
202714 asof_end->default_expr = make_uniq<BoundConstantExpression>(Value::Infinity(asof_type));
202715 break;
202716 case ExpressionType::COMPARE_LESSTHANOREQUALTO:
202717 case ExpressionType::COMPARE_LESSTHAN:
202718 asof_end->orders.emplace_back(OrderType::DESCENDING, OrderByNullType::NULLS_FIRST, asof_column->Copy());
202719 asof_end->default_expr = make_uniq<BoundConstantExpression>(Value::NegativeInfinity(asof_type));
202720 break;
202721 default:
202722 throw InternalException("Invalid ASOF JOIN ordering for WINDOW");
202723 }
202724
202725 asof_end->start = WindowBoundary::UNBOUNDED_PRECEDING;
202726 asof_end->end = WindowBoundary::CURRENT_ROW_ROWS;
202727
202728 vector<unique_ptr<Expression>> window_select;
202729 window_select.emplace_back(std::move(asof_end));
202730
202731 auto &window_types = op.children[1]->types;
202732 window_types.emplace_back(asof_type);
202733
202734 auto &window = Make<PhysicalWindow>(window_types, std::move(window_select), rhs_cardinality);
202735 window.children.emplace_back(right);
202736
202737 // IEJoin(left, window, conditions || asof_comp ~op asof_end)
202738 JoinCondition asof_upper;
202739 asof_upper.left = asof_comp.left->Copy();
202740 asof_upper.right = make_uniq<BoundReferenceExpression>(asof_type, window_types.size() - 1);
202741 switch (asof_comp.comparison) {
202742 case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
202743 asof_upper.comparison = ExpressionType::COMPARE_LESSTHAN;
202744 break;
202745 case ExpressionType::COMPARE_GREATERTHAN:
202746 asof_upper.comparison = ExpressionType::COMPARE_LESSTHANOREQUALTO;
202747 break;
202748 case ExpressionType::COMPARE_LESSTHANOREQUALTO:
202749 asof_upper.comparison = ExpressionType::COMPARE_GREATERTHAN;
202750 break;
202751 case ExpressionType::COMPARE_LESSTHAN:
202752 asof_upper.comparison = ExpressionType::COMPARE_GREATERTHANOREQUALTO;
202753 break;
202754 default:
202755 throw InternalException("Invalid ASOF JOIN comparison for IEJoin");
202756 }
202757
202758 op.conditions.emplace_back(std::move(asof_upper));
202759 return Make<PhysicalIEJoin>(op, left, window, std::move(op.conditions), op.join_type, lhs_cardinality);
202760}
static DUCKDB_API Value NegativeInfinity(const LogicalType &type)
Create the negative infinite value of a given type (numeric only).
Definition duckdb.cpp:132095
static DUCKDB_API Value BIGINT(int64_t value)
Create a bigint Value from a specified value.
Definition duckdb.cpp:132146
static DUCKDB_API Value Infinity(const LogicalType &type)
Create the positive infinite value of a given type (numeric only).
Definition duckdb.cpp:132072
idx_t column_t
Type used for column identifiers.
Definition duckdb.hpp:259

◆ PlanComparisonJoin()

PhysicalOperator & duckdb::PhysicalPlanGenerator::PlanComparisonJoin ( LogicalComparisonJoin & op)
protected
202850 {
202851 // now visit the children
202852 D_ASSERT(op.children.size() == 2);
202853 idx_t lhs_cardinality = op.children[0]->EstimateCardinality(context);
202854 idx_t rhs_cardinality = op.children[1]->EstimateCardinality(context);
202855 auto &left = CreatePlan(*op.children[0]);
202856 auto &right = CreatePlan(*op.children[1]);
202857 left.estimated_cardinality = lhs_cardinality;
202858 right.estimated_cardinality = rhs_cardinality;
202859
202860 if (op.conditions.empty()) {
202861 // no conditions: insert a cross product
202862 return Make<PhysicalCrossProduct>(op.types, left, right, op.estimated_cardinality);
202863 }
202864
202865 idx_t has_range = 0;
202866 bool has_equality = op.HasEquality(has_range);
202867 bool can_merge = has_range > 0;
202868 bool can_iejoin = has_range >= 2 && recursive_cte_tables.empty();
202869 switch (op.join_type) {
202870 case JoinType::SEMI:
202871 case JoinType::ANTI:
202872 case JoinType::RIGHT_ANTI:
202873 case JoinType::RIGHT_SEMI:
202874 case JoinType::MARK:
202875 can_merge = can_merge && op.conditions.size() == 1;
202876 can_iejoin = false;
202877 break;
202878 default:
202879 break;
202880 }
202881 // TODO: Extend PWMJ to handle all comparisons and projection maps
202882 bool prefer_range_joins = Settings::Get<PreferRangeJoinsSetting>(context);
202883 prefer_range_joins = prefer_range_joins && can_iejoin;
202884 if (has_equality && !prefer_range_joins) {
202885 // Equality join with small number of keys : possible perfect join optimization
202886 auto &join = Make<PhysicalHashJoin>(op, left, right, std::move(op.conditions), op.join_type,
202887 op.left_projection_map, op.right_projection_map, std::move(op.mark_types),
202888 op.estimated_cardinality, std::move(op.filter_pushdown));
202889 join.Cast<PhysicalHashJoin>().join_stats = std::move(op.join_stats);
202890 return join;
202891 }
202892
202893 D_ASSERT(op.left_projection_map.empty());
202894 idx_t nested_loop_join_threshold = Settings::Get<NestedLoopJoinThresholdSetting>(context);
202895 if (left.estimated_cardinality < nested_loop_join_threshold ||
202896 right.estimated_cardinality < nested_loop_join_threshold) {
202897 can_iejoin = false;
202898 can_merge = false;
202899 }
202900
202901 if (can_merge && can_iejoin) {
202902 idx_t merge_join_threshold = Settings::Get<MergeJoinThresholdSetting>(context);
202903 if (left.estimated_cardinality < merge_join_threshold || right.estimated_cardinality < merge_join_threshold) {
202904 can_iejoin = false;
202905 }
202906 }
202907
202908 if (can_iejoin) {
202909 return Make<PhysicalIEJoin>(op, left, right, std::move(op.conditions), op.join_type, op.estimated_cardinality,
202910 std::move(op.filter_pushdown));
202911 }
202912 if (can_merge) {
202913 // range join: use piecewise merge join
202914 return Make<PhysicalPiecewiseMergeJoin>(op, left, right, std::move(op.conditions), op.join_type,
202915 op.estimated_cardinality, std::move(op.filter_pushdown));
202916 }
202917 if (PhysicalNestedLoopJoin::IsSupported(op.conditions, op.join_type)) {
202918 // inequality join: use nested loop
202919 return Make<PhysicalNestedLoopJoin>(op, left, right, std::move(op.conditions), op.join_type,
202920 op.estimated_cardinality, std::move(op.filter_pushdown));
202921 }
202922
202923 for (auto &cond : op.conditions) {
202924 RewriteJoinCondition(cond.right, left.types.size());
202925 }
202926 auto condition = JoinCondition::CreateExpression(std::move(op.conditions));
202927 return Make<PhysicalBlockwiseNLJoin>(op, left, right, std::move(condition), op.join_type, op.estimated_cardinality);
202928}
cv::String join(const cv::String &base, const cv::String &path)
static unique_ptr< Expression > CreateExpression(JoinCondition cond)
Turns the JoinCondition into an expression; note that this destroys the JoinCondition as the expressi...
Definition duckdb.cpp:380359

◆ PlanDelimJoin()

PhysicalOperator & duckdb::PhysicalPlanGenerator::PlanDelimJoin ( LogicalComparisonJoin & op)
protected
203823 {
203824 // first create the underlying join
203825 auto &plan = PlanComparisonJoin(op);
203826 // this should create a join, not a cross product
203827 D_ASSERT(plan.type != PhysicalOperatorType::CROSS_PRODUCT);
203828 // duplicate eliminated join
203829 // first gather the scans on the duplicate eliminated data set from the delim side
203830 const idx_t delim_idx = op.delim_flipped ? 0 : 1;
203831 vector<const_reference<PhysicalOperator>> delim_scans;
203832 GatherDelimScans(plan.children[delim_idx], delim_scans, ++this->delim_index);
203833 if (delim_scans.empty()) {
203834 // no duplicate eliminated scans in the delim side!
203835 // in this case we don't need to create a delim join
203836 // just push the normal join
203837 return plan;
203838 }
203839 vector<LogicalType> delim_types;
203840 vector<unique_ptr<Expression>> distinct_groups, distinct_expressions;
203841 for (auto &delim_expr : op.duplicate_eliminated_columns) {
203842 D_ASSERT(delim_expr->GetExpressionType() == ExpressionType::BOUND_REF);
203843 auto &bound_ref = delim_expr->Cast<BoundReferenceExpression>();
203844 delim_types.push_back(bound_ref.return_type);
203845 distinct_groups.push_back(make_uniq<BoundReferenceExpression>(bound_ref.return_type, bound_ref.index));
203846 }
203847
203848 // we still have to create the DISTINCT clause that is used to generate the duplicate eliminated chunk
203849 auto &distinct =
203850 Make<PhysicalHashAggregate>(context, delim_types, std::move(distinct_expressions), std::move(distinct_groups),
203851 delim_scans[0].get().estimated_cardinality);
203852
203853 // Create the duplicate eliminated join.
203854 if (op.delim_flipped) {
203855 return Make<PhysicalRightDelimJoin>(*this, op.types, plan, distinct, delim_scans, op.estimated_cardinality,
203856 optional_idx(this->delim_index));
203857 }
203858 return Make<PhysicalLeftDelimJoin>(*this, op.types, plan, distinct, delim_scans, op.estimated_cardinality,
203859 optional_idx(this->delim_index));
203860}
idx_t delim_index
The index for duplicate eliminated joins.
Definition duckdb.hpp:38165

◆ ExtractAggregateExpressions()

PhysicalOperator & duckdb::PhysicalPlanGenerator::ExtractAggregateExpressions ( PhysicalOperator & child,
vector< unique_ptr< Expression > > & expressions,
vector< unique_ptr< Expression > > & groups,
optional_ptr< vector< GroupingSet > > grouping_sets )
protected
202320 {
202321 vector<unique_ptr<Expression>> expressions;
202322 vector<LogicalType> types;
202323
202324 // bind sorted aggregates
202325 for (auto &aggr : aggregates) {
202326 auto &bound_aggr = aggr->Cast<BoundAggregateExpression>();
202327 if (bound_aggr.order_bys) {
202328 // sorted aggregate!
202329 FunctionBinder::BindSortedAggregate(context, bound_aggr, groups, grouping_sets);
202330 }
202331 }
202332 for (auto &group : groups) {
202333 auto ref = make_uniq<BoundReferenceExpression>(group->return_type, expressions.size());
202334 types.push_back(group->return_type);
202335 expressions.push_back(std::move(group));
202336 group = std::move(ref);
202337 }
202338 for (auto &aggr : aggregates) {
202339 auto &bound_aggr = aggr->Cast<BoundAggregateExpression>();
202340 for (auto &child_expr : bound_aggr.children) {
202341 auto ref = make_uniq<BoundReferenceExpression>(child_expr->return_type, expressions.size());
202342 types.push_back(child_expr->return_type);
202343 expressions.push_back(std::move(child_expr));
202344 child_expr = std::move(ref);
202345 }
202346 if (bound_aggr.filter) {
202347 auto &filter = bound_aggr.filter;
202348 auto ref = make_uniq<BoundReferenceExpression>(filter->return_type, expressions.size());
202349 types.push_back(filter->return_type);
202350 expressions.push_back(std::move(filter));
202351 bound_aggr.filter = std::move(ref);
202352 }
202353 }
202354 if (expressions.empty()) {
202355 return child;
202356 }
202357 auto &proj = Make<PhysicalProjection>(std::move(types), std::move(expressions), child.estimated_cardinality);
202358 proj.children.push_back(child);
202359 return proj;
202360}

◆ ResolveAndPlan()

PhysicalOperator & duckdb::PhysicalPlanGenerator::ResolveAndPlan ( unique_ptr< LogicalOperator > logical)
private
206801 {
206802 auto &profiler = QueryProfiler::Get(context);
206803
206804 // Resolve the types of each operator.
206805 profiler.StartPhase(MetricType::PHYSICAL_PLANNER_RESOLVE_TYPES);
206806 op->ResolveOperatorTypes();
206807 profiler.EndPhase();
206808
206809 // Resolve the column references.
206810 profiler.StartPhase(MetricType::PHYSICAL_PLANNER_COLUMN_BINDING);
206811 ColumnBindingResolver resolver;
206812 resolver.VisitOperator(*op);
206813 profiler.EndPhase();
206814
206815 // Create the main physical plan.
206816 profiler.StartPhase(MetricType::PHYSICAL_PLANNER_CREATE_PLAN);
206817 physical_plan = PlanInternal(*op);
206818 profiler.EndPhase();
206819
206820 // Return a reference to the root of this plan.
206821 return physical_plan->Root();
206822}

◆ PlanInternal()

unique_ptr< PhysicalPlan > duckdb::PhysicalPlanGenerator::PlanInternal ( LogicalOperator & logical)
private
206824 {
206825 if (!physical_plan) {
206826 physical_plan = make_uniq<PhysicalPlan>(Allocator::Get(context));
206827 }
206828 op.estimated_cardinality = op.EstimateCardinality(context);
206829 physical_plan->SetRoot(CreatePlan(op));
206830 physical_plan->Root().estimated_cardinality = op.estimated_cardinality;
206831
206832 auto debug_verify_vector = Settings::Get<DebugVerifyVectorSetting>(context);
206833 if (debug_verify_vector != DebugVectorVerification::NONE) {
206834 if (debug_verify_vector != DebugVectorVerification::DICTIONARY_EXPRESSION &&
206835 debug_verify_vector != DebugVectorVerification::VARIANT_VECTOR) {
206836 physical_plan->SetRoot(Make<PhysicalVerifyVector>(physical_plan->Root(), debug_verify_vector));
206837 }
206838 }
206839 return std::move(physical_plan);
206840}

◆ PreserveInsertionOrder() [2/2]

bool duckdb::PhysicalPlanGenerator::PreserveInsertionOrder ( PhysicalOperator & plan)
private
204847 {
204848 return PreserveInsertionOrder(context, plan);
204849}

◆ UseBatchIndex() [2/2]

bool duckdb::PhysicalPlanGenerator::UseBatchIndex ( PhysicalOperator & plan)
private
204864 {
204865 return UseBatchIndex(context, plan);
204866}

◆ PlanAsOfLoopJoin()

optional_ptr< PhysicalOperator > duckdb::PhysicalPlanGenerator::PlanAsOfLoopJoin ( LogicalComparisonJoin & op,
PhysicalOperator & probe,
PhysicalOperator & build )
private
202403 {
202404 // Plan a inverse nested loop join, then aggregate the values to choose the optimal match for each probe row.
202405 // Use a row number primary key to handle duplicate probe values.
202406 // aggregate the fields to produce at most one match per probe row,
202407 // then project the columns back into the correct order and drop the primary key.
202408 //
202409 // ∏ * \ pk
202410 // |
202411 // Γ pk;first(P),arg_xxx_null(B,inequality)
202412 // |
202413 // ∏ *,inequality
202414 // |
202415 // ⨝ swapped
202416 // / \ 
202417 // B W pk:row_number
202418 // |
202419 // P
202420
202421 LogicalComparisonJoin join_op(InverseJoinType(op.join_type));
202422
202423 join_op.types = op.children[1]->types;
202424 const auto &probe_types = op.children[0]->types;
202425 join_op.types.insert(join_op.types.end(), probe_types.begin(), probe_types.end());
202426
202427 // Project pk
202428 LogicalType pk_type = LogicalType::BIGINT;
202429 join_op.types.emplace_back(pk_type);
202430
202431 // Fill in the projection maps to simplify the code below
202432 // Since NLJ doesn't support projection, but ASOF does,
202433 // we have to track this carefully...
202434 join_op.left_projection_map = op.right_projection_map;
202435 if (join_op.left_projection_map.empty()) {
202436 for (idx_t i = 0; i < op.children[1]->types.size(); ++i) {
202437 join_op.left_projection_map.emplace_back(i);
202438 }
202439 }
202440
202441 join_op.right_projection_map = op.left_projection_map;
202442 if (join_op.right_projection_map.empty()) {
202443 for (idx_t i = 0; i < op.children[0]->types.size(); ++i) {
202444 join_op.right_projection_map.emplace_back(i);
202445 }
202446 }
202447
202448 // Remap predicate column references.
202449 if (op.predicate) {
202450 vector<idx_t> swap_projection_map;
202451 const auto rhs_width = op.children[1]->types.size();
202452 for (const auto &l : join_op.right_projection_map) {
202453 swap_projection_map.emplace_back(l + rhs_width);
202454 }
202455 for (const auto &r : join_op.left_projection_map) {
202456 swap_projection_map.emplace_back(r);
202457 }
202458 join_op.predicate = op.predicate->Copy();
202459 ExpressionIterator::EnumerateExpression(join_op.predicate, [&](Expression &child) {
202460 if (child.GetExpressionClass() == ExpressionClass::BOUND_REF) {
202461 auto &col_idx = child.Cast<BoundReferenceExpression>().index;
202462 const auto new_idx = swap_projection_map[col_idx];
202463 col_idx = new_idx;
202464 }
202465 });
202466 }
202467
202468 auto binder = Binder::CreateBinder(context);
202469 FunctionBinder function_binder(*binder);
202470 auto asof_idx = op.conditions.size();
202471 string arg_min_max;
202472 for (idx_t i = 0; i < op.conditions.size(); ++i) {
202473 const auto &cond = op.conditions[i];
202474 JoinCondition nested_cond;
202475 nested_cond.left = cond.right->Copy();
202476 nested_cond.right = cond.left->Copy();
202477 if (!nested_cond.left || !nested_cond.right) {
202478 return nullptr;
202479 }
202480 nested_cond.comparison = FlipComparisonExpression(cond.comparison);
202481 join_op.conditions.emplace_back(std::move(nested_cond));
202482 switch (cond.comparison) {
202483 case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
202484 case ExpressionType::COMPARE_GREATERTHAN:
202485 D_ASSERT(asof_idx == op.conditions.size());
202486 asof_idx = i;
202487 arg_min_max = "arg_max_null";
202488 break;
202489 case ExpressionType::COMPARE_LESSTHANOREQUALTO:
202490 case ExpressionType::COMPARE_LESSTHAN:
202491 D_ASSERT(asof_idx == op.conditions.size());
202492 asof_idx = i;
202493 arg_min_max = "arg_min_null";
202494 break;
202495 case ExpressionType::COMPARE_EQUAL:
202496 case ExpressionType::COMPARE_NOTEQUAL:
202497 case ExpressionType::COMPARE_DISTINCT_FROM:
202498 break;
202499 default:
202500 // Unsupported NLJ comparison
202501 return nullptr;
202502 }
202503 }
202504
202505 // NLJ does not support some join types
202506 switch (join_op.join_type) {
202507 case JoinType::SEMI:
202508 case JoinType::ANTI:
202509 case JoinType::MARK:
202510 case JoinType::INNER:
202511 case JoinType::RIGHT:
202512 // Unfortunately, this does not check all the join types...
202513 if (!PhysicalNestedLoopJoin::IsSupported(op.conditions, op.join_type)) {
202514 return nullptr;
202515 }
202516 break;
202517 case JoinType::OUTER:
202518 case JoinType::LEFT:
202519 // RIGHT ASOF JOINs produce the entire build table and would require grouping on all build rows,
202520 // which defeats the purpose of this optimisation.
202521 default:
202522 return nullptr;
202523 }
202524
202525 EntryLookupInfo function_lookup(CatalogType::SCALAR_FUNCTION_ENTRY, arg_min_max);
202526 auto arg_min_max_func =
202527 binder->GetCatalogEntry(SYSTEM_CATALOG, DEFAULT_SCHEMA, function_lookup, OnEntryNotFound::RETURN_NULL);
202528 // Can't find the arg_min/max aggregate we need, so give up before we break anything.
202529 if (!arg_min_max_func || arg_min_max_func->type != CatalogType::AGGREGATE_FUNCTION_ENTRY) {
202530 return nullptr;
202531 }
202532 auto &arg_min_max_entry = arg_min_max_func->Cast<AggregateFunctionCatalogEntry>();
202533
202534 // PhysicalHashAggregate requires that the arguments to aggregate functions be bound references,
202535 // so we Project the (shared) ordering argument on the end of the join results.
202536 vector<unique_ptr<Expression>> comp_list;
202537 for (const auto &col_type : join_op.types) {
202538 const auto col_idx = comp_list.size();
202539 comp_list.emplace_back(make_uniq<BoundReferenceExpression>(col_type, col_idx));
202540 }
202541 vector<LogicalType> comp_types = join_op.types;
202542 auto comp_expr = op.conditions[asof_idx].right->Copy();
202543 comp_types.emplace_back(comp_expr->return_type);
202544 comp_list.emplace_back(std::move(comp_expr));
202545
202546 // Bind the aggregates first so we can abort safely if we can't find one.
202547 vector<LogicalType> aggr_types(1, pk_type);
202548
202549 // Wrap all the projected non-pk probe fields in `first` aggregates;
202550 vector<unique_ptr<Expression>> aggregates;
202551 for (const auto &i : join_op.right_projection_map) {
202552 const auto col_idx = op.children[1]->types.size() + i;
202553 const auto col_type = join_op.types[col_idx];
202554 aggr_types.emplace_back(col_type);
202555
202556 vector<unique_ptr<Expression>> aggr_children;
202557 auto col_ref = make_uniq<BoundReferenceExpression>(col_type, col_idx);
202558 aggr_children.push_back(std::move(col_ref));
202559
202560 auto first_aggregate = FirstFunctionGetter::GetFunction(col_type);
202561 auto aggr_expr = make_uniq<BoundAggregateExpression>(std::move(first_aggregate), std::move(aggr_children),
202562 nullptr, nullptr, AggregateType::NON_DISTINCT);
202563 D_ASSERT(col_type == aggr_expr->return_type);
202564 aggregates.emplace_back(std::move(aggr_expr));
202565 }
202566
202567 // Wrap all the projected build fields in `arg_max/min` aggregates using the inequality ordering;
202568 // We are doing all this first in case we can't find a matching function.
202569 for (const auto &col_idx : join_op.left_projection_map) {
202570 const auto col_type = join_op.types[col_idx];
202571 aggr_types.emplace_back(col_type);
202572
202573 vector<unique_ptr<Expression>> aggr_children;
202574 auto col_ref = make_uniq<BoundReferenceExpression>(col_type, col_idx);
202575 aggr_children.push_back(std::move(col_ref));
202576 auto comp_expr = make_uniq<BoundReferenceExpression>(comp_types.back(), comp_types.size() - 1);
202577 aggr_children.push_back(std::move(comp_expr));
202578 vector<LogicalType> child_types;
202579 for (const auto &child : aggr_children) {
202580 child_types.emplace_back(child->return_type);
202581 }
202582
202583 auto &func = arg_min_max_entry;
202584 ErrorData error;
202585 auto best_function = function_binder.BindFunction(func.name, func.functions, child_types, error);
202586 if (!best_function.IsValid()) {
202587 return nullptr;
202588 }
202589 auto bound_function = func.functions.GetFunctionByOffset(best_function.GetIndex());
202590 auto aggr_expr = function_binder.BindAggregateFunction(bound_function, std::move(aggr_children), nullptr,
202591 AggregateType::NON_DISTINCT);
202592 D_ASSERT(col_type == aggr_expr->return_type);
202593 aggregates.emplace_back(std::move(aggr_expr));
202594 }
202595
202596 // Add a synthetic primary integer key to the probe relation using streaming windowing.
202597 vector<unique_ptr<Expression>> window_select;
202598 auto pk = make_uniq<BoundWindowExpression>(ExpressionType::WINDOW_ROW_NUMBER, pk_type, nullptr, nullptr);
202599 pk->start = WindowBoundary::UNBOUNDED_PRECEDING;
202600 pk->end = WindowBoundary::CURRENT_ROW_ROWS;
202601 pk->alias = "row_number";
202602 window_select.emplace_back(std::move(pk));
202603
202604 auto window_types = probe.GetTypes();
202605 window_types.emplace_back(pk_type);
202606
202607 const auto probe_cardinality = op.EstimateCardinality(context);
202608 auto &window = Make<PhysicalStreamingWindow>(window_types, std::move(window_select), probe_cardinality);
202609 window.children.emplace_back(probe);
202610
202611 auto &join = Make<PhysicalNestedLoopJoin>(join_op, build, window, std::move(join_op.conditions), join_op.join_type,
202612 probe_cardinality);
202613
202614 // Plan a projection of the compare column
202615 auto &comp_proj = Make<PhysicalProjection>(std::move(comp_types), std::move(comp_list), probe_cardinality);
202616 comp_proj.children.emplace_back(join);
202617
202618 // Plan an aggregation on the output of the join, grouping by key;
202619 // TODO: Can we make it perfect?
202620 // Note that the NLJ produced all fields, but only the projected ones were aggregated
202621 vector<unique_ptr<Expression>> groups;
202622 auto pk_ref = make_uniq<BoundReferenceExpression>(pk_type, join_op.types.size() - 1);
202623 groups.emplace_back(std::move(pk_ref));
202624
202625 auto &aggr =
202626 Make<PhysicalHashAggregate>(context, aggr_types, std::move(aggregates), std::move(groups), probe_cardinality);
202627 aggr.children.emplace_back(comp_proj);
202628
202629 // Project away primary/grouping key
202630 // The aggregates were generated in the output order of the original ASOF,
202631 // so we just have to shift away the pk
202632 vector<unique_ptr<Expression>> project_list;
202633 for (column_t i = 1; i < aggr.GetTypes().size(); ++i) {
202634 auto col_ref = make_uniq<BoundReferenceExpression>(aggr.GetTypes()[i], i);
202635 project_list.emplace_back(std::move(col_ref));
202636 }
202637
202638 auto &proj = Make<PhysicalProjection>(op.types, std::move(project_list), probe_cardinality);
202639 proj.children.emplace_back(aggr);
202640 return proj;
202641}
GOpaque< Size > size(const GMat &src)
JoinType InverseJoinType(JoinType type)
Gets the inverse JoinType, e.g., LEFT -> RIGHT.
Definition duckdb.cpp:68436
ExpressionType FlipComparisonExpression(ExpressionType type)
Flip a comparison expression, turning e.g. < into >, or = into =.
Definition duckdb.cpp:68052

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