Apache DataFusion SQL Query Engine
ARROW-6695: [Rust] [DataFusion] Remove legacy code for executing logical plan
Andy Grove3ac6e2e81d5f
diff --git a/rust/datafusion/benches/aggregate_query_sql.rs b/rust/datafusion/benches/aggregate_query_sql.rsindex d0c1b0f649..01c70074f5 100644--- a/rust/datafusion/benches/aggregate_query_sql.rs+++ b/rust/datafusion/benches/aggregate_query_sql.rs@@ -35,12 +35,10 @@ use datafusion::execution::context::ExecutionContext;fn aggregate_query(ctx: &Rc<RefCell<ExecutionContext>>, sql: &str) {// execute the querylet mut mut_ctx = ctx.borrow_mut();- let relation = mut_ctx.sql(&sql, 1024 * 1024).unwrap();+ let results = mut_ctx.sql(&sql, 1024 * 1024).unwrap();// display the relation- let mut results = relation.borrow_mut();-- while let Some(_) = results.next().unwrap() {}+ for _batch in results {}}fn create_context() -> Rc<RefCell<ExecutionContext>> {diff --git a/rust/datafusion/src/bin/repl.rs b/rust/datafusion/src/bin/repl.rsindex 7ef042ed43..36deb1300c 100644--- a/rust/datafusion/src/bin/repl.rs+++ b/rust/datafusion/src/bin/repl.rs@@ -19,13 +19,12 @@use arrow::array::*;use arrow::datatypes::{DataType, TimeUnit};+use arrow::record_batch::RecordBatch;use clap::{crate_version, App, Arg};use datafusion::error::{ExecutionError, Result};use datafusion::execution::context::ExecutionContext;-use datafusion::execution::relation::Relation;use prettytable::{Cell, Row, Table};use rustyline::Editor;-use std::cell::RefMut;use std::env;use std::path::Path;@@ -99,16 +98,21 @@ fn exec_and_print(sql: String,batch_size: usize,) -> Result<()> {- let relation = ctx.sql(&sql, batch_size)?;- print_result(relation.borrow_mut())?;+ let results = ctx.sql(&sql, batch_size)?;+ print_result(&results)?;Ok(())}-fn print_result(mut results: RefMut<Relation>) -> Result<()> {+fn print_result(results: &Vec<RecordBatch>) -> Result<()> {let mut row_count = 0;let mut table = Table::new();- let schema = results.schema();++ if results.is_empty() {+ return Ok(());+ }++ let schema = results[0].schema();let mut header = Vec::new();for field in schema.fields() {@@ -116,7 +120,7 @@ fn print_result(mut results: RefMut<Relation>) -> Result<()> {}table.add_row(Row::new(header));- while let Some(batch) = results.next().unwrap() {+ for batch in results {row_count += batch.num_rows();for row in 0..batch.num_rows() {diff --git a/rust/datafusion/src/execution/aggregate.rs b/rust/datafusion/src/execution/aggregate.rsdeleted file mode 100644index 1795f492c5..0000000000--- a/rust/datafusion/src/execution/aggregate.rs+++ /dev/null@@ -1,1474 +0,0 @@-// Licensed to the Apache Software Foundation (ASF) under one-// or more contributor license agreements. See the NOTICE file-// distributed with this work for additional information-// regarding copyright ownership. The ASF licenses this file-// to you under the Apache License, Version 2.0 (the-// "License"); you may not use this file except in compliance-// with the License. You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing,-// software distributed under the License is distributed on an-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY-// KIND, either express or implied. See the License for the-// specific language governing permissions and limitations-// under the License.--//! Execution of a simple aggregate relation containing MIN, MAX, COUNT, SUM aggregate-//! functions with optional GROUP BY columns--use std::cell::RefCell;-use std::rc::Rc;-use std::str;-use std::sync::Arc;--use arrow::array::*;-use arrow::compute;-use arrow::datatypes::{DataType, Schema};-use arrow::record_batch::RecordBatch;--use crate::error::{ExecutionError, Result};-use crate::execution::expression::AggregateType;-use crate::execution::relation::Relation;-use crate::logicalplan::ScalarValue;--use crate::execution::expression::CompiledAggregateExpression;-use crate::execution::expression::CompiledExpr;-use fnv::FnvHashMap;--/// An aggregate relation is made up of zero or more grouping expressions and one-/// or more aggregate expressions-pub(super) struct AggregateRelation {- schema: Arc<Schema>,- input: Rc<RefCell<dyn Relation>>,- group_expr: Vec<CompiledExpr>,- aggr_expr: Vec<CompiledAggregateExpression>,- end_of_results: bool,-}--impl AggregateRelation {- pub fn new(- schema: Arc<Schema>,- input: Rc<RefCell<dyn Relation>>,- group_expr: Vec<CompiledExpr>,- aggr_expr: Vec<CompiledAggregateExpression>,- ) -> Self {- AggregateRelation {- schema,- input,- group_expr,- aggr_expr,- end_of_results: false,- }- }-}--/// 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)]-enum GroupByScalar {- UInt8(u8),- UInt16(u16),- UInt32(u32),- UInt64(u64),- Int8(i8),- Int16(i16),- Int32(i32),- Int64(i64),- Utf8(String),-}--/// Aggregate function that can accept individual values and compute an aggregate-trait AggregateFunction {- /// Get the function name (used for debugging)- fn name(&self) -> &str;-- /// Update the current aggregate value based on a new value. A value of `None`- /// represents a null value.- fn accumulate_scalar(&mut self, value: &Option<ScalarValue>) -> Result<()>;-- /// Update the current aggregate value based on an array.- fn accumulate_batch(&mut self, array: ArrayRef) -> Result<()>;-- /// Return the result of the aggregate function after all values have been processed- /// by calls to `accumulate_scalar`.- fn result(&self) -> Option<ScalarValue>;-- /// Get the data type of the result of the aggregate function. For some operations,- /// such as `min`, `max`, and `sum`, the data type will be the same as the data type- /// of the argument. For other aggregates, such as `count`, the data type is- /// independent of the data type of the input.- fn data_type(&self) -> &DataType;-}--/// Implementation of MIN aggregate function-#[derive(Debug)]-struct MinFunction {- data_type: DataType,- value: Option<ScalarValue>,-}--impl MinFunction {- fn new(data_type: &DataType) -> Self {- Self {- data_type: data_type.clone(),- value: None,- }- }-}--impl AggregateFunction for MinFunction {- fn name(&self) -> &str {- "min"- }-- fn accumulate_scalar(&mut self, value: &Option<ScalarValue>) -> Result<()> {- if self.value.is_none() {- self.value = value.clone();- } else if value.is_some() {- self.value = match (&self.value, value) {- (Some(ScalarValue::UInt8(a)), Some(ScalarValue::UInt8(b))) => {- Some(ScalarValue::UInt8(*a.min(b)))- }- (Some(ScalarValue::UInt16(a)), Some(ScalarValue::UInt16(b))) => {- Some(ScalarValue::UInt16(*a.min(b)))- }- (Some(ScalarValue::UInt32(a)), Some(ScalarValue::UInt32(b))) => {- Some(ScalarValue::UInt32(*a.min(b)))- }- (Some(ScalarValue::UInt64(a)), Some(ScalarValue::UInt64(b))) => {- Some(ScalarValue::UInt64(*a.min(b)))- }- (Some(ScalarValue::Int8(a)), Some(ScalarValue::Int8(b))) => {- Some(ScalarValue::Int8(*a.min(b)))- }- (Some(ScalarValue::Int16(a)), Some(ScalarValue::Int16(b))) => {- Some(ScalarValue::Int16(*a.min(b)))- }- (Some(ScalarValue::Int32(a)), Some(ScalarValue::Int32(b))) => {- Some(ScalarValue::Int32(*a.min(b)))- }- (Some(ScalarValue::Int64(a)), Some(ScalarValue::Int64(b))) => {- Some(ScalarValue::Int64(*a.min(b)))- }- (Some(ScalarValue::Float32(a)), Some(ScalarValue::Float32(b))) => {- Some(ScalarValue::Float32(a.min(*b)))- }- (Some(ScalarValue::Float64(a)), Some(ScalarValue::Float64(b))) => {- Some(ScalarValue::Float64(a.min(*b)))- }- _ => {- return Err(ExecutionError::ExecutionError(- "unsupported data type for MIN".to_string(),- ));- }- }- }- Ok(())- }-- fn accumulate_batch(&mut self, array: ArrayRef) -> Result<()> {- let accumulated_value = array_min(array)?;-- self.accumulate_scalar(&accumulated_value)- }-- fn result(&self) -> Option<ScalarValue> {- self.value.clone()- }-- fn data_type(&self) -> &DataType {- &self.data_type- }-}--/// Implementation of MAX aggregate function-#[derive(Debug)]-struct MaxFunction {- data_type: DataType,- value: Option<ScalarValue>,-}--impl MaxFunction {- fn new(data_type: &DataType) -> Self {- Self {- data_type: data_type.clone(),- value: None,- }- }-}--impl AggregateFunction for MaxFunction {- fn name(&self) -> &str {- "max"- }-- fn accumulate_scalar(&mut self, value: &Option<ScalarValue>) -> Result<()> {- if self.value.is_none() {- self.value = value.clone();- } else if value.is_some() {- self.value = match (&self.value, value) {- (Some(ScalarValue::UInt8(a)), Some(ScalarValue::UInt8(b))) => {- Some(ScalarValue::UInt8(*a.max(b)))- }- (Some(ScalarValue::UInt16(a)), Some(ScalarValue::UInt16(b))) => {- Some(ScalarValue::UInt16(*a.max(b)))- }- (Some(ScalarValue::UInt32(a)), Some(ScalarValue::UInt32(b))) => {- Some(ScalarValue::UInt32(*a.max(b)))- }- (Some(ScalarValue::UInt64(a)), Some(ScalarValue::UInt64(b))) => {- Some(ScalarValue::UInt64(*a.max(b)))- }- (Some(ScalarValue::Int8(a)), Some(ScalarValue::Int8(b))) => {- Some(ScalarValue::Int8(*a.max(b)))- }- (Some(ScalarValue::Int16(a)), Some(ScalarValue::Int16(b))) => {- Some(ScalarValue::Int16(*a.max(b)))- }- (Some(ScalarValue::Int32(a)), Some(ScalarValue::Int32(b))) => {- Some(ScalarValue::Int32(*a.max(b)))- }- (Some(ScalarValue::Int64(a)), Some(ScalarValue::Int64(b))) => {- Some(ScalarValue::Int64(*a.max(b)))- }- (Some(ScalarValue::Float32(a)), Some(ScalarValue::Float32(b))) => {- Some(ScalarValue::Float32(a.max(*b)))- }- (Some(ScalarValue::Float64(a)), Some(ScalarValue::Float64(b))) => {- Some(ScalarValue::Float64(a.max(*b)))- }- _ => {- return Err(ExecutionError::ExecutionError(- "unsupported data type for MAX".to_string(),- ));- }- }- }- Ok(())- }-- fn accumulate_batch(&mut self, array: ArrayRef) -> Result<()> {- let accumulated_value = array_max(array)?;-- self.accumulate_scalar(&accumulated_value)- }-- fn result(&self) -> Option<ScalarValue> {- self.value.clone()- }-- fn data_type(&self) -> &DataType {- &self.data_type- }-}--/// Implementation of SUM aggregate function-#[derive(Debug)]-struct SumFunction {- data_type: DataType,- value: Option<ScalarValue>,-}--impl SumFunction {- fn new(data_type: &DataType) -> Self {- Self {- data_type: data_type.clone(),- value: None,- }- }-}--impl AggregateFunction for SumFunction {- fn name(&self) -> &str {- "sum"- }-- fn accumulate_scalar(&mut self, value: &Option<ScalarValue>) -> Result<()> {- if self.value.is_none() {- self.value = value.clone();- } else if value.is_some() {- self.value = match (&self.value, value) {- (Some(ScalarValue::UInt8(a)), Some(ScalarValue::UInt8(b))) => {- Some(ScalarValue::UInt8(*a + b))- }- (Some(ScalarValue::UInt16(a)), Some(ScalarValue::UInt16(b))) => {- Some(ScalarValue::UInt16(*a + b))- }- (Some(ScalarValue::UInt32(a)), Some(ScalarValue::UInt32(b))) => {- Some(ScalarValue::UInt32(*a + b))- }- (Some(ScalarValue::UInt64(a)), Some(ScalarValue::UInt64(b))) => {- Some(ScalarValue::UInt64(*a + b))- }- (Some(ScalarValue::Int8(a)), Some(ScalarValue::Int8(b))) => {- Some(ScalarValue::Int8(*a + b))- }- (Some(ScalarValue::Int16(a)), Some(ScalarValue::Int16(b))) => {- Some(ScalarValue::Int16(*a + b))- }- (Some(ScalarValue::Int32(a)), Some(ScalarValue::Int32(b))) => {- Some(ScalarValue::Int32(*a + b))- }- (Some(ScalarValue::Int64(a)), Some(ScalarValue::Int64(b))) => {- Some(ScalarValue::Int64(*a + b))- }- (Some(ScalarValue::Float32(a)), Some(ScalarValue::Float32(b))) => {- Some(ScalarValue::Float32(a + *b))- }- (Some(ScalarValue::Float64(a)), Some(ScalarValue::Float64(b))) => {- Some(ScalarValue::Float64(a + *b))- }- _ => {- return Err(ExecutionError::ExecutionError(- "unsupported data type for SUM".to_string(),- ));- }- }- }- Ok(())- }-- fn accumulate_batch(&mut self, array: ArrayRef) -> Result<()> {- let accumulated_value = array_sum(array)?;-- self.accumulate_scalar(&accumulated_value)- }-- fn result(&self) -> Option<ScalarValue> {- self.value.clone()- }-- fn data_type(&self) -> &DataType {- &self.data_type- }-}--/// Implementation of AVG aggregate function-#[derive(Debug)]-struct AvgFunction {- data_type: DataType,- sum_value: SumFunction,- count_value: CountFunction,-}--impl AvgFunction {- fn new(data_type: &DataType) -> Self {- Self {- data_type: DataType::Float64,- sum_value: SumFunction::new(data_type),- count_value: CountFunction::new(),- }- }-}--impl AggregateFunction for AvgFunction {- fn name(&self) -> &str {- "avg"- }-- fn accumulate_scalar(&mut self, value: &Option<ScalarValue>) -> Result<()> {- self.sum_value.accumulate_scalar(value)?;- self.count_value.accumulate_scalar(value)?;-- Ok(())- }-- fn accumulate_batch(&mut self, array: ArrayRef) -> Result<()> {- self.sum_value.accumulate_batch(array.clone())?;- self.count_value.accumulate_batch(array)?;-- Ok(())- }-- fn result(&self) -> Option<ScalarValue> {- let sum = match self.sum_value.result() {- Some(ScalarValue::UInt8(a)) => a as f64,- Some(ScalarValue::UInt16(a)) => a as f64,- Some(ScalarValue::UInt32(a)) => a as f64,- Some(ScalarValue::UInt64(a)) => a as f64,- Some(ScalarValue::Int8(a)) => a as f64,- Some(ScalarValue::Int16(a)) => a as f64,- Some(ScalarValue::Int32(a)) => a as f64,- Some(ScalarValue::Int64(a)) => a as f64,- Some(ScalarValue::Float32(a)) => a as f64,- Some(ScalarValue::Float64(a)) => a as f64,- Some(ScalarValue::Null) => {- return Some(ScalarValue::Null);- }- _ => {- return None;- }- };- let count = match self.count_value.result() {- Some(ScalarValue::UInt64(a)) => a as f64,- Some(ScalarValue::Null) => {- return Some(ScalarValue::Null);- }- _ => {- return None;- }- };- Some(ScalarValue::Float64(sum / count))- }-- fn data_type(&self) -> &DataType {- &self.data_type- }-}--/// Implementation of COUNT aggregate function-#[derive(Debug)]-struct CountFunction {- value: Option<u64>,-}--impl CountFunction {- fn new() -> Self {- Self { value: None }- }-}--impl AggregateFunction for CountFunction {- fn name(&self) -> &str {- "count"- }-- fn accumulate_scalar(&mut self, value: &Option<ScalarValue>) -> Result<()> {- if value.is_some() {- self.value = match self.value {- Some(cur_value) => Some(cur_value + 1),- None => Some(1),- }- }-- Ok(())- }-- fn accumulate_batch(&mut self, array: ArrayRef) -> Result<()> {- let accumulated_value = array_count(array)?;-- if let Some(ScalarValue::UInt64(n)) = accumulated_value {- self.value = match self.value {- Some(cur_value) => Some(cur_value + n),- None => Some(n),- }- };-- Ok(())- }-- fn result(&self) -> Option<ScalarValue> {- match self.value {- Some(n) => Some(ScalarValue::UInt64(n)),- None => None,- }- }-- fn data_type(&self) -> &DataType {- &DataType::UInt64- }-}--struct AccumulatorSet {- aggr_values: Vec<Rc<RefCell<dyn AggregateFunction>>>,-}--impl AccumulatorSet {- fn accumulate_scalar(&mut self, i: usize, value: Option<ScalarValue>) -> Result<()> {- let mut accumulator = self.aggr_values[i].borrow_mut();- accumulator.accumulate_scalar(&value)- }-- fn accumulate_batch(&mut self, i: usize, array: ArrayRef) -> Result<()> {- let mut accumulator = self.aggr_values[i].borrow_mut();- accumulator.accumulate_batch(array)- }-- fn values(&self) -> Vec<Option<ScalarValue>> {- self.aggr_values- .iter()- .map(|x| x.borrow().result().clone())- .collect()- }-}--#[derive(Debug)]-struct MapEntry {- k: Vec<GroupByScalar>,- v: Vec<Option<ScalarValue>>,-}--/// Create an initial aggregate entry-fn create_accumulators(- aggr_expr: &Vec<CompiledAggregateExpression>,-) -> Result<AccumulatorSet> {- let aggr_values: Vec<Rc<RefCell<dyn AggregateFunction>>> = aggr_expr- .iter()- .map(|e| match e.aggr_type() {- AggregateType::Min => {- Ok(Rc::new(RefCell::new(MinFunction::new(e.data_type())))- as Rc<RefCell<dyn AggregateFunction>>)- }- AggregateType::Max => {- Ok(Rc::new(RefCell::new(MaxFunction::new(e.data_type())))- as Rc<RefCell<dyn AggregateFunction>>)- }- AggregateType::Sum => {- Ok(Rc::new(RefCell::new(SumFunction::new(e.data_type())))- as Rc<RefCell<dyn AggregateFunction>>)- }- AggregateType::Avg => {- Ok(Rc::new(RefCell::new(AvgFunction::new(e.data_type())))- as Rc<RefCell<dyn AggregateFunction>>)- }- AggregateType::Count => Ok(Rc::new(RefCell::new(CountFunction::new()))- as Rc<RefCell<dyn AggregateFunction>>),- _ => Err(ExecutionError::ExecutionError(- "unsupported aggregate function".to_string(),- )),- })- .collect::<Result<Vec<Rc<RefCell<_>>>>>()?;-- Ok(AccumulatorSet { aggr_values })-}--fn array_min(array: ArrayRef) -> Result<Option<ScalarValue>> {- 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(),- )),- }-}--fn array_max(array: ArrayRef) -> Result<Option<ScalarValue>> {- 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),- }- }- DataType::UInt16 => {- match compute::max(array.as_any().downcast_ref::<UInt16Array>().unwrap()) {- Some(n) => Ok(Some(ScalarValue::UInt16(n))),- None => Ok(None),- }- }- DataType::UInt32 => {- match compute::max(array.as_any().downcast_ref::<UInt32Array>().unwrap()) {- Some(n) => Ok(Some(ScalarValue::UInt32(n))),- None => Ok(None),- }- }- DataType::UInt64 => {- match compute::max(array.as_any().downcast_ref::<UInt64Array>().unwrap()) {- Some(n) => Ok(Some(ScalarValue::UInt64(n))),- None => Ok(None),- }- }- DataType::Int8 => {- match compute::max(array.as_any().downcast_ref::<Int8Array>().unwrap()) {- Some(n) => Ok(Some(ScalarValue::Int8(n))),- None => Ok(None),- }- }- DataType::Int16 => {- match compute::max(array.as_any().downcast_ref::<Int16Array>().unwrap()) {- Some(n) => Ok(Some(ScalarValue::Int16(n))),- None => Ok(None),- }- }- DataType::Int32 => {- match compute::max(array.as_any().downcast_ref::<Int32Array>().unwrap()) {- Some(n) => Ok(Some(ScalarValue::Int32(n))),- None => Ok(None),- }- }- DataType::Int64 => {- match compute::max(array.as_any().downcast_ref::<Int64Array>().unwrap()) {- Some(n) => Ok(Some(ScalarValue::Int64(n))),- None => Ok(None),- }- }- DataType::Float32 => {- match compute::max(array.as_any().downcast_ref::<Float32Array>().unwrap()) {- Some(n) => Ok(Some(ScalarValue::Float32(n))),- None => Ok(None),- }- }- DataType::Float64 => {- match compute::max(array.as_any().downcast_ref::<Float64Array>().unwrap()) {- Some(n) => Ok(Some(ScalarValue::Float64(n))),- None => Ok(None),- }- }- _ => Err(ExecutionError::ExecutionError(- "Unsupported data type for MAX".to_string(),- )),- }-}--fn array_sum(array: ArrayRef) -> Result<Option<ScalarValue>> {- 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(),- )),- }-}--fn array_count(array: ArrayRef) -> Result<Option<ScalarValue>> {- Ok(Some(ScalarValue::UInt64(- (array.len() - array.null_count()) as u64,- )))-}--fn update_accumulators(- batch: &RecordBatch,- row: usize,- accumulator_set: &mut AccumulatorSet,- aggr_expr: &Vec<CompiledAggregateExpression>,-) -> Result<()> {- // update the accumulators- for j in 0..accumulator_set.aggr_values.len() {- // evaluate the argument to the aggregate function- let array = aggr_expr[j].evaluate_arg(batch)?;-- let value: Option<ScalarValue> = match array.data_type() {- DataType::UInt8 => {- let z = array.as_any().downcast_ref::<UInt8Array>().unwrap();- Some(ScalarValue::UInt8(z.value(row)))- }- DataType::UInt16 => {- let z = array.as_any().downcast_ref::<UInt16Array>().unwrap();- Some(ScalarValue::UInt16(z.value(row)))- }- DataType::UInt32 => {- let z = array.as_any().downcast_ref::<UInt32Array>().unwrap();- Some(ScalarValue::UInt32(z.value(row)))- }- DataType::UInt64 => {- let z = array.as_any().downcast_ref::<UInt64Array>().unwrap();- Some(ScalarValue::UInt64(z.value(row)))- }- DataType::Int8 => {- let z = array.as_any().downcast_ref::<Int8Array>().unwrap();- Some(ScalarValue::Int8(z.value(row)))- }- DataType::Int16 => {- let z = array.as_any().downcast_ref::<Int16Array>().unwrap();- Some(ScalarValue::Int16(z.value(row)))- }- DataType::Int32 => {- let z = array.as_any().downcast_ref::<Int32Array>().unwrap();- Some(ScalarValue::Int32(z.value(row)))- }- DataType::Int64 => {- let z = array.as_any().downcast_ref::<Int64Array>().unwrap();- Some(ScalarValue::Int64(z.value(row)))- }- DataType::Float32 => {- let z = array.as_any().downcast_ref::<Float32Array>().unwrap();- Some(ScalarValue::Float32(z.value(row)))- }- DataType::Float64 => {- let z = array.as_any().downcast_ref::<Float64Array>().unwrap();- Some(ScalarValue::Float64(z.value(row)))- }- other => {- return Err(ExecutionError::ExecutionError(format!(- "Unsupported data type {:?} for result of aggregate expression",- other- )));- }- };-- accumulator_set.accumulate_scalar(j, value)?;- }- Ok(())-}--impl Relation for AggregateRelation {- fn next(&mut self) -> Result<Option<RecordBatch>> {- if self.end_of_results {- Ok(None)- } else {- self.end_of_results = true;- if self.group_expr.is_empty() {- self.without_group_by()- } else {- self.with_group_by()- }- }- }-- fn schema(&self) -> &Arc<Schema> {- &self.schema- }-}--macro_rules! array_from_scalar {- ($BUILDER:ident, $TY:ident, $ACCUM:expr) => {{- let mut b = $BUILDER::new(1);- let mut err = false;- match $ACCUM.result() {- Some(ScalarValue::$TY(n)) => {- b.append_value(n)?;- }- None => {- b.append_null()?;- }- Some(_) => {- err = true;- }- };- if err {- Err(ExecutionError::ExecutionError(- "unexpected type when creating array from scalar value".to_string(),- ))- } else {- Ok(Arc::new(b.finish()) as ArrayRef)- }- }};-}--/// Create array from `key` attribute in map entry (representing a grouping scalar value)-macro_rules! group_array_from_map_entries {- ($BUILDER:ident, $TY:ident, $ENTRIES:expr, $COL_INDEX:expr) => {{- let mut builder = $BUILDER::new($ENTRIES.len());- let mut err = false;- for j in 0..$ENTRIES.len() {- match $ENTRIES[j].k[$COL_INDEX] {- GroupByScalar::$TY(n) => builder.append_value(n).unwrap(),- _ => err = true,- }- }- if err {- Err(ExecutionError::ExecutionError(- "unexpected type when creating array from aggregate map".to_string(),- ))- } else {- Ok(Arc::new(builder.finish()) as ArrayRef)- }- }};-}--/// Create array from `value` attribute in map entry (representing an aggregate scalar-/// value)-macro_rules! aggr_array_from_map_entries {- ($BUILDER:ident, $TY:ident, $ENTRIES:expr, $COL_INDEX:expr) => {{- let mut builder = $BUILDER::new($ENTRIES.len());- let mut err = false;- for j in 0..$ENTRIES.len() {- match $ENTRIES[j].v[$COL_INDEX] {- Some(ScalarValue::$TY(n)) => builder.append_value(n).unwrap(),- None => builder.append_null().unwrap(),- _ => err = true,- }- }- if err {- Err(ExecutionError::ExecutionError(- "unexpected type when creating array from aggregate map".to_string(),- ))- } else {- Ok(Arc::new(builder.finish()) as ArrayRef)- }- }};-}--impl AggregateRelation {- /// perform simple aggregate on entire columns without grouping logic- fn without_group_by(&mut self) -> Result<Option<RecordBatch>> {- let aggr_expr_count = self.aggr_expr.len();- let mut accumulator_set = create_accumulators(&self.aggr_expr)?;-- while let Some(batch) = self.input.borrow_mut().next()? {- for i in 0..aggr_expr_count {- // evaluate the argument to the aggregate function- let array = self.aggr_expr[i].evaluate_arg(&batch)?;- match self.aggr_expr[i].aggr_type() {- AggregateType::Min => accumulator_set.accumulate_batch(i, array)?,- AggregateType::Max => accumulator_set.accumulate_batch(i, array)?,- AggregateType::Sum => accumulator_set.accumulate_batch(i, array)?,- AggregateType::Count => accumulator_set.accumulate_batch(i, array)?,- AggregateType::Avg => accumulator_set.accumulate_batch(i, array)?,- _ => {- return Err(ExecutionError::NotImplemented(- "Unsupported aggregate function".to_string(),- ));- }- }- }- }-- let mut result_columns: Vec<ArrayRef> = vec![];-- for i in 0..aggr_expr_count {- let accum = accumulator_set.aggr_values[i].borrow();- match accum.data_type() {- DataType::UInt8 => {- result_columns.push(array_from_scalar!(UInt8Builder, UInt8, accum)?)- }- DataType::UInt16 => {- result_columns.push(array_from_scalar!(UInt16Builder, UInt16, accum)?)- }- DataType::UInt32 => {- result_columns.push(array_from_scalar!(UInt32Builder, UInt32, accum)?)- }- DataType::UInt64 => {- result_columns.push(array_from_scalar!(UInt64Builder, UInt64, accum)?)- }- DataType::Int8 => {- result_columns.push(array_from_scalar!(Int8Builder, Int8, accum)?)- }- DataType::Int16 => {- result_columns.push(array_from_scalar!(Int16Builder, Int16, accum)?)- }- DataType::Int32 => {- result_columns.push(array_from_scalar!(Int32Builder, Int32, accum)?)- }- DataType::Int64 => {- result_columns.push(array_from_scalar!(Int64Builder, Int64, accum)?)- }- DataType::Float32 => result_columns.push(array_from_scalar!(- Float32Builder,- Float32,- accum- )?),- DataType::Float64 => result_columns.push(array_from_scalar!(- Float64Builder,- Float64,- accum- )?),- _ => return Err(ExecutionError::NotImplemented("tbd".to_string())),- }- }-- Ok(Some(RecordBatch::try_new(- self.schema.clone(),- result_columns,- )?))- }-- fn with_group_by(&mut self) -> Result<Option<RecordBatch>> {- //NOTE this whole method is currently very inefficient with too many per-row- // operations involving pattern matching and downcasting ... I'm sure this- // can be re-implemented in a much more efficient way that takes better- // advantage of Arrow-- // create map to store aggregate results- let mut map: FnvHashMap<Vec<GroupByScalar>, Rc<RefCell<AccumulatorSet>>> =- FnvHashMap::default();-- while let Some(batch) = self.input.borrow_mut().next()? {- // evaulate the group by expressions on this batch- let group_by_keys: Vec<ArrayRef> = self- .group_expr- .iter()- .map(|e| e.invoke(&batch))- .collect::<Result<Vec<ArrayRef>>>()?;-- // iterate over each row in the batch- for row in 0..batch.num_rows() {- // create key- let key: Vec<GroupByScalar> = group_by_keys- .iter()- .map(|col| match col.data_type() {- DataType::UInt8 => {- let array =- col.as_any().downcast_ref::<UInt8Array>().unwrap();- Ok(GroupByScalar::UInt8(array.value(row)))- }- DataType::UInt16 => {- let array =- col.as_any().downcast_ref::<UInt16Array>().unwrap();- Ok(GroupByScalar::UInt16(array.value(row)))- }- DataType::UInt32 => {- let array =- col.as_any().downcast_ref::<UInt32Array>().unwrap();- Ok(GroupByScalar::UInt32(array.value(row)))- }- DataType::UInt64 => {- let array =- col.as_any().downcast_ref::<UInt64Array>().unwrap();- Ok(GroupByScalar::UInt64(array.value(row)))- }- DataType::Int8 => {- let array = col.as_any().downcast_ref::<Int8Array>().unwrap();- Ok(GroupByScalar::Int8(array.value(row)))- }- DataType::Int16 => {- let array =- col.as_any().downcast_ref::<Int16Array>().unwrap();- Ok(GroupByScalar::Int16(array.value(row)))- }- DataType::Int32 => {- let array =- col.as_any().downcast_ref::<Int32Array>().unwrap();- Ok(GroupByScalar::Int32(array.value(row)))- }- DataType::Int64 => {- let array =- col.as_any().downcast_ref::<Int64Array>().unwrap();- Ok(GroupByScalar::Int64(array.value(row)))- }- DataType::Utf8 => {- let array =- col.as_any().downcast_ref::<BinaryArray>().unwrap();- Ok(GroupByScalar::Utf8(String::from(- str::from_utf8(array.value(row)).unwrap(),- )))- }- _ => Err(ExecutionError::ExecutionError(- "Unsupported GROUP BY data type".to_string(),- )),- })- .collect::<Result<Vec<GroupByScalar>>>()?;-- //TODO: find more elegant way to write this instead of hacking around- // ownership issues-- let updated = match map.get(&key) {- Some(entry) => {- let mut accumulator_set = entry.borrow_mut();- update_accumulators(- &batch,- row,- &mut accumulator_set,- &self.aggr_expr,- )?;- true- }- None => false,- };-- if !updated {- let accumulator_set =- Rc::new(RefCell::new(create_accumulators(&self.aggr_expr)?));- {- let mut entry_mut = accumulator_set.borrow_mut();- update_accumulators(- &batch,- row,- &mut entry_mut,- &self.aggr_expr,- )?;- }- map.insert(key.clone(), accumulator_set);- }- }- }-- // convert the map to a vec to make it easier to build arrays- let entries: Vec<MapEntry> = map- .iter()- .map(|(k, v)| {- let x = v.borrow();- MapEntry {- k: k.clone(),- v: x.values(),- }- })- .collect();-- // build the result arrays- let mut result_arrays: Vec<ArrayRef> =- Vec::with_capacity(self.group_expr.len() + self.aggr_expr.len());-- // grouping values- for i in 0..self.group_expr.len() {- let array: Result<ArrayRef> = match self.group_expr[i].data_type() {- DataType::UInt8 => {- group_array_from_map_entries!(UInt8Builder, UInt8, entries, i)- }- DataType::UInt16 => {- group_array_from_map_entries!(UInt16Builder, UInt16, entries, i)- }- DataType::UInt32 => {- group_array_from_map_entries!(UInt32Builder, UInt32, entries, i)- }- DataType::UInt64 => {- group_array_from_map_entries!(UInt64Builder, UInt64, entries, i)- }- DataType::Int8 => {- group_array_from_map_entries!(Int8Builder, Int8, entries, i)- }- DataType::Int16 => {- group_array_from_map_entries!(Int16Builder, Int16, entries, i)- }- DataType::Int32 => {- group_array_from_map_entries!(Int32Builder, Int32, entries, i)- }- DataType::Int64 => {- group_array_from_map_entries!(Int64Builder, Int64, entries, i)- }- DataType::Utf8 => {- let mut builder = BinaryBuilder::new(1);- for j in 0..entries.len() {- match &entries[j].k[i] {- GroupByScalar::Utf8(s) => builder.append_string(&s).unwrap(),- _ => {}- }- }- Ok(Arc::new(builder.finish()) as ArrayRef)- }- _ => Err(ExecutionError::ExecutionError(- "Unsupported group by expr".to_string(),- )),- };- result_arrays.push(array?);- }-- // aggregate values- for i in 0..self.aggr_expr.len() {- let array = match self.aggr_expr[i].data_type() {- DataType::UInt8 => {- aggr_array_from_map_entries!(UInt8Builder, UInt8, entries, i)- }- DataType::UInt16 => {- aggr_array_from_map_entries!(UInt16Builder, UInt16, entries, i)- }- DataType::UInt32 => {- aggr_array_from_map_entries!(UInt32Builder, UInt32, entries, i)- }- DataType::UInt64 => {- aggr_array_from_map_entries!(UInt64Builder, UInt64, entries, i)- }- DataType::Int8 => {- group_array_from_map_entries!(Int8Builder, Int8, entries, i)- }- DataType::Int16 => {- aggr_array_from_map_entries!(Int16Builder, Int16, entries, i)- }- DataType::Int32 => {- aggr_array_from_map_entries!(Int32Builder, Int32, entries, i)- }- DataType::Int64 => {- aggr_array_from_map_entries!(Int64Builder, Int64, entries, i)- }- DataType::Float32 => {- aggr_array_from_map_entries!(Float32Builder, Float32, entries, i)- }- DataType::Float64 => {- aggr_array_from_map_entries!(Float64Builder, Float64, entries, i)- }- _ => Err(ExecutionError::ExecutionError(- "Unsupported aggregate expr".to_string(),- )),- };- result_arrays.push(array?);- }-- Ok(Some(RecordBatch::try_new(- self.schema.clone(),- result_arrays,- )?))- }-}--#[cfg(test)]-mod tests {- use super::*;- use crate::datasource::CsvBatchIterator;- use crate::execution::context::ExecutionContext;- use crate::execution::expression;- use crate::execution::relation::DataSourceRelation;- use crate::logicalplan::Expr;- use crate::test;- use arrow::datatypes::{DataType, Field, Schema};- use std::sync::Mutex;-- #[test]- fn min_f64_group_by_string() {- let schema = test::aggr_test_schema();- let testdata = test::arrow_testdata_path();- let relation =- load_csv(&format!("{}/csv/aggregate_test_100.csv", testdata), &schema);- let context = ExecutionContext::new();-- let aggr_expr = vec![expression::compile_aggregate_expr(- &context,- &Expr::AggregateFunction {- name: String::from("min"),- args: vec![Expr::Column(11)],- return_type: DataType::Float64,- },- &schema,- )- .unwrap()];-- let aggr_schema = Arc::new(Schema::new(vec![Field::new(- "min_lat",- DataType::Float64,- false,- )]));-- let mut projection =- AggregateRelation::new(aggr_schema, relation, vec![], aggr_expr);- let batch = projection.next().unwrap().unwrap();- assert_eq!(1, batch.num_columns());- let min_lat = batch- .column(0)- .as_any()- .downcast_ref::<Float64Array>()- .unwrap();- assert_eq!(0.01479305307777301, min_lat.value(0));- }-- #[test]- fn count() {- let schema = test::aggr_test_schema();- let testdata = test::arrow_testdata_path();- let relation =- load_csv(&format!("{}/csv/aggregate_test_100.csv", testdata), &schema);- let context = ExecutionContext::new();-- let aggr_expr = vec![expression::compile_aggregate_expr(- &context,- &Expr::AggregateFunction {- name: String::from("count"),- args: vec![Expr::Column(11)],- return_type: DataType::UInt64,- },- &schema,- )- .unwrap()];-- let aggr_schema = Arc::new(Schema::new(vec![Field::new(- "count",- DataType::UInt64,- false,- )]));-- let mut projection =- AggregateRelation::new(aggr_schema, relation, vec![], aggr_expr);- let batch = projection.next().unwrap().unwrap();- assert_eq!(1, batch.num_columns());- let count = batch- .column(0)- .as_any()- .downcast_ref::<UInt64Array>()- .unwrap();- assert_eq!(100, count.value(0));- }-- #[test]- fn max_f64_group_by_string() {- let schema = test::aggr_test_schema();- let testdata = test::arrow_testdata_path();- let relation =- load_csv(&format!("{}/csv/aggregate_test_100.csv", testdata), &schema);- let context = ExecutionContext::new();-- let aggr_expr = vec![expression::compile_aggregate_expr(- &context,- &Expr::AggregateFunction {- name: String::from("max"),- args: vec![Expr::Column(11)],- return_type: DataType::Float64,- },- &schema,- )- .unwrap()];-- let aggr_schema = Arc::new(Schema::new(vec![Field::new(- "max_lat",- DataType::Float64,- false,- )]));-- let mut projection =- AggregateRelation::new(aggr_schema, relation, vec![], aggr_expr);- let batch = projection.next().unwrap().unwrap();- assert_eq!(1, batch.num_columns());- let max_lat = batch- .column(0)- .as_any()- .downcast_ref::<Float64Array>()- .unwrap();- assert_eq!(0.9965400387585364, max_lat.value(0));- }-- #[test]- fn test_min_max_sum_count_avg_f64_group_by_uint32() {- let schema = test::aggr_test_schema();- let testdata = test::arrow_testdata_path();- let relation =- load_csv(&format!("{}/csv/aggregate_test_100.csv", testdata), &schema);-- let context = ExecutionContext::new();-- let group_by_expr =- expression::compile_expr(&context, &Expr::Column(1), &schema).unwrap();-- let min_expr = expression::compile_aggregate_expr(- &context,- &Expr::AggregateFunction {- name: String::from("min"),- args: vec![Expr::Column(11)],- return_type: DataType::Float64,- },- &schema,- )- .unwrap();-- let max_expr = expression::compile_aggregate_expr(- &context,- &Expr::AggregateFunction {- name: String::from("max"),- args: vec![Expr::Column(11)],- return_type: DataType::Float64,- },- &schema,- )- .unwrap();-- let sum_expr = expression::compile_aggregate_expr(- &context,- &Expr::AggregateFunction {- name: String::from("sum"),- args: vec![Expr::Column(11)],- return_type: DataType::Float64,- },- &schema,- )- .unwrap();-- let count_expr = expression::compile_aggregate_expr(- &context,- &Expr::AggregateFunction {- name: String::from("count"),- args: vec![Expr::Column(11)],- return_type: DataType::UInt64,- },- &schema,- )- .unwrap();-- let avg_expr = expression::compile_aggregate_expr(- &context,- &Expr::AggregateFunction {- name: String::from("avg"),- args: vec![Expr::Column(11)],- return_type: DataType::Float64,- },- &schema,- )- .unwrap();-- let aggr_schema = Arc::new(Schema::new(vec![- Field::new("c2", DataType::UInt32, false),- Field::new("min", DataType::Float64, false),- Field::new("max", DataType::Float64, false),- Field::new("sum", DataType::Float64, false),- Field::new("count", DataType::UInt64, false),- Field::new("avg", DataType::Float64, false),- ]));-- let mut projection = AggregateRelation::new(- aggr_schema,- relation,- vec![group_by_expr],- vec![min_expr, max_expr, sum_expr, count_expr, avg_expr],- );- let batch = projection.next().unwrap().unwrap();- assert_eq!(6, batch.num_columns());- assert_eq!(5, batch.num_rows());-- let a = batch- .column(0)- .as_any()- .downcast_ref::<UInt32Array>()- .unwrap();- let min = batch- .column(1)- .as_any()- .downcast_ref::<Float64Array>()- .unwrap();- let max = batch- .column(2)- .as_any()- .downcast_ref::<Float64Array>()- .unwrap();- let sum = batch- .column(3)- .as_any()- .downcast_ref::<Float64Array>()- .unwrap();- let count = batch- .column(4)- .as_any()- .downcast_ref::<UInt64Array>()- .unwrap();- let avg = batch- .column(5)- .as_any()- .downcast_ref::<Float64Array>()- .unwrap();-- assert_eq!(4, a.value(0));- assert_eq!(0.02182578039211991, min.value(0));- assert_eq!(0.9237877978193884, max.value(0));- assert_eq!(9.253864188402662, sum.value(0));- assert_eq!(23, count.value(0));- assert_eq!(0.40234192123489837, avg.value(0));-- assert_eq!(5, a.value(1));- assert_eq!(0.01479305307777301, min.value(1));- assert_eq!(0.9723580396501548, max.value(1));- assert_eq!(6.037181692266781, sum.value(1));- assert_eq!(14, count.value(1));- assert_eq!(0.4312272637333415, avg.value(1));-- assert_eq!(2, a.value(2));- assert_eq!(0.16301110515739792, min.value(2));- assert_eq!(0.991517828651004, max.value(2));- assert_eq!(14.400412325480858, sum.value(2));- assert_eq!(22, count.value(2));- assert_eq!(0.6545641966127662, avg.value(2));-- assert_eq!(3, a.value(3));- assert_eq!(0.047343434291126085, min.value(3));- assert_eq!(0.9293883502480845, max.value(3));- assert_eq!(9.966125219358322, sum.value(3));- assert_eq!(19, count.value(3));- assert_eq!(0.5245329062820169, avg.value(3));-- assert_eq!(1, a.value(4));- assert_eq!(0.05636955101974106, min.value(4));- assert_eq!(0.9965400387585364, max.value(4));- assert_eq!(11.239667565763519, sum.value(4));- assert_eq!(22, count.value(4));- assert_eq!(0.5108939802619781, avg.value(4));- }-- fn load_csv(filename: &str, schema: &Arc<Schema>) -> Rc<RefCell<dyn Relation>> {- let ds =- CsvBatchIterator::try_new(filename, schema.clone(), true, &None, 10).unwrap();- Rc::new(RefCell::new(DataSourceRelation::new(Arc::new(Mutex::new(- ds,- )))))- }-}diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex 1f7b2397ab..92a03b60bb 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -25,16 +25,11 @@ use std::sync::Arc;use arrow::datatypes::*;-use crate::arrow::array::{ArrayRef, BooleanBuilder};use crate::arrow::record_batch::RecordBatch;use crate::datasource::csv::CsvFile;use crate::datasource::parquet::ParquetTable;use crate::datasource::TableProvider;use crate::error::{ExecutionError, Result};-use crate::execution::aggregate::AggregateRelation;-use crate::execution::expression::*;-use crate::execution::filter::FilterRelation;-use crate::execution::limit::LimitRelation;use crate::execution::physical_plan::common;use crate::execution::physical_plan::datasource::DatasourceExec;use crate::execution::physical_plan::expressions::{@@ -46,17 +41,12 @@ use crate::execution::physical_plan::merge::MergeExec;use crate::execution::physical_plan::projection::ProjectionExec;use crate::execution::physical_plan::selection::SelectionExec;use crate::execution::physical_plan::{AggregateExpr, ExecutionPlan, PhysicalExpr};-use crate::execution::projection::ProjectRelation;-use crate::execution::relation::{DataSourceRelation, Relation};-use crate::execution::scalar_relation::ScalarRelation;use crate::execution::table_impl::TableImpl;use crate::logicalplan::*;use crate::optimizer::optimizer::OptimizerRule;use crate::optimizer::projection_push_down::ProjectionPushDown;use crate::optimizer::type_coercion::TypeCoercionRule;-use crate::optimizer::utils;-use crate::sql::parser::FileType;-use crate::sql::parser::{DFASTNode, DFParser};+use crate::sql::parser::{DFASTNode, DFParser, FileType};use crate::sql::planner::{SchemaProvider, SqlToRel};use crate::table::Table;use sqlparser::sqlast::{SQLColumnDef, SQLType};@@ -76,14 +66,33 @@ impl ExecutionContext {/// Execute a SQL query and produce a Relation (a schema-aware iterator over a series/// of RecordBatch instances)- pub fn sql(- &mut self,- sql: &str,- batch_size: usize,- ) -> Result<Rc<RefCell<dyn Relation>>> {+ pub fn sql(&mut self, sql: &str, batch_size: usize) -> Result<Vec<RecordBatch>> {let plan = self.create_logical_plan(sql)?;- let plan = self.optimize(&plan)?;- Ok(self.execute(&plan, batch_size)?)++ match plan.as_ref() {+ LogicalPlan::CreateExternalTable {+ ref schema,+ ref name,+ ref location,+ ref file_type,+ ref header_row,+ } => match file_type {+ FileType::CSV => {+ self.register_csv(name, location, schema, *header_row);+ Ok(vec![])+ }+ _ => Err(ExecutionError::ExecutionError(format!(+ "Unsupported file type {:?}.",+ file_type+ ))),+ },++ plan => {+ let plan = self.optimize(&plan)?;+ let plan = self.create_physical_plan(&plan, batch_size)?;+ Ok(self.collect(plan.as_ref())?)+ }+ }}/// Creates a logical plan@@ -420,182 +429,6 @@ impl ExecutionContext {}}}-- /// Execute a logical plan and produce a Relation (a schema-aware iterator over a- /// series of RecordBatch instances)- pub fn execute(- &mut self,- plan: &LogicalPlan,- batch_size: usize,- ) -> Result<Rc<RefCell<dyn Relation>>> {- match *plan {- LogicalPlan::TableScan {- ref table_name,- ref projection,- ..- } => match (*self.datasources).borrow().get(table_name) {- Some(provider) => {- let ds = provider.scan(projection, batch_size)?;- if ds.len() == 1 {- Ok(Rc::new(RefCell::new(DataSourceRelation::new(- ds[0].clone(),- ))))- } else {- Err(ExecutionError::General(- "Execution engine only supports single partition".to_string(),- ))- }- }- _ => Err(ExecutionError::General(format!(- "No table registered as '{}'",- table_name- ))),- },- LogicalPlan::Selection {- ref expr,- ref input,- } => {- let input_rel = self.execute(input, batch_size)?;- let input_schema = input_rel.as_ref().borrow().schema().clone();- let runtime_expr = compile_expr(&self, expr, &input_schema)?;- let rel = FilterRelation::new(input_rel, runtime_expr, input_schema);- Ok(Rc::new(RefCell::new(rel)))- }- LogicalPlan::Projection {- ref expr,- ref input,- ..- } => {- let input_rel = self.execute(input, batch_size)?;-- let input_schema = input_rel.as_ref().borrow().schema().clone();-- let project_columns: Vec<Field> =- utils::exprlist_to_fields(&expr, &input_schema)?;-- let project_schema = Arc::new(Schema::new(project_columns));-- let compiled_expr: Result<Vec<CompiledExpr>> = expr- .iter()- .map(|e| compile_expr(&self, e, &input_schema))- .collect();-- let rel = ProjectRelation::new(input_rel, compiled_expr?, project_schema);-- Ok(Rc::new(RefCell::new(rel)))- }- LogicalPlan::Aggregate {- ref input,- ref group_expr,- ref aggr_expr,- ..- } => {- let input_rel = self.execute(&input, batch_size)?;-- let input_schema = input_rel.as_ref().borrow().schema().clone();-- let compiled_group_expr_result: Result<Vec<CompiledExpr>> = group_expr- .iter()- .map(|e| compile_expr(&self, e, &input_schema))- .collect();- let compiled_group_expr = compiled_group_expr_result?;-- let compiled_aggr_expr_result: Result<Vec<CompiledAggregateExpression>> =- aggr_expr- .iter()- .map(|e| compile_aggregate_expr(&self, e, &input_schema))- .collect();- let compiled_aggr_expr = compiled_aggr_expr_result?;-- let mut output_fields: Vec<Field> = vec![];- for expr in group_expr {- output_fields- .push(utils::expr_to_field(expr, input_schema.as_ref())?);- }- for expr in aggr_expr {- output_fields- .push(utils::expr_to_field(expr, input_schema.as_ref())?);- }- let rel = AggregateRelation::new(- Arc::new(Schema::new(output_fields)),- input_rel,- compiled_group_expr,- compiled_aggr_expr,- );-- Ok(Rc::new(RefCell::new(rel)))- }- LogicalPlan::Limit {- ref expr,- ref input,- ..- } => {- let input_rel = self.execute(input, batch_size)?;-- let input_schema = input_rel.as_ref().borrow().schema().clone();-- match expr {- &Expr::Literal(ref scalar_value) => {- let limit: usize = match scalar_value {- ScalarValue::Int8(x) => Ok(*x as usize),- ScalarValue::Int16(x) => Ok(*x as usize),- ScalarValue::Int32(x) => Ok(*x as usize),- ScalarValue::Int64(x) => Ok(*x as usize),- ScalarValue::UInt8(x) => Ok(*x as usize),- ScalarValue::UInt16(x) => Ok(*x as usize),- ScalarValue::UInt32(x) => Ok(*x as usize),- ScalarValue::UInt64(x) => Ok(*x as usize),- _ => Err(ExecutionError::ExecutionError(- "Limit only support positive integer literals"- .to_string(),- )),- }?;- let rel = LimitRelation::new(input_rel, limit, input_schema);- Ok(Rc::new(RefCell::new(rel)))- }- _ => Err(ExecutionError::ExecutionError(- "Limit only support positive integer literals".to_string(),- )),- }- }-- LogicalPlan::CreateExternalTable {- ref schema,- ref name,- ref location,- ref file_type,- ref header_row,- } => {- match file_type {- FileType::CSV => {- self.register_csv(name, location, schema, *header_row)- }- _ => {- return Err(ExecutionError::ExecutionError(format!(- "Unsupported file type {:?}.",- file_type- )));- }- }- let mut builder = BooleanBuilder::new(1);- builder.append_value(true)?;-- let columns = vec![Arc::new(builder.finish()) as ArrayRef];- Ok(Rc::new(RefCell::new(ScalarRelation::new(- Arc::new(Schema::new(vec![Field::new(- "result",- DataType::Boolean,- false,- )])),- columns,- ))))- }-- _ => Err(ExecutionError::NotImplemented(- "Unsupported logical plan for execution".to_string(),- )),- }- }}struct ExecutionContextSchemaProvider {diff --git a/rust/datafusion/src/execution/expression.rs b/rust/datafusion/src/execution/expression.rsdeleted file mode 100644index 8b182b7035..0000000000--- a/rust/datafusion/src/execution/expression.rs+++ /dev/null@@ -1,451 +0,0 @@-// Licensed to the Apache Software Foundation (ASF) under one-// or more contributor license agreements. See the NOTICE file-// distributed with this work for additional information-// regarding copyright ownership. The ASF licenses this file-// to you under the Apache License, Version 2.0 (the-// "License"); you may not use this file except in compliance-// with the License. You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing,-// software distributed under the License is distributed on an-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY-// KIND, either express or implied. See the License for the-// specific language governing permissions and limitations-// under the License.--//! Evaluation of expressions against RecordBatch instances.--use std::rc::Rc;-use std::sync::Arc;--use arrow::array::*;-use arrow::compute;-use arrow::datatypes::{DataType, Schema};-use arrow::record_batch::RecordBatch;--use crate::error::{ExecutionError, Result};-use crate::execution::context::ExecutionContext;-use crate::logicalplan::{Expr, Operator, ScalarValue};--/// Function that accepts a RecordBatch and returns an ArrayRef-pub type ArrayFunction = Rc<dyn Fn(&RecordBatch) -> Result<ArrayRef>>;--/// Function that accepts an ArrayRef and returns an ArrayRef-pub type CompiledCastFunction = Rc<dyn Fn(&ArrayRef) -> Result<ArrayRef>>;--/// Enumeration of supported aggregate functions-#[allow(missing_docs)] // seems like these variants are self-evident-pub enum AggregateType {- Min,- Max,- Sum,- Count,- CountDistinct,- Avg,-}--/// Compiled expression that can be invoked against a RecordBatch to produce an Array-pub(super) struct CompiledExpr {- name: String,- f: ArrayFunction,- t: DataType,-}--impl CompiledExpr {- /// get the name of the expression- pub fn name(&self) -> &str {- &self.name- }-- /// Get the data type of the expression- pub fn data_type(&self) -> &DataType {- &self.t- }-- /// invoke the compiled expression- pub fn invoke(&self, batch: &RecordBatch) -> Result<ArrayRef> {- (self.f)(batch)- }-}--/// Compiled aggregate expression-pub(super) struct CompiledAggregateExpression {- /// Aggregate type- aggr_type: AggregateType,- /// Arguments to the aggregate expression- args: Vec<CompiledExpr>,- /// Return type of aggregate expression- t: DataType,-}--impl CompiledAggregateExpression {- /// get the aggregate type (Min, Max, Count, etc)- pub fn aggr_type(&self) -> &AggregateType {- &self.aggr_type- }-- /// Get the data type of the expression- pub fn data_type(&self) -> &DataType {- &self.t- }-- /// invoke the compiled expression for the input to the aggregate function- pub fn evaluate_arg(&self, batch: &RecordBatch) -> Result<ArrayRef> {- self.args[0].invoke(batch)- }-}--/// Compiles an aggregate expression into a closure-pub(super) fn compile_aggregate_expr(- ctx: &ExecutionContext,- expr: &Expr,- input_schema: &Schema,-) -> Result<CompiledAggregateExpression> {- match *expr {- Expr::AggregateFunction {- ref name,- ref args,- ref return_type,- } => {- assert_eq!(1, args.len());-- let compiled_args: Vec<CompiledExpr> = args- .iter()- .map(|e| compile_expr(&ctx, e, input_schema))- .collect::<Result<Vec<_>>>()?;-- let func = match name.to_lowercase().as_ref() {- "min" => Ok(AggregateType::Min),- "max" => Ok(AggregateType::Max),- "count" => Ok(AggregateType::Count),- "sum" => Ok(AggregateType::Sum),- "avg" => Ok(AggregateType::Avg),- _ => Err(ExecutionError::General(format!(- "Unsupported aggregate function '{}'",- name- ))),- };-- Ok(CompiledAggregateExpression {- args: compiled_args,- t: return_type.clone(),- aggr_type: func?,- })- }- _ => panic!(),- }-}--macro_rules! binary_op {- ($LEFT:expr, $RIGHT:expr, $OP:ident, $DT:ident) => {{- let ll = $LEFT.as_any().downcast_ref::<$DT>().unwrap();- let rr = $RIGHT.as_any().downcast_ref::<$DT>().unwrap();- Ok(Arc::new(compute::$OP(&ll, &rr)?))- }};-}--macro_rules! math_ops {- ($LEFT:expr, $RIGHT:expr, $BATCH:expr, $OP:ident) => {{- let left_values = $LEFT.invoke($BATCH)?;- let right_values = $RIGHT.invoke($BATCH)?;- match (left_values.data_type(), right_values.data_type()) {- (DataType::Int8, DataType::Int8) => {- binary_op!(left_values, right_values, $OP, Int8Array)- }- (DataType::Int16, DataType::Int16) => {- binary_op!(left_values, right_values, $OP, Int16Array)- }- (DataType::Int32, DataType::Int32) => {- binary_op!(left_values, right_values, $OP, Int32Array)- }- (DataType::Int64, DataType::Int64) => {- binary_op!(left_values, right_values, $OP, Int64Array)- }- (DataType::UInt8, DataType::UInt8) => {- binary_op!(left_values, right_values, $OP, UInt8Array)- }- (DataType::UInt16, DataType::UInt16) => {- binary_op!(left_values, right_values, $OP, UInt16Array)- }- (DataType::UInt32, DataType::UInt32) => {- binary_op!(left_values, right_values, $OP, UInt32Array)- }- (DataType::UInt64, DataType::UInt64) => {- binary_op!(left_values, right_values, $OP, UInt64Array)- }- (DataType::Float32, DataType::Float32) => {- binary_op!(left_values, right_values, $OP, Float32Array)- }- (DataType::Float64, DataType::Float64) => {- binary_op!(left_values, right_values, $OP, Float64Array)- }- (l, r) => Err(ExecutionError::ExecutionError(format!(- "Cannot perform math operation on {:?} and {:?}",- l, r- ))),- }- }};-}--macro_rules! comparison_ops {- ($LEFT:expr, $RIGHT:expr, $BATCH:expr, $OP:ident) => {{- let left_values = $LEFT.invoke($BATCH)?;- let right_values = $RIGHT.invoke($BATCH)?;- match (left_values.data_type(), right_values.data_type()) {- (DataType::Int8, DataType::Int8) => {- binary_op!(left_values, right_values, $OP, Int8Array)- }- (DataType::Int16, DataType::Int16) => {- binary_op!(left_values, right_values, $OP, Int16Array)- }- (DataType::Int32, DataType::Int32) => {- binary_op!(left_values, right_values, $OP, Int32Array)- }- (DataType::Int64, DataType::Int64) => {- binary_op!(left_values, right_values, $OP, Int64Array)- }- (DataType::UInt8, DataType::UInt8) => {- binary_op!(left_values, right_values, $OP, UInt8Array)- }- (DataType::UInt16, DataType::UInt16) => {- binary_op!(left_values, right_values, $OP, UInt16Array)- }- (DataType::UInt32, DataType::UInt32) => {- binary_op!(left_values, right_values, $OP, UInt32Array)- }- (DataType::UInt64, DataType::UInt64) => {- binary_op!(left_values, right_values, $OP, UInt64Array)- }- (DataType::Float32, DataType::Float32) => {- binary_op!(left_values, right_values, $OP, Float32Array)- }- (DataType::Float64, DataType::Float64) => {- binary_op!(left_values, right_values, $OP, Float64Array)- }- (l, r) => Err(ExecutionError::ExecutionError(format!(- "Cannot compare {:?} with {:?}",- l, r- ))),- }- }};-}--macro_rules! boolean_ops {- ($LEFT:expr, $RIGHT:expr, $BATCH:expr, $OP:ident) => {{- let left_values = $LEFT.invoke($BATCH)?;- let right_values = $RIGHT.invoke($BATCH)?;- Ok(Arc::new(compute::$OP(- left_values.as_any().downcast_ref::<BooleanArray>().unwrap(),- right_values- .as_any()- .downcast_ref::<BooleanArray>()- .unwrap(),- )?))- }};-}--macro_rules! literal_array {- ($VALUE:expr, $ARRAY_TYPE:ident, $TY:ident) => {{- let nn = *$VALUE;- Ok(CompiledExpr {- name: format!("{}", nn),- f: Rc::new(move |batch: &RecordBatch| {- let capacity = batch.num_rows();- let mut builder = $ARRAY_TYPE::builder(capacity);- for _ in 0..capacity {- builder.append_value(nn)?;- }- let array = builder.finish();- Ok(Arc::new(array) as ArrayRef)- }),- t: DataType::$TY,- })- }};-}--/// Compiles a scalar expression into a closure-pub(super) fn compile_expr(- ctx: &ExecutionContext,- expr: &Expr,- input_schema: &Schema,-) -> Result<CompiledExpr> {- match expr {- &Expr::Literal(ref value) => match value {- //NOTE: this is a temporary hack .. due to the way expressions like 'a > 1'- // are evaluated, currently the left and right are evaluated- // separately and must result in arrays and then the '>' operator- // is evaluated against the two arrays. This works but is dumb ...- // I intend to optimize this soon to add special handling for- // binary expressions that involve literal values to avoid creating arrays of- // literals filed as https://github.com/andygrove/datafusion/issues/191- ScalarValue::Int8(n) => literal_array!(n, Int8Array, Int8),- ScalarValue::Int16(n) => literal_array!(n, Int16Array, Int16),- ScalarValue::Int32(n) => literal_array!(n, Int32Array, Int32),- ScalarValue::Int64(n) => literal_array!(n, Int64Array, Int64),- ScalarValue::UInt8(n) => literal_array!(n, UInt8Array, UInt8),- ScalarValue::UInt16(n) => literal_array!(n, UInt16Array, UInt16),- ScalarValue::UInt32(n) => literal_array!(n, UInt32Array, UInt32),- ScalarValue::UInt64(n) => literal_array!(n, UInt64Array, UInt64),- ScalarValue::Float32(n) => literal_array!(n, Float32Array, Float32),- ScalarValue::Float64(n) => literal_array!(n, Float64Array, Float64),- other => Err(ExecutionError::ExecutionError(format!(- "Unsupported literal type {:?}",- other- ))),- },- &Expr::Column(index) => {- if index < input_schema.fields().len() {- Ok(CompiledExpr {- name: input_schema.field(index).name().clone(),- f: Rc::new(move |batch: &RecordBatch| {- Ok((*batch.column(index)).clone())- }),- t: input_schema.field(index).data_type().clone(),- })- } else {- Err(ExecutionError::InvalidColumn(format!(- "Column index {} out of bounds",- index- )))- }- }- &Expr::Cast {- ref expr,- ref data_type,- } => match expr.as_ref() {- &Expr::Column(index) => {- let col = input_schema.field(index);- let dt = data_type.clone();- Ok(CompiledExpr {- name: col.name().clone(),- t: col.data_type().clone(),- f: Rc::new(move |batch: &RecordBatch| {- compute::cast(batch.column(index), &dt)- .map_err(|e| ExecutionError::ArrowError(e))- }),- })- }- other => {- let compiled_expr = compile_expr(ctx, other, input_schema)?;- let dt = data_type.clone();- Ok(CompiledExpr {- name: "CAST".to_string(),- t: data_type.clone(),- f: Rc::new(move |batch: &RecordBatch| {- // evaluate the expression- let array = compiled_expr.invoke(batch)?;- // cast the result- compute::cast(&array, &dt)- .map_err(|e| ExecutionError::ArrowError(e))- }),- })- }- },- &Expr::BinaryExpr {- ref left,- ref op,- ref right,- } => {- let left_expr = compile_expr(ctx, left, input_schema)?;- let right_expr = compile_expr(ctx, right, input_schema)?;- let name = format!("{:?} {:?} {:?}", left, op, right);- let op_type = left_expr.data_type().clone();- match op {- &Operator::Eq => Ok(CompiledExpr {- name,- f: Rc::new(move |batch: &RecordBatch| {- comparison_ops!(left_expr, right_expr, batch, eq)- }),- t: DataType::Boolean,- }),- &Operator::NotEq => Ok(CompiledExpr {- name,- f: Rc::new(move |batch: &RecordBatch| {- comparison_ops!(left_expr, right_expr, batch, neq)- }),- t: DataType::Boolean,- }),- &Operator::Lt => Ok(CompiledExpr {- name,- f: Rc::new(move |batch: &RecordBatch| {- comparison_ops!(left_expr, right_expr, batch, lt)- }),- t: DataType::Boolean,- }),- &Operator::LtEq => Ok(CompiledExpr {- name,- f: Rc::new(move |batch: &RecordBatch| {- comparison_ops!(left_expr, right_expr, batch, lt_eq)- }),- t: DataType::Boolean,- }),- &Operator::Gt => Ok(CompiledExpr {- name,- f: Rc::new(move |batch: &RecordBatch| {- comparison_ops!(left_expr, right_expr, batch, gt)- }),- t: DataType::Boolean,- }),- &Operator::GtEq => Ok(CompiledExpr {- name,- f: Rc::new(move |batch: &RecordBatch| {- comparison_ops!(left_expr, right_expr, batch, gt_eq)- }),- t: DataType::Boolean,- }),- &Operator::And => Ok(CompiledExpr {- name,- f: Rc::new(move |batch: &RecordBatch| {- boolean_ops!(left_expr, right_expr, batch, and)- }),- t: DataType::Boolean,- }),- &Operator::Or => Ok(CompiledExpr {- name,- f: Rc::new(move |batch: &RecordBatch| {- boolean_ops!(left_expr, right_expr, batch, or)- }),- t: DataType::Boolean,- }),- &Operator::Plus => Ok(CompiledExpr {- name,- f: Rc::new(move |batch: &RecordBatch| {- math_ops!(left_expr, right_expr, batch, add)- }),- t: op_type,- }),- &Operator::Minus => Ok(CompiledExpr {- name,- f: Rc::new(move |batch: &RecordBatch| {- math_ops!(left_expr, right_expr, batch, subtract)- }),- t: op_type,- }),- &Operator::Multiply => Ok(CompiledExpr {- name,- f: Rc::new(move |batch: &RecordBatch| {- math_ops!(left_expr, right_expr, batch, multiply)- }),- t: op_type,- }),- &Operator::Divide => Ok(CompiledExpr {- name,- f: Rc::new(move |batch: &RecordBatch| {- math_ops!(left_expr, right_expr, batch, divide)- }),- t: op_type,- }),- other => Err(ExecutionError::NotImplemented(format!(- "Unsupported operator: {:?}",- other- ))),- }- }- other => Err(ExecutionError::NotImplemented(format!(- "Unsupported expression {:?}",- other- ))),- }-}diff --git a/rust/datafusion/src/execution/filter.rs b/rust/datafusion/src/execution/filter.rsdeleted file mode 100644index f003517c22..0000000000--- a/rust/datafusion/src/execution/filter.rs+++ /dev/null@@ -1,98 +0,0 @@-// Licensed to the Apache Software Foundation (ASF) under one-// or more contributor license agreements. See the NOTICE file-// distributed with this work for additional information-// regarding copyright ownership. The ASF licenses this file-// to you under the Apache License, Version 2.0 (the-// "License"); you may not use this file except in compliance-// with the License. You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing,-// software distributed under the License is distributed on an-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY-// KIND, either express or implied. See the License for the-// specific language governing permissions and limitations-// under the License.--//! Execution of a filter (predicate) relation. The SQL clause `WHERE expr` represents a-//! filter.--use std::cell::RefCell;-use std::rc::Rc;-use std::sync::Arc;--use arrow::array::*;-use arrow::compute::array_ops::filter;-use arrow::datatypes::Schema;-use arrow::record_batch::RecordBatch;--use crate::error::{ExecutionError, Result};-use crate::execution::expression::CompiledExpr;-use crate::execution::relation::Relation;--/// Implementation of a filter relation-pub(super) struct FilterRelation {- /// The schema for the filter relation. This is always the same as the schema of the- /// input relation.- schema: Arc<Schema>,- /// Relation that is being filtered- input: Rc<RefCell<dyn Relation>>,- /// Filter expression- expr: CompiledExpr,-}--impl FilterRelation {- pub fn new(- input: Rc<RefCell<dyn Relation>>,- expr: CompiledExpr,- schema: Arc<Schema>,- ) -> Self {- Self {- schema,- input,- expr,- }- }-}--impl Relation for FilterRelation {- fn next(&mut self) -> Result<Option<RecordBatch>> {- match self.input.borrow_mut().next()? {- Some(batch) => {- // evaluate the filter expression against the batch- match self- .expr- .invoke(&batch)?- .as_any()- .downcast_ref::<BooleanArray>()- {- Some(filter_bools) => {- let filtered_columns: Result<Vec<ArrayRef>> = (0..batch- .num_columns())- .map(|i| {- match filter(batch.column(i).as_ref(), &filter_bools) {- Ok(result) => Ok(result),- Err(error) => Err(ExecutionError::from(error)),- }- })- .collect();-- let filtered_batch: RecordBatch =- RecordBatch::try_new(self.schema.clone(), filtered_columns?)?;-- Ok(Some(filtered_batch))- }- _ => Err(ExecutionError::ExecutionError(- "Filter expression did not evaluate to boolean".to_string(),- )),- }- }- None => Ok(None),- }- }-- fn schema(&self) -> &Arc<Schema> {- &self.schema- }-}diff --git a/rust/datafusion/src/execution/limit.rs b/rust/datafusion/src/execution/limit.rsdeleted file mode 100644index 84b3ae8f76..0000000000--- a/rust/datafusion/src/execution/limit.rs+++ /dev/null@@ -1,85 +0,0 @@-// Licensed to the Apache Software Foundation (ASF) under one-// or more contributor license agreements. See the NOTICE file-// distributed with this work for additional information-// regarding copyright ownership. The ASF licenses this file-// to you under the Apache License, Version 2.0 (the-// "License"); you may not use this file except in compliance-// with the License. You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing,-// software distributed under the License is distributed on an-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY-// KIND, either express or implied. See the License for the-// specific language governing permissions and limitations-// under the License.--//! Limit relation, to limit the number of rows returned by a relation--use std::cell::RefCell;-use std::rc::Rc;-use std::sync::Arc;--use arrow::datatypes::Schema;-use arrow::record_batch::RecordBatch;--use crate::error::Result;-use crate::execution::physical_plan::limit::truncate_batch;-use crate::execution::relation::Relation;--/// Implementation of a LIMIT relation-pub(super) struct LimitRelation {- /// The relation which the limit is being applied to- input: Rc<RefCell<dyn Relation>>,- /// The schema for the limit relation, which is always the same as the schema of the- /// input relation- schema: Arc<Schema>,- /// The number of rows returned by this relation- limit: usize,- /// The number of rows that have been returned so far- num_consumed_rows: usize,-}--impl LimitRelation {- pub fn new(- input: Rc<RefCell<dyn Relation>>,- limit: usize,- schema: Arc<Schema>,- ) -> Self {- Self {- input,- schema,- limit,- num_consumed_rows: 0,- }- }-}--impl Relation for LimitRelation {- fn next(&mut self) -> Result<Option<RecordBatch>> {- match self.input.borrow_mut().next()? {- Some(batch) => {- let capacity = self.limit - self.num_consumed_rows;-- if capacity <= 0 {- return Ok(None);- }-- if batch.num_rows() > capacity {- let limited_batch = truncate_batch(&batch, capacity)?;- self.num_consumed_rows += capacity;- Ok(Some(limited_batch))- } else {- self.num_consumed_rows += batch.num_rows();- Ok(Some(batch))- }- }- None => Ok(None),- }- }-- fn schema(&self) -> &Arc<Schema> {- &self.schema- }-}diff --git a/rust/datafusion/src/execution/mod.rs b/rust/datafusion/src/execution/mod.rsindex bd9ef91026..5a0e7525bf 100644--- a/rust/datafusion/src/execution/mod.rs+++ b/rust/datafusion/src/execution/mod.rs@@ -17,13 +17,6 @@//! DataFusion query execution-pub mod aggregate;pub mod context;-pub mod expression;-pub mod filter;-pub mod limit;pub mod physical_plan;-pub mod projection;-pub mod relation;-pub mod scalar_relation;pub mod table_impl;diff --git a/rust/datafusion/src/execution/projection.rs b/rust/datafusion/src/execution/projection.rsdeleted file mode 100644index cd4ea93a2c..0000000000--- a/rust/datafusion/src/execution/projection.rs+++ /dev/null@@ -1,144 +0,0 @@-// Licensed to the Apache Software Foundation (ASF) under one-// or more contributor license agreements. See the NOTICE file-// distributed with this work for additional information-// regarding copyright ownership. The ASF licenses this file-// to you under the Apache License, Version 2.0 (the-// "License"); you may not use this file except in compliance-// with the License. You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing,-// software distributed under the License is distributed on an-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY-// KIND, either express or implied. See the License for the-// specific language governing permissions and limitations-// under the License.--//! Defines the projection relation. A projection determines which columns or expressions-//! are returned from a query. The SQL statement `SELECT a, b, a+b FROM t1` is an example-//! of a projection on table `t1` where the expressions `a`, `b`, and `a+b` are the-//! projection expressions.--use std::cell::RefCell;-use std::rc::Rc;-use std::sync::Arc;--use arrow::array::ArrayRef;-use arrow::datatypes::{Field, Schema};-use arrow::record_batch::RecordBatch;--use crate::error::Result;-use crate::execution::expression::CompiledExpr;-use crate::execution::relation::Relation;--/// Projection relation-pub(super) struct ProjectRelation {- /// Schema for the result of the projection- schema: Arc<Schema>,- /// The relation that the projection is being applied to- input: Rc<RefCell<dyn Relation>>,- /// Projection expressions- expr: Vec<CompiledExpr>,-}--impl ProjectRelation {- pub fn new(- input: Rc<RefCell<dyn Relation>>,- expr: Vec<CompiledExpr>,- schema: Arc<Schema>,- ) -> Self {- ProjectRelation {- input,- expr,- schema,- }- }-}--impl Relation for ProjectRelation {- fn next(&mut self) -> Result<Option<RecordBatch>> {- match self.input.borrow_mut().next()? {- Some(batch) => {- let projected_columns: Result<Vec<ArrayRef>> =- self.expr.iter().map(|e| e.invoke(&batch)).collect();-- let schema = Schema::new(- self.expr- .iter()- .map(|e| Field::new(&e.name(), e.data_type().clone(), true))- .collect(),- );-- let projected_batch: RecordBatch =- RecordBatch::try_new(Arc::new(schema), projected_columns?)?;-- Ok(Some(projected_batch))- }- None => Ok(None),- }- }-- fn schema(&self) -> &Arc<Schema> {- &self.schema- }-}--#[cfg(test)]-mod tests {- use super::*;- use crate::datasource::CsvBatchIterator;- use crate::execution::context::ExecutionContext;- use crate::execution::expression;- use crate::execution::relation::DataSourceRelation;- use crate::logicalplan::Expr;- use crate::test;- use arrow::datatypes::{DataType, Field, Schema};- use std::sync::Mutex;-- #[test]- fn project_first_column() {- 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("c3", DataType::Int16, false),- Field::new("c4", DataType::Int32, false),- Field::new("c5", DataType::Int64, false),- Field::new("c6", DataType::UInt8, false),- Field::new("c7", DataType::UInt16, false),- Field::new("c8", DataType::UInt32, false),- Field::new("c9", DataType::UInt64, false),- Field::new("c10", DataType::Float32, false),- Field::new("c11", DataType::Float64, false),- Field::new("c12", DataType::Utf8, false),- ]));-- let testdata = test::arrow_testdata_path();-- let ds = CsvBatchIterator::try_new(- &format!("{}/csv/aggregate_test_100.csv", testdata),- schema.clone(),- true,- &None,- 1024,- )- .unwrap();- let relation = Rc::new(RefCell::new(DataSourceRelation::new(Arc::new(- Mutex::new(ds),- ))));- let context = ExecutionContext::new();-- let projection_expr =- vec![- expression::compile_expr(&context, &Expr::Column(0), schema.as_ref())- .unwrap(),- ];-- let mut projection = ProjectRelation::new(relation, projection_expr, schema);- let batch = projection.next().unwrap().unwrap();- assert_eq!(1, batch.num_columns());-- assert_eq!("c1", batch.schema().field(0).name());- }-}diff --git a/rust/datafusion/src/execution/relation.rs b/rust/datafusion/src/execution/relation.rsdeleted file mode 100644index 81ff138220..0000000000--- a/rust/datafusion/src/execution/relation.rs+++ /dev/null@@ -1,61 +0,0 @@-// Licensed to the Apache Software Foundation (ASF) under one-// or more contributor license agreements. See the NOTICE file-// distributed with this work for additional information-// regarding copyright ownership. The ASF licenses this file-// to you under the Apache License, Version 2.0 (the-// "License"); you may not use this file except in compliance-// with the License. You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing,-// software distributed under the License is distributed on an-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY-// KIND, either express or implied. See the License for the-// specific language governing permissions and limitations-// under the License.--//! A relation is a representation of a set of tuples. A database table is a-//! type of relation. During query execution, each operation on a relation (such as-//! projection, selection, aggregation) results in a new relation.--use std::sync::{Arc, Mutex};--use arrow::datatypes::Schema;-use arrow::record_batch::RecordBatch;--use crate::error::Result;-use crate::execution::physical_plan::BatchIterator;--/// trait for all relations (a relation is essentially just an iterator over batches-/// of data, with a known schema)-pub trait Relation {- /// Get the next `RecordBatch`, or `None` if the iterator is exhausted- fn next(&mut self) -> Result<Option<RecordBatch>>;-- /// get the schema for this relation- fn schema(&self) -> &Arc<Schema>;-}--/// Implementation of a relation that represents a DataFusion data source-pub(super) struct DataSourceRelation {- schema: Arc<Schema>,- ds: Arc<Mutex<dyn BatchIterator>>,-}--impl DataSourceRelation {- pub fn new(ds: Arc<Mutex<dyn BatchIterator>>) -> Self {- let schema = ds.lock().unwrap().schema().clone();- Self { ds, schema }- }-}--impl Relation for DataSourceRelation {- fn next(&mut self) -> Result<Option<RecordBatch>> {- self.ds.lock().unwrap().next()- }-- fn schema(&self) -> &Arc<Schema> {- &self.schema- }-}diff --git a/rust/datafusion/src/execution/scalar_relation.rs b/rust/datafusion/src/execution/scalar_relation.rsdeleted file mode 100644index 436a133dcb..0000000000--- a/rust/datafusion/src/execution/scalar_relation.rs+++ /dev/null@@ -1,66 +0,0 @@-// Licensed to the Apache Software Foundation (ASF) under one-// or more contributor license agreements. See the NOTICE file-// distributed with this work for additional information-// regarding copyright ownership. The ASF licenses this file-// to you under the Apache License, Version 2.0 (the-// "License"); you may not use this file except in compliance-// with the License. You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing,-// software distributed under the License is distributed on an-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY-// KIND, either express or implied. See the License for the-// specific language governing permissions and limitations-// under the License.--//! Scalar relation, emit one fixed scalar value.--use crate::error::Result;-use crate::execution::relation::Relation;-use arrow::array::ArrayRef;-use arrow::datatypes::Schema;-use arrow::record_batch::RecordBatch;-use std::sync::Arc;--/// A relation emit single scalar array;-pub(super) struct ScalarRelation {- /// The schema for the limit relation, which is always the same as the schema of the- /// input relation- schema: Arc<Schema>,-- value: Vec<ArrayRef>,-- /// The number of rows that have been returned so far- emitted: bool,-}--impl ScalarRelation {- pub fn new(schema: Arc<Schema>, value: Vec<ArrayRef>) -> Self {- Self {- schema,- value,- emitted: false,- }- }-}--impl Relation for ScalarRelation {- fn next(&mut self) -> Result<Option<RecordBatch>> {- if self.emitted {- return Ok(None);- }-- self.emitted = true;-- Ok(Some(RecordBatch::try_new(- self.schema().clone(),- self.value.clone(),- )?))- }-- fn schema(&self) -> &Arc<Schema> {- &self.schema- }-}diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex 2532194d5f..bb60603175 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -170,9 +170,9 @@ fn csv_query_avg_multi_batch() {let sql = "SELECT avg(c12) FROM aggregate_test_100";let plan = ctx.create_logical_plan(&sql).unwrap();let plan = ctx.optimize(&plan).unwrap();- let results = ctx.execute(&plan, 4).unwrap();- let mut relation = results.borrow_mut();- let batch = relation.next().unwrap().unwrap();+ let plan = ctx.create_physical_plan(&plan, DEFAULT_BATCH_SIZE).unwrap();+ let results = ctx.collect(plan.as_ref()).unwrap();+ let batch = &results[0];let column = batch.column(0);let array = column.as_any().downcast_ref::<Float64Array>().unwrap();let actual = array.value(0);