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