derive FromRow: added attribute skip for setting default value

This commit is contained in:
Gregor Giesen 2023-01-21 21:24:25 +01:00 committed by Austin Bonander
parent c03926c741
commit 665b859645
2 changed files with 10 additions and 0 deletions

View File

@ -63,6 +63,7 @@ pub struct SqlxChildAttributes {
pub default: bool,
pub flatten: bool,
pub try_from: Option<Type>,
pub skip: bool,
}
pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result<SqlxContainerAttributes> {
@ -155,6 +156,7 @@ pub fn parse_child_attributes(input: &[Attribute]) -> syn::Result<SqlxChildAttri
let mut default = false;
let mut try_from = None;
let mut flatten = false;
let mut skip: bool = false;
for attr in input.iter().filter(|a| a.path.is_ident("sqlx")) {
let meta = attr
@ -177,6 +179,7 @@ pub fn parse_child_attributes(input: &[Attribute]) -> syn::Result<SqlxChildAttri
}) if path.is_ident("try_from") => try_set!(try_from, val.parse()?, value),
Meta::Path(path) if path.is_ident("default") => default = true,
Meta::Path(path) if path.is_ident("flatten") => flatten = true,
Meta::Path(path) if path.is_ident("skip") => skip = true,
u => fail!(u, "unexpected attribute"),
},
u => fail!(u, "unexpected attribute"),
@ -190,6 +193,7 @@ pub fn parse_child_attributes(input: &[Attribute]) -> syn::Result<SqlxChildAttri
default,
flatten,
try_from,
skip,
})
}

View File

@ -72,6 +72,12 @@ fn expand_derive_from_row_struct(
let attributes = parse_child_attributes(&field.attrs).unwrap();
let ty = &field.ty;
if attributes.skip {
return Some(parse_quote!(
let #id: #ty = Default::default();
));
}
let expr: Expr = match (attributes.flatten, attributes.try_from) {
(true, None) => {
predicates.push(parse_quote!(#ty: ::sqlx::FromRow<#lifetime, R>));