no-mistakes-postgres-sql 0.109.129

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::super::conditions::collect_pruned_children;
use super::super::query::outputs::wildcard_owners::WildcardOwners;
use super::super::{query::discard_exists_projection, select_item_expr};
use super::{is_eager, known_aggregate_name};
use crate::erased_visit::VisitErased;
use crate::fx::FxHashSet;
use sqlparser::ast::{Expr, Function, FunctionArguments, Query};

mod outer;

pub(in crate::statements::keyed_lookups) fn is_outer_aggregate(expr: &Expr) -> bool {
    matches!(crate::idents::unwrap_expr(expr), Expr::Function(function)
        if function.over.is_none() && is_eager(function) && qualified_outer_argument(function))
}

pub(in crate::statements::keyed_lookups) fn visit_eager_functions(
    expr: &Expr,
    visit: &mut impl FnMut(&Expr),
) {
    visit_early_functions(expr, Phase::Eager, None, visit);
}

pub(in crate::statements::keyed_lookups) fn visit_ordinary_aggregates(
    expr: &Expr,
    visit: &mut impl FnMut(&Expr),
) {
    visit_early_functions(expr, Phase::Ordinary, None, visit);
}

pub(in crate::statements::keyed_lookups) fn has_possible_ordinary_aggregate(expr: &Expr) -> bool {
    aggregate_is_possible(expr, None)
}

pub(in crate::statements::keyed_lookups) fn has_owned_ordinary_aggregate(
    expr: &Expr,
    current: &WildcardOwners,
) -> bool {
    aggregate_is_possible(expr, Some(current))
}

fn aggregate_is_possible(expr: &Expr, current: Option<&WildcardOwners>) -> bool {
    let mut has_aggregate = false;
    visit_early_functions(expr, Phase::GuardSelection, current, &mut |_| {
        has_aggregate = true;
    });
    has_aggregate
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Phase {
    Eager,
    Ordinary,
    GuardSelection,
}

fn qualified_outer_argument(function: &Function) -> bool {
    if !function.within_group.is_empty() {
        return function
            .within_group
            .iter()
            .any(|item| outer::has_reference(&item.expr))
            || function.filter.as_deref().is_some_and(outer::has_reference);
    }
    matches!(&function.args, FunctionArguments::List(list) if outer::has_reference(list))
        || WildcardOwners::default().uses_outside_wildcard(function) == Some(true)
        || function.filter.as_deref().is_some_and(outer::has_reference)
}

fn current_argument(function: &Function, current: &WildcardOwners) -> bool {
    let owned = |expr: &Expr| outer::has_current_reference(expr, current);
    if !function.within_group.is_empty() {
        return function.within_group.iter().any(|item| owned(&item.expr))
            || function.filter.as_deref().is_some_and(owned);
    }
    matches!(&function.args, FunctionArguments::List(list) if outer::has_current_reference(list, current))
        || current.uses_outside_wildcard(function) == Some(false)
        || function.filter.as_deref().is_some_and(owned)
}

fn visit_early_functions(
    expr: &Expr,
    phase: Phase,
    current: Option<&WildcardOwners>,
    visit: &mut impl FnMut(&Expr),
) {
    use sqlparser::ast::Visitor;
    use std::ops::ControlFlow;

    struct EagerFunctions<'a, F> {
        visit: &'a mut F,
        phase: Phase,
        current: Option<&'a WildcardOwners>,
        depth: usize,
        from_free_subquery: bool,
        blocked_depth: usize,
        blocked_roots: FxHashSet<*const Expr>,
    }

    impl<F> EagerFunctions<'_, F> {
        fn runs_early(&self, expr: &Expr) -> bool {
            let Expr::Function(function) = expr else {
                return false;
            };
            if self.phase != Phase::Eager && function.over.is_some() {
                return false;
            }
            is_eager(function)
                || self.phase == Phase::GuardSelection
                    && matches!(function.name.0.as_slice(), [name]
                        if name.as_ident().is_some_and(known_aggregate_name))
        }
    }

    impl<F: FnMut(&Expr)> Visitor for EagerFunctions<'_, F> {
        type Break = ();

        fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
            if self.depth == 0 {
                self.from_free_subquery = query
                    .body
                    .as_select()
                    .is_some_and(|select| select.from.is_empty());
            }
            self.depth += 1;
            ControlFlow::Continue(())
        }

        fn post_visit_query(&mut self, _: &Query) -> ControlFlow<()> {
            self.depth -= 1;
            if self.depth == 0 {
                self.from_free_subquery = false;
            }
            ControlFlow::Continue(())
        }

        fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
            if self.blocked_depth > 0 || self.blocked_roots.remove(&std::ptr::from_ref(expr)) {
                self.blocked_depth += 1;
                return ControlFlow::Continue(());
            }
            if self.depth == 0 || self.depth == 1 && self.from_free_subquery {
                collect_pruned_children(expr, &mut self.blocked_roots);
                if let Expr::Exists { subquery, .. } = expr {
                    if let Some(select) = subquery
                        .body
                        .as_select()
                        .filter(|select| discard_exists_projection(subquery, select))
                    {
                        self.blocked_roots.extend(
                            select
                                .projection
                                .iter()
                                .filter_map(select_item_expr)
                                .map(std::ptr::from_ref),
                        );
                    }
                }
            }
            if self.runs_early(expr) {
                let outer_owned = self.depth == 1
                    && self.from_free_subquery
                    && matches!(expr, Expr::Function(function)
                        if function.over.is_none() && qualified_outer_argument(function)
                            && self.current.is_none_or(|current| current_argument(function, current)));
                if self.depth == 0 || outer_owned {
                    (self.visit)(expr);
                }
                self.depth += 1;
            }
            ControlFlow::Continue(())
        }

        fn post_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
            if self.blocked_depth > 0 {
                self.blocked_depth -= 1;
                return ControlFlow::Continue(());
            }
            if self.runs_early(expr) {
                self.depth -= 1;
            }
            ControlFlow::Continue(())
        }
    }

    let _ = expr.visit_erased(&mut EagerFunctions {
        visit,
        phase,
        current,
        depth: 0,
        from_free_subquery: false,
        blocked_depth: 0,
        blocked_roots: FxHashSet::default(),
    });
}