toasty-core 0.5.0

Core types, schema representations, and driver interface for Toasty
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
mod primitive;
pub use primitive::{FieldPrimitive, SerializeFormat};

use super::{
    AutoStrategy, BelongsTo, Constraint, Embedded, HasMany, HasOne, Model, ModelId, Schema,
    VariantId,
};
use crate::{Result, driver, stmt};
use std::fmt;

/// A single field within a model.
///
/// Fields are the building blocks of a model's data structure. Each field has a
/// unique [`FieldId`], a name, a type (primitive, embedded, or relation), and
/// metadata such as nullability, primary-key membership, auto-population
/// strategy, and validation constraints.
///
/// # Examples
///
/// ```ignore
/// use toasty_core::schema::app::{Field, Schema};
///
/// let schema: Schema = /* ... */;
/// let model = schema.model(model_id).as_root_unwrap();
/// for field in &model.fields {
///     println!("{}: primary_key={}", field.name, field.primary_key);
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Field {
    /// Uniquely identifies this field within its containing model.
    pub id: FieldId,

    /// The field's application and storage names.
    pub name: FieldName,

    /// The field's type: primitive, embedded, or a relation variant.
    pub ty: FieldTy,

    /// `true` if this field accepts `None` / `NULL` values.
    pub nullable: bool,

    /// `true` if this field is part of the model's primary key.
    pub primary_key: bool,

    /// If set, Toasty automatically populates this field on insert.
    pub auto: Option<AutoStrategy>,

    /// If `true`, this field tracks an OCC version counter.
    pub versionable: bool,

    /// Validation constraints applied to this field's values.
    pub constraints: Vec<Constraint>,

    /// If this field belongs to an enum variant, identifies that variant.
    /// `None` for fields on root models and embedded structs.
    pub variant: Option<VariantId>,
}

/// Uniquely identifies a [`Field`] within a schema.
///
/// Composed of the owning model's [`ModelId`] and a positional index into that
/// model's field list.
///
/// # Examples
///
/// ```
/// use toasty_core::schema::app::{FieldId, ModelId};
///
/// let id = FieldId { model: ModelId(0), index: 2 };
/// assert_eq!(id.index, 2);
/// ```
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FieldId {
    /// The model this field belongs to.
    pub model: ModelId,
    /// Positional index within the model's field list.
    pub index: usize,
}

/// The name of a field, with separate application and storage representations.
///
/// The `app` field is the Rust-facing name (e.g., `user_name`). It is
/// `Option<String>` to support unnamed (tuple) fields in the future; for now it
/// is always `Some`. The optional `storage` field overrides the column name used
/// in the database; when `None`, `app` is used as the storage name.
///
/// # Examples
///
/// ```
/// use toasty_core::schema::app::FieldName;
///
/// let name = FieldName {
///     app: Some("user_name".to_string()),
///     storage: Some("username".to_string()),
/// };
/// assert_eq!(name.storage_name(), Some("username"));
///
/// let default_name = FieldName {
///     app: Some("email".to_string()),
///     storage: None,
/// };
/// assert_eq!(default_name.storage_name(), Some("email"));
/// ```
#[derive(Debug, Clone)]
pub struct FieldName {
    /// The application-level (Rust) name of the field. `None` for unnamed
    /// (tuple) fields.
    pub app: Option<String>,
    /// Optional override for the database column name. When `None`, `app` is
    /// used.
    pub storage: Option<String>,
}

impl FieldName {
    /// Returns the application-level (Rust) name of this field.
    ///
    /// This is a convenience accessor that unwraps the `app` field, which is
    /// `Option<String>` to support unnamed (tuple) fields. Most fields have an
    /// application name, and this method provides direct access without manual
    /// unwrapping.
    ///
    /// # Panics
    ///
    /// Panics if `app` is `None` (i.e., the field is unnamed).
    ///
    /// # Examples
    ///
    /// ```
    /// use toasty_core::schema::app::FieldName;
    ///
    /// let name = FieldName {
    ///     app: Some("user_name".to_string()),
    ///     storage: None,
    /// };
    /// assert_eq!(name.app_unwrap(), "user_name");
    /// ```
    #[track_caller]
    pub fn app_unwrap(&self) -> &str {
        self.app.as_deref().unwrap()
    }

