Skip to main content

datafusion_optimizer/
scalar_subquery_to_join.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`ScalarSubqueryToJoin`] rewriting scalar subquery filters to `JOIN`s
6
7use std::collections::HashMap;
8use std::sync::Arc;
9
10use crate::decorrelate::{
11    PullUpCorrelatedExpr, UN_MATCHED_ROW_INDICATOR, build_join_filter,
12};
13use crate::optimizer::ApplyOrder;
14use crate::utils::evaluates_to_null;
15use crate::{OptimizerConfig, OptimizerRule};
16
17use crate::analyzer::type_coercion::TypeCoercionRewriter;
18use datafusion_common::alias::AliasGenerator;
19use datafusion_common::tree_node::{
20    Transformed, TransformedResult, TreeNode, TreeNodeRecursion, TreeNodeRewriter,
21};
22use datafusion_common::{Column, Result, ScalarValue, assert_or_internal_err, plan_err};
23use datafusion_expr::expr_rewriter::create_col_from_scalar_expr;
24use datafusion_expr::logical_plan::{JoinType, Subquery};
25use datafusion_expr::{Expr, LogicalPlan, LogicalPlanBuilder, lit, not, when};
26
27/// Optimizer rule that rewrites scalar subquery filters to joins and places an
28/// additional projection on top of the filter to preserve the original schema.
29///
30/// When [`datafusion_common::config::OptimizerOptions::enable_physical_uncorrelated_scalar_subquery`] is
31/// true (the default), only *correlated* scalar subqueries are rewritten here;
32/// uncorrelated ones are left for physical execution via `ScalarSubqueryExec`.
33/// When the option is false, all scalar subqueries — correlated and
34/// uncorrelated — are rewritten to left joins by this rule.
35#[derive(Default, Debug)]
36pub struct ScalarSubqueryToJoin {}
37
38impl ScalarSubqueryToJoin {
39    #[expect(missing_docs)]
40    pub fn new() -> Self {
41        Self::default()
42    }
43
44    /// Finds expressions that contain correlated scalar subqueries (and
45    /// recurses when found).
46    ///
47    /// # Arguments
48    /// * `predicate` - A conjunction to split and search.
49    /// * `alias_gen` - Generator used to produce unique aliases for each
50    ///   extracted scalar subquery (e.g. `__scalar_sq_1`, `__scalar_sq_2`).
51    ///   Each subquery is replaced by a column reference using the generated
52    ///   alias, and the same alias is later used to construct the join.
53    ///
54    /// Returns a tuple (subqueries, alias)
55    fn extract_subquery_exprs(
56        &self,
57        predicate: &Expr,
58        alias_gen: &Arc<AliasGenerator>,
59        physical_uncorrelated: bool,
60    ) -> Result<(Vec<(Subquery, String)>, Expr)> {
61        let mut extract = ExtractScalarSubQuery {
62            sub_query_info: vec![],
63            alias_gen,
64            physical_uncorrelated,
65        };
66        predicate
67            .clone()
68            .rewrite(&mut extract)
69            .data()
70            .map(|new_expr| (extract.sub_query_info, new_expr))
71    }
72}
73
74impl OptimizerRule for ScalarSubqueryToJoin {
75    fn rewrite(
76        &self,
77        plan: LogicalPlan,
78        config: &dyn OptimizerConfig,
79    ) -> Result<Transformed<LogicalPlan>> {
80        match plan {
81            LogicalPlan::Filter(filter) => {
82                let physical_uncorrelated = config
83                    .options()
84                    .optimizer
85                    .enable_physical_uncorrelated_scalar_subquery;
86                // Optimization: skip the rest of the rule and its copies if
87                // there are no scalar subqueries this rule should rewrite
88                if !contains_scalar_subquery_to_rewrite(
89                    &filter.predicate,
90                    physical_uncorrelated,
91                ) {
92                    return Ok(Transformed::no(LogicalPlan::Filter(filter)));
93                }
94
95                let (subqueries, mut rewrite_expr) = self.extract_subquery_exprs(
96                    &filter.predicate,
97                    config.alias_generator(),
98                    physical_uncorrelated,
99                )?;
100
101                assert_or_internal_err!(
102                    !subqueries.is_empty(),
103                    "Expected subqueries not found in filter"
104                );
105
106                // iterate through all subqueries in predicate, turning each into a left join
107                let mut cur_input = filter.input.as_ref().clone();
108                for (subquery, alias) in subqueries {
109                    if let Some((optimized_subquery, compensation_exprs)) =
110                        build_join(&subquery, &cur_input, &alias)?
111                    {
112                        if !compensation_exprs.is_empty() {
113                            rewrite_expr = rewrite_expr
114                                .transform_up(|expr| {
115                                    if let Some(compensation_expr) = expr
116                                        .try_as_col()
117                                        .and_then(|col| compensation_exprs.get(col))
118                                    {
119                                        Ok(Transformed::yes(compensation_expr.clone()))
120                                    } else {
121                                        Ok(Transformed::no(expr))
122                                    }
123                                })
124                                .data()?;
125                        }
126                        cur_input = optimized_subquery;
127                    } else {
128                        // if we can't handle all of the subqueries then bail for now
129                        return Ok(Transformed::no(LogicalPlan::Filter(filter)));
130                    }
131                }
132
133                // Preserve original schema as new Join might have more fields than what Filter & parents expect.
134                let projection =
135                    filter.input.schema().columns().into_iter().map(Expr::from);
136                let new_plan = LogicalPlanBuilder::from(cur_input)
137                    .filter(rewrite_expr)?
138                    .project(projection)?
139                    .build()?;
140                Ok(Transformed::yes(new_plan))
141            }
142            LogicalPlan::Projection(projection) => {
143                let physical_uncorrelated = config
144                    .options()
145                    .optimizer
146                    .enable_physical_uncorrelated_scalar_subquery;
147                // Optimization: skip the rest of the rule and its copies if there
148                // are no scalar subqueries this rule should rewrite
149                if !projection.expr.iter().any(|expr| {
150                    contains_scalar_subquery_to_rewrite(expr, physical_uncorrelated)
151                }) {
152                    return Ok(Transformed::no(LogicalPlan::Projection(projection)));
153                }
154
155                let mut all_subqueries = vec![];
156                let mut alias_to_index: HashMap<String, usize> = HashMap::new();
157                let mut rewrite_exprs: Vec<Expr> =
158                    Vec::with_capacity(projection.expr.len());
159                for (idx, expr) in projection.expr.iter().enumerate() {
160                    let (subqueries, rewrite_expr) = self.extract_subquery_exprs(
161                        expr,
162                        config.alias_generator(),
163                        physical_uncorrelated,
164                    )?;
165                    for (_, alias) in &subqueries {
166                        alias_to_index.insert(alias.clone(), idx);
167                    }
168                    all_subqueries.extend(subqueries);
169                    rewrite_exprs.push(rewrite_expr);
170                }
171                assert_or_internal_err!(
172                    !all_subqueries.is_empty(),
173                    "Expected subqueries not found in projection"
174                );
175                // iterate through all subqueries in predicate, turning each into a left join
176                let mut cur_input = projection.input.as_ref().clone();
177                for (subquery, alias) in all_subqueries {
178                    if let Some((optimized_subquery, compensation_exprs)) =
179                        build_join(&subquery, &cur_input, &alias)?
180                    {
181                        cur_input = optimized_subquery;
182                        if !compensation_exprs.is_empty()
183                            && let Some(&idx) = alias_to_index.get(&alias)
184                        {
185                            let new_expr = rewrite_exprs[idx]
186                                .clone()
187                                .transform_up(|expr| {
188                                    if let Some(compensation_expr) = expr
189                                        .try_as_col()
190                                        .and_then(|col| compensation_exprs.get(col))
191                                    {
192                                        Ok(Transformed::yes(compensation_expr.clone()))
193                                    } else {
194                                        Ok(Transformed::no(expr))
195                                    }
196                                })
197                                .data()?;
198                            rewrite_exprs[idx] = new_expr;
199                        }
200                    } else {
201                        // if we can't handle all of the subqueries then bail for now
202                        return Ok(Transformed::no(LogicalPlan::Projection(projection)));
203                    }
204                }
205
206                let mut proj_exprs = Vec::with_capacity(projection.expr.len());
207                for (expr, new_expr) in projection.expr.iter().zip(rewrite_exprs) {
208                    let old_expr_name = expr.schema_name().to_string();
209                    let new_expr_name = new_expr.schema_name().to_string();
210                    if new_expr_name != old_expr_name {
211                        proj_exprs.push(new_expr.alias(old_expr_name))
212                    } else {
213                        proj_exprs.push(new_expr);
214                    }
215                }
216                let new_plan = LogicalPlanBuilder::from(cur_input)
217                    .project(proj_exprs)?
218                    .build()?;
219                Ok(Transformed::yes(new_plan))
220            }
221
222            plan => Ok(Transformed::no(plan)),
223        }
224    }
225
226    fn name(&self) -> &str {
227        "scalar_subquery_to_join"
228    }
229
230    fn apply_order(&self) -> Option<ApplyOrder> {
231        Some(ApplyOrder::TopDown)
232    }
233}
234
235/// Returns true if the expression contains a scalar subquery that this rule
236/// should rewrite to a join.
237///
238/// When `enable_physical_uncorrelated_scalar_subquery` is true (the default) only
239/// correlated scalar subqueries are rewritten — uncorrelated ones are handled
240/// by the physical planner via `ScalarSubqueryExec`. When it is false, all
241/// scalar subqueries (correlated and uncorrelated) are rewritten.
242fn contains_scalar_subquery_to_rewrite(expr: &Expr, physical_uncorrelated: bool) -> bool {
243    expr.exists(|expr| {
244        Ok(matches!(
245            expr,
246            Expr::ScalarSubquery(sq)
247                if !physical_uncorrelated || !sq.outer_ref_columns.is_empty()
248        ))
249    })
250    .expect("Inner is always Ok")
251}
252
253struct ExtractScalarSubQuery<'a> {
254    sub_query_info: Vec<(Subquery, String)>,
255    alias_gen: &'a Arc<AliasGenerator>,
256    physical_uncorrelated: bool,
257}
258
259impl TreeNodeRewriter for ExtractScalarSubQuery<'_> {
260    type Node = Expr;
261
262    fn f_down(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
263        match expr {
264            // Match scalar subqueries this rule should rewrite to a join. When
265            // `physical_uncorrelated` is true, only correlated subqueries are
266            // rewritten — uncorrelated ones are handled later by the physical
267            // planner. When false, both are rewritten.
268            Expr::ScalarSubquery(ref subquery)
269                if !self.physical_uncorrelated
270                    || !subquery.outer_ref_columns.is_empty() =>
271            {
272                let subquery = subquery.clone();
273                let scalar_expr = subquery
274                    .subquery
275                    .head_output_expr()?
276                    .map_or(plan_err!("single expression required."), Ok)?;
277                let subqry_alias = self.alias_gen.next("__scalar_sq");
278                let col =
279                    create_col_from_scalar_expr(&scalar_expr, subqry_alias.clone())?;
280                self.sub_query_info.push((subquery, subqry_alias));
281                Ok(Transformed::new(
282                    Expr::Column(col),
283                    true,
284                    TreeNodeRecursion::Jump,
285                ))
286            }
287            _ => Ok(Transformed::no(expr)),
288        }
289    }
290}
291
292/// Takes a query like:
293///
294/// ```text
295/// select id from customers where balance >
296///     (select avg(total) from orders where orders.c_id = customers.id)
297/// ```
298///
299/// and optimizes it into:
300///
301/// ```text
302/// select c.id from customers c
303/// left join (select c_id, avg(total) from orders group by c_id) o
304/// on o.c_id = c.id
305/// where c.balance > o."avg(total)"
306/// ```
307///
308/// When [`datafusion_common::config::OptimizerOptions::enable_physical_uncorrelated_scalar_subquery`] is
309/// false, this function also handles uncorrelated scalar subqueries, rewriting
310/// them as a `Left Join: Filter: Boolean(true)` instead of leaving them for
311/// `ScalarSubqueryExec`.
312///
313/// # Arguments
314///
315/// * `subquery` - The scalar subquery to rewrite (correlated, or uncorrelated
316///   when `enable_physical_uncorrelated_scalar_subquery` is false).
317/// * `outer_input` - The outer plan that the decorrelated subquery is
318///   left-joined onto — the input of the `Filter` or `Projection` node
319///   that contained the subquery.
320/// * `subquery_alias` - The unique alias assigned to the decorrelated
321///   subquery; used both to qualify the join condition and to produce
322///   column references for the caller to substitute.
323///
324/// Returns `Ok(None)` if the subquery cannot be decorrelated. On success,
325/// returns the rewritten outer plan and a map from each count-bug-affected
326/// column to its `CASE WHEN __always_true IS NULL THEN ... END` compensation
327/// expression, which the caller must substitute into any expression that
328/// references those columns.
329fn build_join(
330    subquery: &Subquery,
331    outer_input: &LogicalPlan,
332    subquery_alias: &str,
333) -> Result<Option<(LogicalPlan, HashMap<Column, Expr>)>> {
334    // `build_join` also handles uncorrelated scalar subqueries (as a left
335    // join with `Boolean(true)`) when the
336    // `enable_physical_uncorrelated_scalar_subquery` option is disabled.
337    let subquery_plan = subquery.subquery.as_ref();
338    let mut pull_up = PullUpCorrelatedExpr::new().with_need_handle_count_bug(true);
339    let decorrelated_subquery = subquery_plan.clone().rewrite(&mut pull_up).data()?;
340    if !pull_up.can_pull_up {
341        return Ok(None);
342    }
343
344    let collected_count_expr_map = pull_up
345        .collected_count_expr_map
346        .get(&decorrelated_subquery)
347        .cloned();
348    let aliased_subquery = LogicalPlanBuilder::from(decorrelated_subquery)
349        .alias(subquery_alias.to_string())?
350        .build()?;
351
352    let join_filter_opt = build_join_filter(
353        pull_up.join_filters,
354        pull_up.correlated_subquery_cols_map.values().flatten(),
355        subquery_alias,
356    )?;
357
358    // When pull-up did not extract any usable join keys (a correlated subquery
359    // whose predicate references only outer columns), fall back to `ON true`:
360    // the decorrelated subquery still yields at most one row per outer row
361    // because its aggregate is grouped by the (empty) set of correlated inner
362    // columns.
363    let join_filter = join_filter_opt.or_else(|| Some(lit(true)));
364
365    let new_plan = LogicalPlanBuilder::from(outer_input.clone())
366        .join_on(aliased_subquery, JoinType::Left, join_filter)?
367        .build()?;
368
369    // Add count-bug compensation for each of the subquery's projected
370    // expressions that yield non-NULL values on empty input. We wrap each
371    // such expression in a CASE that substitutes the empty-input value
372    // when the LEFT JOIN produced synthetic right-side NULLs (no inner
373    // row matched), and uses the actual right-side value (which may
374    // itself be NULL) otherwise.
375    let mut compensation_exprs = HashMap::new();
376    if let Some(expr_map) = collected_count_expr_map {
377        // No session timezone: this builds a *searched* `CASE WHEN`, so the
378        // `CASE expr WHEN` comparison rule never applies, and the only type
379        // introduced is the untyped `Null` of the HAVING arm. The expressions
380        // themselves come from a plan `TypeCoercion` has already coerced.
381        let mut expr_rewrite = TypeCoercionRewriter::new(new_plan.schema());
382        let having_arm = pull_up
383            .pull_up_having_expr
384            .as_ref()
385            .map(|f| (not(f.clone()), lit(ScalarValue::Null)));
386        for (name, result) in expr_map {
387            if evaluates_to_null(result.clone(), result.column_refs())? {
388                // Aggregates whose empty-input value is NULL (max/min/sum/…)
389                // need no compensation: the LEFT JOIN already produces NULL
390                // for unmatched outer rows.
391                continue;
392            }
393
394            let indicator_col =
395                Column::new(Some(subquery_alias), UN_MATCHED_ROW_INDICATOR);
396            // Qualify with the subquery alias to avoid ambiguity when the
397            // outer table has a column with the same name as the aggregate.
398            let value_col = Column::new(Some(subquery_alias), name);
399
400            let mut builder = when(Expr::Column(indicator_col).is_null(), result);
401            if let Some((when_expr, then_expr)) = &having_arm {
402                builder = builder.when(when_expr.clone(), then_expr.clone());
403            }
404            let compensation_expr = builder.otherwise(Expr::Column(value_col.clone()))?;
405            compensation_exprs.insert(
406                value_col,
407                compensation_expr.rewrite(&mut expr_rewrite).data()?,
408            );
409        }
410    }
411
412    Ok(Some((new_plan, compensation_exprs)))
413}
414
415#[cfg(test)]
416mod tests {
417    use std::ops::Add;
418
419    use super::*;
420    use crate::test::*;
421
422    use arrow::datatypes::DataType;
423    use datafusion_expr::test::function_stub::sum;
424
425    use crate::assert_optimized_plan_eq_display_indent_snapshot;
426    use datafusion_expr::{Between, col, expr, out_ref_col, rollup, scalar_subquery};
427    use datafusion_functions_aggregate::min_max::{max, min};
428
429    macro_rules! assert_optimized_plan_equal {
430        (
431            $plan:expr,
432            @ $expected:literal $(,)?
433        ) => {{
434            let rule: Arc<dyn crate::OptimizerRule + Send + Sync> = Arc::new(ScalarSubqueryToJoin::new());
435            assert_optimized_plan_eq_display_indent_snapshot!(
436                rule,
437                $plan,
438                @ $expected,
439            )
440        }};
441    }
442
443    /// A correlated scalar subquery whose aggregate uses `ROLLUP` keeps its
444    /// correlation: the empty set yields a row for outer rows the filter matches
445    /// nothing for, and the join that would replace the filter cannot produce it.
446    /// <https://github.com/apache/datafusion/issues/25519>
447    #[test]
448    fn scalar_subquery_with_rollup_is_not_decorrelated() -> Result<()> {
449        let sq = Arc::new(
450            LogicalPlanBuilder::from(scan_tpch_table("orders"))
451                .filter(
452                    col("orders.o_custkey")
453                        .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
454                )?
455                .aggregate(
456                    vec![rollup(vec![col("orders.o_custkey")])],
457                    vec![max(col("orders.o_custkey"))],
458                )?
459                .project(vec![max(col("orders.o_custkey"))])?
460                .build()?,
461        );
462
463        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
464            .filter(col("customer.c_custkey").eq(scalar_subquery(sq)))?
465            .project(vec![col("customer.c_custkey")])?
466            .build()?;
467
468        assert_optimized_plan_equal!(
469            plan,
470            @r"
471        Projection: customer.c_custkey [c_custkey:Int64]
472          Filter: customer.c_custkey = (<subquery>) [c_custkey:Int64, c_name:Utf8]
473            Subquery: [max(orders.o_custkey):Int64;N]
474              Projection: max(orders.o_custkey) [max(orders.o_custkey):Int64;N]
475                Aggregate: groupBy=[[ROLLUP (orders.o_custkey)]], aggr=[[max(orders.o_custkey)]] [o_custkey:Int64;N, __grouping_id:UInt8, max(orders.o_custkey):Int64;N]
476                  Filter: orders.o_custkey = outer_ref(customer.c_custkey) [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
477                    TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
478            TableScan: customer [c_custkey:Int64, c_name:Utf8]
479        "
480        )
481    }
482
483    /// Test multiple correlated subqueries
484    #[test]
485    fn multiple_subqueries() -> Result<()> {
486        let orders = Arc::new(
487            LogicalPlanBuilder::from(scan_tpch_table("orders"))
488                .filter(
489                    col("orders.o_custkey")
490                        .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
491                )?
492                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
493                .project(vec![max(col("orders.o_custkey"))])?
494                .build()?,
495        );
496
497        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
498            .filter(
499                lit(1)
500                    .lt(scalar_subquery(Arc::clone(&orders)))
501                    .and(lit(1).lt(scalar_subquery(orders))),
502            )?
503            .project(vec![col("customer.c_custkey")])?
504            .build()?;
505
506        assert_optimized_plan_equal!(
507            plan,
508            @r"
509        Projection: customer.c_custkey [c_custkey:Int64]
510          Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
511            Filter: Int32(1) < __scalar_sq_1.max(orders.o_custkey) AND Int32(1) < __scalar_sq_2.max(orders.o_custkey) [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
512              Left Join:  Filter: __scalar_sq_2.o_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
513                Left Join:  Filter: __scalar_sq_1.o_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
514                  TableScan: customer [c_custkey:Int64, c_name:Utf8]
515                  SubqueryAlias: __scalar_sq_1 [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
516                    Projection: max(orders.o_custkey), orders.o_custkey, __always_true [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
517                      Aggregate: groupBy=[[orders.o_custkey, Boolean(true) AS __always_true]], aggr=[[max(orders.o_custkey)]] [o_custkey:Int64, __always_true:Boolean, max(orders.o_custkey):Int64;N]
518                        TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
519                SubqueryAlias: __scalar_sq_2 [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
520                  Projection: max(orders.o_custkey), orders.o_custkey, __always_true [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
521                    Aggregate: groupBy=[[orders.o_custkey, Boolean(true) AS __always_true]], aggr=[[max(orders.o_custkey)]] [o_custkey:Int64, __always_true:Boolean, max(orders.o_custkey):Int64;N]
522                      TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
523        "
524        )
525    }
526
527    /// Test recursive correlated subqueries
528    #[test]
529    fn recursive_subqueries() -> Result<()> {
530        let lineitem = Arc::new(
531            LogicalPlanBuilder::from(scan_tpch_table("lineitem"))
532                .filter(
533                    col("lineitem.l_orderkey")
534                        .eq(out_ref_col(DataType::Int64, "orders.o_orderkey")),
535                )?
536                .aggregate(
537                    Vec::<Expr>::new(),
538                    vec![sum(col("lineitem.l_extendedprice"))],
539                )?
540                .project(vec![sum(col("lineitem.l_extendedprice"))])?
541                .build()?,
542        );
543
544        let orders = Arc::new(
545            LogicalPlanBuilder::from(scan_tpch_table("orders"))
546                .filter(
547                    col("orders.o_custkey")
548                        .eq(out_ref_col(DataType::Int64, "customer.c_custkey"))
549                        .and(col("orders.o_totalprice").lt(scalar_subquery(lineitem))),
550                )?
551                .aggregate(Vec::<Expr>::new(), vec![sum(col("orders.o_totalprice"))])?
552                .project(vec![sum(col("orders.o_totalprice"))])?
553                .build()?,
554        );
555
556        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
557            .filter(col("customer.c_acctbal").lt(scalar_subquery(orders)))?
558            .project(vec![col("customer.c_custkey")])?
559            .build()?;
560
561        assert_optimized_plan_equal!(
562            plan,
563            @r"
564        Projection: customer.c_custkey [c_custkey:Int64]
565          Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
566            Filter: customer.c_acctbal < __scalar_sq_1.sum(orders.o_totalprice) [c_custkey:Int64, c_name:Utf8, sum(orders.o_totalprice):Float64;N, o_custkey:Int64;N, __always_true:Boolean;N]
567              Left Join:  Filter: __scalar_sq_1.o_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8, sum(orders.o_totalprice):Float64;N, o_custkey:Int64;N, __always_true:Boolean;N]
568                TableScan: customer [c_custkey:Int64, c_name:Utf8]
569                SubqueryAlias: __scalar_sq_1 [sum(orders.o_totalprice):Float64;N, o_custkey:Int64, __always_true:Boolean]
570                  Projection: sum(orders.o_totalprice), orders.o_custkey, __always_true [sum(orders.o_totalprice):Float64;N, o_custkey:Int64, __always_true:Boolean]
571                    Aggregate: groupBy=[[orders.o_custkey, Boolean(true) AS __always_true]], aggr=[[sum(orders.o_totalprice)]] [o_custkey:Int64, __always_true:Boolean, sum(orders.o_totalprice):Float64;N]
572                      Projection: orders.o_orderkey, orders.o_custkey, orders.o_orderstatus, orders.o_totalprice [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
573                        Filter: orders.o_totalprice < __scalar_sq_2.sum(lineitem.l_extendedprice) [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N, sum(lineitem.l_extendedprice):Float64;N, l_orderkey:Int64;N, __always_true:Boolean;N]
574                          Left Join:  Filter: __scalar_sq_2.l_orderkey = orders.o_orderkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N, sum(lineitem.l_extendedprice):Float64;N, l_orderkey:Int64;N, __always_true:Boolean;N]
575                            TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
576                            SubqueryAlias: __scalar_sq_2 [sum(lineitem.l_extendedprice):Float64;N, l_orderkey:Int64, __always_true:Boolean]
577                              Projection: sum(lineitem.l_extendedprice), lineitem.l_orderkey, __always_true [sum(lineitem.l_extendedprice):Float64;N, l_orderkey:Int64, __always_true:Boolean]
578                                Aggregate: groupBy=[[lineitem.l_orderkey, Boolean(true) AS __always_true]], aggr=[[sum(lineitem.l_extendedprice)]] [l_orderkey:Int64, __always_true:Boolean, sum(lineitem.l_extendedprice):Float64;N]
579                                  TableScan: lineitem [l_orderkey:Int64, l_partkey:Int64, l_suppkey:Int64, l_linenumber:Int32, l_quantity:Float64, l_extendedprice:Float64]
580        "
581        )
582    }
583
584    /// Test for correlated scalar subquery filter with additional subquery filters
585    #[test]
586    fn scalar_subquery_with_subquery_filters() -> Result<()> {
587        let sq = Arc::new(
588            LogicalPlanBuilder::from(scan_tpch_table("orders"))
589                .filter(
590                    out_ref_col(DataType::Int64, "customer.c_custkey")
591                        .eq(col("orders.o_custkey"))
592                        .and(col("o_orderkey").eq(lit(1))),
593                )?
594                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
595                .project(vec![max(col("orders.o_custkey"))])?
596                .build()?,
597        );
598
599        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
600            .filter(col("customer.c_custkey").eq(scalar_subquery(sq)))?
601            .project(vec![col("customer.c_custkey")])?
602            .build()?;
603
604        assert_optimized_plan_equal!(
605            plan,
606            @r"
607        Projection: customer.c_custkey [c_custkey:Int64]
608          Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
609            Filter: customer.c_custkey = __scalar_sq_1.max(orders.o_custkey) [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
610              Left Join:  Filter: customer.c_custkey = __scalar_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
611                TableScan: customer [c_custkey:Int64, c_name:Utf8]
612                SubqueryAlias: __scalar_sq_1 [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
613                  Projection: max(orders.o_custkey), orders.o_custkey, __always_true [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
614                    Aggregate: groupBy=[[orders.o_custkey, Boolean(true) AS __always_true]], aggr=[[max(orders.o_custkey)]] [o_custkey:Int64, __always_true:Boolean, max(orders.o_custkey):Int64;N]
615                      Filter: orders.o_orderkey = Int32(1) [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
616                        TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
617        "
618        )
619    }
620
621    /// Test for correlated scalar subquery with no columns in schema
622    #[test]
623    fn scalar_subquery_no_cols() -> Result<()> {
624        let sq = Arc::new(
625            LogicalPlanBuilder::from(scan_tpch_table("orders"))
626                .filter(
627                    out_ref_col(DataType::Int64, "customer.c_custkey")
628                        .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
629                )?
630                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
631                .project(vec![max(col("orders.o_custkey"))])?
632                .build()?,
633        );
634
635        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
636            .filter(col("customer.c_custkey").eq(scalar_subquery(sq)))?
637            .project(vec![col("customer.c_custkey")])?
638            .build()?;
639
640        // it will optimize, but fail for the same reason the unoptimized query would
641        assert_optimized_plan_equal!(
642            plan,
643            @r"
644        Projection: customer.c_custkey [c_custkey:Int64]
645          Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
646            Filter: customer.c_custkey = __scalar_sq_1.max(orders.o_custkey) [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N]
647              Left Join:  Filter: Boolean(true) [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N]
648                TableScan: customer [c_custkey:Int64, c_name:Utf8]
649                SubqueryAlias: __scalar_sq_1 [max(orders.o_custkey):Int64;N]
650                  Projection: max(orders.o_custkey) [max(orders.o_custkey):Int64;N]
651                    Aggregate: groupBy=[[]], aggr=[[max(orders.o_custkey)]] [max(orders.o_custkey):Int64;N]
652                      TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
653        "
654        )
655    }
656
657    /// Test for scalar subquery with both columns in schema
658    #[test]
659    fn scalar_subquery_with_no_correlated_cols() -> Result<()> {
660        let sq = Arc::new(
661            LogicalPlanBuilder::from(scan_tpch_table("orders"))
662                .filter(col("orders.o_custkey").eq(col("orders.o_custkey")))?
663                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
664                .project(vec![max(col("orders.o_custkey"))])?
665                .build()?,
666        );
667
668        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
669            .filter(col("customer.c_custkey").eq(scalar_subquery(sq)))?
670            .project(vec![col("customer.c_custkey")])?
671            .build()?;
672
673        assert_optimized_plan_equal!(
674            plan,
675            @r"
676        Projection: customer.c_custkey [c_custkey:Int64]
677          Filter: customer.c_custkey = (<subquery>) [c_custkey:Int64, c_name:Utf8]
678            Subquery: [max(orders.o_custkey):Int64;N]
679              Projection: max(orders.o_custkey) [max(orders.o_custkey):Int64;N]
680                Aggregate: groupBy=[[]], aggr=[[max(orders.o_custkey)]] [max(orders.o_custkey):Int64;N]
681                  Filter: orders.o_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
682                    TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
683            TableScan: customer [c_custkey:Int64, c_name:Utf8]
684        "
685        )
686    }
687
688    /// Test for correlated scalar subquery not equal
689    #[test]
690    fn scalar_subquery_where_not_eq() -> Result<()> {
691        let sq = Arc::new(
692            LogicalPlanBuilder::from(scan_tpch_table("orders"))
693                .filter(
694                    out_ref_col(DataType::Int64, "customer.c_custkey")
695                        .not_eq(col("orders.o_custkey")),
696                )?
697                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
698                .project(vec![max(col("orders.o_custkey"))])?
699                .build()?,
700        );
701
702        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
703            .filter(col("customer.c_custkey").eq(scalar_subquery(sq)))?
704            .project(vec![col("customer.c_custkey")])?
705            .build()?;
706
707        // Unsupported predicate, subquery should not be decorrelated
708        assert_optimized_plan_equal!(
709            plan,
710            @r"
711        Projection: customer.c_custkey [c_custkey:Int64]
712          Filter: customer.c_custkey = (<subquery>) [c_custkey:Int64, c_name:Utf8]
713            Subquery: [max(orders.o_custkey):Int64;N]
714              Projection: max(orders.o_custkey) [max(orders.o_custkey):Int64;N]
715                Aggregate: groupBy=[[]], aggr=[[max(orders.o_custkey)]] [max(orders.o_custkey):Int64;N]
716                  Filter: outer_ref(customer.c_custkey) != orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
717                    TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
718            TableScan: customer [c_custkey:Int64, c_name:Utf8]
719        "
720        )
721    }
722
723    /// Test for correlated scalar subquery less than
724    #[test]
725    fn scalar_subquery_where_less_than() -> Result<()> {
726        let sq = Arc::new(
727            LogicalPlanBuilder::from(scan_tpch_table("orders"))
728                .filter(
729                    out_ref_col(DataType::Int64, "customer.c_custkey")
730                        .lt(col("orders.o_custkey")),
731                )?
732                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
733                .project(vec![max(col("orders.o_custkey"))])?
734                .build()?,
735        );
736
737        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
738            .filter(col("customer.c_custkey").eq(scalar_subquery(sq)))?
739            .project(vec![col("customer.c_custkey")])?
740            .build()?;
741
742        // Unsupported predicate, subquery should not be decorrelated
743        assert_optimized_plan_equal!(
744            plan,
745            @r"
746        Projection: customer.c_custkey [c_custkey:Int64]
747          Filter: customer.c_custkey = (<subquery>) [c_custkey:Int64, c_name:Utf8]
748            Subquery: [max(orders.o_custkey):Int64;N]
749              Projection: max(orders.o_custkey) [max(orders.o_custkey):Int64;N]
750                Aggregate: groupBy=[[]], aggr=[[max(orders.o_custkey)]] [max(orders.o_custkey):Int64;N]
751                  Filter: outer_ref(customer.c_custkey) < orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
752                    TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
753            TableScan: customer [c_custkey:Int64, c_name:Utf8]
754        "
755        )
756    }
757
758    /// Test for correlated scalar subquery filter with subquery disjunction
759    #[test]
760    fn scalar_subquery_with_subquery_disjunction() -> Result<()> {
761        let sq = Arc::new(
762            LogicalPlanBuilder::from(scan_tpch_table("orders"))
763                .filter(
764                    out_ref_col(DataType::Int64, "customer.c_custkey")
765                        .eq(col("orders.o_custkey"))
766                        .or(col("o_orderkey").eq(lit(1))),
767                )?
768                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
769                .project(vec![max(col("orders.o_custkey"))])?
770                .build()?,
771        );
772
773        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
774            .filter(col("customer.c_custkey").eq(scalar_subquery(sq)))?
775            .project(vec![col("customer.c_custkey")])?
776            .build()?;
777
778        // Unsupported predicate, subquery should not be decorrelated
779        assert_optimized_plan_equal!(
780            plan,
781            @r"
782        Projection: customer.c_custkey [c_custkey:Int64]
783          Filter: customer.c_custkey = (<subquery>) [c_custkey:Int64, c_name:Utf8]
784            Subquery: [max(orders.o_custkey):Int64;N]
785              Projection: max(orders.o_custkey) [max(orders.o_custkey):Int64;N]
786                Aggregate: groupBy=[[]], aggr=[[max(orders.o_custkey)]] [max(orders.o_custkey):Int64;N]
787                  Filter: outer_ref(customer.c_custkey) = orders.o_custkey OR orders.o_orderkey = Int32(1) [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
788                    TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
789            TableScan: customer [c_custkey:Int64, c_name:Utf8]
790        "
791        )
792    }
793
794    /// Test for correlated scalar without projection
795    #[test]
796    fn scalar_subquery_no_projection() -> Result<()> {
797        let sq = Arc::new(
798            LogicalPlanBuilder::from(scan_tpch_table("orders"))
799                .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?
800                .build()?,
801        );
802
803        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
804            .filter(col("customer.c_custkey").eq(scalar_subquery(sq)))?
805            .project(vec![col("customer.c_custkey")])?
806            .build()?;
807
808        let expected = "Error during planning: Scalar subquery should only return one column, but found 4: orders.o_orderkey, orders.o_custkey, orders.o_orderstatus, orders.o_totalprice";
809        assert_analyzer_check_err(vec![], plan, expected);
810        Ok(())
811    }
812
813    /// Test for correlated scalar expressions
814    #[test]
815    fn scalar_subquery_project_expr() -> Result<()> {
816        let sq = Arc::new(
817            LogicalPlanBuilder::from(scan_tpch_table("orders"))
818                .filter(
819                    out_ref_col(DataType::Int64, "customer.c_custkey")
820                        .eq(col("orders.o_custkey")),
821                )?
822                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
823                .project(vec![col("max(orders.o_custkey)").add(lit(1))])?
824                .build()?,
825        );
826
827        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
828            .filter(col("customer.c_custkey").eq(scalar_subquery(sq)))?
829            .project(vec![col("customer.c_custkey")])?
830            .build()?;
831
832        assert_optimized_plan_equal!(
833            plan,
834            @r"
835        Projection: customer.c_custkey [c_custkey:Int64]
836          Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
837            Filter: customer.c_custkey = __scalar_sq_1.max(orders.o_custkey) + Int32(1) [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey) + Int32(1):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
838              Left Join:  Filter: customer.c_custkey = __scalar_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey) + Int32(1):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
839                TableScan: customer [c_custkey:Int64, c_name:Utf8]
840                SubqueryAlias: __scalar_sq_1 [max(orders.o_custkey) + Int32(1):Int64;N, o_custkey:Int64, __always_true:Boolean]
841                  Projection: max(orders.o_custkey) + Int32(1), orders.o_custkey, __always_true [max(orders.o_custkey) + Int32(1):Int64;N, o_custkey:Int64, __always_true:Boolean]
842                    Aggregate: groupBy=[[orders.o_custkey, Boolean(true) AS __always_true]], aggr=[[max(orders.o_custkey)]] [o_custkey:Int64, __always_true:Boolean, max(orders.o_custkey):Int64;N]
843                      TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
844        "
845        )
846    }
847
848    /// Test for correlated scalar subquery with non-strong project
849    #[test]
850    fn scalar_subquery_with_non_strong_project() -> Result<()> {
851        let case = Expr::Case(expr::Case {
852            expr: None,
853            when_then_expr: vec![(
854                Box::new(col("max(orders.o_totalprice)")),
855                Box::new(lit("a")),
856            )],
857            else_expr: Some(Box::new(lit("b"))),
858        });
859
860        let sq = Arc::new(
861            LogicalPlanBuilder::from(scan_tpch_table("orders"))
862                .filter(
863                    out_ref_col(DataType::Int64, "customer.c_custkey")
864                        .eq(col("orders.o_custkey")),
865                )?
866                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_totalprice"))])?
867                .project(vec![case])?
868                .build()?,
869        );
870
871        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
872            .project(vec![col("customer.c_custkey"), scalar_subquery(sq)])?
873            .build()?;
874
875        assert_optimized_plan_equal!(
876            plan,
877            @r#"
878        Projection: customer.c_custkey, CASE WHEN __scalar_sq_1.__always_true IS NULL THEN CASE WHEN CAST(Float64(NULL) AS Boolean) THEN Utf8("a") ELSE Utf8("b") END ELSE __scalar_sq_1.CASE WHEN max(orders.o_totalprice) THEN Utf8("a") ELSE Utf8("b") END END AS CASE WHEN max(orders.o_totalprice) THEN Utf8("a") ELSE Utf8("b") END [c_custkey:Int64, CASE WHEN max(orders.o_totalprice) THEN Utf8("a") ELSE Utf8("b") END:Utf8;N]
879          Left Join:  Filter: customer.c_custkey = __scalar_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8, CASE WHEN max(orders.o_totalprice) THEN Utf8("a") ELSE Utf8("b") END:Utf8;N, o_custkey:Int64;N, __always_true:Boolean;N]
880            TableScan: customer [c_custkey:Int64, c_name:Utf8]
881            SubqueryAlias: __scalar_sq_1 [CASE WHEN max(orders.o_totalprice) THEN Utf8("a") ELSE Utf8("b") END:Utf8, o_custkey:Int64, __always_true:Boolean]
882              Projection: CASE WHEN max(orders.o_totalprice) THEN Utf8("a") ELSE Utf8("b") END, orders.o_custkey, __always_true [CASE WHEN max(orders.o_totalprice) THEN Utf8("a") ELSE Utf8("b") END:Utf8, o_custkey:Int64, __always_true:Boolean]
883                Aggregate: groupBy=[[orders.o_custkey, Boolean(true) AS __always_true]], aggr=[[max(orders.o_totalprice)]] [o_custkey:Int64, __always_true:Boolean, max(orders.o_totalprice):Float64;N]
884                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
885        "#
886        )
887    }
888
889    /// Test for correlated scalar subquery multiple projected columns
890    #[test]
891    fn scalar_subquery_multi_col() -> Result<()> {
892        let sq = Arc::new(
893            LogicalPlanBuilder::from(scan_tpch_table("orders"))
894                .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?
895                .project(vec![col("orders.o_custkey"), col("orders.o_orderkey")])?
896                .build()?,
897        );
898
899        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
900            .filter(
901                col("customer.c_custkey")
902                    .eq(scalar_subquery(sq))
903                    .and(col("c_custkey").eq(lit(1))),
904            )?
905            .project(vec![col("customer.c_custkey")])?
906            .build()?;
907
908        let expected = "Error during planning: Scalar subquery should only return one column, but found 2: orders.o_custkey, orders.o_orderkey";
909        assert_analyzer_check_err(vec![], plan, expected);
910        Ok(())
911    }
912
913    /// Test for correlated scalar subquery filter with additional filters
914    #[test]
915    fn scalar_subquery_additional_filters_with_non_equal_clause() -> Result<()> {
916        let sq = Arc::new(
917            LogicalPlanBuilder::from(scan_tpch_table("orders"))
918                .filter(
919                    out_ref_col(DataType::Int64, "customer.c_custkey")
920                        .eq(col("orders.o_custkey")),
921                )?
922                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
923                .project(vec![max(col("orders.o_custkey"))])?
924                .build()?,
925        );
926
927        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
928            .filter(
929                col("customer.c_custkey")
930                    .gt_eq(scalar_subquery(sq))
931                    .and(col("c_custkey").eq(lit(1))),
932            )?
933            .project(vec![col("customer.c_custkey")])?
934            .build()?;
935
936        assert_optimized_plan_equal!(
937            plan,
938            @r"
939        Projection: customer.c_custkey [c_custkey:Int64]
940          Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
941            Filter: customer.c_custkey >= __scalar_sq_1.max(orders.o_custkey) AND customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
942              Left Join:  Filter: customer.c_custkey = __scalar_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
943                TableScan: customer [c_custkey:Int64, c_name:Utf8]
944                SubqueryAlias: __scalar_sq_1 [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
945                  Projection: max(orders.o_custkey), orders.o_custkey, __always_true [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
946                    Aggregate: groupBy=[[orders.o_custkey, Boolean(true) AS __always_true]], aggr=[[max(orders.o_custkey)]] [o_custkey:Int64, __always_true:Boolean, max(orders.o_custkey):Int64;N]
947                      TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
948        "
949        )
950    }
951
952    #[test]
953    fn scalar_subquery_additional_filters_with_equal_clause() -> Result<()> {
954        let sq = Arc::new(
955            LogicalPlanBuilder::from(scan_tpch_table("orders"))
956                .filter(
957                    out_ref_col(DataType::Int64, "customer.c_custkey")
958                        .eq(col("orders.o_custkey")),
959                )?
960                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
961                .project(vec![max(col("orders.o_custkey"))])?
962                .build()?,
963        );
964
965        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
966            .filter(
967                col("customer.c_custkey")
968                    .eq(scalar_subquery(sq))
969                    .and(col("c_custkey").eq(lit(1))),
970            )?
971            .project(vec![col("customer.c_custkey")])?
972            .build()?;
973
974        assert_optimized_plan_equal!(
975            plan,
976            @r"
977        Projection: customer.c_custkey [c_custkey:Int64]
978          Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
979            Filter: customer.c_custkey = __scalar_sq_1.max(orders.o_custkey) AND customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
980              Left Join:  Filter: customer.c_custkey = __scalar_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
981                TableScan: customer [c_custkey:Int64, c_name:Utf8]
982                SubqueryAlias: __scalar_sq_1 [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
983                  Projection: max(orders.o_custkey), orders.o_custkey, __always_true [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
984                    Aggregate: groupBy=[[orders.o_custkey, Boolean(true) AS __always_true]], aggr=[[max(orders.o_custkey)]] [o_custkey:Int64, __always_true:Boolean, max(orders.o_custkey):Int64;N]
985                      TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
986        "
987        )
988    }
989
990    /// Test for correlated scalar subquery filter with disjunctions
991    #[test]
992    fn scalar_subquery_disjunction() -> Result<()> {
993        let sq = Arc::new(
994            LogicalPlanBuilder::from(scan_tpch_table("orders"))
995                .filter(
996                    out_ref_col(DataType::Int64, "customer.c_custkey")
997                        .eq(col("orders.o_custkey")),
998                )?
999                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
1000                .project(vec![max(col("orders.o_custkey"))])?
1001                .build()?,
1002        );
1003
1004        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1005            .filter(
1006                col("customer.c_custkey")
1007                    .eq(scalar_subquery(sq))
1008                    .or(col("customer.c_custkey").eq(lit(1))),
1009            )?
1010            .project(vec![col("customer.c_custkey")])?
1011            .build()?;
1012
1013        assert_optimized_plan_equal!(
1014            plan,
1015            @r"
1016        Projection: customer.c_custkey [c_custkey:Int64]
1017          Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
1018            Filter: customer.c_custkey = __scalar_sq_1.max(orders.o_custkey) OR customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
1019              Left Join:  Filter: customer.c_custkey = __scalar_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
1020                TableScan: customer [c_custkey:Int64, c_name:Utf8]
1021                SubqueryAlias: __scalar_sq_1 [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
1022                  Projection: max(orders.o_custkey), orders.o_custkey, __always_true [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
1023                    Aggregate: groupBy=[[orders.o_custkey, Boolean(true) AS __always_true]], aggr=[[max(orders.o_custkey)]] [o_custkey:Int64, __always_true:Boolean, max(orders.o_custkey):Int64;N]
1024                      TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1025        "
1026        )
1027    }
1028
1029    /// Test for correlated scalar subquery filter
1030    #[test]
1031    fn exists_subquery_correlated() -> Result<()> {
1032        let sq = Arc::new(
1033            LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
1034                .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?
1035                .aggregate(Vec::<Expr>::new(), vec![min(col("c"))])?
1036                .project(vec![min(col("c"))])?
1037                .build()?,
1038        );
1039
1040        let plan = LogicalPlanBuilder::from(test_table_scan_with_name("test")?)
1041            .filter(col("test.c").lt(scalar_subquery(sq)))?
1042            .project(vec![col("test.c")])?
1043            .build()?;
1044
1045        assert_optimized_plan_equal!(
1046            plan,
1047            @r"
1048        Projection: test.c [c:UInt32]
1049          Projection: test.a, test.b, test.c [a:UInt32, b:UInt32, c:UInt32]
1050            Filter: test.c < __scalar_sq_1.min(sq.c) [a:UInt32, b:UInt32, c:UInt32, min(sq.c):UInt32;N, a:UInt32;N, __always_true:Boolean;N]
1051              Left Join:  Filter: test.a = __scalar_sq_1.a [a:UInt32, b:UInt32, c:UInt32, min(sq.c):UInt32;N, a:UInt32;N, __always_true:Boolean;N]
1052                TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1053                SubqueryAlias: __scalar_sq_1 [min(sq.c):UInt32;N, a:UInt32, __always_true:Boolean]
1054                  Projection: min(sq.c), sq.a, __always_true [min(sq.c):UInt32;N, a:UInt32, __always_true:Boolean]
1055                    Aggregate: groupBy=[[sq.a, Boolean(true) AS __always_true]], aggr=[[min(sq.c)]] [a:UInt32, __always_true:Boolean, min(sq.c):UInt32;N]
1056                      TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
1057        "
1058        )
1059    }
1060
1061    /// Test for non-correlated scalar subquery with no filters
1062    #[test]
1063    fn scalar_subquery_non_correlated_no_filters_with_non_equal_clause() -> Result<()> {
1064        let sq = Arc::new(
1065            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1066                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
1067                .project(vec![max(col("orders.o_custkey"))])?
1068                .build()?,
1069        );
1070
1071        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1072            .filter(col("customer.c_custkey").lt(scalar_subquery(sq)))?
1073            .project(vec![col("customer.c_custkey")])?
1074            .build()?;
1075
1076        assert_optimized_plan_equal!(
1077            plan,
1078            @r"
1079        Projection: customer.c_custkey [c_custkey:Int64]
1080          Filter: customer.c_custkey < (<subquery>) [c_custkey:Int64, c_name:Utf8]
1081            Subquery: [max(orders.o_custkey):Int64;N]
1082              Projection: max(orders.o_custkey) [max(orders.o_custkey):Int64;N]
1083                Aggregate: groupBy=[[]], aggr=[[max(orders.o_custkey)]] [max(orders.o_custkey):Int64;N]
1084                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1085            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1086        "
1087        )
1088    }
1089
1090    #[test]
1091    fn scalar_subquery_non_correlated_no_filters_with_equal_clause() -> Result<()> {
1092        let sq = Arc::new(
1093            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1094                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
1095                .project(vec![max(col("orders.o_custkey"))])?
1096                .build()?,
1097        );
1098
1099        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1100            .filter(col("customer.c_custkey").eq(scalar_subquery(sq)))?
1101            .project(vec![col("customer.c_custkey")])?
1102            .build()?;
1103
1104        assert_optimized_plan_equal!(
1105            plan,
1106            @r"
1107        Projection: customer.c_custkey [c_custkey:Int64]
1108          Filter: customer.c_custkey = (<subquery>) [c_custkey:Int64, c_name:Utf8]
1109            Subquery: [max(orders.o_custkey):Int64;N]
1110              Projection: max(orders.o_custkey) [max(orders.o_custkey):Int64;N]
1111                Aggregate: groupBy=[[]], aggr=[[max(orders.o_custkey)]] [max(orders.o_custkey):Int64;N]
1112                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1113            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1114        "
1115        )
1116    }
1117
1118    #[test]
1119    fn correlated_scalar_subquery_in_between_clause() -> Result<()> {
1120        let sq1 = Arc::new(
1121            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1122                .filter(
1123                    out_ref_col(DataType::Int64, "customer.c_custkey")
1124                        .eq(col("orders.o_custkey")),
1125                )?
1126                .aggregate(Vec::<Expr>::new(), vec![min(col("orders.o_custkey"))])?
1127                .project(vec![min(col("orders.o_custkey"))])?
1128                .build()?,
1129        );
1130        let sq2 = Arc::new(
1131            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1132                .filter(
1133                    out_ref_col(DataType::Int64, "customer.c_custkey")
1134                        .eq(col("orders.o_custkey")),
1135                )?
1136                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
1137                .project(vec![max(col("orders.o_custkey"))])?
1138                .build()?,
1139        );
1140
1141        let between_expr = Expr::Between(Between {
1142            expr: Box::new(col("customer.c_custkey")),
1143            negated: false,
1144            low: Box::new(scalar_subquery(sq1)),
1145            high: Box::new(scalar_subquery(sq2)),
1146        });
1147
1148        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1149            .filter(between_expr)?
1150            .project(vec![col("customer.c_custkey")])?
1151            .build()?;
1152
1153        assert_optimized_plan_equal!(
1154            plan,
1155            @r"
1156        Projection: customer.c_custkey [c_custkey:Int64]
1157          Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
1158            Filter: customer.c_custkey BETWEEN __scalar_sq_1.min(orders.o_custkey) AND __scalar_sq_2.max(orders.o_custkey) [c_custkey:Int64, c_name:Utf8, min(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
1159              Left Join:  Filter: customer.c_custkey = __scalar_sq_2.o_custkey [c_custkey:Int64, c_name:Utf8, min(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N, max(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
1160                Left Join:  Filter: customer.c_custkey = __scalar_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8, min(orders.o_custkey):Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
1161                  TableScan: customer [c_custkey:Int64, c_name:Utf8]
1162                  SubqueryAlias: __scalar_sq_1 [min(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
1163                    Projection: min(orders.o_custkey), orders.o_custkey, __always_true [min(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
1164                      Aggregate: groupBy=[[orders.o_custkey, Boolean(true) AS __always_true]], aggr=[[min(orders.o_custkey)]] [o_custkey:Int64, __always_true:Boolean, min(orders.o_custkey):Int64;N]
1165                        TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1166                SubqueryAlias: __scalar_sq_2 [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
1167                  Projection: max(orders.o_custkey), orders.o_custkey, __always_true [max(orders.o_custkey):Int64;N, o_custkey:Int64, __always_true:Boolean]
1168                    Aggregate: groupBy=[[orders.o_custkey, Boolean(true) AS __always_true]], aggr=[[max(orders.o_custkey)]] [o_custkey:Int64, __always_true:Boolean, max(orders.o_custkey):Int64;N]
1169                      TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1170        "
1171        )
1172    }
1173
1174    #[test]
1175    fn uncorrelated_scalar_subquery_in_between_clause() -> Result<()> {
1176        let sq1 = Arc::new(
1177            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1178                .aggregate(Vec::<Expr>::new(), vec![min(col("orders.o_custkey"))])?
1179                .project(vec![min(col("orders.o_custkey"))])?
1180                .build()?,
1181        );
1182        let sq2 = Arc::new(
1183            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1184                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
1185                .project(vec![max(col("orders.o_custkey"))])?
1186                .build()?,
1187        );
1188
1189        let between_expr = Expr::Between(Between {
1190            expr: Box::new(col("customer.c_custkey")),
1191            negated: false,
1192            low: Box::new(scalar_subquery(sq1)),
1193            high: Box::new(scalar_subquery(sq2)),
1194        });
1195
1196        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1197            .filter(between_expr)?
1198            .project(vec![col("customer.c_custkey")])?
1199            .build()?;
1200
1201        assert_optimized_plan_equal!(
1202            plan,
1203            @r"
1204        Projection: customer.c_custkey [c_custkey:Int64]
1205          Filter: customer.c_custkey BETWEEN (<subquery>) AND (<subquery>) [c_custkey:Int64, c_name:Utf8]
1206            Subquery: [min(orders.o_custkey):Int64;N]
1207              Projection: min(orders.o_custkey) [min(orders.o_custkey):Int64;N]
1208                Aggregate: groupBy=[[]], aggr=[[min(orders.o_custkey)]] [min(orders.o_custkey):Int64;N]
1209                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1210            Subquery: [max(orders.o_custkey):Int64;N]
1211              Projection: max(orders.o_custkey) [max(orders.o_custkey):Int64;N]
1212                Aggregate: groupBy=[[]], aggr=[[max(orders.o_custkey)]] [max(orders.o_custkey):Int64;N]
1213                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1214            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1215        "
1216        )
1217    }
1218
1219    #[test]
1220    fn uncorrelated_scalar_subquery_rewritten_when_flag_off() -> Result<()> {
1221        use datafusion_common::config::ConfigOptions;
1222
1223        let sq = Arc::new(
1224            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1225                .aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?
1226                .project(vec![max(col("orders.o_custkey"))])?
1227                .build()?,
1228        );
1229
1230        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1231            .filter(col("customer.c_custkey").eq(scalar_subquery(sq)))?
1232            .project(vec![col("customer.c_custkey")])?
1233            .build()?;
1234
1235        let mut options = ConfigOptions::default();
1236        options
1237            .optimizer
1238            .enable_physical_uncorrelated_scalar_subquery = false;
1239        let context = crate::OptimizerContext::new_with_config_options(Arc::new(options));
1240
1241        let rule: Arc<dyn OptimizerRule + Send + Sync> =
1242            Arc::new(ScalarSubqueryToJoin::new());
1243        let optimizer = crate::Optimizer::with_rules(vec![rule]);
1244        let optimized_plan = optimizer
1245            .optimize(plan, &context, |_, _| {})
1246            .expect("failed to optimize plan");
1247        let formatted_plan = optimized_plan.display_indent_schema();
1248
1249        insta::assert_snapshot!(
1250            formatted_plan,
1251            @r"
1252        Projection: customer.c_custkey [c_custkey:Int64]
1253          Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
1254            Filter: customer.c_custkey = __scalar_sq_1.max(orders.o_custkey) [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N]
1255              Left Join:  Filter: Boolean(true) [c_custkey:Int64, c_name:Utf8, max(orders.o_custkey):Int64;N]
1256                TableScan: customer [c_custkey:Int64, c_name:Utf8]
1257                SubqueryAlias: __scalar_sq_1 [max(orders.o_custkey):Int64;N]
1258                  Projection: max(orders.o_custkey) [max(orders.o_custkey):Int64;N]
1259                    Aggregate: groupBy=[[]], aggr=[[max(orders.o_custkey)]] [max(orders.o_custkey):Int64;N]
1260                      TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1261        "
1262        );
1263
1264        Ok(())
1265    }
1266
1267    #[test]
1268    fn correlated_scalar_subquery_filter_above_correlated_derived_table() -> Result<()> {
1269        let derived = LogicalPlanBuilder::from(scan_tpch_table("orders"))
1270            .filter(
1271                col("orders.o_custkey")
1272                    .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
1273            )?
1274            .aggregate(
1275                Vec::<Expr>::new(),
1276                vec![max(col("orders.o_custkey")).alias("n")],
1277            )?
1278            .project(vec![col("n")])?
1279            .alias("t")?
1280            .build()?;
1281
1282        let sq = Arc::new(
1283            LogicalPlanBuilder::from(derived)
1284                .filter(out_ref_col(DataType::Int64, "customer.c_custkey").gt(lit(0i64)))?
1285                .project(vec![col("t.n")])?
1286                .build()?,
1287        );
1288
1289        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1290            .project(vec![col("customer.c_custkey"), scalar_subquery(sq)])?
1291            .build()?;
1292
1293        assert_optimized_plan_equal!(
1294            plan,
1295            @r"
1296        Projection: customer.c_custkey, __scalar_sq_1.n AS n [c_custkey:Int64, n:Int64;N]
1297          Left Join:  Filter: __scalar_sq_1.o_custkey = customer.c_custkey AND customer.c_custkey > Int64(0) [c_custkey:Int64, c_name:Utf8, n:Int64;N, o_custkey:Int64;N, __always_true:Boolean;N]
1298            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1299            SubqueryAlias: __scalar_sq_1 [n:Int64;N, o_custkey:Int64, __always_true:Boolean]
1300              Projection: t.n, t.o_custkey, t.__always_true [n:Int64;N, o_custkey:Int64, __always_true:Boolean]
1301                SubqueryAlias: t [n:Int64;N, o_custkey:Int64, __always_true:Boolean]
1302                  Projection: n, orders.o_custkey, __always_true [n:Int64;N, o_custkey:Int64, __always_true:Boolean]
1303                    Aggregate: groupBy=[[orders.o_custkey, Boolean(true) AS __always_true]], aggr=[[max(orders.o_custkey) AS n]] [o_custkey:Int64, __always_true:Boolean, n:Int64;N]
1304                      TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1305        "
1306        )
1307    }
1308}