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        self.result_schema_with_control(&uqa_core::memory::ProductionControl::uncontrolled())
138    }
139
140    pub fn result_schema_with_control(
141        &self,
142        control: &uqa_core::memory::ProductionControl<'_>,
143    ) -> Result<RowSchema, SQLError> {
144        let mut ty = ColumnType::Text;
145        for option in &self.options {
146            control.check()?;
147            if option.name == "format" {
148                ty =
149                    match &option.value {
150                        Some(
151                            ExplainOptionValue::String(value) | ExplainOptionValue::Float(value),
152                        ) if value == "xml" => ColumnType::Xml,
153                        Some(
154                            ExplainOptionValue::String(value) | ExplainOptionValue::Float(value),
155                        ) if value == "json" => ColumnType::Json,
156                        Some(_) => ColumnType::Text,
157                        None => {
158                            return Err(diagnostic(
159                                "42601",
160                                control
161                                    .format(format_args!("{} requires a parameter", option.name))?
162                                    .into_parts()
163                                    .0,
164                            ))
165                        }
166                    };
167            }
168        }
169        RowSchema::with_column_metadata_with_control(
170            None,
171            [("QUERY PLAN", Some(&ty), None)],
172            control,
173        )
174    }
175
176    pub fn interpret(&self) -> Result<ExplainSettings, SQLError> {
177        let mut settings = ExplainSettings::default();
178        let mut timing = None;
179        let mut buffers = None;
180        let mut summary = None;
181        for option in &self.options {
182            match option.name.as_str() {
183                "analyze" => settings.analyze = option.boolean()?,
184                "verbose" => settings.verbose = option.boolean()?,
185                "costs" => settings.costs = option.boolean()?,
186                "buffers" => buffers = Some(option.boolean()?),
187                "wal" => settings.wal = option.boolean()?,
188                "settings" => settings.settings = option.boolean()?,
189                "generic_plan" => settings.generic_plan = option.boolean()?,
190                "timing" => timing = Some(option.boolean()?),
191                "summary" => summary = Some(option.boolean()?),
192                "memory" => settings.memory = option.boolean()?,
193                "serialize" => {
194                    settings.serialize = if option.value.is_none() {
195                        ExplainSerialization::Text
196                    } else {
197                        match option.text()?.as_ref() {
198                            "off" | "none" => ExplainSerialization::None,
199                            "text" => ExplainSerialization::Text,
200                            "binary" => ExplainSerialization::Binary,
201                            value => return Err(option.unrecognized_value(value)),
202                        }
203                    };
204                }
205                "format" => {
206                    settings.format = match option.text()?.as_ref() {
207                        "text" => ExplainFormat::Text,
208                        "xml" => ExplainFormat::Xml,
209                        "json" => ExplainFormat::Json,
210                        "yaml" => ExplainFormat::Yaml,
211                        value => return Err(option.unrecognized_value(value)),
212                    };
213                }
214                name => {
215                    return Err(diagnostic(
216                        "42601",
217                        format!("unrecognized EXPLAIN option \"{name}\""),
218                    ));
219                }
220            }
221        }
222        settings.timing = timing.unwrap_or(settings.analyze);
223        settings.buffers = buffers.unwrap_or(settings.analyze);
224        settings.summary = summary.unwrap_or(settings.analyze);
225        for (enabled, name) in [
226            (settings.wal, "WAL"),
227            (settings.timing, "TIMING"),
228            (
229                settings.serialize != ExplainSerialization::None,
230                "SERIALIZE",
231            ),
232        ] {
233            if enabled && !settings.analyze {
234                return Err(diagnostic(
235                    "22023",
236                    format!("EXPLAIN option {name} requires ANALYZE"),
237                ));
238            }
239        }
240        if settings.generic_plan && settings.analyze {
241            return Err(diagnostic(
242                "22023",
243                "EXPLAIN options ANALYZE and GENERIC_PLAN cannot be used together".into(),
244            ));
245        }
246        Ok(settings)
247    }
248}
249
250impl ExplainOption {
251    fn text(&self) -> Result<Cow<'_, str>, SQLError> {
252        Ok(match &self.value {
253            Some(ExplainOptionValue::String(value) | ExplainOptionValue::Float(value)) => {
254                value.as_str().into()
255            }
256            Some(ExplainOptionValue::Integer(value)) => value.to_string().into(),
257            Some(ExplainOptionValue::Boolean(value)) => {
258                if *value { "true" } else { "false" }.into()
259            }
260            None => {
261                return Err(diagnostic(
262                    "42601",
263                    format!("{} requires a parameter", self.name),
264                ))
265            }
266        })
267    }
268
269    fn boolean(&self) -> Result<bool, SQLError> {
270        match &self.value {
271            None => return Ok(true),
272            Some(ExplainOptionValue::Boolean(value)) => return Ok(*value),
273            Some(ExplainOptionValue::Integer(0)) => return Ok(false),
274            Some(ExplainOptionValue::Integer(1)) => return Ok(true),
275            Some(ExplainOptionValue::String(value)) => {
276                if value.eq_ignore_ascii_case("true") || value.eq_ignore_ascii_case("on") {
277                    return Ok(true);
278                }
279                if value.eq_ignore_ascii_case("false") || value.eq_ignore_ascii_case("off") {
280                    return Ok(false);
281                }
282            }
283            _ => {}
284        }
285        Err(diagnostic(
286            "42601",
287            format!("{} requires a Boolean value", self.name),
288        ))
289    }
290
291    fn unrecognized_value(&self, value: &str) -> SQLError {
292        diagnostic(
293            "22023",
294            format!(
295                "unrecognized value for EXPLAIN option \"{}\": \"{value}\"",
296                self.name
297            ),
298        )
299    }
300}
301
302fn diagnostic(sqlstate: &str, message: String) -> SQLError {
303    SQLError::Routine {
304        sqlstate: sqlstate.into(),
305        message,
306    }
307}
308
309#[cfg(test)]
310mod tests;