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

PhysicalHashJoin represents a hash loop join between two tables. More...

Inheritance diagram for duckdb::PhysicalHashJoin:
Collaboration diagram for duckdb::PhysicalHashJoin:

Classes

struct  JoinProjectionColumns

Public Member Functions

 PhysicalHashJoin (PhysicalPlan &physical_plan, LogicalOperator &op, PhysicalOperator &left, PhysicalOperator &right, vector< JoinCondition > cond, JoinType join_type, const vector< idx_t > &left_projection_map, const vector< idx_t > &right_projection_map, vector< LogicalType > delim_types, idx_t estimated_cardinality, unique_ptr< JoinFilterPushdownInfo > pushdown_info)
 PhysicalHashJoin (PhysicalPlan &physical_plan, LogicalOperator &op, PhysicalOperator &left, PhysicalOperator &right, vector< JoinCondition > cond, JoinType join_type, idx_t estimated_cardinality)
unique_ptr< JoinHashTable > InitializeHashTable (ClientContext &context) const
 Initialize HT for this operator.
InsertionOrderPreservingMap< string > ParamsToString () const override
unique_ptr< OperatorState > GetOperatorState (ExecutionContext &context) const override
bool ParallelOperator () const override
unique_ptr< GlobalSinkState > GetGlobalSinkState (ClientContext &context) const override
unique_ptr< LocalSinkState > GetLocalSinkState (ExecutionContext &context) const override
SinkResultType Sink (ExecutionContext &context, DataChunk &chunk, OperatorSinkInput &input) const override
SinkCombineResultType Combine (ExecutionContext &context, OperatorSinkCombineInput &input) const override
void PrepareFinalize (ClientContext &context, GlobalSinkState &global_state) const override
SinkFinalizeType Finalize (Pipeline &pipeline, Event &event, ClientContext &context, OperatorSinkFinalizeInput &input) const override
bool IsSink () const override
bool ParallelSink () const override
Public Member Functions inherited from duckdb::PhysicalComparisonJoin
 PhysicalComparisonJoin (PhysicalPlan &physical_plan, LogicalOperator &op, PhysicalOperatorType type, vector< JoinCondition > cond, JoinType join_type, idx_t estimated_cardinality)
Public Member Functions inherited from duckdb::PhysicalJoin
 PhysicalJoin (PhysicalPlan &physical_plan, LogicalOperator &op, PhysicalOperatorType type, JoinType join_type, idx_t estimated_cardinality)
bool EmptyResultIfRHSIsEmpty () const
void BuildPipelines (Pipeline &current, MetaPipeline &meta_pipeline) override
vector< const_reference< PhysicalOperator > > GetSources () const override
OrderPreservationType SourceOrder () const override
 The type of order emitted by the operator (as a source).
OrderPreservationType OperatorOrder () const override
 The influence the operator has on order (insertion order means no influence).
bool SinkOrderDependent () const override
Public Member Functions inherited from duckdb::CachingPhysicalOperator
 CachingPhysicalOperator (PhysicalPlan &physical_plan, PhysicalOperatorType type, vector< LogicalType > types, idx_t estimated_cardinality)
OperatorResultType Execute (ExecutionContext &context, DataChunk &input, DataChunk &chunk, GlobalOperatorState &gstate, OperatorState &state) const final
OperatorFinalizeResultType FinalExecute (ExecutionContext &context, DataChunk &chunk, GlobalOperatorState &gstate, OperatorState &state) const final
bool RequiresFinalExecute () const final
Public Member Functions inherited from duckdb::PhysicalOperator
 PhysicalOperator (PhysicalPlan &physical_plan, PhysicalOperatorType type, vector< LogicalType > types, idx_t estimated_cardinality)
 PhysicalOperator (const PhysicalOperator &other)=delete
 Deleted copy constructors.
PhysicalOperator & operator= (const PhysicalOperator &)=delete
virtual string GetName () const
virtual string ToString (ExplainFormat format=ExplainFormat::DEFAULT) const
void Print () const
virtual vector< const_reference< PhysicalOperator > > GetChildren () const
const vector< LogicalType > & GetTypes () const
 Return a vector of the types that will be returned by this operator.
virtual bool Equals (const PhysicalOperator &other) const
idx_t EstimatedThreadCount () const
 Functions to help decide how to set up pipeline dependencies.
bool CanSaturateThreads (ClientContext &context) const
virtual void Verify ()
virtual unique_ptr< GlobalOperatorState > GetGlobalOperatorState (ClientContext &context) const
virtual OperatorFinalResultType OperatorFinalize (Pipeline &pipeline, Event &event, ClientContext &context, OperatorFinalizeInput &input) const
virtual bool RequiresOperatorFinalize () const
SourceResultType GetData (ExecutionContext &context, DataChunk &chunk, OperatorSourceInput &input) const
virtual OperatorPartitionData GetPartitionData (ExecutionContext &context, DataChunk &chunk, GlobalSourceState &gstate, LocalSourceState &lstate, const OperatorPartitionInfo &partition_info) const
virtual bool SupportsPartitioning (const OperatorPartitionInfo &partition_info) const
virtual ProgressData GetSinkProgress (ClientContext &context, GlobalSinkState &gstate, const ProgressData source_progress) const
 Returns the current progress percentage, or a negative value if progress bars are not supported.
