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 crate::idents::{ident_key, object_name_identity, relation_part_key};
use crate::statements::limit::is_zero_limited;
use sqlparser::ast::{Expr, ObjectName, Query, SetExpr, Statement, TableFactor, Visit, Visitor};
use std::{
    collections::{BTreeMap, BTreeSet},
    ops::ControlFlow,
};

mod discarded;
pub(crate) use discarded::collect as collect_discarded_exists_queries;
mod shape;
pub(super) use shape::{membership_query, predicates_of, unrestricted_projection};
mod upsert;
pub(super) use upsert::{check_delete_joins, check_merge, check_update_joins, check_upsert};

pub(super) fn check_guard(
    expr: &Expr,
    ctes: &BTreeMap<String, super::VisibleCte<'_>>,
    out: &mut Vec<super::StatementLockCheck>,
) {
    if contains_guard(expr, ctes) {
        out.push(super::StatementLockCheck::Guard);
    }
}

pub(super) fn contains_guard(
    node: &impl Visit,
    ctes: &BTreeMap<String, super::VisibleCte<'_>>,
) -> bool {
    let guards = ctes
        .iter()
        .map(|(name, cte)| (name.clone(), cte.has_guard))
        .collect();
    contains_guard_bindings(node, &guards)
}

pub(super) fn contains_guard_bindings(node: &impl Visit, guards: &BTreeMap<String, bool>) -> bool {
    node.visit_erased(&mut Guard {
        initial: guards,
        scopes: Vec::new(),
        write_targets: Vec::new(),
        discarded_queries: BTreeSet::new(),
    })
    .is_break()
}

struct Scope {
    bindings: Option<BTreeMap<String, bool>>,
    cte_bodies: Vec<*const Query>,
    skipped_locks: Vec<*const Query>,
    wrapped_skip: Option<(*const Query, Vec<Option<String>>)>,
    ignored: bool,
}

struct Guard<'a> {
    initial: &'a BTreeMap<String, bool>,
    scopes: Vec<Scope>,
    write_targets: Vec<Vec<*const TableFactor>>,
    discarded_queries: BTreeSet<*const Query>,
}

impl Guard<'_> {
    fn bindings(&self) -> &BTreeMap<String, bool> {
        self.scopes
            .iter()
            .rev()
            .find_map(|scope| scope.bindings.as_ref())
            .unwrap_or(self.initial)
    }

    fn ignored(&self) -> bool {
        self.scopes.last().is_some_and(|scope| scope.ignored)
    }
}

impl Visitor for Guard<'_> {
    type Break = ();

    fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
        if !self.ignored() {
            discarded::collect(expr, &mut self.discarded_queries);
        }
        ControlFlow::Continue(())
    }

    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
        let parent = self.scopes.last();
        let address = query as *const Query;
        let mut ignored = self.discarded_queries.contains(&address)
            || parent.is_some_and(|scope| scope.ignored || scope.cte_bodies.contains(&address));
        let skip = parent.is_some_and(|scope| scope.skipped_locks.contains(&address));
        let mut targets = super::lock_clause::skip_targets(query);
        if let Some((inner, inherited_targets)) =
            parent.and_then(|scope| scope.wrapped_skip.as_ref())
        {
            if *inner == address {
                targets.extend_from_slice(inherited_targets);
            }
        }
        let bindings = (!ignored && query.with.is_some())
            .then(|| super::cte_scope::guard_bindings(query, self.bindings()));
        if !ignored {
            let visible = bindings.as_ref().unwrap_or_else(|| self.bindings());
            let is_cte = |name: &ObjectName| visible.contains_key(&object_name_identity(name));
            if is_zero_limited(query) {
                if contains_guard_bindings(&query.limit_clause, visible) {
                    return ControlFlow::Break(());
                }
                ignored = true;
            } else if super::lock_clause::blocks_guard(query, skip, &targets, &is_cte)
                || table_guard(&query.body, visible)
            {
                return ControlFlow::Break(());
            }
        }
        self.scopes.push(Scope {
            bindings,
            ignored,
            cte_bodies: query
                .with
                .iter()
                .flat_map(|with| &with.cte_tables)
                .map(|cte| cte.query.as_ref() as *const Query)
                .collect(),
            skipped_locks: super::lock_clause::skipped_subqueries(query, skip, &targets),
            wrapped_skip: match query.body.as_ref() {
                SetExpr::Query(inner) if !targets.is_empty() => Some((inner.as_ref(), targets)),
                _ => None,
            },
        });
        ControlFlow::Continue(())
    }

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

    fn pre_visit_statement(&mut self, statement: &Statement) -> ControlFlow<()> {
        self.write_targets
            .push(super::relation_references::write_targets(statement));
        ControlFlow::Continue(())
    }

    fn post_visit_statement(&mut self, _: &Statement) -> ControlFlow<()> {
        self.write_targets.pop();
        ControlFlow::Continue(())
    }

    fn pre_visit_table_factor(&mut self, relation: &TableFactor) -> ControlFlow<()> {
        if let TableFactor::Table {
            name, args: None, ..
        } = relation
        {
            if !self.ignored()
                && self.bindings().get(&object_name_identity(name)) == Some(&true)
                && !self
                    .write_targets
                    .iter()
                    .any(|targets| targets.contains(&(relation as *const TableFactor)))
            {
                return ControlFlow::Break(());
            }
        }
        ControlFlow::Continue(())
    }
}

fn table_guard(body: &SetExpr, visible: &BTreeMap<String, bool>) -> bool {
    match body {
        SetExpr::Table(table) if table.schema_name.is_none() => table
            .table_name
            .as_ref()
            .is_some_and(|name| visible.get(&relation_part_key(&ident_key(name))) == Some(&true)),
        SetExpr::SetOperation { left, right, .. } => {
            table_guard(left, visible) || table_guard(right, visible)
        }
        _ => false,
    }
}