use crate::catalog::{CatalogTable, SchemaCatalog};
use std::collections::BTreeSet;
pub(super) fn known_ancestors(catalog: &SchemaCatalog, table: &CatalogTable) -> bool {
let mut seen = BTreeSet::from([table.name.as_str()]);
let mut stack = vec![table];
while let Some(current) = stack.pop() {
for ancestor in current.partition_of.iter().chain(¤t.inherited_from) {
let Some(resolved) = catalog.relation(ancestor) else {
return false;
};
if seen.insert(resolved.name.as_str()) {
stack.push(resolved);
}
}
}
true
}
pub(super) fn partition_ancestors<'a>(
catalog: &'a SchemaCatalog,
table: &'a CatalogTable,
) -> Result<Vec<&'a CatalogTable>, String> {
let mut seen = BTreeSet::from([table.name.as_str()]);
let mut ancestors = Vec::new();
let mut current = table;
while let Some(parent_name) = current.partition_of.as_deref() {
let Some(parent) = catalog.relation(parent_name) else {
return Err(format!(
"writes to partition {} with unresolved parent {parent_name}",
current.name
));
};
if !seen.insert(parent.name.as_str()) {
break;
}
ancestors.push(parent);
current = parent;
}
Ok(ancestors)
}
pub(super) fn inheritance_ancestors<'a>(
catalog: &'a SchemaCatalog,
table: &'a CatalogTable,
) -> Result<Vec<&'a CatalogTable>, String> {
let mut seen = BTreeSet::from([table.name.as_str()]);
let mut stack = vec![table];
let mut ancestors = Vec::new();
while let Some(current) = stack.pop() {
for parent_name in ¤t.inherited_from {
let Some(parent) = catalog.relation(parent_name) else {
return Err(format!(
"writes to inherited table {} with unresolved parent {parent_name}",
current.name
));
};
if seen.insert(parent.name.as_str()) {
ancestors.push(parent);
stack.push(parent);
}
}
}
Ok(ancestors)
}
pub(super) fn partition_descendants<'a>(
catalog: &'a SchemaCatalog,
root: &'a str,
) -> Vec<&'a CatalogTable> {
collect_descendants(catalog, root, |candidate, frontier| {
candidate
.partition_of
.as_deref()
.and_then(|parent| catalog.relation(parent))
.is_some_and(|parent| frontier.contains(parent.name.as_str()))
})
}
pub(super) fn inheritance_descendants<'a>(
catalog: &'a SchemaCatalog,
root: &'a str,
) -> Vec<&'a CatalogTable> {
collect_descendants(catalog, root, |candidate, frontier| {
candidate.inherited_from.iter().any(|parent| {
catalog
.relation(parent)
.is_some_and(|parent| frontier.contains(parent.name.as_str()))
})
})
}
fn collect_descendants<'a>(
catalog: &'a SchemaCatalog,
root: &'a str,
matches: impl Fn(&CatalogTable, &BTreeSet<&str>) -> bool,
) -> Vec<&'a CatalogTable> {
let mut seen = BTreeSet::from([root]);
let mut frontier = BTreeSet::from([root]);
let mut out = Vec::new();
loop {
let mut next = BTreeSet::new();
for candidate in catalog.tables() {
if !seen.contains(candidate.name.as_str()) && matches(candidate, &frontier) {
seen.insert(candidate.name.as_str());
next.insert(candidate.name.as_str());
out.push(candidate);
}
}
if next.is_empty() {
return out;
}
frontier = next;
}
}