Skip to content

Commit

Permalink
Generate PgHasArrayType impls for enums
Browse files Browse the repository at this point in the history
  • Loading branch information
isobit authored and rex-remind101 committed Sep 29, 2023
1 parent ee2b2fe commit f966158
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 7 deletions.
6 changes: 0 additions & 6 deletions sqlx-macros-core/src/derives/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,12 +236,6 @@ pub fn check_enum_attributes(input: &DeriveInput) -> syn::Result<SqlxContainerAt
input
);

assert_attribute!(
!attributes.no_pg_array,
"unused #[sqlx(no_pg_array)]; derive does not emit `PgHasArrayType` impls for enums",
input
);

Ok(attributes)
}

Expand Down
30 changes: 30 additions & 0 deletions sqlx-macros-core/src/derives/type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,18 @@ fn expand_derive_has_sql_type_strong_enum(
}
}
));

if !attributes.no_pg_array {
let array_ty_name = pg_array_type_name(ident, attributes.type_name.as_ref());
tts.extend(quote!(
#[automatically_derived]
impl ::sqlx::postgres::PgHasArrayType for #ident {
fn array_type_info() -> ::sqlx::postgres::PgTypeInfo {
::sqlx::postgres::PgTypeInfo::with_name(#array_ty_name)
}
}
));
}
}

if cfg!(feature = "sqlite") {
Expand Down Expand Up @@ -235,3 +247,21 @@ fn type_name(ident: &Ident, explicit_name: Option<&TypeName>) -> TokenStream {
quote_spanned!(ident.span()=> #s)
})
}

fn pg_array_type_name(ident: &Ident, explicit_name: Option<&TypeName>) -> TokenStream {
explicit_name
.map(|tn| {
let s = pg_array_type_name_from_type_name(&tn.val);
quote! { #s }
})
.unwrap_or_else(|| {
let s = pg_array_type_name_from_type_name(&ident.to_string());
quote_spanned!(ident.span()=> #s)
})
}

fn pg_array_type_name_from_type_name(name: &str) -> String {
name.split_once('.')
.map(|(schema, name)| format!("{}._{}", schema, name))
.unwrap_or_else(|| format!("_{}", name))
}
2 changes: 1 addition & 1 deletion tests/postgres/describe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ async fn it_describes_enum() -> anyhow::Result<()> {

let ty = d.columns()[0].type_info();

assert_eq!(ty.name(), "status");
assert_eq!(ty.name(), "public.status");

assert_eq!(
format!("{:?}", ty.kind()),
Expand Down

0 comments on commit f966158

Please sign in to comment.