no-mistakes-postgres-sql 0.109.130

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 sqlparser::ast::{FromTable, Query, SetExpr, Statement, TableFactor, Visitor};
use std::ops::ControlFlow;

struct ReferenceCount<'a> {
    name: &'a str,
    count: usize,
    scopes: Vec<Visibility>,
    writes: Vec<Vec<*const TableFactor>>,
}

struct Visibility {
    hidden: bool,
    early: Vec<*const Query>,
}

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

    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
        let inherited = self
            .scopes
            .last()
            .is_some_and(|scope| scope.hidden && !scope.early.contains(&(query as *const Query)));
        let mut scope = Visibility {
            hidden: inherited,
            early: Vec::new(),
        };
        if !inherited {
            if let Some(with) = &query.with {
                if let Some(index) = with
                    .cte_tables
                    .iter()
                    .position(|cte| cte_name(cte) == self.name)
                {
                    scope.hidden = true;
                    if !with.recursive {
                        scope.early.extend(
                            with.cte_tables[..=index]
                                .iter()
                                .map(|cte| cte.query.as_ref() as *const Query),
                        );
                    }
                }
            }
        }
        if !scope.hidden {
            self.count += count_table_set(&query.body, self.name);
        }
        self.scopes.push(scope);
        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.writes.push(write_targets(statement));
        ControlFlow::Continue(())
    }

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

    fn pre_visit_table_factor(&mut self, relation: &TableFactor) -> ControlFlow<()> {
        if let TableFactor::Table {
            name, args: None, ..
        } = relation
        {
            if !self.scopes.last().is_some_and(|scope| scope.hidden)
                && !self
                    .writes
                    .iter()
                    .any(|targets| targets.contains(&(relation as *const TableFactor)))
                && object_name_identity(name) == self.name
            {
                self.count += 1;
            }
        }
        ControlFlow::Continue(())
    }
}

pub(super) fn write_targets(statement: &Statement) -> Vec<*const TableFactor> {
    match statement {
        Statement::Update(update) => vec![&update.table.relation],
        Statement::Merge(merge) => vec![&merge.table],
        Statement::Delete(delete) => {
            let (FromTable::WithFromKeyword(from) | FromTable::WithoutKeyword(from)) = &delete.from;
            from.iter().map(|table| &raw const table.relation).collect()
        }
        _ => Vec::new(),
    }
}

fn count_table_set(body: &SetExpr, name: &str) -> usize {
    match body {
        SetExpr::Table(table) if table.schema_name.is_none() => usize::from(
            table
                .table_name
                .as_ref()
                .is_some_and(|ident| relation_part_key(&ident_key(ident)) == name),
        ),
        SetExpr::SetOperation { left, right, .. } => {
            count_table_set(left, name) + count_table_set(right, name)
        }
        _ => 0,
    }
}

pub(super) fn single_reference(query: &Query, later: &[sqlparser::ast::Cte], name: &str) -> bool {
    let mut references = ReferenceCount {
        name,
        count: count_table_set(&query.body, name),
        scopes: Vec::new(),
        writes: Vec::new(),
    };
    let _ = query.body.visit_erased(&mut references);
    let _ = query.order_by.visit_erased(&mut references);
    let _ = query.limit_clause.visit_erased(&mut references);
    let _ = query.fetch.visit_erased(&mut references);
    for cte in later {
        let _ = cte.query.visit_erased(&mut references);
    }
    references.count == 1
}

pub(super) fn cte_name(cte: &sqlparser::ast::Cte) -> String {
    relation_part_key(&ident_key(&cte.alias.name))
}

pub(super) fn replaceable_cte(query: &Query) -> Option<&Query> {
    let with = query.with.as_ref().filter(|with| !with.recursive)?;
    let [cte] = with.cte_tables.as_slice() else {
        return None;
    };
    let locked = &*cte.query;
    if locked.with.is_some()
        || !cte.alias.columns.is_empty()
        || !super::lock_clause::replaceable(locked, true)
        || super::lock_clause::bounds_rows(locked)
        || locked.order_by.is_some()
    {
        return None;
    }
    single_reference(query, &[], &cte_name(cte)).then_some(locked)
}