avantgardnerio commented on code in PR #2885: URL: https://github.com/apache/arrow-datafusion/pull/2885#discussion_r926044186
########## datafusion/optimizer/src/decorrelate_scalar_subquery.rs: ########## @@ -0,0 +1,704 @@ +// 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. + +use crate::utils::{ + exprs_to_join_cols, find_join_exprs, has_disjunction, only_or_err, split_conjunction, +}; +use crate::{utils, OptimizerConfig, OptimizerRule}; +use datafusion_common::{context, plan_err, Column, Result}; +use datafusion_expr::logical_plan::{Aggregate, Filter, JoinType, Projection, Subquery}; +use datafusion_expr::{combine_filters, Expr, LogicalPlan, LogicalPlanBuilder, Operator}; +use log::debug; +use std::sync::Arc; + +/// Optimizer rule for rewriting subquery filters to joins +#[derive(Default)] +pub struct DecorrelateScalarSubquery {} + +impl DecorrelateScalarSubquery { + #[allow(missing_docs)] + pub fn new() -> Self { + Self {} + } + + /// Finds expressions that have a scalar subquery in them (and recurses when found) + /// + /// # Arguments + /// * `predicate` - A conjunction to split and search + /// * `optimizer_config` - For generating unique subquery aliases + /// + /// Returns a tuple (subqueries, non-subquery expressions) + fn extract_subquery_exprs( + &self, + predicate: &Expr, + optimizer_config: &mut OptimizerConfig, + ) -> Result<(Vec<SubqueryInfo>, Vec<Expr>)> { + let mut filters = vec![]; + split_conjunction(predicate, &mut filters); // TODO: disjunctions + + let mut subqueries = vec![]; + let mut others = vec![]; + for it in filters.iter() { + match it { + Expr::BinaryExpr { left, op, right } => { + let l_query = Subquery::try_from_expr(left); + let r_query = Subquery::try_from_expr(right); + if l_query.is_err() && r_query.is_err() { + others.push((*it).clone()); + continue; + } + let mut recurse = + |q: Result<&Subquery>, expr: Expr, lhs: bool| -> Result<()> { + let subquery = match q { + Ok(subquery) => subquery, + _ => return Ok(()), + }; + let subquery = + self.optimize(&*subquery.subquery, optimizer_config)?; + let subquery = Arc::new(subquery); + let subquery = Subquery { subquery }; + let res = SubqueryInfo::new(subquery, expr, *op, lhs); + subqueries.push(res); + Ok(()) + }; + recurse(l_query, (**right).clone(), false)?; + recurse(r_query, (**left).clone(), true)?; + // TODO: if subquery doesn't get optimized, optimized children are lost Review Comment: It is... that was one of the big things I was wondering if we should address before merging or not. Honestly, the recursiveness here is both hard to keep in my head, and difficult to follow in the debugger, much less create the right test cases for. It's excellent that @andygrove 's change allows us to just `?` out on a failure, but cases like this where some recursive optimization has _already_ occurred prevent it's use in every situation. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
