From 348e841139fcef289c8e60c3d23261e68e443df0 Mon Sep 17 00:00:00 2001 From: Chris Tsang Date: Sun, 28 Aug 2022 13:30:51 +0800 Subject: [PATCH] Refactor ColumnFromStrErr --- sea-orm-macros/src/derives/column.rs | 15 +++++++++++++-- src/entity/column.rs | 2 +- src/error.rs | 20 ++++++++++---------- 3 files changed, 24 insertions(+), 13 deletions(-) diff --git a/sea-orm-macros/src/derives/column.rs b/sea-orm-macros/src/derives/column.rs index 42e1dfe1d..c60a91d69 100644 --- a/sea-orm-macros/src/derives/column.rs +++ b/sea-orm-macros/src/derives/column.rs @@ -71,7 +71,7 @@ pub fn impl_default_as_str(ident: &Ident, data: &Data) -> syn::Result syn::Result { 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 ) }); + 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 fn from_str(s: &str) -> std::result::Result { 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 }), } } } diff --git a/src/entity/column.rs b/src/entity/column.rs index 8dbff6ea4..6f946f51b 100644 --- a/src/entity/column.rs +++ b/src/entity/column.rs @@ -521,7 +521,7 @@ mod tests { )); assert!(matches!( fruit::Column::from_str("does_not_exist"), - Err(crate::ColumnFromStrErr(_)) + Err(crate::ColumnFromStrErr { .. }) )); } diff --git a/src/error.rs b/src/error.rs index 6d5940953..a5db227eb 100644 --- a/src/error.rs +++ b/src/error.rs @@ -16,7 +16,7 @@ pub enum DbErr { /// Into type into: &'static str, /// TryError - source: Box, + source: Box, }, /// 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, }