Skip to main content

no_mistakes_postgres_sql/locking/
single_row.rs

1//! Columns a `SELECT`'s base relations have pinned, by value or through a join.
2//!
3//! A catalog unique key whose columns are all pinned bounds a relation to one row, however
4//! many `IN` / `= ANY` filters sit beside it. Only top-level `AND` conjuncts of `WHERE` and of
5//! an inner join's `ON` count: an equality inside `OR`, `NOT`, an outer join, or a subquery
6//! does not bound the result.
7
8use super::relations::Relation;
9use crate::sql_names::normalize_table_name;
10use crate::statements::value::is_placeholder_ident_at;
11use sqlparser::ast::{BinaryOperator, Expr, Ident, JoinConstraint, JoinOperator, Select};
12use std::collections::BTreeMap;
13
14/// `left_table.left_column = right_table.right_column`, an inner-join or `WHERE` equality
15/// between two distinct base relations.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct JoinEquality {
18    pub left_table: String,
19    pub left_column: String,
20    pub right_table: String,
21    pub right_column: String,
22}
23
24#[derive(Default)]
25pub(super) struct Pins {
26    /// Columns of each base relation pinned to one bound value.
27    pub(super) bound: BTreeMap<String, Vec<String>>,
28    pub(super) joins: Vec<JoinEquality>,
29}
30
31enum Side {
32    Bound,
33    Column(usize, String),
34    Other,
35}
36
37pub(super) fn analyze(all: &[Relation], select: &Select, positions: &[(u32, u32)]) -> Pins {
38    let mut pins = Pins::default();
39    for relation in all.iter().filter_map(|relation| relation.table.as_ref()) {
40        pins.bound.entry(relation.clone()).or_default();
41    }
42    let mut conjuncts = Vec::new();
43    conjuncts_of(select.selection.as_ref(), &mut conjuncts);
44    for table in &select.from {
45        for join in &table.joins {
46            if let JoinOperator::Join(JoinConstraint::On(on))
47            | JoinOperator::Inner(JoinConstraint::On(on)) = &join.join_operator
48            {
49                conjuncts_of(Some(on), &mut conjuncts);
50            }
51        }
52    }
53    for (left, right) in conjuncts {
54        let (left, right) = (side(left, all, positions), side(right, all, positions));
55        match (left, right) {
56            (Side::Column(index, column), Side::Bound)
57            | (Side::Bound, Side::Column(index, column)) => {
58                if let Some(table) = &all[index].table {
59                    pins.bound.entry(table.clone()).or_default().push(column);
60                }
61            }
62            (Side::Column(a, a_column), Side::Column(b, b_column)) if a != b => {
63                if let (Some(left_table), Some(right_table)) = (&all[a].table, &all[b].table) {
64                    pins.joins.push(JoinEquality {
65                        left_table: left_table.clone(),
66                        left_column: a_column,
67                        right_table: right_table.clone(),
68                        right_column: b_column,
69                    });
70                }
71            }
72            _ => {}
73        }
74    }
75    for columns in pins.bound.values_mut() {
76        columns.sort();
77        columns.dedup();
78    }
79    pins
80}
81
82/// The `left = right` conjuncts reachable through top-level `AND` only.
83fn conjuncts_of<'a>(expr: Option<&'a Expr>, out: &mut Vec<(&'a Expr, &'a Expr)>) {
84    match expr {
85        Some(Expr::Nested(inner)) => conjuncts_of(Some(inner), out),
86        Some(Expr::BinaryOp {
87            left,
88            op: BinaryOperator::And,
89            right,
90        }) => {
91            conjuncts_of(Some(left), out);
92            conjuncts_of(Some(right), out);
93        }
94        Some(Expr::BinaryOp {
95            left,
96            op: BinaryOperator::Eq,
97            right,
98        }) => out.push((left, right)),
99        _ => {}
100    }
101}
102
103fn side(expr: &Expr, all: &[Relation], positions: &[(u32, u32)]) -> Side {
104    match expr {
105        Expr::Nested(inner) => side(inner, all, positions),
106        // A literal or `$n`, possibly cast: one value for the whole statement.
107        Expr::Value(_) => Side::Bound,
108        Expr::Cast { expr: inner, .. } => match side(inner, all, positions) {
109            Side::Bound => Side::Bound,
110            _ => Side::Other,
111        },
112        // A recovered interpolation is exactly one bound value; user-authored text that merely
113        // spells the marker is a column.
114        Expr::Identifier(ident) if is_placeholder_ident_at(ident, Some(positions)) => Side::Bound,
115        // An unqualified column is only attributable when the FROM has one relation.
116        Expr::Identifier(ident) if all.len() == 1 => relation_column(all, 0, ident),
117        Expr::CompoundIdentifier(parts) => qualified(parts, all),
118        _ => Side::Other,
119    }
120}
121
122fn qualified(parts: &[Ident], all: &[Relation]) -> Side {
123    let Some((column, qualifier)) = parts.split_last() else {
124        return Side::Other;
125    };
126    let qualifier = qualifier
127        .iter()
128        .map(ToString::to_string)
129        .collect::<Vec<_>>()
130        .join(".");
131    let qualifier = normalize_table_name(&qualifier);
132    let mut matches = all
133        .iter()
134        .enumerate()
135        .filter(|(_, relation)| relation.names.contains(&qualifier));
136    match (matches.next(), matches.next()) {
137        (Some((index, _)), None) => relation_column(all, index, column),
138        _ => Side::Other,
139    }
140}
141
142fn relation_column(all: &[Relation], index: usize, column: &Ident) -> Side {
143    let Some(table) = &all[index].table else {
144        return Side::Other;
145    };
146    // A self-join cannot tell which alias a pin belongs to, so it proves nothing.
147    let repeated = all
148        .iter()
149        .filter(|other| other.table.as_ref() == Some(table))
150        .count()
151        > 1;
152    if repeated {
153        Side::Other
154    } else {
155        Side::Column(index, normalize_table_name(&column.to_string()))
156    }
157}