Apache DataFusion SQL Query Engine
ARROW-9783: [Rust] [DataFusion] Remove aggregate expression data type
Andy Grove90abaf52c1c0
diff --git a/rust/datafusion/src/dataframe.rs b/rust/datafusion/src/dataframe.rsindex f89f06cb91..ee9ff6a392 100644--- a/rust/datafusion/src/dataframe.rs+++ b/rust/datafusion/src/dataframe.rs@@ -41,7 +41,7 @@ use std::sync::Arc;/// let mut ctx = ExecutionContext::new();/// let df = ctx.read_csv("tests/example.csv", CsvReadOptions::new())?;/// let df = df.filter(col("a").lt_eq(col("b")))?-/// .aggregate(vec![col("a")], vec![df.min(col("b"))?])?+/// .aggregate(vec![col("a")], vec![min(col("b"))?])?/// .limit(100)?;/// let results = df.collect();/// # Ok(())@@ -101,10 +101,10 @@ pub trait DataFrame {/// let df = ctx.read_csv("tests/example.csv", CsvReadOptions::new())?;////// // The following use is the equivalent of "SELECT MIN(b) GROUP BY a"- /// let _ = df.aggregate(vec![col("a")], vec![df.min(col("b"))?])?;+ /// let _ = df.aggregate(vec![col("a")], vec![min(col("b"))?])?;////// // The following use is the equivalent of "SELECT MIN(b)"- /// let _ = df.aggregate(vec![], vec![df.min(col("b"))?])?;+ /// let _ = df.aggregate(vec![], vec![min(col("b"))?])?;/// # Ok(())/// # }/// ```@@ -174,19 +174,4 @@ pub trait DataFrame {/// Return the logical plan represented by this DataFrame.fn to_logical_plan(&self) -> LogicalPlan;-- /// Create an expression to represent the min() aggregate function- fn min(&self, expr: Expr) -> Result<Expr>;-- /// Create an expression to represent the max() aggregate function- fn max(&self, expr: Expr) -> Result<Expr>;-- /// Create an expression to represent the sum() aggregate function- fn sum(&self, expr: Expr) -> Result<Expr>;-- /// Create an expression to represent the avg() aggregate function- fn avg(&self, expr: Expr) -> Result<Expr>;-- /// Create an expression to represent the count() aggregate function- fn count(&self, expr: Expr) -> Result<Expr>;}diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex bb0cb7251a..40549b73cb 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -69,7 +69,7 @@ use crate::sql::{/// let mut ctx = ExecutionContext::new();/// let df = ctx.read_csv("tests/example.csv", CsvReadOptions::new())?;/// let df = df.filter(col("a").lt_eq(col("b")))?-/// .aggregate(vec![col("a")], vec![df.min(col("b"))?])?+/// .aggregate(vec![col("a")], vec![min(col("b"))?])?/// .limit(100)?;/// let results = df.collect();/// # Ok(())@@ -928,10 +928,7 @@ mod tests {]));let plan = LogicalPlanBuilder::scan("default", "test", schema.as_ref(), None)?- .aggregate(- vec![col("c1")],- vec![aggregate_expr("SUM", col("c2"), DataType::UInt32)],- )?+ .aggregate(vec![col("c1")], vec![aggregate_expr("SUM", col("c2"))])?.project(vec![col("c1"), col("SUM(c2)").alias("total_salary")])?.build()?;diff --git a/rust/datafusion/src/execution/dataframe_impl.rs b/rust/datafusion/src/execution/dataframe_impl.rsindex 1df3be4e82..dab6fffd9f 100644--- a/rust/datafusion/src/execution/dataframe_impl.rs+++ b/rust/datafusion/src/execution/dataframe_impl.rs@@ -19,10 +19,9 @@use std::sync::{Arc, Mutex};-use crate::arrow::datatypes::DataType;use crate::arrow::record_batch::RecordBatch;use crate::dataframe::*;-use crate::error::{ExecutionError, Result};+use crate::error::Result;use crate::execution::context::{ExecutionContext, ExecutionContextState};use crate::logicalplan::{col, Expr, LogicalPlan, LogicalPlanBuilder};use arrow::datatypes::Schema;@@ -98,31 +97,6 @@ impl DataFrame for DataFrameImpl {Ok(Arc::new(DataFrameImpl::new(self.ctx_state.clone(), &plan)))}- /// Create an expression to represent the min() aggregate function- fn min(&self, expr: Expr) -> Result<Expr> {- self.aggregate_expr("MIN", expr)- }-- /// Create an expression to represent the max() aggregate function- fn max(&self, expr: Expr) -> Result<Expr> {- self.aggregate_expr("MAX", expr)- }-- /// Create an expression to represent the sum() aggregate function- fn sum(&self, expr: Expr) -> Result<Expr> {- self.aggregate_expr("SUM", expr)- }-- /// Create an expression to represent the avg() aggregate function- fn avg(&self, expr: Expr) -> Result<Expr> {- self.aggregate_expr("AVG", expr)- }-- /// Create an expression to represent the count() aggregate function- fn count(&self, expr: Expr) -> Result<Expr> {- self.aggregate_expr("COUNT", expr)- }-/// Convert to logical planfn to_logical_plan(&self) -> LogicalPlan {self.plan.clone()@@ -139,39 +113,12 @@ impl DataFrame for DataFrameImpl {}}-impl DataFrameImpl {- /// Determine the data type for a given expression- fn get_data_type(&self, expr: &Expr) -> Result<DataType> {- match expr {- Expr::Column(name) => Ok(self- .plan- .schema()- .field_with_name(name)?- .data_type()- .clone()),- _ => Err(ExecutionError::General(format!(- "Could not determine data type for expr {:?}",- expr- ))),- }- }-- /// Create an expression to represent a named aggregate function- fn aggregate_expr(&self, name: &str, expr: Expr) -> Result<Expr> {- let return_type = self.get_data_type(&expr)?;- Ok(Expr::AggregateFunction {- name: name.to_string(),- args: vec![expr.clone()],- return_type,- })- }-}-#[cfg(test)]mod tests {use super::*;use crate::datasource::csv::CsvReadOptions;use crate::execution::context::ExecutionContext;+ use crate::logicalplan::*;use crate::test;#[test]@@ -212,11 +159,11 @@ mod tests {let t = test_table()?;let group_expr = vec![col("c1")];let aggr_expr = vec![- t.min(col("c12"))?,- t.max(col("c12"))?,- t.avg(col("c12"))?,- t.sum(col("c12"))?,- t.count(col("c12"))?,+ min(col("c12"))?,+ max(col("c12"))?,+ avg(col("c12"))?,+ sum(col("c12"))?,+ count(col("c12"))?,];let t2 = t.aggregate(group_expr.clone(), aggr_expr.clone())?;diff --git a/rust/datafusion/src/lib.rs b/rust/datafusion/src/lib.rsindex 0b30f471c2..f6cba3ef40 100644--- a/rust/datafusion/src/lib.rs+++ b/rust/datafusion/src/lib.rs@@ -39,7 +39,7 @@/// let mut ctx = ExecutionContext::new();/// let df = ctx.read_csv("tests/example.csv", CsvReadOptions::new())?;/// let df = df.filter(col("a").lt_eq(col("b")))?-/// .aggregate(vec![col("a")], vec![df.min(col("b"))?])?+/// .aggregate(vec![col("a")], vec![min(col("b"))?])?/// .limit(100)?;/// let results = df.collect();/// # Ok(())diff --git a/rust/datafusion/src/logicalplan.rs b/rust/datafusion/src/logicalplan.rsindex dc8542b4c6..3e08a84253 100644--- a/rust/datafusion/src/logicalplan.rs+++ b/rust/datafusion/src/logicalplan.rs@@ -267,36 +267,8 @@ fn create_name(e: &Expr, input_schema: &Schema) -> Result<String> {/// Returns the datatype of the expression given the input schema// note: the physical plan derived from an expression must match the datatype on this function.pub fn expr_to_field(e: &Expr, input_schema: &Schema) -> Result<Field> {- let data_type = match e {- Expr::Alias(expr, ..) => expr.get_type(input_schema),- Expr::Column(name) => Ok(input_schema.field_with_name(name)?.data_type().clone()),- Expr::Literal(ref lit) => lit.get_datatype(),- Expr::ScalarFunction {- ref return_type, ..- } => Ok(return_type.clone()),- Expr::AggregateFunction {- ref return_type, ..- } => Ok(return_type.clone()),- Expr::Cast { ref data_type, .. } => Ok(data_type.clone()),- Expr::BinaryExpr {- ref left,- ref right,- ..- } => {- let left_type = left.get_type(input_schema)?;- let right_type = right.get_type(input_schema)?;- Ok(utils::get_supertype(&left_type, &right_type).unwrap())- }- _ => Err(ExecutionError::NotImplemented(format!(- "Cannot determine schema type for expression {:?}",- e- ))),- };-- match data_type {- Ok(d) => Ok(Field::new(&e.name(input_schema)?, d, true)),- Err(e) => Err(e),- }+ let data_type = e.get_type(input_schema)?;+ Ok(Field::new(&e.name(input_schema)?, data_type, true))}/// Create field meta-data from an expression, for use in a result set schema@@ -363,8 +335,6 @@ pub enum Expr {name: String,/// List of expressions to feed to the functions as argumentsargs: Vec<Expr>,- /// The `DataType` the expression will yield- return_type: DataType,},/// WildcardWildcard,@@ -379,7 +349,48 @@ impl Expr {Expr::Literal(l) => l.get_datatype(),Expr::Cast { data_type, .. } => Ok(data_type.clone()),Expr::ScalarFunction { return_type, .. } => Ok(return_type.clone()),- Expr::AggregateFunction { return_type, .. } => Ok(return_type.clone()),+ Expr::AggregateFunction { name, args, .. } => {+ match name.to_uppercase().as_str() {+ "MIN" | "MAX" => args[0].get_type(schema),+ "SUM" => match args[0].get_type(schema)? {+ DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64 => Ok(DataType::Int64),+ DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64 => Ok(DataType::UInt64),+ DataType::Float32 => Ok(DataType::Float32),+ DataType::Float64 => Ok(DataType::Float64),+ other => Err(ExecutionError::General(format!(+ "SUM does not support {:?}",+ other+ ))),+ },+ "AVG" => match args[0].get_type(schema)? {+ 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(ExecutionError::General(format!(+ "AVG does not support {:?}",+ other+ ))),+ },+ "COUNT" => Ok(DataType::UInt64),+ other => Err(ExecutionError::General(format!(+ "Invalid aggregate function '{:?}'",+ other+ ))),+ }+ }Expr::Not(_) => Ok(DataType::Boolean),Expr::IsNull(_) => Ok(DataType::Boolean),Expr::IsNotNull(_) => Ok(DataType::Boolean),@@ -538,6 +549,31 @@ pub fn col(name: &str) -> Expr {Expr::Column(name.to_owned())}+/// Create an expression to represent the min() aggregate function+pub fn min(expr: Expr) -> Result<Expr> {+ Ok(aggregate_expr("MIN", expr))+}++/// Create an expression to represent the max() aggregate function+pub fn max(expr: Expr) -> Result<Expr> {+ Ok(aggregate_expr("MAX", expr))+}++/// Create an expression to represent the sum() aggregate function+pub fn sum(expr: Expr) -> Result<Expr> {+ Ok(aggregate_expr("SUM", expr))+}++/// Create an expression to represent the avg() aggregate function+pub fn avg(expr: Expr) -> Result<Expr> {+ Ok(aggregate_expr("AVG", expr))+}++/// Create an expression to represent the count() aggregate function+pub fn count(expr: Expr) -> Result<Expr> {+ Ok(aggregate_expr("COUNT", expr))+}+/// Whether it can be represented as a literal expressionpub trait Literal {/// convert the value to a Literal expression@@ -619,11 +655,10 @@ pub fn length(e: Expr) -> Expr {}/// Create an aggregate expression-pub fn aggregate_expr(name: &str, expr: Expr, return_type: DataType) -> Expr {+pub fn aggregate_expr(name: &str, expr: Expr) -> Expr {Expr::AggregateFunction {name: name.to_owned(),args: vec![expr],- return_type,}}@@ -1292,8 +1327,7 @@ mod tests {)?.aggregate(vec![col("state")],- vec![aggregate_expr("SUM", col("salary"), DataType::Int32)- .alias("total_salary")],+ vec![aggregate_expr("SUM", col("salary")).alias("total_salary")],)?.project(vec![col("state"), col("total_salary")])?.build()?;@@ -1307,6 +1341,7 @@ mod tests {Ok(())}+ #[test]#[test]fn plan_builder_sort() -> Result<()> {let plan = LogicalPlanBuilder::scan(diff --git a/rust/datafusion/src/optimizer/type_coercion.rs b/rust/datafusion/src/optimizer/type_coercion.rsindex a485423975..517f228741 100644--- a/rust/datafusion/src/optimizer/type_coercion.rs+++ b/rust/datafusion/src/optimizer/type_coercion.rs@@ -166,10 +166,7 @@ mod tests {// filter clause needs the type coercion rule applied.filter(col("c7").lt(lit(5_u8)))?.project(vec![col("c1"), col("c2")])?- .aggregate(- vec![col("c1")],- vec![aggregate_expr("SUM", col("c2"), DataType::Int64)],- )?+ .aggregate(vec![col("c1")], vec![aggregate_expr("SUM", col("c2"))])?.sort(vec![col("c1")])?.limit(10)?.build()?;diff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rsindex 9195e19589..1916302d85 100644--- a/rust/datafusion/src/optimizer/utils.rs+++ b/rust/datafusion/src/optimizer/utils.rs@@ -341,11 +341,8 @@ pub fn rewrite_expression(expr: &Expr, expressions: &Vec<Expr>) -> Result<Expr>return_type: return_type.clone(),args: expressions.clone(),}),- Expr::AggregateFunction {- name, return_type, ..- } => Ok(Expr::AggregateFunction {+ Expr::AggregateFunction { name, .. } => Ok(Expr::AggregateFunction {name: name.clone(),- return_type: return_type.clone(),args: expressions.clone(),}),Expr::Cast { data_type, .. } => Ok(Expr::Cast {diff --git a/rust/datafusion/src/prelude.rs b/rust/datafusion/src/prelude.rsindex 658f970b32..d7b8df0eff 100644--- a/rust/datafusion/src/prelude.rs+++ b/rust/datafusion/src/prelude.rs@@ -28,4 +28,4 @@pub use crate::dataframe::DataFrame;pub use crate::execution::context::{ExecutionConfig, ExecutionContext};pub use crate::execution::physical_plan::csv::CsvReadOptions;-pub use crate::logicalplan::{col, lit};+pub use crate::logicalplan::{avg, col, count, lit, max, min, sum};diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rsindex 16da452755..34f6f8ecd3 100644--- a/rust/datafusion/src/sql/planner.rs+++ b/rust/datafusion/src/sql/planner.rs@@ -486,14 +486,9 @@ impl<S: SchemaProvider> SqlToRel<S> {.map(|a| self.sql_to_rex(a, schema)).collect::<Result<Vec<Expr>>>()?;- // return type is same as the argument type for these aggregate- // functions- let return_type = rex_args[0].get_type(schema)?.clone();-Ok(Expr::AggregateFunction {name: name.clone(),args: rex_args,- return_type,})}"count" => {@@ -510,7 +505,6 @@ impl<S: SchemaProvider> SqlToRel<S> {Ok(Expr::AggregateFunction {name: name.clone(),args: rex_args,- return_type: DataType::UInt64,})}_ => match self.schema_provider.get_function_meta(&name) {diff --git a/rust/datafusion/src/test/mod.rs b/rust/datafusion/src/test/mod.rsindex 317c14564f..5b4445afeb 100644--- a/rust/datafusion/src/test/mod.rs+++ b/rust/datafusion/src/test/mod.rs@@ -228,6 +228,5 @@ pub fn max(expr: Expr) -> Expr {Expr::AggregateFunction {name: "MAX".to_owned(),args: vec![expr],- return_type: DataType::Float64,}}