Crates.io | sea-orm-try-into-active-model |
lib.rs | sea-orm-try-into-active-model |
version | 0.2.0 |
source | src |
created_at | 2023-10-26 12:09:46.918659 |
updated_at | 2023-10-26 13:10:03.36039 |
description | TryIntoActiveModel for sea-orm |
homepage | https://gitlab.com/dragonn/sea_orm_try_into_active_model |
repository | https://gitlab.com/dragonn/sea_orm_try_into_active_model |
max_upload_size | |
id | 1014347 |
size | 5,102 |
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 with ActiveModel
the struct can be converted tooerror
- points with error type should try_into_active_model()
convert errors tooSupported 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 directly ActiveValue<T>
or the specified error in the struct error attribute, if not specified the values from helper functions are always wrapped in ActiveValue::Set
and errors are converted into the specifed error type