virtual InsertionOrderPreservingMap< string > ExtraSourceParams (GlobalSourceState &gstate, LocalSourceState &lstate) const
virtual SinkNextBatchType NextBatch (ExecutionContext &context, OperatorSinkNextBatchInput &input) const
virtual OperatorPartitionInfo RequiredPartitionInfo () const
bool AllSourcesSupportBatchIndex () const
template<class TARGET>
TARGET & Cast ()
template<class TARGET>
const TARGET & Cast () const

Public Attributes

vector< LogicalType > condition_types
 The types of the join keys.
JoinProjectionColumns payload_columns
 The indices/types of the payload columns.
JoinProjectionColumns lhs_output_columns
 The indices/types of the lhs columns that need to be output.
JoinProjectionColumns rhs_output_columns
 The indices/types of the rhs columns that need to be output.
vector< LogicalType > delim_types
 Duplicate eliminated types; only used for delim_joins (i.e. correlated subqueries).
vector< unique_ptr< BaseStatistics > > join_stats
 Join Keys statistics (optional).
Public Attributes inherited from duckdb::PhysicalComparisonJoin
vector< JoinCondition > conditions
unique_ptr< JoinFilterPushdownInfo > filter_pushdown
 Scans where we should push generated filters into (if any).
Public Attributes inherited from duckdb::PhysicalJoin
JoinType join_type
Public Attributes inherited from duckdb::CachingPhysicalOperator
bool caching_supported
Public Attributes inherited from duckdb::PhysicalOperator
ArenaLinkedList< reference< PhysicalOperator > > children
 The child operators.
PhysicalOperatorType type
 The physical operator type.
vector< LogicalType > types
 The return types.
idx_t estimated_cardinality
 The estimated cardinality.
unique_ptr< GlobalSinkState > sink_state
 The global sink state.
unique_ptr< GlobalOperatorState > op_state
 The global operator state.
mutex lock
 Lock for (re)setting any of the operator states.

Static Public Attributes

static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::HASH_JOIN
Static Public Attributes inherited from duckdb::PhysicalJoin
static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::INVALID
Static Public Attributes inherited from duckdb::CachingPhysicalOperator
static constexpr const idx_t CACHE_THRESHOLD = 64
Static Public Attributes inherited from duckdb::PhysicalOperator
static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::INVALID

Protected Member Functions

OperatorResultType ExecuteInternal (ExecutionContext &context, DataChunk &input, DataChunk &chunk, GlobalOperatorState &gstate, OperatorState &state) const override
 Child classes need to implement the ExecuteInternal method instead of the Execute.
unique_ptr< GlobalSourceState > GetGlobalSourceState (ClientContext &context) const override
unique_ptr< LocalSourceState > GetLocalSourceState (ExecutionContext &context, GlobalSourceState &gstate) const override
SourceResultType GetDataInternal (ExecutionContext &context, DataChunk &chunk, OperatorSourceInput &input) const override
ProgressData GetProgress (ClientContext &context, GlobalSourceState &gstate) const override
 Returns the current progress percentage, or a negative value if progress bars are not supported.
bool IsSource () const override
 Becomes a source when it is an external join.
bool ParallelSource () const override

Additional Inherited Members

Static Public Member Functions inherited from duckdb::PhysicalComparisonJoin
static void ReorderConditions (vector< JoinCondition > &conditions)
 Re-order join conditions so that equality predicates are first, followed by other predicates.
static void ConstructEmptyJoinResult (JoinType type, bool has_null, DataChunk &input, DataChunk &result)
 Construct the join result of a join with an empty RHS.
static void ConstructFullOuterJoinResult (bool *found_match, ColumnDataCollection &input, DataChunk &result, ColumnDataScanState &scan_state)
 Construct the remainder of a Full Outer Join based on which tuples in the RHS found no match.
Static Public Member Functions inherited from duckdb::PhysicalJoin
static bool HasNullValues (DataChunk &chunk)
static void ConstructSemiJoinResult (DataChunk &left, DataChunk &result, bool found_match[])
static void ConstructAntiJoinResult (DataChunk &left, DataChunk &result, bool found_match[])
static void ConstructMarkJoinResult (DataChunk &join_keys, DataChunk &left, DataChunk &result, bool found_match[], bool has_null)
static void BuildJoinPipelines (Pipeline &current, MetaPipeline &meta_pipeline, PhysicalOperator &op, bool build_rhs=true)
Static Public Member Functions inherited from duckdb::PhysicalOperator
static void SetEstimatedCardinality (InsertionOrderPreservingMap< string > &result, idx_t estimated_cardinality)
static idx_t GetMaxThreadMemory (ClientContext &context)
 The maximum amount of memory the operator should use per thread.
static OperatorCachingMode SelectOperatorCachingMode (ExecutionContext &context)
 Whether operator caching is allowed in the current execution context.

Detailed Description

PhysicalHashJoin represents a hash loop join between two tables.

Constructor & Destructor Documentation

◆ PhysicalHashJoin() [1/2]

