Use ColumnFromStrErr

This commit is contained in:
Chris Tsang 2021-08-23 01:04:13 +08:00
parent 332ab3ccf5
commit e5f290380a
2 changed files with 14 additions and 8 deletions

View File

@ -1,6 +1,6 @@
use heck::{MixedCase, SnakeCase};
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, quote_spanned};
use quote::{quote, quote_spanned};
use syn::{Data, DataEnum, Fields, Variant};
pub fn impl_default_as_str(ident: &Ident, data: &Data) -> syn::Result<TokenStream> {
@ -42,8 +42,6 @@ pub fn impl_default_as_str(ident: &Ident, data: &Data) -> syn::Result<TokenStrea
}
pub fn impl_col_from_str(ident: &Ident, data: &Data) -> syn::Result<TokenStream> {
let parse_error_iden = format_ident!("Parse{}Err", ident);
let data_enum = match data {
Data::Enum(data_enum) => data_enum,
_ => {
@ -63,16 +61,13 @@ pub fn impl_col_from_str(ident: &Ident, data: &Data) -> syn::Result<TokenStream>
});
Ok(quote!(
#[derive(Debug, Clone, Copy)]
pub struct #parse_error_iden;
impl std::str::FromStr for #ident {
type Err = #parse_error_iden;
type Err = sea_orm::ColumnFromStrErr;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
#(#columns),*,
_ => Err(#parse_error_iden),
_ => Err(sea_orm::ColumnFromStrErr(format!("Failed to parse '{}' as `{}`", s, stringify!(#ident)))),
}
}
}

View File

@ -16,3 +16,14 @@ impl std::fmt::Display for DbErr {
}
}
}
#[derive(Debug, Clone)]
pub struct ColumnFromStrErr(pub String);
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())
}
}