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

Class that sorts the data, follows the PhysicalOperator interface. More...

Collaboration diagram for duckdb::Sort:

Public Member Functions

 Sort (ClientContext &context, const vector< BoundOrderByNode > &orders, const vector< LogicalType > &input_types, vector< idx_t > projection_map, bool is_index_sort=false)
unique_ptr< LocalSinkState > GetLocalSinkState (ExecutionContext &context) const
unique_ptr< GlobalSinkState > GetGlobalSinkState (ClientContext &context) const
SinkResultType Sink (ExecutionContext &context, DataChunk &chunk, OperatorSinkInput &input) const
SinkCombineResultType Combine (ExecutionContext &context, OperatorSinkCombineInput &input) const
SinkFinalizeType Finalize (ClientContext &context, OperatorSinkFinalizeInput &input) const
ProgressData GetSinkProgress (ClientContext &context, GlobalSinkState &gstate, const ProgressData source_progress) const
unique_ptr< LocalSourceState > GetLocalSourceState (ExecutionContext &context, GlobalSourceState &gstate) const
unique_ptr< GlobalSourceState > GetGlobalSourceState (ClientContext &context, GlobalSinkState &sink) const
SourceResultType GetData (ExecutionContext &context, DataChunk &chunk, OperatorSourceInput &input) const
OperatorPartitionData GetPartitionData (ExecutionContext &context, DataChunk &chunk, GlobalSourceState &gstate, LocalSourceState &lstate, const OperatorPartitionInfo &partition_info) const
ProgressData GetProgress (ClientContext &context, GlobalSourceState &gstate) const
SourceResultType MaterializeColumnData (ExecutionContext &context, OperatorSourceInput &input) const
unique_ptr< ColumnDataCollection > GetColumnData (OperatorSourceInput &input) const
SourceResultType MaterializeSortedRun (ExecutionContext &context, OperatorSourceInput &input) const
unique_ptr< SortedRun > GetSortedRun (GlobalSourceState &global_state)

Public Attributes

ClientContext & context
 The client context.

Private Attributes

unique_ptr< Expression > create_sort_key
 Key orders, expressions, and layout.
unique_ptr< Expression > decode_sort_key
shared_ptr< TupleDataLayout > key_layout
vector< idx_t > payload_projection_map
 Projection map and payload layout (columns that also appear as key eliminated).
shared_ptr< TupleDataLayout > payload_layout
vector< idx_t > input_projection_map
 Mapping from key/payload layouts to output columns.
vector< SortProjectionColumn > output_projection_columns
bool is_index_sort
 Whether to force an approximate sort.

Friends

class SortLocalSinkState
class SortGlobalSinkState
class SortLocalSourceState
class SortGlobalSourceState
class SortedRun
class SortedRunScanState
class SortedRunMerger
class SortedRunMergerLocalState
class SortedRunMergerGlobalState

Detailed Description

Class that sorts the data, follows the PhysicalOperator interface.

Constructor & Destructor Documentation

◆ Sort()

