no_mistakes_postgres_engine/catalog/
count_owners.rs1use super::{CatalogTable, RelationKind, SchemaCatalog, TriggerEvent, TriggerTiming};
2use std::collections::{BTreeMap, BTreeSet};
3
4mod hierarchy;
5mod shape;
6mod writers;
7
8#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
9pub struct CatalogCountOwners {
10 pub table: String,
11 pub column: String,
12 pub source: String,
13 pub trigger: String,
14 pub key: String,
15 pub view: String,
16}
17
18#[derive(Debug, Default)]
19pub struct CatalogCountOwnerAnalysis {
20 pub findings: Vec<CatalogCountOwners>,
21 pub unanalyzable: Vec<(super::CatalogObjectRef, String)>,
22}
23
24impl SchemaCatalog {
25 pub fn count_owners(&self) -> &CatalogCountOwnerAnalysis {
26 self.projections()
27 .count_owners
28 .get_or_init(|| self.collect_count_owners())
29 }
30
31 fn collect_count_owners(&self) -> CatalogCountOwnerAnalysis {
32 let mut analysis = CatalogCountOwnerAnalysis::default();
33 let mut computed = BTreeMap::<_, Vec<_>>::new();
34 for view in self.views().filter(|view| !view.materialized) {
35 let Ok(query) = self.try_view_query(&view.name) else {
36 analysis.unanalyzable.push((
37 super::CatalogObjectRef::View(view.name.clone()),
38 "view definition could not be parsed as a query".into(),
39 ));
40 continue;
41 };
42 let Some((table, key)) = shape::grouped_count(&query) else {
43 continue;
44 };
45 if let Some(source) = self.relation(&table) {
46 computed
47 .entry((&source.name, key))
48 .or_default()
49 .push(&view.name);
50 }
51 }
52 if computed.is_empty() {
53 return analysis;
54 }
55
56 let effects = writers::collect(self, &mut analysis.unanalyzable);
57 if !effects.complete {
58 return analysis;
59 }
60 let increments = effects.increments();
61 let inheritance_parents: BTreeSet<_> = self
62 .tables()
63 .flat_map(|table| &table.inherited_from)
64 .filter_map(|parent| self.relation(parent).map(|table| &table.name))
65 .collect();
66 let mut findings = Vec::new();
67 for source in self.logical_tables() {
68 if inheritance_parents.contains(&source.name) {
69 continue;
70 }
71 for trigger in &source.triggers {
72 if !trigger.for_each_row
73 || trigger.timing != TriggerTiming::After
74 || trigger.events != [TriggerEvent::Insert]
75 || trigger.when.is_some()
76 {
77 continue;
78 }
79 let Some(increment) = increments.get(&(&source.name, &trigger.name)) else {
80 continue;
81 };
82 let Some(parent) = self.relation(&increment.table) else {
83 continue;
84 };
85 if !direct_counter(self, source, parent, increment) {
86 continue;
87 }
88 if let Some(views) = computed.get(&(&source.name, increment.source_key.clone())) {
89 findings.extend(views.iter().map(|view| CatalogCountOwners {
90 table: parent.name.clone(),
91 column: increment.counter.clone(),
92 source: source.name.clone(),
93 trigger: trigger.name.clone(),
94 key: increment.source_key.clone(),
95 view: (*view).clone(),
96 }));
97 }
98 }
99 }
100 findings.retain(|finding| effects.counts.has_one(&finding.table, &finding.column));
101 findings.sort();
102 findings.dedup();
103 analysis.findings = findings;
104 analysis
105 }
106}
107
108fn direct_counter(
109 catalog: &SchemaCatalog,
110 source: &CatalogTable,
111 parent: &CatalogTable,
112 increment: &shape::Increment,
113) -> bool {
114 hierarchy::known_ancestors(catalog, parent)
115 && parent
116 .columns
117 .iter()
118 .any(|column| column.name == increment.counter && count_compatible(&column.data_type))
119 && !has_before_update_trigger(catalog, parent)
120 && source.foreign_keys.iter().any(|fk| {
121 fk.validated
122 && !fk.deferrable
123 && fk.columns == [increment.source_key.as_str()]
124 && fk.referenced_columns == [increment.parent_key.as_str()]
125 && catalog
126 .relation(&fk.referenced_table)
127 .is_some_and(|table| table.name == parent.name)
128 })
129}
130
131fn has_before_update_trigger(catalog: &SchemaCatalog, table: &CatalogTable) -> bool {
132 let has_trigger = |candidate: &CatalogTable| {
133 candidate.triggers.iter().any(|trigger| {
134 trigger.for_each_row
135 && trigger.timing == TriggerTiming::Before
136 && trigger.events.contains(&TriggerEvent::Update)
137 })
138 };
139 if has_trigger(table) {
140 return true;
141 }
142 if table.partition_of.is_none() && table.relation_kind != RelationKind::PartitionedTable {
143 return false;
144 }
145 hierarchy::partition_ancestors(catalog, table)
146 .map_or(true, |ancestors| ancestors.into_iter().any(has_trigger))
147 || hierarchy::partition_descendants(catalog, &table.name)
148 .into_iter()
149 .any(has_trigger)
150}
151
152fn count_compatible(data_type: &str) -> bool {
153 let data_type = data_type.trim().to_ascii_lowercase();
154 [
155 "smallint", "integer", "bigint", "int2", "int4", "int8", "numeric",
156 ]
157 .iter()
158 .any(|kind| {
159 data_type
160 .strip_prefix(kind)
161 .is_some_and(|rest| rest.is_empty() || rest.starts_with('('))
162 })
163}
164
165#[cfg(test)]
166mod tests;