no-mistakes-postgres-sql 0.109.131

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::word;
use sqlparser::tokenizer::Token;

pub(super) fn unlabeled<'a>(code: &'a [&'a Token]) -> &'a [&'a Token] {
    if let [Token::ShiftLeft, label, Token::ShiftRight, rest @ ..] = code {
        // PostgreSQL permits opening labels on blocks and loops, not IF or SQL actions.
        if identifier(label)
            && rest.first().is_some_and(|token| {
                ["BEGIN", "DECLARE", "FOR", "WHILE", "FOREACH", "LOOP"]
                    .iter()
                    .any(|kind| word(token, kind))
            })
        {
            return rest;
        }
    }
    code
}

pub(super) fn ending(code: &[&Token]) -> bool {
    match code {
        [] => true,
        [kind] => ["IF", "LOOP", "CASE"].iter().any(|name| word(kind, name)) || identifier(kind),
        [kind, name] => word(kind, "LOOP") && identifier(name),
        _ => false,
    }
}

pub(super) fn identifier(token: &Token) -> bool {
    // PostgreSQL's PL/pgSQL scanner uses pl_reserved_kwlist.h, separate from SQL keywords.
    const RESERVED: [&str; 24] = [
        "all", "begin", "by", "case", "declare", "else", "end", "execute", "for", "foreach",
        "from", "if", "in", "into", "loop", "not", "null", "or", "strict", "then", "to", "using",
        "when", "while",
    ];
    matches!(token, Token::Word(word)
        if word.quote_style.is_some()
            || !RESERVED.iter().any(|name| word.value.eq_ignore_ascii_case(name)))
}