Skip to content

Commit

Permalink
Derive PgHasArrayType for transparent sqlx types (#1748)
Browse files Browse the repository at this point in the history
Fixes #1744.
  • Loading branch information
carols10cents authored Mar 23, 2022
1 parent 1af26d8 commit f539215
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
17 changes: 16 additions & 1 deletion sqlx-macros/src/derives/type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,23 @@ fn expand_derive_has_sql_type_transparent(

if attr.transparent {
let mut generics = generics.clone();
let mut array_generics = generics.clone();

generics
.params
.insert(0, parse_quote!(DB: ::sqlx::Database));
generics
.make_where_clause()
.predicates
.push(parse_quote!(#ty: ::sqlx::Type<DB>));

let (impl_generics, _, where_clause) = generics.split_for_impl();

array_generics
.make_where_clause()
.predicates
.push(parse_quote!(#ty: ::sqlx::postgres::PgHasArrayType));
let (array_impl_generics, _, array_where_clause) = array_generics.split_for_impl();

return Ok(quote!(
#[automatically_derived]
impl #impl_generics ::sqlx::Type< DB > for #ident #ty_generics #where_clause {
Expand All @@ -81,6 +88,14 @@ fn expand_derive_has_sql_type_transparent(
<#ty as ::sqlx::Type<DB>>::compatible(ty)
}
}
#[automatically_derived]
#[cfg(feature = "postgres")]
impl #array_impl_generics ::sqlx::postgres::PgHasArrayType for #ident #ty_generics
#array_where_clause {
fn array_type_info() -> ::sqlx::postgres::PgTypeInfo {
<#ty as ::sqlx::postgres::PgHasArrayType>::array_type_info()
}
}
));
}

Expand Down
14 changes: 14 additions & 0 deletions tests/postgres/derives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,20 @@ use std::ops::Bound;
#[sqlx(transparent)]
struct Transparent(i32);

#[sqlx_macros::test]
async fn test_transparent_slice_to_array() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;

let values = vec![Transparent(1), Transparent(2), Transparent(3)];

sqlx::query("SELECT 2 = ANY($1);")
.bind(&values)
.fetch_one(&mut conn)
.await?;

Ok(())
}

// "Weak" enums map to an integer type indicated by #[repr]
#[derive(PartialEq, Copy, Clone, Debug, sqlx::Type)]
#[repr(i32)]
Expand Down

0 comments on commit f539215

Please sign in to comment.