no-mistakes-postgres-sql 0.109.131

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use crate::erased_visit::VisitErased;
use sqlparser::ast::{Expr, GroupByExpr, Query, SetExpr, Visitor};
use std::{collections::BTreeSet, ops::ControlFlow};

pub(crate) fn collect(expr: &Expr, queries: &mut BTreeSet<*const Query>) {
    let Expr::Exists { subquery, .. } = expr else {
        return;
    };
    let SetExpr::Select(select) = subquery.body.as_ref() else {
        return;
    };
    if !matches!(&select.group_by, GroupByExpr::Expressions(keys, modifiers) if keys.is_empty() && modifiers.is_empty())
        || select.having.is_some()
        || !super::super::lock_clause::retains_first_row(subquery.limit_clause.as_ref())
        || subquery.fetch.is_some()
        || !subquery.locks.is_empty()
    {
        return;
    }
    let mut projection = Projection::default();
    if select
        .projection
        .visit_erased(&mut projection)
        .is_continue()
        && select.distinct.visit_erased(&mut projection).is_continue()
        && select
            .named_window
            .visit_erased(&mut projection)
            .is_continue()
        && subquery
            .order_by
            .visit_erased(&mut projection)
            .is_continue()
    {
        queries.extend(projection.queries);
    }
}

#[derive(Default)]
struct Projection {
    queries: Vec<*const Query>,
    depth: usize,
}

impl Visitor for Projection {
    type Break = ();

    fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
        // Without function resolution a projection call may be an aggregate or return a set.
        if self.depth == 0
            && matches!(expr, Expr::Function(_))
            && super::membership_query(expr).is_none()
        {
            return ControlFlow::Break(());
        }
        ControlFlow::Continue(())
    }

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

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