duckdb::Sort::Sort ( ClientContext & context,
const vector< BoundOrderByNode > & orders,
const vector< LogicalType > & input_types,
vector< idx_t > projection_map,
bool is_index_sort = false )
103120 : context(context_p), key_layout(make_shared_ptr<TupleDataLayout>()),
103121 payload_layout(make_shared_ptr<TupleDataLayout>()), is_index_sort(is_index_sort_p) {
103122 // Convert orders to a single "create_sort_key" expression (and corresponding "decode_sort_key")
103123 FunctionBinder binder(context);
103124 vector<unique_ptr<Expression>> create_children;
103125 vector<unique_ptr<Expression>> decode_children;
103126 child_list_t<LogicalType> decode_child_list;
103127 for (idx_t col_idx = 0; col_idx < orders.size(); col_idx++) {
103128 const auto &order = orders[col_idx];
103129
103130 // Create: for each column we have two arguments: 1. the column, 2. sort specifier
103131 create_children.emplace_back(order.expression->Copy());
103132 create_children.emplace_back(make_uniq<BoundConstantExpression>(Value(order.GetOrderModifier())));
103133
103134 // Avoid having unnamed structs fields (otherwise we get a parser exception while binding)
103135 const auto col_name = StringUtil::Format("c%llu", col_idx);
103136 auto col_type = order.expression->return_type;
103137 decode_child_list.emplace_back(col_name, col_type);
103138 col_type = TypeVisitor::VisitReplace(col_type, [](const LogicalType &type) {
103139 if (type.id() != LogicalTypeId::STRUCT) {
103140 return type;
103141 }
103142 child_list_t<LogicalType> internal_child_list;
103143 for (const auto &child : StructType::GetChildTypes(type)) {
103144 internal_child_list.emplace_back(StringUtil::Format("c%llu", internal_child_list.size()), child.second);
103145 }
103146 return LogicalType::STRUCT(std::move(internal_child_list));
103147 });
103148
103149 // Decode: for each column we have two arguments: 1. col name + type, 2. sort specifier
103150 decode_children.emplace_back(make_uniq<BoundConstantExpression>(Value(col_name + " " + col_type.ToString())));
103151 decode_children.emplace_back(make_uniq<BoundConstantExpression>(order.GetOrderModifier()));
103152 }
103153
103154 ErrorData error;
103155 create_sort_key = binder.BindScalarFunction(DEFAULT_SCHEMA, "create_sort_key", std::move(create_children), error);
103156 if (!create_sort_key) {
103157 throw InternalException("Unable to bind create_sort_key in Sort::Sort");
103158 }
103159
103160 switch (create_sort_key->return_type.id()) {
103161 case LogicalTypeId::BIGINT:
103162 decode_children.insert(decode_children.begin(),
103163 make_uniq<BoundReferenceExpression>(LogicalType::BIGINT, static_cast<storage_t>(0)));
103164 break;
103165 default:
103166 D_ASSERT(create_sort_key->return_type.id() == LogicalTypeId::BLOB);
103167 decode_children.insert(decode_children.begin(),
103168 make_uniq<BoundReferenceExpression>(LogicalType::BLOB, static_cast<storage_t>(0)));
103169 }
103170
103171 decode_sort_key = binder.BindScalarFunction(DecodeSortKeyFun::GetFunction(), std::move(decode_children));
103172 if (!decode_sort_key) {
103173 throw InternalException("Unable to bind decode_sort_key in Sort::Sort");
103174 }
103175
103176 // A bit hacky, but this way we make sure that the output does contain the unnamed structs again
103177 decode_sort_key->return_type = LogicalType::STRUCT(std::move(decode_child_list));
103178
103179 // For convenience, we fill the projection map if it is empty
103180 if (projection_map.empty()) {
103181 projection_map.reserve(input_types.size());
103182 for (idx_t col_idx = 0; col_idx < input_types.size(); col_idx++) {
103183 projection_map.push_back(col_idx);
103184 }
103185 }
103186
103187 // We need to output this many columns, reserve
103188 output_projection_columns.reserve(projection_map.size());
103189
103190 // Create mapping from input column to key (so we won't duplicate columns in key/payload)
103191 unordered_map<idx_t, idx_t> input_column_to_key;
103192 for (idx_t key_idx = 0; key_idx < orders.size(); key_idx++) {
103193 const auto &key_order_expr = *orders[key_idx].expression;
103194 if (key_order_expr.GetExpressionClass() == ExpressionClass::BOUND_REF) {
103195 input_column_to_key.emplace(key_order_expr.Cast<BoundReferenceExpression>().index, key_idx);
103196 }
103197 }
103198
103199 // Construct payload layout (excluding columns that also appear as key)
103200 vector<LogicalType> payload_types;
103201 for (idx_t output_col_idx = 0; output_col_idx < projection_map.size(); output_col_idx++) {
103202 const auto &input_col_idx = projection_map[output_col_idx];
103203 const auto it = input_column_to_key.find(input_col_idx);
103204 if (it != input_column_to_key.end()) {
103205 // Projected column also appears as a key, just reference it
103206 output_projection_columns.push_back({false, it->second, output_col_idx});
103207 } else {
103208 // Projected column does not appear as a key, add to payload layout
103209 output_projection_columns.push_back({true, payload_types.size(), output_col_idx});
103210 payload_types.push_back(input_types[input_col_idx]);
103211 input_projection_map.push_back(input_col_idx);
103212 }
103213 }
103214 payload_layout->Initialize(payload_types, TupleDataValidityType::CAN_HAVE_NULL_VALUES);
103215
103216 // Sort the output projection columns so we're gathering the columns in order
103217 std::sort(output_projection_columns.begin(), output_projection_columns.end(),
103218 [](const SortProjectionColumn &lhs, const SortProjectionColumn &rhs) {
103219 if (lhs.is_payload == rhs.is_payload) {
103220 return lhs.layout_col_idx < rhs.layout_col_idx;
103221 }
103222 return lhs.is_payload < rhs.is_payload;
103223 });
103224
103225 // Finally, initialize the key layout (now that we know whether we have a payload)
103226 key_layout->Initialize(orders, create_sort_key->return_type, !payload_types.empty());
103227}
vector< idx_t > input_projection_map
Mapping from key/payload layouts to output columns.
Definition duckdb.cpp:60119
bool is_index_sort
Whether to force an approximate sort.
Definition duckdb.cpp:60123
ClientContext & context
The client context.
Definition duckdb.cpp:60106
unique_ptr< Expression > create_sort_key
Key orders, expressions, and layout.
Definition duckdb.cpp:60110
static string Format(const string fmt_str, ARGS... params)
Format a string using printf semantics.
Definition duckdb.hpp:4002
idx_t storage_t
Type used for storage (column) identifiers.
Definition duckdb.hpp:261
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

