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;
9use chunks::split_statement_tokens;
10pub(crate) use chunks::{last_statement_terminator, next_policy_chunk};
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::{procedural_values, 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 = if procedural_body {
84        super::unicode::tokenize_escape_continuations(&separated, false)
85    } else {
86        super::unicode::tokenize_with_location(&separated, false)
87    };
88    let original_heads = super::original_head::OriginalHeads::capture(&located);
89    // Capture recursive headers before other compatibility rewrites can change their heads.
90    let recursive_views = super::recursive_view::prepare(&mut located);
91    let mut located = super::radix_numbers::repair(&located).unwrap_or(located);
92    super::normalize_table_queries(&mut located);
93    super::ddl_compat::normalize(&mut located);
94    let fetch = super::fetch_expression::prepare(&mut located);
95    if located.is_empty() {
96        return fallback::statements(sql, allow_concurrent_detach, procedural_body);
97    }
98    let mut tokens = located.iter().map(|token| token.token.clone()).collect();
99    generated::rewrite(&mut tokens);
100    rewrite_referential_set_column_lists(&mut tokens);
101    rewrite_drop_index_concurrently(&mut tokens);
102    let mut statements = recover::parse_chunks_with_function_calls(
103        split_statement_tokens(tokens),
104        &located,
105        allow_concurrent_detach,
106        procedural_body,
107        &recursive_views,
108    );
109    recursive_views.restore_statements(&mut statements);
110    original_heads.restore(sql, normalized, &separated, &head_map, &mut statements);
111    for statement in &mut statements {
112        super::fetch_expression::restore(&mut statement.statement, &fetch);
113        super::named_arguments::rewrite(&mut statement.statement);
114    }
115    if fragment {
116        let source: Arc<[TokenWithSpan]> = located.into();
117        for statement in &mut statements {
118            if statement.source.is_none() {
119                statement.source = Some(Arc::clone(&source));
120            }
121        }
122    }
123    statements
124}
125
126fn skip_balanced_parens(tokens: &[Token], open_at: usize) -> Option<usize> {
127    let mut depth = 0usize;
128    let mut index = open_at;
129    while index < tokens.len() {
130        match &tokens[index] {
131            Token::LParen => depth += 1,
132            Token::RParen => {
133                depth -= 1;
134                if depth == 0 {
135                    return Some(index + 1);
136                }
137            }
138            _ => {}
139        }
140        index += 1;
141    }
142    None
143}
144
145pub(super) fn keyword_of(token: &Token) -> Option<Keyword> {
146    match token {
147        Token::Word(word) => Some(word.keyword),
148        _ => None,
149    }
150}
151
152#[cfg(all(test, any(nm_shard_all, nm_shard_1)))]
153mod tests;