Skip to main content

navree_orm/relations/
store.rs

1//! [`Relations`]: the relations loaded on a record, and [`RelationValue`]:
2//! what a loaded relation holds.
3
4use std::any::Any;
5use std::borrow::Cow;
6use std::fmt;
7
8use navree_kernel::BoxFuture;
9use serde::Serialize;
10
11use crate::collection::Collection;
12use crate::error::Result;
13use crate::exec::Target;
14use crate::model::Model;
15use crate::record::Record;
16use crate::relations::any::AnyRecord;
17use crate::value::Value;
18
19type AnyValue = dyn Any + Send + Sync;
20
21/// Saves a loaded value and the records it holds (`Record::push`).
22type PushFn = for<'a, 'b> fn(&'a mut AnyValue, &'a Target<'b>) -> BoxFuture<'a, Result<bool>>;
23
24/// Reads a column of a loaded value that is one row.
25type ColumnFn = fn(&AnyValue, &str) -> Option<Value>;
26
27pub(crate) mod sealed {
28    /// Only the ORM's relation values are relation values.
29    pub trait Sealed {}
30}
31
32/// What a relation holds once it is loaded on a record:
33/// `Option<Record<R>>` for a to-one relation (`belongs_to`, `has_one`,
34/// `has_one_through`, `morph_one`), [`Collection<R>`] for a to-many one
35/// (`has_many`, `belongs_to_many`, `has_many_through`, `morph_many`,
36/// `morph_to_many`), `Option<AnyRecord>` for `morph_to`, and the pivot of a
37/// many-to-many record ([`Pivot`](crate::relations::Pivot), or the
38/// `Record` of a typed pivot model).
39///
40/// Loaded values serialize with the record, and [`Record::push`] saves the
41/// records they hold.
42pub trait RelationValue: Clone + Serialize + Send + Sync + 'static + sealed::Sealed {
43    /// Saves the records the value holds, and theirs (`Record::push`).
44    #[doc(hidden)]
45    fn push_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>>;
46
47    /// Column `column` of a value that is one row (a pivot, or the record
48    /// of a typed pivot model); `None` for other values.
49    #[doc(hidden)]
50    fn column(&self, column: &str) -> Option<Value> {
51        let _ = column;
52        None
53    }
54}
55
56impl<R: Model> sealed::Sealed for Option<Record<R>> {}
57
58impl<R: Model> RelationValue for Option<Record<R>> {
59    fn push_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>> {
60        Box::pin(async move {
61            match self {
62                Some(record) => crate::relations::lazy::push_record(record, target).await,
63                None => Ok(true),
64            }
65        })
66    }
67}
68
69impl<R: Model> sealed::Sealed for Record<R> {}
70
71impl<R: Model> RelationValue for Record<R> {
72    fn push_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>> {
73        crate::relations::lazy::push_record(self, target)
74    }
75
76    fn column(&self, column: &str) -> Option<Value> {
77        self.model.value(column).ok().flatten()
78    }
79}
80
81impl<R: Model> sealed::Sealed for Collection<R> {}
82
83impl<R: Model> RelationValue for Collection<R> {
84    fn push_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>> {
85        Box::pin(async move {
86            for record in self.iter_mut() {
87                if !crate::relations::lazy::push_record(record, target).await? {
88                    return Ok(false);
89                }
90            }
91            Ok(true)
92        })
93    }
94}
95
96impl sealed::Sealed for Option<AnyRecord> {}
97
98impl RelationValue for Option<AnyRecord> {
99    fn push_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>> {
100        Box::pin(async move {
101            match self {
102                Some(record) => record.push_on(target).await,
103                None => Ok(true),
104            }
105        })
106    }
107}
108
109/// A loaded relation: the value, how to clone it, how to serialize it and,
110/// for relation values, how to save the records it holds and read a
111/// column of a one-row value.
112struct Slot {
113    name: Cow<'static, str>,
114    value: Box<AnyValue>,
115    clone: fn(&AnyValue) -> Box<AnyValue>,
116    to_json: fn(&AnyValue) -> Result<serde_json::Value, serde_json::Error>,
117    push: Option<PushFn>,
118    column: Option<ColumnFn>,
119}
120
121impl Slot {
122    /// A copy of the slot.
123    fn duplicate(&self) -> Slot {
124        Slot {
125            name: self.name.clone(),
126            value: (self.clone)(&*self.value),
127            clone: self.clone,
128            to_json: self.to_json,
129            push: self.push,
130            column: self.column,
131        }
132    }
133}
134
135fn column_of<V: RelationValue>(value: &AnyValue, column: &str) -> Option<Value> {
136    value.downcast_ref::<V>()?.column(column)
137}
138
139fn clone_value<T: Clone + Send + Sync + 'static>(value: &AnyValue) -> Box<AnyValue> {
140    match value.downcast_ref::<T>() {
141        Some(value) => Box::new(value.clone()),
142        // A slot only ever holds the type it was stored with.
143        None => Box::new(()),
144    }
145}
146
147fn value_to_json<T: Serialize + 'static>(
148    value: &AnyValue,
149) -> Result<serde_json::Value, serde_json::Error> {
150    match value.downcast_ref::<T>() {
151        Some(value) => serde_json::to_value(value),
152        None => Ok(serde_json::Value::Null),
153    }
154}
155
156fn push_value<'a, 'b, V: RelationValue>(
157    value: &'a mut AnyValue,
158    target: &'a Target<'b>,
159) -> BoxFuture<'a, Result<bool>> {
160    match value.downcast_mut::<V>() {
161        Some(value) => value.push_on(target),
162        None => Box::pin(async { Ok(true) }),
163    }
164}
165
166/// The relations loaded on a record, by name, in loading order.
167///
168/// Values are typed: [`get`](Relations::get) returns a relation only as
169/// the type it was stored as. The ORM stores [`RelationValue`]s
170/// (`Option<Record<R>>`, `Collection<R>`, ...); any other cloneable,
171/// serializable value can be stored with [`set`](Relations::set) (it
172/// serializes with the record, and is not saved by `push`).
173///
174/// ```
175/// use navree_orm::relations::Relations;
176///
177/// let mut relations = Relations::new();
178/// relations.set("tags", vec!["vip".to_owned()]);
179/// assert!(relations.is_loaded("tags"));
180/// assert_eq!(relations.get::<Vec<String>>("tags").unwrap(), &["vip"]);
181/// assert!(relations.get::<u32>("tags").is_none(), "another type");
182/// assert_eq!(relations.to_json().unwrap(), serde_json::json!({"tags": ["vip"]}));
183/// ```
184#[derive(Default)]
185pub struct Relations {
186    slots: Vec<Slot>,
187}
188
189impl Relations {
190    /// No relation loaded.
191    pub fn new() -> Self {
192        Relations::default()
193    }
194
195    fn put(&mut self, slot: Slot) {
196        match self
197            .slots
198            .iter_mut()
199            .find(|existing| existing.name == slot.name)
200        {
201            Some(existing) => *existing = slot,
202            None => self.slots.push(slot),
203        }
204    }
205
206    /// Stores `value` as relation `name`, replacing what was loaded. Any
207    /// cloneable, serializable value can be stored; it serializes with the
208    /// record. Relation values are stored with
209    /// [`set_relation`](Relations::set_relation), which `push` saves.
210    pub fn set<T>(&mut self, name: impl Into<Cow<'static, str>>, value: T)
211    where
212        T: Clone + Serialize + Send + Sync + 'static,
213    {
214        self.put(Slot {
215            name: name.into(),
216            value: Box::new(value),
217            clone: clone_value::<T>,
218            to_json: value_to_json::<T>,
219            push: None,
220            column: None,
221        });
222    }
223
224    /// Stores relation value `value` as relation `name`, replacing what
225    /// was loaded.
226    pub fn set_relation<V: RelationValue>(&mut self, name: impl Into<Cow<'static, str>>, value: V) {
227        self.put(Slot {
228            name: name.into(),
229            value: Box::new(value),
230            clone: clone_value::<V>,
231            to_json: value_to_json::<V>,
232            push: Some(push_value::<V>),
233            column: Some(column_of::<V>),
234        });
235    }
236
237    /// Column `column` of relation `name`, when it holds one row (a pivot,
238    /// or a typed pivot model's record).
239    pub(crate) fn column(&self, name: &str, column: &str) -> Option<Value> {
240        let slot = self.slots.iter().find(|slot| slot.name == name)?;
241        (slot.column?)(&*slot.value, column)
242    }
243
244    /// Relation `name`, when it is loaded as a `T`.
245    pub fn get<T: 'static>(&self, name: &str) -> Option<&T> {
246        self.slots
247            .iter()
248            .find(|slot| slot.name == name)
249            .and_then(|slot| slot.value.downcast_ref::<T>())
250    }
251
252    /// Relation `name` for changes, when it is loaded as a `T`.
253    pub fn get_mut<T: 'static>(&mut self, name: &str) -> Option<&mut T> {
254        self.slots
255            .iter_mut()
256            .find(|slot| slot.name == name)
257            .and_then(|slot| slot.value.downcast_mut::<T>())
258    }
259
260    /// Removes relation `name` and returns it, when it is loaded as a `T`
261    /// (another type is left in place).
262    pub fn take<T: 'static>(&mut self, name: &str) -> Option<T> {
263        let index = self.slots.iter().position(|slot| slot.name == name)?;
264        if !self.slots[index].value.is::<T>() {
265            return None;
266        }
267        let slot = self.slots.remove(index);
268        slot.value.downcast::<T>().ok().map(|value| *value)
269    }
270
271    /// Whether relation `name` is loaded.
272    pub fn is_loaded(&self, name: &str) -> bool {
273        self.slots.iter().any(|slot| slot.name == name)
274    }
275
276    /// Forgets relation `name`.
277    pub fn unset(&mut self, name: &str) {
278        self.slots.retain(|slot| slot.name != name);
279    }
280
281    /// Forgets every relation.
282    pub fn clear(&mut self) {
283        self.slots.clear();
284    }
285
286    /// The names of the loaded relations, in loading order.
287    pub fn names(&self) -> impl Iterator<Item = &str> {
288        self.slots.iter().map(|slot| slot.name.as_ref())
289    }
290
291    /// How many relations are loaded.
292    pub fn len(&self) -> usize {
293        self.slots.len()
294    }
295
296    /// Whether no relation is loaded.
297    pub fn is_empty(&self) -> bool {
298        self.slots.is_empty()
299    }
300
301    /// The loaded relations as a JSON object, by name.
302    pub fn to_json(&self) -> Result<serde_json::Value, serde_json::Error> {
303        let mut object = serde_json::Map::with_capacity(self.slots.len());
304        for slot in &self.slots {
305            object.insert(slot.name.to_string(), (slot.to_json)(&*slot.value)?);
306        }
307        Ok(serde_json::Value::Object(object))
308    }
309
310    /// Copies relation `name` of `other` (if loaded there) into these
311    /// relations.
312    pub(crate) fn copy_from(&mut self, other: &Relations, name: &str) {
313        if let Some(slot) = other.slots.iter().find(|slot| slot.name == name) {
314            self.put(slot.duplicate());
315        }
316    }
317
318    /// Saves the records of every loaded relation value, in loading order;
319    /// `false` when a hook cancelled one of the saves.
320    pub(crate) fn push_all<'a, 'b>(
321        &'a mut self,
322        target: &'a Target<'b>,
323    ) -> BoxFuture<'a, Result<bool>> {
324        Box::pin(async move {
325            for slot in &mut self.slots {
326                if let Some(push) = slot.push
327                    && !push(&mut *slot.value, target).await?
328                {
329                    return Ok(false);
330                }
331            }
332            Ok(true)
333        })
334    }
335}
336
337impl Clone for Relations {
338    fn clone(&self) -> Self {
339        Relations {
340            slots: self.slots.iter().map(Slot::duplicate).collect(),
341        }
342    }
343}
344
345impl fmt::Debug for Relations {
346    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347        f.debug_list().entries(self.names()).finish()
348    }
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    #[test]
356    fn values_are_typed_replaced_cloned_and_taken() {
357        let mut relations = Relations::new();
358        relations.set("owner", Some("anu".to_owned()));
359        relations.set("owner", Some("gauri".to_owned()));
360        assert_eq!(relations.names().collect::<Vec<_>>(), ["owner"]);
361        let copy = relations.clone();
362        relations
363            .get_mut::<Option<String>>("owner")
364            .unwrap()
365            .replace("laksh".into());
366        assert_eq!(
367            copy.get::<Option<String>>("owner").unwrap().as_deref(),
368            Some("gauri")
369        );
370        assert!(relations.take::<u8>("owner").is_none());
371        assert_eq!(relations.len(), 1, "a take of another type leaves it");
372        assert_eq!(
373            relations
374                .take::<Option<String>>("owner")
375                .unwrap()
376                .as_deref(),
377            Some("laksh")
378        );
379        assert!(relations.is_empty());
380        assert_eq!(format!("{copy:?}"), r#"["owner"]"#);
381    }
382}