Skip to content

Apache DataFusion SQL Query Engine

ARROW-9937: [Rust] [DataFusion] Improved aggregations

Jorge C. Leitao7accc695bd16
diff --git a/rust/datafusion/Cargo.toml b/rust/datafusion/Cargo.toml
index 71c16576f6..0ec891d76f 100644
--- a/rust/datafusion/Cargo.toml
+++ b/rust/datafusion/Cargo.toml
@@ -56,6 +56,7 @@ num_cpus = "1.13.0"
chrono = "0.4"
[dev-dependencies]
+rand = "0.7"
criterion = "0.3"
tempfile = "3"
futures = "0.3"
diff --git a/rust/datafusion/benches/aggregate_query_sql.rs b/rust/datafusion/benches/aggregate_query_sql.rs
index d4a82c8ed6..2189f5807e 100644
--- a/rust/datafusion/benches/aggregate_query_sql.rs
+++ b/rust/datafusion/benches/aggregate_query_sql.rs
@@ -19,18 +19,26 @@
extern crate criterion;
use criterion::Criterion;
-use std::env;
+use rand::seq::SliceRandom;
+use rand::Rng;
use std::sync::Arc;
extern crate arrow;
extern crate datafusion;
-use arrow::datatypes::{DataType, Field, Schema};
+use arrow::{
+ array::Float32Array,
+ array::Float64Array,
+ array::StringArray,
+ datatypes::{DataType, Field, Schema},
+ record_batch::RecordBatch,
+};
-use datafusion::datasource::{CsvFile, CsvReadOptions, MemTable};
+use datafusion::datasource::MemTable;
+use datafusion::error::Result;
use datafusion::execution::context::ExecutionContext;
-fn aggregate_query(ctx: &mut ExecutionContext, sql: &str) {
+fn query(ctx: &mut ExecutionContext, sql: &str) {
// execute the query
let df = ctx.sql(&sql).unwrap();
let results = df.collect().unwrap();
@@ -39,72 +47,107 @@ fn aggregate_query(ctx: &mut ExecutionContext, sql: &str) {
for _batch in results {}
}
-fn create_context() -> ExecutionContext {
- // define schema for data source (csv file)
+fn create_data(size: usize, null_density: f64) -> Vec<Option<f64>> {
+ // use random numbers to avoid spurious compiler optimizations wrt to branching
+ let mut rng = rand::thread_rng();
+
+ (0..size)
+ .map(|_| {
+ if rng.gen::<f64>() > null_density {
+ None
+ } else {
+ Some(rng.gen::<f64>())
+ }
+ })
+ .collect()
+}
+
+fn create_context(
+ partitions_len: usize,
+ array_len: usize,
+ batch_size: usize,
+) -> Result<ExecutionContext> {
+ // define a schema.
let schema = Arc::new(Schema::new(vec![
- Field::new("c1", DataType::Utf8, false),
- Field::new("c2", DataType::UInt32, false),
- Field::new("c3", DataType::Int8, false),
- Field::new("c4", DataType::Int16, false),
- Field::new("c5", DataType::Int32, false),
- Field::new("c6", DataType::Int64, false),
- Field::new("c7", DataType::UInt8, false),
- Field::new("c8", DataType::UInt16, false),
- Field::new("c9", DataType::UInt32, false),
- Field::new("c10", DataType::UInt64, false),
- Field::new("c11", DataType::Float32, false),
- Field::new("c12", DataType::Float64, false),
- Field::new("c13", DataType::Utf8, false),
+ Field::new("utf8", DataType::Utf8, false),
+ Field::new("f32", DataType::Float32, false),
+ Field::new("f64", DataType::Float64, false),
]));
- let testdata = env::var("ARROW_TEST_DATA").expect("ARROW_TEST_DATA not defined");
+ // define data.
+ let partitions = (0..partitions_len)
+ .map(|_| {
+ (0..array_len / batch_size / partitions_len)
+ .map(|i| {
+ // the 4 here is the number of different keys.
+ // a higher number increase sparseness
+ let vs = vec![0, 1, 2, 3];
+ let keys: Vec<String> = (0..batch_size)
+ .map(
+ // use random numbers to avoid spurious compiler optimizations wrt to branching
+ |_| format!("hi{:?}", vs.choose(&mut rand::thread_rng())),
+ )
+ .collect();
+ let keys: Vec<&str> = keys.iter().map(|e| &**e).collect();
+
+ let values = create_data(batch_size, 0.5);
+
+ RecordBatch::try_new(
+ schema.clone(),
+ vec![
+ Arc::new(StringArray::from(keys)),
+ Arc::new(Float32Array::from(vec![i as f32; batch_size])),
+ Arc::new(Float64Array::from(values)),
+ ],
+ )
+ .unwrap()
+ })
+ .collect::<Vec<_>>()
+ })
+ .collect::<Vec<_>>();
- // create CSV data source
- let csv = CsvFile::try_new(
- &format!("{}/csv/aggregate_test_100.csv", testdata),
- CsvReadOptions::new().schema(&schema),
- )
- .unwrap();
+ let mut ctx = ExecutionContext::new();
- let mem_table = MemTable::load(&csv).unwrap();
+ // declare a table in memory. In spark API, this corresponds to createDataFrame(...).
+ let provider = MemTable::new(schema, partitions)?;
+ ctx.register_table("t", Box::new(provider));
- // create local execution context
- let mut ctx = ExecutionContext::new();
- ctx.register_table("aggregate_test_100", Box::new(mem_table));
- ctx
+ Ok(ctx)
}
fn criterion_benchmark(c: &mut Criterion) {
- c.bench_function("aggregate_query_no_group_by", |b| {
- let mut ctx = create_context();
+ let partitions_len = 4;
+ let array_len = 32768; // 2^15
+ let batch_size = 2048; // 2^11
+ let mut ctx = create_context(partitions_len, array_len, batch_size).unwrap();
+
+ c.bench_function("aggregate_query_no_group_by 15 12", |b| {
b.iter(|| {
- aggregate_query(
+ query(
&mut ctx,
- "SELECT MIN(c12), MAX(c12) \
- FROM aggregate_test_100",
+ "SELECT MIN(f64), AVG(f64), COUNT(f64) \
+ FROM t",
)
})
});
- c.bench_function("aggregate_query_group_by", |b| {
- let mut ctx = create_context();
+ c.bench_function("aggregate_query_group_by 15 12", |b| {
b.iter(|| {
- aggregate_query(
+ query(
&mut ctx,
- "SELECT c1, MIN(c12), MAX(c12) \
- FROM aggregate_test_100 GROUP BY c1",
+ "SELECT utf8, MIN(f64), AVG(f64), COUNT(f64) \
+ FROM t GROUP BY utf8",
)
})
});
- c.bench_function("aggregate_query_group_by_with_filter", |b| {
- let mut ctx = create_context();
+ c.bench_function("aggregate_query_group_by_with_filter 15 12", |b| {
b.iter(|| {
- aggregate_query(
+ query(
&mut ctx,
- "SELECT c1, MIN(c12), MAX(c12) \
- FROM aggregate_test_100 \
- WHERE c11 > 0.1 AND c11 < 0.9 GROUP BY c1",
+ "SELECT utf8, MIN(f64), AVG(f64), COUNT(f64) \
+ FROM t \
+ WHERE f32 > 10 AND f32 < 20 GROUP BY utf8",
)
})
});
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index c5c5213dad..09cf89217e 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -516,7 +516,8 @@ mod tests {
use crate::test;
use crate::variable::VarType;
use arrow::array::{
- ArrayRef, Int32Array, PrimitiveArrayOps, StringArray, StringArrayOps,
+ ArrayRef, Float64Array, Int32Array, PrimitiveArrayOps, StringArray,
+ StringArrayOps,
};
use arrow::compute::add;
use std::fs::File;
@@ -847,6 +848,24 @@ mod tests {
Ok(())
}
+ #[test]
+ fn aggregate_grouped_empty() -> Result<()> {
+ let results =
+ execute("SELECT c1, AVG(c2) FROM test WHERE c1 = 123 GROUP BY c1", 4)?;
+ assert_eq!(results.len(), 1);
+
+ let batch = &results[0];
+
+ assert_eq!(field_names(batch), vec!["c1", "AVG(c2)"]);
+
+ let expected: Vec<&str> = vec![];
+ let mut rows = test::format_batch(&batch);
+ rows.sort();
+ assert_eq!(rows, expected);
+
+ Ok(())
+ }
+
#[test]
fn aggregate_grouped_max() -> Result<()> {
let results = execute("SELECT c1, MAX(c2) FROM test GROUP BY c1", 4)?;
@@ -1146,6 +1165,41 @@ mod tests {
Ok(())
}
+ #[test]
+ fn simple_avg() -> Result<()> {
+ let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
+
+ let batch1 = RecordBatch::try_new(
+ Arc::new(schema.clone()),
+ vec![Arc::new(Int32Array::from(vec![1, 2, 3]))],
+ )?;
+ let batch2 = RecordBatch::try_new(
+ Arc::new(schema.clone()),
+ vec![Arc::new(Int32Array::from(vec![4, 5]))],
+ )?;
+
+ let mut ctx = ExecutionContext::new();
+
+ let provider = MemTable::new(Arc::new(schema), vec![vec![batch1], vec![batch2]])?;
+ ctx.register_table("t", Box::new(provider));
+
+ let result = collect(&mut ctx, "SELECT AVG(a) FROM t")?;
+
+ let batch = &result[0];
+ assert_eq!(1, batch.num_columns());
+ assert_eq!(1, batch.num_rows());
+
+ let values = batch
+ .column(0)
+ .as_any()
+ .downcast_ref::<Float64Array>()
+ .expect("failed to cast version");
+ assert_eq!(values.len(), 1);
+ // avg(1,2,3,4,5) = 3.0
+ assert_eq!(values.value(0), 3.0_f64);
+ Ok(())
+ }
+
#[test]
fn custom_query_planner() -> Result<()> {
let mut ctx = ExecutionContext::with_config(
diff --git a/rust/datafusion/src/lib.rs b/rust/datafusion/src/lib.rs
index 786d391fa9..92652c7b87 100644
--- a/rust/datafusion/src/lib.rs
+++ b/rust/datafusion/src/lib.rs
@@ -66,6 +66,7 @@ pub mod logical_plan;
pub mod optimizer;
pub mod physical_plan;
pub mod prelude;
+pub mod scalar;
pub mod sql;
pub mod variable;
diff --git a/rust/datafusion/src/logical_plan/mod.rs b/rust/datafusion/src/logical_plan/mod.rs
index e37bd1003d..30759ffced 100644
--- a/rust/datafusion/src/logical_plan/mod.rs
+++ b/rust/datafusion/src/logical_plan/mod.rs
@@ -26,10 +26,13 @@ use std::{any::Any, collections::HashSet, fmt, sync::Arc};
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
-use crate::datasource::csv::{CsvFile, CsvReadOptions};
use crate::datasource::parquet::ParquetTable;
use crate::datasource::TableProvider;
use crate::error::{ExecutionError, Result};
+use crate::{
+ datasource::csv::{CsvFile, CsvReadOptions},
+ scalar::ScalarValue,
+};
use crate::{
physical_plan::{
aggregates, expressions::binary_operator_data_type, functions,
@@ -43,84 +46,6 @@ use functions::{ReturnTypeFunction, ScalarFunctionImplementation, Signature};
mod operators;
pub use operators::Operator;
-/// ScalarValue enumeration
-#[derive(Debug, Clone, PartialEq)]
-pub enum ScalarValue {
- /// null value
- Null,
- /// true or false value
- Boolean(bool),
- /// 32bit float
- Float32(f32),
- /// 64bit float
- Float64(f64),
- /// signed 8bit int
- Int8(i8),
- /// signed 16bit int
- Int16(i16),
- /// signed 32bit int
- Int32(i32),
- /// signed 64bit int
- Int64(i64),
- /// unsigned 8bit int
- UInt8(u8),
- /// unsigned 16bit int
- UInt16(u16),
- /// unsigned 32bit int
- UInt32(u32),
- /// unsigned 64bit int
- UInt64(u64),
- /// utf-8 encoded string
- Utf8(String),
- /// List of scalars packed as a struct
- Struct(Vec<ScalarValue>),
-}
-
-impl ScalarValue {
- /// Getter for the `DataType` of the value
- pub fn get_datatype(&self) -> Result<DataType> {
- match *self {
- ScalarValue::Boolean(_) => Ok(DataType::Boolean),
- ScalarValue::UInt8(_) => Ok(DataType::UInt8),
- ScalarValue::UInt16(_) => Ok(DataType::UInt16),
- ScalarValue::UInt32(_) => Ok(DataType::UInt32),
- ScalarValue::UInt64(_) => Ok(DataType::UInt64),
- ScalarValue::Int8(_) => Ok(DataType::Int8),
- ScalarValue::Int16(_) => Ok(DataType::Int16),
- ScalarValue::Int32(_) => Ok(DataType::Int32),
- ScalarValue::Int64(_) => Ok(DataType::Int64),
- ScalarValue::Float32(_) => Ok(DataType::Float32),
- ScalarValue::Float64(_) => Ok(DataType::Float64),
- ScalarValue::Utf8(_) => Ok(DataType::Utf8),
- _ => Err(ExecutionError::General(format!(
- "Cannot treat {:?} as scalar value",
- self
- ))),
- }
- }
-}
-
-impl fmt::Display for ScalarValue {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- ScalarValue::Boolean(value) => write!(f, "{}", value),
- ScalarValue::UInt8(value) => write!(f, "{}", value),
- ScalarValue::UInt16(value) => write!(f, "{}", value),
- ScalarValue::UInt32(value) => write!(f, "{}", value),
- ScalarValue::UInt64(value) => write!(f, "{}", value),
- ScalarValue::Int8(value) => write!(f, "{}", value),
- ScalarValue::Int16(value) => write!(f, "{}", value),
- ScalarValue::Int32(value) => write!(f, "{}", value),
- ScalarValue::Int64(value) => write!(f, "{}", value),
- ScalarValue::Float32(value) => write!(f, "{}", value),
- ScalarValue::Float64(value) => write!(f, "{}", value),
- ScalarValue::Utf8(value) => write!(f, "{}", value),
- ScalarValue::Null => write!(f, "NULL"),
- ScalarValue::Struct(_) => write!(f, "STRUCT"),
- }
- }
-}
-
fn create_function_name(
fun: &String,
args: &[Expr],
@@ -148,7 +73,7 @@ fn create_name(e: &Expr, input_schema: &Schema) -> Result<String> {
}
Expr::Cast { expr, data_type } => {
let expr = create_name(expr, input_schema)?;
- Ok(format!("CAST({} as {:?})", expr, data_type))
+ Ok(format!("CAST({} AS {:?})", expr, data_type))
}
Expr::Not(expr) => {
let expr = create_name(expr, input_schema)?;
@@ -271,7 +196,7 @@ impl Expr {
Expr::Alias(expr, _) => expr.get_type(schema),
Expr::Column(name) => Ok(schema.field_with_name(name)?.data_type().clone()),
Expr::ScalarVariable(_) => Ok(DataType::Utf8),
- Expr::Literal(l) => l.get_datatype(),
+ Expr::Literal(l) => Ok(l.get_datatype()),
Expr::Cast { data_type, .. } => Ok(data_type.clone()),
Expr::ScalarUDF { fun, args } => {
let data_types = args
@@ -324,10 +249,7 @@ impl Expr {
match self {
Expr::Alias(expr, _) => expr.nullable(input_schema),
Expr::Column(name) => Ok(input_schema.field_with_name(name)?.is_nullable()),
- Expr::Literal(value) => match value {
- ScalarValue::Null => Ok(true),
- _ => Ok(false),
- },
+ Expr::Literal(value) => Ok(value.is_null()),
Expr::ScalarVariable(_) => Ok(true),
Expr::Cast { expr, .. } => expr.nullable(input_schema),
Expr::ScalarFunction { .. } => Ok(true),
@@ -537,13 +459,13 @@ pub trait Literal {
impl Literal for &str {
fn lit(&self) -> Expr {
- Expr::Literal(ScalarValue::Utf8((*self).to_owned()))
+ Expr::Literal(ScalarValue::Utf8(Some((*self).to_owned())))
}
}
impl Literal for String {
fn lit(&self) -> Expr {
- Expr::Literal(ScalarValue::Utf8((*self).to_owned()))
+ Expr::Literal(ScalarValue::Utf8(Some((*self).to_owned())))
}
}
@@ -552,7 +474,7 @@ macro_rules! make_literal {
#[allow(missing_docs)]
impl Literal for $TYPE {
fn lit(&self) -> Expr {
- Expr::Literal(ScalarValue::$SCALAR(self.clone()))
+ Expr::Literal(ScalarValue::$SCALAR(Some(self.clone())))
}
}
};
diff --git a/rust/datafusion/src/physical_plan/aggregates.rs b/rust/datafusion/src/physical_plan/aggregates.rs
index 772e9b6967..4523e13bfb 100644
--- a/rust/datafusion/src/physical_plan/aggregates.rs
+++ b/rust/datafusion/src/physical_plan/aggregates.rs
@@ -103,16 +103,26 @@ pub fn create_aggregate_expr(
fun: &AggregateFunction,
args: &Vec<Arc<dyn PhysicalExpr>>,
input_schema: &Schema,
+ name: String,
) -> Result<Arc<dyn AggregateExpr>> {
// coerce
let arg = coerce(args, input_schema, &signature(fun))?[0].clone();
+ let arg_types = args
+ .iter()
+ .map(|e| e.data_type(input_schema))
+ .collect::<Result<Vec<_>>>()?;
+
+ let return_type = return_type(&fun, &arg_types)?;
+
Ok(match fun {
- AggregateFunction::Count => expressions::count(arg),
- AggregateFunction::Sum => expressions::sum(arg),
- AggregateFunction::Min => expressions::min(arg),
- AggregateFunction::Max => expressions::max(arg),
- AggregateFunction::Avg => expressions::avg(arg),
+ AggregateFunction::Count => {
+ Arc::new(expressions::Count::new(arg, name, return_type))
+ }
+ AggregateFunction::Sum => Arc::new(expressions::Sum::new(arg, name, return_type)),
+ AggregateFunction::Min => Arc::new(expressions::Min::new(arg, name, return_type)),
+ AggregateFunction::Max => Arc::new(expressions::Max::new(arg, name, return_type)),
+ AggregateFunction::Avg => Arc::new(expressions::Avg::new(arg, name, return_type)),
})
}
@@ -135,7 +145,7 @@ fn signature(fun: &AggregateFunction) -> Signature {
match fun {
AggregateFunction::Count => Signature::Any(1),
AggregateFunction::Min | AggregateFunction::Max => {
- let mut valid = vec![DataType::Utf8];
+ let mut valid = vec![DataType::Utf8, DataType::LargeUtf8];
valid.extend_from_slice(NUMERICS);
Signature::Uniform(1, valid)
}
diff --git a/rust/datafusion/src/physical_plan/common.rs b/rust/datafusion/src/physical_plan/common.rs
index c076a7aa7e..e13e64c2f5 100644
--- a/rust/datafusion/src/physical_plan/common.rs
+++ b/rust/datafusion/src/physical_plan/common.rs
@@ -23,11 +23,18 @@ use std::sync::{Arc, Mutex};
use crate::error::{ExecutionError, Result};
-use crate::logical_plan::ScalarValue;
-use arrow::array::{self, ArrayRef, PrimitiveArrayOps, StringArrayOps};
+use array::{
+ BooleanArray, Float32Array, Float64Array, Int16Array, Int32Array, Int64Array,
+ Int8Array, LargeStringArray, StringArray, UInt16Array, UInt32Array, UInt64Array,
+ UInt8Array,
+};
use arrow::datatypes::{DataType, SchemaRef};
use arrow::error::Result as ArrowResult;
use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use arrow::{
+ array::{self, ArrayRef},
+ datatypes::Schema,
+};
/// Iterator over a vector of record batches
pub struct RecordBatchIterator {
@@ -109,99 +116,57 @@ pub fn build_file_list(dir: &str, filenames: &mut Vec<String>, ext: &str) -> Res
Ok(())
}
-/// Get a value from an array as a ScalarValue
-pub fn get_scalar_value(array: &ArrayRef, row: usize) -> Result<Option<ScalarValue>> {
- if array.is_null(row) {
- return Ok(None);
- }
- let value: Option<ScalarValue> = match array.data_type() {
- DataType::UInt8 => {
- let array = array
- .as_any()
- .downcast_ref::<array::UInt8Array>()
- .expect("Failed to cast array");
- Some(ScalarValue::UInt8(array.value(row)))
- }
- DataType::UInt16 => {
- let array = array
- .as_any()
- .downcast_ref::<array::UInt16Array>()
- .expect("Failed to cast array");
- Some(ScalarValue::UInt16(array.value(row)))
- }
- DataType::UInt32 => {
- let array = array
- .as_any()
- .downcast_ref::<array::UInt32Array>()
- .expect("Failed to cast array");
- Some(ScalarValue::UInt32(array.value(row)))
- }
- DataType::UInt64 => {
- let array = array
- .as_any()
- .downcast_ref::<array::UInt64Array>()
- .expect("Failed to cast array");
- Some(ScalarValue::UInt64(array.value(row)))
- }
- DataType::Int8 => {
- let array = array
- .as_any()
- .downcast_ref::<array::Int8Array>()
- .expect("Failed to cast array");
- Some(ScalarValue::Int8(array.value(row)))
- }
- DataType::Int16 => {
- let array = array
- .as_any()
- .downcast_ref::<array::Int16Array>()
- .expect("Failed to cast array");
- Some(ScalarValue::Int16(array.value(row)))
- }
- DataType::Int32 => {
- let array = array
- .as_any()
- .downcast_ref::<array::Int32Array>()
- .expect("Failed to cast array");
- Some(ScalarValue::Int32(array.value(row)))
- }
- DataType::Int64 => {
- let array = array
- .as_any()
- .downcast_ref::<array::Int64Array>()
- .expect("Failed to cast array");
- Some(ScalarValue::Int64(array.value(row)))
- }
- DataType::Float32 => {
- let array = array
- .as_any()
- .downcast_ref::<array::Float32Array>()
- .unwrap();
- Some(ScalarValue::Float32(array.value(row)))
- }
- DataType::Float64 => {
- let array = array
- .as_any()
- .downcast_ref::<array::Float64Array>()
- .unwrap();
- Some(ScalarValue::Float64(array.value(row)))
- }
- DataType::Utf8 => {
- let array = array.as_any().downcast_ref::<array::StringArray>().unwrap();
- Some(ScalarValue::Utf8(array.value(row).to_string()))
- }
- DataType::LargeUtf8 => {
- let array = array
- .as_any()
- .downcast_ref::<array::LargeStringArray>()
- .unwrap();
- Some(ScalarValue::Utf8(array.value(row).to_string()))
- }
- other => {
- return Err(ExecutionError::ExecutionError(format!(
- "Unsupported data type {:?} for result of aggregate expression",
- other
- )));
- }
- };
- Ok(value)
+/// creates an empty record batch.
+pub fn create_batch_empty(schema: &Schema) -> ArrowResult<RecordBatch> {
+ let columns = schema
+ .fields()
+ .iter()
+ .map(|f| match f.data_type() {
+ DataType::Float32 => {
+ Ok(Arc::new(Float32Array::from(vec![] as Vec<f32>)) as ArrayRef)
+ }
+ DataType::Float64 => {
+ Ok(Arc::new(Float64Array::from(vec![] as Vec<f64>)) as ArrayRef)
+ }
+ DataType::Int64 => {
+ Ok(Arc::new(Int64Array::from(vec![] as Vec<i64>)) as ArrayRef)
+ }
+ DataType::Int32 => {
+ Ok(Arc::new(Int32Array::from(vec![] as Vec<i32>)) as ArrayRef)
+ }
+ DataType::Int16 => {
+ Ok(Arc::new(Int16Array::from(vec![] as Vec<i16>)) as ArrayRef)
+ }
+ DataType::Int8 => {
+ Ok(Arc::new(Int8Array::from(vec![] as Vec<i8>)) as ArrayRef)
+ }
+ DataType::UInt64 => {
+ Ok(Arc::new(UInt64Array::from(vec![] as Vec<u64>)) as ArrayRef)
+ }
+ DataType::UInt32 => {
+ Ok(Arc::new(UInt32Array::from(vec![] as Vec<u32>)) as ArrayRef)
+ }
+ DataType::UInt16 => {
+ Ok(Arc::new(UInt16Array::from(vec![] as Vec<u16>)) as ArrayRef)
+ }
+ DataType::UInt8 => {
+ Ok(Arc::new(UInt8Array::from(vec![] as Vec<u8>)) as ArrayRef)
+ }
+ DataType::Utf8 => {
+ Ok(Arc::new(StringArray::from(vec![] as Vec<&str>)) as ArrayRef)
+ }
+ DataType::LargeUtf8 => {
+ Ok(Arc::new(LargeStringArray::from(vec![] as Vec<&str>)) as ArrayRef)
+ }
+ DataType::Boolean => {
+ Ok(Arc::new(BooleanArray::from(vec![] as Vec<bool>)) as ArrayRef)
+ }
+ _ => Err(ExecutionError::NotImplemented(format!(
+ "Cannot convert datatype {:?} to array",
+ f.data_type()
+ ))),
+ })
+ .collect::<Result<_>>()
+ .map_err(ExecutionError::into_arrow_external_error)?;
+ RecordBatch::try_new(Arc::new(schema.to_owned()), columns)
}
diff --git a/rust/datafusion/src/physical_plan/expressions.rs b/rust/datafusion/src/physical_plan/expressions.rs
index a82114c837..8b62079711 100644
--- a/rust/datafusion/src/physical_plan/expressions.rs
+++ b/rust/datafusion/src/physical_plan/expressions.rs
@@ -17,24 +17,19 @@
//! Defines physical expressions that can evaluated at runtime during query execution
-use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;
use std::sync::Arc;
+use std::{cell::RefCell, convert::TryFrom};
use crate::error::{ExecutionError, Result};
-use crate::logical_plan::{Operator, ScalarValue};
-use crate::physical_plan::common::get_scalar_value;
+use crate::logical_plan::Operator;
use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
-use arrow::array::{
- ArrayRef, BooleanArray, Float32Array, Float64Array, Int16Array, Int32Array,
- Int64Array, Int8Array, StringArray, TimestampNanosecondArray, UInt16Array,
- UInt32Array, UInt64Array, UInt8Array,
-};
+use crate::scalar::ScalarValue;
use arrow::array::{
Float32Builder, Float64Builder, Int16Builder, Int32Builder, Int64Builder,
- Int8Builder, StringBuilder, UInt16Builder, UInt32Builder, UInt64Builder,
- UInt8Builder,
+ Int8Builder, LargeStringArray, StringBuilder, UInt16Builder, UInt32Builder,
+ UInt64Builder, UInt8Builder,
};
use arrow::compute;
use arrow::compute::kernels;
@@ -47,6 +42,18 @@ use arrow::compute::kernels::comparison::{
use arrow::compute::kernels::sort::{SortColumn, SortOptions};
use arrow::datatypes::{DataType, Schema, TimeUnit};
use arrow::record_batch::RecordBatch;
+use arrow::{
+ array::{
+ ArrayRef, BooleanArray, Float32Array, Float64Array, Int16Array, Int32Array,
+ Int64Array, Int8Array, StringArray, TimestampNanosecondArray, UInt16Array,
+ UInt32Array, UInt64Array, UInt8Array,
+ },
+ datatypes::Field,
+};
+
+fn format_state_name(name: &str, state_name: &str) -> String {
+ format!("{}[{}]", name, state_name)
+}
/// Represents the column at a given index in a RecordBatch
#[derive(Debug)]
@@ -97,14 +104,10 @@ pub fn col(name: &str) -> Arc<dyn PhysicalExpr> {
/// SUM aggregate expression
#[derive(Debug)]
pub struct Sum {
+ name: String,
+ data_type: DataType,
expr: Arc<dyn PhysicalExpr>,
-}
-
-impl Sum {
- /// Create a new SUM aggregate function
- pub fn new(expr: Arc<dyn PhysicalExpr>) -> Self {
- Self { expr }
- }
+ nullable: bool,
}
/// function return type of a sum
@@ -125,192 +128,216 @@ pub fn sum_return_type(arg_type: &DataType) -> Result<DataType> {
}
}
+impl Sum {
+ /// Create a new SUM aggregate function
+ pub fn new(expr: Arc<dyn PhysicalExpr>, name: String, data_type: DataType) -> Self {
+ Self {
+ name,
+ expr,
+ data_type,
+ nullable: true,
+ }
+ }
+}
+
impl AggregateExpr for Sum {
- fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
- sum_return_type(&self.expr.data_type(input_schema)?)
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(
+ &self.name,
+ self.data_type.clone(),
+ self.nullable,
+ ))
}
- fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
- // null should be returned if no rows are aggregated
- Ok(true)
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![Field::new(
+ &format_state_name(&self.name, "sum"),
+ self.data_type.clone(),
+ self.nullable,
+ )])
}
- fn evaluate_input(&self, batch: &RecordBatch) -> Result<ArrayRef> {
- self.expr.evaluate(batch)
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
}
- fn create_accumulator(&self) -> Rc<RefCell<dyn Accumulator>> {
- Rc::new(RefCell::new(SumAccumulator { sum: None }))
+ fn create_accumulator(&self) -> Result<Rc<RefCell<dyn Accumulator>>> {
+ Ok(Rc::new(RefCell::new(SumAccumulator::try_new(
+ &self.data_type,
+ )?)))
}
+}
- fn create_reducer(&self, column_name: &str) -> Arc<dyn AggregateExpr> {
- Arc::new(Sum::new(Arc::new(Column::new(column_name))))
+#[derive(Debug)]
+struct SumAccumulator {
+ sum: ScalarValue,
+}
+
+impl SumAccumulator {
+ /// new sum accumulator
+ pub fn try_new(data_type: &DataType) -> Result<Self> {
+ Ok(Self {
+ sum: ScalarValue::try_from(data_type)?,
+ })
}
}
-macro_rules! sum_accumulate {
- ($SELF:ident, $VALUE:expr, $ARRAY_TYPE:ident, $SCALAR_VARIANT:ident, $TY:ty) => {{
- $SELF.sum = match $SELF.sum {
- Some(ScalarValue::$SCALAR_VARIANT(n)) => {
- Some(ScalarValue::$SCALAR_VARIANT(n + $VALUE as $TY))
- }
- Some(_) => {
- return Err(ExecutionError::InternalError(
- "Unexpected ScalarValue variant".to_string(),
- ))
- }
- None => Some(ScalarValue::$SCALAR_VARIANT($VALUE as $TY)),
- };
+// returns the new value after sum with the new values, taking nullability into account
+macro_rules! typed_sum_delta_batch {
+ ($VALUES:expr, $ARRAYTYPE:ident, $SCALAR:ident) => {{
+ let array = $VALUES.as_any().downcast_ref::<$ARRAYTYPE>().unwrap();
+ let delta = compute::sum(array);
+ ScalarValue::$SCALAR(delta)
}};
}
-#[derive(Debug)]
-struct SumAccumulator {
- sum: Option<ScalarValue>,
+// sums the array and returns a ScalarValue of its corresponding type.
+fn sum_batch(values: &ArrayRef) -> Result<ScalarValue> {
+ Ok(match values.data_type() {
+ DataType::Float64 => typed_sum_delta_batch!(values, Float64Array, Float64),
+ DataType::Float32 => typed_sum_delta_batch!(values, Float32Array, Float32),
+ DataType::Int64 => typed_sum_delta_batch!(values, Int64Array, Int64),
+ DataType::Int32 => typed_sum_delta_batch!(values, Int32Array, Int32),
+ DataType::Int16 => typed_sum_delta_batch!(values, Int16Array, Int16),
+ DataType::Int8 => typed_sum_delta_batch!(values, Int8Array, Int8),
+ DataType::UInt64 => typed_sum_delta_batch!(values, UInt64Array, UInt64),
+ DataType::UInt32 => typed_sum_delta_batch!(values, UInt32Array, UInt32),
+ DataType::UInt16 => typed_sum_delta_batch!(values, UInt16Array, UInt16),
+ DataType::UInt8 => typed_sum_delta_batch!(values, UInt8Array, UInt8),
+ e => {
+ return Err(ExecutionError::InternalError(format!(
+ "Sum is not expected to receive the type {:?}",
+ e
+ )))
+ }
+ })
}
-impl Accumulator for SumAccumulator {
- fn accumulate_scalar(&mut self, value: Option<ScalarValue>) -> Result<()> {
- if let Some(value) = value {
- match value {
- ScalarValue::Int8(value) => {
- sum_accumulate!(self, value, Int8Array, Int64, i64);
- }
- ScalarValue::Int16(value) => {
- sum_accumulate!(self, value, Int16Array, Int64, i64);
- }
- ScalarValue::Int32(value) => {
- sum_accumulate!(self, value, Int32Array, Int64, i64);
- }
- ScalarValue::Int64(value) => {
- sum_accumulate!(self, value, Int64Array, Int64, i64);
- }
- ScalarValue::UInt8(value) => {
- sum_accumulate!(self, value, UInt8Array, UInt64, u64);
- }
- ScalarValue::UInt16(value) => {
- sum_accumulate!(self, value, UInt16Array, UInt64, u64);
- }
- ScalarValue::UInt32(value) => {
- sum_accumulate!(self, value, UInt32Array, UInt64, u64);
- }
- ScalarValue::UInt64(value) => {
- sum_accumulate!(self, value, UInt64Array, UInt64, u64);
- }
- ScalarValue::Float32(value) => {
- sum_accumulate!(self, value, Float32Array, Float32, f32);
- }
- ScalarValue::Float64(value) => {
- sum_accumulate!(self, value, Float64Array, Float64, f64);
- }
- other => {
- return Err(ExecutionError::General(format!(
- "SUM does not support {:?}",
- other
- )))
- }
- }
+// returns the sum of two scalar values, including coercion into $TYPE.
+macro_rules! typed_sum {
+ ($OLD_VALUE:expr, $DELTA:expr, $SCALAR:ident, $TYPE:ident) => {{
+ ScalarValue::$SCALAR(match ($OLD_VALUE, $DELTA) {
+ (None, None) => None,
+ (Some(a), None) => Some(a.clone()),
+ (None, Some(b)) => Some(b.clone() as $TYPE),
+ (Some(a), Some(b)) => Some(a + (*b as $TYPE)),
+ })
+ }};
+}
+
+fn sum(lhs: &ScalarValue, rhs: &ScalarValue) -> Result<ScalarValue> {
+ Ok(match (lhs, rhs) {
+ // float64 coerces everything to f64
+ (ScalarValue::Float64(lhs), ScalarValue::Float64(rhs)) => {
+ typed_sum!(lhs, rhs, Float64, f64)
+ }
+ (ScalarValue::Float64(lhs), ScalarValue::Float32(rhs)) => {
+ typed_sum!(lhs, rhs, Float64, f64)
+ }
+ (ScalarValue::Float64(lhs), ScalarValue::Int64(rhs)) => {
+ typed_sum!(lhs, rhs, Float64, f64)
}
+ (ScalarValue::Float64(lhs), ScalarValue::Int32(rhs)) => {
+ typed_sum!(lhs, rhs, Float64, f64)
+ }
+ (ScalarValue::Float64(lhs), ScalarValue::Int16(rhs)) => {
+ typed_sum!(lhs, rhs, Float64, f64)
+ }
+ (ScalarValue::Float64(lhs), ScalarValue::Int8(rhs)) => {
+ typed_sum!(lhs, rhs, Float64, f64)
+ }
+ (ScalarValue::Float64(lhs), ScalarValue::UInt64(rhs)) => {
+ typed_sum!(lhs, rhs, Float64, f64)
+ }
+ (ScalarValue::Float64(lhs), ScalarValue::UInt32(rhs)) => {
+ typed_sum!(lhs, rhs, Float64, f64)
+ }
+ (ScalarValue::Float64(lhs), ScalarValue::UInt16(rhs)) => {
+ typed_sum!(lhs, rhs, Float64, f64)
+ }
+ (ScalarValue::Float64(lhs), ScalarValue::UInt8(rhs)) => {
+ typed_sum!(lhs, rhs, Float64, f64)
+ }
+ // float32 has no cast
+ (ScalarValue::Float32(lhs), ScalarValue::Float32(rhs)) => {
+ typed_sum!(lhs, rhs, Float32, f32)
+ }
+ // u64 coerces u* to u64
+ (ScalarValue::UInt64(lhs), ScalarValue::UInt64(rhs)) => {
+ typed_sum!(lhs, rhs, UInt64, u64)
+ }
+ (ScalarValue::UInt64(lhs), ScalarValue::UInt32(rhs)) => {
+ typed_sum!(lhs, rhs, UInt64, u64)
+ }
+ (ScalarValue::UInt64(lhs), ScalarValue::UInt16(rhs)) => {
+ typed_sum!(lhs, rhs, UInt64, u64)
+ }
+ (ScalarValue::UInt64(lhs), ScalarValue::UInt8(rhs)) => {
+ typed_sum!(lhs, rhs, UInt64, u64)
+ }
+ // i64 coerces i* to u64
+ (ScalarValue::Int64(lhs), ScalarValue::Int64(rhs)) => {
+ typed_sum!(lhs, rhs, Int64, i64)
+ }
+ (ScalarValue::Int64(lhs), ScalarValue::Int32(rhs)) => {
+ typed_sum!(lhs, rhs, Int64, i64)
+ }
+ (ScalarValue::Int64(lhs), ScalarValue::Int16(rhs)) => {
+ typed_sum!(lhs, rhs, Int64, i64)
+ }
+ (ScalarValue::Int64(lhs), ScalarValue::Int8(rhs)) => {
+ typed_sum!(lhs, rhs, Int64, i64)
+ }
+ e => {
+ return Err(ExecutionError::InternalError(format!(
+ "Sum is not expected to receive a scalar {:?}",
+ e
+ )))
+ }
+ })
+}
+
+impl Accumulator for SumAccumulator {
+ fn update_batch(&mut self, values: &Vec<ArrayRef>) -> Result<()> {
+ let values = &values[0];
+ self.sum = sum(&self.sum, &sum_batch(values)?)?;
Ok(())
}
- fn accumulate_batch(&mut self, array: &ArrayRef) -> Result<()> {
- let sum = match array.data_type() {
- DataType::UInt8 => {
- match compute::sum(array.as_any().downcast_ref::<UInt8Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::UInt8(n))),
- None => Ok(None),
- }
- }
- DataType::UInt16 => {
- match compute::sum(array.as_any().downcast_ref::<UInt16Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::UInt16(n))),
- None => Ok(None),
- }
- }
- DataType::UInt32 => {
- match compute::sum(array.as_any().downcast_ref::<UInt32Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::UInt32(n))),
- None => Ok(None),
- }
- }
- DataType::UInt64 => {
- match compute::sum(array.as_any().downcast_ref::<UInt64Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::UInt64(n))),
- None => Ok(None),
- }
- }
- DataType::Int8 => {
- match compute::sum(array.as_any().downcast_ref::<Int8Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::Int8(n))),
- None => Ok(None),
- }
- }
- DataType::Int16 => {
- match compute::sum(array.as_any().downcast_ref::<Int16Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::Int16(n))),
- None => Ok(None),
- }
- }
- DataType::Int32 => {
- match compute::sum(array.as_any().downcast_ref::<Int32Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::Int32(n))),
- None => Ok(None),
- }
- }
- DataType::Int64 => {
- match compute::sum(array.as_any().downcast_ref::<Int64Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::Int64(n))),
- None => Ok(None),
- }
- }
- DataType::Float32 => {
- match compute::sum(array.as_any().downcast_ref::<Float32Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::Float32(n))),
- None => Ok(None),
- }
- }
- DataType::Float64 => {
- match compute::sum(array.as_any().downcast_ref::<Float64Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::Float64(n))),
- None => Ok(None),
- }
- }
- _ => Err(ExecutionError::ExecutionError(
- "Unsupported data type for SUM".to_string(),
- )),
- }?;
- self.accumulate_scalar(sum)
+ fn update(&mut self, values: &Vec<ScalarValue>) -> Result<()> {
+ // sum(v1, v2, v3) = v1 + v2 + v3
+ self.sum = sum(&self.sum, &values[0])?;
+ Ok(())
}
- fn get_value(&self) -> Result<Option<ScalarValue>> {
- Ok(self.sum.clone())
+ fn merge(&mut self, states: &Vec<ScalarValue>) -> Result<()> {
+ // sum(sum1, sum2) = sum1 + sum2
+ self.update(states)
+ }
+
+ fn merge_batch(&mut self, states: &Vec<ArrayRef>) -> Result<()> {
+ // sum(sum1, sum2, sum3, ...) = sum1 + sum2 + sum3 + ...
+ self.update_batch(states)
}
-}
-/// Create a sum expression
-pub fn sum(expr: Arc<dyn PhysicalExpr>) -> Arc<dyn AggregateExpr> {
- Arc::new(Sum::new(expr))
+ fn state(&self) -> Result<Vec<ScalarValue>> {
+ Ok(vec![self.sum.clone()])
+ }
+
+ fn evaluate(&self) -> Result<ScalarValue> {
+ Ok(self.sum.clone())
+ }
}
/// AVG aggregate expression
#[derive(Debug)]
pub struct Avg {
+ name: String,
+ data_type: DataType,
+ nullable: bool,
expr: Arc<dyn PhysicalExpr>,
}
-impl Avg {
- /// Create a new AVG aggregate function
- pub fn new(expr: Arc<dyn PhysicalExpr>) -> Self {
- Self { expr }
- }
-}
-
/// function return type of an average
pub fn avg_return_type(arg_type: &DataType) -> Result<DataType> {
match arg_type {
@@ -331,542 +358,604 @@ pub fn avg_return_type(arg_type: &DataType) -> Result<DataType> {
}
}
-impl AggregateExpr for Avg {
- fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
- avg_return_type(&self.expr.data_type(input_schema)?)
+impl Avg {
+ /// Create a new AVG aggregate function
+ pub fn new(expr: Arc<dyn PhysicalExpr>, name: String, data_type: DataType) -> Self {
+ Self {
+ name,
+ expr,
+ data_type,
+ nullable: true,
+ }
}
+}
- fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
- // null should be returned if no rows are aggregated
- Ok(true)
+impl AggregateExpr for Avg {
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(&self.name, DataType::Float64, true))
}
- fn evaluate_input(&self, batch: &RecordBatch) -> Result<ArrayRef> {
- self.expr.evaluate(batch)
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![
+ Field::new(
+ &format_state_name(&self.name, "count"),
+ DataType::UInt64,
+ true,
+ ),
+ Field::new(
+ &format_state_name(&self.name, "sum"),
+ DataType::Float64,
+ true,
+ ),
+ ])
}
- fn create_accumulator(&self) -> Rc<RefCell<dyn Accumulator>> {
- Rc::new(RefCell::new(AvgAccumulator {
- sum: None,
- count: None,
- }))
+ fn create_accumulator(&self) -> Result<Rc<RefCell<dyn Accumulator>>> {
+ Ok(Rc::new(RefCell::new(AvgAccumulator::try_new(
+ // avg is f64
+ &DataType::Float64,
+ )?)))
}
- fn create_reducer(&self, column_name: &str) -> Arc<dyn AggregateExpr> {
- Arc::new(Avg::new(Arc::new(Column::new(column_name))))
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
}
}
-macro_rules! avg_accumulate {
- ($SELF:ident, $VALUE:expr, $ARRAY_TYPE:ident) => {{
- match ($SELF.sum, $SELF.count) {
- (Some(sum), Some(count)) => {
- $SELF.sum = Some(sum + $VALUE as f64);
- $SELF.count = Some(count + 1);
- }
- _ => {
- $SELF.sum = Some($VALUE as f64);
- $SELF.count = Some(1);
- }
- };
- }};
-}
#[derive(Debug)]
struct AvgAccumulator {
- sum: Option<f64>,
- count: Option<i64>,
+ // sum is used for null
+ sum: ScalarValue,
+ count: u64,
+}
+
+impl AvgAccumulator {
+ pub fn try_new(datatype: &DataType) -> Result<Self> {
+ Ok(Self {
+ sum: ScalarValue::try_from(datatype)?,
+ count: 0,
+ })
+ }
}
impl Accumulator for AvgAccumulator {
- fn accumulate_scalar(&mut self, value: Option<ScalarValue>) -> Result<()> {
- if let Some(value) = value {
- match value {
- ScalarValue::Int8(value) => avg_accumulate!(self, value, Int8Array),
- ScalarValue::Int16(value) => avg_accumulate!(self, value, Int16Array),
- ScalarValue::Int32(value) => avg_accumulate!(self, value, Int32Array),
- ScalarValue::Int64(value) => avg_accumulate!(self, value, Int64Array),
- ScalarValue::UInt8(value) => avg_accumulate!(self, value, UInt8Array),
- ScalarValue::UInt16(value) => avg_accumulate!(self, value, UInt16Array),
- ScalarValue::UInt32(value) => avg_accumulate!(self, value, UInt32Array),
- ScalarValue::UInt64(value) => avg_accumulate!(self, value, UInt64Array),
- ScalarValue::Float32(value) => avg_accumulate!(self, value, Float32Array),
- ScalarValue::Float64(value) => avg_accumulate!(self, value, Float64Array),
- other => {
- return Err(ExecutionError::General(format!(
- "AVG does not support {:?}",
- other
- )))
- }
- }
- }
+ fn state(&self) -> Result<Vec<ScalarValue>> {
+ Ok(vec![ScalarValue::from(self.count), self.sum.clone()])
+ }
+
+ fn update(&mut self, values: &Vec<ScalarValue>) -> Result<()> {
+ let values = &values[0];
+
+ self.count += (!values.is_null()) as u64;
+ self.sum = sum(&self.sum, values)?;
+
Ok(())
}
- fn accumulate_batch(&mut self, array: &ArrayRef) -> Result<()> {
- for row in 0..array.len() {
- self.accumulate_scalar(get_scalar_value(array, row)?)?;
- }
+ fn update_batch(&mut self, values: &Vec<ArrayRef>) -> Result<()> {
+ let values = &values[0];
+
+ self.count += (values.len() - values.data().null_count()) as u64;
+ self.sum = sum(&self.sum, &sum_batch(values)?)?;
Ok(())
}
- fn get_value(&self) -> Result<Option<ScalarValue>> {
- match (self.sum, self.count) {
- (Some(sum), Some(count)) => {
- Ok(Some(ScalarValue::Float64(sum / count as f64)))
- }
- _ => Ok(None),
- }
+ fn merge(&mut self, states: &Vec<ScalarValue>) -> Result<()> {
+ let count = &states[0];
+ // counts are summed
+ if let ScalarValue::UInt64(Some(c)) = count {
+ self.count += c
+ } else {
+ unreachable!()
+ };
+
+ // sums are summed
+ self.sum = sum(&self.sum, &states[1])?;
+ Ok(())
}
-}
-/// Create a avg expression
-pub fn avg(expr: Arc<dyn PhysicalExpr>) -> Arc<dyn AggregateExpr> {
- Arc::new(Avg::new(expr))
+ fn merge_batch(&mut self, states: &Vec<ArrayRef>) -> Result<()> {
+ let counts = states[0].as_any().downcast_ref::<UInt64Array>().unwrap();
+ // counts are summed
+ self.count += compute::sum(counts).unwrap_or(0);
+
+ // sums are summed
+ self.sum = sum(&self.sum, &sum_batch(&states[1])?)?;
+ Ok(())
+ }
+
+ fn evaluate(&self) -> Result<ScalarValue> {
+ match self.sum {
+ ScalarValue::Float64(e) => Ok(ScalarValue::Float64(match e {
+ Some(f) => Some(f / self.count as f64),
+ None => None,
+ })),
+ _ => Err(ExecutionError::InternalError(
+ "Sum should be f64 on average".to_string(),
+ )),
+ }
+ }
}
/// MAX aggregate expression
#[derive(Debug)]
pub struct Max {
+ name: String,
+ data_type: DataType,
+ nullable: bool,
expr: Arc<dyn PhysicalExpr>,
}
impl Max {
/// Create a new MAX aggregate function
- pub fn new(expr: Arc<dyn PhysicalExpr>) -> Self {
- Self { expr }
+ pub fn new(expr: Arc<dyn PhysicalExpr>, name: String, data_type: DataType) -> Self {
+ Self {
+ name,
+ expr,
+ data_type,
+ nullable: true,
+ }
}
}
impl AggregateExpr for Max {
- fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
- self.expr.data_type(input_schema)
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(
+ &self.name,
+ self.data_type.clone(),
+ self.nullable,
+ ))
}
- fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
- // null should be returned if no rows are aggregated
- Ok(true)
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![Field::new(
+ &format_state_name(&self.name, "max"),
+ self.data_type.clone(),
+ true,
+ )])
}
- fn evaluate_input(&self, batch: &RecordBatch) -> Result<ArrayRef> {
- self.expr.evaluate(batch)
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
}
- fn create_accumulator(&self) -> Rc<RefCell<dyn Accumulator>> {
- Rc::new(RefCell::new(MaxAccumulator { max: None }))
+ fn create_accumulator(&self) -> Result<Rc<RefCell<dyn Accumulator>>> {
+ Ok(Rc::new(RefCell::new(MaxAccumulator::try_new(
+ &self.data_type,
+ )?)))
}
+}
- fn create_reducer(&self, column_name: &str) -> Arc<dyn AggregateExpr> {
- Arc::new(Max::new(Arc::new(Column::new(column_name))))
- }
+// Statically-typed version of min/max(array) -> ScalarValue for string types.
+macro_rules! typed_min_max_batch_string {
+ ($VALUES:expr, $ARRAYTYPE:ident, $SCALAR:ident, $OP:ident) => {{
+ let array = $VALUES.as_any().downcast_ref::<$ARRAYTYPE>().unwrap();
+ let value = compute::$OP(array);
+ let value = value.and_then(|e| Some(e.to_string()));
+ ScalarValue::$SCALAR(value)
+ }};
}
-macro_rules! max_accumulate {
- ($SELF:ident, $VALUE:expr, $ARRAY_TYPE:ident, $SCALAR_VARIANT:ident) => {{
- match &$SELF.max {
- Some(ScalarValue::$SCALAR_VARIANT(n)) => {
- if ($VALUE) > *n {
- $SELF.max = Some(ScalarValue::$SCALAR_VARIANT($VALUE))
- }
+// Statically-typed version of min/max(array) -> ScalarValue for non-string types.
+macro_rules! typed_min_max_batch {
+ ($VALUES:expr, $ARRAYTYPE:ident, $SCALAR:ident, $OP:ident) => {{
+ let array = $VALUES.as_any().downcast_ref::<$ARRAYTYPE>().unwrap();
+ let value = compute::$OP(array);
+ ScalarValue::$SCALAR(value)
+ }};
+}
+
+// Statically-typed version of min/max(array) -> ScalarValue for non-string types.
+// this is a macro to support both operations (min and max).
+macro_rules! min_max_batch {
+ ($VALUES:expr, $OP:ident) => {{
+ match $VALUES.data_type() {
+ // all types that have a natural order
+ DataType::Float64 => {
+ typed_min_max_batch!($VALUES, Float64Array, Float64, $OP)
}
- Some(_) => {
- return Err(ExecutionError::InternalError(
- "Unexpected ScalarValue variant".to_string(),
- ))
+ DataType::Float32 => {
+ typed_min_max_batch!($VALUES, Float32Array, Float32, $OP)
}
- None => $SELF.max = Some(ScalarValue::$SCALAR_VARIANT($VALUE)),
- };
+ DataType::Int64 => typed_min_max_batch!($VALUES, Int64Array, Int64, $OP),
+ DataType::Int32 => typed_min_max_batch!($VALUES, Int32Array, Int32, $OP),
+ DataType::Int16 => typed_min_max_batch!($VALUES, Int16Array, Int16, $OP),
+ DataType::Int8 => typed_min_max_batch!($VALUES, Int8Array, Int8, $OP),
+ DataType::UInt64 => typed_min_max_batch!($VALUES, UInt64Array, UInt64, $OP),
+ DataType::UInt32 => typed_min_max_batch!($VALUES, UInt32Array, UInt32, $OP),
+ DataType::UInt16 => typed_min_max_batch!($VALUES, UInt16Array, UInt16, $OP),
+ DataType::UInt8 => typed_min_max_batch!($VALUES, UInt8Array, UInt8, $OP),
+ other => {
+ return Err(ExecutionError::NotImplemented(format!(
+ "Min/Max accumulator not implemented for type {:?}",
+ other
+ )))
+ }
+ }
}};
}
-#[derive(Debug)]
-struct MaxAccumulator {
- max: Option<ScalarValue>,
-}
-impl Accumulator for MaxAccumulator {
- fn accumulate_scalar(&mut self, value: Option<ScalarValue>) -> Result<()> {
- if let Some(value) = value {
- match value {
- ScalarValue::Int8(value) => {
- max_accumulate!(self, value, Int8Array, Int8);
- }
- ScalarValue::Int16(value) => {
- max_accumulate!(self, value, Int16Array, Int16)
- }
- ScalarValue::Int32(value) => {
- max_accumulate!(self, value, Int32Array, Int32)
- }
- ScalarValue::Int64(value) => {
- max_accumulate!(self, value, Int64Array, Int64)
- }
- ScalarValue::UInt8(value) => {
- max_accumulate!(self, value, UInt8Array, UInt8)
- }
- ScalarValue::UInt16(value) => {
- max_accumulate!(self, value, UInt16Array, UInt16)
- }
- ScalarValue::UInt32(value) => {
- max_accumulate!(self, value, UInt32Array, UInt32)
- }
- ScalarValue::UInt64(value) => {
- max_accumulate!(self, value, UInt64Array, UInt64)
- }
- ScalarValue::Float32(value) => {
- max_accumulate!(self, value, Float32Array, Float32)
- }
- ScalarValue::Float64(value) => {
- max_accumulate!(self, value, Float64Array, Float64)
- }
- ScalarValue::Utf8(value) => {
- max_accumulate!(self, value, StringArray, Utf8)
- }
- other => {
- return Err(ExecutionError::General(format!(
- "MAX does not support {:?}",
- other
- )))
- }
- }
+/// dynamically-typed min(array) -> ScalarValue
+fn min_batch(values: &ArrayRef) -> Result<ScalarValue> {
+ Ok(match values.data_type() {
+ DataType::Utf8 => {
+ typed_min_max_batch_string!(values, StringArray, Utf8, min_string)
}
- Ok(())
- }
+ DataType::LargeUtf8 => typed_min_max_batch_string!(
+ values,
+ LargeStringArray,
+ LargeUtf8,
+ min_large_string
+ ),
+ _ => min_max_batch!(values, min),
+ })
+}
+
+/// dynamically-typed max(array) -> ScalarValue
+fn max_batch(values: &ArrayRef) -> Result<ScalarValue> {
+ Ok(match values.data_type() {
+ DataType::Utf8 => {
+ typed_min_max_batch_string!(values, StringArray, Utf8, max_string)
+ }
+ DataType::LargeUtf8 => typed_min_max_batch_string!(
+ values,
+ LargeStringArray,
+ LargeUtf8,
+ max_large_string
+ ),
+ _ => min_max_batch!(values, max),
+ })
+}
+
+// min/max of two non-string scalar values.
+macro_rules! typed_min_max {
+ ($VALUE:expr, $DELTA:expr, $SCALAR:ident, $OP:ident) => {{
+ ScalarValue::$SCALAR(match ($VALUE, $DELTA) {
+ (None, None) => None,
+ (Some(a), None) => Some(a.clone()),
+ (None, Some(b)) => Some(b.clone()),
+ (Some(a), Some(b)) => Some((*a).$OP(*b)),
+ })
+ }};
+}
- fn accumulate_batch(&mut self, array: &ArrayRef) -> Result<()> {
- let max = match array.data_type() {
- DataType::UInt8 => {
- match compute::max(array.as_any().downcast_ref::<UInt8Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::UInt8(n))),
- None => Ok(None),
- }
+// min/max of two scalar string values.
+macro_rules! typed_min_max_string {
+ ($VALUE:expr, $DELTA:expr, $SCALAR:ident, $OP:ident) => {{
+ ScalarValue::$SCALAR(match ($VALUE, $DELTA) {
+ (None, None) => None,
+ (Some(a), None) => Some(a.clone()),
+ (None, Some(b)) => Some(b.clone()),
+ (Some(a), Some(b)) => Some((a).$OP(b).clone()),
+ })
+ }};
+}
+
+// min/max of two scalar values of the same type
+macro_rules! min_max {
+ ($VALUE:expr, $DELTA:expr, $OP:ident) => {{
+ Ok(match ($VALUE, $DELTA) {
+ (ScalarValue::Float64(lhs), ScalarValue::Float64(rhs)) => {
+ typed_min_max!(lhs, rhs, Float64, $OP)
}
- DataType::UInt16 => {
- match compute::max(array.as_any().downcast_ref::<UInt16Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::UInt16(n))),
- None => Ok(None),
- }
+ (ScalarValue::Float32(lhs), ScalarValue::Float32(rhs)) => {
+ typed_min_max!(lhs, rhs, Float32, $OP)
}
- DataType::UInt32 => {
- match compute::max(array.as_any().downcast_ref::<UInt32Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::UInt32(n))),
- None => Ok(None),
- }
+ (ScalarValue::UInt64(lhs), ScalarValue::UInt64(rhs)) => {
+ typed_min_max!(lhs, rhs, UInt64, $OP)
}
- DataType::UInt64 => {
- match compute::max(array.as_any().downcast_ref::<UInt64Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::UInt64(n))),
- None => Ok(None),
- }
+ (ScalarValue::UInt32(lhs), ScalarValue::UInt32(rhs)) => {
+ typed_min_max!(lhs, rhs, UInt32, $OP)
}
- DataType::Int8 => {
- match compute::max(array.as_any().downcast_ref::<Int8Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::Int8(n))),
- None => Ok(None),
- }
+ (ScalarValue::UInt16(lhs), ScalarValue::UInt16(rhs)) => {
+ typed_min_max!(lhs, rhs, UInt16, $OP)
}
- DataType::Int16 => {
- match compute::max(array.as_any().downcast_ref::<Int16Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::Int16(n))),
- None => Ok(None),
- }
+ (ScalarValue::UInt8(lhs), ScalarValue::UInt8(rhs)) => {
+ typed_min_max!(lhs, rhs, UInt8, $OP)
}
- DataType::Int32 => {
- match compute::max(array.as_any().downcast_ref::<Int32Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::Int32(n))),
- None => Ok(None),
- }
+ (ScalarValue::Int64(lhs), ScalarValue::Int64(rhs)) => {
+ typed_min_max!(lhs, rhs, Int64, $OP)
}
- DataType::Int64 => {
- match compute::max(array.as_any().downcast_ref::<Int64Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::Int64(n))),
- None => Ok(None),
- }
+ (ScalarValue::Int32(lhs), ScalarValue::Int32(rhs)) => {
+ typed_min_max!(lhs, rhs, Int32, $OP)
}
- DataType::Float32 => {
- match compute::max(array.as_any().downcast_ref::<Float32Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::Float32(n))),
- None => Ok(None),
- }
+ (ScalarValue::Int16(lhs), ScalarValue::Int16(rhs)) => {
+ typed_min_max!(lhs, rhs, Int16, $OP)
}
- DataType::Float64 => {
- match compute::max(array.as_any().downcast_ref::<Float64Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::Float64(n))),
- None => Ok(None),
- }
+ (ScalarValue::Int8(lhs), ScalarValue::Int8(rhs)) => {
+ typed_min_max!(lhs, rhs, Int8, $OP)
}
- _ => Err(ExecutionError::ExecutionError(
- "Unsupported data type for MAX".to_string(),
- )),
- }?;
- self.accumulate_scalar(max)
- }
+ (ScalarValue::Utf8(lhs), ScalarValue::Utf8(rhs)) => {
+ typed_min_max_string!(lhs, rhs, Utf8, $OP)
+ }
+ (ScalarValue::LargeUtf8(lhs), ScalarValue::LargeUtf8(rhs)) => {
+ typed_min_max_string!(lhs, rhs, LargeUtf8, $OP)
+ }
+ e => {
+ return Err(ExecutionError::InternalError(format!(
+ "MIN/MAX is not expected to receive a scalar {:?}",
+ e
+ )))
+ }
+ })
+ }};
+}
- fn get_value(&self) -> Result<Option<ScalarValue>> {
- Ok(self.max.clone())
+/// the minimum of two scalar values
+fn min(lhs: &ScalarValue, rhs: &ScalarValue) -> Result<ScalarValue> {
+ min_max!(lhs, rhs, min)
+}
+
+/// the maximum of two scalar values
+fn max(lhs: &ScalarValue, rhs: &ScalarValue) -> Result<ScalarValue> {
+ min_max!(lhs, rhs, max)
+}
+
+#[derive(Debug)]
+struct MaxAccumulator {
+ max: ScalarValue,
+}
+
+impl MaxAccumulator {
+ /// new max accumulator
+ pub fn try_new(datatype: &DataType) -> Result<Self> {
+ Ok(Self {
+ max: ScalarValue::try_from(datatype)?,
+ })
}
}
-/// Create a max expression
-pub fn max(expr: Arc<dyn PhysicalExpr>) -> Arc<dyn AggregateExpr> {
- Arc::new(Max::new(expr))
+impl Accumulator for MaxAccumulator {
+ fn update_batch(&mut self, values: &Vec<ArrayRef>) -> Result<()> {
+ let values = &values[0];
+ let delta = &max_batch(values)?;
+ self.max = max(&self.max, delta)?;
+ Ok(())
+ }
+
+ fn update(&mut self, values: &Vec<ScalarValue>) -> Result<()> {
+ let value = &values[0];
+ self.max = max(&self.max, value)?;
+ Ok(())
+ }
+
+ fn merge(&mut self, states: &Vec<ScalarValue>) -> Result<()> {
+ self.update(states)
+ }
+
+ fn merge_batch(&mut self, states: &Vec<ArrayRef>) -> Result<()> {
+ self.update_batch(states)
+ }
+
+ fn state(&self) -> Result<Vec<ScalarValue>> {
+ Ok(vec![self.max.clone()])
+ }
+
+ fn evaluate(&self) -> Result<ScalarValue> {
+ Ok(self.max.clone())
+ }
}
/// MIN aggregate expression
#[derive(Debug)]
pub struct Min {
+ name: String,
+ data_type: DataType,
+ nullable: bool,
expr: Arc<dyn PhysicalExpr>,
}
impl Min {
/// Create a new MIN aggregate function
- pub fn new(expr: Arc<dyn PhysicalExpr>) -> Self {
- Self { expr }
+ pub fn new(expr: Arc<dyn PhysicalExpr>, name: String, data_type: DataType) -> Self {
+ Self {
+ name,
+ expr,
+ data_type,
+ nullable: true,
+ }
}
}
impl AggregateExpr for Min {
- fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
- self.expr.data_type(input_schema)
- }
-
- fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
- // null should be returned if no rows are aggregated
- Ok(true)
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(
+ &self.name,
+ self.data_type.clone(),
+ self.nullable,
+ ))
}
- fn evaluate_input(&self, batch: &RecordBatch) -> Result<ArrayRef> {
- self.expr.evaluate(batch)
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![Field::new(
+ &format_state_name(&self.name, "min"),
+ self.data_type.clone(),
+ true,
+ )])
}
- fn create_accumulator(&self) -> Rc<RefCell<dyn Accumulator>> {
- Rc::new(RefCell::new(MinAccumulator { min: None }))
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
}
- fn create_reducer(&self, column_name: &str) -> Arc<dyn AggregateExpr> {
- Arc::new(Min::new(Arc::new(Column::new(column_name))))
+ fn create_accumulator(&self) -> Result<Rc<RefCell<dyn Accumulator>>> {
+ Ok(Rc::new(RefCell::new(MinAccumulator::try_new(
+ &self.data_type,
+ )?)))
}
}
-macro_rules! min_accumulate {
- ($SELF:ident, $VALUE:expr, $ARRAY_TYPE:ident, $SCALAR_VARIANT:ident) => {{
- match &$SELF.min {
- Some(ScalarValue::$SCALAR_VARIANT(n)) => {
- if ($VALUE) < *n {
- $SELF.min = Some(ScalarValue::$SCALAR_VARIANT($VALUE))
- }
- }
- Some(_) => {
- return Err(ExecutionError::InternalError(
- "Unexpected ScalarValue variant".to_string(),
- ))
- }
- None => $SELF.min = Some(ScalarValue::$SCALAR_VARIANT($VALUE)),
- };
- }};
-}
#[derive(Debug)]
struct MinAccumulator {
- min: Option<ScalarValue>,
+ min: ScalarValue,
+}
+
+impl MinAccumulator {
+ /// new min accumulator
+ pub fn try_new(datatype: &DataType) -> Result<Self> {
+ Ok(Self {
+ min: ScalarValue::try_from(datatype)?,
+ })
+ }
}
impl Accumulator for MinAccumulator {
- fn accumulate_scalar(&mut self, value: Option<ScalarValue>) -> Result<()> {
- if let Some(value) = value {
- match value {
- ScalarValue::Int8(value) => {
- min_accumulate!(self, value, Int8Array, Int8);
- }
- ScalarValue::Int16(value) => {
- min_accumulate!(self, value, Int16Array, Int16)
- }
- ScalarValue::Int32(value) => {
- min_accumulate!(self, value, Int32Array, Int32)
- }
- ScalarValue::Int64(value) => {
- min_accumulate!(self, value, Int64Array, Int64)
- }
- ScalarValue::UInt8(value) => {
- min_accumulate!(self, value, UInt8Array, UInt8)
- }
- ScalarValue::UInt16(value) => {
- min_accumulate!(self, value, UInt16Array, UInt16)
- }
- ScalarValue::UInt32(value) => {
- min_accumulate!(self, value, UInt32Array, UInt32)
- }
- ScalarValue::UInt64(value) => {
- min_accumulate!(self, value, UInt64Array, UInt64)
- }
- ScalarValue::Float32(value) => {
- min_accumulate!(self, value, Float32Array, Float32)
- }
- ScalarValue::Float64(value) => {
- min_accumulate!(self, value, Float64Array, Float64)
- }
- ScalarValue::Utf8(value) => {
- min_accumulate!(self, value, StringArray, Utf8)
- }
- other => {
- return Err(ExecutionError::General(format!(
- "MIN does not support {:?}",
- other
- )))
- }
- }
- }
+ fn state(&self) -> Result<Vec<ScalarValue>> {
+ Ok(vec![self.min.clone()])
+ }
+
+ fn update_batch(&mut self, values: &Vec<ArrayRef>) -> Result<()> {
+ let values = &values[0];
+ let delta = &min_batch(values)?;
+ self.min = min(&self.min, delta)?;
Ok(())
}
- fn accumulate_batch(&mut self, array: &ArrayRef) -> Result<()> {
- let min = match array.data_type() {
- DataType::UInt8 => {
- match compute::min(array.as_any().downcast_ref::<UInt8Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::UInt8(n))),
- None => Ok(None),
- }
- }
- DataType::UInt16 => {
- match compute::min(array.as_any().downcast_ref::<UInt16Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::UInt16(n))),
- None => Ok(None),
- }
- }
- DataType::UInt32 => {
- match compute::min(array.as_any().downcast_ref::<UInt32Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::UInt32(n))),
- None => Ok(None),
- }
- }
- DataType::UInt64 => {
- match compute::min(array.as_any().downcast_ref::<UInt64Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::UInt64(n))),
- None => Ok(None),
- }
- }
- DataType::Int8 => {
- match compute::min(array.as_any().downcast_ref::<Int8Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::Int8(n))),
- None => Ok(None),
- }
- }
- DataType::Int16 => {
- match compute::min(array.as_any().downcast_ref::<Int16Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::Int16(n))),
- None => Ok(None),
- }
- }
- DataType::Int32 => {
- match compute::min(array.as_any().downcast_ref::<Int32Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::Int32(n))),
- None => Ok(None),
- }
- }
- DataType::Int64 => {
- match compute::min(array.as_any().downcast_ref::<Int64Array>().unwrap()) {
- Some(n) => Ok(Some(ScalarValue::Int64(n))),
- None => Ok(None),
- }
- }
- DataType::Float32 => {
- match compute::min(array.as_any().downcast_ref::<Float32Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::Float32(n))),
- None => Ok(None),
- }
- }
- DataType::Float64 => {
- match compute::min(array.as_any().downcast_ref::<Float64Array>().unwrap())
- {
- Some(n) => Ok(Some(ScalarValue::Float64(n))),
- None => Ok(None),
- }
- }
- _ => Err(ExecutionError::ExecutionError(
- "Unsupported data type for MIN".to_string(),
- )),
- }?;
- self.accumulate_scalar(min)
+ fn update(&mut self, values: &Vec<ScalarValue>) -> Result<()> {
+ let value = &values[0];
+ self.min = min(&self.min, value)?;
+ Ok(())
}
- fn get_value(&self) -> Result<Option<ScalarValue>> {
- Ok(self.min.clone())
+ fn merge(&mut self, states: &Vec<ScalarValue>) -> Result<()> {
+ self.update(states)
+ }
+
+ fn merge_batch(&mut self, states: &Vec<ArrayRef>) -> Result<()> {
+ self.update_batch(states)
}
-}
-/// Create a min expression
-pub fn min(expr: Arc<dyn PhysicalExpr>) -> Arc<dyn AggregateExpr> {
- Arc::new(Min::new(expr))
+ fn evaluate(&self) -> Result<ScalarValue> {
+ Ok(self.min.clone())
+ }
}
/// COUNT aggregate expression
/// Returns the amount of non-null values of the given expression.
#[derive(Debug)]
pub struct Count {
+ name: String,
+ data_type: DataType,
+ nullable: bool,
expr: Arc<dyn PhysicalExpr>,
}
impl Count {
/// Create a new COUNT aggregate function.
- pub fn new(expr: Arc<dyn PhysicalExpr>) -> Self {
- Self { expr: expr }
+ pub fn new(expr: Arc<dyn PhysicalExpr>, name: String, data_type: DataType) -> Self {
+ Self {
+ name,
+ expr,
+ data_type,
+ nullable: true,
+ }
}
}
impl AggregateExpr for Count {
- fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
- Ok(DataType::UInt64)
- }
-
- fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
- // null should be returned if no rows are aggregated
- Ok(true)
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(
+ &self.name,
+ self.data_type.clone(),
+ self.nullable,
+ ))
}
- fn evaluate_input(&self, batch: &RecordBatch) -> Result<ArrayRef> {
- self.expr.evaluate(batch)
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![Field::new(
+ &format_state_name(&self.name, "count"),
+ self.data_type.clone(),
+ true,
+ )])
}
- fn create_accumulator(&self) -> Rc<RefCell<dyn Accumulator>> {
- Rc::new(RefCell::new(CountAccumulator { count: 0 }))
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
}
- fn create_reducer(&self, column_name: &str) -> Arc<dyn AggregateExpr> {
- Arc::new(Sum::new(Arc::new(Column::new(column_name))))
+ fn create_accumulator(&self) -> Result<Rc<RefCell<dyn Accumulator>>> {
+ Ok(Rc::new(RefCell::new(CountAccumulator::new())))
}
}
#[derive(Debug)]
struct CountAccumulator {
- count: u64,
+ count: ScalarValue,
}
-impl Accumulator for CountAccumulator {
- fn accumulate_scalar(&mut self, value: Option<ScalarValue>) -> Result<()> {
- if value.is_some() {
- self.count += 1;
+impl CountAccumulator {
+ /// new count accumulator
+ pub fn new() -> Self {
+ Self {
+ count: ScalarValue::from(0u64),
}
+ }
+
+ fn update_from_option(&mut self, delta: &Option<u64>) -> Result<()> {
+ self.count = ScalarValue::UInt64(match (&self.count, delta) {
+ (ScalarValue::UInt64(None), None) => None,
+ (ScalarValue::UInt64(None), Some(rhs)) => Some(rhs.clone()),
+ (ScalarValue::UInt64(Some(lhs)), None) => Some(lhs.clone()),
+ (ScalarValue::UInt64(Some(lhs)), Some(rhs)) => Some(lhs + rhs),
+ _ => {
+ return Err(ExecutionError::InternalError(
+ "Code should not be reached reach".to_string(),
+ ))
+ }
+ });
Ok(())
}
+}
- fn accumulate_batch(&mut self, array: &ArrayRef) -> Result<()> {
- self.count += array.len() as u64 - array.null_count() as u64;
+impl Accumulator for CountAccumulator {
+ fn update_batch(&mut self, values: &Vec<ArrayRef>) -> Result<()> {
+ let array = &values[0];
+ let delta = if array.len() == array.data().null_count() {
+ None
+ } else {
+ Some((array.len() - array.data().null_count()) as u64)
+ };
+ self.update_from_option(&delta)
+ }
+
+ fn update(&mut self, values: &Vec<ScalarValue>) -> Result<()> {
+ let value = &values[0];
+ self.count = match (&self.count, value.is_null()) {
+ (ScalarValue::UInt64(None), false) => ScalarValue::from(1u64),
+ (ScalarValue::UInt64(Some(count)), false) => ScalarValue::from(count + 1),
+ // value is null => no change in count
+ (e, true) => e.clone(),
+ (_, false) => {
+ return Err(ExecutionError::InternalError(
+ "Count is always of type u64".to_string(),
+ ))
+ }
+ };
Ok(())
}
- fn get_value(&self) -> Result<Option<ScalarValue>> {
- Ok(Some(ScalarValue::UInt64(self.count)))
+ fn merge(&mut self, states: &Vec<ScalarValue>) -> Result<()> {
+ let count = &states[0];
+ if let ScalarValue::UInt64(delta) = count {
+ self.update_from_option(delta)
+ } else {
+ unreachable!()
+ }
+ }
+
+ fn merge_batch(&mut self, states: &Vec<ArrayRef>) -> Result<()> {
+ let counts = states[0].as_any().downcast_ref::<UInt64Array>().unwrap();
+ let delta = &compute::sum(counts);
+ self.update_from_option(delta)
}
-}
-/// Create a count expression
-pub fn count(expr: Arc<dyn PhysicalExpr>) -> Arc<dyn AggregateExpr> {
- Arc::new(Count::new(expr))
+ fn state(&self) -> Result<Vec<ScalarValue>> {
+ Ok(vec![self.count.clone()])
+ }
+
+ fn evaluate(&self) -> Result<ScalarValue> {
+ Ok(self.count.clone())
+ }
}
/// Invoke a compute kernel on a pair of binary data arrays
@@ -1415,8 +1504,14 @@ impl Literal {
macro_rules! build_literal_array {
($BATCH:ident, $BUILDER:ident, $VALUE:expr) => {{
let mut builder = $BUILDER::new($BATCH.num_rows());
- for _ in 0..$BATCH.num_rows() {
- builder.append_value($VALUE)?;
+ if $VALUE.is_none() {
+ for _ in 0..$BATCH.num_rows() {
+ builder.append_null()?;
+ }
+ } else {
+ for _ in 0..$BATCH.num_rows() {
+ builder.append_value($VALUE.unwrap())?;
+ }
}
Ok(Arc::new(builder.finish()))
}};
@@ -1430,14 +1525,11 @@ impl fmt::Display for Literal {
impl PhysicalExpr for Literal {
fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
- self.value.get_datatype()
+ Ok(self.value.get_datatype())
}
fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
- match &self.value {
- ScalarValue::Null => Ok(true),
- _ => Ok(false),
- }
+ Ok(self.value.is_null())
}
fn evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {
@@ -1470,7 +1562,11 @@ impl PhysicalExpr for Literal {
ScalarValue::Float64(value) => {
build_literal_array!(batch, Float64Builder, *value)
}
- ScalarValue::Utf8(value) => build_literal_array!(batch, StringBuilder, value),
+ ScalarValue::Utf8(value) => build_literal_array!(
+ batch,
+ StringBuilder,
+ value.as_ref().and_then(|e| Some(&*e))
+ ),
other => Err(ExecutionError::General(format!(
"Unsupported literal type {:?}",
other
@@ -1507,7 +1603,6 @@ impl PhysicalSortExpr {
mod tests {
use super::*;
use crate::error::Result;
- use crate::physical_plan::common::get_scalar_value;
use arrow::array::{
LargeStringArray, PrimitiveArray, PrimitiveArrayOps, StringArray, StringArrayOps,
Time64NanosecondArray,
@@ -1599,7 +1694,7 @@ mod tests {
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
// create and evaluate a literal expression
- let literal_expr = lit(ScalarValue::Int32(42));
+ let literal_expr = lit(ScalarValue::from(42i32));
assert_eq!("42", format!("{}", literal_expr));
let literal_array = literal_expr.evaluate(&batch)?;
@@ -1832,80 +1927,6 @@ mod tests {
Ok(())
}
- #[test]
- fn sum_contract() -> Result<()> {
- let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
-
- let sum = sum(col("a"));
- assert_eq!(DataType::Int64, sum.data_type(&schema)?);
-
- // after the aggr expression is applied, the schema changes to:
- let schema = Schema::new(vec![
- schema.field(0).clone(),
- Field::new("SUM(a)", sum.data_type(&schema)?, false),
- ]);
-
- let combiner = sum.create_reducer("SUM(a)");
- assert_eq!(DataType::Int64, combiner.data_type(&schema)?);
-
- Ok(())
- }
-
- #[test]
- fn max_contract() -> Result<()> {
- let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
-
- let max = max(col("a"));
- assert_eq!(DataType::Int32, max.data_type(&schema)?);
-
- // after the aggr expression is applied, the schema changes to:
- let schema = Schema::new(vec![
- schema.field(0).clone(),
- Field::new("Max(a)", max.data_type(&schema)?, false),
- ]);
-
- let combiner = max.create_reducer("Max(a)");
- assert_eq!(DataType::Int32, combiner.data_type(&schema)?);
-
- Ok(())
- }
-
- #[test]
- fn min_contract() -> Result<()> {
- let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
-
- let min = min(col("a"));
- assert_eq!(DataType::Int32, min.data_type(&schema)?);
-
- // after the aggr expression is applied, the schema changes to:
- let schema = Schema::new(vec![
- schema.field(0).clone(),
- Field::new("MIN(a)", min.data_type(&schema)?, false),
- ]);
- let combiner = min.create_reducer("MIN(a)");
- assert_eq!(DataType::Int32, combiner.data_type(&schema)?);
-
- Ok(())
- }
- #[test]
- fn avg_contract() -> Result<()> {
- let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
-
- let avg = avg(col("a"));
- assert_eq!(DataType::Float64, avg.data_type(&schema)?);
-
- // after the aggr expression is applied, the schema changes to:
- let schema = Schema::new(vec![
- schema.field(0).clone(),
- Field::new("SUM(a)", avg.data_type(&schema)?, false),
- ]);
-
- let combiner = avg.create_reducer("SUM(a)");
- assert_eq!(DataType::Float64, combiner.data_type(&schema)?);
-
- Ok(())
- }
-
#[test]
fn sum_i32() -> Result<()> {
let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
@@ -1913,7 +1934,11 @@ mod tests {
let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_sum(&batch)?, Some(ScalarValue::Int64(15)));
+ let agg = Arc::new(Sum::new(col("a"), "bla".to_string(), DataType::Int64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(15i64);
+
+ assert_eq!(expected, actual);
Ok(())
}
@@ -1925,8 +1950,11 @@ mod tests {
let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_avg(&batch)?, Some(ScalarValue::Float64(3_f64)));
+ let agg = Arc::new(Avg::new(col("a"), "bla".to_string(), DataType::Float64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(3_f64);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -1937,7 +1965,11 @@ mod tests {
let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_max(&batch)?, Some(ScalarValue::Int32(5)));
+ let agg = Arc::new(Max::new(col("a"), "bla".to_string(), DataType::Int32));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(5i32);
+
+ assert_eq!(expected, actual);
Ok(())
}
@@ -1949,8 +1981,11 @@ mod tests {
let a = StringArray::from(vec!["d", "a", "c", "b"]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_max(&batch)?, Some(ScalarValue::Utf8("d".to_string())));
+ let agg = Arc::new(Max::new(col("a"), "bla".to_string(), DataType::Utf8));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::Utf8(Some("d".to_string()));
+ assert_eq!(expected, actual);
Ok(())
}
@@ -1961,8 +1996,11 @@ mod tests {
let a = LargeStringArray::from(vec!["d", "a", "c", "b"]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_max(&batch)?, Some(ScalarValue::Utf8("d".to_string())));
+ let agg = Arc::new(Max::new(col("a"), "bla".to_string(), DataType::LargeUtf8));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::LargeUtf8(Some("d".to_string()));
+ assert_eq!(expected, actual);
Ok(())
}
@@ -1973,8 +2011,11 @@ mod tests {
let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_min(&batch)?, Some(ScalarValue::Int32(1)));
+ let agg = Arc::new(Min::new(col("a"), "bla".to_string(), DataType::Int32));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(1i32);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -1985,7 +2026,11 @@ mod tests {
let a = StringArray::from(vec!["d", "a", "c", "b"]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_min(&batch)?, Some(ScalarValue::Utf8("a".to_string())));
+ let agg = Arc::new(Min::new(col("a"), "bla".to_string(), DataType::Utf8));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::Utf8(Some("a".to_string()));
+
+ assert_eq!(expected, actual);
Ok(())
}
@@ -1997,7 +2042,11 @@ mod tests {
let a = LargeStringArray::from(vec!["d", "a", "c", "b"]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_min(&batch)?, Some(ScalarValue::Utf8("a".to_string())));
+ let agg = Arc::new(Min::new(col("a"), "bla".to_string(), DataType::LargeUtf8));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::LargeUtf8(Some("a".to_string()));
+
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2009,7 +2058,11 @@ mod tests {
let a = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5)]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_sum(&batch)?, Some(ScalarValue::Int64(13)));
+ let agg = Arc::new(Sum::new(col("a"), "bla".to_string(), DataType::Int64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(13i64);
+
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2021,7 +2074,11 @@ mod tests {
let a = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5)]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_avg(&batch)?, Some(ScalarValue::Float64(3.25)));
+ let agg = Arc::new(Avg::new(col("a"), "bla".to_string(), DataType::Float64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(3.25f64);
+
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2033,8 +2090,11 @@ mod tests {
let a = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5)]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_max(&batch)?, Some(ScalarValue::Int32(5)));
+ let agg = Arc::new(Max::new(col("a"), "bla".to_string(), DataType::Int32));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(5i32);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2045,8 +2105,11 @@ mod tests {
let a = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5)]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_min(&batch)?, Some(ScalarValue::Int32(1)));
+ let agg = Arc::new(Min::new(col("a"), "bla".to_string(), DataType::Int32));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(1i32);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2057,8 +2120,11 @@ mod tests {
let a = Int32Array::from(vec![None, None]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_sum(&batch)?, None);
+ let agg = Arc::new(Sum::new(col("a"), "bla".to_string(), DataType::Int64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::Int64(None);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2069,8 +2135,11 @@ mod tests {
let a = Int32Array::from(vec![None, None]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_max(&batch)?, None);
+ let agg = Arc::new(Max::new(col("a"), "bla".to_string(), DataType::Int32));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::Int32(None);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2081,8 +2150,11 @@ mod tests {
let a = Int32Array::from(vec![None, None]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_min(&batch)?, None);
+ let agg = Arc::new(Min::new(col("a"), "bla".to_string(), DataType::Int32));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::Int32(None);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2093,8 +2165,11 @@ mod tests {
let a = Int32Array::from(vec![None, None]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_avg(&batch)?, None);
+ let agg = Arc::new(Avg::new(col("a"), "bla".to_string(), DataType::Float64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::Float64(None);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2105,8 +2180,11 @@ mod tests {
let a = UInt32Array::from(vec![1_u32, 2_u32, 3_u32, 4_u32, 5_u32]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_sum(&batch)?, Some(ScalarValue::UInt64(15_u64)));
+ let agg = Arc::new(Sum::new(col("a"), "bla".to_string(), DataType::UInt64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(15u64);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2117,8 +2195,11 @@ mod tests {
let a = UInt32Array::from(vec![1_u32, 2_u32, 3_u32, 4_u32, 5_u32]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_avg(&batch)?, Some(ScalarValue::Float64(3_f64)));
+ let agg = Arc::new(Avg::new(col("a"), "bla".to_string(), DataType::Float64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(3.0f64);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2129,8 +2210,11 @@ mod tests {
let a = UInt32Array::from(vec![1_u32, 2_u32, 3_u32, 4_u32, 5_u32]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_max(&batch)?, Some(ScalarValue::UInt32(5_u32)));
+ let agg = Arc::new(Max::new(col("a"), "bla".to_string(), DataType::UInt32));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(5u32);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2141,8 +2225,11 @@ mod tests {
let a = UInt32Array::from(vec![1_u32, 2_u32, 3_u32, 4_u32, 5_u32]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_min(&batch)?, Some(ScalarValue::UInt32(1_u32)));
+ let agg = Arc::new(Min::new(col("a"), "bla".to_string(), DataType::UInt32));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(1u32);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2153,8 +2240,11 @@ mod tests {
let a = Float32Array::from(vec![1_f32, 2_f32, 3_f32, 4_f32, 5_f32]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_sum(&batch)?, Some(ScalarValue::Float32(15_f32)));
+ let agg = Arc::new(Sum::new(col("a"), "bla".to_string(), DataType::Float32));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(15_f32);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2165,8 +2255,11 @@ mod tests {
let a = Float32Array::from(vec![1_f32, 2_f32, 3_f32, 4_f32, 5_f32]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_avg(&batch)?, Some(ScalarValue::Float64(3_f64)));
+ let agg = Arc::new(Avg::new(col("a"), "bla".to_string(), DataType::Float64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(3_f64);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2177,8 +2270,11 @@ mod tests {
let a = Float32Array::from(vec![1_f32, 2_f32, 3_f32, 4_f32, 5_f32]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_max(&batch)?, Some(ScalarValue::Float32(5_f32)));
+ let agg = Arc::new(Max::new(col("a"), "bla".to_string(), DataType::Float32));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(5_f32);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2189,8 +2285,11 @@ mod tests {
let a = Float32Array::from(vec![1_f32, 2_f32, 3_f32, 4_f32, 5_f32]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_min(&batch)?, Some(ScalarValue::Float32(1_f32)));
+ let agg = Arc::new(Min::new(col("a"), "bla".to_string(), DataType::Float32));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(1_f32);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2201,8 +2300,11 @@ mod tests {
let a = Float64Array::from(vec![1_f64, 2_f64, 3_f64, 4_f64, 5_f64]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_sum(&batch)?, Some(ScalarValue::Float64(15_f64)));
+ let agg = Arc::new(Sum::new(col("a"), "bla".to_string(), DataType::Float64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(15_f64);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2213,8 +2315,11 @@ mod tests {
let a = Float64Array::from(vec![1_f64, 2_f64, 3_f64, 4_f64, 5_f64]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_avg(&batch)?, Some(ScalarValue::Float64(3_f64)));
+ let agg = Arc::new(Avg::new(col("a"), "bla".to_string(), DataType::Float64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(3_f64);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2225,8 +2330,11 @@ mod tests {
let a = Float64Array::from(vec![1_f64, 2_f64, 3_f64, 4_f64, 5_f64]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_max(&batch)?, Some(ScalarValue::Float64(5_f64)));
+ let agg = Arc::new(Max::new(col("a"), "bla".to_string(), DataType::Float64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(5_f64);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2237,8 +2345,11 @@ mod tests {
let a = Float64Array::from(vec![1_f64, 2_f64, 3_f64, 4_f64, 5_f64]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_min(&batch)?, Some(ScalarValue::Float64(1_f64)));
+ let agg = Arc::new(Min::new(col("a"), "bla".to_string(), DataType::Float64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(1_f64);
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2247,7 +2358,12 @@ mod tests {
let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_count(&batch)?, Some(ScalarValue::UInt64(5)));
+
+ let agg = Arc::new(Count::new(col("a"), "bla".to_string(), DataType::UInt64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(5u64);
+
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2256,7 +2372,12 @@ mod tests {
let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
let a = Int32Array::from(vec![Some(1), Some(2), None, None, Some(3), None]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_count(&batch)?, Some(ScalarValue::UInt64(3)));
+
+ let agg = Arc::new(Count::new(col("a"), "bla".to_string(), DataType::UInt64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(3u64);
+
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2265,7 +2386,12 @@ mod tests {
let schema = Schema::new(vec![Field::new("a", DataType::Boolean, false)]);
let a = BooleanArray::from(vec![None, None, None, None, None, None, None, None]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_count(&batch)?, Some(ScalarValue::UInt64(0)));
+
+ let agg = Arc::new(Count::new(col("a"), "bla".to_string(), DataType::UInt64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(0u64);
+
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2274,7 +2400,12 @@ mod tests {
let schema = Schema::new(vec![Field::new("a", DataType::Boolean, false)]);
let a = BooleanArray::from(Vec::<bool>::new());
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_count(&batch)?, Some(ScalarValue::UInt64(0)));
+
+ let agg = Arc::new(Count::new(col("a"), "bla".to_string(), DataType::UInt64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(0u64);
+
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2283,7 +2414,12 @@ mod tests {
let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
let a = StringArray::from(vec!["a", "bb", "ccc", "dddd", "ad"]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_count(&batch)?, Some(ScalarValue::UInt64(5)));
+
+ let agg = Arc::new(Count::new(col("a"), "bla".to_string(), DataType::UInt64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(5u64);
+
+ assert_eq!(expected, actual);
Ok(())
}
@@ -2292,63 +2428,28 @@ mod tests {
let schema = Schema::new(vec![Field::new("a", DataType::LargeUtf8, false)]);
let a = LargeStringArray::from(vec!["a", "bb", "ccc", "dddd", "ad"]);
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- assert_eq!(do_count(&batch)?, Some(ScalarValue::UInt64(5)));
- Ok(())
- }
- fn do_sum(batch: &RecordBatch) -> Result<Option<ScalarValue>> {
- let sum = sum(col("a"));
- let accum = sum.create_accumulator();
- let input = sum.evaluate_input(batch)?;
- let mut accum = accum.borrow_mut();
- for i in 0..batch.num_rows() {
- accum.accumulate_scalar(get_scalar_value(&input, i)?)?;
- }
- accum.get_value()
- }
+ let agg = Arc::new(Count::new(col("a"), "bla".to_string(), DataType::UInt64));
+ let actual = aggregate(&batch, agg)?;
+ let expected = ScalarValue::from(5u64);
- fn do_max(batch: &RecordBatch) -> Result<Option<ScalarValue>> {
- let max = max(col("a"));
- let accum = max.create_accumulator();
- let input = max.evaluate_input(batch)?;
- let mut accum = accum.borrow_mut();
- for i in 0..batch.num_rows() {
- accum.accumulate_scalar(get_scalar_value(&input, i)?)?;
- }
- accum.get_value()
- }
-
- fn do_min(batch: &RecordBatch) -> Result<Option<ScalarValue>> {
- let min = min(col("a"));
- let accum = min.create_accumulator();
- let input = min.evaluate_input(batch)?;
- let mut accum = accum.borrow_mut();
- for i in 0..batch.num_rows() {
- accum.accumulate_scalar(get_scalar_value(&input, i)?)?;
- }
- accum.get_value()
- }
-
- fn do_count(batch: &RecordBatch) -> Result<Option<ScalarValue>> {
- let count = count(col("a"));
- let accum = count.create_accumulator();
- let input = count.evaluate_input(batch)?;
- let mut accum = accum.borrow_mut();
- for i in 0..batch.num_rows() {
- accum.accumulate_scalar(get_scalar_value(&input, i)?)?;
- }
- accum.get_value()
+ assert_eq!(expected, actual);
+ Ok(())
}
- fn do_avg(batch: &RecordBatch) -> Result<Option<ScalarValue>> {
- let avg = avg(col("a"));
- let accum = avg.create_accumulator();
- let input = avg.evaluate_input(batch)?;
+ fn aggregate(
+ batch: &RecordBatch,
+ agg: Arc<dyn AggregateExpr>,
+ ) -> Result<ScalarValue> {
+ let accum = agg.create_accumulator()?;
+ let expr = agg.expressions();
+ let values = expr
+ .iter()
+ .map(|e| e.evaluate(batch))
+ .collect::<Result<Vec<_>>>()?;
let mut accum = accum.borrow_mut();
- for i in 0..batch.num_rows() {
- accum.accumulate_scalar(get_scalar_value(&input, i)?)?;
- }
- accum.get_value()
+ accum.update_batch(&values)?;
+ accum.evaluate()
}
#[test]
diff --git a/rust/datafusion/src/physical_plan/filter.rs b/rust/datafusion/src/physical_plan/filter.rs
index 066f0a0756..e2de19272e 100644
--- a/rust/datafusion/src/physical_plan/filter.rs
+++ b/rust/datafusion/src/physical_plan/filter.rs
@@ -157,10 +157,11 @@ impl RecordBatchReader for FilterExecIter {
mod tests {
use super::*;
- use crate::logical_plan::{Operator, ScalarValue};
+ use crate::logical_plan::Operator;
use crate::physical_plan::csv::{CsvExec, CsvReadOptions};
use crate::physical_plan::expressions::*;
use crate::physical_plan::ExecutionPlan;
+ use crate::scalar::ScalarValue;
use crate::test;
use std::iter::Iterator;
@@ -178,14 +179,14 @@ mod tests {
binary(
col("c2"),
Operator::Gt,
- lit(ScalarValue::UInt32(1)),
+ lit(ScalarValue::from(1u32)),
&schema,
)?,
Operator::And,
binary(
col("c2"),
Operator::Lt,
- lit(ScalarValue::UInt32(4)),
+ lit(ScalarValue::from(4u32)),
&schema,
)?,
&schema,
diff --git a/rust/datafusion/src/physical_plan/functions.rs b/rust/datafusion/src/physical_plan/functions.rs
index 95bd252e1d..496b9853cc 100644
--- a/rust/datafusion/src/physical_plan/functions.rs
+++ b/rust/datafusion/src/physical_plan/functions.rs
@@ -349,9 +349,7 @@ impl PhysicalExpr for ScalarFunctionExpr {
#[cfg(test)]
mod tests {
use super::*;
- use crate::{
- error::Result, logical_plan::ScalarValue, physical_plan::expressions::lit,
- };
+ use crate::{error::Result, physical_plan::expressions::lit, scalar::ScalarValue};
use arrow::{
array::{
ArrayRef, FixedSizeListArray, Float64Array, Int32Array, PrimitiveArrayOps,
@@ -392,11 +390,11 @@ mod tests {
// 2.71828182845904523536... : https://oeis.org/A001113
let exp_f64 = "2.718281828459045";
let exp_f32 = "2.7182817459106445";
- generic_test_math(ScalarValue::Int32(1i32), exp_f64)?;
- generic_test_math(ScalarValue::UInt32(1u32), exp_f64)?;
- generic_test_math(ScalarValue::UInt64(1u64), exp_f64)?;
- generic_test_math(ScalarValue::Float64(1f64), exp_f64)?;
- generic_test_math(ScalarValue::Float32(1f32), exp_f32)?;
+ generic_test_math(ScalarValue::from(1i32), exp_f64)?;
+ generic_test_math(ScalarValue::from(1u32), exp_f64)?;
+ generic_test_math(ScalarValue::from(1u64), exp_f64)?;
+ generic_test_math(ScalarValue::from(1f64), exp_f64)?;
+ generic_test_math(ScalarValue::from(1f32), exp_f32)?;
Ok(())
}
@@ -430,7 +428,7 @@ mod tests {
#[test]
fn test_concat_utf8() -> Result<()> {
- test_concat(ScalarValue::Utf8("aa".to_string()), "aaaa")
+ test_concat(ScalarValue::Utf8(Some("aa".to_string())), "aaaa")
}
#[test]
@@ -487,24 +485,24 @@ mod tests {
#[test]
fn test_array() -> Result<()> {
generic_test_array(
- ScalarValue::Utf8("aa".to_string()),
- ScalarValue::Utf8("aa".to_string()),
+ ScalarValue::Utf8(Some("aa".to_string())),
+ ScalarValue::Utf8(Some("aa".to_string())),
DataType::Utf8,
"StringArray\n[\n \"aa\",\n \"aa\",\n]",
)?;
// different types, to validate that casting happens
generic_test_array(
- ScalarValue::UInt32(1),
- ScalarValue::UInt64(1),
+ ScalarValue::from(1u32),
+ ScalarValue::from(1u64),
DataType::UInt64,
"PrimitiveArray<UInt64>\n[\n 1,\n 1,\n]",
)?;
// different types (another order), to validate that casting happens
generic_test_array(
- ScalarValue::UInt64(1),
- ScalarValue::UInt32(1),
+ ScalarValue::from(1u64),
+ ScalarValue::from(1u32),
DataType::UInt64,
"PrimitiveArray<UInt64>\n[\n 1,\n 1,\n]",
)
diff --git a/rust/datafusion/src/physical_plan/hash_aggregate.rs b/rust/datafusion/src/physical_plan/hash_aggregate.rs
index 25c2f38860..8c2805f76f 100644
--- a/rust/datafusion/src/physical_plan/hash_aggregate.rs
+++ b/rust/datafusion/src/physical_plan/hash_aggregate.rs
@@ -22,29 +22,25 @@ use std::rc::Rc;
use std::sync::{Arc, Mutex};
use crate::error::{ExecutionError, Result};
-use crate::physical_plan::{
- Accumulator, AggregateExpr, Distribution, ExecutionPlan, Partitioning, PhysicalExpr,
-};
+use crate::physical_plan::{Accumulator, AggregateExpr};
+use crate::physical_plan::{Distribution, ExecutionPlan, Partitioning, PhysicalExpr};
-use arrow::array::PrimitiveArrayOps;
-use arrow::array::{
- ArrayBuilder, ArrayRef, Float32Array, Float64Array, Int16Array, Int32Array,
- Int64Array, Int8Array, StringArray, StringArrayOps, UInt16Array, UInt32Array,
- UInt64Array, UInt8Array,
-};
-use arrow::array::{
- Float32Builder, Float64Builder, Int16Builder, Int32Builder, Int64Builder,
- Int8Builder, StringBuilder, UInt16Builder, UInt32Builder, UInt64Builder,
- UInt8Builder,
-};
+use crate::arrow::array::{PrimitiveArrayOps, StringArrayOps};
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use arrow::error::Result as ArrowResult;
use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use arrow::{
+ array::{
+ ArrayRef, Int16Array, Int32Array, Int64Array, Int8Array, StringArray,
+ UInt16Array, UInt32Array, UInt64Array, UInt8Array,
+ },
+ compute,
+};
-use crate::logical_plan::ScalarValue;
-use crate::physical_plan::expressions::col;
use fnv::FnvHashMap;
+use super::{common, expressions::Column};
+
/// Hash aggregate modes
#[derive(Debug, Copy, Clone)]
pub enum AggregateMode {
@@ -59,37 +55,55 @@ pub enum AggregateMode {
pub struct HashAggregateExec {
mode: AggregateMode,
group_expr: Vec<(Arc<dyn PhysicalExpr>, String)>,
- aggr_expr: Vec<(Arc<dyn AggregateExpr>, String)>,
+ aggr_expr: Vec<Arc<dyn AggregateExpr>>,
input: Arc<dyn ExecutionPlan>,
schema: SchemaRef,
}
+fn create_schema(
+ input_schema: &Schema,
+ group_expr: &Vec<(Arc<dyn PhysicalExpr>, String)>,
+ aggr_expr: &Vec<Arc<dyn AggregateExpr>>,
+ mode: AggregateMode,
+) -> Result<Schema> {
+ let mut fields = Vec::with_capacity(group_expr.len() + aggr_expr.len());
+ for (expr, name) in group_expr {
+ fields.push(Field::new(
+ name,
+ expr.data_type(&input_schema)?,
+ expr.nullable(&input_schema)?,
+ ))
+ }
+
+ match mode {
+ AggregateMode::Partial => {
+ // in partial mode, the fields of the accumulator's state
+ for expr in aggr_expr {
+ fields.extend(expr.state_fields()?.iter().cloned())
+ }
+ }
+ AggregateMode::Final => {
+ // in final mode, the field with the final result of the accumulator
+ for expr in aggr_expr {
+ fields.push(expr.field()?)
+ }
+ }
+ }
+
+ Ok(Schema::new(fields))
+}
+
impl HashAggregateExec {
/// Create a new hash aggregate execution plan
pub fn try_new(
mode: AggregateMode,
group_expr: Vec<(Arc<dyn PhysicalExpr>, String)>,
- aggr_expr: Vec<(Arc<dyn AggregateExpr>, String)>,
+ aggr_expr: Vec<Arc<dyn AggregateExpr>>,
input: Arc<dyn ExecutionPlan>,
) -> Result<Self> {
- let input_schema = input.schema();
-
- let mut fields = Vec::with_capacity(group_expr.len() + aggr_expr.len());
- for (expr, name) in &group_expr {
- fields.push(Field::new(
- name,
- expr.data_type(&input_schema)?,
- expr.nullable(&input_schema)?,
- ))
- }
- for (expr, name) in &aggr_expr {
- fields.push(Field::new(
- &name,
- expr.data_type(&input_schema)?,
- expr.nullable(&input_schema)?,
- ))
- }
- let schema = Arc::new(Schema::new(fields));
+ let schema = create_schema(&input.schema(), &group_expr, &aggr_expr, mode)?;
+
+ let schema = Arc::new(schema);
Ok(HashAggregateExec {
mode,
@@ -99,24 +113,6 @@ impl HashAggregateExec {
schema,
})
}
-
- /// Create the final group and aggregate expressions from the initial group and aggregate
- /// expressions
- pub fn make_final_expr(
- &self,
- group_names: Vec<String>,
- agg_names: Vec<String>,
- ) -> (Vec<Arc<dyn PhysicalExpr>>, Vec<Arc<dyn AggregateExpr>>) {
- let final_group: Vec<Arc<dyn PhysicalExpr>> = (0..self.group_expr.len())
- .map(|i| col(&group_names[i]) as Arc<dyn PhysicalExpr>)
- .collect();
-
- let final_aggr: Vec<Arc<dyn AggregateExpr>> = (0..self.aggr_expr.len())
- .map(|i| self.aggr_expr[i].0.create_reducer(&agg_names[i]))
- .collect();
-
- (final_group, final_aggr)
- }
}
impl ExecutionPlan for HashAggregateExec {
@@ -146,18 +142,20 @@ impl ExecutionPlan for HashAggregateExec {
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
let input = self.input.execute(partition)?;
let group_expr = self.group_expr.iter().map(|x| x.0.clone()).collect();
- let aggr_expr = self.aggr_expr.iter().map(|x| x.0.clone()).collect();
+
if self.group_expr.is_empty() {
Ok(Arc::new(Mutex::new(HashAggregateIterator::new(
+ self.mode,
self.schema.clone(),
- aggr_expr,
+ self.aggr_expr.clone(),
input,
))))
} else {
Ok(Arc::new(Mutex::new(GroupedHashAggregateIterator::new(
+ self.mode.clone(),
self.schema.clone(),
group_expr,
- aggr_expr,
+ self.aggr_expr.clone(),
input,
))))
}
@@ -181,28 +179,33 @@ impl ExecutionPlan for HashAggregateExec {
}
}
-/// Create array from single accumulator value
-macro_rules! accum_val {
- ($BUILDER:ident, $SCALAR_TY:ident, $VALUE:expr) => {{
- let mut builder = $BUILDER::new(1);
- match $VALUE {
- Some(ScalarValue::$SCALAR_TY(n)) => {
- builder.append_value(n)?;
- Ok(Arc::new(builder.finish()) as ArrayRef)
- }
- None => {
- builder.append_null()?;
- Ok(Arc::new(builder.finish()) as ArrayRef)
- }
- _ => Err(ExecutionError::ExecutionError(
- "unexpected type when creating aggregate array from no-group aggregate"
- .to_string(),
- )),
- }
- }};
-}
+/*
+The architecture is the following:
+
+1. An accumulator has state that is updated on each batch.
+2. At the end of the aggregation (e.g. end of batches in a partition), the accumulator converts its state to a RecordBatch of a single row
+3. The RecordBatches of all accumulators are merged (`concatenate` in `rust/arrow`) together to a single RecordBatch.
+4. The state's RecordBatch is `merge`d to a new state
+5. The state is mapped to the final value
+
+Why:
+* Accumulators' state can be statically typed, but it is more efficient to transmit data from the accumulators via `Array`
+* The `merge` operation must have access to the state of the aggregators because it uses it to correctly merge
+* It uses Arrow's native dynamically typed object, `Array`.
+* Arrow shines in batch operations and both `merge` and `concatenate` of uniform types are very performant.
+
+Example: average
+
+* the state is `n: u32` and `sum: f64`
+* For every batch, we update them accordingly.
+* At the end of the accumulation (of a partition), we convert `n` and `sum` to a RecordBatch of 1 row and two columns: `[n, sum]`
+* The RecordBatch is (sent back / transmitted over network)
+* Once all N record batches arrive, `merge` is performed, which builds a RecordBatch with N rows and 2 columns.
+* Finally, `get_value` returns an array with one entry computed from the state
+*/
struct GroupedHashAggregateIterator {
+ mode: AggregateMode,
schema: SchemaRef,
group_expr: Vec<Arc<dyn PhysicalExpr>>,
aggr_expr: Vec<Arc<dyn AggregateExpr>>,
@@ -213,12 +216,14 @@ struct GroupedHashAggregateIterator {
impl GroupedHashAggregateIterator {
/// Create a new HashAggregateIterator
pub fn new(
+ mode: AggregateMode,
schema: SchemaRef,
group_expr: Vec<Arc<dyn PhysicalExpr>>,
aggr_expr: Vec<Arc<dyn AggregateExpr>>,
input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,
) -> Self {
GroupedHashAggregateIterator {
+ mode,
schema,
group_expr,
aggr_expr,
@@ -230,22 +235,6 @@ impl GroupedHashAggregateIterator {
type AccumulatorSet = Vec<Rc<RefCell<dyn Accumulator>>>;
-macro_rules! update_accum {
- ($ARRAY:ident, $ARRAY_TY:ident, $SCALAR_TY:expr, $COL:expr, $ACCUM:expr) => {{
- let primitive_array = $ARRAY.as_any().downcast_ref::<$ARRAY_TY>().unwrap();
-
- for row in 0..$ARRAY.len() {
- if $ARRAY.is_valid(row) {
- let value = Some($SCALAR_TY(primitive_array.value(row)));
- let mut accum = $ACCUM[row][$COL].borrow_mut();
- accum
- .accumulate_scalar(value)
- .map_err(ExecutionError::into_arrow_external_error)?;
- }
- }
- }};
-}
-
impl RecordBatchReader for GroupedHashAggregateIterator {
fn schema(&self) -> SchemaRef {
self.schema.clone()
@@ -256,138 +245,122 @@ impl RecordBatchReader for GroupedHashAggregateIterator {
return Ok(None);
}
+ // return single batch
self.finished = true;
- // create map to store accumulators for each unique grouping key
- let mut map: FnvHashMap<Vec<GroupByScalar>, Rc<AccumulatorSet>> =
- FnvHashMap::default();
+ // the expressions to evaluate the batch, one vec of expressions per aggregation
+ let aggregate_expressions = aggregate_expressions(&self.aggr_expr, &self.mode)
+ .map_err(ExecutionError::into_arrow_external_error)?;
+
+ // mapping key -> (set of accumulators, indices of the key in the batch)
+ // * the indexes are updated at each row
+ // * the accumulators are updated at the end of each batch
+ // * the indexes are `clear`ed at the end of each batch
+ let mut accumulators: FnvHashMap<
+ Vec<GroupByScalar>,
+ (AccumulatorSet, Box<Vec<u32>>),
+ > = FnvHashMap::default();
// iterate over all input batches and update the accumulators
let mut input = self.input.lock().unwrap();
// iterate over input and perform aggregation
- while let Some(batch) = input.next_batch()? {
- // evaluate the grouping expressions for this batch
- let group_values = self
- .group_expr
- .iter()
- .map(|expr| {
- expr.evaluate(&batch)
- .map_err(ExecutionError::into_arrow_external_error)
- })
- .collect::<ArrowResult<Vec<_>>>()?;
+ while let Some(batch) = &input.next_batch()? {
+ // evaluate the grouping expressions
+ let group_values = evaluate(&self.group_expr, batch)
+ .map_err(ExecutionError::into_arrow_external_error)?;
- // evaluate the inputs to the aggregate expressions for this batch
- let aggr_input_values = self
- .aggr_expr
- .iter()
- .map(|expr| {
- expr.evaluate_input(&batch)
- .map_err(ExecutionError::into_arrow_external_error)
- })
- .collect::<ArrowResult<Vec<_>>>()?;
+ // evaluate the aggregation expressions.
+ // We could evaluate them after the `take`, but since we need to evaluate all
+ // of them anyways, it is more performant to do it while they are together.
+ let aggr_input_values = evaluate_many(&aggregate_expressions, &batch)
+ .map_err(ExecutionError::into_arrow_external_error)?;
// create vector large enough to hold the grouping key
+ // this is an optimization to avoid allocating `key` on every row.
+ // it will be overwritten on every iteration of the loop below
let mut key = Vec::with_capacity(group_values.len());
for _ in 0..group_values.len() {
key.push(GroupByScalar::UInt32(0));
}
- // iterate over each row in the batch and create the accumulators for each grouping key
- let mut accums: Vec<Rc<AccumulatorSet>> =
- Vec::with_capacity(batch.num_rows());
-
+ // 1.1 construct the key from the group values
+ // 1.2 construct the mapping key if it does not exist
+ // 1.3 add the row' index to `indices`
for row in 0..batch.num_rows() {
- // create grouping key for this row
+ // 1.1
create_key(&group_values, row, &mut key)
.map_err(ExecutionError::into_arrow_external_error)?;
- if let Some(accumulator_set) = map.get(&key) {
- accums.push(accumulator_set.clone());
- } else {
- let accumulator_set: AccumulatorSet = self
- .aggr_expr
- .iter()
- .map(|expr| expr.create_accumulator())
- .collect();
-
- let accumulator_set = Rc::new(accumulator_set);
+ match accumulators.get_mut(&key) {
+ // 1.2
+ None => {
+ let accumulator_set = create_accumulators(&self.aggr_expr)
+ .map_err(ExecutionError::into_arrow_external_error)?;
- map.insert(key.clone(), accumulator_set.clone());
- accums.push(accumulator_set);
+ accumulators.insert(
+ key.clone(),
+ (accumulator_set, Box::new(vec![row as u32])),
+ );
+ }
+ // 1.3
+ Some((_, v)) => v.push(row as u32),
}
}
- // iterate over each non-grouping column in the batch and update the accumulator
- // for each row
- for col in 0..aggr_input_values.len() {
- let array = &aggr_input_values[col];
-
- match array.data_type() {
- DataType::Int8 => {
- update_accum!(array, Int8Array, ScalarValue::Int8, col, accums)
- }
- DataType::Int16 => {
- update_accum!(array, Int16Array, ScalarValue::Int16, col, accums)
- }
- DataType::Int32 => {
- update_accum!(array, Int32Array, ScalarValue::Int32, col, accums)
- }
- DataType::Int64 => {
- update_accum!(array, Int64Array, ScalarValue::Int64, col, accums)
- }
- DataType::UInt8 => {
- update_accum!(array, UInt8Array, ScalarValue::UInt8, col, accums)
- }
- DataType::UInt16 => update_accum!(
- array,
- UInt16Array,
- ScalarValue::UInt16,
- col,
- accums
- ),
- DataType::UInt32 => update_accum!(
- array,
- UInt32Array,
- ScalarValue::UInt32,
- col,
- accums
- ),
- DataType::UInt64 => update_accum!(
- array,
- UInt64Array,
- ScalarValue::UInt64,
- col,
- accums
- ),
- DataType::Float32 => update_accum!(
- array,
- Float32Array,
- ScalarValue::Float32,
- col,
- accums
- ),
- DataType::Float64 => update_accum!(
- array,
- Float64Array,
- ScalarValue::Float64,
- col,
- accums
- ),
- other => {
- return Err(ExecutionError::ExecutionError(format!(
- "Unsupported data type {:?} for result of aggregate expression",
- other
- )).into_arrow_external_error());
- }
- };
- }
+ // 2.1 for each key
+ // 2.2 for each aggregation
+ // 2.3 `take` from each of its arrays the keys' values
+ // 2.4 update / merge the accumulator with the values
+ // 2.5 clear indices
+ accumulators
+ .iter_mut()
+ // 2.1
+ .map(|(_, (accumulator_set, indices))| {
+ // 2.2
+ accumulator_set
+ .iter()
+ .zip(&aggr_input_values)
+ .into_iter()
+ .map(|(accumulator, aggr_array)| {
+ (
+ accumulator,
+ aggr_array
+ .iter()
+ .map(|array| {
+ // 2.3
+ compute::take(
+ array,
+ &UInt32Array::from(*indices.clone()),
+ None, // None: no index check
+ )
+ .unwrap()
+ })
+ .collect::<Vec<ArrayRef>>(),
+ )
+ })
+ // 2.4
+ .map(|(accumulator, values)| match self.mode {
+ AggregateMode::Partial => {
+ accumulator.borrow_mut().update_batch(&values)
+ }
+ AggregateMode::Final => {
+ // note: the aggregation here is over states, not values, thus the merge
+ accumulator.borrow_mut().merge_batch(&values)
+ }
+ })
+ .collect::<Result<()>>()
+ // 2.5
+ .and(Ok(indices.clear()))
+ })
+ .collect::<Result<()>>()
+ .map_err(ExecutionError::into_arrow_external_error)?;
}
let batch = create_batch_from_map(
- &map,
+ &self.mode,
+ &accumulators,
self.group_expr.len(),
- self.aggr_expr.len(),
&self.schema,
)
.map_err(ExecutionError::into_arrow_external_error)?;
@@ -396,7 +369,62 @@ impl RecordBatchReader for GroupedHashAggregateIterator {
}
}
+/// Evaluates expressions against a record batch.
+fn evaluate(
+ expr: &Vec<Arc<dyn PhysicalExpr>>,
+ batch: &RecordBatch,
+) -> Result<Vec<ArrayRef>> {
+ expr.iter()
+ .map(|expr| expr.evaluate(&batch))
+ .collect::<Result<Vec<_>>>()
+}
+
+/// Evaluates expressions against a record batch.
+fn evaluate_many(
+ expr: &Vec<Vec<Arc<dyn PhysicalExpr>>>,
+ batch: &RecordBatch,
+) -> Result<Vec<Vec<ArrayRef>>> {
+ expr.iter()
+ .map(|expr| evaluate(expr, batch))
+ .collect::<Result<Vec<_>>>()
+}
+
+/// uses `state_fields` to build a vec of expressions required to merge the AggregateExpr' accumulator's state.
+fn merge_expressions(
+ expr: &Arc<dyn AggregateExpr>,
+) -> Result<Vec<Arc<dyn PhysicalExpr>>> {
+ Ok(expr
+ .state_fields()?
+ .iter()
+ .map(|f| Arc::new(Column::new(f.name())) as Arc<dyn PhysicalExpr>)
+ .collect::<Vec<_>>())
+}
+
+/// returns physical expressions to evaluate against a batch
+/// The expressions are different depending on `mode`:
+/// * Partial: AggregateExpr::expressions
+/// * Final: columns of `AggregateExpr::state_fields()`
+/// The return value is to be understood as:
+/// * index 0 is the aggregation
+/// * index 1 is the expression i of the aggregation
+fn aggregate_expressions(
+ aggr_expr: &[Arc<dyn AggregateExpr>],
+ mode: &AggregateMode,
+) -> Result<Vec<Vec<Arc<dyn PhysicalExpr>>>> {
+ match mode {
+ AggregateMode::Partial => {
+ Ok(aggr_expr.iter().map(|agg| agg.expressions()).collect())
+ }
+ // in this mode, we build the merge expressions of the aggregation
+ AggregateMode::Final => Ok(aggr_expr
+ .iter()
+ .map(|agg| merge_expressions(agg))
+ .collect::<Result<Vec<_>>>()?),
+ }
+}
+
struct HashAggregateIterator {
+ mode: AggregateMode,
schema: SchemaRef,
aggr_expr: Vec<Arc<dyn AggregateExpr>>,
input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,
@@ -406,11 +434,13 @@ struct HashAggregateIterator {
impl HashAggregateIterator {
/// Create a new HashAggregateIterator
pub fn new(
+ mode: AggregateMode,
schema: SchemaRef,
aggr_expr: Vec<Arc<dyn AggregateExpr>>,
input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,
) -> Self {
HashAggregateIterator {
+ mode,
schema,
aggr_expr,
input,
@@ -429,214 +459,161 @@ impl RecordBatchReader for HashAggregateIterator {
return Ok(None);
}
+ // return single batch
self.finished = true;
- let accumulators: Vec<Rc<RefCell<dyn Accumulator>>> = self
- .aggr_expr
- .iter()
- .map(|expr| expr.create_accumulator())
- .collect();
+ let accumulators = create_accumulators(&self.aggr_expr)
+ .map_err(ExecutionError::into_arrow_external_error)?;
+
+ let expressions = aggregate_expressions(&self.aggr_expr, &self.mode)
+ .map_err(ExecutionError::into_arrow_external_error)?;
- // iterate over all input batches and update the accumulators
let mut input = self.input.lock().unwrap();
- // iterate over input and perform aggregation
+ // 1 for each batch:
+ // 1.1 iterate accumulators and respective expressions together
+ // 1.2 evaluate expressions
+ // 1.3 update / merge accumulators with the expressions' values
+ // 2 convert values to a record batch
while let Some(batch) = input.next_batch()? {
- // evaluate the inputs to the aggregate expressions for this batch
- let aggr_input_values = self
- .aggr_expr
+ // 1.1
+ accumulators
.iter()
- .map(|expr| {
- expr.evaluate_input(&batch)
- .map_err(ExecutionError::into_arrow_external_error)
- })
- .collect::<ArrowResult<Vec<_>>>()?;
+ .zip(&expressions)
+ .map(|(accum, expr)| {
+ // 1.2
+ let values = &expr
+ .iter()
+ .map(|e| e.evaluate(&batch))
+ .collect::<Result<Vec<_>>>()?;
- // iterate over each row in the batch
- let _ = accumulators
- .iter()
- .zip(aggr_input_values.iter())
- .map(|(accum, input)| {
- accum
- .borrow_mut()
- .accumulate_batch(input)
- .map_err(ExecutionError::into_arrow_external_error)
+ // 1.3
+ match self.mode {
+ AggregateMode::Partial => accum.borrow_mut().update_batch(values),
+ AggregateMode::Final => accum.borrow_mut().merge_batch(values),
+ }
})
- .collect::<ArrowResult<Vec<_>>>()?;
- }
-
- let input_schema = input.schema();
-
- // build the result arrays
- let mut result_arrays: Vec<ArrayRef> = Vec::with_capacity(self.aggr_expr.len());
-
- // aggregate values
- for i in 0..self.aggr_expr.len() {
- let aggr_data_type = self.aggr_expr[i]
- .data_type(&input_schema)
- .map_err(ExecutionError::into_arrow_external_error)?;
- let value = accumulators[i]
- .borrow_mut()
- .get_value()
+ .collect::<Result<()>>()
.map_err(ExecutionError::into_arrow_external_error)?;
- let array = match aggr_data_type {
- DataType::UInt8 => accum_val!(UInt8Builder, UInt8, value),
- DataType::UInt16 => accum_val!(UInt16Builder, UInt16, value),
- DataType::UInt32 => accum_val!(UInt32Builder, UInt32, value),
- DataType::UInt64 => accum_val!(UInt64Builder, UInt64, value),
- DataType::Int8 => accum_val!(Int8Builder, Int8, value),
- DataType::Int16 => accum_val!(Int16Builder, Int16, value),
- DataType::Int32 => accum_val!(Int32Builder, Int32, value),
- DataType::Int64 => accum_val!(Int64Builder, Int64, value),
- DataType::Float32 => accum_val!(Float32Builder, Float32, value),
- DataType::Float64 => accum_val!(Float64Builder, Float64, value),
- _ => Err(ExecutionError::ExecutionError(
- "Unsupported aggregate expr".to_string(),
- )),
- };
- result_arrays.push(array.map_err(ExecutionError::into_arrow_external_error)?);
}
- let batch = RecordBatch::try_new(self.schema.clone(), result_arrays)?;
+ // 2
+ let columns = finalize_aggregation(&accumulators, &self.mode)
+ .map_err(ExecutionError::into_arrow_external_error)?;
+
+ let batch = RecordBatch::try_new(self.schema.clone(), columns)?;
Ok(Some(batch))
}
}
-/// Append a grouping expression value to a builder
-macro_rules! group_val {
- ($BUILDER:expr, $BUILDER_TY:ident, $VALUE:expr) => {{
- let builder = $BUILDER
- .downcast_mut::<$BUILDER_TY>()
- .expect("failed to downcast group value builder to expected type");
- builder.append_value($VALUE)?;
- }};
-}
-
-/// Append an aggregate expression value to a builder
-macro_rules! aggr_val {
- ($BUILDER:expr, $BUILDER_TY:ident, $VALUE:expr, $SCALAR_TY:ident) => {{
- let builder = $BUILDER
- .downcast_mut::<$BUILDER_TY>()
- .expect("failed to downcast aggregate value builder to expected type");
- match $VALUE {
- Some(ScalarValue::$SCALAR_TY(n)) => builder.append_value(n)?,
- None => builder.append_null()?,
- Some(other) => {
- return Err(ExecutionError::General(format!(
- "Unexpected data type {:?} for aggregate value",
- other
- )))
- }
- }
- }};
+/// Given Vec<Vec<ArrayRef>>, concatenates the inners `Vec<ArrayRef>` into `ArrayRef`, returning `Vec<ArrayRef>`
+/// This assumes that `arrays` is not empty.
+fn concatenate(arrays: Vec<Vec<ArrayRef>>) -> ArrowResult<Vec<ArrayRef>> {
+ (0..arrays[0].len())
+ .map(|column| {
+ let array_list = arrays.iter().map(|a| a[column].clone()).collect::<Vec<_>>();
+ compute::concat(&array_list)
+ })
+ .collect::<ArrowResult<Vec<_>>>()
}
-/// Create a RecordBatch representing the accumulated results in a map
+/// Create a RecordBatch with all group keys and accumulator' states or values.
fn create_batch_from_map(
- map: &FnvHashMap<Vec<GroupByScalar>, Rc<AccumulatorSet>>,
+ mode: &AggregateMode,
+ accumulators: &FnvHashMap<Vec<GroupByScalar>, (AccumulatorSet, Box<Vec<u32>>)>,
num_group_expr: usize,
- num_aggr_expr: usize,
output_schema: &Schema,
) -> Result<RecordBatch> {
- // create builders based on the output schema data types
- let output_types: Vec<&DataType> = output_schema
- .fields()
+ // 1. for each key
+ // 2. create single-row ArrayRef with all group expressions
+ // 3. create single-row ArrayRef with all aggregate states or values
+ // 4. collect all in a vector per key of vec<ArrayRef>, vec[i][j]
+ // 5. concatenate the arrays over the second index [j] into a single vec<ArrayRef>.
+ let arrays = accumulators
.iter()
- .map(|f| f.data_type())
- .collect();
- let mut builders: Vec<Box<dyn ArrayBuilder>> = vec![];
- for data_type in &output_types {
- let builder: Box<dyn ArrayBuilder> = match data_type {
- DataType::Int8 => Box::new(Int8Builder::new(map.len())),
- DataType::Int16 => Box::new(Int16Builder::new(map.len())),
- DataType::Int32 => Box::new(Int32Builder::new(map.len())),
- DataType::Int64 => Box::new(Int64Builder::new(map.len())),
- DataType::UInt8 => Box::new(UInt8Builder::new(map.len())),
- DataType::UInt16 => Box::new(UInt16Builder::new(map.len())),
- DataType::UInt32 => Box::new(UInt32Builder::new(map.len())),
- DataType::UInt64 => Box::new(UInt64Builder::new(map.len())),
- DataType::Float32 => Box::new(Float32Builder::new(map.len())),
- DataType::Float64 => Box::new(Float64Builder::new(map.len())),
- DataType::Utf8 => Box::new(StringBuilder::new(map.len())),
- _ => {
- return Err(ExecutionError::ExecutionError(
- "Unsupported data type in final aggregate result".to_string(),
- ))
- }
- };
- builders.push(builder);
- }
-
- // iterate over the map
- for (k, v) in map.iter() {
- // add group values to builders
- for i in 0..num_group_expr {
- let builder = builders[i].as_any_mut();
- match &k[i] {
- GroupByScalar::Int8(n) => group_val!(builder, Int8Builder, *n),
- GroupByScalar::Int16(n) => group_val!(builder, Int16Builder, *n),
- GroupByScalar::Int32(n) => group_val!(builder, Int32Builder, *n),
- GroupByScalar::Int64(n) => group_val!(builder, Int64Builder, *n),
- GroupByScalar::UInt8(n) => group_val!(builder, UInt8Builder, *n),
- GroupByScalar::UInt16(n) => group_val!(builder, UInt16Builder, *n),
- GroupByScalar::UInt32(n) => group_val!(builder, UInt32Builder, *n),
- GroupByScalar::UInt64(n) => group_val!(builder, UInt64Builder, *n),
- GroupByScalar::Utf8(str) => group_val!(builder, StringBuilder, str),
- }
- }
-
- // add aggregate values to builders
- for i in 0..num_aggr_expr {
- let value = v[i].borrow().get_value()?;
- let index = num_group_expr + i;
- let builder = builders[index].as_any_mut();
- match output_types[index] {
- DataType::Int8 => aggr_val!(builder, Int8Builder, value, Int8),
- DataType::Int16 => aggr_val!(builder, Int16Builder, value, Int16),
- DataType::Int32 => aggr_val!(builder, Int32Builder, value, Int32),
- DataType::Int64 => aggr_val!(builder, Int64Builder, value, Int64),
- DataType::UInt8 => aggr_val!(builder, UInt8Builder, value, UInt8),
- DataType::UInt16 => aggr_val!(builder, UInt16Builder, value, UInt16),
- DataType::UInt32 => aggr_val!(builder, UInt32Builder, value, UInt32),
- DataType::UInt64 => aggr_val!(builder, UInt64Builder, value, UInt64),
- DataType::Float32 => aggr_val!(builder, Float32Builder, value, Float32),
- DataType::Float64 => aggr_val!(builder, Float64Builder, value, Float64),
- // The aggr_val! macro doesn't work for ScalarValue::Utf8 because it contains
- // String and the builder wants &str. In all other cases the scalar and builder
- // types are the same.
- DataType::Utf8 => {
- let builder = builder
- .downcast_mut::<StringBuilder>()
- .expect("failed to downcast builder to expected type");
- match value {
- Some(ScalarValue::Utf8(str)) => builder.append_value(&str)?,
- None => builder.append_null()?,
- Some(_) => {
- return Err(ExecutionError::ExecutionError(
- "Invalid value for accumulator".to_string(),
- ))
- }
+ .map(|(k, (accumulator_set, _))| {
+ // 2.
+ let mut groups = (0..num_group_expr)
+ .map(|i| match &k[i] {
+ GroupByScalar::Int8(n) => {
+ Arc::new(Int8Array::from(vec![*n])) as ArrayRef
}
- }
- _ => {
- return Err(ExecutionError::ExecutionError(
- "Unsupported aggregate data type".to_string(),
- ))
- }
- };
- }
- }
-
- let arrays: Vec<ArrayRef> = builders
- .iter_mut()
- .map(|builder| builder.finish())
- .collect();
+ GroupByScalar::Int16(n) => Arc::new(Int16Array::from(vec![*n])),
+ GroupByScalar::Int32(n) => Arc::new(Int32Array::from(vec![*n])),
+ GroupByScalar::Int64(n) => Arc::new(Int64Array::from(vec![*n])),
+ GroupByScalar::UInt8(n) => Arc::new(UInt8Array::from(vec![*n])),
+ GroupByScalar::UInt16(n) => Arc::new(UInt16Array::from(vec![*n])),
+ GroupByScalar::UInt32(n) => Arc::new(UInt32Array::from(vec![*n])),
+ GroupByScalar::UInt64(n) => Arc::new(UInt64Array::from(vec![*n])),
+ GroupByScalar::Utf8(str) => Arc::new(StringArray::from(vec![&**str])),
+ })
+ .collect::<Vec<ArrayRef>>();
- let batch = RecordBatch::try_new(Arc::new(output_schema.to_owned()), arrays)?;
+ // 3.
+ groups.extend(
+ finalize_aggregation(accumulator_set, mode)
+ .map_err(ExecutionError::into_arrow_external_error)?,
+ );
+ Ok(groups)
+ })
+ // 4.
+ .collect::<Result<Vec<Vec<ArrayRef>>>>()?;
+
+ let batch = if arrays.len() != 0 {
+ // 5.
+ let columns = concatenate(arrays)?;
+ RecordBatch::try_new(Arc::new(output_schema.to_owned()), columns)?
+ } else {
+ common::create_batch_empty(output_schema)?
+ };
Ok(batch)
}
+fn create_accumulators(
+ aggr_expr: &Vec<Arc<dyn AggregateExpr>>,
+) -> Result<AccumulatorSet> {
+ aggr_expr
+ .iter()
+ .map(|expr| expr.create_accumulator())
+ .collect::<Result<Vec<_>>>()
+}
+
+/// returns a vector of ArrayRefs, where each entry corresponds to either the
+/// final value (mode = Final) or states (mode = Partial)
+fn finalize_aggregation(
+ accumulators: &AccumulatorSet,
+ mode: &AggregateMode,
+) -> Result<Vec<ArrayRef>> {
+ match mode {
+ AggregateMode::Partial => {
+ // build the vector of states
+ let a = accumulators
+ .iter()
+ .map(|accumulator| accumulator.borrow_mut().state())
+ .map(|value| {
+ value.and_then(|e| {
+ Ok(e.iter().map(|v| v.to_array()).collect::<Vec<ArrayRef>>())
+ })
+ })
+ .collect::<Result<Vec<_>>>()?;
+ Ok(a.iter().flatten().cloned().collect::<Vec<_>>())
+ }
+ AggregateMode::Final => {
+ // merge the state to the final value
+ accumulators
+ .iter()
+ .map(|accumulator| {
+ accumulator
+ .borrow_mut()
+ .evaluate()
+ .and_then(|v| Ok(v.to_array()))
+ })
+ .collect::<Result<Vec<ArrayRef>>>()
+ }
+ }
+}
+
/// Enumeration of types that can be used in a GROUP BY expression (all primitives except
/// for floating point numerics)
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
@@ -710,43 +687,94 @@ fn create_key(
#[cfg(test)]
mod tests {
+ use arrow::array::Float64Array;
+
use super::*;
- use crate::physical_plan::csv::{CsvExec, CsvReadOptions};
- use crate::physical_plan::expressions::{col, sum};
+ use crate::physical_plan::expressions::{col, Avg};
use crate::physical_plan::merge::MergeExec;
- use crate::test;
+ use crate::physical_plan::{common, memory::MemoryExec};
+
+ fn some_data() -> ArrowResult<(Arc<Schema>, Vec<RecordBatch>)> {
+ // define a schema.
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::UInt32, false),
+ Field::new("b", DataType::Float64, false),
+ ]));
+
+ // define data.
+ Ok((
+ schema.clone(),
+ vec![
+ RecordBatch::try_new(
+ schema.clone(),
+ vec![
+ Arc::new(UInt32Array::from(vec![2, 3, 4, 4])),
+ Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0])),
+ ],
+ )?,
+ RecordBatch::try_new(
+ schema.clone(),
+ vec![
+ Arc::new(UInt32Array::from(vec![2, 3, 3, 4])),
+ Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0])),
+ ],
+ )?,
+ ],
+ ))
+ }
#[test]
fn aggregate() -> Result<()> {
- let schema = test::aggr_test_schema();
+ let (schema, batches) = some_data().unwrap();
- let partitions = 4;
- let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;
-
- let csv =
- CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), None, 1024)?;
+ let input: Arc<dyn ExecutionPlan> = Arc::new(
+ MemoryExec::try_new(&vec![batches.clone(), batches], schema, None).unwrap(),
+ );
let groups: Vec<(Arc<dyn PhysicalExpr>, String)> =
- vec![(col("c2"), "c2".to_string())];
+ vec![(col("a"), "a".to_string())];
- let aggregates: Vec<(Arc<dyn AggregateExpr>, String)> =
- vec![(sum(col("c4")), "SUM(c4)".to_string())];
+ let aggregates: Vec<Arc<dyn AggregateExpr>> = vec![Arc::new(Avg::new(
+ col("b"),
+ "AVG(b)".to_string(),
+ DataType::Float64,
+ ))];
let partial_aggregate = Arc::new(HashAggregateExec::try_new(
AggregateMode::Partial,
groups.clone(),
aggregates.clone(),
- Arc::new(csv),
+ input,
)?);
- // construct the expressions for the final aggregation
- let (final_group, final_aggr) = partial_aggregate.make_final_expr(
- groups.iter().map(|x| x.1.clone()).collect(),
- aggregates.iter().map(|x| x.1.clone()).collect(),
- );
+ let result = common::collect(partial_aggregate.execute(0)?)?;
+
+ let keys = result[0]
+ .column(0)
+ .as_any()
+ .downcast_ref::<UInt32Array>()
+ .unwrap();
+ assert_eq!(*keys, UInt32Array::from(vec![2, 3, 4]));
+
+ let ns = result[0]
+ .column(1)
+ .as_any()
+ .downcast_ref::<UInt64Array>()
+ .unwrap();
+ assert_eq!(*ns, UInt64Array::from(vec![2, 3, 3]));
+
+ let sums = result[0]
+ .column(2)
+ .as_any()
+ .downcast_ref::<Float64Array>()
+ .unwrap();
+ assert_eq!(*sums, Float64Array::from(vec![2.0, 7.0, 11.0]));
let merge = Arc::new(MergeExec::new(partial_aggregate, 2));
+ let final_group: Vec<Arc<dyn PhysicalExpr>> =
+ (0..groups.len()).map(|i| col(&groups[i].1)).collect();
+
let merged_aggregate = Arc::new(HashAggregateExec::try_new(
AggregateMode::Final,
final_group
@@ -754,20 +782,16 @@ mod tests {
.enumerate()
.map(|(i, expr)| (expr.clone(), groups[i].1.clone()))
.collect(),
- final_aggr
- .iter()
- .enumerate()
- .map(|(i, expr)| (expr.clone(), aggregates[i].1.clone()))
- .collect(),
+ aggregates,
merge,
)?);
- let result = test::execute(merged_aggregate)?;
+ let result = common::collect(merged_aggregate.execute(0)?)?;
assert_eq!(result.len(), 1);
let batch = &result[0];
assert_eq!(batch.num_columns(), 2);
- assert_eq!(batch.num_rows(), 5);
+ assert_eq!(batch.num_rows(), 3);
let a = batch
.column(0)
@@ -777,23 +801,18 @@ mod tests {
let b = batch
.column(1)
.as_any()
- .downcast_ref::<Int64Array>()
+ .downcast_ref::<Float64Array>()
.unwrap();
- let mut group_values = vec![];
- for i in 0..a.len() {
- group_values.push(a.value(i))
- }
-
- let mut aggr_values = vec![];
- for i in 1..=5 {
- // find index of row with this value for the grouping column
- let index = group_values.iter().position(|&r| r == i).unwrap();
- aggr_values.push(b.value(index));
- }
-
- let expected: Vec<i64> = vec![88722, 90999, 80899, -120910, 92287];
- assert_eq!(aggr_values, expected);
+ assert_eq!(*a, UInt32Array::from(vec![2, 3, 4]));
+ assert_eq!(
+ *b,
+ Float64Array::from(vec![
+ 1.0,
+ (2.0 + 3.0 + 2.0) / 3.0,
+ (3.0 + 4.0 + 4.0) / 3.0
+ ])
+ );
Ok(())
}
diff --git a/rust/datafusion/src/physical_plan/mod.rs b/rust/datafusion/src/physical_plan/mod.rs
index f71b2792ff..df399a13a4 100644
--- a/rust/datafusion/src/physical_plan/mod.rs
+++ b/rust/datafusion/src/physical_plan/mod.rs
@@ -22,12 +22,12 @@ use std::fmt::{Debug, Display};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
-use crate::error::Result;
use crate::execution::context::ExecutionContextState;
-use crate::logical_plan::{LogicalPlan, ScalarValue};
-use arrow::array::ArrayRef;
+use crate::logical_plan::LogicalPlan;
+use crate::{error::Result, scalar::ScalarValue};
use arrow::datatypes::{DataType, Schema, SchemaRef};
use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use arrow::{array::ArrayRef, datatypes::Field};
/// Physical query planner that converts a `LogicalPlan` to an
/// `ExecutionPlan` suitable for execution.
@@ -104,30 +104,81 @@ pub trait PhysicalExpr: Send + Sync + Display + Debug {
fn evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef>;
}
-/// Aggregate expression that can be evaluated against a RecordBatch
+/// An aggregate expression that:
+/// * knows its resulting field
+/// * knows how to create its accumulator
+/// * knows its accumulator's state's field
+/// * knows the expressions from whose its accumulator will receive values
pub trait AggregateExpr: Send + Sync + Debug {
- /// Get the data type of this expression, given the schema of the input
- fn data_type(&self, input_schema: &Schema) -> Result<DataType>;
- /// Determine whether this expression is nullable, given the schema of the input
- fn nullable(&self, input_schema: &Schema) -> Result<bool>;
- /// Evaluate the expression being aggregated
- fn evaluate_input(&self, batch: &RecordBatch) -> Result<ArrayRef>;
- /// Create an accumulator for this aggregate expression
- fn create_accumulator(&self) -> Rc<RefCell<dyn Accumulator>>;
- /// Create an aggregate expression for combining the results of accumulators from partitions.
- /// For example, to combine the results of a parallel SUM we just need to do another SUM, but
- /// to combine the results of parallel COUNT we would also use SUM.
- fn create_reducer(&self, column_name: &str) -> Arc<dyn AggregateExpr>;
+ /// the field of the final result of this aggregation.
+ fn field(&self) -> Result<Field>;
+
+ /// the accumulator used to accumulate values from the expressions.
+ /// the accumulator expects the same number of arguments as `expressions` and must
+ /// return states with the same description as `state_fields`
+ fn create_accumulator(&self) -> Result<Rc<RefCell<dyn Accumulator>>>;
+
+ /// the fields that encapsulate the Accumulator's state
+ /// the number of fields here equals the number of states that the accumulator contains
+ fn state_fields(&self) -> Result<Vec<Field>>;
+
+ /// expressions that are passed to the Accumulator.
+ /// Single-column aggregations such as `sum` return a single value, others (e.g. `cov`) return many.
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>>;
}
-/// Aggregate accumulator
-pub trait Accumulator: Debug {
- /// Update the accumulator based on a row in a batch
- fn accumulate_scalar(&mut self, value: Option<ScalarValue>) -> Result<()>;
- /// Update the accumulator based on an array in a batch
- fn accumulate_batch(&mut self, array: &ArrayRef) -> Result<()>;
- /// Get the final value for the accumulator
- fn get_value(&self) -> Result<Option<ScalarValue>>;
+/// An accumulator represents a stateful object that lives throughout the evaluation of multiple rows and
+/// generically accumulates values. An accumulator knows how to:
+/// * update its state from inputs via `update`
+/// * convert its internal state to a vector of scalar values
+/// * update its state from multiple accumulators' states via `merge`
+/// * compute the final value from its internal state via `evaluate`
+pub trait Accumulator: Send + Sync + Debug {
+ /// Returns the state of the accumulator at the end of the accumulation.
+ // in the case of an average on which we track `sum` and `n`, this function should return a vector
+ // of two values, sum and n.
+ fn state(&self) -> Result<Vec<ScalarValue>>;
+
+ /// updates the accumulator's state from a vector of scalars.
+ fn update(&mut self, values: &Vec<ScalarValue>) -> Result<()>;
+
+ /// updates the accumulator's state from a vector of arrays.
+ fn update_batch(&mut self, values: &Vec<ArrayRef>) -> Result<()> {
+ if values.len() == 0 {
+ return Ok(());
+ };
+ (0..values[0].len())
+ .map(|index| {
+ let v = values
+ .iter()
+ .map(|array| ScalarValue::try_from_array(array, index))
+ .collect::<Result<Vec<_>>>()?;
+ self.update(&v)
+ })
+ .collect::<Result<_>>()
+ }
+
+ /// updates the accumulator's state from a vector of scalars.
+ fn merge(&mut self, states: &Vec<ScalarValue>) -> Result<()>;
+
+ /// updates the accumulator's state from a vector of states.
+ fn merge_batch(&mut self, states: &Vec<ArrayRef>) -> Result<()> {
+ if states.len() == 0 {
+ return Ok(());
+ };
+ (0..states[0].len())
+ .map(|index| {
+ let v = states
+ .iter()
+ .map(|array| ScalarValue::try_from_array(array, index))
+ .collect::<Result<Vec<_>>>()?;
+ self.merge(&v)
+ })
+ .collect::<Result<_>>()
+ }
+
+ /// returns its value based on its current state.
+ fn evaluate(&self) -> Result<ScalarValue>;
}
pub mod aggregates;
diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rs
index c2e5826fbb..c7e035cb1e 100644
--- a/rust/datafusion/src/physical_plan/planner.rs
+++ b/rust/datafusion/src/physical_plan/planner.rs
@@ -42,6 +42,7 @@ use crate::physical_plan::{AggregateExpr, ExecutionPlan, PhysicalExpr, PhysicalP
use crate::variable::VarType;
use arrow::compute::SortOptions;
use arrow::datatypes::Schema;
+use expressions::col;
/// This trait permits the `DefaultPhysicalPlanner` to create plans for
/// user defined `ExtensionPlanNode`s
@@ -216,32 +217,18 @@ impl DefaultPhysicalPlanner {
.collect::<Result<Vec<_>>>()?;
let aggregates = aggr_expr
.iter()
- .map(|e| {
- tuple_err((
- self.create_aggregate_expr(e, &input_schema, ctx_state),
- e.name(&input_schema),
- ))
- })
+ .map(|e| self.create_aggregate_expr(e, &input_schema, ctx_state))
.collect::<Result<Vec<_>>>()?;
- let initial_aggr = HashAggregateExec::try_new(
+ let initial_aggr = Arc::new(HashAggregateExec::try_new(
AggregateMode::Partial,
groups.clone(),
aggregates.clone(),
input,
- )?;
-
- if initial_aggr.output_partitioning().partition_count() == 1 {
- return Ok(Arc::new(initial_aggr));
- }
-
- let partial_aggr = Arc::new(initial_aggr);
+ )?);
- // construct the expressions for the final aggregation
- let (final_group, final_aggr) = partial_aggr.make_final_expr(
- groups.iter().map(|x| x.1.clone()).collect(),
- aggregates.iter().map(|x| x.1.clone()).collect(),
- );
+ let final_group: Vec<Arc<dyn PhysicalExpr>> =
+ (0..groups.len()).map(|i| col(&groups[i].1)).collect();
// construct a second aggregation, keeping the final column name equal to the first aggregation
// and the expressions corresponding to the respective aggregate
@@ -252,12 +239,8 @@ impl DefaultPhysicalPlanner {
.enumerate()
.map(|(i, expr)| (expr.clone(), groups[i].1.clone()))
.collect(),
- final_aggr
- .iter()
- .enumerate()
- .map(|(i, expr)| (expr.clone(), aggregates[i].1.clone()))
- .collect(),
- partial_aggr,
+ aggregates,
+ initial_aggr,
)?))
}
LogicalPlan::Filter {
@@ -484,7 +467,12 @@ impl DefaultPhysicalPlanner {
.iter()
.map(|e| self.create_physical_expr(e, input_schema, ctx_state))
.collect::<Result<Vec<_>>>()?;
- aggregates::create_aggregate_expr(fun, &args, input_schema)
+ aggregates::create_aggregate_expr(
+ fun,
+ &args,
+ input_schema,
+ e.name(input_schema)?,
+ )
}
other => Err(ExecutionError::General(format!(
"Invalid aggregate expression '{:?}'",
diff --git a/rust/datafusion/src/scalar.rs b/rust/datafusion/src/scalar.rs
new file mode 100644
index 0000000000..90f5de26ea
--- /dev/null
+++ b/rust/datafusion/src/scalar.rs
@@ -0,0 +1,305 @@
+// 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.
+
+//! This module provides ScalarValue, an enum that can be used for storage of single elements
+
+use std::{convert::TryFrom, fmt, sync::Arc};
+
+use arrow::array::{
+ Array, BooleanArray, Float32Array, Float64Array, Int16Array, Int32Array, Int64Array,
+ Int8Array, LargeStringArray, StringArray, UInt16Array, UInt32Array, UInt64Array,
+ UInt8Array,
+};
+use arrow::{
+ array::{ArrayRef, PrimitiveArrayOps, StringArrayOps},
+ datatypes::DataType,
+};
+
+use crate::error::{ExecutionError, Result};
+
+/// Represents a dynamically typed, nullable single value.
+/// This is the single-valued counter-part of arrow’s `Array`.
+#[derive(Clone, PartialEq)]
+pub enum ScalarValue {
+ /// true or false value
+ Boolean(Option<bool>),
+ /// 32bit float
+ Float32(Option<f32>),
+ /// 64bit float
+ Float64(Option<f64>),
+ /// signed 8bit int
+ Int8(Option<i8>),
+ /// signed 16bit int
+ Int16(Option<i16>),
+ /// signed 32bit int
+ Int32(Option<i32>),
+ /// signed 64bit int
+ Int64(Option<i64>),
+ /// unsigned 8bit int
+ UInt8(Option<u8>),
+ /// unsigned 16bit int
+ UInt16(Option<u16>),
+ /// unsigned 32bit int
+ UInt32(Option<u32>),
+ /// unsigned 64bit int
+ UInt64(Option<u64>),
+ /// utf-8 encoded string.
+ Utf8(Option<String>),
+ /// utf-8 encoded string representing a LargeString's arrow type.
+ LargeUtf8(Option<String>),
+}
+
+macro_rules! typed_cast {
+ ($array:expr, $index:expr, $ARRAYTYPE:ident, $SCALAR:ident) => {{
+ let array = $array.as_any().downcast_ref::<$ARRAYTYPE>().unwrap();
+ ScalarValue::$SCALAR(match array.is_null($index) {
+ true => None,
+ false => Some(array.value($index).into()),
+ })
+ }};
+}
+
+impl ScalarValue {
+ /// Getter for the `DataType` of the value
+ pub fn get_datatype(&self) -> DataType {
+ match *self {
+ ScalarValue::Boolean(_) => DataType::Boolean,
+ ScalarValue::UInt8(_) => DataType::UInt8,
+ ScalarValue::UInt16(_) => DataType::UInt16,
+ ScalarValue::UInt32(_) => DataType::UInt32,
+ ScalarValue::UInt64(_) => DataType::UInt64,
+ ScalarValue::Int8(_) => DataType::Int8,
+ ScalarValue::Int16(_) => DataType::Int16,
+ ScalarValue::Int32(_) => DataType::Int32,
+ ScalarValue::Int64(_) => DataType::Int64,
+ ScalarValue::Float32(_) => DataType::Float32,
+ ScalarValue::Float64(_) => DataType::Float64,
+ ScalarValue::Utf8(_) => DataType::Utf8,
+ ScalarValue::LargeUtf8(_) => DataType::LargeUtf8,
+ }
+ }
+
+ /// whether this value is null or not.
+ pub fn is_null(&self) -> bool {
+ match *self {
+ ScalarValue::Boolean(None)
+ | ScalarValue::UInt8(None)
+ | ScalarValue::UInt16(None)
+ | ScalarValue::UInt32(None)
+ | ScalarValue::UInt64(None)
+ | ScalarValue::Int8(None)
+ | ScalarValue::Int16(None)
+ | ScalarValue::Int32(None)
+ | ScalarValue::Int64(None)
+ | ScalarValue::Float32(None)
+ | ScalarValue::Float64(None)
+ | ScalarValue::Utf8(None)
+ | ScalarValue::LargeUtf8(None) => true,
+ _ => false,
+ }
+ }
+
+ /// Converts a scalar value into an 1-row array.
+ pub fn to_array(&self) -> ArrayRef {
+ match self {
+ ScalarValue::Boolean(e) => Arc::new(BooleanArray::from(vec![*e])) as ArrayRef,
+ ScalarValue::Float64(e) => Arc::new(Float64Array::from(vec![*e])) as ArrayRef,
+ ScalarValue::Float32(e) => Arc::new(Float32Array::from(vec![*e])),
+ ScalarValue::Int8(e) => Arc::new(Int8Array::from(vec![*e])),
+ ScalarValue::Int16(e) => Arc::new(Int16Array::from(vec![*e])),
+ ScalarValue::Int32(e) => Arc::new(Int32Array::from(vec![*e])),
+ ScalarValue::Int64(e) => Arc::new(Int64Array::from(vec![*e])),
+ ScalarValue::UInt8(e) => Arc::new(UInt8Array::from(vec![*e])),
+ ScalarValue::UInt16(e) => Arc::new(UInt16Array::from(vec![*e])),
+ ScalarValue::UInt32(e) => Arc::new(UInt32Array::from(vec![*e])),
+ ScalarValue::UInt64(e) => Arc::new(UInt64Array::from(vec![*e])),
+ ScalarValue::Utf8(e) => Arc::new(StringArray::from(vec![e.as_deref()])),
+ ScalarValue::LargeUtf8(e) => {
+ Arc::new(LargeStringArray::from(vec![e.as_deref()]))
+ }
+ }
+ }
+
+ /// Converts a value in `array` at `index` into a ScalarValue
+ pub fn try_from_array(array: &ArrayRef, index: usize) -> Result<Self> {
+ Ok(match array.data_type() {
+ DataType::Boolean => typed_cast!(array, index, BooleanArray, Boolean),
+ DataType::Float64 => typed_cast!(array, index, Float64Array, Float64),
+ DataType::Float32 => typed_cast!(array, index, Float32Array, Float32),
+ DataType::UInt64 => typed_cast!(array, index, UInt64Array, UInt64),
+ DataType::UInt32 => typed_cast!(array, index, UInt32Array, UInt32),
+ DataType::UInt16 => typed_cast!(array, index, UInt16Array, UInt16),
+ DataType::UInt8 => typed_cast!(array, index, UInt8Array, UInt8),
+ DataType::Int64 => typed_cast!(array, index, Int64Array, Int64),
+ DataType::Int32 => typed_cast!(array, index, Int32Array, Int32),
+ DataType::Int16 => typed_cast!(array, index, Int16Array, Int16),
+ DataType::Int8 => typed_cast!(array, index, Int8Array, Int8),
+ DataType::Utf8 => typed_cast!(array, index, StringArray, Utf8),
+ DataType::LargeUtf8 => typed_cast!(array, index, LargeStringArray, LargeUtf8),
+ other => {
+ return Err(ExecutionError::NotImplemented(format!(
+ "Can't create a scalar of array of type \"{:?}\"",
+ other
+ )))
+ }
+ })
+ }
+}
+
+impl From<f64> for ScalarValue {
+ fn from(value: f64) -> Self {
+ ScalarValue::Float64(Some(value))
+ }
+}
+
+impl From<f32> for ScalarValue {
+ fn from(value: f32) -> Self {
+ ScalarValue::Float32(Some(value))
+ }
+}
+
+impl From<i8> for ScalarValue {
+ fn from(value: i8) -> Self {
+ ScalarValue::Int8(Some(value))
+ }
+}
+
+impl From<i16> for ScalarValue {
+ fn from(value: i16) -> Self {
+ ScalarValue::Int16(Some(value))
+ }
+}
+
+impl From<i32> for ScalarValue {
+ fn from(value: i32) -> Self {
+ ScalarValue::Int32(Some(value))
+ }
+}
+
+impl From<i64> for ScalarValue {
+ fn from(value: i64) -> Self {
+ ScalarValue::Int64(Some(value))
+ }
+}
+
+impl From<bool> for ScalarValue {
+ fn from(value: bool) -> Self {
+ ScalarValue::Boolean(Some(value))
+ }
+}
+
+impl From<u8> for ScalarValue {
+ fn from(value: u8) -> Self {
+ ScalarValue::UInt8(Some(value))
+ }
+}
+
+impl From<u16> for ScalarValue {
+ fn from(value: u16) -> Self {
+ ScalarValue::UInt16(Some(value))
+ }
+}
+
+impl From<u32> for ScalarValue {
+ fn from(value: u32) -> Self {
+ ScalarValue::UInt32(Some(value))
+ }
+}
+
+impl From<u64> for ScalarValue {
+ fn from(value: u64) -> Self {
+ ScalarValue::UInt64(Some(value))
+ }
+}
+
+impl TryFrom<&DataType> for ScalarValue {
+ type Error = ExecutionError;
+
+ fn try_from(datatype: &DataType) -> Result<Self> {
+ Ok(match datatype {
+ &DataType::Boolean => ScalarValue::Boolean(None),
+ &DataType::Float64 => ScalarValue::Float64(None),
+ &DataType::Float32 => ScalarValue::Float32(None),
+ &DataType::Int8 => ScalarValue::Int8(None),
+ &DataType::Int16 => ScalarValue::Int16(None),
+ &DataType::Int32 => ScalarValue::Int32(None),
+ &DataType::Int64 => ScalarValue::Int64(None),
+ &DataType::UInt8 => ScalarValue::UInt8(None),
+ &DataType::UInt16 => ScalarValue::UInt16(None),
+ &DataType::UInt32 => ScalarValue::UInt32(None),
+ &DataType::UInt64 => ScalarValue::UInt64(None),
+ &DataType::Utf8 => ScalarValue::Utf8(None),
+ &DataType::LargeUtf8 => ScalarValue::LargeUtf8(None),
+ _ => {
+ return Err(ExecutionError::NotImplemented(format!(
+ "Can't create a scalar of type \"{:?}\"",
+ datatype
+ )))
+ }
+ })
+ }
+}
+
+macro_rules! format_option {
+ ($F:expr, $EXPR:expr) => {{
+ match $EXPR {
+ Some(e) => write!($F, "{}", e),
+ None => write!($F, "NULL"),
+ }
+ }};
+}
+
+impl fmt::Display for ScalarValue {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match self {
+ ScalarValue::Boolean(e) => format_option!(f, e)?,
+ ScalarValue::Float32(e) => format_option!(f, e)?,
+ ScalarValue::Float64(e) => format_option!(f, e)?,
+ ScalarValue::Int8(e) => format_option!(f, e)?,
+ ScalarValue::Int16(e) => format_option!(f, e)?,
+ ScalarValue::Int32(e) => format_option!(f, e)?,
+ ScalarValue::Int64(e) => format_option!(f, e)?,
+ ScalarValue::UInt8(e) => format_option!(f, e)?,
+ ScalarValue::UInt16(e) => format_option!(f, e)?,
+ ScalarValue::UInt32(e) => format_option!(f, e)?,
+ ScalarValue::UInt64(e) => format_option!(f, e)?,
+ ScalarValue::Utf8(e) => format_option!(f, e)?,
+ ScalarValue::LargeUtf8(e) => format_option!(f, e)?,
+ };
+ Ok(())
+ }
+}
+
+impl fmt::Debug for ScalarValue {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ ScalarValue::Boolean(_) => write!(f, "Boolean({})", self),
+ ScalarValue::Float32(_) => write!(f, "Float32({})", self),
+ ScalarValue::Float64(_) => write!(f, "Float64({})", self),
+ ScalarValue::Int8(_) => write!(f, "Int8({})", self),
+ ScalarValue::Int16(_) => write!(f, "Int16({})", self),
+ ScalarValue::Int32(_) => write!(f, "Int32({})", self),
+ ScalarValue::Int64(_) => write!(f, "Int64({})", self),
+ ScalarValue::UInt8(_) => write!(f, "UInt8({})", self),
+ ScalarValue::UInt16(_) => write!(f, "UInt16({})", self),
+ ScalarValue::UInt32(_) => write!(f, "UInt32({})", self),
+ ScalarValue::UInt64(_) => write!(f, "UInt64({})", self),
+ ScalarValue::Utf8(_) => write!(f, "Utf8(\"{}\")", self),
+ ScalarValue::LargeUtf8(_) => write!(f, "LargeUtf8(\"{}\")", self),
+ }
+ }
+}
diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rs
index 40e6dbf7e6..73d341ecdf 100644
--- a/rust/datafusion/src/sql/planner.rs
+++ b/rust/datafusion/src/sql/planner.rs
@@ -23,9 +23,9 @@ use std::sync::Arc;
use crate::error::{ExecutionError, Result};
use crate::logical_plan::Expr::Alias;
use crate::logical_plan::{
- lit, Expr, LogicalPlan, LogicalPlanBuilder, Operator, PlanType, ScalarValue,
- StringifiedPlan,
+ lit, Expr, LogicalPlan, LogicalPlanBuilder, Operator, PlanType, StringifiedPlan,
};
+use crate::scalar::ScalarValue;
use crate::{
physical_plan::udf::ScalarUDF,
physical_plan::{aggregates, functions},
@@ -343,7 +343,7 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {
match *limit {
Some(ref limit_expr) => {
let n = match self.sql_to_rex(&limit_expr, &input.schema())? {
- Expr::Literal(ScalarValue::Int64(n)) => Ok(n as usize),
+ Expr::Literal(ScalarValue::Int64(Some(n))) => Ok(n as usize),
_ => Err(ExecutionError::General(
"Unexpected expression for LIMIT clause".to_string(),
)),
diff --git a/rust/datafusion/src/test/variable.rs b/rust/datafusion/src/test/variable.rs
index f64934b37f..47d1370e80 100644
--- a/rust/datafusion/src/test/variable.rs
+++ b/rust/datafusion/src/test/variable.rs
@@ -18,7 +18,7 @@
//! System variable provider
use crate::error::Result;
-use crate::logical_plan::ScalarValue;
+use crate::scalar::ScalarValue;
use crate::variable::VarProvider;
/// System variable
@@ -35,7 +35,7 @@ impl VarProvider for SystemVar {
/// get system variable value
fn get_value(&self, var_names: Vec<String>) -> Result<ScalarValue> {
let s = format!("{}-{}", "system-var".to_string(), var_names.concat());
- Ok(ScalarValue::Utf8(s))
+ Ok(ScalarValue::Utf8(Some(s)))
}
}
@@ -53,6 +53,6 @@ impl VarProvider for UserDefinedVar {
/// Get user defined variable value
fn get_value(&self, var_names: Vec<String>) -> Result<ScalarValue> {
let s = format!("{}-{}", "user-defined-var".to_string(), var_names.concat());
- Ok(ScalarValue::Utf8(s))
+ Ok(ScalarValue::Utf8(Some(s)))
}
}
diff --git a/rust/datafusion/src/variable/mod.rs b/rust/datafusion/src/variable/mod.rs
index 44b05b98a9..ebcee18969 100644
--- a/rust/datafusion/src/variable/mod.rs
+++ b/rust/datafusion/src/variable/mod.rs
@@ -18,7 +18,7 @@
//! Variable provider
use crate::error::Result;
-use crate::logical_plan::ScalarValue;
+use crate::scalar::ScalarValue;
/// Variable type, system/user defiend
#[derive(Debug, Clone, PartialEq, Eq, Hash)]