Skip to main content

rok_db_core/
relation.rs

1//! Relations between models, declared with `#[derive(Model)]` attributes.
2//! The parent model must have a single-column primary key.
3//!
4//! Every relation can be queried lazily for one record, or eager-loaded for
5//! many records with a single extra query (avoiding the N+1 problem):
6//!
7//! ```ignore
8//! #[derive(Model)]
9//! #[rok(has_many(posts = Post::USER_ID))]
10//! struct User { id: i64, name: String }
11//!
12//! #[derive(Model)]
13//! struct Post { id: i64, #[rok(belongs_to = User)] user_id: i64, title: String }
14//!
15//! // Lazy: one query for one record.
16//! let posts = user.posts().order_by(Post::ID).all(&db).await?;
17//! let author = post.user().one(&db).await?;
18//!
19//! // Eager: one query for all records.
20//! let users = User::all(&db).await?;
21//! let posts = User::POSTS.load(&db, &users).await?;
22//! for user in &users {
23//!     println!("{} wrote {} posts", user.name, posts.get(user).len());
24//! }
25//! ```
26
27use std::collections::HashMap;
28use std::fmt;
29use std::marker::PhantomData;
30
31use crate::{Column, Executor, Model, Result, Select, Value};
32
33/// Hashable identity of a key value; `None` for SQL `NULL`.
34fn key(value: Option<Value>) -> Option<String> {
35    value.filter(|v| !v.is_null()).map(|v| v.to_string())
36}
37
38/// Relations join on a single primary key column.
39fn require_single_key<M: Model>() -> Result<()> {
40    if M::PRIMARY_KEYS.len() == 1 {
41        Ok(())
42    } else {
43        Err(crate::Error::InvalidQuery(format!(
44            "relations need a single-column primary key; `{}` has a composite key",
45            M::TABLE
46        )))
47    }
48}
49
50/// Distinct, non-null values of `column` across `records`.
51fn distinct_values<M: Model>(records: &[M], column: &str) -> Vec<Value> {
52    let mut seen = std::collections::HashSet::new();
53    records
54        .iter()
55        .filter_map(|r| r.value_of(column))
56        .filter(|v| !v.is_null() && seen.insert(v.to_string()))
57        .collect()
58}
59
60/// `C` belongs to `P` through the foreign key column `C.fk → P.pk`.
61///
62/// Generated as an associated constant by `#[rok(belongs_to = P)]` on the
63/// foreign key field (`Post::USER` for a field `user_id`).
64pub struct BelongsTo<C, P> {
65    foreign_key: &'static str,
66    _models: PhantomData<fn() -> (C, P)>,
67}
68
69impl<C: Model, P: Model> BelongsTo<C, P> {
70    /// Declare the relation through `foreign_key`, a column of `C`.
71    pub const fn new(foreign_key: Column<C>) -> Self {
72        Self {
73            foreign_key: foreign_key.name(),
74            _models: PhantomData,
75        }
76    }
77
78    /// The foreign key column on `C`.
79    pub const fn foreign_key(&self) -> Column<C> {
80        Column::new(self.foreign_key)
81    }
82
83    /// Query the parent of `child` (no rows if the foreign key is `NULL`).
84    pub fn query(&self, child: &C) -> Select<P> {
85        match child.value_of(self.foreign_key).filter(|v| !v.is_null()) {
86            Some(fk) => P::filter(P::primary_key_column().eq(fk)),
87            None => P::filter(crate::Expr::none()),
88        }
89    }
90
91    /// Load the parents of every record in `children` with one query.
92    pub async fn load<'e, E: Executor<'e>>(
93        &self,
94        executor: E,
95        children: &[C],
96    ) -> Result<One<C, P>> {
97        require_single_key::<P>()?;
98        let ids = distinct_values(children, self.foreign_key);
99        let parents = if ids.is_empty() {
100            Vec::new()
101        } else {
102            P::filter(P::primary_key_column().is_in(ids))
103                .all(executor)
104                .await?
105        };
106        let map = parents
107            .into_iter()
108            .filter_map(|p| key(Some(p.primary_key())).map(|k| (k, p)))
109            .collect();
110        Ok(One::new(map, self.foreign_key))
111    }
112}
113
114/// `P` has many `C` through the foreign key column `C.fk → P.pk`.
115///
116/// Generated as an associated constant by
117/// `#[rok(has_many(posts = Post::USER_ID))]` on `P` (`User::POSTS`).
118pub struct HasMany<P, C> {
119    foreign_key: &'static str,
120    _models: PhantomData<fn() -> (P, C)>,
121}
122
123impl<P: Model, C: Model> HasMany<P, C> {
124    /// Declare the relation through `foreign_key`, a column of `C`.
125    pub const fn new(foreign_key: Column<C>) -> Self {
126        Self {
127            foreign_key: foreign_key.name(),
128            _models: PhantomData,
129        }
130    }
131
132    /// The foreign key column on `C`.
133    pub const fn foreign_key(&self) -> Column<C> {
134        Column::new(self.foreign_key)
135    }
136
137    /// Query the children of `parent`.
138    pub fn query(&self, parent: &P) -> Select<C> {
139        C::filter(self.foreign_key().eq(parent.primary_key()))
140    }
141
142    /// Load the children of every record in `parents` with one query.
143    pub async fn load<'e, E: Executor<'e>>(
144        &self,
145        executor: E,
146        parents: &[P],
147    ) -> Result<Many<P, C>> {
148        require_single_key::<P>()?;
149        self.load_from(executor, parents, C::query()).await
150    }
151
152    /// Like [`load`](Self::load), starting from `base` to filter or order
153    /// the children (`Post::order_by(Post::CREATED_AT.desc())`). Limits
154    /// apply to the whole result, not per parent.
155    pub async fn load_from<'e, E: Executor<'e>>(
156        &self,
157        executor: E,
158        parents: &[P],
159        base: Select<C>,
160    ) -> Result<Many<P, C>> {
161        require_single_key::<P>()?;
162        let ids = distinct_values(parents, P::PRIMARY_KEY);
163        let children = if ids.is_empty() {
164            Vec::new()
165        } else {
166            base.filter(self.foreign_key().is_in(ids))
167                .all(executor)
168                .await?
169        };
170        let mut map: HashMap<String, Vec<C>> = HashMap::new();
171        for child in children {
172            if let Some(k) = key(child.value_of(self.foreign_key)) {
173                map.entry(k).or_default().push(child);
174            }
175        }
176        Ok(Many::new(map, P::PRIMARY_KEY))
177    }
178}
179
180/// `P` has at most one `C` through the foreign key column `C.fk → P.pk`.
181///
182/// Generated as an associated constant by
183/// `#[rok(has_one(profile = Profile::USER_ID))]` on `P` (`User::PROFILE`).
184pub struct HasOne<P, C> {
185    foreign_key: &'static str,
186    _models: PhantomData<fn() -> (P, C)>,
187}
188
189impl<P: Model, C: Model> HasOne<P, C> {
190    /// Declare the relation through `foreign_key`, a column of `C`.
191    pub const fn new(foreign_key: Column<C>) -> Self {
192        Self {
193            foreign_key: foreign_key.name(),
194            _models: PhantomData,
195        }
196    }
197
198    /// The foreign key column on `C`.
199    pub const fn foreign_key(&self) -> Column<C> {
200        Column::new(self.foreign_key)
201    }
202
203    /// Query the child of `parent`.
204    pub fn query(&self, parent: &P) -> Select<C> {
205        C::filter(self.foreign_key().eq(parent.primary_key()))
206    }
207
208    /// Load the child of every record in `parents` with one query.
209    pub async fn load<'e, E: Executor<'e>>(&self, executor: E, parents: &[P]) -> Result<One<P, C>> {
210        require_single_key::<P>()?;
211        let ids = distinct_values(parents, P::PRIMARY_KEY);
212        let children = if ids.is_empty() {
213            Vec::new()
214        } else {
215            C::filter(self.foreign_key().is_in(ids))
216                .all(executor)
217                .await?
218        };
219        let map = children
220            .into_iter()
221            .filter_map(|c| key(c.value_of(self.foreign_key)).map(|k| (k, c)))
222            .collect();
223        Ok(One::new(map, P::PRIMARY_KEY))
224    }
225}
226
227/// Eager-loaded single related records, keyed by owner. Returned by
228/// [`BelongsTo::load`] and [`HasOne::load`].
229pub struct One<O, T> {
230    map: HashMap<String, T>,
231    owner_key: &'static str,
232    _owner: PhantomData<fn() -> O>,
233}
234
235impl<O: Model, T> One<O, T> {
236    fn new(map: HashMap<String, T>, owner_key: &'static str) -> Self {
237        Self {
238            map,
239            owner_key,
240            _owner: PhantomData,
241        }
242    }
243
244    /// The record related to `owner`, if any.
245    pub fn get(&self, owner: &O) -> Option<&T> {
246        key(owner.value_of(self.owner_key)).and_then(|k| self.map.get(&k))
247    }
248
249    /// Remove and return the record related to `owner`.
250    pub fn take(&mut self, owner: &O) -> Option<T> {
251        key(owner.value_of(self.owner_key)).and_then(|k| self.map.remove(&k))
252    }
253
254    /// Number of loaded records.
255    pub fn len(&self) -> usize {
256        self.map.len()
257    }
258
259    /// `true` if nothing was loaded.
260    pub fn is_empty(&self) -> bool {
261        self.map.is_empty()
262    }
263
264    /// Iterate over the loaded records (in no particular order).
265    pub fn values(&self) -> impl Iterator<Item = &T> {
266        self.map.values()
267    }
268}
269
270/// Eager-loaded related records grouped by owner. Returned by
271/// [`HasMany::load`].
272pub struct Many<O, T> {
273    map: HashMap<String, Vec<T>>,
274    owner_key: &'static str,
275    _owner: PhantomData<fn() -> O>,
276}
277
278impl<O: Model, T> Many<O, T> {
279    fn new(map: HashMap<String, Vec<T>>, owner_key: &'static str) -> Self {
280        Self {
281            map,
282            owner_key,
283            _owner: PhantomData,
284        }
285    }
286
287    /// The records related to `owner` (empty if none).
288    pub fn get(&self, owner: &O) -> &[T] {
289        key(owner.value_of(self.owner_key))
290            .and_then(|k| self.map.get(&k))
291            .map_or(&[], Vec::as_slice)
292    }
293
294    /// Remove and return the records related to `owner`.
295    pub fn take(&mut self, owner: &O) -> Vec<T> {
296        key(owner.value_of(self.owner_key))
297            .and_then(|k| self.map.remove(&k))
298            .unwrap_or_default()
299    }
300
301    /// Total number of loaded records.
302    pub fn len(&self) -> usize {
303        self.map.values().map(Vec::len).sum()
304    }
305
306    /// `true` if nothing was loaded.
307    pub fn is_empty(&self) -> bool {
308        self.map.is_empty()
309    }
310
311    /// Iterate over every loaded record (in no particular order).
312    pub fn values(&self) -> impl Iterator<Item = &T> {
313        self.map.values().flatten()
314    }
315}
316
317macro_rules! relation_boilerplate {
318    ($($ty:ident<$a:ident, $b:ident>),*) => {$(
319        impl<$a, $b> Clone for $ty<$a, $b> {
320            fn clone(&self) -> Self {
321                *self
322            }
323        }
324        impl<$a, $b> Copy for $ty<$a, $b> {}
325        impl<$a, $b> fmt::Debug for $ty<$a, $b> {
326            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327                f.debug_struct(stringify!($ty))
328                    .field("foreign_key", &self.foreign_key)
329                    .finish()
330            }
331        }
332    )*};
333}
334
335relation_boilerplate!(BelongsTo<C, P>, HasMany<P, C>, HasOne<P, C>);
336
337impl<O, T: fmt::Debug> fmt::Debug for One<O, T> {
338    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339        f.debug_map().entries(self.map.iter()).finish()
340    }
341}
342
343impl<O, T: fmt::Debug> fmt::Debug for Many<O, T> {
344    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345        f.debug_map().entries(self.map.iter()).finish()
346    }
347}