Apache DataFusion SQL Query Engine
feat: Ensure explain format in config is valid (#17549)
Alex Huange2c2d3840e01
diff --git a/datafusion-cli/src/main.rs b/datafusion-cli/src/main.rsindex a28e97a9f8..ab1726f226 100644--- a/datafusion-cli/src/main.rs+++ b/datafusion-cli/src/main.rs@@ -28,6 +28,7 @@ use datafusion::execution::memory_pool::{FairSpillPool, GreedyMemoryPool, MemoryPool, TrackConsumersPool,};use datafusion::execution::runtime_env::RuntimeEnvBuilder;+use datafusion::logical_expr::ExplainFormat;use datafusion::prelude::SessionContext;use datafusion_cli::catalog::DynamicObjectStoreCatalog;use datafusion_cli::functions::{MetadataCacheFunc, ParquetMetadataFunc};@@ -288,7 +289,7 @@ fn get_session_config(args: &Args) -> Result<SessionConfig> {// use easier to understand "tree" mode by default// if the user hasn't specified an explain format in the environmentif env::var_os("DATAFUSION_EXPLAIN_FORMAT").is_none() {- config_options.explain.format = String::from("tree");+ config_options.explain.format = ExplainFormat::Tree;}// in the CLI, we want to show NULL values rather the empty stringsdiff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rsindex abc8862b67..6abb2f5c6d 100644--- a/datafusion/common/src/config.rs+++ b/datafusion/common/src/config.rs@@ -22,6 +22,7 @@ use arrow_ipc::CompressionType;#[cfg(feature = "parquet_encryption")]use crate::encryption::{FileDecryptionProperties, FileEncryptionProperties};use crate::error::_config_err;+use crate::format::ExplainFormat;use crate::parsers::CompressionTypeVariant;use crate::utils::get_available_parallelism;use crate::{DataFusionError, Result};@@ -879,7 +880,7 @@ config_namespace! {/// Display format of explain. Default is "indent"./// When set to "tree", it will print the plan in a tree-rendered format.- pub format: String, default = "indent".to_string()+ pub format: ExplainFormat, default = ExplainFormat::Indent/// (format=tree only) Maximum total width of the rendered tree./// When set to 0, the tree will have no width limit.diff --git a/datafusion/common/src/format.rs b/datafusion/common/src/format.rsindex a4ebd17539..06ec519ef3 100644--- a/datafusion/common/src/format.rs+++ b/datafusion/common/src/format.rs@@ -15,9 +15,15 @@// specific language governing permissions and limitations// under the License.+use std::fmt::{self, Display};+use std::str::FromStr;+use arrow::compute::CastOptions;use arrow::util::display::{DurationFormat, FormatOptions};+use crate::config::{ConfigField, Visit};+use crate::error::{DataFusionError, Result};+/// The default [`FormatOptions`] to use within DataFusion/// Also see [`crate::config::FormatOptions`]pub const DEFAULT_FORMAT_OPTIONS: FormatOptions<'static> =@@ -28,3 +34,174 @@ pub const DEFAULT_CAST_OPTIONS: CastOptions<'static> = CastOptions {safe: false,format_options: DEFAULT_FORMAT_OPTIONS,};++/// Output formats for controlling for Explain plans+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub enum ExplainFormat {+ /// Indent mode+ ///+ /// Example:+ /// ```text+ /// > explain format indent select x from values (1) t(x);+ /// +---------------+-----------------------------------------------------++ /// | plan_type | plan |+ /// +---------------+-----------------------------------------------------++ /// | logical_plan | SubqueryAlias: t |+ /// | | Projection: column1 AS x |+ /// | | Values: (Int64(1)) |+ /// | physical_plan | ProjectionExec: expr=[column1@0 as x] |+ /// | | DataSourceExec: partitions=1, partition_sizes=[1] |+ /// | | |+ /// +---------------+-----------------------------------------------------++ /// ```+ Indent,+ /// Tree mode+ ///+ /// Example:+ /// ```text+ /// > explain format tree select x from values (1) t(x);+ /// +---------------+-------------------------------++ /// | plan_type | plan |+ /// +---------------+-------------------------------++ /// | physical_plan | ┌───────────────────────────┐ |+ /// | | │ ProjectionExec │ |+ /// | | │ -------------------- │ |+ /// | | │ x: column1@0 │ |+ /// | | └─────────────┬─────────────┘ |+ /// | | ┌─────────────┴─────────────┐ |+ /// | | │ DataSourceExec │ |+ /// | | │ -------------------- │ |+ /// | | │ bytes: 128 │ |+ /// | | │ format: memory │ |+ /// | | │ rows: 1 │ |+ /// | | └───────────────────────────┘ |+ /// | | |+ /// +---------------+-------------------------------++ /// ```+ Tree,+ /// Postgres Json mode+ ///+ /// A displayable structure that produces plan in postgresql JSON format.+ ///+ /// Users can use this format to visualize the plan in existing plan+ /// visualization tools, for example [dalibo](https://explain.dalibo.com/)+ ///+ /// Example:+ /// ```text+ /// > explain format pgjson select x from values (1) t(x);+ /// +--------------+--------------------------------------++ /// | plan_type | plan |+ /// +--------------+--------------------------------------++ /// | logical_plan | [ |+ /// | | { |+ /// | | "Plan": { |+ /// | | "Alias": "t", |+ /// | | "Node Type": "Subquery", |+ /// | | "Output": [ |+ /// | | "x" |+ /// | | ], |+ /// | | "Plans": [ |+ /// | | { |+ /// | | "Expressions": [ |+ /// | | "column1 AS x" |+ /// | | ], |+ /// | | "Node Type": "Projection", |+ /// | | "Output": [ |+ /// | | "x" |+ /// | | ], |+ /// | | "Plans": [ |+ /// | | { |+ /// | | "Node Type": "Values", |+ /// | | "Output": [ |+ /// | | "column1" |+ /// | | ], |+ /// | | "Plans": [], |+ /// | | "Values": "(Int64(1))" |+ /// | | } |+ /// | | ] |+ /// | | } |+ /// | | ] |+ /// | | } |+ /// | | } |+ /// | | ] |+ /// +--------------+--------------------------------------++ /// ```+ PostgresJSON,+ /// Graphviz mode+ ///+ /// Example:+ /// ```text+ /// > explain format graphviz select x from values (1) t(x);+ /// +--------------+------------------------------------------------------------------------++ /// | plan_type | plan |+ /// +--------------+------------------------------------------------------------------------++ /// | logical_plan | |+ /// | | // Begin DataFusion GraphViz Plan, |+ /// | | // display it online here: https://dreampuf.github.io/GraphvizOnline |+ /// | | |+ /// | | digraph { |+ /// | | subgraph cluster_1 |+ /// | | { |+ /// | | graph[label="LogicalPlan"] |+ /// | | 2[shape=box label="SubqueryAlias: t"] |+ /// | | 3[shape=box label="Projection: column1 AS x"] |+ /// | | 2 -> 3 [arrowhead=none, arrowtail=normal, dir=back] |+ /// | | 4[shape=box label="Values: (Int64(1))"] |+ /// | | 3 -> 4 [arrowhead=none, arrowtail=normal, dir=back] |+ /// | | } |+ /// | | subgraph cluster_5 |+ /// | | { |+ /// | | graph[label="Detailed LogicalPlan"] |+ /// | | 6[shape=box label="SubqueryAlias: t\nSchema: [x:Int64;N]"] |+ /// | | 7[shape=box label="Projection: column1 AS x\nSchema: [x:Int64;N]"] |+ /// | | 6 -> 7 [arrowhead=none, arrowtail=normal, dir=back] |+ /// | | 8[shape=box label="Values: (Int64(1))\nSchema: [column1:Int64;N]"] |+ /// | | 7 -> 8 [arrowhead=none, arrowtail=normal, dir=back] |+ /// | | } |+ /// | | } |+ /// | | // End DataFusion GraphViz Plan |+ /// | | |+ /// +--------------+------------------------------------------------------------------------++ /// ```+ Graphviz,+}++/// Implement parsing strings to `ExplainFormat`+impl FromStr for ExplainFormat {+ type Err = DataFusionError;++ fn from_str(format: &str) -> Result<Self, Self::Err> {+ match format.to_lowercase().as_str() {+ "indent" => Ok(ExplainFormat::Indent),+ "tree" => Ok(ExplainFormat::Tree),+ "pgjson" => Ok(ExplainFormat::PostgresJSON),+ "graphviz" => Ok(ExplainFormat::Graphviz),+ _ => {+ Err(DataFusionError::Configuration(format!("Invalid explain format. Expected 'indent', 'tree', 'pgjson' or 'graphviz'. Got '{format}'")))+ }+ }+ }+}++impl Display for ExplainFormat {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ let s = match self {+ ExplainFormat::Indent => "indent",+ ExplainFormat::Tree => "tree",+ ExplainFormat::PostgresJSON => "pgjson",+ ExplainFormat::Graphviz => "graphviz",+ };+ write!(f, "{s}")+ }+}++impl ConfigField for ExplainFormat {+ fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {+ v.some(key, self, description)+ }++ fn set(&mut self, _: &str, value: &str) -> Result<()> {+ *self = ExplainFormat::from_str(value)?;+ Ok(())+ }+}diff --git a/datafusion/expr/src/logical_plan/mod.rs b/datafusion/expr/src/logical_plan/mod.rsindex 4bbb9d7ada..7de2fd1174 100644--- a/datafusion/expr/src/logical_plan/mod.rs+++ b/datafusion/expr/src/logical_plan/mod.rs@@ -39,16 +39,18 @@ pub use ddl::{pub use dml::{DmlStatement, WriteOp};pub use plan::{projection_schema, Aggregate, Analyze, ColumnUnnestList, DescribeTable, Distinct,- DistinctOn, EmptyRelation, Explain, ExplainFormat, ExplainOption, Extension,- FetchType, Filter, Join, JoinConstraint, JoinType, Limit, LogicalPlan, Partitioning,- PlanType, Projection, RecursiveQuery, Repartition, SkipType, Sort, StringifiedPlan,- Subquery, SubqueryAlias, TableScan, ToStringifiedPlan, Union, Unnest, Values, Window,+ DistinctOn, EmptyRelation, Explain, ExplainOption, Extension, FetchType, Filter,+ Join, JoinConstraint, JoinType, Limit, LogicalPlan, Partitioning, PlanType,+ Projection, RecursiveQuery, Repartition, SkipType, Sort, StringifiedPlan, Subquery,+ SubqueryAlias, TableScan, ToStringifiedPlan, Union, Unnest, Values, Window,};pub use statement::{Deallocate, Execute, Prepare, SetVariable, Statement, TransactionAccessMode,TransactionConclusion, TransactionEnd, TransactionIsolationLevel, TransactionStart,};+pub use datafusion_common::format::ExplainFormat;+pub use display::display_schema;pub use extension::{UserDefinedLogicalNode, UserDefinedLogicalNodeCore};diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rsindex fba43780ef..7dc750a35c 100644--- a/datafusion/expr/src/logical_plan/plan.rs+++ b/datafusion/expr/src/logical_plan/plan.rs@@ -21,7 +21,6 @@ use std::cmp::Ordering;use std::collections::{HashMap, HashSet};use std::fmt::{self, Debug, Display, Formatter};use std::hash::{Hash, Hasher};-use std::str::FromStr;use std::sync::{Arc, LazyLock};use super::dml::CopyTo;@@ -54,6 +53,7 @@ use crate::{use arrow::datatypes::{DataType, Field, Schema, SchemaRef};use datafusion_common::cse::{NormalizeEq, Normalizeable};+use datafusion_common::format::ExplainFormat;use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeContainer, TreeNodeRecursion,};@@ -2996,154 +2996,6 @@ impl PartialOrd for DescribeTable {}}-/// Output formats for controlling for Explain plans-#[derive(Debug, Clone, PartialEq, Eq, Hash)]-pub enum ExplainFormat {- /// Indent mode- ///- /// Example:- /// ```text- /// > explain format indent select x from values (1) t(x);- /// +---------------+-----------------------------------------------------+- /// | plan_type | plan |- /// +---------------+-----------------------------------------------------+- /// | logical_plan | SubqueryAlias: t |- /// | | Projection: column1 AS x |- /// | | Values: (Int64(1)) |- /// | physical_plan | ProjectionExec: expr=[column1@0 as x] |- /// | | DataSourceExec: partitions=1, partition_sizes=[1] |- /// | | |- /// +---------------+-----------------------------------------------------+- /// ```- Indent,- /// Tree mode- ///- /// Example:- /// ```text- /// > explain format tree select x from values (1) t(x);- /// +---------------+-------------------------------+- /// | plan_type | plan |- /// +---------------+-------------------------------+- /// | physical_plan | ┌───────────────────────────┐ |- /// | | │ ProjectionExec │ |- /// | | │ -------------------- │ |- /// | | │ x: column1@0 │ |- /// | | └─────────────┬─────────────┘ |- /// | | ┌─────────────┴─────────────┐ |- /// | | │ DataSourceExec │ |- /// | | │ -------------------- │ |- /// | | │ bytes: 128 │ |- /// | | │ format: memory │ |- /// | | │ rows: 1 │ |- /// | | └───────────────────────────┘ |- /// | | |- /// +---------------+-------------------------------+- /// ```- Tree,- /// Postgres Json mode- ///- /// A displayable structure that produces plan in postgresql JSON format.- ///- /// Users can use this format to visualize the plan in existing plan- /// visualization tools, for example [dalibo](https://explain.dalibo.com/)- ///- /// Example:- /// ```text- /// > explain format pgjson select x from values (1) t(x);- /// +--------------+--------------------------------------+- /// | plan_type | plan |- /// +--------------+--------------------------------------+- /// | logical_plan | [ |- /// | | { |- /// | | "Plan": { |- /// | | "Alias": "t", |- /// | | "Node Type": "Subquery", |- /// | | "Output": [ |- /// | | "x" |- /// | | ], |- /// | | "Plans": [ |- /// | | { |- /// | | "Expressions": [ |- /// | | "column1 AS x" |- /// | | ], |- /// | | "Node Type": "Projection", |- /// | | "Output": [ |- /// | | "x" |- /// | | ], |- /// | | "Plans": [ |- /// | | { |- /// | | "Node Type": "Values", |- /// | | "Output": [ |- /// | | "column1" |- /// | | ], |- /// | | "Plans": [], |- /// | | "Values": "(Int64(1))" |- /// | | } |- /// | | ] |- /// | | } |- /// | | ] |- /// | | } |- /// | | } |- /// | | ] |- /// +--------------+--------------------------------------+- /// ```- PostgresJSON,- /// Graphviz mode- ///- /// Example:- /// ```text- /// > explain format graphviz select x from values (1) t(x);- /// +--------------+------------------------------------------------------------------------+- /// | plan_type | plan |- /// +--------------+------------------------------------------------------------------------+- /// | logical_plan | |- /// | | // Begin DataFusion GraphViz Plan, |- /// | | // display it online here: https://dreampuf.github.io/GraphvizOnline |- /// | | |- /// | | digraph { |- /// | | subgraph cluster_1 |- /// | | { |- /// | | graph[label="LogicalPlan"] |- /// | | 2[shape=box label="SubqueryAlias: t"] |- /// | | 3[shape=box label="Projection: column1 AS x"] |- /// | | 2 -> 3 [arrowhead=none, arrowtail=normal, dir=back] |- /// | | 4[shape=box label="Values: (Int64(1))"] |- /// | | 3 -> 4 [arrowhead=none, arrowtail=normal, dir=back] |- /// | | } |- /// | | subgraph cluster_5 |- /// | | { |- /// | | graph[label="Detailed LogicalPlan"] |- /// | | 6[shape=box label="SubqueryAlias: t\nSchema: [x:Int64;N]"] |- /// | | 7[shape=box label="Projection: column1 AS x\nSchema: [x:Int64;N]"] |- /// | | 6 -> 7 [arrowhead=none, arrowtail=normal, dir=back] |- /// | | 8[shape=box label="Values: (Int64(1))\nSchema: [column1:Int64;N]"] |- /// | | 7 -> 8 [arrowhead=none, arrowtail=normal, dir=back] |- /// | | } |- /// | | } |- /// | | // End DataFusion GraphViz Plan |- /// | | |- /// +--------------+------------------------------------------------------------------------+- /// ```- Graphviz,-}--/// Implement parsing strings to `ExplainFormat`-impl FromStr for ExplainFormat {- type Err = DataFusionError;-- fn from_str(format: &str) -> std::result::Result<Self, Self::Err> {- match format.to_lowercase().as_str() {- "indent" => Ok(ExplainFormat::Indent),- "tree" => Ok(ExplainFormat::Tree),- "pgjson" => Ok(ExplainFormat::PostgresJSON),- "graphviz" => Ok(ExplainFormat::Graphviz),- _ => {- plan_err!("Invalid explain format. Expected 'indent', 'tree', 'pgjson' or 'graphviz'. Got '{format}'")- }- }- }-}-/// Options for EXPLAIN#[derive(Debug, Clone, PartialEq, Eq, Hash)]pub struct ExplainOption {diff --git a/datafusion/sql/src/statement.rs b/datafusion/sql/src/statement.rsindex 6875cfead6..7f94fce7bd 100644--- a/datafusion/sql/src/statement.rs+++ b/datafusion/sql/src/statement.rs@@ -1711,14 +1711,14 @@ impl<S: ContextProvider> SqlToRel<'_, S> {vec![plan.to_stringified(PlanType::InitialLogicalPlan)];// default to configuration value- let options = self.context_provider.options();- let format = format.as_ref().unwrap_or(&options.explain.format);-// verbose mode only supports indent format- let format: ExplainFormat = if verbose {+ let options = self.context_provider.options();+ let format = if verbose {ExplainFormat::Indent+ } else if let Some(format) = format {+ ExplainFormat::from_str(&format)?} else {- format.parse()?+ options.explain.format.clone()};Ok(LogicalPlan::Explain(Explain {diff --git a/datafusion/sqllogictest/test_files/explain.slt b/datafusion/sqllogictest/test_files/explain.sltindex 2eb4d3e091..a3b6d40aea 100644--- a/datafusion/sqllogictest/test_files/explain.slt+++ b/datafusion/sqllogictest/test_files/explain.slt@@ -523,6 +523,10 @@ explain format 123 select * from values (1);query error DataFusion error: Error during planning: EXPLAIN VERBOSE with FORMAT is not supportedexplain verbose format tree select * from values (1);+# valid explain format+query error DataFusion error: Invalid or Unsupported Configuration: Invalid explain format. Expected 'indent', 'tree', 'pgjson' or 'graphviz'. Got 'xxx'+set datafusion.explain.format = "xxx";+# verbose uses indent mode even when a different mode (e.g tree) is setstatement ok@@ -616,10 +620,10 @@ statement okset datafusion.explain.format = "indent";# no such thing as json mode-query error DataFusion error: Error during planning: Invalid explain format\. Expected 'indent', 'tree', 'pgjson' or 'graphviz'\. Got 'json'+query error DataFusion error: Invalid or Unsupported Configuration: Invalid explain format\. Expected 'indent', 'tree', 'pgjson' or 'graphviz'\. Got 'json'explain format json select * from values (1);-query error DataFusion error: Error during planning: Invalid explain format\. Expected 'indent', 'tree', 'pgjson' or 'graphviz'\. Got 'foo'+query error DataFusion error: Invalid or Unsupported Configuration: Invalid explain format\. Expected 'indent', 'tree', 'pgjson' or 'graphviz'\. Got 'foo'explain format foo select * from values (1);# pgjson mode