Skip to main content

no_mistakes_postgres_sql/
parse.rs

1use sqlparser::ast::Statement;
2use sqlparser::parser::ParserError;
3use std::fmt;
4
5mod copy_data;
6mod ddl_compat;
7mod derived_table;
8mod distinct_group;
9pub(super) mod fetch_expression;
10mod function_sources;
11pub(crate) use function_sources::orphan_chunk_tokens;
12#[doc(hidden)]
13pub use function_sources::partition as partition_function_sources;
14mod lenient;
15pub(crate) use lenient::extension_has_version;
16mod lock_of_list;
17mod lock_strength;
18mod named_arguments;
19#[doc(hidden)]
20pub mod operator_boundary;
21mod original_head;
22mod prepared;
23pub use lenient::parse_postgres_body_with_function_sources;
24#[doc(hidden)]
25pub use lenient::parse_postgres_sql_with_function_sources;
26pub(crate) use lenient::rewrite::rewrite_referential_set_column_lists_located;
27#[doc(hidden)]
28pub use lenient::routine_failures::statement_lines as statement_failure_lines;
29#[doc(hidden)]
30pub use lenient::LocatedStatement;
31pub(crate) use lenient::ProceduralBodyState;
32#[doc(hidden)]
33pub use prepared::PreparedSql;
34mod radix_numbers;
35mod recursive_view;
36pub(crate) use recursive_view::RecursiveViews;
37pub mod source_comments;
38mod source_escape;
39mod source_unicode;
40mod sql_text;
41mod standalone_table;
42mod statement_head;
43mod table_boundary;
44mod table_only;
45use sql_text::located_statements;
46pub(super) use sql_text::{normalize_copy_data, normalize_copy_data_for_tokens};
47pub(super) mod unicode;
48mod unicode_decode;
49
50/// Match the built-in language using PostgreSQL identifier casing.
51pub(super) fn is_plpgsql_language(token: &sqlparser::tokenizer::Token) -> bool {
52    matches!(token, sqlparser::tokenizer::Token::Word(language)
53        if language.value == "plpgsql"
54            || language.quote_style.is_none() && language.value.eq_ignore_ascii_case("plpgsql"))
55}
56
57/// Parse failure for PostgreSQL SQL. Never panics.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct PostgresParseError {
60    pub message: String,
61}
62
63impl fmt::Display for PostgresParseError {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.write_str(&self.message)
66    }
67}
68
69impl std::error::Error for PostgresParseError {}
70
71impl From<ParserError> for PostgresParseError {
72    fn from(error: ParserError) -> Self {
73        let message = match error {
74            ParserError::ParserError(message) | ParserError::TokenizerError(message) => message,
75            ParserError::RecursionLimitExceeded => error.to_string(),
76        };
77        Self { message }
78    }
79}
80
81/// Parse `sql` with the PostgreSQL dialect.
82pub fn parse_postgres_sql(sql: &str) -> Result<Vec<Statement>, PostgresParseError> {
83    PreparedSql::new(sql).parse()
84}
85
86/// Parse a standalone PostgreSQL expression via `SELECT <expression>`.
87pub fn parse_postgres_expression(expression: &str) -> Option<sqlparser::ast::Expr> {
88    let mut statements = parse_postgres_sql(&format!("SELECT {expression}")).ok()?;
89    let Statement::Query(query) = statements.pop()? else {
90        return None;
91    };
92    let sqlparser::ast::SetExpr::Select(select) = *query.body else {
93        return None;
94    };
95    (select.projection.len() == 1).then_some(())?;
96    match select.projection.into_iter().next()? {
97        sqlparser::ast::SelectItem::UnnamedExpr(expression)
98        | sqlparser::ast::SelectItem::ExprWithAlias {
99            expr: expression, ..
100        } => Some(expression),
101        _ => None,
102    }
103}
104
105pub(super) struct PreparedPostgresTokens {
106    pub tokens: Vec<sqlparser::tokenizer::TokenWithSpan>,
107    /// Pre-rewrite lexical tokens for procedural occurrence classification.
108    /// Ordinary preparation leaves this empty. A procedural walk retains the
109    /// inventory so `FOR UPDATE OF a, b` is not expanded into duplicate DML facts.
110    pub occurrence_tokens: Vec<sqlparser::tokenizer::TokenWithSpan>,
111    pub recursive_views: RecursiveViews,
112    pub lexical_error: Option<sqlparser::tokenizer::TokenizerError>,
113}
114
115/// Prepare one source-fact token inventory while retaining a valid lexical prefix.
116pub(super) fn prepare_postgres_tokens(sql: &str) -> PreparedPostgresTokens {
117    prepare_postgres_tokens_inner(sql, false)
118}
119
120/// Prepare tokens and retain the pre-rewrite inventory for a procedural walk.
121pub(crate) fn prepare_postgres_tokens_for_walk(sql: &str) -> PreparedPostgresTokens {
122    prepare_postgres_tokens_inner(sql, true)
123}
124
125fn prepare_postgres_tokens_inner(
126    sql: &str,
127    retain_occurrence_tokens: bool,
128) -> PreparedPostgresTokens {
129    let normalized = normalize_copy_data(sql);
130    let separated = distinct_group::separate_distinct_grouping(&normalized);
131    let escaped = source_escape::prepare(&separated);
132    let boundary = operator_boundary::Prepared::new(&escaped.sql);
133    let mut tokens = Vec::new();
134    let mut lexical_error =
135        sqlparser::tokenizer::Tokenizer::new(&source_unicode::SourceDialect, boundary.sql())
136            .tokenize_with_location_into_buf(&mut tokens)
137            .err();
138    boundary.restore(&mut tokens);
139    if let Some(error) = &mut lexical_error {
140        boundary.restore_error(error);
141    }
142    escaped.restore(&mut tokens);
143    source_unicode::prepare(&mut tokens);
144    let mut tokens = radix_numbers::repair(&tokens).unwrap_or(tokens);
145    let occurrence_tokens = if retain_occurrence_tokens {
146        tokens.clone()
147    } else {
148        Vec::new()
149    };
150    normalize_table_queries(&mut tokens);
151    let recursive_views = recursive_view::prepare(&mut tokens);
152    PreparedPostgresTokens {
153        tokens,
154        occurrence_tokens,
155        recursive_views,
156        lexical_error,
157    }
158}
159
160fn normalize_table_queries(tokens: &mut Vec<sqlparser::tokenizer::TokenWithSpan>) {
161    table_only::normalize(tokens);
162    derived_table::normalize(tokens);
163    standalone_table::normalize(tokens);
164    table_boundary::normalize(tokens);
165    lock_strength::normalize(tokens);
166    lock_of_list::normalize(tokens);
167}
168
169/// Parse `sql`, skipping unparseable statements instead of failing the file.
170/// Peels `DO $tag$` bodies, rewrites PostgreSQL 18 `GENERATED ... VIRTUAL` to
171/// `STORED`, and strips `ON DELETE SET NULL/DEFAULT` column lists before parse.
172pub fn parse_postgres_sql_lenient(sql: &str) -> Vec<Statement> {
173    lenient::parse_postgres_sql_lenient(sql)
174}
175
176#[doc(hidden)]
177pub fn parse_postgres_sql_lenient_with_sources(
178    sql: &str,
179    normalized: &str,
180) -> Vec<LocatedStatement> {
181    lenient::parse_postgres_sql_lenient_with_sources(sql, normalized)
182}
183
184pub(crate) fn expand_chr_encoded_sql(sql: &str) -> Option<String> {
185    lenient::expand_chr_encoded_sql(sql)
186}
187
188#[cfg(all(test, any(nm_shard_all, nm_shard_0)))]
189mod analyze_list_tests;
190#[cfg(all(test, any(nm_shard_all, nm_shard_1)))]
191mod expression_tests;
192#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
193mod radix_first_tests;
194#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
195mod radix_large_tests;
196#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
197mod radix_lenient_tests;
198#[cfg(all(test, any(nm_shard_all, nm_shard_1)))]
199mod recovered_hex_tests;
200#[cfg(all(test, any(nm_shard_all, nm_shard_1)))]
201mod tests;
202#[cfg(all(test, any(nm_shard_all, nm_shard_1)))]
203mod uppercase_hex_tests;