Skip to content

Allow single-field named structs to be transparent #3971

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
22 changes: 14 additions & 8 deletions sqlx-macros-core/src/derives/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,17 @@ use quote::quote;
use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::{
parse_quote, Arm, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, FieldsNamed,
FieldsUnnamed, Stmt, TypeParamBound, Variant,
parse_quote, Arm, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, FieldsNamed, Stmt,
TypeParamBound, Variant,
};

pub fn expand_derive_decode(input: &DeriveInput) -> syn::Result<TokenStream> {
let attrs = parse_container_attributes(&input.attrs)?;
match &input.data {
Data::Struct(DataStruct {
fields: Fields::Unnamed(FieldsUnnamed { unnamed, .. }),
..
}) if unnamed.len() == 1 => {
expand_derive_decode_transparent(input, unnamed.first().unwrap())
Data::Struct(DataStruct { fields, .. })
if fields.len() == 1 && (matches!(fields, Fields::Unnamed(_)) || attrs.transparent) =>
Copy link
Collaborator

@abonander abonander Aug 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should change the following assert to mention that #[sqlx(transparent)] is only allowed on tuple structs or structs with a single named field:

assert_attribute!(
!attributes.transparent,
"unexpected #[sqlx(transparent)]",
input
);

Otherwise if the user adds one field, they'll just get a confusing unexpected #[sqlx(transparent)] error.

{
expand_derive_decode_transparent(input, fields.iter().next().unwrap())
}
Data::Enum(DataEnum { variants, .. }) => match attrs.repr {
Some(_) => expand_derive_decode_weak_enum(input, variants),
Expand Down Expand Up @@ -72,6 +71,12 @@ fn expand_derive_decode_transparent(
.push(parse_quote!(#ty: ::sqlx::decode::Decode<'r, DB>));
let (impl_generics, _, where_clause) = generics.split_for_impl();

let field_ident = if let Some(ident) = &field.ident {
quote! { #ident }
} else {
quote! { 0 }
};

let tts = quote!(
#[automatically_derived]
impl #impl_generics ::sqlx::decode::Decode<'r, DB> for #ident #ty_generics #where_clause {
Expand All @@ -83,7 +88,8 @@ fn expand_derive_decode_transparent(
dyn ::std::error::Error + 'static + ::std::marker::Send + ::std::marker::Sync,
>,
> {
<#ty as ::sqlx::decode::Decode<'r, DB>>::decode(value).map(Self)
<#ty as ::sqlx::decode::Decode<'r, DB>>::decode(value)
.map(|val| Self { #field_ident: val })
}
}
);
Expand Down
23 changes: 14 additions & 9 deletions sqlx-macros-core/src/derives/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,17 @@ use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::{
parse_quote, Data, DataEnum, DataStruct, DeriveInput, Expr, Field, Fields, FieldsNamed,
FieldsUnnamed, Lifetime, LifetimeParam, Stmt, TypeParamBound, Variant,
Lifetime, LifetimeParam, Stmt, TypeParamBound, Variant,
};

pub fn expand_derive_encode(input: &DeriveInput) -> syn::Result<TokenStream> {
let args = parse_container_attributes(&input.attrs)?;

match &input.data {
Data::Struct(DataStruct {
fields: Fields::Unnamed(FieldsUnnamed { unnamed, .. }),
..
}) if unnamed.len() == 1 => {
expand_derive_encode_transparent(input, unnamed.first().unwrap())
Data::Struct(DataStruct { fields, .. })
if fields.len() == 1 && (matches!(fields, Fields::Unnamed(_)) || args.transparent) =>
{
expand_derive_encode_transparent(input, fields.iter().next().unwrap())
}
Data::Enum(DataEnum { variants, .. }) => match args.repr {
Some(_) => expand_derive_encode_weak_enum(input, variants),
Expand Down Expand Up @@ -77,6 +76,12 @@ fn expand_derive_encode_transparent(
.push(parse_quote!(#ty: ::sqlx::encode::Encode<#lifetime, DB>));
let (impl_generics, _, where_clause) = generics.split_for_impl();

let field_ident = if let Some(ident) = &field.ident {
quote! { #ident }
} else {
quote! { 0 }
};

Ok(quote!(
#[automatically_derived]
impl #impl_generics ::sqlx::encode::Encode<#lifetime, DB> for #ident #ty_generics
Expand All @@ -86,15 +91,15 @@ fn expand_derive_encode_transparent(
&self,
buf: &mut <DB as ::sqlx::database::Database>::ArgumentBuffer<#lifetime>,
) -> ::std::result::Result<::sqlx::encode::IsNull, ::sqlx::error::BoxDynError> {
<#ty as ::sqlx::encode::Encode<#lifetime, DB>>::encode_by_ref(&self.0, buf)
<#ty as ::sqlx::encode::Encode<#lifetime, DB>>::encode_by_ref(&self.#field_ident, buf)
}

fn produces(&self) -> Option<DB::TypeInfo> {
<#ty as ::sqlx::encode::Encode<#lifetime, DB>>::produces(&self.0)
<#ty as ::sqlx::encode::Encode<#lifetime, DB>>::produces(&self.#field_ident)
}

fn size_hint(&self) -> usize {
<#ty as ::sqlx::encode::Encode<#lifetime, DB>>::size_hint(&self.0)
<#ty as ::sqlx::encode::Encode<#lifetime, DB>>::size_hint(&self.#field_ident)
}
}
))
Expand Down
26 changes: 12 additions & 14 deletions sqlx-macros-core/src/derives/type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,32 @@ use quote::{quote, quote_spanned};
use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::{
parse_quote, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, FieldsNamed,
FieldsUnnamed, Variant,
parse_quote, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, FieldsNamed, Variant,
};

pub fn expand_derive_type(input: &DeriveInput) -> syn::Result<TokenStream> {
let attrs = parse_container_attributes(&input.attrs)?;
match &input.data {
// Newtype structs:
// struct Foo(i32);
Data::Struct(DataStruct {
fields: Fields::Unnamed(FieldsUnnamed { unnamed, .. }),
..
}) => {
if unnamed.len() == 1 {
expand_derive_has_sql_type_transparent(input, unnamed.first().unwrap())
} else {
Err(syn::Error::new_spanned(
input,
"structs with zero or more than one unnamed field are not supported",
))
}
Data::Struct(DataStruct { fields, .. })
if fields.len() == 1 && (matches!(fields, Fields::Unnamed(_)) || attrs.transparent) =>
{
expand_derive_has_sql_type_transparent(input, fields.iter().next().unwrap())
}
// Record types
// struct Foo { foo: i32, bar: String }
Data::Struct(DataStruct {
fields: Fields::Named(FieldsNamed { named, .. }),
..
}) => expand_derive_has_sql_type_struct(input, named),
Data::Struct(DataStruct {
fields: Fields::Unnamed(..),
..
}) => Err(syn::Error::new_spanned(
input,
"structs with zero or more than one unnamed field are not supported",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In hindsight, this wording is really clunky.

How about: tuple structs may only have a single field

)),
Data::Struct(DataStruct {
fields: Fields::Unit,
..
Expand Down
Loading