Apache DataFusion SQL Query Engine
Add `internal_err!` error macro (#7293)
comphead518efca8dc05
diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rsindex 41c2657e1c..b7a91684bb 100644--- a/datafusion/common/src/config.rs+++ b/datafusion/common/src/config.rs@@ -16,7 +16,7 @@// under the License.//! Runtime configuration, via [`ConfigOptions`]-+use crate::error::_internal_err;use crate::{DataFusionError, Result};use std::any::Any;use std::collections::{BTreeMap, HashMap};@@ -65,10 +65,10 @@ use std::fmt::Display;/// "field1" => self.field1.set(rem, value),/// "field2" => self.field2.set(rem, value),/// "field3" => self.field3.set(rem, value),-/// _ => Err(DataFusionError::Internal(format!(+/// _ => _internal_err!(/// "Config value \"{}\" not found on MyConfig",/// key-/// ))),+/// ),/// }/// }///@@ -510,9 +510,7 @@ impl ConfigField for ConfigOptions {"optimizer" => self.optimizer.set(rem, value),"explain" => self.explain.set(rem, value),"sql_parser" => self.sql_parser.set(rem, value),- _ => Err(DataFusionError::Internal(format!(- "Config value \"{key}\" not found on ConfigOptions"- ))),+ _ => _internal_err!("Config value \"{key}\" not found on ConfigOptions"),}}diff --git a/datafusion/common/src/error.rs b/datafusion/common/src/error.rsindex 240194d868..d10796bfa8 100644--- a/datafusion/common/src/error.rs+++ b/datafusion/common/src/error.rs@@ -415,7 +415,6 @@ macro_rules! unwrap_or_internal_err {};}-#[macro_export]macro_rules! with_dollar_sign {($($body:tt)*) => {macro_rules! __with_dollar_sign { $($body)* }@@ -449,6 +448,13 @@ macro_rules! make_error {// Exposes a macro to create `DataFusionError::Plan`make_error!(plan_err, Plan);+// Exposes a macro to create `DataFusionError::Internal`+make_error!(internal_err, Internal);++// To avoid compiler error when using macro in the same crate:+// macros from the current crate cannot be referred to by absolute paths+pub use internal_err as _internal_err;+#[cfg(test)]mod test {use std::sync::Arc;diff --git a/datafusion/common/src/scalar.rs b/datafusion/common/src/scalar.rsindex 0fc1ca3dc7..26185b3799 100644--- a/datafusion/common/src/scalar.rs+++ b/datafusion/common/src/scalar.rs@@ -30,7 +30,7 @@ use crate::cast::{as_fixed_size_binary_array, as_fixed_size_list_array, as_list_array, as_struct_array,};use crate::delta::shift_months;-use crate::error::{DataFusionError, Result};+use crate::error::{DataFusionError, Result, _internal_err};use arrow::buffer::NullBuffer;use arrow::compute::nullif;use arrow::datatypes::{i256, FieldRef, Fields, SchemaBuilder};@@ -699,9 +699,9 @@ macro_rules! primitive_right {Ok(ScalarValue::$SCALAR(Some($TERM.recip())))};($TERM:expr, /, $SCALAR:ident) => {- Err(DataFusionError::Internal(format!(+ internal_err!("Can not divide an uninitialized value to a non-floating point value",- )))+ )};($TERM:expr, &, $SCALAR:ident) => {Ok(ScalarValue::$SCALAR(Some($TERM)))@@ -834,12 +834,12 @@ macro_rules! impl_bit_op_arithmetic {(ScalarValue::Int8(lhs), ScalarValue::Int8(rhs)) => {primitive_op!(lhs, rhs, Int8, $OPERATION)}- _ => Err(DataFusionError::Internal(format!(+ _ => _internal_err!("Operator {} is not implemented for types {:?} and {:?}",stringify!($OPERATION),$LHS,$RHS- ))),+ ),}};}@@ -850,12 +850,12 @@ macro_rules! impl_bool_op_arithmetic {(ScalarValue::Boolean(lhs), ScalarValue::Boolean(rhs)) => {primitive_op!(lhs, rhs, Boolean, $OPERATION)}- _ => Err(DataFusionError::Internal(format!(+ _ => _internal_err!("Operator {} is not implemented for types {:?} and {:?}",stringify!($OPERATION),$LHS,$RHS- ))),+ ),}};}@@ -1020,12 +1020,12 @@ macro_rules! impl_op_arithmetic {true,)))),// todo: Add Decimal256 support- _ => Err(DataFusionError::Internal(format!(+ _ => _internal_err!("Operator {} is not implemented for types {:?} and {:?}",stringify!($OPERATION),$LHS,$RHS- ))),+ ),}};}@@ -1790,9 +1790,9 @@ impl ScalarValue {if precision <= DECIMAL128_MAX_PRECISION && scale.unsigned_abs() <= precision {return Ok(ScalarValue::Decimal128(Some(value), precision, scale));}- Err(DataFusionError::Internal(format!(+ _internal_err!("Can not new a decimal type ScalarValue for precision {precision} and scale {scale}"- )))+ )}/// Returns a [`ScalarValue::Utf8`] representing `val`@@ -2051,9 +2051,9 @@ impl ScalarValue {ScalarValue::Decimal256(Some(v), precision, scale) => Ok(ScalarValue::Decimal256(Some(v.neg_wrapping()), *precision, *scale),),- value => Err(DataFusionError::Internal(format!(+ value => _internal_err!("Can not run arithmetic negative on scalar value {value:?}"- ))),+ ),}}@@ -2257,11 +2257,11 @@ impl ScalarValue {if let ScalarValue::$SCALAR_TY(v) = sv {Ok(v)} else {- Err(DataFusionError::Internal(format!(+ _internal_err!("Inconsistent types in ScalarValue::iter_to_array. \Expected {:?}, got {:?}",data_type, sv- )))+ )}}).collect::<Result<$ARRAY_TY>>()?;@@ -2277,11 +2277,11 @@ impl ScalarValue {if let ScalarValue::$SCALAR_TY(v, _) = sv {Ok(v)} else {- Err(DataFusionError::Internal(format!(+ _internal_err!("Inconsistent types in ScalarValue::iter_to_array. \Expected {:?}, got {:?}",data_type, sv- )))+ )}}).collect::<Result<$ARRAY_TY>>()?;@@ -2299,11 +2299,11 @@ impl ScalarValue {if let ScalarValue::$SCALAR_TY(v) = sv {Ok(v)} else {- Err(DataFusionError::Internal(format!(+ _internal_err!("Inconsistent types in ScalarValue::iter_to_array. \Expected {:?}, got {:?}",data_type, sv- )))+ )}}).collect::<Result<$ARRAY_TY>>()?;@@ -2352,11 +2352,11 @@ impl ScalarValue {builder.values().append_null();}sv => {- return Err(DataFusionError::Internal(format!(+ return _internal_err!("Inconsistent types in ScalarValue::iter_to_array. \Expected Utf8, got {:?}",sv- )))+ )}}}@@ -2366,11 +2366,11 @@ impl ScalarValue {builder.append(false);}sv => {- return Err(DataFusionError::Internal(format!(+ return _internal_err!("Inconsistent types in ScalarValue::iter_to_array. \Expected List, got {:?}",sv- )))+ )}}}@@ -2524,9 +2524,7 @@ impl ScalarValue {}};} else {- return Err(DataFusionError::Internal(format!(- "Expected Struct but found: {scalar}"- )));+ return _internal_err!("Expected Struct but found: {scalar}");};}@@ -2554,9 +2552,9 @@ impl ScalarValue {}}_ => {- Err(DataFusionError::Internal(format!(+ _internal_err!("Expected scalar of type {value_type} but found: {scalar} {scalar:?}"- )))+ )}}).collect::<Result<Vec<_>>>()?;@@ -2582,10 +2580,10 @@ impl ScalarValue {if let ScalarValue::FixedSizeBinary(_, v) = sv {Ok(v)} else {- Err(DataFusionError::Internal(format!(+ _internal_err!("Inconsistent types in ScalarValue::iter_to_array. \Expected {data_type:?}, got {sv:?}"- )))+ )}}).collect::<Result<Vec<_>>>()?;@@ -2611,11 +2609,11 @@ impl ScalarValue {| DataType::Union(_, _)| DataType::Map(_, _)| DataType::RunEndEncoded(_, _) => {- return Err(DataFusionError::Internal(format!(+ return _internal_err!("Unsupported creation of {:?} array from ScalarValue {:?}",data_type,scalars.peek()- )));+ );}};@@ -2703,9 +2701,9 @@ impl ScalarValue {}}} else {- return Err(DataFusionError::Internal(format!(+ return _internal_err!("Expected ScalarValue::List element. Received {scalar:?}"- )));+ );}}@@ -3641,11 +3639,11 @@ macro_rules! impl_try_from {fn try_from(value: ScalarValue) -> Result<Self> {match value {ScalarValue::$SCALAR(Some(inner_value)) => Ok(inner_value),- _ => Err(DataFusionError::Internal(format!(+ _ => _internal_err!("Cannot convert {:?} to {}",value,std::any::type_name::<Self>()- ))),+ ),}}}@@ -3665,11 +3663,11 @@ impl TryFrom<ScalarValue> for i32 {| ScalarValue::Date32(Some(inner_value))| ScalarValue::Time32Second(Some(inner_value))| ScalarValue::Time32Millisecond(Some(inner_value)) => Ok(inner_value),- _ => Err(DataFusionError::Internal(format!(+ _ => _internal_err!("Cannot convert {:?} to {}",value,std::any::type_name::<Self>()- ))),+ ),}}}@@ -3688,11 +3686,11 @@ impl TryFrom<ScalarValue> for i64 {| ScalarValue::TimestampMicrosecond(Some(inner_value), _)| ScalarValue::TimestampMillisecond(Some(inner_value), _)| ScalarValue::TimestampSecond(Some(inner_value), _) => Ok(inner_value),- _ => Err(DataFusionError::Internal(format!(+ _ => _internal_err!("Cannot convert {:?} to {}",value,std::any::type_name::<Self>()- ))),+ ),}}}@@ -3704,11 +3702,11 @@ impl TryFrom<ScalarValue> for i128 {fn try_from(value: ScalarValue) -> Result<Self> {match value {ScalarValue::Decimal128(Some(inner_value), _, _) => Ok(inner_value),- _ => Err(DataFusionError::Internal(format!(+ _ => _internal_err!("Cannot convert {:?} to {}",value,std::any::type_name::<Self>()- ))),+ ),}}}@@ -3720,11 +3718,11 @@ impl TryFrom<ScalarValue> for i256 {fn try_from(value: ScalarValue) -> Result<Self> {match value {ScalarValue::Decimal256(Some(inner_value), _, _) => Ok(inner_value),- _ => Err(DataFusionError::Internal(format!(+ _ => _internal_err!("Cannot convert {:?} to {}",value,std::any::type_name::<Self>()- ))),+ ),}}}diff --git a/datafusion/core/src/physical_optimizer/join_selection.rs b/datafusion/core/src/physical_optimizer/join_selection.rsindex 9ecfb8993f..be75bf5cea 100644--- a/datafusion/core/src/physical_optimizer/join_selection.rs+++ b/datafusion/core/src/physical_optimizer/join_selection.rs@@ -38,6 +38,7 @@ use crate::physical_plan::projection::ProjectionExec;use crate::physical_plan::ExecutionPlan;use arrow_schema::Schema;+use datafusion_common::internal_err;use datafusion_common::tree_node::{Transformed, TreeNode};use datafusion_common::{DataFusionError, JoinType};use datafusion_physical_expr::expressions::Column;@@ -537,9 +538,7 @@ fn swap_join_according_to_unboundedness((_,JoinType::Right | JoinType::RightSemi | JoinType::RightAnti | JoinType::Full,- ) => Err(DataFusionError::Internal(format!(- "{join_type} join cannot be swapped for unbounded input."- ))),+ ) => internal_err!("{join_type} join cannot be swapped for unbounded input."),(PartitionMode::Partitioned, _) => {swap_hash_join(hash_join, PartitionMode::Partitioned)}diff --git a/datafusion/core/src/physical_optimizer/pruning.rs b/datafusion/core/src/physical_optimizer/pruning.rsindex b0e59499ee..efb1304319 100644--- a/datafusion/core/src/physical_optimizer/pruning.rs+++ b/datafusion/core/src/physical_optimizer/pruning.rs@@ -46,7 +46,7 @@ use arrow::{};use datafusion_common::{downcast_value, ScalarValue};use datafusion_common::{- plan_err,+ internal_err, plan_err,tree_node::{Transformed, TreeNode},};use datafusion_physical_expr::utils::collect_columns;@@ -186,10 +186,10 @@ impl PruningPredicate {Ok(vec![v; statistics.num_containers()])}other => {- Err(DataFusionError::Internal(format!(+ internal_err!("Unexpected result of pruning predicate evaluation. Expected Boolean array \or scalar but got {other:?}"- )))+ )}}}@@ -399,11 +399,11 @@ fn build_statistics_record_batch<S: PruningStatistics>(let array = array.unwrap_or_else(|| new_null_array(data_type, num_containers));if num_containers != array.len() {- return Err(DataFusionError::Internal(format!(+ return internal_err!("mismatched statistics length. Expected {}, got {}",num_containers,array.len()- )));+ );}// cast statistics array to required data type (e.g. parquetdiff --git a/datafusion/core/src/physical_plan/aggregates/mod.rs b/datafusion/core/src/physical_plan/aggregates/mod.rsindex be3b868499..a2878140b8 100644--- a/datafusion/core/src/physical_plan/aggregates/mod.rs+++ b/datafusion/core/src/physical_plan/aggregates/mod.rs@@ -1238,7 +1238,7 @@ mod tests {use arrow::compute::{concat_batches, SortOptions};use arrow::datatypes::{DataType, Field, Schema, SchemaRef};use arrow::record_batch::RecordBatch;- use datafusion_common::{DataFusionError, Result, ScalarValue};+ use datafusion_common::{internal_err, DataFusionError, Result, ScalarValue};use datafusion_execution::runtime_env::{RuntimeConfig, RuntimeEnv};use datafusion_physical_expr::expressions::{lit, ApproxDistinct, Column, Count, FirstValue, LastValue, Median,@@ -1670,9 +1670,7 @@ mod tests {self: Arc<Self>,_: Vec<Arc<dyn ExecutionPlan>>,) -> Result<Arc<dyn ExecutionPlan>> {- Err(DataFusionError::Internal(format!(- "Children cannot be replaced in {self:?}"- )))+ internal_err!("Children cannot be replaced in {self:?}")}fn execute(diff --git a/datafusion/core/src/physical_plan/analyze.rs b/datafusion/core/src/physical_plan/analyze.rsindex d8c87d2f51..132cd358ff 100644--- a/datafusion/core/src/physical_plan/analyze.rs+++ b/datafusion/core/src/physical_plan/analyze.rs@@ -25,7 +25,7 @@ use crate::physical_plan::{Statistics,};use arrow::{array::StringBuilder, datatypes::SchemaRef, record_batch::RecordBatch};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};use futures::StreamExt;use super::expressions::PhysicalSortExpr;@@ -124,9 +124,9 @@ impl ExecutionPlan for AnalyzeExec {context: Arc<TaskContext>,) -> Result<SendableRecordBatchStream> {if 0 != partition {- return Err(DataFusionError::Internal(format!(+ return internal_err!("AnalyzeExec invalid partition. Expected 0, got {partition}"- )));+ );}// Gather futures that will run each input partition indiff --git a/datafusion/core/src/physical_plan/coalesce_partitions.rs b/datafusion/core/src/physical_plan/coalesce_partitions.rsindex cc2c9b5e4b..da84a5898a 100644--- a/datafusion/core/src/physical_plan/coalesce_partitions.rs+++ b/datafusion/core/src/physical_plan/coalesce_partitions.rs@@ -31,7 +31,7 @@ use crate::physical_plan::{};use arrow::datatypes::SchemaRef;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};use datafusion_execution::TaskContext;/// Merge execution plan executes partitions in parallel and combines them into a single@@ -120,9 +120,7 @@ impl ExecutionPlan for CoalescePartitionsExec {) -> Result<SendableRecordBatchStream> {// CoalescePartitionsExec produces a single partitionif 0 != partition {- return Err(DataFusionError::Internal(format!(- "CoalescePartitionsExec invalid partition {partition}"- )));+ return internal_err!("CoalescePartitionsExec invalid partition {partition}");}let input_partitions = self.input.output_partitioning().partition_count();diff --git a/datafusion/core/src/physical_plan/empty.rs b/datafusion/core/src/physical_plan/empty.rsindex 7da4e80c12..b38486991e 100644--- a/datafusion/core/src/physical_plan/empty.rs+++ b/datafusion/core/src/physical_plan/empty.rs@@ -26,7 +26,7 @@ use crate::physical_plan::{use arrow::array::{ArrayRef, NullArray};use arrow::datatypes::{DataType, Field, Fields, Schema, SchemaRef};use arrow::record_batch::RecordBatch;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};use log::trace;use super::expressions::PhysicalSortExpr;@@ -149,10 +149,11 @@ impl ExecutionPlan for EmptyExec {trace!("Start EmptyExec::execute for partition {} of context session_id {} and task_id {:?}", partition, context.session_id(), context.task_id());if partition >= self.partitions {- return Err(DataFusionError::Internal(format!(+ return internal_err!("EmptyExec invalid partition {} (expected less than {})",- partition, self.partitions- )));+ partition,+ self.partitions+ );}Ok(Box::pin(MemoryStream::try_new(diff --git a/datafusion/core/src/physical_plan/explain.rs b/datafusion/core/src/physical_plan/explain.rsindex d732e70f8a..7ee6f268d8 100644--- a/datafusion/core/src/physical_plan/explain.rs+++ b/datafusion/core/src/physical_plan/explain.rs@@ -22,7 +22,7 @@ use std::sync::Arc;use datafusion_common::display::StringifiedPlan;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};use crate::physical_plan::{DisplayFormatType, ExecutionPlan, Partitioning, Statistics};use arrow::{array::StringBuilder, datatypes::SchemaRef, record_batch::RecordBatch};@@ -123,9 +123,7 @@ impl ExecutionPlan for ExplainExec {) -> Result<SendableRecordBatchStream> {trace!("Start ExplainExec::execute for partition {} of context session_id {} and task_id {:?}", partition, context.session_id(), context.task_id());if 0 != partition {- return Err(DataFusionError::Internal(format!(- "ExplainExec invalid partition {partition}"- )));+ return internal_err!("ExplainExec invalid partition {partition}");}let mut type_builder =diff --git a/datafusion/core/src/physical_plan/joins/hash_join.rs b/datafusion/core/src/physical_plan/joins/hash_join.rsindex 3522656142..da0161e163 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::{plan_err, DataFusionError, JoinType, Result};+use datafusion_common::{internal_err, plan_err, DataFusionError, JoinType, Result};use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};use datafusion_execution::TaskContext;use datafusion_physical_expr::OrderingEquivalenceProperties;@@ -430,10 +430,10 @@ impl ExecutionPlan for HashJoinExec {let right_partitions = self.right.output_partitioning().partition_count();if self.mode == PartitionMode::Partitioned && left_partitions != right_partitions{- return Err(DataFusionError::Internal(format!(+ return internal_err!("Invalid HashJoinExec, partition count mismatch {left_partitions}!={right_partitions},\- consider using RepartitionExec",- )));+ consider using RepartitionExec"+ );}let join_metrics = BuildProbeJoinMetrics::new(partition, &self.metrics);@@ -1157,9 +1157,9 @@ pub fn equal_rows(}other => {// This is internal because we should have caught this before.- err = Some(Err(DataFusionError::Internal(format!(+ err = Some(internal_err!("Unsupported data type in hasher: {other}"- ))));+ ));false}});diff --git a/datafusion/core/src/physical_plan/joins/sort_merge_join.rs b/datafusion/core/src/physical_plan/joins/sort_merge_join.rsindex 902b022857..71d34359f3 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::{plan_err, DataFusionError, JoinType, Result};+use datafusion_common::{internal_err, plan_err, DataFusionError, JoinType, Result};use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};use datafusion_execution::TaskContext;use datafusion_physical_expr::{OrderingEquivalenceProperties, PhysicalSortRequirement};@@ -325,10 +325,10 @@ impl ExecutionPlan for SortMergeJoinExec {let left_partitions = self.left.output_partitioning().partition_count();let right_partitions = self.right.output_partitioning().partition_count();if left_partitions != right_partitions {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Invalid SortMergeJoinExec, partition count mismatch {left_partitions}!={right_partitions},\- consider using RepartitionExec",- )));+ consider using RepartitionExec"+ );}let (on_left, on_right) = self.on.iter().cloned().unzip();let (streamed, buffered, on_streamed, on_buffered) =diff --git a/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rs b/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rsindex 64231a9ba9..3309a39b61 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::{plan_err, JoinType};+use datafusion_common::{internal_err, plan_err, JoinType};use datafusion_common::{DataFusionError, Result};use datafusion_execution::TaskContext;@@ -498,10 +498,10 @@ impl ExecutionPlan for SymmetricHashJoinExec {let left_partitions = self.left.output_partitioning().partition_count();let right_partitions = self.right.output_partitioning().partition_count();if left_partitions != right_partitions {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Invalid SymmetricHashJoinExec, partition count mismatch {left_partitions}!={right_partitions},\- consider using RepartitionExec",- )));+ consider using RepartitionExec"+ );}// If `filter_state` and `filter` are both present, then calculate sorted filter expressions// for both sides, and build an expression graph if one is not already built.diff --git a/datafusion/core/src/physical_plan/limit.rs b/datafusion/core/src/physical_plan/limit.rsindex d493d1c56e..4d1766cd6e 100644--- a/datafusion/core/src/physical_plan/limit.rs+++ b/datafusion/core/src/physical_plan/limit.rs@@ -33,7 +33,7 @@ use super::{DisplayAs, RecordBatchStream, SendableRecordBatchStream, Statistics}use arrow::array::ArrayRef;use arrow::datatypes::SchemaRef;use arrow::record_batch::{RecordBatch, RecordBatchOptions};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};use datafusion_execution::TaskContext;use datafusion_physical_expr::OrderingEquivalenceProperties;@@ -165,9 +165,7 @@ impl ExecutionPlan for GlobalLimitExec {);// GlobalLimitExec has a single output partitionif 0 != partition {- return Err(DataFusionError::Internal(format!(- "GlobalLimitExec invalid partition {partition}"- )));+ return internal_err!("GlobalLimitExec invalid partition {partition}");}// GlobalLimitExec requires a single input partitiondiff --git a/datafusion/core/src/physical_plan/memory.rs b/datafusion/core/src/physical_plan/memory.rsindex be8385b586..877410c97c 100644--- a/datafusion/core/src/physical_plan/memory.rs+++ b/datafusion/core/src/physical_plan/memory.rs@@ -25,7 +25,7 @@ use super::{use arrow::datatypes::SchemaRef;use arrow::record_batch::RecordBatch;use core::fmt;-use datafusion_common::{project_schema, Result};+use datafusion_common::{internal_err, project_schema, Result};use std::any::Any;use std::sync::Arc;use std::task::{Context, Poll};@@ -128,9 +128,7 @@ impl ExecutionPlan for MemoryExec {self: Arc<Self>,_: Vec<Arc<dyn ExecutionPlan>>,) -> Result<Arc<dyn ExecutionPlan>> {- Err(DataFusionError::Internal(format!(- "Children cannot be replaced in {self:?}"- )))+ internal_err!("Children cannot be replaced in {self:?}")}fn execute(diff --git a/datafusion/core/src/physical_plan/sorts/sort_preserving_merge.rs b/datafusion/core/src/physical_plan/sorts/sort_preserving_merge.rsindex 97d5813610..e90b67101e 100644--- a/datafusion/core/src/physical_plan/sorts/sort_preserving_merge.rs+++ b/datafusion/core/src/physical_plan/sorts/sort_preserving_merge.rs@@ -33,7 +33,7 @@ use crate::physical_plan::{use datafusion_execution::memory_pool::MemoryConsumer;use arrow::datatypes::SchemaRef;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};use datafusion_execution::TaskContext;use datafusion_physical_expr::{EquivalenceProperties, OrderingEquivalenceProperties, PhysicalSortRequirement,@@ -202,9 +202,9 @@ impl ExecutionPlan for SortPreservingMergeExec {partition);if 0 != partition {- return Err(DataFusionError::Internal(format!(+ return internal_err!("SortPreservingMergeExec invalid partition {partition}"- )));+ );}let input_partitions = self.input.output_partitioning().partition_count();diff --git a/datafusion/core/src/physical_plan/stream.rs b/datafusion/core/src/physical_plan/stream.rsindex 2e9d40cfe5..695ca35714 100644--- a/datafusion/core/src/physical_plan/stream.rs+++ b/datafusion/core/src/physical_plan/stream.rs@@ -24,6 +24,7 @@ use std::task::Poll;use crate::physical_plan::displayable;use arrow::{datatypes::SchemaRef, record_batch::RecordBatch};+use datafusion_common::internal_err;use datafusion_common::DataFusionError;use datafusion_common::Result;use datafusion_execution::TaskContext;@@ -180,9 +181,7 @@ impl RecordBatchReceiverStreamBuilder {// the JoinSet were aborted, which in turn// would imply that the receiver has been// dropped and this code is not running- return Some(Err(DataFusionError::Internal(format!(- "Non Panic Task error: {e}"- ))));+ return Some(internal_err!("Non Panic Task error: {e}"));}}}diff --git a/datafusion/core/src/physical_plan/streaming.rs b/datafusion/core/src/physical_plan/streaming.rsindex 28623f2995..6c33f88a39 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::{plan_err, DataFusionError, Result, Statistics};+use datafusion_common::{internal_err, plan_err, DataFusionError, Result, Statistics};use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr};use log::debug;@@ -165,9 +165,7 @@ impl ExecutionPlan for StreamingTableExec {self: Arc<Self>,_children: Vec<Arc<dyn ExecutionPlan>>,) -> Result<Arc<dyn ExecutionPlan>> {- Err(DataFusionError::Internal(format!(- "Children cannot be replaced in {self:?}"- )))+ internal_err!("Children cannot be replaced in {self:?}")}fn execute(diff --git a/datafusion/core/src/physical_plan/values.rs b/datafusion/core/src/physical_plan/values.rsindex 757e020350..ff5e719690 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::{plan_err, ScalarValue};+use datafusion_common::{internal_err, plan_err, ScalarValue};use datafusion_common::{DataFusionError, Result};use datafusion_execution::TaskContext;use std::any::Any;@@ -147,9 +147,9 @@ impl ExecutionPlan for ValuesExec {) -> Result<SendableRecordBatchStream> {// GlobalLimitExec has a single output partitionif 0 != partition {- return Err(DataFusionError::Internal(format!(+ return internal_err!("ValuesExec invalid partition {partition} (expected 0)"- )));+ );}Ok(Box::pin(MemoryStream::try_new(diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rsindex f154c2a173..85396576d9 100644--- a/datafusion/core/src/physical_planner.rs+++ b/datafusion/core/src/physical_planner.rs@@ -73,7 +73,7 @@ use crate::{use arrow::compute::SortOptions;use arrow::datatypes::{Schema, SchemaRef};use async_trait::async_trait;-use datafusion_common::{plan_err, DFSchema, ScalarValue};+use datafusion_common::{internal_err, plan_err, DFSchema, ScalarValue};use datafusion_expr::expr::{self, AggregateFunction, AggregateUDF, Alias, Between, BinaryExpr, Cast,GetFieldAccess, GetIndexedField, GroupingSet, InList, Like, ScalarUDF, TryCast,@@ -1819,9 +1819,7 @@ pub fn create_aggregate_expr_with_name_and_maybe_filter(udaf::create_aggregate_expr(fun, &args, physical_input_schema, name);Ok((agg_expr?, filter, order_by))}- other => Err(DataFusionError::Internal(format!(- "Invalid aggregate expression '{other:?}'"- ))),+ other => internal_err!("Invalid aggregate expression '{other:?}'"),}}diff --git a/datafusion/core/src/test/exec.rs b/datafusion/core/src/test/exec.rsindex 63c86084ea..682f31a7fe 100644--- a/datafusion/core/src/test/exec.rs+++ b/datafusion/core/src/test/exec.rs@@ -44,6 +44,8 @@ use crate::{execution::context::TaskContext, physical_plan::stream::RecordBatchStreamAdapter,};+use datafusion_common::internal_err;+/// Index into the data that has been returned so far#[derive(Debug, Default, Clone)]pub struct BatchIndex {@@ -444,9 +446,7 @@ impl ExecutionPlan for ErrorExec {partition: usize,_context: Arc<TaskContext>,) -> Result<SendableRecordBatchStream> {- Err(DataFusionError::Internal(format!(- "ErrorExec, unsurprisingly, errored in partition {partition}"- )))+ internal_err!("ErrorExec, unsurprisingly, errored in partition {partition}")}fn statistics(&self) -> Statistics {@@ -612,9 +612,7 @@ impl ExecutionPlan for BlockingExec {self: Arc<Self>,_: Vec<Arc<dyn ExecutionPlan>>,) -> Result<Arc<dyn ExecutionPlan>> {- Err(DataFusionError::Internal(format!(- "Children cannot be replaced in {self:?}"- )))+ internal_err!("Children cannot be replaced in {self:?}")}fn execute(@@ -749,10 +747,7 @@ impl ExecutionPlan for PanicExec {self: Arc<Self>,_: Vec<Arc<dyn ExecutionPlan>>,) -> Result<Arc<dyn ExecutionPlan>> {- Err(DataFusionError::Internal(format!(- "Children cannot be replaced in {:?}",- self- )))+ internal_err!("Children cannot be replaced in {:?}", self)}fn execute(diff --git a/datafusion/core/tests/user_defined/user_defined_plan.rs b/datafusion/core/tests/user_defined/user_defined_plan.rsindex 0771ef7f79..57a802804b 100644--- a/datafusion/core/tests/user_defined/user_defined_plan.rs+++ b/datafusion/core/tests/user_defined/user_defined_plan.rs@@ -68,6 +68,7 @@ use arrow::{};use datafusion::{common::cast::{as_int64_array, as_string_array},+ common::internal_err,common::DFSchemaRef,error::{DataFusionError, Result},execution::{@@ -480,9 +481,7 @@ impl ExecutionPlan for TopKExec {context: Arc<TaskContext>,) -> Result<SendableRecordBatchStream> {if 0 != partition {- return Err(DataFusionError::Internal(format!(- "TopKExec invalid partition {partition}"- )));+ return internal_err!("TopKExec invalid partition {partition}");}Ok(Box::pin(TopKReader {diff --git a/datafusion/expr/src/built_in_function.rs b/datafusion/expr/src/built_in_function.rsindex a0c7a839e7..35c117a12c 100644--- a/datafusion/expr/src/built_in_function.rs+++ b/datafusion/expr/src/built_in_function.rs@@ -24,7 +24,7 @@ use crate::{Volatility,};use arrow::datatypes::{DataType, Field, Fields, IntervalUnit, TimeUnit};-use datafusion_common::{plan_err, DataFusionError, Result};+use datafusion_common::{internal_err, plan_err, DataFusionError, Result};use std::collections::HashMap;use std::fmt;use std::str::FromStr;@@ -527,9 +527,9 @@ impl BuiltinScalarFunction {}}_ => {- return Err(DataFusionError::Internal(format!(+ return internal_err!("The {self} function can only accept list as the args."- )))+ )}}}@@ -544,9 +544,9 @@ impl BuiltinScalarFunction {}BuiltinScalarFunction::ArrayElement => match &input_expr_types[0] {List(field) => Ok(field.data_type().clone()),- _ => Err(DataFusionError::Internal(format!(+ _ => internal_err!("The {self} function can only accept list as the first argument"- ))),+ ),},BuiltinScalarFunction::ArrayLength => Ok(UInt64),BuiltinScalarFunction::ArrayNdims => Ok(UInt64),@@ -610,9 +610,9 @@ impl BuiltinScalarFunction {Timestamp(Microsecond, _) => Ok(Timestamp(Microsecond, None)),Timestamp(Millisecond, _) => Ok(Timestamp(Millisecond, None)),Timestamp(Second, _) => Ok(Timestamp(Second, None)),- _ => Err(DataFusionError::Internal(format!(+ _ => internal_err!("The {self} function can only accept timestamp as the second arg."- ))),+ ),}}BuiltinScalarFunction::InitCap => {@@ -1405,19 +1405,19 @@ macro_rules! make_utf8_to_return_type {DataType::Null => DataType::Null,_ => {// this error is internal as `data_types` should have captured this.- return Err(DataFusionError::Internal(format!(+ return internal_err!("The {:?} function can only accept strings.",name- )));+ );}}}_ => {// this error is internal as `data_types` should have captured this.- return Err(DataFusionError::Internal(format!(+ return internal_err!("The {:?} function can only accept strings.",name- )));+ );}})}@@ -1436,9 +1436,9 @@ fn utf8_or_binary_to_binary_type(arg_type: &DataType, name: &str) -> Result<DataDataType::Null => DataType::Null,_ => {// this error is internal as `data_types` should have captured this.- return Err(DataFusionError::Internal(format!(+ return internal_err!("The {name:?} function can only accept strings or binary arrays."- )));+ );}})}diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rsindex 1ee4fb810d..85eb59098c 100644--- a/datafusion/expr/src/logical_plan/plan.rs+++ b/datafusion/expr/src/logical_plan/plan.rs@@ -39,9 +39,9 @@ use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeVisitor, VisitRecursion,};use datafusion_common::{- aggregate_functional_dependencies, plan_err, Column, DFField, DFSchema, DFSchemaRef,- DataFusionError, FunctionalDependencies, OwnedTableReference, Result, ScalarValue,- UnnestOptions,+ aggregate_functional_dependencies, internal_err, plan_err, Column, DFField, DFSchema,+ DFSchemaRef, DataFusionError, FunctionalDependencies, OwnedTableReference, Result,+ ScalarValue, UnnestOptions,};// backwards compatibilitypub use datafusion_common::display::{PlanType, StringifiedPlan, ToStringifiedPlan};@@ -791,11 +791,11 @@ impl LogicalPlan {})?;// check if the data type of the value matches the data type of the placeholderif Some(value.get_datatype()) != *data_type {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Placeholder value type mismatch: expected {:?}, got {:?}",data_type,value.get_datatype()- )));+ );}// Replace the placeholder with the valueOk(Transformed::Yes(Expr::Literal(value.clone())))diff --git a/datafusion/expr/src/type_coercion/aggregates.rs b/datafusion/expr/src/type_coercion/aggregates.rsindex 2dc806e57c..094b6e9da4 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::{plan_err, DataFusionError, Result};+use datafusion_common::{internal_err, plan_err, DataFusionError, Result};use std::ops::Deref;use crate::{AggregateFunction, Signature, TypeSignature};@@ -330,9 +330,9 @@ fn check_arg_count(}}_ => {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Aggregate functions do not support this {signature:?}"- )));+ );}}Ok(())diff --git a/datafusion/expr/src/utils.rs b/datafusion/expr/src/utils.rsindex 90307f1491..88fd9fa6b7 100644--- a/datafusion/expr/src/utils.rs+++ b/datafusion/expr/src/utils.rs@@ -36,8 +36,8 @@ use datafusion_common::tree_node::{RewriteRecursion, TreeNode, TreeNodeRewriter, VisitRecursion,};use datafusion_common::{- plan_err, Column, Constraints, DFField, DFSchema, DFSchemaRef, DataFusionError,- Result, ScalarValue, TableReference,+ internal_err, plan_err, Column, Constraints, DFField, DFSchema, DFSchemaRef,+ DataFusionError, Result, ScalarValue, TableReference,};use sqlparser::ast::{ExceptSelectItem, ExcludeSelectItem, WildcardAdditionalOptions};use std::cmp::Ordering;@@ -593,9 +593,9 @@ pub fn group_window_expr_by_sort_keys(}Ok(())}- other => Err(DataFusionError::Internal(format!(- "Impossibly got non-window expr {other:?}",- ))),+ other => internal_err!(+ "Impossibly got non-window expr {other:?}"+ ),})?;Ok(result)}@@ -875,9 +875,9 @@ pub fn from_plan(if let Expr::BinaryExpr(BinaryExpr { left, op:Operator::Eq, right }) = unalias_expr {Ok((*left, *right))} else {- Err(DataFusionError::Internal(format!(+ internal_err!("The front part expressions should be an binary equiality expression, actual:{equi_expr}"- )))+ )}}).collect::<Result<Vec<(Expr, Expr)>>>()?;diff --git a/datafusion/expr/src/window_state.rs b/datafusion/expr/src/window_state.rsindex 09ed83a5a3..ade4e7e3b9 100644--- a/datafusion/expr/src/window_state.rs+++ b/datafusion/expr/src/window_state.rs@@ -26,6 +26,7 @@ use arrow::{record_batch::RecordBatch,};use datafusion_common::{+ internal_err,utils::{compare_rows, get_row_at_idx, search_in_slice},DataFusionError, Result, ScalarValue,};@@ -201,9 +202,9 @@ impl WindowFrameContext {WindowFrameBound::CurrentRow => idx,// UNBOUNDED FOLLOWINGWindowFrameBound::Following(ScalarValue::UInt64(None)) => {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Frame start cannot be UNBOUNDED FOLLOWING '{window_frame:?}'"- )))+ )}WindowFrameBound::Following(ScalarValue::UInt64(Some(n))) => {std::cmp::min(idx + n as usize, length)@@ -216,9 +217,9 @@ impl WindowFrameContext {let end = match window_frame.end_bound {// UNBOUNDED PRECEDINGWindowFrameBound::Preceding(ScalarValue::UInt64(None)) => {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Frame end cannot be UNBOUNDED PRECEDING '{window_frame:?}'"- )))+ )}WindowFrameBound::Preceding(ScalarValue::UInt64(Some(n))) => {if idx >= n as usize {diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rsindex f0e5f114b7..b5d25eb3ed 100644--- a/datafusion/optimizer/src/analyzer/type_coercion.rs+++ b/datafusion/optimizer/src/analyzer/type_coercion.rs@@ -24,7 +24,7 @@ use arrow::datatypes::{DataType, IntervalUnit};use datafusion_common::config::ConfigOptions;use datafusion_common::tree_node::{RewriteRecursion, TreeNodeRewriter};use datafusion_common::{- plan_err, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue,+ internal_err, plan_err, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue,};use datafusion_expr::expr::{self, Between, BinaryExpr, Case, Exists, InList, InSubquery, Like, ScalarFunction,@@ -492,9 +492,9 @@ fn coerce_window_frame(} else if is_datetime(col_type) {&DataType::Interval(IntervalUnit::MonthDayNano)} else {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Cannot run range queries on datatype: {col_type:?}"- )));+ );}} else {return Err(DataFusionError::Internal(diff --git a/datafusion/optimizer/src/simplify_expressions/utils.rs b/datafusion/optimizer/src/simplify_expressions/utils.rsindex daebfc5a2b..28c61427c5 100644--- a/datafusion/optimizer/src/simplify_expressions/utils.rs+++ b/datafusion/optimizer/src/simplify_expressions/utils.rs@@ -18,7 +18,7 @@//! Utility functions for expression simplificationuse crate::simplify_expressions::SimplifyInfo;-use datafusion_common::{DataFusionError, Result, ScalarValue};+use datafusion_common::{internal_err, DataFusionError, Result, ScalarValue};use datafusion_expr::expr::ScalarFunction;use datafusion_expr::{expr::{Between, BinaryExpr, InList},@@ -226,9 +226,7 @@ pub fn is_negative_of(not_expr: &Expr, expr: &Expr) -> bool {pub fn as_bool_lit(expr: Expr) -> Result<Option<bool>> {match expr {Expr::Literal(ScalarValue::Boolean(v)) => Ok(v),- _ => Err(DataFusionError::Internal(format!(- "Expected boolean literal, got {expr:?}"- ))),+ _ => internal_err!("Expected boolean literal, got {expr:?}"),}}@@ -438,9 +436,9 @@ pub fn simpl_concat(args: Vec<Expr>) -> Result<Expr> {ScalarValue::Utf8(Some(v)) | ScalarValue::LargeUtf8(Some(v)),) => contiguous_scalar += &v,Expr::Literal(x) => {- return Err(DataFusionError::Internal(format!(+ return internal_err!("The scalar {x} should be casted to string type during the type coercion."- )))+ )}// If the arg is not a literal, we should first push the current `contiguous_scalar`// to the `new_args` (if it is not empty) and reset it to empty string.@@ -496,7 +494,7 @@ pub fn simpl_concat_ws(delimiter: &Expr, args: &[Expr]) -> Result<Expr> {}}}- Expr::Literal(s) => return Err(DataFusionError::Internal(format!("The scalar {s} should be casted to string type during the type coercion."))),+ Expr::Literal(s) => return internal_err!("The scalar {s} should be casted to string type during the type coercion."),// If the arg is not a literal, we should first push the current `contiguous_scalar`// to the `new_args` and reset it to None.// Then pushing this arg to the `new_args`.@@ -521,9 +519,9 @@ pub fn simpl_concat_ws(delimiter: &Expr, args: &[Expr]) -> Result<Expr> {None => Ok(Expr::Literal(ScalarValue::Utf8(None))),}}- Expr::Literal(d) => Err(DataFusionError::Internal(format!(+ Expr::Literal(d) => internal_err!("The scalar {d} should be casted to string type during the type coercion."- ))),+ ),d => Ok(concat_ws(d.clone(),args.iter()diff --git a/datafusion/optimizer/src/unwrap_cast_in_comparison.rs b/datafusion/optimizer/src/unwrap_cast_in_comparison.rsindex daa695f771..0be856ca9b 100644--- a/datafusion/optimizer/src/unwrap_cast_in_comparison.rs+++ b/datafusion/optimizer/src/unwrap_cast_in_comparison.rs@@ -26,7 +26,9 @@ use arrow::datatypes::{};use arrow::temporal_conversions::{MICROSECONDS, MILLISECONDS, NANOSECONDS};use datafusion_common::tree_node::{RewriteRecursion, TreeNodeRewriter};-use datafusion_common::{DFSchemaRef, DataFusionError, Result, ScalarValue};+use datafusion_common::{+ internal_err, DFSchemaRef, DataFusionError, Result, ScalarValue,+};use datafusion_expr::expr::{BinaryExpr, Cast, InList, TryCast};use datafusion_expr::expr_rewriter::rewrite_preserving_name;use datafusion_expr::utils::from_plan;@@ -226,10 +228,10 @@ impl TreeNodeRewriter for UnwrapCastExprRewriter {.map(|right| {let right_type = right.get_type(&self.schema)?;if !is_support_data_type(&right_type) {- return Err(DataFusionError::Internal(format!(+ return internal_err!("The type of list expr {} not support",&right_type- )));+ );}match right {Expr::Literal(right_lit_value) => {@@ -240,16 +242,16 @@ impl TreeNodeRewriter for UnwrapCastExprRewriter {if let Some(value) = casted_scalar_value {Ok(lit(value))} else {- Err(DataFusionError::Internal(format!(+ internal_err!("Can't cast the list expr {:?} to type {:?}",right_lit_value, &internal_left_type- )))+ )}}- other_expr => Err(DataFusionError::Internal(format!(+ other_expr => internal_err!("Only support literal expr to optimize, but the expr is {:?}",&other_expr- ))),+ ),}}).collect::<Result<Vec<_>>>();@@ -322,9 +324,7 @@ fn try_cast_literal_to_type(DataType::Timestamp(_, _) => 1_i128,DataType::Decimal128(_, scale) => 10_i128.pow(*scale as u32),other_type => {- return Err(DataFusionError::Internal(format!(- "Error target data type {other_type:?}"- )));+ return internal_err!("Error target data type {other_type:?}");}};let (target_min, target_max) = match target_type {@@ -345,9 +345,7 @@ fn try_cast_literal_to_type(MAX_DECIMAL_FOR_EACH_PRECISION[*precision as usize - 1],),other_type => {- return Err(DataFusionError::Internal(format!(- "Error target data type {other_type:?}"- )));+ return internal_err!("Error target data type {other_type:?}");}};let lit_value_target_type = match lit_value {@@ -383,9 +381,7 @@ fn try_cast_literal_to_type(}}other_value => {- return Err(DataFusionError::Internal(format!(- "Invalid literal value {other_value:?}"- )));+ return internal_err!("Invalid literal value {other_value:?}");}};@@ -440,9 +436,7 @@ fn try_cast_literal_to_type(ScalarValue::Decimal128(Some(value), *p, *s)}other_type => {- return Err(DataFusionError::Internal(format!(- "Error target data type {other_type:?}"- )));+ return internal_err!("Error target data type {other_type:?}");}};Ok(Some(result_scalar))diff --git a/datafusion/physical-expr/src/aggregate/approx_percentile_cont.rs b/datafusion/physical-expr/src/aggregate/approx_percentile_cont.rsindex 46825a5fc0..86d173be84 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::internal_err;use datafusion_common::plan_err;use datafusion_common::DataFusionError;use datafusion_common::Result;@@ -372,9 +373,9 @@ impl ApproxPercentileAccumulator {.filter_map(|v| v.try_as_f64().transpose()).collect::<Result<Vec<_>>>()?)}- e => Err(DataFusionError::Internal(format!(+ e => internal_err!("APPROX_PERCENTILE_CONT is not expected to receive the type {e:?}"- ))),+ ),}}}diff --git a/datafusion/physical-expr/src/aggregate/average.rs b/datafusion/physical-expr/src/aggregate/average.rsindex 9c01093edf..85651c1f7c 100644--- a/datafusion/physical-expr/src/aggregate/average.rs+++ b/datafusion/physical-expr/src/aggregate/average.rs@@ -40,6 +40,7 @@ use arrow::{use arrow_array::{Array, ArrowNativeTypeOp, ArrowNumericType, ArrowPrimitiveType, PrimitiveArray,};+use datafusion_common::internal_err;use datafusion_common::{downcast_value, ScalarValue};use datafusion_common::{DataFusionError, Result};use datafusion_expr::Accumulator;@@ -273,9 +274,9 @@ impl Accumulator for AvgAccumulator {DataType::Decimal128(p, s) => {Ok(ScalarValue::Decimal128(None, *p, *s))}- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("Error returned data type in AvgAccumulator {other:?}"- ))),+ ),},Some(value) => {// now the sum_type and return type is not the same, need to convert the sum type to return typediff --git a/datafusion/physical-expr/src/aggregate/bit_and_or_xor.rs b/datafusion/physical-expr/src/aggregate/bit_and_or_xor.rsindex dfc07cc04b..3dda6d6bcf 100644--- a/datafusion/physical-expr/src/aggregate/bit_and_or_xor.rs+++ b/datafusion/physical-expr/src/aggregate/bit_and_or_xor.rs@@ -34,6 +34,7 @@ use arrow::{},datatypes::Field,};+use datafusion_common::internal_err;use datafusion_common::{downcast_value, DataFusionError, Result, ScalarValue};use datafusion_expr::Accumulator;use std::collections::HashSet;@@ -96,9 +97,9 @@ macro_rules! bit_and_or_xor_batch {typed_bit_and_or_xor_batch!($VALUES, UInt8Array, UInt8, $OP)}e => {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Bit and/Bit or/Bit xor is not expected to receive the type {e:?}"- )));+ );}}}};diff --git a/datafusion/physical-expr/src/aggregate/bool_and_or.rs b/datafusion/physical-expr/src/aggregate/bool_and_or.rsindex f963f680df..9e1015fd2a 100644--- a/datafusion/physical-expr/src/aggregate/bool_and_or.rs+++ b/datafusion/physical-expr/src/aggregate/bool_and_or.rs@@ -23,6 +23,7 @@ use arrow::{array::{ArrayRef, BooleanArray},datatypes::Field,};+use datafusion_common::internal_err;use datafusion_common::{downcast_value, DataFusionError, Result, ScalarValue};use datafusion_expr::Accumulator;use std::any::Any;@@ -51,9 +52,9 @@ macro_rules! bool_and_or_batch {typed_bool_and_or_batch!($VALUES, BooleanArray, Boolean, $OP)}e => {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Bool and/Bool or is not expected to receive the type {e:?}"- )));+ );}}}};diff --git a/datafusion/physical-expr/src/aggregate/count_distinct.rs b/datafusion/physical-expr/src/aggregate/count_distinct.rsindex 94e6c08283..3f91b2a0db 100644--- a/datafusion/physical-expr/src/aggregate/count_distinct.rs+++ b/datafusion/physical-expr/src/aggregate/count_distinct.rs@@ -213,6 +213,7 @@ mod tests {Int64Array, Int8Array, UInt16Array, UInt32Array, UInt64Array, UInt8Array,};use arrow::datatypes::DataType;+ use datafusion_common::internal_err;macro_rules! state_to_vec {($LIST:expr, $DATA_TYPE:ident, $PRIM_TY:ty) => {{@@ -445,9 +446,9 @@ mod tests {ScalarValue::Int64(c) => c.ok_or_else(|| {DataFusionError::Internal("Found None count".to_string())}),- scalar => Err(DataFusionError::Internal(format!(- "Found non int64 scalar value from count: {scalar}"- ))),+ scalar => {+ internal_err!("Found non int64 scalar value from count: {scalar}")+ }}?;Ok((state_vec, count))};diff --git a/datafusion/physical-expr/src/aggregate/median.rs b/datafusion/physical-expr/src/aggregate/median.rsindex 28f1fc3199..2f60966093 100644--- a/datafusion/physical-expr/src/aggregate/median.rs+++ b/datafusion/physical-expr/src/aggregate/median.rs@@ -23,6 +23,7 @@ use crate::{AggregateExpr, PhysicalExpr};use arrow::array::{Array, ArrayRef, UInt32Array};use arrow::compute::sort_to_indices;use arrow::datatypes::{DataType, Field};+use datafusion_common::internal_err;use datafusion_common::{DataFusionError, Result, ScalarValue};use datafusion_expr::Accumulator;use std::any::Any;@@ -150,9 +151,9 @@ impl Accumulator for MedianAccumulator {}ScalarValue::List(None, _) => {} // skip empty statev => {- return Err(DataFusionError::Internal(format!(+ return internal_err!("unexpected state in median. Expected DataType::List, got {v:?}"- )))+ )}}}@@ -211,9 +212,7 @@ impl Accumulator for MedianAccumulator {ScalarValue::Decimal128(Some(v / 2), p, s)}v => {- return Err(DataFusionError::Internal(format!(- "Unsupported type in MedianAccumulator: {v:?}"- )))+ return internal_err!("Unsupported type in MedianAccumulator: {v:?}")}}} else {diff --git a/datafusion/physical-expr/src/aggregate/min_max.rs b/datafusion/physical-expr/src/aggregate/min_max.rsindex 613e653251..bcd16c0a1f 100644--- a/datafusion/physical-expr/src/aggregate/min_max.rs+++ b/datafusion/physical-expr/src/aggregate/min_max.rs@@ -44,6 +44,7 @@ use arrow_array::types::{Decimal128Type, Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, Int8Type,UInt16Type, UInt32Type, UInt64Type, UInt8Type,};+use datafusion_common::internal_err;use datafusion_common::ScalarValue;use datafusion_common::{downcast_value, DataFusionError, Result};use datafusion_expr::Accumulator;@@ -243,10 +244,10 @@ impl AggregateExpr for Max {// https://github.com/apache/arrow-datafusion/issues/6906// This is only reached if groups_accumulator_supported is out of sync- _ => Err(DataFusionError::Internal(format!(+ _ => internal_err!("GroupsAccumulator not supported for max({})",self.data_type- ))),+ ),}}@@ -383,10 +384,10 @@ macro_rules! min_max_batch {}other => {// This should have been handled before- return Err(DataFusionError::Internal(format!(+ return internal_err!("Min/Max accumulator not implemented for type {:?}",other- )));+ );}}}};@@ -485,10 +486,10 @@ macro_rules! min_max {if lhsp.eq(rhsp) && lhss.eq(rhss) {typed_min_max!(lhsv, rhsv, Decimal128, $OP, lhsp, lhss)} else {- return Err(DataFusionError::Internal(format!(+ return internal_err!("MIN/MAX is not expected to receive scalars of incompatible types {:?}",(lhs, rhs)- )));+ );}}(ScalarValue::Boolean(lhs), ScalarValue::Boolean(rhs)) => {@@ -627,10 +628,10 @@ macro_rules! min_max {interval_min_max!($OP, $VALUE, $DELTA)}e => {- return Err(DataFusionError::Internal(format!(+ return internal_err!("MIN/MAX is not expected to receive scalars of incompatible types {:?}",e- )))+ )}})}};@@ -875,10 +876,10 @@ impl AggregateExpr for Min {instantiate_min_accumulator!(self, i128, Decimal128Type)}// This is only reached if groups_accumulator_supported is out of sync- _ => Err(DataFusionError::Internal(format!(+ _ => internal_err!("GroupsAccumulator not supported for min({})",self.data_type- ))),+ ),}}diff --git a/datafusion/physical-expr/src/aggregate/sum.rs b/datafusion/physical-expr/src/aggregate/sum.rsindex 9ac90cef4b..2c89884988 100644--- a/datafusion/physical-expr/src/aggregate/sum.rs+++ b/datafusion/physical-expr/src/aggregate/sum.rs@@ -43,6 +43,7 @@ use arrow_array::types::{Decimal128Type, Decimal256Type, Float32Type, Float64Type, Int32Type, Int64Type,UInt32Type, UInt64Type,};+use datafusion_common::internal_err;use datafusion_common::{downcast_value, DataFusionError, Result, ScalarValue};use datafusion_expr::Accumulator;@@ -292,9 +293,7 @@ pub(crate) fn sum_batch(values: &ArrayRef, sum_type: &DataType) -> Result<ScalarDataType::UInt16 => typed_sum_delta_batch!(values, UInt16Array, UInt16),DataType::UInt8 => typed_sum_delta_batch!(values, UInt8Array, UInt8),e => {- return Err(DataFusionError::Internal(format!(- "Sum is not expected to receive the type {e:?}"- )));+ return internal_err!("Sum is not expected to receive the type {e:?}");}})}diff --git a/datafusion/physical-expr/src/aggregate/utils.rs b/datafusion/physical-expr/src/aggregate/utils.rsindex aada51c9ef..e86eb1dc1f 100644--- a/datafusion/physical-expr/src/aggregate/utils.rs+++ b/datafusion/physical-expr/src/aggregate/utils.rs@@ -23,6 +23,7 @@ use arrow::datatypes::{MAX_DECIMAL_FOR_EACH_PRECISION, MIN_DECIMAL_FOR_EACH_PRECuse arrow_array::cast::AsArray;use arrow_array::types::Decimal128Type;use arrow_schema::{DataType, Field};+use datafusion_common::internal_err;use datafusion_common::{DataFusionError, Result, ScalarValue};use datafusion_expr::Accumulator;use std::any::Any;@@ -141,9 +142,7 @@ pub fn calculate_result_decimal_for_avg(*target_scale,))}- other => Err(DataFusionError::Internal(format!(- "Invalid target type in AvgAccumulator {other:?}"- ))),+ other => internal_err!("Invalid target type in AvgAccumulator {other:?}"),}}diff --git a/datafusion/physical-expr/src/analysis.rs b/datafusion/physical-expr/src/analysis.rsindex 68691a6eda..7d9163763e 100644--- a/datafusion/physical-expr/src/analysis.rs+++ b/datafusion/physical-expr/src/analysis.rs@@ -24,7 +24,9 @@ use crate::utils::collect_columns;use crate::PhysicalExpr;use arrow::datatypes::Schema;-use datafusion_common::{ColumnStatistics, DataFusionError, Result, ScalarValue};+use datafusion_common::{+ internal_err, ColumnStatistics, DataFusionError, Result, ScalarValue,+};use std::fmt::Debug;use std::sync::Arc;@@ -197,10 +199,7 @@ fn shrink_boundaries()?;if !(0.0..=1.0).contains(&selectivity) {- return Err(DataFusionError::Internal(format!(- "Selectivity is out of limit: {}",- selectivity- )));+ return internal_err!("Selectivity is out of limit: {}", selectivity);}Ok(AnalysisContext::new(target_boundaries).with_selectivity(selectivity))diff --git a/datafusion/physical-expr/src/array_expressions.rs b/datafusion/physical-expr/src/array_expressions.rsindex 819b389cff..4f678681b7 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::{plan_err, ScalarValue};+use datafusion_common::{internal_err, plan_err, ScalarValue};use datafusion_common::{DataFusionError, Result};use datafusion_expr::ColumnarValue;use itertools::Itertools;@@ -638,10 +638,10 @@ macro_rules! append {/// Array_append SQL functionpub fn array_append(args: &[ArrayRef]) -> Result<ArrayRef> {if args.len() != 2 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Array_append function requires two arguments, got {}",args.len()- )));+ );}let arr = as_list_array(&args[0])?;@@ -728,10 +728,10 @@ macro_rules! prepend {/// Array_prepend SQL functionpub fn array_prepend(args: &[ArrayRef]) -> Result<ArrayRef> {if args.len() != 2 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Array_prepend function requires two arguments, got {}",args.len()- )));+ );}let element = &args[0];@@ -1974,9 +1974,9 @@ macro_rules! array_has_any_non_list_check {if let Some(elem) = elem {res |= arr.iter().dedup().flatten().any(|x| x == elem);} else {- return Err(DataFusionError::Internal(format!(+ return internal_err!("array_has_any does not support Null type for element in sub_array"- )));+ );}}res@@ -2068,9 +2068,9 @@ macro_rules! array_has_all_non_list_check {if let Some(elem) = elem {res &= arr.iter().dedup().flatten().any(|x| x == elem);} else {- return Err(DataFusionError::Internal(format!(+ return internal_err!("array_has_all does not support Null type for element in sub_array"- )));+ );}}resdiff --git a/datafusion/physical-expr/src/conditional_expressions.rs b/datafusion/physical-expr/src/conditional_expressions.rsindex 09c5b382da..37adb2d71c 100644--- a/datafusion/physical-expr/src/conditional_expressions.rs+++ b/datafusion/physical-expr/src/conditional_expressions.rs@@ -19,17 +19,17 @@ use arrow::array::{new_null_array, Array, BooleanArray};use arrow::compute::kernels::zip::zip;use arrow::compute::{and, is_not_null, is_null};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};use datafusion_expr::ColumnarValue;/// coalesce evaluates to the first value which is not NULLpub fn coalesce(args: &[ColumnarValue]) -> Result<ColumnarValue> {// do not accept 0 arguments.if args.is_empty() {- return Err(DataFusionError::Internal(format!(+ return internal_err!("coalesce was called with {} arguments. It requires at least 1.",args.len()- )));+ );}let return_type = args[0].data_type();diff --git a/datafusion/physical-expr/src/crypto_expressions.rs b/datafusion/physical-expr/src/crypto_expressions.rsindex 3c2a095361..e143cc0a20 100644--- a/datafusion/physical-expr/src/crypto_expressions.rs+++ b/datafusion/physical-expr/src/crypto_expressions.rs@@ -28,7 +28,7 @@ use datafusion_common::{cast::{as_binary_array, as_generic_binary_array, as_generic_string_array},plan_err,};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};use datafusion_expr::ColumnarValue;use md5::Md5;use sha2::{Sha224, Sha256, Sha384, Sha512};@@ -66,9 +66,9 @@ fn digest_process(DataType::LargeBinary => {digest_algorithm.digest_binary_array::<i64>(a.as_ref())}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function {digest_algorithm}",- ))),+ other => internal_err!(+ "Unsupported data type {other:?} for function {digest_algorithm}"+ ),},ColumnarValue::Scalar(scalar) => match scalar {ScalarValue::Utf8(a) | ScalarValue::LargeUtf8(a) => {@@ -77,9 +77,9 @@ fn digest_process(}ScalarValue::Binary(a) | ScalarValue::LargeBinary(a) => Ok(digest_algorithm.digest_scalar(a.as_ref().map(|v: &Vec<u8>| v.as_slice()))),- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function {digest_algorithm}",- ))),+ other => internal_err!(+ "Unsupported data type {other:?} for function {digest_algorithm}"+ ),},}}@@ -238,11 +238,11 @@ macro_rules! define_digest_function {#[doc = $DOC]pub fn $NAME(args: &[ColumnarValue]) -> Result<ColumnarValue> {if args.len() != 1 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("{:?} args were supplied but {} takes exactly one argument",args.len(),- DigestAlgorithm::$METHOD.to_string(),- )));+ DigestAlgorithm::$METHOD.to_string()+ );}digest_process(&args[0], DigestAlgorithm::$METHOD)}@@ -264,11 +264,11 @@ fn hex_encode<T: AsRef<[u8]>>(data: T) -> String {/// computes md5 hash digest of the given inputpub fn md5(args: &[ColumnarValue]) -> Result<ColumnarValue> {if args.len() != 1 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("{:?} args were supplied but {} takes exactly one argument",args.len(),- DigestAlgorithm::Md5,- )));+ DigestAlgorithm::Md5+ );}let value = digest_process(&args[0], DigestAlgorithm::Md5)?;// md5 requires special handling because of its unique utf8 return type@@ -333,19 +333,17 @@ define_digest_function!(/// Standard algorithms are md5, sha1, sha224, sha256, sha384 and sha512.pub fn digest(args: &[ColumnarValue]) -> Result<ColumnarValue> {if args.len() != 2 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("{:?} args were supplied but digest takes exactly two arguments",- args.len(),- )));+ args.len()+ );}let digest_algorithm = match &args[1] {ColumnarValue::Scalar(scalar) => match scalar {ScalarValue::Utf8(Some(method)) | ScalarValue::LargeUtf8(Some(method)) => {method.parse::<DigestAlgorithm>()}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function digest",- ))),+ other => internal_err!("Unsupported data type {other:?} for function digest"),},ColumnarValue::Array(_) => Err(DataFusionError::Internal("Digest using dynamically decided method is not yet supported".into(),diff --git a/datafusion/physical-expr/src/datetime_expressions.rs b/datafusion/physical-expr/src/datetime_expressions.rsindex ca96be2a1b..11d797841f 100644--- a/datafusion/physical-expr/src/datetime_expressions.rs+++ b/datafusion/physical-expr/src/datetime_expressions.rs@@ -42,7 +42,7 @@ use datafusion_common::cast::{as_timestamp_microsecond_array, as_timestamp_millisecond_array,as_timestamp_nanosecond_array, as_timestamp_second_array,};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};use datafusion_common::{ScalarType, ScalarValue};use datafusion_expr::ColumnarValue;use std::sync::Arc;@@ -66,11 +66,11 @@ whereF: Fn(&'a str) -> Result<O::Native>,{if args.len() != 1 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("{:?} args were supplied but {} takes exactly one argument",args.len(),- name,- )));+ name+ );}let array = as_generic_string_array::<T>(args[0])?;@@ -100,9 +100,7 @@ whereDataType::LargeUtf8 => Ok(ColumnarValue::Array(Arc::new(unary_string_to_primitive_function::<i64, O, _>(&[a.as_ref()], op, name)?,))),- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function {name}",- ))),+ other => internal_err!("Unsupported data type {other:?} for function {name}"),},ColumnarValue::Scalar(scalar) => match scalar {ScalarValue::Utf8(a) => {@@ -113,9 +111,7 @@ wherelet result = a.as_ref().map(|x| (op)(x)).transpose()?;Ok(ColumnarValue::Scalar(S::scalar(result)))}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function {name}"- ))),+ other => internal_err!("Unsupported data type {other:?} for function {name}"),},}}@@ -725,10 +721,7 @@ macro_rules! extract_date_part {.map(|v| cast(&(Arc::new(v) as ArrayRef), &DataType::Float64))?)}},- datatype => Err(DataFusionError::Internal(format!(- "Extract does not support datatype {:?}",- datatype- ))),+ datatype => internal_err!("Extract does not support datatype {:?}", datatype),}};}@@ -855,12 +848,7 @@ where}}}- _ => {- return Err(DataFusionError::Internal(format!(- "Can not convert {:?} to epoch",- array.data_type()- )))- }+ _ => return internal_err!("Can not convert {:?} to epoch", array.data_type()),}Ok(b.finish())}diff --git a/datafusion/physical-expr/src/encoding_expressions.rs b/datafusion/physical-expr/src/encoding_expressions.rsindex 88d1bec70f..9a521d9d36 100644--- a/datafusion/physical-expr/src/encoding_expressions.rs+++ b/datafusion/physical-expr/src/encoding_expressions.rs@@ -25,7 +25,7 @@ use base64::{engine::general_purpose, Engine as _};use datafusion_common::ScalarValue;use datafusion_common::{cast::{as_generic_binary_array, as_generic_string_array},- plan_err,+ internal_err, plan_err,};use datafusion_common::{DataFusionError, Result};use datafusion_expr::ColumnarValue;@@ -45,9 +45,9 @@ fn encode_process(value: &ColumnarValue, encoding: Encoding) -> Result<ColumnarVDataType::LargeUtf8 => encoding.encode_utf8_array::<i64>(a.as_ref()),DataType::Binary => encoding.encode_binary_array::<i32>(a.as_ref()),DataType::LargeBinary => encoding.encode_binary_array::<i64>(a.as_ref()),- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function encode({encoding})",- ))),+ other => internal_err!(+ "Unsupported data type {other:?} for function encode({encoding})"+ ),},ColumnarValue::Scalar(scalar) => {match scalar {@@ -61,9 +61,9 @@ fn encode_process(value: &ColumnarValue, encoding: Encoding) -> Result<ColumnarV),ScalarValue::LargeBinary(a) => Ok(encoding.encode_large_scalar(a.as_ref().map(|v: &Vec<u8>| v.as_slice()))),- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function encode({encoding})",- ))),+ other => internal_err!(+ "Unsupported data type {other:?} for function encode({encoding})"+ ),}}}@@ -76,9 +76,9 @@ fn decode_process(value: &ColumnarValue, encoding: Encoding) -> Result<ColumnarVDataType::LargeUtf8 => encoding.decode_utf8_array::<i64>(a.as_ref()),DataType::Binary => encoding.decode_binary_array::<i32>(a.as_ref()),DataType::LargeBinary => encoding.decode_binary_array::<i64>(a.as_ref()),- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function decode({encoding})",- ))),+ other => internal_err!(+ "Unsupported data type {other:?} for function decode({encoding})"+ ),},ColumnarValue::Scalar(scalar) => {match scalar {@@ -92,9 +92,9 @@ fn decode_process(value: &ColumnarValue, encoding: Encoding) -> Result<ColumnarV}ScalarValue::LargeBinary(a) => encoding.decode_large_scalar(a.as_ref().map(|v: &Vec<u8>| v.as_slice())),- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function decode({encoding})",- ))),+ other => internal_err!(+ "Unsupported data type {other:?} for function decode({encoding})"+ ),}}}@@ -295,10 +295,10 @@ impl FromStr for Encoding {/// Standard encodings are base64 and hex.pub fn encode(args: &[ColumnarValue]) -> Result<ColumnarValue> {if args.len() != 2 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("{:?} args were supplied but encode takes exactly two arguments",- args.len(),- )));+ args.len()+ );}let encoding = match &args[1] {ColumnarValue::Scalar(scalar) => match scalar {@@ -321,10 +321,10 @@ pub fn encode(args: &[ColumnarValue]) -> Result<ColumnarValue> {/// Standard encodings are base64 and hex.pub fn decode(args: &[ColumnarValue]) -> Result<ColumnarValue> {if args.len() != 2 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("{:?} args were supplied but decode takes exactly two arguments",- args.len(),- )));+ args.len()+ );}let encoding = match &args[1] {ColumnarValue::Scalar(scalar) => match scalar {diff --git a/datafusion/physical-expr/src/expressions/binary.rs b/datafusion/physical-expr/src/expressions/binary.rsindex 3e2a3d4183..ece5089ba3 100644--- a/datafusion/physical-expr/src/expressions/binary.rs+++ b/datafusion/physical-expr/src/expressions/binary.rs@@ -73,6 +73,7 @@ use crate::PhysicalExpr;use arrow_array::{Datum, Scalar};use datafusion_common::cast::as_boolean_array;+use datafusion_common::internal_err;use datafusion_common::ScalarValue;use datafusion_common::{DataFusionError, Result};use datafusion_expr::type_coercion::binary::get_result_type;@@ -253,11 +254,11 @@ macro_rules! compute_utf8_op_scalar {} else if $RIGHT.is_null() {Ok(Arc::new(new_null_array($OP_TYPE, $LEFT.len())))} else {- Err(DataFusionError::Internal(format!(+ internal_err!("compute_utf8_op_scalar for '{}' failed to cast literal value {}",stringify!($OP),$RIGHT- )))+ )}}};}@@ -381,10 +382,10 @@ macro_rules! binary_string_array_op {match $LEFT.data_type() {DataType::Utf8 => compute_utf8_op!($LEFT, $RIGHT, $OP, StringArray),DataType::LargeUtf8 => compute_utf8_op!($LEFT, $RIGHT, $OP, LargeStringArray),- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("Data type {:?} not supported for binary operation '{}' on string arrays",other, stringify!($OP)- ))),+ ),}}};}@@ -452,10 +453,10 @@ macro_rules! binary_array_op {compute_op!($LEFT, $RIGHT, $OP, IntervalMonthDayNanoArray)}DataType::Boolean => compute_bool_op!($LEFT, $RIGHT, $OP, BooleanArray),- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("Data type {:?} not supported for binary operation '{}' on dyn arrays",other, stringify!($OP)- ))),+ ),}}};}@@ -478,10 +479,10 @@ macro_rules! binary_string_array_flag_op {DataType::LargeUtf8 => {compute_utf8_flag_op!($LEFT, $RIGHT, $OP, LargeStringArray, $NOT, $FLAG)}- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("Data type {:?} not supported for binary_string_array_flag_op operation '{}' on string array",other, stringify!($OP)- ))),+ ),}}};}@@ -520,10 +521,10 @@ macro_rules! binary_string_array_flag_op_scalar {DataType::LargeUtf8 => {compute_utf8_flag_op_scalar!($LEFT, $RIGHT, $OP, LargeStringArray, $NOT, $FLAG)}- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("Data type {:?} not supported for binary_string_array_flag_op_scalar operation '{}' on string array",other, stringify!($OP)- ))),+ ),};Some(result)}};@@ -546,10 +547,10 @@ macro_rules! compute_utf8_flag_op_scalar {}Ok(Arc::new(array))} else {- Err(DataFusionError::Internal(format!(+ internal_err!("compute_utf8_flag_op_scalar failed to cast literal value {} for operation '{}'",$RIGHT, stringify!($OP)- )))+ )}}};}@@ -752,9 +753,9 @@ macro_rules! binary_array_op_dyn_scalar {ScalarValue::IntervalYearMonth(v) => compute_op_dyn_scalar!($LEFT, v, $OP, $OP_TYPE),ScalarValue::IntervalDayTime(v) => compute_op_dyn_scalar!($LEFT, v, $OP, $OP_TYPE),ScalarValue::IntervalMonthDayNano(v) => compute_op_dyn_scalar!($LEFT, v, $OP, $OP_TYPE),- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("Data type {:?} not supported for scalar operation '{}' on dyn array",- other, stringify!($OP)))+ other, stringify!($OP))};Some(result)@@ -793,9 +794,9 @@ fn to_result_type_array(if value_type.as_ref() == result_type {Ok(cast(&array, result_type)?)} else {- Err(DataFusionError::Internal(format!(+ internal_err!("Incompatible Dictionary value type {value_type:?} with result type {result_type:?} of Binary operator {op:?}"- )))+ )}}_ => Ok(array),@@ -941,22 +942,24 @@ impl BinaryExpr {if left_data_type == &DataType::Boolean {boolean_op!(&left, &right, and_kleene)} else {- Err(DataFusionError::Internal(format!(+ internal_err!("Cannot evaluate binary expression {:?} with types {:?} and {:?}",self.op,left.data_type(),right.data_type()- )))+ )}}Or => {if left_data_type == &DataType::Boolean {boolean_op!(&left, &right, or_kleene)} else {- Err(DataFusionError::Internal(format!(+ internal_err!("Cannot evaluate binary expression {:?} with types {:?} and {:?}",- self.op, left_data_type, right_data_type- )))+ self.op,+ left_data_type,+ right_data_type+ )}}RegexMatch => {diff --git a/datafusion/physical-expr/src/expressions/binary/kernels.rs b/datafusion/physical-expr/src/expressions/binary/kernels.rsindex 185b9416d3..22cadec409 100644--- a/datafusion/physical-expr/src/expressions/binary/kernels.rs+++ b/datafusion/physical-expr/src/expressions/binary/kernels.rs@@ -24,6 +24,7 @@ use arrow::compute::kernels::bitwise::{bitwise_xor, bitwise_xor_scalar,};use arrow::datatypes::DataType;+use datafusion_common::internal_err;use datafusion_common::{DataFusionError, Result, ScalarValue};use std::sync::Arc;@@ -68,11 +69,11 @@ macro_rules! create_dyn_kernel {DataType::UInt64 => {call_bitwise_kernel!(left, right, $KERNEL, UInt64Array)}- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("Data type {:?} not supported for binary operation '{}' on dyn arrays",other,- stringify!($KERNEL),- ))),+ stringify!($KERNEL)+ ),}}};@@ -114,11 +115,11 @@ macro_rules! create_dyn_scalar_kernel {DataType::UInt16 => call_bitwise_scalar_kernel!(array, scalar, $KERNEL, UInt16Array, u16),DataType::UInt32 => call_bitwise_scalar_kernel!(array, scalar, $KERNEL, UInt32Array, u32),DataType::UInt64 => call_bitwise_scalar_kernel!(array, scalar, $KERNEL, UInt64Array, u64),- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("Data type {:?} not supported for binary operation '{}' on dyn arrays",other,- stringify!($KERNEL),- ))),+ stringify!($KERNEL)+ ),};Some(result)}diff --git a/datafusion/physical-expr/src/expressions/column.rs b/datafusion/physical-expr/src/expressions/column.rsindex f40a05c49a..5955faa645 100644--- a/datafusion/physical-expr/src/expressions/column.rs+++ b/datafusion/physical-expr/src/expressions/column.rs@@ -29,7 +29,7 @@ use arrow::{record_batch::RecordBatch,};use datafusion_common::plan_err;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};use datafusion_expr::ColumnarValue;/// Represents the column at a given index in a RecordBatch@@ -125,10 +125,10 @@ impl Column {if self.index < input_schema.fields.len() {Ok(())} else {- Err(DataFusionError::Internal(format!(+ internal_err!("PhysicalExpr Column references column '{}' at index {} (zero-based) but input schema only has {} columns: {:?}",self.name,- self.index, input_schema.fields.len(), input_schema.fields().iter().map(|f| f.name().clone()).collect::<Vec<String>>())))+ self.index, input_schema.fields.len(), input_schema.fields().iter().map(|f| f.name().clone()).collect::<Vec<String>>())}}}diff --git a/datafusion/physical-expr/src/expressions/in_list.rs b/datafusion/physical-expr/src/expressions/in_list.rsindex 722edb22de..8e7372d6e3 100644--- a/datafusion/physical-expr/src/expressions/in_list.rs+++ b/datafusion/physical-expr/src/expressions/in_list.rs@@ -35,7 +35,7 @@ use arrow::util::bit_iterator::BitIndexIterator;use arrow::{downcast_dictionary_array, downcast_primitive_array};use datafusion_common::{cast::{as_boolean_array, as_generic_binary_array, as_string_array},- DataFusionError, Result, ScalarValue,+ internal_err, DataFusionError, Result, ScalarValue,};use datafusion_expr::ColumnarValue;use hashbrown::hash_map::RawEntryMut;@@ -356,9 +356,9 @@ pub fn in_list(for list_expr in list.iter() {let list_expr_data_type = list_expr.data_type(schema)?;if !expr_data_type.eq(&list_expr_data_type) {- return Err(DataFusionError::Internal(format!(+ return internal_err!("The data type inlist should be same, the value type is {expr_data_type}, one of list expr type is {list_expr_data_type}"- )));+ );}}let static_filter = try_cast_static_filter_to_set(&list, schema).ok();diff --git a/datafusion/physical-expr/src/expressions/like.rs b/datafusion/physical-expr/src/expressions/like.rsindex 9523a4efd8..b3d366142a 100644--- a/datafusion/physical-expr/src/expressions/like.rs+++ b/datafusion/physical-expr/src/expressions/like.rs@@ -31,7 +31,7 @@ use arrow::{record_batch::RecordBatch,};use arrow_schema::{DataType, Schema};-use datafusion_common::{DataFusionError, Result, ScalarValue};+use datafusion_common::{internal_err, DataFusionError, Result, ScalarValue};use datafusion_expr::ColumnarValue;// Like expression@@ -136,12 +136,12 @@ impl PhysicalExpr for LikeExpr {DataType::Dictionary(_, dict_t),) if dict_t.as_ref() == scalar_t => {}_ => {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Cannot evaluate {} expression with types {:?} and {:?}",self.op_name(),expr_data_type,pattern_data_type- )));+ );}}@@ -207,10 +207,10 @@ macro_rules! binary_string_array_op_scalar {let result: Result<Arc<dyn Array>> = match $LEFT.data_type() {DataType::Utf8 => compute_utf8_op_scalar!($LEFT, $RIGHT, $OP, StringArray, $OP_TYPE),DataType::LargeUtf8 => compute_utf8_op_scalar!($LEFT, $RIGHT, $OP, LargeStringArray, $OP_TYPE),- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("Data type {:?} not supported for scalar operation '{}' on string array",other, stringify!($OP)- ))),+ ),};Some(result)}};@@ -278,9 +278,9 @@ pub fn like(let expr_type = &expr.data_type(input_schema)?;let pattern_type = &pattern.data_type(input_schema)?;if !expr_type.eq(pattern_type) {- return Err(DataFusionError::Internal(format!(+ return internal_err!("The type of {expr_type} AND {pattern_type} of like physical should be same"- )));+ );}Ok(Arc::new(LikeExpr::new(negated,diff --git a/datafusion/physical-expr/src/expressions/not.rs b/datafusion/physical-expr/src/expressions/not.rsindex 51cb8235a0..2535c2f199 100644--- a/datafusion/physical-expr/src/expressions/not.rs+++ b/datafusion/physical-expr/src/expressions/not.rs@@ -26,7 +26,9 @@ use crate::physical_expr::down_cast_any_ref;use crate::PhysicalExpr;use arrow::datatypes::{DataType, Schema};use arrow::record_batch::RecordBatch;-use datafusion_common::{cast::as_boolean_array, DataFusionError, Result, ScalarValue};+use datafusion_common::{+ cast::as_boolean_array, internal_err, DataFusionError, Result, ScalarValue,+};use datafusion_expr::ColumnarValue;/// Not expression@@ -83,10 +85,10 @@ impl PhysicalExpr for NotExpr {}let value_type = scalar.get_datatype();if value_type != DataType::Boolean {- return Err(DataFusionError::Internal(format!(+ return internal_err!("NOT '{:?}' can't be evaluated because the expression's type is {:?}, not boolean or NULL",- self.arg, value_type,- )));+ self.arg, value_type+ );}let bool_value: bool = scalar.try_into()?;Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some(diff --git a/datafusion/physical-expr/src/expressions/nullif.rs b/datafusion/physical-expr/src/expressions/nullif.rsindex a2a61d16af..f21b41ebf3 100644--- a/datafusion/physical-expr/src/expressions/nullif.rs+++ b/datafusion/physical-expr/src/expressions/nullif.rs@@ -18,7 +18,9 @@use arrow::array::Array;use arrow::compute::eq_dyn;use arrow::compute::kernels::nullif::nullif;-use datafusion_common::{cast::as_boolean_array, DataFusionError, Result, ScalarValue};+use datafusion_common::{+ cast::as_boolean_array, internal_err, DataFusionError, Result, ScalarValue,+};use datafusion_expr::ColumnarValue;use super::binary::array_eq_scalar;@@ -29,10 +31,10 @@ use super::binary::array_eq_scalar;///pub fn nullif_func(args: &[ColumnarValue]) -> Result<ColumnarValue> {if args.len() != 2 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("{:?} args were supplied but NULLIF takes exactly two args",- args.len(),- )));+ args.len()+ );}let (lhs, rhs) = (&args[0], &args[1]);diff --git a/datafusion/physical-expr/src/functions.rs b/datafusion/physical-expr/src/functions.rsindex 81c673ea83..ab7601f7d7 100644--- a/datafusion/physical-expr/src/functions.rs+++ b/datafusion/physical-expr/src/functions.rs@@ -43,7 +43,7 @@ use arrow::{datatypes::TimeUnit,datatypes::{DataType, Int32Type, Int64Type, Schema},};-use datafusion_common::{DataFusionError, Result, ScalarValue};+use datafusion_common::{internal_err, DataFusionError, Result, ScalarValue};use datafusion_expr::{BuiltinScalarFunction, ColumnarValue, ScalarFunctionImplementation,};@@ -82,9 +82,9 @@ pub fn create_physical_expr(}Ok(DataType::Utf8) => datetime_expressions::to_timestamp,other => {- return Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function to_timestamp",- )));+ return internal_err!(+ "Unsupported data type {other:?} for function to_timestamp"+ );}})}@@ -101,9 +101,9 @@ pub fn create_physical_expr(}Ok(DataType::Utf8) => datetime_expressions::to_timestamp_millis,other => {- return Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function to_timestamp_millis",- )));+ return internal_err!(+ "Unsupported data type {other:?} for function to_timestamp_millis"+ );}})}@@ -120,9 +120,9 @@ pub fn create_physical_expr(}Ok(DataType::Utf8) => datetime_expressions::to_timestamp_micros,other => {- return Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function to_timestamp_micros",- )));+ return internal_err!(+ "Unsupported data type {other:?} for function to_timestamp_micros"+ );}})}@@ -139,9 +139,9 @@ pub fn create_physical_expr(}Ok(DataType::Utf8) => datetime_expressions::to_timestamp_seconds,other => {- return Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function to_timestamp_seconds",- )));+ return internal_err!(+ "Unsupported data type {other:?} for function to_timestamp_seconds"+ );}}}),@@ -155,9 +155,9 @@ pub fn create_physical_expr()},other => {- return Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function from_unixtime",- )));+ return internal_err!(+ "Unsupported data type {other:?} for function from_unixtime"+ );}}}),@@ -193,10 +193,10 @@ macro_rules! invoke_if_encoding_expressions_feature_flag {macro_rules! invoke_if_encoding_expressions_feature_flag {($FUNC:ident, $NAME:expr) => {|_: &[ColumnarValue]| -> Result<ColumnarValue> {- Err(DataFusionError::Internal(format!(+ internal_err!("function {} requires compilation with feature flag: encoding_expressions.",$NAME- )))+ )}};}@@ -213,10 +213,10 @@ macro_rules! invoke_if_crypto_expressions_feature_flag {macro_rules! invoke_if_crypto_expressions_feature_flag {($FUNC:ident, $NAME:expr) => {|_: &[ColumnarValue]| -> Result<ColumnarValue> {- Err(DataFusionError::Internal(format!(+ internal_err!("function {} requires compilation with feature flag: crypto_expressions.",$NAME- )))+ )}};}@@ -233,10 +233,10 @@ macro_rules! invoke_on_array_if_regex_expressions_feature_flag {macro_rules! invoke_on_array_if_regex_expressions_feature_flag {($FUNC:ident, $T:tt, $NAME:expr) => {|_: &[ArrayRef]| -> Result<ArrayRef> {- Err(DataFusionError::Internal(format!(+ internal_err!("function {} requires compilation with feature flag: regex_expressions.",$NAME- )))+ )}};}@@ -253,10 +253,10 @@ macro_rules! invoke_on_columnar_value_if_regex_expressions_feature_flag {macro_rules! invoke_on_columnar_value_if_regex_expressions_feature_flag {($FUNC:ident, $T:tt, $NAME:expr) => {|_: &[ColumnarValue]| -> Result<ScalarFunctionImplementation> {- Err(DataFusionError::Internal(format!(+ internal_err!("function {} requires compilation with feature flag: regex_expressions.",$NAME- )))+ )}};}@@ -273,10 +273,10 @@ macro_rules! invoke_if_unicode_expressions_feature_flag {macro_rules! invoke_if_unicode_expressions_feature_flag {($FUNC:ident, $T:tt, $NAME:expr) => {|_: &[ArrayRef]| -> Result<ArrayRef> {- Err(DataFusionError::Internal(format!(+ internal_err!("function {} requires compilation with feature flag: unicode_expressions.",$NAME- )))+ )}};}@@ -504,9 +504,7 @@ pub fn create_physical_fun(DataType::LargeUtf8 => {make_scalar_function(string_expressions::ascii::<i64>)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function ascii",- ))),+ other => internal_err!("Unsupported data type {other:?} for function ascii"),}),BuiltinScalarFunction::BitLength => Arc::new(|args| match &args[0] {ColumnarValue::Array(v) => Ok(ColumnarValue::Array(bit_length(v.as_ref())?)),@@ -527,9 +525,7 @@ pub fn create_physical_fun(DataType::LargeUtf8 => {make_scalar_function(string_expressions::btrim::<i64>)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function btrim",- ))),+ other => internal_err!("Unsupported data type {other:?} for function btrim"),}),BuiltinScalarFunction::CharacterLength => {Arc::new(|args| match args[0].data_type() {@@ -549,9 +545,9 @@ pub fn create_physical_fun();make_scalar_function(func)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function character_length",- ))),+ other => internal_err!(+ "Unsupported data type {other:?} for function character_length"+ ),})}BuiltinScalarFunction::Chr => {@@ -590,9 +586,9 @@ pub fn create_physical_fun(DataType::LargeUtf8 => {make_scalar_function(string_expressions::initcap::<i64>)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function initcap",- ))),+ other => {+ internal_err!("Unsupported data type {other:?} for function initcap")+ }}),BuiltinScalarFunction::Left => Arc::new(|args| match args[0].data_type() {DataType::Utf8 => {@@ -603,9 +599,7 @@ pub fn create_physical_fun(let func = invoke_if_unicode_expressions_feature_flag!(left, i64, "left");make_scalar_function(func)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function left",- ))),+ other => internal_err!("Unsupported data type {other:?} for function left"),}),BuiltinScalarFunction::Lower => Arc::new(string_expressions::lower),BuiltinScalarFunction::Lpad => Arc::new(|args| match args[0].data_type() {@@ -617,9 +611,7 @@ pub fn create_physical_fun(let func = invoke_if_unicode_expressions_feature_flag!(lpad, i64, "lpad");make_scalar_function(func)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function lpad",- ))),+ other => internal_err!("Unsupported data type {other:?} for function lpad"),}),BuiltinScalarFunction::Ltrim => Arc::new(|args| match args[0].data_type() {DataType::Utf8 => {@@ -628,9 +620,7 @@ pub fn create_physical_fun(DataType::LargeUtf8 => {make_scalar_function(string_expressions::ltrim::<i64>)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function ltrim",- ))),+ other => internal_err!("Unsupported data type {other:?} for function ltrim"),}),BuiltinScalarFunction::MD5 => {Arc::new(invoke_if_crypto_expressions_feature_flag!(md5, "md5"))@@ -675,9 +665,9 @@ pub fn create_physical_fun();make_scalar_function(func)(args)}- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("Unsupported data type {other:?} for function regexp_match"- ))),+ ),})}BuiltinScalarFunction::RegexpReplace => {@@ -700,9 +690,9 @@ pub fn create_physical_fun(let func = specializer_func(args)?;func(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function regexp_replace",- ))),+ other => internal_err!(+ "Unsupported data type {other:?} for function regexp_replace"+ ),})}BuiltinScalarFunction::Repeat => Arc::new(|args| match args[0].data_type() {@@ -712,9 +702,7 @@ pub fn create_physical_fun(DataType::LargeUtf8 => {make_scalar_function(string_expressions::repeat::<i64>)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function repeat",- ))),+ other => internal_err!("Unsupported data type {other:?} for function repeat"),}),BuiltinScalarFunction::Replace => Arc::new(|args| match args[0].data_type() {DataType::Utf8 => {@@ -723,9 +711,9 @@ pub fn create_physical_fun(DataType::LargeUtf8 => {make_scalar_function(string_expressions::replace::<i64>)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function replace",- ))),+ other => {+ internal_err!("Unsupported data type {other:?} for function replace")+ }}),BuiltinScalarFunction::Reverse => Arc::new(|args| match args[0].data_type() {DataType::Utf8 => {@@ -738,9 +726,9 @@ pub fn create_physical_fun(invoke_if_unicode_expressions_feature_flag!(reverse, i64, "reverse");make_scalar_function(func)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function reverse",- ))),+ other => {+ internal_err!("Unsupported data type {other:?} for function reverse")+ }}),BuiltinScalarFunction::Right => Arc::new(|args| match args[0].data_type() {DataType::Utf8 => {@@ -753,9 +741,7 @@ pub fn create_physical_fun(invoke_if_unicode_expressions_feature_flag!(right, i64, "right");make_scalar_function(func)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function right",- ))),+ other => internal_err!("Unsupported data type {other:?} for function right"),}),BuiltinScalarFunction::Rpad => Arc::new(|args| match args[0].data_type() {DataType::Utf8 => {@@ -766,9 +752,7 @@ pub fn create_physical_fun(let func = invoke_if_unicode_expressions_feature_flag!(rpad, i64, "rpad");make_scalar_function(func)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function rpad",- ))),+ other => internal_err!("Unsupported data type {other:?} for function rpad"),}),BuiltinScalarFunction::Rtrim => Arc::new(|args| match args[0].data_type() {DataType::Utf8 => {@@ -777,9 +761,7 @@ pub fn create_physical_fun(DataType::LargeUtf8 => {make_scalar_function(string_expressions::rtrim::<i64>)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function rtrim",- ))),+ other => internal_err!("Unsupported data type {other:?} for function rtrim"),}),BuiltinScalarFunction::SHA224 => {Arc::new(invoke_if_crypto_expressions_feature_flag!(sha224, "sha224"))@@ -800,9 +782,9 @@ pub fn create_physical_fun(DataType::LargeUtf8 => {make_scalar_function(string_expressions::split_part::<i64>)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function split_part",- ))),+ other => {+ internal_err!("Unsupported data type {other:?} for function split_part")+ }}),BuiltinScalarFunction::StartsWith => Arc::new(|args| match args[0].data_type() {DataType::Utf8 => {@@ -811,9 +793,9 @@ pub fn create_physical_fun(DataType::LargeUtf8 => {make_scalar_function(string_expressions::starts_with::<i64>)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function starts_with",- ))),+ other => {+ internal_err!("Unsupported data type {other:?} for function starts_with")+ }}),BuiltinScalarFunction::Strpos => Arc::new(|args| match args[0].data_type() {DataType::Utf8 => {@@ -828,9 +810,7 @@ pub fn create_physical_fun();make_scalar_function(func)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function strpos",- ))),+ other => internal_err!("Unsupported data type {other:?} for function strpos"),}),BuiltinScalarFunction::Substr => Arc::new(|args| match args[0].data_type() {DataType::Utf8 => {@@ -843,9 +823,7 @@ pub fn create_physical_fun(invoke_if_unicode_expressions_feature_flag!(substr, i64, "substr");make_scalar_function(func)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function substr",- ))),+ other => internal_err!("Unsupported data type {other:?} for function substr"),}),BuiltinScalarFunction::ToHex => Arc::new(|args| match args[0].data_type() {DataType::Int32 => {@@ -854,9 +832,7 @@ pub fn create_physical_fun(DataType::Int64 => {make_scalar_function(string_expressions::to_hex::<Int64Type>)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function to_hex",- ))),+ other => internal_err!("Unsupported data type {other:?} for function to_hex"),}),BuiltinScalarFunction::Translate => Arc::new(|args| match args[0].data_type() {DataType::Utf8 => {@@ -875,9 +851,9 @@ pub fn create_physical_fun();make_scalar_function(func)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function translate",- ))),+ other => {+ internal_err!("Unsupported data type {other:?} for function translate")+ }}),BuiltinScalarFunction::Trim => Arc::new(|args| match args[0].data_type() {DataType::Utf8 => {@@ -886,16 +862,14 @@ pub fn create_physical_fun(DataType::LargeUtf8 => {make_scalar_function(string_expressions::btrim::<i64>)(args)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function trim",- ))),+ other => internal_err!("Unsupported data type {other:?} for function trim"),}),BuiltinScalarFunction::Upper => Arc::new(string_expressions::upper),BuiltinScalarFunction::Uuid => Arc::new(string_expressions::uuid),_ => {- return Err(DataFusionError::Internal(format!(+ return internal_err!("create_physical_fun: Unsupported scalar function {fun:?}"- )));+ );}})}@@ -2877,8 +2851,8 @@ mod tests {}}Err(..) => {- return Err(DataFusionError::Internal(format!(- "Builtin scalar function {fun} didn't got the right error with empty arguments")));+ return internal_err!(+ "Builtin scalar function {fun} didn't got the right error with empty arguments");}}}diff --git a/datafusion/physical-expr/src/hash_utils.rs b/datafusion/physical-expr/src/hash_utils.rsindex cf0a3f5eab..59651c5cc9 100644--- a/datafusion/physical-expr/src/hash_utils.rs+++ b/datafusion/physical-expr/src/hash_utils.rs@@ -27,7 +27,7 @@ use datafusion_common::{cast::{as_boolean_array, as_generic_binary_array, as_primitive_array, as_string_array,},- DataFusionError, Result,+ internal_err, DataFusionError, Result,};use std::sync::Arc;@@ -296,10 +296,10 @@ pub fn create_hashes<'a>(}_ => {// This is internal because we should have caught this before.- return Err(DataFusionError::Internal(format!(+ return internal_err!("Unsupported data type in hasher: {}",col.data_type()- )));+ );}}}diff --git a/datafusion/physical-expr/src/intervals/interval_aritmetic.rs b/datafusion/physical-expr/src/intervals/interval_aritmetic.rsindex f72006ab5c..3396e3ee5f 100644--- a/datafusion/physical-expr/src/intervals/interval_aritmetic.rs+++ b/datafusion/physical-expr/src/intervals/interval_aritmetic.rs@@ -28,7 +28,7 @@ use crate::intervals::rounding::alter_fp_rounding_mode;use arrow::compute::{cast_with_options, CastOptions};use arrow::datatypes::DataType;use arrow_array::ArrowNativeTypeOp;-use datafusion_common::{DataFusionError, Result, ScalarValue};+use datafusion_common::{internal_err, DataFusionError, Result, ScalarValue};use datafusion_expr::type_coercion::binary::get_result_type;use datafusion_expr::Operator;@@ -258,9 +258,9 @@ impl Interval {if lower_type == upper_type {Ok(lower_type)} else {- Err(DataFusionError::Internal(format!(- "Interval bounds have different types: {lower_type} != {upper_type}",- )))+ internal_err!(+ "Interval bounds have different types: {lower_type} != {upper_type}"+ )}}diff --git a/datafusion/physical-expr/src/math_expressions.rs b/datafusion/physical-expr/src/math_expressions.rsindex e62d24497b..907ca95951 100644--- a/datafusion/physical-expr/src/math_expressions.rs+++ b/datafusion/physical-expr/src/math_expressions.rs@@ -20,6 +20,7 @@use arrow::array::ArrayRef;use arrow::array::{BooleanArray, Float32Array, Float64Array, Int64Array};use arrow::datatypes::DataType;+use datafusion_common::internal_err;use datafusion_common::ScalarValue;use datafusion_common::ScalarValue::{Float32, Int64};use datafusion_common::{DataFusionError, Result};@@ -39,10 +40,7 @@ macro_rules! downcast_compute_op {arrow::compute::kernels::arity::unary(array, |x| x.$FUNC());Ok(Arc::new(res))}- _ => Err(DataFusionError::Internal(format!(- "Invalid data type for {}",- $NAME- ))),+ _ => internal_err!("Invalid data type for {}", $NAME),}}};}@@ -59,10 +57,11 @@ macro_rules! unary_primitive_array_op {let result = downcast_compute_op!(array, $NAME, $FUNC, Float64Array);Ok(ColumnarValue::Array(result?))}- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("Unsupported data type {:?} for function {}",- other, $NAME,- ))),+ other,+ $NAME+ ),},ColumnarValue::Scalar(a) => match a {ScalarValue::Float32(a) => Ok(ColumnarValue::Scalar(@@ -71,11 +70,11 @@ macro_rules! unary_primitive_array_op {ScalarValue::Float64(a) => Ok(ColumnarValue::Scalar(ScalarValue::Float64(a.map(|x| x.$FUNC())),)),- _ => Err(DataFusionError::Internal(format!(+ _ => internal_err!("Unsupported data type {:?} for function {}",($VALUE).data_type(),- $NAME,- ))),+ $NAME+ ),},}}};@@ -189,9 +188,7 @@ pub fn factorial(args: &[ArrayRef]) -> Result<ArrayRef> {Int64Array,{ |value: i64| { (1..=value).product() } })) as ArrayRef),- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function factorial."- ))),+ other => internal_err!("Unsupported data type {other:?} for function factorial."),}}@@ -238,9 +235,7 @@ pub fn gcd(args: &[ArrayRef]) -> Result<ArrayRef> {Int64Array,{ compute_gcd })) as ArrayRef),- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function gcd"- ))),+ other => internal_err!("Unsupported data type {other:?} for function gcd"),}}@@ -266,9 +261,7 @@ pub fn lcm(args: &[ArrayRef]) -> Result<ArrayRef> {Int64Array,{ compute_lcm })) as ArrayRef),- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function lcm"- ))),+ other => internal_err!("Unsupported data type {other:?} for function lcm"),}}@@ -313,9 +306,7 @@ pub fn nanvl(args: &[ArrayRef]) -> Result<ArrayRef> {)) as ArrayRef)}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function nanvl"- ))),+ other => internal_err!("Unsupported data type {other:?} for function nanvl"),}}@@ -399,10 +390,10 @@ pub fn random(args: &[ColumnarValue]) -> Result<ColumnarValue> {/// Round SQL functionpub fn round(args: &[ArrayRef]) -> Result<ArrayRef> {if args.len() != 1 && args.len() != 2 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("round function requires one or two arguments, got {}",args.len()- )));+ );}let mut decimal_places = ColumnarValue::Scalar(ScalarValue::Int64(Some(0)));@@ -486,9 +477,7 @@ pub fn round(args: &[ArrayRef]) -> Result<ArrayRef> {)),},- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function round"- ))),+ other => internal_err!("Unsupported data type {other:?} for function round"),}}@@ -513,9 +502,7 @@ pub fn power(args: &[ArrayRef]) -> Result<ArrayRef> {{ i64::pow })) as ArrayRef),- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function power"- ))),+ other => internal_err!("Unsupported data type {other:?} for function power"),}}@@ -540,9 +527,7 @@ pub fn atan2(args: &[ArrayRef]) -> Result<ArrayRef> {{ f32::atan2 })) as ArrayRef),- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function atan2"- ))),+ other => internal_err!("Unsupported data type {other:?} for function atan2"),}}@@ -600,9 +585,7 @@ pub fn log(args: &[ArrayRef]) -> Result<ArrayRef> {)),},- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function log"- ))),+ other => internal_err!("Unsupported data type {other:?} for function log"),}}@@ -623,9 +606,7 @@ pub fn cot(args: &[ArrayRef]) -> Result<ArrayRef> {{ compute_cot32 })) as ArrayRef),- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function cot"- ))),+ other => internal_err!("Unsupported data type {other:?} for function cot"),}}@@ -642,10 +623,10 @@ fn compute_cot64(x: f64) -> f64 {/// Truncate(numeric, decimalPrecision) and trunc(numeric) SQL functionpub fn trunc(args: &[ArrayRef]) -> Result<ArrayRef> {if args.len() != 1 && args.len() != 2 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("truncate function requires one or two arguments, got {}",args.len()- )));+ );}//if only one arg then invoke toolchain trunc(num) and precision = 0 by default@@ -692,9 +673,7 @@ pub fn trunc(args: &[ArrayRef]) -> Result<ArrayRef> {"trunc function requires a scalar or array for precision".to_string(),)),},- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function trunc"- ))),+ other => internal_err!("Unsupported data type {other:?} for function trunc"),}}diff --git a/datafusion/physical-expr/src/planner.rs b/datafusion/physical-expr/src/planner.rsindex 3a698eb8c7..3f94be0e1b 100644--- a/datafusion/physical-expr/src/planner.rs+++ b/datafusion/physical-expr/src/planner.rs@@ -26,7 +26,7 @@ use crate::{};use arrow::datatypes::Schema;use datafusion_common::plan_err;-use datafusion_common::{DFSchema, DataFusionError, Result, ScalarValue};+use datafusion_common::{internal_err, DFSchema, DataFusionError, Result, ScalarValue};use datafusion_expr::expr::{Alias, Cast, InList, ScalarFunction, ScalarUDF};use datafusion_expr::{binary_expr, Between, BinaryExpr, Expr, GetFieldAccess, GetIndexedField, Like,@@ -50,12 +50,12 @@ pub fn create_physical_expr(execution_props: &ExecutionProps,) -> Result<Arc<dyn PhysicalExpr>> {if input_schema.fields.len() != input_dfschema.fields().len() {- return Err(DataFusionError::Internal(format!(+ return internal_err!("create_physical_expr expected same number of fields, got \Arrow schema with {} and DataFusion schema with {}",input_schema.fields.len(),input_dfschema.fields().len()- )));+ );}match e {Expr::Alias(Alias { expr, .. }) => Ok(create_physical_expr(diff --git a/datafusion/physical-expr/src/regex_expressions.rs b/datafusion/physical-expr/src/regex_expressions.rsindex 419eafb1c8..f213336602 100644--- a/datafusion/physical-expr/src/regex_expressions.rs+++ b/datafusion/physical-expr/src/regex_expressions.rs@@ -27,7 +27,9 @@ use arrow::array::{};use arrow::compute;use datafusion_common::plan_err;-use datafusion_common::{cast::as_generic_string_array, DataFusionError, Result};+use datafusion_common::{+ cast::as_generic_string_array, internal_err, DataFusionError, Result,+};use datafusion_expr::{ColumnarValue, ScalarFunctionImplementation};use hashbrown::HashMap;use lazy_static::lazy_static;@@ -71,9 +73,9 @@ pub fn regexp_match<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {_ => compute::regexp_match(values, regex, flags).map_err(DataFusionError::ArrowError),}}- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("regexp_match was called with {other} arguments. It requires at least 2 and at most 3."- ))),+ ),}}@@ -186,9 +188,9 @@ pub fn regexp_replace<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef>Ok(Arc::new(result) as ArrayRef)}- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("regexp_replace was called with {other} arguments. It requires at least 3 and at most 4."- ))),+ ),}}@@ -219,9 +221,9 @@ fn _regexp_replace_static_pattern_replace<T: OffsetSizeTrait>(3 => None,4 => Some(fetch_string_arg!(&args[3], "flags", T, _regexp_replace_early_abort)),other => {- return Err(DataFusionError::Internal(format!(+ return internal_err!("regexp_replace was called with {other} arguments. It requires at least 3 and at most 4."- )))+ )}};diff --git a/datafusion/physical-expr/src/string_expressions.rs b/datafusion/physical-expr/src/string_expressions.rsindex 34319b9d97..00f0fe4abb 100644--- a/datafusion/physical-expr/src/string_expressions.rs+++ b/datafusion/physical-expr/src/string_expressions.rs@@ -34,7 +34,7 @@ use datafusion_common::{},ScalarValue,};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};use datafusion_expr::ColumnarValue;use std::iter;use std::sync::Arc;@@ -58,11 +58,11 @@ whereF: Fn(&'a str) -> R,{if args.len() != 1 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("{:?} args were supplied but {} takes exactly one argument",args.len(),- name,- )));+ name+ );}let string_array = as_generic_string_array::<T>(args[0])?;@@ -98,9 +98,7 @@ where&[a.as_ref()], op, name)?)))}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function {name}",- ))),+ other => internal_err!("Unsupported data type {other:?} for function {name}"),},ColumnarValue::Scalar(scalar) => match scalar {ScalarValue::Utf8(a) => {@@ -111,9 +109,7 @@ wherelet result = a.as_ref().map(|x| (op)(x).as_ref().to_string());Ok(ColumnarValue::Scalar(ScalarValue::LargeUtf8(result)))}- other => Err(DataFusionError::Internal(format!(- "Unsupported data type {other:?} for function {name}",- ))),+ other => internal_err!("Unsupported data type {other:?} for function {name}"),},}}@@ -177,9 +173,9 @@ pub fn btrim<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {Ok(Arc::new(result) as ArrayRef)}- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("btrim was called with {other} arguments. It requires at least 1 and at most 2."- ))),+ ),}}@@ -219,10 +215,10 @@ pub fn chr(args: &[ArrayRef]) -> Result<ArrayRef> {pub fn concat(args: &[ColumnarValue]) -> Result<ColumnarValue> {// do not accept 0 arguments.if args.is_empty() {- return Err(DataFusionError::Internal(format!(+ return internal_err!("concat was called with {} arguments. It requires at least 1.",args.len()- )));+ );}// first, decide whether to return a scalar or a vector.@@ -285,10 +281,10 @@ pub fn concat_ws(args: &[ArrayRef]) -> Result<ArrayRef> {// do not accept 0 or 1 arguments.if args.len() < 2 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("concat_ws was called with {} arguments. It requires at least 2.",args.len()- )));+ );}// first map is the iterator, second is for the `Option<_>`@@ -383,9 +379,9 @@ pub fn ltrim<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {Ok(Arc::new(result) as ArrayRef)}- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("ltrim was called with {other} arguments. It requires at least 1 and at most 2."- ))),+ ),}}@@ -459,9 +455,9 @@ pub fn rtrim<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {Ok(Arc::new(result) as ArrayRef)}- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("rtrim was called with {other} arguments. It requires at least 1 and at most 2."- ))),+ ),}}@@ -531,9 +527,7 @@ where} else if let Some(value_isize) = value.to_isize() {Ok(Some(format!("{value_isize:x}")))} else {- Err(DataFusionError::Internal(format!(- "Unsupported data type {integer:?} for function to_hex",- )))+ internal_err!("Unsupported data type {integer:?} for function to_hex")}} else {Ok(None)diff --git a/datafusion/physical-expr/src/unicode_expressions.rs b/datafusion/physical-expr/src/unicode_expressions.rsindex 9f09402494..92084cf433 100644--- a/datafusion/physical-expr/src/unicode_expressions.rs+++ b/datafusion/physical-expr/src/unicode_expressions.rs@@ -27,7 +27,7 @@ use arrow::{};use datafusion_common::{cast::{as_generic_string_array, as_int64_array},- DataFusionError, Result,+ internal_err, DataFusionError, Result,};use hashbrown::HashMap;use std::cmp::{max, Ordering};@@ -312,9 +312,9 @@ pub fn rpad<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {Ok(Arc::new(result) as ArrayRef)}- other => Err(DataFusionError::Internal(format!(+ other => internal_err!("rpad was called with {other} arguments. It requires at least 2 and at most 3."- ))),+ ),}}@@ -406,9 +406,9 @@ pub fn substr<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {Ok(Arc::new(result) as ArrayRef)}- other => Err(DataFusionError::Internal(format!(- "substr was called with {other} arguments. It requires 2 or 3."- ))),+ other => {+ internal_err!("substr was called with {other} arguments. It requires 2 or 3.")+ }}}diff --git a/datafusion/physical-expr/src/window/window_expr.rs b/datafusion/physical-expr/src/window/window_expr.rsindex 3cc022f88f..b0ea7d1b01 100644--- a/datafusion/physical-expr/src/window/window_expr.rs+++ b/datafusion/physical-expr/src/window/window_expr.rs@@ -21,7 +21,7 @@ use arrow::compute::kernels::sort::SortColumn;use arrow::compute::SortOptions;use arrow::datatypes::Field;use arrow::record_batch::RecordBatch;-use datafusion_common::{DataFusionError, Result, ScalarValue};+use datafusion_common::{internal_err, DataFusionError, Result, ScalarValue};use datafusion_expr::window_state::{PartitionBatchState, WindowAggState, WindowFrameContext,};@@ -97,10 +97,7 @@ pub trait WindowExpr: Send + Sync + Debug {_partition_batches: &PartitionBatches,_window_agg_state: &mut PartitionWindowAggStates,) -> Result<()> {- Err(DataFusionError::Internal(format!(- "evaluate_stateful is not implemented for {}",- self.name()- )))+ internal_err!("evaluate_stateful is not implemented for {}", self.name())}/// Expressions that's from the window function's partition by clause, empty if absentdiff --git a/datafusion/proto/src/common.rs b/datafusion/proto/src/common.rsindex cbbb469f08..b18831048e 100644--- a/datafusion/proto/src/common.rs+++ b/datafusion/proto/src/common.rs@@ -15,13 +15,13 @@// specific language governing permissions and limitations// under the License.-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};pub(crate) fn str_to_byte(s: &String, description: &str) -> Result<u8> {if s.len() != 1 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Invalid CSV {description}: expected single character, got {s}"- )));+ );}Ok(s.as_bytes()[0])}diff --git a/datafusion/proto/src/logical_plan/mod.rs b/datafusion/proto/src/logical_plan/mod.rsindex 511b288442..d218cdf3e6 100644--- a/datafusion/proto/src/logical_plan/mod.rs+++ b/datafusion/proto/src/logical_plan/mod.rs@@ -39,8 +39,8 @@ use datafusion::{prelude::SessionContext,};use datafusion_common::{- context, parsers::CompressionTypeVariant, DataFusionError, OwnedTableReference,- Result,+ context, internal_err, parsers::CompressionTypeVariant, DataFusionError,+ OwnedTableReference, Result,};use datafusion_expr::logical_plan::DdlStatement;use datafusion_expr::DropView;@@ -225,11 +225,11 @@ impl AsLogicalPlan for LogicalPlanNode {let values: Vec<Vec<Expr>> = if values.values_list.is_empty() {Ok(Vec::new())} else if values.values_list.len() % n_cols != 0 {- Err(DataFusionError::Internal(format!(+ internal_err!("Invalid values list length, expect {} to be divisible by {}",values.values_list.len(),n_cols- )))+ )} else {values.values_list@@ -503,9 +503,7 @@ impl AsLogicalPlan for LogicalPlanNode {let file_type = create_extern_table.file_type.as_str();if ctx.table_factory(file_type).is_none() {- Err(DataFusionError::Internal(format!(- "No TableProviderFactory for file type: {file_type}"- )))?+ internal_err!("No TableProviderFactory for file type: {file_type}")?}let mut order_exprs = vec![];diff --git a/datafusion/proto/src/physical_plan/mod.rs b/datafusion/proto/src/physical_plan/mod.rsindex 7fe193ffbb..8d4f5138f9 100644--- a/datafusion/proto/src/physical_plan/mod.rs+++ b/datafusion/proto/src/physical_plan/mod.rs@@ -47,7 +47,7 @@ use datafusion::physical_plan::windows::{create_window_expr, WindowAggExec};use datafusion::physical_plan::{udaf, AggregateExpr, ExecutionPlan, Partitioning, PhysicalExpr, WindowExpr,};-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};use prost::bytes::BufMut;use prost::Message;@@ -651,9 +651,9 @@ impl AsExecutionPlan for PhysicalPlanNode {},})} else {- Err(DataFusionError::Internal(format!(+ internal_err!("physical_plan::from_proto() {self:?}"- )))+ )}}).collect::<Result<Vec<_>, _>>()?;@@ -698,9 +698,9 @@ impl AsExecutionPlan for PhysicalPlanNode {},})} else {- Err(DataFusionError::Internal(format!(+ internal_err!("physical_plan::from_proto() {self:?}"- )))+ )}}).collect::<Result<Vec<_>, _>>()?;@@ -1300,9 +1300,9 @@ impl AsExecutionPlan for PhysicalPlanNode {)),})}- Err(e) => Err(DataFusionError::Internal(format!(+ Err(e) => internal_err!("Unsupported plan and extension codec failed with [{e}]. Plan: {plan_clone:?}"- ))),+ ),}}}diff --git a/datafusion/proto/src/physical_plan/to_proto.rs b/datafusion/proto/src/physical_plan/to_proto.rsindex 243e035f38..96bc5617d2 100644--- a/datafusion/proto/src/physical_plan/to_proto.rs+++ b/datafusion/proto/src/physical_plan/to_proto.rs@@ -52,7 +52,7 @@ use datafusion::physical_expr::expressions::{GetFieldAccessExpr, GetIndexedFielduse datafusion::physical_expr::{PhysicalSortExpr, ScalarFunctionExpr};use datafusion::physical_plan::joins::utils::JoinSide;use datafusion::physical_plan::udaf::AggregateFunctionExpr;-use datafusion_common::{DataFusionError, Result};+use datafusion_common::{internal_err, DataFusionError, Result};impl TryFrom<Arc<dyn AggregateExpr>> for protobuf::PhysicalExprNode {type Error = DataFusionError;@@ -405,9 +405,7 @@ impl TryFrom<Arc<dyn PhysicalExpr>> for protobuf::PhysicalExprNode {),})} else {- Err(DataFusionError::Internal(format!(- "physical_plan::to_proto() unsupported expression {value:?}"- )))+ internal_err!("physical_plan::to_proto() unsupported expression {value:?}")}}}diff --git a/datafusion/sql/src/expr/identifier.rs b/datafusion/sql/src/expr/identifier.rsindex 94faa08e51..5a081136cc 100644--- a/datafusion/sql/src/expr/identifier.rs+++ b/datafusion/sql/src/expr/identifier.rs@@ -17,7 +17,7 @@use crate::planner::{ContextProvider, PlannerContext, SqlToRel};use datafusion_common::{- Column, DFField, DFSchema, DataFusionError, Result, TableReference,+ internal_err, Column, DFField, DFSchema, DataFusionError, Result, TableReference,};use datafusion_expr::{Case, Expr};use sqlparser::ast::{Expr as SQLExpr, Ident};@@ -90,9 +90,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {planner_context: &mut PlannerContext,) -> Result<Expr> {if ids.len() < 2 {- return Err(DataFusionError::Internal(format!(- "Not a compound identifier: {ids:?}"- )));+ return internal_err!("Not a compound identifier: {ids:?}");}if ids[0].value.starts_with('@') {@@ -119,9 +117,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {// Though ideally once that support is in place, this code should work with it// TODO: remove when can support multiple nested identifiersif ids.len() > 5 {- return Err(DataFusionError::Internal(format!(- "Unsupported compound identifier: {ids:?}"- )));+ return internal_err!("Unsupported compound identifier: {ids:?}");}let search_result = search_dfschema(&ids, schema);@@ -130,10 +126,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {Some((field, nested_names)) if !nested_names.is_empty() => {// TODO: remove when can support multiple nested identifiersif nested_names.len() > 1 {- return Err(DataFusionError::Internal(format!(+ return internal_err!("Nested identifiers not yet supported for column {}",field.qualified_column().quoted_flat_name()- )));+ );}let nested_name = nested_names[0].to_string();Ok(Expr::Column(field.qualified_column()).field(nested_name))@@ -146,9 +142,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {// return default where use all identifiers to not have a nested field// this len check is because at 5 identifiers will have to have a nested fieldif ids.len() == 5 {- Err(DataFusionError::Internal(format!(- "Unsupported compound identifier: {ids:?}"- )))+ internal_err!("Unsupported compound identifier: {ids:?}")} else {// check the outer_query_schema and try to find a matchif let Some(outer) = planner_context.outer_query_schema() {@@ -159,10 +153,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {if !nested_names.is_empty() =>{// TODO: remove when can support nested identifiers for OuterReferenceColumn- Err(DataFusionError::Internal(format!(+ internal_err!("Nested identifiers are not yet supported for OuterReferenceColumn {}",field.qualified_column().quoted_flat_name()- )))+ )}// found matching field with no spare identifier(s)Some((field, _nested_names)) => {@@ -269,10 +263,7 @@ fn form_identifier(idents: &[String]) -> Result<(Option<TableReference>, &String}),&idents[3],)),- _ => Err(DataFusionError::Internal(format!(- "Incorrect number of identifiers: {}",- idents.len()- ))),+ _ => internal_err!("Incorrect number of identifiers: {}", idents.len()),}}diff --git a/datafusion/substrait/src/logical_plan/producer.rs b/datafusion/substrait/src/logical_plan/producer.rsindex d3337e736d..495ccf1e35 100644--- a/datafusion/substrait/src/logical_plan/producer.rs+++ b/datafusion/substrait/src/logical_plan/producer.rs@@ -28,6 +28,7 @@ use datafusion::{scalar::ScalarValue,};+use datafusion::common::internal_err;use datafusion::common::DFSchemaRef;#[allow(unused_imports)]use datafusion::logical_expr::aggregate_function;@@ -539,11 +540,11 @@ pub fn to_substrait_agg_measure(Expr::Alias(Alias{expr,..})=> {to_substrait_agg_measure(expr, schema, extension_info)}- _ => Err(DataFusionError::Internal(format!(+ _ => internal_err!("Expression must be compatible with aggregation. Unsupported expression: {:?}. ExpressionType: {:?}",expr,expr.variant_name()- ))),+ ),}}