use std::collections::BTreeSet;
use std::ops::Deref;
use std::sync::Arc;
use crate::analyzer::type_coercion::TypeCoercionRewriter;
use crate::decorrelate::{
PullUpCorrelatedExpr, UN_MATCHED_ROW_INDICATOR, build_join_filter,
};
use crate::extract_equijoin_predicate::split_eq_and_noneq_join_predicate;
use crate::optimizer::ApplyOrder;
use crate::{OptimizerConfig, OptimizerRule};
use datafusion_common::alias::AliasGenerator;
use datafusion_common::tree_node::{
Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
};
use datafusion_common::{
Column, DFSchema, NullEquality, Result, ScalarValue, assert_or_internal_err,
internal_datafusion_err, internal_err, not_impl_err, plan_err,
};
use datafusion_expr::expr::{Exists, InSubquery, in_subquery_tuple_values};
use datafusion_expr::expr_rewriter::{
create_col_from_scalar_expr, strip_outer_reference,
};
use datafusion_expr::logical_plan::{JoinType, Subquery};
use datafusion_expr::utils::{conjunction, expr_to_columns, split_conjunction_owned};
use datafusion_expr::{
BinaryExpr, Expr, ExprSchemable, Filter, LogicalPlan, LogicalPlanBuilder, Operator,
exists, in_subquery, lit, not, not_exists, not_in_subquery, when,
};
use log::debug;
#[derive(Default, Debug)]
pub struct DecorrelatePredicateSubquery {}
impl DecorrelatePredicateSubquery {
#[expect(missing_docs)]
pub fn new() -> Self {
Self::default()
}
}
impl OptimizerRule for DecorrelatePredicateSubquery {
fn rewrite(
&self,
plan: LogicalPlan,
config: &dyn OptimizerConfig,
) -> Result<Transformed<LogicalPlan>> {
let plan = plan
.map_subqueries(|subquery| {
subquery.transform_down(|p| self.rewrite(p, config))
})?
.data;
if let LogicalPlan::Projection(projection) = plan {
if !projection.expr.iter().any(has_subquery) {
return Ok(Transformed::no(LogicalPlan::Projection(projection)));
}
let original_projection = projection.clone();
let mut cur_input = Arc::unwrap_or_clone(projection.input);
let mut rewritten_exprs = Vec::with_capacity(projection.expr.len());
for expr in projection.expr {
let original_name = expr.schema_name().to_string();
let (new_input, mut rewritten_expr) =
rewrite_inner_subqueries(cur_input, expr, config, true, true)?;
if has_subquery(&rewritten_expr) {
return Ok(Transformed::no(LogicalPlan::Projection(
original_projection,
)));
}
cur_input = new_input;
if rewritten_expr.schema_name().to_string() != original_name {
rewritten_expr = rewritten_expr.alias(original_name);
}
rewritten_exprs.push(rewritten_expr);
}
let new_plan = LogicalPlanBuilder::from(cur_input)
.project(rewritten_exprs)?
.build()?;
return Ok(Transformed::yes(new_plan));
}
let LogicalPlan::Filter(filter) = plan else {
return Ok(Transformed::no(plan));
};
if !has_subquery(&filter.predicate) {
return Ok(Transformed::no(LogicalPlan::Filter(filter)));
}
let (with_subqueries, mut other_exprs): (Vec<_>, Vec<_>) =
split_conjunction_owned(filter.predicate)
.into_iter()
.partition(has_subquery);
assert_or_internal_err!(
!with_subqueries.is_empty(),
"can not find expected subqueries in DecorrelatePredicateSubquery"
);
let mut cur_input = Arc::unwrap_or_clone(filter.input);
let original_schema = cur_input.schema().columns();
for subquery_expr in with_subqueries {
match extract_subquery_info(subquery_expr) {
SubqueryPredicate::Top(subquery) => {
match build_join_top(&subquery, &cur_input, config.alias_generator())?
{
Some(plan) => cur_input = plan,
None => match subquery.expr() {
expr @ Expr::InSubquery(InSubquery {
negated: true, ..
}) => {
let (plan, expr) = rewrite_inner_subqueries(
cur_input, expr, config, true, true,
)?;
cur_input = plan;
other_exprs.push(expr);
}
expr => other_exprs.push(expr),
},
}
}
SubqueryPredicate::Embedded(expr) => {
let (plan, expr_without_subqueries) =
rewrite_filter_subqueries(cur_input, expr, config)?;
cur_input = plan;
other_exprs.push(expr_without_subqueries);
}
}
}
let expr = conjunction(other_exprs);
if let Some(expr) = expr {
let new_filter = Filter::try_new(expr, Arc::new(cur_input))?;
cur_input = LogicalPlan::Filter(new_filter);
}
if cur_input.schema().fields().len() != original_schema.len() {
cur_input = LogicalPlanBuilder::from(cur_input)
.project(original_schema.into_iter().map(Expr::from))?
.build()?;
}
Ok(Transformed::yes(cur_input))
}
fn name(&self) -> &str {
"decorrelate_predicate_subquery"
}
fn apply_order(&self) -> Option<ApplyOrder> {
Some(ApplyOrder::TopDown)
}
}
fn rewrite_filter_subqueries(
outer: LogicalPlan,
expr: Expr,
config: &dyn OptimizerConfig,
) -> Result<(LogicalPlan, Expr)> {
match expr {
Expr::BinaryExpr(BinaryExpr {
left,
op: op @ (Operator::And | Operator::Or),
right,
}) => {
let (outer, left) = rewrite_filter_subqueries(outer, *left, config)?;
let (outer, right) = rewrite_filter_subqueries(outer, *right, config)?;
Ok((
outer,
Expr::BinaryExpr(BinaryExpr::new(Box::new(left), op, Box::new(right))),
))
}
Expr::InSubquery(in_subquery) => {
let needs_null_aware_mark =
in_subquery.negated || has_subquery(&in_subquery.expr);
rewrite_inner_subqueries(
outer,
Expr::InSubquery(in_subquery),
config,
false,
needs_null_aware_mark,
)
}
other => rewrite_inner_subqueries(outer, other, config, false, true),
}
}
fn rewrite_inner_subqueries(
outer: LogicalPlan,
expr: Expr,
config: &dyn OptimizerConfig,
materialize_in_value: bool,
needs_null_aware_mark: bool,
) -> Result<(LogicalPlan, Expr)> {
let mut cur_input = outer;
let alias = config.alias_generator();
let expr_without_subqueries = expr.transform(|e| match e {
Expr::Exists(Exists {
subquery: Subquery { subquery, .. },
negated,
}) => match mark_join(
&cur_input,
&subquery,
None,
negated,
alias,
needs_null_aware_mark,
)? {
Some(MarkJoin {
plan,
mark: exists_expr,
..
}) => {
cur_input = plan;
Ok(Transformed::yes(exists_expr))
}
None if negated => Ok(Transformed::no(not_exists(subquery))),
None => Ok(Transformed::no(exists(subquery))),
},
Expr::InSubquery(InSubquery {
expr,
subquery: Subquery { subquery, .. },
negated,
}) => {
let rewritten = if materialize_in_value {
in_subquery_value_mark_join(
&cur_input,
&subquery,
*expr.clone(),
negated,
alias,
)?
} else {
let in_predicate = subquery
.head_output_expr()?
.map_or(plan_err!("single expression required."), |output_expr| {
Ok(Expr::eq(*expr.clone(), output_expr))
})?;
mark_join(
&cur_input,
&subquery,
Some(&in_predicate),
negated,
alias,
needs_null_aware_mark,
)?
.map(|join| (join.plan, join.mark))
};
match rewritten {
Some((plan, exists_expr)) => {
cur_input = plan;
Ok(Transformed::yes(exists_expr))
}
None if negated => Ok(Transformed::no(not_in_subquery(*expr, subquery))),
None => Ok(Transformed::no(in_subquery(*expr, subquery))),
}
}
_ => Ok(Transformed::no(e)),
})?;
Ok((cur_input, expr_without_subqueries.data))
}
fn in_subquery_value_mark_join(
left: &LogicalPlan,
subquery: &LogicalPlan,
expr: Expr,
negated: bool,
alias: &Arc<AliasGenerator>,
) -> Result<Option<(LogicalPlan, Expr)>> {
let output_expr = subquery
.head_output_expr()?
.map_or(plan_err!("single expression required."), Ok)?;
let in_predicate = Expr::eq(expr.clone(), output_expr.clone());
let Some(MarkJoin {
plan: matched_plan,
mark: matched,
three_valued_exact,
}) = mark_join(left, subquery, Some(&in_predicate), false, alias, true)?
else {
return Ok(None);
};
if three_valued_exact {
return Ok(Some((
matched_plan,
if negated { not(matched) } else { matched },
)));
}
if in_subquery_tuple_values(&expr, subquery)?.is_some() {
return internal_err!(
"a multi-column IN subquery needs a three-valued exact mark join"
);
}
let null_subquery = LogicalPlanBuilder::from(subquery.clone())
.filter(output_expr.is_null())?
.build()?;
let Some(MarkJoin {
plan: null_plan,
mark: subquery_has_null,
..
}) = mark_join(&matched_plan, &null_subquery, None, false, alias, true)?
else {
return Ok(None);
};
let Some(MarkJoin {
plan: final_plan,
mark: subquery_non_empty,
..
}) = mark_join(&null_plan, subquery, None, false, alias, true)?
else {
return Ok(None);
};
let unknown = subquery_has_null.or(expr.is_null().and(subquery_non_empty));
let result = when(matched, lit(true))
.when(unknown, lit(ScalarValue::Boolean(None)))
.otherwise(lit(false))?;
Ok(Some((
final_plan,
if negated { not(result) } else { result },
)))
}
enum SubqueryPredicate {
Top(SubqueryInfo),
Embedded(Expr),
}
fn extract_subquery_info(expr: Expr) -> SubqueryPredicate {
match expr {
Expr::Not(not_expr) => match *not_expr {
Expr::InSubquery(InSubquery {
expr,
subquery,
negated,
}) => SubqueryPredicate::Top(SubqueryInfo::new_with_in_expr(
subquery, *expr, !negated,
)),
Expr::Exists(Exists { subquery, negated }) => {
SubqueryPredicate::Top(SubqueryInfo::new(subquery, !negated))
}
expr => SubqueryPredicate::Embedded(not(expr)),
},
Expr::InSubquery(InSubquery {
expr,
subquery,
negated,
}) => SubqueryPredicate::Top(SubqueryInfo::new_with_in_expr(
subquery, *expr, negated,
)),
Expr::Exists(Exists { subquery, negated }) => {
SubqueryPredicate::Top(SubqueryInfo::new(subquery, negated))
}
expr => SubqueryPredicate::Embedded(expr),
}
}
fn has_subquery(expr: &Expr) -> bool {
expr.exists(|e| match e {
Expr::InSubquery(_) | Expr::Exists(_) => Ok(true),
_ => Ok(false),
})
.unwrap()
}
fn build_join_top(
query_info: &SubqueryInfo,
left: &LogicalPlan,
alias: &Arc<AliasGenerator>,
) -> Result<Option<LogicalPlan>> {
let where_in_expr_opt = &query_info.where_in_expr;
let in_predicate_opt = where_in_expr_opt
.clone()
.map(|where_in_expr| {
query_info
.query
.subquery
.head_output_expr()?
.map_or(plan_err!("single expression required."), |expr| {
Ok(Expr::eq(where_in_expr, expr))
})
})
.map_or(Ok(None), |v| v.map(Some))?;
let join_type = match query_info.negated {
true => JoinType::LeftAnti,
false => JoinType::LeftSemi,
};
let subquery = query_info.query.subquery.as_ref();
let subquery_alias = alias.next("__correlated_sq");
Ok(build_join(
left,
subquery,
in_predicate_opt.as_ref(),
join_type,
&subquery_alias,
true,
)?
.map(|join| join.plan))
}
fn mark_join(
left: &LogicalPlan,
subquery: &LogicalPlan,
in_predicate_opt: Option<&Expr>,
negated: bool,
alias_generator: &Arc<AliasGenerator>,
needs_null_aware_mark: bool,
) -> Result<Option<MarkJoin>> {
let alias = alias_generator.next("__correlated_sq");
let exists_col = Expr::Column(Column::new(Some(alias.clone()), "mark"));
let exists_expr = if negated { !exists_col } else { exists_col };
Ok(build_join(
left,
subquery,
in_predicate_opt,
JoinType::LeftMark,
&alias,
needs_null_aware_mark,
)?
.map(|join| MarkJoin {
plan: join.plan,
mark: exists_expr,
three_valued_exact: join.mark_is_three_valued_exact,
}))
}
struct MarkJoin {
plan: LogicalPlan,
mark: Expr,
three_valued_exact: bool,
}
fn values_are_first_keys(
in_values: &[InValue],
join_filter: &Expr,
left_schema: &DFSchema,
right_schema: &DFSchema,
) -> Result<bool> {
let (equijoin_keys, _) = split_eq_and_noneq_join_predicate(
join_filter.clone(),
left_schema,
right_schema,
)?;
Ok(equijoin_keys.len() >= in_values.len()
&& equijoin_keys
.iter()
.zip(in_values)
.all(|((value, column), in_value)| {
value == &in_value.value && column == &in_value.subquery_column
}))
}
struct InValue {
value: Expr,
subquery_column: Expr,
value_as_written: Expr,
output_expr: Expr,
}
impl InValue {
fn may_be_null_in_scope(
&self,
left_schema: &DFSchema,
right_schema: &DFSchema,
scope_filters: &[Expr],
) -> Result<bool> {
Ok(key_may_be_null_in_scope(
self.value.nullable(left_schema)?,
&self.value_as_written,
true,
scope_filters,
) || key_may_be_null_in_scope(
self.subquery_column.nullable(right_schema)?,
&self.output_expr,
false,
scope_filters,
))
}
}
fn key_may_be_null_in_scope(
nullable: bool,
key: &Expr,
key_is_outer: bool,
scope_filters: &[Expr],
) -> bool {
if !nullable {
return false;
}
let key = strip_casts(key);
!scope_filters
.iter()
.any(|filter| filter_rejects_null(filter, key, key_is_outer))
}
fn filter_rejects_null(filter: &Expr, key: &Expr, key_is_outer: bool) -> bool {
let is_key = |side: &Expr| {
let side = strip_casts(side);
if key_is_outer {
side.contains_outer()
&& side.column_refs().is_empty()
&& &strip_outer_reference(side.clone()) == key
} else {
!side.contains_outer() && side == key
}
};
match filter {
Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
matches!(
op,
Operator::Eq
| Operator::NotEq
| Operator::Lt
| Operator::LtEq
| Operator::Gt
| Operator::GtEq
) && (is_key(left) || is_key(right))
}
Expr::IsNotNull(expr) => is_key(expr),
_ => false,
}
}
fn strip_casts(expr: &Expr) -> &Expr {
let mut expr = expr;
while let Expr::Cast(cast) = expr {
expr = cast.expr.as_ref();
}
expr
}
fn in_join_filter(in_values: &[InValue], correlation: Option<Expr>) -> Result<Expr> {
conjunction(
in_values
.iter()
.map(|in_value| {
Expr::eq(in_value.value.clone(), in_value.subquery_column.clone())
})
.chain(correlation),
)
.ok_or_else(|| internal_datafusion_err!("an `IN` predicate has at least one value"))
}
fn subquery_output_expr(subquery: &LogicalPlan, i: usize) -> Result<Expr> {
match subquery {
_ if i == 0 => subquery
.head_output_expr()?
.ok_or_else(|| internal_datafusion_err!("subquery has no output expression")),
LogicalPlan::Projection(projection) => Ok(projection.expr[i].clone()),
_ => Ok(Expr::Column(Column::from(
subquery.schema().qualified_field(i),
))),
}
}
fn with_null_aware_value_keys(
plan: LogicalPlan,
null_aware_value_keys: usize,
) -> Result<LogicalPlan> {
let LogicalPlan::Join(join) = plan else {
return internal_err!("expected a join, got {}", plan.display());
};
if !join.null_aware {
return Ok(LogicalPlan::Join(join));
}
Ok(LogicalPlan::Join(
join.with_null_aware_value_keys(null_aware_value_keys),
))
}
fn subquery_operands_are_bare_columns(
join_filters: &[Expr],
subquery_cols: &BTreeSet<Column>,
) -> bool {
join_filters.iter().all(|filter| {
let mut bare = true;
filter
.apply(|e| {
let refs = e.column_refs();
if !refs.is_empty()
&& !e.contains_outer()
&& refs.iter().all(|c| subquery_cols.contains(*c))
{
bare = matches!(e, Expr::Column(_));
return Ok(if bare {
TreeNodeRecursion::Jump
} else {
TreeNodeRecursion::Stop
});
}
Ok(TreeNodeRecursion::Continue)
})
.expect("infallible");
bare
})
}
struct BuiltJoin {
plan: LogicalPlan,
mark_is_three_valued_exact: bool,
}
fn build_join(
left: &LogicalPlan,
subquery: &LogicalPlan,
in_predicate_opt: Option<&Expr>,
join_type: JoinType,
alias: &str,
needs_null_aware_mark: bool,
) -> Result<Option<BuiltJoin>> {
let exists_sub_query = in_predicate_opt.is_none();
let rewrite =
|handle_count_bug: bool| -> Result<(LogicalPlan, PullUpCorrelatedExpr)> {
let mut pull_up = PullUpCorrelatedExpr::new()
.with_in_predicate_opt(in_predicate_opt.cloned())
.with_exists_sub_query(exists_sub_query)
.with_need_handle_count_bug(handle_count_bug);
let new_plan = subquery.clone().rewrite(&mut pull_up).data()?;
Ok((new_plan, pull_up))
};
let (mut new_plan, mut pull_up) = rewrite(exists_sub_query)?;
let mut count_bug_compensation = pull_up
.collected_count_expr_map
.get(&new_plan)
.filter(|m| !m.is_empty())
.cloned();
let reads_agg_output = count_bug_compensation.as_ref().is_some_and(|expr_map| {
pull_up
.join_filters
.iter()
.flat_map(|f| f.column_refs())
.any(|c| expr_map.contains_key(&c.name))
});
let subquery_cols: BTreeSet<Column> = pull_up
.correlated_subquery_cols_map
.values()
.flatten()
.cloned()
.collect();
let keys_are_bare = count_bug_compensation.is_none()
|| subquery_operands_are_bare_columns(&pull_up.join_filters, &subquery_cols);
let compensable = pull_up.can_pull_up
&& !reads_agg_output
&& keys_are_bare
&& (count_bug_compensation.is_some() || pull_up.pull_up_having_expr.is_none());
if exists_sub_query && !compensable {
(new_plan, pull_up) = rewrite(false)?;
count_bug_compensation = None;
}
if !pull_up.can_pull_up {
return Ok(None);
}
if !exists_sub_query && pull_up.pulled_up_scalar_agg {
let null_reads_as_false = match join_type {
JoinType::LeftSemi => true,
JoinType::LeftMark => !needs_null_aware_mark,
_ => false,
};
let count_bug_is_harmless = match rewrite(true) {
Ok((plan, pull_up)) => pull_up
.collected_count_expr_map
.get(&plan)
.filter(|m| !m.is_empty())
.is_none_or(|empty_input_values| {
null_reads_as_false
&& empty_input_values
.get(subquery.schema().field(0).name())
.is_some_and(|value| {
matches!(value, Expr::Literal(v, _) if v.is_null())
})
}),
Err(_) => false,
};
if !count_bug_is_harmless {
return Ok(None);
}
}
let sub_query_alias = LogicalPlanBuilder::from(new_plan)
.alias(alias.to_string())?
.build()?;
let join_filter_opt = build_join_filter(
pull_up.join_filters,
pull_up.correlated_subquery_cols_map.values().flatten(),
alias,
)?;
if let Some(expr_map) = count_bug_compensation
&& !expr_map.is_empty()
{
return build_join_with_count_bug(
left,
sub_query_alias,
join_filter_opt,
join_type,
alias,
&expr_map,
pull_up.pull_up_having_expr.as_ref(),
)
.map(|plan| {
Some(BuiltJoin {
plan,
mark_is_three_valued_exact: false,
})
});
}
let in_values = match in_predicate_opt {
Some(Expr::BinaryExpr(BinaryExpr {
left,
op: Operator::Eq,
right,
})) => {
let values = match in_subquery_tuple_values(left, subquery)? {
Some(values) => values.into_owned(),
None => vec![left.deref().clone()],
};
values
.into_iter()
.enumerate()
.map(|(i, value)| {
let output_expr = if i == 0 {
right.deref().clone()
} else {
subquery_output_expr(subquery, i)?
};
let right_col =
create_col_from_scalar_expr(&output_expr, alias.to_string())?;
Ok(InValue {
value: value.clone(),
subquery_column: Expr::Column(right_col),
value_as_written: value,
output_expr,
})
})
.collect::<Result<Vec<_>>>()?
}
Some(_) => return Ok(None),
None => vec![],
};
let mut value_may_be_null = false;
for in_value in &in_values {
value_may_be_null |= in_value.may_be_null_in_scope(
left.schema(),
sub_query_alias.schema(),
&pull_up.correlated_filters,
)?;
}
let null_aware = value_may_be_null
&& match join_type {
JoinType::LeftAnti => true,
JoinType::LeftMark => needs_null_aware_mark,
_ => false,
};
let mut projected_left = None;
let mut in_values = in_values;
if null_aware
&& in_values
.iter()
.any(|in_value| in_value.value.column_refs().is_empty())
{
let left_schema = left.schema();
let mut projections = left_schema
.columns()
.into_iter()
.map(Expr::from)
.collect::<Vec<_>>();
let is_tuple = in_values.len() > 1;
for (i, in_value) in in_values.iter_mut().enumerate() {
if !in_value.value.column_refs().is_empty() {
continue;
}
let mut value_name = if is_tuple {
format!("{alias}_value_{i}")
} else {
format!("{alias}_value")
};
while left_schema.fields().iter().any(|f| f.name() == &value_name) {
value_name.push('_');
}
let value_col = Column::new_unqualified(value_name);
let constant =
std::mem::replace(&mut in_value.value, Expr::Column(value_col.clone()));
projections.push(constant.alias(value_col.name()));
}
projected_left = Some(
LogicalPlanBuilder::from(left.clone())
.project(projections)?
.build()?,
);
}
let left = projected_left.as_ref().unwrap_or(left);
let join_filter = match (in_values.is_empty(), join_filter_opt) {
(false, correlation_opt) => in_join_filter(&in_values, correlation_opt)?,
(true, Some(correlation)) => correlation,
(true, None) => lit(true),
};
let value_is_first_key = null_aware
&& values_are_first_keys(
&in_values,
&join_filter,
left.schema(),
sub_query_alias.schema(),
)?;
if null_aware && !value_is_first_key && in_values.len() > 1 {
return not_impl_err!(
"Multi-column NOT IN subquery is not supported when a tuple element is not a hashable equi-join key: {join_filter}"
);
}
let null_aware_value_keys = in_values.len().max(1);
if join_type == JoinType::LeftAnti && null_aware && !value_is_first_key {
return Ok(None);
}
if matches!(join_type, JoinType::LeftMark | JoinType::RightMark) {
let right_schema = sub_query_alias.schema();
let mut needed = std::collections::HashSet::new();
expr_to_columns(&join_filter, &mut needed)?;
if let Some(in_pred) = in_predicate_opt {
expr_to_columns(in_pred, &mut needed)?;
}
let mut right_col_indices: Vec<usize> = needed
.into_iter()
.filter_map(|column| right_schema.index_of_column(&column).ok())
.collect();
right_col_indices.sort_unstable();
right_col_indices.dedup();
let right_proj_exprs: Vec<Expr> = right_col_indices
.into_iter()
.map(|index| Expr::Column(Column::from(right_schema.qualified_field(index))))
.collect();
let right_projected = if !right_proj_exprs.is_empty() {
LogicalPlanBuilder::from(sub_query_alias.clone())
.project(right_proj_exprs)?
.build()?
} else {
sub_query_alias.clone()
};
let mark_is_three_valued_exact = !in_values.is_empty()
&& (!value_may_be_null || (null_aware && value_is_first_key));
let new_plan = with_null_aware_value_keys(
LogicalPlanBuilder::from(left.clone())
.join_detailed_with_options(
right_projected,
join_type,
(Vec::<Column>::new(), Vec::<Column>::new()),
Some(join_filter),
NullEquality::NullEqualsNothing,
null_aware,
)?
.build()?,
null_aware_value_keys,
)?;
debug!(
"predicate subquery optimized:\n{}",
new_plan.display_indent()
);
return Ok(Some(BuiltJoin {
plan: new_plan,
mark_is_three_valued_exact,
}));
}
let new_plan = if null_aware {
with_null_aware_value_keys(
LogicalPlanBuilder::from(left.clone())
.join_detailed_with_options(
sub_query_alias,
join_type,
(Vec::<Column>::new(), Vec::<Column>::new()), Some(join_filter),
NullEquality::NullEqualsNothing,
true, )?
.build()?,
null_aware_value_keys,
)?
} else {
LogicalPlanBuilder::from(left.clone())
.join_on(sub_query_alias, join_type, Some(join_filter))?
.build()?
};
debug!(
"predicate subquery optimized:\n{}",
new_plan.display_indent()
);
Ok(Some(BuiltJoin {
plan: new_plan,
mark_is_three_valued_exact: false,
}))
}
fn build_join_with_count_bug(
left: &LogicalPlan,
sub_query_alias: LogicalPlan,
join_filter_opt: Option<Expr>,
join_type: JoinType,
alias: &str,
expr_map: &crate::decorrelate::ExprResultMap,
pull_up_having_expr: Option<&Expr>,
) -> Result<LogicalPlan> {
let pull_up_having_expr = pull_up_having_expr
.map(|f| {
f.clone()
.transform_up(|e| match e {
Expr::Column(c) => Ok(Transformed::yes(Expr::Column(Column::new(
Some(alias),
c.name,
)))),
_ => Ok(Transformed::no(e)),
})
.data()
})
.transpose()?;
let pull_up_having_expr = pull_up_having_expr.as_ref();
let joined = LogicalPlanBuilder::from(left.clone())
.join_on(sub_query_alias, JoinType::Left, join_filter_opt)?
.build()?;
let left_projection: Vec<Expr> = left
.schema()
.columns()
.into_iter()
.map(Expr::from)
.collect();
let indicator_col = Expr::Column(Column::new(Some(alias), UN_MATCHED_ROW_INDICATOR));
let having_arm = pull_up_having_expr.map(|f| f.clone().is_not_true());
let mut expr_rewrite = TypeCoercionRewriter::new(joined.schema());
let unmatched_having_default = match pull_up_having_expr {
Some(f) => f
.clone()
.transform_up(|e| {
if let Expr::Column(Column { name, .. }) = &e
&& let Some(default_value) = expr_map.get(name)
{
return Ok(Transformed::yes(default_value.clone()));
}
Ok(Transformed::no(e))
})
.data()
.and_then(|simplified| simplified.rewrite(&mut expr_rewrite).data())?,
None => lit(true),
};
let exists_expr = match having_arm {
Some(when_expr) => when(
indicator_col.clone().is_null(),
unmatched_having_default.is_true(),
)
.when(when_expr, lit(false))
.otherwise(lit(true))?
.rewrite(&mut expr_rewrite)
.data()?,
None => lit(true),
};
let new_plan = match join_type {
JoinType::LeftMark | JoinType::RightMark => {
let mut proj_exprs = left_projection;
proj_exprs.push(exists_expr.alias_qualified(Some(alias), "mark"));
LogicalPlanBuilder::from(joined)
.project(proj_exprs)?
.build()?
}
JoinType::LeftAnti => LogicalPlanBuilder::from(joined)
.filter(not(exists_expr))?
.project(left_projection)?
.build()?,
JoinType::LeftSemi => LogicalPlanBuilder::from(joined)
.filter(exists_expr)?
.project(left_projection)?
.build()?,
_ => {
return internal_err!("unsupported join type {join_type:?}");
}
};
debug!(
"predicate subquery (count bug) optimized:\n{}",
new_plan.display_indent()
);
Ok(new_plan)
}
#[derive(Debug)]
struct SubqueryInfo {
query: Subquery,
where_in_expr: Option<Expr>,
negated: bool,
}
impl SubqueryInfo {
pub fn new(query: Subquery, negated: bool) -> Self {
Self {
query,
where_in_expr: None,
negated,
}
}
pub fn new_with_in_expr(query: Subquery, expr: Expr, negated: bool) -> Self {
Self {
query,
where_in_expr: Some(expr),
negated,
}
}
pub fn expr(self) -> Expr {
match self.where_in_expr {
Some(expr) => match self.negated {
true => not_in_subquery(expr, self.query.subquery),
false => in_subquery(expr, self.query.subquery),
},
None => match self.negated {
true => not_exists(self.query.subquery),
false => exists(self.query.subquery),
},
}
}
}
#[cfg(test)]
mod tests {
use std::ops::Add;
use super::*;
use crate::test::*;
use crate::assert_optimized_plan_eq_display_indent_snapshot;
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_expr::builder::table_source;
use datafusion_expr::{
TableScanBuilder, and, binary_expr, col, cube, grouping_set, out_ref_col, rollup,
table_scan,
};
use datafusion_functions_aggregate::count::count_udaf;
macro_rules! assert_optimized_plan_equal {
(
$plan:expr,
@ $expected:literal $(,)?
) => {{
let rule: Arc<dyn crate::OptimizerRule + Send + Sync> = Arc::new(DecorrelatePredicateSubquery::new());
assert_optimized_plan_eq_display_indent_snapshot!(
rule,
$plan,
@ $expected,
)
}};
}
fn test_subquery_with_name(name: &str) -> Result<Arc<LogicalPlan>> {
let table_scan = test_table_scan_with_name(name)?;
Ok(Arc::new(
LogicalPlanBuilder::from(table_scan)
.project(vec![col("c")])?
.build()?,
))
}
fn nullable_scalar_mark_scan(name: &str) -> Result<LogicalPlan> {
let schema = Schema::new(vec![
Field::new("id", DataType::Int32, true),
Field::new("grp", DataType::Int32, true),
]);
table_scan(Some(name), &schema, None)?.build()
}
fn nullable_key_expr() -> Result<Expr> {
when(col("test.c").eq(lit(1u32)), lit(ScalarValue::UInt32(None)))
.otherwise(col("test.c"))
}
fn has_null_aware_left_mark_join(plan: &LogicalPlan) -> bool {
if let LogicalPlan::Join(join) = plan
&& join.join_type == JoinType::LeftMark
{
return join.null_aware;
}
plan.inputs().into_iter().any(has_null_aware_left_mark_join)
}
fn has_non_null_aware_left_mark_join(plan: &LogicalPlan) -> bool {
if let LogicalPlan::Join(join) = plan
&& join.join_type == JoinType::LeftMark
{
return !join.null_aware;
}
plan.inputs()
.into_iter()
.any(has_non_null_aware_left_mark_join)
}
fn optimize_with_decorrelate(plan: LogicalPlan) -> Result<LogicalPlan> {
let optimizer = crate::Optimizer::with_rules(vec![Arc::new(
DecorrelatePredicateSubquery::new(),
)]);
optimizer.optimize(plan, &crate::OptimizerContext::new(), |_, _| {})
}
fn correlated_grouping_set_subquery(
name: &str,
group_expr: Expr,
) -> Result<Arc<LogicalPlan>> {
Ok(Arc::new(
LogicalPlanBuilder::from(test_table_scan_with_name(name)?)
.filter(
col(format!("{name}.c")).eq(out_ref_col(DataType::UInt32, "test.c")),
)?
.aggregate(vec![group_expr], Vec::<Expr>::new())?
.project(vec![col(format!("{name}.c"))])?
.build()?,
))
}
#[test]
fn exists_subquery_with_rollup_is_not_decorrelated() -> Result<()> {
let subquery = correlated_grouping_set_subquery("sq", rollup(vec![col("sq.c")]))?;
let plan = LogicalPlanBuilder::from(test_table_scan()?)
.filter(exists(subquery))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
Filter: EXISTS (<subquery>) [a:UInt32, b:UInt32, c:UInt32]
Subquery: [c:UInt32;N]
Projection: sq.c [c:UInt32;N]
Aggregate: groupBy=[[ROLLUP (sq.c)]], aggr=[[]] [c:UInt32;N, __grouping_id:UInt8]
Filter: sq.c = outer_ref(test.c) [a:UInt32, b:UInt32, c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn in_subquery_with_cube_is_not_decorrelated() -> Result<()> {
let subquery = Arc::new(
LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
.filter(col("sq.a").eq(out_ref_col(DataType::UInt32, "test.a")))?
.aggregate(vec![cube(vec![col("sq.c")])], Vec::<Expr>::new())?
.project(vec![col("sq.c")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(test_table_scan()?)
.filter(in_subquery(col("test.c"), subquery))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
Filter: test.c IN (<subquery>) [a:UInt32, b:UInt32, c:UInt32]
Subquery: [c:UInt32;N]
Projection: sq.c [c:UInt32;N]
Aggregate: groupBy=[[CUBE (sq.c)]], aggr=[[]] [c:UInt32;N, __grouping_id:UInt8]
Filter: sq.a = outer_ref(test.a) [a:UInt32, b:UInt32, c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn exists_subquery_with_partial_grouping_set_is_not_decorrelated() -> Result<()> {
let subquery = correlated_grouping_set_subquery(
"sq",
grouping_set(vec![vec![col("sq.c")], vec![col("sq.b")]]),
)?;
let plan = LogicalPlanBuilder::from(test_table_scan()?)
.filter(exists(subquery))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
Filter: EXISTS (<subquery>) [a:UInt32, b:UInt32, c:UInt32]
Subquery: [c:UInt32;N]
Projection: sq.c [c:UInt32;N]
Aggregate: groupBy=[[GROUPING SETS ((sq.c), (sq.b))]], aggr=[[]] [c:UInt32;N, b:UInt32;N, __grouping_id:UInt8]
Filter: sq.c = outer_ref(test.c) [a:UInt32, b:UInt32, c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn exists_subquery_with_covering_grouping_set_is_decorrelated() -> Result<()> {
let subquery = correlated_grouping_set_subquery(
"sq",
grouping_set(vec![vec![col("sq.c")], vec![col("sq.c"), col("sq.b")]]),
)?;
let plan = LogicalPlanBuilder::from(test_table_scan()?)
.filter(exists(subquery))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: __correlated_sq_1.c = test.c [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32;N]
Projection: sq.c [c:UInt32;N]
Aggregate: groupBy=[[GROUPING SETS ((sq.c), (sq.c, sq.b))]], aggr=[[]] [c:UInt32;N, b:UInt32;N, __grouping_id:UInt8]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn in_subquery_multiple() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(and(
in_subquery(col("c"), test_subquery_with_name("sq_1")?),
in_subquery(col("b"), test_subquery_with_name("sq_2")?),
))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: test.b = __correlated_sq_2.c [a:UInt32, b:UInt32, c:UInt32]
LeftSemi Join: Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq_1.c [c:UInt32]
TableScan: sq_1 [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_2 [c:UInt32]
Projection: sq_2.c [c:UInt32]
TableScan: sq_2 [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn in_subquery_with_and_filters() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(and(
in_subquery(col("c"), test_subquery_with_name("sq")?),
and(
binary_expr(col("a"), Operator::Eq, lit(1_u32)),
binary_expr(col("b"), Operator::Lt, lit(30_u32)),
),
))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
Filter: test.a = UInt32(1) AND test.b < UInt32(30) [a:UInt32, b:UInt32, c:UInt32]
LeftSemi Join: Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn in_subquery_nested() -> Result<()> {
let table_scan = test_table_scan()?;
let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
.filter(in_subquery(col("a"), test_subquery_with_name("sq_nested")?))?
.project(vec![col("a")])?
.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(in_subquery(col("b"), Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: test.b = __correlated_sq_2.a [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_2 [a:UInt32]
Projection: sq.a [a:UInt32]
LeftSemi Join: Filter: sq.a = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq_nested.c [c:UInt32]
TableScan: sq_nested [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn multiple_subqueries() -> Result<()> {
let orders = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
col("orders.o_custkey")
.eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(
in_subquery(col("customer.c_custkey"), Arc::clone(&orders))
.and(in_subquery(col("customer.c_custkey"), orders)),
)?
.project(vec![col("customer.c_custkey")])?
.build()?;
debug!("plan to optimize:\n{}", plan.display_indent());
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_2.o_custkey [c_custkey:Int64, c_name:Utf8]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
SubqueryAlias: __correlated_sq_2 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn recursive_subqueries() -> Result<()> {
let lineitem = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("lineitem"))
.filter(
col("lineitem.l_orderkey")
.eq(out_ref_col(DataType::Int64, "orders.o_orderkey")),
)?
.project(vec![col("lineitem.l_orderkey")])?
.build()?,
);
let orders = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
in_subquery(col("orders.o_orderkey"), lineitem).and(
col("orders.o_custkey")
.eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(in_subquery(col("customer.c_custkey"), orders))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_2.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_2 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
LeftSemi Join: Filter: orders.o_orderkey = __correlated_sq_1.l_orderkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
SubqueryAlias: __correlated_sq_1 [l_orderkey:Int64]
Projection: lineitem.l_orderkey [l_orderkey:Int64]
TableScan: lineitem [l_orderkey:Int64, l_partkey:Int64, l_suppkey:Int64, l_linenumber:Int32, l_quantity:Float64, l_extendedprice:Float64]
"
)
}
#[test]
fn in_subquery_with_subquery_filters() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(col("orders.o_custkey"))
.and(col("o_orderkey").eq(lit(1))),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(in_subquery(col("customer.c_custkey"), sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
Filter: orders.o_orderkey = Int32(1) [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn in_subquery_no_cols() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(in_subquery(col("customer.c_custkey"), sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn in_subquery_with_no_correlated_cols() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(col("orders.o_custkey").eq(col("orders.o_custkey")))?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(in_subquery(col("customer.c_custkey"), sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
Filter: orders.o_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn in_subquery_where_not_eq() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.not_eq(col("orders.o_custkey")),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(in_subquery(col("customer.c_custkey"), sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey AND customer.c_custkey != __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn in_subquery_where_less_than() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.lt(col("orders.o_custkey")),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(in_subquery(col("customer.c_custkey"), sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey AND customer.c_custkey < __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn in_subquery_with_subquery_disjunction() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(col("orders.o_custkey"))
.or(col("o_orderkey").eq(lit(1))),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(in_subquery(col("customer.c_custkey"), sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey AND (customer.c_custkey = __correlated_sq_1.o_custkey OR __correlated_sq_1.o_orderkey = Int32(1)) [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64, o_orderkey:Int64]
Projection: orders.o_custkey, orders.o_orderkey [o_custkey:Int64, o_orderkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn in_subquery_no_projection() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(in_subquery(col("customer.c_custkey"), sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
let expected = "Invalid (non-executable) plan after Analyzer\
\ncaused by\
\nError during planning: InSubquery should only return one column, but found 4";
assert_analyzer_check_err(vec![], plan, expected);
Ok(())
}
#[test]
fn in_subquery_join_expr() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(col("orders.o_custkey")),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(in_subquery(col("customer.c_custkey").add(lit(1)), sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey + Int32(1) = __correlated_sq_1.o_custkey AND customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn in_subquery_project_expr() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(col("orders.o_custkey")),
)?
.project(vec![col("orders.o_custkey").add(lit(1))])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(in_subquery(col("customer.c_custkey"), sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.orders.o_custkey + Int32(1) AND customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [orders.o_custkey + Int32(1):Int64, o_custkey:Int64]
Projection: orders.o_custkey + Int32(1), orders.o_custkey [orders.o_custkey + Int32(1):Int64, o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn in_subquery_multi_col() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(col("orders.o_custkey")),
)?
.project(vec![col("orders.o_custkey"), col("orders.o_orderkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(
in_subquery(col("customer.c_custkey"), sq)
.and(col("c_custkey").eq(lit(1))),
)?
.project(vec![col("customer.c_custkey")])?
.build()?;
let expected = "Invalid (non-executable) plan after Analyzer\
\ncaused by\
\nError during planning: InSubquery should only return one column";
assert_analyzer_check_err(vec![], plan, expected);
Ok(())
}
#[test]
fn should_support_additional_filters() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(col("orders.o_custkey")),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(
in_subquery(col("customer.c_custkey"), sq)
.and(col("c_custkey").eq(lit(1))),
)?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
Filter: customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn in_subquery_correlated() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
.filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?
.project(vec![col("c")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(test_table_scan_with_name("test")?)
.filter(in_subquery(col("c"), sq))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: test.c = __correlated_sq_1.c AND test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
Projection: sq.c, sq.a [c:UInt32, a:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn in_subquery_simple() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(in_subquery(col("c"), test_subquery_with_name("sq")?))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn in_subquery_in_projection() -> Result<()> {
let plan = LogicalPlanBuilder::from(test_table_scan()?)
.project(vec![
in_subquery(col("c"), test_subquery_with_name("sq")?).alias("is_present"),
])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: __correlated_sq_1.mark AS is_present [is_present:Boolean;N]
LeftMark Join: Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32, mark:Boolean;N]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
Projection: __correlated_sq_1.c [c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn in_subquery_in_projection_with_residual_filter() -> Result<()> {
let subquery = Arc::new(
LogicalPlanBuilder::from(nullable_scalar_mark_scan("inner_t")?)
.filter(
out_ref_col(DataType::Int32, "outer_t.grp").gt(col("inner_t.grp")),
)?
.project(vec![col("inner_t.id")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(nullable_scalar_mark_scan("outer_t")?)
.project(vec![
in_subquery(col("outer_t.id"), subquery).alias("is_present"),
])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: __correlated_sq_1.mark AS is_present [is_present:Boolean;N]
LeftMark Join: Filter: outer_t.id = __correlated_sq_1.id AND outer_t.grp > __correlated_sq_1.grp null_aware [id:Int32;N, grp:Int32;N, mark:Boolean;N]
TableScan: outer_t [id:Int32;N, grp:Int32;N]
Projection: __correlated_sq_1.id, __correlated_sq_1.grp [id:Int32;N, grp:Int32;N]
SubqueryAlias: __correlated_sq_1 [id:Int32;N, grp:Int32;N]
Projection: inner_t.id, inner_t.grp [id:Int32;N, grp:Int32;N]
TableScan: inner_t [id:Int32;N, grp:Int32;N]
"
)
}
#[test]
fn not_in_subquery_in_projection() -> Result<()> {
let subquery = Arc::new(
LogicalPlanBuilder::from(nullable_scalar_mark_scan("inner_t")?)
.project(vec![col("inner_t.id")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(nullable_scalar_mark_scan("outer_t")?)
.project(vec![
not_in_subquery(col("outer_t.id"), subquery).alias("is_absent"),
])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: NOT __correlated_sq_1.mark AS is_absent [is_absent:Boolean;N]
LeftMark Join: Filter: outer_t.id = __correlated_sq_1.id null_aware [id:Int32;N, grp:Int32;N, mark:Boolean;N]
TableScan: outer_t [id:Int32;N, grp:Int32;N]
Projection: __correlated_sq_1.id [id:Int32;N]
SubqueryAlias: __correlated_sq_1 [id:Int32;N]
Projection: inner_t.id [id:Int32;N]
TableScan: inner_t [id:Int32;N, grp:Int32;N]
"
)
}
#[test]
fn in_subquery_in_projection_with_nullable_key_expr() -> Result<()> {
let plan = LogicalPlanBuilder::from(test_table_scan()?)
.project(vec![
in_subquery(nullable_key_expr()?, test_subquery_with_name("sq")?)
.alias("is_present"),
])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: __correlated_sq_1.mark AS is_present [is_present:Boolean;N]
LeftMark Join: Filter: CASE WHEN test.c = UInt32(1) THEN UInt32(NULL) ELSE test.c END = __correlated_sq_1.c null_aware [a:UInt32, b:UInt32, c:UInt32, mark:Boolean;N]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
Projection: __correlated_sq_1.c [c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn not_in_subquery_filter_with_nullable_key_expr() -> Result<()> {
let plan = LogicalPlanBuilder::from(test_table_scan()?)
.filter(not_in_subquery(
nullable_key_expr()?,
test_subquery_with_name("sq")?,
))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftAnti Join: Filter: CASE WHEN test.c = UInt32(1) THEN UInt32(NULL) ELSE test.c END = __correlated_sq_1.c null_aware [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn unsupported_correlated_in_projection_is_left_unchanged() -> Result<()> {
let subquery = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(col("orders.o_custkey")),
)?
.limit(0, Some(1))?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.project(vec![
in_subquery(col("customer.c_custkey"), subquery).alias("is_present"),
])?
.build()?;
let result = DecorrelatePredicateSubquery::new()
.rewrite(plan.clone(), &crate::OptimizerContext::new())?;
assert!(!result.transformed);
assert_eq!(result.data, plan);
Ok(())
}
#[test]
fn not_in_subquery_simple() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(not_in_subquery(col("c"), test_subquery_with_name("sq")?))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftAnti Join: Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn wrapped_not_in_subquery() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(not(in_subquery(col("c"), test_subquery_with_name("sq")?)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftAnti Join: Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn wrapped_not_not_in_subquery() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(not(not_in_subquery(
col("c"),
test_subquery_with_name("sq")?,
)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn constant_not_in_subquery_projects_value_as_join_key() -> Result<()> {
let outer_scan = nullable_scalar_mark_scan("outer_t")?;
let inner_scan = nullable_scalar_mark_scan("inner_t")?;
let subquery = Arc::new(
LogicalPlanBuilder::from(inner_scan)
.project(vec![col("inner_t.id")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(outer_scan)
.filter(not_in_subquery(lit(3i32), subquery))?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: outer_t.id, outer_t.grp [id:Int32;N, grp:Int32;N]
LeftAnti Join: Filter: __correlated_sq_1_value = __correlated_sq_1.id null_aware [id:Int32;N, grp:Int32;N, __correlated_sq_1_value:Int32]
Projection: outer_t.id, outer_t.grp, Int32(3) AS __correlated_sq_1_value [id:Int32;N, grp:Int32;N, __correlated_sq_1_value:Int32]
TableScan: outer_t [id:Int32;N, grp:Int32;N]
SubqueryAlias: __correlated_sq_1 [id:Int32;N]
Projection: inner_t.id [id:Int32;N]
TableScan: inner_t [id:Int32;N, grp:Int32;N]
"
)
}
#[test]
fn null_constant_not_in_non_nullable_subquery_is_null_aware() -> Result<()> {
let plan = LogicalPlanBuilder::from(test_table_scan()?)
.filter(not_in_subquery(
lit(ScalarValue::UInt32(None)),
test_subquery_with_name("sq")?,
))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
Projection: test.a, test.b, test.c [a:UInt32, b:UInt32, c:UInt32]
LeftAnti Join: Filter: __correlated_sq_1_value = __correlated_sq_1.c null_aware [a:UInt32, b:UInt32, c:UInt32, __correlated_sq_1_value:UInt32;N]
Projection: test.a, test.b, test.c, UInt32(NULL) AS __correlated_sq_1_value [a:UInt32, b:UInt32, c:UInt32, __correlated_sq_1_value:UInt32;N]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn non_nullable_key_expr_not_in_is_not_null_aware() -> Result<()> {
let plan = LogicalPlanBuilder::from(test_table_scan()?)
.filter(not_in_subquery(
col("test.c") + lit(1u32),
test_subquery_with_name("sq")?,
))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftAnti Join: Filter: test.c + UInt32(1) = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn correlated_not_in_mark_join_is_null_aware_for_hashable_filter() -> Result<()> {
let outer_scan = nullable_scalar_mark_scan("outer_t")?;
let inner_scan = nullable_scalar_mark_scan("inner_t")?;
let subquery = Arc::new(
LogicalPlanBuilder::from(inner_scan)
.filter(
out_ref_col(DataType::Int32, "outer_t.grp").eq(col("inner_t.grp")),
)?
.project(vec![col("inner_t.id")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(outer_scan)
.filter(not_in_subquery(col("outer_t.id"), subquery).is_null())?
.build()?;
let optimized = optimize_with_decorrelate(plan)?;
assert!(
has_null_aware_left_mark_join(&optimized),
"{}",
optimized.display_indent_schema()
);
Ok(())
}
#[test]
fn mark_join_for_in_predicate_correlation_is_not_null_aware() -> Result<()> {
let outer_scan = nullable_scalar_mark_scan("outer_t")?;
let inner_scan = nullable_scalar_mark_scan("inner_t")?;
let subquery = Arc::new(
LogicalPlanBuilder::from(inner_scan)
.filter(out_ref_col(DataType::Int32, "outer_t.id").eq(col("inner_t.id")))?
.project(vec![col("inner_t.id")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(outer_scan)
.filter(in_subquery(col("outer_t.id"), subquery).is_null())?
.build()?;
let optimized = optimize_with_decorrelate(plan)?;
assert!(
has_non_null_aware_left_mark_join(&optimized),
"{}",
optimized.display_indent_schema()
);
Ok(())
}
#[test]
fn mark_join_for_in_predicate_correlation_below_rollup_is_null_aware() -> Result<()> {
let subquery = correlated_grouping_set_subquery("sq", rollup(vec![col("sq.c")]))?;
let plan = LogicalPlanBuilder::from(test_table_scan()?)
.project(vec![in_subquery(col("test.c"), subquery).alias("m")])?
.build()?;
let optimized = optimize_with_decorrelate(plan)?;
assert!(
has_null_aware_left_mark_join(&optimized),
"{}",
optimized.display_indent_schema()
);
Ok(())
}
#[test]
fn anti_join_for_in_predicate_correlation_is_not_null_aware() -> Result<()> {
let outer_scan = nullable_scalar_mark_scan("outer_t")?;
let inner_scan = nullable_scalar_mark_scan("inner_t")?;
let subquery = Arc::new(
LogicalPlanBuilder::from(inner_scan)
.filter(out_ref_col(DataType::Int32, "outer_t.id").eq(col("inner_t.id")))?
.project(vec![col("inner_t.id")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(outer_scan)
.filter(not_in_subquery(col("outer_t.id"), subquery))?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
LeftAnti Join: Filter: outer_t.id = __correlated_sq_1.id [id:Int32;N, grp:Int32;N]
TableScan: outer_t [id:Int32;N, grp:Int32;N]
SubqueryAlias: __correlated_sq_1 [id:Int32;N]
Projection: inner_t.id [id:Int32;N]
TableScan: inner_t [id:Int32;N, grp:Int32;N]
"
)
}
#[test]
fn in_subquery_both_side_expr() -> Result<()> {
let table_scan = test_table_scan()?;
let subquery_scan = test_table_scan_with_name("sq")?;
let subquery = LogicalPlanBuilder::from(subquery_scan)
.project(vec![col("c") * lit(2u32)])?
.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(in_subquery(col("c") + lit(1u32), Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: test.c + UInt32(1) = __correlated_sq_1.sq.c * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [sq.c * UInt32(2):UInt32]
Projection: sq.c * UInt32(2) [sq.c * UInt32(2):UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn in_subquery_join_filter_and_inner_filter() -> Result<()> {
let table_scan = test_table_scan()?;
let subquery_scan = test_table_scan_with_name("sq")?;
let subquery = LogicalPlanBuilder::from(subquery_scan)
.filter(
out_ref_col(DataType::UInt32, "test.a")
.eq(col("sq.a"))
.and(col("sq.a").add(lit(1u32)).eq(col("sq.b"))),
)?
.project(vec![col("c") * lit(2u32)])?
.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(in_subquery(col("c") + lit(1u32), Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: test.c + UInt32(1) = __correlated_sq_1.sq.c * UInt32(2) AND test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [sq.c * UInt32(2):UInt32, a:UInt32]
Projection: sq.c * UInt32(2), sq.a [sq.c * UInt32(2):UInt32, a:UInt32]
Filter: sq.a + UInt32(1) = sq.b [a:UInt32, b:UInt32, c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn in_subquery_multi_project_subquery_cols() -> Result<()> {
let table_scan = test_table_scan()?;
let subquery_scan = test_table_scan_with_name("sq")?;
let subquery = LogicalPlanBuilder::from(subquery_scan)
.filter(
out_ref_col(DataType::UInt32, "test.a")
.add(out_ref_col(DataType::UInt32, "test.b"))
.eq(col("sq.a").add(col("sq.b")))
.and(col("sq.a").add(lit(1u32)).eq(col("sq.b"))),
)?
.project(vec![col("c") * lit(2u32)])?
.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(in_subquery(col("c") + lit(1u32), Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: test.c + UInt32(1) = __correlated_sq_1.sq.c * UInt32(2) AND test.a + test.b = __correlated_sq_1.a + __correlated_sq_1.b [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [sq.c * UInt32(2):UInt32, a:UInt32, b:UInt32]
Projection: sq.c * UInt32(2), sq.a, sq.b [sq.c * UInt32(2):UInt32, a:UInt32, b:UInt32]
Filter: sq.a + UInt32(1) = sq.b [a:UInt32, b:UInt32, c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn two_in_subquery_with_outer_filter() -> Result<()> {
let table_scan = test_table_scan()?;
let subquery_scan1 = test_table_scan_with_name("sq1")?;
let subquery_scan2 = test_table_scan_with_name("sq2")?;
let subquery1 = LogicalPlanBuilder::from(subquery_scan1)
.filter(out_ref_col(DataType::UInt32, "test.a").gt(col("sq1.a")))?
.project(vec![col("c") * lit(2u32)])?
.build()?;
let subquery2 = LogicalPlanBuilder::from(subquery_scan2)
.filter(out_ref_col(DataType::UInt32, "test.a").gt(col("sq2.a")))?
.project(vec![col("c") * lit(2u32)])?
.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(
in_subquery(col("c") + lit(1u32), Arc::new(subquery1)).and(
in_subquery(col("c") * lit(2u32), Arc::new(subquery2))
.and(col("test.c").gt(lit(1u32))),
),
)?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
Filter: test.c > UInt32(1) [a:UInt32, b:UInt32, c:UInt32]
LeftSemi Join: Filter: test.c * UInt32(2) = __correlated_sq_2.sq2.c * UInt32(2) AND test.a > __correlated_sq_2.a [a:UInt32, b:UInt32, c:UInt32]
LeftSemi Join: Filter: test.c + UInt32(1) = __correlated_sq_1.sq1.c * UInt32(2) AND test.a > __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [sq1.c * UInt32(2):UInt32, a:UInt32]
Projection: sq1.c * UInt32(2), sq1.a [sq1.c * UInt32(2):UInt32, a:UInt32]
TableScan: sq1 [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_2 [sq2.c * UInt32(2):UInt32, a:UInt32]
Projection: sq2.c * UInt32(2), sq2.a [sq2.c * UInt32(2):UInt32, a:UInt32]
TableScan: sq2 [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn in_subquery_with_same_table() -> Result<()> {
let outer_scan = test_table_scan()?;
let subquery_scan = test_table_scan()?;
let subquery = LogicalPlanBuilder::from(subquery_scan)
.filter(col("test.a").gt(col("test.b")))?
.project(vec![col("c")])?
.build()?;
let plan = LogicalPlanBuilder::from(outer_scan)
.filter(in_subquery(col("test.a"), Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: test.a = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: test.c [c:UInt32]
Filter: test.a > test.b [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn in_subquery_correlated_with_same_table() -> Result<()> {
let outer_scan = test_table_scan()?;
let subquery_scan = test_table_scan()?;
let subquery = LogicalPlanBuilder::from(subquery_scan)
.filter(out_ref_col(DataType::UInt32, "test.a").gt(col("test.a")))?
.project(vec![col("c")])?
.build()?;
let plan = LogicalPlanBuilder::from(outer_scan)
.filter(in_subquery(col("test.b"), Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: test.b = __correlated_sq_1.c AND test.a > __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
Projection: test.c, test.a [c:UInt32, a:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn multiple_exists_subqueries() -> Result<()> {
let orders = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
col("orders.o_custkey")
.eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(exists(Arc::clone(&orders)).and(exists(orders)))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: __correlated_sq_2.o_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8]
LeftSemi Join: Filter: __correlated_sq_1.o_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
SubqueryAlias: __correlated_sq_2 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn recursive_exists_subqueries() -> Result<()> {
let lineitem = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("lineitem"))
.filter(
col("lineitem.l_orderkey")
.eq(out_ref_col(DataType::Int64, "orders.o_orderkey")),
)?
.project(vec![col("lineitem.l_orderkey")])?
.build()?,
);
let orders = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
exists(lineitem).and(
col("orders.o_custkey")
.eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(exists(orders))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: __correlated_sq_2.o_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_2 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
LeftSemi Join: Filter: __correlated_sq_1.l_orderkey = orders.o_orderkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
SubqueryAlias: __correlated_sq_1 [l_orderkey:Int64]
Projection: lineitem.l_orderkey [l_orderkey:Int64]
TableScan: lineitem [l_orderkey:Int64, l_partkey:Int64, l_suppkey:Int64, l_linenumber:Int32, l_quantity:Float64, l_extendedprice:Float64]
"
)
}
#[test]
fn exists_subquery_with_subquery_filters() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(col("orders.o_custkey"))
.and(col("o_orderkey").eq(lit(1))),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(exists(sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
Filter: orders.o_orderkey = Int32(1) [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn exists_subquery_no_cols() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(out_ref_col(DataType::Int64, "customer.c_custkey").eq(lit(1u32)))?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(exists(sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = UInt32(1) [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn exists_subquery_with_no_correlated_cols() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(col("orders.o_custkey").eq(col("orders.o_custkey")))?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(exists(sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: Boolean(true) [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
Filter: orders.o_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn exists_subquery_where_not_eq() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.not_eq(col("orders.o_custkey")),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(exists(sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey != __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn exists_subquery_where_less_than() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.lt(col("orders.o_custkey")),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(exists(sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey < __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn exists_subquery_with_subquery_disjunction() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(col("orders.o_custkey"))
.or(col("o_orderkey").eq(lit(1))),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(exists(sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey OR __correlated_sq_1.o_orderkey = Int32(1) [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64, o_orderkey:Int64]
Projection: orders.o_custkey, orders.o_orderkey [o_custkey:Int64, o_orderkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn exists_subquery_no_projection() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(col("orders.o_custkey")),
)?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(exists(sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn exists_subquery_project_expr() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(col("orders.o_custkey")),
)?
.project(vec![col("orders.o_custkey").add(lit(1))])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(exists(sq))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [orders.o_custkey + Int32(1):Int64, o_custkey:Int64]
Projection: orders.o_custkey + Int32(1), orders.o_custkey [orders.o_custkey + Int32(1):Int64, o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn exists_subquery_should_support_additional_filters() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(
out_ref_col(DataType::Int64, "customer.c_custkey")
.eq(col("orders.o_custkey")),
)?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(exists(sq).and(col("c_custkey").eq(lit(1))))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
Filter: customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8]
LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn exists_subquery_disjunction() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(scan_tpch_table("orders"))
.filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?
.project(vec![col("orders.o_custkey")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
.filter(exists(sq).or(col("customer.c_custkey").eq(lit(1))))?
.project(vec![col("customer.c_custkey")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: customer.c_custkey [c_custkey:Int64]
Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
Filter: __correlated_sq_1.mark OR customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8, mark:Boolean;N]
LeftMark Join: Filter: Boolean(true) [c_custkey:Int64, c_name:Utf8, mark:Boolean;N]
TableScan: customer [c_custkey:Int64, c_name:Utf8]
SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
Projection: orders.o_custkey [o_custkey:Int64]
Filter: customer.c_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
"
)
}
#[test]
fn exists_subquery_disjunction_with_count_bug() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
.filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?
.aggregate(Vec::<Expr>::new(), vec![count_udaf().call(vec![])])?
.build()?,
);
let plan = LogicalPlanBuilder::from(test_table_scan()?)
.filter(exists(sq).or(col("test.c").eq(lit(1))))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
Projection: test.a, test.b, test.c [a:UInt32, b:UInt32, c:UInt32]
Filter: __correlated_sq_1.mark OR test.c = Int32(1) [a:UInt32, b:UInt32, c:UInt32, mark:Boolean]
Projection: test.a, test.b, test.c, Boolean(true) AS mark [a:UInt32, b:UInt32, c:UInt32, mark:Boolean]
Left Join: Filter: test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, __always_true:Boolean;N, count():Int64;N]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [a:UInt32, __always_true:Boolean, count():Int64]
Aggregate: groupBy=[[sq.a, Boolean(true) AS __always_true]], aggr=[[count()]] [a:UInt32, __always_true:Boolean, count():Int64]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn exists_subquery_correlated() -> Result<()> {
let sq = Arc::new(
LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
.filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?
.project(vec![col("c")])?
.build()?,
);
let plan = LogicalPlanBuilder::from(test_table_scan_with_name("test")?)
.filter(exists(sq))?
.project(vec![col("test.c")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.c [c:UInt32]
LeftSemi Join: Filter: test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
Projection: sq.c, sq.a [c:UInt32, a:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn exists_subquery_simple() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(exists(test_subquery_with_name("sq")?))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn not_exists_subquery_simple() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(not_exists(test_subquery_with_name("sq")?))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftAnti Join: Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn two_exists_subquery_with_outer_filter() -> Result<()> {
let table_scan = test_table_scan()?;
let subquery_scan1 = test_table_scan_with_name("sq1")?;
let subquery_scan2 = test_table_scan_with_name("sq2")?;
let subquery1 = LogicalPlanBuilder::from(subquery_scan1)
.filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq1.a")))?
.project(vec![col("c")])?
.build()?;
let subquery2 = LogicalPlanBuilder::from(subquery_scan2)
.filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq2.a")))?
.project(vec![col("c")])?
.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(
exists(Arc::new(subquery1))
.and(exists(Arc::new(subquery2)).and(col("test.c").gt(lit(1u32)))),
)?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
Filter: test.c > UInt32(1) [a:UInt32, b:UInt32, c:UInt32]
LeftSemi Join: Filter: test.a = __correlated_sq_2.a [a:UInt32, b:UInt32, c:UInt32]
LeftSemi Join: Filter: test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
Projection: sq1.c, sq1.a [c:UInt32, a:UInt32]
TableScan: sq1 [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_2 [c:UInt32, a:UInt32]
Projection: sq2.c, sq2.a [c:UInt32, a:UInt32]
TableScan: sq2 [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn exists_subquery_expr_filter() -> Result<()> {
let table_scan = test_table_scan()?;
let subquery_scan = test_table_scan_with_name("sq")?;
let subquery = LogicalPlanBuilder::from(subquery_scan)
.filter(
(lit(1u32) + col("sq.a"))
.gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),
)?
.project(vec![lit(1u32)])?
.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(exists(Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: UInt32(1) + __correlated_sq_1.a > test.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [UInt32(1):UInt32, a:UInt32]
Projection: UInt32(1), sq.a [UInt32(1):UInt32, a:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn exists_subquery_with_same_table() -> Result<()> {
let outer_scan = test_table_scan()?;
let subquery_scan = test_table_scan()?;
let subquery = LogicalPlanBuilder::from(subquery_scan)
.filter(col("test.a").gt(col("test.b")))?
.project(vec![col("c")])?
.build()?;
let plan = LogicalPlanBuilder::from(outer_scan)
.filter(exists(Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32]
Projection: test.c [c:UInt32]
Filter: test.a > test.b [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn exists_distinct_subquery() -> Result<()> {
let table_scan = test_table_scan()?;
let subquery_scan = test_table_scan_with_name("sq")?;
let subquery = LogicalPlanBuilder::from(subquery_scan)
.filter(
(lit(1u32) + col("sq.a"))
.gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),
)?
.project(vec![col("sq.c")])?
.distinct()?
.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(exists(Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: UInt32(1) + __correlated_sq_1.a > test.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
Distinct: [c:UInt32, a:UInt32]
Projection: sq.c, sq.a [c:UInt32, a:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn exists_distinct_expr_subquery() -> Result<()> {
let table_scan = test_table_scan()?;
let subquery_scan = test_table_scan_with_name("sq")?;
let subquery = LogicalPlanBuilder::from(subquery_scan)
.filter(
(lit(1u32) + col("sq.a"))
.gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),
)?
.project(vec![col("sq.b") + col("sq.c")])?
.distinct()?
.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(exists(Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: UInt32(1) + __correlated_sq_1.a > test.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [sq.b + sq.c:UInt32, a:UInt32]
Distinct: [sq.b + sq.c:UInt32, a:UInt32]
Projection: sq.b + sq.c, sq.a [sq.b + sq.c:UInt32, a:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn exists_distinct_subquery_with_literal() -> Result<()> {
let table_scan = test_table_scan()?;
let subquery_scan = test_table_scan_with_name("sq")?;
let subquery = LogicalPlanBuilder::from(subquery_scan)
.filter(
(lit(1u32) + col("sq.a"))
.gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),
)?
.project(vec![lit(1u32), col("sq.c")])?
.distinct()?
.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(exists(Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: UInt32(1) + __correlated_sq_1.a > test.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [UInt32(1):UInt32, c:UInt32, a:UInt32]
Distinct: [UInt32(1):UInt32, c:UInt32, a:UInt32]
Projection: UInt32(1), sq.c, sq.a [UInt32(1):UInt32, c:UInt32, a:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
#[test]
fn exists_uncorrelated_unnest() -> Result<()> {
let subquery_table_source = table_source(&Schema::new(vec![Field::new(
"arr",
DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true))),
true,
)]));
let subquery_table_scan =
TableScanBuilder::new("sq", subquery_table_source).build()?;
let subquery = LogicalPlanBuilder::table_scan(subquery_table_scan)?
.unnest_column("arr")?
.build()?;
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(exists(Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [arr:Int32;N]
Unnest: lists[sq.arr|depth=1] structs[] [arr:Int32;N]
TableScan: sq [arr:List(Int32);N]
"
)
}
#[test]
fn exists_correlated_unnest() -> Result<()> {
let table_scan = test_table_scan()?;
let subquery_table_source = table_source(&Schema::new(vec![Field::new(
"a",
DataType::List(Arc::new(Field::new_list_field(DataType::UInt32, true))),
true,
)]));
let subquery_table_scan =
TableScanBuilder::new("sq", subquery_table_source).build()?;
let subquery = LogicalPlanBuilder::table_scan(subquery_table_scan)?
.unnest_column("a")?
.filter(col("a").eq(out_ref_col(DataType::UInt32, "test.b")))?
.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(exists(Arc::new(subquery)))?
.project(vec![col("test.b")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.b [b:UInt32]
LeftSemi Join: Filter: __correlated_sq_1.a = test.b [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [a:UInt32;N]
Unnest: lists[sq.a|depth=1] structs[] [a:UInt32;N]
TableScan: sq [a:List(UInt32);N]
"
)
}
#[test]
fn upper_case_ident() -> Result<()> {
let fields = vec![
Field::new("A", DataType::UInt32, false),
Field::new("B", DataType::UInt32, false),
];
let schema = Schema::new(fields);
let table_scan_a = table_scan(Some("\"TEST_A\""), &schema, None)?.build()?;
let table_scan_b = table_scan(Some("\"TEST_B\""), &schema, None)?.build()?;
let subquery = LogicalPlanBuilder::from(table_scan_b)
.filter(col("\"A\"").eq(out_ref_col(DataType::UInt32, "\"TEST_A\".\"A\"")))?
.project(vec![lit(1)])?
.build()?;
let plan = LogicalPlanBuilder::from(table_scan_a)
.filter(exists(Arc::new(subquery)))?
.project(vec![col("\"TEST_A\".\"B\"")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: TEST_A.B [B:UInt32]
LeftSemi Join: Filter: __correlated_sq_1.A = TEST_A.A [A:UInt32, B:UInt32]
TableScan: TEST_A [A:UInt32, B:UInt32]
SubqueryAlias: __correlated_sq_1 [Int32(1):Int32, A:UInt32]
Projection: Int32(1), TEST_B.A [Int32(1):Int32, A:UInt32]
TableScan: TEST_B [A:UInt32, B:UInt32]
"
)
}
#[test]
fn exists_subquery_filter_on_unnested_column() -> Result<()> {
let list_type =
DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true)));
let schema = Schema::new(vec![
Field::new("id", DataType::Int32, true),
Field::new("arr", list_type.clone(), true),
]);
let subquery = Arc::new(
table_scan(Some("sq"), &schema, None)?
.filter(col("sq.arr").eq(out_ref_col(list_type, "outer_t.arr")))?
.unnest_column("arr")?
.project(vec![col("sq.id")])?
.build()?,
);
let plan = table_scan(Some("outer_t"), &schema, None)?
.filter(exists(subquery))?
.project(vec![col("outer_t.id")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: outer_t.id [id:Int32;N]
Filter: EXISTS (<subquery>) [id:Int32;N, arr:List(Int32);N]
Subquery: [id:Int32;N]
Projection: sq.id [id:Int32;N]
Unnest: lists[sq.arr|depth=1] structs[] [id:Int32;N, arr:Int32;N]
Filter: sq.arr = outer_ref(outer_t.arr) [id:Int32;N, arr:List(Int32);N]
TableScan: sq [id:Int32;N, arr:List(Int32);N]
TableScan: outer_t [id:Int32;N, arr:List(Int32);N]
"
)
}
#[test]
fn exists_subquery_filter_above_correlated_derived_table() -> Result<()> {
let sq_scan = test_table_scan_with_name("sq")?;
let derived = LogicalPlanBuilder::from(sq_scan)
.filter(col("sq.c").eq(out_ref_col(DataType::UInt32, "test.a")))?
.project(vec![col("sq.c")])?
.alias("t")?
.build()?;
let subquery = LogicalPlanBuilder::from(derived)
.filter(out_ref_col(DataType::UInt32, "test.b").gt(lit(0u32)))?
.project(vec![lit(1)])?
.build()?;
let outer_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(outer_scan)
.filter(exists(Arc::new(subquery)))?
.project(vec![col("test.a")])?
.build()?;
assert_optimized_plan_equal!(
plan,
@r"
Projection: test.a [a:UInt32]
LeftSemi Join: Filter: __correlated_sq_1.c = test.a AND test.b > UInt32(0) [a:UInt32, b:UInt32, c:UInt32]
TableScan: test [a:UInt32, b:UInt32, c:UInt32]
SubqueryAlias: __correlated_sq_1 [Int32(1):Int32, c:UInt32]
Projection: Int32(1), t.c [Int32(1):Int32, c:UInt32]
SubqueryAlias: t [c:UInt32]
Projection: sq.c [c:UInt32]
TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
"
)
}
}