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

QueryProfiler collects the profiling metrics of a query. More...

#include <duckdb.hpp>

Collaboration diagram for duckdb::QueryProfiler:

Public Types

using TreeMap = reference_map_t<const PhysicalOperator, reference<ProfilingNode>>

Public Member Functions

DUCKDB_API QueryProfiler (ClientContext &context)
DUCKDB_API bool IsEnabled () const
DUCKDB_API bool IsDetailedEnabled () const
DUCKDB_API ProfilerPrintFormat GetPrintFormat (ExplainFormat format=ExplainFormat::DEFAULT) const
DUCKDB_API bool PrintOptimizerOutput () const
DUCKDB_API string GetSaveLocation () const
DUCKDB_API void Start (const string &query)
DUCKDB_API void Reset ()
DUCKDB_API void StartQuery (const string &query, bool is_explain_analyze=false, bool start_at_optimizer=false)
DUCKDB_API void EndQuery ()
DUCKDB_API void FinalizeMetrics ()
 Finalize query metrics for output; safe to call multiple times.
DUCKDB_API void AddToCounter (MetricType type, const idx_t amount)
 Adds amount to a specific metric type.
DUCKDB_API ActiveTimer StartTimer (MetricType type)
 Start/End a timer for a specific metric type.
DUCKDB_API void StartExplainAnalyze ()
DUCKDB_API void Flush (OperatorProfiler &profiler)
 Adds the timings gathered by an OperatorProfiler to this query profiler.
DUCKDB_API void SetBlockedTime (const double &blocked_thread_time)
 Adds the top level query information to the global profiler.
DUCKDB_API void StartPhase (MetricType phase_metric)
DUCKDB_API void EndPhase ()
DUCKDB_API void Initialize (const PhysicalOperator &root)
DUCKDB_API string QueryTreeToString () const
DUCKDB_API void QueryTreeToStream (std::ostream &str) const
DUCKDB_API void Print ()
DUCKDB_API string ToString (ExplainFormat format=ExplainFormat::DEFAULT) const
 return the printed as a string. Unlike ToString, which is always formatted as a string, the return value is formatted based on the current print format (see GetPrintFormat()).
DUCKDB_API string ToString (ProfilerPrintFormat format) const
DUCKDB_API void ToLog () const
DUCKDB_API string ToJSON () const
DUCKDB_API void WriteToFile (const char *path, string &info) const
DUCKDB_API idx_t GetBytesRead () const
DUCKDB_API idx_t GetBytesWritten () const
idx_t OperatorSize ()
void Finalize (ProfilingNode &node)
optional_ptr< ProfilingNode > GetRoot ()
 Return the root of the query tree.
DUCKDB_API void GetRootUnderLock (const std::function< void(optional_ptr< ProfilingNode >)> &callback)
 Provides access to the root of the query tree, but ensures there are no concurrent modifications. This can be useful when implementing continuous profiling or making customizations.
const TreeMap & GetTreeMap () const

Static Public Member Functions

static DUCKDB_API QueryProfiler & Get (ClientContext &context)
static Value JSONSanitize (const Value &input)
static string JSONSanitize (const string &text)
static string DrawPadded (const string &str, idx_t width)

Private Types

using PhaseTimingStorage = unordered_map<MetricType, double, MetricTypeHashFunction>
 A mapping of the phase names to the timings.
using PhaseTimingItem = PhaseTimingStorage::value_type

Private Member Functions

unique_ptr< ProfilingNode > CreateTree (const PhysicalOperator &root, const profiler_settings_t &settings, const idx_t depth=0)
void Render (const ProfilingNode &node, std::ostream &str) const
string RenderDisabledMessage (ProfilerPrintFormat format) const
void MoveOptimizerPhasesToRoot ()
void FinalizeMetricsInternal ()
bool OperatorRequiresProfiling (const PhysicalOperatorType op_type)
 Check whether or not an operator type requires query profiling. If none of the ops in a query require profiling no profiling information is output.
ExplainFormat GetExplainFormat (ProfilerPrintFormat format) const

Private Attributes

ClientContext & context
bool running
 Whether or not the query profiler is running.
std::mutex lock
 The lock used for accessing the global query profiler or flushing information to it from a thread.
bool query_requires_profiling
 Whether or not the query requires profiling.
unique_ptr< ProfilingNode > root
 The root of the query tree.
QueryMetrics query_metrics
 Top level query information.
TreeMap tree_map
 A map of a Physical Operator pointer to a tree node.
bool is_explain_analyze
 Whether or not we are running as part of a explain_analyze query.
bool metrics_finalized
 Whether root metrics have been finalized for output.
Profiler phase_profiler
 The timer used to time the individual phases of the planning process.
PhaseTimingStorage phase_timings
vector< MetricType > phase_stack
 The stack of currently active phases.

Detailed Description

QueryProfiler collects the profiling metrics of a query.