    /// Returns the storage (database column) name for this field, if one can
    /// be determined.
    ///
    /// Returns `storage` if set, otherwise falls back to `app`. Returns `None`
    /// only when both fields are `None`.
    pub fn storage_name(&self) -> Option<&str> {
        self.storage.as_deref().or(self.app.as_deref())
    }

    /// Returns the storage (database column) name for this field.
    ///
    /// This is a convenience wrapper around [`storage_name`](FieldName::storage_name)
    /// for callers that expect a name to always be present.
    ///
    /// # Panics
    ///
    /// Panics if both `storage` and `app` are `None`.
    pub fn storage_name_unwrap(&self) -> &str {
        self.storage_name()
            .expect("must specify app name or storage name")
    }
}

impl fmt::Display for FieldName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.app.as_deref().unwrap_or("<unnamed>"))
    }
}

/// The type of a [`Field`], distinguishing primitives, embedded types, and
/// relation variants.
///
/// # Examples
///
/// ```
/// use toasty_core::schema::app::{FieldPrimitive, FieldTy};
/// use toasty_core::stmt::Type;
///
/// let ty = FieldTy::Primitive(FieldPrimitive {
///     ty: Type::String,
///     storage_ty: None,
///     serialize: None,
/// });
/// assert!(ty.is_primitive());
/// assert!(!ty.is_relation());
/// ```
#[derive(Clone)]
pub enum FieldTy {
    /// A primitive (scalar) field backed by a single column.
    Primitive(FieldPrimitive),
    /// An embedded struct or enum, flattened into the parent table.
    Embedded(Embedded),
    /// The owning side of a relationship (stores the foreign key).
    BelongsTo(BelongsTo),
    /// The inverse side of a one-to-many relationship.
    HasMany(HasMany),
    /// The inverse side of a one-to-one relationship.
    HasOne(HasOne),
}

impl Field {
    /// Returns this field's [`FieldId`].
    pub fn id(&self) -> FieldId {
        self.id
    }

    /// Returns a reference to this field's [`FieldName`].
    pub fn name(&self) -> &FieldName {
        &self.name
    }

    /// Returns a reference to this field's [`FieldTy`].
    pub fn ty(&self) -> &FieldTy {
        &self.ty
    }

    /// Returns `true` if this field is nullable.
    pub fn nullable(&self) -> bool {
        self.nullable
    }

    /// Returns `true` if this field is part of the primary key.
    pub fn primary_key(&self) -> bool {
        self.primary_key
    }

    /// Returns the auto-population strategy, if one is configured.
    pub fn auto(&self) -> Option<&AutoStrategy> {
        self.auto.as_ref()
    }

    /// Returns `true` if this field uses auto-increment for value generation.
    pub fn is_auto_increment(&self) -> bool {
        self.auto().map(|auto| auto.is_increment()).unwrap_or(false)
    }

    /// Returns `true` if this field tracks an OCC version counter.
    pub fn is_versionable(&self) -> bool {
        self.versionable
    }

    /// Returns `true` if this field is a relation (`BelongsTo`, `HasMany`, or
    /// `HasOne`).
    pub fn is_relation(&self) -> bool {
        self.ty.is_relation()
    }

    /// Returns a fully qualified name for the field.
    pub fn full_name(&self, schema: &Schema) -> Option<String> {
        self.name.app.as_ref().map(|app_name| {
            let model = schema.model(self.id.model);
            format!("{}::{}", model.name().upper_camel_case(), app_name)
        })
    }

    /// If the field is a relation, return the relation's target ModelId.
    pub fn relation_target_id(&self) -> Option<ModelId> {
        match &self.ty {
            FieldTy::BelongsTo(belongs_to) => Some(belongs_to.target),
            FieldTy::HasMany(has_many) => Some(has_many.target),
            _ => None,
        }
    }

