Apache DataFusion SQL Query Engine
Move logical expression type-coercion code from `physical-expr` crate to `expr` crate (#2257)
Andy Grove5f0b61b0db98
diff --git a/ballista/rust/core/src/serde/physical_plan/from_proto.rs b/ballista/rust/core/src/serde/physical_plan/from_proto.rsindex 7e759bd606..6cd2dc18c8 100644--- a/ballista/rust/core/src/serde/physical_plan/from_proto.rs+++ b/ballista/rust/core/src/serde/physical_plan/from_proto.rs@@ -36,7 +36,7 @@ use datafusion::logical_plan::FunctionRegistry;use datafusion::physical_plan::file_format::FileScanConfig;-use datafusion::physical_plan::window_functions::WindowFunction;+use datafusion::logical_expr::window_function::WindowFunction;use datafusion::physical_plan::{expressions::{diff --git a/ballista/rust/core/src/serde/physical_plan/mod.rs b/ballista/rust/core/src/serde/physical_plan/mod.rsindex 955725957d..ed268820f3 100644--- a/ballista/rust/core/src/serde/physical_plan/mod.rs+++ b/ballista/rust/core/src/serde/physical_plan/mod.rs@@ -1064,10 +1064,11 @@ mod roundtrip_tests {use datafusion::arrow::array::ArrayRef;use datafusion::execution::context::ExecutionProps;+ use datafusion::logical_expr::{BuiltinScalarFunction, Volatility};use datafusion::logical_plan::create_udf;use datafusion::physical_plan::functions;use datafusion::physical_plan::functions::{- make_scalar_function, BuiltinScalarFunction, ScalarFunctionExpr, Volatility,+ make_scalar_function, ScalarFunctionExpr,};use datafusion::physical_plan::projection::ProjectionExec;use datafusion::{diff --git a/ballista/rust/core/src/serde/physical_plan/to_proto.rs b/ballista/rust/core/src/serde/physical_plan/to_proto.rsindex d022766d85..1b96a8556c 100644--- a/ballista/rust/core/src/serde/physical_plan/to_proto.rs+++ b/ballista/rust/core/src/serde/physical_plan/to_proto.rs@@ -45,7 +45,8 @@ use datafusion::physical_plan::{AggregateExpr, PhysicalExpr};use crate::serde::{protobuf, BallistaError};-use datafusion::physical_plan::functions::{BuiltinScalarFunction, ScalarFunctionExpr};+use datafusion::logical_expr::BuiltinScalarFunction;+use datafusion::physical_plan::functions::ScalarFunctionExpr;impl TryInto<protobuf::PhysicalExprNode> for Arc<dyn AggregateExpr> {type Error = BallistaError;diff --git a/datafusion-examples/examples/simple_udaf.rs b/datafusion-examples/examples/simple_udaf.rsindex f3829c9ffa..925835bc18 100644--- a/datafusion-examples/examples/simple_udaf.rs+++ b/datafusion-examples/examples/simple_udaf.rs@@ -23,9 +23,8 @@ use datafusion::arrow::{};use datafusion::from_slice::FromSlice;-use datafusion::physical_plan::functions::Volatility;use datafusion::{error::Result, logical_plan::create_udaf, physical_plan::Accumulator};-use datafusion::{prelude::*, scalar::ScalarValue};+use datafusion::{logical_expr::Volatility, prelude::*, scalar::ScalarValue};use std::sync::Arc;// create local session context with an in-memory tablediff --git a/datafusion-examples/examples/simple_udf.rs b/datafusion-examples/examples/simple_udf.rsindex 321adcf1fc..f6244f215f 100644--- a/datafusion-examples/examples/simple_udf.rs+++ b/datafusion-examples/examples/simple_udf.rs@@ -21,7 +21,7 @@ use datafusion::{datatypes::DataType,record_batch::RecordBatch,},- physical_plan::functions::Volatility,+ logical_expr::Volatility,};use datafusion::from_slice::FromSlice;diff --git a/datafusion/core/src/dataframe.rs b/datafusion/core/src/dataframe.rsindex 9414f2887d..eac9ae29ad 100644--- a/datafusion/core/src/dataframe.rs+++ b/datafusion/core/src/dataframe.rs@@ -648,12 +648,14 @@ mod tests {use super::*;use crate::execution::options::CsvReadOptions;- use crate::physical_plan::{window_functions, ColumnarValue};+ use crate::physical_plan::ColumnarValue;use crate::{assert_batches_sorted_eq, execution::context::SessionContext};use crate::{logical_plan::*, test_util};use arrow::datatypes::DataType;- use datafusion_expr::ScalarFunctionImplementation;use datafusion_expr::Volatility;+ use datafusion_expr::{+ BuiltInWindowFunction, ScalarFunctionImplementation, WindowFunction,+ };#[tokio::test]async fn select_columns() -> Result<()> {@@ -693,9 +695,7 @@ mod tests {// build plan using Table APIlet t = test_table().await?;let first_row = Expr::WindowFunction {- fun: window_functions::WindowFunction::BuiltInWindowFunction(- window_functions::BuiltInWindowFunction::FirstValue,- ),+ fun: WindowFunction::BuiltInWindowFunction(BuiltInWindowFunction::FirstValue),args: vec![col("aggregate_test_100.c1")],partition_by: vec![col("aggregate_test_100.c2")],order_by: vec![],diff --git a/datafusion/core/src/datasource/listing/helpers.rs b/datafusion/core/src/datasource/listing/helpers.rsindex a6fd125437..362a8545be 100644--- a/datafusion/core/src/datasource/listing/helpers.rs+++ b/datafusion/core/src/datasource/listing/helpers.rs@@ -41,12 +41,12 @@ use crate::{error::Result,execution::context::SessionContext,logical_plan::{self, Expr, ExprVisitable, ExpressionVisitor, Recursion},- physical_plan::functions::Volatility,scalar::ScalarValue,};use super::{PartitionedFile, PartitionedFileStream};use datafusion_data_access::{object_store::ObjectStore, FileMeta, SizedFile};+use datafusion_expr::Volatility;const FILE_SIZE_COLUMN_NAME: &str = "_df_part_file_size_";const FILE_PATH_COLUMN_NAME: &str = "_df_part_file_path_";diff --git a/datafusion/core/src/execution/context.rs b/datafusion/core/src/execution/context.rsindex 4bb77fb93c..f7262def03 100644--- a/datafusion/core/src/execution/context.rs+++ b/datafusion/core/src/execution/context.rs@@ -1603,7 +1603,7 @@ mod tests {use crate::execution::context::QueryPlanner;use crate::from_slice::FromSlice;use crate::logical_plan::{binary_expr, lit, Operator};- use crate::physical_plan::functions::{make_scalar_function, Volatility};+ use crate::physical_plan::functions::make_scalar_function;use crate::test;use crate::variable::VarType;use crate::{@@ -1622,6 +1622,7 @@ mod tests {use arrow::datatypes::*;use arrow::record_batch::RecordBatch;use async_trait::async_trait;+ use datafusion_expr::Volatility;use std::fs::File;use std::sync::Weak;use std::thread::{self, JoinHandle};diff --git a/datafusion/core/src/lib.rs b/datafusion/core/src/lib.rsindex a952b69ae7..94835c3d52 100644--- a/datafusion/core/src/lib.rs+++ b/datafusion/core/src/lib.rs@@ -225,8 +225,9 @@ pub mod variable;pub use arrow;pub use parquet;-// re-export object store dependencies+// re-export DataFusion cratespub use datafusion_data_access;+pub use datafusion_expr as logical_expr;#[cfg(feature = "row")]pub mod row;diff --git a/datafusion/core/src/logical_plan/expr_schema.rs b/datafusion/core/src/logical_plan/expr_schema.rsindex e6801f7b7f..e0cef29795 100644--- a/datafusion/core/src/logical_plan/expr_schema.rs+++ b/datafusion/core/src/logical_plan/expr_schema.rs@@ -16,12 +16,11 @@// under the License.use super::Expr;-use crate::physical_plan::{- aggregates, expressions::binary_operator_data_type, functions, window_functions,-};+use crate::logical_expr::{aggregate_function, function, window_function};use arrow::compute::can_cast_types;use arrow::datatypes::DataType;use datafusion_common::{DFField, DFSchema, DataFusionError, ExprSchema, Result};+use datafusion_expr::binary_rule::binary_operator_data_type;use datafusion_expr::field_util::get_indexed_field;/// trait to allow expr to typable with respect to a schema@@ -76,21 +75,21 @@ impl ExprSchemable for Expr {.iter().map(|e| e.get_type(schema)).collect::<Result<Vec<_>>>()?;- functions::return_type(fun, &data_types)+ function::return_type(fun, &data_types)}Expr::WindowFunction { fun, args, .. } => {let data_types = args.iter().map(|e| e.get_type(schema)).collect::<Result<Vec<_>>>()?;- window_functions::return_type(fun, &data_types)+ window_function::return_type(fun, &data_types)}Expr::AggregateFunction { fun, args, .. } => {let data_types = args.iter().map(|e| e.get_type(schema)).collect::<Result<Vec<_>>>()?;- aggregates::return_type(fun, &data_types)+ aggregate_function::return_type(fun, &data_types)}Expr::AggregateUDF { fun, args, .. } => {let data_types = argsdiff --git a/datafusion/core/src/optimizer/simplify_expressions.rs b/datafusion/core/src/optimizer/simplify_expressions.rsindex 8e1e7d319e..394ab68bd0 100644--- a/datafusion/core/src/optimizer/simplify_expressions.rs+++ b/datafusion/core/src/optimizer/simplify_expressions.rs@@ -26,13 +26,13 @@ use crate::logical_plan::{};use crate::optimizer::optimizer::OptimizerRule;use crate::optimizer::utils;-use crate::physical_plan::functions::Volatility;use crate::physical_plan::planner::create_physical_expr;use crate::scalar::ScalarValue;use crate::{error::Result, logical_plan::Operator};use arrow::array::new_null_array;use arrow::datatypes::{DataType, Field, Schema};use arrow::record_batch::RecordBatch;+use datafusion_expr::Volatility;/// Provides simplification information based on schema and propertiespub(crate) struct SimplifyContext<'a, 'b> {@@ -735,6 +735,7 @@ mod tests {use arrow::array::{ArrayRef, Int32Array};use chrono::{DateTime, TimeZone, Utc};+ use datafusion_expr::BuiltinScalarFunction;use super::*;use crate::assert_contains;@@ -742,7 +743,7 @@ mod tests {and, binary_expr, call_fn, col, create_udf, lit, lit_timestamp_nano, DFField,Expr, LogicalPlanBuilder,};- use crate::physical_plan::functions::{make_scalar_function, BuiltinScalarFunction};+ use crate::physical_plan::functions::make_scalar_function;use crate::physical_plan::udf::ScalarUDF;#[test]diff --git a/datafusion/core/src/physical_plan/aggregate_rule.rs b/datafusion/core/src/physical_plan/aggregate_rule.rsindex 3e917ccb15..71775eba96 100644--- a/datafusion/core/src/physical_plan/aggregate_rule.rs+++ b/datafusion/core/src/physical_plan/aggregate_rule.rs@@ -17,101 +17,4 @@//! Support the coercion rule for aggregate function.-pub use datafusion_physical_expr::coercion_rule::aggregate_rule::{- coerce_exprs, coerce_types,-};--#[cfg(test)]-mod tests {- use super::*;- use crate::physical_plan::aggregates;- use arrow::datatypes::DataType;- use datafusion_expr::AggregateFunction;-- #[test]- fn test_aggregate_coerce_types() {- // test input args with error number input types- let fun = AggregateFunction::Min;- let input_types = vec![DataType::Int64, DataType::Int32];- let signature = aggregates::signature(&fun);- let result = coerce_types(&fun, &input_types, &signature);- assert_eq!("Error during planning: The function Min expects 1 arguments, but 2 were provided", result.unwrap_err().to_string());-- // test input args is invalid data type for sum or avg- let fun = AggregateFunction::Sum;- let input_types = vec![DataType::Utf8];- let signature = aggregates::signature(&fun);- let result = coerce_types(&fun, &input_types, &signature);- assert_eq!(- "Error during planning: The function Sum does not support inputs of type Utf8.",- result.unwrap_err().to_string()- );- let fun = AggregateFunction::Avg;- let signature = aggregates::signature(&fun);- let result = coerce_types(&fun, &input_types, &signature);- assert_eq!(- "Error during planning: The function Avg does not support inputs of type Utf8.",- result.unwrap_err().to_string()- );-- // test count, array_agg, approx_distinct, min, max.- // the coerced types is same with input types- let funs = vec![- AggregateFunction::Count,- AggregateFunction::ArrayAgg,- AggregateFunction::ApproxDistinct,- AggregateFunction::Min,- AggregateFunction::Max,- ];- let input_types = vec![- vec![DataType::Int32],- vec![DataType::Decimal(10, 2)],- vec![DataType::Utf8],- ];- for fun in funs {- for input_type in &input_types {- let signature = aggregates::signature(&fun);- let result = coerce_types(&fun, input_type, &signature);- assert_eq!(*input_type, result.unwrap());- }- }- // test sum, avg- let funs = vec![AggregateFunction::Sum, AggregateFunction::Avg];- let input_types = vec![- vec![DataType::Int32],- vec![DataType::Float32],- vec![DataType::Decimal(20, 3)],- ];- for fun in funs {- for input_type in &input_types {- let signature = aggregates::signature(&fun);- let result = coerce_types(&fun, input_type, &signature);- assert_eq!(*input_type, result.unwrap());- }- }-- // ApproxPercentileCont input types- let input_types = vec![- vec![DataType::Int8, DataType::Float64],- vec![DataType::Int16, DataType::Float64],- vec![DataType::Int32, DataType::Float64],- vec![DataType::Int64, DataType::Float64],- vec![DataType::UInt8, DataType::Float64],- vec![DataType::UInt16, DataType::Float64],- vec![DataType::UInt32, DataType::Float64],- vec![DataType::UInt64, DataType::Float64],- vec![DataType::Float32, DataType::Float64],- vec![DataType::Float64, DataType::Float64],- ];- for input_type in &input_types {- let signature =- aggregates::signature(&AggregateFunction::ApproxPercentileCont);- let result = coerce_types(- &AggregateFunction::ApproxPercentileCont,- input_type,- &signature,- );- assert_eq!(*input_type, result.unwrap());- }- }-}+pub use datafusion_physical_expr::coercion_rule::aggregate_rule::coerce_exprs;diff --git a/datafusion/core/src/physical_plan/aggregates.rs b/datafusion/core/src/physical_plan/aggregates.rsindex cfa3168c67..f04c81c2ab 100644--- a/datafusion/core/src/physical_plan/aggregates.rs+++ b/datafusion/core/src/physical_plan/aggregates.rs@@ -26,66 +26,16 @@//! * Signature: see `Signature`//! * Return type: a function `(arg_types) -> return_type`. E.g. for min, ([f32]) -> f32, ([f64]) -> f64.-use super::aggregate_rule::{coerce_exprs, coerce_types};-use super::{- functions::{Signature, TypeSignature, Volatility},- AggregateExpr, PhysicalExpr,-};+use super::aggregate_rule::coerce_exprs;+use super::{AggregateExpr, PhysicalExpr};use crate::error::{DataFusionError, Result};use crate::physical_plan::expressions;-use arrow::datatypes::{DataType, Field, Schema, TimeUnit};+use arrow::datatypes::Schema;+use datafusion_expr::aggregate_function;+use datafusion_expr::aggregate_function::return_type;pub use datafusion_expr::AggregateFunction;-use expressions::{- avg_return_type, correlation_return_type, covariance_return_type, stddev_return_type,- sum_return_type, variance_return_type,-};use std::sync::Arc;-/// Returns the datatype of the aggregate function.-/// This is used to get the returned data type for aggregate expr.-pub fn return_type(- fun: &AggregateFunction,- input_expr_types: &[DataType],-) -> Result<DataType> {- // Note that this function *must* return the same type that the respective physical expression returns- // or the execution panics.-- let coerced_data_types = coerce_types(fun, input_expr_types, &signature(fun))?;-- match fun {- // TODO If the datafusion is compatible with PostgreSQL, the returned data type should be INT64.- AggregateFunction::Count | AggregateFunction::ApproxDistinct => {- Ok(DataType::UInt64)- }- AggregateFunction::Max | AggregateFunction::Min => {- // For min and max agg function, the returned type is same as input type.- // The coerced_data_types is same with input_types.- Ok(coerced_data_types[0].clone())- }- AggregateFunction::Sum => sum_return_type(&coerced_data_types[0]),- AggregateFunction::Variance => variance_return_type(&coerced_data_types[0]),- AggregateFunction::VariancePop => variance_return_type(&coerced_data_types[0]),- AggregateFunction::Covariance => covariance_return_type(&coerced_data_types[0]),- AggregateFunction::CovariancePop => {- covariance_return_type(&coerced_data_types[0])- }- AggregateFunction::Correlation => correlation_return_type(&coerced_data_types[0]),- AggregateFunction::Stddev => stddev_return_type(&coerced_data_types[0]),- AggregateFunction::StddevPop => stddev_return_type(&coerced_data_types[0]),- AggregateFunction::Avg => avg_return_type(&coerced_data_types[0]),- AggregateFunction::ArrayAgg => Ok(DataType::List(Box::new(Field::new(- "item",- coerced_data_types[0].clone(),- true,- )))),- AggregateFunction::ApproxPercentileCont => Ok(coerced_data_types[0].clone()),- AggregateFunction::ApproxPercentileContWithWeight => {- Ok(coerced_data_types[0].clone())- }- AggregateFunction::ApproxMedian => Ok(coerced_data_types[0].clone()),- }-}-/// Create a physical aggregation expression./// This function errors when `input_phy_exprs`' can't be coerced to a valid argument type of the aggregation function.pub fn create_aggregate_expr(@@ -97,8 +47,12 @@ pub fn create_aggregate_expr() -> Result<Arc<dyn AggregateExpr>> {let name = name.into();// get the coerced phy exprs if some expr need to be wrapped with the try cast.- let coerced_phy_exprs =- coerce_exprs(fun, input_phy_exprs, input_schema, &signature(fun))?;+ let coerced_phy_exprs = coerce_exprs(+ fun,+ input_phy_exprs,+ input_schema,+ &aggregate_function::signature(fun),+ )?;if coerced_phy_exprs.is_empty() {return Err(DataFusionError::Plan(format!("Invalid or wrong number of arguments passed to aggregate: '{}'",@@ -300,83 +254,6 @@ pub fn create_aggregate_expr(})}-static STRINGS: &[DataType] = &[DataType::Utf8, DataType::LargeUtf8];--static NUMERICS: &[DataType] = &[- DataType::Int8,- DataType::Int16,- DataType::Int32,- DataType::Int64,- DataType::UInt8,- DataType::UInt16,- DataType::UInt32,- DataType::UInt64,- DataType::Float32,- DataType::Float64,-];--static TIMESTAMPS: &[DataType] = &[- DataType::Timestamp(TimeUnit::Second, None),- DataType::Timestamp(TimeUnit::Millisecond, None),- DataType::Timestamp(TimeUnit::Microsecond, None),- DataType::Timestamp(TimeUnit::Nanosecond, None),-];--static DATES: &[DataType] = &[DataType::Date32, DataType::Date64];--/// the signatures supported by the function `fun`.-pub(super) fn signature(fun: &AggregateFunction) -> Signature {- // note: the physical expression must accept the type returned by this function or the execution panics.- match fun {- AggregateFunction::Count- | AggregateFunction::ApproxDistinct- | AggregateFunction::ArrayAgg => Signature::any(1, Volatility::Immutable),- AggregateFunction::Min | AggregateFunction::Max => {- let valid = STRINGS- .iter()- .chain(NUMERICS.iter())- .chain(TIMESTAMPS.iter())- .chain(DATES.iter())- .cloned()- .collect::<Vec<_>>();- Signature::uniform(1, valid, Volatility::Immutable)- }- AggregateFunction::Avg- | AggregateFunction::Sum- | AggregateFunction::Variance- | AggregateFunction::VariancePop- | AggregateFunction::Stddev- | AggregateFunction::StddevPop- | AggregateFunction::ApproxMedian => {- Signature::uniform(1, NUMERICS.to_vec(), Volatility::Immutable)- }- AggregateFunction::Covariance | AggregateFunction::CovariancePop => {- Signature::uniform(2, NUMERICS.to_vec(), Volatility::Immutable)- }- AggregateFunction::Correlation => {- Signature::uniform(2, NUMERICS.to_vec(), Volatility::Immutable)- }- AggregateFunction::ApproxPercentileCont => Signature::one_of(- // Accept any numeric value paired with a float64 percentile- NUMERICS- .iter()- .map(|t| TypeSignature::Exact(vec![t.clone(), DataType::Float64]))- .collect(),- Volatility::Immutable,- ),- AggregateFunction::ApproxPercentileContWithWeight => Signature::one_of(- // Accept any numeric value paired with a float64 percentile- NUMERICS- .iter()- .map(|t| {- TypeSignature::Exact(vec![t.clone(), t.clone(), DataType::Float64])- })- .collect(),- Volatility::Immutable,- ),- }-}-#[cfg(test)]mod tests {use super::*;@@ -386,6 +263,8 @@ mod tests {Variance,};use crate::{error::Result, scalar::ScalarValue};+ use arrow::datatypes::{DataType, Field};+ use datafusion_expr::aggregate_function::NUMERICS;#[test]fn test_count_arragg_approx_expr() -> Result<()> {diff --git a/datafusion/core/src/physical_plan/functions.rs b/datafusion/core/src/physical_plan/functions.rsindex ae7a2bd7bb..60cb33a80f 100644--- a/datafusion/core/src/physical_plan/functions.rs+++ b/datafusion/core/src/physical_plan/functions.rs@@ -29,26 +29,22 @@//! This module also has a set of coercion rules to improve user experience: if an argument i32 is passed//! to a function that supports f64, it is coerced to f64.-use super::{- type_coercion::{coerce, data_types},- ColumnarValue, PhysicalExpr,-};+use super::{type_coercion::coerce, ColumnarValue, PhysicalExpr};use crate::execution::context::ExecutionProps;use crate::physical_plan::expressions::{- cast_column, nullif_func, DEFAULT_DATAFUSION_CAST_OPTIONS, SUPPORTED_NULLIF_TYPES,+ cast_column, nullif_func, DEFAULT_DATAFUSION_CAST_OPTIONS,};use crate::{error::{DataFusionError, Result},+ logical_expr::{function, BuiltinScalarFunction, ScalarFunctionImplementation},scalar::ScalarValue,};use arrow::{array::ArrayRef,compute::kernels::length::{bit_length, length},datatypes::TimeUnit,- datatypes::{DataType, Field, Int32Type, Int64Type, Schema},+ datatypes::{DataType, Int32Type, Int64Type, Schema},};-use datafusion_expr::ScalarFunctionImplementation;-pub use datafusion_expr::{BuiltinScalarFunction, Signature, TypeSignature, Volatility};use datafusion_physical_expr::array_expressions;use datafusion_physical_expr::conditional_expressions;use datafusion_physical_expr::datetime_expressions;@@ -56,195 +52,6 @@ use datafusion_physical_expr::math_expressions;use datafusion_physical_expr::string_expressions;use std::sync::Arc;-macro_rules! make_utf8_to_return_type {- ($FUNC:ident, $largeUtf8Type:expr, $utf8Type:expr) => {- fn $FUNC(arg_type: &DataType, name: &str) -> Result<DataType> {- Ok(match arg_type {- DataType::LargeUtf8 => $largeUtf8Type,- DataType::Utf8 => $utf8Type,- _ => {- // this error is internal as `data_types` should have captured this.- return Err(DataFusionError::Internal(format!(- "The {:?} function can only accept strings.",- name- )));- }- })- }- };-}--make_utf8_to_return_type!(utf8_to_str_type, DataType::LargeUtf8, DataType::Utf8);-make_utf8_to_return_type!(utf8_to_int_type, DataType::Int64, DataType::Int32);-make_utf8_to_return_type!(utf8_to_binary_type, DataType::Binary, DataType::Binary);--/// Returns the datatype of the scalar function-pub fn return_type(- fun: &BuiltinScalarFunction,- input_expr_types: &[DataType],-) -> Result<DataType> {- // Note that this function *must* return the same type that the respective physical expression returns- // or the execution panics.-- if input_expr_types.is_empty() && !fun.supports_zero_argument() {- return Err(DataFusionError::Internal(format!(- "Builtin scalar function {} does not support empty arguments",- fun- )));- }-- // verify that this is a valid set of data types for this function- data_types(input_expr_types, &signature(fun))?;-- // the return type of the built in function.- // Some built-in functions' return type depends on the incoming type.- match fun {- BuiltinScalarFunction::Array => Ok(DataType::FixedSizeList(- Box::new(Field::new("item", input_expr_types[0].clone(), true)),- input_expr_types.len() as i32,- )),- BuiltinScalarFunction::Ascii => Ok(DataType::Int32),- BuiltinScalarFunction::BitLength => {- utf8_to_int_type(&input_expr_types[0], "bit_length")- }- BuiltinScalarFunction::Btrim => utf8_to_str_type(&input_expr_types[0], "btrim"),- BuiltinScalarFunction::CharacterLength => {- utf8_to_int_type(&input_expr_types[0], "character_length")- }- BuiltinScalarFunction::Chr => Ok(DataType::Utf8),- BuiltinScalarFunction::Coalesce => {- // COALESCE has multiple args and they might get coerced, get a preview of this- let coerced_types = data_types(input_expr_types, &signature(fun));- coerced_types.map(|types| types[0].clone())- }- BuiltinScalarFunction::Concat => Ok(DataType::Utf8),- BuiltinScalarFunction::ConcatWithSeparator => Ok(DataType::Utf8),- BuiltinScalarFunction::DatePart => Ok(DataType::Int32),- BuiltinScalarFunction::DateTrunc => {- Ok(DataType::Timestamp(TimeUnit::Nanosecond, None))- }- BuiltinScalarFunction::InitCap => {- utf8_to_str_type(&input_expr_types[0], "initcap")- }- BuiltinScalarFunction::Left => utf8_to_str_type(&input_expr_types[0], "left"),- BuiltinScalarFunction::Lower => utf8_to_str_type(&input_expr_types[0], "lower"),- BuiltinScalarFunction::Lpad => utf8_to_str_type(&input_expr_types[0], "lpad"),- BuiltinScalarFunction::Ltrim => utf8_to_str_type(&input_expr_types[0], "ltrim"),- BuiltinScalarFunction::MD5 => utf8_to_str_type(&input_expr_types[0], "md5"),- BuiltinScalarFunction::NullIf => {- // NULLIF has two args and they might get coerced, get a preview of this- let coerced_types = data_types(input_expr_types, &signature(fun));- coerced_types.map(|typs| typs[0].clone())- }- BuiltinScalarFunction::OctetLength => {- utf8_to_int_type(&input_expr_types[0], "octet_length")- }- BuiltinScalarFunction::Random => Ok(DataType::Float64),- BuiltinScalarFunction::RegexpReplace => {- utf8_to_str_type(&input_expr_types[0], "regex_replace")- }- BuiltinScalarFunction::Repeat => utf8_to_str_type(&input_expr_types[0], "repeat"),- BuiltinScalarFunction::Replace => {- utf8_to_str_type(&input_expr_types[0], "replace")- }- BuiltinScalarFunction::Reverse => {- utf8_to_str_type(&input_expr_types[0], "reverse")- }- BuiltinScalarFunction::Right => utf8_to_str_type(&input_expr_types[0], "right"),- BuiltinScalarFunction::Rpad => utf8_to_str_type(&input_expr_types[0], "rpad"),- BuiltinScalarFunction::Rtrim => utf8_to_str_type(&input_expr_types[0], "rtrimp"),- BuiltinScalarFunction::SHA224 => {- utf8_to_binary_type(&input_expr_types[0], "sha224")- }- BuiltinScalarFunction::SHA256 => {- utf8_to_binary_type(&input_expr_types[0], "sha256")- }- BuiltinScalarFunction::SHA384 => {- utf8_to_binary_type(&input_expr_types[0], "sha384")- }- BuiltinScalarFunction::SHA512 => {- utf8_to_binary_type(&input_expr_types[0], "sha512")- }- BuiltinScalarFunction::Digest => {- utf8_to_binary_type(&input_expr_types[0], "digest")- }- BuiltinScalarFunction::SplitPart => {- utf8_to_str_type(&input_expr_types[0], "split_part")- }- BuiltinScalarFunction::StartsWith => Ok(DataType::Boolean),- BuiltinScalarFunction::Strpos => utf8_to_int_type(&input_expr_types[0], "strpos"),- BuiltinScalarFunction::Substr => utf8_to_str_type(&input_expr_types[0], "substr"),- BuiltinScalarFunction::ToHex => Ok(match input_expr_types[0] {- DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 => {- DataType::Utf8- }- _ => {- // this error is internal as `data_types` should have captured this.- return Err(DataFusionError::Internal(- "The to_hex function can only accept integers.".to_string(),- ));- }- }),- BuiltinScalarFunction::ToTimestamp => {- Ok(DataType::Timestamp(TimeUnit::Nanosecond, None))- }- BuiltinScalarFunction::ToTimestampMillis => {- Ok(DataType::Timestamp(TimeUnit::Millisecond, None))- }- BuiltinScalarFunction::ToTimestampMicros => {- Ok(DataType::Timestamp(TimeUnit::Microsecond, None))- }- BuiltinScalarFunction::ToTimestampSeconds => {- Ok(DataType::Timestamp(TimeUnit::Second, None))- }- BuiltinScalarFunction::Now => Ok(DataType::Timestamp(- TimeUnit::Nanosecond,- Some("UTC".to_owned()),- )),- BuiltinScalarFunction::Translate => {- utf8_to_str_type(&input_expr_types[0], "translate")- }- BuiltinScalarFunction::Trim => utf8_to_str_type(&input_expr_types[0], "trim"),- BuiltinScalarFunction::Upper => utf8_to_str_type(&input_expr_types[0], "upper"),- BuiltinScalarFunction::RegexpMatch => Ok(match input_expr_types[0] {- DataType::LargeUtf8 => {- DataType::List(Box::new(Field::new("item", DataType::LargeUtf8, true)))- }- DataType::Utf8 => {- DataType::List(Box::new(Field::new("item", DataType::Utf8, true)))- }- _ => {- // this error is internal as `data_types` should have captured this.- return Err(DataFusionError::Internal(- "The regexp_extract function can only accept strings.".to_string(),- ));- }- }),-- BuiltinScalarFunction::Abs- | BuiltinScalarFunction::Acos- | BuiltinScalarFunction::Asin- | BuiltinScalarFunction::Atan- | BuiltinScalarFunction::Ceil- | BuiltinScalarFunction::Cos- | BuiltinScalarFunction::Exp- | BuiltinScalarFunction::Floor- | BuiltinScalarFunction::Log- | BuiltinScalarFunction::Ln- | BuiltinScalarFunction::Log10- | BuiltinScalarFunction::Log2- | BuiltinScalarFunction::Round- | BuiltinScalarFunction::Signum- | BuiltinScalarFunction::Sin- | BuiltinScalarFunction::Sqrt- | BuiltinScalarFunction::Tan- | BuiltinScalarFunction::Trunc => match input_expr_types[0] {- DataType::Float32 => Ok(DataType::Float32),- _ => Ok(DataType::Float64),- },- }-}-/// Create a physical (function) expression./// This function errors when `args`' can't be coerced to a valid argument type of the function.pub fn create_physical_expr(@@ -253,14 +60,15 @@ pub fn create_physical_expr(input_schema: &Schema,execution_props: &ExecutionProps,) -> Result<Arc<dyn PhysicalExpr>> {- let coerced_phy_exprs = coerce(input_phy_exprs, input_schema, &signature(fun))?;+ let coerced_phy_exprs =+ coerce(input_phy_exprs, input_schema, &function::signature(fun))?;let coerced_expr_types = coerced_phy_exprs.iter().map(|e| e.data_type(input_schema)).collect::<Result<Vec<_>>>()?;- let data_type = return_type(fun, &coerced_expr_types)?;+ let data_type = function::return_type(fun, &coerced_expr_types)?;let fun_expr: ScalarFunctionImplementation = match fun {// These functions need args and input schema to pick an implementation@@ -359,283 +167,6 @@ pub fn create_physical_expr()))}-/// the signatures supported by the function `fun`.-fn signature(fun: &BuiltinScalarFunction) -> Signature {- // note: the physical expression must accept the type returned by this function or the execution panics.-- // for now, the list is small, as we do not have many built-in functions.- match fun {- BuiltinScalarFunction::Array => Signature::variadic(- array_expressions::SUPPORTED_ARRAY_TYPES.to_vec(),- fun.volatility(),- ),- BuiltinScalarFunction::Concat | BuiltinScalarFunction::ConcatWithSeparator => {- Signature::variadic(vec![DataType::Utf8], fun.volatility())- }- BuiltinScalarFunction::Coalesce => Signature::variadic(- conditional_expressions::SUPPORTED_COALESCE_TYPES.to_vec(),- fun.volatility(),- ),- BuiltinScalarFunction::Ascii- | BuiltinScalarFunction::BitLength- | BuiltinScalarFunction::CharacterLength- | BuiltinScalarFunction::InitCap- | BuiltinScalarFunction::Lower- | BuiltinScalarFunction::MD5- | BuiltinScalarFunction::OctetLength- | BuiltinScalarFunction::Reverse- | BuiltinScalarFunction::SHA224- | BuiltinScalarFunction::SHA256- | BuiltinScalarFunction::SHA384- | BuiltinScalarFunction::SHA512- | BuiltinScalarFunction::Trim- | BuiltinScalarFunction::Upper => Signature::uniform(- 1,- vec![DataType::Utf8, DataType::LargeUtf8],- fun.volatility(),- ),- BuiltinScalarFunction::Btrim- | BuiltinScalarFunction::Ltrim- | BuiltinScalarFunction::Rtrim => Signature::one_of(- vec![- TypeSignature::Exact(vec![DataType::Utf8]),- TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8]),- ],- fun.volatility(),- ),- BuiltinScalarFunction::Chr | BuiltinScalarFunction::ToHex => {- Signature::uniform(1, vec![DataType::Int64], fun.volatility())- }- BuiltinScalarFunction::Lpad | BuiltinScalarFunction::Rpad => Signature::one_of(- vec![- TypeSignature::Exact(vec![DataType::Utf8, DataType::Int64]),- TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Int64]),- TypeSignature::Exact(vec![- DataType::Utf8,- DataType::Int64,- DataType::Utf8,- ]),- TypeSignature::Exact(vec![- DataType::LargeUtf8,- DataType::Int64,- DataType::Utf8,- ]),- TypeSignature::Exact(vec![- DataType::Utf8,- DataType::Int64,- DataType::LargeUtf8,- ]),- TypeSignature::Exact(vec![- DataType::LargeUtf8,- DataType::Int64,- DataType::LargeUtf8,- ]),- ],- fun.volatility(),- ),- BuiltinScalarFunction::Left- | BuiltinScalarFunction::Repeat- | BuiltinScalarFunction::Right => Signature::one_of(- vec![- TypeSignature::Exact(vec![DataType::Utf8, DataType::Int64]),- TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Int64]),- ],- fun.volatility(),- ),- BuiltinScalarFunction::ToTimestamp => Signature::uniform(- 1,- vec![- DataType::Utf8,- DataType::Int64,- DataType::Timestamp(TimeUnit::Millisecond, None),- DataType::Timestamp(TimeUnit::Microsecond, None),- DataType::Timestamp(TimeUnit::Second, None),- ],- fun.volatility(),- ),- BuiltinScalarFunction::ToTimestampMillis => Signature::uniform(- 1,- vec![- DataType::Utf8,- DataType::Int64,- DataType::Timestamp(TimeUnit::Nanosecond, None),- DataType::Timestamp(TimeUnit::Microsecond, None),- DataType::Timestamp(TimeUnit::Second, None),- ],- fun.volatility(),- ),- BuiltinScalarFunction::ToTimestampMicros => Signature::uniform(- 1,- vec![- DataType::Utf8,- DataType::Int64,- DataType::Timestamp(TimeUnit::Nanosecond, None),- DataType::Timestamp(TimeUnit::Millisecond, None),- DataType::Timestamp(TimeUnit::Second, None),- ],- fun.volatility(),- ),- BuiltinScalarFunction::ToTimestampSeconds => Signature::uniform(- 1,- vec![- DataType::Utf8,- DataType::Int64,- DataType::Timestamp(TimeUnit::Nanosecond, None),- DataType::Timestamp(TimeUnit::Microsecond, None),- DataType::Timestamp(TimeUnit::Millisecond, None),- ],- fun.volatility(),- ),- BuiltinScalarFunction::Digest => {- Signature::exact(vec![DataType::Utf8, DataType::Utf8], fun.volatility())- }- BuiltinScalarFunction::DateTrunc => Signature::exact(- vec![- DataType::Utf8,- DataType::Timestamp(TimeUnit::Nanosecond, None),- ],- fun.volatility(),- ),- BuiltinScalarFunction::DatePart => Signature::one_of(- vec![- TypeSignature::Exact(vec![DataType::Utf8, DataType::Date32]),- TypeSignature::Exact(vec![DataType::Utf8, DataType::Date64]),- TypeSignature::Exact(vec![- DataType::Utf8,- DataType::Timestamp(TimeUnit::Second, None),- ]),- TypeSignature::Exact(vec![- DataType::Utf8,- DataType::Timestamp(TimeUnit::Microsecond, None),- ]),- TypeSignature::Exact(vec![- DataType::Utf8,- DataType::Timestamp(TimeUnit::Millisecond, None),- ]),- TypeSignature::Exact(vec![- DataType::Utf8,- DataType::Timestamp(TimeUnit::Nanosecond, None),- ]),- ],- fun.volatility(),- ),- BuiltinScalarFunction::SplitPart => Signature::one_of(- vec![- TypeSignature::Exact(vec![- DataType::Utf8,- DataType::Utf8,- DataType::Int64,- ]),- TypeSignature::Exact(vec![- DataType::LargeUtf8,- DataType::Utf8,- DataType::Int64,- ]),- TypeSignature::Exact(vec![- DataType::Utf8,- DataType::LargeUtf8,- DataType::Int64,- ]),- TypeSignature::Exact(vec![- DataType::LargeUtf8,- DataType::LargeUtf8,- DataType::Int64,- ]),- ],- fun.volatility(),- ),-- BuiltinScalarFunction::Strpos | BuiltinScalarFunction::StartsWith => {- Signature::one_of(- vec![- TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8]),- TypeSignature::Exact(vec![DataType::Utf8, DataType::LargeUtf8]),- TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Utf8]),- TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::LargeUtf8]),- ],- fun.volatility(),- )- }-- BuiltinScalarFunction::Substr => Signature::one_of(- vec![- TypeSignature::Exact(vec![DataType::Utf8, DataType::Int64]),- TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Int64]),- TypeSignature::Exact(vec![- DataType::Utf8,- DataType::Int64,- DataType::Int64,- ]),- TypeSignature::Exact(vec![- DataType::LargeUtf8,- DataType::Int64,- DataType::Int64,- ]),- ],- fun.volatility(),- ),-- BuiltinScalarFunction::Replace | BuiltinScalarFunction::Translate => {- Signature::one_of(- vec![TypeSignature::Exact(vec![- DataType::Utf8,- DataType::Utf8,- DataType::Utf8,- ])],- fun.volatility(),- )- }- BuiltinScalarFunction::RegexpReplace => Signature::one_of(- vec![- TypeSignature::Exact(vec![- DataType::Utf8,- DataType::Utf8,- DataType::Utf8,- ]),- TypeSignature::Exact(vec![- DataType::Utf8,- DataType::Utf8,- DataType::Utf8,- DataType::Utf8,- ]),- ],- fun.volatility(),- ),-- BuiltinScalarFunction::NullIf => {- Signature::uniform(2, SUPPORTED_NULLIF_TYPES.to_vec(), fun.volatility())- }- BuiltinScalarFunction::RegexpMatch => Signature::one_of(- vec![- TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8]),- TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Utf8]),- TypeSignature::Exact(vec![- DataType::Utf8,- DataType::Utf8,- DataType::Utf8,- ]),- TypeSignature::Exact(vec![- DataType::LargeUtf8,- DataType::Utf8,- DataType::Utf8,- ]),- ],- fun.volatility(),- ),- BuiltinScalarFunction::Random => Signature::exact(vec![], fun.volatility()),- // math expressions expect 1 argument of type f64 or f32- // priority is given to f64 because e.g. `sqrt(1i32)` is in IR (real numbers) and thus we- // return the best approximation for it (in f64).- // We accept f32 because in this case it is clear that the best approximation- // will be as good as the number of digits in the number- _ => Signature::uniform(- 1,- vec![DataType::Float64, DataType::Float32],- fun.volatility(),- ),- }-}-pub use datafusion_physical_expr::ScalarFunctionExpr;#[cfg(feature = "crypto_expressions")]diff --git a/datafusion/core/src/physical_plan/mod.rs b/datafusion/core/src/physical_plan/mod.rsindex f3d9ced624..e38b9d5121 100644--- a/datafusion/core/src/physical_plan/mod.rs+++ b/datafusion/core/src/physical_plan/mod.rs@@ -573,5 +573,4 @@ pub mod udaf;pub mod udf;pub mod union;pub mod values;-pub mod window_functions;pub mod windows;diff --git a/datafusion/core/src/physical_plan/type_coercion.rs b/datafusion/core/src/physical_plan/type_coercion.rsindex b4133565ae..9f9103c595 100644--- a/datafusion/core/src/physical_plan/type_coercion.rs+++ b/datafusion/core/src/physical_plan/type_coercion.rs@@ -31,12 +31,12 @@use std::{sync::Arc, vec};-use arrow::datatypes::{DataType, Schema, TimeUnit};+use arrow::datatypes::Schema;-use super::{functions::Signature, PhysicalExpr};-use crate::error::{DataFusionError, Result};+use super::PhysicalExpr;+use crate::error::Result;use crate::physical_plan::expressions::try_cast;-use crate::physical_plan::functions::TypeSignature;+use datafusion_expr::{type_coercion::data_types, Signature};/// Returns `expressions` coerced to types compatible with/// `signature`, if possible.@@ -65,193 +65,13 @@ pub fn coerce(.collect::<Result<Vec<_>>>()}-/// Returns the data types that each argument must be coerced to match-/// `signature`.-///-/// See the module level documentation for more detail on coercion.-pub fn data_types(- current_types: &[DataType],- signature: &Signature,-) -> Result<Vec<DataType>> {- if current_types.is_empty() {- return Ok(vec![]);- }- let valid_types = get_valid_types(&signature.type_signature, current_types)?;-- if valid_types- .iter()- .any(|data_type| data_type == current_types)- {- return Ok(current_types.to_vec());- }-- for valid_types in valid_types {- if let Some(types) = maybe_data_types(&valid_types, current_types) {- return Ok(types);- }- }-- // none possible -> Error- Err(DataFusionError::Plan(format!(- "Coercion from {:?} to the signature {:?} failed.",- current_types, &signature.type_signature- )))-}--fn get_valid_types(- signature: &TypeSignature,- current_types: &[DataType],-) -> Result<Vec<Vec<DataType>>> {- let valid_types = match signature {- TypeSignature::Variadic(valid_types) => valid_types- .iter()- .map(|valid_type| current_types.iter().map(|_| valid_type.clone()).collect())- .collect(),- TypeSignature::Uniform(number, valid_types) => valid_types- .iter()- .map(|valid_type| (0..*number).map(|_| valid_type.clone()).collect())- .collect(),- TypeSignature::VariadicEqual => {- // one entry with the same len as current_types, whose type is `current_types[0]`.- vec![current_types- .iter()- .map(|_| current_types[0].clone())- .collect()]- }- TypeSignature::Exact(valid_types) => vec![valid_types.clone()],- TypeSignature::Any(number) => {- if current_types.len() != *number {- return Err(DataFusionError::Plan(format!(- "The function expected {} arguments but received {}",- number,- current_types.len()- )));- }- vec![(0..*number).map(|i| current_types[i].clone()).collect()]- }- TypeSignature::OneOf(types) => types- .iter()- .filter_map(|t| get_valid_types(t, current_types).ok())- .flatten()- .collect::<Vec<_>>(),- };-- Ok(valid_types)-}--/// Try to coerce current_types into valid_types.-fn maybe_data_types(- valid_types: &[DataType],- current_types: &[DataType],-) -> Option<Vec<DataType>> {- if valid_types.len() != current_types.len() {- return None;- }-- let mut new_type = Vec::with_capacity(valid_types.len());- for (i, valid_type) in valid_types.iter().enumerate() {- let current_type = ¤t_types[i];-- if current_type == valid_type {- new_type.push(current_type.clone())- } else {- // attempt to coerce- if can_coerce_from(valid_type, current_type) {- new_type.push(valid_type.clone())- } else {- // not possible- return None;- }- }- }- Some(new_type)-}--/// Return true if a value of type `type_from` can be coerced-/// (losslessly converted) into a value of `type_to`-///-/// See the module level documentation for more detail on coercion.-pub fn can_coerce_from(type_into: &DataType, type_from: &DataType) -> bool {- use self::DataType::*;- match type_into {- Int8 => matches!(type_from, Int8),- Int16 => matches!(type_from, Int8 | Int16 | UInt8),- Int32 => matches!(type_from, Int8 | Int16 | Int32 | UInt8 | UInt16),- Int64 => matches!(- type_from,- Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32- ),- UInt8 => matches!(type_from, UInt8),- UInt16 => matches!(type_from, UInt8 | UInt16),- UInt32 => matches!(type_from, UInt8 | UInt16 | UInt32),- UInt64 => matches!(type_from, UInt8 | UInt16 | UInt32 | UInt64),- Float32 => matches!(- type_from,- Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64 | Float32- ),- Float64 => matches!(- type_from,- Int8 | Int16- | Int32- | Int64- | UInt8- | UInt16- | UInt32- | UInt64- | Float32- | Float64- ),- Timestamp(TimeUnit::Nanosecond, None) => matches!(type_from, Timestamp(_, None)),- Utf8 | LargeUtf8 => true,- _ => false,- }-}-#[cfg(test)]mod tests {use super::*;- use crate::physical_plan::{- expressions::col,- functions::{TypeSignature, Volatility},- };use arrow::datatypes::{DataType, Field, Schema};-- #[test]- fn test_maybe_data_types() {- // this vec contains: arg1, arg2, expected result- let cases = vec![- // 2 entries, same values- (- vec![DataType::UInt8, DataType::UInt16],- vec![DataType::UInt8, DataType::UInt16],- Some(vec![DataType::UInt8, DataType::UInt16]),- ),- // 2 entries, can coerse values- (- vec![DataType::UInt16, DataType::UInt16],- vec![DataType::UInt8, DataType::UInt16],- Some(vec![DataType::UInt16, DataType::UInt16]),- ),- // 0 entries, all good- (vec![], vec![], Some(vec![])),- // 2 entries, can't coerce- (- vec![DataType::Boolean, DataType::UInt16],- vec![DataType::UInt8, DataType::UInt16],- None,- ),- // u32 -> u16 is possible- (- vec![DataType::Boolean, DataType::UInt32],- vec![DataType::Boolean, DataType::UInt16],- Some(vec![DataType::Boolean, DataType::UInt32]),- ),- ];-- for case in cases {- assert_eq!(maybe_data_types(&case.0, &case.1), case.2)- }- }+ use datafusion_common::DataFusionError;+ use datafusion_expr::Volatility;+ use datafusion_physical_expr::expressions::col;#[test]fn test_coerce() -> Result<()> {@@ -380,28 +200,4 @@ mod tests {Ok(())}-- #[test]- fn test_get_valid_types_one_of() -> Result<()> {- let signature =- TypeSignature::OneOf(vec![TypeSignature::Any(1), TypeSignature::Any(2)]);-- let invalid_types = get_valid_types(- &signature,- &[DataType::Int32, DataType::Int32, DataType::Int32],- )?;- assert_eq!(invalid_types.len(), 0);-- let args = vec![DataType::Int32, DataType::Int32];- let valid_types = get_valid_types(&signature, &args)?;- assert_eq!(valid_types.len(), 1);- assert_eq!(valid_types[0], args);-- let args = vec![DataType::Int32];- let valid_types = get_valid_types(&signature, &args)?;- assert_eq!(valid_types.len(), 1);- assert_eq!(valid_types[0], args);-- Ok(())- }}diff --git a/datafusion/core/src/physical_plan/window_functions.rs b/datafusion/core/src/physical_plan/window_functions.rsdeleted file mode 100644index b667bfe86f..0000000000--- a/datafusion/core/src/physical_plan/window_functions.rs+++ /dev/null@@ -1,200 +0,0 @@-// 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.--//! Window functions provide the ability to perform calculations across-//! sets of rows that are related to the current query row.-//!-//! see also <https://www.postgresql.org/docs/current/functions-window.html>--use crate::error::Result;-use crate::physical_plan::functions::{TypeSignature, Volatility};-use crate::physical_plan::{aggregates, functions::Signature, type_coercion::data_types};-use arrow::datatypes::DataType;-pub use datafusion_expr::{BuiltInWindowFunction, WindowFunction};--/// Returns the datatype of the window function-pub fn return_type(- fun: &WindowFunction,- input_expr_types: &[DataType],-) -> Result<DataType> {- match fun {- WindowFunction::AggregateFunction(fun) => {- aggregates::return_type(fun, input_expr_types)- }- WindowFunction::BuiltInWindowFunction(fun) => {- return_type_for_built_in(fun, input_expr_types)- }- }-}--/// Returns the datatype of the built-in window function-pub(super) fn return_type_for_built_in(- fun: &BuiltInWindowFunction,- input_expr_types: &[DataType],-) -> Result<DataType> {- // Note that this function *must* return the same type that the respective physical expression returns- // or the execution panics.-- // verify that this is a valid set of data types for this function- data_types(input_expr_types, &signature_for_built_in(fun))?;-- match fun {- BuiltInWindowFunction::RowNumber- | BuiltInWindowFunction::Rank- | BuiltInWindowFunction::DenseRank => Ok(DataType::UInt64),- BuiltInWindowFunction::PercentRank | BuiltInWindowFunction::CumeDist => {- Ok(DataType::Float64)- }- BuiltInWindowFunction::Ntile => Ok(DataType::UInt32),- BuiltInWindowFunction::Lag- | BuiltInWindowFunction::Lead- | BuiltInWindowFunction::FirstValue- | BuiltInWindowFunction::LastValue- | BuiltInWindowFunction::NthValue => Ok(input_expr_types[0].clone()),- }-}--/// the signatures supported by the function `fun`.-pub fn signature(fun: &WindowFunction) -> Signature {- match fun {- WindowFunction::AggregateFunction(fun) => aggregates::signature(fun),- WindowFunction::BuiltInWindowFunction(fun) => signature_for_built_in(fun),- }-}--/// the signatures supported by the built-in window function `fun`.-pub(super) fn signature_for_built_in(fun: &BuiltInWindowFunction) -> Signature {- // note: the physical expression must accept the type returned by this function or the execution panics.- match fun {- BuiltInWindowFunction::RowNumber- | BuiltInWindowFunction::Rank- | BuiltInWindowFunction::DenseRank- | BuiltInWindowFunction::PercentRank- | BuiltInWindowFunction::CumeDist => Signature::any(0, Volatility::Immutable),- BuiltInWindowFunction::Lag | BuiltInWindowFunction::Lead => Signature::one_of(- vec![- TypeSignature::Any(1),- TypeSignature::Any(2),- TypeSignature::Any(3),- ],- Volatility::Immutable,- ),- BuiltInWindowFunction::FirstValue | BuiltInWindowFunction::LastValue => {- Signature::any(1, Volatility::Immutable)- }- BuiltInWindowFunction::Ntile => {- Signature::exact(vec![DataType::UInt64], Volatility::Immutable)- }- BuiltInWindowFunction::NthValue => Signature::any(2, Volatility::Immutable),- }-}--#[cfg(test)]-mod tests {- use super::*;- use std::str::FromStr;-- #[test]- fn test_count_return_type() -> Result<()> {- let fun = WindowFunction::from_str("count")?;- let observed = return_type(&fun, &[DataType::Utf8])?;- assert_eq!(DataType::UInt64, observed);-- let observed = return_type(&fun, &[DataType::UInt64])?;- assert_eq!(DataType::UInt64, observed);-- Ok(())- }-- #[test]- fn test_first_value_return_type() -> Result<()> {- let fun = WindowFunction::from_str("first_value")?;- let observed = return_type(&fun, &[DataType::Utf8])?;- assert_eq!(DataType::Utf8, observed);-- let observed = return_type(&fun, &[DataType::UInt64])?;- assert_eq!(DataType::UInt64, observed);-- Ok(())- }-- #[test]- fn test_last_value_return_type() -> Result<()> {- let fun = WindowFunction::from_str("last_value")?;- let observed = return_type(&fun, &[DataType::Utf8])?;- assert_eq!(DataType::Utf8, observed);-- let observed = return_type(&fun, &[DataType::Float64])?;- assert_eq!(DataType::Float64, observed);-- Ok(())- }-- #[test]- fn test_lead_return_type() -> Result<()> {- let fun = WindowFunction::from_str("lead")?;- let observed = return_type(&fun, &[DataType::Utf8])?;- assert_eq!(DataType::Utf8, observed);-- let observed = return_type(&fun, &[DataType::Float64])?;- assert_eq!(DataType::Float64, observed);-- Ok(())- }-- #[test]- fn test_lag_return_type() -> Result<()> {- let fun = WindowFunction::from_str("lag")?;- let observed = return_type(&fun, &[DataType::Utf8])?;- assert_eq!(DataType::Utf8, observed);-- let observed = return_type(&fun, &[DataType::Float64])?;- assert_eq!(DataType::Float64, observed);-- Ok(())- }-- #[test]- fn test_nth_value_return_type() -> Result<()> {- let fun = WindowFunction::from_str("nth_value")?;- let observed = return_type(&fun, &[DataType::Utf8, DataType::UInt64])?;- assert_eq!(DataType::Utf8, observed);-- let observed = return_type(&fun, &[DataType::Float64, DataType::UInt64])?;- assert_eq!(DataType::Float64, observed);-- Ok(())- }-- #[test]- fn test_percent_rank_return_type() -> Result<()> {- let fun = WindowFunction::from_str("percent_rank")?;- let observed = return_type(&fun, &[])?;- assert_eq!(DataType::Float64, observed);-- Ok(())- }-- #[test]- fn test_cume_dist_return_type() -> Result<()> {- let fun = WindowFunction::from_str("cume_dist")?;- let observed = return_type(&fun, &[])?;- assert_eq!(DataType::Float64, observed);-- Ok(())- }-}diff --git a/datafusion/core/src/physical_plan/windows/mod.rs b/datafusion/core/src/physical_plan/windows/mod.rsindex 34f7730f9d..c1a53aca61 100644--- a/datafusion/core/src/physical_plan/windows/mod.rs+++ b/datafusion/core/src/physical_plan/windows/mod.rs@@ -25,12 +25,14 @@ use crate::physical_plan::{PhysicalSortExpr, RowNumber,},type_coercion::coerce,- window_functions::{signature_for_built_in, BuiltInWindowFunction, WindowFunction},PhysicalExpr,};use crate::scalar::ScalarValue;use arrow::datatypes::Schema;-use datafusion_expr::WindowFrame;+use datafusion_expr::{+ window_function::{signature_for_built_in, BuiltInWindowFunction, WindowFunction},+ WindowFrame,+};use datafusion_physical_expr::window::BuiltInWindowFunctionExpr;use std::convert::TryInto;use std::sync::Arc;diff --git a/datafusion/core/src/sql/planner.rs b/datafusion/core/src/sql/planner.rsindex cff38d47b4..2f2bdc5feb 100644--- a/datafusion/core/src/sql/planner.rs+++ b/datafusion/core/src/sql/planner.rs@@ -40,14 +40,13 @@ use crate::scalar::ScalarValue;use crate::sql::utils::{make_decimal_type, normalize_ident};use crate::{error::{DataFusionError, Result},+ physical_plan::aggregates,physical_plan::udaf::AggregateUDF,-};-use crate::{physical_plan::udf::ScalarUDF,- physical_plan::{aggregates, functions, window_functions},sql::parser::{CreateExternalTable, FileType, Statement as DFStatement},};use arrow::datatypes::*;+use datafusion_expr::{window_function::WindowFunction, BuiltinScalarFunction};use hashbrown::HashMap;use sqlparser::ast::{@@ -1418,7 +1417,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {SQLExpr::Value(Value::Boolean(n)) => Ok(lit(n)),SQLExpr::Value(Value::Null) => Ok(Expr::Literal(ScalarValue::Utf8(None))),SQLExpr::Extract { field, expr } => Ok(Expr::ScalarFunction {- fun: functions::BuiltinScalarFunction::DatePart,+ fun: BuiltinScalarFunction::DatePart,args: vec![Expr::Literal(ScalarValue::Utf8(Some(format!("{}", field)))),self.sql_expr_to_logical_expr(*expr, schema)?,@@ -1672,7 +1671,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {Ok(Expr::ScalarFunction {- fun: functions::BuiltinScalarFunction::Substr,+ fun: BuiltinScalarFunction::Substr,args,})}@@ -1689,15 +1688,15 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {SQLExpr::Trim { expr, trim_where } => {let (fun, where_expr) = match trim_where {Some((TrimWhereField::Leading, expr)) => {- (functions::BuiltinScalarFunction::Ltrim, Some(expr))+ (BuiltinScalarFunction::Ltrim, Some(expr))}Some((TrimWhereField::Trailing, expr)) => {- (functions::BuiltinScalarFunction::Rtrim, Some(expr))+ (BuiltinScalarFunction::Rtrim, Some(expr))}Some((TrimWhereField::Both, expr)) => {- (functions::BuiltinScalarFunction::Btrim, Some(expr))+ (BuiltinScalarFunction::Btrim, Some(expr))}- None => (functions::BuiltinScalarFunction::Trim, None),+ None => (BuiltinScalarFunction::Trim, None),};let arg = self.sql_expr_to_logical_expr(*expr, schema)?;let args = match where_expr {@@ -1720,7 +1719,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {};// first, scalar built-in- if let Ok(fun) = functions::BuiltinScalarFunction::from_str(&name) {+ if let Ok(fun) = BuiltinScalarFunction::from_str(&name) {let args = self.function_args_to_expr(function.args, schema)?;return Ok(Expr::ScalarFunction { fun, args });@@ -1753,13 +1752,13 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {}}).transpose()?;- let fun = window_functions::WindowFunction::from_str(&name)?;+ let fun = WindowFunction::from_str(&name)?;match fun {- window_functions::WindowFunction::AggregateFunction(+ WindowFunction::AggregateFunction(aggregate_fun,) => {return Ok(Expr::WindowFunction {- fun: window_functions::WindowFunction::AggregateFunction(+ fun: WindowFunction::AggregateFunction(aggregate_fun.clone(),),args: self.aggregate_fn_to_expr(@@ -1772,11 +1771,11 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {window_frame,});}- window_functions::WindowFunction::BuiltInWindowFunction(+ WindowFunction::BuiltInWindowFunction(window_fun,) => {return Ok(Expr::WindowFunction {- fun: window_functions::WindowFunction::BuiltInWindowFunction(+ fun: WindowFunction::BuiltInWindowFunction(window_fun,),args: self.function_args_to_expr(function.args, schema)?,@@ -2308,9 +2307,8 @@ fn parse_sql_number(n: &str) -> Result<Expr> {#[cfg(test)]mod tests {use crate::datasource::empty::EmptyTable;- use crate::physical_plan::functions::Volatility;use crate::{assert_contains, logical_plan::create_udf, sql::parser::DFParser};- use datafusion_expr::ScalarFunctionImplementation;+ use datafusion_expr::{ScalarFunctionImplementation, Volatility};use super::*;diff --git a/datafusion/core/src/sql/utils.rs b/datafusion/core/src/sql/utils.rsindex c970e9c67a..5e090c99b5 100644--- a/datafusion/core/src/sql/utils.rs+++ b/datafusion/core/src/sql/utils.rs@@ -548,7 +548,7 @@ mod tests {use super::*;use crate::logical_plan::col;use crate::physical_plan::aggregates::AggregateFunction;- use crate::physical_plan::window_functions::WindowFunction;+ use datafusion_expr::window_function::WindowFunction;#[test]fn test_group_window_expr_by_sort_keys_empty_case() -> Result<()> {diff --git a/datafusion/core/tests/sql/mod.rs b/datafusion/core/tests/sql/mod.rsindex 05f328d3a6..300ad0d9f7 100644--- a/datafusion/core/tests/sql/mod.rs+++ b/datafusion/core/tests/sql/mod.rs@@ -34,7 +34,6 @@ use datafusion::from_slice::FromSlice;use datafusion::logical_plan::plan::{Aggregate, Projection};use datafusion::logical_plan::LogicalPlan;use datafusion::logical_plan::TableScan;-use datafusion::physical_plan::functions::Volatility;use datafusion::physical_plan::metrics::MetricValue;use datafusion::physical_plan::ExecutionPlan;use datafusion::physical_plan::ExecutionPlanVisitor;@@ -46,6 +45,7 @@ use datafusion::{physical_plan::ColumnarValue,};use datafusion::{execution::context::SessionContext, physical_plan::displayable};+use datafusion_expr::Volatility;/// A macro to assert that some particular line contains two substrings///diff --git a/datafusion/expr/src/aggregate_function.rs b/datafusion/expr/src/aggregate_function.rsindex 545155ca9d..4e590c4670 100644--- a/datafusion/expr/src/aggregate_function.rs+++ b/datafusion/expr/src/aggregate_function.rs@@ -17,9 +17,38 @@//! Aggregate function module contains all built-in aggregate functions definitions+use crate::{Signature, TypeSignature, Volatility};+use arrow::datatypes::{+ DataType, Field, TimeUnit, DECIMAL_MAX_PRECISION, DECIMAL_MAX_SCALE,+};use datafusion_common::{DataFusionError, Result};+use std::ops::Deref;use std::{fmt, str::FromStr};+pub static STRINGS: &[DataType] = &[DataType::Utf8, DataType::LargeUtf8];++pub static NUMERICS: &[DataType] = &[+ DataType::Int8,+ DataType::Int16,+ DataType::Int32,+ DataType::Int64,+ DataType::UInt8,+ DataType::UInt16,+ DataType::UInt32,+ DataType::UInt64,+ DataType::Float32,+ DataType::Float64,+];++pub static TIMESTAMPS: &[DataType] = &[+ DataType::Timestamp(TimeUnit::Second, None),+ DataType::Timestamp(TimeUnit::Millisecond, None),+ DataType::Timestamp(TimeUnit::Microsecond, None),+ DataType::Timestamp(TimeUnit::Nanosecond, None),+];++pub static DATES: &[DataType] = &[DataType::Date32, DataType::Date64];+/// Enum of all built-in aggregate functions#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]pub enum AggregateFunction {@@ -101,3 +130,733 @@ impl FromStr for AggregateFunction {})}}++/// Returns the datatype of the aggregate function.+/// This is used to get the returned data type for aggregate expr.+pub fn return_type(+ fun: &AggregateFunction,+ input_expr_types: &[DataType],+) -> Result<DataType> {+ // Note that this function *must* return the same type that the respective physical expression returns+ // or the execution panics.++ let coerced_data_types = coerce_types(fun, input_expr_types, &signature(fun))?;++ match fun {+ // TODO If the datafusion is compatible with PostgreSQL, the returned data type should be INT64.+ AggregateFunction::Count | AggregateFunction::ApproxDistinct => {+ Ok(DataType::UInt64)+ }+ AggregateFunction::Max | AggregateFunction::Min => {+ // For min and max agg function, the returned type is same as input type.+ // The coerced_data_types is same with input_types.+ Ok(coerced_data_types[0].clone())+ }+ AggregateFunction::Sum => sum_return_type(&coerced_data_types[0]),+ AggregateFunction::Variance => variance_return_type(&coerced_data_types[0]),+ AggregateFunction::VariancePop => variance_return_type(&coerced_data_types[0]),+ AggregateFunction::Covariance => covariance_return_type(&coerced_data_types[0]),+ AggregateFunction::CovariancePop => {+ covariance_return_type(&coerced_data_types[0])+ }+ AggregateFunction::Correlation => correlation_return_type(&coerced_data_types[0]),+ AggregateFunction::Stddev => stddev_return_type(&coerced_data_types[0]),+ AggregateFunction::StddevPop => stddev_return_type(&coerced_data_types[0]),+ AggregateFunction::Avg => avg_return_type(&coerced_data_types[0]),+ AggregateFunction::ArrayAgg => Ok(DataType::List(Box::new(Field::new(+ "item",+ coerced_data_types[0].clone(),+ true,+ )))),+ AggregateFunction::ApproxPercentileCont => Ok(coerced_data_types[0].clone()),+ AggregateFunction::ApproxPercentileContWithWeight => {+ Ok(coerced_data_types[0].clone())+ }+ AggregateFunction::ApproxMedian => Ok(coerced_data_types[0].clone()),+ }+}++/// Returns the coerced data type for each `input_types`.+/// Different aggregate function with different input data type will get corresponding coerced data type.+pub fn coerce_types(+ agg_fun: &AggregateFunction,+ input_types: &[DataType],+ signature: &Signature,+) -> Result<Vec<DataType>> {+ // Validate input_types matches (at least one of) the func signature.+ check_arg_count(agg_fun, input_types, &signature.type_signature)?;++ match agg_fun {+ AggregateFunction::Count | AggregateFunction::ApproxDistinct => {+ Ok(input_types.to_vec())+ }+ AggregateFunction::ArrayAgg => Ok(input_types.to_vec()),+ AggregateFunction::Min | AggregateFunction::Max => {+ // min and max support the dictionary data type+ // unpack the dictionary to get the value+ get_min_max_result_type(input_types)+ }+ AggregateFunction::Sum => {+ // Refer to https://www.postgresql.org/docs/8.2/functions-aggregate.html doc+ // smallint, int, bigint, real, double precision, decimal, or interval.+ if !is_sum_support_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ Ok(input_types.to_vec())+ }+ AggregateFunction::Avg => {+ // Refer to https://www.postgresql.org/docs/8.2/functions-aggregate.html doc+ // smallint, int, bigint, real, double precision, decimal, or interval+ if !is_avg_support_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ Ok(input_types.to_vec())+ }+ AggregateFunction::Variance => {+ if !is_variance_support_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ Ok(input_types.to_vec())+ }+ AggregateFunction::VariancePop => {+ if !is_variance_support_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ Ok(input_types.to_vec())+ }+ AggregateFunction::Covariance => {+ if !is_covariance_support_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ Ok(input_types.to_vec())+ }+ AggregateFunction::CovariancePop => {+ if !is_covariance_support_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ Ok(input_types.to_vec())+ }+ AggregateFunction::Stddev => {+ if !is_stddev_support_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ Ok(input_types.to_vec())+ }+ AggregateFunction::StddevPop => {+ if !is_stddev_support_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ Ok(input_types.to_vec())+ }+ AggregateFunction::Correlation => {+ if !is_correlation_support_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ Ok(input_types.to_vec())+ }+ AggregateFunction::ApproxPercentileCont => {+ if !is_approx_percentile_cont_supported_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ if !matches!(input_types[1], DataType::Float64) {+ return Err(DataFusionError::Plan(format!(+ "The percentile argument for {:?} must be Float64, not {:?}.",+ agg_fun, input_types[1]+ )));+ }+ Ok(input_types.to_vec())+ }+ AggregateFunction::ApproxPercentileContWithWeight => {+ if !is_approx_percentile_cont_supported_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ if !is_approx_percentile_cont_supported_arg_type(&input_types[1]) {+ return Err(DataFusionError::Plan(format!(+ "The weight argument for {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[1]+ )));+ }+ if !matches!(input_types[2], DataType::Float64) {+ return Err(DataFusionError::Plan(format!(+ "The percentile argument for {:?} must be Float64, not {:?}.",+ agg_fun, input_types[2]+ )));+ }+ Ok(input_types.to_vec())+ }+ AggregateFunction::ApproxMedian => {+ if !is_approx_percentile_cont_supported_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ Ok(input_types.to_vec())+ }+ }+}++/// the signatures supported by the function `fun`.+pub fn signature(fun: &AggregateFunction) -> Signature {+ // note: the physical expression must accept the type returned by this function or the execution panics.+ match fun {+ AggregateFunction::Count+ | AggregateFunction::ApproxDistinct+ | AggregateFunction::ArrayAgg => Signature::any(1, Volatility::Immutable),+ AggregateFunction::Min | AggregateFunction::Max => {+ let valid = STRINGS+ .iter()+ .chain(NUMERICS.iter())+ .chain(TIMESTAMPS.iter())+ .chain(DATES.iter())+ .cloned()+ .collect::<Vec<_>>();+ Signature::uniform(1, valid, Volatility::Immutable)+ }+ AggregateFunction::Avg+ | AggregateFunction::Sum+ | AggregateFunction::Variance+ | AggregateFunction::VariancePop+ | AggregateFunction::Stddev+ | AggregateFunction::StddevPop+ | AggregateFunction::ApproxMedian => {+ Signature::uniform(1, NUMERICS.to_vec(), Volatility::Immutable)+ }+ AggregateFunction::Covariance | AggregateFunction::CovariancePop => {+ Signature::uniform(2, NUMERICS.to_vec(), Volatility::Immutable)+ }+ AggregateFunction::Correlation => {+ Signature::uniform(2, NUMERICS.to_vec(), Volatility::Immutable)+ }+ AggregateFunction::ApproxPercentileCont => Signature::one_of(+ // Accept any numeric value paired with a float64 percentile+ NUMERICS+ .iter()+ .map(|t| TypeSignature::Exact(vec![t.clone(), DataType::Float64]))+ .collect(),+ Volatility::Immutable,+ ),+ AggregateFunction::ApproxPercentileContWithWeight => Signature::one_of(+ // Accept any numeric value paired with a float64 percentile+ NUMERICS+ .iter()+ .map(|t| {+ TypeSignature::Exact(vec![t.clone(), t.clone(), DataType::Float64])+ })+ .collect(),+ Volatility::Immutable,+ ),+ }+}++/// function return type of a sum+pub fn sum_return_type(arg_type: &DataType) -> Result<DataType> {+ match arg_type {+ DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 => {+ Ok(DataType::Int64)+ }+ DataType::UInt8 | DataType::UInt16 | DataType::UInt32 | DataType::UInt64 => {+ Ok(DataType::UInt64)+ }+ // In the https://www.postgresql.org/docs/current/functions-aggregate.html doc,+ // the result type of floating-point is FLOAT64 with the double precision.+ DataType::Float64 | DataType::Float32 => Ok(DataType::Float64),+ DataType::Decimal(precision, scale) => {+ // in the spark, the result type is DECIMAL(min(38,precision+10), s)+ // ref: https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66+ let new_precision = DECIMAL_MAX_PRECISION.min(*precision + 10);+ Ok(DataType::Decimal(new_precision, *scale))+ }+ other => Err(DataFusionError::Plan(format!(+ "SUM does not support type \"{:?}\"",+ other+ ))),+ }+}++/// function return type of variance+pub fn variance_return_type(arg_type: &DataType) -> Result<DataType> {+ match arg_type {+ DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Float32+ | DataType::Float64 => Ok(DataType::Float64),+ other => Err(DataFusionError::Plan(format!(+ "VAR does not support {:?}",+ other+ ))),+ }+}++/// function return type of covariance+pub fn covariance_return_type(arg_type: &DataType) -> Result<DataType> {+ match arg_type {+ DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Float32+ | DataType::Float64 => Ok(DataType::Float64),+ other => Err(DataFusionError::Plan(format!(+ "COVAR does not support {:?}",+ other+ ))),+ }+}++/// function return type of correlation+pub fn correlation_return_type(arg_type: &DataType) -> Result<DataType> {+ match arg_type {+ DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Float32+ | DataType::Float64 => Ok(DataType::Float64),+ other => Err(DataFusionError::Plan(format!(+ "CORR does not support {:?}",+ other+ ))),+ }+}++/// function return type of standard deviation+pub fn stddev_return_type(arg_type: &DataType) -> Result<DataType> {+ match arg_type {+ DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Float32+ | DataType::Float64 => Ok(DataType::Float64),+ other => Err(DataFusionError::Plan(format!(+ "STDDEV does not support {:?}",+ other+ ))),+ }+}++/// function return type of an average+pub fn avg_return_type(arg_type: &DataType) -> Result<DataType> {+ match arg_type {+ DataType::Decimal(precision, scale) => {+ // in the spark, the result type is DECIMAL(min(38,precision+4), min(38,scale+4)).+ // ref: https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Average.scala#L66+ let new_precision = DECIMAL_MAX_PRECISION.min(*precision + 4);+ let new_scale = DECIMAL_MAX_SCALE.min(*scale + 4);+ Ok(DataType::Decimal(new_precision, new_scale))+ }+ DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Float32+ | DataType::Float64 => Ok(DataType::Float64),+ other => Err(DataFusionError::Plan(format!(+ "AVG does not support {:?}",+ other+ ))),+ }+}++/// Validate the length of `input_types` matches the `signature` for `agg_fun`.+///+/// This method DOES NOT validate the argument types - only that (at least one,+/// in the case of [`TypeSignature::OneOf`]) signature matches the desired+/// number of input types.+fn check_arg_count(+ agg_fun: &AggregateFunction,+ input_types: &[DataType],+ signature: &TypeSignature,+) -> Result<()> {+ match signature {+ TypeSignature::Uniform(agg_count, _) | TypeSignature::Any(agg_count) => {+ if input_types.len() != *agg_count {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} expects {:?} arguments, but {:?} were provided",+ agg_fun,+ agg_count,+ input_types.len()+ )));+ }+ }+ TypeSignature::Exact(types) => {+ if types.len() != input_types.len() {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} expects {:?} arguments, but {:?} were provided",+ agg_fun,+ types.len(),+ input_types.len()+ )));+ }+ }+ TypeSignature::OneOf(variants) => {+ let ok = variants+ .iter()+ .any(|v| check_arg_count(agg_fun, input_types, v).is_ok());+ if !ok {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not accept {:?} function arguments.",+ agg_fun,+ input_types.len()+ )));+ }+ }+ _ => {+ return Err(DataFusionError::Internal(format!(+ "Aggregate functions do not support this {:?}",+ signature+ )));+ }+ }+ Ok(())+}++fn get_min_max_result_type(input_types: &[DataType]) -> Result<Vec<DataType>> {+ // make sure that the input types only has one element.+ assert_eq!(input_types.len(), 1);+ // min and max support the dictionary data type+ // unpack the dictionary to get the value+ match &input_types[0] {+ DataType::Dictionary(_, dict_value_type) => {+ // TODO add checker, if the value type is complex data type+ Ok(vec![dict_value_type.deref().clone()])+ }+ // TODO add checker for datatype which min and max supported+ // For example, the `Struct` and `Map` type are not supported in the MIN and MAX function+ _ => Ok(input_types.to_vec()),+ }+}++pub fn is_sum_support_arg_type(arg_type: &DataType) -> bool {+ matches!(+ arg_type,+ DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::Float32+ | DataType::Float64+ | DataType::Decimal(_, _)+ )+}++pub fn is_avg_support_arg_type(arg_type: &DataType) -> bool {+ matches!(+ arg_type,+ DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::Float32+ | DataType::Float64+ | DataType::Decimal(_, _)+ )+}++pub fn is_variance_support_arg_type(arg_type: &DataType) -> bool {+ matches!(+ arg_type,+ DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::Float32+ | DataType::Float64+ )+}++pub fn is_covariance_support_arg_type(arg_type: &DataType) -> bool {+ matches!(+ arg_type,+ DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::Float32+ | DataType::Float64+ )+}++pub fn is_stddev_support_arg_type(arg_type: &DataType) -> bool {+ matches!(+ arg_type,+ DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::Float32+ | DataType::Float64+ )+}++pub fn is_correlation_support_arg_type(arg_type: &DataType) -> bool {+ matches!(+ arg_type,+ DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::Float32+ | DataType::Float64+ )+}++/// Return `true` if `arg_type` is of a [`DataType`] that the+/// [`ApproxPercentileCont`] aggregation can operate on.+pub fn is_approx_percentile_cont_supported_arg_type(arg_type: &DataType) -> bool {+ matches!(+ arg_type,+ DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::Float32+ | DataType::Float64+ )+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::aggregate_function;+ use arrow::datatypes::DataType;++ #[test]+ fn test_aggregate_coerce_types() {+ // test input args with error number input types+ let fun = AggregateFunction::Min;+ let input_types = vec![DataType::Int64, DataType::Int32];+ let signature = aggregate_function::signature(&fun);+ let result = coerce_types(&fun, &input_types, &signature);+ assert_eq!("Error during planning: The function Min expects 1 arguments, but 2 were provided", result.unwrap_err().to_string());++ // test input args is invalid data type for sum or avg+ let fun = AggregateFunction::Sum;+ let input_types = vec![DataType::Utf8];+ let signature = aggregate_function::signature(&fun);+ let result = coerce_types(&fun, &input_types, &signature);+ assert_eq!(+ "Error during planning: The function Sum does not support inputs of type Utf8.",+ result.unwrap_err().to_string()+ );+ let fun = AggregateFunction::Avg;+ let signature = aggregate_function::signature(&fun);+ let result = coerce_types(&fun, &input_types, &signature);+ assert_eq!(+ "Error during planning: The function Avg does not support inputs of type Utf8.",+ result.unwrap_err().to_string()+ );++ // test count, array_agg, approx_distinct, min, max.+ // the coerced types is same with input types+ let funs = vec![+ AggregateFunction::Count,+ AggregateFunction::ArrayAgg,+ AggregateFunction::ApproxDistinct,+ AggregateFunction::Min,+ AggregateFunction::Max,+ ];+ let input_types = vec![+ vec![DataType::Int32],+ vec![DataType::Decimal(10, 2)],+ vec![DataType::Utf8],+ ];+ for fun in funs {+ for input_type in &input_types {+ let signature = aggregate_function::signature(&fun);+ let result = coerce_types(&fun, input_type, &signature);+ assert_eq!(*input_type, result.unwrap());+ }+ }+ // test sum, avg+ let funs = vec![AggregateFunction::Sum, AggregateFunction::Avg];+ let input_types = vec![+ vec![DataType::Int32],+ vec![DataType::Float32],+ vec![DataType::Decimal(20, 3)],+ ];+ for fun in funs {+ for input_type in &input_types {+ let signature = aggregate_function::signature(&fun);+ let result = coerce_types(&fun, input_type, &signature);+ assert_eq!(*input_type, result.unwrap());+ }+ }++ // ApproxPercentileCont input types+ let input_types = vec![+ vec![DataType::Int8, DataType::Float64],+ vec![DataType::Int16, DataType::Float64],+ vec![DataType::Int32, DataType::Float64],+ vec![DataType::Int64, DataType::Float64],+ vec![DataType::UInt8, DataType::Float64],+ vec![DataType::UInt16, DataType::Float64],+ vec![DataType::UInt32, DataType::Float64],+ vec![DataType::UInt64, DataType::Float64],+ vec![DataType::Float32, DataType::Float64],+ vec![DataType::Float64, DataType::Float64],+ ];+ for input_type in &input_types {+ let signature =+ aggregate_function::signature(&AggregateFunction::ApproxPercentileCont);+ let result = coerce_types(+ &AggregateFunction::ApproxPercentileCont,+ input_type,+ &signature,+ );+ assert_eq!(*input_type, result.unwrap());+ }+ }++ #[test]+ fn test_avg_return_data_type() -> Result<()> {+ let data_type = DataType::Decimal(10, 5);+ let result_type = avg_return_type(&data_type)?;+ assert_eq!(DataType::Decimal(14, 9), result_type);++ let data_type = DataType::Decimal(36, 10);+ let result_type = avg_return_type(&data_type)?;+ assert_eq!(DataType::Decimal(38, 14), result_type);+ Ok(())+ }++ #[test]+ fn test_variance_return_data_type() -> Result<()> {+ let data_type = DataType::Float64;+ let result_type = variance_return_type(&data_type)?;+ assert_eq!(DataType::Float64, result_type);++ let data_type = DataType::Decimal(36, 10);+ assert!(variance_return_type(&data_type).is_err());+ Ok(())+ }++ #[test]+ fn test_sum_return_data_type() -> Result<()> {+ let data_type = DataType::Decimal(10, 5);+ let result_type = sum_return_type(&data_type)?;+ assert_eq!(DataType::Decimal(20, 5), result_type);++ let data_type = DataType::Decimal(36, 10);+ let result_type = sum_return_type(&data_type)?;+ assert_eq!(DataType::Decimal(38, 10), result_type);+ Ok(())+ }++ #[test]+ fn test_stddev_return_data_type() -> Result<()> {+ let data_type = DataType::Float64;+ let result_type = stddev_return_type(&data_type)?;+ assert_eq!(DataType::Float64, result_type);++ let data_type = DataType::Decimal(36, 10);+ assert!(stddev_return_type(&data_type).is_err());+ Ok(())+ }++ #[test]+ fn test_covariance_return_data_type() -> Result<()> {+ let data_type = DataType::Float64;+ let result_type = covariance_return_type(&data_type)?;+ assert_eq!(DataType::Float64, result_type);++ let data_type = DataType::Decimal(36, 10);+ assert!(covariance_return_type(&data_type).is_err());+ Ok(())+ }++ #[test]+ fn test_correlation_return_data_type() -> Result<()> {+ let data_type = DataType::Float64;+ let result_type = correlation_return_type(&data_type)?;+ assert_eq!(DataType::Float64, result_type);++ let data_type = DataType::Decimal(36, 10);+ assert!(correlation_return_type(&data_type).is_err());+ Ok(())+ }+}diff --git a/datafusion/expr/src/array_expressions.rs b/datafusion/expr/src/array_expressions.rsnew file mode 100644index 0000000000..6469437866--- /dev/null+++ b/datafusion/expr/src/array_expressions.rs@@ -0,0 +1,37 @@+// 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.++use arrow::datatypes::DataType;++/// Currently supported types by the array function.+/// The order of these types correspond to the order on which coercion applies+/// This should thus be from least informative to most informative+pub static SUPPORTED_ARRAY_TYPES: &[DataType] = &[+ DataType::Boolean,+ DataType::UInt8,+ DataType::UInt16,+ DataType::UInt32,+ DataType::UInt64,+ DataType::Int8,+ DataType::Int16,+ DataType::Int32,+ DataType::Int64,+ DataType::Float32,+ DataType::Float64,+ DataType::Utf8,+ DataType::LargeUtf8,+];diff --git a/datafusion/physical-expr/src/coercion_rule/binary_rule.rs b/datafusion/expr/src/binary_rule.rssimilarity index 94%rename from datafusion/physical-expr/src/coercion_rule/binary_rule.rsrename to datafusion/expr/src/binary_rule.rsindex 1233ed9800..ad46770f10 100644--- a/datafusion/physical-expr/src/coercion_rule/binary_rule.rs+++ b/datafusion/expr/src/binary_rule.rs@@ -17,15 +17,59 @@//! Coercion rules for matching argument types for binary operators+use crate::Operator;use arrow::compute::can_cast_types;use arrow::datatypes::{DataType, DECIMAL_MAX_PRECISION, DECIMAL_MAX_SCALE};use datafusion_common::DataFusionError;use datafusion_common::Result;-use datafusion_expr::Operator;++/// 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.+///+/// This function makes some assumptions about the underlying available computations.+pub fn binary_operator_data_type(+ lhs_type: &DataType,+ op: &Operator,+ rhs_type: &DataType,+) -> Result<DataType> {+ // validate that it is possible to perform the operation on incoming types.+ // (or the return datatype cannot be inferred)+ let result_type = coerce_types(lhs_type, op, rhs_type)?;++ match op {+ // operators that return a boolean+ Operator::Eq+ | Operator::NotEq+ | Operator::And+ | Operator::Or+ | Operator::Like+ | Operator::NotLike+ | Operator::Lt+ | Operator::Gt+ | Operator::GtEq+ | Operator::LtEq+ | Operator::RegexMatch+ | Operator::RegexIMatch+ | Operator::RegexNotMatch+ | Operator::RegexNotIMatch+ | Operator::IsDistinctFrom+ | Operator::IsNotDistinctFrom => Ok(DataType::Boolean),+ // bitwise operations return the common coerced type+ Operator::BitwiseAnd | Operator::BitwiseOr => Ok(result_type),+ // math operations return the same value as the common coerced type+ Operator::Plus+ | Operator::Minus+ | Operator::Divide+ | Operator::Multiply+ | Operator::Modulo => Ok(result_type),+ // string operations return the same values as the common coerced type+ Operator::StringConcat => Ok(result_type),+ }+}/// 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(+pub fn coerce_types(lhs_type: &DataType,op: &Operator,rhs_type: &DataType,@@ -551,10 +595,10 @@ fn eq_coercion(lhs_type: &DataType, rhs_type: &DataType) -> Option<DataType> {#[cfg(test)]mod tests {use super::*;+ use crate::Operator;use arrow::datatypes::DataType;use datafusion_common::DataFusionError;use datafusion_common::Result;- use datafusion_expr::Operator;#[test]fn test_coercion_error() -> Result<()> {diff --git a/datafusion/expr/src/conditional_expressions.rs b/datafusion/expr/src/conditional_expressions.rsnew file mode 100644index 0000000000..bafa2c724f--- /dev/null+++ b/datafusion/expr/src/conditional_expressions.rs@@ -0,0 +1,37 @@+// 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.++use arrow::datatypes::DataType;++/// Currently supported types by the coalesce function.+/// The order of these types correspond to the order on which coercion applies+/// This should thus be from least informative to most informative+pub static SUPPORTED_COALESCE_TYPES: &[DataType] = &[+ DataType::Boolean,+ DataType::UInt8,+ DataType::UInt16,+ DataType::UInt32,+ DataType::UInt64,+ DataType::Int8,+ DataType::Int16,+ DataType::Int32,+ DataType::Int64,+ DataType::Float32,+ DataType::Float64,+ DataType::Utf8,+ DataType::LargeUtf8,+];diff --git a/datafusion/expr/src/function.rs b/datafusion/expr/src/function.rsindex 3689ff759a..93c5d0e12f 100644--- a/datafusion/expr/src/function.rs+++ b/datafusion/expr/src/function.rs@@ -17,10 +17,15 @@//! Function module contains typing and signature for built-in and user defined functions.-use crate::Accumulator;+use crate::nullif::SUPPORTED_NULLIF_TYPES;+use crate::type_coercion::data_types;use crate::ColumnarValue;-use arrow::datatypes::DataType;-use datafusion_common::Result;+use crate::{+ array_expressions, conditional_expressions, Accumulator, BuiltinScalarFunction,+ Signature, TypeSignature,+};+use arrow::datatypes::{DataType, Field, TimeUnit};+use datafusion_common::{DataFusionError, Result};use std::sync::Arc;/// Scalar function@@ -46,3 +51,469 @@ pub type AccumulatorFunctionImplementation =/// its state, given its return datatype.pub type StateTypeFunction =Arc<dyn Fn(&DataType) -> Result<Arc<Vec<DataType>>> + Send + Sync>;++macro_rules! make_utf8_to_return_type {+ ($FUNC:ident, $largeUtf8Type:expr, $utf8Type:expr) => {+ fn $FUNC(arg_type: &DataType, name: &str) -> Result<DataType> {+ Ok(match arg_type {+ DataType::LargeUtf8 => $largeUtf8Type,+ DataType::Utf8 => $utf8Type,+ _ => {+ // this error is internal as `data_types` should have captured this.+ return Err(DataFusionError::Internal(format!(+ "The {:?} function can only accept strings.",+ name+ )));+ }+ })+ }+ };+}++make_utf8_to_return_type!(utf8_to_str_type, DataType::LargeUtf8, DataType::Utf8);+make_utf8_to_return_type!(utf8_to_int_type, DataType::Int64, DataType::Int32);+make_utf8_to_return_type!(utf8_to_binary_type, DataType::Binary, DataType::Binary);++/// Returns the datatype of the scalar function+pub fn return_type(+ fun: &BuiltinScalarFunction,+ input_expr_types: &[DataType],+) -> Result<DataType> {+ // Note that this function *must* return the same type that the respective physical expression returns+ // or the execution panics.++ if input_expr_types.is_empty() && !fun.supports_zero_argument() {+ return Err(DataFusionError::Internal(format!(+ "Builtin scalar function {} does not support empty arguments",+ fun+ )));+ }++ // verify that this is a valid set of data types for this function+ data_types(input_expr_types, &signature(fun))?;++ // the return type of the built in function.+ // Some built-in functions' return type depends on the incoming type.+ match fun {+ BuiltinScalarFunction::Array => Ok(DataType::FixedSizeList(+ Box::new(Field::new("item", input_expr_types[0].clone(), true)),+ input_expr_types.len() as i32,+ )),+ BuiltinScalarFunction::Ascii => Ok(DataType::Int32),+ BuiltinScalarFunction::BitLength => {+ utf8_to_int_type(&input_expr_types[0], "bit_length")+ }+ BuiltinScalarFunction::Btrim => utf8_to_str_type(&input_expr_types[0], "btrim"),+ BuiltinScalarFunction::CharacterLength => {+ utf8_to_int_type(&input_expr_types[0], "character_length")+ }+ BuiltinScalarFunction::Chr => Ok(DataType::Utf8),+ BuiltinScalarFunction::Coalesce => {+ // COALESCE has multiple args and they might get coerced, get a preview of this+ let coerced_types = data_types(input_expr_types, &signature(fun));+ coerced_types.map(|types| types[0].clone())+ }+ BuiltinScalarFunction::Concat => Ok(DataType::Utf8),+ BuiltinScalarFunction::ConcatWithSeparator => Ok(DataType::Utf8),+ BuiltinScalarFunction::DatePart => Ok(DataType::Int32),+ BuiltinScalarFunction::DateTrunc => {+ Ok(DataType::Timestamp(TimeUnit::Nanosecond, None))+ }+ BuiltinScalarFunction::InitCap => {+ utf8_to_str_type(&input_expr_types[0], "initcap")+ }+ BuiltinScalarFunction::Left => utf8_to_str_type(&input_expr_types[0], "left"),+ BuiltinScalarFunction::Lower => utf8_to_str_type(&input_expr_types[0], "lower"),+ BuiltinScalarFunction::Lpad => utf8_to_str_type(&input_expr_types[0], "lpad"),+ BuiltinScalarFunction::Ltrim => utf8_to_str_type(&input_expr_types[0], "ltrim"),+ BuiltinScalarFunction::MD5 => utf8_to_str_type(&input_expr_types[0], "md5"),+ BuiltinScalarFunction::NullIf => {+ // NULLIF has two args and they might get coerced, get a preview of this+ let coerced_types = data_types(input_expr_types, &signature(fun));+ coerced_types.map(|typs| typs[0].clone())+ }+ BuiltinScalarFunction::OctetLength => {+ utf8_to_int_type(&input_expr_types[0], "octet_length")+ }+ BuiltinScalarFunction::Random => Ok(DataType::Float64),+ BuiltinScalarFunction::RegexpReplace => {+ utf8_to_str_type(&input_expr_types[0], "regex_replace")+ }+ BuiltinScalarFunction::Repeat => utf8_to_str_type(&input_expr_types[0], "repeat"),+ BuiltinScalarFunction::Replace => {+ utf8_to_str_type(&input_expr_types[0], "replace")+ }+ BuiltinScalarFunction::Reverse => {+ utf8_to_str_type(&input_expr_types[0], "reverse")+ }+ BuiltinScalarFunction::Right => utf8_to_str_type(&input_expr_types[0], "right"),+ BuiltinScalarFunction::Rpad => utf8_to_str_type(&input_expr_types[0], "rpad"),+ BuiltinScalarFunction::Rtrim => utf8_to_str_type(&input_expr_types[0], "rtrimp"),+ BuiltinScalarFunction::SHA224 => {+ utf8_to_binary_type(&input_expr_types[0], "sha224")+ }+ BuiltinScalarFunction::SHA256 => {+ utf8_to_binary_type(&input_expr_types[0], "sha256")+ }+ BuiltinScalarFunction::SHA384 => {+ utf8_to_binary_type(&input_expr_types[0], "sha384")+ }+ BuiltinScalarFunction::SHA512 => {+ utf8_to_binary_type(&input_expr_types[0], "sha512")+ }+ BuiltinScalarFunction::Digest => {+ utf8_to_binary_type(&input_expr_types[0], "digest")+ }+ BuiltinScalarFunction::SplitPart => {+ utf8_to_str_type(&input_expr_types[0], "split_part")+ }+ BuiltinScalarFunction::StartsWith => Ok(DataType::Boolean),+ BuiltinScalarFunction::Strpos => utf8_to_int_type(&input_expr_types[0], "strpos"),+ BuiltinScalarFunction::Substr => utf8_to_str_type(&input_expr_types[0], "substr"),+ BuiltinScalarFunction::ToHex => Ok(match input_expr_types[0] {+ DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 => {+ DataType::Utf8+ }+ _ => {+ // this error is internal as `data_types` should have captured this.+ return Err(DataFusionError::Internal(+ "The to_hex function can only accept integers.".to_string(),+ ));+ }+ }),+ BuiltinScalarFunction::ToTimestamp => {+ Ok(DataType::Timestamp(TimeUnit::Nanosecond, None))+ }+ BuiltinScalarFunction::ToTimestampMillis => {+ Ok(DataType::Timestamp(TimeUnit::Millisecond, None))+ }+ BuiltinScalarFunction::ToTimestampMicros => {+ Ok(DataType::Timestamp(TimeUnit::Microsecond, None))+ }+ BuiltinScalarFunction::ToTimestampSeconds => {+ Ok(DataType::Timestamp(TimeUnit::Second, None))+ }+ BuiltinScalarFunction::Now => Ok(DataType::Timestamp(+ TimeUnit::Nanosecond,+ Some("UTC".to_owned()),+ )),+ BuiltinScalarFunction::Translate => {+ utf8_to_str_type(&input_expr_types[0], "translate")+ }+ BuiltinScalarFunction::Trim => utf8_to_str_type(&input_expr_types[0], "trim"),+ BuiltinScalarFunction::Upper => utf8_to_str_type(&input_expr_types[0], "upper"),+ BuiltinScalarFunction::RegexpMatch => Ok(match input_expr_types[0] {+ DataType::LargeUtf8 => {+ DataType::List(Box::new(Field::new("item", DataType::LargeUtf8, true)))+ }+ DataType::Utf8 => {+ DataType::List(Box::new(Field::new("item", DataType::Utf8, true)))+ }+ _ => {+ // this error is internal as `data_types` should have captured this.+ return Err(DataFusionError::Internal(+ "The regexp_extract function can only accept strings.".to_string(),+ ));+ }+ }),++ BuiltinScalarFunction::Abs+ | BuiltinScalarFunction::Acos+ | BuiltinScalarFunction::Asin+ | BuiltinScalarFunction::Atan+ | BuiltinScalarFunction::Ceil+ | BuiltinScalarFunction::Cos+ | BuiltinScalarFunction::Exp+ | BuiltinScalarFunction::Floor+ | BuiltinScalarFunction::Log+ | BuiltinScalarFunction::Ln+ | BuiltinScalarFunction::Log10+ | BuiltinScalarFunction::Log2+ | BuiltinScalarFunction::Round+ | BuiltinScalarFunction::Signum+ | BuiltinScalarFunction::Sin+ | BuiltinScalarFunction::Sqrt+ | BuiltinScalarFunction::Tan+ | BuiltinScalarFunction::Trunc => match input_expr_types[0] {+ DataType::Float32 => Ok(DataType::Float32),+ _ => Ok(DataType::Float64),+ },+ }+}++/// the signatures supported by the function `fun`.+pub fn signature(fun: &BuiltinScalarFunction) -> Signature {+ // note: the physical expression must accept the type returned by this function or the execution panics.++ // for now, the list is small, as we do not have many built-in functions.+ match fun {+ BuiltinScalarFunction::Array => Signature::variadic(+ array_expressions::SUPPORTED_ARRAY_TYPES.to_vec(),+ fun.volatility(),+ ),+ BuiltinScalarFunction::Concat | BuiltinScalarFunction::ConcatWithSeparator => {+ Signature::variadic(vec![DataType::Utf8], fun.volatility())+ }+ BuiltinScalarFunction::Coalesce => Signature::variadic(+ conditional_expressions::SUPPORTED_COALESCE_TYPES.to_vec(),+ fun.volatility(),+ ),+ BuiltinScalarFunction::Ascii+ | BuiltinScalarFunction::BitLength+ | BuiltinScalarFunction::CharacterLength+ | BuiltinScalarFunction::InitCap+ | BuiltinScalarFunction::Lower+ | BuiltinScalarFunction::MD5+ | BuiltinScalarFunction::OctetLength+ | BuiltinScalarFunction::Reverse+ | BuiltinScalarFunction::SHA224+ | BuiltinScalarFunction::SHA256+ | BuiltinScalarFunction::SHA384+ | BuiltinScalarFunction::SHA512+ | BuiltinScalarFunction::Trim+ | BuiltinScalarFunction::Upper => Signature::uniform(+ 1,+ vec![DataType::Utf8, DataType::LargeUtf8],+ fun.volatility(),+ ),+ BuiltinScalarFunction::Btrim+ | BuiltinScalarFunction::Ltrim+ | BuiltinScalarFunction::Rtrim => Signature::one_of(+ vec![+ TypeSignature::Exact(vec![DataType::Utf8]),+ TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8]),+ ],+ fun.volatility(),+ ),+ BuiltinScalarFunction::Chr | BuiltinScalarFunction::ToHex => {+ Signature::uniform(1, vec![DataType::Int64], fun.volatility())+ }+ BuiltinScalarFunction::Lpad | BuiltinScalarFunction::Rpad => Signature::one_of(+ vec![+ TypeSignature::Exact(vec![DataType::Utf8, DataType::Int64]),+ TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Int64]),+ TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::Int64,+ DataType::Utf8,+ ]),+ TypeSignature::Exact(vec![+ DataType::LargeUtf8,+ DataType::Int64,+ DataType::Utf8,+ ]),+ TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::Int64,+ DataType::LargeUtf8,+ ]),+ TypeSignature::Exact(vec![+ DataType::LargeUtf8,+ DataType::Int64,+ DataType::LargeUtf8,+ ]),+ ],+ fun.volatility(),+ ),+ BuiltinScalarFunction::Left+ | BuiltinScalarFunction::Repeat+ | BuiltinScalarFunction::Right => Signature::one_of(+ vec![+ TypeSignature::Exact(vec![DataType::Utf8, DataType::Int64]),+ TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Int64]),+ ],+ fun.volatility(),+ ),+ BuiltinScalarFunction::ToTimestamp => Signature::uniform(+ 1,+ vec![+ DataType::Utf8,+ DataType::Int64,+ DataType::Timestamp(TimeUnit::Millisecond, None),+ DataType::Timestamp(TimeUnit::Microsecond, None),+ DataType::Timestamp(TimeUnit::Second, None),+ ],+ fun.volatility(),+ ),+ BuiltinScalarFunction::ToTimestampMillis => Signature::uniform(+ 1,+ vec![+ DataType::Utf8,+ DataType::Int64,+ DataType::Timestamp(TimeUnit::Nanosecond, None),+ DataType::Timestamp(TimeUnit::Microsecond, None),+ DataType::Timestamp(TimeUnit::Second, None),+ ],+ fun.volatility(),+ ),+ BuiltinScalarFunction::ToTimestampMicros => Signature::uniform(+ 1,+ vec![+ DataType::Utf8,+ DataType::Int64,+ DataType::Timestamp(TimeUnit::Nanosecond, None),+ DataType::Timestamp(TimeUnit::Millisecond, None),+ DataType::Timestamp(TimeUnit::Second, None),+ ],+ fun.volatility(),+ ),+ BuiltinScalarFunction::ToTimestampSeconds => Signature::uniform(+ 1,+ vec![+ DataType::Utf8,+ DataType::Int64,+ DataType::Timestamp(TimeUnit::Nanosecond, None),+ DataType::Timestamp(TimeUnit::Microsecond, None),+ DataType::Timestamp(TimeUnit::Millisecond, None),+ ],+ fun.volatility(),+ ),+ BuiltinScalarFunction::Digest => {+ Signature::exact(vec![DataType::Utf8, DataType::Utf8], fun.volatility())+ }+ BuiltinScalarFunction::DateTrunc => Signature::exact(+ vec![+ DataType::Utf8,+ DataType::Timestamp(TimeUnit::Nanosecond, None),+ ],+ fun.volatility(),+ ),+ BuiltinScalarFunction::DatePart => Signature::one_of(+ vec![+ TypeSignature::Exact(vec![DataType::Utf8, DataType::Date32]),+ TypeSignature::Exact(vec![DataType::Utf8, DataType::Date64]),+ TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::Timestamp(TimeUnit::Second, None),+ ]),+ TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::Timestamp(TimeUnit::Microsecond, None),+ ]),+ TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::Timestamp(TimeUnit::Millisecond, None),+ ]),+ TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::Timestamp(TimeUnit::Nanosecond, None),+ ]),+ ],+ fun.volatility(),+ ),+ BuiltinScalarFunction::SplitPart => Signature::one_of(+ vec![+ TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::Utf8,+ DataType::Int64,+ ]),+ TypeSignature::Exact(vec![+ DataType::LargeUtf8,+ DataType::Utf8,+ DataType::Int64,+ ]),+ TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::LargeUtf8,+ DataType::Int64,+ ]),+ TypeSignature::Exact(vec![+ DataType::LargeUtf8,+ DataType::LargeUtf8,+ DataType::Int64,+ ]),+ ],+ fun.volatility(),+ ),++ BuiltinScalarFunction::Strpos | BuiltinScalarFunction::StartsWith => {+ Signature::one_of(+ vec![+ TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8]),+ TypeSignature::Exact(vec![DataType::Utf8, DataType::LargeUtf8]),+ TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Utf8]),+ TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::LargeUtf8]),+ ],+ fun.volatility(),+ )+ }++ BuiltinScalarFunction::Substr => Signature::one_of(+ vec![+ TypeSignature::Exact(vec![DataType::Utf8, DataType::Int64]),+ TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Int64]),+ TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::Int64,+ DataType::Int64,+ ]),+ TypeSignature::Exact(vec![+ DataType::LargeUtf8,+ DataType::Int64,+ DataType::Int64,+ ]),+ ],+ fun.volatility(),+ ),++ BuiltinScalarFunction::Replace | BuiltinScalarFunction::Translate => {+ Signature::one_of(+ vec![TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::Utf8,+ DataType::Utf8,+ ])],+ fun.volatility(),+ )+ }+ BuiltinScalarFunction::RegexpReplace => Signature::one_of(+ vec![+ TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::Utf8,+ DataType::Utf8,+ ]),+ TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::Utf8,+ DataType::Utf8,+ DataType::Utf8,+ ]),+ ],+ fun.volatility(),+ ),++ BuiltinScalarFunction::NullIf => {+ Signature::uniform(2, SUPPORTED_NULLIF_TYPES.to_vec(), fun.volatility())+ }+ BuiltinScalarFunction::RegexpMatch => Signature::one_of(+ vec![+ TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8]),+ TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Utf8]),+ TypeSignature::Exact(vec![+ DataType::Utf8,+ DataType::Utf8,+ DataType::Utf8,+ ]),+ TypeSignature::Exact(vec![+ DataType::LargeUtf8,+ DataType::Utf8,+ DataType::Utf8,+ ]),+ ],+ fun.volatility(),+ ),+ BuiltinScalarFunction::Random => Signature::exact(vec![], fun.volatility()),+ // math expressions expect 1 argument of type f64 or f32+ // priority is given to f64 because e.g. `sqrt(1i32)` is in IR (real numbers) and thus we+ // return the best approximation for it (in f64).+ // We accept f32 because in this case it is clear that the best approximation+ // will be as good as the number of digits in the number+ _ => Signature::uniform(+ 1,+ vec![DataType::Float64, DataType::Float32],+ fun.volatility(),+ ),+ }+}diff --git a/datafusion/expr/src/lib.rs b/datafusion/expr/src/lib.rsindex b5709d305a..e6220e96c0 100644--- a/datafusion/expr/src/lib.rs+++ b/datafusion/expr/src/lib.rs@@ -16,20 +16,25 @@// under the License.mod accumulator;-mod aggregate_function;+pub mod aggregate_function;+pub mod array_expressions;+pub mod binary_rule;mod built_in_function;mod columnar_value;+pub mod conditional_expressions;pub mod expr;pub mod expr_fn;pub mod field_util;-mod function;+pub mod function;mod literal;+mod nullif;mod operator;mod signature;+pub mod type_coercion;mod udaf;mod udf;-mod window_frame;-mod window_function;+pub mod window_frame;+pub mod window_function;pub use accumulator::Accumulator;pub use aggregate_function::AggregateFunction;@@ -42,6 +47,7 @@ pub use function::{StateTypeFunction,};pub use literal::{lit, lit_timestamp_nano, Literal, TimestampLiteral};+pub use nullif::SUPPORTED_NULLIF_TYPES;pub use operator::Operator;pub use signature::{Signature, TypeSignature, Volatility};pub use udaf::AggregateUDF;diff --git a/datafusion/expr/src/nullif.rs b/datafusion/expr/src/nullif.rsnew file mode 100644index 0000000000..d2ed042062--- /dev/null+++ b/datafusion/expr/src/nullif.rs@@ -0,0 +1,35 @@+// 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.++use arrow::datatypes::DataType;++/// Currently supported types by the nullif function.+/// The order of these types correspond to the order on which coercion applies+/// This should thus be from least informative to most informative+pub static SUPPORTED_NULLIF_TYPES: &[DataType] = &[+ DataType::Boolean,+ DataType::UInt8,+ DataType::UInt16,+ DataType::UInt32,+ DataType::UInt64,+ DataType::Int8,+ DataType::Int16,+ DataType::Int32,+ DataType::Int64,+ DataType::Float32,+ DataType::Float64,+];diff --git a/datafusion/expr/src/type_coercion.rs b/datafusion/expr/src/type_coercion.rsnew file mode 100644index 0000000000..5b8b303611--- /dev/null+++ b/datafusion/expr/src/type_coercion.rs@@ -0,0 +1,244 @@+// 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.++//! Type coercion rules for functions with multiple valid signatures+//!+//! Coercion is performed automatically by DataFusion when the types+//! of arguments passed to a function do not exacty match the types+//! required by that function. In this case, DataFusion will attempt to+//! *coerce* the arguments to types accepted by the function by+//! inserting CAST operations.+//!+//! CAST operations added by coercion are lossless and never discard+//! information. For example coercion from i32 -> i64 might be+//! performed because all valid i32 values can be represented using an+//! i64. However, i64 -> i32 is never performed as there are i64+//! values which can not be represented by i32 values.+//!++use crate::{Signature, TypeSignature};+use arrow::datatypes::{DataType, TimeUnit};+use datafusion_common::{DataFusionError, Result};++/// Returns the data types that each argument must be coerced to match+/// `signature`.+///+/// See the module level documentation for more detail on coercion.+pub fn data_types(+ current_types: &[DataType],+ signature: &Signature,+) -> Result<Vec<DataType>> {+ if current_types.is_empty() {+ return Ok(vec![]);+ }+ let valid_types = get_valid_types(&signature.type_signature, current_types)?;++ if valid_types+ .iter()+ .any(|data_type| data_type == current_types)+ {+ return Ok(current_types.to_vec());+ }++ for valid_types in valid_types {+ if let Some(types) = maybe_data_types(&valid_types, current_types) {+ return Ok(types);+ }+ }++ // none possible -> Error+ Err(DataFusionError::Plan(format!(+ "Coercion from {:?} to the signature {:?} failed.",+ current_types, &signature.type_signature+ )))+}++fn get_valid_types(+ signature: &TypeSignature,+ current_types: &[DataType],+) -> Result<Vec<Vec<DataType>>> {+ let valid_types = match signature {+ TypeSignature::Variadic(valid_types) => valid_types+ .iter()+ .map(|valid_type| current_types.iter().map(|_| valid_type.clone()).collect())+ .collect(),+ TypeSignature::Uniform(number, valid_types) => valid_types+ .iter()+ .map(|valid_type| (0..*number).map(|_| valid_type.clone()).collect())+ .collect(),+ TypeSignature::VariadicEqual => {+ // one entry with the same len as current_types, whose type is `current_types[0]`.+ vec![current_types+ .iter()+ .map(|_| current_types[0].clone())+ .collect()]+ }+ TypeSignature::Exact(valid_types) => vec![valid_types.clone()],+ TypeSignature::Any(number) => {+ if current_types.len() != *number {+ return Err(DataFusionError::Plan(format!(+ "The function expected {} arguments but received {}",+ number,+ current_types.len()+ )));+ }+ vec![(0..*number).map(|i| current_types[i].clone()).collect()]+ }+ TypeSignature::OneOf(types) => types+ .iter()+ .filter_map(|t| get_valid_types(t, current_types).ok())+ .flatten()+ .collect::<Vec<_>>(),+ };++ Ok(valid_types)+}++/// Try to coerce current_types into valid_types.+fn maybe_data_types(+ valid_types: &[DataType],+ current_types: &[DataType],+) -> Option<Vec<DataType>> {+ if valid_types.len() != current_types.len() {+ return None;+ }++ let mut new_type = Vec::with_capacity(valid_types.len());+ for (i, valid_type) in valid_types.iter().enumerate() {+ let current_type = ¤t_types[i];++ if current_type == valid_type {+ new_type.push(current_type.clone())+ } else {+ // attempt to coerce+ if can_coerce_from(valid_type, current_type) {+ new_type.push(valid_type.clone())+ } else {+ // not possible+ return None;+ }+ }+ }+ Some(new_type)+}++/// Return true if a value of type `type_from` can be coerced+/// (losslessly converted) into a value of `type_to`+///+/// See the module level documentation for more detail on coercion.+pub fn can_coerce_from(type_into: &DataType, type_from: &DataType) -> bool {+ use self::DataType::*;+ match type_into {+ Int8 => matches!(type_from, Int8),+ Int16 => matches!(type_from, Int8 | Int16 | UInt8),+ Int32 => matches!(type_from, Int8 | Int16 | Int32 | UInt8 | UInt16),+ Int64 => matches!(+ type_from,+ Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32+ ),+ UInt8 => matches!(type_from, UInt8),+ UInt16 => matches!(type_from, UInt8 | UInt16),+ UInt32 => matches!(type_from, UInt8 | UInt16 | UInt32),+ UInt64 => matches!(type_from, UInt8 | UInt16 | UInt32 | UInt64),+ Float32 => matches!(+ type_from,+ Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64 | Float32+ ),+ Float64 => matches!(+ type_from,+ Int8 | Int16+ | Int32+ | Int64+ | UInt8+ | UInt16+ | UInt32+ | UInt64+ | Float32+ | Float64+ ),+ Timestamp(TimeUnit::Nanosecond, None) => matches!(type_from, Timestamp(_, None)),+ Utf8 | LargeUtf8 => true,+ _ => false,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use arrow::datatypes::DataType;++ #[test]+ fn test_maybe_data_types() {+ // this vec contains: arg1, arg2, expected result+ let cases = vec![+ // 2 entries, same values+ (+ vec![DataType::UInt8, DataType::UInt16],+ vec![DataType::UInt8, DataType::UInt16],+ Some(vec![DataType::UInt8, DataType::UInt16]),+ ),+ // 2 entries, can coerse values+ (+ vec![DataType::UInt16, DataType::UInt16],+ vec![DataType::UInt8, DataType::UInt16],+ Some(vec![DataType::UInt16, DataType::UInt16]),+ ),+ // 0 entries, all good+ (vec![], vec![], Some(vec![])),+ // 2 entries, can't coerce+ (+ vec![DataType::Boolean, DataType::UInt16],+ vec![DataType::UInt8, DataType::UInt16],+ None,+ ),+ // u32 -> u16 is possible+ (+ vec![DataType::Boolean, DataType::UInt32],+ vec![DataType::Boolean, DataType::UInt16],+ Some(vec![DataType::Boolean, DataType::UInt32]),+ ),+ ];++ for case in cases {+ assert_eq!(maybe_data_types(&case.0, &case.1), case.2)+ }+ }++ #[test]+ fn test_get_valid_types_one_of() -> Result<()> {+ let signature =+ TypeSignature::OneOf(vec![TypeSignature::Any(1), TypeSignature::Any(2)]);++ let invalid_types = get_valid_types(+ &signature,+ &[DataType::Int32, DataType::Int32, DataType::Int32],+ )?;+ assert_eq!(invalid_types.len(), 0);++ let args = vec![DataType::Int32, DataType::Int32];+ let valid_types = get_valid_types(&signature, &args)?;+ assert_eq!(valid_types.len(), 1);+ assert_eq!(valid_types[0], args);++ let args = vec![DataType::Int32];+ let valid_types = get_valid_types(&signature, &args)?;+ assert_eq!(valid_types.len(), 1);+ assert_eq!(valid_types[0], args);++ Ok(())+ }+}diff --git a/datafusion/expr/src/window_function.rs b/datafusion/expr/src/window_function.rsindex cdb4a158e1..e3daa0922f 100644--- a/datafusion/expr/src/window_function.rs+++ b/datafusion/expr/src/window_function.rs@@ -15,10 +15,16 @@// specific language governing permissions and limitations// under the License.-//! Window function module contains foundational types that are used to represent window functions-//! in DataFusion.+//! Window functions provide the ability to perform calculations across+//! sets of rows that are related to the current query row.+//!+//! see also <https://www.postgresql.org/docs/current/functions-window.html>+//!use crate::aggregate_function::AggregateFunction;+use crate::type_coercion::data_types;+use crate::{aggregate_function, Signature, TypeSignature, Volatility};+use arrow::datatypes::DataType;use datafusion_common::{DataFusionError, Result};use std::{fmt, str::FromStr};@@ -135,9 +141,177 @@ impl FromStr for BuiltInWindowFunction {}}+/// Returns the datatype of the window function+pub fn return_type(+ fun: &WindowFunction,+ input_expr_types: &[DataType],+) -> Result<DataType> {+ match fun {+ WindowFunction::AggregateFunction(fun) => {+ aggregate_function::return_type(fun, input_expr_types)+ }+ WindowFunction::BuiltInWindowFunction(fun) => {+ return_type_for_built_in(fun, input_expr_types)+ }+ }+}++/// Returns the datatype of the built-in window function+fn return_type_for_built_in(+ fun: &BuiltInWindowFunction,+ input_expr_types: &[DataType],+) -> Result<DataType> {+ // Note that this function *must* return the same type that the respective physical expression returns+ // or the execution panics.++ // verify that this is a valid set of data types for this function+ data_types(input_expr_types, &signature_for_built_in(fun))?;++ match fun {+ BuiltInWindowFunction::RowNumber+ | BuiltInWindowFunction::Rank+ | BuiltInWindowFunction::DenseRank => Ok(DataType::UInt64),+ BuiltInWindowFunction::PercentRank | BuiltInWindowFunction::CumeDist => {+ Ok(DataType::Float64)+ }+ BuiltInWindowFunction::Ntile => Ok(DataType::UInt32),+ BuiltInWindowFunction::Lag+ | BuiltInWindowFunction::Lead+ | BuiltInWindowFunction::FirstValue+ | BuiltInWindowFunction::LastValue+ | BuiltInWindowFunction::NthValue => Ok(input_expr_types[0].clone()),+ }+}++/// the signatures supported by the function `fun`.+pub fn signature(fun: &WindowFunction) -> Signature {+ match fun {+ WindowFunction::AggregateFunction(fun) => aggregate_function::signature(fun),+ WindowFunction::BuiltInWindowFunction(fun) => signature_for_built_in(fun),+ }+}++/// the signatures supported by the built-in window function `fun`.+pub fn signature_for_built_in(fun: &BuiltInWindowFunction) -> Signature {+ // note: the physical expression must accept the type returned by this function or the execution panics.+ match fun {+ BuiltInWindowFunction::RowNumber+ | BuiltInWindowFunction::Rank+ | BuiltInWindowFunction::DenseRank+ | BuiltInWindowFunction::PercentRank+ | BuiltInWindowFunction::CumeDist => Signature::any(0, Volatility::Immutable),+ BuiltInWindowFunction::Lag | BuiltInWindowFunction::Lead => Signature::one_of(+ vec![+ TypeSignature::Any(1),+ TypeSignature::Any(2),+ TypeSignature::Any(3),+ ],+ Volatility::Immutable,+ ),+ BuiltInWindowFunction::FirstValue | BuiltInWindowFunction::LastValue => {+ Signature::any(1, Volatility::Immutable)+ }+ BuiltInWindowFunction::Ntile => {+ Signature::exact(vec![DataType::UInt64], Volatility::Immutable)+ }+ BuiltInWindowFunction::NthValue => Signature::any(2, Volatility::Immutable),+ }+}+#[cfg(test)]mod tests {use super::*;+ use std::str::FromStr;++ #[test]+ fn test_count_return_type() -> Result<()> {+ let fun = WindowFunction::from_str("count")?;+ let observed = return_type(&fun, &[DataType::Utf8])?;+ assert_eq!(DataType::UInt64, observed);++ let observed = return_type(&fun, &[DataType::UInt64])?;+ assert_eq!(DataType::UInt64, observed);++ Ok(())+ }++ #[test]+ fn test_first_value_return_type() -> Result<()> {+ let fun = WindowFunction::from_str("first_value")?;+ let observed = return_type(&fun, &[DataType::Utf8])?;+ assert_eq!(DataType::Utf8, observed);++ let observed = return_type(&fun, &[DataType::UInt64])?;+ assert_eq!(DataType::UInt64, observed);++ Ok(())+ }++ #[test]+ fn test_last_value_return_type() -> Result<()> {+ let fun = WindowFunction::from_str("last_value")?;+ let observed = return_type(&fun, &[DataType::Utf8])?;+ assert_eq!(DataType::Utf8, observed);++ let observed = return_type(&fun, &[DataType::Float64])?;+ assert_eq!(DataType::Float64, observed);++ Ok(())+ }++ #[test]+ fn test_lead_return_type() -> Result<()> {+ let fun = WindowFunction::from_str("lead")?;+ let observed = return_type(&fun, &[DataType::Utf8])?;+ assert_eq!(DataType::Utf8, observed);++ let observed = return_type(&fun, &[DataType::Float64])?;+ assert_eq!(DataType::Float64, observed);++ Ok(())+ }++ #[test]+ fn test_lag_return_type() -> Result<()> {+ let fun = WindowFunction::from_str("lag")?;+ let observed = return_type(&fun, &[DataType::Utf8])?;+ assert_eq!(DataType::Utf8, observed);++ let observed = return_type(&fun, &[DataType::Float64])?;+ assert_eq!(DataType::Float64, observed);++ Ok(())+ }++ #[test]+ fn test_nth_value_return_type() -> Result<()> {+ let fun = WindowFunction::from_str("nth_value")?;+ let observed = return_type(&fun, &[DataType::Utf8, DataType::UInt64])?;+ assert_eq!(DataType::Utf8, observed);++ let observed = return_type(&fun, &[DataType::Float64, DataType::UInt64])?;+ assert_eq!(DataType::Float64, observed);++ Ok(())+ }++ #[test]+ fn test_percent_rank_return_type() -> Result<()> {+ let fun = WindowFunction::from_str("percent_rank")?;+ let observed = return_type(&fun, &[])?;+ assert_eq!(DataType::Float64, observed);++ Ok(())+ }++ #[test]+ fn test_cume_dist_return_type() -> Result<()> {+ let fun = WindowFunction::from_str("cume_dist")?;+ let observed = return_type(&fun, &[])?;+ assert_eq!(DataType::Float64, observed);++ Ok(())+ }#[test]fn test_window_function_case_insensitive() -> Result<()> {diff --git a/datafusion/physical-expr/src/array_expressions.rs b/datafusion/physical-expr/src/array_expressions.rsindex ca396d0b7b..cf220149f5 100644--- a/datafusion/physical-expr/src/array_expressions.rs+++ b/datafusion/physical-expr/src/array_expressions.rs@@ -105,22 +105,3 @@ pub fn array(values: &[ColumnarValue]) -> Result<ColumnarValue> {Ok(ColumnarValue::Array(array_array(&arrays)?))}--/// Currently supported types by the array function.-/// The order of these types correspond to the order on which coercion applies-/// This should thus be from least informative to most informative-pub static SUPPORTED_ARRAY_TYPES: &[DataType] = &[- DataType::Boolean,- DataType::UInt8,- DataType::UInt16,- DataType::UInt32,- DataType::UInt64,- DataType::Int8,- DataType::Int16,- DataType::Int32,- DataType::Int64,- DataType::Float32,- DataType::Float64,- DataType::Utf8,- DataType::LargeUtf8,-];diff --git a/datafusion/physical-expr/src/coercion_rule/aggregate_rule.rs b/datafusion/physical-expr/src/coercion_rule/aggregate_rule.rsindex 9b3920ddfd..7cf9c0301f 100644--- a/datafusion/physical-expr/src/coercion_rule/aggregate_rule.rs+++ b/datafusion/physical-expr/src/coercion_rule/aggregate_rule.rs@@ -17,243 +17,13 @@//! Support the coercion rule for aggregate function.-use crate::expressions::{- is_approx_percentile_cont_supported_arg_type, is_avg_support_arg_type,- is_correlation_support_arg_type, is_covariance_support_arg_type,- is_stddev_support_arg_type, is_sum_support_arg_type, is_variance_support_arg_type,- try_cast,-};+use crate::expressions::try_cast;use crate::PhysicalExpr;-use arrow::datatypes::DataType;use arrow::datatypes::Schema;-use datafusion_common::{DataFusionError, Result};-use datafusion_expr::AggregateFunction;-use datafusion_expr::{Signature, TypeSignature};-use std::ops::Deref;+use datafusion_common::Result;+use datafusion_expr::{aggregate_function, AggregateFunction, Signature};use std::sync::Arc;-/// Returns the coerced data type for each `input_types`.-/// Different aggregate function with different input data type will get corresponding coerced data type.-pub fn coerce_types(- agg_fun: &AggregateFunction,- input_types: &[DataType],- signature: &Signature,-) -> Result<Vec<DataType>> {- // Validate input_types matches (at least one of) the func signature.- check_arg_count(agg_fun, input_types, &signature.type_signature)?;-- match agg_fun {- AggregateFunction::Count | AggregateFunction::ApproxDistinct => {- Ok(input_types.to_vec())- }- AggregateFunction::ArrayAgg => Ok(input_types.to_vec()),- AggregateFunction::Min | AggregateFunction::Max => {- // min and max support the dictionary data type- // unpack the dictionary to get the value- get_min_max_result_type(input_types)- }- AggregateFunction::Sum => {- // Refer to https://www.postgresql.org/docs/8.2/functions-aggregate.html doc- // smallint, int, bigint, real, double precision, decimal, or interval.- if !is_sum_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));- }- Ok(input_types.to_vec())- }- AggregateFunction::Avg => {- // Refer to https://www.postgresql.org/docs/8.2/functions-aggregate.html doc- // smallint, int, bigint, real, double precision, decimal, or interval- if !is_avg_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));- }- Ok(input_types.to_vec())- }- AggregateFunction::Variance => {- if !is_variance_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));- }- Ok(input_types.to_vec())- }- AggregateFunction::VariancePop => {- if !is_variance_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));- }- Ok(input_types.to_vec())- }- AggregateFunction::Covariance => {- if !is_covariance_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));- }- Ok(input_types.to_vec())- }- AggregateFunction::CovariancePop => {- if !is_covariance_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));- }- Ok(input_types.to_vec())- }- AggregateFunction::Stddev => {- if !is_stddev_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));- }- Ok(input_types.to_vec())- }- AggregateFunction::StddevPop => {- if !is_stddev_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));- }- Ok(input_types.to_vec())- }- AggregateFunction::Correlation => {- if !is_correlation_support_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));- }- Ok(input_types.to_vec())- }- AggregateFunction::ApproxPercentileCont => {- if !is_approx_percentile_cont_supported_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));- }- if !matches!(input_types[1], DataType::Float64) {- return Err(DataFusionError::Plan(format!(- "The percentile argument for {:?} must be Float64, not {:?}.",- agg_fun, input_types[1]- )));- }- Ok(input_types.to_vec())- }- AggregateFunction::ApproxPercentileContWithWeight => {- if !is_approx_percentile_cont_supported_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));- }- if !is_approx_percentile_cont_supported_arg_type(&input_types[1]) {- return Err(DataFusionError::Plan(format!(- "The weight argument for {:?} does not support inputs of type {:?}.",- agg_fun, input_types[1]- )));- }- if !matches!(input_types[2], DataType::Float64) {- return Err(DataFusionError::Plan(format!(- "The percentile argument for {:?} must be Float64, not {:?}.",- agg_fun, input_types[2]- )));- }- Ok(input_types.to_vec())- }- AggregateFunction::ApproxMedian => {- if !is_approx_percentile_cont_supported_arg_type(&input_types[0]) {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not support inputs of type {:?}.",- agg_fun, input_types[0]- )));- }- Ok(input_types.to_vec())- }- }-}--/// Validate the length of `input_types` matches the `signature` for `agg_fun`.-///-/// This method DOES NOT validate the argument types - only that (at least one,-/// in the case of [`TypeSignature::OneOf`]) signature matches the desired-/// number of input types.-fn check_arg_count(- agg_fun: &AggregateFunction,- input_types: &[DataType],- signature: &TypeSignature,-) -> Result<()> {- match signature {- TypeSignature::Uniform(agg_count, _) | TypeSignature::Any(agg_count) => {- if input_types.len() != *agg_count {- return Err(DataFusionError::Plan(format!(- "The function {:?} expects {:?} arguments, but {:?} were provided",- agg_fun,- agg_count,- input_types.len()- )));- }- }- TypeSignature::Exact(types) => {- if types.len() != input_types.len() {- return Err(DataFusionError::Plan(format!(- "The function {:?} expects {:?} arguments, but {:?} were provided",- agg_fun,- types.len(),- input_types.len()- )));- }- }- TypeSignature::OneOf(variants) => {- let ok = variants- .iter()- .any(|v| check_arg_count(agg_fun, input_types, v).is_ok());- if !ok {- return Err(DataFusionError::Plan(format!(- "The function {:?} does not accept {:?} function arguments.",- agg_fun,- input_types.len()- )));- }- }- _ => {- return Err(DataFusionError::Internal(format!(- "Aggregate functions do not support this {:?}",- signature- )));- }- }- Ok(())-}--fn get_min_max_result_type(input_types: &[DataType]) -> Result<Vec<DataType>> {- // make sure that the input types only has one element.- assert_eq!(input_types.len(), 1);- // min and max support the dictionary data type- // unpack the dictionary to get the value- match &input_types[0] {- DataType::Dictionary(_, dict_value_type) => {- // TODO add checker, if the value type is complex data type- Ok(vec![dict_value_type.deref().clone()])- }- // TODO add checker for datatype which min and max supported- // For example, the `Struct` and `Map` type are not supported in the MIN and MAX function- _ => Ok(input_types.to_vec()),- }-}-/// Returns the coerced exprs for each `input_exprs`./// Get the coerced data type from `aggregate_rule::coerce_types` and add `try_cast` if the/// data type of `input_exprs` need to be coerced.@@ -272,7 +42,8 @@ pub fn coerce_exprs(.collect::<Result<Vec<_>>>()?;// get the coerced data types- let coerced_types = coerce_types(agg_fun, &input_types, signature)?;+ let coerced_types =+ aggregate_function::coerce_types(agg_fun, &input_types, signature)?;// try cast if needinput_exprsdiff --git a/datafusion/physical-expr/src/coercion_rule/mod.rs b/datafusion/physical-expr/src/coercion_rule/mod.rsindex fa8d4da3c1..0b2df7a84a 100644--- a/datafusion/physical-expr/src/coercion_rule/mod.rs+++ b/datafusion/physical-expr/src/coercion_rule/mod.rs@@ -21,4 +21,3 @@//! Binary operation rulepub mod aggregate_rule;-pub mod binary_rule;diff --git a/datafusion/physical-expr/src/conditional_expressions.rs b/datafusion/physical-expr/src/conditional_expressions.rsindex 4e8675f8e3..09c5b382da 100644--- a/datafusion/physical-expr/src/conditional_expressions.rs+++ b/datafusion/physical-expr/src/conditional_expressions.rs@@ -18,7 +18,6 @@use arrow::array::{new_null_array, Array, BooleanArray};use arrow::compute::kernels::zip::zip;use arrow::compute::{and, is_not_null, is_null};-use arrow::datatypes::DataType;use datafusion_common::{DataFusionError, Result};use datafusion_expr::ColumnarValue;@@ -79,22 +78,3 @@ pub fn coalesce(args: &[ColumnarValue]) -> Result<ColumnarValue> {Ok(result)}}--/// Currently supported types by the coalesce function.-/// The order of these types correspond to the order on which coercion applies-/// This should thus be from least informative to most informative-pub static SUPPORTED_COALESCE_TYPES: &[DataType] = &[- DataType::Boolean,- DataType::UInt8,- DataType::UInt16,- DataType::UInt32,- DataType::UInt64,- DataType::Int8,- DataType::Int16,- DataType::Int32,- DataType::Int64,- DataType::Float32,- DataType::Float64,- DataType::Utf8,- DataType::LargeUtf8,-];diff --git a/datafusion/physical-expr/src/expressions/approx_percentile_cont.rs b/datafusion/physical-expr/src/expressions/approx_percentile_cont.rsindex 36a57093a0..65d478cc74 100644--- a/datafusion/physical-expr/src/expressions/approx_percentile_cont.rs+++ b/datafusion/physical-expr/src/expressions/approx_percentile_cont.rs@@ -35,24 +35,6 @@ use datafusion_expr::Accumulator;use ordered_float::OrderedFloat;use std::{any::Any, iter, sync::Arc};-/// Return `true` if `arg_type` is of a [`DataType`] that the-/// [`ApproxPercentileCont`] aggregation can operate on.-pub fn is_approx_percentile_cont_supported_arg_type(arg_type: &DataType) -> bool {- matches!(- arg_type,- DataType::UInt8- | DataType::UInt16- | DataType::UInt32- | DataType::UInt64- | DataType::Int8- | DataType::Int16- | DataType::Int32- | DataType::Int64- | DataType::Float32- | DataType::Float64- )-}-/// APPROX_PERCENTILE_CONT aggregate expression#[derive(Debug)]pub struct ApproxPercentileCont {diff --git a/datafusion/physical-expr/src/expressions/average.rs b/datafusion/physical-expr/src/expressions/average.rsindex 8888ee9936..5c26e6c9d9 100644--- a/datafusion/physical-expr/src/expressions/average.rs+++ b/datafusion/physical-expr/src/expressions/average.rs@@ -23,7 +23,7 @@ use std::sync::Arc;use crate::{AggregateExpr, PhysicalExpr};use arrow::compute;-use arrow::datatypes::{DataType, DECIMAL_MAX_PRECISION, DECIMAL_MAX_SCALE};+use arrow::datatypes::DataType;use arrow::{array::{ArrayRef, UInt64Array},datatypes::Field,@@ -42,50 +42,6 @@ pub struct Avg {data_type: DataType,}-/// function return type of an average-pub fn avg_return_type(arg_type: &DataType) -> Result<DataType> {- match arg_type {- DataType::Decimal(precision, scale) => {- // in the spark, the result type is DECIMAL(min(38,precision+4), min(38,scale+4)).- // ref: https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Average.scala#L66- let new_precision = DECIMAL_MAX_PRECISION.min(*precision + 4);- let new_scale = DECIMAL_MAX_SCALE.min(*scale + 4);- Ok(DataType::Decimal(new_precision, new_scale))- }- DataType::Int8- | DataType::Int16- | DataType::Int32- | DataType::Int64- | DataType::UInt8- | DataType::UInt16- | DataType::UInt32- | DataType::UInt64- | DataType::Float32- | DataType::Float64 => Ok(DataType::Float64),- other => Err(DataFusionError::Plan(format!(- "AVG does not support {:?}",- other- ))),- }-}--pub fn is_avg_support_arg_type(arg_type: &DataType) -> bool {- matches!(- arg_type,- DataType::UInt8- | DataType::UInt16- | DataType::UInt32- | DataType::UInt64- | DataType::Int8- | DataType::Int16- | DataType::Int32- | DataType::Int64- | DataType::Float32- | DataType::Float64- | DataType::Decimal(_, _)- )-}-impl Avg {/// Create a new AVG aggregate functionpub fn new(@@ -220,18 +176,6 @@ mod tests {use arrow::{array::*, datatypes::*};use datafusion_common::Result;- #[test]- fn test_avg_return_data_type() -> Result<()> {- let data_type = DataType::Decimal(10, 5);- let result_type = avg_return_type(&data_type)?;- assert_eq!(DataType::Decimal(14, 9), result_type);-- let data_type = DataType::Decimal(36, 10);- let result_type = avg_return_type(&data_type)?;- assert_eq!(DataType::Decimal(38, 14), result_type);- Ok(())- }-#[test]fn avg_decimal() -> Result<()> {// test aggdiff --git a/datafusion/physical-expr/src/expressions/binary.rs b/datafusion/physical-expr/src/expressions/binary.rsindex 7b2e82952a..a155fa5eda 100644--- a/datafusion/physical-expr/src/expressions/binary.rs+++ b/datafusion/physical-expr/src/expressions/binary.rs@@ -54,13 +54,12 @@ use arrow::datatypes::{ArrowNumericType, DataType, Schema, TimeUnit};use arrow::error::ArrowError::DivideByZero;use arrow::record_batch::RecordBatch;-use crate::coercion_rule::binary_rule::coerce_types;use crate::expressions::try_cast;use crate::PhysicalExpr;use datafusion_common::ScalarValue;use datafusion_common::{DataFusionError, Result};-use datafusion_expr::ColumnarValue;-use datafusion_expr::Operator;+use datafusion_expr::binary_rule::binary_operator_data_type;+use datafusion_expr::{binary_rule::coerce_types, ColumnarValue, Operator};// TODO move to arrow_rs// https://github.com/apache/arrow-rs/issues/1312@@ -988,50 +987,6 @@ macro_rules! compute_utf8_flag_op_scalar {}};}-/// 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.-///-/// This function makes some assumptions about the underlying available computations.-pub fn binary_operator_data_type(- lhs_type: &DataType,- op: &Operator,- rhs_type: &DataType,-) -> Result<DataType> {- // validate that it is possible to perform the operation on incoming types.- // (or the return datatype cannot be inferred)- let result_type = coerce_types(lhs_type, op, rhs_type)?;-- match op {- // operators that return a boolean- Operator::Eq- | Operator::NotEq- | Operator::And- | Operator::Or- | Operator::Like- | Operator::NotLike- | Operator::Lt- | Operator::Gt- | Operator::GtEq- | Operator::LtEq- | Operator::RegexMatch- | Operator::RegexIMatch- | Operator::RegexNotMatch- | Operator::RegexNotIMatch- | Operator::IsDistinctFrom- | Operator::IsNotDistinctFrom => Ok(DataType::Boolean),- // bitwise operations return the common coerced type- Operator::BitwiseAnd | Operator::BitwiseOr => Ok(result_type),- // math operations return the same value as the common coerced type- Operator::Plus- | Operator::Minus- | Operator::Divide- | Operator::Multiply- | Operator::Modulo => Ok(result_type),- // string operations return the same values as the common coerced type- Operator::StringConcat => Ok(result_type),- }-}-impl PhysicalExpr for BinaryExpr {/// Return a reference to Any that can be used for downcastingfn as_any(&self) -> &dyn Any {diff --git a/datafusion/physical-expr/src/expressions/correlation.rs b/datafusion/physical-expr/src/expressions/correlation.rsindex 3f7b28a902..516dca305b 100644--- a/datafusion/physical-expr/src/expressions/correlation.rs+++ b/datafusion/physical-expr/src/expressions/correlation.rs@@ -22,8 +22,8 @@ use crate::{AggregateExpr, PhysicalExpr,};use arrow::{array::ArrayRef, datatypes::DataType, datatypes::Field};+use datafusion_common::Result;use datafusion_common::ScalarValue;-use datafusion_common::{DataFusionError, Result};use datafusion_expr::Accumulator;use std::any::Any;use std::sync::Arc;@@ -38,42 +38,6 @@ pub struct Correlation {expr2: Arc<dyn PhysicalExpr>,}-/// function return type of correlation-pub fn correlation_return_type(arg_type: &DataType) -> Result<DataType> {- match arg_type {- DataType::Int8- | DataType::Int16- | DataType::Int32- | DataType::Int64- | DataType::UInt8- | DataType::UInt16- | DataType::UInt32- | DataType::UInt64- | DataType::Float32- | DataType::Float64 => Ok(DataType::Float64),- other => Err(DataFusionError::Plan(format!(- "CORR does not support {:?}",- other- ))),- }-}--pub fn is_correlation_support_arg_type(arg_type: &DataType) -> bool {- matches!(- arg_type,- DataType::UInt8- | DataType::UInt16- | DataType::UInt32- | DataType::UInt64- | DataType::Int8- | DataType::Int16- | DataType::Int32- | DataType::Int64- | DataType::Float32- | DataType::Float64- )-}-impl Correlation {/// Create a new COVAR_POP aggregate functionpub fn new(@@ -348,17 +312,6 @@ mod tests {)}- #[test]- fn test_correlation_return_data_type() -> Result<()> {- let data_type = DataType::Float64;- let result_type = correlation_return_type(&data_type)?;- assert_eq!(DataType::Float64, result_type);-- let data_type = DataType::Decimal(36, 10);- assert!(correlation_return_type(&data_type).is_err());- Ok(())- }-#[test]fn correlation_i32_with_nulls_1() -> Result<()> {let a: ArrayRef =diff --git a/datafusion/physical-expr/src/expressions/covariance.rs b/datafusion/physical-expr/src/expressions/covariance.rsindex 539a869be9..dd0895cbac 100644--- a/datafusion/physical-expr/src/expressions/covariance.rs+++ b/datafusion/physical-expr/src/expressions/covariance.rs@@ -50,42 +50,6 @@ pub struct CovariancePop {expr2: Arc<dyn PhysicalExpr>,}-/// function return type of covariance-pub fn covariance_return_type(arg_type: &DataType) -> Result<DataType> {- match arg_type {- DataType::Int8- | DataType::Int16- | DataType::Int32- | DataType::Int64- | DataType::UInt8- | DataType::UInt16- | DataType::UInt32- | DataType::UInt64- | DataType::Float32- | DataType::Float64 => Ok(DataType::Float64),- other => Err(DataFusionError::Plan(format!(- "COVAR does not support {:?}",- other- ))),- }-}--pub fn is_covariance_support_arg_type(arg_type: &DataType) -> bool {- matches!(- arg_type,- DataType::UInt8- | DataType::UInt16- | DataType::UInt32- | DataType::UInt64- | DataType::Int8- | DataType::Int16- | DataType::Int32- | DataType::Int64- | DataType::Float32- | DataType::Float64- )-}-impl Covariance {/// Create a new COVAR aggregate functionpub fn new(@@ -523,17 +487,6 @@ mod tests {)}- #[test]- fn test_covariance_return_data_type() -> Result<()> {- let data_type = DataType::Float64;- let result_type = covariance_return_type(&data_type)?;- assert_eq!(DataType::Float64, result_type);-- let data_type = DataType::Decimal(36, 10);- assert!(covariance_return_type(&data_type).is_err());- Ok(())- }-#[test]fn covariance_i32_with_nulls_1() -> Result<()> {let a: ArrayRef = Arc::new(Int32Array::from(vec![Some(1), None, Some(3)]));diff --git a/datafusion/physical-expr/src/expressions/mod.rs b/datafusion/physical-expr/src/expressions/mod.rsindex 775c4ccd4b..a230e790ff 100644--- a/datafusion/physical-expr/src/expressions/mod.rs+++ b/datafusion/physical-expr/src/expressions/mod.rs@@ -60,26 +60,19 @@ pub mod helpers {pub use approx_distinct::ApproxDistinct;pub use approx_median::ApproxMedian;-pub use approx_percentile_cont::{- is_approx_percentile_cont_supported_arg_type, ApproxPercentileCont,-};+pub use approx_percentile_cont::ApproxPercentileCont;pub use approx_percentile_cont_with_weight::ApproxPercentileContWithWeight;pub use array_agg::ArrayAgg;-pub use average::is_avg_support_arg_type;-pub use average::{avg_return_type, Avg, AvgAccumulator};-pub use binary::{binary, binary_operator_data_type, BinaryExpr};+pub use average::{Avg, AvgAccumulator};+pub use binary::{binary, BinaryExpr};pub use case::{case, CaseExpr};pub use cast::{cast, cast_column, cast_with_options, CastExpr, DEFAULT_DATAFUSION_CAST_OPTIONS,};pub use column::{col, Column};-pub use correlation::{- correlation_return_type, is_correlation_support_arg_type, Correlation,-};+pub use correlation::Correlation;pub use count::Count;-pub use covariance::{- covariance_return_type, is_covariance_support_arg_type, Covariance, CovariancePop,-};+pub use covariance::{Covariance, CovariancePop};pub use cume_dist::cume_dist;pub use distinct_expressions::{DistinctArrayAgg, DistinctCount};@@ -94,17 +87,14 @@ pub use min_max::{MaxAccumulator, MinAccumulator};pub use negative::{negative, NegativeExpr};pub use not::{not, NotExpr};pub use nth_value::NthValue;-pub use nullif::{nullif_func, SUPPORTED_NULLIF_TYPES};+pub use nullif::nullif_func;pub use rank::{dense_rank, percent_rank, rank};pub use row_number::RowNumber;pub use stats::StatsType;-pub use stddev::{is_stddev_support_arg_type, stddev_return_type, Stddev, StddevPop};-pub use sum::is_sum_support_arg_type;-pub use sum::{sum_return_type, Sum};+pub use stddev::{Stddev, StddevPop};+pub use sum::Sum;pub use try_cast::{try_cast, TryCastExpr};-pub use variance::{- is_variance_support_arg_type, variance_return_type, Variance, VariancePop,-};+pub use variance::{Variance, VariancePop};/// returns the name of the statepub fn format_state_name(name: &str, state_name: &str) -> String {diff --git a/datafusion/physical-expr/src/expressions/negative.rs b/datafusion/physical-expr/src/expressions/negative.rsindex 4974bdb329..0887a35006 100644--- a/datafusion/physical-expr/src/expressions/negative.rs+++ b/datafusion/physical-expr/src/expressions/negative.rs@@ -28,10 +28,9 @@ use arrow::{record_batch::RecordBatch,};-use crate::coercion_rule::binary_rule::is_signed_numeric;use crate::PhysicalExpr;use datafusion_common::{DataFusionError, Result};-use datafusion_expr::ColumnarValue;+use datafusion_expr::{binary_rule::is_signed_numeric, ColumnarValue};/// Invoke a compute kernel on array(s)macro_rules! compute_op {diff --git a/datafusion/physical-expr/src/expressions/nullif.rs b/datafusion/physical-expr/src/expressions/nullif.rsindex a078e2228e..307e3a07f3 100644--- a/datafusion/physical-expr/src/expressions/nullif.rs+++ b/datafusion/physical-expr/src/expressions/nullif.rs@@ -102,23 +102,6 @@ pub fn nullif_func(args: &[ColumnarValue]) -> Result<ColumnarValue> {}}-/// Currently supported types by the nullif function.-/// The order of these types correspond to the order on which coercion applies-/// This should thus be from least informative to most informative-pub static SUPPORTED_NULLIF_TYPES: &[DataType] = &[- DataType::Boolean,- DataType::UInt8,- DataType::UInt16,- DataType::UInt32,- DataType::UInt64,- DataType::Int8,- DataType::Int16,- DataType::Int32,- DataType::Int64,- DataType::Float32,- DataType::Float64,-];-#[cfg(test)]mod tests {use super::*;diff --git a/datafusion/physical-expr/src/expressions/stddev.rs b/datafusion/physical-expr/src/expressions/stddev.rsindex 8a5d4e8861..425d6f36bb 100644--- a/datafusion/physical-expr/src/expressions/stddev.rs+++ b/datafusion/physical-expr/src/expressions/stddev.rs@@ -42,42 +42,6 @@ pub struct StddevPop {expr: Arc<dyn PhysicalExpr>,}-/// function return type of standard deviation-pub fn stddev_return_type(arg_type: &DataType) -> Result<DataType> {- match arg_type {- DataType::Int8- | DataType::Int16- | DataType::Int32- | DataType::Int64- | DataType::UInt8- | DataType::UInt16- | DataType::UInt32- | DataType::UInt64- | DataType::Float32- | DataType::Float64 => Ok(DataType::Float64),- other => Err(DataFusionError::Plan(format!(- "STDDEV does not support {:?}",- other- ))),- }-}--pub fn is_stddev_support_arg_type(arg_type: &DataType) -> bool {- matches!(- arg_type,- DataType::UInt8- | DataType::UInt16- | DataType::UInt32- | DataType::UInt64- | DataType::Int8- | DataType::Int16- | DataType::Int32- | DataType::Int64- | DataType::Float32- | DataType::Float64- )-}-impl Stddev {/// Create a new STDDEV aggregate functionpub fn new(@@ -344,17 +308,6 @@ mod tests {)}- #[test]- fn test_stddev_return_data_type() -> Result<()> {- let data_type = DataType::Float64;- let result_type = stddev_return_type(&data_type)?;- assert_eq!(DataType::Float64, result_type);-- let data_type = DataType::Decimal(36, 10);- assert!(stddev_return_type(&data_type).is_err());- Ok(())- }-#[test]fn test_stddev_1_input() -> Result<()> {let a: ArrayRef = Arc::new(Float64Array::from(vec![1_f64]));diff --git a/datafusion/physical-expr/src/expressions/sum.rs b/datafusion/physical-expr/src/expressions/sum.rsindex 9945620443..84594fe7a5 100644--- a/datafusion/physical-expr/src/expressions/sum.rs+++ b/datafusion/physical-expr/src/expressions/sum.rs@@ -23,7 +23,7 @@ use std::sync::Arc;use crate::{AggregateExpr, PhysicalExpr};use arrow::compute;-use arrow::datatypes::{DataType, DECIMAL_MAX_PRECISION};+use arrow::datatypes::DataType;use arrow::{array::{ArrayRef, Float32Array, Float64Array, Int16Array, Int32Array, Int64Array,@@ -47,48 +47,6 @@ pub struct Sum {nullable: bool,}-/// function return type of a sum-pub fn sum_return_type(arg_type: &DataType) -> Result<DataType> {- match arg_type {- DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 => {- Ok(DataType::Int64)- }- DataType::UInt8 | DataType::UInt16 | DataType::UInt32 | DataType::UInt64 => {- Ok(DataType::UInt64)- }- // In the https://www.postgresql.org/docs/current/functions-aggregate.html doc,- // the result type of floating-point is FLOAT64 with the double precision.- DataType::Float64 | DataType::Float32 => Ok(DataType::Float64),- DataType::Decimal(precision, scale) => {- // in the spark, the result type is DECIMAL(min(38,precision+10), s)- // ref: https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66- let new_precision = DECIMAL_MAX_PRECISION.min(*precision + 10);- Ok(DataType::Decimal(new_precision, *scale))- }- other => Err(DataFusionError::Plan(format!(- "SUM does not support type \"{:?}\"",- other- ))),- }-}--pub fn is_sum_support_arg_type(arg_type: &DataType) -> bool {- matches!(- arg_type,- DataType::UInt8- | DataType::UInt16- | DataType::UInt32- | DataType::UInt64- | DataType::Int8- | DataType::Int16- | DataType::Int32- | DataType::Int64- | DataType::Float32- | DataType::Float64- | DataType::Decimal(_, _)- )-}-impl Sum {/// Create a new SUM aggregate functionpub fn new(@@ -380,18 +338,6 @@ mod tests {use arrow::record_batch::RecordBatch;use datafusion_common::Result;- #[test]- fn test_sum_return_data_type() -> Result<()> {- let data_type = DataType::Decimal(10, 5);- let result_type = sum_return_type(&data_type)?;- assert_eq!(DataType::Decimal(20, 5), result_type);-- let data_type = DataType::Decimal(36, 10);- let result_type = sum_return_type(&data_type)?;- assert_eq!(DataType::Decimal(38, 10), result_type);- Ok(())- }-#[test]fn sum_decimal() -> Result<()> {// test sumdiff --git a/datafusion/physical-expr/src/expressions/variance.rs b/datafusion/physical-expr/src/expressions/variance.rsindex 70f25ce53f..5a9dc080d5 100644--- a/datafusion/physical-expr/src/expressions/variance.rs+++ b/datafusion/physical-expr/src/expressions/variance.rs@@ -48,42 +48,6 @@ pub struct VariancePop {expr: Arc<dyn PhysicalExpr>,}-/// function return type of variance-pub fn variance_return_type(arg_type: &DataType) -> Result<DataType> {- match arg_type {- DataType::Int8- | DataType::Int16- | DataType::Int32- | DataType::Int64- | DataType::UInt8- | DataType::UInt16- | DataType::UInt32- | DataType::UInt64- | DataType::Float32- | DataType::Float64 => Ok(DataType::Float64),- other => Err(DataFusionError::Plan(format!(- "VAR does not support {:?}",- other- ))),- }-}--pub fn is_variance_support_arg_type(arg_type: &DataType) -> bool {- matches!(- arg_type,- DataType::UInt8- | DataType::UInt16- | DataType::UInt32- | DataType::UInt64- | DataType::Int8- | DataType::Int16- | DataType::Int32- | DataType::Int64- | DataType::Float32- | DataType::Float64- )-}-impl Variance {/// Create a new VARIANCE aggregate functionpub fn new(@@ -426,17 +390,6 @@ mod tests {)}- #[test]- fn test_variance_return_data_type() -> Result<()> {- let data_type = DataType::Float64;- let result_type = variance_return_type(&data_type)?;- assert_eq!(DataType::Float64, result_type);-- let data_type = DataType::Decimal(36, 10);- assert!(variance_return_type(&data_type).is_err());- Ok(())- }-#[test]fn test_variance_1_input() -> Result<()> {let a: ArrayRef = Arc::new(Float64Array::from(vec![1_f64]));diff --git a/datafusion/proto/src/from_proto.rs b/datafusion/proto/src/from_proto.rsindex 0aa24dd8ea..daad11d7a9 100644--- a/datafusion/proto/src/from_proto.rs+++ b/datafusion/proto/src/from_proto.rs@@ -27,6 +27,7 @@ use datafusion::prelude::bit_length;use datafusion::{arrow::datatypes::{DataType, Field, IntervalUnit, Schema, TimeUnit, UnionMode},error::DataFusionError,+ logical_expr::{BuiltInWindowFunction, BuiltinScalarFunction},logical_plan::{abs, acos, ascii, asin, atan, ceil, character_length, chr, concat_expr,concat_ws_expr, cos, digest, exp, floor, left, ln, log10, log2, now_expr, nullif,@@ -36,10 +37,7 @@ use datafusion::{window_frames::{WindowFrame, WindowFrameBound, WindowFrameUnits},Column, DFField, DFSchema, DFSchemaRef, Expr, Operator,},- physical_plan::{- aggregates::AggregateFunction, functions::BuiltinScalarFunction,- window_functions::BuiltInWindowFunction,- },+ physical_plan::aggregates::AggregateFunction,prelude::{array, btrim, coalesce, date_part, date_trunc, lower, lpad, ltrim, md5,octet_length, regexp_match, rpad, rtrim, sha224, sha256, sha384, sha512, trim,@@ -914,7 +912,7 @@ pub fn parse_expr(proto: &protobuf::LogicalExprNode,registry: &dyn FunctionRegistry,) -> Result<Expr, Error> {- use datafusion::physical_plan::window_functions;+ use datafusion::logical_expr::window_function;use protobuf::{logical_expr_node::ExprType, window_expr_node, ScalarFunction};let expr_type = proto@@ -970,7 +968,7 @@ pub fn parse_expr(let aggr_function = protobuf::AggregateFunction::try_from(i)?.into();Ok(Expr::WindowFunction {- fun: window_functions::WindowFunction::AggregateFunction(+ fun: window_function::WindowFunction::AggregateFunction(aggr_function,),args: vec![parse_required_expr(&expr.expr, registry, "expr")?],@@ -985,7 +983,7 @@ pub fn parse_expr(.into();Ok(Expr::WindowFunction {- fun: window_functions::WindowFunction::BuiltInWindowFunction(+ fun: window_function::WindowFunction::BuiltInWindowFunction(built_in_function,),args: vec![parse_required_expr(&expr.expr, registry, "expr")?],diff --git a/datafusion/proto/src/lib.rs b/datafusion/proto/src/lib.rsindex 17e148fb94..8228954a9d 100644--- a/datafusion/proto/src/lib.rs+++ b/datafusion/proto/src/lib.rs@@ -30,12 +30,13 @@ mod roundtrip_tests {use super::protobuf;use datafusion::arrow::array::ArrayRef;use datafusion::logical_plan::create_udaf;- use datafusion::physical_plan::functions::{make_scalar_function, Volatility};+ use datafusion::physical_plan::functions::make_scalar_function;use datafusion::physical_plan::Accumulator;use datafusion::{arrow::datatypes::{DataType, Field, IntervalUnit, TimeUnit, UnionMode},+ logical_expr::{BuiltinScalarFunction::Sqrt, Volatility},logical_plan::{col, Expr},- physical_plan::{aggregates, functions::BuiltinScalarFunction::Sqrt},+ physical_plan::aggregates,prelude::*,scalar::ScalarValue,};diff --git a/datafusion/proto/src/to_proto.rs b/datafusion/proto/src/to_proto.rsindex 1e05f80472..9c2e11b6da 100644--- a/datafusion/proto/src/to_proto.rs+++ b/datafusion/proto/src/to_proto.rs@@ -34,15 +34,12 @@ use datafusion::{arrow::datatypes::{DataType, Field, IntervalUnit, Schema, SchemaRef, TimeUnit, UnionMode,},+ logical_expr::{BuiltInWindowFunction, BuiltinScalarFunction, WindowFunction},logical_plan::{window_frames::{WindowFrame, WindowFrameBound, WindowFrameUnits},Column, DFField, DFSchemaRef, Expr,},- physical_plan::{- aggregates::AggregateFunction,- functions::BuiltinScalarFunction,- window_functions::{BuiltInWindowFunction, WindowFunction},- },+ physical_plan::aggregates::AggregateFunction,scalar::ScalarValue,};