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 /// The versionable field, if any. Points directly into `fields` to avoid scanning.
167 pub version_field: Option<FieldId>,
168}
169
170impl ModelRoot {
171 /// Builds a `SELECT` query that filters by this model's primary key using
172 /// the supplied `input` to resolve argument values.
173 pub fn find_by_id(&self, mut input: impl stmt::Input) -> stmt::Query {
174 let filter = match &self.primary_key.fields[..] {
175 [pk_field] => stmt::Expr::eq(
176 stmt::Expr::ref_self_field(pk_field),
177 input
178 .resolve_arg(&0.into(), &stmt::Projection::identity())
179 .unwrap(),
180 ),
181 pk_fields => stmt::Expr::and_from_vec(
182 pk_fields
183 .iter()
184 .enumerate()
185 .map(|(i, pk_field)| {
186 stmt::Expr::eq(
187 stmt::Expr::ref_self_field(pk_field),
188 input
189 .resolve_arg(&i.into(), &stmt::Projection::identity())
190 .unwrap(),
191 )
192 })
193 .collect(),
194 ),
195 };
196
197 stmt::Query::new_select(self.id, filter)
198 }
199
200 /// Iterate over the fields used for the model's primary key.
201 pub fn primary_key_fields(&self) -> impl ExactSizeIterator<Item = &'_ Field> {
202 self.primary_key
203 .fields
204 .iter()
205 .map(|pk_field| &self.fields[pk_field.index])
206 }
207
208 /// Returns the versionable field, if one is defined on this model.
209 pub fn version_field(&self) -> Option<&Field> {
210 self.version_field.map(|id| &self.fields[id.index])
211 }
212
213 /// Looks up a field by its application-level name.
214 ///
215 /// Returns `None` if no field with that name exists on this model.
216 pub fn field_by_name(&self, name: &str) -> Option<&Field> {
217 self.fields
218 .iter()
219 .find(|field| field.name.app.as_deref() == Some(name))
220 }
221
222 pub(crate) fn verify(&self, db: &driver::Capability) -> Result<()> {
223 for field in &self.fields {
224 field.verify(db)?;
225 }
226 Ok(())
227 }
228}
229
230/// An embedded struct model whose fields are flattened into its parent model's
231/// database table.
232///
233/// Embedded structs do not have their own table or primary key. Their fields
234/// become additional columns in the parent table. Indices declared on an
235/// embedded struct's fields are propagated to physical DB indices on the parent
236/// table.
237///
238/// # Examples
239///
240/// ```ignore
241/// let embedded = model.as_embedded_struct_unwrap();
242/// for field in &embedded.fields {
243/// println!(" embedded field: {}", field.name);
244/// }
245/// ```
246#[derive(Debug, Clone)]
247pub struct EmbeddedStruct {
248 /// Uniquely identifies this model within the schema.
249 pub id: ModelId,
250
251 /// The model's name.
252 pub name: Name,
253
254 /// Fields contained by this embedded struct.
255 pub fields: Vec<Field>,
256
257 /// Indices defined on this embedded struct's fields.
258 ///
259 /// These reference fields within this embedded struct (not the parent
260 /// model). The schema builder propagates them to physical DB indices on
261 /// the parent table's flattened columns.
262 pub indices: Vec<Index>,
263}
264
265impl EmbeddedStruct {
266 pub(crate) fn verify(&self, db: &driver::Capability) -> Result<()> {
267 for field in &self.fields {
268 field.verify(db)?;
269 }
270 Ok(())
271 }
272}
273
274/// An embedded enum model stored in the parent table via a discriminant column
275/// and optional per-variant data columns.
276///
277/// The discriminant column holds a value (integer or string) identifying the active variant.
278/// Variants may optionally carry data fields, which are stored as additional
279/// nullable columns in the parent table.
280///
281/// # Examples
282///
283/// ```ignore
284/// let ee = model.as_embedded_enum_unwrap();
285/// for variant in &ee.variants {
286/// println!("variant {} = {}", variant.name.upper_camel_case(), variant.discriminant);
287/// }
288/// ```
289#[derive(Debug, Clone)]
290pub struct EmbeddedEnum {
291 /// Uniquely identifies this model within the schema.
292 pub id: ModelId,
293
294 /// The model's name.
295 pub name: Name,
296
297 /// The primitive type used for the discriminant column.
298 pub discriminant: FieldPrimitive,
299
300 /// The enum's variants.
301 pub variants: Vec<EnumVariant>,
302
303 /// All fields across all variants, with global indices. Each field's
304 /// [`variant`](Field::variant) identifies which variant it belongs to.
305 pub fields: Vec<Field>,
306
307 /// Indices defined on this embedded enum's variant fields.
308 ///
309 /// These reference fields within this embedded enum (not the parent
310 /// model). The schema builder propagates them to physical DB indices on
311 /// the parent table's flattened columns.
312 pub indices: Vec<Index>,
313}
314
315/// One variant of an [`EmbeddedEnum`].
316///
317/// Each variant has a name and a discriminant value (integer or string) that is
318/// stored in the database to identify which variant is active.
319#[derive(Debug, Clone)]
320pub struct EnumVariant {
321 /// The Rust variant name.
322 pub name: Name,
323
324 /// The discriminant value stored in the database column.
325 /// Typically `Value::I64` for integer discriminants or `Value::String` for
326 /// string discriminants.
327 pub discriminant: stmt::Value,
328}
329
330impl EmbeddedEnum {
331 /// Returns true if at least one variant carries data fields.
332 pub fn has_data_variants(&self) -> bool {
333 !self.fields.is_empty()
334 }
335
336 /// Returns fields belonging to a specific variant.
337 pub fn variant_fields(&self, variant_index: usize) -> impl Iterator<Item = &Field> {
338 let variant_id = VariantId {
339 model: self.id,
340 index: variant_index,
341 };
342 self.fields
343 .iter()
344 .filter(move |f| f.variant == Some(variant_id))
345 }
346
347 pub(crate) fn verify(&self, db: &driver::Capability) -> Result<()> {
348 for field in &self.fields {
349 field.verify(db)?;
350 }
351 Ok(())
352 }
353}
354
355/// Uniquely identifies a [`Model`] within a [`Schema`](super::Schema).
356///
357/// `ModelId` wraps a `usize` index into the schema's model map. It is `Copy`
358/// and can be used as a key for lookups.
359///
360/// # Examples
361///
362/// ```
363/// use toasty_core::schema::app::ModelId;
364///
365/// let id = ModelId(0);
366/// let field_id = id.field(2);
367/// assert_eq!(field_id.model, id);
368/// assert_eq!(field_id.index, 2);
369/// ```
370#[derive(Copy, Clone, Eq, PartialEq, Hash)]
371#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
372pub struct ModelId(pub usize);
373
374impl Model {
375 /// Returns this model's [`ModelId`].
376 pub fn id(&self) -> ModelId {
377 match self {
378 Model::Root(root) => root.id,
379 Model::EmbeddedStruct(embedded) => embedded.id,
380 Model::EmbeddedEnum(e) => e.id,
381 }
382 }
383
384 /// Returns a reference to this model's [`Name`].
385 pub fn name(&self) -> &Name {
386 match self {
387 Model::Root(root) => &root.name,
388 Model::EmbeddedStruct(embedded) => &embedded.name,
389 Model::EmbeddedEnum(e) => &e.name,
390 }
391 }
392
393 /// Returns true if this is a root model (has a table and primary key)
394 pub fn is_root(&self) -> bool {
395 matches!(self, Model::Root(_))
396 }
397
398 /// Returns true if this is an embedded model (flattened into parent)
399 pub fn is_embedded(&self) -> bool {
400 matches!(self, Model::EmbeddedStruct(_) | Model::EmbeddedEnum(_))
401 }
402
403 /// Returns true if this model can be the target of a relation
404 pub fn can_be_relation_target(&self) -> bool {
405 self.is_root()
406 }
407
408 /// Returns the inner [`ModelRoot`] if this is a root model.
409 pub fn as_root(&self) -> Option<&ModelRoot> {
410 match self {
411 Model::Root(root) => Some(root),
412 _ => None,
413 }
414 }
415
416 /// Returns a reference to the root model data.
417 ///
418 /// # Panics
419 ///
420 /// Panics if this is not a [`Model::Root`].
421 pub fn as_root_unwrap(&self) -> &ModelRoot {
422 match self {
423 Model::Root(root) => root,
424 Model::EmbeddedStruct(_) => panic!("expected root model, found embedded struct"),
425 Model::EmbeddedEnum(_) => panic!("expected root model, found embedded enum"),
426 }
427 }
428
429 /// Returns a mutable reference to the root model data.
430 ///
431 /// # Panics
432 ///
433 /// Panics if this is not a [`Model::Root`].
434 pub fn as_root_mut_unwrap(&mut self) -> &mut ModelRoot {
435 match self {
436 Model::Root(root) => root,
437 Model::EmbeddedStruct(_) => panic!("expected root model, found embedded struct"),
438 Model::EmbeddedEnum(_) => panic!("expected root model, found embedded enum"),
439 }
440 }
441
442 /// Returns a reference to the embedded struct data.
443 ///
444 /// # Panics
445 ///
446 /// Panics if this is not a [`Model::EmbeddedStruct`].
447 pub fn as_embedded_struct_unwrap(&self) -> &EmbeddedStruct {
448 match self {
449 Model::EmbeddedStruct(embedded) => embedded,
450 Model::Root(_) => panic!("expected embedded struct, found root model"),
451 Model::EmbeddedEnum(_) => panic!("expected embedded struct, found embedded enum"),
452 }
453 }
454
455 /// Returns a reference to the embedded enum data.
456 ///
457 /// # Panics
458 ///
459 /// Panics if this is not a [`Model::EmbeddedEnum`].
460 pub fn as_embedded_enum_unwrap(&self) -> &EmbeddedEnum {
461 match self {
462 Model::EmbeddedEnum(e) => e,
463 Model::Root(_) => panic!("expected embedded enum, found root model"),
464 Model::EmbeddedStruct(_) => panic!("expected embedded enum, found embedded struct"),
465 }
466 }
467
468 pub(crate) fn verify(&self, db: &driver::Capability) -> Result<()> {
469 match self {
470 Model::Root(root) => root.verify(db),
471 Model::EmbeddedStruct(embedded) => embedded.verify(db),
472 Model::EmbeddedEnum(e) => e.verify(db),
473 }
474 }
475}
476
477/// Identifies a specific variant within an [`EmbeddedEnum`] model.
478///
479/// # Examples
480///
481/// ```
482/// use toasty_core::schema::app::ModelId;
483///
484/// let variant_id = ModelId(1).variant(0);
485/// assert_eq!(variant_id.model, ModelId(1));
486/// assert_eq!(variant_id.index, 0);
487/// ```
488#[derive(Copy, Clone, PartialEq, Eq, Hash)]
489pub struct VariantId {
490 /// The enum model this variant belongs to.
491 pub model: ModelId,
492 /// Index of the variant within `EmbeddedEnum::variants`.
493 pub index: usize,
494}
495
496impl fmt::Debug for VariantId {
497 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
498 write!(fmt, "VariantId({}/{})", self.model.0, self.index)
499 }
500}
501
502impl ModelId {
503 /// Create a `FieldId` representing the current model's field at index
504 /// `index`.
505 pub const fn field(self, index: usize) -> FieldId {
506 FieldId { model: self, index }
507 }
508
509 /// Create a `VariantId` representing the current model's variant at
510 /// `index`.
511 pub const fn variant(self, index: usize) -> VariantId {
512 VariantId { model: self, index }
513 }
514
515 pub(crate) const fn placeholder() -> Self {
516 Self(usize::MAX)
517 }
518}
519
520impl From<&Self> for ModelId {
521 fn from(src: &Self) -> Self {
522 *src
523 }
524}
525
526impl From<&mut Self> for ModelId {
527 fn from(src: &mut Self) -> Self {
528 *src
529 }
530}
531
532impl From<&Model> for ModelId {
533 fn from(value: &Model) -> Self {
534 value.id()
535 }
536}
537
538impl From<&ModelRoot> for ModelId {
539 fn from(value: &ModelRoot) -> Self {
540 value.id
541 }
542}
543
544impl fmt::Debug for ModelId {
545 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
546 write!(fmt, "ModelId({})", self.0)
547 }
548}