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

JoinHashTable is a linear probing HT that is used for computing joins. More...

Collaboration diagram for duckdb::JoinHashTable:

Classes

struct  ScanStructure
struct  SharedState
struct  ProbeState
struct  InsertState
struct  ProbeSpillLocalAppendState
struct  ProbeSpill

Public Types

using ValidityBytes = TemplatedValidityMask<uint8_t>

Public Member Functions

 JoinHashTable (ClientContext &context, const PhysicalOperator &op, const vector< JoinCondition > &conditions, vector< LogicalType > build_types, JoinType type, const vector< idx_t > &output_columns)
void Build (PartitionedTupleDataAppendState &append_state, DataChunk &keys, DataChunk &input)
 Add the given data to the HT.
void Merge (JoinHashTable &other)
 Merge another HT into this one.
void Unpartition ()
 Combines the partitions in sink_collection into data_collection, as if it were not partitioned.
void AllocatePointerTable ()
 Allocate the pointer table for the probe.
void InitializePointerTable (idx_t entry_idx_from, idx_t entry_idx_to)
 Initialize the pointer table for the probe.
void Finalize (idx_t chunk_idx_from, idx_t chunk_idx_to, bool parallel)
void Probe (ScanStructure &scan_structure, DataChunk &keys, TupleDataChunkState &key_state, ProbeState &probe_state, optional_ptr< Vector > precomputed_hashes=nullptr)
 Probe the HT with the given input chunk, resulting in the given result.
void ScanFullOuter (JoinHTScanState &state, Vector &addresses, DataChunk &result) const
 Scan the HT to construct the full outer join result.
idx_t Count () const
idx_t SizeInBytes () const
PartitionedTupleData & GetSinkCollection ()
TupleDataCollection & GetDataCollection ()
idx_t ScanKeyColumn (Vector &addresses, Vector &result, idx_t column_index) const
bool NullValuesAreEqual (idx_t col_idx) const
idx_t GetRadixBits () const
idx_t PointerTableCapacity (idx_t count) const
 Capacity of the pointer table given the ht count.
idx_t PointerTableSize (idx_t count) const
 Size of the pointer table (in bytes).
void SetBuildBloomFilter (const bool should_build)
BloomFilter & GetBloomFilter ()
idx_t GetTotalSize (const vector< unique_ptr< JoinHashTable > > &local_hts, idx_t &max_partition_size, idx_t &max_partition_count) const
 Get total size of HT if all partitions would be built.
idx_t GetTotalSize (const vector< idx_t > &partition_sizes, const vector< idx_t > &partition_counts, idx_t &max_partition_size, idx_t &max_partition_count) const
idx_t GetRemainingSize () const
 Get the remaining size of the unbuilt partitions.
void SetRepartitionRadixBits (const idx_t max_ht_size, const idx_t max_partition_size, const idx_t max_partition_count)
 Sets number of radix bits according to the max ht size.
void InitializePartitionMasks ()
 Initialized "current_partitions" and "completed_partitions".
idx_t CurrentPartitionCount () const
 How many partitions are currently active.
idx_t FinishedPartitionCount () const
 How many partitions are fully done.
void Repartition (JoinHashTable &global_ht)
 Partition this HT.
void Reset ()
 Delete blocks that belong to the current partitioned HT.
bool PrepareExternalFinalize (const idx_t max_ht_size)
 Build HT for the next partitioned probe round.
void ProbeAndSpill (ScanStructure &scan_structure, DataChunk &probe_keys, TupleDataChunkState &key_state, ProbeState &probe_state, DataChunk &probe_chunk, ProbeSpill &probe_spill, ProbeSpillLocalAppendState &spill_state, DataChunk &spill_chunk)
 Probe whatever we can, sink the rest into a thread-local HT.

Static Public Member Functions

static idx_t FillWithHTOffsets (JoinHTScanState &state, Vector &addresses)
 Fill the pointer with all the addresses from the hashtable for full scan.

Public Attributes

ClientContext & context
const PhysicalOperator & op
BufferManager & buffer_manager
 BufferManager.
const vector< JoinCondition > & conditions
 The join conditions.
vector< LogicalType > equality_types
 The types of the keys used in equality comparison.
vector< LogicalType > condition_types
 The types of the keys.
vector< LogicalType > build_types
 The types of all conditions.
const vector< idx_t > & output_columns
 Positions of the columns that need to output.
vector< ExpressionType > equality_predicates
 The comparison predicates that only contain equality predicates.
vector< ExpressionType > non_equality_predicates
 The comparison predicates that contain non-equality predicates.
vector< column_t > equality_predicate_columns
 The column indices of the equality predicates to be used to compare the rows.
vector< column_t > non_equality_predicate_columns
 The column indices of the non-equality predicates to be used to compare the rows.
shared_ptr< TupleDataLayout > layout_ptr
 Data column layout.
RowMatcher row_matcher_build
unique_ptr< RowMatcher > row_matcher_probe
unique_ptr< RowMatcher > row_matcher_probe_no_match_sel
 Matches the same rows as the row_matcher, but also returns a vector for no matches.
bool needs_chain_matcher
 Is true if there are predicates that are not equality predicates and we need to use the matchers during probing.
bool chains_longer_than_one
 If there is more than one element in the chain, we need to scan the next elements of the chain.
idx_t capacity = DConstants::INVALID_INDEX
 The capacity of the HT. Is the same as hash_map.GetSize() / sizeof(ht_entry_t).
idx_t entry_size
 The size of an entry as stored in the HashTable.
idx_t tuple_size
 The total tuple size.
idx_t pointer_offset
 Next pointer offset in tuple, also used for the position of the hash, which then gets overwritten by the pointer.
Vector vfound
 A constant false column for initialising right outer joins.
JoinType join_type
 The join type of the HT.
bool finalized
 Whether or not the HT has been finalized.
bool has_null
 Whether or not any of the key elements contain NULL.
uint64_t bitmask = DConstants::INVALID_INDEX
 Bitmask for getting relevant bits from the hashes to determine the position.
bool single_join_error_on_multiple_rows = true
 Whether or not we error on multiple rows found per match in a SINGLE join.
bool insert_duplicate_keys = true
 Whether or not to perform deduplication based on join_keys when building ht.
atomic< idx_t > total_probe_matches {0}
 Number of probe matches.
struct { 
   mutex   mj_lock 
   vector< LogicalType >   correlated_types 
   vector< unique_ptr< Expression > >   correlated_aggregates 
 The aggregate expression nodes used by the HT.
   unique_ptr< GroupedAggregateHashTable >   correlated_counts 
 The HT that holds the group counts for every correlated column.
   DataChunk   group_chunk 
 Group chunk used for aggregating into correlated_counts.
   DataChunk   correlated_payload 
 Payload chunk used for aggregating into correlated_counts.
   DataChunk   result_chunk 
 Result chunk used for aggregating into correlated_counts.
} correlated_mark_join_info
double load_factor = DEFAULT_LOAD_FACTOR

Static Public Attributes

static constexpr const idx_t USE_SALT_THRESHOLD = 8192
static constexpr const idx_t INITIAL_RADIX_BITS = 4
static constexpr double DEFAULT_LOAD_FACTOR = 2.0
 For a LOAD_FACTOR of 2.0, the HT is between 25% and 50% full.
