Skip to main content

rustcmdpev_core/
parser.rs

1use crate::structure::data::explain::Explain;
2use crate::structure::raw::{schema_profile_from_hint, PostgresSchemaProfile, RawExplain, RawPlan};
3use crate::structure::tree::PlanTree;
4use crate::VisualizeError;
5
6/// Parser-level configuration.
7///
8/// Currently the only knob is the optional `postgres_version_hint`, which lets
9/// callers steer schema-profile selection when the JSON payload itself does
10/// not carry a `PostgreSQL Version` field. The hint is parsed for a leading
11/// integer (e.g. `"12"`, `"PostgreSQL 13.4"`) and ignored if no major version
12/// can be extracted.
13#[derive(Debug, Clone, Default)]
14pub struct ParseOptions {
15    pub postgres_version_hint: Option<String>,
16}
17
18impl ParseOptions {
19    pub fn new() -> Self {
20        Self::default()
21    }
22
23    pub fn with_postgres_version_hint(mut self, hint: impl Into<String>) -> Self {
24        self.postgres_version_hint = Some(hint.into());
25        self
26    }
27
28    pub fn schema_profile_hint(&self) -> Option<PostgresSchemaProfile> {
29        self.postgres_version_hint
30            .as_deref()
31            .and_then(schema_profile_from_hint)
32    }
33}
34
35/// Parse the top-level PostgreSQL EXPLAIN JSON array into raw serde models.
36pub fn parse_raw_explains(input: &str) -> Result<Vec<RawExplain>, VisualizeError> {
37    serde_json::from_str(input).map_err(VisualizeError::InvalidJson)
38}
39
40/// Convert a raw explain document into the strongly typed domain model.
41pub fn build_domain_explain(raw: RawExplain) -> Result<Explain, VisualizeError> {
42    raw.into_domain()
43}
44
45/// Convert a raw explain into the domain model, respecting an explicit version
46/// hint when the JSON metadata does not name a PostgreSQL version.
47pub fn build_domain_explain_with(
48    raw: RawExplain,
49    options: &ParseOptions,
50) -> Result<Explain, VisualizeError> {
51    let mut effective_profile = raw.schema_profile();
52    if effective_profile == PostgresSchemaProfile::Unknown {
53        if let Some(hinted) = options.schema_profile_hint() {
54            effective_profile = hinted;
55        }
56    }
57
58    let RawExplain { metadata, plan } = raw;
59    let plan = plan
60        .ok_or(VisualizeError::MissingPlan)?
61        .into_domain(effective_profile)?;
62
63    let postgres_version = metadata
64        .postgres_version
65        .clone()
66        .or_else(|| options.postgres_version_hint.clone());
67
68    Ok(Explain {
69        plan,
70        postgres_version,
71        planning_time: metadata.planning_time,
72        execution_time: metadata.execution_time,
73        ..Default::default()
74    })
75}
76
77/// Validate the domain plan as an explicit tree with structural invariants.
78pub fn validate_plan_tree(explain: Explain) -> Result<Explain, VisualizeError> {
79    let tree = PlanTree::new(explain.plan.clone())?;
80    Ok(Explain {
81        plan: tree.into_root(),
82        ..explain
83    })
84}
85
86/// Run the full parser pipeline from raw JSON through validated domain explain.
87pub fn parse_explain_document(input: &str) -> Result<Explain, VisualizeError> {
88    parse_explain_document_with(input, &ParseOptions::default())
89}
90
91/// Like [`parse_explain_document`] but accepting a `ParseOptions` value.
92pub fn parse_explain_document_with(
93    input: &str,
94    options: &ParseOptions,
95) -> Result<Explain, VisualizeError> {
96    let raw_explain = parse_raw_explains(input)?
97        .into_iter()
98        .next()
99        .ok_or(VisualizeError::EmptyExplainArray)?;
100    let mut explain = build_domain_explain_with(raw_explain.clone(), options)?;
101
102    if raw_explain.schema_profile() == PostgresSchemaProfile::Unknown
103        && options.schema_profile_hint().is_none()
104    {
105        explain.postgres_version = None;
106    }
107
108    validate_plan_tree(explain)
109}
110
111// Avoid an "unused" warning if no caller of `RawPlan` needs it from here yet.
112#[allow(dead_code)]
113fn _ensure_raw_plan_visible(_: &RawPlan) {}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    const PG12_PAYLOAD_NO_VERSION: &str = r#"[{"Plan":{"Node Type":"Seq Scan","Total Cost":1.0,"Actual Total Time":0.5,"Actual Rows":1,"Actual Loops":1,"IO Read Time":1.5}}]"#;
120
121    #[test]
122    fn version_hint_picks_legacy_io_timing_for_pg12() {
123        let options = ParseOptions::new().with_postgres_version_hint("12");
124        let explain = parse_explain_document_with(PG12_PAYLOAD_NO_VERSION, &options)
125            .expect("parse with hint");
126        assert!((explain.plan.io_timing.io_read_time - 1.5).abs() < 1e-9);
127        assert_eq!(explain.postgres_version.as_deref(), Some("12"));
128    }
129
130    #[test]
131    fn version_hint_picks_modern_io_timing_for_pg13_plus() {
132        let options = ParseOptions::new().with_postgres_version_hint("PostgreSQL 16.1");
133        let explain = parse_explain_document_with(PG12_PAYLOAD_NO_VERSION, &options)
134            .expect("parse with hint");
135        // Legacy `IO Read Time` is preserved on modern profile only when canonical is missing.
136        assert!((explain.plan.io_timing.io_read_time - 1.5).abs() < 1e-9);
137        assert_eq!(explain.postgres_version.as_deref(), Some("PostgreSQL 16.1"));
138    }
139
140    #[test]
141    fn metadata_version_in_payload_wins_over_hint() {
142        let payload = r#"[{"PostgreSQL Version":"PostgreSQL 12","Plan":{"Node Type":"Seq Scan","Total Cost":1.0,"Actual Total Time":0.5,"Actual Rows":1,"Actual Loops":1}}]"#;
143        let options = ParseOptions::new().with_postgres_version_hint("PostgreSQL 16.1");
144        let explain = parse_explain_document_with(payload, &options).expect("parse");
145        assert_eq!(explain.postgres_version.as_deref(), Some("PostgreSQL 12"));
146    }
147
148    #[test]
149    fn invalid_hint_is_ignored_and_does_not_error() {
150        let options = ParseOptions::new().with_postgres_version_hint("not-a-version");
151        let explain = parse_explain_document_with(PG12_PAYLOAD_NO_VERSION, &options)
152            .expect("parse with bad hint");
153        assert!(explain.postgres_version.is_none());
154    }
155
156    #[test]
157    fn no_hint_preserves_existing_unknown_profile_behavior() {
158        let explain = parse_explain_document(PG12_PAYLOAD_NO_VERSION).expect("parse no hint");
159        assert!(explain.postgres_version.is_none());
160    }
161}