Skip to main content

rustcmdpev_core/structure/
tree.rs

1use crate::constants::{MAX_PLAN_DEPTH, MAX_PLAN_NODES};
2use crate::structure::data::plan::Plan;
3use crate::VisualizeError;
4
5/// Summary information derived while validating a plan tree.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct TreeStats {
8    pub node_count: usize,
9    pub max_depth: usize,
10}
11
12/// A validated plan tree with explicit root node semantics.
13#[derive(Debug, Clone)]
14pub struct PlanTree {
15    root: Plan,
16    stats: TreeStats,
17}
18
19impl PlanTree {
20    /// Build a validated plan tree rooted at the supplied plan node.
21    pub fn new(root: Plan) -> Result<Self, VisualizeError> {
22        let mut node_count = 0;
23        let stats = validate_node(&root, 0, "Plan", &mut node_count)?;
24        Ok(Self { root, stats })
25    }
26
27    /// Return the validated root plan node.
28    pub fn root(&self) -> &Plan {
29        &self.root
30    }
31
32    /// Return aggregate tree statistics gathered during validation.
33    pub fn stats(&self) -> TreeStats {
34        self.stats
35    }
36
37    /// Consume the wrapper and return the validated root node.
38    pub fn into_root(self) -> Plan {
39        self.root
40    }
41}
42
43fn validate_node(
44    plan: &Plan,
45    depth: usize,
46    path: &str,
47    node_count: &mut usize,
48) -> Result<TreeStats, VisualizeError> {
49    if depth > MAX_PLAN_DEPTH {
50        return Err(VisualizeError::InvalidPlan(format!(
51            "{path} exceeds maximum supported plan depth of {MAX_PLAN_DEPTH}"
52        )));
53    }
54    if plan.identity.node_type.trim().is_empty() {
55        return Err(VisualizeError::InvalidPlan(format!(
56            "{path}.Node Type must be populated"
57        )));
58    }
59    *node_count += 1;
60    if *node_count > MAX_PLAN_NODES {
61        return Err(VisualizeError::InvalidPlan(format!(
62            "plan exceeds maximum supported node count of {MAX_PLAN_NODES}"
63        )));
64    }
65    validate_non_negative(plan.estimates.startup_cost, &format!("{path}.Startup Cost"))?;
66    validate_non_negative(plan.estimates.total_cost, &format!("{path}.Total Cost"))?;
67    validate_non_negative(
68        plan.actuals.actual_startup_time,
69        &format!("{path}.Actual Startup Time"),
70    )?;
71    validate_non_negative(
72        plan.actuals.actual_total_time,
73        &format!("{path}.Actual Total Time"),
74    )?;
75    validate_non_negative(
76        plan.io_timing.io_read_time,
77        &format!("{path}.I/O Read Time"),
78    )?;
79    validate_non_negative(
80        plan.io_timing.io_write_time,
81        &format!("{path}.I/O Write Time"),
82    )?;
83
84    let mut stats = TreeStats {
85        node_count: 1,
86        max_depth: depth,
87    };
88
89    for (index, child) in plan.plans.iter().enumerate() {
90        let child_stats = validate_node(
91            child,
92            depth + 1,
93            &format!("{path}.Plans[{index}]"),
94            node_count,
95        )?;
96        stats.node_count += child_stats.node_count;
97        stats.max_depth = stats.max_depth.max(child_stats.max_depth);
98    }
99
100    Ok(stats)
101}
102
103fn validate_non_negative(value: f64, path: &str) -> Result<(), VisualizeError> {
104    if !value.is_finite() {
105        return Err(VisualizeError::InvalidPlan(format!(
106            "{path} must be finite"
107        )));
108    }
109    if value < 0.0 {
110        return Err(VisualizeError::InvalidPlan(format!(
111            "{path} must be non-negative"
112        )));
113    }
114    Ok(())
115}