Skip to main content

no_mistakes_postgres_sql/
conflict.rs

1use crate::{canonical_order_keys, parse_postgres_sql, CanonicalOrderKey};
2use anyhow::{bail, Result};
3use collect::collect_statement;
4use raw::{raw_conflicts, sanitize};
5use single_row::query_is_potentially_multi_row;
6use sqlparser::ast::{Insert, SelectItem, SetExpr, TableObject};
7use std::collections::{BTreeMap, BTreeSet};
8
9mod collect;
10mod prepared;
11pub(crate) use prepared::{analyze_parsed, reliable_chunk_tokens, ConflictChunks};
12mod pinned;
13pub use pinned::{
14    expression_is_constant, SqlPinnedJoinEquality, SqlPinnedRelation, SqlPinnedSource,
15};
16mod raw;
17mod scope;
18pub use scope::SqlSourceRelation;
19#[cfg(all(test, any(nm_shard_all, nm_shard_0)))]
20mod consumer_recovery_tests;
21#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
22mod pinned_join_tests;
23#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
24mod prepared_tests;
25mod single_row;
26#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
27mod single_row_tests;
28#[cfg(all(test, any(nm_shard_all, nm_shard_0)))]
29mod tests;
30
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct SqlConflictInsertFact {
33    pub table: String,
34    pub target: SqlConflictTarget,
35    pub source: SqlInsertSourceShape,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum SqlConflictTarget {
40    Columns {
41        expressions: Vec<String>,
42        predicate: Option<String>,
43    },
44    Constraint(String),
45    Targetless,
46}
47
48#[derive(Debug, Clone, Default, PartialEq, Eq)]
49pub struct SqlInsertSourceShape {
50    pub multi_row: bool,
51    /// Set when the source reads one or more inner-joined plain relations whose top-level
52    /// equalities may bound every relation to one row via catalog unique keys.
53    pub pinned_source: Option<SqlPinnedSource>,
54    /// Select-list expressions by position, for positional `ORDER BY`; `None` with a wildcard.
55    pub select_list: Option<Vec<String>>,
56    pub order: Option<Vec<CanonicalOrderKey>>,
57    pub projections: Option<BTreeMap<String, String>>,
58    pub order_aliases: BTreeMap<String, String>,
59    /// Select-list expressions that are literals or bound parameters.
60    pub constant_projections: BTreeSet<String>,
61    /// The `FROM` relations, or `None` when they cannot be listed.
62    pub relations: Option<Vec<SqlSourceRelation>>,
63}
64
65/// Recall-safe prefilter: quoted/commented text may retain extra calls, never
66/// discard a real INSERT, including one inside a data-modifying CTE.
67#[doc(hidden)]
68pub fn may_have_insert(sql: &str) -> bool {
69    sql.as_bytes()
70        .windows(b"insert".len())
71        .any(|word| word.eq_ignore_ascii_case(b"insert"))
72}
73
74/// A conflict-only request can omit ordinary INSERTs, including malformed ones:
75/// without CONFLICT text the existing policy has no clause to analyze.
76#[doc(hidden)]
77pub fn may_have_insert_conflict(sql: &str) -> bool {
78    may_have_insert(sql)
79        && sql
80            .as_bytes()
81            .windows(b"conflict".len())
82            .any(|word| word.eq_ignore_ascii_case(b"conflict"))
83}
84
85pub fn analyze_conflict_inserts(sql: &str) -> Result<Vec<SqlConflictInsertFact>> {
86    analyze_conflict_inserts_with_binds(sql, &[])
87}
88
89/// `binds` are the `(line, column)` positions of identifiers recovered from template
90/// interpolations; only those identifiers count as bound values.
91pub fn analyze_conflict_inserts_with_binds(
92    sql: &str,
93    binds: &[(u32, u32)],
94) -> Result<Vec<SqlConflictInsertFact>> {
95    let raw = raw_conflicts(sql)?;
96    if raw.is_empty() {
97        return Ok(Vec::new());
98    }
99    let sanitized = sanitize(sql, &raw);
100    let statements = parse_postgres_sql(&sanitized)?;
101    let mut raw = raw.into_iter();
102    let mut inserts = Vec::new();
103    for statement in &statements {
104        collect_statement(statement, &mut raw, binds, &mut inserts)?;
105    }
106    if raw.next().is_some() {
107        bail!("could not align ON CONFLICT clauses with INSERT statements");
108    }
109    Ok(inserts)
110}
111
112fn analyze_insert(
113    insert: &Insert,
114    target: SqlConflictTarget,
115    binds: &[(u32, u32)],
116) -> Result<SqlConflictInsertFact> {
117    let table = match &insert.table {
118        TableObject::TableName(name) => name.to_string(),
119        _ => bail!("INSERT target is not a table name"),
120    };
121    let source = insert
122        .source
123        .as_deref()
124        .map_or(SqlInsertSourceShape::default(), |query| {
125            SqlInsertSourceShape {
126                multi_row: query_is_potentially_multi_row(query, binds),
127                pinned_source: pinned::pinned_source(query, binds),
128                select_list: single_row::select_list(query.body.as_ref()),
129                order: query.order_by.as_ref().and_then(canonical_order_keys),
130                projections: projection_map(insert, query.body.as_ref()),
131                order_aliases: order_aliases(query.body.as_ref()),
132                constant_projections: scope::constant_projections(query, binds),
133                relations: scope::source_relations(query),
134            }
135        });
136    Ok(SqlConflictInsertFact {
137        table,
138        target,
139        source,
140    })
141}
142
143fn projection_map(insert: &Insert, body: &SetExpr) -> Option<BTreeMap<String, String>> {
144    if insert.columns.is_empty() {
145        return None;
146    }
147    let SetExpr::Select(select) = body else {
148        return None;
149    };
150    if insert.columns.len() != select.projection.len() {
151        return None;
152    }
153    insert
154        .columns
155        .iter()
156        .zip(&select.projection)
157        .map(|(column, projection)| {
158            let expression = match projection {
159                SelectItem::UnnamedExpr(expression)
160                | SelectItem::ExprWithAlias {
161                    expr: expression, ..
162                } => expression.to_string(),
163                _ => return None,
164            };
165            Some((column.to_string().to_ascii_lowercase(), expression))
166        })
167        .collect()
168}
169
170fn order_aliases(body: &SetExpr) -> BTreeMap<String, String> {
171    let SetExpr::Select(select) = body else {
172        return BTreeMap::new();
173    };
174    select
175        .projection
176        .iter()
177        .filter_map(|projection| {
178            let SelectItem::ExprWithAlias { expr, alias } = projection else {
179                return None;
180            };
181            Some((alias.value.to_ascii_lowercase(), expr.to_string()))
182        })
183        .collect()
184}