Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add #[sea_orm(skip)] for FromQueryResult macro #1954

Merged
merged 4 commits into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 58 additions & 16 deletions sea-orm-macros/src/derives/from_query_result.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,29 @@
use self::util::GetMeta;
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, quote_spanned};
use syn::{ext::IdentExt, Data, DataStruct, Field, Fields, Generics};
use quote::{format_ident, quote, quote_spanned, ToTokens};
use syn::{
ext::IdentExt, punctuated::Punctuated, token::Comma, Data, DataStruct, Fields, Generics, Meta,
};

pub struct FromQueryResultItem {
pub skip: bool,
pub ident: Ident,
}
impl ToTokens for FromQueryResultItem {
fn to_tokens(&self, tokens: &mut TokenStream) {
let Self { ident, skip } = self;
if *skip {
tokens.extend(quote! {
#ident: std::default::Default::default(),
});
} else {
let name = ident.unraw().to_string();
tokens.extend(quote! {
#ident: row.try_get(pre, #name)?,
});
}
}
}

/// Method to derive a [QueryResult](sea_orm::QueryResult)
pub fn expand_derive_from_query_result(
Expand All @@ -19,30 +42,49 @@ pub fn expand_derive_from_query_result(
})
}
};
let mut field = Vec::with_capacity(fields.len());

let field: Vec<Ident> = fields
.into_iter()
.map(|Field { ident, .. }| format_ident!("{}", ident.unwrap().to_string()))
.collect();

let name: Vec<TokenStream> = field
.iter()
.map(|f| {
let s = f.unraw().to_string();
quote! { #s }
})
.collect();

for parsed_field in fields.into_iter() {
let mut skip = false;
for attr in parsed_field.attrs.iter() {
if !attr.path().is_ident("sea_orm") {
continue;
}
if let Ok(list) = attr.parse_args_with(Punctuated::<Meta, Comma>::parse_terminated) {
for meta in list.iter() {
skip = meta.exists("skip");
}
}
}
let ident = format_ident!("{}", parsed_field.ident.unwrap().to_string());
field.push(FromQueryResultItem { skip, ident });
}
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

Ok(quote!(
#[automatically_derived]
impl #impl_generics sea_orm::FromQueryResult for #ident #ty_generics #where_clause {
fn from_query_result(row: &sea_orm::QueryResult, pre: &str) -> std::result::Result<Self, sea_orm::DbErr> {
Ok(Self {
#(#field: row.try_get(pre, #name)?),*
#(#field)*
})
}
}
))
}
mod util {
use syn::Meta;

pub(super) trait GetMeta {
fn exists(&self, k: &str) -> bool;
}

impl GetMeta for Meta {
fn exists(&self, k: &str) -> bool {
let Meta::Path(path) = self else {
return false;
};
path.is_ident(k)
}
}
}
7 changes: 6 additions & 1 deletion sea-orm-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,9 @@ pub fn derive_active_enum(input: TokenStream) -> TokenStream {

/// Convert a query result into the corresponding Model.
///
/// ### Attributes
/// - `skip`: Will not try to pull this field from the query result. And set it to the default value of the type.
///
/// ### Usage
///
/// ```
Expand All @@ -588,10 +591,12 @@ pub fn derive_active_enum(input: TokenStream) -> TokenStream {
/// struct SelectResult {
/// name: String,
/// num_of_fruits: i32,
/// #[sea_orm(skip)]
/// skip_me: i32,
/// }
/// ```
#[cfg(feature = "derive")]
#[proc_macro_derive(FromQueryResult)]
#[proc_macro_derive(FromQueryResult, attributes(sea_orm))]
pub fn derive_from_query_result(input: TokenStream) -> TokenStream {
let DeriveInput {
ident,
Expand Down
7 changes: 7 additions & 0 deletions tests/derive_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,10 @@ where
{
_foo: T::Item,
}

#[derive(FromQueryResult)]
struct FromQueryAttributeTests {
#[sea_orm(skip)]
_foo: i32,
_bar: String,
}
Loading