toasty_core/schema/app/
model.rs

1use super::{Field, FieldId, FieldPrimitive, Index, Name, PrimaryKey};
2use crate::{Result, driver, stmt};
3use indexmap::IndexMap;
4use std::fmt;
5
6/// A model in the application schema.
7///
8/// Models come in three flavors:
9///
10/// - [`Model::Root`] -- a top-level model backed by its own database table.
11/// - [`Model::EmbeddedStruct`] -- a struct whose fields are flattened into a
12///   parent model's table.
13/// - [`Model::EmbeddedEnum`] -- an enum stored via a discriminant column plus
14///   optional per-variant data columns in the parent table.
15///
16/// # Examples
17///
18/// ```ignore
19/// use toasty_core::schema::app::{Model, Schema};
20///
21/// let schema: Schema = /* built from derive macros */;
22/// for model in schema.models() {
23///     if model.is_root() {
24///         println!("Root model: {}", model.name().upper_camel_case());
25///     }
26/// }
27/// ```
28#[derive(Debug, Clone)]
29pub enum Model {
30    /// A root model that maps to its own database table and can be queried
31    /// directly.
32    Root(ModelRoot),
33    /// An embedded struct whose fields are flattened into its parent model's
34    /// table.
35    EmbeddedStruct(EmbeddedStruct),
36    /// An embedded enum stored as a discriminant column (plus optional
37    /// per-variant data columns) in the parent table.
38    EmbeddedEnum(EmbeddedEnum),
39}
40
41/// An ordered collection of [`Model`] definitions.
42///
43/// `ModelSet` is the primary container used to hold all models in a schema.
44/// Models are stored in insertion order and can be iterated over by reference
45/// or by value.
46///
47/// # Examples
48///
49/// ```
50/// use toasty_core::schema::app::{Model, ModelSet};
51///
52/// let mut set = ModelSet::new();
53/// assert_eq!(set.iter().len(), 0);
54/// ```
55#[derive(Debug, Clone, Default)]
56pub struct ModelSet {
57    models: IndexMap<ModelId, Model>,
58}
59
60impl ModelSet {
61    /// Creates an empty `ModelSet`.
62    pub fn new() -> Self {
63        Self::default()
64    }
65
66    /// Returns the number of models in the set.
67    pub fn len(&self) -> usize {
68        self.models.len()
69    }
70
71    /// Returns `true` if the set contains no models.
72    pub fn is_empty(&self) -> bool {
73        self.models.is_empty()
74    }
75
76    /// Returns `true` if the set contains a model with the given ID.
77    pub fn contains(&self, id: ModelId) -> bool {
78        self.models.contains_key(&id)
79    }
80
81    /// Inserts a model into the set, keyed by its [`ModelId`].
82    ///
83    /// If a model with the same ID already exists, it is replaced.
84    pub fn add(&mut self, model: Model) {
85        self.models.insert(model.id(), model);
86    }
87
88    /// Returns an iterator over the models in insertion order.
89    pub fn iter(&self) -> impl ExactSizeIterator<Item = &Model> {
90        self.models.values()
91    }
92}
93
94impl<'a> IntoIterator for &'a ModelSet {
95    type Item = &'a Model;
96    type IntoIter = indexmap::map::Values<'a, ModelId, Model>;
97
98    fn into_iter(self) -> Self::IntoIter {
99        self.models.values()
100    }
101}
102
103impl IntoIterator for ModelSet {
104    type Item = Model;
105    type IntoIter = ModelSetIntoIter;
106
107    fn into_iter(self) -> Self::IntoIter {
108        ModelSetIntoIter {
109            inner: self.models.into_iter(),
110        }
111    }
112}
113
114/// An owning iterator over the models in a [`ModelSet`].
115pub struct ModelSetIntoIter {
116    inner: indexmap::map::IntoIter<ModelId, Model>,
117}
118
119impl Iterator for ModelSetIntoIter {
120    type Item = Model;
121
122    fn next(&mut self) -> Option<Self::Item> {
123        self.inner.next().map(|(_, model)| model)
124    }
125
126    fn size_hint(&self) -> (usize, Option<usize>) {
127        self.inner.size_hint()
128    }
129}
130
131impl ExactSizeIterator for ModelSetIntoIter {}
132
133/// A root model backed by its own database table.
134///
135/// Root models have a primary key, may define indices, and are the only model
136/// kind that can be the target of relations. They are the main entities users
137/// interact with through Toasty's query API.
138///
139/// # Examples
140///
141/// ```ignore
142/// let root = model.as_root_unwrap();
143/// let pk_fields: Vec<_> = root.primary_key_fields().collect();
144/// ```
145#[derive(Debug, Clone)]
146pub struct ModelRoot {
147    /// Uniquely identifies this model within the schema.
148    pub id: ModelId,
149
150    /// The model's name.
151    pub name: Name,
152
153    /// All fields defined on this model.
154    pub fields: Vec<Field>,
155
156    /// The primary key definition. Root models always have a primary key.
157    pub primary_key: PrimaryKey,
158
159    /// Optional explicit table name. When `None`, a name is derived from the
160    /// model name.
161    pub table_name: Option<String>,
162
163    /// Secondary indices defined on this model.
164    pub indices: Vec<Index>,
165}
166
167impl ModelRoot {
168    /// Builds a `SELECT` query that filters by this model's primary key using
169    /// the supplied `input` to resolve argument values.
170    pub fn find_by_id(&self, mut input: impl stmt::Input) -> stmt::Query {
171        let filter = match &self.primary_key.fields[..] {
172            [pk_field] => stmt::Expr::eq(
173                stmt::Expr::ref_self_field(pk_field),
174                input
175                    .resolve_arg(&0.into(), &stmt::Projection::identity())
176                    .unwrap(),
177            ),
178            pk_fields => stmt::Expr::and_from_vec(
179                pk_fields
180                    .iter()
181                    .enumerate()
182                    .map(|(i, pk_field)| {
183                        stmt::Expr::eq(
184                            stmt::Expr::ref_self_field(pk_field),
185                            input
186                                .resolve_arg(&i.into(), &stmt::Projection::identity())
187                                .unwrap(),
188                        )
189                    })
190                    .collect(),
191            ),
192        };
193
194        stmt::Query::new_select(self.id, filter)
195    }
196
197    /// Iterate over the fields used for the model's primary key.
198    pub fn primary_key_fields(&self) -> impl ExactSizeIterator<Item = &'_ Field> {
199        self.primary_key
200            .fields
201            .iter()
202            .map(|pk_field| &self.fields[pk_field.index])
203    }
204
205    /// Looks up a field by its application-level name.
206    ///
207    /// Returns `None` if no field with that name exists on this model.
208    pub fn field_by_name(&self, name: &str) -> Option<&Field> {
209        self.fields
210            .iter()
211            .find(|field| field.name.app.as_deref() == Some(name))
212    }
213
214    pub(crate) fn verify(&self, db: &driver::Capability) -> Result<()> {
215        for field in &self.fields {
216            field.verify(db)?;
217        }
218        Ok(())
219    }
220}
221
222/// An embedded struct model whose fields are flattened into its parent model's
223/// database table.
224///
225/// Embedded structs do not have their own table or primary key. Their fields
226/// become additional columns in the parent table. Indices declared on an
227/// embedded struct's fields are propagated to physical DB indices on the parent
228/// table.
229///
230/// # Examples
231///
232/// ```ignore
233/// let embedded = model.as_embedded_struct_unwrap();
234/// for field in &embedded.fields {
235///     println!("  embedded field: {}", field.name);
236/// }
237/// ```
238#[derive(Debug, Clone)]
239pub struct EmbeddedStruct {
240    /// Uniquely identifies this model within the schema.
241    pub id: ModelId,
242
243    /// The model's name.
244    pub name: Name,
245
246    /// Fields contained by this embedded struct.
247    pub fields: Vec<Field>,
248
249    /// Indices defined on this embedded struct's fields.
250    ///
251    /// These reference fields within this embedded struct (not the parent
252    /// model). The schema builder propagates them to physical DB indices on
253    /// the parent table's flattened columns.
254    pub indices: Vec<Index>,
255}
256
257impl EmbeddedStruct {
258    pub(crate) fn verify(&self, db: &driver::Capability) -> Result<()> {
259        for field in &self.fields {
260            field.verify(db)?;
261        }
262        Ok(())
263    }
264}
265
266/// An embedded enum model stored in the parent table via a discriminant column
267/// and optional per-variant data columns.
268///
269/// The discriminant column holds a value (integer or string) identifying the active variant.
270/// Variants may optionally carry data fields, which are stored as additional
271/// nullable columns in the parent table.
272///
273/// # Examples
274///
275/// ```ignore
276/// let ee = model.as_embedded_enum_unwrap();
277/// for variant in &ee.variants {
278///     println!("variant {} = {}", variant.name.upper_camel_case(), variant.discriminant);
279/// }
280/// ```
281#[derive(Debug, Clone)]
282pub struct EmbeddedEnum {
283    /// Uniquely identifies this model within the schema.
284    pub id: ModelId,
285
286    /// The model's name.
287    pub name: Name,
288
289    /// The primitive type used for the discriminant column.
290    pub discriminant: FieldPrimitive,
291
292    /// The enum's variants.
293    pub variants: Vec<EnumVariant>,
294
295    /// All fields across all variants, with global indices. Each field's
296    /// [`variant`](Field::variant) identifies which variant it belongs to.
297    pub fields: Vec<Field>,
298
299    /// Indices defined on this embedded enum's variant fields.
300    ///
301    /// These reference fields within this embedded enum (not the parent
302    /// model). The schema builder propagates them to physical DB indices on
303    /// the parent table's flattened columns.
304    pub indices: Vec<Index>,
305}
306
307/// One variant of an [`EmbeddedEnum`].
308///
309/// Each variant has a name and a discriminant value (integer or string) that is
310/// stored in the database to identify which variant is active.
311#[derive(Debug, Clone)]
312pub struct EnumVariant {
313    /// The Rust variant name.
314    pub name: Name,
315
316    /// The discriminant value stored in the database column.
317    /// Typically `Value::I64` for integer discriminants or `Value::String` for
318    /// string discriminants.
319    pub discriminant: stmt::Value,
320}
321
322impl EmbeddedEnum {
323    /// Returns true if at least one variant carries data fields.
324    pub fn has_data_variants(&self) -> bool {
325        !self.fields.is_empty()
326    }
327
328    /// Returns fields belonging to a specific variant.
329    pub fn variant_fields(&self, variant_index: usize) -> impl Iterator<Item = &Field> {
330        let variant_id = VariantId {
331            model: self.id,
332            index: variant_index,
333        };
334        self.fields
335            .iter()
336            .filter(move |f| f.variant == Some(variant_id))
337    }
338
339    pub(crate) fn verify(&self, db: &driver::Capability) -> Result<()> {
340        for field in &self.fields {
341            field.verify(db)?;
342        }
343        Ok(())
344    }
345}
346
347/// Uniquely identifies a [`Model`] within a [`Schema`](super::Schema).
348///
349/// `ModelId` wraps a `usize` index into the schema's model map. It is `Copy`
350/// and can be used as a key for lookups.
351///
352/// # Examples
353///
354/// ```
355/// use toasty_core::schema::app::ModelId;
356///
357/// let id = ModelId(0);
358/// let field_id = id.field(2);
359/// assert_eq!(field_id.model, id);
360/// assert_eq!(field_id.index, 2);
361/// ```
362#[derive(Copy, Clone, Eq, PartialEq, Hash)]
363#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
364pub struct ModelId(pub usize);
365
366impl Model {
367    /// Returns this model's [`ModelId`].
368    pub fn id(&self) -> ModelId {
369        match self {
370            Model::Root(root) => root.id,
371            Model::EmbeddedStruct(embedded) => embedded.id,
372            Model::EmbeddedEnum(e) => e.id,
373        }
374    }
375
376    /// Returns a reference to this model's [`Name`].
377    pub fn name(&self) -> &Name {
378        match self {
379            Model::Root(root) => &root.name,
380            Model::EmbeddedStruct(embedded) => &embedded.name,
381            Model::EmbeddedEnum(e) => &e.name,
382        }
383    }
384
385    /// Returns true if this is a root model (has a table and primary key)
386    pub fn is_root(&self) -> bool {
387        matches!(self, Model::Root(_))
388    }
389
390    /// Returns true if this is an embedded model (flattened into parent)
391    pub fn is_embedded(&self) -> bool {
392        matches!(self, Model::EmbeddedStruct(_) | Model::EmbeddedEnum(_))
393    }
394
395    /// Returns true if this model can be the target of a relation
396    pub fn can_be_relation_target(&self) -> bool {
397        self.is_root()
398    }
399
400    /// Returns the inner [`ModelRoot`] if this is a root model.
401    pub fn as_root(&self) -> Option<&ModelRoot> {
402        match self {
403            Model::Root(root) => Some(root),
404            _ => None,
405        }
406    }
407
408    /// Returns a reference to the root model data.
409    ///
410    /// # Panics
411    ///
412    /// Panics if this is not a [`Model::Root`].
413    pub fn as_root_unwrap(&self) -> &ModelRoot {
414        match self {
415            Model::Root(root) => root,
416            Model::EmbeddedStruct(_) => panic!("expected root model, found embedded struct"),
417            Model::EmbeddedEnum(_) => panic!("expected root model, found embedded enum"),
418        }
419    }
420
421    /// Returns a mutable reference to the root model data.
422    ///
423    /// # Panics
424    ///
425    /// Panics if this is not a [`Model::Root`].
426    pub fn as_root_mut_unwrap(&mut self) -> &mut ModelRoot {
427        match self {
428            Model::Root(root) => root,
429            Model::EmbeddedStruct(_) => panic!("expected root model, found embedded struct"),
430            Model::EmbeddedEnum(_) => panic!("expected root model, found embedded enum"),
431        }
432    }
433
434    /// Returns a reference to the embedded struct data.
435    ///
436    /// # Panics
437    ///
438    /// Panics if this is not a [`Model::EmbeddedStruct`].
439    pub fn as_embedded_struct_unwrap(&self) -> &EmbeddedStruct {
440        match self {
441            Model::EmbeddedStruct(embedded) => embedded,
442            Model::Root(_) => panic!("expected embedded struct, found root model"),
443            Model::EmbeddedEnum(_) => panic!("expected embedded struct, found embedded enum"),
444        }
445    }
446
447    /// Returns a reference to the embedded enum data.
448    ///
449    /// # Panics
450    ///
451    /// Panics if this is not a [`Model::EmbeddedEnum`].
452    pub fn as_embedded_enum_unwrap(&self) -> &EmbeddedEnum {
453        match self {
454            Model::EmbeddedEnum(e) => e,
455            Model::Root(_) => panic!("expected embedded enum, found root model"),
456            Model::EmbeddedStruct(_) => panic!("expected embedded enum, found embedded struct"),
457        }
458    }
459
460    pub(crate) fn verify(&self, db: &driver::Capability) -> Result<()> {
461        match self {
462            Model::Root(root) => root.verify(db),
463            Model::EmbeddedStruct(embedded) => embedded.verify(db),
464            Model::EmbeddedEnum(e) => e.verify(db),
465        }
466    }
467}
468
469/// Identifies a specific variant within an [`EmbeddedEnum`] model.
470///
471/// # Examples
472///
473/// ```
474/// use toasty_core::schema::app::ModelId;
475///
476/// let variant_id = ModelId(1).variant(0);
477/// assert_eq!(variant_id.model, ModelId(1));
478/// assert_eq!(variant_id.index, 0);
479/// ```
480#[derive(Copy, Clone, PartialEq, Eq, Hash)]
481pub struct VariantId {
482    /// The enum model this variant belongs to.
483    pub model: ModelId,
484    /// Index of the variant within `EmbeddedEnum::variants`.
485    pub index: usize,
486}
487
488impl fmt::Debug for VariantId {
489    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
490        write!(fmt, "VariantId({}/{})", self.model.0, self.index)
491    }
492}
493
494impl ModelId {
495    /// Create a `FieldId` representing the current model's field at index
496    /// `index`.
497    pub const fn field(self, index: usize) -> FieldId {
498        FieldId { model: self, index }
499    }
500
501    /// Create a `VariantId` representing the current model's variant at
502    /// `index`.
503    pub const fn variant(self, index: usize) -> VariantId {
504        VariantId { model: self, index }
505    }
506
507    pub(crate) const fn placeholder() -> Self {
508        Self(usize::MAX)
509    }
510}
511
512impl From<&Self> for ModelId {
513    fn from(src: &Self) -> Self {
514        *src
515    }
516}
517
518impl From<&mut Self> for ModelId {
519    fn from(src: &mut Self) -> Self {
520        *src
521    }
522}
523
524impl From<&Model> for ModelId {
525    fn from(value: &Model) -> Self {
526        value.id()
527    }
528}
529
530impl From<&ModelRoot> for ModelId {
531    fn from(value: &ModelRoot) -> Self {
532        value.id
533    }
534}
535
536impl fmt::Debug for ModelId {
537    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
538        write!(fmt, "ModelId({})", self.0)
539    }
540}