Skip to content

Apache DataFusion SQL Query Engine

Refactor: Add `LogicalPlan::observe_expressions` to walk expressions (#4906)

Andrew Lambd49c805c9349
diff --git a/datafusion/expr/src/expr_visitor.rs b/datafusion/expr/src/expr_visitor.rs
index ed80547f11..82862eb873 100644
--- a/datafusion/expr/src/expr_visitor.rs
+++ b/datafusion/expr/src/expr_visitor.rs
@@ -220,3 +220,36 @@ impl ExprVisitable for Expr {
visitor.post_visit(self)
}
}
+
+struct VisitorAdapter<F, E> {
+ f: F,
+ err: std::result::Result<(), E>,
+}
+
+impl<F, E> ExpressionVisitor for VisitorAdapter<F, E>
+where
+ F: FnMut(&Expr) -> std::result::Result<(), E>,
+{
+ fn pre_visit(mut self, expr: &Expr) -> Result<Recursion<Self>> {
+ if let Err(e) = (self.f)(expr) {
+ // save the error for later (it may not be a DataFusionError
+ self.err = Err(e);
+ Ok(Recursion::Stop(self))
+ } else {
+ // keep going
+ Ok(Recursion::Continue(self))
+ }
+ }
+}
+
+/// Conveniece function for using a mutable function as an expression visiitor
+///
+/// TODO make this match names in physical plan
+pub fn walk_expr_down<F, E>(expr: &Expr, f: F) -> std::result::Result<(), E>
+where
+ F: FnMut(&Expr) -> std::result::Result<(), E>,
+{
+ // the visit is fallable, so unwrap here
+ let adapter = expr.accept(VisitorAdapter { f, err: Ok(()) }).unwrap();
+ adapter.err
+}
diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs
index 5ac8800d5e..4a86ea0fcc 100644
--- a/datafusion/expr/src/logical_plan/plan.rs
+++ b/datafusion/expr/src/logical_plan/plan.rs
@@ -15,8 +15,8 @@
// specific language governing permissions and limitations
// under the License.
-use crate::expr::BinaryExpr;
use crate::expr_rewriter::{ExprRewritable, ExprRewriter};
+use crate::expr_visitor::walk_expr_down;
///! Logical plan types
use crate::logical_plan::builder::validate_unique_names;
use crate::logical_plan::display::{GraphvizVisitor, IndentVisitor};
@@ -233,42 +233,71 @@ impl LogicalPlan {
/// logical plan node. This does not include expressions in any
/// children
pub fn expressions(self: &LogicalPlan) -> Vec<Expr> {
+ let mut exprs = vec![];
+ self.inspect_expressions(|e| {
+ exprs.push(e.clone());
+ Ok(()) as Result<(), DataFusionError>
+ })
+ // closure always returns OK
+ .unwrap();
+ exprs
+ }
+
+ /// Calls `f` on all expressions (non-recursively) in the current
+ /// logical plan node. This does not include expressions in any
+ /// children.
+ pub fn inspect_expressions<F, E>(self: &LogicalPlan, mut f: F) -> Result<(), E>
+ where
+ F: FnMut(&Expr) -> Result<(), E>,
+ {
match self {
- LogicalPlan::Projection(Projection { expr, .. }) => expr.clone(),
+ LogicalPlan::Projection(Projection { expr, .. }) => {
+ expr.iter().try_for_each(f)
+ }
LogicalPlan::Values(Values { values, .. }) => {
- values.iter().flatten().cloned().collect()
+ values.iter().flatten().try_for_each(f)
}
- LogicalPlan::Filter(Filter { predicate, .. }) => vec![predicate.clone()],
+ LogicalPlan::Filter(Filter { predicate, .. }) => f(predicate),
LogicalPlan::Repartition(Repartition {
partitioning_scheme,
..
}) => match partitioning_scheme {
- Partitioning::Hash(expr, _) => expr.clone(),
- Partitioning::DistributeBy(expr) => expr.clone(),
- Partitioning::RoundRobinBatch(_) => vec![],
+ Partitioning::Hash(expr, _) => expr.iter().try_for_each(f),
+ Partitioning::DistributeBy(expr) => expr.iter().try_for_each(f),
+ Partitioning::RoundRobinBatch(_) => Ok(()),
},
- LogicalPlan::Window(Window { window_expr, .. }) => window_expr.clone(),
+ LogicalPlan::Window(Window { window_expr, .. }) => {
+ window_expr.iter().try_for_each(f)
+ }
LogicalPlan::Aggregate(Aggregate {
group_expr,
aggr_expr,
..
- }) => group_expr.iter().chain(aggr_expr.iter()).cloned().collect(),
+ }) => group_expr.iter().chain(aggr_expr.iter()).try_for_each(f),
// There are two part of expression for join, equijoin(on) and non-equijoin(filter).
// 1. the first part is `on.len()` equijoin expressions, and the struct of each expr is `left-on = right-on`.
// 2. the second part is non-equijoin(filter).
- LogicalPlan::Join(Join { on, filter, .. }) => on
- .iter()
- .map(|(l, r)| Expr::eq(l.clone(), r.clone()))
- .chain(
- filter
- .as_ref()
- .map(|expr| vec![expr.clone()])
- .unwrap_or_default(),
- )
- .collect(),
- LogicalPlan::Sort(Sort { expr, .. }) => expr.clone(),
- LogicalPlan::Extension(extension) => extension.node.expressions(),
- LogicalPlan::TableScan(TableScan { filters, .. }) => filters.clone(),
+ LogicalPlan::Join(Join { on, filter, .. }) => {
+ on.iter()
+ // it not ideal to create an expr here to analyze them, but could cache it on the Join itself
+ .map(|(l, r)| Expr::eq(l.clone(), r.clone()))
+ .try_for_each(|e| f(&e))?;
+
+ if let Some(filter) = filter.as_ref() {
+ f(filter)
+ } else {
+ Ok(())
+ }
+ }
+ LogicalPlan::Sort(Sort { expr, .. }) => expr.iter().try_for_each(f),
+ LogicalPlan::Extension(extension) => {
+ // would be nice to avoid this copy -- maybe can
+ // update extension to just observer Exprs
+ extension.node.expressions().iter().try_for_each(f)
+ }
+ LogicalPlan::TableScan(TableScan { filters, .. }) => {
+ filters.iter().try_for_each(f)
+ }
// plans without expressions
LogicalPlan::EmptyRelation(_)
| LogicalPlan::Subquery(_)
@@ -287,9 +316,7 @@ impl LogicalPlan {
| LogicalPlan::Explain(_)
| LogicalPlan::Union(_)
| LogicalPlan::Distinct(_)
- | LogicalPlan::Prepare(_) => {
- vec![]
- }
+ | LogicalPlan::Prepare(_) => Ok(()),
}
}
@@ -376,7 +403,8 @@ impl LogicalPlan {
from_plan(self, &self.expressions(), inputs)
}
- /// Convert a prepare logical plan into its inner logical plan with all params replaced with their corresponding values
+ /// Convert a prepared [`LogicalPlan`] into its inner logical plan
+ /// with all params replaced with their corresponding values
pub fn with_param_values(
self,
param_values: Vec<ScalarValue>,
@@ -459,7 +487,7 @@ pub trait PlanVisitor {
}
impl LogicalPlan {
- /// returns all inputs in the logical plan. Returns Ok(true) if
+ /// Visits all inputs in the logical plan. Returns Ok(true) if
/// all nodes were visited, and Ok(false) if any call to
/// `pre_visit` or `post_visit` returned Ok(false) and may have
/// cut short the recursion
@@ -471,11 +499,12 @@ impl LogicalPlan {
return Ok(false);
}
+ // Now visit any subqueries in expressions
+ self.visit_subqueries(visitor)?;
+
let recurse = match self {
- LogicalPlan::Projection(Projection { .. }) => {
- self.visit_all_inputs(visitor)?
- }
- LogicalPlan::Filter(Filter { .. }) => self.visit_all_inputs(visitor)?,
+ LogicalPlan::Projection(Projection { input, .. }) => input.accept(visitor)?,
+ LogicalPlan::Filter(Filter { input, .. }) => input.accept(visitor)?,
LogicalPlan::Repartition(Repartition { input, .. }) => {
input.accept(visitor)?
}
@@ -537,55 +566,36 @@ impl LogicalPlan {
Ok(true)
}
- /// Visit all inputs, including subqueries
- pub fn visit_all_inputs<V>(&self, visitor: &mut V) -> Result<bool, V::Error>
+ /// applies visitor to any subqueries in the plan
+ fn visit_subqueries<V>(&self, v: &mut V) -> Result<bool, V::Error>
where
V: PlanVisitor,
{
- for input in self.all_inputs() {
- if !input.accept(visitor)? {
- return Ok(false);
- }
- }
-
+ self.inspect_expressions(|expr| {
+ // recursively look for subqueries
+ walk_expr_down(expr, |expr| {
+ match expr {
+ Expr::Exists { subquery, .. }
+ | Expr::InSubquery { subquery, .. }
+ | Expr::ScalarSubquery(subquery) => {
+ // use a synthetic plan so the visitor sees a
+ // LogicalPlan::Subquery (even though it is
+ // actually a Subquery alias)
+ let synthetic_plan = LogicalPlan::Subquery(subquery.clone());
+ synthetic_plan.accept(v)?;
+ }
+ _ => {}
+ }
+ Ok(())
+ })
+ })?;
+ // continue recursion
Ok(true)
}
- /// Get all plan inputs, including subqueries from expressions
- fn all_inputs(&self) -> Vec<Arc<LogicalPlan>> {
- let mut inputs = vec![];
- for expr in self.expressions() {
- Self::collect_subqueries(&expr, &mut inputs);
- }
- for input in self.inputs() {
- inputs.push(Arc::new(input.clone()));
- }
- inputs
- }
-
- fn collect_subqueries(expr: &Expr, sub: &mut Vec<Arc<LogicalPlan>>) {
- match expr {
- Expr::Alias(expr, ..) => {
- Self::collect_subqueries(expr, sub);
- }
- Expr::BinaryExpr(BinaryExpr { left, right, .. }) => {
- Self::collect_subqueries(left, sub);
- Self::collect_subqueries(right, sub);
- }
- Expr::Exists { subquery, .. } => {
- sub.push(Arc::new(LogicalPlan::Subquery(subquery.clone())));
- }
- Expr::InSubquery { subquery, .. } => {
- sub.push(Arc::new(LogicalPlan::Subquery(subquery.clone())));
- }
- Expr::ScalarSubquery(subquery) => {
- sub.push(Arc::new(LogicalPlan::Subquery(subquery.clone())));
- }
- _ => {}
- }
- }
-
- /// Return a logical plan with all placeholders/params (e.g $1 $2, ...) replaced with corresponding values provided in the prams_values
+ /// Return a logical plan with all placeholders/params (e.g $1 $2,
+ /// ...) replaced with corresponding values provided in the
+ /// params_values
pub fn replace_params_with_values(
&self,
param_values: &Vec<ScalarValue>,
@@ -606,7 +616,8 @@ impl LogicalPlan {
Ok(new_plan)
}
- /// Return an Expr with all placeholders replaced with their corresponding values provided in the prams_values
+ /// Return an Expr with all placeholders replaced with their
+ /// corresponding values provided in the params_values
fn replace_placeholders_with_values(
expr: Expr,
param_values: &Vec<ScalarValue>,
diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs
index 99b3f43b13..e53c35b85a 100644
--- a/datafusion/optimizer/src/push_down_filter.rs
+++ b/datafusion/optimizer/src/push_down_filter.rs
@@ -397,7 +397,7 @@ fn push_down_all_join(
.chain(once(keep_condition.into_iter().reduce(Expr::and).unwrap()))
.collect()
} else {
- plan.expressions()
+ expr
};
let plan = from_plan(plan, &expr, &[left, right])?;