use std::collections::BTreeSet;
use std::sync::Arc;
use crate::push_down_filter::lr_is_preserved;
use crate::simplify_expressions::ExprSimplifier;
use crate::utils::replace_qualified_name;
use datafusion_common::nested_struct::is_injective_cast;
use datafusion_common::tree_node::{
Transformed, TransformedResult, TreeNode, TreeNodeRecursion, TreeNodeRewriter,
};
use datafusion_common::utils::has_float_leaf;
use datafusion_common::{
Column, DFSchema, DFSchemaRef, HashMap, Result, ScalarValue, assert_or_internal_err,
plan_err,
};
use datafusion_expr::expr::{Alias, GroupingSet};
use datafusion_expr::expr_rewriter::strip_outer_reference;
use datafusion_expr::logical_plan::{Join, JoinType};
use datafusion_expr::simplify::SimplifyContext;
use datafusion_expr::utils::{collect_subquery_cols, conjunction, split_conjunction};
use datafusion_expr::{
Aggregate, BinaryExpr, Cast, Distinct, EmptyRelation, Expr, ExprSchemable, FetchType,
LogicalPlan, LogicalPlanBuilder, MaterializedCte, MaterializedCtePlan, Operator,
SkipType, Window, expr, lit,
};
#[derive(Debug)]
pub struct PullUpCorrelatedExpr {
pub join_filters: Vec<Expr>,
pub correlated_subquery_cols_map: HashMap<LogicalPlan, BTreeSet<Column>>,
pub in_predicate_opt: Option<Expr>,
pub exists_sub_query: bool,
pub can_pull_up: bool,
can_pull_over_aggregation: bool,
can_extend_partition_by: bool,
pub need_handle_count_bug: bool,
pub collected_count_expr_map: HashMap<LogicalPlan, ExprResultMap>,
pub pull_up_having_expr: Option<Expr>,
pub pulled_up_scalar_agg: bool,
pub correlated_filters: Vec<Expr>,
column_refs_above: Vec<BTreeSet<Column>>,
depends_only_on_input_having_rows_above: Vec<bool>,
}
impl Default for PullUpCorrelatedExpr {
fn default() -> Self {
Self::new()
}
}
impl PullUpCorrelatedExpr {
pub fn new() -> Self {
Self {
join_filters: vec![],
correlated_subquery_cols_map: HashMap::new(),
in_predicate_opt: None,
exists_sub_query: false,
can_pull_up: true,
can_pull_over_aggregation: true,
can_extend_partition_by: true,
need_handle_count_bug: false,
collected_count_expr_map: HashMap::new(),
pull_up_having_expr: None,
pulled_up_scalar_agg: false,
correlated_filters: Vec::new(),
column_refs_above: Vec::new(),
depends_only_on_input_having_rows_above: Vec::new(),
}
}
pub fn with_need_handle_count_bug(mut self, need_handle_count_bug: bool) -> Self {
self.need_handle_count_bug = need_handle_count_bug;
self
}
pub fn with_in_predicate_opt(mut self, in_predicate_opt: Option<Expr>) -> Self {
self.in_predicate_opt = in_predicate_opt;
self
}
pub fn with_exists_sub_query(mut self, exists_sub_query: bool) -> Self {
self.exists_sub_query = exists_sub_query;
self
}
}
#[derive(Debug, PartialEq, Eq)]
enum GroupingSetsPullUp {
NoColumnsToAdd,
SafeToExtend,
Unsafe,
}
pub const UN_MATCHED_ROW_INDICATOR: &str = "__always_true";
pub type ExprResultMap = HashMap<String, Expr>;
impl TreeNodeRewriter for PullUpCorrelatedExpr {
type Node = LogicalPlan;
fn f_down(&mut self, plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
let mut column_refs = BTreeSet::new();
for expr in plan.expressions() {
column_refs.extend(expr.column_refs().into_iter().cloned());
}
self.column_refs_above.push(column_refs);
self.depends_only_on_input_having_rows_above
.push(depends_only_on_input_having_rows(&plan));
match plan {
LogicalPlan::Filter(_) => Ok(Transformed::no(plan)),
LogicalPlan::Subquery(_) => {
Ok(Transformed::new(plan, false, TreeNodeRecursion::Jump))
}
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref cte))
if !cte.cte.all_out_ref_exprs().is_empty() =>
{
Ok(self.stop_pull_up(plan))
}
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
let continuation =
Arc::unwrap_or_clone(cte.continuation).rewrite(self)?;
Ok(Transformed::new(
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
MaterializedCte {
continuation: Arc::new(continuation.data),
..cte
},
)),
continuation.transformed,
TreeNodeRecursion::Jump,
))
}
LogicalPlan::Join(ref join) if !correlated_inputs_are_preserved(join) => {
Ok(self.stop_pull_up(plan))
}
LogicalPlan::AsOfJoin(ref join) if holds_outer_reference(&join.right) => {
Ok(self.stop_pull_up(plan))
}
LogicalPlan::Unnest(ref unnest)
if correlated_filter_columns(&unnest.input).iter().any(|col| {
unnest
.exec_columns
.iter()
.any(|exec_col| exec_col.name == col.name)
}) =>
{
Ok(self.stop_pull_up(plan))
}
LogicalPlan::Union(_) | LogicalPlan::Sort(_) | LogicalPlan::Extension(_) => {
if holds_outer_reference(&plan) {
Ok(self.stop_pull_up(plan))
} else {
Ok(Transformed::no(plan))
}
}
LogicalPlan::Limit(ref limit) => {
if !holds_outer_reference(&plan) {
return Ok(Transformed::no(plan));
}
if !self.exists_sub_query {
return Ok(self.stop_pull_up(plan));
}
let fetch = limit.get_fetch_type()?;
if matches!(fetch, FetchType::Literal(Some(0))) {
return Ok(Transformed::yes(LogicalPlan::EmptyRelation(
EmptyRelation {
produce_one_row: false,
schema: Arc::clone(limit.input.schema()),
},
)));
}
let (_, above) = self
.depends_only_on_input_having_rows_above
.split_last()
.expect("f_down pushed this Limit's own entry");
if !above.iter().all(|follows| *follows) {
return Ok(self.stop_pull_up(plan));
}
match (limit.get_skip_type()?, fetch) {
(SkipType::Literal(0), FetchType::Literal(_)) => {
self.column_refs_above.pop();
self.depends_only_on_input_having_rows_above.pop();
let mut t = self.f_down((*limit.input).clone())?;
t.transformed = true;
Ok(t)
}
_ => Ok(self.stop_pull_up(plan)),
}
}
LogicalPlan::Projection(_)
| LogicalPlan::Aggregate(_)
| LogicalPlan::Distinct(Distinct::All(_))
| LogicalPlan::Window(_)
| LogicalPlan::Unnest(_)
| LogicalPlan::Join(_)
| LogicalPlan::AsOfJoin(_)
| LogicalPlan::Repartition(_)
| LogicalPlan::SubqueryAlias(_)
| LogicalPlan::TableScan(_)
| LogicalPlan::EmptyRelation(_)
| LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_))
| LogicalPlan::Values(_) => {
if plan.contains_outer_reference() {
Ok(self.stop_pull_up(plan))
} else {
Ok(Transformed::no(plan))
}
}
LogicalPlan::Distinct(Distinct::On(_))
| LogicalPlan::RecursiveQuery(_)
| LogicalPlan::Statement(_)
| LogicalPlan::Explain(_)
| LogicalPlan::Analyze(_)
| LogicalPlan::Dml(_)
| LogicalPlan::Ddl(_)
| LogicalPlan::Copy(_)
| LogicalPlan::Show(_) => {
if holds_outer_reference(&plan) {
Ok(self.stop_pull_up(plan))
} else {
Ok(Transformed::no(plan))
}
}
}
}
fn f_up(&mut self, plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
self.column_refs_above.pop();
self.depends_only_on_input_having_rows_above.pop();
if !self.correlated_filters.is_empty() && may_reintroduce_nulls(&plan) {
self.correlated_filters.clear();
}
let subquery_schema = plan.schema();
match &plan {
LogicalPlan::Filter(plan_filter) => {
let subquery_filter_exprs = split_conjunction(&plan_filter.predicate);
for &expr in subquery_filter_exprs.iter().filter(|e| e.contains_outer()) {
self.can_pull_over_aggregation &= can_pullup_over_aggregation(expr);
self.can_extend_partition_by &=
is_partitionable_equality(expr, plan_filter.input.schema());
}
for expr in &subquery_filter_exprs {
if expr.contains_outer() && !self.correlated_filters.contains(expr) {
self.correlated_filters.push((*expr).clone());
}
}
let (mut join_filters, subquery_filters) =
find_join_exprs(subquery_filter_exprs);
if let Some(in_predicate) = &self.in_predicate_opt {
join_filters = remove_duplicated_filter(join_filters, in_predicate)?;
}
let correlated_subquery_cols =
collect_subquery_cols(&join_filters, subquery_schema)?;
for expr in join_filters {
if !self.join_filters.contains(&expr) {
self.join_filters.push(expr)
}
}
let mut expr_result_map_for_count_bug = HashMap::new();
let pull_up_expr_opt = if let Some(expr_result_map) =
self.collected_count_expr_map.get(&*plan_filter.input)
{
if let Some(expr) = conjunction(subquery_filters.clone()) {
filter_exprs_evaluation_result_on_empty_batch(
&expr,
Arc::clone(plan_filter.input.schema()),
expr_result_map,
&mut expr_result_map_for_count_bug,
)?
} else {
None
}
} else {
None
};
if self.exists_sub_query
&& self.pull_up_having_expr.is_some()
&& let Some(expr) = conjunction(subquery_filters.clone())
{
let unqualified_expr = expr
.transform_up(|e| {
if let Expr::Column(Column { name, .. }) = &e {
Ok(Transformed::yes(Expr::Column(
Column::new_unqualified(name),
)))
} else {
Ok(Transformed::no(e))
}
})
.data()?;
let combined = match self.pull_up_having_expr.take() {
Some(existing) => existing.and(unqualified_expr),
None => unqualified_expr,
};
self.pull_up_having_expr = Some(combined);
let new_plan =
LogicalPlanBuilder::from((*plan_filter.input).clone()).build()?;
let mut carried_correlated_cols = correlated_subquery_cols;
if let Some(existing) =
self.correlated_subquery_cols_map.get(&*plan_filter.input)
{
carried_correlated_cols.extend(existing.iter().cloned());
}
self.correlated_subquery_cols_map
.insert(new_plan.clone(), carried_correlated_cols);
if !expr_result_map_for_count_bug.is_empty() {
self.collected_count_expr_map
.insert(new_plan.clone(), expr_result_map_for_count_bug);
} else if let Some(input_map) = self
.collected_count_expr_map
.get(&*plan_filter.input)
.cloned()
{
self.collected_count_expr_map
.insert(new_plan.clone(), input_map);
}
return Ok(Transformed::yes(new_plan));
}
match (&pull_up_expr_opt, &self.pull_up_having_expr) {
(Some(_), Some(_)) => {
plan_err!("Unsupported Subquery plan")
}
(Some(_), None) => {
self.pull_up_having_expr = pull_up_expr_opt;
let new_plan =
LogicalPlanBuilder::from((*plan_filter.input).clone())
.build()?;
self.correlated_subquery_cols_map
.entry(new_plan.clone())
.or_default()
.extend(correlated_subquery_cols);
Ok(Transformed::yes(new_plan))
}
(None, _) => {
let mut plan =
LogicalPlanBuilder::from((*plan_filter.input).clone());
if let Some(expr) = conjunction(subquery_filters) {
plan = plan.filter(expr)?
}
let new_plan = plan.build()?;
self.correlated_subquery_cols_map
.entry(new_plan.clone())
.or_default()
.extend(correlated_subquery_cols);
Ok(Transformed::yes(new_plan))
}
}
}
LogicalPlan::Projection(projection)
if self.in_predicate_opt.is_some() || !self.join_filters.is_empty() =>
{
let mut local_correlated_cols = BTreeSet::new();
collect_local_correlated_cols(
&plan,
&self.correlated_subquery_cols_map,
&mut local_correlated_cols,
);
let mut missing_exprs = self.collect_missing_exprs(
&projection.expr,
&local_correlated_cols,
projection.input.schema(),
)?;
let mut expr_result_map_for_count_bug = HashMap::new();
if let Some(expr_result_map) =
self.collected_count_expr_map.get(&*projection.input)
{
proj_exprs_evaluation_result_on_empty_batch(
&missing_exprs,
projection.input.schema(),
expr_result_map,
&mut expr_result_map_for_count_bug,
)?;
if !expr_result_map_for_count_bug.is_empty() {
let un_matched_row = Expr::Column(Column::new_unqualified(
UN_MATCHED_ROW_INDICATOR.to_string(),
));
missing_exprs.push(un_matched_row);
}
}
let new_plan = LogicalPlanBuilder::from((*projection.input).clone())
.project(missing_exprs)?
.build()?;
if !expr_result_map_for_count_bug.is_empty() {
self.collected_count_expr_map
.insert(new_plan.clone(), expr_result_map_for_count_bug);
}
Ok(Transformed::yes(new_plan))
}
LogicalPlan::Aggregate(aggregate)
if self.in_predicate_opt.is_some() || !self.join_filters.is_empty() =>
{
if self.pulled_up_scalar_agg {
self.can_pull_up = false;
return Ok(Transformed::new(plan, false, TreeNodeRecursion::Stop));
}
let is_distinct = aggregate.aggr_expr.is_empty();
if !is_distinct {
self.can_pull_up = self.can_pull_up && self.can_pull_over_aggregation;
}
let mut local_correlated_cols = BTreeSet::new();
collect_local_correlated_cols(
&plan,
&self.correlated_subquery_cols_map,
&mut local_correlated_cols,
);
let mut missing_exprs = if aggregate
.group_expr
.iter()
.any(|expr| matches!(expr, Expr::GroupingSet(_)))
{
match self
.grouping_sets_pull_up_outcome(aggregate, &local_correlated_cols)
{
GroupingSetsPullUp::NoColumnsToAdd => {
aggregate.group_expr.to_vec()
}
GroupingSetsPullUp::SafeToExtend => {
self.collect_missing_exprs(
&aggregate.group_expr,
&local_correlated_cols,
aggregate.input.schema(),
)?
}
GroupingSetsPullUp::Unsafe => {
self.can_pull_up = false;
self.collect_missing_exprs(
&aggregate.group_expr,
&local_correlated_cols,
aggregate.input.schema(),
)?
}
}
} else {
self.collect_missing_exprs(
&aggregate.group_expr,
&local_correlated_cols,
aggregate.input.schema(),
)?
};
let mut expr_result_map_for_count_bug = HashMap::new();
if self.need_handle_count_bug
&& aggregate.group_expr.is_empty()
&& !missing_exprs.is_empty()
{
agg_exprs_evaluation_result_on_empty_batch(
&aggregate.aggr_expr,
aggregate.input.schema(),
&mut expr_result_map_for_count_bug,
)?;
if !expr_result_map_for_count_bug.is_empty() {
let un_matched_row = lit(true).alias(UN_MATCHED_ROW_INDICATOR);
missing_exprs.push(un_matched_row);
}
}
if aggregate.group_expr.is_empty() {
self.pulled_up_scalar_agg = true;
}
let new_plan = LogicalPlanBuilder::from((*aggregate.input).clone())
.aggregate(missing_exprs, aggregate.aggr_expr.to_vec())?
.build()?;
if !expr_result_map_for_count_bug.is_empty() {
self.collected_count_expr_map
.insert(new_plan.clone(), expr_result_map_for_count_bug);
}
Ok(Transformed::yes(new_plan))
}
LogicalPlan::SubqueryAlias(alias) => {
let mut local_correlated_cols = BTreeSet::new();
collect_local_correlated_cols(
&plan,
&self.correlated_subquery_cols_map,
&mut local_correlated_cols,
);
let mut new_correlated_cols = BTreeSet::new();
for col in local_correlated_cols.iter() {
new_correlated_cols
.insert(Column::new(Some(alias.alias.clone()), col.name.clone()));
}
let new_plan = if alias.input.schema().fields().len()
!= alias.schema.fields().len()
{
LogicalPlanBuilder::from((*alias.input).clone())
.alias(alias.alias.clone())?
.build()?
} else {
plan.clone()
};
self.correlated_subquery_cols_map
.insert(new_plan.clone(), new_correlated_cols);
if let Some(input_map) = self.collected_count_expr_map.get(&*alias.input)
{
self.collected_count_expr_map
.insert(new_plan.clone(), input_map.clone());
}
if new_plan != plan {
Ok(Transformed::yes(new_plan))
} else {
Ok(Transformed::no(plan))
}
}
LogicalPlan::Limit(limit) => {
if let Some(input_map) =
self.collected_count_expr_map.get(&*limit.input).cloned()
{
self.collected_count_expr_map
.insert(plan.clone(), input_map);
}
Ok(Transformed::no(plan))
}
LogicalPlan::Window(window) => {
let mut local_correlated_cols = BTreeSet::new();
collect_local_correlated_cols(
&plan,
&self.correlated_subquery_cols_map,
&mut local_correlated_cols,
);
if !local_correlated_cols.is_empty()
&& !window
.window_expr
.iter()
.all(|expr| partitions_by_all(expr, &local_correlated_cols))
{
if self.can_extend_partition_by && !self.pulled_up_scalar_agg {
let extended =
partition_window_by(window, &local_correlated_cols)?;
return self.pass_through_pulled_up_cols(extended);
}
self.can_pull_up = false;
}
self.pass_through_pulled_up_cols(plan)
}
LogicalPlan::Unnest(_) => self.pass_through_pulled_up_cols(plan),
_ => Ok(Transformed::no(plan)),
}
}
}
impl PullUpCorrelatedExpr {
fn stop_pull_up(&mut self, plan: LogicalPlan) -> Transformed<LogicalPlan> {
self.can_pull_up = false;
Transformed::new(plan, false, TreeNodeRecursion::Jump)
}
fn pass_through_pulled_up_cols(
&mut self,
plan: LogicalPlan,
) -> Result<Transformed<LogicalPlan>> {
if plan
.inputs()
.iter()
.any(|input| self.collected_count_expr_map.contains_key(*input))
{
self.can_pull_up = false;
}
Ok(Transformed::yes(plan.recompute_schema()?))
}
fn grouping_sets_pull_up_outcome(
&self,
aggregate: &Aggregate,
correlated_subquery_cols: &BTreeSet<Column>,
) -> GroupingSetsPullUp {
let group_expr = &aggregate.group_expr;
let grouping_sets = group_expr
.iter()
.filter_map(|expr| match expr {
Expr::GroupingSet(grouping_set) => Some(grouping_set),
_ => None,
})
.collect::<Vec<_>>();
if grouping_sets.is_empty() {
return GroupingSetsPullUp::NoColumnsToAdd;
}
let mut required_cols = correlated_subquery_cols.iter().collect::<BTreeSet<_>>();
if let Some(pull_up_having) = &self.pull_up_having_expr {
required_cols.extend(pull_up_having.column_refs());
}
required_cols.retain(|col| {
!group_expr
.iter()
.any(|expr| matches!(expr, Expr::Column(c) if c == *col))
});
if required_cols.is_empty() {
return GroupingSetsPullUp::NoColumnsToAdd;
}
let already_covered =
grouping_sets.iter().all(|grouping_set| match grouping_set {
GroupingSet::Rollup(_) | GroupingSet::Cube(_) => false,
GroupingSet::GroupingSets(sets) => sets.iter().all(|set| {
required_cols.iter().all(|col| {
set.iter()
.any(|expr| matches!(expr, Expr::Column(c) if c == *col))
})
}),
});
if already_covered {
return GroupingSetsPullUp::NoColumnsToAdd;
}
let has_empty_set = grouping_sets.iter().any(|grouping_set| match grouping_set {
GroupingSet::Rollup(_) | GroupingSet::Cube(_) => true,
GroupingSet::GroupingSets(sets) => sets.iter().any(|set| set.is_empty()),
});
let unsafe_read = self.column_refs_above.iter().flatten().any(|col| {
col.name == Aggregate::INTERNAL_GROUPING_ID || required_cols.contains(col)
});
if has_empty_set || unsafe_read {
GroupingSetsPullUp::Unsafe
} else {
GroupingSetsPullUp::SafeToExtend
}
}
fn collect_missing_exprs(
&mut self,
exprs: &[Expr],
correlated_subquery_cols: &BTreeSet<Column>,
_subquery_schema: &DFSchemaRef,
) -> Result<Vec<Expr>> {
let mut missing_exprs =
Vec::with_capacity(exprs.len() + correlated_subquery_cols.len());
for expr in exprs {
if !missing_exprs.contains(expr) {
missing_exprs.push(expr.clone())
}
}
for col in correlated_subquery_cols.iter() {
let col_expr = Expr::Column(col.clone());
if !collides_with_existing(&missing_exprs, &col_expr) {
missing_exprs.push(col_expr)
}
}
if let Some(pull_up_having) = &self.pull_up_having_expr {
for col in pull_up_having.column_refs() {
let col_expr = Expr::Column(col.clone());
let already_present = missing_exprs
.iter()
.any(|expr| matches!(expr, Expr::Column(c) if c.name == col.name))
|| collides_with_existing(&missing_exprs, &col_expr);
if !already_present {
missing_exprs.push(col_expr)
}
}
}
Ok(missing_exprs)
}
}
fn depends_only_on_input_having_rows(plan: &LogicalPlan) -> bool {
matches!(
plan,
LogicalPlan::Projection(_)
| LogicalPlan::SubqueryAlias(_)
| LogicalPlan::Sort(_)
| LogicalPlan::Window(_)
| LogicalPlan::Repartition(_)
| LogicalPlan::Distinct(Distinct::All(_))
| LogicalPlan::Aggregate(_)
| LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(_))
)
}
fn may_reintroduce_nulls(plan: &LogicalPlan) -> bool {
match plan {
LogicalPlan::Join(join) => {
matches!(
join.join_type,
JoinType::Left | JoinType::Right | JoinType::Full
)
}
LogicalPlan::Union(_) => true,
LogicalPlan::Aggregate(aggregate) => aggregate
.group_expr
.iter()
.any(|expr| matches!(expr, Expr::GroupingSet(_))),
_ => false,
}
}
fn correlated_inputs_are_preserved(join: &Join) -> bool {
let (left_preserved, right_preserved) = lr_is_preserved(join.join_type);
(left_preserved || !holds_outer_reference(&join.left))
&& (right_preserved || !holds_outer_reference(&join.right))
}
fn holds_outer_reference(plan: &LogicalPlan) -> bool {
let mut found = false;
plan.apply(|node| {
Ok(match node {
LogicalPlan::Subquery(_) => TreeNodeRecursion::Jump,
_ if node.contains_outer_reference() => {
found = true;
TreeNodeRecursion::Stop
}
_ => TreeNodeRecursion::Continue,
})
})
.expect("apply closure is infallible");
found
}
fn correlated_filter_columns(plan: &LogicalPlan) -> Vec<Column> {
let mut cols = vec![];
plan.apply(|node| {
Ok(match node {
LogicalPlan::Subquery(_) => TreeNodeRecursion::Jump,
LogicalPlan::Filter(filter) => {
for expr in split_conjunction(&filter.predicate) {
if expr.contains_outer() {
cols.extend(expr.column_refs().into_iter().cloned());
}
}
TreeNodeRecursion::Continue
}
_ => TreeNodeRecursion::Continue,
})
})
.expect("apply closure is infallible");
cols
}
fn partition_window_by(window: &Window, cols: &BTreeSet<Column>) -> Result<LogicalPlan> {
let window_expr = window
.window_expr
.iter()
.map(|expr| {
add_partition_by(expr, cols).alias_if_changed(expr.schema_name().to_string())
})
.collect::<Result<Vec<_>>>()?;
Window::try_new(window_expr, Arc::clone(&window.input)).map(LogicalPlan::Window)
}
fn add_partition_by(expr: &Expr, cols: &BTreeSet<Column>) -> Expr {
match expr {
Expr::Alias(alias) => Expr::Alias(Alias {
expr: Box::new(add_partition_by(&alias.expr, cols)),
..alias.clone()
}),
Expr::WindowFunction(window_fun) => {
let mut window_fun = window_fun.clone();
for col in cols {
let partitioned = window_fun
.params
.partition_by
.iter()
.any(|expr| matches!(expr, Expr::Column(c) if c == col));
if !partitioned {
window_fun
.params
.partition_by
.push(Expr::Column(col.clone()));
}
}
Expr::WindowFunction(window_fun)
}
_ => expr.clone(),
}
}
fn partitions_by_all(expr: &Expr, cols: &BTreeSet<Column>) -> bool {
let mut expr = expr;
while let Expr::Alias(Alias { expr: inner, .. }) = expr {
expr = inner;
}
let Expr::WindowFunction(window_fun) = expr else {
return false;
};
let partition_by = &window_fun.params.partition_by;
cols.iter().all(|col| {
partition_by
.iter()
.any(|expr| matches!(expr, Expr::Column(c) if c == col))
})
}
fn collides_with_existing(exprs: &[Expr], candidate: &Expr) -> bool {
let candidate_name = candidate.schema_name().to_string();
exprs
.iter()
.any(|expr| expr.schema_name().to_string() == candidate_name)
}
fn can_pullup_over_aggregation(expr: &Expr) -> bool {
split_column_equality(expr).is_some()
}
fn is_partitionable_equality(expr: &Expr, schema: &DFSchema) -> bool {
let Some((col_side, other)) = split_column_equality(expr) else {
return false;
};
let (col, cast_to) = match col_side {
Expr::Cast(Cast { expr, field }) => (&**expr, Some(field.data_type())),
_ => (col_side, None),
};
let Ok(col_type) = col.get_type(schema) else {
return false;
};
!other.is_volatile()
&& !has_float_leaf(&col_type)
&& cast_to.is_none_or(|to| is_injective_cast(&col_type, to))
}
fn split_column_equality(expr: &Expr) -> Option<(&Expr, &Expr)> {
let Expr::BinaryExpr(BinaryExpr {
left,
op: Operator::Eq,
right,
}) = expr
else {
return None;
};
[(&**left, &**right), (&**right, &**left)]
.into_iter()
.find(|(col_side, other)| {
let is_col = match col_side {
Expr::Column(_) => true,
Expr::Cast(Cast { expr, .. }) => matches!(&**expr, Expr::Column(_)),
_ => false,
};
is_col && !other.any_column_refs()
})
}
fn collect_local_correlated_cols(
plan: &LogicalPlan,
all_cols_map: &HashMap<LogicalPlan, BTreeSet<Column>>,
local_cols: &mut BTreeSet<Column>,
) {
for child in plan.inputs() {
if let Some(cols) = all_cols_map.get(child) {
local_cols.extend(cols.iter().cloned());
}
if !matches!(child, LogicalPlan::SubqueryAlias(_)) {
collect_local_correlated_cols(child, all_cols_map, local_cols);
}
}
}
pub(crate) fn find_join_exprs(exprs: Vec<&Expr>) -> (Vec<Expr>, Vec<Expr>) {
let mut joins = vec![];
let mut others = vec![];
for filter in exprs {
if filter.contains_outer() {
if !matches!(filter, Expr::BinaryExpr(BinaryExpr { left, op: Operator::Eq, right }) if left.eq(right))
{
joins.push(filter.clone());
}
} else {
others.push(filter.clone());
}
}
(joins, others)
}
pub(crate) fn build_join_filter<'a>(
join_filters: Vec<Expr>,
correlated_cols: impl IntoIterator<Item = &'a Column>,
subquery_alias: &str,
) -> Result<Option<Expr>> {
let correlated_cols = correlated_cols
.into_iter()
.cloned()
.collect::<BTreeSet<_>>();
conjunction(join_filters)
.map(|filter| {
replace_qualified_name(filter, &correlated_cols, subquery_alias)
.map(strip_outer_reference)
})
.transpose()
}
fn remove_duplicated_filter(
filters: Vec<Expr>,
in_predicate: &Expr,
) -> Result<Vec<Expr>> {
assert_or_internal_err!(
match in_predicate {
Expr::BinaryExpr(b) => b.op.swap() == Some(b.op),
_ => true,
},
"in_predicate must use a commutative operator"
);
Ok(filters
.into_iter()
.filter(|filter| {
let filter = &strip_outer_reference(filter.clone());
if filter == in_predicate {
return false;
}
!match (filter, in_predicate) {
(Expr::BinaryExpr(a_expr), Expr::BinaryExpr(b_expr)) => {
a_expr.op == b_expr.op
&& ((a_expr.left == b_expr.left && a_expr.right == b_expr.right)
|| (a_expr.left == b_expr.right
&& a_expr.right == b_expr.left))
}
_ => false,
}
})
.collect::<Vec<_>>())
}
fn agg_exprs_evaluation_result_on_empty_batch(
agg_expr: &[Expr],
schema: &DFSchemaRef,
expr_result_map_for_count_bug: &mut ExprResultMap,
) -> Result<()> {
let info = SimplifyContext::builder()
.with_schema(Arc::clone(schema))
.build();
let simplifier = ExprSimplifier::new(info);
for e in agg_expr.iter() {
let result_expr = e
.clone()
.transform_up(|expr| {
let new_expr = if let Expr::AggregateFunction(agg) = &expr {
let return_type = expr.get_type(schema.as_ref())?;
let default_value = agg.func.default_value(&return_type)?;
Transformed::yes(Expr::Literal(default_value, None))
} else {
Transformed::no(expr)
};
Ok(new_expr)
})
.data()?;
let result_expr = result_expr.unalias();
let result_expr = simplifier.simplify(result_expr)?;
expr_result_map_for_count_bug.insert(e.schema_name().to_string(), result_expr);
}
Ok(())
}
fn proj_exprs_evaluation_result_on_empty_batch(
proj_expr: &[Expr],
schema: &DFSchemaRef,
input_expr_result_map_for_count_bug: &ExprResultMap,
expr_result_map_for_count_bug: &mut ExprResultMap,
) -> Result<()> {
for expr in proj_expr.iter() {
let result_expr = expr
.clone()
.transform_up(|expr| {
if let Expr::Column(Column { name, .. }) = &expr {
if let Some(result_expr) =
input_expr_result_map_for_count_bug.get(name)
{
Ok(Transformed::yes(result_expr.clone()))
} else {
Ok(Transformed::no(expr))
}
} else {
Ok(Transformed::no(expr))
}
})
.data()?;
let is_constant = !expr.any_column_refs() && !expr.contains_outer();
if result_expr.ne(expr) || is_constant {
let info = SimplifyContext::builder()
.with_schema(Arc::clone(schema))
.build();
let simplifier = ExprSimplifier::new(info);
let result_expr = simplifier.simplify(result_expr)?;
let expr_name = match expr {
Expr::Alias(Alias { name, .. }) => name.to_string(),
Expr::Column(Column {
relation: _,
name,
spans: _,
}) => name.to_string(),
_ => expr.schema_name().to_string(),
};
expr_result_map_for_count_bug.insert(expr_name, result_expr);
}
}
Ok(())
}
fn filter_exprs_evaluation_result_on_empty_batch(
filter_expr: &Expr,
schema: DFSchemaRef,
input_expr_result_map_for_count_bug: &ExprResultMap,
expr_result_map_for_count_bug: &mut ExprResultMap,
) -> Result<Option<Expr>> {
let result_expr = filter_expr
.clone()
.transform_up(|expr| {
if let Expr::Column(Column { name, .. }) = &expr {
if let Some(result_expr) = input_expr_result_map_for_count_bug.get(name) {
Ok(Transformed::yes(result_expr.clone()))
} else {
Ok(Transformed::no(expr))
}
} else {
Ok(Transformed::no(expr))
}
})
.data()?;
let pull_up_expr = if result_expr.ne(filter_expr) {
let info = SimplifyContext::builder().with_schema(schema).build();
let simplifier = ExprSimplifier::new(info);
let result_expr = simplifier.simplify(result_expr)?;
match &result_expr {
Expr::Literal(ScalarValue::Null, _)
| Expr::Literal(ScalarValue::Boolean(None), _)
| Expr::Literal(ScalarValue::Boolean(Some(false)), _) => {
for (name, exprs) in input_expr_result_map_for_count_bug {
expr_result_map_for_count_bug.insert(name.clone(), exprs.clone());
}
None
}
Expr::Literal(ScalarValue::Boolean(Some(true)), _) => {
for (name, exprs) in input_expr_result_map_for_count_bug {
expr_result_map_for_count_bug.insert(name.clone(), exprs.clone());
}
Some(filter_expr.clone())
}
_ => {
for input_expr in input_expr_result_map_for_count_bug.values() {
let new_expr = Expr::Case(expr::Case {
expr: None,
when_then_expr: vec![(
Box::new(result_expr.clone()),
Box::new(input_expr.clone()),
)],
else_expr: Some(Box::new(Expr::Literal(ScalarValue::Null, None))),
});
let expr_key = new_expr.schema_name().to_string();
expr_result_map_for_count_bug.insert(expr_key, new_expr);
}
None
}
}
} else {
for (name, exprs) in input_expr_result_map_for_count_bug {
expr_result_map_for_count_bug.insert(name.clone(), exprs.clone());
}
None
};
Ok(pull_up_expr)
}
#[cfg(test)]
mod tests {
use super::*;
use arrow::datatypes::DataType;
use datafusion_expr::{col, out_ref_col};
#[test]
fn test_find_join_exprs_preserves_outer_references() {
let outer = out_ref_col(DataType::Int32, "t.a");
let correlated = col("t.a").eq(outer.clone());
let self_equality = outer.clone().eq(outer);
let local = col("t.b").gt(lit(2));
assert_eq!(
find_join_exprs(vec![&correlated, &self_equality, &local]),
(vec![correlated], vec![local])
);
}
#[test]
fn test_build_join_filter() -> Result<()> {
assert_eq!(build_join_filter(vec![], [], "sq")?, None);
let column = Column::from("t.a");
let outer = out_ref_col(DataType::Int32, "t.a");
let filters = vec![col("t.a").eq(outer.clone()), outer.gt(lit(1))];
assert_eq!(
build_join_filter(filters, [&column, &column], "sq")?,
Some(col("sq.a").eq(col("t.a")).and(col("t.a").gt(lit(1))))
);
Ok(())
}
}