use super::{CatalogTable, RelationKind, SchemaCatalog, TriggerEvent, TriggerTiming};
use std::collections::{BTreeMap, BTreeSet};
mod hierarchy;
mod shape;
mod writers;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct CatalogCountOwners {
pub table: String,
pub column: String,
pub source: String,
pub trigger: String,
pub key: String,
pub view: String,
}
#[derive(Debug, Default)]
pub struct CatalogCountOwnerAnalysis {
pub findings: Vec<CatalogCountOwners>,
pub unanalyzable: Vec<(super::CatalogObjectRef, String)>,
}
impl SchemaCatalog {
pub fn count_owners(&self) -> &CatalogCountOwnerAnalysis {
self.projections()
.count_owners
.get_or_init(|| self.collect_count_owners())
}
fn collect_count_owners(&self) -> CatalogCountOwnerAnalysis {
let mut analysis = CatalogCountOwnerAnalysis::default();
let mut computed = BTreeMap::<_, Vec<_>>::new();
for view in self.views().filter(|view| !view.materialized) {
let Ok(query) = self.try_view_query(&view.name) else {
analysis.unanalyzable.push((
super::CatalogObjectRef::View(view.name.clone()),
"view definition could not be parsed as a query".into(),
));
continue;
};
let Some((table, key)) = shape::grouped_count(&query) else {
continue;
};
if let Some(source) = self.relation(&table) {
computed
.entry((&source.name, key))
.or_default()
.push(&view.name);
}
}
if computed.is_empty() {
return analysis;
}
let effects = writers::collect(self, &mut analysis.unanalyzable);
if !effects.complete {
return analysis;
}
let increments = effects.increments();
let inheritance_parents: BTreeSet<_> = self
.tables()
.flat_map(|table| &table.inherited_from)
.filter_map(|parent| self.relation(parent).map(|table| &table.name))
.collect();
let mut findings = Vec::new();
for source in self.logical_tables() {
if inheritance_parents.contains(&source.name) {
continue;
}
for trigger in &source.triggers {
if !trigger.for_each_row
|| trigger.timing != TriggerTiming::After
|| trigger.events != [TriggerEvent::Insert]
|| trigger.when.is_some()
{
continue;
}
let Some(increment) = increments.get(&(&source.name, &trigger.name)) else {
continue;
};
let Some(parent) = self.relation(&increment.table) else {
continue;
};
if !direct_counter(self, source, parent, increment) {
continue;
}
if let Some(views) = computed.get(&(&source.name, increment.source_key.clone())) {
findings.extend(views.iter().map(|view| CatalogCountOwners {
table: parent.name.clone(),
column: increment.counter.clone(),
source: source.name.clone(),
trigger: trigger.name.clone(),
key: increment.source_key.clone(),
view: (*view).clone(),
}));
}
}
}
findings.retain(|finding| effects.counts.has_one(&finding.table, &finding.column));
findings.sort();
findings.dedup();
analysis.findings = findings;
analysis
}
}
fn direct_counter(
catalog: &SchemaCatalog,
source: &CatalogTable,
parent: &CatalogTable,
increment: &shape::Increment,
) -> bool {
hierarchy::known_ancestors(catalog, parent)
&& parent
.columns
.iter()
.any(|column| column.name == increment.counter && count_compatible(&column.data_type))
&& !has_before_update_trigger(catalog, parent)
&& source.foreign_keys.iter().any(|fk| {
fk.validated
&& !fk.deferrable
&& fk.columns == [increment.source_key.as_str()]
&& fk.referenced_columns == [increment.parent_key.as_str()]
&& catalog
.relation(&fk.referenced_table)
.is_some_and(|table| table.name == parent.name)
})
}
fn has_before_update_trigger(catalog: &SchemaCatalog, table: &CatalogTable) -> bool {
let has_trigger = |candidate: &CatalogTable| {
candidate.triggers.iter().any(|trigger| {
trigger.for_each_row
&& trigger.timing == TriggerTiming::Before
&& trigger.events.contains(&TriggerEvent::Update)
})
};
if has_trigger(table) {
return true;
}
if table.partition_of.is_none() && table.relation_kind != RelationKind::PartitionedTable {
return false;
}
hierarchy::partition_ancestors(catalog, table)
.map_or(true, |ancestors| ancestors.into_iter().any(has_trigger))
|| hierarchy::partition_descendants(catalog, &table.name)
.into_iter()
.any(has_trigger)
}
fn count_compatible(data_type: &str) -> bool {
let data_type = data_type.trim().to_ascii_lowercase();
[
"smallint", "integer", "bigint", "int2", "int4", "int8", "numeric",
]
.iter()
.any(|kind| {
data_type
.strip_prefix(kind)
.is_some_and(|rest| rest.is_empty() || rest.starts_with('('))
})
}
#[cfg(test)]
mod tests;