1use std::collections::HashMap;
8use std::fmt;
9
10use crate::{
11 Aggregate, AsOfJoin, Distinct, DistinctOn, DmlStatement, Expr, Filter, Join, Limit,
12 LogicalPlan, MaterializedCte, MaterializedCtePlan, MaterializedCteScan, Partitioning,
13 Projection, RecursiveQuery, Repartition, Show, ShowKind, Sort, Subquery,
14 SubqueryAlias, TableProviderFilterPushDown, TableScan, Unnest, Values, Window,
15 WriteOp, expr_vec_fmt,
16};
17
18use crate::dml::CopyTo;
19use crate::logical_plan::information_schema::ColumnsDetail;
20use arrow::datatypes::Schema;
21use datafusion_common::display::GraphvizBuilder;
22use datafusion_common::tree_node::{TreeNodeRecursion, TreeNodeVisitor};
23use datafusion_common::{Column, DataFusionError, internal_datafusion_err};
24use serde::Serialize;
25use serde::ser::SerializeMap;
26
27pub struct IndentVisitor<'a, 'b> {
33 f: &'a mut fmt::Formatter<'b>,
34 with_schema: bool,
36 indent: usize,
38}
39
40impl<'a, 'b> IndentVisitor<'a, 'b> {
41 pub fn new(f: &'a mut fmt::Formatter<'b>, with_schema: bool) -> Self {
44 Self {
45 f,
46 with_schema,
47 indent: 0,
48 }
49 }
50}
51
52impl<'n> TreeNodeVisitor<'n> for IndentVisitor<'_, '_> {
53 type Node = LogicalPlan;
54
55 fn f_down(
56 &mut self,
57 plan: &'n LogicalPlan,
58 ) -> datafusion_common::Result<TreeNodeRecursion> {
59 if self.indent > 0 {
60 writeln!(self.f)?;
61 }
62 write!(self.f, "{:indent$}", "", indent = self.indent * 2)?;
63 write!(self.f, "{}", plan.display())?;
64 if self.with_schema {
65 write!(self.f, " {}", display_schema(plan.schema().as_arrow()))?;
66 }
67
68 self.indent += 1;
69 Ok(TreeNodeRecursion::Continue)
70 }
71
72 fn f_up(
73 &mut self,
74 _plan: &'n LogicalPlan,
75 ) -> datafusion_common::Result<TreeNodeRecursion> {
76 self.indent -= 1;
77 Ok(TreeNodeRecursion::Continue)
78 }
79}
80
81pub fn display_schema(schema: &Schema) -> impl fmt::Display + '_ {
100 struct Wrapper<'a>(&'a Schema);
101
102 impl fmt::Display for Wrapper<'_> {
103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104 write!(f, "[")?;
105 for (idx, field) in self.0.fields().iter().enumerate() {
106 if idx > 0 {
107 write!(f, ", ")?;
108 }
109 let nullable_str = if field.is_nullable() { ";N" } else { "" };
110 write!(f, "{}:{}{}", field.name(), field.data_type(), nullable_str)?;
111 }
112 write!(f, "]")
113 }
114 }
115 Wrapper(schema)
116}
117
118pub struct GraphvizVisitor<'a, 'b> {
122 f: &'a mut fmt::Formatter<'b>,
123 graphviz_builder: GraphvizBuilder,
124 with_schema: bool,
126
127 parent_ids: Vec<usize>,
130}
131
132impl<'a, 'b> GraphvizVisitor<'a, 'b> {
133 pub fn new(f: &'a mut fmt::Formatter<'b>) -> Self {
134 Self {
135 f,
136 graphviz_builder: GraphvizBuilder::default(),
137 with_schema: false,
138 parent_ids: Vec::new(),
139 }
140 }
141
142 pub fn set_with_schema(&mut self, with_schema: bool) {
144 self.with_schema = with_schema;
145 }
146
147 pub fn pre_visit_plan(&mut self, label: &str) -> fmt::Result {
148 self.graphviz_builder.start_cluster(self.f, label)
149 }
150
151 pub fn post_visit_plan(&mut self) -> fmt::Result {
152 self.graphviz_builder.end_cluster(self.f)
153 }
154
155 pub fn start_graph(&mut self) -> fmt::Result {
156 self.graphviz_builder.start_graph(self.f)
157 }
158
159 pub fn end_graph(&mut self) -> fmt::Result {
160 self.graphviz_builder.end_graph(self.f)
161 }
162}
163
164impl<'n> TreeNodeVisitor<'n> for GraphvizVisitor<'_, '_> {
165 type Node = LogicalPlan;
166
167 fn f_down(
168 &mut self,
169 plan: &'n LogicalPlan,
170 ) -> datafusion_common::Result<TreeNodeRecursion> {
171 let id = self.graphviz_builder.next_id();
172
173 let label = if self.with_schema {
176 format!(
177 r"{}\nSchema: {}",
178 plan.display(),
179 display_schema(plan.schema().as_arrow())
180 )
181 } else {
182 format!("{}", plan.display())
183 };
184
185 self.graphviz_builder
186 .add_node(self.f, id, &label, None)
187 .map_err(|_e| internal_datafusion_err!("Fail to format"))?;
188
189 if let Some(parent_id) = self.parent_ids.last() {
192 self.graphviz_builder
193 .add_edge(self.f, *parent_id, id)
194 .map_err(|_e| internal_datafusion_err!("Fail to format"))?;
195 }
196
197 self.parent_ids.push(id);
198 Ok(TreeNodeRecursion::Continue)
199 }
200
201 fn f_up(
202 &mut self,
203 _plan: &LogicalPlan,
204 ) -> datafusion_common::Result<TreeNodeRecursion> {
205 let res = self.parent_ids.pop();
208 res.ok_or(internal_datafusion_err!("Fail to format"))
209 .map(|_| TreeNodeRecursion::Continue)
210 }
211}
212
213macro_rules! pg_fields {
215 ($($key:literal : $value:expr),* $(,)?) => {
216 PgJsonFields(vec![$(($key, serde_json::json!($value))),*])
217 };
218}
219
220struct PgJsonFields(Vec<(&'static str, serde_json::Value)>);
224
225impl PgJsonFields {
226 fn push(&mut self, key: &'static str, value: impl Into<serde_json::Value>) {
227 self.0.push((key, value.into()));
228 }
229}
230
231struct PgJsonNode {
234 fields: PgJsonFields,
235 plans: Vec<PgJsonNode>,
236 output: Option<Vec<String>>,
237}
238
239impl Serialize for PgJsonNode {
240 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
241 let mut map = serializer.serialize_map(None)?;
242 for (key, value) in &self.fields.0 {
243 map.serialize_entry(key, value)?;
244 }
245 map.serialize_entry("Plans", &self.plans)?;
246 if let Some(output) = &self.output {
247 map.serialize_entry("Output", output)?;
248 }
249 map.end()
250 }
251}
252
253#[derive(Serialize)]
255struct PgJsonRoot {
256 #[serde(rename = "Plan")]
257 plan: PgJsonNode,
258}
259
260pub struct PgJsonVisitor<'a, 'b> {
308 f: &'a mut fmt::Formatter<'b>,
309
310 objects: HashMap<u32, PgJsonNode>,
312
313 next_id: u32,
314
315 with_schema: bool,
317
318 parent_ids: Vec<u32>,
321}
322
323impl<'a, 'b> PgJsonVisitor<'a, 'b> {
324 pub fn new(f: &'a mut fmt::Formatter<'b>) -> Self {
325 Self {
326 f,
327 objects: HashMap::new(),
328 next_id: 0,
329 with_schema: false,
330 parent_ids: Vec::new(),
331 }
332 }
333
334 pub fn with_schema(&mut self, with_schema: bool) {
336 self.with_schema = with_schema;
337 }
338
339 fn to_json_value(node: &LogicalPlan) -> PgJsonFields {
341 match node {
342 LogicalPlan::EmptyRelation(_) => {
343 pg_fields!(
344 "Node Type": "EmptyRelation",
345 )
346 }
347 LogicalPlan::RecursiveQuery(RecursiveQuery { is_distinct, .. }) => {
348 pg_fields!(
349 "Node Type": "RecursiveQuery",
350 "Is Distinct": is_distinct,
351 )
352 }
353 LogicalPlan::Values(Values { values, .. }) => {
354 let str_values = values
355 .iter()
356 .take(5)
358 .map(|row| {
359 let item = row
360 .iter()
361 .map(|expr| expr.to_string())
362 .collect::<Vec<_>>()
363 .join(", ");
364 format!("({item})")
365 })
366 .collect::<Vec<_>>()
367 .join(", ");
368
369 let eclipse = if values.len() > 5 { "..." } else { "" };
370
371 let values_str = format!("{str_values}{eclipse}");
372 pg_fields!(
373 "Node Type": "Values",
374 "Values": values_str
375 )
376 }
377 LogicalPlan::TableScan(TableScan {
378 source,
379 table_name,
380 filters,
381 fetch,
382 skip,
383 ..
384 }) => {
385 let mut object = pg_fields!(
386 "Node Type": "TableScan",
387 "Relation Name": table_name.table(),
388 );
389
390 if let Some(s) = table_name.schema() {
391 object.push("Schema", serde_json::Value::String(s.to_string()));
392 }
393
394 if let Some(c) = table_name.catalog() {
395 object.push("Catalog", serde_json::Value::String(c.to_string()));
396 }
397
398 if !filters.is_empty() {
399 let mut full_filter = vec![];
400 let mut partial_filter = vec![];
401 let mut unsupported_filters = vec![];
402 let filters: Vec<&Expr> = filters.iter().collect();
403
404 if let Ok(results) = source.supports_filters_pushdown(&filters) {
405 filters.iter().zip(results.iter()).for_each(
406 |(x, res)| match res {
407 TableProviderFilterPushDown::Exact => full_filter.push(x),
408 TableProviderFilterPushDown::Inexact => {
409 partial_filter.push(x)
410 }
411 TableProviderFilterPushDown::Unsupported => {
412 unsupported_filters.push(x)
413 }
414 },
415 );
416 }
417
418 if !full_filter.is_empty() {
419 object.push(
420 "Full Filters",
421 serde_json::Value::String(expr_vec_fmt!(full_filter)),
422 );
423 }
424 if !partial_filter.is_empty() {
425 object.push(
426 "Partial Filters",
427 serde_json::Value::String(expr_vec_fmt!(partial_filter)),
428 );
429 }
430 if !unsupported_filters.is_empty() {
431 object.push(
432 "Unsupported Filters",
433 serde_json::Value::String(expr_vec_fmt!(unsupported_filters)),
434 );
435 }
436 }
437
438 if let Some(f) = fetch {
439 object.push("Fetch", serde_json::Value::Number((*f).into()));
440 }
441
442 if let Some(s) = skip {
443 object.push("Skip", serde_json::Value::Number((*s).into()));
444 }
445
446 object
447 }
448 LogicalPlan::Projection(Projection { expr, .. }) => {
449 pg_fields!(
450 "Node Type": "Projection",
451 "Expressions": expr.iter().map(|e| e.to_string()).collect::<Vec<_>>()
452 )
453 }
454 LogicalPlan::Dml(DmlStatement { table_name, op, .. }) => {
455 let mut object = pg_fields!(
456 "Node Type": "Dml",
457 "Operation": op.name(),
458 "Table Name": table_name.table()
459 );
460 if let WriteOp::MergeInto(merge_op) = op {
461 object.push("On", serde_json::Value::String(merge_op.on.to_string()));
462 object.push(
463 "Clauses",
464 serde_json::Value::Array(
465 merge_op
466 .clauses
467 .iter()
468 .map(|clause| {
469 serde_json::Value::String(clause.to_string())
470 })
471 .collect(),
472 ),
473 );
474 }
475 object
476 }
477 LogicalPlan::Copy(CopyTo {
478 input: _,
479 output_url,
480 file_type,
481 partition_by: _,
482 options,
483 output_schema: _,
484 }) => {
485 let op_str = options
486 .iter()
487 .map(|(k, v)| format!("{k}={v}"))
488 .collect::<Vec<_>>()
489 .join(", ");
490 pg_fields!(
491 "Node Type": "CopyTo",
492 "Output URL": output_url,
493 "File Type": file_type.get_ext(),
494 "Options": op_str
495 )
496 }
497 LogicalPlan::Ddl(ddl) => {
498 pg_fields!(
499 "Node Type": "Ddl",
500 "Operation": format!("{}", ddl.display())
501 )
502 }
503 LogicalPlan::Filter(Filter {
504 predicate: expr, ..
505 }) => {
506 pg_fields!(
507 "Node Type": "Filter",
508 "Condition": format!("{}", expr)
509 )
510 }
511 LogicalPlan::Window(Window { window_expr, .. }) => {
512 pg_fields!(
513 "Node Type": "WindowAggr",
514 "Expressions": expr_vec_fmt!(window_expr)
515 )
516 }
517 LogicalPlan::Aggregate(Aggregate {
518 group_expr,
519 aggr_expr,
520 ..
521 }) => {
522 pg_fields!(
523 "Node Type": "Aggregate",
524 "Group By": expr_vec_fmt!(group_expr),
525 "Aggregates": expr_vec_fmt!(aggr_expr)
526 )
527 }
528 LogicalPlan::Sort(Sort { expr, fetch, .. }) => {
529 let mut object = pg_fields!(
530 "Node Type": "Sort",
531 "Sort Key": expr_vec_fmt!(expr),
532 );
533
534 if let Some(fetch) = fetch {
535 object.push("Fetch", serde_json::Value::Number((*fetch).into()));
536 }
537
538 object
539 }
540 LogicalPlan::Join(Join {
541 on: keys,
542 filter,
543 join_constraint,
544 join_type,
545 ..
546 }) => {
547 let join_expr: Vec<String> =
548 keys.iter().map(|(l, r)| format!("{l} = {r}")).collect();
549 let filter_expr = filter
550 .as_ref()
551 .map(|expr| format!(" Filter: {expr}"))
552 .unwrap_or_else(|| "".to_string());
553 pg_fields!(
554 "Node Type": format!("{} Join", join_type),
555 "Join Constraint": format!("{:?}", join_constraint),
556 "Join Keys": join_expr.join(", "),
557 "Filter": filter_expr.to_string()
558 )
559 }
560 LogicalPlan::AsOfJoin(AsOfJoin {
561 on,
562 match_condition,
563 join_constraint,
564 ..
565 }) => {
566 let join_expr: Vec<String> =
567 on.iter().map(|(l, r)| format!("{l} = {r}")).collect();
568 pg_fields!(
569 "Node Type": "AsOf Join",
570 "Join Constraint": format!("{join_constraint:?}"),
571 "Join Keys": join_expr.join(", "),
572 "Match Condition": match_condition.to_string()
573 )
574 }
575 LogicalPlan::Repartition(Repartition {
576 partitioning_scheme,
577 ..
578 }) => match partitioning_scheme {
579 Partitioning::RoundRobinBatch(n) => {
580 pg_fields!(
581 "Node Type": "Repartition",
582 "Partitioning Scheme": "RoundRobinBatch",
583 "Partition Count": n
584 )
585 }
586 Partitioning::Hash(expr, n) => {
587 let hash_expr: Vec<String> =
588 expr.iter().map(|e| format!("{e}")).collect();
589
590 pg_fields!(
591 "Node Type": "Repartition",
592 "Partitioning Scheme": "Hash",
593 "Partition Count": n,
594 "Partitioning Key": hash_expr
595 )
596 }
597 Partitioning::Range(range) => {
598 let range_expr: Vec<String> =
599 range.ordering().iter().map(|e| format!("{e}")).collect();
600 let split_points: Vec<String> = range
601 .split_points()
602 .iter()
603 .map(|e| format!("{e}"))
604 .collect();
605
606 pg_fields!(
607 "Node Type": "Repartition",
608 "Partitioning Scheme": "Range",
609 "Partition Count": range.partition_count(),
610 "Partitioning Key": range_expr,
611 "Split Points": split_points
612 )
613 }
614 Partitioning::DistributeBy(expr) => {
615 let dist_by_expr: Vec<String> =
616 expr.iter().map(|e| format!("{e}")).collect();
617 pg_fields!(
618 "Node Type": "Repartition",
619 "Partitioning Scheme": "DistributeBy",
620 "Partitioning Key": dist_by_expr
621 )
622 }
623 },
624 LogicalPlan::Limit(Limit { skip, fetch, .. }) => {
625 let mut object = pg_fields!("Node Type": "Limit");
626 if let Some(s) = skip {
627 object.push("Skip", s.to_string());
628 }
629 if let Some(f) = fetch {
630 object.push("Fetch", f.to_string());
631 }
632 object
633 }
634 LogicalPlan::Subquery(Subquery { .. }) => {
635 pg_fields!(
636 "Node Type": "Subquery"
637 )
638 }
639 LogicalPlan::SubqueryAlias(SubqueryAlias { alias, .. }) => {
640 pg_fields!(
641 "Node Type": "Subquery",
642 "Alias": alias.table(),
643 )
644 }
645 LogicalPlan::Statement(statement) => {
646 pg_fields!(
647 "Node Type": "Statement",
648 "Statement": format!("{}", statement.display())
649 )
650 }
651 LogicalPlan::Distinct(distinct) => match distinct {
652 Distinct::All(_) => {
653 pg_fields!(
654 "Node Type": "DistinctAll"
655 )
656 }
657 Distinct::On(DistinctOn {
658 on_expr,
659 select_expr,
660 sort_expr,
661 ..
662 }) => {
663 let mut object = pg_fields!(
664 "Node Type": "DistinctOn",
665 "On": expr_vec_fmt!(on_expr),
666 "Select": expr_vec_fmt!(select_expr),
667 );
668 if let Some(sort_expr) = sort_expr {
669 object.push(
670 "Sort",
671 serde_json::Value::String(expr_vec_fmt!(sort_expr)),
672 );
673 }
674
675 object
676 }
677 },
678 LogicalPlan::Explain { .. } => {
679 pg_fields!(
680 "Node Type": "Explain"
681 )
682 }
683 LogicalPlan::Analyze { .. } => {
684 pg_fields!(
685 "Node Type": "Analyze"
686 )
687 }
688 LogicalPlan::Union(_) => {
689 pg_fields!(
690 "Node Type": "Union"
691 )
692 }
693 LogicalPlan::Extension(e) => {
694 pg_fields!(
695 "Node Type": e.node.name(),
696 "Detail": format!("{:?}", e.node)
697 )
698 }
699 LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte {
700 name,
701 ..
702 })) => {
703 pg_fields!(
704 "Node Type": "MaterializedCte",
705 "Name": name,
706 )
707 }
708 LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(
709 MaterializedCteScan { name, .. },
710 )) => {
711 pg_fields!(
712 "Node Type": "MaterializedCteScan",
713 "Name": name,
714 )
715 }
716 LogicalPlan::Show(Show { kind, .. }) => match kind {
717 ShowKind::Describe { .. } => {
718 pg_fields!(
719 "Node Type": "Describe"
720 )
721 }
722 ShowKind::Tables => {
723 pg_fields!(
724 "Node Type": "ShowTables"
725 )
726 }
727 ShowKind::Columns {
728 table_ref,
729 detail: ColumnsDetail::Describe,
730 } => {
731 pg_fields!(
732 "Node Type": "DescribeTable",
733 "Relation Name": table_ref.table()
734 )
735 }
736 ShowKind::Columns { table_ref, detail } => {
737 pg_fields!(
738 "Node Type": "ShowColumns",
739 "Relation Name": table_ref.table(),
740 "Detail": format!("{detail:?}")
741 )
742 }
743 ShowKind::CreateTable { table_ref } => {
744 pg_fields!(
745 "Node Type": "ShowCreateTable",
746 "Relation Name": table_ref.table()
747 )
748 }
749 ShowKind::Variables { name, verbose } => {
750 let mut object = pg_fields!(
751 "Node Type": "ShowVariables",
752 "Verbose": verbose
753 );
754 if let Some(name) = name {
755 object.push("Variable", serde_json::Value::String(name.clone()));
756 }
757 object
758 }
759 ShowKind::Functions { filter } => {
760 let mut object = pg_fields!(
761 "Node Type": "ShowFunctions"
762 );
763 if let Some(filter) = filter {
764 object.push("Filter", serde_json::Value::String(filter.clone()));
765 }
766 object
767 }
768 },
769 LogicalPlan::Unnest(Unnest {
770 input: plan,
771 list_type_columns: list_col_indices,
772 struct_type_columns: struct_col_indices,
773 ..
774 }) => {
775 let input_columns = plan.schema().columns();
776 let list_type_columns = list_col_indices
777 .iter()
778 .map(|(i, unnest_info)| {
779 format!("{}|depth={:?}", input_columns[*i], unnest_info.depth)
780 })
781 .collect::<Vec<String>>();
782 let struct_type_columns = struct_col_indices
783 .iter()
784 .map(|i| &input_columns[*i])
785 .collect::<Vec<&Column>>();
786 pg_fields!(
787 "Node Type": "Unnest",
788 "ListColumn": expr_vec_fmt!(list_type_columns),
789 "StructColumn": expr_vec_fmt!(struct_type_columns),
790 )
791 }
792 }
793 }
794}
795
796impl<'n> TreeNodeVisitor<'n> for PgJsonVisitor<'_, '_> {
797 type Node = LogicalPlan;
798
799 fn f_down(
800 &mut self,
801 node: &'n LogicalPlan,
802 ) -> datafusion_common::Result<TreeNodeRecursion> {
803 let id = self.next_id;
804 self.next_id += 1;
805 let object = PgJsonNode {
806 fields: Self::to_json_value(node),
807 plans: vec![],
808 output: self.with_schema.then(|| {
809 node.schema()
810 .fields()
811 .iter()
812 .map(|f| f.name().to_string())
813 .collect()
814 }),
815 };
816
817 self.objects.insert(id, object);
818 self.parent_ids.push(id);
819 Ok(TreeNodeRecursion::Continue)
820 }
821
822 fn f_up(
823 &mut self,
824 _node: &Self::Node,
825 ) -> datafusion_common::Result<TreeNodeRecursion> {
826 let id = self.parent_ids.pop().unwrap();
827
828 let current_node = self
829 .objects
830 .remove(&id)
831 .ok_or_else(|| internal_datafusion_err!("Missing current node!"))?;
832
833 if let Some(parent_id) = self.parent_ids.last() {
834 let parent_node = self
835 .objects
836 .get_mut(parent_id)
837 .expect("Missing parent node!");
838 parent_node.plans.push(current_node);
839 } else {
840 let plan = [PgJsonRoot { plan: current_node }];
842 write!(
843 self.f,
844 "{}",
845 serde_json::to_string_pretty(&plan)
846 .map_err(|e| DataFusionError::External(Box::new(e)))?
847 )?;
848 }
849
850 Ok(TreeNodeRecursion::Continue)
851 }
852}
853
854#[cfg(test)]
855mod tests {
856 use arrow::datatypes::{DataType, Field};
857 use insta::assert_snapshot;
858
859 use super::*;
860
861 #[test]
862 fn test_display_empty_schema() {
863 let schema = Schema::empty();
864 assert_snapshot!(display_schema(&schema), @"[]");
865 }
866
867 #[test]
868 fn test_display_schema() {
869 let schema = Schema::new(vec![
870 Field::new("id", DataType::Int32, false),
871 Field::new("first_name", DataType::Utf8, true),
872 ]);
873
874 assert_snapshot!(display_schema(&schema), @"[id:Int32, first_name:Utf8;N]");
875 }
876}