use crate::erased_visit_fn::visit_expressions;
use crate::idents::visit_shallow_exprs;
pub(in crate::statements::keyed_lookups) mod wildcard_owners;
use self::wildcard_owners::WildcardOwners;
use super::super::expr_norm::function::pure_name;
use super::super::select_item_expr;
use crate::erased_visit::VisitErased;
use crate::idents::{object_name_identity, unwrap_expr};
use sqlparser::ast::{Distinct, Expr, Function, GroupByExpr, Query, Select, TableFactor, Visitor};
use std::ops::ControlFlow;
pub(super) fn select_has_discardable_outputs(
select: &Select,
plain: impl FnMut(&Expr) -> bool,
) -> bool {
select.having.is_none()
&& matches!(
select.distinct,
None | Some(Distinct::All | Distinct::Distinct)
)
&& matches!(&select.group_by, GroupByExpr::Expressions(exprs, modifiers)
if exprs.is_empty() && modifiers.is_empty())
&& select
.projection
.iter()
.filter_map(select_item_expr)
.all(plain)
}
pub(in crate::statements::keyed_lookups) fn global_aggregate_output(
select: &Select,
order_by: &[&Expr],
) -> bool {
let GroupByExpr::Expressions(keys, modifiers) = &select.group_by else {
return false;
};
if !modifiers.is_empty() {
return false;
}
if !keys.is_empty() {
return !grouping_needs_rows(&select.group_by);
}
if select.having.is_some() {
return true;
}
let mut current = WildcardOwners::default();
current.enter_select(select);
let has_aggregate =
|expr: &Expr| super::super::function_clauses::has_owned_ordinary_aggregate(expr, ¤t);
let distinct = match &select.distinct {
Some(Distinct::On(expressions)) => expressions.as_slice(),
_ => &[],
};
if select
.projection
.iter()
.filter_map(select_item_expr)
.chain(order_by.iter().copied())
.chain(distinct)
.any(has_aggregate)
{
return true;
}
let mut named_has_aggregate = false;
visit_shallow_exprs(&select.named_window, &mut |expr| {
named_has_aggregate |= has_aggregate(expr);
});
named_has_aggregate
}
pub(in crate::statements::keyed_lookups) fn plain_output(expr: &Expr) -> bool {
match unwrap_expr(expr) {
Expr::Identifier(_) | Expr::CompoundIdentifier(_) | Expr::Value(_) => true,
Expr::Subquery(query) => query
.visit_erased(&mut AggregateOwners::default())
.is_continue(),
_ => false,
}
}
fn possible_outer_aggregate(expr: &Expr, wildcard_owners: &WildcardOwners) -> ControlFlow<()> {
let Expr::Function(function) = expr else {
return ControlFlow::Continue(());
};
if function.over.is_some() || known_scalar(function) {
return ControlFlow::Continue(());
}
match wildcard_owners.uses_outside_wildcard(function, None) {
Some(true) => return ControlFlow::Break(()),
Some(false) => return ControlFlow::Continue(()),
None => {}
}
visit_expressions(function, |input| match input {
Expr::Identifier(_) | Expr::CompoundIdentifier(_) => ControlFlow::Break(()),
_ => ControlFlow::Continue(()),
})
}
pub(in crate::statements::keyed_lookups) fn known_scalar(function: &Function) -> bool {
if pure_name(function).is_some()
|| super::super::function_clauses::coalesce_arguments(function).is_some()
{
return true;
}
let identity = object_name_identity(&function.name);
identity
.strip_prefix("pg_catalog.")
.is_some_and(catalog_nonaggregate_name)
}
pub(in crate::statements::keyed_lookups) fn catalog_nonaggregate_name(name: &str) -> bool {
super::super::builtins::catalog_scalar_name(name)
|| crate::statements::SCALAR_BUILTINS.contains(&name)
|| crate::statements::SET_RETURNING_BUILTINS.contains(&name)
}
pub(in crate::statements::keyed_lookups) fn per_row_output(expr: &Expr) -> bool {
if matches!(
unwrap_expr(expr),
Expr::Identifier(_) | Expr::CompoundIdentifier(_) | Expr::Value(_) | Expr::Subquery(_)
) {
return plain_output(expr);
}
expr.visit_erased(&mut AggregateOwners::default())
.is_continue()
}
#[derive(Default)]
struct AggregateOwners {
wildcard_owners: WildcardOwners,
}
impl Visitor for AggregateOwners {
type Break = ();
fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
self.wildcard_owners.enter_query(query);
ControlFlow::Continue(())
}
fn post_visit_query(&mut self, _: &Query) -> ControlFlow<()> {
self.wildcard_owners.leave_query();
ControlFlow::Continue(())
}
fn pre_visit_select(&mut self, select: &Select) -> ControlFlow<()> {
self.wildcard_owners.enter_select(select);
ControlFlow::Continue(())
}
fn post_visit_select(&mut self, select: &Select) -> ControlFlow<()> {
self.wildcard_owners.leave_select(select);
ControlFlow::Continue(())
}
fn pre_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> {
self.wildcard_owners.enter_factor(factor);
ControlFlow::Continue(())
}
fn post_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> {
self.wildcard_owners.leave_factor(factor);
ControlFlow::Continue(())
}
fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
self.wildcard_owners.enter_expression(expr);
if self.wildcard_owners.in_query() {
return possible_outer_aggregate(expr, &self.wildcard_owners);
}
if matches!(expr, Expr::Function(function)
if function.over.is_none() && !known_scalar(function))
{
return ControlFlow::Break(());
}
ControlFlow::Continue(())
}
fn post_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
self.wildcard_owners.leave_expression(expr);
ControlFlow::Continue(())
}
}
pub(super) fn grouping_needs_rows(group_by: &GroupByExpr) -> bool {
matches!(group_by, GroupByExpr::Expressions(exprs, _) if exprs.iter().any(nonempty_group_key))
}
fn nonempty_group_key(expr: &Expr) -> bool {
match unwrap_expr(expr) {
Expr::Rollup(_) | Expr::Cube(_) => false,
Expr::GroupingSets(options) => options.iter().all(|set| set.iter().any(nonempty_group_key)),
Expr::Tuple(keys) => keys.iter().any(nonempty_group_key),
_ => true,
}
}
#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
mod tests;