use doido_core::Inflector;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AssociationKind {
BelongsTo,
HasOne,
HasMany,
HasAndBelongsToMany,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Association {
pub name: String,
pub kind: AssociationKind,
pub foreign_key: String,
pub table: String,
}
impl Association {
pub fn belongs_to(name: &str) -> Self {
Self {
name: name.to_string(),
kind: AssociationKind::BelongsTo,
foreign_key: Inflector::foreign_key(name),
table: Inflector::tableize(name),
}
}
pub fn has_one(owner: &str, name: &str) -> Self {
Self {
name: name.to_string(),
kind: AssociationKind::HasOne,
foreign_key: Inflector::foreign_key(owner),
table: Inflector::tableize(name),
}
}
pub fn has_many(owner: &str, name: &str) -> Self {
Self {
name: name.to_string(),
kind: AssociationKind::HasMany,
foreign_key: Inflector::foreign_key(owner),
table: Inflector::tableize(&Inflector::singularize(name)),
}
}
pub fn has_and_belongs_to_many(name: &str) -> Self {
Self {
name: name.to_string(),
kind: AssociationKind::HasAndBelongsToMany,
foreign_key: Inflector::foreign_key(&Inflector::singularize(name)),
table: Inflector::tableize(&Inflector::singularize(name)),
}
}
}
pub fn join_table(a: &str, b: &str) -> String {
let mut tables = [Inflector::tableize(a), Inflector::tableize(b)];
tables.sort();
format!("{}_{}", tables[0], tables[1])
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PolymorphicAssociation {
pub name: String,
pub type_column: String,
pub id_column: String,
}
impl PolymorphicAssociation {
pub fn belongs_to(name: &str) -> Self {
Self {
name: name.to_string(),
type_column: format!("{name}_type"),
id_column: format!("{name}_id"),
}
}
}
pub fn sti_type_column() -> &'static str {
"type"
}