static constexpr double EXTERNAL_LOAD_FACTOR = 1.5
 For a LOAD_FACTOR of 1.5, the HT is between 33% and 67% full.
static constexpr idx_t MINIMUM_CAPACITY = 16384
 Minimum capacity of the pointer table.

Private Member Functions

void InitializeScanStructure (ScanStructure &scan_structure, DataChunk &keys, TupleDataChunkState &key_state, const SelectionVector *&current_sel)
void Hash (DataChunk &keys, const SelectionVector &sel, idx_t count, Vector &hashes)
bool UseSalt () const
void GetRowPointers (DataChunk &keys, TupleDataChunkState &key_state, ProbeState &state, Vector &hashes_v, const SelectionVector *sel, idx_t &count, Vector &pointers_result_v, SelectionVector &match_sel, bool has_sel)
void InsertHashes (Vector &hashes_v, idx_t count, TupleDataChunkState &chunk_state, InsertState &insert_statebool, bool parallel)
 Insert the given set of locations into the HT with the given set of hashes_v.
idx_t PrepareKeys (DataChunk &keys, vector< TupleDataVectorFormat > &vector_data, const SelectionVector *&current_sel, SelectionVector &sel, bool build_side)
 Prepares keys by filtering NULLs.
 JoinHashTable (const JoinHashTable &)=delete
 Copying not allowed.

Private Attributes

mutex data_lock
 Lock for combining data_collection when merging HTs.
unique_ptr< PartitionedTupleData > sink_collection
 Partitioned data collection that the data is sunk into when building.
unique_ptr< TupleDataCollection > data_collection
 The DataCollection holding the main data of the hash table.
AllocatedData hash_map
 The hash map of the HT, created after finalization.
ht_entry_t * entries = nullptr
vector< bool > null_values_are_equal
 Whether or not NULL values are considered equal in each of the comparisons.
unsafe_unique_array< data_t > dead_end
 An empty tuple that's a "dead end", can be used to stop chains early.
BloomFilter bloom_filter
 Whether or not to use a bloom filter will be determined by the operator.
bool should_build_bloom_filter = false
idx_t radix_bits
 The current number of radix bits used to partition.
ValidityMask current_partitions
 Bits set to 1 for currently active partitions.
ValidityMask completed_partitions
 Bits set to 1 for completed partitions.

Detailed Description

JoinHashTable is a linear probing HT that is used for computing joins.

The JoinHashTable concatenates incoming chunks inside a linked list of data ptrs. The storage looks like this internally. [SERIALIZED ROW][NEXT POINTER] [SERIALIZED ROW][NEXT POINTER] There is a separate hash map of pointers that point into this table. This is what is used to resolve the hashes. [POINTER] [POINTER] [POINTER] The pointers are either NULL

Constructor & Destructor Documentation

◆ JoinHashTable()

duckdb::JoinHashTable::JoinHashTable ( ClientContext & context,
const PhysicalOperator & op,
const vector< JoinCondition > & conditions,
vector< LogicalType > build_types,
JoinType type,
const vector< idx_t > & output_columns )
157416 : context(context_p), op(op_p), buffer_manager(BufferManager::GetBufferManager(context)), conditions(conditions_p),
157417 build_types(std::move(btypes)), output_columns(output_columns_p), entry_size(0), tuple_size(0),
157418 vfound(Value::BOOLEAN(false)), join_type(type_p), finalized(false), has_null(false),
157419 radix_bits(INITIAL_RADIX_BITS) {
157420 for (idx_t i = 0; i < conditions.size(); ++i) {
157421 auto &condition = conditions[i];
157422 D_ASSERT(condition.left->return_type == condition.right->return_type);
157423 auto type = condition.left->return_type;
157424 if (condition.comparison == ExpressionType::COMPARE_EQUAL ||
157425 condition.comparison == ExpressionType::COMPARE_NOT_DISTINCT_FROM) {
157426 // ensure that all equality conditions are at the front,
157427 // and that all other conditions are at the back
157428 D_ASSERT(equality_types.size() == condition_types.size());
157429 equality_types.push_back(type);
157430 equality_predicates.push_back(condition.comparison);
157431 equality_predicate_columns.push_back(i);
157432
157433 } else {
157434 // all non-equality conditions are at the back
157435 non_equality_predicates.push_back(condition.comparison);
157436 non_equality_predicate_columns.push_back(i);
157437 }
157438
157439 null_values_are_equal.push_back(condition.comparison == ExpressionType::COMPARE_DISTINCT_FROM ||
157440 condition.comparison == ExpressionType::COMPARE_NOT_DISTINCT_FROM);
157441
157442 condition_types.push_back(type);
157443 }
157444 // at least one equality is necessary
157445 D_ASSERT(!equality_types.empty());
157446
157447 // Types for the layout
157448 auto layout = make_shared_ptr<TupleDataLayout>();
157449 vector<LogicalType> layout_types(condition_types);
157450 layout_types.insert(layout_types.end(), build_types.begin(), build_types.end());
157452 // full/right outer joins need an extra bool to keep track of whether or not a tuple has found a matching entry
157453 // we place the bool before the NEXT pointer
157454 layout_types.emplace_back(LogicalType::BOOLEAN);
157455 }
157456 layout_types.emplace_back(LogicalType::HASH);
157457 layout->Initialize(layout_types, TupleDataValidityType::CAN_HAVE_NULL_VALUES);
157458 layout_ptr = std::move(layout);
157459
157460 // Initialize the row matcher that are used for filtering during the probing only if there are non-equality
157461 if (!non_equality_predicates.empty()) {
157462 row_matcher_probe = unique_ptr<RowMatcher>(new RowMatcher());
157463 row_matcher_probe_no_match_sel = unique_ptr<RowMatcher>(new RowMatcher());
157464
157468
157469 needs_chain_matcher = true;
157470 } else {
157471 needs_chain_matcher = false;
157472 }
157473
157474 chains_longer_than_one = false;
157476
157477 const auto &offsets = layout_ptr->GetOffsets();
157478 tuple_size = offsets[condition_types.size() + build_types.size()];
157479 pointer_offset = offsets.back();
157480 entry_size = layout_ptr->GetRowWidth();
157481
157482 data_collection = make_uniq<TupleDataCollection>(buffer_manager, layout_ptr, MemoryTag::HASH_TABLE);
157483 sink_collection = make_uniq<RadixPartitionedTupleData>(buffer_manager, layout_ptr, MemoryTag::HASH_TABLE,
157484 radix_bits, layout_ptr->ColumnCount() - 1);
157485
157486 dead_end = make_unsafe_uniq_array_uninitialized<data_t>(layout_ptr->GetRowWidth());
157487 memset(dead_end.get(), 0, layout_ptr->GetRowWidth());
157488
157489 if (join_type == JoinType::SINGLE) {
157490 single_join_error_on_multiple_rows = Settings::Get<ScalarSubqueryErrorOnMultipleRowsSetting>(context);
157491 }
157492
157493 if (conditions.size() == 1 &&
157494 (join_type == JoinType::SEMI || join_type == JoinType::ANTI || join_type == JoinType::MARK)) {
157495 insert_duplicate_keys = false;
157496 }
157497
157499}
unique_ptr< RowMatcher > row_matcher_probe
Definition duckdb.cpp:157161
vector< LogicalType > build_types
The types of all conditions.
Definition duckdb.cpp:157142
bool chains_longer_than_one
If there is more than one element in the chain, we need to scan the next elements of the chain.
Definition duckdb.cpp:157168
unique_ptr< TupleDataCollection > data_collection
The DataCollection holding the main data of the hash table.
Definition duckdb.cpp:157238
vector< column_t > equality_predicate_columns
The column indices of the equality predicates to be used to compare the rows.
Definition duckdb.cpp:157151
unique_ptr< PartitionedTupleData > sink_collection
Partitioned data collection that the data is sunk into when building.
Definition duckdb.cpp:157236
unique_ptr< RowMatcher > row_matcher_probe_no_match_sel
Matches the same rows as the row_matcher, but also returns a vector for no matches.
Definition duckdb.cpp:157163
vector< column_t > non_equality_predicate_columns
The column indices of the non-equality predicates to be used to compare the rows.
Definition duckdb.cpp:157153
const vector< idx_t > & output_columns
Positions of the columns that need to output.
Definition duckdb.cpp:157144
void InitializePartitionMasks()
Initialized "current_partitions" and "completed_partitions".
Definition duckdb.cpp:158956
vector< ExpressionType > equality_predicates
The comparison predicates that only contain equality predicates.
Definition duckdb.cpp:157146
Vector vfound
A constant false column for initialising right outer joins.
Definition duckdb.cpp:157179
bool finalized
Whether or not the HT has been finalized.
Definition duckdb.cpp:157183
vector< ExpressionType > non_equality_predicates
The comparison predicates that contain non-equality predicates.
Definition duckdb.cpp:157148
bool has_null
Whether or not any of the key elements contain NULL.
Definition duckdb.cpp:157185
vector< bool > null_values_are_equal
Whether or not NULL values are considered equal in each of the comparisons.
Definition duckdb.cpp:157244
vector< LogicalType > condition_types
The types of the keys.
Definition duckdb.cpp:157140
idx_t radix_bits
The current number of radix bits used to partition.
Definition duckdb.cpp:157369
shared_ptr< TupleDataLayout > layout_ptr
Data column layout.
Definition duckdb.cpp:157155
JoinType join_type
The join type of the HT.
Definition duckdb.cpp:157181
idx_t entry_size
The size of an entry as stored in the HashTable.
Definition duckdb.cpp:157173
const vector< JoinCondition > & conditions
The join conditions.
Definition duckdb.cpp:157136
bool needs_chain_matcher
Is true if there are predicates that are not equality predicates and we need to use the matchers duri...
Definition duckdb.cpp:157165
RowMatcher row_matcher_build
Definition duckdb.cpp:157158
vector< LogicalType > equality_types
The types of the keys used in equality comparison.
Definition duckdb.cpp:157138
bool insert_duplicate_keys
Whether or not to perform deduplication based on join_keys when building ht.
Definition duckdb.cpp:157191
bool single_join_error_on_multiple_rows
Whether or not we error on multiple rows found per match in a SINGLE join.
Definition duckdb.cpp:157189
idx_t pointer_offset
Next pointer offset in tuple, also used for the position of the hash, which then gets overwritten by ...
Definition duckdb.cpp:157177
BufferManager & buffer_manager
BufferManager.
Definition duckdb.cpp:157134
unsafe_unique_array< data_t > dead_end
An empty tuple that's a "dead end", can be used to stop chains early.
Definition duckdb.cpp:157246
idx_t tuple_size
The total tuple size.
Definition duckdb.cpp:157175
static DUCKDB_API Value BOOLEAN(bool value)
Create a boolean Value from a specified value.
Definition duckdb.cpp:132118
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
bool PropagatesBuildSide(JoinType type)
Whether the build side is propagated out of the join.
Definition duckdb.cpp:68427

