Refactoring

This commit is contained in:
Billy Chan 2021-10-20 12:23:55 +08:00
parent 5b0720065f
commit b1e10aec86
No known key found for this signature in database
GPG Key ID: A2D690CAC7DF3CC7

View File

@ -1,5 +1,4 @@
use sea_orm::{entity::prelude::*, TryGetError, TryGetable}; use sea_orm::entity::prelude::*;
use sea_query::{Nullable, ValueType, ValueTypeErr};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)] #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "active_enum")] #[sea_orm(table_name = "active_enum")]
@ -15,73 +14,11 @@ pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {} impl ActiveModelBehavior for ActiveModel {}
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq, DeriveActiveEnum)]
#[sea_orm(rs_type = "String", db_type = "String(Some(1))")]
pub enum Category { pub enum Category {
#[sea_orm(string_value = "B")]
Big, Big,
#[sea_orm(string_value = "S")]
Small, Small,
} }
impl ActiveEnum for Category {
type Value = String;
fn to_value(&self) -> Self::Value {
match self {
Self::Big => "B",
Self::Small => "S",
}
.to_owned()
}
fn try_from_value(v: &Self::Value) -> Result<Self, DbErr> {
match v.as_ref() {
"B" => Ok(Self::Big),
"S" => Ok(Self::Small),
_ => Err(DbErr::Query(format!(
"unexpected value for {} enum: {}",
stringify!(Category),
v
))),
}
}
fn db_type() -> ColumnDef {
ColumnType::String(Some(1)).def()
}
}
impl Into<Value> for Category {
fn into(self) -> Value {
self.to_value().into()
}
}
impl TryGetable for Category {
fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, TryGetError> {
let value = <<Self as ActiveEnum>::Value as TryGetable>::try_get(res, pre, col)?;
Self::try_from_value(&value).map_err(|e| TryGetError::DbErr(e))
}
}
impl ValueType for Category {
fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
let value = <<Self as ActiveEnum>::Value as ValueType>::try_from(v)?;
Self::try_from_value(&value).map_err(|_| ValueTypeErr)
}
fn type_name() -> String {
<<Self as ActiveEnum>::Value as ValueType>::type_name()
}
fn column_type() -> sea_query::ColumnType {
<Self as ActiveEnum>::db_type()
.get_column_type()
.to_owned()
.into()
}
}
impl Nullable for Category {
fn null() -> Value {
<<Self as ActiveEnum>::Value as Nullable>::null()
}
}