no-mistakes-postgres-sql 0.109.131

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;
use crate::erased_visit::VisitErased;
use crate::fx::FxHashSet;
use crate::idents::ident_key;
use sqlparser::ast::{Expr, Function, FunctionArguments, Query, Select, TableFactor};

mod outer;
pub(in crate::statements::keyed_lookups) use outer::{
    belongs_to_current_select, belongs_to_root_select,
};
use outer::{current_argument, qualified_outer_argument};

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,
}

pub(in crate::statements::keyed_lookups) fn could_be_custom_aggregate(function: &Function) -> bool {
    matches!(&function.args, FunctionArguments::List(list) if !list.args.is_empty())
        && !matches!(function.name.0.as_slice(), [.., schema, _]
            if schema.as_ident().is_some_and(|schema| ident_key(schema) == "pg_catalog"))
        && !super::super::query::outputs::known_scalar(function)
}

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,
        nested: WildcardOwners,
        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 && could_be_custom_aggregate(function)
        }
    }

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

        fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
            self.nested.enter_query(query);
            self.depth += 1;
            ControlFlow::Continue(())
        }

        fn post_visit_query(&mut self, _: &Query) -> ControlFlow<()> {
            self.depth -= 1;
            self.nested.leave_query();
            ControlFlow::Continue(())
        }

        fn pre_visit_select(&mut self, select: &Select) -> ControlFlow<()> {
            self.nested.enter_select(select);
            ControlFlow::Continue(())
        }

        fn post_visit_select(&mut self, select: &Select) -> ControlFlow<()> {
            self.nested.leave_select(select);
            ControlFlow::Continue(())
        }

        fn pre_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> {
            self.nested.enter_factor(factor);
            ControlFlow::Continue(())
        }

        fn post_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> {
            self.nested.leave_factor(factor);
            ControlFlow::Continue(())
        }

        fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
            self.nested.enter_expression(expr);
            if self.blocked_depth > 0 || self.blocked_roots.remove(&std::ptr::from_ref(expr)) {
                self.blocked_depth += 1;
                return ControlFlow::Continue(());
            }
            if self.phase != Phase::GuardSelection && self.depth <= 1 {
                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.nested.in_query()
                    && matches!(expr, Expr::Function(function)
                        if function.over.is_none()
                            && !current_argument(function, &self.nested, self.current)
                            && qualified_outer_argument(function)
                            && self.current.is_none_or(|current| current_argument(function, current, None)));
                if self.depth == 0 || outer_owned {
                    (self.visit)(expr);
                }
                self.depth += 1;
            }
            ControlFlow::Continue(())
        }

        fn post_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
            self.nested.leave_expression(expr);
            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,
        nested: WildcardOwners::default(),
        blocked_depth: 0,
        blocked_roots: FxHashSet::default(),
    });
}