1use 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#[derive(Debug, Clone, Copy, PartialEq)]
43pub enum DisplayFormatType {
44 Default,
49 Verbose,
53 TreeRender,
85}
86
87#[derive(Debug, Clone)]
121pub struct DisplayableExecutionPlan<'a> {
122 inner: &'a dyn ExecutionPlan,
123 show_metrics: ShowMetrics,
125 show_statistics: bool,
127 show_schema: bool,
129 metric_types: Vec<MetricType>,
131 metric_categories: Option<Vec<MetricCategory>>,
134 metric_names: Option<Vec<String>>,
137 tree_maximum_render_width: usize,
139 summary: Option<AnalyzeSummary>,
142}
143
144#[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 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 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 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 pub fn set_show_schema(mut self, show_schema: bool) -> Self {
212 self.show_schema = show_schema;
213 self
214 }
215
216 pub fn set_show_statistics(mut self, show_statistics: bool) -> Self {
218 self.show_statistics = show_statistics;
219 self
220 }
221
222 pub fn set_metric_types(mut self, metric_types: Vec<MetricType>) -> Self {
224 self.metric_types = metric_types;
225 self
226 }
227
228 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 pub fn set_metric_names(mut self, metric_names: Vec<String>) -> Self {
253 self.metric_names = Some(metric_names);
254 self
255 }
256
257 pub fn set_tree_maximum_render_width(mut self, width: usize) -> Self {
259 self.tree_maximum_render_width = width;
260 self
261 }
262
263 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 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 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 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 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 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#[derive(Debug, Clone, Copy)]
539enum ShowMetrics {
540 None,
542
543 Aggregated,
545
546 Full,
548}
549
550struct IndentVisitor<'a, 'b> {
560 t: DisplayFormatType,
562 f: &'a mut Formatter<'b>,
564 indent: usize,
566 show_metrics: ShowMetrics,
568 show_statistics: bool,
570 show_schema: bool,
572 metric_types: &'a [MetricType],
574 metric_categories: Option<&'a [MetricCategory]>,
576 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 t: DisplayFormatType,
648 show_metrics: ShowMetrics,
650 show_statistics: bool,
652 metric_types: &'a [MetricType],
654 metric_categories: Option<&'a [MetricCategory]>,
656 metric_names: Option<&'a [String]>,
658
659 graphviz_builder: GraphvizBuilder,
660 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
764struct 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#[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#[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#[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 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 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 format!("{}", One(plan))
853 .replace('\n', " ")
854 .trim()
855 .to_string()
856 }
857
858 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 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 other => serde_json::Value::String(format!("{other}")),
890 }
891 }
892
893 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 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 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 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
1001struct TreeRenderVisitor<'a, 'b> {
1025 f: &'a mut Formatter<'b>,
1027 maximum_render_width: usize,
1029}
1030
1031impl TreeRenderVisitor<'_, '_> {
1032 const LTCORNER: &'static str = "┌"; const RTCORNER: &'static str = "┐"; const LDCORNER: &'static str = "└"; const RDCORNER: &'static str = "┘"; const TMIDDLE: &'static str = "┬"; const LMIDDLE: &'static str = "├"; const DMIDDLE: &'static str = "┴"; const VERTICAL: &'static str = "│"; const HORIZONTAL: &'static str = "─"; const NODE_RENDER_WIDTH: usize = 29; const MAX_EXTRA_LINES: usize = 30; 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 self.render_top_layer(&root, y)?;
1060 self.render_box_content(&root, y)?;
1062 self.render_bottom_layer(&root, y)?;
1064 }
1065
1066 Ok(())
1067 }
1068
1069 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 write!(self.f, "{}", Self::HORIZONTAL)?;
1096 } else {
1097 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 continue;
1115 }
1116 write!(self.f, "{}", " ".repeat(Self::NODE_RENDER_WIDTH))?;
1118 }
1119 }
1120 writeln!(self.f)?;
1121
1122 Ok(())
1123 }
1124
1125 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 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 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 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 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 write!(
1213 self.f,
1214 "{}",
1215 " ".repeat(Self::NODE_RENDER_WIDTH / 2)
1216 )?;
1217 }
1218 }
1219 } else if has_child_to_the_right {
1220 write!(
1223 self.f,
1224 "{}",
1225 Self::HORIZONTAL.repeat(Self::NODE_RENDER_WIDTH)
1226 )?;
1227 } else if has_adjacent_nodes {
1228 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 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 write!(self.f, "{}", " ".repeat(Self::NODE_RENDER_WIDTH))?;
1254 }
1255 } else if has_adjacent_nodes {
1256 write!(self.f, "{}", " ".repeat(Self::NODE_RENDER_WIDTH))?;
1258 }
1259 }
1260 writeln!(self.f)?;
1261 }
1262
1263 Ok(())
1264 }
1265
1266 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 write!(self.f, "{}", Self::TMIDDLE)?;
1296 } else {
1297 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 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 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 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 let char_width = 1;
1453
1454 if render_width + char_width > Self::NODE_RENDER_WIDTH - 2 {
1456 if start_pos + 8 > last_possible_split {
1457 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 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 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
1489pub trait DisplayAs {
1491 fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> fmt::Result;
1496}
1497
1498pub 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
1507pub 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#[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")] 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 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 #[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}