Apache DataFusion SQL Query Engine
ARROW-8197: [Rust] [DataFusion] Fix schema returned by physical plan
Andy Grovefd78ce891d2e
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex 6dfb3d2b19..3ea06480b7 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -35,7 +35,7 @@ use crate::error::{ExecutionError, Result};use crate::execution::physical_plan::common;use crate::execution::physical_plan::datasource::DatasourceExec;use crate::execution::physical_plan::expressions::{- Avg, BinaryExpr, CastExpr, Column, Count, Literal, Max, Min, Sum,+ Alias, Avg, BinaryExpr, CastExpr, Column, Count, Literal, Max, Min, Sum,};use crate::execution::physical_plan::hash_aggregate::HashAggregateExec;use crate::execution::physical_plan::limit::LimitExec;@@ -380,7 +380,13 @@ impl ExecutionContext {input_schema: &Schema,) -> Result<Arc<dyn PhysicalExpr>> {match e {- Expr::Column(i) => Ok(Arc::new(Column::new(*i))),+ Expr::Alias(expr, name) => {+ let expr = self.create_physical_expr(expr, input_schema)?;+ Ok(Arc::new(Alias::new(expr, &name)))+ }+ Expr::Column(i) => {+ Ok(Arc::new(Column::new(*i, &input_schema.field(*i).name())))+ }Expr::Literal(value) => Ok(Arc::new(Literal::new(value.clone()))),Expr::BinaryExpr { left, op, right } => Ok(Arc::new(BinaryExpr::new(self.create_physical_expr(left, input_schema)?,@@ -719,6 +725,38 @@ mod tests {Ok(())}+ #[test]+ fn aggregate_with_alias() -> Result<()> {+ let tmp_dir = TempDir::new("execute")?;+ let mut ctx = create_ctx(&tmp_dir, 1)?;++ let schema = Arc::new(Schema::new(vec![+ Field::new("c1", DataType::UInt32, false),+ Field::new("c2", DataType::UInt64, false),+ ]));++ let plan = LogicalPlanBuilder::scan(+ "default",+ "test",+ schema.as_ref(),+ Some(vec![0, 1]),+ )?+ .aggregate(+ vec![col(0)],+ vec![aggregate_expr("SUM", col(1), DataType::Int32)],+ )?+ .project(&vec![col(0), col(1).alias("total_salary")])?+ .build()?;++ let physical_plan = ctx.create_physical_plan(&Arc::new(plan), 1024)?;+ assert_eq!("c1", physical_plan.schema().field(0).name().as_str());+ assert_eq!(+ "total_salary",+ physical_plan.schema().field(1).name().as_str()+ );+ Ok(())+ }+#[test]fn write_csv_results() -> Result<()> {// create partitioned input file and contextdiff --git a/rust/datafusion/src/execution/physical_plan/expressions.rs b/rust/datafusion/src/execution/physical_plan/expressions.rsindex 32ce99ed90..9969eeddf1 100644--- a/rust/datafusion/src/execution/physical_plan/expressions.rs+++ b/rust/datafusion/src/execution/physical_plan/expressions.rs@@ -46,22 +46,56 @@ use arrow::compute::kernels::comparison::{use arrow::datatypes::{DataType, Schema, TimeUnit};use arrow::record_batch::RecordBatch;+/// Represents an aliased expression+pub struct Alias {+ expr: Arc<dyn PhysicalExpr>,+ alias: String,+}++impl Alias {+ /// Create a new aliased expression+ pub fn new(expr: Arc<dyn PhysicalExpr>, alias: &str) -> Self {+ Self {+ expr: expr.clone(),+ alias: alias.to_owned(),+ }+ }+}++impl PhysicalExpr for Alias {+ fn name(&self) -> String {+ self.alias.clone()+ }++ fn data_type(&self, input_schema: &Schema) -> Result<DataType> {+ self.expr.data_type(input_schema)+ }++ fn evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {+ self.expr.evaluate(batch)+ }+}+/// Represents the column at a given index in a RecordBatchpub struct Column {index: usize,+ name: String,}impl Column {/// Create a new column expression- pub fn new(index: usize) -> Self {- Self { index }+ pub fn new(index: usize, name: &str) -> Self {+ Self {+ index,+ name: name.to_owned(),+ }}}impl PhysicalExpr for Column {/// Get the name to use in a schema to represent the result of this expressionfn name(&self) -> String {- format!("c{}", self.index)+ self.name.clone()}/// Get the data type of this expression, given the schema of the input@@ -76,8 +110,8 @@ impl PhysicalExpr for Column {}/// Create a column expression-pub fn col(i: usize) -> Arc<dyn PhysicalExpr> {- Arc::new(Column::new(i))+pub fn col(i: usize, schema: &Schema) -> Arc<dyn PhysicalExpr> {+ Arc::new(Column::new(i, &schema.field(i).name()))}/// SUM aggregate expression@@ -123,7 +157,7 @@ impl AggregateExpr for Sum {}fn create_reducer(&self, column_index: usize) -> Arc<dyn AggregateExpr> {- Arc::new(Sum::new(Arc::new(Column::new(column_index))))+ Arc::new(Sum::new(Arc::new(Column::new(column_index, &self.name()))))}}@@ -324,7 +358,7 @@ impl AggregateExpr for Avg {}fn create_reducer(&self, column_index: usize) -> Arc<dyn AggregateExpr> {- Arc::new(Avg::new(Arc::new(Column::new(column_index))))+ Arc::new(Avg::new(Arc::new(Column::new(column_index, &self.name()))))}}@@ -437,7 +471,7 @@ impl AggregateExpr for Max {}fn create_reducer(&self, column_index: usize) -> Arc<dyn AggregateExpr> {- Arc::new(Max::new(Arc::new(Column::new(column_index))))+ Arc::new(Max::new(Arc::new(Column::new(column_index, &self.name()))))}}@@ -636,7 +670,7 @@ impl AggregateExpr for Min {}fn create_reducer(&self, column_index: usize) -> Arc<dyn AggregateExpr> {- Arc::new(Min::new(Arc::new(Column::new(column_index))))+ Arc::new(Min::new(Arc::new(Column::new(column_index, &self.name()))))}}@@ -823,7 +857,7 @@ impl AggregateExpr for Count {}fn create_reducer(&self, column_index: usize) -> Arc<dyn AggregateExpr> {- Arc::new(Sum::new(Arc::new(Column::new(column_index))))+ Arc::new(Sum::new(Arc::new(Column::new(column_index, &self.name()))))}}@@ -1252,7 +1286,7 @@ mod tests {)?;// expression: "a < b"- let lt = binary(col(0), Operator::Lt, col(1));+ let lt = binary(col(0, &schema), Operator::Lt, col(1, &schema));let result = lt.evaluate(&batch)?;assert_eq!(result.len(), 5);@@ -1283,9 +1317,9 @@ mod tests {// expression: "a < b OR a == b"let expr = binary(- binary(col(0), Operator::Lt, col(1)),+ binary(col(0, &schema), Operator::Lt, col(1, &schema)),Operator::Or,- binary(col(0), Operator::Eq, col(1)),+ binary(col(0, &schema), Operator::Eq, col(1, &schema)),);let result = expr.evaluate(&batch)?;assert_eq!(result.len(), 5);@@ -1330,7 +1364,7 @@ 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)])?;- let cast = CastExpr::try_new(col(0), &schema, DataType::UInt32)?;+ let cast = CastExpr::try_new(col(0, &schema), &schema, DataType::UInt32)?;let result = cast.evaluate(&batch)?;assert_eq!(result.len(), 5);@@ -1349,7 +1383,7 @@ 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)])?;- let cast = CastExpr::try_new(col(0), &schema, DataType::Utf8)?;+ let cast = CastExpr::try_new(col(0, &schema), &schema, DataType::Utf8)?;let result = cast.evaluate(&batch)?;assert_eq!(result.len(), 5);@@ -1369,7 +1403,7 @@ mod tests {let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;let cast = CastExpr::try_new(- col(0),+ col(0, &schema),&schema,DataType::Timestamp(TimeUnit::Nanosecond, None),)?;@@ -1388,7 +1422,7 @@ mod tests {#[test]fn invalid_cast() -> Result<()> {let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);- match CastExpr::try_new(col(0), &schema, DataType::Int32) {+ match CastExpr::try_new(col(0, &schema), &schema, DataType::Int32) {Err(ExecutionError::General(ref str)) => {assert_eq!(str, "Invalid CAST from Utf8 to Int32");Ok(())@@ -1401,7 +1435,7 @@ mod tests {fn sum_contract() -> Result<()> {let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);- let sum = sum(col(0));+ let sum = sum(col(0, &schema));assert_eq!("SUM".to_string(), sum.name());assert_eq!(DataType::Int64, sum.data_type(&schema)?);@@ -1416,7 +1450,7 @@ mod tests {fn max_contract() -> Result<()> {let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);- let max = max(col(0));+ let max = max(col(0, &schema));assert_eq!("MAX".to_string(), max.name());assert_eq!(DataType::Int64, max.data_type(&schema)?);@@ -1431,7 +1465,7 @@ mod tests {fn min_contract() -> Result<()> {let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);- let min = min(col(0));+ let min = min(col(0, &schema));assert_eq!("MIN".to_string(), min.name());assert_eq!(DataType::Int64, min.data_type(&schema)?);@@ -1445,7 +1479,7 @@ mod tests {fn avg_contract() -> Result<()> {let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);- let avg = avg(col(0));+ let avg = avg(col(0, &schema));assert_eq!("AVG".to_string(), avg.name());assert_eq!(DataType::Float64, avg.data_type(&schema)?);@@ -1781,7 +1815,7 @@ mod tests {}fn do_sum(batch: &RecordBatch) -> Result<Option<ScalarValue>> {- let sum = sum(col(0));+ let sum = sum(col(0, &batch.schema()));let accum = sum.create_accumulator();let input = sum.evaluate_input(batch)?;let mut accum = accum.borrow_mut();@@ -1792,7 +1826,7 @@ mod tests {}fn do_max(batch: &RecordBatch) -> Result<Option<ScalarValue>> {- let max = max(col(0));+ let max = max(col(0, &batch.schema()));let accum = max.create_accumulator();let input = max.evaluate_input(batch)?;let mut accum = accum.borrow_mut();@@ -1803,7 +1837,7 @@ mod tests {}fn do_min(batch: &RecordBatch) -> Result<Option<ScalarValue>> {- let min = min(col(0));+ let min = min(col(0, &batch.schema()));let accum = min.create_accumulator();let input = min.evaluate_input(batch)?;let mut accum = accum.borrow_mut();@@ -1814,7 +1848,7 @@ mod tests {}fn do_count(batch: &RecordBatch) -> Result<Option<ScalarValue>> {- let count = count(col(0));+ let count = count(col(0, &batch.schema()));let accum = count.create_accumulator();let input = count.evaluate_input(batch)?;let mut accum = accum.borrow_mut();@@ -1825,7 +1859,7 @@ mod tests {}fn do_avg(batch: &RecordBatch) -> Result<Option<ScalarValue>> {- let avg = avg(col(0));+ let avg = avg(col(0, &batch.schema()));let accum = avg.create_accumulator();let input = avg.evaluate_input(batch)?;let mut accum = accum.borrow_mut();@@ -1925,9 +1959,8 @@ mod tests {op: Operator,expected: PrimitiveArray<T>,) -> Result<()> {+ let arithmetic_op = binary(col(0, schema.as_ref()), op, col(1, schema.as_ref()));let batch = RecordBatch::try_new(schema, data)?;-- let arithmetic_op = binary(col(0), op, col(1));let result = arithmetic_op.evaluate(&batch)?;assert_array_eq::<T>(expected, result);@@ -1956,7 +1989,7 @@ mod tests {let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;// expression: "!a"- let lt = not(col(0));+ let lt = not(col(0, &schema));let result = lt.evaluate(&batch)?;assert_eq!(result.len(), 2);diff --git a/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs b/rust/datafusion/src/execution/physical_plan/hash_aggregate.rsindex 528db3b392..5e42e15909 100644--- a/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs+++ b/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs@@ -84,7 +84,10 @@ impl HashAggregateExec {&self,) -> (Vec<Arc<dyn PhysicalExpr>>, Vec<Arc<dyn AggregateExpr>>) {let final_group: Vec<Arc<dyn PhysicalExpr>> = (0..self.group_expr.len())- .map(|i| Arc::new(Column::new(i)) as Arc<dyn PhysicalExpr>)+ .map(|i| {+ Arc::new(Column::new(i, &self.group_expr[i].name()))+ as Arc<dyn PhysicalExpr>+ }).collect();let final_aggr: Vec<Arc<dyn AggregateExpr>> = (0..self.aggr_expr.len())@@ -733,11 +736,11 @@ mod tests {let partitions = 4;let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;- let csv = CsvExec::try_new(&path, schema, true, None, 1024)?;+ let csv = CsvExec::try_new(&path, schema.clone(), true, None, 1024)?;- let group_expr: Vec<Arc<dyn PhysicalExpr>> = vec![col(1)];+ let group_expr: Vec<Arc<dyn PhysicalExpr>> = vec![col(1, schema.as_ref())];- let aggr_expr: Vec<Arc<dyn AggregateExpr>> = vec![sum(col(3))];+ let aggr_expr: Vec<Arc<dyn AggregateExpr>> = vec![sum(col(3, schema.as_ref()))];let partition_aggregate = HashAggregateExec::try_new(group_expr.clone(),diff --git a/rust/datafusion/src/execution/physical_plan/projection.rs b/rust/datafusion/src/execution/physical_plan/projection.rsindex 3cbf3d3887..3ae8ba0ffb 100644--- a/rust/datafusion/src/execution/physical_plan/projection.rs+++ b/rust/datafusion/src/execution/physical_plan/projection.rs@@ -150,10 +150,14 @@ mod tests {let partitions = 4;let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;- let csv = CsvExec::try_new(&path, schema, true, None, 1024)?;+ let csv = CsvExec::try_new(&path, schema.clone(), true, None, 1024)?;- let projection =- ProjectionExec::try_new(vec![Arc::new(Column::new(0))], Arc::new(csv))?;+ let projection = ProjectionExec::try_new(+ vec![Arc::new(Column::new(0, &schema.as_ref().field(0).name()))],+ Arc::new(csv),+ )?;++ assert_eq!("c1", projection.schema.field(0).name().as_str());let mut partition_count = 0;let mut row_count = 0;diff --git a/rust/datafusion/src/execution/physical_plan/selection.rs b/rust/datafusion/src/execution/physical_plan/selection.rsindex 7bea172c39..ea74a89147 100644--- a/rust/datafusion/src/execution/physical_plan/selection.rs+++ b/rust/datafusion/src/execution/physical_plan/selection.rs@@ -159,12 +159,20 @@ mod tests {let partitions = 4;let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;- let csv = CsvExec::try_new(&path, schema, true, None, 1024)?;+ let csv = CsvExec::try_new(&path, schema.clone(), true, None, 1024)?;let predicate: Arc<dyn PhysicalExpr> = binary(- binary(col(1), Operator::Gt, lit(ScalarValue::UInt32(1))),+ binary(+ col(1, schema.as_ref()),+ Operator::Gt,+ lit(ScalarValue::UInt32(1)),+ ),Operator::And,- binary(col(1), Operator::Lt, lit(ScalarValue::UInt32(4))),+ binary(+ col(1, schema.as_ref()),+ Operator::Lt,+ lit(ScalarValue::UInt32(4)),+ ),);let selection: Arc<dyn ExecutionPlan> =diff --git a/rust/datafusion/src/logicalplan.rs b/rust/datafusion/src/logicalplan.rsindex ec47f28a0b..48fbae96ef 100644--- a/rust/datafusion/src/logicalplan.rs+++ b/rust/datafusion/src/logicalplan.rs@@ -179,6 +179,8 @@ impl ScalarValue {/// Relation expression#[derive(Clone, PartialEq)]pub enum Expr {+ /// An aliased expression+ Alias(Arc<Expr>, String),/// index into a value within the row or complex valueColumn(usize),/// literal value@@ -236,6 +238,7 @@ impl Expr {/// Find the `DataType` for the expressionpub fn get_type(&self, schema: &Schema) -> DataType {match self {+ Expr::Alias(expr, _) => expr.get_type(schema),Expr::Column(n) => schema.field(*n).data_type().clone(),Expr::Literal(l) => l.get_datatype(),Expr::Cast { data_type, .. } => data_type.clone(),@@ -341,6 +344,11 @@ impl Expr {pub fn not(&self) -> Expr {Expr::Not(Arc::new(self.clone()))}++ /// Alias+ pub fn alias(&self, name: &str) -> Expr {+ Expr::Alias(Arc::new(self.clone()), name.to_owned())+ }}/// Create a column expression@@ -365,6 +373,7 @@ pub fn aggregate_expr(name: &str, expr: Expr, return_type: DataType) -> Expr {impl fmt::Debug for Expr {fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {match self {+ Expr::Alias(expr, alias) => write!(f, "{:?} AS {}", expr, alias),Expr::Column(i) => write!(f, "#{}", i),Expr::Literal(v) => write!(f, "{:?}", v),Expr::Cast { expr, data_type } => {@@ -807,10 +816,12 @@ mod tests {vec![col(0)],vec![aggregate_expr("SUM", col(1), DataType::Int32)],)?+ .project(&vec![col(0), col(1).alias("total_salary")])?.build()?;- let expected = "Aggregate: groupBy=[[#0]], aggr=[[SUM(#1)]]\n \- TableScan: employee.csv projection=Some([3, 4])";+ let expected = "Projection: #0, #1 AS total_salary\+ \n Aggregate: groupBy=[[#0]], aggr=[[SUM(#1)]]\+ \n TableScan: employee.csv projection=Some([3, 4])";assert_eq!(expected, format!("{:?}", plan));diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex 1ccffa64ad..5a541c9d4d 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -229,6 +229,10 @@ impl ProjectionPushDown {fn rewrite_expr(&self, expr: &Expr, mapping: &HashMap<usize, usize>) -> Result<Expr> {match expr {+ Expr::Alias(expr, name) => Ok(Expr::Alias(+ Arc::new(self.rewrite_expr(expr, mapping)?),+ name.clone(),+ )),Expr::Column(i) => Ok(Expr::Column(self.new_index(mapping, i)?)),Expr::Literal(_) => Ok(expr.clone()),Expr::Not(e) => Ok(Expr::Not(Arc::new(self.rewrite_expr(e, mapping)?))),diff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rsindex 7991701011..b4d9889db9 100644--- a/rust/datafusion/src/optimizer/utils.rs+++ b/rust/datafusion/src/optimizer/utils.rs@@ -34,6 +34,7 @@ pub fn exprlist_to_column_indices(expr: &Vec<Expr>, accum: &mut HashSet<usize>)/// referenced in the expressionpub fn expr_to_column_indices(expr: &Expr, accum: &mut HashSet<usize>) {match expr {+ Expr::Alias(expr, _) => expr_to_column_indices(expr, accum),Expr::Column(i) => {accum.insert(*i);}@@ -55,6 +56,9 @@ pub fn expr_to_column_indices(expr: &Expr, accum: &mut HashSet<usize>) {/// Create field meta-data from an expression, for use in a result set schemapub fn expr_to_field(e: &Expr, input_schema: &Schema) -> Result<Field> {match e {+ Expr::Alias(expr, name) => {+ Ok(Field::new(name, expr.get_type(input_schema), true))+ }Expr::Column(i) => {let input_schema_field_count = input_schema.fields().len();if *i < input_schema_field_count {