◆ ~JoinHashTable()

duckdb::JoinHashTable::~JoinHashTable ( )
157501 {
157502}

Member Function Documentation

◆ Build()

void duckdb::JoinHashTable::Build ( PartitionedTupleDataAppendState & append_state,
DataChunk & keys,
DataChunk & input )

Add the given data to the HT.

157752 {
157753 D_ASSERT(!finalized);
157754 D_ASSERT(keys.size() == payload.size());
157755 if (keys.size() == 0) {
157756 return;
157757 }
157758 // special case: correlated mark join
157759 if (join_type == JoinType::MARK && !correlated_mark_join_info.correlated_types.empty()) {
157760 auto &info = correlated_mark_join_info;
157761 lock_guard<mutex> mj_lock(info.mj_lock);
157762 // Correlated MARK join
157763 // for the correlated mark join we need to keep track of COUNT(*) and COUNT(COLUMN) for each of the correlated
157764 // columns push into the aggregate hash table
157765 D_ASSERT(info.correlated_counts);
157766 info.group_chunk.SetCardinality(keys);
157767 for (idx_t i = 0; i < info.correlated_types.size(); i++) {
157768 info.group_chunk.data[i].Reference(keys.data[i]);
157769 }
157770 if (info.correlated_payload.data.empty()) {
157771 vector<LogicalType> types;
157772 types.push_back(keys.data[info.correlated_types.size()].GetType());
157773 info.correlated_payload.InitializeEmpty(types);
157774 }
157775 info.correlated_payload.SetCardinality(keys);
157776 info.correlated_payload.data[0].Reference(keys.data[info.correlated_types.size()]);
157777 info.correlated_counts->AddChunk(info.group_chunk, info.correlated_payload, AggregateType::NON_DISTINCT);
157778 }
157779
157780 // build a chunk to append to the data collection [keys, payload, (optional "found" boolean), hash]
157781 DataChunk source_chunk;
157782 source_chunk.InitializeEmpty(layout_ptr->GetTypes());
157783 for (idx_t i = 0; i < keys.ColumnCount(); i++) {
157784 source_chunk.data[i].Reference(keys.data[i]);
157785 }
157786 idx_t col_offset = keys.ColumnCount();
157787 D_ASSERT(build_types.size() == payload.ColumnCount());
157788 for (idx_t i = 0; i < payload.ColumnCount(); i++) {
157789 source_chunk.data[col_offset + i].Reference(payload.data[i]);
157790 }
157791 col_offset += payload.ColumnCount();
157793 // for FULL/RIGHT OUTER joins initialize the "found" boolean to false
157794 source_chunk.data[col_offset].Reference(vfound);
157795 col_offset++;
157796 }
157797 Vector hash_values(LogicalType::HASH);
157798 source_chunk.data[col_offset].Reference(hash_values);
157799 source_chunk.SetCardinality(keys);
157800
157801 // ToUnifiedFormat the source chunk
157802 TupleDataCollection::ToUnifiedFormat(append_state.chunk_state, source_chunk);
157803
157804 // prepare the keys for processing
157805 const SelectionVector *current_sel;
157806 SelectionVector sel(STANDARD_VECTOR_SIZE);
157807 idx_t added_count = PrepareKeys(keys, append_state.chunk_state.vector_data, current_sel, sel, true);
157808 if (added_count < keys.size()) {
157809 has_null = true;
157810 }
157811 if (added_count == 0) {
157812 return;
157813 }
157814
157815 // hash the keys and obtain an entry in the list
157816 // note that we only hash the keys used in the equality comparison
157817 Hash(keys, *current_sel, added_count, hash_values);
157818
157819 // Re-reference and ToUnifiedFormat the hash column after computing it
157820 source_chunk.data[col_offset].Reference(hash_values);
157821 hash_values.ToUnifiedFormat(source_chunk.size(), append_state.chunk_state.vector_data.back().unified);
157822
157823 // We already called TupleDataCollection::ToUnifiedFormat, so we can AppendUnified here
157824 sink_collection->AppendUnified(append_state, source_chunk, *current_sel, added_count);
157825}
DUCKDB_API void InitializeEmpty(const vector< LogicalType > &types)
Initializes a DataChunk with the given types and without any vector data allocation.
Definition duckdb.cpp:116783
vector< Vector > data
The vectors owned by the DataChunk.
Definition duckdb.hpp:11445
idx_t PrepareKeys(DataChunk &keys, vector< TupleDataVectorFormat > &vector_data, const SelectionVector *&current_sel, SelectionVector &sel, bool build_side)
Prepares keys by filtering NULLs.
Definition duckdb.cpp:157827
static void ToUnifiedFormat(TupleDataChunkState &chunk_state, DataChunk &new_chunk)
Creates a UnifiedVectorFormat in the given Chunk state for the given DataChunk.
Definition duckdb.cpp:125999
Here is the call graph for this function:

