Skip to main content

uqa_sql/
explain.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Ordered EXPLAIN syntax, result descriptions and execution option interpretation.
8
9use serde::{Deserialize, Serialize};
10use std::borrow::Cow;
11
12use crate::{ColumnType, RowSchema, SQLError};
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub enum ExplainOptionValue {
16    Boolean(bool),
17    Integer(i32),
18    Float(String),
19    String(String),
20}
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct ExplainOption {
24    pub name: String,
25    pub value: Option<ExplainOptionValue>,
26}
27
28/// Retain every occurrence in parser order. Describing a result reads FORMAT; executing the command interprets all options before planning its body.
29#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(from = "StoredOptions")]
31pub struct ExplainOptions {
32    pub options: Vec<ExplainOption>,
33}
34
35/// Older stored statements used these three fields. Deserialize them into the same ordered representation; new serialization has only the options list.
36#[derive(Deserialize)]
37struct StoredOptions {
38    options: Option<Vec<ExplainOption>>,
39    analyze: Option<bool>,
40    verbose: Option<bool>,
41    format: Option<String>,
42}
43
44impl From<StoredOptions> for ExplainOptions {
45    fn from(stored: StoredOptions) -> Self {
46        let options = stored.options.unwrap_or_else(|| {
47            let mut options = Vec::new();
48            for (name, value) in [("analyze", stored.analyze), ("verbose", stored.verbose)] {
49                if let Some(value) = value {
50                    options.push(ExplainOption {
51                        name: name.into(),
52                        value: Some(ExplainOptionValue::Boolean(value)),
53                    });
54                }
55            }
56            if let Some(format) = stored.format {
57                options.push(ExplainOption {
58                    name: "format".into(),
59                    value: Some(ExplainOptionValue::String(format)),
60                });
61            }
62            options
63        });
64        Self { options }
65    }
66}
67
68#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
69pub enum ExplainFormat {
70    #[default]
71    Text,
72    Xml,
73    Json,
74    Yaml,
75}
76
77#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
78pub enum ExplainSerialization {
79    #[default]
80    None,
81    Text,
82    Binary,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
86#[expect(
87    clippy::struct_excessive_bools,
88    reason = "EXPLAIN options are independent SQL switches"
89)]
90pub struct ExplainSettings {
91    pub analyze: bool,
92    pub verbose: bool,
93    pub costs: bool,
94    pub buffers: bool,
95    pub wal: bool,
96    pub settings: bool,
97    pub generic_plan: bool,
98    pub timing: bool,
99    pub summary: bool,
100    pub memory: bool,
101    pub serialize: ExplainSerialization,
102    pub format: ExplainFormat,
103}
104
105impl Default for ExplainSettings {
106    fn default() -> Self {
107        Self {
108            analyze: false,
109            verbose: false,
110            costs: true,
111            buffers: false,
112            wal: false,
113            settings: false,
114            generic_plan: false,
115            timing: false,
116            summary: false,
117            memory: false,
118            serialize: ExplainSerialization::None,
119            format: ExplainFormat::Text,
120        }
121    }
122}
123
124impl ExplainOptions {
125    /// Ordinary analysis without an external parameter hook reads only `GENERIC_PLAN` before the body. All other option diagnostics retain their execution order.
126    pub fn infers_unbound_parameters(&self) -> Result<bool, SQLError> {
127        let mut generic = false;
128        for option in &self.options {
129            if option.name == "generic_plan" {
130                generic = option.boolean()?;
131            }
132        }
133        Ok(generic)
134    }
135
136    pub fn result_schema(&self) -> Result<RowSchema, SQLError> {
137        let mut ty = ColumnType::Text;
138        for option in &self.options {
139            if option.name == "format" {
140                ty = match option.text()?.as_ref() {
141                    "xml" => ColumnType::Xml,
142                    "json" => ColumnType::Json,
143                    _ => ColumnType::Text,
144                };
145            }
146        }
147        Ok(RowSchema::with_types(
148            vec!["QUERY PLAN".into()],
149            vec![Some(ty)],
150        ))
151    }
152
153    pub fn interpret(&self) -> Result<ExplainSettings, SQLError> {
154        let mut settings = ExplainSettings::default();
155        let mut timing = None;
156        let mut buffers = None;
157        let mut summary = None;
158        for option in &self.options {
159            match option.name.as_str() {
160                "analyze" => settings.analyze = option.boolean()?,
161                "verbose" => settings.verbose = option.boolean()?,
162                "costs" => settings.costs = option.boolean()?,
163                "buffers" => buffers = Some(option.boolean()?),
164                "wal" => settings.wal = option.boolean()?,
165                "settings" => settings.settings = option.boolean()?,
166                "generic_plan" => settings.generic_plan = option.boolean()?,
167                "timing" => timing = Some(option.boolean()?),
168                "summary" => summary = Some(option.boolean()?),
169                "memory" => settings.memory = option.boolean()?,
170                "serialize" => {
171                    settings.serialize = if option.value.is_none() {
172                        ExplainSerialization::Text
173                    } else {
174                        match option.text()?.as_ref() {
175                            "off" | "none" => ExplainSerialization::None,
176                            "text" => ExplainSerialization::Text,
177                            "binary" => ExplainSerialization::Binary,
178                            value => return Err(option.unrecognized_value(value)),
179                        }
180                    };
181                }
182                "format" => {
183                    settings.format = match option.text()?.as_ref() {
184                        "text" => ExplainFormat::Text,
185                        "xml" => ExplainFormat::Xml,
186                        "json" => ExplainFormat::Json,
187                        "yaml" => ExplainFormat::Yaml,
188                        value => return Err(option.unrecognized_value(value)),
189                    };
190                }
191                name => {
192                    return Err(diagnostic(
193                        "42601",
194                        format!("unrecognized EXPLAIN option \"{name}\""),
195                    ));
196                }
197            }
198        }
199        settings.timing = timing.unwrap_or(settings.analyze);
200        settings.buffers = buffers.unwrap_or(settings.analyze);
201        settings.summary = summary.unwrap_or(settings.analyze);
202        for (enabled, name) in [
203            (settings.wal, "WAL"),
204            (settings.timing, "TIMING"),
205            (
206                settings.serialize != ExplainSerialization::None,
207                "SERIALIZE",
208            ),
209        ] {
210            if enabled && !settings.analyze {
211                return Err(diagnostic(
212                    "22023",
213                    format!("EXPLAIN option {name} requires ANALYZE"),
214                ));
215            }
216        }
217        if settings.generic_plan && settings.analyze {
218            return Err(diagnostic(
219                "22023",
220                "EXPLAIN options ANALYZE and GENERIC_PLAN cannot be used together".into(),
221            ));
222        }
223        Ok(settings)
224    }
225}
226
227impl ExplainOption {
228    fn text(&self) -> Result<Cow<'_, str>, SQLError> {
229        Ok(match &self.value {
230            Some(ExplainOptionValue::String(value) | ExplainOptionValue::Float(value)) => {
231                value.as_str().into()
232            }
233            Some(ExplainOptionValue::Integer(value)) => value.to_string().into(),
234            Some(ExplainOptionValue::Boolean(value)) => {
235                if *value { "true" } else { "false" }.into()
236            }
237            None => {
238                return Err(diagnostic(
239                    "42601",
240                    format!("{} requires a parameter", self.name),
241                ))
242            }
243        })
244    }
245
246    fn boolean(&self) -> Result<bool, SQLError> {
247        match &self.value {
248            None => return Ok(true),
249            Some(ExplainOptionValue::Boolean(value)) => return Ok(*value),
250            Some(ExplainOptionValue::Integer(0)) => return Ok(false),
251            Some(ExplainOptionValue::Integer(1)) => return Ok(true),
252            Some(ExplainOptionValue::String(value)) => {
253                if value.eq_ignore_ascii_case("true") || value.eq_ignore_ascii_case("on") {
254                    return Ok(true);
255                }
256                if value.eq_ignore_ascii_case("false") || value.eq_ignore_ascii_case("off") {
257                    return Ok(false);
258                }
259            }
260            _ => {}
261        }
262        Err(diagnostic(
263            "42601",
264            format!("{} requires a Boolean value", self.name),
265        ))
266    }
267
268    fn unrecognized_value(&self, value: &str) -> SQLError {
269        diagnostic(
270            "22023",
271            format!(
272                "unrecognized value for EXPLAIN option \"{}\": \"{value}\"",
273                self.name
274            ),
275        )
276    }
277}
278
279fn diagnostic(sqlstate: &str, message: String) -> SQLError {
280    SQLError::Routine {
281        sqlstate: sqlstate.into(),
282        message,
283    }
284}
285
286#[cfg(test)]
287mod tests;