From 2e08e55e0ba9130649255593bb0eea63acd1a14d Mon Sep 17 00:00:00 2001 From: OriolMunoz <20519866+OriolMunoz@users.noreply.github.com> Date: Tue, 7 Jul 2020 21:51:30 +0200 Subject: [PATCH] Support for #[sqlx(default)] --- sqlx-macros/src/derives/attributes.rs | 6 ++++-- sqlx-macros/src/derives/row.rs | 17 ++++++++++++++--- tests/postgres/derives.rs | 23 +++++++++++++++++++++++ 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/sqlx-macros/src/derives/attributes.rs b/sqlx-macros/src/derives/attributes.rs index e349f2e914..c07e006c38 100644 --- a/sqlx-macros/src/derives/attributes.rs +++ b/sqlx-macros/src/derives/attributes.rs @@ -42,6 +42,7 @@ pub struct SqlxContainerAttributes { pub struct SqlxChildAttributes { pub rename: Option, + pub default: bool, } pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result { @@ -116,6 +117,7 @@ pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result syn::Result { let mut rename = None; + let mut default = false; for attr in input { let meta = attr @@ -132,7 +134,7 @@ pub fn parse_child_attributes(input: &[Attribute]) -> syn::Result try_set!(rename, val.value(), value), - + Meta::Path(path) if path.is_ident("default") => default = true, u => fail!(u, "unexpected attribute"), }, u => fail!(u, "unexpected attribute"), @@ -143,7 +145,7 @@ pub fn parse_child_attributes(input: &[Attribute]) -> syn::Result { + Ok(Default::default()) + }, + e => Err(e) + })?;), + ) + } else { + Some(parse_quote!( + let #id: #ty = row.try_get(#id_s)?; + )) + } }); let names = fields.iter().map(|field| &field.ident); diff --git a/tests/postgres/derives.rs b/tests/postgres/derives.rs index 14dacdd966..9fbbf28681 100644 --- a/tests/postgres/derives.rs +++ b/tests/postgres/derives.rs @@ -381,3 +381,26 @@ async fn test_from_row_with_rename() -> anyhow::Result<()> { Ok(()) } + +#[cfg(feature = "macros")] +#[sqlx_macros::test] +async fn test_default() -> anyhow::Result<()> { + #[derive(Debug, sqlx::FromRow)] + struct HasDefault { + not_default: i32, + #[sqlx(default)] + default: Option, + } + + let mut conn = new::().await?; + + let has_default: HasDefault = sqlx::query_as(r#"SELECT 1 AS not_default"#) + .fetch_one(&mut conn) + .await?; + println!("{:?}", has_default); + + assert_eq!(has_default.not_default, 1); + assert_eq!(has_default.default, None); + + Ok(()) +}