Member Function Documentation

◆ GetLocalSinkState()

unique_ptr< LocalSinkState > duckdb::Sort::GetLocalSinkState ( ExecutionContext & context) const
103337 {
103338 return make_uniq<SortLocalSinkState>(*this, context.client);
103339}

◆ GetGlobalSinkState()

unique_ptr< GlobalSinkState > duckdb::Sort::GetGlobalSinkState ( ClientContext & context) const
103341 {
103342 return make_uniq<SortGlobalSinkState>(context);
103343}

◆ Sink()

SinkResultType duckdb::Sort::Sink ( ExecutionContext & context,
DataChunk & chunk,
OperatorSinkInput & input ) const
103369 {
103370 auto &gstate = input.global_state.Cast<SortGlobalSinkState>();
103371 auto &lstate = input.local_state.Cast<SortLocalSinkState>();
103372
103373 if (!lstate.sorted_run) {
103374 lstate.InitializeSortedRun(*this, context.client);
103375 gstate.UpdateLocalState(lstate);
103376 }
103377
103378 // Sink data into sorted run
103379 lstate.key.Reset();
103380 lstate.payload.Reset();
103381 lstate.key_executor.Execute(chunk, lstate.key);
103382 lstate.payload.ReferenceColumns(chunk, input_projection_map);
103383 lstate.sorted_run->Sink(lstate.key, lstate.payload);
103384
103385 // Try to finish this call to Sink
103386 unique_lock<mutex> guard;
103387 if (TryFinishSink(gstate, lstate, guard)) {
103388 return SinkResultType::NEED_MORE_INPUT;
103389 }
103390
103391 // Grab the lock, update the local state, and see if we can finish now
103392 guard = gstate.Lock();
103393 gstate.UpdateLocalState(lstate);
103394 if (TryFinishSink(gstate, lstate, guard)) {
103395 return SinkResultType::NEED_MORE_INPUT;
103396 }
103397
103398 // Still no, this thread must try to increase the limit
103399 gstate.TryIncreaseReservation(context.client, lstate, is_index_sort, guard);
103400 gstate.UpdateLocalState(lstate);
103401 guard.unlock(); // Can unlock now, local state is definitely up-to-date
103402
103403 // This can return false if we somehow still don't have enough memory
103404 // We'll likely run into an OOM exception
103405 TryFinishSink(gstate, lstate, guard);
103406
103407 return SinkResultType::NEED_MORE_INPUT;
103408}
static bool TryFinishSink(SortGlobalSinkState &gstate, SortLocalSinkState &lstate, unique_lock< mutex > &guard)
Returns true if the Sink call is done (either because run size is small or because run was finalized)...
Definition duckdb.cpp:103346

◆ Combine()

SinkCombineResultType duckdb::Sort::Combine ( ExecutionContext & context,
OperatorSinkCombineInput & input ) const
103410 {
103411 auto &gstate = input.global_state.Cast<SortGlobalSinkState>();
103412 auto &lstate = input.local_state.Cast<SortLocalSinkState>();
103413
103414 if (!lstate.sorted_run) {
103415 return SinkCombineResultType::FINISHED;
103416 }
103417
103418 // Set any_combined under lock
103419 auto guard = gstate.Lock();
103420 gstate.any_combined = true;
103421 guard.unlock();
103422
103423 // Do the final local sort (lock-free)
103424 lstate.sorted_run->Finalize(gstate.external);
103425
103426 // Append to global state (grabs lock)
103427 gstate.AddSortedRun(lstate);
103428
103429 return SinkCombineResultType::FINISHED;
103430}

