Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 44 additions & 9 deletions datafusion/src/optimizer/projection_push_down.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ use crate::optimizer::utils;
use crate::sql::utils::find_sort_exprs;
use arrow::datatypes::{Field, Schema};
use arrow::error::Result as ArrowResult;
use std::{collections::HashSet, sync::Arc};
use std::{
collections::{BTreeSet, HashSet},
sync::Arc,
};
use utils::optimize_explain;

/// Optimizer that removes unused projections and aggregations from plans
Expand Down Expand Up @@ -75,9 +78,12 @@ fn get_projected_schema(
//
// we discard non-existing columns because some column names are not part of the schema,
// e.g. when the column derives from an aggregation
let mut projection: Vec<usize> = required_columns
//
// Use BTreeSet to remove potential duplicates (e.g. union) as
// well as to sort the projection to ensure deterministic behavior
let mut projection: BTreeSet<usize> = required_columns
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I did not use a BTreeSet one of the UNION ALL tests failed due to a duplicate column being projected.

Copy link
Member

@houqp houqp Jun 25, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

curious when should we use a HashSet v.s. BTreeSet? EDIT: nvm, saw you removed the sort afterwards :P

Copy link
Contributor Author

@alamb alamb Jun 26, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah - exactly - I used the BTreeSet as we needed the ids sorted anyways

.iter()
.filter(|c| c.relation.as_ref() == table_name)
.filter(|c| c.relation.is_none() || c.relation.as_ref() == table_name)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the core change -- don't compare the relation qualifier if there is none -- otherwise if c = Column { relation: None, name: "a"} and the table name is Some("foo") the column will be filtered, even if foo has a column named a

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good catch 👍

.map(|c| schema.index_of(&c.name))
.filter_map(ArrowResult::ok)
.collect();
Expand All @@ -87,21 +93,18 @@ fn get_projected_schema(
// Ensure that we are reading at least one column from the table in case the query
// does not reference any columns directly such as "SELECT COUNT(1) FROM table",
// except when the table is empty (no column)
projection.push(0);
projection.insert(0);
} else {
// for table scan without projection, we default to return all columns
projection = schema
.fields()
.iter()
.enumerate()
.map(|(i, _)| i)
.collect::<Vec<usize>>();
.collect::<BTreeSet<usize>>();
}
}

// sort the projection otherwise we get non-deterministic behavior
projection.sort_unstable();

// create the projected schema
let mut projected_fields: Vec<DFField> = Vec::with_capacity(projection.len());
match table_name {
Expand All @@ -120,6 +123,7 @@ fn get_projected_schema(
}
}

let projection = projection.into_iter().collect::<Vec<_>>();
Ok((projection, projected_fields.to_dfschema_ref()?))
}

Expand Down Expand Up @@ -438,7 +442,9 @@ fn optimize_plan(
mod tests {

use super::*;
use crate::logical_plan::{col, lit, max, min, Expr, JoinType, LogicalPlanBuilder};
use crate::logical_plan::{
col, exprlist_to_fields, lit, max, min, Expr, JoinType, LogicalPlanBuilder,
};
use crate::test::*;
use arrow::datatypes::DataType;

Expand Down Expand Up @@ -568,6 +574,35 @@ mod tests {
Ok(())
}

#[test]
fn table_scan_projected_schema_non_qualified_relation() -> Result<()> {
let table_scan = test_table_scan()?;
let input_schema = table_scan.schema();
assert_eq!(3, input_schema.fields().len());
assert_fields_eq(&table_scan, vec!["a", "b", "c"]);

// Build the LogicalPlan directly (don't use PlanBuilder), so
// that the Column references are unqualified (e.g. their
// relation is `None`). PlanBuilder resolves the expressions
let expr = vec![col("a"), col("b")];
let projected_fields = exprlist_to_fields(&expr, input_schema).unwrap();
let projected_schema = DFSchema::new(projected_fields).unwrap();
let plan = LogicalPlan::Projection {
expr,
input: Arc::new(table_scan),
schema: Arc::new(projected_schema),
};

assert_fields_eq(&plan, vec!["a", "b"]);

let expected = "Projection: #a, #b\
\n TableScan: test projection=Some([0, 1])";

assert_optimized_plan_eq(&plan, expected);

Ok(())
}

#[test]
fn table_limit() -> Result<()> {
let table_scan = test_table_scan()?;
Expand Down