Apache DataFusion SQL Query Engine
Support sort on unprojected columns (#1415)
Liang-Chi Hsieh591932fc9a67
diff --git a/datafusion/src/logical_plan/builder.rs b/datafusion/src/logical_plan/builder.rsindex fc7df59558..91d5a9d21e 100644--- a/datafusion/src/logical_plan/builder.rs+++ b/datafusion/src/logical_plan/builder.rs@@ -29,6 +29,7 @@ use crate::logical_plan::plan::{Aggregate, Analyze, EmptyRelation, Explain, Filter, Join, Projection, Sort,TableScan, ToStringifiedPlan, Union, Window,};+use crate::optimizer::utils;use crate::prelude::*;use crate::scalar::ScalarValue;use arrow::{@@ -466,11 +467,112 @@ impl LogicalPlanBuilder {})))}+ /// Add missing sort columns to downstream projection+ fn add_missing_columns(+ &self,+ curr_plan: LogicalPlan,+ missing_cols: &[Column],+ ) -> Result<LogicalPlan> {+ match curr_plan.clone() {+ LogicalPlan::Projection(Projection {+ input,+ expr,+ schema: _,+ alias,+ }) if missing_cols+ .iter()+ .all(|c| input.schema().field_from_column(c).is_ok()) =>+ {+ let input_schema = input.schema();++ let mut new_expr = Vec::new();+ new_expr.extend(expr);+ missing_cols.iter().try_for_each::<_, Result<()>>(|c| {+ new_expr.push(normalize_col(Expr::Column(c.clone()), &input)?);++ Ok(())+ })?;++ let new_inputs =+ curr_plan.inputs().into_iter().cloned().collect::<Vec<_>>();++ let new_schema =+ DFSchema::new(exprlist_to_fields(&new_expr, input_schema)?)?;++ Ok(LogicalPlan::Projection(Projection {+ expr: new_expr,+ input: Arc::new(new_inputs.get(0).unwrap().clone()),+ schema: DFSchemaRef::new(new_schema),+ alias,+ }))+ }+ _ => {+ let inputs = curr_plan.inputs();+ let mut new_inputs = vec![];+ inputs.iter().try_for_each::<_, Result<()>>(|input_plan| {+ let new_input =+ self.add_missing_columns((*input_plan).clone(), missing_cols)?;+ new_inputs.push(new_input);++ Ok(())+ })?;++ let expr = curr_plan.expressions();+ utils::from_plan(&curr_plan, &expr, &new_inputs)+ }+ }+ }+/// Apply a sort- pub fn sort(&self, exprs: impl IntoIterator<Item = impl Into<Expr>>) -> Result<Self> {- Ok(Self::from(LogicalPlan::Sort(Sort {- expr: normalize_cols(exprs, &self.plan)?,- input: Arc::new(self.plan.clone()),+ pub fn sort(+ &self,+ exprs: impl IntoIterator<Item = impl Into<Expr>> + Clone,+ ) -> Result<Self> {+ let schema = self.plan.schema();++ // Collect sort columns that are missing in the input plan's schema+ let mut missing_cols: Vec<Column> = vec![];+ exprs+ .clone()+ .into_iter()+ .try_for_each::<_, Result<()>>(|expr| {+ let mut columns: HashSet<Column> = HashSet::new();+ utils::expr_to_columns(&expr.into(), &mut columns)?;++ columns.into_iter().for_each(|c| {+ if schema.field_from_column(&c).is_err() {+ missing_cols.push(c);+ }+ });++ Ok(())+ })?;++ if missing_cols.is_empty() {+ return Ok(Self::from(LogicalPlan::Sort(Sort {+ expr: normalize_cols(exprs, &self.plan)?,+ input: Arc::new(self.plan.clone()),+ })));+ }++ let plan = self.add_missing_columns(self.plan.clone(), &missing_cols)?;+ let sort_plan = LogicalPlan::Sort(Sort {+ expr: normalize_cols(exprs, &plan)?,+ input: Arc::new(plan.clone()),+ });+ // remove pushed down sort columns+ let new_expr = schema+ .fields()+ .iter()+ .map(|f| Expr::Column(f.qualified_column()))+ .collect();+ let new_schema = DFSchema::new(exprlist_to_fields(&new_expr, schema)?)?;++ Ok(Self::from(LogicalPlan::Projection(Projection {+ expr: new_expr,+ input: Arc::new(sort_plan),+ schema: DFSchemaRef::new(new_schema),+ alias: None,})))}diff --git a/datafusion/tests/dataframe.rs b/datafusion/tests/dataframe.rsindex b93e21f4ab..76b9600812 100644--- a/datafusion/tests/dataframe.rs+++ b/datafusion/tests/dataframe.rs@@ -23,10 +23,11 @@ use arrow::{record_batch::RecordBatch,};+use datafusion::assert_batches_eq;use datafusion::error::Result;-use datafusion::{datasource::MemTable, prelude::JoinType};-use datafusion::execution::context::ExecutionContext;+use datafusion::logical_plan::{col, Expr};+use datafusion::{datasource::MemTable, prelude::JoinType};#[tokio::test]async fn join() -> Result<()> {@@ -77,3 +78,45 @@ async fn join() -> Result<()> {Ok(())}++#[tokio::test]+async fn sort_on_unprojected_columns() -> Result<()> {+ let schema = Schema::new(vec![+ Field::new("a", DataType::Int32, false),+ Field::new("b", DataType::Int32, false),+ ]);++ let batch = RecordBatch::try_new(+ Arc::new(schema.clone()),+ vec![+ Arc::new(Int32Array::from(vec![1, 10, 10, 100])),+ Arc::new(Int32Array::from(vec![2, 12, 12, 120])),+ ],+ )+ .unwrap();++ let mut ctx = ExecutionContext::new();+ let provider = MemTable::try_new(Arc::new(schema), vec![vec![batch]]).unwrap();+ ctx.register_table("t", Arc::new(provider)).unwrap();++ let df = ctx+ .table("t")+ .unwrap()+ .select(vec![col("a")])+ .unwrap()+ .sort(vec![Expr::Sort {+ expr: Box::new(col("b")),+ asc: false,+ nulls_first: true,+ }])+ .unwrap();+ let results = df.collect().await.unwrap();++ let expected = vec![+ "+-----+", "| a |", "+-----+", "| 100 |", "| 10 |", "| 10 |", "| 1 |",+ "+-----+",+ ];+ assert_batches_eq!(expected, &results);++ Ok(())+}diff --git a/datafusion/tests/sql.rs b/datafusion/tests/sql.rsindex 136e4f34a8..4619e53499 100644--- a/datafusion/tests/sql.rs+++ b/datafusion/tests/sql.rs@@ -6356,6 +6356,21 @@ async fn test_expect_distinct() -> Result<()> {Ok(())}+#[tokio::test]+async fn test_sort_unprojected_col() -> Result<()> {+ let mut ctx = ExecutionContext::new();+ register_alltypes_parquet(&mut ctx).await;+ // execute the query+ let sql = "SELECT id FROM alltypes_plain ORDER BY int_col, double_col";+ let actual = execute_to_batches(&mut ctx, sql).await;+ let expected = vec![+ "+----+", "| id |", "+----+", "| 4 |", "| 6 |", "| 2 |", "| 0 |", "| 5 |",+ "| 7 |", "| 3 |", "| 1 |", "+----+",+ ];+ assert_batches_eq!(expected, &actual);+ Ok(())+}+#[tokio::test]async fn test_nulls_first_asc() -> Result<()> {let mut ctx = ExecutionContext::new();