no_mistakes_postgres_sql/conflict/
pinned.rs1use super::single_row::{projection_expr, single_valued};
4use super::SqlConflictInsertFact;
5use crate::idents::{ident_key, object_name_ident};
6use sqlparser::ast::{
7 Expr, GroupByExpr, JoinConstraint, JoinOperator, ObjectName, ObjectNamePart, Query, SetExpr,
8 TableFactor, TableWithJoins, With,
9};
10
11mod predicates;
12pub(super) use predicates::expr_is_constant;
13pub use predicates::expression_is_constant;
14use predicates::{collect_pins, RelationSpec};
15
16pub(super) fn pinned_source(query: &Query, binds: &[(u32, u32)]) -> Option<SqlPinnedSource> {
19 if query.with.is_some() {
20 return None;
21 }
22 let SetExpr::Select(select) = query.body.as_ref() else {
23 return None;
24 };
25 if select.from.is_empty()
26 || has_grouping_sets(&select.group_by)
27 || !select
28 .projection
29 .iter()
30 .all(|item| projection_expr(item).is_some_and(|expr| single_valued(expr, true, binds)))
31 {
32 return None;
33 }
34 let mut specs = Vec::new();
35 let mut predicates = Vec::new();
36 for from in &select.from {
37 collect_from(from, &mut specs, &mut predicates)?;
38 }
39 if let Some(selection) = select.selection.as_ref() {
40 predicates.push(selection);
41 }
42 let mut relations: Vec<SqlPinnedRelation> = specs
43 .iter()
44 .map(|spec| SqlPinnedRelation {
45 table: spec.table.clone(),
46 columns: Vec::new(),
47 })
48 .collect();
49 let mut join_equalities = Vec::new();
50 for predicate in predicates {
51 collect_pins(
52 predicate,
53 &specs,
54 binds,
55 &mut relations,
56 &mut join_equalities,
57 );
58 }
59 let has_constant_pin = relations
60 .iter()
61 .any(|relation| !relation.columns.is_empty());
62 let all_referenced = has_constant_pin
63 && relations.iter().enumerate().all(|(index, relation)| {
64 !relation.columns.is_empty()
65 || join_equalities
66 .iter()
67 .any(|eq| eq.left_relation == index || eq.right_relation == index)
68 });
69 all_referenced.then_some(SqlPinnedSource {
70 relations,
71 join_equalities,
72 })
73}
74
75fn has_grouping_sets(group_by: &GroupByExpr) -> bool {
76 matches!(
77 group_by,
78 GroupByExpr::Expressions(exprs, _)
79 if exprs
80 .iter()
81 .any(|expr| matches!(expr, Expr::GroupingSets(_) | Expr::Cube(_) | Expr::Rollup(_)))
82 )
83}
84
85fn collect_from<'a>(
86 from: &'a TableWithJoins,
87 specs: &mut Vec<RelationSpec>,
88 predicates: &mut Vec<&'a Expr>,
89) -> Option<()> {
90 specs.push(relation_spec(&from.relation)?);
91 for join in &from.joins {
92 match &join.join_operator {
93 JoinOperator::Join(JoinConstraint::On(on))
94 | JoinOperator::Inner(JoinConstraint::On(on)) => predicates.push(on),
95 JoinOperator::CrossJoin(JoinConstraint::None) => {}
96 _ => return None,
97 }
98 specs.push(relation_spec(&join.relation)?);
99 }
100 Some(())
101}
102
103fn relation_spec(factor: &TableFactor) -> Option<RelationSpec> {
104 let TableFactor::Table {
105 name,
106 alias,
107 args: None,
108 ..
109 } = factor
110 else {
111 return None;
112 };
113 if alias
114 .as_ref()
115 .is_some_and(|alias| !alias.columns.is_empty())
116 {
117 return None;
118 }
119 let qualifier = match alias {
120 Some(alias) => ident_key(&alias.name),
121 None => ident_key(object_name_ident(name)?),
122 };
123 let qualified_table = alias.is_none().then(|| two_part_name(name)).flatten();
124 Some(RelationSpec {
125 table: name.to_string(),
126 qualifier,
127 qualified_table,
128 })
129}
130
131fn two_part_name(name: &ObjectName) -> Option<(String, String)> {
132 match name.0.as_slice() {
133 [ObjectNamePart::Identifier(schema), ObjectNamePart::Identifier(table)] => {
134 Some((ident_key(schema), ident_key(table)))
135 }
136 _ => None,
137 }
138}
139
140#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct SqlPinnedRelation {
143 pub table: String,
144 pub columns: Vec<String>,
145}
146
147#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct SqlPinnedJoinEquality {
150 pub left_relation: usize,
151 pub left_column: String,
152 pub right_relation: usize,
153 pub right_column: String,
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct SqlPinnedSource {
159 pub relations: Vec<SqlPinnedRelation>,
160 pub join_equalities: Vec<SqlPinnedJoinEquality>,
161}
162
163pub(super) fn forget_shadowed(inserts: &mut [SqlConflictInsertFact], with: &With) {
165 for insert in inserts {
166 let shadowed = insert.source.pinned_source.as_ref().is_some_and(|source| {
167 source.relations.iter().any(|pinned| {
168 let name = pinned
169 .table
170 .rsplit('.')
171 .next()
172 .unwrap_or_default()
173 .trim_matches('"');
174 with.cte_tables
175 .iter()
176 .any(|cte| cte.alias.name.value.eq_ignore_ascii_case(name))
177 })
178 });
179 if shadowed {
180 insert.source.pinned_source = None;
181 }
182 }
183}