Skip to content

Commit

Permalink
More flexible Selectable derive
Browse files Browse the repository at this point in the history
Resolves diesel-rs#2950

Previously, if fields had `embed`, the `Selectable` derive supposed that
they implemented `Selectable<DB>` for every `DB: Backend`.

If that wasn't the case (generic subfield or backend-specific impl) the
derive would fail.

This commit fixes this issue by introducing the appropriate additional
`where` bounds.
  • Loading branch information
Ten0 committed Nov 21, 2021
1 parent 9cb852b commit 24c7a83
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
9 changes: 9 additions & 0 deletions diesel_derives/src/selectable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,19 @@ pub fn derive(item: syn::DeriveInput) -> Result<proc_macro2::TokenStream, Diagno
let model = Model::from_item(&item)?;

let (_, ty_generics, _) = item.generics.split_for_impl();

let mut generics = item.generics.clone();
generics
.params
.push(parse_quote!(__DB: diesel::backend::Backend));
for embed_field in model.fields().iter().filter(|f| f.has_flag("embed")) {
let embed_ty = &embed_field.ty;
generics
.where_clause
.get_or_insert_with(|| parse_quote!(where))
.predicates
.push(parse_quote!(#embed_ty: Selectable<__DB>));
}
let (impl_generics, _, where_clause) = generics.split_for_impl();

let struct_name = &item.ident;
Expand Down
8 changes: 5 additions & 3 deletions diesel_derives/tests/selectable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,22 @@ fn tuple_struct() {
fn embedded_struct() {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Queryable, Selectable)]
#[table_name = "my_structs"]
struct A {
struct A<B> {
foo: i32,
#[diesel(embed)]
b: B,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Queryable, Selectable)]
#[table_name = "my_structs"]
struct B {
struct C {
bar: i32,
}

let conn = &mut connection();
let data = my_structs::table.select(A::as_select()).get_result(conn);
let data = my_structs::table
.select(A::<C>::as_select())
.get_result(conn);
assert!(data.is_err());
}

Expand Down

0 comments on commit 24c7a83

Please sign in to comment.