use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use schema_core::{
DatabaseSchema, Field, IndexMapping, IndexName, IndexSchema, RelationKey, TableName,
};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct QualifiedTable {
pub schema: DatabaseSchema,
pub table: TableName,
}
impl QualifiedTable {
pub fn new(schema: DatabaseSchema, table: TableName) -> Self {
Self { schema, table }
}
}
impl fmt::Display for QualifiedTable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}", self.schema.as_ref(), self.table.as_ref())
}
}
impl PartialOrd for QualifiedTable {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for QualifiedTable {
fn cmp(&self, other: &Self) -> Ordering {
(self.schema.as_ref(), self.table.as_ref())
.cmp(&(other.schema.as_ref(), other.table.as_ref()))
}
}
#[derive(Debug, Clone, Default)]
pub struct SourceSpec {
indexes: BTreeMap<IndexName, IndexSchema>,
}
impl SourceSpec {
pub fn new(indexes: BTreeMap<IndexName, IndexSchema>) -> Self {
Self { indexes }
}
pub fn indexes(&self) -> impl Iterator<Item = (&IndexName, &IndexSchema)> {
self.indexes.iter()
}
pub fn schema(&self, index: &IndexName) -> Option<&IndexSchema> {
self.indexes.get(index)
}
pub fn index_mappings(&self) -> Vec<IndexMapping> {
self.indexes
.iter()
.map(|(name, schema)| schema.resolve(name.clone()))
.collect()
}
pub fn all_tables(&self) -> BTreeSet<QualifiedTable> {
let mut tables = BTreeSet::new();
for schema in self.indexes.values() {
tables.insert(QualifiedTable::new(
schema.db_schema.clone(),
schema.table.clone(),
));
collect_relation_tables(&schema.fields, &schema.db_schema, &mut tables);
}
tables
}
}
fn collect_relation_tables(
fields: &[Field],
db_schema: &DatabaseSchema,
out: &mut BTreeSet<QualifiedTable>,
) {
for field in fields {
if let Some(relation) = field.relation() {
out.insert(QualifiedTable::new(
db_schema.clone(),
relation.table().clone(),
));
if let RelationKey::Through(through) = relation.key() {
out.insert(QualifiedTable::new(
db_schema.clone(),
through.table.clone(),
));
}
}
collect_relation_tables(field.children(), db_schema, out);
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests;