toasty_core/schema/app/constraint.rs
1mod length;
2pub use length::ConstraintLength;
3
4use crate::{Result, stmt};
5
6/// A validation constraint applied to a field.
7///
8/// Constraints are checked at the application level before values are persisted
9/// to the database. If a constraint check fails, the operation returns an error
10/// instead of sending the value to the driver.
11///
12/// # Examples
13///
14/// ```
15/// use toasty_core::schema::app::Constraint;
16///
17/// let c = Constraint::length_less_than(255);
18/// // The constraint can be checked against field values at runtime.
19/// ```
20#[derive(Debug, Clone)]
21pub enum Constraint {
22 /// A length constraint on a string field.
23 Length(ConstraintLength),
24}
25
26impl Constraint {
27 /// Creates a length constraint requiring the value to be shorter than `max`
28 /// characters.
29 ///
30 /// # Examples
31 ///
32 /// ```
33 /// use toasty_core::schema::app::Constraint;
34 ///
35 /// let c = Constraint::length_less_than(100);
36 /// ```
37 pub fn length_less_than(max: u64) -> Self {
38 ConstraintLength {
39 min: None,
40 max: Some(max),
41 }
42 .into()
43 }
44
45 /// Validates `expr` against this constraint.
46 ///
47 /// Returns `Ok(())` if the value satisfies the constraint, or an error
48 /// describing the violation.
49 pub fn check(&self, expr: &stmt::Entry<'_>) -> Result<()> {
50 match self {
51 Constraint::Length(length) => length.check(expr),
52 }
53 }
54}