no-mistakes-postgres-sql 0.109.130

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
mod generated;
use sqlparser::ast::Statement;
use sqlparser::keywords::Keyword;
use sqlparser::tokenizer::{Token, TokenWithSpan};
use std::sync::Arc;

mod chr;
mod chunks;
pub(super) use chunks::located_chunks;
use chunks::split_statement_tokens;
pub(crate) use chunks::{last_statement_terminator, next_policy_chunk};
pub(super) use chunks::{next_non_ws, skip_ws};
pub(crate) use generated::rewrite_located as rewrite_virtual_generated_columns_located;
mod create_compat;
mod fallback;
mod pg_ast;
pub(super) mod pg_ident;
mod query_compat;
mod recover;
pub(crate) use recover::failure::extension_has_version;
pub(super) mod rewrite;
pub(super) mod routine_failures;
mod source;
pub(super) use chr::{expand_chr_encoded_sql, rewrite_chr_tokens};
pub(crate) use recover::{procedural_values, BodyState as ProceduralBodyState};
pub use source::LocatedStatement;

use rewrite::{rewrite_drop_index_concurrently, rewrite_referential_set_column_lists};

/// Tokenize, rewrite PG18 virtual generated columns,
/// `ON DELETE` column lists on `SET NULL` / `SET DEFAULT`, and
/// `DROP INDEX CONCURRENTLY`, then parse each statement.
///
/// Unparseable `DO $tag$ … $tag$` statements are peeled so schema DDL inside
/// the body can still parse. Remaining unparseable chunks recover `ALTER TABLE`,
/// `CREATE TABLE`, `CREATE [UNIQUE] INDEX`, and DML after PL/pgSQL wrappers.
pub(super) fn parse_postgres_sql_lenient(sql: &str) -> Vec<Statement> {
    parse_with_sources(sql, false, true, false)
        .into_iter()
        .filter(|located| !located.function_projection)
        .map(|located| located.statement)
        .collect()
}

pub fn parse_postgres_body_with_function_sources(sql: &str) -> Vec<LocatedStatement> {
    parse_with_sources(sql, true, false, true)
}

pub fn parse_postgres_sql_with_function_sources(sql: &str) -> Vec<LocatedStatement> {
    parse_with_sources(sql, false, true, false)
}

pub(super) fn parse_postgres_sql_lenient_with_sources(
    sql: &str,
    normalized: &str,
) -> Vec<LocatedStatement> {
    parse_with_normalized_sources(sql, normalized, false, true, false)
}

fn parse_with_sources(
    sql: &str,
    fragment: bool,
    allow_concurrent_detach: bool,
    procedural_body: bool,
) -> Vec<LocatedStatement> {
    let normalized = super::normalize_copy_data(sql);
    parse_with_normalized_sources(
        sql,
        &normalized,
        fragment,
        allow_concurrent_detach,
        procedural_body,
    )
}

fn parse_with_normalized_sources(
    sql: &str,
    normalized: &str,
    fragment: bool,
    allow_concurrent_detach: bool,
    procedural_body: bool,
) -> Vec<LocatedStatement> {
    let (separated, head_map) = super::distinct_group::separate_with_head_map(normalized);
    let mut located = if procedural_body {
        super::unicode::tokenize_escape_continuations(&separated, false)
    } else {
        super::unicode::tokenize_with_location(&separated, false)
    };
    let original_heads = super::original_head::OriginalHeads::capture(&located);
    // Capture recursive headers before other compatibility rewrites can change their heads.
    let recursive_views = super::recursive_view::prepare(&mut located);
    let mut located = super::radix_numbers::repair(&located).unwrap_or(located);
    super::normalize_table_queries(&mut located);
    super::ddl_compat::normalize(&mut located);
    let fetch = super::fetch_expression::prepare(&mut located);
    if located.is_empty() {
        return fallback::statements(sql, allow_concurrent_detach, procedural_body);
    }
    let mut tokens = located.iter().map(|token| token.token.clone()).collect();
    generated::rewrite(&mut tokens);
    rewrite_referential_set_column_lists(&mut tokens);
    rewrite_drop_index_concurrently(&mut tokens);
    let mut statements = recover::parse_chunks_with_function_calls(
        split_statement_tokens(tokens),
        &located,
        allow_concurrent_detach,
        procedural_body,
        &recursive_views,
    );
    recursive_views.restore_statements(&mut statements);
    original_heads.restore(sql, normalized, &separated, &head_map, &mut statements);
    for statement in &mut statements {
        super::fetch_expression::restore(&mut statement.statement, &fetch);
        super::named_arguments::rewrite(&mut statement.statement);
    }
    if fragment {
        let source: Arc<[TokenWithSpan]> = located.into();
        for statement in &mut statements {
            if statement.source.is_none() {
                statement.source = Some(Arc::clone(&source));
            }
        }
    }
    statements
}

fn skip_balanced_parens(tokens: &[Token], open_at: usize) -> Option<usize> {
    let mut depth = 0usize;
    let mut index = open_at;
    while index < tokens.len() {
        match &tokens[index] {
            Token::LParen => depth += 1,
            Token::RParen => {
                depth -= 1;
                if depth == 0 {
                    return Some(index + 1);
                }
            }
            _ => {}
        }
        index += 1;
    }
    None
}

pub(super) fn keyword_of(token: &Token) -> Option<Keyword> {
    match token {
        Token::Word(word) => Some(word.keyword),
        _ => None,
    }
}

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