Skip to main content

datafusion_common/
format.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::fmt::{self, Display};
6use std::str::FromStr;
7
8use arrow::compute::CastOptions;
9use arrow::util::display::{DurationFormat, FormatOptions};
10
11use crate::config::{ConfigField, Visit};
12use crate::error::{DataFusionError, Result};
13#[cfg(feature = "sql")]
14use sqlparser::ast::{Expr, UtilityOption, Value, ValueWithSpan};
15
16/// The default [`FormatOptions`] to use within DataFusion
17/// Also see [`crate::config::FormatOptions`]
18pub const DEFAULT_FORMAT_OPTIONS: FormatOptions<'static> =
19    FormatOptions::new().with_duration_format(DurationFormat::Pretty);
20
21/// The default [`CastOptions`] to use within DataFusion
22pub const DEFAULT_CAST_OPTIONS: CastOptions<'static> = CastOptions {
23    safe: false,
24    format_options: DEFAULT_FORMAT_OPTIONS,
25};
26
27/// Output formats for controlling for Explain plans
28#[derive(Debug, Clone, PartialEq, Eq, Hash)]
29pub enum ExplainFormat {
30    /// Indent mode
31    ///
32    /// Example:
33    /// ```text
34    /// > explain format indent select x from values (1) t(x);
35    /// +---------------+-----------------------------------------------------+
36    /// | plan_type     | plan                                                |
37    /// +---------------+-----------------------------------------------------+
38    /// | logical_plan  | SubqueryAlias: t                                    |
39    /// |               |   Projection: column1 AS x                          |
40    /// |               |     Values: (Int64(1))                              |
41    /// | physical_plan | ProjectionExec: expr=[column1@0 as x]               |
42    /// |               |   DataSourceExec: partitions=1, partition_sizes=[1] |
43    /// |               |                                                     |
44    /// +---------------+-----------------------------------------------------+
45    /// ```
46    Indent,
47    /// Tree mode
48    ///
49    /// Example:
50    /// ```text
51    /// > explain format tree select x from values (1) t(x);
52    /// +---------------+-------------------------------+
53    /// | plan_type     | plan                          |
54    /// +---------------+-------------------------------+
55    /// | physical_plan | ┌───────────────────────────┐ |
56    /// |               | │       ProjectionExec      │ |
57    /// |               | │    --------------------   │ |
58    /// |               | │        x: column1@0       │ |
59    /// |               | └─────────────┬─────────────┘ |
60    /// |               | ┌─────────────┴─────────────┐ |
61    /// |               | │       DataSourceExec      │ |
62    /// |               | │    --------------------   │ |
63    /// |               | │         bytes: 128        │ |
64    /// |               | │       format: memory      │ |
65    /// |               | │          rows: 1          │ |
66    /// |               | └───────────────────────────┘ |
67    /// |               |                               |
68    /// +---------------+-------------------------------+
69    /// ```
70    Tree,
71    /// Postgres Json mode
72    ///
73    /// A displayable structure that produces plan in postgresql JSON format.
74    ///
75    /// Users can use this format to visualize the plan in existing plan
76    /// visualization tools, for example [dalibo](https://explain.dalibo.com/)
77    ///
78    /// Example:
79    /// ```text
80    /// > explain format pgjson select x from values (1) t(x);
81    /// +--------------+--------------------------------------+
82    /// | plan_type    | plan                                 |
83    /// +--------------+--------------------------------------+
84    /// | logical_plan | [                                    |
85    /// |              |   {                                  |
86    /// |              |     "Plan": {                        |
87    /// |              |       "Alias": "t",                  |
88    /// |              |       "Node Type": "Subquery",       |
89    /// |              |       "Output": [                    |
90    /// |              |         "x"                          |
91    /// |              |       ],                             |
92    /// |              |       "Plans": [                     |
93    /// |              |         {                            |
94    /// |              |           "Expressions": [           |
95    /// |              |             "column1 AS x"           |
96    /// |              |           ],                         |
97    /// |              |           "Node Type": "Projection", |
98    /// |              |           "Output": [                |
99    /// |              |             "x"                      |
100    /// |              |           ],                         |
101    /// |              |           "Plans": [                 |
102    /// |              |             {                        |
103    /// |              |               "Node Type": "Values", |
104    /// |              |               "Output": [            |
105    /// |              |                 "column1"            |
106    /// |              |               ],                     |
107    /// |              |               "Plans": [],           |
108    /// |              |               "Values": "(Int64(1))" |
109    /// |              |             }                        |
110    /// |              |           ]                          |
111    /// |              |         }                            |
112    /// |              |       ]                              |
113    /// |              |     }                                |
114    /// |              |   }                                  |
115    /// |              | ]                                    |
116    /// +--------------+--------------------------------------+
117    /// ```
118    PostgresJSON,
119    /// Graphviz mode
120    ///
121    /// Example:
122    /// ```text
123    /// > explain format graphviz select x from values (1) t(x);
124    /// +--------------+------------------------------------------------------------------------+
125    /// | plan_type    | plan                                                                   |
126    /// +--------------+------------------------------------------------------------------------+
127    /// | logical_plan |                                                                        |
128    /// |              | // Begin DataFusion GraphViz Plan,                                     |
129    /// |              | // display it online here: https://dreampuf.github.io/GraphvizOnline   |
130    /// |              |                                                                        |
131    /// |              | digraph {                                                              |
132    /// |              |   subgraph cluster_1                                                   |
133    /// |              |   {                                                                    |
134    /// |              |     graph[label="LogicalPlan"]                                         |
135    /// |              |     2[shape=box label="SubqueryAlias: t"]                              |
136    /// |              |     3[shape=box label="Projection: column1 AS x"]                      |
137    /// |              |     2 -> 3 [arrowhead=none, arrowtail=normal, dir=back]                |
138    /// |              |     4[shape=box label="Values: (Int64(1))"]                            |
139    /// |              |     3 -> 4 [arrowhead=none, arrowtail=normal, dir=back]                |
140    /// |              |   }                                                                    |
141    /// |              |   subgraph cluster_5                                                   |
142    /// |              |   {                                                                    |
143    /// |              |     graph[label="Detailed LogicalPlan"]                                |
144    /// |              |     6[shape=box label="SubqueryAlias: t\nSchema: [x:Int64;N]"]         |
145    /// |              |     7[shape=box label="Projection: column1 AS x\nSchema: [x:Int64;N]"] |
146    /// |              |     6 -> 7 [arrowhead=none, arrowtail=normal, dir=back]                |
147    /// |              |     8[shape=box label="Values: (Int64(1))\nSchema: [column1:Int64;N]"] |
148    /// |              |     7 -> 8 [arrowhead=none, arrowtail=normal, dir=back]                |
149    /// |              |   }                                                                    |
150    /// |              | }                                                                      |
151    /// |              | // End DataFusion GraphViz Plan                                        |
152    /// |              |                                                                        |
153    /// +--------------+------------------------------------------------------------------------+
154    /// ```
155    Graphviz,
156}
157
158/// Implement  parsing strings to `ExplainFormat`
159impl FromStr for ExplainFormat {
160    type Err = DataFusionError;
161
162    fn from_str(format: &str) -> Result<Self, Self::Err> {
163        match format.to_lowercase().as_str() {
164            "indent" => Ok(ExplainFormat::Indent),
165            "tree" => Ok(ExplainFormat::Tree),
166            "pgjson" => Ok(ExplainFormat::PostgresJSON),
167            "graphviz" => Ok(ExplainFormat::Graphviz),
168            _ => Err(DataFusionError::Configuration(format!(
169                "Invalid explain format. Expected 'indent', 'tree', 'pgjson' or 'graphviz'. Got '{format}'"
170            ))),
171        }
172    }
173}
174
175impl Display for ExplainFormat {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        let s = match self {
178            ExplainFormat::Indent => "indent",
179            ExplainFormat::Tree => "tree",
180            ExplainFormat::PostgresJSON => "pgjson",
181            ExplainFormat::Graphviz => "graphviz",
182        };
183        write!(f, "{s}")
184    }
185}
186
187impl ConfigField for ExplainFormat {
188    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
189        v.some(key, self, description)
190    }
191
192    fn set(&mut self, _: &str, value: &str) -> Result<()> {
193        *self = ExplainFormat::from_str(value)?;
194        Ok(())
195    }
196}
197
198/// Categorizes metrics so the display layer can choose the desired verbosity.
199///
200/// The `datafusion.explain.analyze_level` configuration controls which
201/// type is shown:
202/// - `"dev"` (the default): all metrics are shown.
203/// - `"summary"`: only metrics tagged as `Summary` are shown.
204///
205/// This is orthogonal to [`MetricCategory`], which filters by *what kind*
206/// of value a metric represents (rows / bytes / timing).
207///
208/// # Difference from `EXPLAIN ANALYZE VERBOSE`
209///
210/// The `VERBOSE` keyword controls whether per-partition metrics are shown
211/// (when specified) or aggregated metrics are displayed (when omitted).
212/// In contrast, `MetricType` determines which *levels* of metrics are
213/// displayed.
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
215pub enum MetricType {
216    /// Common metrics for high-level insights (answering which operator is slow)
217    Summary,
218    /// For deep operator-level introspection for developers
219    Dev,
220}
221
222impl MetricType {
223    /// Returns the set of metric types that should be shown for this level.
224    ///
225    /// `Dev` is a superset of `Summary`: when the user selects
226    /// `analyze_level = 'dev'`, both `Summary` and `Dev` metrics are shown.
227    pub fn included_types(self) -> Vec<MetricType> {
228        match self {
229            MetricType::Summary => vec![MetricType::Summary],
230            MetricType::Dev => vec![MetricType::Summary, MetricType::Dev],
231        }
232    }
233}
234
235impl FromStr for MetricType {
236    type Err = DataFusionError;
237
238    fn from_str(s: &str) -> Result<Self, Self::Err> {
239        match s.trim().to_lowercase().as_str() {
240            "summary" => Ok(Self::Summary),
241            "dev" => Ok(Self::Dev),
242            other => Err(DataFusionError::Configuration(format!(
243                "Invalid explain analyze level. Expected 'summary' or 'dev'. Got '{other}'"
244            ))),
245        }
246    }
247}
248
249impl Display for MetricType {
250    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251        match self {
252            Self::Summary => write!(f, "summary"),
253            Self::Dev => write!(f, "dev"),
254        }
255    }
256}
257
258impl ConfigField for MetricType {
259    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
260        v.some(key, self, description)
261    }
262
263    fn set(&mut self, _: &str, value: &str) -> Result<()> {
264        *self = MetricType::from_str(value)?;
265        Ok(())
266    }
267}
268
269/// Classifies a metric by what it measures.
270///
271/// This is orthogonal to [`MetricType`] (Summary / Dev), which controls
272/// *verbosity*. `MetricCategory` controls *what kind of value* is shown,
273/// so that `EXPLAIN ANALYZE` output can be narrowed to only the categories
274/// that are useful in a given context.
275///
276/// In particular this is useful for testing since metrics differ in their stability across runs:
277/// - [`Rows`](Self::Rows) and [`Bytes`](Self::Bytes) depend only on the plan
278///   and the data, so they are mostly deterministic across runs (given the same
279///   input). Variations can existing e.g. because of non-deterministic ordering
280///   of evaluation between threads.
281///   Running with a single target partition often makes these metrics stable enough to assert on in tests.
282/// - [`Timing`](Self::Timing) depends on hardware, system load, scheduling,
283///   etc., so it varies from run to run even on the same machine.
284///
285/// [`MetricCategory`] is especially useful in sqllogictest (`.slt`) files:
286/// setting `datafusion.explain.analyze_categories = 'rows'` lets a test
287/// assert on row-count metrics without sprinkling `<slt:ignore>` over every
288/// timing value.
289///
290/// Metrics that do not declare a category (the default for custom
291/// `Count` / `Gauge` metrics) are treated as
292/// [`Uncategorized`](Self::Uncategorized) for filtering purposes.
293#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
294pub enum MetricCategory {
295    /// Row counts and related dimensionless counters: `output_rows`,
296    /// `spilled_rows`, `output_batches`, pruning metrics, ratios, etc.
297    ///
298    /// Mostly deterministic given the same plan and data.
299    Rows,
300    /// Byte measurements: `output_bytes`, `spilled_bytes`,
301    /// `current_memory_usage`, `bytes_scanned`, etc.
302    ///
303    /// Mostly deterministic given the same plan and data.
304    Bytes,
305    /// Wall-clock durations and timestamps: `elapsed_compute`,
306    /// operator-defined `Time` metrics, `start_timestamp` /
307    /// `end_timestamp`, etc.
308    ///
309    /// **Non-deterministic** — varies across runs even on the same hardware.
310    Timing,
311    /// Catch-all for metrics that do not fit into [`Rows`](Self::Rows),
312    /// [`Bytes`](Self::Bytes), or [`Timing`](Self::Timing).
313    ///
314    /// Custom `Count` / `Gauge` metrics that are not explicitly assigned
315    /// a category are treated as `Uncategorized` for filtering purposes.
316    ///
317    /// This variant lets users explicitly include or exclude these
318    /// metrics, e.g.:
319    /// ```sql
320    /// SET datafusion.explain.analyze_categories = 'rows, bytes, uncategorized';
321    /// ```
322    Uncategorized,
323}
324
325impl FromStr for MetricCategory {
326    type Err = DataFusionError;
327
328    fn from_str(s: &str) -> Result<Self, Self::Err> {
329        match s.trim().to_lowercase().as_str() {
330            "rows" => Ok(Self::Rows),
331            "bytes" => Ok(Self::Bytes),
332            "timing" => Ok(Self::Timing),
333            "uncategorized" => Ok(Self::Uncategorized),
334            other => Err(DataFusionError::Configuration(format!(
335                "Invalid metric category '{other}'. \
336                 Expected 'rows', 'bytes', 'timing', or 'uncategorized'."
337            ))),
338        }
339    }
340}
341
342impl Display for MetricCategory {
343    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344        match self {
345            Self::Rows => write!(f, "rows"),
346            Self::Bytes => write!(f, "bytes"),
347            Self::Timing => write!(f, "timing"),
348            Self::Uncategorized => write!(f, "uncategorized"),
349        }
350    }
351}
352
353/// Controls which [`MetricCategory`] values are shown in `EXPLAIN ANALYZE`.
354///
355/// Set via `SET datafusion.explain.analyze_categories = '...'`.
356///
357/// See [`MetricCategory`] for the determinism properties that motivate
358/// this filter.
359#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
360pub enum ExplainAnalyzeCategories {
361    /// Show all metrics regardless of category (the default).
362    #[default]
363    All,
364    /// Show only metrics whose category is in the list.
365    /// Metrics with no declared category are treated as
366    /// [`Uncategorized`](MetricCategory::Uncategorized) for filtering.
367    ///
368    /// An **empty** vec means "plan only" — suppress all metrics.
369    Only(Vec<MetricCategory>),
370}
371
372impl FromStr for ExplainAnalyzeCategories {
373    type Err = DataFusionError;
374
375    fn from_str(s: &str) -> Result<Self, Self::Err> {
376        let s = s.trim().to_lowercase();
377        match s.as_str() {
378            "all" => Ok(Self::All),
379            "none" => Ok(Self::Only(vec![])),
380            other => {
381                let mut cats = Vec::new();
382                for part in other.split(',') {
383                    cats.push(part.trim().parse::<MetricCategory>()?);
384                }
385                cats.dedup();
386                Ok(Self::Only(cats))
387            }
388        }
389    }
390}
391
392impl Display for ExplainAnalyzeCategories {
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        match self {
395            Self::All => write!(f, "all"),
396            Self::Only(cats) if cats.is_empty() => write!(f, "none"),
397            Self::Only(cats) => {
398                let mut first = true;
399                for cat in cats {
400                    if !first {
401                        write!(f, ",")?;
402                    }
403                    first = false;
404                    write!(f, "{cat}")?;
405                }
406                Ok(())
407            }
408        }
409    }
410}
411
412impl ConfigField for ExplainAnalyzeCategories {
413    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
414        v.some(key, self, description)
415    }
416
417    fn set(&mut self, _: &str, value: &str) -> Result<()> {
418        *self = ExplainAnalyzeCategories::from_str(value)?;
419        Ok(())
420    }
421}
422
423/// Normalized options for a single `EXPLAIN` statement.
424///
425/// This collects the knobs that can be set per-statement from either the
426/// legacy keyword form (`EXPLAIN ANALYZE VERBOSE FORMAT tree ...`) or the
427/// Postgres-style `EXPLAIN (option [arg], ...) ...` form supported on
428/// dialects whose
429/// [`Dialect::supports_explain_with_utility_options`](https://docs.rs/sqlparser/latest/sqlparser/dialect/trait.Dialect.html#method.supports_explain_with_utility_options)
430/// returns `true`.
431///
432/// Fields that are `None` / `false` mean "not set at the statement level" —
433/// the physical planner falls back to the corresponding session config
434/// value.
435#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
436pub struct ExplainStatementOptions {
437    /// Whether to actually execute the plan and gather metrics.
438    ///
439    /// Corresponds to the `ANALYZE` keyword or the `ANALYZE` option.
440    pub analyze: bool,
441    /// Whether to include extra detail in the output.
442    ///
443    /// Corresponds to the `VERBOSE` keyword or the `VERBOSE` option.
444    pub verbose: bool,
445    /// Output format for the plan. When `None`, the session-config
446    /// default (`datafusion.explain.format`) is used.
447    pub format: Option<ExplainFormat>,
448    /// Override for [`MetricType`] (summary / dev) when running
449    /// `EXPLAIN ANALYZE`.
450    pub analyze_level: Option<MetricType>,
451    /// Override for [`ExplainAnalyzeCategories`] (rows / bytes / timing
452    /// / uncategorized) when running `EXPLAIN ANALYZE`.
453    pub analyze_categories: Option<ExplainAnalyzeCategories>,
454    /// Override for `datafusion.explain.show_statistics`.
455    pub show_statistics: Option<bool>,
456}
457
458#[cfg(feature = "sql")]
459impl ExplainStatementOptions {
460    /// Parse a list of [`UtilityOption`] values (produced by sqlparser's
461    /// `parse_utility_options`) into a normalized [`ExplainStatementOptions`].
462    ///
463    /// Argument grammar accepted:
464    /// - `OPTION` — bare, implies `TRUE` for boolean options.
465    /// - `OPTION TRUE` / `OPTION FALSE`
466    /// - `OPTION ON` / `OPTION OFF`
467    /// - `OPTION 1` / `OPTION 0`
468    /// - `OPTION <ident>` or `OPTION '<string>'` for format / level / metrics.
469    ///
470    /// Options recognized by DataFusion are: `ANALYZE`, `VERBOSE`, `FORMAT`,
471    /// `METRICS`, `LEVEL`, `TIMING`, `SUMMARY`, `COSTS`.
472    ///
473    /// Postgres-only options (`BUFFERS`, `WAL`, `SETTINGS`, `GENERIC_PLAN`,
474    /// `MEMORY`) return a helpful "not supported" error. Any other option
475    /// name produces an `unknown EXPLAIN option` error.
476    pub fn from_utility_options(opts: &[UtilityOption]) -> Result<Self> {
477        let mut out = ExplainStatementOptions::default();
478        // Track whether METRICS was explicitly set so TIMING can merge
479        // into it rather than overwrite.
480        let mut metrics_explicit = false;
481
482        for opt in opts {
483            let name = opt.name.value.to_ascii_lowercase();
484            match name.as_str() {
485                "analyze" => {
486                    out.analyze = parse_bool_arg(opt.arg.as_ref(), &name)?;
487                }
488                "verbose" => {
489                    out.verbose = parse_bool_arg(opt.arg.as_ref(), &name)?;
490                }
491                "format" => {
492                    let s = parse_ident_or_string_arg(opt.arg.as_ref(), &name)?;
493                    out.format = Some(ExplainFormat::from_str(&s)?);
494                }
495                "metrics" => {
496                    let s = parse_ident_or_string_arg(opt.arg.as_ref(), &name)?;
497                    out.analyze_categories =
498                        Some(ExplainAnalyzeCategories::from_str(&s)?);
499                    metrics_explicit = true;
500                }
501                "level" => {
502                    let s = parse_ident_or_string_arg(opt.arg.as_ref(), &name)?;
503                    out.analyze_level = Some(MetricType::from_str(&s)?);
504                }
505                "timing" => {
506                    let enable = parse_bool_arg(opt.arg.as_ref(), &name)?;
507                    out.analyze_categories = Some(adjust_timing(
508                        out.analyze_categories.take(),
509                        enable,
510                        metrics_explicit,
511                    ));
512                }
513                "summary" => {
514                    let summary = parse_bool_arg(opt.arg.as_ref(), &name)?;
515                    out.analyze_level = Some(if summary {
516                        MetricType::Summary
517                    } else {
518                        MetricType::Dev
519                    });
520                }
521                "costs" => {
522                    out.show_statistics = Some(parse_bool_arg(opt.arg.as_ref(), &name)?);
523                }
524                // Postgres options DataFusion does not model. Give a helpful
525                // pointer rather than silently accepting them.
526                "buffers" | "wal" | "settings" | "generic_plan" | "memory" => {
527                    let upper = name.to_ascii_uppercase();
528                    return Err(DataFusionError::NotImplemented(format!(
529                        "EXPLAIN option {upper} is not supported by DataFusion; \
530                         see METRICS for category filtering"
531                    )));
532                }
533                _ => {
534                    return Err(DataFusionError::Plan(format!(
535                        "unknown EXPLAIN option: {}",
536                        opt.name.value
537                    )));
538                }
539            }
540        }
541
542        Ok(out)
543    }
544}
545
546/// Parse a boolean argument for an EXPLAIN option.
547///
548/// `None` (bare option, e.g. `ANALYZE`) is treated as `true`. Accepts
549/// identifiers `TRUE`/`FALSE`/`ON`/`OFF` (case-insensitive) and the numeric
550/// literals `0` / `1`.
551#[cfg(feature = "sql")]
552fn parse_bool_arg(arg: Option<&Expr>, name: &str) -> Result<bool> {
553    let Some(expr) = arg else {
554        return Ok(true);
555    };
556    match expr {
557        Expr::Identifier(ident) => match ident.value.to_ascii_lowercase().as_str() {
558            "true" | "on" => Ok(true),
559            "false" | "off" => Ok(false),
560            other => Err(DataFusionError::Plan(format!(
561                "expected boolean for EXPLAIN option {name}, got '{other}'"
562            ))),
563        },
564        Expr::Value(ValueWithSpan { value, .. }) => match value {
565            Value::Boolean(b) => Ok(*b),
566            Value::Number(n, _) => match n.as_str() {
567                "0" => Ok(false),
568                "1" => Ok(true),
569                other => Err(DataFusionError::Plan(format!(
570                    "expected boolean (0 or 1) for EXPLAIN option {name}, got '{other}'"
571                ))),
572            },
573            Value::SingleQuotedString(s) | Value::DoubleQuotedString(s) => {
574                match s.to_ascii_lowercase().as_str() {
575                    "true" | "on" | "1" => Ok(true),
576                    "false" | "off" | "0" => Ok(false),
577                    other => Err(DataFusionError::Plan(format!(
578                        "expected boolean for EXPLAIN option {name}, got '{other}'"
579                    ))),
580                }
581            }
582            other => Err(DataFusionError::Plan(format!(
583                "expected boolean for EXPLAIN option {name}, got '{other}'"
584            ))),
585        },
586        other => Err(DataFusionError::Plan(format!(
587            "expected boolean for EXPLAIN option {name}, got '{other}'"
588        ))),
589    }
590}
591
592/// Parse an identifier-or-string argument (used for `FORMAT`, `METRICS`,
593/// `LEVEL`).
594#[cfg(feature = "sql")]
595fn parse_ident_or_string_arg(arg: Option<&Expr>, name: &str) -> Result<String> {
596    let expr = arg.ok_or_else(|| {
597        DataFusionError::Plan(format!(
598            "EXPLAIN option {} requires an argument",
599            name.to_ascii_uppercase()
600        ))
601    })?;
602    match expr {
603        Expr::Identifier(ident) => Ok(ident.value.clone()),
604        Expr::Value(ValueWithSpan { value, .. }) => match value {
605            Value::SingleQuotedString(s) | Value::DoubleQuotedString(s) => Ok(s.clone()),
606            other => Err(DataFusionError::Plan(format!(
607                "expected identifier or string for EXPLAIN option {name}, got '{other}'"
608            ))),
609        },
610        other => Err(DataFusionError::Plan(format!(
611            "expected identifier or string for EXPLAIN option {name}, got '{other}'"
612        ))),
613    }
614}
615
616/// Merge a `TIMING on/off` option into an existing `METRICS` selection.
617///
618/// If METRICS was already specified, we only add/remove the Timing category
619/// within that selection. If METRICS was not specified, TIMING effectively
620/// means "Only(Timing)" when on, or "show everything except timing" when off.
621#[cfg(feature = "sql")]
622fn adjust_timing(
623    current: Option<ExplainAnalyzeCategories>,
624    enable: bool,
625    metrics_explicit: bool,
626) -> ExplainAnalyzeCategories {
627    // METRICS was not specified — TIMING alone shapes the selection.
628    if !metrics_explicit {
629        return if enable {
630            ExplainAnalyzeCategories::All
631        } else {
632            ExplainAnalyzeCategories::Only(vec![
633                MetricCategory::Rows,
634                MetricCategory::Bytes,
635                MetricCategory::Uncategorized,
636            ])
637        };
638    }
639
640    // METRICS was specified explicitly earlier — merge into its list. When
641    // METRICS was explicit, `current` is always `Some(_)`; fall back to All
642    // to be safe.
643    match current.unwrap_or(ExplainAnalyzeCategories::All) {
644        ExplainAnalyzeCategories::All if enable => ExplainAnalyzeCategories::All,
645        ExplainAnalyzeCategories::All => {
646            // Everything except timing: rows, bytes, uncategorized.
647            ExplainAnalyzeCategories::Only(vec![
648                MetricCategory::Rows,
649                MetricCategory::Bytes,
650                MetricCategory::Uncategorized,
651            ])
652        }
653        ExplainAnalyzeCategories::Only(mut cats) if enable => {
654            if !cats.contains(&MetricCategory::Timing) {
655                cats.push(MetricCategory::Timing);
656            }
657            ExplainAnalyzeCategories::Only(cats)
658        }
659        ExplainAnalyzeCategories::Only(cats) => ExplainAnalyzeCategories::Only(
660            cats.into_iter()
661                .filter(|c| *c != MetricCategory::Timing)
662                .collect(),
663        ),
664    }
665}
666
667#[cfg(all(test, feature = "sql"))]
668mod explain_options_tests {
669    use super::*;
670    use sqlparser::ast::Ident;
671    use sqlparser::tokenizer::Span;
672
673    fn bare(name: &str) -> UtilityOption {
674        UtilityOption {
675            name: Ident {
676                value: name.to_string(),
677                quote_style: None,
678                span: Span::empty(),
679            },
680            arg: None,
681        }
682    }
683
684    fn with_ident_arg(name: &str, arg: &str) -> UtilityOption {
685        UtilityOption {
686            name: Ident {
687                value: name.to_string(),
688                quote_style: None,
689                span: Span::empty(),
690            },
691            arg: Some(Expr::Identifier(Ident {
692                value: arg.to_string(),
693                quote_style: None,
694                span: Span::empty(),
695            })),
696        }
697    }
698
699    fn with_string_arg(name: &str, arg: &str) -> UtilityOption {
700        UtilityOption {
701            name: Ident {
702                value: name.to_string(),
703                quote_style: None,
704                span: Span::empty(),
705            },
706            arg: Some(Expr::Value(ValueWithSpan {
707                value: Value::SingleQuotedString(arg.to_string()),
708                span: Span::empty(),
709            })),
710        }
711    }
712
713    fn with_bool_arg(name: &str, b: bool) -> UtilityOption {
714        UtilityOption {
715            name: Ident {
716                value: name.to_string(),
717                quote_style: None,
718                span: Span::empty(),
719            },
720            arg: Some(Expr::Value(ValueWithSpan {
721                value: Value::Boolean(b),
722                span: Span::empty(),
723            })),
724        }
725    }
726
727    fn with_number_arg(name: &str, n: &str) -> UtilityOption {
728        UtilityOption {
729            name: Ident {
730                value: name.to_string(),
731                quote_style: None,
732                span: Span::empty(),
733            },
734            arg: Some(Expr::Value(ValueWithSpan {
735                value: Value::Number(n.to_string(), false),
736                span: Span::empty(),
737            })),
738        }
739    }
740
741    #[test]
742    fn bare_analyze_and_verbose() {
743        let opts = ExplainStatementOptions::from_utility_options(&[
744            bare("ANALYZE"),
745            bare("VERBOSE"),
746        ])
747        .unwrap();
748        assert!(opts.analyze);
749        assert!(opts.verbose);
750        assert!(opts.format.is_none());
751    }
752
753    #[test]
754    fn format_from_ident_and_string() {
755        let opts = ExplainStatementOptions::from_utility_options(&[with_ident_arg(
756            "FORMAT", "tree",
757        )])
758        .unwrap();
759        assert_eq!(opts.format, Some(ExplainFormat::Tree));
760
761        let opts = ExplainStatementOptions::from_utility_options(&[with_string_arg(
762            "FORMAT", "pgjson",
763        )])
764        .unwrap();
765        assert_eq!(opts.format, Some(ExplainFormat::PostgresJSON));
766    }
767
768    #[test]
769    fn metrics_and_level() {
770        let opts = ExplainStatementOptions::from_utility_options(&[
771            with_string_arg("METRICS", "rows,bytes"),
772            with_ident_arg("LEVEL", "dev"),
773        ])
774        .unwrap();
775        assert_eq!(
776            opts.analyze_categories,
777            Some(ExplainAnalyzeCategories::Only(vec![
778                MetricCategory::Rows,
779                MetricCategory::Bytes,
780            ]))
781        );
782        assert_eq!(opts.analyze_level, Some(MetricType::Dev));
783    }
784
785    #[test]
786    fn on_off_numeric_bool() {
787        let opts = ExplainStatementOptions::from_utility_options(&[
788            with_ident_arg("ANALYZE", "ON"),
789            with_ident_arg("VERBOSE", "off"),
790            with_bool_arg("COSTS", true),
791        ])
792        .unwrap();
793        assert!(opts.analyze);
794        assert!(!opts.verbose);
795        assert_eq!(opts.show_statistics, Some(true));
796
797        let opts = ExplainStatementOptions::from_utility_options(&[
798            with_number_arg("ANALYZE", "1"),
799            with_number_arg("VERBOSE", "0"),
800        ])
801        .unwrap();
802        assert!(opts.analyze);
803        assert!(!opts.verbose);
804    }
805
806    #[test]
807    fn summary_sugar_sets_level() {
808        let opts = ExplainStatementOptions::from_utility_options(&[with_ident_arg(
809            "SUMMARY", "ON",
810        )])
811        .unwrap();
812        assert_eq!(opts.analyze_level, Some(MetricType::Summary));
813
814        let opts = ExplainStatementOptions::from_utility_options(&[with_bool_arg(
815            "SUMMARY", false,
816        )])
817        .unwrap();
818        assert_eq!(opts.analyze_level, Some(MetricType::Dev));
819    }
820
821    #[test]
822    fn timing_merges_with_metrics() {
823        // METRICS then TIMING off → timing is removed from the list
824        let opts = ExplainStatementOptions::from_utility_options(&[
825            with_string_arg("METRICS", "rows,timing"),
826            with_bool_arg("TIMING", false),
827        ])
828        .unwrap();
829        assert_eq!(
830            opts.analyze_categories,
831            Some(ExplainAnalyzeCategories::Only(vec![MetricCategory::Rows]))
832        );
833
834        // METRICS 'rows' then TIMING on → timing is appended
835        let opts = ExplainStatementOptions::from_utility_options(&[
836            with_string_arg("METRICS", "rows"),
837            with_bool_arg("TIMING", true),
838        ])
839        .unwrap();
840        assert_eq!(
841            opts.analyze_categories,
842            Some(ExplainAnalyzeCategories::Only(vec![
843                MetricCategory::Rows,
844                MetricCategory::Timing,
845            ]))
846        );
847    }
848
849    #[test]
850    fn timing_alone() {
851        let opts = ExplainStatementOptions::from_utility_options(&[with_bool_arg(
852            "TIMING", false,
853        )])
854        .unwrap();
855        assert_eq!(
856            opts.analyze_categories,
857            Some(ExplainAnalyzeCategories::Only(vec![
858                MetricCategory::Rows,
859                MetricCategory::Bytes,
860                MetricCategory::Uncategorized,
861            ]))
862        );
863    }
864
865    #[test]
866    fn unknown_option_rejected() {
867        let err =
868            ExplainStatementOptions::from_utility_options(&[bare("FOO")]).unwrap_err();
869        assert!(
870            err.to_string().contains("unknown EXPLAIN option: FOO"),
871            "got: {err}"
872        );
873    }
874
875    #[test]
876    fn postgres_only_options_rejected() {
877        for pg_only in ["BUFFERS", "WAL", "SETTINGS", "GENERIC_PLAN", "MEMORY"] {
878            let err = ExplainStatementOptions::from_utility_options(&[bare(pg_only)])
879                .unwrap_err();
880            let msg = err.to_string();
881            assert!(
882                msg.contains(pg_only),
883                "msg did not include {pg_only}: {msg}"
884            );
885            assert!(msg.contains("not supported"), "msg: {msg}");
886        }
887    }
888}