Apache DataFusion SQL Query Engine
Skip casting result array for binary numerical operators result between array and scalar if possible (#6438)
Liang-Chi Hsieh0c7a3b63ccfb
diff --git a/datafusion/physical-expr/src/expressions/binary.rs b/datafusion/physical-expr/src/expressions/binary.rsindex 841a8dcf75..295d5fe655 100644--- a/datafusion/physical-expr/src/expressions/binary.rs+++ b/datafusion/physical-expr/src/expressions/binary.rs@@ -1059,16 +1059,18 @@ fn to_result_type_array(array: ArrayRef,result_type: &DataType,) -> Result<ArrayRef> {- if op.is_numerical_operators() {+ if array.data_type() == result_type {+ Ok(array)+ } else if op.is_numerical_operators() {match array.data_type() {DataType::Dictionary(_, value_type) => {if value_type.as_ref() == result_type {Ok(cast(&array, result_type)?)} else {Err(DataFusionError::Internal(format!(- "Incompatible Dictionary value type {:?} with result type {:?} of Binary operator {:?}",- value_type, result_type, op- )))+ "Incompatible Dictionary value type {:?} with result type {:?} of Binary operator {:?}",+ value_type, result_type, op+ )))}}_ => Ok(array),@@ -5634,4 +5636,37 @@ mod tests {);assert_eq!(expr.to_string(), "(1 OR 2) AND (3 OR 4)");}++ #[test]+ fn test_to_result_type_array() {+ let values = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));+ let keys = Int8Array::from(vec![Some(0), None, Some(2), Some(3)]);+ let dictionary =+ Arc::new(DictionaryArray::try_new(keys, values).unwrap()) as ArrayRef;++ // Casting Dictionary to Int32+ let casted =+ to_result_type_array(&Operator::Plus, dictionary.clone(), &DataType::Int32)+ .unwrap();+ assert_eq!(+ &casted,+ &(Arc::new(Int32Array::from(vec![Some(1), None, Some(3), Some(4)]))+ as ArrayRef)+ );++ // Array has same datatype as result type, no casting+ let casted = to_result_type_array(+ &Operator::Plus,+ dictionary.clone(),+ dictionary.data_type(),+ )+ .unwrap();+ assert_eq!(&casted, &dictionary);++ // Not numerical operator, no casting+ let casted =+ to_result_type_array(&Operator::Eq, dictionary.clone(), &DataType::Int32)+ .unwrap();+ assert_eq!(&casted, &dictionary);+ }}