Skip to main content

no_mistakes_postgres_sql/
dml.rs

1//! Cheap DML write-target extraction and generated-column write matching.
2
3use regex::Regex;
4use std::sync::LazyLock;
5
6#[doc(hidden)]
7pub mod writes;
8
9pub use writes::{
10    find_generated_column_writes, GeneratedColumnWrite, GeneratedTable, GeneratedTableColumns,
11};
12
13/// Matches `UPDATE`, `INSERT INTO`, and `MERGE INTO` table names.
14static WRITE_TARGET: LazyLock<Regex> = LazyLock::new(|| {
15    Regex::new(
16        r#"(?is)\b(?:UPDATE|INSERT\s+INTO|MERGE\s+INTO)\s+(?:ONLY\s+)?((?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)(?:\s*\.\s*(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*))*)"#,
17    )
18    .expect("dml write-target regex")
19});
20
21static IDENT: LazyLock<Regex> = LazyLock::new(|| {
22    Regex::new(r#"(?:"((?:[^"]|"")+)"|([A-Za-z_][\w$]*))"#).expect("dml identifier regex")
23});
24
25/// Table names targeted by UPDATE / INSERT INTO / MERGE INTO.
26///
27/// This is a cheap prefilter. It does not parse SQL. `UPDATE SET` (no table)
28/// can yield a dummy `SET` token, which later parse matching ignores.
29pub fn extract_dml_write_targets(sql: &str) -> Vec<String> {
30    let mut targets: Vec<String> = WRITE_TARGET
31        .captures_iter(sql)
32        .filter_map(|caps| {
33            caps.get(1)
34                .map(|matched| last_relation_name(matched.as_str()))
35        })
36        .filter(|name| !name.is_empty() && !name.eq_ignore_ascii_case("SET"))
37        .collect();
38    targets.sort();
39    targets.dedup();
40    targets
41}
42
43fn last_relation_name(qualified: &str) -> String {
44    IDENT
45        .captures_iter(qualified)
46        .filter_map(|caps| {
47            caps.get(1)
48                .or_else(|| caps.get(2))
49                .map(|part| part.as_str().replace("\"\"", "\""))
50        })
51        .last()
52        .unwrap_or_default()
53}
54
55#[cfg(all(test, any(nm_shard_all, nm_shard_1)))]
56mod tests;