no-mistakes-postgres-sql 0.109.131

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use sqlparser::{
    dialect::PostgreSqlDialect,
    tokenizer::{Span, Token, TokenWithSpan, Tokenizer, Whitespace},
};

fn is_string_literal(token: &Token) -> bool {
    matches!(
        token,
        Token::SingleQuotedString(_)
            | Token::EscapedStringLiteral(_)
            | Token::NationalStringLiteral(_)
            | Token::SingleQuotedByteStringLiteral(_)
            | Token::HexStringLiteral(_)
            | Token::UnicodeStringLiteral(_)
    )
}

pub(crate) fn canonical(
    tokens: &[TokenWithSpan],
    trim_terminators: bool,
) -> impl Iterator<Item = String> + '_ {
    let end = if trim_terminators {
        tokens
            .iter()
            .rposition(|token| !matches!(token.token, Token::Whitespace(_) | Token::SemiColon))
            .map_or(0, |index| index + 1)
    } else {
        tokens.len()
    };
    let slice = &tokens[..end];
    let mut index = 0;
    std::iter::from_fn(move || {
        while index < slice.len() {
            let token = &slice[index];
            match &token.token {
                Token::Whitespace(_) => {
                    let prev = index.checked_sub(1).map(|before| &slice[before].token);
                    let mut newline = false;
                    let mut block_comment = false;
                    while index < slice.len() {
                        let Token::Whitespace(ws) = &slice[index].token else {
                            break;
                        };
                        if matches!(ws, Whitespace::MultiLineComment(_)) {
                            block_comment = true;
                        } else if matches!(ws, Whitespace::Newline)
                            || slice[index].span.end.line > slice[index].span.start.line
                        {
                            newline = true;
                        }
                        index += 1;
                    }
                    if newline
                        && !block_comment
                        && prev.is_some_and(is_string_literal)
                        && slice
                            .get(index)
                            .is_some_and(|next| matches!(next.token, Token::SingleQuotedString(_)))
                    {
                        return Some("\n".to_string());
                    }
                }
                Token::Word(word)
                    if word.quote_style.is_none()
                        && word.value.eq_ignore_ascii_case("u")
                        && index + 2 < slice.len()
                        && matches!(slice[index + 1].token, Token::Ampersand)
                        && token.span.end == slice[index + 1].span.start
                        && slice[index + 1].span.end == slice[index + 2].span.start
                        && matches!(
                            &slice[index + 2].token,
                            Token::Word(quoted) if quoted.quote_style == Some('"')
                        ) =>
                {
                    let combined = format!("u&{}", slice[index + 2].token);
                    index += 3;
                    return Some(combined);
                }
                Token::Number(_, _) => {
                    index += 1;
                    if let Some(word) = slice.get(index).and_then(|next| match &next.token {
                        Token::Word(word)
                            if word.quote_style.is_none() && token.span.end == next.span.start =>
                        {
                            Some(word)
                        }
                        _ => None,
                    }) {
                        index += 1;
                        return Some(format!(
                            "{}{}",
                            token.token,
                            word.value.to_ascii_lowercase()
                        ));
                    }
                    return Some(token.token.to_string());
                }
                Token::Word(word) if word.quote_style.is_none() => {
                    index += 1;
                    return Some(word.value.to_ascii_lowercase());
                }
                other => {
                    index += 1;
                    return Some(other.to_string());
                }
            }
        }
        None
    })
}

fn lex_with_prefix(sql: &str) -> (Vec<TokenWithSpan>, bool) {
    let unicode = sql.contains("U&'") || sql.contains("u&'");
    if unicode {
        let raw = super::unicode::tokenize_fingerprint_literals(sql);
        if !raw.is_empty() {
            return (raw, false);
        }
    }
    let mut parsed = Vec::new();
    let prepared = super::operator_boundary::Prepared::new(sql);
    let failed = Tokenizer::new(&PostgreSqlDialect {}, prepared.sql())
        .with_unescape(false)
        .tokenize_with_location_into_buf(&mut parsed)
        .is_err();
    prepared.restore(&mut parsed);
    if unicode && failed {
        let raw = super::unicode::tokenize_fingerprint_literals(&sql[..prefix_end(sql, &parsed)]);
        if !raw.is_empty() {
            return (raw, true);
        }
    }
    (parsed, failed)
}

pub fn lex_native_with_prefix(sql: &str) -> Vec<TokenWithSpan> {
    lex_with_prefix(&super::normalize_copy_data_for_tokens(sql)).0
}

pub fn statements(tokens: &[TokenWithSpan]) -> impl Iterator<Item = (Span, Vec<String>)> + '_ {
    super::lenient::located_chunks(tokens).filter_map(|chunk| {
        let mut code = chunk
            .iter()
            .filter(|item| !matches!(item.token, Token::Whitespace(_)));
        let first = code.next()?;
        let last = code.next_back().unwrap_or(first);
        Some((
            Span::new(first.span.start, last.span.end),
            canonical(chunk, false).collect(),
        ))
    })
}

pub fn from_source(sql: &str, trim_terminators: bool) -> Vec<String> {
    let (parsed, failed) = lex_with_prefix(sql);
    let tail = failed.then(|| {
        let offset = prefix_end(sql, &parsed);
        let tail = sql[offset..].trim_start();
        tail.strip_suffix("\r\n")
            .or_else(|| tail.strip_suffix('\n'))
            .unwrap_or(tail)
            .to_owned()
    });
    canonical(&parsed, trim_terminators && !failed)
        .chain(tail)
        .collect()
}

fn prefix_end(sql: &str, parsed: &[TokenWithSpan]) -> usize {
    parsed
        .last()
        .and_then(|token| {
            let end = token.span.end;
            super::unicode::location_offset(sql, end.line, end.column)
        })
        .unwrap_or(0)
}

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