no-mistakes-postgres-sql 0.109.124

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::{keyword_of, next_non_ws};
use sqlparser::keywords::Keyword;
use sqlparser::tokenizer::{Token, TokenWithSpan, Whitespace};

mod column;
mod members;

use members::action_list_matches_foreign_key;

/// Drop PostgreSQL column lists on `ON DELETE SET NULL` and
/// `ON DELETE SET DEFAULT`. sqlparser 0.63 rejects `SET NULL (column)`, which
/// hides the named `NOT VALID` add and makes a later `VALIDATE CONSTRAINT`
/// look unmatched. The action keyword stays, so the recorded delete action is
/// still `SET NULL` or `SET DEFAULT`. Only a nonempty comma-separated
/// identifier list is removed, and only when every name is one of the
/// foreign key's referencing columns. Empty lists, expressions, unquoted
/// reserved words, columns outside the key, `ON UPDATE` lists, and column
/// `SET DEFAULT (expression)` stay, so invalid SQL is not rewritten into a
/// constraint PostgreSQL would accept.
pub(super) fn rewrite_referential_set_column_lists(tokens: &mut Vec<Token>) {
    for (open, end) in referential_set_column_list_ranges(tokens).into_iter().rev() {
        tokens.drain(open..end);
    }
}

/// Apply the same validated rewrite without shifting source positions used by
/// the structured procedural parser. The original source and occurrence tokens
/// remain available for reporting.
pub(crate) fn rewrite_referential_set_column_lists_located(tokens: &mut [TokenWithSpan]) {
    let plain = tokens
        .iter()
        .map(|token| token.token.clone())
        .collect::<Vec<_>>();
    for (open, end) in referential_set_column_list_ranges(&plain) {
        for token in &mut tokens[open..end] {
            token.token = Token::Whitespace(Whitespace::Space);
        }
    }
}

fn referential_set_column_list_ranges(tokens: &[Token]) -> Vec<(usize, usize)> {
    let mut ranges = Vec::new();
    let mut index = 0;
    while index < tokens.len() {
        if let Some((open, end)) = referential_set_column_list_at(tokens, index) {
            ranges.push((open, end));
            index = end;
            continue;
        }
        index += 1;
    }
    ranges
}

fn referential_set_column_list_at(tokens: &[Token], on_at: usize) -> Option<(usize, usize)> {
    if keyword_of(tokens.get(on_at)?) != Some(Keyword::ON) {
        return None;
    }
    let action_at = next_non_ws(tokens, on_at + 1)?;
    if keyword_of(tokens.get(action_at)?) != Some(Keyword::DELETE) {
        return None;
    }
    let set_at = next_non_ws(tokens, action_at + 1)?;
    if keyword_of(tokens.get(set_at)?) != Some(Keyword::SET) {
        return None;
    }
    let value_at = next_non_ws(tokens, set_at + 1)?;
    match keyword_of(tokens.get(value_at)?) {
        Some(Keyword::NULL | Keyword::DEFAULT) => {}
        _ => return None,
    }
    let open = next_non_ws(tokens, value_at + 1)?;
    if !matches!(tokens.get(open)?, Token::LParen) {
        return None;
    }
    let end = super::skip_balanced_parens(tokens, open)?;
    action_list_matches_foreign_key(tokens, open, end, on_at).then_some((open, end))
}

pub(super) fn rewrite_drop_index_concurrently(tokens: &mut Vec<Token>) {
    let mut index = 0;
    while index < tokens.len() {
        if keyword_of(&tokens[index]) == Some(Keyword::DROP) {
            if let Some(concurrent) = drop_index_concurrently_at(tokens, index) {
                tokens.remove(concurrent);
                continue;
            }
        }
        index += 1;
    }
}

fn drop_index_concurrently_at(tokens: &[Token], drop_at: usize) -> Option<usize> {
    let index_at = next_non_ws(tokens, drop_at + 1)?;
    if keyword_of(&tokens[index_at]) != Some(Keyword::INDEX) {
        return None;
    }
    let concurrent_at = next_non_ws(tokens, index_at + 1)?;
    (keyword_of(&tokens[concurrent_at]) == Some(Keyword::CONCURRENTLY)).then_some(concurrent_at)
}

pub(super) fn rewrite_chr_calls(tokens: &mut Vec<Token>) {
    let mut index = 0;
    while index < tokens.len() {
        if let Some((end, value)) = chr_call_at(tokens, index) {
            tokens.splice(index..=end, [Token::SingleQuotedString(value)]);
        }
        index += 1;
    }
}

fn chr_call_at(tokens: &[Token], start: usize) -> Option<(usize, String)> {
    if !is_chr_ident(&tokens[start]) {
        return None;
    }
    let open = next_non_ws(tokens, start + 1)?;
    if !matches!(tokens.get(open)?, Token::LParen) {
        return None;
    }
    let number_at = next_non_ws(tokens, open + 1)?;
    let Token::Number(raw, _) = tokens.get(number_at)? else {
        return None;
    };
    let code = raw.parse::<u32>().ok()?;
    let value = char::from_u32(code)?.to_string();
    let close = next_non_ws(tokens, number_at + 1)?;
    matches!(tokens.get(close)?, Token::RParen).then_some((close, value))
}

fn is_chr_ident(token: &Token) -> bool {
    matches!(token, Token::Word(word) if word.value.eq_ignore_ascii_case("chr"))
}

#[cfg(all(test, any(nm_shard_all, nm_shard_0)))]
#[path = "rewrite/tests.rs"]
mod tests;