Constructor & Destructor Documentation

◆ QueryProfiler()

duckdb::QueryProfiler::QueryProfiler ( ClientContext & context)
explicit
295052 : context(context_p), running(false), query_requires_profiling(false), is_explain_analyze(false),
295053 metrics_finalized(false) {
295054}
bool is_explain_analyze
Whether or not we are running as part of a explain_analyze query.
Definition duckdb.hpp:36922
bool query_requires_profiling
Whether or not the query requires profiling.
Definition duckdb.hpp:36911
bool metrics_finalized
Whether root metrics have been finalized for output.
Definition duckdb.hpp:36924
bool running
Whether or not the query profiler is running.
Definition duckdb.hpp:36906

Member Function Documentation

◆ IsEnabled()

bool duckdb::QueryProfiler::IsEnabled ( ) const
295056 {
295057 return is_explain_analyze || ClientConfig::GetConfig(context).enable_profiler;
295058}

◆ IsDetailedEnabled()

bool duckdb::QueryProfiler::IsDetailedEnabled ( ) const
295060 {
295061 return !is_explain_analyze && ClientConfig::GetConfig(context).enable_detailed_profiling;
295062}

◆ GetPrintFormat()

ProfilerPrintFormat duckdb::QueryProfiler::GetPrintFormat ( ExplainFormat format = ExplainFormat::DEFAULT) const
295064 {
295065 auto print_format = ClientConfig::GetConfig(context).profiler_print_format;
295066 switch (format) {
295067 case ExplainFormat::DEFAULT:
295068 if (print_format != ProfilerPrintFormat::NO_OUTPUT) {
295069 return print_format;
295070 }
295071 DUCKDB_EXPLICIT_FALLTHROUGH;
295072 case ExplainFormat::TEXT:
295073 return ProfilerPrintFormat::QUERY_TREE;
295074 case ExplainFormat::JSON:
295075 return ProfilerPrintFormat::JSON;
295076 case ExplainFormat::HTML:
295077 return ProfilerPrintFormat::HTML;
295078 case ExplainFormat::GRAPHVIZ:
295079 return ProfilerPrintFormat::GRAPHVIZ;
295080 case ExplainFormat::MERMAID:
295081 return ProfilerPrintFormat::MERMAID;
295082 default:
295083 throw NotImplementedException("No mapping from ExplainFormat::%s to ProfilerPrintFormat",
295084 EnumUtil::ToString(format));
295085 }
295086}
std::basic_string< Char > format(const S &format_str, Args &&... args)
Definition duckdb.cpp:16295

◆ PrintOptimizerOutput()

bool duckdb::QueryProfiler::PrintOptimizerOutput ( ) const
295109 {
295110 return GetPrintFormat() == ProfilerPrintFormat::QUERY_TREE_OPTIMIZER || IsDetailedEnabled();
295111}

◆ GetSaveLocation()

string duckdb::QueryProfiler::GetSaveLocation ( ) const
295113 {
295114 return is_explain_analyze ? string() : ClientConfig::GetConfig(context).profiler_save_location;
295115}

◆ Get()

QueryProfiler & duckdb::QueryProfiler::Get ( ClientContext & context)
static
295117 {
295118 return *ClientData::Get(context).profiler;
295119}

◆ Start()

void duckdb::QueryProfiler::Start ( const string & query)
295121 {
295122 Reset();
295123 running = true;
295124 query_metrics.query_name = query;
295125 query_metrics.latency_timer = make_uniq<ActiveTimer>(StartTimer(MetricType::LATENCY));
295126}
QueryMetrics query_metrics
Top level query information.
Definition duckdb.hpp:36917
DUCKDB_API ActiveTimer StartTimer(MetricType type)
Start/End a timer for a specific metric type.
Definition duckdb.cpp:295277

◆ Reset()

void duckdb::QueryProfiler::Reset ( )
295128 {
295129 tree_map.clear();
295130 root = nullptr;
295131 phase_timings.clear();
295132 phase_stack.clear();
295133 running = false;
295134 query_metrics.Reset();
295135 metrics_finalized = false;
295136}
unique_ptr< ProfilingNode > root
The root of the query tree.
Definition duckdb.hpp:36914
vector< MetricType > phase_stack
The stack of currently active phases.
Definition duckdb.hpp:36939
TreeMap tree_map
A map of a Physical Operator pointer to a tree node.
Definition duckdb.hpp:36920

◆ StartQuery()

void duckdb::QueryProfiler::StartQuery ( const string & query,
bool is_explain_analyze = false,
bool start_at_optimizer = false )
295138 {
295139 lock_guard<std::mutex> guard(lock);
295140 if (is_explain_analyze_p) {
295141 StartExplainAnalyze();
295142 }
295143 if (!IsEnabled()) {
295144 return;
295145 }
295146 if (start_at_optimizer && !PrintOptimizerOutput()) {
295147 // This is the StartQuery call before the optimizer, but we don't have to print optimizer output
295148 return;
295149 }
295150 if (running) {
295151 // Called while already running: this should only happen when we print optimizer output
295152 // D_ASSERT(PrintOptimizerOutput());
295153 return;
295154 }
295155 Start(query);
295156}
std::mutex lock
The lock used for accessing the global query profiler or flushing information to it from a thread.
Definition duckdb.hpp:36908