duckdb::PhysicalHashJoin::PhysicalHashJoin ( PhysicalPlan & physical_plan,
LogicalOperator & op,
PhysicalOperator & left,
PhysicalOperator & right,
vector< JoinCondition > cond,
JoinType join_type,
const vector< idx_t > & left_projection_map,
const vector< idx_t > & right_projection_map,
vector< LogicalType > delim_types,
idx_t estimated_cardinality,
unique_ptr< JoinFilterPushdownInfo > pushdown_info )
184248 : PhysicalComparisonJoin(physical_plan, op, PhysicalOperatorType::HASH_JOIN, std::move(cond), join_type,
184250 delim_types(std::move(delim_types)) {
184251 filter_pushdown = std::move(pushdown_info_p);
184252
184253 children.push_back(left);
184254 children.push_back(right);
184255
184256 // Collect condition types, and which conditions are just references (so we won't duplicate them in the payload)
184257 unordered_map<idx_t, idx_t> build_columns_in_conditions;
184258 for (idx_t cond_idx = 0; cond_idx < conditions.size(); cond_idx++) {
184259 auto &condition = conditions[cond_idx];
184260 condition_types.push_back(condition.left->return_type);
184261 if (condition.right->GetExpressionClass() == ExpressionClass::BOUND_REF) {
184262 build_columns_in_conditions.emplace(condition.right->Cast<BoundReferenceExpression>().index, cond_idx);
184263 }
184264 }
184265
184266 auto &lhs_input_types = children[0].get().GetTypes();
184267
184268 // Create a projection map for the LHS (if it was empty), for convenience
184269 lhs_output_columns.col_idxs = left_projection_map;
184270 if (lhs_output_columns.col_idxs.empty()) {
184271 lhs_output_columns.col_idxs.reserve(lhs_input_types.size());
184272 for (idx_t i = 0; i < lhs_input_types.size(); i++) {
184273 lhs_output_columns.col_idxs.emplace_back(i);
184274 }
184275 }
184276
184277 for (auto &lhs_col : lhs_output_columns.col_idxs) {
184278 auto &lhs_col_type = lhs_input_types[lhs_col];
184279 lhs_output_columns.col_types.push_back(lhs_col_type);
184280 }
184281
184282 // For ANTI, SEMI and MARK join, we only need to store the keys, so for these the payload/RHS types are empty
184283 if (join_type == JoinType::ANTI || join_type == JoinType::SEMI || join_type == JoinType::MARK) {
184284 return;
184285 }
184286
184287 auto &rhs_input_types = children[1].get().GetTypes();
184288
184289 // Create a projection map for the RHS (if it was empty), for convenience
184290 auto right_projection_map_copy = right_projection_map;
184291 if (right_projection_map_copy.empty()) {
184292 right_projection_map_copy.reserve(rhs_input_types.size());
184293 for (idx_t i = 0; i < rhs_input_types.size(); i++) {
184294 right_projection_map_copy.emplace_back(i);
184295 }
184296 }
184297
184298 // Now fill payload expressions/types and RHS columns/types
184299 for (auto &rhs_col : right_projection_map_copy) {
184300 auto &rhs_col_type = rhs_input_types[rhs_col];
184301
184302 auto it = build_columns_in_conditions.find(rhs_col);
184303 if (it == build_columns_in_conditions.end()) {
184304 // This rhs column is not a join key
184305 payload_columns.col_idxs.push_back(rhs_col);
184306 payload_columns.col_types.push_back(rhs_col_type);
184307 rhs_output_columns.col_idxs.push_back(condition_types.size() + payload_columns.col_types.size() - 1);
184308 } else {
184309 // This rhs column is a join key
184310 rhs_output_columns.col_idxs.push_back(it->second);
184311 }
184312 rhs_output_columns.col_types.push_back(rhs_col_type);
184313 }
184314}
unique_ptr< JoinFilterPushdownInfo > filter_pushdown
Scans where we should push generated filters into (if any).
Definition duckdb.cpp:180824
JoinProjectionColumns payload_columns
The indices/types of the payload columns.
Definition duckdb.cpp:181129
JoinProjectionColumns rhs_output_columns
The indices/types of the rhs columns that need to be output.
Definition duckdb.cpp:181133
JoinProjectionColumns lhs_output_columns
The indices/types of the lhs columns that need to be output.
Definition duckdb.cpp:181131
vector< LogicalType > delim_types
Duplicate eliminated types; only used for delim_joins (i.e. correlated subqueries).
Definition duckdb.cpp:181136
vector< LogicalType > condition_types
The types of the join keys.
Definition duckdb.cpp:181126
idx_t estimated_cardinality
The estimated cardinality.
Definition duckdb.hpp:22154
ArenaLinkedList< reference< PhysicalOperator > > children
The child operators.
Definition duckdb.hpp:22148
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ PhysicalHashJoin() [2/2]

duckdb::PhysicalHashJoin::PhysicalHashJoin ( PhysicalPlan & physical_plan,
LogicalOperator & op,
PhysicalOperator & left,
PhysicalOperator & right,
vector< JoinCondition > cond,
JoinType join_type,
idx_t estimated_cardinality )
184319 : PhysicalHashJoin(physical_plan, op, left, right, std::move(cond), join_type, {}, {}, {}, estimated_cardinality,
184320 nullptr) {
184321}

Member Function Documentation

◆ InitializeHashTable()

unique_ptr< JoinHashTable > duckdb::PhysicalHashJoin::InitializeHashTable ( ClientContext & context) const

Initialize HT for this operator.

184469 {
184470 auto result = make_uniq<JoinHashTable>(context, *this, conditions, payload_columns.col_types, join_type,
184471 rhs_output_columns.col_idxs);
184472 if (!delim_types.empty() && join_type == JoinType::MARK) {
184473 // correlated MARK join
184474 if (delim_types.size() + 1 == conditions.size()) {
184475 // the correlated MARK join has one more condition than the amount of correlated columns
184476 // this is the case in a correlated ANY() expression
184477 // in this case we need to keep track of additional entries, namely:
184478 // - (1) the total amount of elements per group
184479 // - (2) the amount of non-null elements per group
184480 // we need these to correctly deal with the cases of either:
184481 // - (1) the group being empty [in which case the result is always false, even if the comparison is NULL]
184482 // - (2) the group containing a NULL value [in which case FALSE becomes NULL]
184483 auto &info = result->correlated_mark_join_info;
184484
184485 vector<LogicalType> delim_payload_types;
184486 vector<BoundAggregateExpression *> correlated_aggregates;
184487 unique_ptr<BoundAggregateExpression> aggr;
184488
184489 // jury-rigging the GroupedAggregateHashTable
184490 // we need a count_star and a count to get counts with and without NULLs
184491
184492 FunctionBinder function_binder(context);
184493 aggr = function_binder.BindAggregateFunction(CountStarFun::GetFunction(), {}, nullptr,
184494 AggregateType::NON_DISTINCT);
184495 correlated_aggregates.push_back(&*aggr);
184496 delim_payload_types.push_back(aggr->return_type);
184497 info.correlated_aggregates.push_back(std::move(aggr));
184498
184499 auto count_fun = CountFunctionBase::GetFunction();
184500 vector<unique_ptr<Expression>> children;
184501 // this is a dummy but we need it to make the hash table understand whats going on
184502 children.push_back(make_uniq_base<Expression, BoundReferenceExpression>(count_fun.GetReturnType(), 0U));
184503 aggr = function_binder.BindAggregateFunction(count_fun, std::move(children), nullptr,
184504 AggregateType::NON_DISTINCT);
184505 correlated_aggregates.push_back(&*aggr);
184506 delim_payload_types.push_back(aggr->return_type);
184507 info.correlated_aggregates.push_back(std::move(aggr));
184508
184509 auto &allocator = BufferAllocator::Get(context);
184510 info.correlated_counts = make_uniq<GroupedAggregateHashTable>(context, allocator, delim_types,
184511 delim_payload_types, correlated_aggregates);
184512 info.correlated_types = delim_types;
184513 info.group_chunk.Initialize(allocator, delim_types);
184514 info.result_chunk.Initialize(allocator, delim_payload_types);
184515 }
184516 }
184517 return result;
184518}

◆ ParamsToString()

InsertionOrderPreservingMap< string > duckdb::PhysicalHashJoin::ParamsToString ( ) const
overridevirtual

Reimplemented from duckdb::PhysicalComparisonJoin.

185814 {
185815 InsertionOrderPreservingMap<string> result;
185816 result["Join Type"] = EnumUtil::ToString(join_type);
185817
185818 string condition_info;
185819 for (idx_t i = 0; i < conditions.size(); i++) {
185820 auto &join_condition = conditions[i];
185821 if (i > 0) {
185822 condition_info += "\n";
185823 }
185824 condition_info +=
185825 StringUtil::Format("%s %s %s", join_condition.left->GetName(),
185826 ExpressionTypeToOperator(join_condition.comparison), join_condition.right->GetName());
185827 }
185828 result["Conditions"] = condition_info;
185829
185830 SetEstimatedCardinality(result, estimated_cardinality);
185831 return result;
185832}
static string Format(const string fmt_str, ARGS... params)
Format a string using printf semantics.
Definition duckdb.hpp:4002

◆ GetOperatorState()

unique_ptr< OperatorState > duckdb::PhysicalHashJoin::GetOperatorState ( ExecutionContext & context) const
overridevirtual

Reimplemented from duckdb::PhysicalOperator.

185254 {
185255 auto &allocator = BufferAllocator::Get(context.client);
185256 auto &sink = sink_state->Cast<HashJoinGlobalSinkState>();
185257 auto state = make_uniq<HashJoinOperatorState>(context.client, sink);
185258 state->lhs_join_keys.Initialize(allocator, condition_types);
185259 if (!lhs_output_columns.col_types.empty()) {
185260 state->lhs_output.Initialize(allocator, lhs_output_columns.col_types);
185261 }
185262 if (sink.perfect_join_executor) {
185263 state->perfect_hash_join_state = sink.perfect_join_executor->GetOperatorState(context);
185264 } else {
185265 for (auto &cond : conditions) {
185266 state->probe_executor.AddExpression(*cond.left);
185267 }
185269 }
185270 if (sink.external) {
185271 state->spill_chunk.Initialize(allocator, sink.probe_types);
185272 sink.InitializeProbeSpill();
185273 }
185274
185275 return std::move(state);
185276}
unique_ptr< GlobalSinkState > sink_state
The global sink state.
Definition duckdb.hpp:22157
void InitializeChunkState(TupleDataChunkState &chunk_state, vector< column_t > column_ids={})
Definition duckdb.cpp:125879

◆ ParallelOperator()

bool duckdb::PhysicalHashJoin::ParallelOperator ( ) const
inlineoverridevirtual

Reimplemented from duckdb::PhysicalOperator.

181148 {
181149 return true;
181150 }

◆ ExecuteInternal()

OperatorResultType duckdb::PhysicalHashJoin::ExecuteInternal ( ExecutionContext & context,
DataChunk & input,
DataChunk & chunk,
GlobalOperatorState & gstate,
OperatorState & state ) const
overrideprotectedvirtual

Child classes need to implement the ExecuteInternal method instead of the Execute.

Implements duckdb::CachingPhysicalOperator.

185279 {
185280 auto &state = state_p.Cast<HashJoinOperatorState>();
185281 auto &sink = sink_state->Cast<HashJoinGlobalSinkState>();
185282 D_ASSERT(sink.finalized);
185283 D_ASSERT(!sink.scanned_data);
185284
185285 if (sink.hash_table->Count() == 0) {
185286 if (EmptyResultIfRHSIsEmpty()) {
185287 return OperatorResultType::FINISHED;
185288 }
185289 state.lhs_output.ReferenceColumns(input, lhs_output_columns.col_idxs);
185290 ConstructEmptyJoinResult(sink.hash_table->join_type, sink.hash_table->has_null, state.lhs_output, chunk);
185291 return OperatorResultType::NEED_MORE_INPUT;
185292 }
185293
185294 if (sink.perfect_join_executor) {
185295 D_ASSERT(!sink.external);
185296 state.lhs_output.ReferenceColumns(input, lhs_output_columns.col_idxs);
185297 return sink.perfect_join_executor->ProbePerfectHashTable(context, input, state.lhs_output, chunk,
185298 *state.perfect_hash_join_state);
185299 }
185300
185301 if (sink.external && !state.initialized) {
185302 // some initialization for external hash join
185303 if (!sink.probe_spill) {
185304 sink.InitializeProbeSpill();
185305 }
185306 state.spill_state = sink.probe_spill->RegisterThread();
185307 state.initialized = true;
185308 }
185309
185310 if (state.scan_structure.is_null) {
185311 // probe the HT, start by resolving the join keys for the left chunk
185312 state.lhs_join_keys.Reset();
185313 state.probe_executor.Execute(input, state.lhs_join_keys);
185314
185315 // perform the actual probe
185316 if (sink.external) {
185317 sink.hash_table->ProbeAndSpill(state.scan_structure, state.lhs_join_keys, state.join_key_state,
185318 state.probe_state, input, *sink.probe_spill, state.spill_state,
185319 state.spill_chunk);
185320 } else {
185321 sink.hash_table->Probe(state.scan_structure, state.lhs_join_keys, state.join_key_state, state.probe_state);
185322 }
185323 }
185324
185325 state.lhs_output.ReferenceColumns(input, lhs_output_columns.col_idxs);
185326 state.scan_structure.Next(state.lhs_join_keys, state.lhs_output, chunk);
185327
185328 if (state.scan_structure.PointersExhausted() && chunk.size() == 0) {
185329 state.scan_structure.is_null = true;
185330 return OperatorResultType::NEED_MORE_INPUT;
185331 }
185332 return OperatorResultType::HAVE_MORE_OUTPUT;
185333}
static void ConstructEmptyJoinResult(JoinType type, bool has_null, DataChunk &input, DataChunk &result)
Construct the join result of a join with an empty RHS.
Definition duckdb.cpp:183858
Here is the call graph for this function:

◆ GetGlobalSourceState()

unique_ptr< GlobalSourceState > duckdb::PhysicalHashJoin::GetGlobalSourceState ( ClientContext & context) const
overrideprotectedvirtual

Reimplemented from duckdb::PhysicalOperator.

185444 {
185445 return make_uniq<HashJoinGlobalSourceState>(*this, context);
185446}

◆ GetLocalSourceState()

unique_ptr< LocalSourceState > duckdb::PhysicalHashJoin::GetLocalSourceState ( ExecutionContext & context,
GlobalSourceState & gstate ) const
overrideprotectedvirtual

Reimplemented from duckdb::PhysicalOperator.

185449 {
185450 return make_uniq<HashJoinLocalSourceState>(*this, sink_state->Cast<HashJoinGlobalSinkState>(),
185451 BufferAllocator::Get(context.client));
185452}

◆ GetDataInternal()

SourceResultType duckdb::PhysicalHashJoin::GetDataInternal ( ExecutionContext & context,
DataChunk & chunk,
OperatorSourceInput & input ) const
overrideprotectedvirtual

Reimplemented from duckdb::PhysicalOperator.

185739 {
185740 auto &sink = sink_state->Cast<HashJoinGlobalSinkState>();
185741 auto &gstate = input.global_state.Cast<HashJoinGlobalSourceState>();
185742 auto &lstate = input.local_state.Cast<HashJoinLocalSourceState>();
185743 sink.scanned_data = true;
185744
185745 if (!sink.external && !PropagatesBuildSide(join_type)) {
185746 auto guard = gstate.Lock();
185747 if (gstate.global_stage != HashJoinSourceStage::DONE) {
185748 gstate.global_stage = HashJoinSourceStage::DONE;
185749 sink.hash_table->Reset();
185750 sink.temporary_memory_state->SetZero();
185751 }
185752 return SourceResultType::FINISHED;
185753 }
185754
185755 if (gstate.global_stage == HashJoinSourceStage::INIT) {
185756 gstate.Initialize(sink);
185757 }
185758
185759 // Any call to GetData must produce tuples, otherwise the pipeline executor thinks that we're done
185760 // Therefore, we loop until we've produced tuples, or until the operator is actually done
185761 while (gstate.global_stage != HashJoinSourceStage::DONE && chunk.size() == 0) {
185762 if (!lstate.TaskFinished() || gstate.AssignTask(sink, lstate)) {
185763 lstate.ExecuteTask(sink, gstate, chunk);
185764 } else {
185765 auto guard = gstate.Lock();
185766 if (gstate.TryPrepareNextStage(sink) || gstate.global_stage == HashJoinSourceStage::DONE) {
185767 gstate.UnblockTasks(guard);
185768 } else {
185769 return gstate.BlockSource(guard, input.interrupt_state);
185770 }
185771 }
185772 }
185773
185774 return chunk.size() == 0 ? SourceResultType::FINISHED : SourceResultType::HAVE_MORE_OUTPUT;
185775}
bool PropagatesBuildSide(JoinType type)
Whether the build side is propagated out of the join.
Definition duckdb.cpp:68427

◆ GetProgress()

ProgressData duckdb::PhysicalHashJoin::GetProgress ( ClientContext & context,
GlobalSourceState & gstate ) const
overrideprotectedvirtual

Returns the current progress percentage, or a negative value if progress bars are not supported.

Reimplemented from duckdb::PhysicalOperator.

185777 {
185778 auto &sink = sink_state->Cast<HashJoinGlobalSinkState>();
185779 auto &gstate = gstate_p.Cast<HashJoinGlobalSourceState>();
185780
185781 ProgressData res;
185782
185783 if (!sink.external) {
185784 if (PropagatesBuildSide(join_type)) {
185785 res.done = static_cast<double>(gstate.full_outer_chunk_done);
185786 res.total = static_cast<double>(gstate.full_outer_chunk_count);
185787 return res;
185788 }
185789 res.done = 0.0;
185790 res.total = 1.0;
185791 return res;
185792 }
185793
185794 const auto &ht = *sink.hash_table;
185795 const auto num_partitions = static_cast<double>(RadixPartitioning::NumberOfPartitions(ht.GetRadixBits()));
185796
185797 res.done = static_cast<double>(ht.FinishedPartitionCount());
185798 res.total = num_partitions;
185799
185800 const auto probe_chunk_done = static_cast<double>(gstate.probe_chunk_done);
185801 const auto probe_chunk_count = static_cast<double>(gstate.probe_chunk_count);
185802 if (probe_chunk_count != 0) {
185803 // Progress of the current round of probing
185804 auto probe_progress = probe_chunk_done / probe_chunk_count;
185805 // Weighed by the number of partitions
185806 probe_progress *= static_cast<double>(ht.CurrentPartitionCount());
185807 // Add it to the progress
185808 res.done += probe_progress;
185809 }
185810
185811 return res;
185812}
static constexpr idx_t NumberOfPartitions(idx_t radix_bits)
The number of partitions for a given number of radix bits.
Definition duckdb.cpp:93425
Here is the call graph for this function:

◆ IsSource()

bool duckdb::PhysicalHashJoin::IsSource ( ) const
inlineoverrideprotectedvirtual

Becomes a source when it is an external join.

Reimplemented from duckdb::PhysicalOperator.

181167 {
181168 return true;
181169 }

◆ ParallelSource()

bool duckdb::PhysicalHashJoin::ParallelSource ( ) const
inlineoverrideprotectedvirtual

Reimplemented from duckdb::PhysicalOperator.

181171 {
181172 return true;
181173 }

◆ GetGlobalSinkState()

unique_ptr< GlobalSinkState > duckdb::PhysicalHashJoin::GetGlobalSinkState ( ClientContext & context) const
overridevirtual

Reimplemented from duckdb::PhysicalOperator.

184520 {
184521 return make_uniq<HashJoinGlobalSinkState>(*this, context);
184522}

◆ GetLocalSinkState()

unique_ptr< LocalSinkState > duckdb::PhysicalHashJoin::GetLocalSinkState ( ExecutionContext & context) const
overridevirtual

Reimplemented from duckdb::PhysicalOperator.

184524 {
184525 auto &gstate = sink_state->Cast<HashJoinGlobalSinkState>();
184526 return make_uniq<HashJoinLocalSinkState>(*this, context.client, gstate);
184527}

◆ Sink()

SinkResultType duckdb::PhysicalHashJoin::Sink ( ExecutionContext & context,
DataChunk & chunk,
OperatorSinkInput & input ) const
overridevirtual

The sink method is called constantly with new input, as long as new input is available. Note that this method CAN be called in parallel, proper locking is needed when accessing dat a inside the GlobalSinkState.

Reimplemented from duckdb::PhysicalOperator.

184540 {
184541 auto &gstate = input.global_state.Cast<HashJoinGlobalSinkState>();
184542 auto &lstate = input.local_state.Cast<HashJoinLocalSinkState>();
184543
184544 // resolve the join keys for the right chunk
184545 lstate.join_keys.Reset();
184546 lstate.join_key_executor.Execute(chunk, lstate.join_keys);
184547
184548 if (filter_pushdown && !gstate.skip_filter_pushdown) {
184549 filter_pushdown->Sink(lstate.join_keys, *lstate.local_filter_state);
184550 }
184551
184552 if (payload_columns.col_types.empty()) { // there are only keys: place an empty chunk in the payload
184553 lstate.payload_chunk.SetCardinality(chunk.size());
184554 } else { // there are payload columns
184555 lstate.payload_chunk.ReferenceColumns(chunk, payload_columns.col_idxs);
184556 }
184557
184558 // build the HT
184559 lstate.hash_table->Build(lstate.append_state, lstate.join_keys, lstate.payload_chunk);
184560
184561 return SinkResultType::NEED_MORE_INPUT;
184562}

◆ Combine()

SinkCombineResultType duckdb::PhysicalHashJoin::Combine ( ExecutionContext & context,
OperatorSinkCombineInput & input ) const
overridevirtual

The combine is called when a single thread has completed execution of its part of the pipeline, it is the final time that a specific LocalSinkState is accessible. This method can be called in parallel while other Sink() or Combine() calls are active on the same GlobalSinkState.

Reimplemented from duckdb::PhysicalOperator.

184568 {
184569 auto &gstate = input.global_state.Cast<HashJoinGlobalSinkState>();
184570 auto &lstate = input.local_state.Cast<HashJoinLocalSinkState>();
184571
184572 lstate.hash_table->GetSinkCollection().FlushAppendState(lstate.append_state);
184573 auto guard = gstate.Lock();
184574 gstate.local_hash_tables.push_back(std::move(lstate.hash_table));
184575 if (gstate.local_hash_tables.size() == gstate.active_local_states) {
184576 // Set to 0 until PrepareFinalize
184577 gstate.temporary_memory_state->SetZero();
184578 }
184579
184580 auto &client_profiler = QueryProfiler::Get(context.client);
184581 context.thread.profiler.Flush(*this);
184582 client_profiler.Flush(context.thread.profiler);
184583 if (filter_pushdown && !gstate.skip_filter_pushdown) {
184584 filter_pushdown->Combine(*gstate.global_filter_state, *lstate.local_filter_state);
184585 }
184586
184587 return SinkCombineResultType::FINISHED;
184588}

◆ PrepareFinalize()

void duckdb::PhysicalHashJoin::PrepareFinalize ( ClientContext & context,
GlobalSinkState & sink_state ) const
overridevirtual

(optional) function that will be called before Finalize For now, its only use is to to communicate memory usage in multi-join pipelines through TemporaryMemoryManager

Reimplemented from duckdb::PhysicalOperator.

184659 {
184660 auto &gstate = global_state.Cast<HashJoinGlobalSinkState>();
184661 const auto &ht = *gstate.hash_table;
184662
184663 gstate.total_size =
184664 ht.GetTotalSize(gstate.local_hash_tables, gstate.max_partition_size, gstate.max_partition_count);
184665 gstate.probe_side_requirement =
184666 GetPartitioningSpaceRequirement(context, children[0].get().GetTypes(), ht.GetRadixBits(), gstate.num_threads);
184667 const auto max_partition_ht_size =
184668 gstate.max_partition_size + gstate.hash_table->PointerTableSize(gstate.max_partition_count);
184669 gstate.temporary_memory_state->SetMinimumReservation(max_partition_ht_size + gstate.probe_side_requirement);
184670
184671 bool all_constant;
184672 gstate.temporary_memory_state->SetMaterializationPenalty(GetTupleWidth(children[0].get().GetTypes(), all_constant));
184673 gstate.temporary_memory_state->SetRemainingSize(gstate.total_size);
184674}
const vector< LogicalType > & GetTypes() const
Return a vector of the types that will be returned by this operator.
Definition duckdb.hpp:22174
__host__ cudaTextureObject_t get() const noexcept
Here is the call graph for this function:

◆ Finalize()

SinkFinalizeType duckdb::PhysicalHashJoin::Finalize ( Pipeline & pipeline,
Event & event,
ClientContext & context,
OperatorSinkFinalizeInput & input ) const
overridevirtual

The finalize is called when ALL threads are finished execution. It is called only once per pipeline, and is entirely single threaded. If Finalize returns SinkResultType::Finished, the sink is marked as finished

Reimplemented from duckdb::PhysicalOperator.

185120 {
185121 auto &sink = input.global_state.Cast<HashJoinGlobalSinkState>();
185122 auto &ht = *sink.hash_table;
185123
185124 sink.temporary_memory_state->UpdateReservation(context);
185125 sink.external = sink.temporary_memory_state->GetReservation() < sink.total_size;
185126 if (sink.external) {
185127 // For external join we reduce the load factor, this may even prevent the external join altogether
185128 ht.load_factor = JoinHashTable::EXTERNAL_LOAD_FACTOR;
185129
185130 idx_t temp_max_partition_size;
185131 idx_t temp_max_partition_count;
185132 idx_t temp_total_size =
185133 ht.GetTotalSize(sink.local_hash_tables, temp_max_partition_size, temp_max_partition_count);
185134
185135 if (temp_total_size < sink.temporary_memory_state->GetReservation()) {
185136 // We prevented the external join by reducing the load factor. Update the state accordingly
185137 sink.temporary_memory_state->SetMinimumReservation(temp_total_size);
185138 sink.temporary_memory_state->SetRemainingSizeAndUpdateReservation(context, temp_total_size);
185139
185140 sink.total_size = temp_total_size;
185141 sink.max_partition_size = temp_max_partition_size;
185142 sink.max_partition_count = temp_max_partition_count;
185143
185144 sink.external = false;
185145 }
185146 }
185147 DUCKDB_LOG(context, PhysicalOperatorLogType, *this, "PhysicalHashJoin", "Finalize",
185148 {{"external", to_string(sink.external)}});
185149 if (sink.external) {
185150 // External Hash Join
185151 sink.perfect_join_executor.reset();
185152
185153 const auto max_partition_ht_size = sink.max_partition_size + ht.PointerTableSize(sink.max_partition_count);
185154 const auto very_very_skewed = // No point in repartitioning if it's this skewed
185155 static_cast<double>(max_partition_ht_size) >= 0.8 * static_cast<double>(sink.total_size);
185156 if (!very_very_skewed &&
185157 (max_partition_ht_size + sink.probe_side_requirement) > sink.temporary_memory_state->GetReservation()) {
185158 // We have to repartition
185159 const auto radix_bits_before = ht.GetRadixBits();
185160 ht.SetRepartitionRadixBits(sink.temporary_memory_state->GetReservation(), sink.max_partition_size,
185161 sink.max_partition_count);
185162 DUCKDB_LOG(context, PhysicalOperatorLogType, *this, "PhysicalHashJoin", "Repartition",
185163 {{"partitions_before", to_string(RadixPartitioning::NumberOfPartitions(radix_bits_before))},
185164 {"partitions_after", to_string(RadixPartitioning::NumberOfPartitions(ht.GetRadixBits()))}});
185165 auto new_event = make_shared_ptr<HashJoinRepartitionEvent>(pipeline, *this, sink, sink.local_hash_tables);
185166 event.InsertEvent(std::move(new_event));
185167 } else {
185168 // No repartitioning!
185169 for (auto &local_ht : sink.local_hash_tables) {
185170 ht.Merge(*local_ht);
185171 }
185172 sink.local_hash_tables.clear();
185173 D_ASSERT(sink.temporary_memory_state->GetReservation() >= sink.probe_side_requirement);
185174 sink.hash_table->PrepareExternalFinalize(sink.temporary_memory_state->GetReservation() -
185175 sink.probe_side_requirement);
185176 sink.ScheduleFinalize(pipeline, event);
185177 }
185178 sink.finalized = true;
185179 return SinkFinalizeType::READY;
185180 }
185181
185182 // In-memory Hash Join
185183 for (auto &local_ht : sink.local_hash_tables) {
185184 ht.Merge(*local_ht);
185185 }
185186 sink.local_hash_tables.clear();
185187 ht.Unpartition();
185188
185189 Value min;
185190 Value max;
185191 unique_ptr<DataChunk> filter_min_max = nullptr;
185192
185193 if (filter_pushdown && !sink.skip_filter_pushdown && ht.Count() > 0) {
185194 filter_min_max = filter_pushdown->FinalizeMinMax(*sink.global_filter_state);
185195 min = filter_min_max->data[0].GetValue(0);
185196 max = filter_min_max->data[1].GetValue(0);
185197 } else if (TypeIsIntegral(conditions[0].right->return_type.InternalType())) {
185198 min = Value::MinimumValue(conditions[0].right->return_type);
185199 max = Value::MaximumValue(conditions[0].right->return_type);
185200 }
185201
185202 // check for possible perfect hash table
185203 auto use_perfect_hash = sink.perfect_join_executor->CanDoPerfectHashJoin(*this, min, max);
185204 if (use_perfect_hash) {
185205 D_ASSERT(ht.equality_types.size() == 1);
185206 auto key_type = ht.equality_types[0];
185207 use_perfect_hash = sink.perfect_join_executor->BuildPerfectHashTable(key_type);
185208 }
185209
185210 if (filter_min_max) {
185211 filter_pushdown->FinalizeFilters(context, &ht, *this, std::move(filter_min_max), use_perfect_hash);
185212 }
185213
185214 // In case of a large build side or duplicates, use regular hash join
185215 if (!use_perfect_hash) {
185216 sink.perfect_join_executor.reset();
185217 sink.ScheduleFinalize(pipeline, event);
185218 }
185219 sink.finalized = true;
185220 if (ht.Count() == 0 && EmptyResultIfRHSIsEmpty()) {
185221 return SinkFinalizeType::NO_OUTPUT_POSSIBLE;
185222 }
185223 return SinkFinalizeType::READY;
185224}
static constexpr double EXTERNAL_LOAD_FACTOR
For a LOAD_FACTOR of 1.5, the HT is between 33% and 67% full.
Definition duckdb.cpp:157315
static DUCKDB_API Value MinimumValue(const LogicalType &type)
Create the lowest possible value of a given type (numeric only).
Definition duckdb.cpp:131884
static DUCKDB_API Value MaximumValue(const LogicalType &type)
Create the highest possible value of a given type (numeric only).
Definition duckdb.cpp:131980
std::string to_string(const T &value)
Definition duckdb.cpp:19425
static softfloat min()
static softfloat max()
Here is the call graph for this function:

◆ IsSink()

bool duckdb::PhysicalHashJoin::IsSink ( ) const
inlineoverridevirtual

Reimplemented from duckdb::PhysicalOperator.

181186 {
181187 return true;
181188 }

◆ ParallelSink()

bool duckdb::PhysicalHashJoin::ParallelSink ( ) const
inlineoverridevirtual

Reimplemented from duckdb::PhysicalOperator.

181189 {
181190 return true;
181191 }

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