Skip to main content

datafusion_physical_plan/
display.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Implementation of physical plan display. See
19//! [`crate::displayable`] for examples of how to format
20
21use std::collections::{BTreeMap, HashMap};
22use std::fmt;
23use std::fmt::Formatter;
24use std::time::Duration;
25
26use serde::Serialize;
27
28use arrow::datatypes::SchemaRef;
29
30use datafusion_common::display::{GraphvizBuilder, PlanType, StringifiedPlan};
31use datafusion_expr::display_schema;
32use datafusion_physical_expr::LexOrdering;
33
34use crate::metrics::{MetricCategory, MetricType, MetricValue};
35use crate::render_tree::RenderTree;
36
37use crate::statistics::{StatisticsArgs, StatisticsContext};
38
39use super::{ExecutionPlan, ExecutionPlanVisitor, accept};
40
41/// Options for controlling how each [`ExecutionPlan`] should format itself
42#[derive(Debug, Clone, Copy, PartialEq)]
43pub enum DisplayFormatType {
44    /// Default, compact format. Example: `FilterExec: c12 < 10.0`
45    ///
46    /// This format is designed to provide a detailed textual description
47    /// of all parts of the plan.
48    Default,
49    /// Verbose, showing all available details.
50    ///
51    /// This form is even more detailed than [`Self::Default`]
52    Verbose,
53    /// TreeRender, displayed in the `tree` explain type.
54    ///
55    /// This format is inspired by DuckDB's explain plans. The information
56    /// presented should be "user friendly", and contain only the most relevant
57    /// information for understanding a plan. It should NOT contain the same level
58    /// of detail information as the  [`Self::Default`] format.
59    ///
60    /// In this mode, each line has one of two formats:
61    ///
62    /// 1. A string without a `=`, which is printed in its own line
63    ///
64    /// 2. A string with a `=` that is treated as a `key=value pair`. Everything
65    ///    before the first `=` is treated as the key, and everything after the
66    ///    first `=` is treated as the value.
67    ///
68    /// For example, if the output of `TreeRender` is this:
69    /// ```text
70    /// Parquet
71    /// partition_sizes=[1]
72    /// ```
73    ///
74    /// It is rendered in the center of a box in the following way:
75    ///
76    /// ```text
77    /// ┌───────────────────────────┐
78    /// │       DataSourceExec      │
79    /// │    --------------------   │
80    /// │    partition_sizes: [1]   │
81    /// │          Parquet          │
82    /// └───────────────────────────┘
83    /// ```
84    TreeRender,
85}
86
87/// Wraps an `ExecutionPlan` with various methods for formatting
88///
89///
90/// # Example
91/// ```
92/// # use std::sync::Arc;
93/// # use arrow::datatypes::{Field, Schema, DataType};
94/// # use datafusion_expr::Operator;
95/// # use datafusion_physical_expr::expressions::{binary, col, lit};
96/// # use datafusion_physical_plan::{displayable, ExecutionPlan};
97/// # use datafusion_physical_plan::empty::EmptyExec;
98/// # use datafusion_physical_plan::filter::FilterExec;
99/// # let schema = Schema::new(vec![Field::new("i", DataType::Int32, false)]);
100/// # let plan = EmptyExec::new(Arc::new(schema));
101/// # let i = col("i", &plan.schema()).unwrap();
102/// # let predicate = binary(i, Operator::Eq, lit(1), &plan.schema()).unwrap();
103/// # let plan: Arc<dyn ExecutionPlan> = Arc::new(FilterExec::try_new(predicate, Arc::new(plan)).unwrap());
104/// // Get a one line description (Displayable)
105/// let display_plan = displayable(plan.as_ref());
106///
107/// // you can use the returned objects to format plans
108/// // where you can use `Display` such as  format! or println!
109/// assert_eq!(
110///    &format!("The plan is: {}", display_plan.one_line()),
111///   "The plan is: FilterExec: i@0 = 1\n"
112/// );
113/// // You can also print out the plan and its children in indented mode
114/// assert_eq!(display_plan.indent(false).to_string(),
115///   "FilterExec: i@0 = 1\
116///   \n  EmptyExec\
117///   \n"
118/// );
119/// ```
120#[derive(Debug, Clone)]
121pub struct DisplayableExecutionPlan<'a> {
122    inner: &'a dyn ExecutionPlan,
123    /// How to show metrics
124    show_metrics: ShowMetrics,
125    /// If statistics should be displayed
126    show_statistics: bool,
127    /// If schema should be displayed. See [`Self::set_show_schema`]
128    show_schema: bool,
129    /// Which metric categories should be included when rendering
130    metric_types: Vec<MetricType>,
131    /// Optional filter by semantic category (rows / bytes / timing).
132    /// `None` means show all categories; `Some(vec![])` means plan-only.
133    metric_categories: Option<Vec<MetricCategory>>,
134    /// Optional filter by metric names. Only metric names in this list
135    /// will be rendered.
136    metric_names: Option<Vec<String>>,
137    // (TreeRender) Maximum total width of the rendered tree
138    tree_maximum_render_width: usize,
139    /// Optional summary totals (currently only used by `pgjson`) — the total
140    /// row count and wall-clock duration of the `AnalyzeExec` execution.
141    summary: Option<AnalyzeSummary>,
142}
143
144/// Summary information attached to the root of an `EXPLAIN ANALYZE`
145/// pgjson render.
146#[derive(Debug, Clone, Copy)]
147struct AnalyzeSummary {
148    total_rows: Option<usize>,
149    duration: Option<Duration>,
150}
151
152impl<'a> DisplayableExecutionPlan<'a> {
153    fn default_metric_types() -> Vec<MetricType> {
154        vec![MetricType::Summary, MetricType::Dev]
155    }
156
157    /// Create a wrapper around an [`ExecutionPlan`] which can be
158    /// pretty printed in a variety of ways
159    pub fn new(inner: &'a dyn ExecutionPlan) -> Self {
160        Self {
161            inner,
162            show_metrics: ShowMetrics::None,
163            show_statistics: false,
164            show_schema: false,
165            metric_types: Self::default_metric_types(),
166            metric_categories: None,
167            metric_names: None,
168            tree_maximum_render_width: 240,
169            summary: None,
170        }
171    }
172
173    /// Create a wrapper around an [`ExecutionPlan`] which can be
174    /// pretty printed in a variety of ways that also shows aggregated
175    /// metrics
176    pub fn with_metrics(inner: &'a dyn ExecutionPlan) -> Self {
177        Self {
178            inner,
179            show_metrics: ShowMetrics::Aggregated,
180            show_statistics: false,
181            show_schema: false,
182            metric_types: Self::default_metric_types(),
183            metric_categories: None,
184            metric_names: None,
185            tree_maximum_render_width: 240,
186            summary: None,
187        }
188    }
189
190    /// Create a wrapper around an [`ExecutionPlan`] which can be
191    /// pretty printed in a variety of ways that also shows all low
192    /// level metrics
193    pub fn with_full_metrics(inner: &'a dyn ExecutionPlan) -> Self {
194        Self {
195            inner,
196            show_metrics: ShowMetrics::Full,
197            show_statistics: false,
198            show_schema: false,
199            metric_types: Self::default_metric_types(),
200            metric_categories: None,
201            metric_names: None,
202            tree_maximum_render_width: 240,
203            summary: None,
204        }
205    }
206
207    /// Enable display of schema
208    ///
209    /// If true, plans will be displayed with schema information at the end
210    /// of each line. The format is `schema=[[a:Int32;N, b:Int32;N, c:Int32;N]]`
211    pub fn set_show_schema(mut self, show_schema: bool) -> Self {
212        self.show_schema = show_schema;
213        self
214    }
215
216    /// Enable display of statistics
217    pub fn set_show_statistics(mut self, show_statistics: bool) -> Self {
218        self.show_statistics = show_statistics;
219        self
220    }
221
222    /// Specify which metric types should be rendered alongside the plan
223    pub fn set_metric_types(mut self, metric_types: Vec<MetricType>) -> Self {
224        self.metric_types = metric_types;
225        self
226    }
227
228    /// Specify which metric categories to include.
229    ///
230    /// - `None` means show all categories (default).
231    /// - `Some(vec![])` means plan-only — suppress all metrics.
232    /// - `Some(vec![Rows])` means show only row-count metrics (plus
233    ///   uncategorized metrics).
234    ///
235    /// See [`MetricCategory`] for the determinism properties of each
236    /// category.
237    pub fn set_metric_categories(
238        mut self,
239        metric_categories: Option<Vec<MetricCategory>>,
240    ) -> Self {
241        self.metric_categories = metric_categories;
242        self
243    }
244
245    /// Specify which metric names to include.
246    ///
247    /// - An empty vector means plan-only — suppress all metrics.
248    /// - `vec!["metric_1"]` means show only the metric named `metric_1`.
249    ///
250    /// Name filtering is intersected with other types of filters, like metric
251    /// category and metric type.
252    pub fn set_metric_names(mut self, metric_names: Vec<String>) -> Self {
253        self.metric_names = Some(metric_names);
254        self
255    }
256
257    /// Set the maximum render width for the tree format
258    pub fn set_tree_maximum_render_width(mut self, width: usize) -> Self {
259        self.tree_maximum_render_width = width;
260        self
261    }
262
263    /// Attach an `EXPLAIN ANALYZE` summary (total output rows and duration)
264    /// to the rendered output. Currently only used by [`Self::pgjson`], which
265    /// serializes the summary alongside the root plan object.
266    pub fn set_summary(
267        mut self,
268        total_rows: Option<usize>,
269        duration: Option<Duration>,
270    ) -> Self {
271        self.summary = Some(AnalyzeSummary {
272            total_rows,
273            duration,
274        });
275        self
276    }
277
278    /// Return a `format`able structure that produces a single line
279    /// per node.
280    ///
281    /// ```text
282    /// ProjectionExec: expr=[a]
283    ///   CoalesceBatchesExec: target_batch_size=8192
284    ///     FilterExec: a < 5
285    ///       RepartitionExec: partitioning=RoundRobinBatch(16)
286    ///         DataSourceExec: source=...",
287    /// ```
288    pub fn indent(&self, verbose: bool) -> impl fmt::Display + 'a {
289        let format_type = if verbose {
290            DisplayFormatType::Verbose
291        } else {
292            DisplayFormatType::Default
293        };
294        struct Wrapper<'a> {
295            format_type: DisplayFormatType,
296            plan: &'a dyn ExecutionPlan,
297            show_metrics: ShowMetrics,
298            show_statistics: bool,
299            show_schema: bool,
300            metric_types: Vec<MetricType>,
301            metric_categories: Option<Vec<MetricCategory>>,
302            metric_names: Option<Vec<String>>,
303        }
304        impl fmt::Display for Wrapper<'_> {
305            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
306                let mut visitor = IndentVisitor {
307                    t: self.format_type,
308                    f,
309                    indent: 0,
310                    show_metrics: self.show_metrics,
311                    show_statistics: self.show_statistics,
312                    show_schema: self.show_schema,
313                    metric_types: &self.metric_types,
314                    metric_categories: self.metric_categories.as_deref(),
315                    metric_names: self.metric_names.as_deref(),
316                };
317                accept(self.plan, &mut visitor)
318            }
319        }
320        Wrapper {
321            format_type,
322            plan: self.inner,
323            show_metrics: self.show_metrics,
324            show_statistics: self.show_statistics,
325            show_schema: self.show_schema,
326            metric_types: self.metric_types.clone(),
327            metric_categories: self.metric_categories.clone(),
328            metric_names: self.metric_names.clone(),
329        }
330    }
331
332    /// Returns a `format`able structure that produces graphviz format for execution plan, which can
333    /// be directly visualized [here](https://dreampuf.github.io/GraphvizOnline).
334    ///
335    /// An example is
336    /// ```dot
337    /// strict digraph dot_plan {
338    //     0[label="ProjectionExec: expr=[id@0 + 2 as employee.id + Int32(2)]",tooltip=""]
339    //     1[label="EmptyExec",tooltip=""]
340    //     0 -> 1
341    // }
342    /// ```
343    pub fn graphviz(&self) -> impl fmt::Display + 'a {
344        struct Wrapper<'a> {
345            plan: &'a dyn ExecutionPlan,
346            show_metrics: ShowMetrics,
347            show_statistics: bool,
348            metric_types: Vec<MetricType>,
349            metric_categories: Option<Vec<MetricCategory>>,
350            metric_names: Option<Vec<String>>,
351        }
352        impl fmt::Display for Wrapper<'_> {
353            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
354                let t = DisplayFormatType::Default;
355
356                let mut visitor = GraphvizVisitor {
357                    f,
358                    t,
359                    show_metrics: self.show_metrics,
360                    show_statistics: self.show_statistics,
361                    metric_types: &self.metric_types,
362                    metric_categories: self.metric_categories.as_deref(),
363                    metric_names: self.metric_names.as_deref(),
364                    graphviz_builder: GraphvizBuilder::default(),
365                    parents: Vec::new(),
366                };
367
368                visitor.start_graph()?;
369
370                accept(self.plan, &mut visitor)?;
371
372                visitor.end_graph()?;
373                Ok(())
374            }
375        }
376
377        Wrapper {
378            plan: self.inner,
379            show_metrics: self.show_metrics,
380            show_statistics: self.show_statistics,
381            metric_types: self.metric_types.clone(),
382            metric_categories: self.metric_categories.clone(),
383            metric_names: self.metric_names.clone(),
384        }
385    }
386
387    /// Formats the plan using a ASCII art like tree
388    ///
389    /// See [`DisplayFormatType::TreeRender`] for more details.
390    pub fn tree_render(&self) -> impl fmt::Display + 'a {
391        struct Wrapper<'a> {
392            plan: &'a dyn ExecutionPlan,
393            maximum_render_width: usize,
394        }
395        impl fmt::Display for Wrapper<'_> {
396            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
397                let mut visitor = TreeRenderVisitor {
398                    f,
399                    maximum_render_width: self.maximum_render_width,
400                };
401                visitor.visit(self.plan)
402            }
403        }
404        Wrapper {
405            plan: self.inner,
406            maximum_render_width: self.tree_maximum_render_width,
407        }
408    }
409
410    /// Returns a `format`able structure that produces PostgreSQL-style JSON
411    /// output, mirroring the logical-plan pgjson format.
412    ///
413    /// Each node is rendered as a JSON object with:
414    /// - `"Node Type"` — `ExecutionPlan::name()`
415    /// - `"Details"` — the one-line `DisplayAs::Default` rendering
416    /// - `"Output"` — schema column names (when `set_show_schema(true)`)
417    /// - `"Actual Rows"` / `"Actual Total Time"` — PG-canonical metric keys
418    ///   populated from `output_rows` / `elapsed_compute` when available
419    /// - `"Extras"` — remaining metrics keyed by DataFusion metric name
420    /// - `"Plans"` — array of child nodes
421    ///
422    /// When a summary has been set via [`Self::set_summary`], `"Total Rows"`
423    /// and `"Duration"` fields are attached at the root.
424    pub fn pgjson(&self, verbose: bool) -> impl fmt::Display + 'a {
425        struct Wrapper<'a> {
426            plan: &'a dyn ExecutionPlan,
427            verbose: bool,
428            show_metrics: ShowMetrics,
429            show_schema: bool,
430            metric_types: Vec<MetricType>,
431            metric_categories: Option<Vec<MetricCategory>>,
432            metric_names: Option<Vec<String>>,
433            summary: Option<AnalyzeSummary>,
434        }
435        impl fmt::Display for Wrapper<'_> {
436            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
437                let mut visitor = PgJsonExecutionPlanVisitor {
438                    verbose: self.verbose,
439                    show_metrics: self.show_metrics,
440                    show_schema: self.show_schema,
441                    metric_types: &self.metric_types,
442                    metric_categories: self.metric_categories.as_deref(),
443                    metric_names: self.metric_names.as_deref(),
444                    objects: HashMap::new(),
445                    parent_ids: Vec::new(),
446                    next_id: 0,
447                    root: None,
448                };
449                accept(self.plan, &mut visitor).map_err(|_| fmt::Error)?;
450                let root = visitor.root.ok_or(fmt::Error)?;
451                let doc = [PgJsonRoot {
452                    plan: root,
453                    total_rows: self.summary.and_then(|s| s.total_rows),
454                    duration: self
455                        .summary
456                        .and_then(|s| s.duration)
457                        .map(|d| format!("{d:?}")),
458                }];
459                write!(
460                    f,
461                    "{}",
462                    serde_json::to_string_pretty(&doc).map_err(|_| fmt::Error)?
463                )
464            }
465        }
466
467        Wrapper {
468            plan: self.inner,
469            verbose,
470            show_metrics: self.show_metrics,
471            show_schema: self.show_schema,
472            metric_types: self.metric_types.clone(),
473            metric_categories: self.metric_categories.clone(),
474            metric_names: self.metric_names.clone(),
475            summary: self.summary,
476        }
477    }
478
479    /// Return a single-line summary of the root of the plan
480    /// Example: `ProjectionExec: expr=[a@0 as a]`.
481    pub fn one_line(&self) -> impl fmt::Display + 'a {
482        struct Wrapper<'a> {
483            plan: &'a dyn ExecutionPlan,
484            show_metrics: ShowMetrics,
485            show_statistics: bool,
486            show_schema: bool,
487            metric_types: Vec<MetricType>,
488            metric_categories: Option<Vec<MetricCategory>>,
489            metric_names: Option<Vec<String>>,
490        }
491
492        impl fmt::Display for Wrapper<'_> {
493            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
494                let mut visitor = IndentVisitor {
495                    f,
496                    t: DisplayFormatType::Default,
497                    indent: 0,
498                    show_metrics: self.show_metrics,
499                    show_statistics: self.show_statistics,
500                    show_schema: self.show_schema,
501                    metric_types: &self.metric_types,
502                    metric_categories: self.metric_categories.as_deref(),
503                    metric_names: self.metric_names.as_deref(),
504                };
505                visitor.pre_visit(self.plan)?;
506                Ok(())
507            }
508        }
509
510        Wrapper {
511            plan: self.inner,
512            show_metrics: self.show_metrics,
513            show_statistics: self.show_statistics,
514            show_schema: self.show_schema,
515            metric_types: self.metric_types.clone(),
516            metric_categories: self.metric_categories.clone(),
517            metric_names: self.metric_names.clone(),
518        }
519    }
520
521    #[deprecated(since = "47.0.0", note = "indent() or tree_render() instead")]
522    pub fn to_stringified(
523        &self,
524        verbose: bool,
525        plan_type: PlanType,
526        explain_format: DisplayFormatType,
527    ) -> StringifiedPlan {
528        match (&explain_format, &plan_type) {
529            (DisplayFormatType::TreeRender, PlanType::FinalPhysicalPlan) => {
530                StringifiedPlan::new(plan_type, self.tree_render().to_string())
531            }
532            _ => StringifiedPlan::new(plan_type, self.indent(verbose).to_string()),
533        }
534    }
535}
536
537/// Enum representing the different levels of metrics to display
538#[derive(Debug, Clone, Copy)]
539enum ShowMetrics {
540    /// Do not show any metrics
541    None,
542
543    /// Show aggregated metrics across partition
544    Aggregated,
545
546    /// Show full per-partition metrics
547    Full,
548}
549
550/// Formats plans with a single line per node.
551///
552/// # Example
553///
554/// ```text
555/// ProjectionExec: expr=[column1@0 + 2 as column1 + Int64(2)]
556///   FilterExec: column1@0 = 5
557///     ValuesExec
558/// ```
559struct IndentVisitor<'a, 'b> {
560    /// How to format each node
561    t: DisplayFormatType,
562    /// Write to this formatter
563    f: &'a mut Formatter<'b>,
564    /// Indent size
565    indent: usize,
566    /// How to show metrics
567    show_metrics: ShowMetrics,
568    /// If statistics should be displayed
569    show_statistics: bool,
570    /// If schema should be displayed
571    show_schema: bool,
572    /// Which metric types should be rendered
573    metric_types: &'a [MetricType],
574    /// Optional filter by semantic category (rows / bytes / timing).
575    metric_categories: Option<&'a [MetricCategory]>,
576    /// Optional filter by metric name.
577    metric_names: Option<&'a [String]>,
578}
579
580impl ExecutionPlanVisitor for IndentVisitor<'_, '_> {
581    type Error = fmt::Error;
582    fn pre_visit(&mut self, plan: &dyn ExecutionPlan) -> Result<bool, Self::Error> {
583        write!(self.f, "{:indent$}", "", indent = self.indent * 2)?;
584        plan.fmt_as(self.t, self.f)?;
585        match self.show_metrics {
586            ShowMetrics::None => {}
587            ShowMetrics::Aggregated => {
588                if let Some(metrics) = plan.metrics() {
589                    let mut metrics = metrics
590                        .filter_by_metric_types(self.metric_types)
591                        .aggregate_by_name()
592                        .sorted_for_display()
593                        .timestamps_removed();
594                    if let Some(cats) = self.metric_categories {
595                        metrics = metrics.filter_by_categories(cats);
596                    }
597                    if let Some(names) = self.metric_names {
598                        metrics = metrics.filter_by_names(names);
599                    }
600                    write!(self.f, ", metrics=[{metrics}]")?;
601                } else {
602                    write!(self.f, ", metrics=[]")?;
603                }
604            }
605            ShowMetrics::Full => {
606                if let Some(metrics) = plan.metrics() {
607                    let mut metrics = metrics.filter_by_metric_types(self.metric_types);
608                    if let Some(cats) = self.metric_categories {
609                        metrics = metrics.filter_by_categories(cats);
610                    }
611                    if let Some(names) = self.metric_names {
612                        metrics = metrics.filter_by_names(names);
613                    }
614                    write!(self.f, ", metrics=[{metrics}]")?;
615                } else {
616                    write!(self.f, ", metrics=[]")?;
617                }
618            }
619        }
620        if self.show_statistics {
621            let stats = StatisticsContext::new()
622                .compute(plan, &StatisticsArgs::new())
623                .map_err(|_e| fmt::Error)?;
624            write!(self.f, ", statistics=[{stats}]")?;
625        }
626        if self.show_schema {
627            write!(
628                self.f,
629                ", schema={}",
630                display_schema(plan.schema().as_ref())
631            )?;
632        }
633        writeln!(self.f)?;
634        self.indent += 1;
635        Ok(true)
636    }
637
638    fn post_visit(&mut self, _plan: &dyn ExecutionPlan) -> Result<bool, Self::Error> {
639        self.indent -= 1;
640        Ok(true)
641    }
642}
643
644struct GraphvizVisitor<'a, 'b> {
645    f: &'a mut Formatter<'b>,
646    /// How to format each node
647    t: DisplayFormatType,
648    /// How to show metrics
649    show_metrics: ShowMetrics,
650    /// If statistics should be displayed
651    show_statistics: bool,
652    /// Which metric types should be rendered
653    metric_types: &'a [MetricType],
654    /// Optional filter by semantic category
655    metric_categories: Option<&'a [MetricCategory]>,
656    /// Optional filter by metric name.
657    metric_names: Option<&'a [String]>,
658
659    graphviz_builder: GraphvizBuilder,
660    /// Used to record parent node ids when visiting a plan.
661    parents: Vec<usize>,
662}
663
664impl GraphvizVisitor<'_, '_> {
665    fn start_graph(&mut self) -> fmt::Result {
666        self.graphviz_builder.start_graph(self.f)
667    }
668
669    fn end_graph(&mut self) -> fmt::Result {
670        self.graphviz_builder.end_graph(self.f)
671    }
672}
673
674impl ExecutionPlanVisitor for GraphvizVisitor<'_, '_> {
675    type Error = fmt::Error;
676
677    fn pre_visit(&mut self, plan: &dyn ExecutionPlan) -> Result<bool, Self::Error> {
678        let id = self.graphviz_builder.next_id();
679
680        struct Wrapper<'a>(&'a dyn ExecutionPlan, DisplayFormatType);
681
682        impl fmt::Display for Wrapper<'_> {
683            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
684                self.0.fmt_as(self.1, f)
685            }
686        }
687
688        let label = { format!("{}", Wrapper(plan, self.t)) };
689
690        let metrics = match self.show_metrics {
691            ShowMetrics::None => "".to_string(),
692            ShowMetrics::Aggregated => {
693                if let Some(metrics) = plan.metrics() {
694                    let mut metrics = metrics
695                        .filter_by_metric_types(self.metric_types)
696                        .aggregate_by_name()
697                        .sorted_for_display()
698                        .timestamps_removed();
699                    if let Some(cats) = self.metric_categories {
700                        metrics = metrics.filter_by_categories(cats);
701                    }
702                    if let Some(names) = self.metric_names {
703                        metrics = metrics.filter_by_names(names);
704                    }
705                    format!("metrics=[{metrics}]")
706                } else {
707                    "metrics=[]".to_string()
708                }
709            }
710            ShowMetrics::Full => {
711                if let Some(metrics) = plan.metrics() {
712                    let mut metrics = metrics.filter_by_metric_types(self.metric_types);
713                    if let Some(cats) = self.metric_categories {
714                        metrics = metrics.filter_by_categories(cats);
715                    }
716                    if let Some(names) = self.metric_names {
717                        metrics = metrics.filter_by_names(names);
718                    }
719                    format!("metrics=[{metrics}]")
720                } else {
721                    "metrics=[]".to_string()
722                }
723            }
724        };
725
726        let statistics = if self.show_statistics {
727            let stats = StatisticsContext::new()
728                .compute(plan, &StatisticsArgs::new())
729                .map_err(|_e| fmt::Error)?;
730            format!("statistics=[{stats}]")
731        } else {
732            "".to_string()
733        };
734
735        let delimiter = if !metrics.is_empty() && !statistics.is_empty() {
736            ", "
737        } else {
738            ""
739        };
740
741        self.graphviz_builder.add_node(
742            self.f,
743            id,
744            &label,
745            Some(&format!("{metrics}{delimiter}{statistics}")),
746        )?;
747
748        if let Some(parent_node_id) = self.parents.last() {
749            self.graphviz_builder
750                .add_edge(self.f, *parent_node_id, id)?;
751        }
752
753        self.parents.push(id);
754
755        Ok(true)
756    }
757
758    fn post_visit(&mut self, _plan: &dyn ExecutionPlan) -> Result<bool, Self::Error> {
759        self.parents.pop();
760        Ok(true)
761    }
762}
763
764/// Formats physical plans into PostgreSQL-style JSON output with live
765/// per-operator metrics.
766///
767/// This visitor mirrors the logical-plan `PgJsonVisitor` in
768/// `datafusion-expr`: during `pre_visit` it assembles a JSON object for the
769/// current node; during `post_visit` it attaches that object into its
770/// parent's `"Plans"` array (or stores it as the root).
771struct PgJsonExecutionPlanVisitor<'a> {
772    verbose: bool,
773    show_metrics: ShowMetrics,
774    show_schema: bool,
775    metric_types: &'a [MetricType],
776    metric_categories: Option<&'a [MetricCategory]>,
777    metric_names: Option<&'a [String]>,
778    objects: HashMap<u32, PgJsonNode>,
779    parent_ids: Vec<u32>,
780    next_id: u32,
781    root: Option<PgJsonNode>,
782}
783
784/// Top-level entry of the `pgjson` output. Field order is the output order.
785#[derive(Serialize)]
786struct PgJsonRoot {
787    #[serde(rename = "Plan")]
788    plan: PgJsonNode,
789    #[serde(rename = "Total Rows", skip_serializing_if = "Option::is_none")]
790    total_rows: Option<usize>,
791    #[serde(rename = "Duration", skip_serializing_if = "Option::is_none")]
792    duration: Option<String>,
793}
794
795/// One node of the `pgjson` output. Field order is the output order, so the
796/// JSON reads top-down like a PostgreSQL plan, with `"Plans"` last.
797#[derive(Serialize)]
798struct PgJsonNode {
799    #[serde(rename = "Node Type")]
800    node_type: String,
801    #[serde(rename = "Details")]
802    details: String,
803    #[serde(rename = "Output", skip_serializing_if = "Option::is_none")]
804    output: Option<Vec<String>>,
805    #[serde(rename = "Actual Rows", skip_serializing_if = "Option::is_none")]
806    actual_rows: Option<usize>,
807    #[serde(rename = "Actual Total Time", skip_serializing_if = "Option::is_none")]
808    actual_total_time: Option<f64>,
809    #[serde(rename = "Extras", skip_serializing_if = "PgJsonExtras::is_empty")]
810    extras: PgJsonExtras,
811    #[serde(rename = "Plans")]
812    plans: Vec<PgJsonNode>,
813}
814
815/// Non-canonical metrics of a node, serialized as a JSON object whose keys
816/// keep their insertion order (independent of `serde_json`'s
817/// `preserve_order` feature).
818#[derive(Default)]
819struct PgJsonExtras(Vec<(String, serde_json::Value)>);
820
821impl PgJsonExtras {
822    fn is_empty(&self) -> bool {
823        self.0.is_empty()
824    }
825
826    /// Insert or replace `key`. A replaced key keeps its original position.
827    fn insert(&mut self, key: &str, value: serde_json::Value) {
828        match self.0.iter_mut().find(|(k, _)| k == key) {
829            Some((_, v)) => *v = value,
830            None => self.0.push((key.to_string(), value)),
831        }
832    }
833}
834
835impl Serialize for PgJsonExtras {
836    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
837        serializer.collect_map(self.0.iter().map(|(k, v)| (k, v)))
838    }
839}
840
841impl PgJsonExecutionPlanVisitor<'_> {
842    /// Produce the one-line `DisplayAs::Default` rendering of a node.
843    fn one_line_details(plan: &dyn ExecutionPlan) -> String {
844        struct One<'b>(&'b dyn ExecutionPlan);
845        impl fmt::Display for One<'_> {
846            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
847                self.0.fmt_as(DisplayFormatType::Default, f)
848            }
849        }
850        // Some operators include internal newlines; collapse them so the
851        // rendered JSON value stays on a single line.
852        format!("{}", One(plan))
853            .replace('\n', " ")
854            .trim()
855            .to_string()
856    }
857
858    /// Render the given `MetricValue` into the most natural `serde_json::Value`
859    /// we can produce: a number for simple counts/gauges/times, a float-ms for
860    /// `ElapsedCompute`, and a string fallback for anything else.
861    fn metric_value_to_json(value: &MetricValue) -> serde_json::Value {
862        match value {
863            MetricValue::OutputRows(c) => serde_json::Value::from(c.value()),
864            MetricValue::SpillCount(c)
865            | MetricValue::OutputBatches(c)
866            | MetricValue::SpilledRows(c) => serde_json::Value::from(c.value()),
867            MetricValue::SpilledBytes(c) | MetricValue::OutputBytes(c) => {
868                serde_json::Value::from(c.value())
869            }
870            MetricValue::CurrentMemoryUsage(g) => serde_json::Value::from(g.value()),
871            MetricValue::ElapsedCompute(t) => {
872                // Emit as float milliseconds to align with PG's
873                // `"Actual Total Time"` convention. DataFusion tracks compute
874                // time (summed across partitions), not wall time — visualizers
875                // should be read with that caveat in mind.
876                let ms = (t.value() as f64) / 1_000_000.0;
877                serde_json::Value::from(ms)
878            }
879            MetricValue::Count { count, .. } => serde_json::Value::from(count.value()),
880            MetricValue::Gauge { gauge, .. } => serde_json::Value::from(gauge.value()),
881            MetricValue::PeakMemoryUsage { gauge, .. } => {
882                serde_json::Value::from(gauge.value())
883            }
884            MetricValue::Time { time, .. } => {
885                let ms = (time.value() as f64) / 1_000_000.0;
886                serde_json::Value::from(ms)
887            }
888            // Timestamps, PruningMetrics, Ratio, Custom: fall back to Display.
889            other => serde_json::Value::String(format!("{other}")),
890        }
891    }
892
893    /// Populate `"Actual Rows"`, `"Actual Total Time"`, and `"Extras"` for
894    /// the given node from its aggregated `MetricsSet`, honoring the same
895    /// filtering pipeline used by `IndentVisitor`.
896    fn attach_metrics(&self, plan: &dyn ExecutionPlan, object: &mut PgJsonNode) {
897        if matches!(self.show_metrics, ShowMetrics::None) {
898            return;
899        }
900        let Some(metrics) = plan.metrics() else {
901            return;
902        };
903
904        let metrics = match self.show_metrics {
905            ShowMetrics::None => return,
906            ShowMetrics::Aggregated => metrics
907                .filter_by_metric_types(self.metric_types)
908                .aggregate_by_name()
909                .sorted_for_display()
910                .timestamps_removed(),
911            ShowMetrics::Full => metrics.filter_by_metric_types(self.metric_types),
912        };
913        let metrics = if let Some(cats) = self.metric_categories {
914            metrics.filter_by_categories(cats)
915        } else {
916            metrics
917        };
918
919        let metrics = if let Some(names) = self.metric_names {
920            metrics.filter_by_names(names)
921        } else {
922            metrics
923        };
924
925        // Build the Extras bucket, while extracting PG-canonical keys to the
926        // top level.
927        for metric in metrics.iter() {
928            let value = metric.value();
929            match value {
930                MetricValue::OutputRows(c) => {
931                    object.actual_rows = Some(c.value());
932                }
933                MetricValue::ElapsedCompute(t) => {
934                    let ms = (t.value() as f64) / 1_000_000.0;
935                    object.actual_total_time = Some(ms);
936                }
937                _ => {
938                    object
939                        .extras
940                        .insert(value.name(), Self::metric_value_to_json(value));
941                }
942            }
943        }
944    }
945}
946
947impl ExecutionPlanVisitor for PgJsonExecutionPlanVisitor<'_> {
948    type Error = fmt::Error;
949
950    fn pre_visit(&mut self, plan: &dyn ExecutionPlan) -> Result<bool, Self::Error> {
951        let id = self.next_id;
952        self.next_id += 1;
953
954        // Build fields in reading order: Node Type, Details, (schema),
955        // (metrics), Plans last — so the JSON output reads top-down like a
956        // PostgreSQL plan.
957        let mut object = PgJsonNode {
958            node_type: plan.name().to_string(),
959            details: Self::one_line_details(plan),
960            output: None,
961            actual_rows: None,
962            actual_total_time: None,
963            extras: PgJsonExtras::default(),
964            plans: vec![],
965        };
966
967        if self.show_schema || self.verbose {
968            // Always include output columns when a caller asked for schema;
969            // also include them in verbose mode so the pgjson output mirrors
970            // the extra context shown by indent's verbose flag.
971            object.output = Some(
972                plan.schema()
973                    .fields()
974                    .iter()
975                    .map(|f| f.name().to_string())
976                    .collect(),
977            );
978        }
979
980        self.attach_metrics(plan, &mut object);
981
982        self.objects.insert(id, object);
983        self.parent_ids.push(id);
984        Ok(true)
985    }
986
987    fn post_visit(&mut self, _plan: &dyn ExecutionPlan) -> Result<bool, Self::Error> {
988        let id = self.parent_ids.pop().ok_or(fmt::Error)?;
989        let current = self.objects.remove(&id).ok_or(fmt::Error)?;
990
991        if let Some(parent_id) = self.parent_ids.last() {
992            let parent = self.objects.get_mut(parent_id).ok_or(fmt::Error)?;
993            parent.plans.push(current);
994        } else {
995            self.root = Some(current);
996        }
997        Ok(true)
998    }
999}
1000
1001/// This module implements a tree-like art renderer for execution plans,
1002/// based on DuckDB's implementation:
1003/// <https://github.com/duckdb/duckdb/blob/main/src/include/duckdb/common/tree_renderer/text_tree_renderer.hpp>
1004///
1005/// The rendered output looks like this:
1006/// ```text
1007/// ┌───────────────────────────┐
1008/// │    CoalesceBatchesExec    │
1009/// └─────────────┬─────────────┘
1010/// ┌─────────────┴─────────────┐
1011/// │        HashJoinExec       ├──────────────┐
1012/// └─────────────┬─────────────┘              │
1013/// ┌─────────────┴─────────────┐┌─────────────┴─────────────┐
1014/// │       DataSourceExec      ││       DataSourceExec      │
1015/// └───────────────────────────┘└───────────────────────────┘
1016/// ```
1017///
1018/// The renderer uses a three-layer approach for each node:
1019/// 1. Top layer: renders the top borders and connections
1020/// 2. Content layer: renders the node content and vertical connections
1021/// 3. Bottom layer: renders the bottom borders and connections
1022///
1023/// Each node is rendered in a box of fixed width (NODE_RENDER_WIDTH).
1024struct TreeRenderVisitor<'a, 'b> {
1025    /// Write to this formatter
1026    f: &'a mut Formatter<'b>,
1027    /// Maximum total width of the rendered tree
1028    maximum_render_width: usize,
1029}
1030
1031impl TreeRenderVisitor<'_, '_> {
1032    // Unicode box-drawing characters for creating borders and connections.
1033    const LTCORNER: &'static str = "┌"; // Left top corner
1034    const RTCORNER: &'static str = "┐"; // Right top corner
1035    const LDCORNER: &'static str = "└"; // Left bottom corner
1036    const RDCORNER: &'static str = "┘"; // Right bottom corner
1037
1038    const TMIDDLE: &'static str = "┬"; // Top T-junction (connects down)
1039    const LMIDDLE: &'static str = "├"; // Left T-junction (connects right)
1040    const DMIDDLE: &'static str = "┴"; // Bottom T-junction (connects up)
1041
1042    const VERTICAL: &'static str = "│"; // Vertical line
1043    const HORIZONTAL: &'static str = "─"; // Horizontal line
1044
1045    // TODO: Make these variables configurable.
1046    const NODE_RENDER_WIDTH: usize = 29; // Width of each node's box
1047    const MAX_EXTRA_LINES: usize = 30; // Maximum number of extra info lines per node
1048
1049    /// Main entry point for rendering an execution plan as a tree.
1050    /// The rendering process happens in three stages for each level of the tree:
1051    /// 1. Render top borders and connections
1052    /// 2. Render node content and vertical connections
1053    /// 3. Render bottom borders and connections
1054    pub fn visit(&mut self, plan: &dyn ExecutionPlan) -> Result<(), fmt::Error> {
1055        let root = RenderTree::create_tree(plan);
1056
1057        for y in 0..root.height {
1058            // Start by rendering the top layer.
1059            self.render_top_layer(&root, y)?;
1060            // Now we render the content of the boxes
1061            self.render_box_content(&root, y)?;
1062            // Render the bottom layer of each of the boxes
1063            self.render_bottom_layer(&root, y)?;
1064        }
1065
1066        Ok(())
1067    }
1068
1069    /// Renders the top layer of boxes at the given y-level of the tree.
1070    /// This includes:
1071    /// - Top corners (┌─┐) for nodes
1072    /// - Horizontal connections between nodes
1073    /// - Vertical connections to parent nodes
1074    fn render_top_layer(
1075        &mut self,
1076        root: &RenderTree,
1077        y: usize,
1078    ) -> Result<(), fmt::Error> {
1079        for x in 0..root.width {
1080            if self.maximum_render_width > 0
1081                && x * Self::NODE_RENDER_WIDTH >= self.maximum_render_width
1082            {
1083                break;
1084            }
1085
1086            if root.has_node(x, y) {
1087                write!(self.f, "{}", Self::LTCORNER)?;
1088                write!(
1089                    self.f,
1090                    "{}",
1091                    Self::HORIZONTAL.repeat(Self::NODE_RENDER_WIDTH / 2 - 1)
1092                )?;
1093                if y == 0 {
1094                    // top level node: no node above this one
1095                    write!(self.f, "{}", Self::HORIZONTAL)?;
1096                } else {
1097                    // render connection to node above this one
1098                    write!(self.f, "{}", Self::DMIDDLE)?;
1099                }
1100                write!(
1101                    self.f,
1102                    "{}",
1103                    Self::HORIZONTAL.repeat(Self::NODE_RENDER_WIDTH / 2 - 1)
1104                )?;
1105                write!(self.f, "{}", Self::RTCORNER)?;
1106            } else {
1107                let mut has_adjacent_nodes = false;
1108                for i in 0..(root.width - x) {
1109                    has_adjacent_nodes = has_adjacent_nodes || root.has_node(x + i, y);
1110                }
1111                if !has_adjacent_nodes {
1112                    // There are no nodes to the right side of this position
1113                    // no need to fill the empty space
1114                    continue;
1115                }
1116                // there are nodes next to this, fill the space
1117                write!(self.f, "{}", " ".repeat(Self::NODE_RENDER_WIDTH))?;
1118            }
1119        }
1120        writeln!(self.f)?;
1121
1122        Ok(())
1123    }
1124
1125    /// Renders the content layer of boxes at the given y-level of the tree.
1126    /// This includes:
1127    /// - Node names and extra information
1128    /// - Vertical borders (│) for boxes
1129    /// - Vertical connections between nodes
1130    fn render_box_content(
1131        &mut self,
1132        root: &RenderTree,
1133        y: usize,
1134    ) -> Result<(), fmt::Error> {
1135        let mut extra_info: Vec<Vec<String>> = vec![vec![]; root.width];
1136        let mut extra_height = 0;
1137
1138        for (x, extra_info_item) in extra_info.iter_mut().enumerate().take(root.width) {
1139            if let Some(node) = root.get_node(x, y) {
1140                Self::split_up_extra_info(
1141                    &node.extra_text,
1142                    extra_info_item,
1143                    Self::MAX_EXTRA_LINES,
1144                );
1145                if extra_info_item.len() > extra_height {
1146                    extra_height = extra_info_item.len();
1147                }
1148            }
1149        }
1150
1151        let halfway_point = extra_height.div_ceil(2);
1152
1153        // Render the actual node.
1154        for render_y in 0..=extra_height {
1155            for (x, _) in root.nodes.iter().enumerate().take(root.width) {
1156                if self.maximum_render_width > 0
1157                    && x * Self::NODE_RENDER_WIDTH >= self.maximum_render_width
1158                {
1159                    break;
1160                }
1161
1162                let mut has_adjacent_nodes = false;
1163                for i in 0..(root.width - x) {
1164                    has_adjacent_nodes = has_adjacent_nodes || root.has_node(x + i, y);
1165                }
1166
1167                if let Some(node) = root.get_node(x, y) {
1168                    write!(self.f, "{}", Self::VERTICAL)?;
1169
1170                    // Figure out what to render.
1171                    let mut render_text = if render_y == 0 {
1172                        node.name.clone()
1173                    } else if render_y <= extra_info[x].len() {
1174                        extra_info[x][render_y - 1].clone()
1175                    } else {
1176                        String::new()
1177                    };
1178
1179                    render_text = Self::adjust_text_for_rendering(
1180                        &render_text,
1181                        Self::NODE_RENDER_WIDTH - 2,
1182                    );
1183                    write!(self.f, "{render_text}")?;
1184
1185                    if render_y == halfway_point && node.child_positions.len() > 1 {
1186                        write!(self.f, "{}", Self::LMIDDLE)?;
1187                    } else {
1188                        write!(self.f, "{}", Self::VERTICAL)?;
1189                    }
1190                } else if render_y == halfway_point {
1191                    let has_child_to_the_right =
1192                        Self::should_render_whitespace(root, x, y);
1193                    if root.has_node(x, y + 1) {
1194                        // Node right below this one.
1195                        write!(
1196                            self.f,
1197                            "{}",
1198                            Self::HORIZONTAL.repeat(Self::NODE_RENDER_WIDTH / 2)
1199                        )?;
1200                        if has_child_to_the_right {
1201                            write!(self.f, "{}", Self::TMIDDLE)?;
1202                            // Have another child to the right, Keep rendering the line.
1203                            write!(
1204                                self.f,
1205                                "{}",
1206                                Self::HORIZONTAL.repeat(Self::NODE_RENDER_WIDTH / 2)
1207                            )?;
1208                        } else {
1209                            write!(self.f, "{}", Self::RTCORNER)?;
1210                            if has_adjacent_nodes {
1211                                // Only a child below this one: fill the reset with spaces.
1212                                write!(
1213                                    self.f,
1214                                    "{}",
1215                                    " ".repeat(Self::NODE_RENDER_WIDTH / 2)
1216                                )?;
1217                            }
1218                        }
1219                    } else if has_child_to_the_right {
1220                        // Child to the right, but no child right below this one: render a full
1221                        // line.
1222                        write!(
1223                            self.f,
1224                            "{}",
1225                            Self::HORIZONTAL.repeat(Self::NODE_RENDER_WIDTH)
1226                        )?;
1227                    } else if has_adjacent_nodes {
1228                        // Empty spot: render spaces.
1229                        write!(self.f, "{}", " ".repeat(Self::NODE_RENDER_WIDTH))?;
1230                    }
1231                } else if render_y >= halfway_point {
1232                    if root.has_node(x, y + 1) {
1233                        // Have a node below this empty spot: render a vertical line.
1234                        write!(
1235                            self.f,
1236                            "{}{}",
1237                            " ".repeat(Self::NODE_RENDER_WIDTH / 2),
1238                            Self::VERTICAL
1239                        )?;
1240                        if has_adjacent_nodes
1241                            || Self::should_render_whitespace(root, x, y)
1242                        {
1243                            write!(
1244                                self.f,
1245                                "{}",
1246                                " ".repeat(Self::NODE_RENDER_WIDTH / 2)
1247                            )?;
1248                        }
1249                    } else if has_adjacent_nodes
1250                        || Self::should_render_whitespace(root, x, y)
1251                    {
1252                        // Empty spot: render spaces.
1253                        write!(self.f, "{}", " ".repeat(Self::NODE_RENDER_WIDTH))?;
1254                    }
1255                } else if has_adjacent_nodes {
1256                    // Empty spot: render spaces.
1257                    write!(self.f, "{}", " ".repeat(Self::NODE_RENDER_WIDTH))?;
1258                }
1259            }
1260            writeln!(self.f)?;
1261        }
1262
1263        Ok(())
1264    }
1265
1266    /// Renders the bottom layer of boxes at the given y-level of the tree.
1267    /// This includes:
1268    /// - Bottom corners (└─┘) for nodes
1269    /// - Horizontal connections between nodes
1270    /// - Vertical connections to child nodes
1271    fn render_bottom_layer(
1272        &mut self,
1273        root: &RenderTree,
1274        y: usize,
1275    ) -> Result<(), fmt::Error> {
1276        for x in 0..=root.width {
1277            if self.maximum_render_width > 0
1278                && x * Self::NODE_RENDER_WIDTH >= self.maximum_render_width
1279            {
1280                break;
1281            }
1282            let mut has_adjacent_nodes = false;
1283            for i in 0..(root.width - x) {
1284                has_adjacent_nodes = has_adjacent_nodes || root.has_node(x + i, y);
1285            }
1286            if root.get_node(x, y).is_some() {
1287                write!(self.f, "{}", Self::LDCORNER)?;
1288                write!(
1289                    self.f,
1290                    "{}",
1291                    Self::HORIZONTAL.repeat(Self::NODE_RENDER_WIDTH / 2 - 1)
1292                )?;
1293                if root.has_node(x, y + 1) {
1294                    // node below this one: connect to that one
1295                    write!(self.f, "{}", Self::TMIDDLE)?;
1296                } else {
1297                    // no node below this one: end the box
1298                    write!(self.f, "{}", Self::HORIZONTAL)?;
1299                }
1300                write!(
1301                    self.f,
1302                    "{}",
1303                    Self::HORIZONTAL.repeat(Self::NODE_RENDER_WIDTH / 2 - 1)
1304                )?;
1305                write!(self.f, "{}", Self::RDCORNER)?;
1306            } else if root.has_node(x, y + 1) {
1307                write!(self.f, "{}", " ".repeat(Self::NODE_RENDER_WIDTH / 2))?;
1308                write!(self.f, "{}", Self::VERTICAL)?;
1309                if has_adjacent_nodes || Self::should_render_whitespace(root, x, y) {
1310                    write!(self.f, "{}", " ".repeat(Self::NODE_RENDER_WIDTH / 2))?;
1311                }
1312            } else if has_adjacent_nodes || Self::should_render_whitespace(root, x, y) {
1313                write!(self.f, "{}", " ".repeat(Self::NODE_RENDER_WIDTH))?;
1314            }
1315        }
1316        writeln!(self.f)?;
1317
1318        Ok(())
1319    }
1320
1321    fn extra_info_separator() -> String {
1322        "-".repeat(Self::NODE_RENDER_WIDTH - 9)
1323    }
1324
1325    fn remove_padding(s: &str) -> String {
1326        s.trim().to_string()
1327    }
1328
1329    pub fn split_up_extra_info(
1330        extra_info: &HashMap<String, String>,
1331        result: &mut Vec<String>,
1332        max_lines: usize,
1333    ) {
1334        if extra_info.is_empty() {
1335            return;
1336        }
1337
1338        result.push(Self::extra_info_separator());
1339
1340        let mut requires_padding = false;
1341        let mut was_inlined = false;
1342
1343        // use BTreeMap for repeatable key order
1344        let sorted_extra_info: BTreeMap<_, _> = extra_info.iter().collect();
1345        for (key, value) in sorted_extra_info {
1346            let mut str = Self::remove_padding(value);
1347            let mut is_inlined = false;
1348            let available_width = Self::NODE_RENDER_WIDTH - 7;
1349            let total_size = key.len() + str.len() + 2;
1350            let is_multiline = str.contains('\n');
1351
1352            if str.is_empty() {
1353                str = key.to_string();
1354            } else if !is_multiline && total_size < available_width {
1355                str = format!("{key}: {str}");
1356                is_inlined = true;
1357            } else {
1358                str = format!("{key}:\n{str}");
1359            }
1360
1361            if is_inlined && was_inlined {
1362                requires_padding = false;
1363            }
1364
1365            if requires_padding {
1366                result.push(String::new());
1367            }
1368
1369            let mut splits: Vec<String> = str.split('\n').map(String::from).collect();
1370            if splits.len() > max_lines {
1371                let mut truncated_splits = Vec::new();
1372                for split in splits.iter().take(max_lines / 2) {
1373                    truncated_splits.push(split.clone());
1374                }
1375                truncated_splits.push("...".to_string());
1376                for split in splits.iter().skip(splits.len() - max_lines / 2) {
1377                    truncated_splits.push(split.clone());
1378                }
1379                splits = truncated_splits;
1380            }
1381            for split in splits {
1382                Self::split_string_buffer(&split, result);
1383            }
1384            if result.len() > max_lines {
1385                result.truncate(max_lines);
1386                result.push("...".to_string());
1387            }
1388
1389            requires_padding = true;
1390            was_inlined = is_inlined;
1391        }
1392    }
1393
1394    /// Adjusts text to fit within the specified width by:
1395    /// 1. Truncating with ellipsis if too long
1396    /// 2. Center-aligning within the available space if shorter
1397    fn adjust_text_for_rendering(source: &str, max_render_width: usize) -> String {
1398        let render_width = source.chars().count();
1399        if render_width > max_render_width {
1400            let truncated = &source[..max_render_width - 3];
1401            format!("{truncated}...")
1402        } else {
1403            let total_spaces = max_render_width - render_width;
1404            let half_spaces = total_spaces / 2;
1405            let extra_left_space = if total_spaces.is_multiple_of(2) { 0 } else { 1 };
1406            format!(
1407                "{}{}{}",
1408                " ".repeat(half_spaces + extra_left_space),
1409                source,
1410                " ".repeat(half_spaces)
1411            )
1412        }
1413    }
1414
1415    /// Determines if whitespace should be rendered at a given position.
1416    /// This is important for:
1417    /// 1. Maintaining proper spacing between sibling nodes
1418    /// 2. Ensuring correct alignment of connections between parents and children
1419    /// 3. Preserving the tree structure's visual clarity
1420    fn should_render_whitespace(root: &RenderTree, x: usize, y: usize) -> bool {
1421        let mut found_children = 0;
1422
1423        for i in (0..=x).rev() {
1424            let node = root.get_node(i, y);
1425            if root.has_node(i, y + 1) {
1426                found_children += 1;
1427            }
1428            if let Some(node) = node {
1429                if node.child_positions.len() > 1
1430                    && found_children < node.child_positions.len()
1431                {
1432                    return true;
1433                }
1434
1435                return false;
1436            }
1437        }
1438
1439        false
1440    }
1441
1442    fn split_string_buffer(source: &str, result: &mut Vec<String>) {
1443        let mut character_pos = 0;
1444        let mut start_pos = 0;
1445        let mut render_width = 0;
1446        let mut last_possible_split = 0;
1447
1448        let chars: Vec<char> = source.chars().collect();
1449
1450        while character_pos < chars.len() {
1451            // Treating each char as width 1 for simplification
1452            let char_width = 1;
1453
1454            // Does the next character make us exceed the line length?
1455            if render_width + char_width > Self::NODE_RENDER_WIDTH - 2 {
1456                if start_pos + 8 > last_possible_split {
1457                    // The last character we can split on is one of the first 8 characters of the line
1458                    // to not create very small lines we instead split on the current character
1459                    last_possible_split = character_pos;
1460                }
1461
1462                result.push(source[start_pos..last_possible_split].to_string());
1463                render_width = character_pos - last_possible_split;
1464                start_pos = last_possible_split;
1465                character_pos = last_possible_split;
1466            }
1467
1468            // check if we can split on this character
1469            if Self::can_split_on_this_char(chars[character_pos]) {
1470                last_possible_split = character_pos;
1471            }
1472
1473            character_pos += 1;
1474            render_width += char_width;
1475        }
1476
1477        if source.len() > start_pos {
1478            // append the remainder of the input
1479            result.push(source[start_pos..].to_string());
1480        }
1481    }
1482
1483    fn can_split_on_this_char(c: char) -> bool {
1484        (!c.is_ascii_digit() && !c.is_ascii_uppercase() && !c.is_ascii_lowercase())
1485            && c != '_'
1486    }
1487}
1488
1489/// Trait for types which could have additional details when formatted in `Verbose` mode
1490pub trait DisplayAs {
1491    /// Format according to `DisplayFormatType`, used when verbose representation looks
1492    /// different from the default one
1493    ///
1494    /// Should not include a newline
1495    fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> fmt::Result;
1496}
1497
1498/// A new type wrapper to display `T` implementing`DisplayAs` using the `Default` mode
1499pub struct DefaultDisplay<T>(pub T);
1500
1501impl<T: DisplayAs> fmt::Display for DefaultDisplay<T> {
1502    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1503        self.0.fmt_as(DisplayFormatType::Default, f)
1504    }
1505}
1506
1507/// A new type wrapper to display `T` implementing `DisplayAs` using the `Verbose` mode
1508pub struct VerboseDisplay<T>(pub T);
1509
1510impl<T: DisplayAs> fmt::Display for VerboseDisplay<T> {
1511    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1512        self.0.fmt_as(DisplayFormatType::Verbose, f)
1513    }
1514}
1515
1516/// A wrapper to customize partitioned file display
1517#[derive(Debug)]
1518pub struct ProjectSchemaDisplay<'a>(pub &'a SchemaRef);
1519
1520impl fmt::Display for ProjectSchemaDisplay<'_> {
1521    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1522        let parts: Vec<_> = self
1523            .0
1524            .fields()
1525            .iter()
1526            .map(|x| x.name().to_owned())
1527            .collect::<Vec<String>>();
1528        write!(f, "[{}]", parts.join(", "))
1529    }
1530}
1531
1532pub fn display_orderings(f: &mut Formatter, orderings: &[LexOrdering]) -> fmt::Result {
1533    if !orderings.is_empty() {
1534        let start = if orderings.len() == 1 {
1535            ", output_ordering="
1536        } else {
1537            ", output_orderings=["
1538        };
1539        write!(f, "{start}")?;
1540        for (idx, ordering) in orderings.iter().enumerate() {
1541            match idx {
1542                0 => write!(f, "[{ordering}]")?,
1543                _ => write!(f, ", [{ordering}]")?,
1544            }
1545        }
1546        let end = if orderings.len() == 1 { "" } else { "]" };
1547        write!(f, "{end}")?;
1548    }
1549    Ok(())
1550}
1551
1552#[cfg(test)]
1553mod tests {
1554    use std::fmt::Write;
1555    use std::sync::Arc;
1556
1557    use datafusion_common::{
1558        Result, Statistics, internal_datafusion_err, tree_node::TreeNodeRecursion,
1559    };
1560    use datafusion_execution::{SendableRecordBatchStream, TaskContext};
1561    use datafusion_physical_expr::PhysicalExpr;
1562
1563    use crate::statistics::StatisticsArgs;
1564    use crate::{
1565        ChildrenPropertiesMode, DisplayAs, ExecutionPlan, PlanProperties,
1566        ReplaceChildrenOptions,
1567    };
1568
1569    use super::DisplayableExecutionPlan;
1570
1571    #[derive(Debug, Clone, Copy)]
1572    enum TestStatsExecPlan {
1573        Panic,
1574        Error,
1575        Ok,
1576    }
1577
1578    impl DisplayAs for TestStatsExecPlan {
1579        fn fmt_as(
1580            &self,
1581            _t: crate::DisplayFormatType,
1582            f: &mut std::fmt::Formatter,
1583        ) -> std::fmt::Result {
1584            write!(f, "TestStatsExecPlan")
1585        }
1586    }
1587
1588    impl ExecutionPlan for TestStatsExecPlan {
1589        fn name(&self) -> &'static str {
1590            "TestStatsExecPlan"
1591        }
1592
1593        fn properties(&self) -> &Arc<PlanProperties> {
1594            unimplemented!()
1595        }
1596
1597        fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
1598            vec![]
1599        }
1600
1601        fn replace_children(
1602            self: Arc<Self>,
1603            _: Vec<Arc<dyn ExecutionPlan>>,
1604            _: ReplaceChildrenOptions,
1605        ) -> Result<Arc<dyn ExecutionPlan>> {
1606            unimplemented!()
1607        }
1608
1609        fn apply_expressions(
1610            &self,
1611            _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
1612        ) -> Result<TreeNodeRecursion> {
1613            Ok(TreeNodeRecursion::Continue)
1614        }
1615
1616        fn with_new_children(
1617            self: Arc<Self>,
1618            children: Vec<Arc<dyn ExecutionPlan>>,
1619        ) -> Result<Arc<dyn ExecutionPlan>> {
1620            self.replace_children(
1621                children,
1622                ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
1623            )
1624        }
1625
1626        fn execute(
1627            &self,
1628            _: usize,
1629            _: Arc<TaskContext>,
1630        ) -> Result<SendableRecordBatchStream> {
1631            todo!()
1632        }
1633
1634        fn statistics_from_inputs(
1635            &self,
1636            _input_stats: &[Arc<Statistics>],
1637            args: &StatisticsArgs,
1638        ) -> Result<Arc<Statistics>> {
1639            if args.partition().is_some() {
1640                return Ok(Arc::new(Statistics::new_unknown(self.schema().as_ref())));
1641            }
1642            match self {
1643                Self::Panic => panic!("expected panic"),
1644                Self::Error => Err(internal_datafusion_err!("expected error")),
1645                Self::Ok => Ok(Arc::new(Statistics::new_unknown(self.schema().as_ref()))),
1646            }
1647        }
1648    }
1649
1650    fn test_stats_display(exec: TestStatsExecPlan, show_stats: bool) {
1651        let display =
1652            DisplayableExecutionPlan::new(&exec).set_show_statistics(show_stats);
1653
1654        let mut buf = String::new();
1655        write!(&mut buf, "{}", display.one_line()).unwrap();
1656        let buf = buf.trim();
1657        assert_eq!(buf, "TestStatsExecPlan");
1658    }
1659
1660    #[test]
1661    fn test_display_when_stats_panic_with_no_show_stats() {
1662        test_stats_display(TestStatsExecPlan::Panic, false);
1663    }
1664
1665    #[test]
1666    fn test_display_when_stats_error_with_no_show_stats() {
1667        test_stats_display(TestStatsExecPlan::Error, false);
1668    }
1669
1670    #[test]
1671    fn test_display_when_stats_ok_with_no_show_stats() {
1672        test_stats_display(TestStatsExecPlan::Ok, false);
1673    }
1674
1675    #[test]
1676    #[should_panic(expected = "expected panic")]
1677    fn test_display_when_stats_panic_with_show_stats() {
1678        test_stats_display(TestStatsExecPlan::Panic, true);
1679    }
1680
1681    #[test]
1682    #[should_panic(expected = "Error")] // fmt::Error
1683    fn test_display_when_stats_error_with_show_stats() {
1684        test_stats_display(TestStatsExecPlan::Error, true);
1685    }
1686
1687    #[test]
1688    fn test_display_when_stats_ok_with_show_stats() {
1689        test_stats_display(TestStatsExecPlan::Ok, false);
1690    }
1691
1692    mod pgjson {
1693        use std::sync::Arc;
1694        use std::time::Duration;
1695
1696        use arrow::datatypes::{DataType, Field, Schema};
1697        use insta::assert_snapshot;
1698
1699        use super::super::DisplayableExecutionPlan;
1700        use crate::empty::EmptyExec;
1701        use crate::filter::FilterExec;
1702        use crate::projection::ProjectionExec;
1703        use crate::{ChildrenPropertiesMode, ExecutionPlan, ReplaceChildrenOptions};
1704        use datafusion_physical_expr::expressions::{binary, col, lit};
1705        use datafusion_physical_expr::{Partitioning, PhysicalExpr};
1706
1707        fn sample_plan() -> Arc<dyn ExecutionPlan> {
1708            let schema = Arc::new(Schema::new(vec![
1709                Field::new("a", DataType::Int32, false),
1710                Field::new("b", DataType::Int32, false),
1711            ]));
1712            let empty = Arc::new(EmptyExec::new(Arc::clone(&schema)));
1713            let predicate = binary(
1714                col("a", &schema).unwrap(),
1715                datafusion_expr::Operator::Gt,
1716                lit(5i32),
1717                &schema,
1718            )
1719            .unwrap();
1720            let filter = Arc::new(FilterExec::try_new(predicate, empty).unwrap());
1721            let proj_expr: Vec<(Arc<dyn PhysicalExpr>, String)> =
1722                vec![(col("a", &schema).unwrap(), "a".to_string())];
1723            let _ = Partitioning::UnknownPartitioning(1);
1724            Arc::new(ProjectionExec::try_new(proj_expr, filter).unwrap())
1725        }
1726
1727        #[test]
1728        fn pgjson_renders_plan_without_metrics() {
1729            let plan = sample_plan();
1730            let out = DisplayableExecutionPlan::new(plan.as_ref())
1731                .pgjson(false)
1732                .to_string();
1733            let value: serde_json::Value = serde_json::from_str(&out).unwrap();
1734            // Root is an array with one {"Plan": ...} entry.
1735            let root = value
1736                .as_array()
1737                .expect("root array")
1738                .first()
1739                .expect("root entry")
1740                .get("Plan")
1741                .expect("plan object");
1742            assert_eq!(root["Node Type"].as_str(), Some("ProjectionExec"));
1743            assert!(root.get("Actual Rows").is_none());
1744            assert!(root.get("Extras").is_none());
1745            let plans = root["Plans"].as_array().expect("Plans array");
1746            assert_eq!(plans.len(), 1);
1747            assert_eq!(plans[0]["Node Type"].as_str(), Some("FilterExec"));
1748        }
1749
1750        #[test]
1751        fn pgjson_emits_pg_canonical_metric_keys() {
1752            use crate::metrics::{Count, Metric, MetricValue, MetricsSet, Time};
1753            use crate::{DisplayFormatType, ExecutionPlan, PlanProperties};
1754            use datafusion_common::Result;
1755            use datafusion_execution::{SendableRecordBatchStream, TaskContext};
1756
1757            // Wrap `sample_plan()` with an adapter node that exposes a
1758            // hand-crafted `MetricsSet` so we can assert the PG key mapping
1759            // without running anything.
1760            #[derive(Debug)]
1761            struct WithMetrics {
1762                inner: Arc<dyn ExecutionPlan>,
1763                metrics: MetricsSet,
1764            }
1765            impl crate::DisplayAs for WithMetrics {
1766                fn fmt_as(
1767                    &self,
1768                    _t: DisplayFormatType,
1769                    f: &mut std::fmt::Formatter,
1770                ) -> std::fmt::Result {
1771                    write!(f, "WithMetrics")
1772                }
1773            }
1774            impl ExecutionPlan for WithMetrics {
1775                fn name(&self) -> &'static str {
1776                    "WithMetrics"
1777                }
1778                fn properties(&self) -> &Arc<PlanProperties> {
1779                    self.inner.properties()
1780                }
1781                fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
1782                    vec![&self.inner]
1783                }
1784                fn apply_expressions(
1785                    &self,
1786                    _f: &mut dyn FnMut(
1787                        &Arc<dyn PhysicalExpr>,
1788                    ) -> Result<
1789                        datafusion_common::tree_node::TreeNodeRecursion,
1790                    >,
1791                ) -> Result<datafusion_common::tree_node::TreeNodeRecursion>
1792                {
1793                    Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue)
1794                }
1795
1796                fn replace_children(
1797                    self: Arc<Self>,
1798                    _: Vec<Arc<dyn ExecutionPlan>>,
1799                    _: ReplaceChildrenOptions,
1800                ) -> Result<Arc<dyn ExecutionPlan>> {
1801                    unimplemented!()
1802                }
1803                fn with_new_children(
1804                    self: Arc<Self>,
1805                    children: Vec<Arc<dyn ExecutionPlan>>,
1806                ) -> Result<Arc<dyn ExecutionPlan>> {
1807                    self.replace_children(
1808                        children,
1809                        ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
1810                    )
1811                }
1812                fn execute(
1813                    &self,
1814                    _: usize,
1815                    _: Arc<TaskContext>,
1816                ) -> Result<SendableRecordBatchStream> {
1817                    unimplemented!()
1818                }
1819                fn metrics(&self) -> Option<MetricsSet> {
1820                    Some(self.metrics.clone())
1821                }
1822            }
1823
1824            let mut metrics = MetricsSet::new();
1825            let rows = Count::new();
1826            rows.add(42);
1827            metrics.push(Arc::new(Metric::new(MetricValue::OutputRows(rows), None)));
1828            let elapsed = Time::new();
1829            elapsed.add_duration(Duration::from_millis(5));
1830            metrics.push(Arc::new(Metric::new(
1831                MetricValue::ElapsedCompute(elapsed),
1832                None,
1833            )));
1834            let batches = Count::new();
1835            batches.add(7);
1836            metrics.push(Arc::new(Metric::new(
1837                MetricValue::OutputBatches(batches),
1838                None,
1839            )));
1840
1841            let plan: Arc<dyn ExecutionPlan> = Arc::new(WithMetrics {
1842                inner: sample_plan(),
1843                metrics,
1844            });
1845
1846            let out = DisplayableExecutionPlan::with_metrics(plan.as_ref())
1847                .pgjson(false)
1848                .to_string();
1849            let value: serde_json::Value = serde_json::from_str(&out).unwrap();
1850            let root = value[0].get("Plan").expect("plan");
1851            assert_eq!(root["Actual Rows"].as_u64(), Some(42));
1852            assert_eq!(root["Actual Total Time"].as_f64(), Some(5.0));
1853            assert_eq!(root["Extras"]["output_batches"].as_u64(), Some(7));
1854
1855            let metric_names = vec!["output_rows".to_string()];
1856            for rendered in [
1857                DisplayableExecutionPlan::with_metrics(plan.as_ref())
1858                    .set_metric_names(metric_names.clone())
1859                    .indent(false)
1860                    .to_string(),
1861                DisplayableExecutionPlan::with_full_metrics(plan.as_ref())
1862                    .set_metric_names(metric_names.clone())
1863                    .indent(false)
1864                    .to_string(),
1865                DisplayableExecutionPlan::with_metrics(plan.as_ref())
1866                    .set_metric_names(metric_names.clone())
1867                    .graphviz()
1868                    .to_string(),
1869                DisplayableExecutionPlan::with_full_metrics(plan.as_ref())
1870                    .set_metric_names(metric_names.clone())
1871                    .graphviz()
1872                    .to_string(),
1873            ] {
1874                assert!(rendered.contains("output_rows"));
1875                assert!(!rendered.contains("elapsed_compute"));
1876                assert!(!rendered.contains("output_batches"));
1877            }
1878
1879            let out = DisplayableExecutionPlan::with_metrics(plan.as_ref())
1880                .set_metric_names(metric_names)
1881                .pgjson(false)
1882                .to_string();
1883            let value: serde_json::Value = serde_json::from_str(&out).unwrap();
1884            let root = value[0].get("Plan").expect("plan");
1885            assert_eq!(root["Actual Rows"].as_u64(), Some(42));
1886            assert!(root.get("Actual Total Time").is_none());
1887            assert!(root.get("Extras").is_none());
1888        }
1889
1890        #[test]
1891        fn pgjson_includes_summary_when_set() {
1892            let plan = sample_plan();
1893            let out = DisplayableExecutionPlan::with_metrics(plan.as_ref())
1894                .set_summary(Some(42), Some(Duration::from_millis(7)))
1895                .pgjson(false)
1896                .to_string();
1897            let value: serde_json::Value = serde_json::from_str(&out).unwrap();
1898            let entry = &value.as_array().unwrap()[0];
1899            assert_eq!(entry["Total Rows"].as_u64(), Some(42));
1900            assert!(entry["Duration"].is_string());
1901        }
1902
1903        #[test]
1904        fn pgjson_snapshot_of_sample_plan() {
1905            let plan = sample_plan();
1906            let out = DisplayableExecutionPlan::new(plan.as_ref())
1907                .pgjson(false)
1908                .to_string();
1909            assert_snapshot!(out, @r#"
1910            [
1911              {
1912                "Plan": {
1913                  "Node Type": "ProjectionExec",
1914                  "Details": "ProjectionExec: expr=[a@0 as a]",
1915                  "Plans": [
1916                    {
1917                      "Node Type": "FilterExec",
1918                      "Details": "FilterExec: a@0 > 5",
1919                      "Plans": [
1920                        {
1921                          "Node Type": "EmptyExec",
1922                          "Details": "EmptyExec",
1923                          "Plans": []
1924                        }
1925                      ]
1926                    }
1927                  ]
1928                }
1929              }
1930            ]
1931            "#);
1932        }
1933    }
1934}