Don't include Identifiable in db_type if no id field

This commit is contained in:
2025-10-18 19:49:42 -04:00
parent 5e051ca706
commit af30c4b5c9

View File

@@ -30,6 +30,11 @@ pub fn db_type(attr: TokenStream, item: TokenStream) -> TokenStream {
.into(); .into();
}; };
let has_id_field = fields.named.iter().any(|field|
field.ident.as_ref()
.map_or(false, |field| field == "id")
);
// Filter out fields with the `#[omit_new]` attribute // Filter out fields with the `#[omit_new]` attribute
let new_fields = fields.named.iter().filter(|field| { let new_fields = fields.named.iter().filter(|field| {
!field !field
@@ -89,12 +94,23 @@ pub fn db_type(attr: TokenStream, item: TokenStream) -> TokenStream {
// Get the table path from the attribute // Get the table path from the attribute
let table_path = parse_macro_input!(attr as Path); let table_path = parse_macro_input!(attr as Path);
// Generate the expanded code // Don't include the Identifiable derive for structs without an `id` field
let expanded = quote! { let full_type_derives = if has_id_field {
#[cfg_attr(feature = "ssr", derive( quote! {
diesel::prelude::Queryable, diesel::prelude::Queryable,
diesel::prelude::Selectable, diesel::prelude::Selectable,
diesel::prelude::Identifiable))] diesel::prelude::Identifiable
}
} else {
quote! {
diesel::prelude::Queryable,
diesel::prelude::Selectable
}
};
// Generate the expanded code
let expanded = quote! {
#[cfg_attr(feature = "ssr", derive(#full_type_derives))]
#[cfg_attr(feature = "ssr", diesel(check_for_backend(diesel::pg::Pg)))] #[cfg_attr(feature = "ssr", diesel(check_for_backend(diesel::pg::Pg)))]
#[cfg_attr(feature = "ssr", diesel(table_name = #table_path))] #[cfg_attr(feature = "ssr", diesel(table_name = #table_path))]
#clean_derive_input #clean_derive_input