Apache DataFusion SQL Query Engine
Add `plan_err!` error macro (#7115)
compheade695de0ad6b8
diff --git a/benchmarks/src/tpch/mod.rs b/benchmarks/src/tpch/mod.rsindex 1b6350278d..8965ebea7f 100644--- a/benchmarks/src/tpch/mod.rs+++ b/benchmarks/src/tpch/mod.rs@@ -20,10 +20,10 @@use arrow::datatypes::SchemaBuilder;use datafusion::{arrow::datatypes::{DataType, Field, Schema},+ common::plan_err,error::{DataFusionError, Result},};use std::fs;-mod run;pub use run::RunOpt;@@ -158,13 +158,9 @@ pub fn get_query_sql(query: usize) -> Result<Vec<String>> {Err(e) => errors.push(format!("{filename}: {e}")),};}- Err(DataFusionError::Plan(format!(- "invalid query. Could not find query: {errors:?}"- )))+ plan_err!("invalid query. Could not find query: {:?}", errors)} else {- Err(DataFusionError::Plan(- "invalid query. Expected value between 1 and 22".to_owned(),- ))+ plan_err!("invalid query. Expected value between 1 and 22")}}diff --git a/datafusion-cli/src/exec.rs b/datafusion-cli/src/exec.rsindex adbdb06e52..4de7eb5afe 100644--- a/datafusion-cli/src/exec.rs+++ b/datafusion-cli/src/exec.rs@@ -263,6 +263,7 @@ async fn create_external_table(#[cfg(test)]mod tests {use super::*;+ use datafusion::common::plan_err;async fn create_external_table_test(location: &str, sql: &str) -> Result<()> {let ctx = SessionContext::new();@@ -271,9 +272,7 @@ mod tests {if let LogicalPlan::Ddl(DdlStatement::CreateExternalTable(cmd)) = &plan {create_external_table(&ctx, cmd).await?;} else {- return Err(DataFusionError::Plan(- "LogicalPlan is not a CreateExternalTable".to_string(),- ));+ return plan_err!("LogicalPlan is not a CreateExternalTable");}ctx.runtime_env()diff --git a/datafusion-cli/src/object_storage.rs b/datafusion-cli/src/object_storage.rsindex 86958cc6b7..c39d1915eb 100644--- a/datafusion-cli/src/object_storage.rs+++ b/datafusion-cli/src/object_storage.rs@@ -159,6 +159,8 @@ fn get_bucket_name(url: &Url) -> Result<&str> {#[cfg(test)]mod tests {+ use super::*;+ use datafusion::common::plan_err;use datafusion::{datasource::listing::ListingTableUrl,logical_expr::{DdlStatement, LogicalPlan},@@ -166,8 +168,6 @@ mod tests {};use object_store::{aws::AmazonS3ConfigKey, gcp::GoogleConfigKey};- use super::*;-#[tokio::test]async fn s3_object_store_builder() -> Result<()> {let access_key_id = "fake_access_key_id";@@ -195,9 +195,7 @@ mod tests {assert_eq!(value, builder.get_config_value(&key).unwrap());}} else {- return Err(DataFusionError::Plan(- "LogicalPlan is not a CreateExternalTable".to_string(),- ));+ return plan_err!("LogicalPlan is not a CreateExternalTable");}Ok(())@@ -228,9 +226,7 @@ mod tests {assert_eq!(value, builder.get_config_value(&key).unwrap());}} else {- return Err(DataFusionError::Plan(- "LogicalPlan is not a CreateExternalTable".to_string(),- ));+ return plan_err!("LogicalPlan is not a CreateExternalTable");}Ok(())@@ -265,9 +261,7 @@ mod tests {assert_eq!(value, builder.get_config_value(&key).unwrap());}} else {- return Err(DataFusionError::Plan(- "LogicalPlan is not a CreateExternalTable".to_string(),- ));+ return plan_err!("LogicalPlan is not a CreateExternalTable");}Ok(())diff --git a/datafusion-examples/examples/rewrite_expr.rs b/datafusion-examples/examples/rewrite_expr.rsindex c6c5d8cfd8..e657baab3d 100644--- a/datafusion-examples/examples/rewrite_expr.rs+++ b/datafusion-examples/examples/rewrite_expr.rs@@ -18,7 +18,7 @@use arrow::datatypes::{DataType, Field, Schema, SchemaRef};use datafusion_common::config::ConfigOptions;use datafusion_common::tree_node::{Transformed, TreeNode};-use datafusion_common::{DataFusionError, Result, ScalarValue};+use datafusion_common::{plan_err, DataFusionError, Result, ScalarValue};use datafusion_expr::{AggregateUDF, Between, Expr, Filter, LogicalPlan, ScalarUDF, TableSource, WindowUDF,};@@ -200,7 +200,7 @@ impl ContextProvider for MyContextProvider {])),}))} else {- Err(DataFusionError::Plan("table not found".to_string()))+ plan_err!("table not found")}}diff --git a/datafusion-examples/examples/simple_udwf.rs b/datafusion-examples/examples/simple_udwf.rsindex c5c166a579..15cfffe65f 100644--- a/datafusion-examples/examples/simple_udwf.rs+++ b/datafusion-examples/examples/simple_udwf.rs@@ -26,7 +26,7 @@ use datafusion::datasource::file_format::options::CsvReadOptions;use datafusion::error::Result;use datafusion::prelude::*;-use datafusion_common::{DataFusionError, ScalarValue};+use datafusion_common::{plan_err, DataFusionError, ScalarValue};use datafusion_expr::{PartitionEvaluator, Signature, Volatility, WindowFrame, WindowUDF,};@@ -140,11 +140,11 @@ fn smooth_it() -> WindowUDF {/// arguments of `arg_types`.fn return_type(arg_types: &[DataType]) -> Result<Arc<DataType>> {if arg_types.len() != 1 {- return Err(DataFusionError::Plan(format!(+ return plan_err!("my_udwf expects 1 argument, got {}: {:?}",arg_types.len(),arg_types- )));+ );}Ok(Arc::new(arg_types[0].clone()))}diff --git a/datafusion/common/src/error.rs b/datafusion/common/src/error.rsindex 656cd76ce5..240194d868 100644--- a/datafusion/common/src/error.rs+++ b/datafusion/common/src/error.rs@@ -99,18 +99,6 @@ macro_rules! context {};}-#[macro_export]-macro_rules! plan_err {- ($desc:expr) => {- Err(datafusion_common::DataFusionError::Plan(format!(- "{} at {}:{}",- $desc,- file!(),- line!()- )))- };-}-/// Schema-related errors#[derive(Debug)]pub enum SchemaError {@@ -411,6 +399,56 @@ impl DataFusionError {}}+/// Unwrap an `Option` if possible. Otherwise return an `DataFusionError::Internal`.+/// In normal usage of DataFusion the unwrap should always succeed.+///+/// Example: `let values = unwrap_or_internal_err!(values)`+#[macro_export]+macro_rules! unwrap_or_internal_err {+ ($Value: ident) => {+ $Value.ok_or_else(|| {+ DataFusionError::Internal(format!(+ "{} should not be None",+ stringify!($Value)+ ))+ })?+ };+}++#[macro_export]+macro_rules! with_dollar_sign {+ ($($body:tt)*) => {+ macro_rules! __with_dollar_sign { $($body)* }+ __with_dollar_sign!($);+ }+}++/// Add a macros for concise DataFusionError::* errors declaration+/// supports placeholders the same way as `format!`+/// Examples:+/// plan_err!("Error")+/// plan_err!("Error {}", val)+/// plan_err!("Error {:?}", val)+/// plan_err!("Error {val}")+/// plan_err!("Error {val:?}")+macro_rules! make_error {+ ($NAME:ident, $ERR:ident) => {+ with_dollar_sign! {+ ($d:tt) => {+ #[macro_export]+ macro_rules! $NAME {+ ($d($d args:expr),*) => {+ Err(DataFusionError::$ERR(format!($d($d args),*).into()))+ }+ }+ }+ }+ };+}++// Exposes a macro to create `DataFusionError::Plan`+make_error!(plan_err, Plan);+#[cfg(test)]mod test {use std::sync::Arc;@@ -488,6 +526,39 @@ mod test {);}+ #[test]+ fn test_make_error_parse_input() {+ let res: Result<(), DataFusionError> = plan_err!("Err");+ let res = res.unwrap_err();+ assert_eq!(res.to_string(), "Error during planning: Err");++ let extra1 = "extra1";+ let extra2 = "extra2";++ let res: Result<(), DataFusionError> = plan_err!("Err {} {}", extra1, extra2);+ let res = res.unwrap_err();+ assert_eq!(res.to_string(), "Error during planning: Err extra1 extra2");++ let res: Result<(), DataFusionError> =+ plan_err!("Err {:?} {:#?}", extra1, extra2);+ let res = res.unwrap_err();+ assert_eq!(+ res.to_string(),+ "Error during planning: Err \"extra1\" \"extra2\""+ );++ let res: Result<(), DataFusionError> = plan_err!("Err {extra1} {extra2}");+ let res = res.unwrap_err();+ assert_eq!(res.to_string(), "Error during planning: Err extra1 extra2");++ let res: Result<(), DataFusionError> = plan_err!("Err {extra1:?} {extra2:#?}");+ let res = res.unwrap_err();+ assert_eq!(+ res.to_string(),+ "Error during planning: Err \"extra1\" \"extra2\""+ );+ }+/// Model what happens when implementing SendableRecordBatchStream:/// DataFusion code needs to return an ArrowErrorfn return_arrow_error() -> arrow::error::Result<()> {@@ -510,26 +581,3 @@ mod test {assert_eq!(std::mem::discriminant(e), std::mem::discriminant(&exp),)}}--#[macro_export]-macro_rules! internal_err {- ($($arg:tt)*) => {- Err(DataFusionError::Internal(format!($($arg)*)))- };-}--/// Unwrap an `Option` if possible. Otherwise return an `DataFusionError::Internal`.-/// In normal usage of DataFusion the unwrap should always succeed.-///-/// Example: `let values = unwrap_or_internal_err!(values)`-#[macro_export]-macro_rules! unwrap_or_internal_err {- ($Value: ident) => {- $Value.ok_or_else(|| {- DataFusionError::Internal(format!(- "{} should not be None",- stringify!($Value)- ))- })?- };-}diff --git a/datafusion/core/src/datasource/file_format/options.rs b/datafusion/core/src/datasource/file_format/options.rsindex 69449e9f8d..a50066fd97 100644--- a/datafusion/core/src/datasource/file_format/options.rs+++ b/datafusion/core/src/datasource/file_format/options.rs@@ -21,7 +21,7 @@ use std::sync::Arc;use arrow::datatypes::{DataType, Schema, SchemaRef};use async_trait::async_trait;-use datafusion_common::DataFusionError;+use datafusion_common::{plan_err, DataFusionError};use crate::datasource::file_format::arrow::{ArrowFormat, DEFAULT_ARROW_EXTENSION};use crate::datasource::file_format::avro::DEFAULT_AVRO_EXTENSION;@@ -439,10 +439,9 @@ pub trait ReadOptions<'a> {.to_listing_options(config).infer_schema(&state, &table_path).await?),- (None, true) => Err(DataFusionError::Plan(- "Schema inference for infinite data sources is not supported."- .to_string(),- )),+ (None, true) => {+ plan_err!("Schema inference for infinite data sources is not supported.")+ }}}}diff --git a/datafusion/core/src/datasource/listing/table.rs b/datafusion/core/src/datasource/listing/table.rsindex c27dcaf391..2d8ba99563 100644--- a/datafusion/core/src/datasource/listing/table.rs+++ b/datafusion/core/src/datasource/listing/table.rs@@ -25,7 +25,7 @@ use arrow::datatypes::{DataType, Field, SchemaBuilder, SchemaRef};use arrow_schema::Schema;use async_trait::async_trait;use dashmap::DashMap;-use datafusion_common::{SchemaExt, ToDFSchema};+use datafusion_common::{plan_err, SchemaExt, ToDFSchema};use datafusion_expr::expr::Sort;use datafusion_optimizer::utils::conjunction;use datafusion_physical_expr::{create_physical_expr, LexOrdering, PhysicalSortExpr};@@ -640,14 +640,10 @@ impl ListingTable {})}else {- Err(DataFusionError::Plan(- format!("Expected single column references in output_ordering, got {expr}")- ))+ plan_err!("Expected single column references in output_ordering, got {expr}")}} else {- Err(DataFusionError::Plan(- format!("Expected Expr::Sort in output_ordering, but got {expr}")- ))+ plan_err!("Expected Expr::Sort in output_ordering, but got {expr}")}}).collect::<Result<Vec<_>>>()?;@@ -777,17 +773,16 @@ impl TableProvider for ListingTable {) -> Result<Arc<dyn ExecutionPlan>> {// Check that the schema of the plan matches the schema of this table.if !self.schema().equivalent_names_and_types(&input.schema()) {- return Err(DataFusionError::Plan(+ return plan_err!(// Return an error if schema of the input query does not match with the table schema.- "Inserting query must have the same schema with the table.".to_string(),- ));+ "Inserting query must have the same schema with the table."+ );}if self.table_paths().len() > 1 {- return Err(DataFusionError::Plan(+ return plan_err!("Writing to a table backed by multiple files is not supported yet"- .to_owned(),- ));+ );}let table_path = &self.table_paths()[0];@@ -806,10 +801,9 @@ impl TableProvider for ListingTable {let file_groups = file_list_stream.try_collect::<Vec<_>>().await?;if file_groups.len() > 1 {- return Err(DataFusionError::Plan(+ return plan_err!("Datafusion currently supports tables from single partition and/or file."- .to_owned(),- ));+ );}// Sink related option, apart from formatdiff --git a/datafusion/core/src/datasource/memory.rs b/datafusion/core/src/datasource/memory.rsindex 4b6653c688..5bac551cf6 100644--- a/datafusion/core/src/datasource/memory.rs+++ b/datafusion/core/src/datasource/memory.rs@@ -26,13 +26,13 @@ use std::sync::Arc;use arrow::datatypes::SchemaRef;use arrow::record_batch::RecordBatch;use async_trait::async_trait;-use datafusion_common::{Constraints, SchemaExt};+use datafusion_common::{plan_err, Constraints, DataFusionError, SchemaExt};use datafusion_execution::TaskContext;use tokio::sync::RwLock;use tokio::task::JoinSet;use crate::datasource::{TableProvider, TableType};-use crate::error::{DataFusionError, Result};+use crate::error::Result;use crate::execution::context::SessionState;use crate::logical_expr::Expr;use crate::physical_plan::insert::{DataSink, InsertExec};@@ -65,9 +65,7 @@ impl MemTable {"mem table schema does not contain batches schema. \Target_schema: {schema:?}. Batches Schema: {batches_schema:?}");- return Err(DataFusionError::Plan(- "Mismatch between schema and batches".to_string(),- ));+ return plan_err!("Mismatch between schema and batches");}}@@ -210,9 +208,9 @@ impl TableProvider for MemTable {// Create a physical plan from the logical plan.// Check that the schema of the plan matches the schema of this table.if !self.schema().equivalent_names_and_types(&input.schema()) {- return Err(DataFusionError::Plan(- "Inserting query must have the same schema with the table.".to_string(),- ));+ return plan_err!(+ "Inserting query must have the same schema with the table."+ );}let sink = Arc::new(MemSink::new(self.batches.clone()));Ok(Arc::new(InsertExec::new(input, sink, self.schema.clone())))diff --git a/datafusion/core/src/datasource/physical_plan/mod.rs b/datafusion/core/src/datasource/physical_plan/mod.rsindex 5ca045ab29..35fb789aaf 100644--- a/datafusion/core/src/datasource/physical_plan/mod.rs+++ b/datafusion/core/src/datasource/physical_plan/mod.rs@@ -61,7 +61,10 @@ use crate::{scalar::ScalarValue,};-use datafusion_common::tree_node::{TreeNode, VisitRecursion};+use datafusion_common::{+ plan_err,+ tree_node::{TreeNode, VisitRecursion},+};use datafusion_physical_expr::expressions::Column;use arrow::compute::cast;@@ -557,12 +560,12 @@ impl SchemaAdapter {projection.push(file_idx);}false => {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Cannot cast file schema field {} of type {:?} to table schema field of type {:?}",file_field.name(),file_field.data_type(),table_field.data_type()- )))+ )}}}diff --git a/datafusion/core/src/datasource/streaming.rs b/datafusion/core/src/datasource/streaming.rsindex 97962ab9b7..3eb120653c 100644--- a/datafusion/core/src/datasource/streaming.rs+++ b/datafusion/core/src/datasource/streaming.rs@@ -23,7 +23,7 @@ use std::sync::Arc;use arrow::datatypes::SchemaRef;use async_trait::async_trait;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_expr::{Expr, TableType};use log::debug;@@ -52,9 +52,7 @@ impl StreamingTable {"target schema does not contain partition schema. \Target_schema: {schema:?}. Partiton Schema: {partition_schema:?}");- return Err(DataFusionError::Plan(- "Mismatch between schema and batches".to_string(),- ));+ return plan_err!("Mismatch between schema and batches");}}diff --git a/datafusion/core/src/execution/context.rs b/datafusion/core/src/execution/context.rsindex 622da6f5a7..ce9165f027 100644--- a/datafusion/core/src/execution/context.rs+++ b/datafusion/core/src/execution/context.rs@@ -28,7 +28,7 @@ use crate::{optimizer::optimizer::Optimizer,physical_optimizer::optimizer::{PhysicalOptimizer, PhysicalOptimizerRule},};-use datafusion_common::alias::AliasGenerator;+use datafusion_common::{alias::AliasGenerator, plan_err};use datafusion_execution::registry::SerializerRegistry;use datafusion_expr::{logical_plan::{DdlStatement, Statement},@@ -955,10 +955,9 @@ impl SessionContext {(Some(s), _) => s,(None, false) => options.infer_schema(&self.state(), &table_path).await?,(None, true) => {- return Err(DataFusionError::Plan(+ return plan_err!("Schema inference for infinite data sources is not supported."- .to_string(),- ))+ )}};let config = ListingTableConfig::new(table_path)@@ -1179,7 +1178,7 @@ impl SessionContext {let schema = self.state.read().schema_for_ref(table_ref)?;match schema.table(&table).await {Some(ref provider) => Ok(Arc::clone(provider)),- _ => Err(DataFusionError::Plan(format!("No table named '{table}'"))),+ _ => plan_err!("No table named '{table}'"),}}diff --git a/datafusion/core/src/physical_optimizer/pipeline_checker.rs b/datafusion/core/src/physical_optimizer/pipeline_checker.rsindex b12c4ef93f..9736eb381c 100644--- a/datafusion/core/src/physical_optimizer/pipeline_checker.rs+++ b/datafusion/core/src/physical_optimizer/pipeline_checker.rs@@ -26,7 +26,7 @@ use crate::physical_plan::joins::SymmetricHashJoinExec;use crate::physical_plan::{with_new_children_if_necessary, ExecutionPlan};use datafusion_common::config::OptimizerOptions;use datafusion_common::tree_node::{Transformed, TreeNode, VisitRecursion};-use datafusion_common::DataFusionError;+use datafusion_common::{plan_err, DataFusionError};use datafusion_physical_expr::intervals::{check_support, is_datatype_supported};use std::sync::Arc;@@ -142,7 +142,7 @@ pub fn check_finiteness_requirements({const MSG: &str = "Join operation cannot operate on a non-prunable stream without enabling \the 'allow_symmetric_joins_without_pruning' configuration flag";- return Err(DataFusionError::Plan(MSG.to_owned()));+ return plan_err!("{}", MSG);}}inputdiff --git a/datafusion/core/src/physical_optimizer/pruning.rs b/datafusion/core/src/physical_optimizer/pruning.rsindex 8fb3058308..b0e59499ee 100644--- a/datafusion/core/src/physical_optimizer/pruning.rs+++ b/datafusion/core/src/physical_optimizer/pruning.rs@@ -44,8 +44,11 @@ use arrow::{datatypes::{DataType, Field, Schema, SchemaRef},record_batch::RecordBatch,};-use datafusion_common::tree_node::{Transformed, TreeNode};use datafusion_common::{downcast_value, ScalarValue};+use datafusion_common::{+ plan_err,+ tree_node::{Transformed, TreeNode},+};use datafusion_physical_expr::utils::collect_columns;use datafusion_physical_expr::{expressions as phys_expr, PhysicalExprRef};use log::trace;@@ -453,10 +456,9 @@ impl<'a> PruningExpressionBuilder<'a> {(0, 1) => (right, left, right_columns, reverse_operator(op)?),_ => {// if more than one column used in expression - not supported- return Err(DataFusionError::Plan(+ return plan_err!("Multi-column expressions are not currently supported"- .to_string(),- ));+ );}};@@ -471,9 +473,7 @@ impl<'a> PruningExpressionBuilder<'a> {let field = match schema.column_with_name(column.name()) {Some((_, f)) => f,_ => {- return Err(DataFusionError::Plan(- "Field not found in schema".to_string(),- ));+ return plan_err!("Field not found in schema");}};@@ -525,9 +525,7 @@ fn rewrite_expr_to_prunable(schema: DFSchema,) -> Result<(PhysicalExprRef, Operator, PhysicalExprRef)> {if !is_compare_op(op) {- return Err(DataFusionError::Plan(- "rewrite_expr_to_prunable only support compare expression".to_string(),- ));+ return plan_err!("rewrite_expr_to_prunable only support compare expression");}let column_expr_any = column_expr.as_any();@@ -574,9 +572,7 @@ fn rewrite_expr_to_prunable(} else if let Some(not) = column_expr_any.downcast_ref::<phys_expr::NotExpr>() {// `!col = true` --> `col = !true`if op != Operator::Eq && op != Operator::NotEq {- return Err(DataFusionError::Plan(- "Not with operator other than Eq / NotEq is not supported".to_string(),- ));+ return plan_err!("Not with operator other than Eq / NotEq is not supported");}if not.arg()@@ -588,14 +584,10 @@ fn rewrite_expr_to_prunable(let right = Arc::new(phys_expr::NotExpr::new(scalar_expr.clone()));Ok((left, reverse_operator(op)?, right))} else {- Err(DataFusionError::Plan(format!(- "Not with complex expression {column_expr:?} is not supported"- )))+ plan_err!("Not with complex expression {column_expr:?} is not supported")}} else {- Err(DataFusionError::Plan(format!(- "column expression {column_expr:?} is not supported"- )))+ plan_err!("column expression {column_expr:?} is not supported")}}@@ -630,9 +622,9 @@ fn verify_support_type_for_prune(from_type: &DataType, to_type: &DataType) -> Re) {Ok(())} else {- Err(DataFusionError::Plan(format!(+ plan_err!("Try Cast/Cast with from type {from_type} to type {to_type} is not supported"- )))+ )}}@@ -841,85 +833,85 @@ fn build_predicate_expression(fn build_statistics_expr(expr_builder: &mut PruningExpressionBuilder,) -> Result<Arc<dyn PhysicalExpr>> {- let statistics_expr: Arc<dyn PhysicalExpr> =- match expr_builder.op() {- Operator::NotEq => {- // column != literal => (min, max) = literal =>- // !(min != literal && max != literal) ==>- // min != literal || literal != max- let min_column_expr = expr_builder.min_column_expr()?;- let max_column_expr = expr_builder.max_column_expr()?;- Arc::new(phys_expr::BinaryExpr::new(- Arc::new(phys_expr::BinaryExpr::new(- min_column_expr,- Operator::NotEq,- expr_builder.scalar_expr().clone(),- )),- Operator::Or,- Arc::new(phys_expr::BinaryExpr::new(- expr_builder.scalar_expr().clone(),- Operator::NotEq,- max_column_expr,- )),- ))- }- Operator::Eq => {- // column = literal => (min, max) = literal => min <= literal && literal <= max- // (column / 2) = 4 => (column_min / 2) <= 4 && 4 <= (column_max / 2)- let min_column_expr = expr_builder.min_column_expr()?;- let max_column_expr = expr_builder.max_column_expr()?;+ let statistics_expr: Arc<dyn PhysicalExpr> = match expr_builder.op() {+ Operator::NotEq => {+ // column != literal => (min, max) = literal =>+ // !(min != literal && max != literal) ==>+ // min != literal || literal != max+ let min_column_expr = expr_builder.min_column_expr()?;+ let max_column_expr = expr_builder.max_column_expr()?;+ Arc::new(phys_expr::BinaryExpr::new(Arc::new(phys_expr::BinaryExpr::new(- Arc::new(phys_expr::BinaryExpr::new(- min_column_expr,- Operator::LtEq,- expr_builder.scalar_expr().clone(),- )),- Operator::And,- Arc::new(phys_expr::BinaryExpr::new(- expr_builder.scalar_expr().clone(),- Operator::LtEq,- max_column_expr,- )),- ))- }- Operator::Gt => {- // column > literal => (min, max) > literal => max > literal- Arc::new(phys_expr::BinaryExpr::new(- expr_builder.max_column_expr()?,- Operator::Gt,+ min_column_expr,+ Operator::NotEq,expr_builder.scalar_expr().clone(),- ))- }- Operator::GtEq => {- // column >= literal => (min, max) >= literal => max >= literal+ )),+ Operator::Or,Arc::new(phys_expr::BinaryExpr::new(- expr_builder.max_column_expr()?,- Operator::GtEq,expr_builder.scalar_expr().clone(),- ))- }- Operator::Lt => {- // column < literal => (min, max) < literal => min < literal+ Operator::NotEq,+ max_column_expr,+ )),+ ))+ }+ Operator::Eq => {+ // column = literal => (min, max) = literal => min <= literal && literal <= max+ // (column / 2) = 4 => (column_min / 2) <= 4 && 4 <= (column_max / 2)+ let min_column_expr = expr_builder.min_column_expr()?;+ let max_column_expr = expr_builder.max_column_expr()?;+ Arc::new(phys_expr::BinaryExpr::new(Arc::new(phys_expr::BinaryExpr::new(- expr_builder.min_column_expr()?,- Operator::Lt,+ min_column_expr,+ Operator::LtEq,expr_builder.scalar_expr().clone(),- ))- }- Operator::LtEq => {- // column <= literal => (min, max) <= literal => min <= literal+ )),+ Operator::And,Arc::new(phys_expr::BinaryExpr::new(- expr_builder.min_column_expr()?,- Operator::LtEq,expr_builder.scalar_expr().clone(),- ))- }- // other expressions are not supported- _ => return Err(DataFusionError::Plan(+ Operator::LtEq,+ max_column_expr,+ )),+ ))+ }+ Operator::Gt => {+ // column > literal => (min, max) > literal => max > literal+ Arc::new(phys_expr::BinaryExpr::new(+ expr_builder.max_column_expr()?,+ Operator::Gt,+ expr_builder.scalar_expr().clone(),+ ))+ }+ Operator::GtEq => {+ // column >= literal => (min, max) >= literal => max >= literal+ Arc::new(phys_expr::BinaryExpr::new(+ expr_builder.max_column_expr()?,+ Operator::GtEq,+ expr_builder.scalar_expr().clone(),+ ))+ }+ Operator::Lt => {+ // column < literal => (min, max) < literal => min < literal+ Arc::new(phys_expr::BinaryExpr::new(+ expr_builder.min_column_expr()?,+ Operator::Lt,+ expr_builder.scalar_expr().clone(),+ ))+ }+ Operator::LtEq => {+ // column <= literal => (min, max) <= literal => min <= literal+ Arc::new(phys_expr::BinaryExpr::new(+ expr_builder.min_column_expr()?,+ Operator::LtEq,+ expr_builder.scalar_expr().clone(),+ ))+ }+ // other expressions are not supported+ _ => {+ return plan_err!("expressions other than (neq, eq, gt, gteq, lt, lteq) are not supported"- .to_string(),- )),- };+ )+ }+ };Ok(statistics_expr)}diff --git a/datafusion/core/src/physical_optimizer/sort_enforcement.rs b/datafusion/core/src/physical_optimizer/sort_enforcement.rsindex 97fc79720b..644aea1f38 100644--- a/datafusion/core/src/physical_optimizer/sort_enforcement.rs+++ b/datafusion/core/src/physical_optimizer/sort_enforcement.rs@@ -56,7 +56,7 @@ use crate::physical_plan::{with_new_children_if_necessary, Distribution, Executiuse arrow::datatypes::SchemaRef;use datafusion_common::tree_node::{Transformed, TreeNode, VisitRecursion};use datafusion_common::utils::{get_at_indices, longest_consecutive_prefix};-use datafusion_common::DataFusionError;+use datafusion_common::{plan_err, DataFusionError};use datafusion_physical_expr::utils::{convert_to_expr, get_indices_of_matching_exprs, ordering_satisfy,ordering_satisfy_requirement_concrete,@@ -597,17 +597,16 @@ fn analyze_window_sort_removal(sort_tree: &mut ExecTree,window_exec: &Arc<dyn ExecutionPlan>,) -> Result<Option<PlanWithCorrespondingSort>> {- let (window_expr, partition_keys) = if let Some(exec) =- window_exec.as_any().downcast_ref::<BoundedWindowAggExec>()- {- (exec.window_expr(), &exec.partition_keys)- } else if let Some(exec) = window_exec.as_any().downcast_ref::<WindowAggExec>() {- (exec.window_expr(), &exec.partition_keys)- } else {- return Err(DataFusionError::Plan(- "Expects to receive either WindowAggExec of BoundedWindowAggExec".to_string(),- ));- };+ let (window_expr, partition_keys) =+ if let Some(exec) = window_exec.as_any().downcast_ref::<BoundedWindowAggExec>() {+ (exec.window_expr(), &exec.partition_keys)+ } else if let Some(exec) = window_exec.as_any().downcast_ref::<WindowAggExec>() {+ (exec.window_expr(), &exec.partition_keys)+ } else {+ return plan_err!(+ "Expects to receive either WindowAggExec of BoundedWindowAggExec"+ );+ };let partitionby_exprs = window_expr[0].partition_by();let orderby_sort_keys = window_expr[0].order_by();@@ -814,10 +813,7 @@ fn get_sort_exprs(sort_preserving_merge_exec.fetch(),))} else {- Err(DataFusionError::Plan(- "Given ExecutionPlan is not a SortExec or a SortPreservingMergeExec"- .to_string(),- ))+ plan_err!("Given ExecutionPlan is not a SortExec or a SortPreservingMergeExec")}}diff --git a/datafusion/core/src/physical_optimizer/sort_pushdown.rs b/datafusion/core/src/physical_optimizer/sort_pushdown.rsindex eb7fb49ac9..aaa2b6de2b 100644--- a/datafusion/core/src/physical_optimizer/sort_pushdown.rs+++ b/datafusion/core/src/physical_optimizer/sort_pushdown.rs@@ -27,7 +27,7 @@ use crate::physical_plan::sorts::sort::SortExec;use crate::physical_plan::{with_new_children_if_necessary, ExecutionPlan};use datafusion_common::tree_node::{Transformed, TreeNode, VisitRecursion};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_expr::JoinType;use datafusion_physical_expr::expressions::Column;use datafusion_physical_expr::utils::{@@ -424,10 +424,9 @@ fn shift_right_required(if new_right_required.len() == parent_required.len() {Ok(new_right_required)} else {- Err(DataFusionError::Plan(+ plan_err!("Expect to shift all the parent required column indexes for SortMergeJoin"- .to_string(),- ))+ )}}diff --git a/datafusion/core/src/physical_plan/aggregates/mod.rs b/datafusion/core/src/physical_plan/aggregates/mod.rsindex ac04be0c33..473d4eb131 100644--- a/datafusion/core/src/physical_plan/aggregates/mod.rs+++ b/datafusion/core/src/physical_plan/aggregates/mod.rs@@ -30,7 +30,7 @@ use arrow::array::ArrayRef;use arrow::datatypes::{Field, Schema, SchemaRef};use arrow::record_batch::RecordBatch;use datafusion_common::utils::longest_consecutive_prefix;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_execution::TaskContext;use datafusion_expr::Accumulator;use datafusion_physical_expr::{@@ -555,10 +555,9 @@ fn calc_required_input_ordering(*aggr_expr = reverse;*ob_expr = ob_expr.as_ref().map(|obs| reverse_order_bys(obs));} else {- return Err(DataFusionError::Plan(+ return plan_err!("Aggregate expression should have a reverse expression"- .to_string(),- ));+ );}}Ok(())@@ -848,9 +847,9 @@ impl ExecutionPlan for AggregateExec {if children[0] {if self.aggregation_ordering.is_none() {// Cannot run without breaking pipeline.- Err(DataFusionError::Plan(- "Aggregate Error: `GROUP BY` clauses with columns without ordering and GROUPING SETS are not supported for unbounded inputs.".to_string(),- ))+ plan_err!(+ "Aggregate Error: `GROUP BY` clauses with columns without ordering and GROUPING SETS are not supported for unbounded inputs."+ )} else {Ok(true)}diff --git a/datafusion/core/src/physical_plan/common.rs b/datafusion/core/src/physical_plan/common.rsindex 19c05eaada..f6b8fb33c9 100644--- a/datafusion/core/src/physical_plan/common.rs+++ b/datafusion/core/src/physical_plan/common.rs@@ -23,7 +23,7 @@ use crate::physical_plan::{ColumnStatistics, ExecutionPlan, Statistics};use arrow::datatypes::Schema;use arrow::ipc::writer::{FileWriter, IpcWriteOptions};use arrow::record_batch::RecordBatch;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_execution::memory_pool::MemoryReservation;use datafusion_physical_expr::expressions::{BinaryExpr, Column};use datafusion_physical_expr::{PhysicalExpr, PhysicalSortExpr};@@ -50,9 +50,7 @@ pub fn build_checked_file_list(dir: &str, ext: &str) -> Result<Vec<String>> {let mut filenames: Vec<String> = Vec::new();build_file_list_recurse(dir, &mut filenames, ext)?;if filenames.is_empty() {- return Err(DataFusionError::Plan(format!(- "No files found at {dir} with file extension {ext}"- )));+ return plan_err!("No files found at {dir} with file extension {ext}");}Ok(filenames)}@@ -86,7 +84,7 @@ fn build_file_list_recurse(filenames.push(path_name.to_string());}} else {- return Err(DataFusionError::Plan("Invalid path".to_string()));+ return plan_err!("Invalid path");}}}diff --git a/datafusion/core/src/physical_plan/filter.rs b/datafusion/core/src/physical_plan/filter.rsindex 29a705daf0..e8c181a34b 100644--- a/datafusion/core/src/physical_plan/filter.rs+++ b/datafusion/core/src/physical_plan/filter.rs@@ -37,7 +37,7 @@ use arrow::compute::filter_record_batch;use arrow::datatypes::{DataType, SchemaRef};use arrow::record_batch::RecordBatch;use datafusion_common::cast::as_boolean_array;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_execution::TaskContext;use datafusion_expr::Operator;use datafusion_physical_expr::expressions::BinaryExpr;@@ -74,9 +74,9 @@ impl FilterExec {input: input.clone(),metrics: ExecutionPlanMetricsSet::new(),}),- other => Err(DataFusionError::Plan(format!(- "Filter predicate must return boolean values, not {other:?}"- ))),+ other => {+ plan_err!("Filter predicate must return boolean values, not {other:?}")+ }}}diff --git a/datafusion/core/src/physical_plan/joins/cross_join.rs b/datafusion/core/src/physical_plan/joins/cross_join.rsindex 1ecbfbea95..eaee9892d0 100644--- a/datafusion/core/src/physical_plan/joins/cross_join.rs+++ b/datafusion/core/src/physical_plan/joins/cross_join.rs@@ -34,7 +34,7 @@ use crate::physical_plan::{SendableRecordBatchStream, Statistics,};use async_trait::async_trait;-use datafusion_common::DataFusionError;+use datafusion_common::{plan_err, DataFusionError};use datafusion_common::{Result, ScalarValue};use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};use datafusion_execution::TaskContext;@@ -176,10 +176,9 @@ impl ExecutionPlan for CrossJoinExec {/// infinite, returns an error to indicate this.fn unbounded_output(&self, children: &[bool]) -> Result<bool> {if children[0] || children[1] {- Err(DataFusionError::Plan(+ plan_err!("Cross Join Error: Cross join is not supported for the unbounded inputs."- .to_string(),- ))+ )} else {Ok(false)}diff --git a/datafusion/core/src/physical_plan/joins/hash_join.rs b/datafusion/core/src/physical_plan/joins/hash_join.rsindex b97f2806e6..2108893ccb 100644--- a/datafusion/core/src/physical_plan/joins/hash_join.rs+++ b/datafusion/core/src/physical_plan/joins/hash_join.rs@@ -76,7 +76,7 @@ use arrow::{use arrow_array::cast::downcast_array;use arrow_schema::ArrowError;use datafusion_common::cast::{as_dictionary_array, as_string_array};-use datafusion_common::{DataFusionError, JoinType, Result};+use datafusion_common::{plan_err, DataFusionError, JoinType, Result};use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};use datafusion_execution::TaskContext;use datafusion_physical_expr::OrderingEquivalenceProperties;@@ -138,9 +138,7 @@ impl HashJoinExec {let left_schema = left.schema();let right_schema = right.schema();if on.is_empty() {- return Err(DataFusionError::Plan(- "On constraints in HashJoinExec should be non-empty".to_string(),- ));+ return plan_err!("On constraints in HashJoinExec should be non-empty");}check_join_is_valid(&left_schema, &right_schema, &on)?;@@ -310,14 +308,14 @@ impl ExecutionPlan for HashJoinExec {));if breaking {- Err(DataFusionError::Plan(format!(+ plan_err!("Join Error: The join with cannot be executed with unbounded inputs. {}",if left && right {"Currently, we do not support unbounded inputs on both sides."} else {"Please consider a different type of join or sources."}- )))+ )} else {Ok(left || right)}@@ -469,10 +467,10 @@ impl ExecutionPlan for HashJoinExec {))}PartitionMode::Auto => {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Invalid HashJoinExec, unsupported PartitionMode {:?} in execute()",PartitionMode::Auto- )));+ );}};diff --git a/datafusion/core/src/physical_plan/joins/sort_merge_join.rs b/datafusion/core/src/physical_plan/joins/sort_merge_join.rsindex 4b34ecbcc2..b3721eb4d6 100644--- a/datafusion/core/src/physical_plan/joins/sort_merge_join.rs+++ b/datafusion/core/src/physical_plan/joins/sort_merge_join.rs@@ -49,7 +49,7 @@ use arrow::compute::{concat_batches, take, SortOptions};use arrow::datatypes::{DataType, SchemaRef, TimeUnit};use arrow::error::ArrowError;use arrow::record_batch::RecordBatch;-use datafusion_common::{DataFusionError, JoinType, Result};+use datafusion_common::{plan_err, DataFusionError, JoinType, Result};use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};use datafusion_execution::TaskContext;use datafusion_physical_expr::{OrderingEquivalenceProperties, PhysicalSortRequirement};@@ -108,11 +108,11 @@ impl SortMergeJoinExec {check_join_is_valid(&left_schema, &right_schema, &on)?;if sort_options.len() != on.len() {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Expected number of sort options: {}, actual: {}",on.len(),sort_options.len()- )));+ );}let (left_sort_exprs, right_sort_exprs): (Vec<_>, Vec<_>) = ondiff --git a/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rs b/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rsindex 1818e4b91c..dc8bcc2edb 100644--- a/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rs+++ b/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rs@@ -75,7 +75,7 @@ use crate::physical_plan::{RecordBatchStream, SendableRecordBatchStream, Statistics,};use datafusion_common::utils::bisect;-use datafusion_common::JoinType;+use datafusion_common::{plan_err, JoinType};use datafusion_common::{DataFusionError, Result};use datafusion_execution::TaskContext;@@ -278,9 +278,9 @@ impl SymmetricHashJoinExec {// Error out if no "on" contraints are given:if on.is_empty() {- return Err(DataFusionError::Plan(- "On constraints in SymmetricHashJoinExec should be non-empty".to_string(),- ));+ return plan_err!(+ "On constraints in SymmetricHashJoinExec should be non-empty"+ );}// Check if the join is valid with the given on constraints:diff --git a/datafusion/core/src/physical_plan/joins/utils.rs b/datafusion/core/src/physical_plan/joins/utils.rsindex 3366ee8ffa..abba191f04 100644--- a/datafusion/core/src/physical_plan/joins/utils.rs+++ b/datafusion/core/src/physical_plan/joins/utils.rs@@ -40,7 +40,9 @@ use arrow::datatypes::{Field, Schema, SchemaBuilder};use arrow::record_batch::{RecordBatch, RecordBatchOptions};use datafusion_common::cast::as_boolean_array;use datafusion_common::tree_node::{Transformed, TreeNode};-use datafusion_common::{DataFusionError, JoinType, Result, ScalarValue, SharedResult};+use datafusion_common::{+ plan_err, DataFusionError, JoinType, Result, ScalarValue, SharedResult,+};use datafusion_physical_expr::expressions::Column;use datafusion_physical_expr::{EquivalentClass, LexOrdering, LexOrderingRef, OrderingEquivalenceProperties,@@ -92,9 +94,9 @@ fn check_join_set_is_valid(let right_missing = on_right.difference(right).collect::<HashSet<_>>();if !left_missing.is_empty() | !right_missing.is_empty() {- return Err(DataFusionError::Plan(format!(- "The left or right side of the join does not have all columns on \"on\": \nMissing on the left: {left_missing:?}\nMissing on the right: {right_missing:?}",- )));+ return plan_err!(+ "The left or right side of the join does not have all columns on \"on\": \nMissing on the left: {left_missing:?}\nMissing on the right: {right_missing:?}"+ );};Ok(())diff --git a/datafusion/core/src/physical_plan/sorts/sort.rs b/datafusion/core/src/physical_plan/sorts/sort.rsindex f660f0acf8..fc45acbc43 100644--- a/datafusion/core/src/physical_plan/sorts/sort.rs+++ b/datafusion/core/src/physical_plan/sorts/sort.rs@@ -35,7 +35,7 @@ use arrow::compute::{concat_batches, lexsort_to_indices, take};use arrow::datatypes::SchemaRef;use arrow::ipc::reader::FileReader;use arrow::record_batch::RecordBatch;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_execution::memory_pool::{human_readable_size, MemoryConsumer, MemoryReservation,};@@ -556,9 +556,7 @@ impl ExecutionPlan for SortExec {/// infinite, returns an error to indicate this.fn unbounded_output(&self, children: &[bool]) -> Result<bool> {if children[0] {- Err(DataFusionError::Plan(- "Sort Error: Can not sort unbounded inputs.".to_string(),- ))+ plan_err!("Sort Error: Can not sort unbounded inputs.")} else {Ok(false)}diff --git a/datafusion/core/src/physical_plan/streaming.rs b/datafusion/core/src/physical_plan/streaming.rsindex 58f4596a6e..28623f2995 100644--- a/datafusion/core/src/physical_plan/streaming.rs+++ b/datafusion/core/src/physical_plan/streaming.rs@@ -24,7 +24,7 @@ use arrow::datatypes::SchemaRef;use async_trait::async_trait;use futures::stream::StreamExt;-use datafusion_common::{DataFusionError, Result, Statistics};+use datafusion_common::{plan_err, DataFusionError, Result, Statistics};use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr};use log::debug;@@ -69,9 +69,7 @@ impl StreamingTableExec {"target schema does not contain partition schema. \Target_schema: {schema:?}. Partiton Schema: {partition_schema:?}");- return Err(DataFusionError::Plan(- "Mismatch between schema and batches".to_string(),- ));+ return plan_err!("Mismatch between schema and batches");}}diff --git a/datafusion/core/src/physical_plan/values.rs b/datafusion/core/src/physical_plan/values.rsindex 70e00ed034..757e020350 100644--- a/datafusion/core/src/physical_plan/values.rs+++ b/datafusion/core/src/physical_plan/values.rs@@ -26,7 +26,7 @@ use crate::physical_plan::{use arrow::array::new_null_array;use arrow::datatypes::SchemaRef;use arrow::record_batch::RecordBatch;-use datafusion_common::ScalarValue;+use datafusion_common::{plan_err, ScalarValue};use datafusion_common::{DataFusionError, Result};use datafusion_execution::TaskContext;use std::any::Any;@@ -48,7 +48,7 @@ impl ValuesExec {data: Vec<Vec<Arc<dyn PhysicalExpr>>>,) -> Result<Self> {if data.is_empty() {- return Err(DataFusionError::Plan("Values list cannot be empty".into()));+ return plan_err!("Values list cannot be empty");}let n_row = data.len();let n_col = schema.fields().len();@@ -72,9 +72,9 @@ impl ValuesExec {ScalarValue::try_from_array(&a, 0)}Ok(ColumnarValue::Array(a)) => {- Err(DataFusionError::Plan(format!(+ plan_err!("Cannot have array values {a:?} in a values list"- )))+ )}Err(err) => Err(err),}diff --git a/datafusion/core/src/physical_plan/windows/bounded_window_agg_exec.rs b/datafusion/core/src/physical_plan/windows/bounded_window_agg_exec.rsindex 1f0da4a8e6..4889f667f3 100644--- a/datafusion/core/src/physical_plan/windows/bounded_window_agg_exec.rs+++ b/datafusion/core/src/physical_plan/windows/bounded_window_agg_exec.rs@@ -31,7 +31,7 @@ use crate::physical_plan::{ColumnStatistics, DisplayAs, DisplayFormatType, Distribution, ExecutionPlan,Partitioning, RecordBatchStream, SendableRecordBatchStream, Statistics, WindowExpr,};-use datafusion_common::Result;+use datafusion_common::{plan_err, Result};use datafusion_execution::TaskContext;use ahash::RandomState;@@ -611,9 +611,9 @@ impl LinearSearch {.iter().map(|item| match item.evaluate(record_batch)? {ColumnarValue::Array(array) => Ok(array),- ColumnarValue::Scalar(scalar) => Err(DataFusionError::Plan(format!(- "Sort operation is not applicable to scalar value {scalar}"- ))),+ ColumnarValue::Scalar(scalar) => {+ plan_err!("Sort operation is not applicable to scalar value {scalar}")+ }}).collect()}diff --git a/datafusion/core/src/physical_plan/windows/window_agg_exec.rs b/datafusion/core/src/physical_plan/windows/window_agg_exec.rsindex 7e7fc22965..83979af2f4 100644--- a/datafusion/core/src/physical_plan/windows/window_agg_exec.rs+++ b/datafusion/core/src/physical_plan/windows/window_agg_exec.rs@@ -39,8 +39,8 @@ use arrow::{record_batch::RecordBatch,};use datafusion_common::utils::{evaluate_partition_ranges, get_at_indices};-use datafusion_common::DataFusionError;use datafusion_common::Result;+use datafusion_common::{plan_err, DataFusionError};use datafusion_execution::TaskContext;use datafusion_physical_expr::{OrderingEquivalenceProperties, PhysicalSortRequirement};use futures::stream::Stream;@@ -176,10 +176,9 @@ impl ExecutionPlan for WindowAggExec {/// infinite, returns an error to indicate this.fn unbounded_output(&self, children: &[bool]) -> Result<bool> {if children[0] {- Err(DataFusionError::Plan(+ plan_err!("Window Error: Windowing is not currently support for unbounded inputs."- .to_string(),- ))+ )} else {Ok(false)}diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rsindex 72fd554ed7..947a3f4387 100644--- a/datafusion/core/src/physical_planner.rs+++ b/datafusion/core/src/physical_planner.rs@@ -62,7 +62,7 @@ use crate::{use arrow::compute::SortOptions;use arrow::datatypes::{Schema, SchemaRef};use async_trait::async_trait;-use datafusion_common::{DFSchema, ScalarValue};+use datafusion_common::{plan_err, DFSchema, ScalarValue};use datafusion_expr::expr::{self, AggregateFunction, AggregateUDF, Alias, Between, BinaryExpr, Cast,GetIndexedField, GroupingSet, InList, Like, ScalarUDF, TryCast, WindowFunction,@@ -1206,19 +1206,20 @@ impl DefaultPhysicalPlanner {).await?;}- let plan = maybe_plan.ok_or_else(|| DataFusionError::Plan(format!(- "No installed planner was able to convert the custom node to an execution plan: {:?}", e.node- )))?;+ let plan = match maybe_plan {+ Some(v) => Ok(v),+ _ => plan_err!("No installed planner was able to convert the custom node to an execution plan: {:?}", e.node)+ }?;// Ensure the ExecutionPlan's schema matches the// declared logical schema to catch and warn about// logic errors when creating user defined plans.if !e.node.schema().matches_arrow_schema(&plan.schema()) {- Err(DataFusionError::Plan(format!(+ plan_err!("Extension planner for {:?} created an ExecutionPlan with mismatched schema. \LogicalPlan schema: {:?}, ExecutionPlan schema: {:?}",e.node, e.node.schema(), plan.schema()- )))+ )} else {Ok(plan)}@@ -1555,10 +1556,10 @@ pub fn create_window_expr_with_name(}).collect::<Result<Vec<_>>>()?;if !is_window_valid(window_frame) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Invalid window frame: start bound ({}) cannot be larger than end bound ({})",window_frame.start_bound, window_frame.end_bound- )));+ );}let window_frame = Arc::new(window_frame.clone());@@ -1572,9 +1573,7 @@ pub fn create_window_expr_with_name(physical_input_schema,)}- other => Err(DataFusionError::Plan(format!(- "Invalid window expression '{other:?}'"- ))),+ other => plan_err!("Invalid window expression '{other:?}'"),}}diff --git a/datafusion/core/tests/sql/mod.rs b/datafusion/core/tests/sql/mod.rsindex 85a8064285..c1adcf9d0a 100644--- a/datafusion/core/tests/sql/mod.rs+++ b/datafusion/core/tests/sql/mod.rs@@ -40,6 +40,7 @@ use datafusion::{};use datafusion::{execution::context::SessionContext, physical_plan::displayable};use datafusion_common::cast::as_float64_array;+use datafusion_common::plan_err;use datafusion_common::{assert_contains, assert_not_contains};use datafusion_expr::Volatility;use object_store::path::Path;@@ -405,10 +406,7 @@ async fn register_tpch_csv_data(DataType::Decimal128(_, _) => {cols.push(Box::new(Decimal128Builder::with_capacity(records.len())))}- _ => {- let msg = format!("Not implemented: {}", field.data_type());- Err(DataFusionError::Plan(msg))?- }+ _ => plan_err!("Not implemented: {}", field.data_type())?,}}@@ -446,10 +444,7 @@ async fn register_tpch_csv_data(let value_i128 = val.parse::<i128>().unwrap();sb.append_value(value_i128);}- _ => Err(DataFusionError::Plan(format!(- "Not implemented: {}",- field.data_type()- )))?,+ _ => plan_err!("Not implemented: {}", field.data_type())?,}}}diff --git a/datafusion/expr/src/aggregate_function.rs b/datafusion/expr/src/aggregate_function.rsindex ac0ac3079e..ec854a6b7d 100644--- a/datafusion/expr/src/aggregate_function.rs+++ b/datafusion/expr/src/aggregate_function.rs@@ -19,7 +19,7 @@use crate::{type_coercion::aggregates::*, Signature, TypeSignature, Volatility};use arrow::datatypes::{DataType, Field};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use std::sync::Arc;use std::{fmt, str::FromStr};use strum_macros::EnumIter;@@ -166,9 +166,7 @@ impl FromStr for AggregateFunction {// other"grouping" => AggregateFunction::Grouping,_ => {- return Err(DataFusionError::Plan(format!(- "There is no built-in function named {name}"- )));+ return plan_err!("There is no built-in function named {name}");}})}diff --git a/datafusion/expr/src/built_in_function.rs b/datafusion/expr/src/built_in_function.rsindex 535ac84457..3bcf0ec4c5 100644--- a/datafusion/expr/src/built_in_function.rs+++ b/datafusion/expr/src/built_in_function.rs@@ -23,7 +23,7 @@ use crate::{conditional_expressions, struct_expressions, Signature, TypeSignature, Volatility,};use arrow::datatypes::{DataType, Field, Fields, IntervalUnit, TimeUnit};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use std::collections::HashMap;use std::fmt;use std::str::FromStr;@@ -483,9 +483,7 @@ impl BuiltinScalarFunction {// or the execution panics.if input_expr_types.is_empty() && !self.supports_zero_argument() {- return Err(DataFusionError::Plan(- self.generate_signature_error_msg(input_expr_types),- ));+ return plan_err!("{}", self.generate_signature_error_msg(input_expr_types));}// verify that this is a valid set of data types for this function@@ -1353,9 +1351,7 @@ impl FromStr for BuiltinScalarFunction {if let Some(func) = NAME_TO_FUNCTION.get(name) {Ok(*func)} else {- Err(DataFusionError::Plan(format!(- "There is no built-in function named {name}"- )))+ plan_err!("There is no built-in function named {name}")}}}diff --git a/datafusion/expr/src/conditional_expressions.rs b/datafusion/expr/src/conditional_expressions.rsindex aba4406138..c31bd04eaf 100644--- a/datafusion/expr/src/conditional_expressions.rs+++ b/datafusion/expr/src/conditional_expressions.rs@@ -19,7 +19,7 @@use crate::expr::Case;use crate::{expr_schema::ExprSchemable, Expr};use arrow::datatypes::DataType;-use datafusion_common::{DFSchema, DataFusionError, Result};+use datafusion_common::{plan_err, DFSchema, DataFusionError, Result};use std::collections::HashSet;/// Currently supported types by the coalesce function.@@ -102,9 +102,9 @@ impl CaseBuilder {} else {let unique_types: HashSet<&DataType> = then_types.iter().collect();if unique_types.len() != 1 {- return Err(DataFusionError::Plan(format!(+ return plan_err!("CASE expression 'then' values had multiple data types: {unique_types:?}"- )));+ );}}diff --git a/datafusion/expr/src/expr.rs b/datafusion/expr/src/expr.rsindex 485b91141f..ce916e1731 100644--- a/datafusion/expr/src/expr.rs+++ b/datafusion/expr/src/expr.rs@@ -915,7 +915,7 @@ impl Expr {pub fn try_into_col(&self) -> Result<Column> {match self {Expr::Column(it) => Ok(it.clone()),- _ => plan_err!(format!("Could not coerce '{self}' into Column!")),+ _ => plan_err!("Could not coerce '{self}' into Column!"),}}diff --git a/datafusion/expr/src/expr_schema.rs b/datafusion/expr/src/expr_schema.rsindex 4a2673bcc9..e988ed8c3f 100644--- a/datafusion/expr/src/expr_schema.rs+++ b/datafusion/expr/src/expr_schema.rs@@ -25,7 +25,9 @@ use crate::type_coercion::binary::get_result_type;use crate::{LogicalPlan, Projection, Subquery};use arrow::compute::can_cast_types;use arrow::datatypes::DataType;-use datafusion_common::{Column, DFField, DFSchema, DataFusionError, ExprSchema, Result};+use datafusion_common::{+ plan_err, Column, DFField, DFSchema, DataFusionError, ExprSchema, Result,+};use std::collections::HashMap;use std::sync::Arc;@@ -330,9 +332,7 @@ impl ExprSchemable for Expr {_ => Ok(Expr::Cast(Cast::new(Box::new(self), cast_to_type.clone()))),}} else {- Err(DataFusionError::Plan(format!(- "Cannot automatically convert {this_type:?} to {cast_to_type:?}"- )))+ plan_err!("Cannot automatically convert {this_type:?} to {cast_to_type:?}")}}}diff --git a/datafusion/expr/src/field_util.rs b/datafusion/expr/src/field_util.rsindex feb96928c1..2af2422297 100644--- a/datafusion/expr/src/field_util.rs+++ b/datafusion/expr/src/field_util.rs@@ -18,7 +18,7 @@//! Utility functions for complex field accessuse arrow::datatypes::{DataType, Field};-use datafusion_common::{DataFusionError, Result, ScalarValue};+use datafusion_common::{plan_err, DataFusionError, Result, ScalarValue};/// Returns the field access indexed by `key` from a [`DataType::List`] or [`DataType::Struct`]/// # Error@@ -32,22 +32,20 @@ pub fn get_indexed_field(data_type: &DataType, key: &ScalarValue) -> Result<Fiel}(DataType::Struct(fields), ScalarValue::Utf8(Some(s))) => {if s.is_empty() {- Err(DataFusionError::Plan(- "Struct based indexed access requires a non empty string".to_string(),- ))+ plan_err!(+ "Struct based indexed access requires a non empty string"+ )} else {let field = fields.iter().find(|f| f.name() == s);field.ok_or(DataFusionError::Plan(format!("Field {s} not found in struct"))).map(|f| f.as_ref().clone())}}- (DataType::Struct(_), _) => Err(DataFusionError::Plan(- "Only utf8 strings are valid as an indexed field in a struct".to_string(),- )),- (DataType::List(_), _) => Err(DataFusionError::Plan(- "Only ints are valid as an indexed field in a list".to_string(),- )),- (other, _) => Err(DataFusionError::Plan(- format!("The expression to get an indexed field is only valid for `List` or `Struct` types, got {other}")- )),+ (DataType::Struct(_), _) => plan_err!(+ "Only utf8 strings are valid as an indexed field in a struct"+ ),+ (DataType::List(_), _) => plan_err!(+ "Only ints are valid as an indexed field in a list"+ ),+ (other, _) => plan_err!("The expression to get an indexed field is only valid for `List` or `Struct` types, got {other}"),}}diff --git a/datafusion/expr/src/logical_plan/builder.rs b/datafusion/expr/src/logical_plan/builder.rsindex 4d985456f9..a121553ea5 100644--- a/datafusion/expr/src/logical_plan/builder.rs+++ b/datafusion/expr/src/logical_plan/builder.rs@@ -40,6 +40,7 @@ use crate::{Expr, ExprSchemable, TableSource,};use arrow::datatypes::{DataType, Schema, SchemaRef};+use datafusion_common::plan_err;use datafusion_common::{display::ToStringifiedPlan, Column, DFField, DFSchema, DFSchemaRef, DataFusionError,FunctionalDependencies, OwnedTableReference, Result, ScalarValue, TableReference,@@ -128,13 +129,11 @@ impl LogicalPlanBuilder {/// If the values include params/binders such as $1, $2, $3, etc, then the `param_data_types` should be provided.pub fn values(mut values: Vec<Vec<Expr>>) -> Result<Self> {if values.is_empty() {- return Err(DataFusionError::Plan("Values list cannot be empty".into()));+ return plan_err!("Values list cannot be empty");}let n_cols = values[0].len();if n_cols == 0 {- return Err(DataFusionError::Plan(- "Values list cannot be zero length".into(),- ));+ return plan_err!("Values list cannot be zero length");}let empty_schema = DFSchema::empty();let mut field_types: Vec<Option<DataType>> = Vec::with_capacity(n_cols);@@ -145,12 +144,12 @@ impl LogicalPlanBuilder {let mut nulls: Vec<(usize, usize)> = Vec::new();for (i, row) in values.iter().enumerate() {if row.len() != n_cols {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Inconsistent data length across values list: got {} values in row {} but expected {}",row.len(),i,n_cols- )));+ );}field_types = row.iter()@@ -163,8 +162,7 @@ impl LogicalPlanBuilder {let data_type = expr.get_type(&empty_schema)?;if let Some(prev_data_type) = &field_types[j] {if prev_data_type != &data_type {- let err = format!("Inconsistent data type across values list at row {i} column {j}");- return Err(DataFusionError::Plan(err));+ return plan_err!("Inconsistent data type across values list at row {i} column {j}");}}Ok(Some(data_type))@@ -258,9 +256,7 @@ impl LogicalPlanBuilder {let table_name = table_name.into();if table_name.table().is_empty() {- return Err(DataFusionError::Plan(- "table_name cannot be empty".to_string(),- ));+ return plan_err!("table_name cannot be empty");}let schema = table_source.schema();@@ -505,9 +501,7 @@ impl LogicalPlanBuilder {.map(|col| col.flat_name()).collect::<String>();- Err(DataFusionError::Plan(format!(- "For SELECT DISTINCT, ORDER BY expressions {missing_col_names} must appear in select list",- )))+ plan_err!("For SELECT DISTINCT, ORDER BY expressions {missing_col_names} must appear in select list")}/// Apply a sort@@ -633,9 +627,7 @@ impl LogicalPlanBuilder {null_equals_null: bool,) -> Result<Self> {if join_keys.0.len() != join_keys.1.len() {- return Err(DataFusionError::Plan(- "left_keys and right_keys were not the same length".to_string(),- ));+ return plan_err!("left_keys and right_keys were not the same length");}let filter = if let Some(expr) = filter {@@ -931,9 +923,9 @@ impl LogicalPlanBuilder {let right_len = right_plan.schema().fields().len();if left_len != right_len {- return Err(DataFusionError::Plan(format!(+ return plan_err!("INTERSECT/EXCEPT query must have the same number of columns. Left is {left_len} and right is {right_len}."- )));+ );}let join_keys = left_plan@@ -979,9 +971,7 @@ impl LogicalPlanBuilder {filter: Option<Expr>,) -> Result<Self> {if equi_exprs.0.len() != equi_exprs.1.len() {- return Err(DataFusionError::Plan(- "left_keys and right_keys were not the same length".to_string(),- ));+ return plan_err!("left_keys and right_keys were not the same length");}let join_key_pairs = equi_exprs@@ -1124,12 +1114,10 @@ pub(crate) fn validate_unique_names<'a>(Ok(())},Some((existing_position, existing_expr)) => {- Err(DataFusionError::Plan(- format!("{node_name} require unique expression names \+ plan_err!("{node_name} require unique expression names \but the expression \"{existing_expr}\" at position {existing_position} and \"{expr}\" \- at position {position} have the same name. Consider aliasing (\"AS\") one of them.",+ at position {position} have the same name. Consider aliasing (\"AS\") one of them.")- ))}}})@@ -1168,9 +1156,8 @@ pub fn union(left_plan: LogicalPlan, right_plan: LogicalPlan) -> Result<LogicalP// check union plan length same.let right_col_num = right_plan.schema().fields().len();if right_col_num != left_col_num {- return Err(DataFusionError::Plan(format!(- "Union queries must have the same number of columns, (left is {left_col_num}, right is {right_col_num})")- ));+ return plan_err!(+ "Union queries must have the same number of columns, (left is {left_col_num}, right is {right_col_num})");}// create union schema@@ -1223,7 +1210,7 @@ pub fn union(left_plan: LogicalPlan, right_plan: LogicalPlan) -> Result<LogicalP.collect::<Result<Vec<_>>>()?;if inputs.is_empty() {- return Err(DataFusionError::Plan("Empty UNION".to_string()));+ return plan_err!("Empty UNION");}Ok(LogicalPlan::Union(Union {@@ -1747,9 +1734,7 @@ mod tests {assert_eq!("id", &name);Ok(())}- _ => Err(DataFusionError::Plan(- "Plan should have returned an DataFusionError::SchemaError".to_string(),- )),+ _ => plan_err!("Plan should have returned an DataFusionError::SchemaError"),}}@@ -1776,9 +1761,7 @@ mod tests {assert_eq!("state", &name);Ok(())}- _ => Err(DataFusionError::Plan(- "Plan should have returned an DataFusionError::SchemaError".to_string(),- )),+ _ => plan_err!("Plan should have returned an DataFusionError::SchemaError"),}}diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rsindex c0af08a366..0181f4b567 100644--- a/datafusion/expr/src/logical_plan/plan.rs+++ b/datafusion/expr/src/logical_plan/plan.rs@@ -527,23 +527,23 @@ impl LogicalPlan {LogicalPlan::Prepare(prepare_lp) => {// Verify if the number of params matches the number of valuesif prepare_lp.data_types.len() != param_values.len() {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Expected {} parameters, got {}",prepare_lp.data_types.len(),param_values.len()- )));+ );}// Verify if the types of the params matches the types of the valueslet iter = prepare_lp.data_types.iter().zip(param_values.iter());for (i, (param_type, value)) in iter.enumerate() {if *param_type != value.get_datatype() {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Expected parameter of type {:?}, got {:?} at index {}",param_type,value.get_datatype(),i- )));+ );}}@@ -736,9 +736,7 @@ impl LogicalPlan {match (prev, data_type) {(Some(Some(prev)), Some(dt)) => {if prev != dt {- Err(DataFusionError::Plan(format!(- "Conflicting types for {id}"- )))?;+ plan_err!("Conflicting types for {id}")?;}}(_, Some(dt)) => {@@ -767,9 +765,7 @@ impl LogicalPlan {match &expr {Expr::Placeholder(Placeholder { id, data_type }) => {if id.is_empty() || id == "$0" {- return Err(DataFusionError::Plan(- "Empty placeholder id".to_string(),- ));+ return plan_err!("Empty placeholder id");}// convert id (in format $1, $2, ..) to idx (0, 1, ..)let idx = id[1..].parse::<usize>().map_err(|e| {@@ -1299,7 +1295,7 @@ impl Projection {schema: DFSchemaRef,) -> Result<Self> {if expr.len() != schema.fields().len() {- return Err(DataFusionError::Plan(format!("Projection has mismatch between number of expressions ({}) and number of fields in schema ({})", expr.len(), schema.fields().len())));+ return plan_err!("Projection has mismatch between number of expressions ({}) and number of fields in schema ({})", expr.len(), schema.fields().len());}// Update functional dependencies of `input` according to projection// expressions:@@ -1393,19 +1389,19 @@ impl Filter {// ignore errors resolving the expression against the schema.if let Ok(predicate_type) = predicate.get_type(input.schema()) {if predicate_type != DataType::Boolean {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Cannot create filter with non-boolean predicate '{predicate}' returning {predicate_type}"- )));+ );}}// filter predicates should not be aliasedif let Expr::Alias(Alias { expr, name, .. }) = predicate {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Attempted to create Filter predicate with \expression `{expr}` aliased as '{name}'. Filter predicates should not be \aliased."- )));+ );}Ok(Self { predicate, input })@@ -1650,18 +1646,17 @@ impl Aggregate {schema: DFSchemaRef,) -> Result<Self> {if group_expr.is_empty() && aggr_expr.is_empty() {- return Err(DataFusionError::Plan(+ return plan_err!("Aggregate requires at least one grouping or aggregate expression"- .to_string(),- ));+ );}let group_expr_count = grouping_set_expr_count(&group_expr)?;if schema.fields().len() != group_expr_count + aggr_expr.len() {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Aggregate schema has wrong number of fields. Expected {} got {}",group_expr_count + aggr_expr.len(),schema.fields().len()- )));+ );}let aggregate_func_dependencies =diff --git a/datafusion/expr/src/type_coercion/aggregates.rs b/datafusion/expr/src/type_coercion/aggregates.rsindex 95ca6ab718..f057aaba97 100644--- a/datafusion/expr/src/type_coercion/aggregates.rs+++ b/datafusion/expr/src/type_coercion/aggregates.rs@@ -19,7 +19,7 @@ use arrow::datatypes::{DataType, TimeUnit, DECIMAL128_MAX_PRECISION, DECIMAL128_MAX_SCALE,DECIMAL256_MAX_PRECISION, DECIMAL256_MAX_SCALE,};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use std::ops::Deref;use crate::{AggregateFunction, Signature, TypeSignature};@@ -106,10 +106,11 @@ pub fn coerce_types(// Refer to https://www.postgresql.org/docs/8.2/functions-aggregate.html doc// smallint, int, bigint, real, double precision, decimal, or interval.if !is_sum_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));+ agg_fun,+ input_types[0]+ );}Ok(input_types.to_vec())}@@ -117,10 +118,11 @@ pub fn coerce_types(// Refer to https://www.postgresql.org/docs/8.2/functions-aggregate.html doc// smallint, int, bigint, real, double precision, decimal, or intervalif !is_avg_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));+ agg_fun,+ input_types[0]+ );}Ok(input_types.to_vec())}@@ -130,10 +132,11 @@ pub fn coerce_types(// Refer to https://www.postgresql.org/docs/8.2/functions-aggregate.html doc// smallint, int, bigint, real, double precision, decimal, or interval.if !is_bit_and_or_xor_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));+ agg_fun,+ input_types[0]+ );}Ok(input_types.to_vec())}@@ -141,46 +144,51 @@ pub fn coerce_types(// Refer to https://www.postgresql.org/docs/8.2/functions-aggregate.html doc// smallint, int, bigint, real, double precision, decimal, or interval.if !is_bool_and_or_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));+ agg_fun,+ input_types[0]+ );}Ok(input_types.to_vec())}AggregateFunction::Variance | AggregateFunction::VariancePop => {if !is_variance_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));+ agg_fun,+ input_types[0]+ );}Ok(input_types.to_vec())}AggregateFunction::Covariance | AggregateFunction::CovariancePop => {if !is_covariance_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));+ agg_fun,+ input_types[0]+ );}Ok(input_types.to_vec())}AggregateFunction::Stddev | AggregateFunction::StddevPop => {if !is_stddev_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));+ agg_fun,+ input_types[0]+ );}Ok(input_types.to_vec())}AggregateFunction::Correlation => {if !is_correlation_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));+ agg_fun,+ input_types[0]+ );}Ok(input_types.to_vec())}@@ -189,64 +197,70 @@ pub fn coerce_types(let input_types_valid = // number of input already checked beforevalid_types.contains(&input_types[0]) && valid_types.contains(&input_types[1]);if !input_types_valid {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));+ agg_fun,+ input_types[0]+ );}Ok(input_types.to_vec())}AggregateFunction::ApproxPercentileCont => {if !is_approx_percentile_cont_supported_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));+ agg_fun,+ input_types[0]+ );}if input_types.len() == 3 && !is_integer_arg_type(&input_types[2]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The percentile sample points count for {:?} must be integer, not {:?}.",agg_fun, input_types[2]- )));+ );}let mut result = input_types.to_vec();if can_coerce_from(&DataType::Float64, &input_types[1]) {result[1] = DataType::Float64;} else {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Could not coerce the percent argument for {:?} to Float64. Was {:?}.",agg_fun, input_types[1]- )));+ );}Ok(result)}AggregateFunction::ApproxPercentileContWithWeight => {if !is_approx_percentile_cont_supported_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));+ agg_fun,+ input_types[0]+ );}if !is_approx_percentile_cont_supported_arg_type(&input_types[1]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The weight argument for {:?} does not support inputs of type {:?}.",- agg_fun, input_types[1]- )));+ agg_fun,+ input_types[1]+ );}if !matches!(input_types[2], DataType::Float64) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The percentile argument for {:?} must be Float64, not {:?}.",- agg_fun, input_types[2]- )));+ agg_fun,+ input_types[2]+ );}Ok(input_types.to_vec())}AggregateFunction::ApproxMedian => {if !is_approx_percentile_cont_supported_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));+ agg_fun,+ input_types[0]+ );}Ok(input_types.to_vec())}@@ -270,22 +284,22 @@ fn check_arg_count(match signature {TypeSignature::Uniform(agg_count, _) | TypeSignature::Any(agg_count) => {if input_types.len() != *agg_count {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} expects {:?} arguments, but {:?} were provided",agg_fun,agg_count,input_types.len()- )));+ );}}TypeSignature::Exact(types) => {if types.len() != input_types.len() {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} expects {:?} arguments, but {:?} were provided",agg_fun,types.len(),input_types.len()- )));+ );}}TypeSignature::OneOf(variants) => {@@ -293,18 +307,18 @@ fn check_arg_count(.iter().any(|v| check_arg_count(agg_fun, input_types, v).is_ok());if !ok {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {:?} does not accept {:?} function arguments.",agg_fun,input_types.len()- )));+ );}}TypeSignature::VariadicAny => {if input_types.is_empty() {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function {agg_fun:?} expects at least one argument"- )));+ );}}_ => {@@ -355,9 +369,7 @@ pub fn sum_return_type(arg_type: &DataType) -> Result<DataType> {DataType::Dictionary(_, dict_value_type) => {sum_return_type(dict_value_type.as_ref())}- other => Err(DataFusionError::Plan(format!(- "SUM does not support type \"{other:?}\""- ))),+ other => plan_err!("SUM does not support type \"{other:?}\""),}}@@ -366,9 +378,7 @@ pub fn variance_return_type(arg_type: &DataType) -> Result<DataType> {if NUMERICS.contains(arg_type) {Ok(DataType::Float64)} else {- Err(DataFusionError::Plan(format!(- "VAR does not support {arg_type:?}"- )))+ plan_err!("VAR does not support {arg_type:?}")}}@@ -377,9 +387,7 @@ pub fn covariance_return_type(arg_type: &DataType) -> Result<DataType> {if NUMERICS.contains(arg_type) {Ok(DataType::Float64)} else {- Err(DataFusionError::Plan(format!(- "COVAR does not support {arg_type:?}"- )))+ plan_err!("COVAR does not support {arg_type:?}")}}@@ -388,9 +396,7 @@ pub fn correlation_return_type(arg_type: &DataType) -> Result<DataType> {if NUMERICS.contains(arg_type) {Ok(DataType::Float64)} else {- Err(DataFusionError::Plan(format!(- "CORR does not support {arg_type:?}"- )))+ plan_err!("CORR does not support {arg_type:?}")}}@@ -399,9 +405,7 @@ pub fn stddev_return_type(arg_type: &DataType) -> Result<DataType> {if NUMERICS.contains(arg_type) {Ok(DataType::Float64)} else {- Err(DataFusionError::Plan(format!(- "STDDEV does not support {arg_type:?}"- )))+ plan_err!("STDDEV does not support {arg_type:?}")}}@@ -426,9 +430,7 @@ pub fn avg_return_type(arg_type: &DataType) -> Result<DataType> {DataType::Dictionary(_, dict_value_type) => {avg_return_type(dict_value_type.as_ref())}- other => Err(DataFusionError::Plan(format!(- "AVG does not support {other:?}"- ))),+ other => plan_err!("AVG does not support {other:?}"),}}@@ -449,9 +451,7 @@ pub fn avg_sum_type(arg_type: &DataType) -> Result<DataType> {DataType::Dictionary(_, dict_value_type) => {avg_sum_type(dict_value_type.as_ref())}- other => Err(DataFusionError::Plan(format!(- "AVG does not support {other:?}"- ))),+ other => plan_err!("AVG does not support {other:?}"),}}diff --git a/datafusion/expr/src/type_coercion/binary.rs b/datafusion/expr/src/type_coercion/binary.rsindex 0113408fcc..602448f1a2 100644--- a/datafusion/expr/src/type_coercion/binary.rs+++ b/datafusion/expr/src/type_coercion/binary.rs@@ -23,8 +23,8 @@ use arrow::datatypes::{DECIMAL256_MAX_PRECISION, DECIMAL256_MAX_SCALE,};-use datafusion_common::DataFusionError;use datafusion_common::Result;+use datafusion_common::{plan_err, DataFusionError};use crate::type_coercion::is_numeric;use crate::Operator;@@ -82,9 +82,9 @@ fn signature(lhs: &DataType, op: &Operator, rhs: &DataType) -> Result<Signature>| (DataType::Null, DataType::Null)| (DataType::Boolean, DataType::Null)| (DataType::Null, DataType::Boolean) => Ok(Signature::uniform(DataType::Boolean)),- _ => Err(DataFusionError::Plan(format!(+ _ => plan_err!("Cannot infer common argument type for logical boolean operation {lhs} {op} {rhs}"- ))),+ ),},Operator::RegexMatch |Operator::RegexIMatch |@@ -164,9 +164,9 @@ fn signature(lhs: &DataType, op: &Operator, rhs: &DataType) -> Result<Signature>// Numeric arithmetic, e.g. Int32 + Int32Ok(Signature::uniform(numeric))} else {- Err(DataFusionError::Plan(format!(+ plan_err!("Cannot coerce arithmetic expression {lhs} {op} {rhs} to valid types"- )))+ )}}}diff --git a/datafusion/expr/src/type_coercion/functions.rs b/datafusion/expr/src/type_coercion/functions.rsindex d86914325f..371a3950ac 100644--- a/datafusion/expr/src/type_coercion/functions.rs+++ b/datafusion/expr/src/type_coercion/functions.rs@@ -20,7 +20,7 @@ use arrow::{compute::can_cast_types,datatypes::{DataType, TimeUnit},};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};/// Performs type coercion for function arguments.///@@ -52,10 +52,11 @@ pub fn data_types(}// none possible -> Error- Err(DataFusionError::Plan(format!(+ plan_err!("Coercion from {:?} to the signature {:?} failed.",- current_types, &signature.type_signature- )))+ current_types,+ &signature.type_signature+ )}fn get_valid_types(@@ -84,11 +85,11 @@ fn get_valid_types(TypeSignature::Exact(valid_types) => vec![valid_types.clone()],TypeSignature::Any(number) => {if current_types.len() != *number {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The function expected {} arguments but received {}",number,current_types.len()- )));+ );}vec![(0..*number).map(|i| current_types[i].clone()).collect()]}diff --git a/datafusion/expr/src/utils.rs b/datafusion/expr/src/utils.rsindex efaf291398..8940eeed01 100644--- a/datafusion/expr/src/utils.rs+++ b/datafusion/expr/src/utils.rs@@ -34,8 +34,8 @@ use datafusion_common::tree_node::{RewriteRecursion, TreeNode, TreeNodeRewriter, VisitRecursion,};use datafusion_common::{- Column, Constraints, DFField, DFSchema, DFSchemaRef, DataFusionError, Result,- ScalarValue, TableReference,+ plan_err, Column, Constraints, DFField, DFSchema, DFSchemaRef, DataFusionError,+ Result, ScalarValue, TableReference,};use sqlparser::ast::{ExceptSelectItem, ExcludeSelectItem, WildcardAdditionalOptions};use std::cmp::Ordering;@@ -60,10 +60,9 @@ pub fn exprlist_to_columns(expr: &[Expr], accum: &mut HashSet<Column>) -> Resultpub fn grouping_set_expr_count(group_expr: &[Expr]) -> Result<usize> {if let Some(Expr::GroupingSet(grouping_set)) = group_expr.first() {if group_expr.len() > 1 {- return Err(DataFusionError::Plan(+ return plan_err!("Invalid group by expressions, GroupingSet must be the only expression"- .to_string(),- ));+ );}Ok(grouping_set.distinct_expr().len())} else {@@ -114,7 +113,7 @@ fn powerset<T>(slice: &[T]) -> Result<Vec<Vec<&T>>, String> {fn check_grouping_set_size_limit(size: usize) -> Result<()> {let max_grouping_set_size = 65535;if size > max_grouping_set_size {- return Err(DataFusionError::Plan(format!("The number of group_expression in grouping_set exceeds the maximum limit {max_grouping_set_size}, found {size}")));+ return plan_err!("The number of group_expression in grouping_set exceeds the maximum limit {max_grouping_set_size}, found {size}");}Ok(())@@ -124,7 +123,7 @@ fn check_grouping_set_size_limit(size: usize) -> Result<()> {fn check_grouping_sets_size_limit(size: usize) -> Result<()> {let max_grouping_sets_size = 4096;if size > max_grouping_sets_size {- return Err(DataFusionError::Plan(format!("The number of grouping_set in grouping_sets exceeds the maximum limit {max_grouping_sets_size}, found {size}")));+ return plan_err!("The number of grouping_set in grouping_sets exceeds the maximum limit {max_grouping_sets_size}, found {size}");}Ok(())@@ -252,10 +251,9 @@ pub fn enumerate_grouping_sets(group_expr: Vec<Expr>) -> Result<Vec<Expr>> {pub fn grouping_set_to_exprlist(group_expr: &[Expr]) -> Result<Vec<Expr>> {if let Some(Expr::GroupingSet(grouping_set)) = group_expr.first() {if group_expr.len() > 1 {- return Err(DataFusionError::Plan(+ return plan_err!("Invalid group by expressions, GroupingSet must be the only expression"- .to_string(),- ));+ );}Ok(grouping_set.distinct_expr())} else {@@ -340,9 +338,7 @@ fn get_excluded_columns(// if HashSet size, and vector length are different, this means that some of the excluded columns// are not unique. In this case return error.if n_elem != unique_idents.len() {- return Err(DataFusionError::Plan(- "EXCLUDE or EXCEPT contains duplicate column names".to_string(),- ));+ return plan_err!("EXCLUDE or EXCEPT contains duplicate column names");}let mut result = vec![];@@ -441,9 +437,7 @@ pub fn expand_qualified_wildcard(.cloned().collect();if qualified_fields.is_empty() {- return Err(DataFusionError::Plan(format!(- "Invalid qualifier {qualifier}"- )));+ return plan_err!("Invalid qualifier {qualifier}");}let qualified_schema =DFSchema::new_with_metadata(qualified_fields, schema.metadata().clone())?@@ -480,9 +474,7 @@ pub fn generate_sort_key(Expr::Sort(Sort { expr, .. }) => {Ok(Expr::Sort(Sort::new(expr.clone(), true, false)))}- _ => Err(DataFusionError::Plan(- "Order by only accepts sort expressions".to_string(),- )),+ _ => plan_err!("Order by only accepts sort expressions"),}).collect::<Result<Vec<_>>>()?;@@ -964,15 +956,11 @@ pub fn from_plan(// If this check cannot pass it means some optimizer pass is// trying to optimize Explain directlyif expr.is_empty() {- return Err(DataFusionError::Plan(- "Invalid EXPLAIN command. Expression is empty".to_string(),- ));+ return plan_err!("Invalid EXPLAIN command. Expression is empty");}if inputs.is_empty() {- return Err(DataFusionError::Plan(- "Invalid EXPLAIN command. Inputs are empty".to_string(),- ));+ return plan_err!("Invalid EXPLAIN command. Inputs are empty");}Ok(plan.clone())diff --git a/datafusion/expr/src/window_frame.rs b/datafusion/expr/src/window_frame.rsindex b2d1882788..5c9cfcae66 100644--- a/datafusion/expr/src/window_frame.rs+++ b/datafusion/expr/src/window_frame.rs@@ -23,7 +23,7 @@//! - An ending frame boundary,//! - An EXCLUDE clause.-use datafusion_common::{DataFusionError, Result, ScalarValue};+use datafusion_common::{plan_err, DataFusionError, Result, ScalarValue};use sqlparser::ast;use sqlparser::parser::ParserError::ParserError;use std::convert::{From, TryFrom};@@ -68,14 +68,14 @@ impl TryFrom<ast::WindowFrame> for WindowFrame {if let WindowFrameBound::Following(val) = &start_bound {if val.is_null() {- plan_error(- "Invalid window frame: start bound cannot be UNBOUNDED FOLLOWING",+ plan_err!(+ "Invalid window frame: start bound cannot be UNBOUNDED FOLLOWING")?}} else if let WindowFrameBound::Preceding(val) = &end_bound {if val.is_null() {- plan_error(- "Invalid window frame: end bound cannot be UNBOUNDED PRECEDING",+ plan_err!(+ "Invalid window frame: end bound cannot be UNBOUNDED PRECEDING")?}};@@ -161,10 +161,10 @@ pub fn regularize(mut frame: WindowFrame, order_bys: usize) -> Result<WindowFramframe.end_bound = WindowFrameBound::Following(ScalarValue::UInt64(None));}} else {- plan_error("RANGE requires exactly one ORDER BY column")?+ plan_err!("RANGE requires exactly one ORDER BY column")?}} else if frame.units == WindowFrameUnits::Groups && order_bys == 0 {- plan_error("GROUPS requires an ORDER BY clause")?+ plan_err!("GROUPS requires an ORDER BY clause")?};Ok(frame)}@@ -252,16 +252,12 @@ pub fn convert_frame_bound_to_scalar_value(v: ast::Expr) -> Result<ScalarValue>result}}- _ => plan_error(- "Invalid window frame: frame offsets must be non negative integers",+ _ => plan_err!(+ "Invalid window frame: frame offsets must be non negative integers")?,})))}-fn plan_error<T>(err_message: &str) -> Result<T> {- Err(DataFusionError::Plan(err_message.to_string()))-}-impl fmt::Display for WindowFrameBound {fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {match self {diff --git a/datafusion/expr/src/window_function.rs b/datafusion/expr/src/window_function.rsindex 1c847a4541..89c59baa4c 100644--- a/datafusion/expr/src/window_function.rs+++ b/datafusion/expr/src/window_function.rs@@ -24,7 +24,7 @@ use crate::aggregate_function::AggregateFunction;use crate::type_coercion::functions::data_types;use crate::{AggregateUDF, Signature, TypeSignature, Volatility, WindowUDF};use arrow::datatypes::DataType;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use std::sync::Arc;use std::{fmt, str::FromStr};use strum_macros::EnumIter;@@ -145,11 +145,7 @@ impl FromStr for BuiltInWindowFunction {"FIRST_VALUE" => BuiltInWindowFunction::FirstValue,"LAST_VALUE" => BuiltInWindowFunction::LastValue,"NTH_VALUE" => BuiltInWindowFunction::NthValue,- _ => {- return Err(DataFusionError::Plan(format!(- "There is no built-in window function named {name}"- )))- }+ _ => return plan_err!("There is no built-in window function named {name}"),})}}diff --git a/datafusion/optimizer/src/analyzer/subquery.rs b/datafusion/optimizer/src/analyzer/subquery.rsindex c36a74c328..fee6377114 100644--- a/datafusion/optimizer/src/analyzer/subquery.rs+++ b/datafusion/optimizer/src/analyzer/subquery.rs@@ -18,7 +18,7 @@use crate::analyzer::check_plan;use crate::utils::{collect_subquery_cols, split_conjunction};use datafusion_common::tree_node::{TreeNode, VisitRecursion};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_expr::expr_rewriter::strip_outer_reference;use datafusion_expr::{Aggregate, BinaryExpr, Cast, Expr, Filter, Join, JoinType, LogicalPlan, Operator,@@ -42,11 +42,11 @@ pub fn check_subquery_expr(if let Expr::ScalarSubquery(subquery) = expr {// Scalar subquery should only return one columnif subquery.subquery.schema().fields().len() > 1 {- return Err(datafusion_common::DataFusionError::Plan(format!(+ return plan_err!("Scalar subquery should only return one column, but found {}: {}",subquery.subquery.schema().fields().len(),- subquery.subquery.schema().field_names().join(", "),- )));+ subquery.subquery.schema().field_names().join(", ")+ );}// Correlated scalar subquery must be aggregated to return at most one rowif !subquery.outer_ref_columns.is_empty() {@@ -71,10 +71,9 @@ pub fn check_subquery_expr({Ok(())} else {- Err(DataFusionError::Plan(+ plan_err!("Correlated scalar subquery must be aggregated to return at most one row"- .to_string(),- ))+ )}}}?;@@ -84,18 +83,16 @@ pub fn check_subquery_expr(LogicalPlan::Aggregate(Aggregate {group_expr, aggr_expr,..}) => {if group_expr.contains(expr) && !aggr_expr.contains(expr) {// TODO revisit this validation logic- Err(DataFusionError::Plan(+ plan_err!("Correlated scalar subquery in the GROUP BY clause must also be in the aggregate expressions"- .to_string(),- ))+ )} else {Ok(())}},- _ => Err(DataFusionError::Plan(+ _ => plan_err!("Correlated scalar subquery can only be used in Projection, Filter, Aggregate plan nodes"- .to_string(),- ))+ )}?;}check_correlations_in_subquery(inner_plan, true)@@ -103,11 +100,11 @@ pub fn check_subquery_expr(if let Expr::InSubquery(subquery) = expr {// InSubquery should only return one columnif subquery.subquery.subquery.schema().fields().len() > 1 {- return Err(datafusion_common::DataFusionError::Plan(format!(+ return plan_err!("InSubquery should only return one column, but found {}: {}",subquery.subquery.subquery.schema().fields().len(),- subquery.subquery.subquery.schema().field_names().join(", "),- )));+ subquery.subquery.subquery.schema().field_names().join(", ")+ );}}match outer_plan {@@ -116,11 +113,10 @@ pub fn check_subquery_expr(| LogicalPlan::Window(_)| LogicalPlan::Aggregate(_)| LogicalPlan::Join(_) => Ok(()),- _ => Err(DataFusionError::Plan(+ _ => plan_err!("In/Exist subquery can only be used in \Projection, Filter, Window functions, Aggregate and Join plan nodes"- .to_string(),- )),+ ),}?;check_correlations_in_subquery(inner_plan, false)}@@ -142,9 +138,7 @@ fn check_inner_plan(can_contain_outer_ref: bool,) -> Result<()> {if !can_contain_outer_ref && contains_outer_reference(inner_plan) {- return Err(DataFusionError::Plan(- "Accessing outer reference columns is not allowed in the plan".to_string(),- ));+ return plan_err!("Accessing outer reference columns is not allowed in the plan");}// We want to support as many operators as possible inside the correlated subquerymatch inner_plan {@@ -166,9 +160,9 @@ fn check_inner_plan(.filter(|expr| !can_pullup_over_aggregation(expr)).collect::<Vec<_>>();if is_aggregate && is_scalar && !maybe_unsupport.is_empty() {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Correlated column is not allowed in predicate: {predicate}"- )));+ );}check_inner_plan(input, is_scalar, is_aggregate, can_contain_outer_ref)}@@ -231,9 +225,7 @@ fn check_inner_plan(Ok(())}},- _ => Err(DataFusionError::Plan(- "Unsupported operator in the subquery plan.".to_string(),- )),+ _ => plan_err!("Unsupported operator in the subquery plan."),}}@@ -249,10 +241,9 @@ fn check_aggregation_in_scalar_subquery(agg: &Aggregate,) -> Result<()> {if agg.aggr_expr.is_empty() {- return Err(DataFusionError::Plan(+ return plan_err!("Correlated scalar subquery must be aggregated to return at most one row"- .to_string(),- ));+ );}if !agg.group_expr.is_empty() {let correlated_exprs = get_correlated_expressions(inner_plan)?;@@ -268,10 +259,9 @@ fn check_aggregation_in_scalar_subquery(if !group_columns.all(|group| inner_subquery_cols.contains(&group)) {// Group BY columns must be a subset of columns in the correlated expressions- return Err(DataFusionError::Plan(+ return plan_err!("A GROUP BY clause in a scalar correlated subquery cannot contain non-correlated columns"- .to_string(),- ));+ );}}Ok(())@@ -341,10 +331,9 @@ fn check_mixed_out_refer_in_window(window: &Window) -> Result<()> {win_expr.contains_outer() && !win_expr.to_columns().unwrap().is_empty()});if mixed {- Err(DataFusionError::Plan(+ plan_err!("Window expressions should not contain a mixed of outer references and inner columns"- .to_string(),- ))+ )} else {Ok(())}diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rsindex 2bd7fd67d8..9d313e8474 100644--- a/datafusion/optimizer/src/analyzer/type_coercion.rs+++ b/datafusion/optimizer/src/analyzer/type_coercion.rs@@ -23,7 +23,9 @@ use arrow::datatypes::{DataType, IntervalUnit};use datafusion_common::config::ConfigOptions;use datafusion_common::tree_node::{RewriteRecursion, TreeNodeRewriter};-use datafusion_common::{DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue};+use datafusion_common::{+ plan_err, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue,+};use datafusion_expr::expr::{self, Between, BinaryExpr, Case, Exists, InList, InSubquery, Like, ScalarFunction,ScalarUDF, WindowFunction,@@ -293,9 +295,9 @@ impl TreeNodeRewriter for TypeCoercionRewriter {let result_type =get_coerce_type_for_list(&expr_data_type, &list_data_types);match result_type {- None => Err(DataFusionError::Plan(format!(+ None => plan_err!("Can not find compatible types to compare {expr_data_type:?} with {list_data_types:?}"- ))),+ ),Some(coerced_type) => {// find the coerced typelet cast_expr = expr.cast_to(&coerced_type, &self.schema)?;diff --git a/datafusion/optimizer/src/decorrelate.rs b/datafusion/optimizer/src/decorrelate.rsindex 8cd90072ff..b5cf737338 100644--- a/datafusion/optimizer/src/decorrelate.rs+++ b/datafusion/optimizer/src/decorrelate.rs@@ -22,7 +22,7 @@ use crate::utils::{use datafusion_common::tree_node::{RewriteRecursion, Transformed, TreeNode, TreeNodeRewriter,};-use datafusion_common::Result;+use datafusion_common::{plan_err, Result};use datafusion_common::{Column, DFSchemaRef, DataFusionError, ScalarValue};use datafusion_expr::expr::Alias;use datafusion_expr::{expr, EmptyRelation, Expr, LogicalPlan, LogicalPlanBuilder};@@ -132,9 +132,7 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {match (&pull_up_expr_opt, &self.pull_up_having_expr) {(Some(_), Some(_)) => {// Error path- Err(DataFusionError::Plan(- "Unsupported Subquery plan".to_string(),- ))+ plan_err!("Unsupported Subquery plan")}(Some(_), None) => {self.pull_up_having_expr = pull_up_expr_opt;diff --git a/datafusion/optimizer/src/decorrelate_predicate_subquery.rs b/datafusion/optimizer/src/decorrelate_predicate_subquery.rsindex d3500304af..432d7f053a 100644--- a/datafusion/optimizer/src/decorrelate_predicate_subquery.rs+++ b/datafusion/optimizer/src/decorrelate_predicate_subquery.rs@@ -21,7 +21,7 @@ use crate::utils::{conjunction, replace_qualified_name, split_conjunction};use crate::{OptimizerConfig, OptimizerRule};use datafusion_common::alias::AliasGenerator;use datafusion_common::tree_node::TreeNode;-use datafusion_common::{Column, DataFusionError, Result};+use datafusion_common::{plan_err, Column, DataFusionError, Result};use datafusion_expr::expr::{Exists, InSubquery};use datafusion_expr::expr_rewriter::create_col_from_scalar_expr;use datafusion_expr::logical_plan::{JoinType, Subquery};@@ -204,12 +204,13 @@ fn build_join(let in_predicate_opt = where_in_expr_opt.clone().map(|where_in_expr| {- query_info.query.subquery.head_output_expr()?.map_or(- Err(DataFusionError::Plan(- "single expression required.".to_string(),- )),- |expr| Ok(Expr::eq(where_in_expr, expr)),- )+ query_info+ .query+ .subquery+ .head_output_expr()?+ .map_or(plan_err!("single expression required."), |expr| {+ Ok(Expr::eq(where_in_expr, expr))+ })}).map_or(Ok(None), |v| v.map(Some))?;diff --git a/datafusion/optimizer/src/eliminate_cross_join.rs b/datafusion/optimizer/src/eliminate_cross_join.rsindex 533566a0bf..ec4d8a2cbf 100644--- a/datafusion/optimizer/src/eliminate_cross_join.rs+++ b/datafusion/optimizer/src/eliminate_cross_join.rs@@ -20,7 +20,7 @@ use std::collections::HashSet;use std::sync::Arc;use crate::{utils, OptimizerConfig, OptimizerRule};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_expr::expr::{BinaryExpr, Expr};use datafusion_expr::logical_plan::{CrossJoin, Filter, Join, JoinConstraint, JoinType, LogicalPlan, Projection,@@ -155,9 +155,7 @@ fn flatten_join_inputs(vec![left, right]}_ => {- return Err(DataFusionError::Plan(- "flatten_join_inputs just can call join/cross_join".to_string(),- ));+ return plan_err!("flatten_join_inputs just can call join/cross_join");}};diff --git a/datafusion/optimizer/src/optimizer.rs b/datafusion/optimizer/src/optimizer.rsindex 920b9ea18f..caac4c34bd 100644--- a/datafusion/optimizer/src/optimizer.rs+++ b/datafusion/optimizer/src/optimizer.rs@@ -447,7 +447,9 @@ mod tests {use crate::optimizer::Optimizer;use crate::test::test_table_scan;use crate::{OptimizerConfig, OptimizerContext, OptimizerRule};- use datafusion_common::{DFField, DFSchema, DFSchemaRef, DataFusionError, Result};+ use datafusion_common::{+ plan_err, DFField, DFSchema, DFSchemaRef, DataFusionError, Result,+ };use datafusion_expr::logical_plan::EmptyRelation;use datafusion_expr::{col, lit, LogicalPlan, LogicalPlanBuilder, Projection};use std::sync::{Arc, Mutex};@@ -613,7 +615,7 @@ mod tests {_: &LogicalPlan,_: &dyn OptimizerConfig,) -> Result<Option<LogicalPlan>> {- Err(DataFusionError::Plan("rule failed".to_string()))+ plan_err!("rule failed")}fn name(&self) -> &str {diff --git a/datafusion/optimizer/src/propagate_empty_relation.rs b/datafusion/optimizer/src/propagate_empty_relation.rsindex 01e16058ec..4de7596b32 100644--- a/datafusion/optimizer/src/propagate_empty_relation.rs+++ b/datafusion/optimizer/src/propagate_empty_relation.rs@@ -15,7 +15,7 @@// specific language governing permissions and limitations// under the License.-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_expr::logical_plan::LogicalPlan;use datafusion_expr::{EmptyRelation, JoinType, Projection, Union};use std::sync::Arc;@@ -156,9 +156,7 @@ fn binary_plan_children_is_empty(plan: &LogicalPlan) -> Result<(bool, bool)> {};Ok((left_empty, right_empty))}- _ => Err(DataFusionError::Plan(- "plan just can have two child".to_string(),- )),+ _ => plan_err!("plan just can have two child"),}}@@ -177,9 +175,7 @@ fn empty_child(plan: &LogicalPlan) -> Result<Option<LogicalPlan>> {}_ => Ok(None),},- _ => Err(DataFusionError::Plan(- "plan just can have one child".to_string(),- )),+ _ => plan_err!("plan just can have one child"),}}diff --git a/datafusion/optimizer/src/push_down_projection.rs b/datafusion/optimizer/src/push_down_projection.rsindex eb9ae3c981..0469f678e0 100644--- a/datafusion/optimizer/src/push_down_projection.rs+++ b/datafusion/optimizer/src/push_down_projection.rs@@ -26,7 +26,7 @@ use crate::{OptimizerConfig, OptimizerRule};use arrow::error::Result as ArrowResult;use datafusion_common::ScalarValue::UInt8;use datafusion_common::{- Column, DFField, DFSchema, DFSchemaRef, DataFusionError, Result, ToDFSchema,+ plan_err, Column, DFField, DFSchema, DFSchemaRef, DataFusionError, Result, ToDFSchema,};use datafusion_expr::expr::{AggregateFunction, Alias};use datafusion_expr::utils::exprlist_to_fields;@@ -443,9 +443,7 @@ fn get_expr(columns: &HashSet<Column>, schema: &DFSchemaRef) -> Result<Vec<Expr>}).collect::<Vec<Expr>>();if columns.len() != expr.len() {- Err(DataFusionError::Plan(format!(- "required columns can't push down, columns: {columns:?}"- )))+ plan_err!("required columns can't push down, columns: {columns:?}")} else {Ok(expr)}diff --git a/datafusion/optimizer/src/scalar_subquery_to_join.rs b/datafusion/optimizer/src/scalar_subquery_to_join.rsindex 357a2775cc..96d2f45d80 100644--- a/datafusion/optimizer/src/scalar_subquery_to_join.rs+++ b/datafusion/optimizer/src/scalar_subquery_to_join.rs@@ -23,7 +23,7 @@ use datafusion_common::alias::AliasGenerator;use datafusion_common::tree_node::{RewriteRecursion, Transformed, TreeNode, TreeNodeRewriter,};-use datafusion_common::{Column, DataFusionError, Result, ScalarValue};+use datafusion_common::{plan_err, Column, DataFusionError, Result, ScalarValue};use datafusion_expr::expr_rewriter::create_col_from_scalar_expr;use datafusion_expr::logical_plan::{JoinType, Subquery};use datafusion_expr::{expr, EmptyRelation, Expr, LogicalPlan, LogicalPlanBuilder};@@ -215,12 +215,10 @@ impl TreeNodeRewriter for ExtractScalarSubQuery {let subqry_alias = self.alias_gen.next("__scalar_sq");self.sub_query_info.push((subquery.clone(), subqry_alias.clone()));- let scalar_expr = subquery.subquery.head_output_expr()?.map_or(- Err(DataFusionError::Plan(- "single expression required.".to_string(),- )),- Ok,- )?;+ let scalar_expr = subquery+ .subquery+ .head_output_expr()?+ .map_or(plan_err!("single expression required."), Ok)?;Ok(Expr::Column(create_col_from_scalar_expr(&scalar_expr,subqry_alias,diff --git a/datafusion/optimizer/src/utils.rs b/datafusion/optimizer/src/utils.rsindex adb3bf6302..a3e7e42875 100644--- a/datafusion/optimizer/src/utils.rs+++ b/datafusion/optimizer/src/utils.rs@@ -18,6 +18,7 @@//! Collection of utility functions that are leveraged by the query optimizer rulesuse crate::{OptimizerConfig, OptimizerRule};+use datafusion_common::DataFusionError;use datafusion_common::{plan_err, Column, DFSchemaRef};use datafusion_common::{DFSchema, Result};use datafusion_expr::expr::{Alias, BinaryExpr};diff --git a/datafusion/optimizer/tests/optimizer_integration.rs b/datafusion/optimizer/tests/optimizer_integration.rsindex 8027e6882e..142ae870d4 100644--- a/datafusion/optimizer/tests/optimizer_integration.rs+++ b/datafusion/optimizer/tests/optimizer_integration.rs@@ -18,7 +18,7 @@use arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit};use chrono::{DateTime, NaiveDateTime, Utc};use datafusion_common::config::ConfigOptions;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_expr::{AggregateUDF, LogicalPlan, ScalarUDF, TableSource, WindowUDF};use datafusion_optimizer::analyzer::Analyzer;use datafusion_optimizer::optimizer::Optimizer;@@ -392,7 +392,7 @@ impl ContextProvider for MySchemaProvider {schema: Arc::new(schema),}))} else {- Err(DataFusionError::Plan("table does not exist".to_string()))+ plan_err!("table does not exist")}}diff --git a/datafusion/physical-expr/src/aggregate/approx_percentile_cont.rs b/datafusion/physical-expr/src/aggregate/approx_percentile_cont.rsindex f0a44cc97a..46825a5fc0 100644--- a/datafusion/physical-expr/src/aggregate/approx_percentile_cont.rs+++ b/datafusion/physical-expr/src/aggregate/approx_percentile_cont.rs@@ -27,6 +27,7 @@ use arrow::{},datatypes::{DataType, Field},};+use datafusion_common::plan_err;use datafusion_common::DataFusionError;use datafusion_common::Result;use datafusion_common::{downcast_value, ScalarValue};@@ -152,9 +153,9 @@ fn validate_input_percentile_expr(expr: &Arc<dyn PhysicalExpr>) -> Result<f64> {// Ensure the percentile is between 0 and 1.if !(0.0..=1.0).contains(&percentile) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Percentile value must be between 0.0 and 1.0 inclusive, {percentile} is invalid"- )));+ );}Ok(percentile)}diff --git a/datafusion/physical-expr/src/aggregate/build_in.rs b/datafusion/physical-expr/src/aggregate/build_in.rsindex 45c98b0187..ca799f755a 100644--- a/datafusion/physical-expr/src/aggregate/build_in.rs+++ b/datafusion/physical-expr/src/aggregate/build_in.rs@@ -344,6 +344,7 @@ mod tests {DistinctArrayAgg, DistinctCount, Max, Min, Stddev, Sum, Variance,};use arrow::datatypes::{DataType, Field};+ use datafusion_common::plan_err;use datafusion_common::ScalarValue;use datafusion_expr::type_coercion::aggregates::NUMERICS;use datafusion_expr::{type_coercion, Signature};@@ -1224,9 +1225,9 @@ mod tests {let coerced_phy_exprs =coerce_exprs_for_test(fun, input_phy_exprs, input_schema, &fun.signature())?;if coerced_phy_exprs.is_empty() {- return Err(DataFusionError::Plan(format!(- "Invalid or wrong number of arguments passed to aggregate: '{name}'",- )));+ return plan_err!(+ "Invalid or wrong number of arguments passed to aggregate: '{name}'"+ );}create_aggregate_expr(fun, distinct, &coerced_phy_exprs, &[], input_schema, name)}diff --git a/datafusion/physical-expr/src/array_expressions.rs b/datafusion/physical-expr/src/array_expressions.rsindex 6940456657..4e32a00471 100644--- a/datafusion/physical-expr/src/array_expressions.rs+++ b/datafusion/physical-expr/src/array_expressions.rs@@ -24,7 +24,7 @@ use arrow::datatypes::{DataType, Field, UInt64Type};use arrow_buffer::NullBuffer;use core::any::type_name;use datafusion_common::cast::{as_generic_string_array, as_int64_array, as_list_array};-use datafusion_common::ScalarValue;+use datafusion_common::{plan_err, ScalarValue};use datafusion_common::{DataFusionError, Result};use datafusion_expr::ColumnarValue;use itertools::Itertools;@@ -255,9 +255,7 @@ fn compute_array_dims(arr: Option<ArrayRef>) -> Result<Option<Vec<Option<u64>>>>fn array_array(args: &[ArrayRef], data_type: DataType) -> Result<ArrayRef> {// do not accept 0 arguments.if args.is_empty() {- return Err(DataFusionError::Plan(- "Array requires at least one argument".to_string(),- ));+ return plan_err!("Array requires at least one argument");}let res = match data_type {diff --git a/datafusion/physical-expr/src/crypto_expressions.rs b/datafusion/physical-expr/src/crypto_expressions.rsindex c940933b10..3c2a095361 100644--- a/datafusion/physical-expr/src/crypto_expressions.rs+++ b/datafusion/physical-expr/src/crypto_expressions.rs@@ -23,10 +23,11 @@ use arrow::{};use blake2::{Blake2b512, Blake2s256, Digest};use blake3::Hasher as Blake3;-use datafusion_common::cast::{- as_binary_array, as_generic_binary_array, as_generic_string_array,-};use datafusion_common::ScalarValue;+use datafusion_common::{+ cast::{as_binary_array, as_generic_binary_array, as_generic_string_array},+ plan_err,+};use datafusion_common::{DataFusionError, Result};use datafusion_expr::ColumnarValue;use md5::Md5;@@ -224,9 +225,9 @@ impl FromStr for DigestAlgorithm {.map(|i| i.to_string()).collect::<Vec<_>>().join(", ");- return Err(DataFusionError::Plan(format!(- "There is no built-in digest algorithm named '{name}', currently supported algorithms are: {options}",- )));+ return plan_err!(+ "There is no built-in digest algorithm named '{name}', currently supported algorithms are: {options}"+ );}})}diff --git a/datafusion/physical-expr/src/encoding_expressions.rs b/datafusion/physical-expr/src/encoding_expressions.rsindex e8b4331e92..88d1bec70f 100644--- a/datafusion/physical-expr/src/encoding_expressions.rs+++ b/datafusion/physical-expr/src/encoding_expressions.rs@@ -22,8 +22,11 @@ use arrow::{datatypes::DataType,};use base64::{engine::general_purpose, Engine as _};-use datafusion_common::cast::{as_generic_binary_array, as_generic_string_array};use datafusion_common::ScalarValue;+use datafusion_common::{+ cast::{as_generic_binary_array, as_generic_string_array},+ plan_err,+};use datafusion_common::{DataFusionError, Result};use datafusion_expr::ColumnarValue;use std::sync::Arc;@@ -279,9 +282,9 @@ impl FromStr for Encoding {.map(|i| i.to_string()).collect::<Vec<_>>().join(", ");- return Err(DataFusionError::Plan(format!(- "There is no built-in encoding named '{name}', currently supported encodings are: {options}",- )));+ return plan_err!(+ "There is no built-in encoding named '{name}', currently supported encodings are: {options}"+ );}})}diff --git a/datafusion/physical-expr/src/expressions/binary.rs b/datafusion/physical-expr/src/expressions/binary.rsindex d2fc4600b9..34633f6e1d 100644--- a/datafusion/physical-expr/src/expressions/binary.rs+++ b/datafusion/physical-expr/src/expressions/binary.rs@@ -86,6 +86,7 @@ use crate::physical_expr::down_cast_any_ref;use crate::PhysicalExpr;use datafusion_common::cast::as_boolean_array;+use datafusion_common::plan_err;use datafusion_common::ScalarValue;use datafusion_common::{DataFusionError, Result};use datafusion_expr::type_coercion::binary::{@@ -1124,9 +1125,9 @@ pub fn binary(if (is_utf8_or_large_utf8(lhs_type) && is_timestamp(rhs_type))|| (is_timestamp(lhs_type) && is_utf8_or_large_utf8(rhs_type)){- return Err(DataFusionError::Plan(format!(+ return plan_err!("The type of {lhs_type} {op:?} {rhs_type} of binary physical should be same"- )));+ );}if !lhs_type.eq(rhs_type) && (!is_decimal(lhs_type) && !is_decimal(rhs_type)) {return Err(DataFusionError::Internal(format!(diff --git a/datafusion/physical-expr/src/expressions/case.rs b/datafusion/physical-expr/src/expressions/case.rsindex 91fa9bbb93..506c01b6f3 100644--- a/datafusion/physical-expr/src/expressions/case.rs+++ b/datafusion/physical-expr/src/expressions/case.rs@@ -404,6 +404,7 @@ mod tests {use arrow::datatypes::DataType::Float64;use arrow::datatypes::*;use datafusion_common::cast::{as_float64_array, as_int32_array};+ use datafusion_common::plan_err;use datafusion_common::tree_node::{Transformed, TreeNode};use datafusion_common::ScalarValue;use datafusion_expr::type_coercion::binary::comparison_coercion;@@ -966,9 +967,9 @@ mod tests {let coerce_type =get_case_common_type(&when_thens, else_expr.clone(), input_schema);let (when_thens, else_expr) = match coerce_type {- None => Err(DataFusionError::Plan(format!(+ None => plan_err!("Can't get a common type for then {when_thens:?} and else {else_expr:?} expression"- ))),+ ),Some(data_type) => {// cast then exprlet left = when_thensdiff --git a/datafusion/physical-expr/src/expressions/column.rs b/datafusion/physical-expr/src/expressions/column.rsindex 3b0d77b304..f40a05c49a 100644--- a/datafusion/physical-expr/src/expressions/column.rs+++ b/datafusion/physical-expr/src/expressions/column.rs@@ -28,6 +28,7 @@ use arrow::{datatypes::{DataType, Schema},record_batch::RecordBatch,};+use datafusion_common::plan_err;use datafusion_common::{DataFusionError, Result};use datafusion_expr::ColumnarValue;@@ -175,9 +176,7 @@ impl PhysicalExpr for UnKnownColumn {/// Evaluate the expressionfn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {- Err(DataFusionError::Plan(- "UnKnownColumn::evaluate() should not be called".to_owned(),- ))+ plan_err!("UnKnownColumn::evaluate() should not be called")}fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {diff --git a/datafusion/physical-expr/src/expressions/in_list.rs b/datafusion/physical-expr/src/expressions/in_list.rsindex 3eb25cea82..722edb22de 100644--- a/datafusion/physical-expr/src/expressions/in_list.rs+++ b/datafusion/physical-expr/src/expressions/in_list.rs@@ -377,6 +377,7 @@ mod tests {use super::*;use crate::expressions;use crate::expressions::{col, lit, try_cast};+ use datafusion_common::plan_err;use datafusion_common::Result;use datafusion_expr::type_coercion::binary::comparison_coercion;@@ -396,9 +397,9 @@ mod tests {.collect();let result_type = get_coerce_type(expr_type, &list_types);match result_type {- None => Err(DataFusionError::Plan(format!(+ None => plan_err!("Can not find compatible types to compare {expr_type:?} with {list_types:?}"- ))),+ ),Some(data_type) => {// find the coerced typelet cast_expr = try_cast(expr, input_schema, data_type.clone())?;diff --git a/datafusion/physical-expr/src/expressions/no_op.rs b/datafusion/physical-expr/src/expressions/no_op.rsindex 584d1d6695..497fb42fe4 100644--- a/datafusion/physical-expr/src/expressions/no_op.rs+++ b/datafusion/physical-expr/src/expressions/no_op.rs@@ -28,7 +28,7 @@ use arrow::{use crate::physical_expr::down_cast_any_ref;use crate::PhysicalExpr;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_expr::ColumnarValue;/// A place holder expression, can not be evaluated.@@ -65,9 +65,7 @@ impl PhysicalExpr for NoOp {}fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {- Err(DataFusionError::Plan(- "NoOp::evaluate() should not be called".to_owned(),- ))+ plan_err!("NoOp::evaluate() should not be called")}fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {diff --git a/datafusion/physical-expr/src/functions.rs b/datafusion/physical-expr/src/functions.rsindex 5e7d7e566e..080cbcd62f 100644--- a/datafusion/physical-expr/src/functions.rs+++ b/datafusion/physical-expr/src/functions.rs@@ -897,6 +897,7 @@ mod tests {record_batch::RecordBatch,};use datafusion_common::cast::as_uint64_array;+ use datafusion_common::plan_err;use datafusion_common::{Result, ScalarValue};use datafusion_expr::type_coercion::functions::data_types;use datafusion_expr::Signature;@@ -2846,16 +2847,16 @@ mod tests {match expr {Ok(..) => {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Builtin scalar function {fun} does not support empty arguments"- )));+ );}Err(DataFusionError::Plan(err)) => {if !err.contains("No function matches the given name and argument types"){- return Err(DataFusionError::Internal(format!(- "Builtin scalar function {fun} didn't got the right error message with empty arguments")));+ return plan_err!(+ "Builtin scalar function {fun} didn't got the right error message with empty arguments");}}Err(..) => {diff --git a/datafusion/physical-expr/src/planner.rs b/datafusion/physical-expr/src/planner.rsindex 72a5ccef34..f4e4e8b134 100644--- a/datafusion/physical-expr/src/planner.rs+++ b/datafusion/physical-expr/src/planner.rs@@ -26,6 +26,7 @@ use crate::{PhysicalExpr,};use arrow::datatypes::{DataType, Schema};+use datafusion_common::plan_err;use datafusion_common::{DFSchema, DataFusionError, Result, ScalarValue};use datafusion_expr::expr::{Alias, Cast, InList, ScalarFunction, ScalarUDF};use datafusion_expr::{@@ -75,9 +76,7 @@ pub fn create_physical_expr(let scalar_value = provider.get_value(variable_names.clone())?;Ok(Arc::new(Literal::new(scalar_value)))}- _ => Err(DataFusionError::Plan(- "No system variable provider found".to_string(),- )),+ _ => plan_err!("No system variable provider found"),}} else {match execution_props.get_var_provider(VarType::UserDefined) {@@ -85,9 +84,7 @@ pub fn create_physical_expr(let scalar_value = provider.get_value(variable_names.clone())?;Ok(Arc::new(Literal::new(scalar_value)))}- _ => Err(DataFusionError::Plan(- "No user defined variable provider found".to_string(),- )),+ _ => plan_err!("No user defined variable provider found"),}}}diff --git a/datafusion/physical-expr/src/regex_expressions.rs b/datafusion/physical-expr/src/regex_expressions.rsindex 3965897093..419eafb1c8 100644--- a/datafusion/physical-expr/src/regex_expressions.rs+++ b/datafusion/physical-expr/src/regex_expressions.rs@@ -26,6 +26,7 @@ use arrow::array::{OffsetSizeTrait,};use arrow::compute;+use datafusion_common::plan_err;use datafusion_common::{cast::as_generic_string_array, DataFusionError, Result};use datafusion_expr::{ColumnarValue, ScalarFunctionImplementation};use hashbrown::HashMap;@@ -65,7 +66,7 @@ pub fn regexp_match<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {match flags {Some(f) if f.iter().any(|s| s == Some("g")) => {- Err(DataFusionError::Plan("regexp_match() does not support the \"global\" option".to_owned()))+ plan_err!("regexp_match() does not support the \"global\" option")},_ => compute::regexp_match(values, regex, flags).map_err(DataFusionError::ArrowError),}diff --git a/datafusion/physical-expr/src/sort_expr.rs b/datafusion/physical-expr/src/sort_expr.rsindex 0ba4627bc7..83d32dfeec 100644--- a/datafusion/physical-expr/src/sort_expr.rs+++ b/datafusion/physical-expr/src/sort_expr.rs@@ -24,6 +24,7 @@ use crate::PhysicalExpr;use arrow::compute::kernels::sort::{SortColumn, SortOptions};use arrow::record_batch::RecordBatch;+use datafusion_common::plan_err;use datafusion_common::{DataFusionError, Result};use datafusion_expr::ColumnarValue;@@ -64,9 +65,9 @@ impl PhysicalSortExpr {let array_to_sort = match value_to_sort {ColumnarValue::Array(array) => array,ColumnarValue::Scalar(scalar) => {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Sort operation is not applicable to scalar value {scalar}"- )));+ );}};Ok(SortColumn {diff --git a/datafusion/proto/src/bytes/registry.rs b/datafusion/proto/src/bytes/registry.rsindex 9d2cb06f63..024bb949ba 100644--- a/datafusion/proto/src/bytes/registry.rs+++ b/datafusion/proto/src/bytes/registry.rs@@ -18,6 +18,7 @@use std::{collections::HashSet, sync::Arc};use datafusion::execution::registry::FunctionRegistry;+use datafusion_common::plan_err;use datafusion_common::{DataFusionError, Result};use datafusion_expr::{AggregateUDF, ScalarUDF, WindowUDF};@@ -31,20 +32,14 @@ impl FunctionRegistry for NoRegistry {}fn udf(&self, name: &str) -> Result<Arc<ScalarUDF>> {- Err(DataFusionError::Plan(- format!("No function registry provided to deserialize, so can not deserialize User Defined Function '{name}'"))- )+ plan_err!("No function registry provided to deserialize, so can not deserialize User Defined Function '{name}'")}fn udaf(&self, name: &str) -> Result<Arc<AggregateUDF>> {- Err(DataFusionError::Plan(- format!("No function registry provided to deserialize, so can not deserialize User Defined Aggregate Function '{name}'"))- )+ plan_err!("No function registry provided to deserialize, so can not deserialize User Defined Aggregate Function '{name}'")}fn udwf(&self, name: &str) -> Result<Arc<WindowUDF>> {- Err(DataFusionError::Plan(- format!("No function registry provided to deserialize, so can not deserialize User Defined Window Function '{name}'"))- )+ plan_err!("No function registry provided to deserialize, so can not deserialize User Defined Window Function '{name}'")}}diff --git a/datafusion/proto/src/logical_plan/mod.rs b/datafusion/proto/src/logical_plan/mod.rsindex 9cbce29ed6..d00e5e2f59 100644--- a/datafusion/proto/src/logical_plan/mod.rs+++ b/datafusion/proto/src/logical_plan/mod.rs@@ -1462,7 +1462,9 @@ mod roundtrip_tests {create_udf, CsvReadOptions, SessionConfig, SessionContext,};use datafusion::test_util::{TestTableFactory, TestTableProvider};- use datafusion_common::{DFSchemaRef, DataFusionError, Result, ScalarValue};+ use datafusion_common::{+ plan_err, DFSchemaRef, DataFusionError, Result, ScalarValue,+ };use datafusion_expr::expr::{self, Between, BinaryExpr, Case, Cast, GroupingSet, InList, Like, ScalarFunction,ScalarUDF, Sort,@@ -2915,11 +2917,11 @@ mod roundtrip_tests {fn return_type(arg_types: &[DataType]) -> Result<Arc<DataType>> {if arg_types.len() != 1 {- return Err(DataFusionError::Plan(format!(+ return plan_err!("dummy_udwf expects 1 argument, got {}: {:?}",arg_types.len(),arg_types- )));+ );}Ok(Arc::new(arg_types[0].clone()))}diff --git a/datafusion/sql/examples/sql.rs b/datafusion/sql/examples/sql.rsindex 59b7921d67..8a12cc32b6 100644--- a/datafusion/sql/examples/sql.rs+++ b/datafusion/sql/examples/sql.rs@@ -17,7 +17,7 @@use arrow_schema::{DataType, Field, Schema};use datafusion_common::config::ConfigOptions;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_expr::WindowUDF;use datafusion_expr::{logical_plan::builder::LogicalTableSource, AggregateUDF, ScalarUDF, TableSource,@@ -108,10 +108,7 @@ impl ContextProvider for MySchemaProvider {fn get_table_provider(&self, name: TableReference) -> Result<Arc<dyn TableSource>> {match self.tables.get(name.table()) {Some(table) => Ok(table.clone()),- _ => Err(DataFusionError::Plan(format!(- "Table not found: {}",- name.table()- ))),+ _ => plan_err!("Table not found: {}", name.table()),}}diff --git a/datafusion/sql/src/expr/arrow_cast.rs b/datafusion/sql/src/expr/arrow_cast.rsindex 46957a9cdd..549d46c5e2 100644--- a/datafusion/sql/src/expr/arrow_cast.rs+++ b/datafusion/sql/src/expr/arrow_cast.rs@@ -23,6 +23,7 @@ use std::{fmt::Display, iter::Peekable, str::Chars, sync::Arc};use arrow_schema::{DataType, Field, IntervalUnit, TimeUnit};use datafusion_common::{DFSchema, DataFusionError, Result, ScalarValue};+use datafusion_common::plan_err;use datafusion_expr::{Expr, ExprSchemable};pub const ARROW_CAST_NAME: &str = "arrow_cast";@@ -51,10 +52,7 @@ pub const ARROW_CAST_NAME: &str = "arrow_cast";/// [`BuiltinScalarFunction`]: datafusion_expr::BuiltinScalarFunctionpub fn create_arrow_cast(mut args: Vec<Expr>, schema: &DFSchema) -> Result<Expr> {if args.len() != 2 {- return Err(DataFusionError::Plan(format!(- "arrow_cast needs 2 arguments, {} provided",- args.len()- )));+ return plan_err!("arrow_cast needs 2 arguments, {} provided", args.len());}let arg1 = args.pop().unwrap();let arg0 = args.pop().unwrap();@@ -63,9 +61,9 @@ pub fn create_arrow_cast(mut args: Vec<Expr>, schema: &DFSchema) -> Result<Expr>let data_type_string = if let Expr::Literal(ScalarValue::Utf8(Some(v))) = arg1 {v} else {- return Err(DataFusionError::Plan(format!(+ return plan_err!("arrow_cast requires its second argument to be a constant string, got {arg1}"- )));+ );};// do the actual lookup to the appropriate data typediff --git a/datafusion/sql/src/expr/function.rs b/datafusion/sql/src/expr/function.rsindex f08f357ec4..362a2ac42a 100644--- a/datafusion/sql/src/expr/function.rs+++ b/datafusion/sql/src/expr/function.rs@@ -16,6 +16,7 @@// under the License.use crate::planner::{ContextProvider, PlannerContext, SqlToRel};+use datafusion_common::plan_err;use datafusion_common::{DFSchema, DataFusionError, Result};use datafusion_expr::expr::{ScalarFunction, ScalarUDF};use datafusion_expr::function::suggest_valid_function;@@ -65,9 +66,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {// required ordering should be defined in OVER clause.let is_function_window = function.over.is_some();if !function.order_by.is_empty() && is_function_window {- return Err(DataFusionError::Plan(- "Aggregate ORDER BY is not implemented for window functions".to_string(),- ));+ return plan_err!(+ "Aggregate ORDER BY is not implemented for window functions"+ );}// then, window function@@ -160,9 +161,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {// Could not find the relevant function, so return an errorlet suggested_func_name = suggest_valid_function(&name, is_function_window);- Err(DataFusionError::Plan(format!(- "Invalid function '{name}'.\nDid you mean '{suggested_func_name}'?"- )))+ plan_err!("Invalid function '{name}'.\nDid you mean '{suggested_func_name}'?")}pub(super) fn sql_named_function_to_expr(diff --git a/datafusion/sql/src/expr/grouping_set.rs b/datafusion/sql/src/expr/grouping_set.rsindex 34dfac158a..254f5079b7 100644--- a/datafusion/sql/src/expr/grouping_set.rs+++ b/datafusion/sql/src/expr/grouping_set.rs@@ -16,6 +16,7 @@// under the License.use crate::planner::{ContextProvider, PlannerContext, SqlToRel};+use datafusion_common::plan_err;use datafusion_common::{DFSchema, DataFusionError, Result};use datafusion_expr::{Expr, GroupingSet};use sqlparser::ast::Expr as SQLExpr;@@ -48,10 +49,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {.into_iter().map(|v| {if v.len() != 1 {- Err(DataFusionError::Plan(+ plan_err!("Tuple expressions are not supported for Rollup expressions"- .to_string(),- ))+ )} else {self.sql_expr_to_logical_expr(v[0].clone(), schema, planner_context)}@@ -70,10 +70,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {.into_iter().map(|v| {if v.len() != 1 {- Err(DataFusionError::Plan(- "Tuple expressions not are supported for Cube expressions"- .to_string(),- ))+ plan_err!("Tuple expressions not are supported for Cube expressions")} else {self.sql_expr_to_logical_expr(v[0].clone(), schema, planner_context)}diff --git a/datafusion/sql/src/expr/mod.rs b/datafusion/sql/src/expr/mod.rsindex 0630bcb7e8..126ae4d11b 100644--- a/datafusion/sql/src/expr/mod.rs+++ b/datafusion/sql/src/expr/mod.rs@@ -29,6 +29,7 @@ mod value;use crate::planner::{ContextProvider, PlannerContext, SqlToRel};use arrow_schema::DataType;+use datafusion_common::plan_err;use datafusion_common::tree_node::{Transformed, TreeNode};use datafusion_common::{Column, DFSchema, DataFusionError, Result, ScalarValue};use datafusion_expr::expr::ScalarFunction;@@ -414,9 +415,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {let pattern = self.sql_expr_to_logical_expr(pattern, schema, planner_context)?;let pattern_type = pattern.get_type(schema)?;if pattern_type != DataType::Utf8 && pattern_type != DataType::Null {- return Err(DataFusionError::Plan(- "Invalid pattern in LIKE expression".to_string(),- ));+ return plan_err!("Invalid pattern in LIKE expression");}Ok(Expr::Like(Like::new(negated,@@ -439,9 +438,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {let pattern = self.sql_expr_to_logical_expr(pattern, schema, planner_context)?;let pattern_type = pattern.get_type(schema)?;if pattern_type != DataType::Utf8 && pattern_type != DataType::Null {- return Err(DataFusionError::Plan(- "Invalid pattern in SIMILAR TO expression".to_string(),- ));+ return plan_err!("Invalid pattern in SIMILAR TO expression");}Ok(Expr::SimilarTo(Like::new(negated,@@ -503,10 +500,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {)?)),order_by,))),- _ => Err(DataFusionError::Plan(+ _ => plan_err!("AggregateExpressionWithFilter expression was not an AggregateFunction"- .to_string(),- )),+ ),}}}@@ -628,10 +624,7 @@ mod tests {) -> Result<Arc<dyn TableSource>> {match self.tables.get(name.table()) {Some(table) => Ok(table.clone()),- _ => Err(DataFusionError::Plan(format!(- "Table not found: {}",- name.table()- ))),+ _ => plan_err!("Table not found: {}", name.table()),}}diff --git a/datafusion/sql/src/expr/substring.rs b/datafusion/sql/src/expr/substring.rsindex 1a95266615..d95a25b8fa 100644--- a/datafusion/sql/src/expr/substring.rs+++ b/datafusion/sql/src/expr/substring.rs@@ -16,6 +16,7 @@// under the License.use crate::planner::{ContextProvider, PlannerContext, SqlToRel};+use datafusion_common::plan_err;use datafusion_common::{DFSchema, DataFusionError, Result, ScalarValue};use datafusion_expr::expr::ScalarFunction;use datafusion_expr::{BuiltinScalarFunction, Expr};@@ -62,9 +63,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {substring_for: None,};- return Err(DataFusionError::Plan(format!(- "Substring without for/from is not valid {orig_sql:?}"- )));+ return plan_err!("Substring without for/from is not valid {orig_sql:?}");}};diff --git a/datafusion/sql/src/expr/value.rs b/datafusion/sql/src/expr/value.rsindex c34b657181..642ac5d8d0 100644--- a/datafusion/sql/src/expr/value.rs+++ b/datafusion/sql/src/expr/value.rs@@ -18,7 +18,7 @@use crate::planner::{ContextProvider, PlannerContext, SqlToRel};use arrow::compute::kernels::cast_utils::parse_interval_month_day_nano;use arrow_schema::DataType;-use datafusion_common::{DFSchema, DataFusionError, Result, ScalarValue};+use datafusion_common::{plan_err, DFSchema, DataFusionError, Result, ScalarValue};use datafusion_expr::expr::{BinaryExpr, Placeholder};use datafusion_expr::{lit, Expr, Operator};use log::debug;@@ -44,14 +44,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {if let Some(v) = try_decode_hex_literal(&s) {Ok(lit(v))} else {- Err(DataFusionError::Plan(format!(- "Invalid HexStringLiteral '{s}'"- )))+ plan_err!("Invalid HexStringLiteral '{s}'")}}- _ => Err(DataFusionError::Plan(format!(- "Unsupported Value '{value:?}'",- ))),+ _ => plan_err!("Unsupported Value '{value:?}'"),}}@@ -104,15 +100,13 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {let index = param[1..].parse::<usize>();let idx = match index {Ok(0) => {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Invalid placeholder, zero is not a valid index: {param}"- )));+ );}Ok(index) => index - 1,Err(_) => {- return Err(DataFusionError::Plan(format!(- "Invalid placeholder, not a number: {param}"- )));+ return plan_err!("Invalid placeholder, not a number: {param}");}};// Check if the placeholder is in the parameter listdiff --git a/datafusion/sql/src/planner.rs b/datafusion/sql/src/planner.rsindex efa3077c3b..0f54638d74 100644--- a/datafusion/sql/src/planner.rs+++ b/datafusion/sql/src/planner.rs@@ -29,6 +29,7 @@ use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};use sqlparser::ast::{DataType as SQLDataType, Ident, ObjectName, TableAlias};use datafusion_common::config::ConfigOptions;+use datafusion_common::plan_err;use datafusion_common::{unqualified_field_not_found, DFSchema, DataFusionError, Result};use datafusion_common::{OwnedTableReference, TableReference};use datafusion_expr::logical_plan::{LogicalPlan, LogicalPlanBuilder};@@ -243,11 +244,11 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {if idents.is_empty() {Ok(plan)} else if idents.len() != plan.schema().fields().len() {- Err(DataFusionError::Plan(format!(+ plan_err!("Source table contains {} columns but only {} names given as column alias",plan.schema().fields().len(),- idents.len(),- )))+ idents.len()+ )} else {let fields = plan.schema().fields().clone();LogicalPlanBuilder::from(plan)@@ -461,10 +462,7 @@ pub(crate) fn idents_to_table_reference(let catalog = taker.take(enable_normalization);Ok(OwnedTableReference::full(catalog, schema, table))}- _ => Err(DataFusionError::Plan(format!(- "Unsupported compound identifier '{:?}'",- taker.0,- ))),+ _ => plan_err!("Unsupported compound identifier '{:?}'", taker.0),}}diff --git a/datafusion/sql/src/query.rs b/datafusion/sql/src/query.rsindex 34b24b0594..272998e4a8 100644--- a/datafusion/sql/src/query.rs+++ b/datafusion/sql/src/query.rs@@ -27,6 +27,7 @@ use sqlparser::ast::{Expr as SQLExpr, Offset as SQLOffset, OrderByExpr, Query, SetExpr, Value,};+use datafusion_common::plan_err;use sqlparser::parser::ParserError::ParserError;impl<'a, S: ContextProvider> SqlToRel<'a, S> {@@ -117,15 +118,11 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {)? {Expr::Literal(ScalarValue::Int64(Some(s))) => {if s < 0 {- return Err(DataFusionError::Plan(format!(- "Offset must be >= 0, '{s}' was provided."- )));+ return plan_err!("Offset must be >= 0, '{s}' was provided.");}Ok(s as usize)}- _ => Err(DataFusionError::Plan(- "Unexpected expression in OFFSET clause".to_string(),- )),+ _ => plan_err!("Unexpected expression in OFFSET clause"),}?,_ => 0,};@@ -142,9 +139,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {Expr::Literal(ScalarValue::Int64(Some(n))) if n >= 0 => {Ok(n as usize)}- _ => Err(DataFusionError::Plan(- "LIMIT must not be negative".to_string(),- )),+ _ => plan_err!("LIMIT must not be negative"),}?;Some(n)}diff --git a/datafusion/sql/src/select.rs b/datafusion/sql/src/select.rsindex 59656587fa..a4e6ae007f 100644--- a/datafusion/sql/src/select.rs+++ b/datafusion/sql/src/select.rs@@ -24,6 +24,7 @@ use crate::utils::{resolve_columns, resolve_positions_to_exprs,};+use datafusion_common::plan_err;use datafusion_common::{get_target_functional_dependencies, DFSchemaRef, DataFusionError, Result,};@@ -170,8 +171,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {)?} else {match having_expr_opt {- Some(having_expr) => return Err(DataFusionError::Plan(- format!("HAVING clause references: {having_expr} must appear in the GROUP BY clause or be used in an aggregate function"))),+ Some(having_expr) => return plan_err!("HAVING clause references: {having_expr} must appear in the GROUP BY clause or be used in an aggregate function"),None => (plan, select_exprs, having_expr_opt)}};@@ -358,9 +358,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {Self::check_wildcard_options(&options)?;if empty_from {- return Err(DataFusionError::Plan(- "SELECT * with no tables specified is not valid".to_string(),- ));+ return plan_err!("SELECT * with no tables specified is not valid");}// do not expand from outer schemaexpand_wildcard(plan.schema().as_ref(), plan, Some(options))@@ -521,10 +519,10 @@ fn check_conflicting_windows(window_defs: &[NamedWindowDefinition]) -> Result<()for (i, window_def_i) in window_defs.iter().enumerate() {for window_def_j in window_defs.iter().skip(i + 1) {if window_def_i.0 == window_def_j.0 {- return Err(DataFusionError::Plan(format!(+ return plan_err!("The window {} is defined multiple times!",window_def_i.0- )));+ );}}}@@ -553,9 +551,7 @@ fn match_window_definitions(}// All named windows must be defined with a WindowSpec.if let Some(WindowType::NamedWindow(ident)) = &f.over {- return Err(DataFusionError::Plan(format!(- "The window {ident} is not defined!"- )));+ return plan_err!("The window {ident} is not defined!");}}}diff --git a/datafusion/sql/src/statement.rs b/datafusion/sql/src/statement.rsindex 4af32337f7..cb4a7cb527 100644--- a/datafusion/sql/src/statement.rs+++ b/datafusion/sql/src/statement.rs@@ -53,6 +53,7 @@ use sqlparser::ast::{};use sqlparser::parser::ParserError::ParserError;+use datafusion_common::plan_err;use std::collections::{BTreeMap, HashMap, HashSet};use std::sync::Arc;@@ -140,11 +141,11 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {let plan = if !columns.is_empty() {let schema = self.build_schema(columns)?.to_dfschema_ref()?;if schema.fields().len() != input_schema.fields().len() {- return Err(DataFusionError::Plan(format!(+ return plan_err!("Mismatch: {} columns specified, but result has {} columns",schema.fields().len(),input_schema.fields().len()- )));+ );}let input_fields = input_schema.fields();let project_exprs = schema@@ -356,39 +357,25 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {returning,} => {if or.is_some() {- Err(DataFusionError::Plan(- "Inserts with or clauses not supported".to_owned(),- ))?;+ plan_err!("Inserts with or clauses not supported")?;}if overwrite {- Err(DataFusionError::Plan(- "Insert overwrite is not supported".to_owned(),- ))?;+ plan_err!("Insert overwrite is not supported")?;}if partitioned.is_some() {- Err(DataFusionError::Plan(- "Partitioned inserts not yet supported".to_owned(),- ))?;+ plan_err!("Partitioned inserts not yet supported")?;}if !after_columns.is_empty() {- Err(DataFusionError::Plan(- "After-columns clause not supported".to_owned(),- ))?;+ plan_err!("After-columns clause not supported")?;}if table {- Err(DataFusionError::Plan(- "Table clause not supported".to_owned(),- ))?;+ plan_err!("Table clause not supported")?;}if on.is_some() {- Err(DataFusionError::Plan(- "Insert-on clause not supported".to_owned(),- ))?;+ plan_err!("Insert-on clause not supported")?;}if returning.is_some() {- Err(DataFusionError::Plan(- "Insert-returning clause not yet supported".to_owned(),- ))?;+ plan_err!("Insert-returning clause not supported")?;}let _ = into; // optional keyword doesn't change behaviorself.insert_to_plan(table_name, columns, source)@@ -402,9 +389,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {returning,} => {if returning.is_some() {- Err(DataFusionError::Plan(- "Update-returning clause not yet supported".to_owned(),- ))?;+ plan_err!("Update-returning clause not yet supported")?;}self.update_to_plan(table, assignments, from, selection)}@@ -417,20 +402,15 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {from,} => {if !tables.is_empty() {- return Err(DataFusionError::NotImplemented(- "DELETE <TABLE> not supported".to_string(),- ));+ plan_err!("DELETE <TABLE> not supported")?;}if using.is_some() {- Err(DataFusionError::Plan(- "Using clause not supported".to_owned(),- ))?;+ plan_err!("Using clause not supported")?;}+if returning.is_some() {- Err(DataFusionError::Plan(- "Delete-returning clause not yet supported".to_owned(),- ))?;+ plan_err!("Delete-returning clause not yet supported")?;}let table_name = self.get_delete_target(from)?;self.delete_to_plan(table_name, selection)@@ -541,9 +521,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {// we only support the basic "SHOW TABLES"// https://github.com/apache/arrow-datafusion/issues/3188if db_name.is_some() || filter.is_some() || full || extended {- Err(DataFusionError::Plan(- "Unsupported parameters to SHOW TABLES".to_string(),- ))+ plan_err!("Unsupported parameters to SHOW TABLES")} else {let query = "SELECT * FROM information_schema.tables;";let mut rewrite = DFParser::parse_sql(query)?;@@ -551,10 +529,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {self.statement_to_plan(rewrite.pop_front().unwrap()) // length of rewrite is 1}} else {- Err(DataFusionError::Plan(- "SHOW TABLES is not supported unless information_schema is enabled"- .to_string(),- ))+ plan_err!("SHOW TABLES is not supported unless information_schema is enabled")}}@@ -590,10 +565,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {) -> Result<Vec<Vec<datafusion_expr::Expr>>> {// Ask user to provide a schema if schema is empty.if !order_exprs.is_empty() && schema.fields().is_empty() {- return Err(DataFusionError::Plan(+ return plan_err!("Provide a schema before specifying the order while creating a table."- .to_owned(),- ));+ );}let mut all_results = vec![];@@ -605,9 +579,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {for column in expr.to_columns()?.iter() {if !schema.has_column(column) {// Return an error if any column is not in the schema:- return Err(DataFusionError::Plan(format!(- "Column {column} is not in schema"- )));+ return plan_err!("Column {column} is not in schema");}}}@@ -640,18 +612,14 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {// semantic checksif file_type == "PARQUET" && !columns.is_empty() {- Err(DataFusionError::Plan(- "Column definitions can not be specified for PARQUET files.".into(),- ))?;+ plan_err!("Column definitions can not be specified for PARQUET files.")?;}if file_type != "CSV"&& file_type != "JSON"&& file_compression_type != CompressionTypeVariant::UNCOMPRESSED{- Err(DataFusionError::Plan(- "File compression type can be specified for CSV/JSON files.".into(),- ))?;+ plan_err!("File compression type can be specified for CSV/JSON files.")?;}let schema = self.build_schema(columns)?;@@ -718,10 +686,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {let variable = object_name_to_string(&ObjectName(variable.to_vec()));if !self.has_table("information_schema", "df_settings") {- return Err(DataFusionError::Plan(+ return plan_err!("SHOW [VARIABLE] is not supported unless information_schema is enabled"- .to_string(),- ));+ );}let variable_lower = variable.to_lowercase();@@ -790,10 +757,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {| Value::HexStringLiteral(_)| Value::Null| Value::Placeholder(_) => {- return Err(DataFusionError::Plan(format!(- "Unsupported Value {}",- value[0]- )));+ return plan_err!("Unsupported Value {}", value[0]);}},// for capture signed number e.g. +8, -8@@ -801,17 +765,11 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {UnaryOperator::Plus => format!("+{expr}"),UnaryOperator::Minus => format!("-{expr}"),_ => {- return Err(DataFusionError::Plan(format!(- "Unsupported Value {}",- value[0]- )));+ return plan_err!("Unsupported Value {}", value[0]);}},_ => {- return Err(DataFusionError::Plan(format!(- "Unsupported Value {}",- value[0]- )));+ return plan_err!("Unsupported Value {}", value[0]);}};@@ -874,9 +832,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {) -> Result<LogicalPlan> {let table_name = match &table.relation {TableFactor::Table { name, .. } => name.clone(),- _ => Err(DataFusionError::Plan(- "Cannot update non-table relation!".to_string(),- ))?,+ _ => plan_err!("Cannot update non-table relation!")?,};// Do a table lookup to verify the table exists@@ -1053,9 +1009,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {PlannerContext::new().with_prepare_param_data_types(prepare_param_data_types);let source = self.query_to_plan(*source, &mut planner_context)?;if fields.len() != source.schema().fields().len() {- Err(DataFusionError::Plan(- "Column count doesn't match insert query!".to_owned(),- ))?;+ plan_err!("Column count doesn't match insert query!")?;}let exprs = index_mapping@@ -1090,16 +1044,13 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {filter: Option<ShowStatementFilter>,) -> Result<LogicalPlan> {if filter.is_some() {- return Err(DataFusionError::Plan(- "SHOW COLUMNS with WHERE or LIKE is not supported".to_string(),- ));+ return plan_err!("SHOW COLUMNS with WHERE or LIKE is not supported");}if !self.has_table("information_schema", "columns") {- return Err(DataFusionError::Plan(+ return plan_err!("SHOW COLUMNS is not supported unless information_schema is enabled"- .to_string(),- ));+ );}// Figure out the where clauselet where_clause = object_name_to_qualifier(@@ -1132,10 +1083,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {sql_table_name: ObjectName,) -> Result<LogicalPlan> {if !self.has_table("information_schema", "tables") {- return Err(DataFusionError::Plan(+ return plan_err!("SHOW CREATE TABLE is not supported unless information_schema is enabled"- .to_string(),- ));+ );}// Figure out the where clauselet where_clause = object_name_to_qualifier(diff --git a/datafusion/sql/src/utils.rs b/datafusion/sql/src/utils.rsindex 27e62526b8..57815989ab 100644--- a/datafusion/sql/src/utils.rs+++ b/datafusion/sql/src/utils.rs@@ -20,6 +20,7 @@use arrow_schema::{DataType, DECIMAL128_MAX_PRECISION, DECIMAL_DEFAULT_SCALE};use sqlparser::ast::Ident;+use datafusion_common::plan_err;use datafusion_common::{DataFusionError, Result, ScalarValue};use datafusion_expr::expr::{AggregateFunction, AggregateUDF, Alias, Between, BinaryExpr, Case, GetIndexedField,@@ -121,12 +122,12 @@ fn check_column_satisfies_expr(message_prefix: &str,) -> Result<()> {if !columns.contains(expr) {- return Err(DataFusionError::Plan(format!(+ return plan_err!("{}: Expression {} could not be resolved from available columns: {}",message_prefix,expr,expr_vec_fmt!(columns)- )));+ );}Ok(())}@@ -511,9 +512,7 @@ pub(crate) fn make_decimal_type((Some(p), Some(s)) => (p as u8, s as i8),(Some(p), None) => (p as u8, 0),(None, Some(_)) => {- return Err(DataFusionError::Plan(- "Cannot specify only scale for decimal data type".to_string(),- ))+ return plan_err!("Cannot specify only scale for decimal data type")}(None, None) => (DECIMAL128_MAX_PRECISION, DECIMAL_DEFAULT_SCALE),};@@ -523,9 +522,9 @@ pub(crate) fn make_decimal_type(|| precision > DECIMAL128_MAX_PRECISION|| scale.unsigned_abs() > precision{- Err(DataFusionError::Plan(format!(+ plan_err!("Decimal(precision = {precision}, scale = {scale}) should satisfy `0 < precision <= 38`, and `scale <= precision`."- )))+ )} else {Ok(DataType::Decimal128(precision, scale))}diff --git a/datafusion/sql/tests/sql_integration.rs b/datafusion/sql/tests/sql_integration.rsindex 26663f88c3..f19ddfc053 100644--- a/datafusion/sql/tests/sql_integration.rs+++ b/datafusion/sql/tests/sql_integration.rs@@ -22,6 +22,7 @@ use std::{sync::Arc, vec};use arrow_schema::*;use sqlparser::dialect::{Dialect, GenericDialect, HiveDialect, MySqlDialect};+use datafusion_common::plan_err;use datafusion_common::{assert_contains, config::ConfigOptions, DataFusionError, Result, ScalarValue,TableReference,@@ -2695,10 +2696,7 @@ impl ContextProvider for MockContextProvider {Field::new("Id", DataType::UInt32, false),Field::new("lower", DataType::UInt32, false),])),- _ => Err(DataFusionError::Plan(format!(- "No table named: {} found",- name.table()- ))),+ _ => plan_err!("No table named: {} found", name.table()),};match schema {diff --git a/datafusion/substrait/src/logical_plan/consumer.rs b/datafusion/substrait/src/logical_plan/consumer.rsindex 2c37f7ede1..4e4d71ddb6 100644--- a/datafusion/substrait/src/logical_plan/consumer.rs+++ b/datafusion/substrait/src/logical_plan/consumer.rs@@ -53,6 +53,7 @@ use substrait::proto::{};use substrait::proto::{FunctionArgument, SortField};+use datafusion::common::plan_err;use datafusion::logical_expr::expr::{InList, Sort};use std::collections::HashMap;use std::str::FromStr;@@ -165,7 +166,7 @@ pub async fn from_substrait_plan(Ok(from_substrait_rel(ctx, root.input.as_ref().unwrap(), &function_extension).await?)}},- None => Err(DataFusionError::Plan("Cannot parse plan relation: None".to_string()))+ None => plan_err!("Cannot parse plan relation: None")}},_ => Err(DataFusionError::NotImplemented(format!(@@ -362,8 +363,7 @@ pub async fn from_substrait_rel(// TODO: collect only one null_eq_nulllet join_exprs: Vec<(Column, Column, bool)> = predicates.iter()- .map(|p| {- match p {+ .map(|p| match p {Expr::BinaryExpr(BinaryExpr { left, op, right }) => {match (left.as_ref(), right.as_ref()) {(Expr::Column(l), Expr::Column(r)) => match op {@@ -371,20 +371,14 @@ pub async fn from_substrait_rel(Operator::IsNotDistinctFrom => {Ok((l.clone(), r.clone(), true))}- _ => Err(DataFusionError::Plan(- "invalid join condition op".to_string(),- )),+ _ => plan_err!("invalid join condition op"),},- _ => Err(DataFusionError::Plan(- "invalid join condition expression".to_string(),- )),+ _ => plan_err!("invalid join condition expression"),}}- _ => Err(DataFusionError::Plan(+ _ => plan_err!("Non-binary expression is not supported in join condition"- .to_string(),- )),- }+ ),}).collect::<Result<Vec<_>>>()?;let (left_cols, right_cols, null_eq_nulls): (Vec<_>, Vec<_>, Vec<_>) =@@ -407,9 +401,7 @@ pub async fn from_substrait_rel(join_filter,)?.build(),- None => Err(DataFusionError::Plan(- "Join without join keys require a valid filter".to_string(),- )),+ None => plan_err!("Join without join keys require a valid filter"),},}}@@ -417,9 +409,7 @@ pub async fn from_substrait_rel(Some(ReadType::NamedTable(nt)) => {let table_reference = match nt.names.len() {0 => {- return Err(DataFusionError::Plan(- "No table name found in NamedTable".to_string(),- ));+ return plan_err!("No table name found in NamedTable");}1 => TableReference::Bare {table: (&nt.names[0]).into(),@@ -459,9 +449,7 @@ pub async fn from_substrait_rel()?);Ok(LogicalPlan::TableScan(scan))}- _ => Err(DataFusionError::Plan(- "unexpected plan for table".to_string(),- )),+ _ => plan_err!("unexpected plan for table"),}}_ => Ok(t),@@ -564,14 +552,10 @@ fn from_substrait_jointype(join_type: i32) -> Result<JoinType> {join_rel::JoinType::Outer => Ok(JoinType::Full),join_rel::JoinType::Anti => Ok(JoinType::LeftAnti),join_rel::JoinType::Semi => Ok(JoinType::LeftSemi),- _ => Err(DataFusionError::Plan(format!(- "unsupported join type {substrait_join_type:?}"- ))),+ _ => plan_err!("unsupported join type {substrait_join_type:?}"),}} else {- Err(DataFusionError::Plan(format!(- "invalid join type variant {join_type:?}"- )))+ plan_err!("invalid join type variant {join_type:?}")}}