use std::borrow::Cow;
use crate::column::Column;
use crate::model::Model;
use crate::relations::belongs_to::BelongsTo;
use crate::relations::belongs_to_many::{BelongsToMany, Pivot};
use crate::relations::has::{HasMany, HasOne};
use crate::relations::morph::MorphTo;
use crate::relations::through::{HasManyThrough, HasOneThrough, PendingThrough};
pub trait KeyColumn<M> {
#[doc(hidden)]
fn key_column(&self) -> Cow<'static, str>;
}
impl<M, T> KeyColumn<M> for Column<M, T> {
fn key_column(&self) -> Cow<'static, str> {
Cow::Owned(
crate::ir::ColumnRef::parse(self.name().to_owned())
.name
.into_owned(),
)
}
}
impl<M> KeyColumn<M> for &'static str {
fn key_column(&self) -> Cow<'static, str> {
Cow::Borrowed(self)
}
}
impl<M> KeyColumn<M> for String {
fn key_column(&self) -> Cow<'static, str> {
Cow::Owned(self.clone())
}
}
pub trait Relationships: Model {
fn belongs_to<R: Model, T>(&self, foreign_key: Column<Self, T>) -> BelongsTo<Self, R> {
BelongsTo::new(
Some(self.clone()),
KeyColumn::<Self>::key_column(&foreign_key),
)
}
fn has_one<R: Model, T>(&self, foreign_key: Column<R, T>) -> HasOne<Self, R> {
HasOne::new(Some(self.clone()), KeyColumn::<R>::key_column(&foreign_key))
}
fn has_many<R: Model, T>(&self, foreign_key: Column<R, T>) -> HasMany<Self, R> {
HasMany::new(Some(self.clone()), KeyColumn::<R>::key_column(&foreign_key))
}
fn belongs_to_many<R: Model>(
&self,
table: impl Into<Cow<'static, str>>,
) -> BelongsToMany<Self, R, Pivot> {
BelongsToMany::new(Some(self.clone()), table.into())
}
fn has_one_through<R: Model, T: Model, A, B>(
&self,
first_key: Column<T, A>,
second_key: Column<R, B>,
) -> HasOneThrough<Self, R> {
HasOneThrough::new(
Some(self.clone()),
T::meta(),
KeyColumn::<T>::key_column(&first_key),
KeyColumn::<R>::key_column(&second_key),
)
}
fn has_many_through<R: Model, T: Model, A, B>(
&self,
first_key: Column<T, A>,
second_key: Column<R, B>,
) -> HasManyThrough<Self, R> {
HasManyThrough::new(
Some(self.clone()),
T::meta(),
KeyColumn::<T>::key_column(&first_key),
KeyColumn::<R>::key_column(&second_key),
)
}
fn morph_one<R: Model>(&self, name: &str) -> HasOne<Self, R> {
HasOne::new_morph(Some(self.clone()), name)
}
fn morph_many<R: Model>(&self, name: &str) -> HasMany<Self, R> {
HasMany::new_morph(Some(self.clone()), name)
}
fn morph_to(&self, name: &str) -> MorphTo<Self> {
MorphTo::new(Some(self.clone()), name)
}
fn morph_to_many<R: Model>(
&self,
name: &str,
table: impl Into<Cow<'static, str>>,
) -> BelongsToMany<Self, R, Pivot> {
BelongsToMany::new_morph(Some(self.clone()), name, table.into(), false)
}
fn morphed_by_many<R: Model>(
&self,
name: &str,
table: impl Into<Cow<'static, str>>,
) -> BelongsToMany<Self, R, Pivot> {
BelongsToMany::new_morph(Some(self.clone()), name, table.into(), true)
}
fn through<L>(&self, local: impl Fn(&Self) -> L) -> PendingThrough<Self, L> {
PendingThrough::new(self.clone(), local(self))
}
}
impl<M: Model> Relationships for M {}