1use std::collections::HashMap;
28use std::fmt;
29use std::marker::PhantomData;
30
31use crate::{Column, Executor, Model, Result, Select, Value};
32
33fn key(value: Option<Value>) -> Option<String> {
35 value.filter(|v| !v.is_null()).map(|v| v.to_string())
36}
37
38fn 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
50fn 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
60pub 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 pub const fn new(foreign_key: Column<C>) -> Self {
72 Self {
73 foreign_key: foreign_key.name(),
74 _models: PhantomData,
75 }
76 }
77
78 pub const fn foreign_key(&self) -> Column<C> {
80 Column::new(self.foreign_key)
81 }
82
83 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 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
114pub 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 pub const fn new(foreign_key: Column<C>) -> Self {
126 Self {
127 foreign_key: foreign_key.name(),
128 _models: PhantomData,
129 }
130 }
131
132 pub const fn foreign_key(&self) -> Column<C> {
134 Column::new(self.foreign_key)
135 }
136
137 pub fn query(&self, parent: &P) -> Select<C> {
139 C::filter(self.foreign_key().eq(parent.primary_key()))
140 }
141
142 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 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
180pub 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 pub const fn new(foreign_key: Column<C>) -> Self {
192 Self {
193 foreign_key: foreign_key.name(),
194 _models: PhantomData,
195 }
196 }
197
198 pub const fn foreign_key(&self) -> Column<C> {
200 Column::new(self.foreign_key)
201 }
202
203 pub fn query(&self, parent: &P) -> Select<C> {
205 C::filter(self.foreign_key().eq(parent.primary_key()))
206 }
207
208 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
227pub 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 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 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 pub fn len(&self) -> usize {
256 self.map.len()
257 }
258
259 pub fn is_empty(&self) -> bool {
261 self.map.is_empty()
262 }
263
264 pub fn values(&self) -> impl Iterator<Item = &T> {
266 self.map.values()
267 }
268}
269
270pub 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 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 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 pub fn len(&self) -> usize {
303 self.map.values().map(Vec::len).sum()
304 }
305
306 pub fn is_empty(&self) -> bool {
308 self.map.is_empty()
309 }
310
311 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}