no-mistakes-postgres-sql 0.109.130

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
//! Recognize procedural-only chunks inside an already identified PL/pgSQL body.
use sqlparser::ast::Statement;
use sqlparser::tokenizer::{Token, TokenWithSpan};
use std::sync::Arc;
mod assignment;
pub(super) use assignment::{comma_parts as assignment_parts, target as assignment_target};
mod commands;
mod declaration;
mod labels;
mod lock_values;
pub(crate) fn procedural_values(sql: &str, declarations: bool) -> Vec<sqlparser::ast::Expr> {
    let tokens = super::super::super::unicode::tokenize_escape_continuations(sql, false);
    let mut state = BodyState { declarations };
    super::super::chunks::located_chunks(&tokens)
        .flat_map(|chunk| lock_values::lock_values(chunk, &mut state))
        .collect()
}
mod ranges;
mod sql;

/// Declaration sections last across semicolon chunks, including in nested blocks.
#[derive(Default)]
pub(crate) struct BodyState {
    pub(crate) declarations: bool,
}

pub(super) fn filter_body(
    statements: Vec<super::LocatedStatement>,
    schema_wrapper: bool,
) -> Vec<super::LocatedStatement> {
    let mut procedural = BodyState::default();
    let mut previous: Option<Arc<[TokenWithSpan]>> = None;
    let mut control = false;
    statements
        .into_iter()
        .filter_map(|mut located| {
            if let Some(tokens) = &located.chunk_tokens {
                if previous
                    .as_ref()
                    .is_none_or(|previous| !Arc::ptr_eq(previous, tokens))
                {
                    control = procedural.control_chunk(tokens);
                    previous = Some(Arc::clone(tokens));
                }
            } else {
                // A lexical failure owns no tokens and cannot inherit a preceding control chunk.
                control = false;
                if schema_wrapper {
                    if let Some(failure) = &mut located.recovery_failure {
                        failure.schema_unanalyzable = false;
                    }
                }
            }
            if is_begin_or_end(&located.statement)
                || control
                    && located
                        .recovery_failure
                        .as_ref()
                        .is_some_and(|failure| failure.schema_unanalyzable)
            {
                return None;
            }
            if control {
                located.recovery_failure = None;
            }
            if let Some(failure) = &mut located.recovery_failure {
                failure.procedural_body = true;
            }
            Some(located)
        })
        .collect()
}

impl BodyState {
    pub(crate) fn control_chunk(&mut self, tokens: &[TokenWithSpan]) -> bool {
        let normalized = ranges::normalize(tokens);
        let code: Vec<_> = normalized
            .iter()
            .map(|token| &token.token)
            .filter(|token| !matches!(token, Token::Whitespace(_) | Token::SemiColon))
            .collect();
        self.control(&code)
    }

    fn control(&mut self, code: &[&Token]) -> bool {
        let code = labels::unlabeled(code);
        if code.first().is_some_and(|token| word(token, "DECLARE")) {
            self.declarations = true;
            let tail = &code[1..];
            return if tail.first().is_some_and(|token| word(token, "BEGIN")) {
                self.control(tail)
            } else {
                tail.is_empty() || declaration::matches(tail)
            };
        }
        if code.first().is_some_and(|token| word(token, "BEGIN")) {
            self.declarations = false;
            return code.len() == 1 || self.control(&code[1..]);
        }
        if code.first().is_some_and(|token| word(token, "END")) {
            self.declarations = false;
            return labels::ending(&code[1..]);
        }
        if self.declarations {
            return declaration::matches(code);
        }
        let Some(first) = code.first() else {
            return false;
        };
        if word(first, "ELSE") {
            return code.len() == 1 || self.control(&code[1..]);
        }
        if ["IF", "ELSIF", "ELSEIF", "WHEN", "CASE"]
            .iter()
            .any(|kind| word(first, kind))
        {
            return boundary(code, "THEN").is_some_and(|at| {
                (!word(first, "IF") && !(word(first, "ELSIF") || word(first, "ELSEIF"))
                    || assignment::expression(&code[1..at]))
                    && (at + 1 == code.len() || self.control(&code[at + 1..]))
            });
        }
        if ["FOR", "WHILE", "FOREACH"]
            .iter()
            .any(|kind| word(first, kind))
        {
            return boundary(code, "LOOP").is_some_and(|at| {
                (if word(first, "FOR") {
                    commands::for_header(&code[..at])
                } else if word(first, "WHILE") {
                    assignment::expression(&code[1..at])
                } else {
                    commands::foreach_header(&code[..at])
                }) && (at + 1 == code.len()
                    || self.control(&code[at + 1..])
                    || commands::dml(&code[at + 1..]))
            });
        }
        if word(first, "LOOP") || word(first, "EXCEPTION") {
            return code.len() == 1 || self.control(&code[1..]);
        }
        if word(first, "NULL") {
            return code.len() == 1;
        }
        // RETURN QUERY carries SQL. If that SQL is unknown, keep its marker.
        if word(first, "RETURN") && code.get(1).is_some_and(|next| word(next, "QUERY")) {
            return false;
        }
        if word(first, "PERFORM") {
            return sql::perform(&code[1..]);
        }
        if ["EXIT", "CONTINUE", "RETURN", "RAISE", "ASSERT"]
            .iter()
            .any(|kind| word(first, kind))
        {
            return true;
        }
        assignment::matches(code) || commands::matches(code) || sql::matches(code)
    }
}

fn boundary(code: &[&Token], expected: &str) -> Option<usize> {
    crate::parse::procedural_boundary::find(code.iter().copied().enumerate().skip(1), expected)
}

fn word(token: &Token, expected: &str) -> bool {
    matches!(token, Token::Word(word) if word.quote_style.is_none() && word.value.eq_ignore_ascii_case(expected))
}

fn is_begin_or_end(statement: &Statement) -> bool {
    matches!(
        statement,
        Statement::StartTransaction { begin: true, .. } | Statement::Commit { end: true, .. }
    )
}

#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
mod tests;