◆ EndQuery()

void duckdb::QueryProfiler::EndQuery ( )
295222 {
295223 unique_lock<std::mutex> guard(lock);
295224 if (!IsEnabled() || !running) {
295225 return;
295226 }
295227
295228 FinalizeMetricsInternal();
295229 running = false;
295230 bool emit_output = false;
295231
295232 // Print or output the query profiling after query termination.
295233 // EXPLAIN ANALYZE output is not written by the profiler.
295234 if (IsEnabled() && !is_explain_analyze && ClientConfig::GetConfig(context).emit_profiler_output) {
295235 emit_output = true;
295236 }
295237
295238 is_explain_analyze = false;
295239
295240 guard.unlock();
295241
295242 // To log is inexpensive, whether to log or not depends on whether logging is active
295243 ToLog();
295244
295245 if (emit_output) {
295246 string tree = ToString();
295247 auto save_location = GetSaveLocation();
295248
295249 if (save_location.empty()) {
295250 Printer::Print(tree);
295251 Printer::Print("\n");
295252 } else {
295253 WriteToFile(save_location.c_str(), tree);
295254 }
295255 }
295256}
static DUCKDB_API void Print(OutputStream stream, const string &str)
Print the object to the stream.
Definition duckdb.cpp:92556
DUCKDB_API string ToString(ExplainFormat format=ExplainFormat::DEFAULT) const
return the printed as a string. Unlike ToString, which is always formatted as a string,...
Definition duckdb.cpp:295281

◆ FinalizeMetrics()

void duckdb::QueryProfiler::FinalizeMetrics ( )

Finalize query metrics for output; safe to call multiple times.

295258 {
295259 lock_guard<std::mutex> guard(lock);
295260 FinalizeMetricsInternal();
295261}

◆ AddToCounter()

void duckdb::QueryProfiler::AddToCounter ( MetricType type,
const idx_t amount )

Adds amount to a specific metric type.

295263 {
295264 if (IsEnabled()) {
295265 query_metrics.UpdateMetric(type, amount);
295266 }
295267}

◆ StartTimer()

ActiveTimer duckdb::QueryProfiler::StartTimer ( MetricType type)

Start/End a timer for a specific metric type.

295277 {
295278 return ActiveTimer(query_metrics, type, IsEnabled());
295279}

◆ StartExplainAnalyze()

void duckdb::QueryProfiler::StartExplainAnalyze ( )
295218 {
295219 is_explain_analyze = true;
295220}

◆ Flush()

void duckdb::QueryProfiler::Flush ( OperatorProfiler & profiler)

Adds the timings gathered by an OperatorProfiler to this query profiler.

295496 {
295497 lock_guard<std::mutex> guard(lock);
295498 if (!IsEnabled() || !running) {
295499 return;
295500 }
295501 for (auto &node : profiler.operator_infos) {
295502 auto &op = node.first.get();
295503 auto entry = tree_map.find(op);
295504 D_ASSERT(entry != tree_map.end());
295505
295506 auto &tree_node = entry->second.get();
295507 auto &info = tree_node.GetProfilingInfo();
295508
295509 if (ProfilingInfo::Enabled(profiler.settings, MetricType::OPERATOR_TIMING)) {
295510 info.MetricSum<double>(MetricType::OPERATOR_TIMING, node.second.time);
295511 }
295512 if (ProfilingInfo::Enabled(profiler.settings, MetricType::OPERATOR_CARDINALITY)) {
295513 info.MetricSum<idx_t>(MetricType::OPERATOR_CARDINALITY, node.second.elements_returned);
295514 }
295515 if (ProfilingInfo::Enabled(profiler.settings, MetricType::OPERATOR_ROWS_SCANNED)) {
295516 info.MetricSum<idx_t>(MetricType::OPERATOR_ROWS_SCANNED, node.second.rows_scanned);
295517 }
295518 if (ProfilingInfo::Enabled(profiler.settings, MetricType::RESULT_SET_SIZE)) {
295519 info.MetricSum<idx_t>(MetricType::RESULT_SET_SIZE, node.second.result_set_size);
295520 }
295521 if (ProfilingInfo::Enabled(profiler.settings, MetricType::EXTRA_INFO)) {
295522 info.metrics[MetricType::EXTRA_INFO] = Value::MAP(node.second.extra_info);
295523 }
295524 if (ProfilingInfo::Enabled(profiler.settings, MetricType::SYSTEM_PEAK_BUFFER_MEMORY)) {
295525 query_metrics.query_global_info.MetricMax(MetricType::SYSTEM_PEAK_BUFFER_MEMORY,
295526 node.second.system_peak_buffer_manager_memory);
295527 }
295528 if (ProfilingInfo::Enabled(profiler.settings, MetricType::SYSTEM_PEAK_TEMP_DIR_SIZE)) {
295529 query_metrics.query_global_info.MetricMax(MetricType::SYSTEM_PEAK_TEMP_DIR_SIZE,
295530 node.second.system_peak_temp_directory_size);
295531 }
295532 }
295533 profiler.operator_infos.clear();
295534}
static bool Enabled(const profiler_settings_t &settings, const MetricType metric)
Returns true, if the query profiler must collect this metric.
Definition duckdb.cpp:294685
static DUCKDB_API Value MAP(const LogicalType &child_type, vector< Value > values)
Create a map value with the given entries.
Definition duckdb.cpp:132466
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
Here is the call graph for this function:

