Skip to main content

no_mistakes_postgres_sql/parse/
lenient.rs

1mod generated;
2use sqlparser::ast::Statement;
3use sqlparser::keywords::Keyword;
4use sqlparser::tokenizer::{Token, TokenWithSpan};
5use std::sync::Arc;
6
7mod chr;
8mod chunks;
9pub(crate) use chunks::next_policy_chunk;
10use chunks::split_statement_tokens;
11pub(super) use chunks::{next_non_ws, skip_ws};
12pub(crate) use generated::rewrite_located as rewrite_virtual_generated_columns_located;
13mod create_compat;
14mod fallback;
15mod pg_ast;
16pub(super) mod pg_ident;
17mod query_compat;
18mod recover;
19pub(crate) use recover::failure::extension_has_version;
20pub(super) mod rewrite;
21pub(super) mod routine_failures;
22mod source;
23pub(super) use chr::{expand_chr_encoded_sql, rewrite_chr_tokens};
24pub(crate) use recover::BodyState as ProceduralBodyState;
25pub use source::LocatedStatement;
26
27use rewrite::{rewrite_drop_index_concurrently, rewrite_referential_set_column_lists};
28
29/// Tokenize, rewrite PG18 virtual generated columns,
30/// `ON DELETE` column lists on `SET NULL` / `SET DEFAULT`, and
31/// `DROP INDEX CONCURRENTLY`, then parse each statement.
32///
33/// Unparseable `DO $tag$ … $tag$` statements are peeled so schema DDL inside
34/// the body can still parse. Remaining unparseable chunks recover `ALTER TABLE`,
35/// `CREATE TABLE`, `CREATE [UNIQUE] INDEX`, and DML after PL/pgSQL wrappers.
36pub(super) fn parse_postgres_sql_lenient(sql: &str) -> Vec<Statement> {
37    parse_with_sources(sql, false, true, false)
38        .into_iter()
39        .filter(|located| !located.function_projection)
40        .map(|located| located.statement)
41        .collect()
42}
43
44pub fn parse_postgres_body_with_function_sources(sql: &str) -> Vec<LocatedStatement> {
45    parse_with_sources(sql, true, false, true)
46}
47
48pub fn parse_postgres_sql_with_function_sources(sql: &str) -> Vec<LocatedStatement> {
49    parse_with_sources(sql, false, true, false)
50}
51
52pub(super) fn parse_postgres_sql_lenient_with_sources(
53    sql: &str,
54    normalized: &str,
55) -> Vec<LocatedStatement> {
56    parse_with_normalized_sources(sql, normalized, false, true, false)
57}
58
59fn parse_with_sources(
60    sql: &str,
61    fragment: bool,
62    allow_concurrent_detach: bool,
63    procedural_body: bool,
64) -> Vec<LocatedStatement> {
65    let normalized = super::normalize_copy_data(sql);
66    parse_with_normalized_sources(
67        sql,
68        &normalized,
69        fragment,
70        allow_concurrent_detach,
71        procedural_body,
72    )
73}
74
75fn parse_with_normalized_sources(
76    sql: &str,
77    normalized: &str,
78    fragment: bool,
79    allow_concurrent_detach: bool,
80    procedural_body: bool,
81) -> Vec<LocatedStatement> {
82    let (separated, head_map) = super::distinct_group::separate_with_head_map(normalized);
83    let mut located = super::unicode::tokenize_with_location(&separated, false);
84    let original_heads = super::original_head::OriginalHeads::capture(&located);
85    // Capture recursive headers before other compatibility rewrites can change their heads.
86    let recursive_views = super::recursive_view::prepare(&mut located);
87    let mut located = super::radix_numbers::repair(&located).unwrap_or(located);
88    super::normalize_table_queries(&mut located);
89    super::ddl_compat::normalize(&mut located);
90    let fetch = super::fetch_expression::prepare(&mut located);
91    if located.is_empty() {
92        return fallback::statements(sql, allow_concurrent_detach, procedural_body);
93    }
94    let mut tokens = located.iter().map(|token| token.token.clone()).collect();
95    generated::rewrite(&mut tokens);
96    rewrite_referential_set_column_lists(&mut tokens);
97    rewrite_drop_index_concurrently(&mut tokens);
98    let mut statements = recover::parse_chunks_with_function_calls(
99        split_statement_tokens(tokens),
100        &located,
101        allow_concurrent_detach,
102        procedural_body,
103        &recursive_views,
104    );
105    recursive_views.restore_statements(&mut statements);
106    original_heads.restore(sql, normalized, &separated, &head_map, &mut statements);
107    for statement in &mut statements {
108        super::fetch_expression::restore(&mut statement.statement, &fetch);
109        super::named_arguments::rewrite(&mut statement.statement);
110    }
111    if fragment {
112        let source: Arc<[TokenWithSpan]> = located.into();
113        for statement in &mut statements {
114            if statement.source.is_none() {
115                statement.source = Some(Arc::clone(&source));
116            }
117        }
118    }
119    statements
120}
121
122fn skip_balanced_parens(tokens: &[Token], open_at: usize) -> Option<usize> {
123    let mut depth = 0usize;
124    let mut index = open_at;
125    while index < tokens.len() {
126        match &tokens[index] {
127            Token::LParen => depth += 1,
128            Token::RParen => {
129                depth -= 1;
130                if depth == 0 {
131                    return Some(index + 1);
132                }
133            }
134            _ => {}
135        }
136        index += 1;
137    }
138    None
139}
140
141pub(super) fn keyword_of(token: &Token) -> Option<Keyword> {
142    match token {
143        Token::Word(word) => Some(word.keyword),
144        _ => None,
145    }
146}
147
148#[cfg(all(test, any(nm_shard_all, nm_shard_1)))]
149mod tests;