2 unstable releases
0.2.0 | Oct 26, 2023 |
---|---|
0.1.0 | Oct 26, 2023 |
#2065 in Database interfaces
7KB
sea-orm-try-into-active-model
Provides DeriveTryIntoActiveModel
derive macro and TryIntoActiveModel
trait
Usage example:
use sea_orm_try_into_active_model::DeriveTryIntoActiveModel;
use sea_orm::entity::prelude::*;
use sea_orm::ActiveEnum;
use sea_orm::ActiveValue;
use sea_orm::Value;
use strum::VariantNames;
use strum_macros::EnumVariantNames;
use strum_macros::EnumString;
use strum_macros::IntoStaticStr;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, EnumIter, DeriveActiveEnum, IntoStaticStr, EnumString, EnumVariantNames]
#[sea_orm(rs_type = "i32", db_type = "Integer")]
#[repr(i32)]
pub enum Kind {
Type1 = 0,
Type2 = 1,
}
#[derive(Clone, Debug, DeriveEntityModel, Eq)]
#[sea_orm(schema_name = "generic_devices", table_name = "list")]
pub struct DeviceInfo {
#[sea_orm(primary_key, auto_increment = false, unique)]
pub brand_id: i32,
pub object_uuid: Option<Uuid>,
pub kind: Kind,
}
#[derive(DeriveTryIntoActiveModel)]
#[sea_orm(
active_model = GenericDevice::ActiveModel,
error = anyhow::Error
)]
pub struct DeviceInfoPost {
pub brand_id: i32,
#[sea_orm(try_into = "try_parse_option_uuid")]
pub object_uuid: Option<String>,
#[sea_orm(try_into = "try_parse_to_enum", direct)]
pub kind: i32,
}
pub fn try_parse_to_enum<T: ActiveEnum + VariantNames + Into<Value>>(
value: T::Value,
) -> Result<ActiveValue<T>, ParseError> {
Ok(ActiveValue::Set(T::try_from_value(&value).map_err(|_| e_active_enum::<T>(value))?))
}
pub fn try_parse_option_uuid(value: Option<String>) -> Result<Option<Uuid>, uuid::Error> {
value.map(|v| v.parse()).transpose()
}
this code will add the method try_into_active_model()
on DeviceInfoPost
with will convert it to DeviceInfo::ActiveModel
if none of the provided parsers fails. If one of them fail it will return an error specified in error
attribute.
Supported struct attributes inside #[sea_orm()
:
active_model
- points withActiveModel
the struct can be converted tooerror
- points with error type shouldtry_into_active_model()
convert errors too
Supported field attributes inside #[sea_orm()]
:
try_into
- specifies a helper function with should be used to convert the value into the ActiveModel valuedirect
- specifies that the helper function does return directlyActiveValue<T>
or the specified error in the struct error attribute, if not specified the values from helper functions are always wrapped inActiveValue::Set
and errors are converted into the specifed error type
Dependencies
~8.5MB
~123K SLoC