◆ SetBlockedTime()

void duckdb::QueryProfiler::SetBlockedTime ( const double & blocked_thread_time)

Adds the top level query information to the global profiler.

295536 {
295537 lock_guard<std::mutex> guard(lock);
295538 if (!IsEnabled() || !running) {
295539 return;
295540 }
295541
295542 auto &info = root->GetProfilingInfo();
295543 if (info.Enabled(info.expanded_settings, MetricType::BLOCKED_THREAD_TIME)) {
295544 query_metrics.query_global_info.metrics[MetricType::BLOCKED_THREAD_TIME] = blocked_thread_time;
295545 }
295546}

◆ StartPhase()

void duckdb::QueryProfiler::StartPhase ( MetricType phase_metric)
295316 {
295317 lock_guard<std::mutex> guard(lock);
295318 if (!IsEnabled() || !running) {
295319 return;
295320 }
295321
295322 // start a new phase
295323 phase_stack.push_back(phase_metric);
295324 // restart the timer
295325 phase_profiler.Start();
295326}
Profiler phase_profiler
The timer used to time the individual phases of the planning process.
Definition duckdb.hpp:36933

◆ EndPhase()

void duckdb::QueryProfiler::EndPhase ( )
295328 {
295329 lock_guard<std::mutex> guard(lock);
295330 if (!IsEnabled() || !running) {
295331 return;
295332 }
295333 D_ASSERT(!phase_stack.empty());
295334
295335 // end the timer
295336 phase_profiler.End();
295337 // add the timing to all currently active phases
295338 for (auto &phase : phase_stack) {
295339 phase_timings[phase] += phase_profiler.Elapsed();
295340 }
295341 // now remove the last added phase
295342 phase_stack.pop_back();
295343
295344 if (!phase_stack.empty()) {
295345 phase_profiler.Start();
295346 }
295347}
void phase(InputArray x, InputArray y, OutputArray angle, bool angleInDegrees=false)

◆ Initialize()

