Derive Macro DeriveValueType

#[derive(DeriveValueType)]
{
    // Attributes available to this derive:
    #[sea_orm]
}
Expand description

Implements traits for types that wrap a database value type.

This procedure macro implements From<T> for Value, sea_orm::TryGetTable, and sea_query::ValueType for the wrapper type T.

The wrapped type must be sea_orm::Value compatible.

§Usage

use sea_orm::DeriveValueType;

#[derive(DeriveValueType)]
struct MyString(String);

#[derive(DeriveValueType)]
struct MyNumber(i32);

It’s also possible to derive value type for enum-strings. Basically the underlying type is String, and the custom must implement methods to_str and from_str.

§Example

use sea_orm::{sea_query::ValueTypeErr, DeriveValueType};

#[derive(DeriveValueType)]
#[sea_orm(value_type = "String")]
pub enum Tag {
    Hard,
    Soft,
}

impl std::fmt::Display for Tag {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Hard => "hard",
                Self::Soft => "soft",
            }
        )
    }
}

impl std::str::FromStr for Tag {
    type Err = ValueTypeErr;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "hard" => Self::Hard,
            "soft" => Self::Soft,
            _ => return Err(ValueTypeErr),
        })
    }
}

from_str defaults to std::str::FromStr::from_str. to_str defaults to std::string::ToString::to_string. They can be overridden with custom functions.

use sea_orm::{sea_query::ValueTypeErr, DeriveValueType};

#[derive(DeriveValueType)]
#[sea_orm(
    value_type = "String",
    from_str = "Tag::from_str",
    to_str = "Tag::to_str"
)]
pub enum Tag {
    Color,
    Grey,
}

impl Tag {
    fn to_str(&self) -> &'static str {
        match self {
            Self::Color => "color",
            Self::Grey => "grey",
        }
    }

    fn from_str(s: &str) -> Result<Self, ValueTypeErr> {
        Ok(match s {
            "color" => Self::Color,
            "grey" => Self::Grey,
            _ => return Err(ValueTypeErr),
        })
    }
}