Apache DataFusion SQL Query Engine
support comparison for decimal data type and refactor the binary coercion rule (#1483)
Kun Liu1c39f5ce865e
diff --git a/ballista/rust/core/Cargo.toml b/ballista/rust/core/Cargo.tomlindex bbf8e274c5..190f7b85ba 100644--- a/ballista/rust/core/Cargo.toml+++ b/ballista/rust/core/Cargo.toml@@ -44,7 +44,6 @@ uuid = { version = "0.8", features = ["v4"] }chrono = { version = "0.4", default-features = false }arrow-flight = { version = "7.0.0" }-datafusion = { path = "../../../datafusion", version = "6.0.0" }[dev-dependencies]diff --git a/datafusion/src/physical_plan/coercion_rule/binary_rule.rs b/datafusion/src/physical_plan/coercion_rule/binary_rule.rsnew file mode 100644index 0000000000..9fc29d6ee2--- /dev/null+++ b/datafusion/src/physical_plan/coercion_rule/binary_rule.rs@@ -0,0 +1,229 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++//! Support the coercion rule for binary operation++use crate::arrow::datatypes::DataType;+use crate::error::{DataFusionError, Result};+use crate::logical_plan::Operator;+use crate::physical_plan::expressions::coercion::{+ dictionary_coercion, eq_coercion, is_numeric, like_coercion, numerical_coercion,+ string_coercion, temporal_coercion,+};++/// Coercion rules for all binary operators. Returns the output type+/// of applying `op` to an argument of `lhs_type` and `rhs_type`.+pub(crate) fn coerce_types(+ lhs_type: &DataType,+ op: &Operator,+ rhs_type: &DataType,+) -> Result<DataType> {+ // This result MUST be compatible with `binary_coerce`+ let result = match op {+ Operator::And | Operator::Or => match (lhs_type, rhs_type) {+ // logical binary boolean operators can only be evaluated in bools+ (DataType::Boolean, DataType::Boolean) => Some(DataType::Boolean),+ _ => None,+ },+ // logical equality operators have their own rules, and always return a boolean+ Operator::Eq | Operator::NotEq => comparison_eq_coercion(lhs_type, rhs_type),+ // order-comparison operators have their own rules+ Operator::Lt | Operator::Gt | Operator::GtEq | Operator::LtEq => {+ comparison_order_coercion(lhs_type, rhs_type)+ }+ // "like" operators operate on strings and always return a boolean+ Operator::Like | Operator::NotLike => like_coercion(lhs_type, rhs_type),+ // for math expressions, the final value of the coercion is also the return type+ // because coercion favours higher information types+ // TODO: support decimal data type+ Operator::Plus+ | Operator::Minus+ | Operator::Modulo+ | Operator::Divide+ | Operator::Multiply => numerical_coercion(lhs_type, rhs_type),+ Operator::RegexMatch+ | Operator::RegexIMatch+ | Operator::RegexNotMatch+ | Operator::RegexNotIMatch => string_coercion(lhs_type, rhs_type),+ Operator::IsDistinctFrom | Operator::IsNotDistinctFrom => {+ eq_coercion(lhs_type, rhs_type)+ }+ };++ // re-write the error message of failed coercions to include the operator's information+ match result {+ None => Err(DataFusionError::Plan(+ format!(+ "'{:?} {} {:?}' can't be evaluated because there isn't a common type to coerce the types to",+ lhs_type, op, rhs_type+ ),+ )),+ Some(t) => Ok(t)+ }+}++fn comparison_eq_coercion(lhs_type: &DataType, rhs_type: &DataType) -> Option<DataType> {+ if lhs_type == rhs_type {+ // same type => equality is possible+ return Some(lhs_type.clone());+ }+ comparison_binary_numeric_coercion(lhs_type, rhs_type)+ .or_else(|| dictionary_coercion(lhs_type, rhs_type))+ .or_else(|| temporal_coercion(lhs_type, rhs_type))+}++fn comparison_order_coercion(+ lhs_type: &DataType,+ rhs_type: &DataType,+) -> Option<DataType> {+ if lhs_type == rhs_type {+ // same type => all good+ return Some(lhs_type.clone());+ }+ comparison_binary_numeric_coercion(lhs_type, rhs_type)+ .or_else(|| string_coercion(lhs_type, rhs_type))+ .or_else(|| dictionary_coercion(lhs_type, rhs_type))+ .or_else(|| temporal_coercion(lhs_type, rhs_type))+}++fn comparison_binary_numeric_coercion(+ lhs_type: &DataType,+ rhs_type: &DataType,+) -> Option<DataType> {+ use arrow::datatypes::DataType::*;+ if !is_numeric(lhs_type) || !is_numeric(rhs_type) {+ return None;+ };++ // same type => all good+ if lhs_type == rhs_type {+ return Some(lhs_type.clone());+ }++ // these are ordered from most informative to least informative so+ // that the coercion removes the least amount of information+ match (lhs_type, rhs_type) {+ // support decimal data type for comparison operation+ (Decimal(p1, s1), Decimal(p2, s2)) => Some(Decimal(*p1.max(p2), *s1.max(s2))),+ (Decimal(_, _), _) => get_comparison_common_decimal_type(lhs_type, rhs_type),+ (_, Decimal(_, _)) => get_comparison_common_decimal_type(rhs_type, lhs_type),+ (Float64, _) | (_, Float64) => Some(Float64),+ (_, Float32) | (Float32, _) => Some(Float32),+ (Int64, _) | (_, Int64) => Some(Int64),+ (Int32, _) | (_, Int32) => Some(Int32),+ (Int16, _) | (_, Int16) => Some(Int16),+ (Int8, _) | (_, Int8) => Some(Int8),+ (UInt64, _) | (_, UInt64) => Some(UInt64),+ (UInt32, _) | (_, UInt32) => Some(UInt32),+ (UInt16, _) | (_, UInt16) => Some(UInt16),+ (UInt8, _) | (_, UInt8) => Some(UInt8),+ _ => None,+ }+}++fn get_comparison_common_decimal_type(+ decimal_type: &DataType,+ other_type: &DataType,+) -> Option<DataType> {+ let other_decimal_type = &match other_type {+ // This conversion rule is from spark+ // https://github.com/apache/spark/blob/1c81ad20296d34f137238dadd67cc6ae405944eb/sql/catalyst/src/main/scala/org/apache/spark/sql/types/DecimalType.scala#L127+ DataType::Int8 => DataType::Decimal(3, 0),+ DataType::Int16 => DataType::Decimal(5, 0),+ DataType::Int32 => DataType::Decimal(10, 0),+ DataType::Int64 => DataType::Decimal(20, 0),+ DataType::Float32 => DataType::Decimal(14, 7),+ DataType::Float64 => DataType::Decimal(30, 15),+ _ => {+ return None;+ }+ };+ match (decimal_type, &other_decimal_type) {+ (DataType::Decimal(p1, s1), DataType::Decimal(p2, s2)) => {+ let new_precision = p1.max(p2);+ let new_scale = s1.max(s2);+ Some(DataType::Decimal(*new_precision, *new_scale))+ }+ _ => None,+ }+}++#[cfg(test)]+mod tests {+ use crate::arrow::datatypes::DataType;+ use crate::error::{DataFusionError, Result};+ use crate::logical_plan::Operator;+ use crate::physical_plan::coercion_rule::binary_rule::coerce_types;++ #[test]++ fn test_coercion_error() -> Result<()> {+ let result_type =+ coerce_types(&DataType::Float32, &Operator::Plus, &DataType::Utf8);++ if let Err(DataFusionError::Plan(e)) = result_type {+ assert_eq!(e, "'Float32 + Utf8' can't be evaluated because there isn't a common type to coerce the types to");+ Ok(())+ } else {+ Err(DataFusionError::Internal(+ "Coercion should have returned an DataFusionError::Internal".to_string(),+ ))+ }+ }++ #[test]+ fn test_decimal_binary_comparison_coercion() -> Result<()> {+ let input_decimal = DataType::Decimal(20, 3);+ let input_types = [+ DataType::Int8,+ DataType::Int16,+ DataType::Int32,+ DataType::Int64,+ DataType::Float32,+ DataType::Float64,+ DataType::Decimal(38, 10),+ ];+ let result_types = [+ DataType::Decimal(20, 3),+ DataType::Decimal(20, 3),+ DataType::Decimal(20, 3),+ DataType::Decimal(20, 3),+ DataType::Decimal(20, 7),+ DataType::Decimal(30, 15),+ DataType::Decimal(38, 10),+ ];+ let comparison_op_types = [+ Operator::NotEq,+ Operator::Eq,+ Operator::Gt,+ Operator::GtEq,+ Operator::Lt,+ Operator::LtEq,+ ];+ for (i, input_type) in input_types.iter().enumerate() {+ let expect_type = &result_types[i];+ for op in comparison_op_types {+ let result_type = coerce_types(&input_decimal, &op, input_type)?;+ assert_eq!(expect_type, &result_type);+ }+ }+ // negative test+ let result_type = coerce_types(&input_decimal, &Operator::Eq, &DataType::Boolean);+ assert!(result_type.is_err());+ Ok(())+ }+}diff --git a/datafusion/src/physical_plan/coercion_rule/mod.rs b/datafusion/src/physical_plan/coercion_rule/mod.rsindex 1aeabda793..83e091aa5e 100644--- a/datafusion/src/physical_plan/coercion_rule/mod.rs+++ b/datafusion/src/physical_plan/coercion_rule/mod.rs@@ -18,5 +18,7 @@//! Define coercion rules for different Expr type.//!//! Aggregate function rule+//! Binary operation rulepub(crate) mod aggregate_rule;+pub(crate) mod binary_rule;diff --git a/datafusion/src/physical_plan/expressions/binary.rs b/datafusion/src/physical_plan/expressions/binary.rsindex bd593fd6ec..cf340b5369 100644--- a/datafusion/src/physical_plan/expressions/binary.rs+++ b/datafusion/src/physical_plan/expressions/binary.rs@@ -45,14 +45,11 @@ use arrow::record_batch::RecordBatch;use crate::error::{DataFusionError, Result};use crate::logical_plan::Operator;+use crate::physical_plan::coercion_rule::binary_rule::coerce_types;use crate::physical_plan::expressions::try_cast;use crate::physical_plan::{ColumnarValue, PhysicalExpr};use crate::scalar::ScalarValue;-use super::coercion::{- eq_coercion, like_coercion, numerical_coercion, order_coercion, string_coercion,-};-// Simple (low performance) kernels until optimized kernels are added to arrow// See https://github.com/apache/arrow-rs/issues/960@@ -79,6 +76,193 @@ fn is_not_distinct_from_bool(.collect())}+// TODO add iter for decimal array+// TODO move this to arrow-rs+// https://github.com/apache/arrow-rs/issues/1083+pub(super) fn eq_decimal_scalar(+ left: &DecimalArray,+ right: i128,+) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) {+ bool_builder.append_null()?;+ } else {+ bool_builder.append_value(left.value(i) == right)?;+ }+ }+ Ok(bool_builder.finish())+}++pub(super) fn eq_decimal(+ left: &DecimalArray,+ right: &DecimalArray,+) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) || right.is_null(i) {+ bool_builder.append_null()?;+ } else {+ bool_builder.append_value(left.value(i) == right.value(i))?;+ }+ }+ Ok(bool_builder.finish())+}++fn neq_decimal_scalar(left: &DecimalArray, right: i128) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) {+ bool_builder.append_null()?;+ } else {+ bool_builder.append_value(left.value(i) != right)?;+ }+ }+ Ok(bool_builder.finish())+}++fn neq_decimal(left: &DecimalArray, right: &DecimalArray) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) || right.is_null(i) {+ bool_builder.append_null()?;+ } else {+ bool_builder.append_value(left.value(i) != right.value(i))?;+ }+ }+ Ok(bool_builder.finish())+}++fn lt_decimal_scalar(left: &DecimalArray, right: i128) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) {+ bool_builder.append_null()?;+ } else {+ bool_builder.append_value(left.value(i) < right)?;+ }+ }+ Ok(bool_builder.finish())+}++fn lt_decimal(left: &DecimalArray, right: &DecimalArray) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) || right.is_null(i) {+ bool_builder.append_null()?;+ } else {+ bool_builder.append_value(left.value(i) < right.value(i))?;+ }+ }+ Ok(bool_builder.finish())+}++fn lt_eq_decimal_scalar(left: &DecimalArray, right: i128) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) {+ bool_builder.append_null()?;+ } else {+ bool_builder.append_value(left.value(i) <= right)?;+ }+ }+ Ok(bool_builder.finish())+}++fn lt_eq_decimal(left: &DecimalArray, right: &DecimalArray) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) || right.is_null(i) {+ bool_builder.append_null()?;+ } else {+ bool_builder.append_value(left.value(i) <= right.value(i))?;+ }+ }+ Ok(bool_builder.finish())+}++fn gt_decimal_scalar(left: &DecimalArray, right: i128) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) {+ bool_builder.append_null()?;+ } else {+ bool_builder.append_value(left.value(i) > right)?;+ }+ }+ Ok(bool_builder.finish())+}++fn gt_decimal(left: &DecimalArray, right: &DecimalArray) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) || right.is_null(i) {+ bool_builder.append_null()?;+ } else {+ bool_builder.append_value(left.value(i) > right.value(i))?;+ }+ }+ Ok(bool_builder.finish())+}++fn gt_eq_decimal_scalar(left: &DecimalArray, right: i128) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) {+ bool_builder.append_null()?;+ } else {+ bool_builder.append_value(left.value(i) >= right)?;+ }+ }+ Ok(bool_builder.finish())+}++fn gt_eq_decimal(left: &DecimalArray, right: &DecimalArray) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) || right.is_null(i) {+ bool_builder.append_null()?;+ } else {+ bool_builder.append_value(left.value(i) >= right.value(i))?;+ }+ }+ Ok(bool_builder.finish())+}++fn is_distinct_from_decimal(+ left: &DecimalArray,+ right: &DecimalArray,+) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) && right.is_null(i) {+ bool_builder.append_value(false)?;+ } else if left.is_null(i) || right.is_null(i) {+ bool_builder.append_value(true)?;+ } else {+ bool_builder.append_value(left.value(i) != right.value(i))?;+ }+ }+ Ok(bool_builder.finish())+}++fn is_not_distinct_from_decimal(+ left: &DecimalArray,+ right: &DecimalArray,+) -> Result<BooleanArray> {+ let mut bool_builder = BooleanBuilder::new(left.len());+ for i in 0..left.len() {+ if left.is_null(i) && right.is_null(i) {+ bool_builder.append_value(true)?;+ } else if left.is_null(i) || right.is_null(i) {+ bool_builder.append_value(false)?;+ } else {+ bool_builder.append_value(left.value(i) == right.value(i))?;+ }+ }+ Ok(bool_builder.finish())+}+/// Binary expression#[derive(Debug)]pub struct BinaryExpr {@@ -119,6 +303,24 @@ impl std::fmt::Display for BinaryExpr {}}+macro_rules! compute_decimal_op_scalar {+ ($LEFT:expr, $RIGHT:expr, $OP:ident, $DT:ident) => {{+ let ll = $LEFT.as_any().downcast_ref::<$DT>().unwrap();+ Ok(Arc::new(paste::expr! {[<$OP _decimal_scalar>]}(+ ll,+ $RIGHT.try_into()?,+ )?))+ }};+}++macro_rules! compute_decimal_op {+ ($LEFT:expr, $RIGHT:expr, $OP:ident, $DT:ident) => {{+ let ll = $LEFT.as_any().downcast_ref::<$DT>().unwrap();+ let rr = $RIGHT.as_any().downcast_ref::<$DT>().unwrap();+ Ok(Arc::new(paste::expr! {[<$OP _decimal>]}(ll, rr)?))+ }};+}+/// Invoke a compute kernel on a pair of binary data arraysmacro_rules! compute_utf8_op {($LEFT:expr, $RIGHT:expr, $OP:ident, $DT:ident) => {{@@ -198,6 +400,7 @@ macro_rules! compute_bool_op {}/// Invoke a compute kernel on a data array and a scalar value+/// LEFT is array, RIGHT is scalar valuemacro_rules! compute_op_scalar {($LEFT:expr, $RIGHT:expr, $OP:ident, $DT:ident) => {{use std::convert::TryInto;@@ -318,6 +521,7 @@ macro_rules! binary_primitive_array_op_scalar {macro_rules! binary_array_op_scalar {($LEFT:expr, $RIGHT:expr, $OP:ident) => {{let result: Result<Arc<dyn Array>> = match $LEFT.data_type() {+ DataType::Decimal(_,_) => compute_decimal_op_scalar!($LEFT, $RIGHT, $OP, DecimalArray),DataType::Int8 => compute_op_scalar!($LEFT, $RIGHT, $OP, Int8Array),DataType::Int16 => compute_op_scalar!($LEFT, $RIGHT, $OP, Int16Array),DataType::Int32 => compute_op_scalar!($LEFT, $RIGHT, $OP, Int32Array),@@ -363,6 +567,7 @@ macro_rules! binary_array_op_scalar {macro_rules! binary_array_op {($LEFT:expr, $RIGHT:expr, $OP:ident) => {{match $LEFT.data_type() {+ DataType::Decimal(_,_) => compute_decimal_op!($LEFT, $RIGHT, $OP, DecimalArray),DataType::Int8 => compute_op!($LEFT, $RIGHT, $OP, Int8Array),DataType::Int16 => compute_op!($LEFT, $RIGHT, $OP, Int16Array),DataType::Int32 => compute_op!($LEFT, $RIGHT, $OP, Int32Array),@@ -501,58 +706,6 @@ macro_rules! compute_utf8_flag_op_scalar {}};}-/// Coercion rules for all binary operators. Returns the output type-/// of applying `op` to an argument of `lhs_type` and `rhs_type`.-fn common_binary_type(- lhs_type: &DataType,- op: &Operator,- rhs_type: &DataType,-) -> Result<DataType> {- // This result MUST be compatible with `binary_coerce`- let result = match op {- Operator::And | Operator::Or => match (lhs_type, rhs_type) {- // logical binary boolean operators can only be evaluated in bools- (DataType::Boolean, DataType::Boolean) => Some(DataType::Boolean),- _ => None,- },- // logical equality operators have their own rules, and always return a boolean- Operator::Eq | Operator::NotEq => eq_coercion(lhs_type, rhs_type),- // "like" operators operate on strings and always return a boolean- Operator::Like | Operator::NotLike => like_coercion(lhs_type, rhs_type),- // order-comparison operators have their own rules- Operator::Lt | Operator::Gt | Operator::GtEq | Operator::LtEq => {- order_coercion(lhs_type, rhs_type)- }- // for math expressions, the final value of the coercion is also the return type- // because coercion favours higher information types- Operator::Plus- | Operator::Minus- | Operator::Modulo- | Operator::Divide- | Operator::Multiply => numerical_coercion(lhs_type, rhs_type),- Operator::RegexMatch- | Operator::RegexIMatch- | Operator::RegexNotMatch- | Operator::RegexNotIMatch => string_coercion(lhs_type, rhs_type),- Operator::IsDistinctFrom | Operator::IsNotDistinctFrom => {- eq_coercion(lhs_type, rhs_type)- }- };-- // re-write the error message of failed coercions to include the operator's information- match result {- None => {- Err(DataFusionError::Plan(- format!(- "'{:?} {} {:?}' can't be evaluated because there isn't a common type to coerce the types to",- lhs_type, op, rhs_type- ),- ))- },- Some(t) => Ok(t)- }-}-/// Returns the return type of a binary operator or an error when the binary operator cannot/// perform the computation between the argument's types, even after type coercion.///@@ -564,7 +717,7 @@ pub fn binary_operator_data_type() -> Result<DataType> {// validate that it is possible to perform the operation on incoming types.// (or the return datatype cannot be inferred)- let common_type = common_binary_type(lhs_type, op, rhs_type)?;+ let result_type = coerce_types(lhs_type, op, rhs_type)?;match op {// operators that return a boolean@@ -589,7 +742,7 @@ pub fn binary_operator_data_type(| Operator::Minus| Operator::Divide| Operator::Multiply- | Operator::Modulo => Ok(common_type),+ | Operator::Modulo => Ok(result_type),}}@@ -728,13 +881,9 @@ impl BinaryExpr {) -> Result<Option<Result<ArrayRef>>> {let scalar_result = match &self.op {Operator::Lt => binary_array_op_scalar!(array, scalar.clone(), gt),- Operator::LtEq => {- binary_array_op_scalar!(array, scalar.clone(), gt_eq)- }+ Operator::LtEq => binary_array_op_scalar!(array, scalar.clone(), gt_eq),Operator::Gt => binary_array_op_scalar!(array, scalar.clone(), lt),- Operator::GtEq => {- binary_array_op_scalar!(array, scalar.clone(), lt_eq)- }+ Operator::GtEq => binary_array_op_scalar!(array, scalar.clone(), lt_eq),Operator::Eq => binary_array_op_scalar!(array, scalar.clone(), eq),Operator::NotEq => {binary_array_op_scalar!(array, scalar.clone(), neq)@@ -869,11 +1018,11 @@ fn binary_cast(let lhs_type = &lhs.data_type(input_schema)?;let rhs_type = &rhs.data_type(input_schema)?;- let cast_type = common_binary_type(lhs_type, op, rhs_type)?;+ let result_type = coerce_types(lhs_type, op, rhs_type)?;Ok((- try_cast(lhs, input_schema, cast_type.clone())?,- try_cast(rhs, input_schema, cast_type)?,+ try_cast(lhs, input_schema, result_type.clone())?,+ try_cast(rhs, input_schema, result_type)?,))}@@ -905,8 +1054,9 @@ mod tests {l: Arc<dyn PhysicalExpr>,op: Operator,r: Arc<dyn PhysicalExpr>,+ input_schema: &Schema,) -> Arc<dyn PhysicalExpr> {- Arc::new(BinaryExpr::new(l, op, r))+ binary(l, op, r, input_schema).unwrap()}#[test]@@ -919,7 +1069,12 @@ mod tests {let b = Int32Array::from(vec![1, 2, 4, 8, 16]);// expression: "a < b"- let lt = binary_simple(col("a", &schema)?, Operator::Lt, col("b", &schema)?);+ let lt = binary_simple(+ col("a", &schema)?,+ Operator::Lt,+ col("b", &schema)?,+ &schema,+ );let batch =RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)])?;@@ -949,9 +1104,20 @@ mod tests {// expression: "a < b OR a == b"let expr = binary_simple(- binary_simple(col("a", &schema)?, Operator::Lt, col("b", &schema)?),+ binary_simple(+ col("a", &schema)?,+ Operator::Lt,+ col("b", &schema)?,+ &schema,+ ),Operator::Or,- binary_simple(col("a", &schema)?, Operator::Eq, col("b", &schema)?),+ binary_simple(+ col("a", &schema)?,+ Operator::Eq,+ col("b", &schema)?,+ &schema,+ ),+ &schema,);let batch =RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)])?;@@ -1423,7 +1589,8 @@ mod tests {op: Operator,expected: PrimitiveArray<T>,) -> Result<()> {- let arithmetic_op = binary_simple(col("a", &schema)?, op, col("b", &schema)?);+ let arithmetic_op =+ binary_simple(col("a", &schema)?, op, col("b", &schema)?, &schema);let batch = RecordBatch::try_new(schema, data)?;let result = arithmetic_op.evaluate(&batch)?.into_array(batch.num_rows());@@ -1432,15 +1599,16 @@ mod tests {}fn apply_logic_op(- schema: SchemaRef,- left: BooleanArray,- right: BooleanArray,+ schema: &SchemaRef,+ left: &ArrayRef,+ right: &ArrayRef,op: Operator,expected: BooleanArray,) -> Result<()> {- let arithmetic_op = binary_simple(col("a", &schema)?, op, col("b", &schema)?);- let data: Vec<ArrayRef> = vec![Arc::new(left), Arc::new(right)];- let batch = RecordBatch::try_new(schema, data)?;+ let arithmetic_op =+ binary_simple(col("a", schema)?, op, col("b", schema)?, schema);+ let data: Vec<ArrayRef> = vec![left.clone(), right.clone()];+ let batch = RecordBatch::try_new(schema.clone(), data)?;let result = arithmetic_op.evaluate(&batch)?.into_array(batch.num_rows());assert_eq!(result.as_ref(), &expected);@@ -1450,14 +1618,14 @@ mod tests {// Test `scalar <op> arr` produces expectedfn apply_logic_op_scalar_arr(schema: &SchemaRef,- scalar: bool,+ scalar: &ScalarValue,arr: &ArrayRef,op: Operator,expected: &BooleanArray,) -> Result<()> {- let scalar = lit(scalar.into());+ let scalar = lit(scalar.clone());- let arithmetic_op = binary_simple(scalar, op, col("a", schema)?);+ let arithmetic_op = binary_simple(scalar, op, col("a", schema)?, schema);let batch = RecordBatch::try_new(Arc::clone(schema), vec![Arc::clone(arr)])?;let result = arithmetic_op.evaluate(&batch)?.into_array(batch.num_rows());assert_eq!(result.as_ref(), expected);@@ -1469,13 +1637,13 @@ mod tests {fn apply_logic_op_arr_scalar(schema: &SchemaRef,arr: &ArrayRef,- scalar: bool,+ scalar: &ScalarValue,op: Operator,expected: &BooleanArray,) -> Result<()> {- let scalar = lit(scalar.into());+ let scalar = lit(scalar.clone());- let arithmetic_op = binary_simple(col("a", schema)?, op, scalar);+ let arithmetic_op = binary_simple(col("a", schema)?, op, scalar, schema);let batch = RecordBatch::try_new(Arc::clone(schema), vec![Arc::clone(arr)])?;let result = arithmetic_op.evaluate(&batch)?.into_array(batch.num_rows());assert_eq!(result.as_ref(), expected);@@ -1489,7 +1657,7 @@ mod tests {Field::new("a", DataType::Boolean, true),Field::new("b", DataType::Boolean, true),]);- let a = BooleanArray::from(vec![+ let a = Arc::new(BooleanArray::from(vec![Some(true),Some(false),None,@@ -1499,8 +1667,8 @@ mod tests {Some(true),Some(false),None,- ]);- let b = BooleanArray::from(vec![+ ])) as ArrayRef;+ let b = Arc::new(BooleanArray::from(vec![Some(true),Some(true),Some(true),@@ -1510,7 +1678,7 @@ mod tests {None,None,None,- ]);+ ])) as ArrayRef;let expected = BooleanArray::from(vec![Some(true),@@ -1523,7 +1691,7 @@ mod tests {Some(false),None,]);- apply_logic_op(Arc::new(schema), a, b, Operator::And, expected)?;+ apply_logic_op(&Arc::new(schema), &a, &b, Operator::And, expected)?;Ok(())}@@ -1534,7 +1702,7 @@ mod tests {Field::new("a", DataType::Boolean, true),Field::new("b", DataType::Boolean, true),]);- let a = BooleanArray::from(vec![+ let a = Arc::new(BooleanArray::from(vec![Some(true),Some(false),None,@@ -1544,8 +1712,8 @@ mod tests {Some(true),Some(false),None,- ]);- let b = BooleanArray::from(vec![+ ])) as ArrayRef;+ let b = Arc::new(BooleanArray::from(vec![Some(true),Some(true),Some(true),@@ -1555,7 +1723,7 @@ mod tests {None,None,None,- ]);+ ])) as ArrayRef;let expected = BooleanArray::from(vec![Some(true),@@ -1568,7 +1736,7 @@ mod tests {None,None,]);- apply_logic_op(Arc::new(schema), a, b, Operator::Or, expected)?;+ apply_logic_op(&Arc::new(schema), &a, &b, Operator::Or, expected)?;Ok(())}@@ -1577,12 +1745,12 @@ mod tests {////// a: [true, true, true, NULL, NULL, NULL, false, false, false]/// b: [true, NULL, false, true, NULL, false, true, NULL, false]- fn bool_test_arrays() -> (SchemaRef, BooleanArray, BooleanArray) {+ fn bool_test_arrays() -> (SchemaRef, ArrayRef, ArrayRef) {let schema = Schema::new(vec![Field::new("a", DataType::Boolean, false),Field::new("b", DataType::Boolean, false),]);- let a = [+ let a: BooleanArray = [Some(true),Some(true),Some(true),@@ -1595,7 +1763,7 @@ mod tests {].iter().collect();- let b = [+ let b: BooleanArray = [Some(true),None,Some(false),@@ -1608,7 +1776,7 @@ mod tests {].iter().collect();- (Arc::new(schema), a, b)+ (Arc::new(schema), Arc::new(a), Arc::new(b))}/// Returns (schema, BooleanArray) with [true, NULL, false]@@ -1634,19 +1802,47 @@ mod tests {].iter().collect();- apply_logic_op(schema, a, b, Operator::Eq, expected).unwrap();+ apply_logic_op(&schema, &a, &b, Operator::Eq, expected).unwrap();}#[test]fn eq_op_bool_scalar() {let (schema, a) = scalar_bool_test_array();let expected = [Some(true), None, Some(false)].iter().collect();- apply_logic_op_scalar_arr(&schema, true, &a, Operator::Eq, &expected).unwrap();- apply_logic_op_arr_scalar(&schema, &a, true, Operator::Eq, &expected).unwrap();+ apply_logic_op_scalar_arr(+ &schema,+ &ScalarValue::from(true),+ &a,+ Operator::Eq,+ &expected,+ )+ .unwrap();+ apply_logic_op_arr_scalar(+ &schema,+ &a,+ &ScalarValue::from(true),+ Operator::Eq,+ &expected,+ )+ .unwrap();let expected = [Some(false), None, Some(true)].iter().collect();- apply_logic_op_scalar_arr(&schema, false, &a, Operator::Eq, &expected).unwrap();- apply_logic_op_arr_scalar(&schema, &a, false, Operator::Eq, &expected).unwrap();+ apply_logic_op_scalar_arr(+ &schema,+ &ScalarValue::from(false),+ &a,+ Operator::Eq,+ &expected,+ )+ .unwrap();+ apply_logic_op_arr_scalar(+ &schema,+ &a,+ &ScalarValue::from(false),+ Operator::Eq,+ &expected,+ )+ .unwrap();}#[test]@@ -1665,21 +1861,47 @@ mod tests {].iter().collect();- apply_logic_op(schema, a, b, Operator::NotEq, expected).unwrap();+ apply_logic_op(&schema, &a, &b, Operator::NotEq, expected).unwrap();}#[test]fn neq_op_bool_scalar() {let (schema, a) = scalar_bool_test_array();let expected = [Some(false), None, Some(true)].iter().collect();- apply_logic_op_scalar_arr(&schema, true, &a, Operator::NotEq, &expected).unwrap();- apply_logic_op_arr_scalar(&schema, &a, true, Operator::NotEq, &expected).unwrap();+ apply_logic_op_scalar_arr(+ &schema,+ &ScalarValue::from(true),+ &a,+ Operator::NotEq,+ &expected,+ )+ .unwrap();+ apply_logic_op_arr_scalar(+ &schema,+ &a,+ &ScalarValue::from(true),+ Operator::NotEq,+ &expected,+ )+ .unwrap();let expected = [Some(true), None, Some(false)].iter().collect();- apply_logic_op_scalar_arr(&schema, false, &a, Operator::NotEq, &expected)- .unwrap();- apply_logic_op_arr_scalar(&schema, &a, false, Operator::NotEq, &expected)- .unwrap();+ apply_logic_op_scalar_arr(+ &schema,+ &ScalarValue::from(false),+ &a,+ Operator::NotEq,+ &expected,+ )+ .unwrap();+ apply_logic_op_arr_scalar(+ &schema,+ &a,+ &ScalarValue::from(false),+ Operator::NotEq,+ &expected,+ )+ .unwrap();}#[test]@@ -1698,23 +1920,51 @@ mod tests {].iter().collect();- apply_logic_op(schema, a, b, Operator::Lt, expected).unwrap();+ apply_logic_op(&schema, &a, &b, Operator::Lt, expected).unwrap();}#[test]fn lt_op_bool_scalar() {let (schema, a) = scalar_bool_test_array();let expected = [Some(false), None, Some(false)].iter().collect();- apply_logic_op_scalar_arr(&schema, true, &a, Operator::Lt, &expected).unwrap();+ apply_logic_op_scalar_arr(+ &schema,+ &ScalarValue::from(true),+ &a,+ Operator::Lt,+ &expected,+ )+ .unwrap();let expected = [Some(false), None, Some(true)].iter().collect();- apply_logic_op_arr_scalar(&schema, &a, true, Operator::Lt, &expected).unwrap();+ apply_logic_op_arr_scalar(+ &schema,+ &a,+ &ScalarValue::from(true),+ Operator::Lt,+ &expected,+ )+ .unwrap();let expected = [Some(true), None, Some(false)].iter().collect();- apply_logic_op_scalar_arr(&schema, false, &a, Operator::Lt, &expected).unwrap();+ apply_logic_op_scalar_arr(+ &schema,+ &ScalarValue::from(false),+ &a,+ Operator::Lt,+ &expected,+ )+ .unwrap();let expected = [Some(false), None, Some(false)].iter().collect();- apply_logic_op_arr_scalar(&schema, &a, false, Operator::Lt, &expected).unwrap();+ apply_logic_op_arr_scalar(+ &schema,+ &a,+ &ScalarValue::from(false),+ Operator::Lt,+ &expected,+ )+ .unwrap();}#[test]@@ -1733,23 +1983,51 @@ mod tests {].iter().collect();- apply_logic_op(schema, a, b, Operator::LtEq, expected).unwrap();+ apply_logic_op(&schema, &a, &b, Operator::LtEq, expected).unwrap();}#[test]fn lt_eq_op_bool_scalar() {let (schema, a) = scalar_bool_test_array();let expected = [Some(true), None, Some(false)].iter().collect();- apply_logic_op_scalar_arr(&schema, true, &a, Operator::LtEq, &expected).unwrap();+ apply_logic_op_scalar_arr(+ &schema,+ &ScalarValue::from(true),+ &a,+ Operator::LtEq,+ &expected,+ )+ .unwrap();let expected = [Some(true), None, Some(true)].iter().collect();- apply_logic_op_arr_scalar(&schema, &a, true, Operator::LtEq, &expected).unwrap();+ apply_logic_op_arr_scalar(+ &schema,+ &a,+ &ScalarValue::from(true),+ Operator::LtEq,+ &expected,+ )+ .unwrap();let expected = [Some(true), None, Some(true)].iter().collect();- apply_logic_op_scalar_arr(&schema, false, &a, Operator::LtEq, &expected).unwrap();+ apply_logic_op_scalar_arr(+ &schema,+ &ScalarValue::from(false),+ &a,+ Operator::LtEq,+ &expected,+ )+ .unwrap();let expected = [Some(false), None, Some(true)].iter().collect();- apply_logic_op_arr_scalar(&schema, &a, false, Operator::LtEq, &expected).unwrap();+ apply_logic_op_arr_scalar(+ &schema,+ &a,+ &ScalarValue::from(false),+ Operator::LtEq,+ &expected,+ )+ .unwrap();}#[test]@@ -1768,23 +2046,51 @@ mod tests {].iter().collect();- apply_logic_op(schema, a, b, Operator::Gt, expected).unwrap();+ apply_logic_op(&schema, &a, &b, Operator::Gt, expected).unwrap();}#[test]fn gt_op_bool_scalar() {let (schema, a) = scalar_bool_test_array();let expected = [Some(false), None, Some(true)].iter().collect();- apply_logic_op_scalar_arr(&schema, true, &a, Operator::Gt, &expected).unwrap();+ apply_logic_op_scalar_arr(+ &schema,+ &ScalarValue::from(true),+ &a,+ Operator::Gt,+ &expected,+ )+ .unwrap();let expected = [Some(false), None, Some(false)].iter().collect();- apply_logic_op_arr_scalar(&schema, &a, true, Operator::Gt, &expected).unwrap();+ apply_logic_op_arr_scalar(+ &schema,+ &a,+ &ScalarValue::from(true),+ Operator::Gt,+ &expected,+ )+ .unwrap();let expected = [Some(false), None, Some(false)].iter().collect();- apply_logic_op_scalar_arr(&schema, false, &a, Operator::Gt, &expected).unwrap();+ apply_logic_op_scalar_arr(+ &schema,+ &ScalarValue::from(false),+ &a,+ Operator::Gt,+ &expected,+ )+ .unwrap();let expected = [Some(true), None, Some(false)].iter().collect();- apply_logic_op_arr_scalar(&schema, &a, false, Operator::Gt, &expected).unwrap();+ apply_logic_op_arr_scalar(+ &schema,+ &a,+ &ScalarValue::from(false),+ Operator::Gt,+ &expected,+ )+ .unwrap();}#[test]@@ -1803,23 +2109,51 @@ mod tests {].iter().collect();- apply_logic_op(schema, a, b, Operator::GtEq, expected).unwrap();+ apply_logic_op(&schema, &a, &b, Operator::GtEq, expected).unwrap();}#[test]fn gt_eq_op_bool_scalar() {let (schema, a) = scalar_bool_test_array();let expected = [Some(true), None, Some(true)].iter().collect();- apply_logic_op_scalar_arr(&schema, true, &a, Operator::GtEq, &expected).unwrap();+ apply_logic_op_scalar_arr(+ &schema,+ &ScalarValue::from(true),+ &a,+ Operator::GtEq,+ &expected,+ )+ .unwrap();let expected = [Some(true), None, Some(false)].iter().collect();- apply_logic_op_arr_scalar(&schema, &a, true, Operator::GtEq, &expected).unwrap();+ apply_logic_op_arr_scalar(+ &schema,+ &a,+ &ScalarValue::from(true),+ Operator::GtEq,+ &expected,+ )+ .unwrap();let expected = [Some(false), None, Some(true)].iter().collect();- apply_logic_op_scalar_arr(&schema, false, &a, Operator::GtEq, &expected).unwrap();+ apply_logic_op_scalar_arr(+ &schema,+ &ScalarValue::from(false),+ &a,+ Operator::GtEq,+ &expected,+ )+ .unwrap();let expected = [Some(true), None, Some(true)].iter().collect();- apply_logic_op_arr_scalar(&schema, &a, false, Operator::GtEq, &expected).unwrap();+ apply_logic_op_arr_scalar(+ &schema,+ &a,+ &ScalarValue::from(false),+ Operator::GtEq,+ &expected,+ )+ .unwrap();}#[test]@@ -1838,7 +2172,7 @@ mod tests {].iter().collect();- apply_logic_op(schema, a, b, Operator::IsDistinctFrom, expected).unwrap();+ apply_logic_op(&schema, &a, &b, Operator::IsDistinctFrom, expected).unwrap();}#[test]@@ -1857,22 +2191,7 @@ mod tests {].iter().collect();- apply_logic_op(schema, a, b, Operator::IsNotDistinctFrom, expected).unwrap();- }-- #[test]- fn test_coersion_error() -> Result<()> {- let expr =- common_binary_type(&DataType::Float32, &Operator::Plus, &DataType::Utf8);-- if let Err(DataFusionError::Plan(e)) = expr {- assert_eq!(e, "'Float32 + Utf8' can't be evaluated because there isn't a common type to coerce the types to");- Ok(())- } else {- Err(DataFusionError::Internal(- "Coercion should have returned an DataFusionError::Internal".to_string(),- ))- }+ apply_logic_op(&schema, &a, &b, Operator::IsNotDistinctFrom, expected).unwrap();}#[test]@@ -1893,7 +2212,7 @@ mod tests {let expr = (0..tree_depth).into_iter().map(|_| col("a", schema.as_ref()).unwrap())- .reduce(|l, r| binary_simple(l, Operator::Plus, r))+ .reduce(|l, r| binary_simple(l, Operator::Plus, r, &schema)).unwrap();let result = expr@@ -1907,4 +2226,348 @@ mod tests {.collect();assert_eq!(result.as_ref(), &expected);}++ fn create_decimal_array(+ array: &[Option<i128>],+ precision: usize,+ scale: usize,+ ) -> Result<DecimalArray> {+ let mut decimal_builder = DecimalBuilder::new(array.len(), precision, scale);+ for value in array {+ match value {+ None => {+ decimal_builder.append_null()?;+ }+ Some(v) => {+ decimal_builder.append_value(*v)?;+ }+ }+ }+ Ok(decimal_builder.finish())+ }++ #[test]+ fn comparison_decimal_op_test() -> Result<()> {+ let value_i128: i128 = 123;+ let decimal_array = create_decimal_array(+ &[+ Some(value_i128),+ None,+ Some(value_i128 - 1),+ Some(value_i128 + 1),+ ],+ 25,+ 3,+ )?;+ // eq: array = i128+ let result = eq_decimal_scalar(&decimal_array, value_i128)?;+ assert_eq!(+ BooleanArray::from(vec![Some(true), None, Some(false), Some(false)]),+ result+ );+ // neq: array != i128+ let result = neq_decimal_scalar(&decimal_array, value_i128)?;+ assert_eq!(+ BooleanArray::from(vec![Some(false), None, Some(true), Some(true)]),+ result+ );+ // lt: array < i128+ let result = lt_decimal_scalar(&decimal_array, value_i128)?;+ assert_eq!(+ BooleanArray::from(vec![Some(false), None, Some(true), Some(false)]),+ result+ );+ // lt_eq: array <= i128+ let result = lt_eq_decimal_scalar(&decimal_array, value_i128)?;+ assert_eq!(+ BooleanArray::from(vec![Some(true), None, Some(true), Some(false)]),+ result+ );+ // gt: array > i128+ let result = gt_decimal_scalar(&decimal_array, value_i128)?;+ assert_eq!(+ BooleanArray::from(vec![Some(false), None, Some(false), Some(true)]),+ result+ );+ // gt_eq: array >= i128+ let result = gt_eq_decimal_scalar(&decimal_array, value_i128)?;+ assert_eq!(+ BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]),+ result+ );++ let left_decimal_array = decimal_array;+ let right_decimal_array = create_decimal_array(+ &[+ Some(value_i128 - 1),+ Some(value_i128),+ Some(value_i128 + 1),+ Some(value_i128 + 1),+ ],+ 25,+ 3,+ )?;+ // eq: left == right+ let result = eq_decimal(&left_decimal_array, &right_decimal_array)?;+ assert_eq!(+ BooleanArray::from(vec![Some(false), None, Some(false), Some(true)]),+ result+ );+ // neq: left != right+ let result = neq_decimal(&left_decimal_array, &right_decimal_array)?;+ assert_eq!(+ BooleanArray::from(vec![Some(true), None, Some(true), Some(false)]),+ result+ );+ // lt: left < right+ let result = lt_decimal(&left_decimal_array, &right_decimal_array)?;+ assert_eq!(+ BooleanArray::from(vec![Some(false), None, Some(true), Some(false)]),+ result+ );+ // lt_eq: left <= right+ let result = lt_eq_decimal(&left_decimal_array, &right_decimal_array)?;+ assert_eq!(+ BooleanArray::from(vec![Some(false), None, Some(true), Some(true)]),+ result+ );+ // gt: left > right+ let result = gt_decimal(&left_decimal_array, &right_decimal_array)?;+ assert_eq!(+ BooleanArray::from(vec![Some(true), None, Some(false), Some(false)]),+ result+ );+ // gt_eq: left >= right+ let result = gt_eq_decimal(&left_decimal_array, &right_decimal_array)?;+ assert_eq!(+ BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]),+ result+ );+ // is_distinct: left distinct right+ let result = is_distinct_from_decimal(&left_decimal_array, &right_decimal_array)?;+ assert_eq!(+ BooleanArray::from(vec![Some(true), Some(true), Some(true), Some(false)]),+ result+ );+ // is_distinct: left distinct right+ let result =+ is_not_distinct_from_decimal(&left_decimal_array, &right_decimal_array)?;+ assert_eq!(+ BooleanArray::from(vec![Some(false), Some(false), Some(false), Some(true)]),+ result+ );+ Ok(())+ }++ #[test]+ fn comparison_decimal_expr_test() -> Result<()> {+ let decimal_scalar = ScalarValue::Decimal128(Some(123_456), 10, 3);+ let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int64, true)]));+ // scalar == array+ apply_logic_op_scalar_arr(+ &schema,+ &decimal_scalar,+ &(Arc::new(Int64Array::from(vec![Some(124), None])) as ArrayRef),+ Operator::Eq,+ &BooleanArray::from(vec![Some(false), None]),+ )+ .unwrap();++ // array != scalar+ apply_logic_op_arr_scalar(+ &schema,+ &(Arc::new(Int64Array::from(vec![Some(123), None, Some(1)])) as ArrayRef),+ &decimal_scalar,+ Operator::NotEq,+ &BooleanArray::from(vec![Some(true), None, Some(true)]),+ )+ .unwrap();++ // array < scalar+ apply_logic_op_arr_scalar(+ &schema,+ &(Arc::new(Int64Array::from(vec![Some(123), None, Some(124)])) as ArrayRef),+ &decimal_scalar,+ Operator::Lt,+ &BooleanArray::from(vec![Some(true), None, Some(false)]),+ )+ .unwrap();++ // array > scalar+ apply_logic_op_arr_scalar(+ &schema,+ &(Arc::new(Int64Array::from(vec![Some(123), None, Some(124)])) as ArrayRef),+ &decimal_scalar,+ Operator::Gt,+ &BooleanArray::from(vec![Some(false), None, Some(true)]),+ )+ .unwrap();++ let schema =+ Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, true)]));+ // array == scalar+ apply_logic_op_arr_scalar(+ &schema,+ &(Arc::new(Float64Array::from(vec![Some(123.456), None, Some(123.457)]))+ as ArrayRef),+ &decimal_scalar,+ Operator::Eq,+ &BooleanArray::from(vec![Some(true), None, Some(false)]),+ )+ .unwrap();++ // array <= scalar+ apply_logic_op_arr_scalar(+ &schema,+ &(Arc::new(Float64Array::from(vec![+ Some(123.456),+ None,+ Some(123.457),+ Some(123.45),+ ])) as ArrayRef),+ &decimal_scalar,+ Operator::LtEq,+ &BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]),+ )+ .unwrap();+ // array >= scalar+ apply_logic_op_arr_scalar(+ &schema,+ &(Arc::new(Float64Array::from(vec![+ Some(123.456),+ None,+ Some(123.457),+ Some(123.45),+ ])) as ArrayRef),+ &decimal_scalar,+ Operator::GtEq,+ &BooleanArray::from(vec![Some(true), None, Some(true), Some(false)]),+ )+ .unwrap();++ // compare decimal array with other array type+ let schema = Arc::new(Schema::new(vec![+ Field::new("a", DataType::Int64, true),+ Field::new("b", DataType::Decimal(10, 0), true),+ ]));++ let value: i64 = 123;++ let decimal_array = Arc::new(create_decimal_array(+ &[+ Some(value as i128),+ None,+ Some((value - 1) as i128),+ Some((value + 1) as i128),+ ],+ 10,+ 0,+ )?) as ArrayRef;++ let int64_array = Arc::new(Int64Array::from(vec![+ Some(value),+ Some(value - 1),+ Some(value),+ Some(value + 1),+ ])) as ArrayRef;++ // eq: int64array == decimal array+ apply_logic_op(+ &schema,+ &int64_array,+ &decimal_array,+ Operator::Eq,+ BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]),+ )+ .unwrap();+ // neq: int64array != decimal array+ apply_logic_op(+ &schema,+ &int64_array,+ &decimal_array,+ Operator::NotEq,+ BooleanArray::from(vec![Some(false), None, Some(true), Some(false)]),+ )+ .unwrap();++ let schema = Arc::new(Schema::new(vec![+ Field::new("a", DataType::Float64, true),+ Field::new("b", DataType::Decimal(10, 2), true),+ ]));++ let value: i128 = 123;+ let decimal_array = Arc::new(create_decimal_array(+ &[+ Some(value as i128), // 1.23+ None,+ Some((value - 1) as i128), // 1.22+ Some((value + 1) as i128), // 1.24+ ],+ 10,+ 2,+ )?) as ArrayRef;+ let float64_array = Arc::new(Float64Array::from(vec![+ Some(1.23),+ Some(1.22),+ Some(1.23),+ Some(1.24),+ ])) as ArrayRef;+ // lt: float64array < decimal array+ apply_logic_op(+ &schema,+ &float64_array,+ &decimal_array,+ Operator::Lt,+ BooleanArray::from(vec![Some(false), None, Some(false), Some(false)]),+ )+ .unwrap();+ // lt_eq: float64array <= decimal array+ apply_logic_op(+ &schema,+ &float64_array,+ &decimal_array,+ Operator::LtEq,+ BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]),+ )+ .unwrap();+ // gt: float64array > decimal array+ apply_logic_op(+ &schema,+ &float64_array,+ &decimal_array,+ Operator::Gt,+ BooleanArray::from(vec![Some(false), None, Some(true), Some(false)]),+ )+ .unwrap();+ apply_logic_op(+ &schema,+ &float64_array,+ &decimal_array,+ Operator::GtEq,+ BooleanArray::from(vec![Some(true), None, Some(true), Some(true)]),+ )+ .unwrap();+ // is distinct: float64array is distinct decimal array+ // TODO: now we do not refactor the `is distinct or is not distinct` rule of coercion.+ // the decimal array will be casted to float64array+ apply_logic_op(+ &schema,+ &float64_array,+ &decimal_array,+ Operator::IsDistinctFrom,+ BooleanArray::from(vec![Some(false), Some(true), Some(true), Some(false)]),+ )+ .unwrap();+ // is not distinct+ apply_logic_op(+ &schema,+ &float64_array,+ &decimal_array,+ Operator::IsNotDistinctFrom,+ BooleanArray::from(vec![Some(true), Some(false), Some(false), Some(true)]),+ )+ .unwrap();++ Ok(())+ }}diff --git a/datafusion/src/physical_plan/expressions/coercion.rs b/datafusion/src/physical_plan/expressions/coercion.rsindex a449a8d129..a303e8b3ef 100644--- a/datafusion/src/physical_plan/expressions/coercion.rs+++ b/datafusion/src/physical_plan/expressions/coercion.rs@@ -30,6 +30,7 @@ pub fn is_signed_numeric(dt: &DataType) -> bool {| DataType::Float16| DataType::Float32| DataType::Float64+ | DataType::Decimal(_, _))}@@ -190,20 +191,6 @@ pub fn eq_coercion(lhs_type: &DataType, rhs_type: &DataType) -> Option<DataType>.or_else(|| temporal_coercion(lhs_type, rhs_type))}-// coercion rules that assume an ordered set, such as "less than".-// These are the union of all numerical coercion rules and all string coercion rules-pub fn order_coercion(lhs_type: &DataType, rhs_type: &DataType) -> Option<DataType> {- if lhs_type == rhs_type {- // same type => all good- return Some(lhs_type.clone());- }-- numerical_coercion(lhs_type, rhs_type)- .or_else(|| string_coercion(lhs_type, rhs_type))- .or_else(|| dictionary_coercion(lhs_type, rhs_type))- .or_else(|| temporal_coercion(lhs_type, rhs_type))-}-#[cfg(test)]mod tests {use super::*;diff --git a/datafusion/src/physical_plan/expressions/mod.rs b/datafusion/src/physical_plan/expressions/mod.rsindex afc0486ebf..2200ee03d5 100644--- a/datafusion/src/physical_plan/expressions/mod.rs+++ b/datafusion/src/physical_plan/expressions/mod.rs@@ -32,7 +32,7 @@ mod average;mod binary;mod case;mod cast;-mod coercion;+pub(crate) mod coercion;mod column;mod count;mod cume_dist;diff --git a/datafusion/src/physical_plan/expressions/nullif.rs b/datafusion/src/physical_plan/expressions/nullif.rsindex 1d91599848..1671b4411c 100644--- a/datafusion/src/physical_plan/expressions/nullif.rs+++ b/datafusion/src/physical_plan/expressions/nullif.rs@@ -19,6 +19,7 @@ use std::sync::Arc;use super::ColumnarValue;use crate::error::{DataFusionError, Result};+use crate::physical_plan::expressions::binary::{eq_decimal, eq_decimal_scalar};use crate::scalar::ScalarValue;use arrow::array::Array;use arrow::array::*;diff --git a/datafusion/src/scalar.rs b/datafusion/src/scalar.rsindex e7c7db5217..586a69b971 100644--- a/datafusion/src/scalar.rs+++ b/datafusion/src/scalar.rs@@ -1663,6 +1663,22 @@ impl TryFrom<ScalarValue> for i64 {}}+// special implementation for i128 because of Decimal128+impl TryFrom<ScalarValue> for i128 {+ type Error = DataFusionError;++ fn try_from(value: ScalarValue) -> Result<Self> {+ match value {+ ScalarValue::Decimal128(Some(inner_value), _, _) => Ok(inner_value),+ _ => Err(DataFusionError::Internal(format!(+ "Cannot convert {:?} to {}",+ value,+ std::any::type_name::<Self>()+ ))),+ }+ }+}+impl_try_from!(UInt8, u8);impl_try_from!(UInt16, u16);impl_try_from!(UInt32, u32);@@ -1919,6 +1935,8 @@ mod tests {fn scalar_decimal_test() {let decimal_value = ScalarValue::Decimal128(Some(123), 10, 1);assert_eq!(DataType::Decimal(10, 1), decimal_value.get_datatype());+ let try_into_value: i128 = decimal_value.clone().try_into().unwrap();+ assert_eq!(123_i128, try_into_value);assert!(!decimal_value.is_null());let neg_decimal_value = decimal_value.arithmetic_negate();match neg_decimal_value {