    /// If the field is a relation, return the target of the relation.
    pub fn relation_target<'a>(&self, schema: &'a Schema) -> Option<&'a Model> {
        self.relation_target_id().map(|id| schema.model(id))
    }

    /// Returns the expression type this field evaluates to.
    ///
    /// For primitives this is the scalar type; for relations and embedded types
    /// it is the type visible to the application layer.
    pub fn expr_ty(&self) -> &stmt::Type {
        match &self.ty {
            FieldTy::Primitive(primitive) => &primitive.ty,
            FieldTy::Embedded(embedded) => &embedded.expr_ty,
            FieldTy::BelongsTo(belongs_to) => &belongs_to.expr_ty,
            FieldTy::HasMany(has_many) => &has_many.expr_ty,
            FieldTy::HasOne(has_one) => &has_one.expr_ty,
        }
    }

    /// Returns the paired relation field, if this field is a relation.
    ///
    /// For `BelongsTo` this returns the inverse `HasMany`/`HasOne` (if linked).
    /// For `HasMany` and `HasOne` this returns the paired `BelongsTo`.
    /// Returns `None` for primitive and embedded fields.
    pub fn pair(&self) -> Option<FieldId> {
        match &self.ty {
            FieldTy::Primitive(_) => None,
            FieldTy::Embedded(_) => None,
            FieldTy::BelongsTo(belongs_to) => belongs_to.pair,
            FieldTy::HasMany(has_many) => Some(has_many.pair),
            FieldTy::HasOne(has_one) => Some(has_one.pair),
        }
    }

    pub(crate) fn verify(&self, db: &driver::Capability) -> Result<()> {
        if let FieldTy::Primitive(primitive) = &self.ty
            && let Some(storage_ty) = &primitive.storage_ty
        {
            storage_ty.verify(db)?;
        }

        Ok(())
    }
}

impl FieldTy {
    /// Returns `true` if this is a [`FieldTy::Primitive`].
    pub fn is_primitive(&self) -> bool {
        matches!(self, Self::Primitive(..))
    }

    /// Returns the inner [`FieldPrimitive`] if this is a primitive field.
    pub fn as_primitive(&self) -> Option<&FieldPrimitive> {
        match self {
            Self::Primitive(primitive) => Some(primitive),
            _ => None,
        }
    }

    /// Returns the inner [`FieldPrimitive`], panicking if this is not a
    /// primitive field.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not [`FieldTy::Primitive`].
    #[track_caller]
    pub fn as_primitive_unwrap(&self) -> &FieldPrimitive {
        match self {
            Self::Primitive(simple) => simple,
            _ => panic!("expected simple field, but was {self:?}"),
        }
    }

    /// Returns a mutable reference to the inner [`FieldPrimitive`], panicking
    /// if this is not a primitive field.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not [`FieldTy::Primitive`].
    #[track_caller]
    pub fn as_primitive_mut_unwrap(&mut self) -> &mut FieldPrimitive {
        match self {
            Self::Primitive(simple) => simple,
            _ => panic!("expected simple field, but was {self:?}"),
        }
    }

    /// Returns `true` if this is a [`FieldTy::Embedded`].
    pub fn is_embedded(&self) -> bool {
        matches!(self, Self::Embedded(..))
    }

    /// Returns the inner [`Embedded`] if this is an embedded field.
    pub fn as_embedded(&self) -> Option<&Embedded> {
        match self {
            Self::Embedded(embedded) => Some(embedded),
            _ => None,
        }
    }

    /// Returns the inner [`Embedded`], panicking if this is not an embedded
    /// field.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not [`FieldTy::Embedded`].
    #[track_caller]
    pub fn as_embedded_unwrap(&self) -> &Embedded {
        match self {
            Self::Embedded(embedded) => embedded,
            _ => panic!("expected embedded field, but was {self:?}"),
        }
    }

    /// Returns a mutable reference to the inner [`Embedded`], panicking if
    /// this is not an embedded field.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not [`FieldTy::Embedded`].
    #[track_caller]
    pub fn as_embedded_mut_unwrap(&mut self) -> &mut Embedded {
        match self {
            Self::Embedded(embedded) => embedded,
            _ => panic!("expected embedded field, but was {self:?}"),
        }
    }

    /// Returns `true` if this is a relation type (`BelongsTo`, `HasMany`, or
    /// `HasOne`).
    pub fn is_relation(&self) -> bool {
        matches!(
            self,
            Self::BelongsTo(..) | Self::HasMany(..) | Self::HasOne(..)
        )
    }

    /// Returns `true` if this is a `HasMany` or `HasOne` relation.
    pub fn is_has_n(&self) -> bool {
        matches!(self, Self::HasMany(..) | Self::HasOne(..))
    }

    /// Returns `true` if this is a [`FieldTy::HasMany`].
    pub fn is_has_many(&self) -> bool {
        matches!(self, Self::HasMany(..))
    }

    /// Returns the inner [`HasMany`] if this is a has-many field.
    pub fn as_has_many(&self) -> Option<&HasMany> {
        match self {
            Self::HasMany(has_many) => Some(has_many),
            _ => None,
        }
    }

