Skip to main content

velesdb_core/velesql/explain/
formatter.rs

1//! Query plan rendering and formatting for EXPLAIN output.
2//!
3//! Extracted from `explain.rs` for maintainability (04-06 module splitting).
4//! Handles tree rendering, JSON serialization, and Display formatting.
5
6use std::fmt::{self, Write as _};
7
8use super::{
9    FilterPlan, FilterStrategy, FusionInfo, IndexType, MatchTraversalPlan, PlanNode, QueryPlan,
10};
11
12impl QueryPlan {
13    /// Renders the plan as a tree string.
14    #[must_use]
15    pub fn to_tree(&self) -> String {
16        let mut output = String::from("Query Plan:\n");
17        Self::render_node(&self.root, &mut output, "", true);
18
19        Self::render_with_options(&self.with_options, &mut output);
20        Self::render_let_bindings(&self.let_bindings, &mut output);
21        Self::render_fusion_info(self.fusion_info.as_ref(), &mut output);
22
23        let _ = write!(
24            output,
25            "\nEstimated cost: {:.3}ms\n",
26            self.estimated_cost_ms
27        );
28
29        if let Some(ref idx) = self.index_used {
30            let _ = writeln!(output, "Index used: {}", idx.as_str());
31        }
32
33        if self.filter_strategy != FilterStrategy::None {
34            let _ = writeln!(output, "Filter strategy: {}", self.filter_strategy.as_str());
35        }
36
37        if let Some(hit) = self.cache_hit {
38            let _ = writeln!(output, "Cache hit: {hit}");
39        }
40        if let Some(count) = self.plan_reuse_count {
41            let _ = writeln!(output, "Plan reuse count: {count}");
42        }
43
44        output
45    }
46
47    /// Renders WITH clause options into the tree output.
48    fn render_with_options(options: &[(String, String)], output: &mut String) {
49        if options.is_empty() {
50            return;
51        }
52        let _ = writeln!(output, "\nWITH options:");
53        for (key, value) in options {
54            let _ = writeln!(output, "  {key} = {value}");
55        }
56    }
57
58    /// Renders LET bindings into the tree output.
59    fn render_let_bindings(bindings: &[String], output: &mut String) {
60        if bindings.is_empty() {
61            return;
62        }
63        let _ = writeln!(output, "\nLET bindings:");
64        for binding in bindings {
65            let _ = writeln!(output, "  {binding}");
66        }
67    }
68
69    /// Renders FUSION info into the tree output.
70    fn render_fusion_info(info: Option<&FusionInfo>, output: &mut String) {
71        let Some(fi) = info else { return };
72        let _ = writeln!(output, "\nFUSION:");
73        let _ = writeln!(output, "  Strategy: {}", fi.strategy);
74        if let Some(k) = fi.k {
75            let _ = writeln!(output, "  k: {k}");
76        }
77        if let Some(ref w) = fi.weights {
78            let _ = writeln!(output, "  Weights: {w}");
79        }
80    }
81
82    pub(crate) fn render_node(node: &PlanNode, output: &mut String, prefix: &str, is_last: bool) {
83        let connector = if is_last { "└─ " } else { "├─ " };
84        let child_prefix = format!("{}{}", prefix, if is_last { "   " } else { "│  " });
85
86        match node {
87            PlanNode::VectorSearch(vs) => {
88                let _ = writeln!(output, "{prefix}{connector}VectorSearch");
89                let _ = writeln!(output, "{child_prefix}├─ Collection: {}", vs.collection);
90                let _ = writeln!(output, "{child_prefix}├─ ef_search: {}", vs.ef_search);
91                let _ = writeln!(output, "{child_prefix}└─ Candidates: {}", vs.candidates);
92            }
93            PlanNode::Filter(f) => {
94                Self::render_filter_node(f, output, prefix, connector, &child_prefix);
95            }
96            PlanNode::Limit(l) => {
97                let _ = writeln!(output, "{prefix}{connector}Limit: {}", l.count);
98            }
99            PlanNode::Offset(o) => {
100                let _ = writeln!(output, "{prefix}{connector}Offset: {}", o.count);
101            }
102            PlanNode::TableScan(ts) => {
103                let _ = writeln!(output, "{prefix}{connector}TableScan: {}", ts.collection);
104            }
105            PlanNode::IndexLookup(il) => {
106                let _ = writeln!(
107                    output,
108                    "{prefix}{connector}IndexLookup({}.{})",
109                    il.label, il.property
110                );
111                let _ = writeln!(output, "{child_prefix}└─ Value: {}", il.value);
112            }
113            PlanNode::Sequence(nodes) => {
114                for (i, child) in nodes.iter().enumerate() {
115                    Self::render_node(child, output, prefix, i == nodes.len() - 1);
116                }
117            }
118            PlanNode::MatchTraversal(mt) => {
119                Self::render_match_traversal_node(mt, output, prefix, connector, &child_prefix);
120            }
121        }
122    }
123
124    /// Renders a `Filter` plan node into the tree output.
125    fn render_filter_node(
126        f: &FilterPlan,
127        output: &mut String,
128        prefix: &str,
129        connector: &str,
130        child_prefix: &str,
131    ) {
132        let _ = writeln!(output, "{prefix}{connector}Filter");
133        let _ = writeln!(output, "{child_prefix}├─ Conditions: {}", f.conditions);
134        // R7: estimated_rows and estimation_method are rendered when present.
135        if let Some(rows) = f.estimated_rows {
136            let _ = writeln!(output, "{child_prefix}├─ Estimated rows: {rows}");
137        }
138        if let Some(ref method) = f.estimation_method {
139            let _ = writeln!(output, "{child_prefix}├─ Estimation method: {method}");
140        }
141        let _ = writeln!(
142            output,
143            "{child_prefix}└─ Selectivity: {:.1}%",
144            f.selectivity * 100.0
145        );
146    }
147
148    /// Renders a `MatchTraversal` plan node into the tree output.
149    fn render_match_traversal_node(
150        mt: &MatchTraversalPlan,
151        output: &mut String,
152        prefix: &str,
153        connector: &str,
154        child_prefix: &str,
155    ) {
156        let _ = writeln!(output, "{prefix}{connector}MatchTraversal");
157        let _ = writeln!(output, "{child_prefix}├─ Strategy: {}", mt.strategy);
158        if !mt.start_labels.is_empty() {
159            let _ = writeln!(
160                output,
161                "{child_prefix}├─ Start Labels: [{}]",
162                mt.start_labels.join(", ")
163            );
164        }
165        let _ = writeln!(output, "{child_prefix}├─ Max Depth: {}", mt.max_depth);
166        let _ = writeln!(
167            output,
168            "{child_prefix}├─ Relationships: {}",
169            mt.relationship_count
170        );
171        if let Some(threshold) = mt.similarity_threshold {
172            let _ = writeln!(
173                output,
174                "{child_prefix}└─ Similarity Threshold: {:.2}",
175                threshold
176            );
177        } else {
178            let _ = writeln!(
179                output,
180                "{child_prefix}└─ Similarity: {}",
181                if mt.has_similarity { "yes" } else { "no" }
182            );
183        }
184    }
185
186    /// Renders the plan as JSON.
187    ///
188    /// # Errors
189    ///
190    /// Returns an error if serialization fails.
191    pub fn to_json(&self) -> Result<String, serde_json::Error> {
192        serde_json::to_string_pretty(self)
193    }
194}
195
196impl IndexType {
197    /// Returns the index type as a string.
198    #[must_use]
199    pub const fn as_str(&self) -> &'static str {
200        match self {
201            Self::Hnsw => "HNSW",
202            Self::Flat => "Flat",
203            Self::BinaryQuantization => "BinaryQuantization",
204            Self::Property => "PropertyIndex",
205        }
206    }
207}
208
209impl FilterStrategy {
210    /// Returns the filter strategy as a string.
211    #[must_use]
212    pub const fn as_str(&self) -> &'static str {
213        match self {
214            Self::None => "none",
215            Self::PreFilter => "pre-filtering (high selectivity)",
216            Self::PostFilter => "post-filtering (low selectivity)",
217        }
218    }
219}
220
221impl super::super::ast::CompareOp {
222    /// Returns the operator as a string.
223    #[must_use]
224    pub const fn as_str(&self) -> &'static str {
225        match self {
226            Self::Eq => "=",
227            Self::NotEq => "!=",
228            Self::Gt => ">",
229            Self::Gte => ">=",
230            Self::Lt => "<",
231            Self::Lte => "<=",
232        }
233    }
234}
235
236impl fmt::Display for QueryPlan {
237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238        write!(f, "{}", self.to_tree())
239    }
240}
241
242/// Formats a `WithValue` for human-readable EXPLAIN display.
243pub(super) fn format_with_value(v: &super::super::ast::WithValue) -> String {
244    match v {
245        super::super::ast::WithValue::String(s) | super::super::ast::WithValue::Identifier(s) => {
246            s.clone()
247        }
248        super::super::ast::WithValue::Integer(i) => i.to_string(),
249        super::super::ast::WithValue::Float(f) => f.to_string(),
250        super::super::ast::WithValue::Boolean(b) => b.to_string(),
251    }
252}