toasty-core 0.10.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
mod primitive;
pub use primitive::{FieldPrimitive, SerializeFormat};

use super::{AutoStrategy, BelongsTo, Constraint, Embedded, Has, ModelId, VariantId, Via};
use crate::{Result, driver, schema::Name, 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,

    /// If `true`, this field is excluded from default queries and must be
    /// loaded on demand via the per-field `.exec()` method.
    pub deferred: 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>,

    /// The shared logical field this variant field participates in, from
    /// `#[shared(<ident>)]`. Variant fields declaring the same identifier are
    /// backed by a single shared column. `None` for fields that own their
    /// column outright (including all fields outside enum variants).
    pub shared: Option<Name>,
}

/// 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())
    }
}

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.as_primitive().is_some());
/// 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 relationship.
    Has(Has),
    /// A relation reached by following a path of existing relations.
    Via(Via),
}

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 `true` if this field is nullable.
    pub fn nullable(&self) -> bool {
        self.nullable
    }

    /// 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`, `Has`, or
    /// `Via`).
    pub fn is_relation(&self) -> bool {
        self.ty.is_relation()
    }

    /// 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::Has(has) => Some(has.target),
            FieldTy::Via(via) => Some(via.target),
            _ => None,
        }
    }

    /// 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::Has(has) => &has.expr_ty,
            FieldTy::Via(via) => &via.expr_ty,
        }
    }

    /// Returns the paired relation field, if this field is a relation.
    ///
    /// For `BelongsTo` this returns the inverse `Has` relation (if linked).
    /// For `Has` this returns the paired `BelongsTo`.
    /// Returns `None` for primitive and embedded fields, and for multi-step
    /// (`via`) relations, which have no pair.
    pub fn pair(&self) -> Option<FieldId> {
        match &self.ty {
            FieldTy::Primitive(_) => None,
            FieldTy::Embedded(_) => None,
            FieldTy::BelongsTo(belongs_to) => belongs_to.pair,
            FieldTy::Has(has) => Some(has.pair_id),
            FieldTy::Via(_) => None,
        }
    }

    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 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 `true` if this is a relation type (`BelongsTo`, `Has`, or
    /// `Via`).
    pub fn is_relation(&self) -> bool {
        matches!(self, Self::BelongsTo(..) | Self::Has(..) | Self::Via(..))
    }

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

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

    /// Returns `true` if this is a many-valued [`FieldTy::Has`].
    pub fn is_has_many(&self) -> bool {
        self.as_has().is_some_and(Has::is_many)
    }

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

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

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

    /// Returns `true` if this is a one-valued [`FieldTy::Has`].
    pub fn is_has_one(&self) -> bool {
        self.as_has().is_some_and(Has::is_one)
    }

    /// Returns the inner [`Has`], panicking if this is not a one-valued has
    /// field.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not a one-valued [`FieldTy::Has`].
    #[track_caller]
    pub fn as_has_one_unwrap(&self) -> &Has {
        self.as_has_one()
            .unwrap_or_else(|| 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::Has(ty) => ty.fmt(fmt),
            Self::Via(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)
    }
}