◆ Finalize()

SinkFinalizeType duckdb::Sort::Finalize ( ClientContext & context,
OperatorSinkFinalizeInput & input ) const
103432 {
103433 auto &gstate = input.global_state.Cast<SortGlobalSinkState>();
103434 if (gstate.sorted_runs.empty()) {
103435 return SinkFinalizeType::NO_OUTPUT_POSSIBLE;
103436 }
103437
103438 idx_t maximum_run_count = 0;
103439 for (const auto &sorted_run : gstate.sorted_runs) {
103440 gstate.total_count += sorted_run->Count();
103441 maximum_run_count = MaxValue(maximum_run_count, sorted_run->Count());
103442 }
103443 if (context.config.verify_parallelism) {
103444 gstate.partition_size = STANDARD_VECTOR_SIZE;
103445 } else {
103446 gstate.partition_size = MinValue<idx_t>(gstate.total_count, DEFAULT_ROW_GROUP_SIZE);
103447 }
103448
103449 return SinkFinalizeType::READY;
103450}

◆ GetSinkProgress()

ProgressData duckdb::Sort::GetSinkProgress ( ClientContext & context,
GlobalSinkState & gstate,
const ProgressData source_progress ) const
103453 {
103454 auto &gstate = gstate_p.Cast<SortGlobalSinkState>();
103455 // Estimate that half of the Sink effort is sorting
103456 ProgressData res;
103457 const auto sorted_tuples = static_cast<double>(gstate.sorted_tuples);
103458 res.done = source_progress.done / 2 + sorted_tuples / 2;
103459 res.total = source_progress.total;
103460 res.invalid = source_progress.invalid;
103461 return res;
103462}

◆ GetLocalSourceState()

unique_ptr< LocalSourceState > duckdb::Sort::GetLocalSourceState ( ExecutionContext & context,
GlobalSourceState & gstate ) const
103513 {
103514 return make_uniq<SortLocalSourceState>(*this, context, gstate.Cast<SortGlobalSourceState>());
103515}

◆ GetGlobalSourceState()

unique_ptr< GlobalSourceState > duckdb::Sort::GetGlobalSourceState ( ClientContext & context,
GlobalSinkState & sink ) const
103517 {
103518 return make_uniq<SortGlobalSourceState>(*this, context, sink.Cast<SortGlobalSinkState>());
103519}

◆ GetData()

SourceResultType duckdb::Sort::GetData ( ExecutionContext & context,
DataChunk & chunk,
OperatorSourceInput & input ) const
103521 {
103522 auto &gstate = input.global_state.Cast<SortGlobalSourceState>();
103523 if (gstate.merger.total_count == 0) {
103524 return SourceResultType::FINISHED;
103525 }
103526 auto &lstate = input.local_state.Cast<SortLocalSourceState>();
103527 OperatorSourceInput merger_input {*gstate.merger_global_state, *lstate.merger_local_state, input.interrupt_state};
103528 return gstate.merger.GetData(context, chunk, merger_input);
103529}

◆ GetPartitionData()

OperatorPartitionData duckdb::Sort::GetPartitionData ( ExecutionContext & context,
DataChunk & chunk,
GlobalSourceState & gstate,
LocalSourceState & lstate,
const OperatorPartitionInfo & partition_info ) const
103541 {
103542 auto &gstate = gstate_p.Cast<SortGlobalSourceState>();
103543 auto &lstate = lstate_p.Cast<SortLocalSourceState>();
103544 return gstate.merger.GetPartitionData(context, chunk, *gstate.merger_global_state, *lstate.merger_local_state,
103545 partition_info);
103546}

◆ GetProgress()

ProgressData duckdb::Sort::GetProgress ( ClientContext & context,
GlobalSourceState & gstate ) const
103531 {
103532 auto &gstate = gstate_p.Cast<SortGlobalSourceState>();
103533 if (gstate.merger.total_count == 0) {
103534 return ProgressData {};
103535 }
103536 return gstate.merger.GetProgress(context, *gstate.merger_global_state);
103537}