◆ Merge()

void duckdb::JoinHashTable::Merge ( JoinHashTable & other)

Merge another HT into this one.

157504 {
157505 {
157506 lock_guard<mutex> guard(data_lock);
157507 data_collection->Combine(*other.data_collection);
157508 }
157509
157510 if (join_type == JoinType::MARK) {
157511 auto &info = correlated_mark_join_info;
157512 lock_guard<mutex> mj_lock(info.mj_lock);
157513 has_null = has_null || other.has_null;
157514 if (!info.correlated_types.empty()) {
157515 auto &other_info = other.correlated_mark_join_info;
157516 info.correlated_counts->Combine(*other_info.correlated_counts);
157517 }
157518 }
157519
157520 sink_collection->Combine(*other.sink_collection);
157521}
mutex data_lock
Lock for combining data_collection when merging HTs.
Definition duckdb.cpp:157234
Here is the caller graph for this function:

◆ Unpartition()

void duckdb::JoinHashTable::Unpartition ( )

Combines the partitions in sink_collection into data_collection, as if it were not partitioned.

158925 {
158926 data_collection = sink_collection->GetUnpartitioned();
158927}

◆ AllocatePointerTable()

void duckdb::JoinHashTable::AllocatePointerTable ( )

Allocate the pointer table for the probe.

158109 {
158110 capacity = PointerTableCapacity(Count());
158111 D_ASSERT(IsPowerOfTwo(capacity));
158112
158113 constexpr uint64_t MAX_HASHTABLE_CAPACITY = (1ULL << 48) - 1;
158114 if (capacity >= MAX_HASHTABLE_CAPACITY) {
158115 throw InternalException("Hashtable capacity exceeds 48-bit limit (2^48 - 1)");
158116 }
158117
158118 if (should_build_bloom_filter) {
158119 bloom_filter.Initialize(context, Count());
158120 }
158121
158122 if (hash_map.get()) {
158123 // There is already a hash map
158124 auto current_capacity = hash_map.GetSize() / sizeof(ht_entry_t);
158125 if (capacity > current_capacity) {
158126 // Need more space
158127 hash_map = buffer_manager.GetBufferAllocator().Allocate(capacity * sizeof(ht_entry_t));
158128 entries = reinterpret_cast<ht_entry_t *>(hash_map.get());
158129 } else {
158130 // Just use the current hash map
158131 capacity = current_capacity;
158132 }
158133 } else {
158134 // Allocate a hash map
158135 hash_map = buffer_manager.GetBufferAllocator().Allocate(capacity * sizeof(ht_entry_t));
158136 entries = reinterpret_cast<ht_entry_t *>(hash_map.get());
158137 }
158138 D_ASSERT(hash_map.GetSize() == capacity * sizeof(ht_entry_t));
158139
158140 bitmask = capacity - 1;
158141
158142 DUCKDB_LOG(context, PhysicalOperatorLogType, op, "JoinHashTable", "Build",
158143 {{"rows", to_string(data_collection->Count())},
158144 {"size", to_string(data_collection->SizeInBytes() + hash_map.GetSize())}});
158145}
BloomFilter bloom_filter
Whether or not to use a bloom filter will be determined by the operator.
Definition duckdb.cpp:157249
AllocatedData hash_map
The hash map of the HT, created after finalization.
Definition duckdb.cpp:157241
uint64_t bitmask
Bitmask for getting relevant bits from the hashes to determine the position.
Definition duckdb.cpp:157187
idx_t capacity
The capacity of the HT. Is the same as hash_map.GetSize() / sizeof(ht_entry_t).
Definition duckdb.cpp:157171
idx_t PointerTableCapacity(idx_t count) const
Capacity of the pointer table given the ht count.
Definition duckdb.cpp:157322
std::string to_string(const T &value)
Definition duckdb.cpp:19425
::uint64_t uint64_t
Here is the call graph for this function:

◆ InitializePointerTable()

void duckdb::JoinHashTable::InitializePointerTable ( idx_t entry_idx_from,
idx_t entry_idx_to )

Initialize the pointer table for the probe.

158147 {
158148 // initialize HT with all-zero entries
158149 std::fill_n(entries + entry_idx_from, entry_idx_to - entry_idx_from, ht_entry_t());
158150}

◆ Finalize()

void duckdb::JoinHashTable::Finalize ( idx_t chunk_idx_from,
idx_t chunk_idx_to,
bool parallel )

Finalize the build of the HT, constructing the actual hash table and making the HT ready for probing. Finalize must be called before any call to Probe, and after Finalize is called Build should no longer be ever called.

158152 {
158153 // Pointer table should be allocated
158154 D_ASSERT(hash_map.get());
158155
158156 Vector hashes(LogicalType::HASH);
158157 auto hash_data = FlatVector::GetData<hash_t>(hashes);
158158
158159 TupleDataChunkIterator iterator(*data_collection, TupleDataPinProperties::KEEP_EVERYTHING_PINNED, chunk_idx_from,
158160 chunk_idx_to, false);
158161 const auto row_locations = iterator.GetRowLocations();
158162
158163 InsertState insert_state(*this);
158164 do {
158165 const auto count = iterator.GetCurrentChunkCount();
158166 for (idx_t i = 0; i < count; i++) {
158167 hash_data[i] = Load<hash_t>(row_locations[i] + pointer_offset);
158168 }
158169 TupleDataChunkState &chunk_state = iterator.GetChunkState();
158170
158171 InsertHashes(hashes, count, chunk_state, insert_state, parallel);
158172 } while (iterator.Next());
158173}
void InsertHashes(Vector &hashes_v, idx_t count, TupleDataChunkState &chunk_state, InsertState &insert_statebool, bool parallel)
Insert the given set of locations into the HT with the given set of hashes_v.
Definition duckdb.cpp:158094
@ KEEP_EVERYTHING_PINNED
Keeps all passed blocks pinned while scanning/iterating over the chunks (for both reading/writing).
Definition duckdb.cpp:56599
Definition duckdb.cpp:157068
Here is the call graph for this function:

