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

Allow ignoring attributes for deriving FromRow #2366

Merged
merged 5 commits into from
Mar 14, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
38 changes: 38 additions & 0 deletions sqlx-core/src/from_row.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,44 @@ use crate::row::Row;
///
/// This field is compatible with the `default` attribute.
///
/// #### `skip`
///
/// This is a variant of the `default` attribute which instead always takes the value from
/// the `Default` implementation for this field type ignoring any results in your query.
/// This can be useful, if some field does not satifisfy the trait bounds (i.e.
/// `sqlx::decode::Decode`, `sqlx::type::Type`), in particular in case of nested structures.
/// For example:
///
/// ```rust,ignore
/// #[derive(sqlx::FromRow)]
/// struct Address {
/// user_name: String,
/// street: String,
/// city: String,
/// }
///
/// #[derive(sqlx::FromRow)]
/// struct User {
/// name: String,
/// #[sqlx(skip)]
/// addresses: Vec<Address>,
/// }
/// ```
///
/// Given 2 querys
///
/// ```sql
/// SELECT name FROM users;
/// ```
///
/// and
///
/// ```sql
/// SELECT user_name, street, city addresses;
/// ```
///
/// the addresses can be assigned to the empty `addresses` field of each `User`.
///
/// ## Manual implementation
///
/// You can also implement the [`FromRow`] trait by hand. This can be useful if you
Expand Down
4 changes: 4 additions & 0 deletions sqlx-macros-core/src/derives/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand Down Expand Up @@ -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
Expand All @@ -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"),
Expand All @@ -190,6 +193,7 @@ pub fn parse_child_attributes(input: &[Attribute]) -> syn::Result<SqlxChildAttri
default,
flatten,
try_from,
skip,
})
}

Expand Down
6 changes: 6 additions & 0 deletions sqlx-macros-core/src/derives/row.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>));
Expand Down
28 changes: 28 additions & 0 deletions tests/postgres/derives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -614,3 +614,31 @@ async fn test_flatten() -> anyhow::Result<()> {

Ok(())
}

#[cfg(feature = "macros")]
#[sqlx_macros::test]
async fn test_skip() -> anyhow::Result<()> {
#[derive(Debug, Default, sqlx::FromRow)]
struct AccountDefault {
default: Option<i32>,
}

#[derive(Debug, sqlx::FromRow)]
struct AccountKeyword {
id: i32,
#[sqlx(skip)]
default: AccountDefault,
}

let mut conn = new::<Postgres>().await?;

let account: AccountKeyword = sqlx::query_as(r#"SELECT * from (VALUES (1)) accounts("id")"#)
.fetch_one(&mut conn)
.await?;
println!("{:?}", account);

assert_eq!(1, account.id);
assert_eq!(None, account.default.default);

Ok(())
}