◆ MaterializeColumnData()

SourceResultType duckdb::Sort::MaterializeColumnData ( ExecutionContext & context,
OperatorSourceInput & input ) const
103551 {
103552 auto &gstate = input.global_state.Cast<SortGlobalSourceState>();
103553
103554 // Derive output types
103555 vector<LogicalType> types;
103556 types.resize(output_projection_columns.size());
103557 for (auto &opc : output_projection_columns) {
103558 const auto &type = opc.is_payload ? payload_layout->GetTypes()[opc.layout_col_idx]
103559 : StructType::GetChildType(decode_sort_key->return_type, opc.layout_col_idx);
103560 types[opc.output_col_idx] = type;
103561 }
103562
103563 // Initialize scan chunk
103564 DataChunk chunk;
103565 chunk.Initialize(context.client, types);
103566
103567 // Initialize local output collection
103568 auto local_column_data =
103569 make_uniq<BatchedDataCollection>(context.client, types, ColumnDataAllocatorType::BUFFER_MANAGER_ALLOCATOR);
103570
103571 while (true) {
103572 // Check for interrupts since this could be a long-running task
103573 if (context.client.interrupted.load(std::memory_order_relaxed)) {
103574 throw InterruptException();
103575 }
103576 // Scan a chunk
103577 chunk.Reset();
103578 GetData(context, chunk, input);
103579 if (chunk.size() == 0) {
103580 break;
103581 }
103582 // Append to the output collection
103583 const auto batch_index =
103584 GetPartitionData(context, chunk, input.global_state, input.local_state, OperatorPartitionInfo())
103585 .batch_index;
103586 local_column_data->Append(chunk, batch_index);
103587 }
103588
103589 // Merge into global output collection
103590 {
103591 auto guard = gstate.Lock();
103592 if (!gstate.column_data) {
103593 gstate.column_data = std::move(local_column_data);
103594 } else {
103595 gstate.column_data->Merge(*local_column_data);
103596 }
103597 }
103598
103599 // Destroy local state before returning
103600 input.local_state.Cast<SortLocalSourceState>().merger_local_state.reset();
103601
103602 // Return type indicates whether materialization is done
103603 const auto progress_data = GetProgress(context.client, input.global_state);
103604 if (progress_data.done == progress_data.total) {
103605 // Destroy global state before returning
103606 gstate.Destroy();
103607 return SourceResultType::FINISHED;
103608 }
103609 return SourceResultType::HAVE_MORE_OUTPUT;
103610}
DUCKDB_API void Reset()
Definition duckdb.cpp:116840
DUCKDB_API void Initialize(ClientContext &context, const vector< LogicalType > &types, idx_t capacity=STANDARD_VECTOR_SIZE)
Definition duckdb.cpp:116791
@ BUFFER_MANAGER_ALLOCATOR
Use a buffer manager to allocate large chunks of memory that vectors then use.
Definition duckdb.hpp:18799

◆ GetColumnData()

unique_ptr< ColumnDataCollection > duckdb::Sort::GetColumnData ( OperatorSourceInput & input) const
103612 {
103613 auto &gstate = input.global_state.Cast<SortGlobalSourceState>();
103614 auto guard = gstate.Lock();
103615 return gstate.column_data->FetchCollection();
103616}

◆ MaterializeSortedRun()

SourceResultType duckdb::Sort::MaterializeSortedRun ( ExecutionContext & context,
OperatorSourceInput & input ) const
103618 {
103619 auto &gstate = input.global_state.Cast<SortGlobalSourceState>();
103620 if (gstate.merger.total_count == 0) {
103621 return SourceResultType::FINISHED;
103622 }
103623 auto &lstate = input.local_state.Cast<SortLocalSourceState>();
103624 OperatorSourceInput merger_input {*gstate.merger_global_state, *lstate.merger_local_state, input.interrupt_state};
103625 return gstate.merger.MaterializeSortedRun(context, merger_input);
103626}

◆ GetSortedRun()

unique_ptr< SortedRun > duckdb::Sort::GetSortedRun ( GlobalSourceState & global_state)
103628 {
103629 auto &gstate = global_state.Cast<SortGlobalSourceState>();
103630 if (gstate.merger.total_count == 0) {
103631 return nullptr;
103632 }
103633 return gstate.merger.GetSortedRun(*gstate.merger_global_state);
103634}

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