◆ Probe()

void duckdb::JoinHashTable::Probe ( ScanStructure & scan_structure,
DataChunk & keys,
TupleDataChunkState & key_state,
ProbeState & probe_state,
optional_ptr< Vector > precomputed_hashes = nullptr )

Probe the HT with the given input chunk, resulting in the given result.

158199 {
158200 const SelectionVector *current_sel;
158201 InitializeScanStructure(scan_structure, keys, key_state, current_sel);
158202 if (scan_structure.count == 0) {
158203 return;
158204 }
158205 if (precomputed_hashes) {
158206 GetRowPointers(keys, key_state, probe_state, *precomputed_hashes, current_sel, scan_structure.count,
158207 scan_structure.pointers, scan_structure.sel_vector, scan_structure.has_null_value_filter);
158208 } else {
158209 Vector hashes(LogicalType::HASH);
158210 // hash all the keys
158211 Hash(keys, *current_sel, scan_structure.count, hashes);
158212
158213 // now initialize the pointers of the scan structure based on the hashes
158214 GetRowPointers(keys, key_state, probe_state, hashes, current_sel, scan_structure.count, scan_structure.pointers,
158215 scan_structure.sel_vector, scan_structure.has_null_value_filter);
158216 }
158217}
void GetRowPointers(DataChunk &keys, TupleDataChunkState &key_state, ProbeState &state, Vector &hashes_v, const SelectionVector *sel, idx_t &count, Vector &pointers_result_v, SelectionVector &match_sel, bool has_sel)
Definition duckdb.cpp:157711
Here is the call graph for this function:

◆ ScanFullOuter()

void duckdb::JoinHashTable::ScanFullOuter ( JoinHTScanState & state,
Vector & addresses,
DataChunk & result ) const

Scan the HT to construct the full outer join result.

158769 {
158770 // scan the HT starting from the current position and check which rows from the build side did not find a match
158771 auto key_locations = FlatVector::GetData<data_ptr_t>(addresses);
158772 idx_t found_entries = 0;
158773
158774 auto &iterator = state.iterator;
158775 if (iterator.Done()) {
158776 return;
158777 }
158778
158779 // When scanning Full Outer for right semi joins, we only propagate matches that have true
158780 // Right Semi Joins do not propagate values during the probe phase, since we do not want to
158781 // duplicate RHS rows.
158782 bool match_propagation_value = false;
158783 if (join_type == JoinType::RIGHT_SEMI) {
158784 match_propagation_value = true;
158785 }
158786
158787 const auto row_locations = iterator.GetRowLocations();
158788 do {
158789 const auto count = iterator.GetCurrentChunkCount();
158790 for (idx_t i = state.offset_in_chunk; i < count; i++) {
158791 auto found_match = Load<bool>(row_locations[i] + tuple_size);
158792 if (found_match == match_propagation_value) {
158793 key_locations[found_entries++] = row_locations[i];
158794 if (found_entries == STANDARD_VECTOR_SIZE) {
158795 state.offset_in_chunk = i + 1;
158796 break;
158797 }
158798 }
158799 }
158800 if (found_entries == STANDARD_VECTOR_SIZE) {
158801 break;
158802 }
158803 state.offset_in_chunk = 0;
158804 } while (iterator.Next());
158805
158806 // now gather from the found rows
158807 if (found_entries == 0) {
158808 return;
158809 }
158810 result.SetCardinality(found_entries);
158811
158812 idx_t left_column_count = result.ColumnCount() - output_columns.size();
158813 if (join_type == JoinType::RIGHT_SEMI || join_type == JoinType::RIGHT_ANTI) {
158814 left_column_count = 0;
158815 }
158816 const auto &sel_vector = *FlatVector::IncrementalSelectionVector();
158817 // set the left side as a constant NULL
158818 for (idx_t i = 0; i < left_column_count; i++) {
158819 Vector &vec = result.data[i];
158820 vec.SetVectorType(VectorType::CONSTANT_VECTOR);
158821 ConstantVector::SetNull(vec, true);
158822 }
158823
158824 // gather the values from the RHS
158825 for (idx_t i = 0; i < output_columns.size(); i++) {
158826 auto &vector = result.data[left_column_count + i];
158827 const auto output_col_idx = output_columns[i];
158828 D_ASSERT(vector.GetType() == layout_ptr->GetTypes()[output_col_idx]);
158829 data_collection->Gather(addresses, sel_vector, found_entries, output_col_idx, vector, sel_vector, nullptr);
158830 }
158831}

◆ FillWithHTOffsets()

idx_t duckdb::JoinHashTable::FillWithHTOffsets ( JoinHTScanState & state,
Vector & addresses )
static

Fill the pointer with all the addresses from the hashtable for full scan.

158833 {
158834 // iterate over HT
158835 auto key_locations = FlatVector::GetData<data_ptr_t>(addresses);
158836 idx_t key_count = 0;
158837
158838 auto &iterator = state.iterator;
158839 const auto row_locations = iterator.GetRowLocations();
158840 do {
158841 const auto count = iterator.GetCurrentChunkCount();
158842 for (idx_t i = 0; i < count; i++) {
158843 key_locations[key_count + i] = row_locations[i];
158844 }
158845 key_count += count;
158846 } while (iterator.Next());
158847
158848 return key_count;
158849}
Here is the caller graph for this function:

◆ Count()

idx_t duckdb::JoinHashTable::Count ( ) const
inline
157109 {
157110 return data_collection->Count();
157111 }

◆ SizeInBytes()

idx_t duckdb::JoinHashTable::SizeInBytes ( ) const
inline
157112 {
157113 return data_collection->SizeInBytes();
157114 }

◆ GetSinkCollection()

PartitionedTupleData & duckdb::JoinHashTable::GetSinkCollection ( )
inline
157116 {
157117 return *sink_collection;
157118 }

◆ GetDataCollection()

TupleDataCollection & duckdb::JoinHashTable::GetDataCollection ( )
inline
157120 {
157121 return *data_collection;
157122 }

◆ ScanKeyColumn()

idx_t duckdb::JoinHashTable::ScanKeyColumn ( Vector & addresses,
Vector & result,
idx_t column_index ) const

Perform a full scan of a build column, filling the provided addresses vector and result vector. Returns the number of tuples found (can be smaller than the vector capacity).

