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

derive FromRow: sqlx(default) for all fields #2801

Merged
merged 6 commits into from
Oct 17, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
16 changes: 8 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions sqlx-core/src/from_row.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,21 @@ use crate::{error::Error, row::Row};
/// will set the value of the field `location` to the default value of `Option<String>`,
/// which is `None`.
///
/// Moreover, if the struct has an implementation for [`Default`], you can use the `default``
/// attribute at the struct level rather than for each single field. This way the default
/// value of each attribute is optained from the particular `Default` implementation.
grgi marked this conversation as resolved.
Show resolved Hide resolved
/// For example:
///
/// ```rust, ignore
/// #[derive(Default, sqlx::FromRow)]
/// #[sqlx(default)]
/// struct Options {
/// option_a: Option<i32>,
/// option_b: Option<String>,
/// option_c: Option<bool>,
/// }
/// ```
///
grgi marked this conversation as resolved.
Show resolved Hide resolved
/// ### `flatten`
///
/// If you want to handle a field that implements [`FromRow`],
Expand Down
7 changes: 7 additions & 0 deletions sqlx-macros-core/src/derives/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ pub struct SqlxContainerAttributes {
pub rename_all: Option<RenameAll>,
pub repr: Option<Ident>,
pub no_pg_array: bool,
pub default: bool,
}

pub struct SqlxChildAttributes {
Expand All @@ -74,6 +75,7 @@ pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result<SqlxContai
let mut type_name = None;
let mut rename_all = None;
let mut no_pg_array = None;
let mut default = None;

for attr in input
.iter()
Expand Down Expand Up @@ -129,6 +131,10 @@ pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result<SqlxContai
)
}

Meta::Path(p) if p.is_ident("default") => {
try_set!(default, true, value)
}

u => fail!(u, "unexpected attribute"),
},
u => fail!(u, "unexpected attribute"),
Expand Down Expand Up @@ -156,6 +162,7 @@ pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result<SqlxContai
type_name,
rename_all,
no_pg_array: no_pg_array.unwrap_or(false),
default: default.unwrap_or(false),
})
}

Expand Down
20 changes: 20 additions & 0 deletions sqlx-macros-core/src/derives/row.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,17 @@ fn expand_derive_from_row_struct(

let container_attributes = parse_container_attributes(&input.attrs)?;

let default_instance: Option<Stmt>;

if container_attributes.default {
predicates.push(parse_quote!(#ident: ::std::default::Default));
default_instance = Some(parse_quote!(
let __default = #ident::default();
));
} else {
default_instance = None;
}

let reads: Vec<Stmt> = fields
.iter()
.filter_map(|field| -> Option<Stmt> {
Expand Down Expand Up @@ -148,6 +159,13 @@ fn expand_derive_from_row_struct(
},
e => ::std::result::Result::Err(e)
})?;))
} else if container_attributes.default {
Some(parse_quote!(let #id: #ty = #expr.or_else(|e| match e {
::sqlx::Error::ColumnNotFound(_) => {
::std::result::Result::Ok(__default.#id)
},
e => ::std::result::Result::Err(e)
})?;))
} else {
Some(parse_quote!(
let #id: #ty = #expr?;
Expand All @@ -164,6 +182,8 @@ fn expand_derive_from_row_struct(
#[automatically_derived]
impl #impl_generics ::sqlx::FromRow<#lifetime, R> for #ident #ty_generics #where_clause {
fn from_row(row: &#lifetime R) -> ::sqlx::Result<Self> {
#default_instance

#(#reads)*

::std::result::Result::Ok(#ident {
Expand Down
35 changes: 35 additions & 0 deletions tests/postgres/derives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,41 @@ async fn test_default() -> anyhow::Result<()> {
Ok(())
}

#[cfg(feature = "macros")]
#[sqlx_macros::test]
async fn test_struct_default() -> anyhow::Result<()> {
#[derive(Debug, sqlx::FromRow)]
#[sqlx(default)]
struct HasDefault {
not_default: Option<i32>,
default_a: Option<String>,
default_b: Option<i32>,
}

impl Default for HasDefault {
fn default() -> HasDefault {
HasDefault {
not_default: None,
default_a: None,
default_b: Some(0),
}
}
}

let mut conn = new::<Postgres>().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, Some(1));
assert_eq!(has_default.default_a, None);
assert_eq!(has_default.default_b, Some(0));

Ok(())
}

#[cfg(feature = "macros")]
#[sqlx_macros::test]
async fn test_flatten() -> anyhow::Result<()> {
Expand Down
Loading