laravel-casts 0.2.0

Eloquent-style attribute casts for laravel-rust models: DateCast and DateTimeCast read, write and serialize a date column in a PHP format
Documentation
//! The contract of a typed cast: a model field whose column holds something else.

use crate::CastError;
use laravel::db::{Decode, Nullable, Value};

/// A model field stored as another type: the column holds [`ColumnCast::Repr`], the program works with `Self`.
///
/// | Laravel               | here                          |
/// |-----------------------|-------------------------------|
/// | `get(..., $value)`    | [`ColumnCast::from_repr`]     |
/// | `set(..., $value)`    | [`ColumnCast::to_repr`]       |
/// | `serialize(...)`      | the type's own `Serialize`    |
/// | the incoming request  | the type's own `Deserialize`  |
///
/// Implement it, then call [`impl_column_cast!`](crate::impl_column_cast) once: it gives the type the `laravel-rust`
/// traits a model field needs (`Decode`, `Nullable` and `From` for [`Value`]). SQL `NULL` is the one of `Repr`, so what
/// `None` writes always has the encoding of the column. [`crate::DateCast`] and [`crate::DateTimeCast`] implement it
/// too.
///
/// For a newtype that is stored as its one field, with nothing to check or convert, `#[derive(laravel::Newtype)]`
/// already does this: use that instead.
///
/// How the type looks outside the database is not part of the contract. Derive or implement `serde` for it; the
/// example goes through `String` both ways, so the request is checked by the same code as everything else.
///
/// ```
/// use laravel::db::Value;
/// use laravel_casts::{CastError, ColumnCast, impl_column_cast};
/// use serde::{Deserialize, Serialize};
///
/// /// Cents in the column, `12.50` outside.
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
/// #[serde(try_from = "String", into = "String")]
/// struct Money(i64);
///
/// impl ColumnCast for Money {
///     type Repr = i64;
///
///     fn from_repr(cents: i64) -> Result<Self, CastError> {
///         Ok(Self(cents))
///     }
///     fn to_repr(&self) -> i64 {
///         self.0
///     }
/// }
/// impl_column_cast!(Money);
///
/// impl From<Money> for String {
///     fn from(money: Money) -> Self {
///         // The sign apart: -5 cents is `-0.05`.
///         let sign = if money.0 < 0 { "-" } else { "" };
///         let cents = money.0.unsigned_abs();
///         format!("{sign}{}.{:02}", cents / 100, cents % 100)
///     }
/// }
///
/// impl TryFrom<String> for Money {
///     type Error = CastError;
///
///     fn try_from(text: String) -> Result<Self, CastError> {
///         let refused = || CastError::Rejected(format!("\"{text}\" is not an amount"));
///         let (sign, amount) = text.strip_prefix('-').map_or(("", text.as_str()), |rest| ("-", rest));
///         let (whole, cents) = amount.split_once('.').unwrap_or((amount, ""));
///         let digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
///         // `12.5` is 1250 cents; a third decimal is refused, not rounded away.
///         if whole.is_empty() || cents.len() > 2 || !digits(whole) || !digits(cents) {
///             return Err(refused());
///         }
///         format!("{sign}{whole}{cents:0<2}").parse().map(Self).map_err(|_| refused())
///     }
/// }
///
/// let bound: Value = Money(1250).into();
/// assert_eq!(bound, Value::BigInteger(Some(1250)));
/// assert_eq!(serde_json::to_string(&Money(1250)).unwrap(), "\"12.50\"");
/// assert_eq!(serde_json::from_str::<Money>("\"-1.5\"").unwrap(), Money(-150));
/// assert!(serde_json::from_str::<Money>("\"12.005\"").is_err());
/// ```
pub trait ColumnCast: Sized {
    /// What the column holds: any type `laravel-rust` reads and writes (text, a number, a date, `db::Json<T>`).
    type Repr: Decode + Nullable + Into<Value<'static>>;

    /// `get`: the value of what the column holds.
    ///
    /// # Errors
    /// The column holds something this type cannot be. Reading the row fails with it.
    fn from_repr(repr: Self::Repr) -> Result<Self, CastError>;

    /// `set`: what the column holds for this value. Binding a borrowed value builds it too, so text is copied.
    fn to_repr(&self) -> Self::Repr;
}

/// Gives a type that implements [`ColumnCast`] the traits a `laravel-rust` model field asks for: `Decode`, `Nullable`,
/// and `From<T>`, `From<&T>` and `From<&&T>` for `Value`.
#[macro_export]
macro_rules! impl_column_cast {
    ($ty:ty) => {
        impl $crate::__private::Decode for $ty {
            fn decode(
                row: &$crate::__private::AnyRow,
                index: usize,
            ) -> $crate::__private::Result<Self> {
                let repr =
                    <<$ty as $crate::ColumnCast>::Repr as $crate::__private::Decode>::decode(
                        row, index,
                    )?;
                ::core::result::Result::Ok(<$ty as $crate::ColumnCast>::from_repr(repr)?)
            }
        }

        impl $crate::__private::Nullable for $ty {
            fn null() -> $crate::__private::Value<'static> {
                <<$ty as $crate::ColumnCast>::Repr as $crate::__private::Nullable>::null()
            }
        }

        impl ::core::convert::From<$ty> for $crate::__private::Value<'_> {
            fn from(cast: $ty) -> Self {
                ::core::convert::Into::into(<$ty as $crate::ColumnCast>::to_repr(&cast))
            }
        }

        impl<'__cast> ::core::convert::From<&'__cast $ty> for $crate::__private::Value<'__cast> {
            fn from(cast: &'__cast $ty) -> Self {
                ::core::convert::Into::into(<$ty as $crate::ColumnCast>::to_repr(cast))
            }
        }

        impl<'__cast> ::core::convert::From<&&'__cast $ty> for $crate::__private::Value<'__cast> {
            fn from(cast: &&'__cast $ty) -> Self {
                ::core::convert::Into::into(<$ty as $crate::ColumnCast>::to_repr(*cast))
            }
        }
    };
}