1use 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#[derive(Default, Debug)]
36pub struct ScalarSubqueryToJoin {}
37
38impl ScalarSubqueryToJoin {
39 #[expect(missing_docs)]
40 pub fn new() -> Self {
41 Self::default()
42 }
43
44 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 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 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 return Ok(Transformed::no(LogicalPlan::Filter(filter)));
130 }
131 }
132
133 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 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 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 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
235fn 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 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
292fn build_join(
330 subquery: &Subquery,
331 outer_input: &LogicalPlan,
332 subquery_alias: &str,
333) -> Result<Option<(LogicalPlan, HashMap<Column, Expr>)>> {
334 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 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 let mut compensation_exprs = HashMap::new();
376 if let Some(expr_map) = collected_count_expr_map {
377 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 continue;
392 }
393
394 let indicator_col =
395 Column::new(Some(subquery_alias), UN_MATCHED_ROW_INDICATOR);
396 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 #[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]
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]
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]
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]
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 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]
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]
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 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]
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 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]
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 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]
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]
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]
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]
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]
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]
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]
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]
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}