158851 {
158852 // nothing to scan if the build side is empty
158853 if (data_collection->ChunkCount() == 0) {
158854 return 0;
158855 }
158856 D_ASSERT(result.GetType() == layout_ptr->GetTypes()[column_index]);
158857 JoinHTScanState join_ht_state(*data_collection, 0, data_collection->ChunkCount(),
158859 auto key_count = FillWithHTOffsets(join_ht_state, addresses);
158860 if (key_count == 0) {
158861 return 0;
158862 }
158863 const auto &sel = *FlatVector::IncrementalSelectionVector();
158864 data_collection->Gather(addresses, sel, key_count, column_index, result, sel, nullptr);
158865 return key_count;
158866}
static idx_t FillWithHTOffsets(JoinHTScanState &state, Vector &addresses)
Fill the pointer with all the addresses from the hashtable for full scan.
Definition duckdb.cpp:158833
Here is the call graph for this function:

◆ NullValuesAreEqual()

bool duckdb::JoinHashTable::NullValuesAreEqual ( idx_t col_idx) const
inline
157127 {
157128 return null_values_are_equal[col_idx];
157129 }

◆ InitializeScanStructure()

void duckdb::JoinHashTable::InitializeScanStructure ( ScanStructure & scan_structure,
DataChunk & keys,
TupleDataChunkState & key_state,
const SelectionVector *& current_sel )
private
158176 {
158177 D_ASSERT(Count() > 0); // should be handled before
158178 D_ASSERT(finalized);
158179
158180 // set up the scan structure
158181 scan_structure.is_null = false;
158182 scan_structure.finished = false;
158183 if (join_type != JoinType::INNER) {
158184 memset(scan_structure.found_match.get(), 0, sizeof(bool) * STANDARD_VECTOR_SIZE);
158185 }
158186
158187 // first prepare the keys for probing
158188 TupleDataCollection::ToUnifiedFormat(key_state, keys);
158189 scan_structure.count = PrepareKeys(keys, key_state.vector_data, current_sel, scan_structure.sel_vector, false);
158190
158191 if (scan_structure.count < keys.size()) {
158192 scan_structure.has_null_value_filter = true;
158193 } else {
158194 scan_structure.has_null_value_filter = false;
158195 }
158196}

◆ Hash()

void duckdb::JoinHashTable::Hash ( DataChunk & keys,
const SelectionVector & sel,
idx_t count,
Vector & hashes )
private
157723 {
157724 if (count == keys.size()) {
157725 // no null values are filtered: use regular hash functions
157726 VectorOperations::Hash(keys.data[0], hashes, keys.size());
157727 for (idx_t i = 1; i < equality_types.size(); i++) {
157728 VectorOperations::CombineHash(hashes, keys.data[i], keys.size());
157729 }
157730 } else {
157731 // null values were filtered: use selection vector
157732 VectorOperations::Hash(keys.data[0], hashes, sel, count);
157733 for (idx_t i = 1; i < equality_types.size(); i++) {
157734 VectorOperations::CombineHash(hashes, keys.data[i], sel, count);
157735 }
157736 }
157737}

◆ UseSalt()

bool duckdb::JoinHashTable::UseSalt ( ) const
inlineprivate
157706 {
157707 // only use salt for large hash tables
157708 return this->capacity > USE_SALT_THRESHOLD;
157709}
static constexpr const idx_t USE_SALT_THRESHOLD
Definition duckdb.cpp:156974

◆ GetRowPointers()

void duckdb::JoinHashTable::GetRowPointers ( DataChunk & keys,
TupleDataChunkState & key_state,
ProbeState & state,
Vector & hashes_v,
const SelectionVector * sel,
idx_t & count,
Vector & pointers_result_v,
SelectionVector & match_sel,
bool has_sel )
private

Gets a pointer to the entry in the HT for each of the hashes_v using linear probing. Will update the key_match_sel vector and the count argument to the number and position of the matches

157713 {
157714 if (UseSalt()) {
157715 GetRowPointersInternal<true>(keys, key_state, state, hashes_v, sel, count, *this, entries, pointers_result_v,
157716 match_sel, has_sel);
157717 } else {
157718 GetRowPointersInternal<false>(keys, key_state, state, hashes_v, sel, count, *this, entries, pointers_result_v,
157719 match_sel, has_sel);
157720 }
157721}
static void GetRowPointersInternal(DataChunk &keys, TupleDataChunkState &key_state, JoinHashTable::ProbeState &state, Vector &hashes_v, const SelectionVector *row_sel, idx_t &count, JoinHashTable &ht, ht_entry_t *entries, Vector &pointers_result_v, SelectionVector &match_sel, bool has_row_sel)
Definition duckdb.cpp:157632
Here is the call graph for this function:
Here is the caller graph for this function:

◆ InsertHashes()

void duckdb::JoinHashTable::InsertHashes ( Vector & hashes_v,
idx_t count,
TupleDataChunkState & chunk_state,
InsertState & insert_statebool,
bool parallel )
private

Insert the given set of locations into the HT with the given set of hashes_v.

158095 {
158096 // Insert Hashes into the BF
158097 if (bloom_filter.IsInitialized()) {
158098 bloom_filter.InsertHashes(hashes_v, count);
158099 }
158100 auto atomic_entries = reinterpret_cast<atomic<ht_entry_t> *>(this->entries);
158101 auto row_locations = chunk_state.row_locations;
158102 if (parallel) {
158103 InsertHashesLoop<true>(atomic_entries, row_locations, hashes_v, count, insert_state, *data_collection, *this);
158104 } else {
158105 InsertHashesLoop<false>(atomic_entries, row_locations, hashes_v, count, insert_state, *data_collection, *this);
158106 }
158107}
Here is the caller graph for this function:

◆ PrepareKeys()

idx_t duckdb::JoinHashTable::PrepareKeys ( DataChunk & keys,
vector< TupleDataVectorFormat > & vector_data,
const SelectionVector *& current_sel,
SelectionVector & sel,
bool build_side )
private

Prepares keys by filtering NULLs.

157828 {
157829 // figure out which keys are NULL, and create a selection vector out of them
157830 current_sel = FlatVector::IncrementalSelectionVector();
157831 idx_t added_count = keys.size();
157832 if (build_side && PropagatesBuildSide(join_type)) {
157833 // in case of a right or full outer join, we cannot remove NULL keys from the build side
157834 return added_count;
157835 }
157836
157837 for (idx_t col_idx = 0; col_idx < keys.ColumnCount(); col_idx++) {
157838 // see internal issue 3717.
157839 if (join_type == JoinType::MARK && !correlated_mark_join_info.correlated_types.empty()) {
157840 continue;
157841 }
157842 if (null_values_are_equal[col_idx]) {
157843 continue;
157844 }
157845 auto &col_key_data = vector_data[col_idx].unified;
157846 if (col_key_data.validity.AllValid()) {
157847 continue;
157848 }
157849 added_count = FilterNullValues(col_key_data, *current_sel, added_count, sel);
157850 // null values are NOT equal for this column, filter them out
157851 current_sel = &sel;
157852 }
157853 return added_count;
157854}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetRadixBits()

idx_t duckdb::JoinHashTable::GetRadixBits ( ) const
inline
157308 {
157309 return radix_bits;
157310 }

◆ PointerTableCapacity()

idx_t duckdb::JoinHashTable::PointerTableCapacity ( idx_t count) const
inline

Capacity of the pointer table given the ht count.

157322 {
157323 const auto capacity = NextPowerOfTwo(LossyNumericCast<idx_t>(static_cast<double>(count) * load_factor));
157324 return MaxValue<idx_t>(capacity, MINIMUM_CAPACITY);
157325 }
static constexpr idx_t MINIMUM_CAPACITY
Minimum capacity of the pointer table.
Definition duckdb.cpp:157317
Here is the caller graph for this function:

◆ PointerTableSize()

idx_t duckdb::JoinHashTable::PointerTableSize ( idx_t count) const
inline

Size of the pointer table (in bytes).

157327 {
157328 return PointerTableCapacity(count) * sizeof(data_ptr_t);
157329 }
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetBuildBloomFilter()

void duckdb::JoinHashTable::SetBuildBloomFilter ( const bool should_build)
inline
157331 {
157332 this->should_build_bloom_filter = should_build;
157333 }

◆ GetBloomFilter()

BloomFilter & duckdb::JoinHashTable::GetBloomFilter ( )
inline
157335 {
157336 return bloom_filter;
157337 }

◆ GetTotalSize() [1/2]

idx_t duckdb::JoinHashTable::GetTotalSize ( const vector< unique_ptr< JoinHashTable > > & local_hts,
idx_t & max_partition_size,
idx_t & max_partition_count ) const

Get total size of HT if all partitions would be built.

158897 {
158898 const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits);
158899 vector<idx_t> partition_sizes(num_partitions, 0);
158900 vector<idx_t> partition_counts(num_partitions, 0);
158901 for (auto &ht : local_hts) {
158902 ht->GetSinkCollection().GetSizesAndCounts(partition_sizes, partition_counts);
158903 }
158904
158905 return GetTotalSize(partition_sizes, partition_counts, max_partition_size, max_partition_count);
158906}
idx_t GetTotalSize(const vector< unique_ptr< JoinHashTable > > &local_hts, idx_t &max_partition_size, idx_t &max_partition_count) const
Get total size of HT if all partitions would be built.
Definition duckdb.cpp:158896
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:
Here is the caller graph for this function:

