Skip to main content

icydb_schema/node/
entity.rs

1use crate::prelude::*;
2use std::any::Any;
3
4///
5/// Entity
6///
7
8#[derive(Clone, Debug, Serialize)]
9pub struct Entity {
10    def: Def,
11    store: &'static str,
12    primary_key: PrimaryKey,
13
14    #[serde(skip_serializing_if = "Option::is_none")]
15    name: Option<&'static str>,
16
17    #[serde(skip_serializing_if = "<[_]>::is_empty")]
18    indexes: &'static [Index],
19
20    fields: FieldList,
21    ty: Type,
22}
23
24impl Entity {
25    #[must_use]
26    pub const fn new(
27        def: Def,
28        store: &'static str,
29        primary_key: PrimaryKey,
30        name: Option<&'static str>,
31        indexes: &'static [Index],
32        fields: FieldList,
33        ty: Type,
34    ) -> Self {
35        Self {
36            def,
37            store,
38            primary_key,
39            name,
40            indexes,
41            fields,
42            ty,
43        }
44    }
45
46    #[must_use]
47    pub const fn def(&self) -> &Def {
48        &self.def
49    }
50
51    #[must_use]
52    pub const fn store(&self) -> &'static str {
53        self.store
54    }
55
56    #[must_use]
57    pub const fn primary_key(&self) -> &PrimaryKey {
58        &self.primary_key
59    }
60
61    #[must_use]
62    pub const fn name(&self) -> Option<&'static str> {
63        self.name
64    }
65
66    #[must_use]
67    pub const fn indexes(&self) -> &'static [Index] {
68        self.indexes
69    }
70
71    #[must_use]
72    pub const fn fields(&self) -> &FieldList {
73        &self.fields
74    }
75
76    #[must_use]
77    pub const fn ty(&self) -> &Type {
78        &self.ty
79    }
80
81    /// Return the scalar primary key field if this entity uses a scalar
82    /// primary-key contract.
83    #[must_use]
84    pub fn scalar_primary_key_field(&self) -> Option<&Field> {
85        self.fields().get(self.primary_key().scalar_field()?)
86    }
87
88    /// Resolve the entity name used for schema identity.
89    #[must_use]
90    pub fn resolved_name(&self) -> &'static str {
91        self.name().unwrap_or_else(|| self.def().ident())
92    }
93}
94
95impl MacroNode for Entity {
96    fn as_any(&self) -> &dyn Any {
97        self
98    }
99}
100
101impl ValidateNode for Entity {
102    fn validate(&self) -> Result<(), ErrorTree> {
103        let mut errs = ErrorTree::new();
104        let schema = schema_read();
105
106        // store
107        match schema.cast_node::<Store>(self.store()) {
108            Ok(_) => {}
109            Err(e) => errs.add(e),
110        }
111
112        errs.result()
113    }
114}
115
116impl VisitableNode for Entity {
117    fn route_key(&self) -> String {
118        self.def().path()
119    }
120
121    fn drive<V: Visitor>(&self, v: &mut V) {
122        self.def().accept(v);
123        self.fields().accept(v);
124        self.ty().accept(v);
125    }
126}