Skip to main content

navree_orm/relations/
define.rs

1//! Defining relations: the [`Relationships`] methods every model has
2//! (`self.belongs_to(..)`, `self.has_many(..)`, ...), and [`KeyColumn`],
3//! the columns they take.
4
5use std::borrow::Cow;
6
7use crate::column::Column;
8use crate::model::Model;
9use crate::relations::belongs_to::BelongsTo;
10use crate::relations::belongs_to_many::{BelongsToMany, Pivot};
11use crate::relations::has::{HasMany, HasOne};
12use crate::relations::morph::MorphTo;
13use crate::relations::through::{HasManyThrough, HasOneThrough, PendingThrough};
14
15/// A column of model `M` given to a relation: a typed column
16/// (`Company::ID`) or a name (`"uuid"`).
17pub trait KeyColumn<M> {
18    /// The column's name.
19    #[doc(hidden)]
20    fn key_column(&self) -> Cow<'static, str>;
21}
22
23impl<M, T> KeyColumn<M> for Column<M, T> {
24    fn key_column(&self) -> Cow<'static, str> {
25        Cow::Owned(
26            crate::ir::ColumnRef::parse(self.name().to_owned())
27                .name
28                .into_owned(),
29        )
30    }
31}
32
33impl<M> KeyColumn<M> for &'static str {
34    fn key_column(&self) -> Cow<'static, str> {
35        Cow::Borrowed(self)
36    }
37}
38
39impl<M> KeyColumn<M> for String {
40    fn key_column(&self) -> Cow<'static, str> {
41        Cow::Owned(self.clone())
42    }
43}
44
45/// The relation definitions of every model. Call them on `self` in a
46/// `#[relations]` impl block (which names each relation after its method
47/// and needs no import of this trait), or on a record for a one-off
48/// relation.
49///
50/// ```
51/// # use navree_orm::__doc_models::{Activity, Company, Tag, Uuid};
52/// use navree_orm::prelude::*;
53/// use navree_orm::relations::{BelongsTo, BelongsToMany, HasMany};
54///
55/// #[derive(Model, Clone, Debug, Default, serde::Serialize)]
56/// pub struct Deal {
57///     pub id: Uuid,
58///     pub company_id: Option<i64>,
59///     pub title: String,
60/// }
61///
62/// #[relations]
63/// impl Deal {
64///     /// The company the deal is with.
65///     pub fn company(&self) -> BelongsTo<Deal, Company> {
66///         self.belongs_to(Deal::COMPANY_ID)
67///     }
68///
69///     /// The deal's activities, newest first.
70///     pub fn activities(&self) -> HasMany<Deal, Activity> {
71///         self.has_many(Activity::DEAL_ID).latest()
72///     }
73///
74///     /// The deal's tags, through the `deal_tag` pivot table.
75///     pub fn tags(&self) -> BelongsToMany<Deal, Tag> {
76///         self.belongs_to_many("deal_tag").with_timestamps()
77///     }
78/// }
79///
80/// assert_eq!(Deal::relation_names(), ["company", "activities", "tags"]);
81/// ```
82pub trait Relationships: Model {
83    /// The record of `R` this record's `foreign_key` column points at (by
84    /// `R`'s key unless [`owner_key`](BelongsTo::owner_key) says
85    /// otherwise): a deal's company.
86    fn belongs_to<R: Model, T>(&self, foreign_key: Column<Self, T>) -> BelongsTo<Self, R> {
87        BelongsTo::new(
88            Some(self.clone()),
89            KeyColumn::<Self>::key_column(&foreign_key),
90        )
91    }
92
93    /// The record of `R` whose `foreign_key` column holds this record's
94    /// key (or [`local_key`](HasOne::local_key)): a user's profile.
95    fn has_one<R: Model, T>(&self, foreign_key: Column<R, T>) -> HasOne<Self, R> {
96        HasOne::new(Some(self.clone()), KeyColumn::<R>::key_column(&foreign_key))
97    }
98
99    /// The records of `R` whose `foreign_key` column holds this record's
100    /// key: a deal's activities.
101    fn has_many<R: Model, T>(&self, foreign_key: Column<R, T>) -> HasMany<Self, R> {
102        HasMany::new(Some(self.clone()), KeyColumn::<R>::key_column(&foreign_key))
103    }
104
105    /// The records of `R` linked to this one by rows of pivot table
106    /// `table`, whose columns `{self}_id` and `{related}_id` hold the two
107    /// keys (see [`BelongsToMany`] for other names). The conventional
108    /// table is both models' snake_case names in alphabetical order,
109    /// joined by `_` (`deal_tag`).
110    fn belongs_to_many<R: Model>(
111        &self,
112        table: impl Into<Cow<'static, str>>,
113    ) -> BelongsToMany<Self, R, Pivot> {
114        BelongsToMany::new(Some(self.clone()), table.into())
115    }
116
117    /// The record of `R` reached through model `T`: `T`'s `first_key`
118    /// holds this record's key, and `R`'s `second_key` holds `T`'s key (a
119    /// supplier's account history through its user).
120    fn has_one_through<R: Model, T: Model, A, B>(
121        &self,
122        first_key: Column<T, A>,
123        second_key: Column<R, B>,
124    ) -> HasOneThrough<Self, R> {
125        HasOneThrough::new(
126            Some(self.clone()),
127            T::meta(),
128            KeyColumn::<T>::key_column(&first_key),
129            KeyColumn::<R>::key_column(&second_key),
130        )
131    }
132
133    /// The records of `R` reached through model `T`: a country's posts
134    /// through its users.
135    fn has_many_through<R: Model, T: Model, A, B>(
136        &self,
137        first_key: Column<T, A>,
138        second_key: Column<R, B>,
139    ) -> HasManyThrough<Self, R> {
140        HasManyThrough::new(
141            Some(self.clone()),
142            T::meta(),
143            KeyColumn::<T>::key_column(&first_key),
144            KeyColumn::<R>::key_column(&second_key),
145        )
146    }
147
148    /// The record of `R` whose `{name}_type` and `{name}_id` columns hold
149    /// this record's morph name and key: a deal's image.
150    fn morph_one<R: Model>(&self, name: &str) -> HasOne<Self, R> {
151        HasOne::new_morph(Some(self.clone()), name)
152    }
153
154    /// The records of `R` whose `{name}_type` and `{name}_id` columns hold
155    /// this record's morph name and key: a deal's comments.
156    fn morph_many<R: Model>(&self, name: &str) -> HasMany<Self, R> {
157        HasMany::new_morph(Some(self.clone()), name)
158    }
159
160    /// The record of any model this record's `{name}_type` and `{name}_id`
161    /// columns point at: a comment's commentable.
162    fn morph_to(&self, name: &str) -> MorphTo<Self> {
163        MorphTo::new(Some(self.clone()), name)
164    }
165
166    /// The records of `R` linked to this one by rows of polymorphic pivot
167    /// table `table` (`taggables`: `tag_id`, `taggable_id`,
168    /// `taggable_type`), `name` being the polymorphic name (`taggable`).
169    fn morph_to_many<R: Model>(
170        &self,
171        name: &str,
172        table: impl Into<Cow<'static, str>>,
173    ) -> BelongsToMany<Self, R, Pivot> {
174        BelongsToMany::new_morph(Some(self.clone()), name, table.into(), false)
175    }
176
177    /// The inverse of [`morph_to_many`](Relationships::morph_to_many): the
178    /// records of `R` that tagged this record (a tag's deals).
179    fn morphed_by_many<R: Model>(
180        &self,
181        name: &str,
182        table: impl Into<Cow<'static, str>>,
183    ) -> BelongsToMany<Self, R, Pivot> {
184        BelongsToMany::new_morph(Some(self.clone()), name, table.into(), true)
185    }
186
187    /// A through relation composed of two relations: `self.through(
188    /// Deal::company).has(Company::contacts)` reaches a deal's contacts
189    /// through its company.
190    fn through<L>(&self, local: impl Fn(&Self) -> L) -> PendingThrough<Self, L> {
191        PendingThrough::new(self.clone(), local(self))
192    }
193}
194
195impl<M: Model> Relationships for M {}