◆ GetTotalSize() [2/2]

idx_t duckdb::JoinHashTable::GetTotalSize ( const vector< idx_t > & partition_sizes,
const vector< idx_t > & partition_counts,
idx_t & max_partition_size,
idx_t & max_partition_count ) const
158869 {
158870 const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits);
158871
158872 idx_t total_size = 0;
158873 idx_t total_count = 0;
158874 idx_t max_partition_ht_size = 0;
158875 max_partition_size = 0;
158876 max_partition_count = 0;
158877 for (idx_t i = 0; i < num_partitions; i++) {
158878 total_size += partition_sizes[i];
158879 total_count += partition_counts[i];
158880
158881 auto partition_size = partition_sizes[i] + PointerTableSize(partition_counts[i]);
158882 if (partition_size > max_partition_ht_size) {
158883 max_partition_ht_size = partition_size;
158884 max_partition_size = partition_sizes[i];
158885 max_partition_count = partition_counts[i];
158886 }
158887 }
158888
158889 if (total_count == 0) {
158890 return 0;
158891 }
158892
158893 return total_size + PointerTableSize(total_count);
158894}
idx_t PointerTableSize(idx_t count) const
Size of the pointer table (in bytes).
Definition duckdb.cpp:157327

◆ GetRemainingSize()

idx_t duckdb::JoinHashTable::GetRemainingSize ( ) const

Get the remaining size of the unbuilt partitions.

158908 {
158909 const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits);
158910 auto &partitions = sink_collection->GetPartitions();
158911
158912 idx_t count = 0;
158913 idx_t data_size = 0;
158914 for (idx_t partition_idx = 0; partition_idx < num_partitions; partition_idx++) {
158915 if (completed_partitions.RowIsValidUnsafe(partition_idx)) {
158916 continue;
158917 }
158918 count += partitions[partition_idx]->Count();
158919 data_size += partitions[partition_idx]->SizeInBytes();
158920 }
158921
158922 return data_size + PointerTableSize(count);
158923}
ValidityMask completed_partitions
Bits set to 1 for completed partitions.
Definition duckdb.cpp:157374
Here is the call graph for this function:

◆ SetRepartitionRadixBits()

void duckdb::JoinHashTable::SetRepartitionRadixBits ( const idx_t max_ht_size,
const idx_t max_partition_size,
const idx_t max_partition_count )

Sets number of radix bits according to the max ht size.

158930 {
158931 D_ASSERT(max_partition_size + PointerTableSize(max_partition_count) > max_ht_size);
158932
158933 const auto max_added_bits = RadixPartitioning::MAX_RADIX_BITS - radix_bits;
158934 idx_t added_bits = 1;
158935 for (; added_bits < max_added_bits; added_bits++) {
158936 double partition_multiplier = static_cast<double>(RadixPartitioning::NumberOfPartitions(added_bits));
158937
158938 auto new_estimated_size = static_cast<double>(max_partition_size) / partition_multiplier;
158939 auto new_estimated_count = static_cast<double>(max_partition_count) / partition_multiplier;
158940 auto new_estimated_ht_size =
158941 new_estimated_size + static_cast<double>(PointerTableSize(LossyNumericCast<idx_t>(new_estimated_count)));
158942
158943 if (new_estimated_ht_size <= static_cast<double>(max_ht_size) / 4) {
158944 // Aim for an estimated partition size of max_ht_size / 4
158945 break;
158946 }
158947 }
158948 radix_bits += added_bits;
158949 sink_collection = make_uniq<RadixPartitionedTupleData>(buffer_manager, layout_ptr, MemoryTag::HASH_TABLE,
158950 radix_bits, layout_ptr->ColumnCount() - 1);
158951
158952 // Need to initialize again after changing the number of bits
158954}
static constexpr const idx_t MAX_RADIX_BITS
4096 partitions ought to be enough to go out-of-core properly
Definition duckdb.cpp:93422
Here is the call graph for this function:

◆ InitializePartitionMasks()

void duckdb::JoinHashTable::InitializePartitionMasks ( )

Initialized "current_partitions" and "completed_partitions".

158956 {
158957 const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits);
158958
158959 current_partitions.Initialize(num_partitions);
158960 current_partitions.SetAllInvalid(num_partitions);
158961
158962 completed_partitions.Initialize(num_partitions);
158963 completed_partitions.SetAllInvalid(num_partitions);
158964}
ValidityMask current_partitions
Bits set to 1 for currently active partitions.
Definition duckdb.cpp:157372
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CurrentPartitionCount()

idx_t duckdb::JoinHashTable::CurrentPartitionCount ( ) const

How many partitions are currently active.

158966 {
158967 const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits);
158968 D_ASSERT(current_partitions.Capacity() == num_partitions);
158969 return current_partitions.CountValid(num_partitions);
158970}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FinishedPartitionCount()

idx_t duckdb::JoinHashTable::FinishedPartitionCount ( ) const

How many partitions are fully done.

158972 {
158973 const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits);
158974 D_ASSERT(completed_partitions.Capacity() == num_partitions);
158975 // We already marked the active partitions as done, so we have to subtract them here
158976 return completed_partitions.CountValid(num_partitions) - CurrentPartitionCount();
158977}
idx_t CurrentPartitionCount() const
How many partitions are currently active.
Definition duckdb.cpp:158966
Here is the call graph for this function:

◆ Repartition()

void duckdb::JoinHashTable::Repartition ( JoinHashTable & global_ht)

Partition this HT.

158979 {
158980 auto new_sink_collection = make_uniq<RadixPartitionedTupleData>(
158981 buffer_manager, layout_ptr, MemoryTag::HASH_TABLE, global_ht.radix_bits, layout_ptr->ColumnCount() - 1);
158982 sink_collection->Repartition(context, *new_sink_collection);
158983 sink_collection = std::move(new_sink_collection);
158984 global_ht.Merge(*this);
158985}
Here is the call graph for this function:

◆ Reset()

void duckdb::JoinHashTable::Reset ( )

Delete blocks that belong to the current partitioned HT.

