Skip to main content

datafusion_common/display/
graphviz.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Logic related to creating DOT language graphs.
6
7use std::fmt;
8
9#[derive(Default)]
10pub struct GraphvizBuilder {
11    id_gen: usize,
12}
13
14impl GraphvizBuilder {
15    // Generate next id in graphviz.
16    pub fn next_id(&mut self) -> usize {
17        self.id_gen += 1;
18        self.id_gen
19    }
20
21    // Write out the start of whole graph.
22    pub fn start_graph(&mut self, f: &mut fmt::Formatter) -> fmt::Result {
23        writeln!(
24            f,
25            r#"
26// Begin DataFusion GraphViz Plan,
27// display it online here: https://dreampuf.github.io/GraphvizOnline
28"#
29        )?;
30        writeln!(f, "digraph {{")
31    }
32
33    pub fn end_graph(&mut self, f: &mut fmt::Formatter) -> fmt::Result {
34        writeln!(f, "}}")?;
35        writeln!(f, "// End DataFusion GraphViz Plan")
36    }
37
38    // write out the start of the subgraph cluster
39    pub fn start_cluster(&mut self, f: &mut fmt::Formatter, title: &str) -> fmt::Result {
40        writeln!(f, "  subgraph cluster_{}", self.next_id())?;
41        writeln!(f, "  {{")?;
42        writeln!(f, "    graph[label={}]", Self::quoted(title))
43    }
44
45    // write out the end of the subgraph cluster
46    pub fn end_cluster(&mut self, f: &mut fmt::Formatter) -> fmt::Result {
47        writeln!(f, "  }}")
48    }
49
50    /// makes a quoted string suitable for inclusion in a graphviz chart
51    pub fn quoted(label: &str) -> String {
52        let label = label.replace('"', "_");
53        format!("\"{label}\"")
54    }
55
56    pub fn add_node(
57        &self,
58        f: &mut fmt::Formatter,
59        id: usize,
60        label: &str,
61        tooltip: Option<&str>,
62    ) -> fmt::Result {
63        let tooltip = tooltip
64            .map(|tooltip| format!(", tooltip={}", GraphvizBuilder::quoted(tooltip)))
65            .unwrap_or_default();
66
67        writeln!(
68            f,
69            "    {}[shape=box label={}{}]",
70            id,
71            GraphvizBuilder::quoted(label),
72            tooltip,
73        )
74    }
75
76    pub fn add_edge(
77        &self,
78        f: &mut fmt::Formatter,
79        from_id: usize,
80        to_id: usize,
81    ) -> fmt::Result {
82        writeln!(
83            f,
84            "    {from_id} -> {to_id} [arrowhead=none, arrowtail=normal, dir=back]"
85        )
86    }
87}