Skip to main content

no_mistakes_postgres_engine/embedded/dml_kind/
mod.rs

1//! Top-level DML kind after a complete `WITH` prefix, if any.
2//!
3//! Incomplete CTE lists and unknown leading keywords return `None` so callers
4//! fail closed instead of claiming a reconstructed statement.
5
6mod lex;
7
8use lex::{skip_balanced_paren, skip_ident, skip_trivia, starts_keyword};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub(crate) enum TopLevelDml {
12    Select,
13    Insert,
14    Update,
15    Delete,
16    Merge,
17}
18
19impl TopLevelDml {
20    pub(crate) fn is_insert_family(self) -> bool {
21        matches!(self, Self::Insert | Self::Merge)
22    }
23}
24
25/// True when recovered SQL is missing, incomplete, or a top-level INSERT/MERGE.
26pub fn recovered_sql_needs_insert_check(sql: Option<&str>) -> bool {
27    match sql {
28        None => true,
29        Some(sql) => top_level_dml_kind(sql).is_none_or(TopLevelDml::is_insert_family),
30    }
31}
32
33/// True when recovered SQL is missing, incomplete, or contains a query,
34/// including query-bearing DML and CTEs.
35pub fn recovered_sql_may_select(sql: Option<&str>) -> bool {
36    recovered_contains(sql, &["select"])
37}
38
39/// True when recovered SQL is missing, incomplete, or contains a column write,
40/// including data-modifying CTEs under SELECT/DELETE.
41pub fn recovered_sql_may_write_columns(sql: Option<&str>) -> bool {
42    recovered_contains(sql, &["insert", "update", "merge"])
43}
44
45fn recovered_contains(sql: Option<&str>, keywords: &[&str]) -> bool {
46    sql.is_none_or(|sql| {
47        if top_level_dml_kind(sql).is_none() {
48            return true;
49        }
50        let mut index = 0;
51        while index < sql.len() {
52            if let Some(end) = lex::skip_delimited(sql, index) {
53                index = end;
54                continue;
55            }
56            if keywords
57                .iter()
58                .any(|keyword| starts_keyword(sql, index, keyword))
59            {
60                return true;
61            }
62            index += 1;
63        }
64        false
65    })
66}
67
68pub(crate) fn top_level_dml_kind(sql: &str) -> Option<TopLevelDml> {
69    let mut index = skip_trivia(sql, 0);
70    if starts_keyword(sql, index, "with") {
71        index = skip_complete_with(sql, index)?;
72        index = skip_trivia(sql, index);
73    }
74    classify_dml(sql, index)
75}
76
77fn skip_complete_with(sql: &str, mut index: usize) -> Option<usize> {
78    index += 4;
79    index = skip_trivia(sql, index);
80    if starts_keyword(sql, index, "recursive") {
81        index += 9;
82        index = skip_trivia(sql, index);
83    }
84    loop {
85        index = skip_cte(sql, index)?;
86        index = skip_trivia(sql, index);
87        if sql.as_bytes().get(index) == Some(&b',') {
88            index = skip_trivia(sql, index + 1);
89            continue;
90        }
91        return Some(index);
92    }
93}
94
95fn skip_cte(sql: &str, mut index: usize) -> Option<usize> {
96    index = skip_ident(sql, index)?;
97    index = skip_trivia(sql, index);
98    if sql.as_bytes().get(index) == Some(&b'(') {
99        index = skip_balanced_paren(sql, index)?;
100        index = skip_trivia(sql, index);
101    }
102    if !starts_keyword(sql, index, "as") {
103        return None;
104    }
105    index = skip_trivia(sql, index + 2);
106    if starts_keyword(sql, index, "not") {
107        index = skip_trivia(sql, index + 3);
108        if !starts_keyword(sql, index, "materialized") {
109            return None;
110        }
111        index = skip_trivia(sql, index + 12);
112    } else if starts_keyword(sql, index, "materialized") {
113        index = skip_trivia(sql, index + 12);
114    }
115    skip_balanced_paren(sql, index)
116}
117
118fn classify_dml(sql: &str, index: usize) -> Option<TopLevelDml> {
119    const KINDS: &[(&str, TopLevelDml)] = &[
120        ("select", TopLevelDml::Select),
121        ("insert", TopLevelDml::Insert),
122        ("update", TopLevelDml::Update),
123        ("delete", TopLevelDml::Delete),
124        ("merge", TopLevelDml::Merge),
125    ];
126    KINDS
127        .iter()
128        .find(|(keyword, _)| starts_keyword(sql, index, keyword))
129        .map(|(_, kind)| *kind)
130}