158987 {
158988 data_collection->Reset();
158989 hash_map.Reset();
158991 finalized = false;
158992}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PrepareExternalFinalize()

bool duckdb::JoinHashTable::PrepareExternalFinalize ( const idx_t max_ht_size)

Build HT for the next partitioned probe round.

158994 {
158995 if (finalized) {
158996 Reset();
158997 }
158998
158999 const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits);
159000 D_ASSERT(current_partitions.Capacity() == num_partitions);
159001 D_ASSERT(completed_partitions.Capacity() == num_partitions);
159002 D_ASSERT(current_partitions.CheckAllInvalid(num_partitions));
159003
159004 if (completed_partitions.CheckAllValid(num_partitions)) {
159005 return false; // All partitions are done
159006 }
159007
159008 // Create vector with unfinished partition indices
159009 auto &partitions = sink_collection->GetPartitions();
159010 auto min_partition_size = NumericLimits<idx_t>::Maximum();
159011 vector<idx_t> partition_indices;
159012 partition_indices.reserve(num_partitions);
159013 for (idx_t partition_idx = 0; partition_idx < num_partitions; partition_idx++) {
159014 if (completed_partitions.RowIsValidUnsafe(partition_idx)) {
159015 continue;
159016 }
159017 partition_indices.push_back(partition_idx);
159018 // Keep track of min partition size
159019 const auto size =
159020 partitions[partition_idx]->SizeInBytes() + PointerTableSize(partitions[partition_idx]->Count());
159021 min_partition_size = MinValue(min_partition_size, size);
159022 }
159023
159024 // Sort partitions by size, from small to large
159025 std::stable_sort(partition_indices.begin(), partition_indices.end(), [&](const idx_t &lhs, const idx_t &rhs) {
159026 const auto lhs_size = partitions[lhs]->SizeInBytes() + PointerTableSize(partitions[lhs]->Count());
159027 const auto rhs_size = partitions[rhs]->SizeInBytes() + PointerTableSize(partitions[rhs]->Count());
159028 // We divide by min_partition_size, effectively rouding everything down to a multiple of min_partition_size
159029 // Makes it so minor differences in partition sizes don't mess up the original order
159030 // Retaining as much of the original order as possible reduces I/O (partition idx determines eviction queue idx)
159031 return lhs_size / min_partition_size < rhs_size / min_partition_size;
159032 });
159033
159034 // Determine which partitions should go next
159035 idx_t count = 0;
159036 idx_t data_size = 0;
159037 for (const auto &partition_idx : partition_indices) {
159038 D_ASSERT(!completed_partitions.RowIsValidUnsafe(partition_idx));
159039 const auto incl_count = count + partitions[partition_idx]->Count();
159040 const auto incl_data_size = data_size + partitions[partition_idx]->SizeInBytes();
159041 const auto incl_ht_size = incl_data_size + PointerTableSize(incl_count);
159042 if (count > 0 && incl_ht_size > max_ht_size) {
159043 break; // Always add at least one partition
159044 }
159045 count = incl_count;
159046 data_size = incl_data_size;
159047 current_partitions.SetValidUnsafe(partition_idx); // Mark as currently active
159048 data_collection->Combine(*partitions[partition_idx]); // Move partition to the main data collection
159049 completed_partitions.SetValidUnsafe(partition_idx); // Also already mark as done
159050 }
159051 D_ASSERT(Count() == count);
159052
159053 return true;
159054}
void Reset()
Delete blocks that belong to the current partitioned HT.
Definition duckdb.cpp:158987
GOpaque< Size > size(const GMat &src)
Here is the call graph for this function:

◆ ProbeAndSpill()

void duckdb::JoinHashTable::ProbeAndSpill ( ScanStructure & scan_structure,
DataChunk & probe_keys,
TupleDataChunkState & key_state,
ProbeState & probe_state,
DataChunk & probe_chunk,
ProbeSpill & probe_spill,
ProbeSpillLocalAppendState & spill_state,
DataChunk & spill_chunk )

Probe whatever we can, sink the rest into a thread-local HT.

159058 {
159059 // hash all the keys
159060 Vector hashes(LogicalType::HASH);
159061 Hash(probe_keys, *FlatVector::IncrementalSelectionVector(), probe_keys.size(), hashes);
159062
159063 // find out which keys we can match with the current pinned partitions
159064 SelectionVector true_sel(STANDARD_VECTOR_SIZE);
159065 SelectionVector false_sel(STANDARD_VECTOR_SIZE);
159066 const auto true_count =
159067 RadixPartitioning::Select(hashes, FlatVector::IncrementalSelectionVector(), probe_keys.size(), radix_bits,
159068 current_partitions, &true_sel, &false_sel);
159069 const auto false_count = probe_keys.size() - true_count;
159070
159071 // can't probe these values right now, append to spill
159072 spill_chunk.Reset();
159073 spill_chunk.Reference(probe_chunk);
159074 spill_chunk.data.back().Reference(hashes);
159075 spill_chunk.Slice(false_sel, false_count);
159076 probe_spill.Append(spill_chunk, spill_state);
159077
159078 // slice the stuff we CAN probe right now
159079 hashes.Slice(true_sel, true_count);
159080 probe_keys.Slice(true_sel, true_count);
159081 probe_chunk.Slice(true_sel, true_count);
159082
159083 const SelectionVector *current_sel;
159084 InitializeScanStructure(scan_structure, probe_keys, key_state, current_sel);
159085 if (scan_structure.count == 0) {
159086 return;
159087 }
159088
159089 // now initialize the pointers of the scan structure based on the hashes
159090 GetRowPointers(probe_keys, key_state, probe_state, hashes, current_sel, scan_structure.count,
159091 scan_structure.pointers, scan_structure.sel_vector, scan_structure.has_null_value_filter);
159092}
DUCKDB_API void Reference(DataChunk &chunk)
Set the DataChunk to reference another data chunk.
Definition duckdb.cpp:116879
DUCKDB_API void Reset()
Definition duckdb.cpp:116840
static idx_t Select(Vector &hashes, const SelectionVector *sel, idx_t count, idx_t radix_bits, const ValidityMask &partition_mask, SelectionVector *true_sel, SelectionVector *false_sel)
Select using a cutoff on the radix bits of the hash.
Definition duckdb.cpp:93621
Here is the call graph for this function:

Member Data Documentation

◆ USE_SALT_THRESHOLD

const idx_t duckdb::JoinHashTable::USE_SALT_THRESHOLD = 8192
staticconstexpr

only compare salts with the ht entries if the capacity is larger than 8192 so that it does not fit into the CPU cache

◆ row_matcher_build

RowMatcher duckdb::JoinHashTable::row_matcher_build

Matches the equal condition rows during the build phase of the hash join to prevent duplicates in a list because of hash-collisions

◆ row_matcher_probe

unique_ptr<RowMatcher> duckdb::JoinHashTable::row_matcher_probe

Efficiently matches the non-equi rows during the probing phase, only there if non_equality_predicates is not empty

◆ total_probe_matches

atomic<idx_t> duckdb::JoinHashTable::total_probe_matches {0}

Number of probe matches.

157193{0};

◆ correlated_types

vector<LogicalType> duckdb::JoinHashTable::correlated_types

The types of the duplicate eliminated columns, only used in correlated MARK JOIN for flattening ANY()/ALL() expressions


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