no-mistakes-postgres-sql 0.109.129

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use crate::erased_visit::VisitErased;
use crate::statements::lock_writes::collect_discarded_exists_queries;
use crate::statements::{is_zero_limited, reachable_ctes};
use sqlparser::ast::{Expr, Query, Spanned, Statement, Visitor};
use std::collections::BTreeSet;
use std::ops::ControlFlow;

#[derive(Clone, Copy, Default)]
pub(crate) struct TriggerSource<'a> {
    pub(super) enabled: bool,
    pub(super) mapped_line: Option<&'a dyn Fn(usize) -> usize>,
}

impl TriggerSource<'_> {
    pub(super) fn line_at(self, origin: super::dynamic::Origin) -> usize {
        self.mapped_line
            .map_or(origin.line, |line_at| line_at(origin.offset))
    }
}

pub(crate) fn body_facts(
    sql: &str,
    procedural: bool,
    trigger: TriggerSource<'_>,
    declarations: bool,
) -> crate::types::SqlSchemaFileFacts {
    let located = if procedural {
        crate::parse::parse_postgres_body_with_function_sources(sql)
    } else {
        crate::parse::parse_postgres_sql_with_function_sources(sql)
    };
    let mut locks = Locks {
        sql,
        source: trigger,
        ..Locks::default()
    };
    if trigger.enabled {
        let mut executed = Vec::new();
        for statement in &located {
            if matches!(statement.statement, Statement::Prepare { .. })
                || procedural && matches!(statement.statement, Statement::Declare { .. })
            {
                continue;
            }
            crate::statements::walk_executed(&statement.statement, &mut executed);
        }
        for statement in executed {
            match statement {
                Statement::CreateView(view) if !view.materialized => {}
                Statement::CreateTable(table) if table.with_data.is_some_and(|data| !data.data) => {
                }
                _ => {
                    let _ = statement.visit_erased(&mut locks);
                }
            }
        }
        if procedural {
            locks.lines.extend(value_lines(sql, declarations, trigger));
        }
    }
    let mut facts =
        super::recovery::extract_located_migration_facts(sql, located, procedural, trigger);
    facts.trigger_row_lock_lines.extend(locks.lines);
    facts
}

pub(super) fn value_lines(sql: &str, declarations: bool, source: TriggerSource<'_>) -> Vec<usize> {
    let mut locks = Locks {
        sql,
        source,
        ..Locks::default()
    };
    for value in crate::parse::procedural_values(sql, declarations) {
        let _ = value.visit_erased(&mut locks);
    }
    locks.lines
}

#[derive(Default)]
struct Locks<'a> {
    lines: Vec<usize>,
    sql: &'a str,
    source: TriggerSource<'a>,
    discarded: BTreeSet<*const Query>,
    ignored: Vec<bool>,
}

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

    fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
        if !self.ignored.last().copied().unwrap_or(false) {
            collect_discarded_exists_queries(expr, &mut self.discarded);
        }
        ControlFlow::Continue(())
    }

    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
        let mut ignored = self.ignored.last().copied().unwrap_or(false)
            || self.discarded.contains(&std::ptr::from_ref(query));
        if !ignored {
            let zero_limit = is_zero_limited(query);
            if let Some(with) = &query.with {
                let reachable: BTreeSet<_> = reachable_ctes(query, with, zero_limit)
                    .into_iter()
                    .collect();
                self.discarded.extend(
                    with.cte_tables
                        .iter()
                        .enumerate()
                        .filter(|(index, _)| !reachable.contains(index))
                        .map(|(_, cte)| std::ptr::from_ref(cte.query.as_ref())),
                );
            }
            if zero_limit {
                let _ = query.with.visit_erased(self);
                let _ = query.limit_clause.visit_erased(self);
                ignored = true;
            }
        }
        self.ignored.push(ignored);
        if !ignored && !query.locks.is_empty() {
            let start = query.span().start;
            let line = self
                .source
                .mapped_line
                .map_or(start.line.max(1) as usize, |line_at| {
                    let offset =
                        super::dynamic::location_offset(self.sql, start.line, start.column)
                            .unwrap_or_default();
                    line_at(offset)
                });
            self.lines.push(line);
        }
        ControlFlow::Continue(())
    }

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