Skip to main content

toasty/schema/
has_many.rs

1use super::{Deferred, Load, Model, RelationManyField};
2
3use toasty_core::schema::Name;
4use toasty_core::schema::app::{self, FieldId, FieldTy, ModelId};
5use toasty_core::stmt;
6
7impl<M: Model> RelationManyField for Vec<M> {
8    type Target = M;
9
10    const DEFERRED: bool = false;
11
12    fn reload(target: &mut Self, value: stmt::Value) -> crate::Result<()> {
13        <Self as Load>::reload(target, value)
14    }
15
16    fn many_relation_field_ty(
17        singular: Name,
18        pair: Option<FieldId>,
19        via: Option<stmt::Path>,
20    ) -> FieldTy {
21        many_relation_field_ty::<M>(singular, pair, via)
22    }
23}
24
25impl<M: Model> RelationManyField for Deferred<Vec<M>> {
26    type Target = M;
27
28    const DEFERRED: bool = true;
29
30    fn reload(target: &mut Self, _value: stmt::Value) -> crate::Result<()> {
31        target.unload();
32        Ok(())
33    }
34
35    fn many_relation_field_ty(
36        singular: Name,
37        pair: Option<FieldId>,
38        via: Option<stmt::Path>,
39    ) -> FieldTy {
40        many_relation_field_ty::<M>(singular, pair, via)
41    }
42}
43
44fn many_relation_field_ty<M: Model>(
45    singular: Name,
46    pair: Option<FieldId>,
47    via: Option<stmt::Path>,
48) -> FieldTy {
49    let target = <M as Model>::id();
50    let expr_ty = stmt::Type::List(Box::new(stmt::Type::Model(target)));
51    let cardinality = app::Cardinality::Many { singular };
52
53    match via {
54        Some(path) => FieldTy::Via(app::Via::new(target, expr_ty, cardinality, path, None)),
55        None => FieldTy::Has(app::Has {
56            target,
57            expr_ty,
58            cardinality,
59            pair_id: pair.unwrap_or(FieldId {
60                model: ModelId(usize::MAX),
61                index: usize::MAX,
62            }),
63        }),
64    }
65}