void duckdb::QueryProfiler::Initialize ( const PhysicalOperator & root)
295903 : {
295904 ConvertedJSONHolder json_holder;
295905 json_holder.doc = yyjson_mut_doc_new(nullptr);
295906 auto result_obj = yyjson_mut_obj(json_holder.doc);
295907 yyjson_mut_doc_set_root(json_holder.doc, result_obj);
295908
295909 yyjson_mut_obj_add_str(json_holder.doc, result_obj, "result", "disabled");
295910 return StringifyAndFree(json_holder, result_obj);
295911 }
295912 default:
295913 throw InternalException("Unknown ProfilerPrintFormat \"%s\"", EnumUtil::ToString(format));
295914 }
295915}
295916
295917void QueryProfiler::Initialize(const PhysicalOperator &root_op) {
295918 lock_guard<std::mutex> guard(lock);
295919 if (!IsEnabled() || !running) {
yyjson_api_inline void yyjson_mut_doc_set_root(yyjson_mut_doc *doc, yyjson_mut_val *root)
Definition duckdb.cpp:42425
yyjson_api yyjson_mut_doc * yyjson_mut_doc_new(const yyjson_alc *alc)
Definition duckdb.cpp:599384
yyjson_api_inline bool yyjson_mut_obj_add_str(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key, const char *val)
Definition duckdb.cpp:43974
yyjson_api_inline yyjson_mut_val * yyjson_mut_obj(yyjson_mut_doc *doc)
Definition duckdb.cpp:43608

◆ QueryTreeToString()

string duckdb::QueryProfiler::QueryTreeToString ( ) const
295585 {
295586 duckdb::stringstream str;
295587 QueryTreeToStream(str);
295588 return str.str();
295589}

◆ QueryTreeToStream()

void duckdb::QueryProfiler::QueryTreeToStream ( std::ostream & str) const
295650 {
295651 lock_guard<std::mutex> guard(lock);
295652
295653 bool show_query_name = false;
295654 if (root) {
295655 auto &info = root->GetProfilingInfo();
295656 auto &settings = info.expanded_settings;
295657 show_query_name = info.Enabled(settings, MetricType::QUERY_NAME);
295658 }
295659 ss << "┌─────────────────────────────────────┐\n";
295660 ss << "│┌───────────────────────────────────┐│\n";
295661 ss << "││ Query Profiling Information ││\n";
295662 ss << "│└───────────────────────────────────┘│\n";
295663 ss << "└─────────────────────────────────────┘\n";
295664 ss << (show_query_name ? StringUtil::Replace(query_metrics.query_name, "\n", " ") : "") + "\n";
295665
295666 // checking the tree to ensure the query is really empty
295667 // the query string is empty when a logical plan is deserialized
295668 if (query_metrics.query_name.empty() && !root) {
295669 return;
295670 }
295671
295672 for (auto &state : context.registered_state->States()) {
295673 state->WriteProfilingInformation(ss);
295674 }
295675
295676 constexpr idx_t TOTAL_BOX_WIDTH = 50;
295677 ss << "┌────────────────────────────────────────────────┐\n";
295678 ss << "│┌──────────────────────────────────────────────┐│\n";
295679 string total_time = "Total Time: " + RenderTiming(query_metrics.GetMetricInSeconds(MetricType::LATENCY));
295680 ss << "││" + DrawPadded(total_time, TOTAL_BOX_WIDTH - 4) + "││\n";
295681 ss << "│└──────────────────────────────────────────────┘│\n";
295682 ss << "└────────────────────────────────────────────────┘\n";
295683 // render the main operator tree
295684 if (root) {
295685 // print phase timings
295686 if (PrintOptimizerOutput()) {
295687 PrintPhaseTimingsToStream(ss, root->GetProfilingInfo(), TOTAL_BOX_WIDTH);
295688 }
295689 Render(*root, ss);
295690 }
295691}

◆ Print()

void duckdb::QueryProfiler::Print ( )

◆ ToString() [1/2]

string duckdb::QueryProfiler::ToString ( ExplainFormat format = ExplainFormat::DEFAULT) const

return the printed as a string. Unlike ToString, which is always formatted as a string, the return value is formatted based on the current print format (see GetPrintFormat()).

295281 {
295282 return ToString(GetPrintFormat(explain_format));
295283}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ToString() [2/2]

string duckdb::QueryProfiler::ToString ( ProfilerPrintFormat format) const
295285 {
295286 if (!IsEnabled()) {
295287 return RenderDisabledMessage(format);
295288 }
295289 switch (format) {
295290 case ProfilerPrintFormat::QUERY_TREE:
295291 case ProfilerPrintFormat::QUERY_TREE_OPTIMIZER:
295292 return QueryTreeToString();
295293 case ProfilerPrintFormat::JSON:
295294 return ToJSON();
295295 case ProfilerPrintFormat::NO_OUTPUT:
295296 return "";
295297 case ProfilerPrintFormat::HTML:
295298 case ProfilerPrintFormat::GRAPHVIZ:
295299 case ProfilerPrintFormat::MERMAID: {
295300 lock_guard<std::mutex> guard(lock);
295301 // checking the tree to ensure the query is really empty
295302 // the query string is empty when a logical plan is deserialized
295303 if (query_metrics.query_name.empty() && !root) {
295304 return "";
295305 }
295306 auto renderer = TreeRenderer::CreateRenderer(GetExplainFormat(format));
295307 stringstream str;
295308 renderer->Render(*root, str);
295309 return str.str();
295310 }
295311 default:
295312 throw InternalException("Unknown ProfilerPrintFormat \"%s\"", EnumUtil::ToString(format));
295313 }
295314}

◆ JSONSanitize()

Value duckdb::QueryProfiler::JSONSanitize ( const Value & input)
static
295693 {
295694 D_ASSERT(input.type().id() == LogicalTypeId::MAP);
295695
295696 InsertionOrderPreservingMap<string> result;
295697 auto children = MapValue::GetChildren(input);
295698 for (auto &child : children) {
295699 auto struct_children = StructValue::GetChildren(child);
295700 auto key = struct_children[0].GetValue<string>();
295701 auto value = struct_children[1].GetValue<string>();
295702
295703 if (StringUtil::StartsWith(key, "__")) {
295704 key = StringUtil::Replace(key, "__", "");
295705 key = StringUtil::Replace(key, "_", " ");
295706 key = StringUtil::Title(key);
295707 }
295708 result[key] = value;
295709 }
295710 return Value::MAP(result);
295711}
static DUCKDB_API bool StartsWith(string str, string prefix)
Returns true if the target string starts with the given prefix.
Definition duckdb.cpp:109377
static DUCKDB_API string Title(const string &str)
Convert a string to Title Case.
Definition duckdb.cpp:109637

◆ DrawPadded()

string duckdb::QueryProfiler::DrawPadded ( const string & str,
idx_t width )
static
295548 {
295549 if (str.size() > width) {
295550 return str.substr(0, width);
295551 } else {
295552 width -= str.size();
295553 auto half_spaces = width / 2;
295554 auto extra_left_space = NumericCast<idx_t>(width % 2 != 0 ? 1 : 0);
295555 return string(half_spaces + extra_left_space, ' ') + str + string(half_spaces, ' ');
295556 }
295557}

◆ ToLog()

void duckdb::QueryProfiler::ToLog ( ) const
295777 {
295778 lock_guard<std::mutex> guard(lock);
295779
295780 if (!root) {
295781 // No root, not much to do
295782 return;
295783 }
295784
295785 auto &settings = root->GetProfilingInfo();
295786
295787 settings.WriteMetricsToLog(context);
295788}

◆ ToJSON()

string duckdb::QueryProfiler::ToJSON ( ) const
295790 {
295791 lock_guard<std::mutex> guard(lock);
295792 ConvertedJSONHolder json_holder;
295793
295794 json_holder.doc = yyjson_mut_doc_new(nullptr);
295795 auto result_obj = yyjson_mut_obj(json_holder.doc);
295796 yyjson_mut_doc_set_root(json_holder.doc, result_obj);
295797
295798 if (query_metrics.query_name.empty() && !root) {
295799 yyjson_mut_obj_add_str(json_holder.doc, result_obj, "result", "empty");
295800 return StringifyAndFree(json_holder, result_obj);
295801 }
295802 if (!root) {
295803 yyjson_mut_obj_add_str(json_holder.doc, result_obj, "result", "error");
295804 return StringifyAndFree(json_holder, result_obj);
295805 }
295806
295807 auto &settings = root->GetProfilingInfo();
295808
295809 settings.WriteMetricsToJSON(json_holder.doc, result_obj);
295810
295811 // recursively print the physical operator tree
295812 auto children_list = yyjson_mut_arr(json_holder.doc);
295813 yyjson_mut_obj_add_val(json_holder.doc, result_obj, "children", children_list);
295814 auto child = ToJSONRecursive(json_holder.doc, *root->GetChild(0));
295815 yyjson_mut_arr_add_val(children_list, child);
295816 return StringifyAndFree(json_holder, result_obj);
295817}
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr(yyjson_mut_doc *doc)
Definition duckdb.cpp:42941
yyjson_api_inline bool yyjson_mut_obj_add_val(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key, yyjson_mut_val *val)
Definition duckdb.cpp:44042
yyjson_api_inline bool yyjson_mut_arr_add_val(yyjson_mut_val *arr, yyjson_mut_val *val)
Definition duckdb.cpp:43342

◆ WriteToFile()

void duckdb::QueryProfiler::WriteToFile ( const char * path,
string & info ) const
295819 {
295820 auto &fs = FileSystem::GetFileSystem(context);
295821 auto flags = FileOpenFlags::FILE_FLAGS_WRITE | FileOpenFlags::FILE_FLAGS_FILE_CREATE_NEW;
295822 auto file = fs.OpenFile(path, flags);
295823 file->Write((void *)info.c_str(), info.size());
295824 file->Close();
295825}

◆ GetBytesRead()

idx_t duckdb::QueryProfiler::GetBytesRead ( ) const
295269 {
295270 return query_metrics.GetMetricValue(MetricType::TOTAL_BYTES_READ);
295271}

◆ GetBytesWritten()

idx_t duckdb::QueryProfiler::GetBytesWritten ( ) const
295273 {
295274 return query_metrics.GetMetricValue(MetricType::TOTAL_BYTES_WRITTEN);
295275}

◆ OperatorSize()

idx_t duckdb::QueryProfiler::OperatorSize ( )
inline
36878 {
36879 return tree_map.size();
36880 }

◆ Finalize()

void duckdb::QueryProfiler::Finalize ( ProfilingNode & node)
295202 {
295203 for (idx_t i = 0; i < node.GetChildCount(); i++) {
295204 auto child = node.GetChild(i);
295205 Finalize(*child);
295206
295207 auto &info = node.GetProfilingInfo();
295208 auto type = PhysicalOperatorType(info.GetMetricValue<uint8_t>(MetricType::OPERATOR_TYPE));
295209 if (type == PhysicalOperatorType::UNION &&
295210 info.Enabled(info.expanded_settings, MetricType::OPERATOR_CARDINALITY)) {
295211 auto &child_info = child->GetProfilingInfo();
295212 auto value = child_info.metrics[MetricType::OPERATOR_CARDINALITY].GetValue<idx_t>();
295213 info.MetricSum(MetricType::OPERATOR_CARDINALITY, value);
295214 }
295215 }
295216}

◆ GetRoot()

optional_ptr< ProfilingNode > duckdb::QueryProfiler::GetRoot ( )
inline

Return the root of the query tree.

36885 {
36886 return root.get();
36887 }
Here is the caller graph for this function:

◆ GetRootUnderLock()

DUCKDB_API void duckdb::QueryProfiler::GetRootUnderLock ( const std::function< void(optional_ptr< ProfilingNode >)> & callback)
inline

Provides access to the root of the query tree, but ensures there are no concurrent modifications. This can be useful when implementing continuous profiling or making customizations.

36891 {
36892 lock_guard<std::mutex> guard(lock);
36893 callback(GetRoot());
36894 }
optional_ptr< ProfilingNode > GetRoot()
Return the root of the query tree.
Definition duckdb.hpp:36885
Here is the call graph for this function:

◆ CreateTree()

unique_ptr< ProfilingNode > duckdb::QueryProfiler::CreateTree ( const PhysicalOperator & root,
const profiler_settings_t & settings,
const idx_t depth = 0 )
private
295845 {
295846 if (OperatorRequiresProfiling(root_p.type)) {
295848 }
295849
295850 unique_ptr<ProfilingNode> node = make_uniq<ProfilingNode>();
295851 auto &info = node->GetProfilingInfo();
295852 info = ProfilingInfo(settings, depth);
295853 auto child_settings = settings;
295854 if (depth == 0) {
295855 child_settings = EraseQueryRootSettings(child_settings);
295856 }
295857 node->depth = depth;
295858
295859 if (depth != 0) {
295860 info.metrics[MetricType::OPERATOR_NAME] = root_p.GetName();
295861 info.MetricSum<uint8_t>(MetricType::OPERATOR_TYPE, static_cast<uint8_t>(root_p.type));
295862 }
295863 if (info.Enabled(info.settings, MetricType::EXTRA_INFO)) {
295864 info.metrics[MetricType::EXTRA_INFO] = Value::MAP(root_p.ParamsToString());
295865 }
295866
295867 tree_map.insert(make_pair(reference<const PhysicalOperator>(root_p), reference<ProfilingNode>(*node)));
295868 auto children = root_p.GetChildren();
295869 for (auto &child : children) {
295870 auto child_node = CreateTree(child.get(), child_settings, depth + 1);
295871 node->AddChild(std::move(child_node));
295872 }
295873 return node;
295874}
bool OperatorRequiresProfiling(const PhysicalOperatorType op_type)
Check whether or not an operator type requires query profiling. If none of the ops in a query require...
Definition duckdb.cpp:295158
double depth(InputArray R, InputArray t, InputArray X)
::uint8_t uint8_t

◆ Render()

void duckdb::QueryProfiler::Render ( const ProfilingNode & node,
std::ostream & str ) const
private
295925 {
295926 // query does not require profiling: disable profiling for this query
295927 running = false;
295928 tree_map.clear();
295929 root = nullptr;

◆ RenderDisabledMessage()

string duckdb::QueryProfiler::RenderDisabledMessage ( ProfilerPrintFormat format) const
private
295876 {
295877 switch (format) {
295878 case ProfilerPrintFormat::NO_OUTPUT:
295879 return "";
295880 case ProfilerPrintFormat::QUERY_TREE:
295881 case ProfilerPrintFormat::QUERY_TREE_OPTIMIZER:
295882 return "Query profiling is disabled. Use 'PRAGMA enable_profiling;' to enable profiling!";
295883 case ProfilerPrintFormat::HTML:
295884 return R"(
295885 <!DOCTYPE html>
295886 <html lang="en"><head/><body>
295887 Query profiling is disabled. Use 'PRAGMA enable_profiling;' to enable profiling!
295888 </body></html>
295889 )";
295890 case ProfilerPrintFormat::GRAPHVIZ:
295891 return R"(
295892 digraph G {
295893 node [shape=box, style=rounded, fontname="Courier New", fontsize=10];
295894 node_0_0 [label="Query profiling is disabled. Use 'PRAGMA enable_profiling;' to enable profiling!"];
295895 }
295896 )";
295897 case ProfilerPrintFormat::MERMAID:
295898 return R"(flowchart TD
295899 node_0_0["`**DISABLED**
295900Query profiling is disabled.
295901Use 'PRAGMA enable_profiling;' to enable profiling!`"]

◆ GetTreeMap()

const TreeMap & duckdb::QueryProfiler::GetTreeMap ( ) const
inline
36927 {
36928 return tree_map;
36929 }

◆ MoveOptimizerPhasesToRoot()

void duckdb::QueryProfiler::MoveOptimizerPhasesToRoot ( )
private
295935 {
295936 TextTreeRenderer renderer;
295937 if (IsDetailedEnabled()) {
295938 renderer.EnableDetailed();
295939 } else {
295940 renderer.EnableStandard();
295941 }
295942 renderer.Render(node, ss);
295943}
295944
295945void QueryProfiler::Print() {
295946 Printer::Print(QueryTreeToString());

◆ FinalizeMetricsInternal()

void duckdb::QueryProfiler::FinalizeMetricsInternal ( )
private
295949 {
295950 auto &root_info = root->GetProfilingInfo();
295951 auto &root_metrics = root_info.metrics;
295952
295953 for (auto &entry : phase_timings) {
295954 auto &phase = entry.first;
295955 auto &timing = entry.second;
295956 if (root_info.Enabled(root_info.expanded_settings, phase)) {
295957 root_metrics[phase] = Value::CreateValue(timing);
295958 }
295959 }
295960}
295961
295962void QueryProfiler::FinalizeMetricsInternal() {
295963 if (metrics_finalized || !IsEnabled() || !root) {
295964 return;
295965 }
295966
295967 if (query_metrics.latency_timer) {
295968 query_metrics.latency_timer->EndTimer();
295969 }
295970
295971 auto &info = root->GetProfilingInfo();
295972 if (info.Enabled(info.expanded_settings, MetricType::OPERATOR_CARDINALITY)) {
295973 Finalize(*root->GetChild(0));
295974 }
295975

◆ OperatorRequiresProfiling()

bool duckdb::QueryProfiler::OperatorRequiresProfiling ( const PhysicalOperatorType op_type)
private

Check whether or not an operator type requires query profiling. If none of the ops in a query require profiling no profiling information is output.

295158 {
295159 const auto &config = ClientConfig::GetConfig(context);
295160 if (config.profiling_coverage == ProfilingCoverage::ALL) {
295161 return true;
295162 }
295163
295164 switch (op_type) {
295165 case PhysicalOperatorType::ORDER_BY:
295166 case PhysicalOperatorType::RESERVOIR_SAMPLE:
295167 case PhysicalOperatorType::STREAMING_SAMPLE:
295168 case PhysicalOperatorType::LIMIT:
295169 case PhysicalOperatorType::LIMIT_PERCENT:
295170 case PhysicalOperatorType::STREAMING_LIMIT:
295171 case PhysicalOperatorType::TOP_N:
295172 case PhysicalOperatorType::WINDOW:
295173 case PhysicalOperatorType::UNNEST:
295174 case PhysicalOperatorType::UNGROUPED_AGGREGATE:
295175 case PhysicalOperatorType::HASH_GROUP_BY:
295176 case PhysicalOperatorType::FILTER:
295177 case PhysicalOperatorType::PROJECTION:
295178 case PhysicalOperatorType::COPY_TO_FILE:
295179 case PhysicalOperatorType::TABLE_SCAN:
295180 case PhysicalOperatorType::CHUNK_SCAN:
295181 case PhysicalOperatorType::DELIM_SCAN:
295182 case PhysicalOperatorType::EXPRESSION_SCAN:
295183 case PhysicalOperatorType::BLOCKWISE_NL_JOIN:
295184 case PhysicalOperatorType::NESTED_LOOP_JOIN:
295185 case PhysicalOperatorType::HASH_JOIN:
295186 case PhysicalOperatorType::CROSS_PRODUCT:
295187 case PhysicalOperatorType::PIECEWISE_MERGE_JOIN:
295188 case PhysicalOperatorType::IE_JOIN:
295189 case PhysicalOperatorType::LEFT_DELIM_JOIN:
295190 case PhysicalOperatorType::RIGHT_DELIM_JOIN:
295191 case PhysicalOperatorType::UNION:
295192 case PhysicalOperatorType::RECURSIVE_CTE:
295193 case PhysicalOperatorType::RECURSIVE_KEY_CTE:
295194 case PhysicalOperatorType::EMPTY_RESULT:
295195 case PhysicalOperatorType::EXTENSION:
295196 return true;
295197 default:
295198 return false;
295199 }
295200}

◆ GetExplainFormat()

ExplainFormat duckdb::QueryProfiler::GetExplainFormat ( ProfilerPrintFormat format) const
private
295088 {
295089 switch (format) {
295090 case ProfilerPrintFormat::QUERY_TREE:
295091 case ProfilerPrintFormat::QUERY_TREE_OPTIMIZER:
295092 return ExplainFormat::TEXT;
295093 case ProfilerPrintFormat::JSON:
295094 return ExplainFormat::JSON;
295095 case ProfilerPrintFormat::HTML:
295096 return ExplainFormat::HTML;
295097 case ProfilerPrintFormat::GRAPHVIZ:
295098 return ExplainFormat::GRAPHVIZ;
295099 case ProfilerPrintFormat::MERMAID:
295100 return ExplainFormat::MERMAID;
295101 case ProfilerPrintFormat::NO_OUTPUT:
295102 throw InternalException("Should not attempt to get ExplainFormat for ProfilerPrintFormat::NO_OUTPUT");
295103 default:
295104 throw NotImplementedException("No mapping from ProfilePrintFormat::%s to ExplainFormat",
295105 EnumUtil::ToString(format));
295106 }
295107}

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