    /// Returns the inner [`HasMany`], panicking if this is not a has-many
    /// field.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not [`FieldTy::HasMany`].
    #[track_caller]
    pub fn as_has_many_unwrap(&self) -> &HasMany {
        match self {
            Self::HasMany(has_many) => has_many,
            _ => panic!("expected field to be `HasMany`, but was {self:?}"),
        }
    }

    /// Returns a mutable reference to the inner [`HasMany`], panicking if
    /// this is not a has-many field.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not [`FieldTy::HasMany`].
    #[track_caller]
    pub fn as_has_many_mut_unwrap(&mut self) -> &mut HasMany {
        match self {
            Self::HasMany(has_many) => has_many,
            _ => panic!("expected field to be `HasMany`, but was {self:?}"),
        }
    }

    /// Returns the inner [`HasOne`] if this is a has-one field.
    pub fn as_has_one(&self) -> Option<&HasOne> {
        match self {
            Self::HasOne(has_one) => Some(has_one),
            _ => None,
        }
    }

    /// Returns `true` if this is a [`FieldTy::HasOne`].
    pub fn is_has_one(&self) -> bool {
        matches!(self, Self::HasOne(..))
    }

    /// Returns the inner [`HasOne`], panicking if this is not a has-one field.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not [`FieldTy::HasOne`].
    #[track_caller]
    pub fn as_has_one_unwrap(&self) -> &HasOne {
        match self {
            Self::HasOne(has_one) => has_one,
            _ => panic!("expected field to be `HasOne`, but it was {self:?}"),
        }
    }

    /// Returns a mutable reference to the inner [`HasOne`], panicking if
    /// this is not a has-one field.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not [`FieldTy::HasOne`].
    #[track_caller]
    pub fn as_has_one_mut_unwrap(&mut self) -> &mut HasOne {
        match self {
            Self::HasOne(has_one) => has_one,
            _ => panic!("expected field to be `HasOne`, but it was {self:?}"),
        }
    }

    /// Returns `true` if this is a [`FieldTy::BelongsTo`].
    pub fn is_belongs_to(&self) -> bool {
        matches!(self, Self::BelongsTo(..))
    }

    /// Returns the inner [`BelongsTo`] if this is a belongs-to field.
    pub fn as_belongs_to(&self) -> Option<&BelongsTo> {
        match self {
            Self::BelongsTo(belongs_to) => Some(belongs_to),
            _ => None,
        }
    }

    /// Returns the inner [`BelongsTo`], panicking if this is not a belongs-to
    /// field.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not [`FieldTy::BelongsTo`].
    #[track_caller]
    pub fn as_belongs_to_unwrap(&self) -> &BelongsTo {
        match self {
            Self::BelongsTo(belongs_to) => belongs_to,
            _ => panic!("expected field to be `BelongsTo`, but was {self:?}"),
        }
    }

    /// Returns a mutable reference to the inner [`BelongsTo`], panicking if
    /// this is not a belongs-to field.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not [`FieldTy::BelongsTo`].
    #[track_caller]
    pub fn as_belongs_to_mut_unwrap(&mut self) -> &mut BelongsTo {
        match self {
            Self::BelongsTo(belongs_to) => belongs_to,
            _ => panic!("expected field to be `BelongsTo`, but was {self:?}"),
        }
    }
}

impl fmt::Debug for FieldTy {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Primitive(ty) => ty.fmt(fmt),
            Self::Embedded(ty) => ty.fmt(fmt),
            Self::BelongsTo(ty) => ty.fmt(fmt),
            Self::HasMany(ty) => ty.fmt(fmt),
            Self::HasOne(ty) => ty.fmt(fmt),
        }
    }
}

impl FieldId {
    pub(crate) fn placeholder() -> Self {
        Self {
            model: ModelId::placeholder(),
            index: usize::MAX,
        }
    }

    pub(crate) fn is_placeholder(&self) -> bool {
        self.index == usize::MAX && self.model == ModelId::placeholder()
    }
}

impl From<&Self> for FieldId {
    fn from(val: &Self) -> Self {
        *val
    }
}

impl From<&Field> for FieldId {
    fn from(val: &Field) -> Self {
        val.id
    }
}

impl From<FieldId> for usize {
    fn from(val: FieldId) -> Self {
        val.index
    }
}

impl fmt::Debug for FieldId {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(fmt, "FieldId({}/{})", self.model.0, self.index)
    }
}