Refactor ColumnFromStrErr

This commit is contained in:
Chris Tsang 2022-08-28 13:30:51 +08:00
parent 0b754eab0b
commit 348e841139
3 changed files with 24 additions and 13 deletions

View File

@ -71,7 +71,7 @@ pub fn impl_default_as_str(ident: &Ident, data: &Data) -> syn::Result<TokenStrea
))
}
/// Implement a column using for an enum using [DeriveColumn](sea_orm::DeriveColumn)
/// Implement a column for an enum using [DeriveColumn](sea_orm::DeriveColumn)
pub fn impl_col_from_str(ident: &Ident, data: &Data) -> syn::Result<TokenStream> {
let data_enum = match data {
Data::Enum(data_enum) => data_enum,
@ -91,6 +91,17 @@ pub fn impl_col_from_str(ident: &Ident, data: &Data) -> syn::Result<TokenStream>
)
});
let entity_name = data_enum
.variants
.first()
.map(|column| {
let column_iden = column.ident.clone();
quote!(
#ident::#column_iden.entity_name().to_string()
)
})
.unwrap();
Ok(quote!(
#[automatically_derived]
impl std::str::FromStr for #ident {
@ -99,7 +110,7 @@ pub fn impl_col_from_str(ident: &Ident, data: &Data) -> syn::Result<TokenStream>
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s {
#(#columns),*,
_ => Err(sea_orm::ColumnFromStrErr(format!("Failed to parse '{}' as `{}`", s, stringify!(#ident)))),
_ => Err(sea_orm::ColumnFromStrErr{ string: s.to_owned(), entity: #entity_name }),
}
}
}

View File

@ -521,7 +521,7 @@ mod tests {
));
assert!(matches!(
fruit::Column::from_str("does_not_exist"),
Err(crate::ColumnFromStrErr(_))
Err(crate::ColumnFromStrErr { .. })
));
}

View File

@ -16,7 +16,7 @@ pub enum DbErr {
/// Into type
into: &'static str,
/// TryError
source: Box<dyn std::error::Error + Send>,
source: Box<dyn std::error::Error + Send + Sync>,
},
/// Type error: the specified type cannot be converted from u64. This is not a runtime error.
#[error("Type `{0}` cannot be converted from u64")]
@ -69,14 +69,14 @@ impl PartialEq for DbErr {
}
}
/// An error from a failed column operation when trying to convert the column to a string
#[derive(Debug, Clone)]
pub struct ColumnFromStrErr(pub String);
impl Eq for DbErr {}
impl std::error::Error for ColumnFromStrErr {}
impl std::fmt::Display for ColumnFromStrErr {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0.as_str())
}
/// Error during `impl FromStr for Entity::Column`
#[derive(Error, Debug)]
#[error("Failed to match \"{string}\" as Column for `{entity}`")]
pub struct ColumnFromStrErr {
/// Source of error
pub string: String,
/// Entity this column belongs to
pub entity: String,
}