Skip to content

Apache DataFusion SQL Query Engine

ARROW-10547: [Rust][DataFusion] Do not lose Filters with UserDefined plan nodes

alambac3273dc8148
diff --git a/rust/datafusion/src/optimizer/filter_push_down.rs b/rust/datafusion/src/optimizer/filter_push_down.rs
index 28a99eedfe..36c23dcf74 100644
--- a/rust/datafusion/src/optimizer/filter_push_down.rs
+++ b/rust/datafusion/src/optimizer/filter_push_down.rs
@@ -14,7 +14,7 @@
//! Filter Push Down optimizer rule ensures that filters are applied as early as possible in the plan
-use crate::error::Result;
+use crate::error::{DataFusionError, Result};
use crate::logical_plan::Expr;
use crate::logical_plan::{and, LogicalPlan};
use crate::optimizer::optimizer::OptimizerRule;
@@ -90,7 +90,7 @@ impl OptimizerRule for FilterPushDown {
// construct optimized position of each of the new filters
// E.g. when we have a filter (c1 + c2 > 2), c1's max depth is 10 and c2 is 11, we
// can push the filter to depth 10
- let mut new_filtersnew_filters: BTreeMap<usize, Expr> = BTreeMap::new();
+ let mut new_filters: BTreeMap<usize, Expr> = BTreeMap::new();
for (filter_depth, expr) in result.filters {
// get all columns on the filter expression
let mut filter_columns: HashSet<String> = HashSet::new();
@@ -126,13 +126,13 @@ impl OptimizerRule for FilterPushDown {
}
// AND filter expressions that would be placed on the same depth
- if let Some(existing_expression) = new_filtersnew_filters.get(&new_depth) {
+ if let Some(existing_expression) = new_filters.get(&new_depth) {
new_expression = and(existing_expression, &new_expression)
}
- new_filtersnew_filters.insert(new_depth, new_expression);
+ new_filters.insert(new_depth, new_expression);
}
- optimize_plan(plan, &new_filtersnew_filters, 0)
+ optimize_plan(plan, &new_filters, 0)
}
}
@@ -214,6 +214,36 @@ fn analyze_plan(plan: &LogicalPlan, depth: usize) -> Result<AnalysisResult> {
result.break_points.insert(depth, columns);
Ok(result)
}
+ LogicalPlan::Extension { node } => {
+ let inputs = node.inputs();
+
+ let mut result = match inputs.len() {
+ 0 => AnalysisResult {
+ break_points: BTreeMap::new(),
+ filters: BTreeMap::new(),
+ projections: BTreeMap::new(),
+ },
+ 1 => analyze_plan(inputs[0], depth + 1)?,
+ _ => {
+ return Err(DataFusionError::NotImplemented(
+ "Not Yet Implemented: Predicate pushdown for multiple inputs"
+ .into(),
+ ))
+ }
+ };
+
+ // collect all columns that break at this depth
+ let columns = node
+ .schema()
+ .fields()
+ .iter()
+ .map(|f| f.name().clone())
+ .collect::<HashSet<_>>();
+ result.break_points.insert(depth, columns);
+
+ Ok(result)
+ }
+
// all other plans add breaks to all their columns to indicate that filters can't proceed further.
_ => {
let columns = plan
@@ -619,4 +649,27 @@ mod tests {
assert_optimized_plan_eq(&plan, expected);
Ok(())
}
+
+ /// verifies that filters on a plan with user nodes are not lost
+ /// (ARROW-10547)
+ #[test]
+ fn filters_user_defined_node() -> Result<()> {
+ let table_scan = test_table_scan()?;
+ let plan = LogicalPlanBuilder::from(&table_scan)
+ .filter(col("a").lt_eq(lit(1i64)))?
+ .build()?;
+
+ let plan = crate::test::user_defined::new(plan);
+
+ let expected = "\
+ TestUserDefined\
+ \n Filter: #a LtEq Int64(1)\
+ \n TableScan: test projection=None";
+
+ // not part of the test
+ assert_eq!(format!("{:?}", plan), expected);
+
+ assert_optimized_plan_eq(&plan, expected);
+ Ok(())
+ }
}
diff --git a/rust/datafusion/src/test/mod.rs b/rust/datafusion/src/test/mod.rs
index 67ae056c88..e995c9428d 100644
--- a/rust/datafusion/src/test/mod.rs
+++ b/rust/datafusion/src/test/mod.rs
@@ -249,6 +249,7 @@ pub fn assert_fields_eq(plan: &LogicalPlan, expected: Vec<&str>) {
assert_eq!(actual, expected);
}
+pub mod user_defined;
pub mod variable;
mod tests {
diff --git a/rust/datafusion/src/test/user_defined.rs b/rust/datafusion/src/test/user_defined.rs
new file mode 100644
index 0000000000..505f5cdafa
--- /dev/null
+++ b/rust/datafusion/src/test/user_defined.rs
@@ -0,0 +1,78 @@
+// 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.
+
+//! Simple user defined logical plan node for testing
+
+use std::{
+ any::Any,
+ fmt::{self, Debug},
+ sync::Arc,
+};
+
+use arrow::datatypes::SchemaRef;
+
+use crate::logical_plan::{Expr, LogicalPlan, UserDefinedLogicalNode};
+
+/// Create a new user defined plan node, for testing
+pub fn new(input: LogicalPlan) -> LogicalPlan {
+ let node = Arc::new(TestUserDefinedPlanNode { input });
+ LogicalPlan::Extension { node }
+}
+
+struct TestUserDefinedPlanNode {
+ input: LogicalPlan,
+}
+
+impl Debug for TestUserDefinedPlanNode {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ self.fmt_for_explain(f)
+ }
+}
+
+impl UserDefinedLogicalNode for TestUserDefinedPlanNode {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn inputs(&self) -> Vec<&LogicalPlan> {
+ vec![&self.input]
+ }
+
+ fn schema(&self) -> &SchemaRef {
+ self.input.schema()
+ }
+
+ fn expressions(&self) -> Vec<Expr> {
+ vec![]
+ }
+
+ fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "TestUserDefined")
+ }
+
+ fn from_template(
+ &self,
+ exprs: &Vec<Expr>,
+ inputs: &Vec<LogicalPlan>,
+ ) -> Arc<dyn UserDefinedLogicalNode + Send + Sync> {
+ assert_eq!(inputs.len(), 1, "input size inconsistent");
+ assert_eq!(exprs.len(), 0, "expression size inconsistent");
+ Arc::new(TestUserDefinedPlanNode {
+ input: inputs[0].clone(),
+ })
+ }
+}