fix(postgres): derive PgHasArrayType for enums

This commit is contained in:
Austin Bonander 2024-05-31 13:33:43 -07:00
parent 10192019d8
commit 80359d1ada
2 changed files with 36 additions and 5 deletions

View File

@ -130,7 +130,7 @@ fn expand_derive_has_sql_type_weak_enum(
let attr = check_weak_enum_attributes(input, variants)?;
let repr = attr.repr.unwrap();
let ident = &input.ident;
let ts = quote!(
let mut ts = quote!(
#[automatically_derived]
impl<DB: ::sqlx::Database> ::sqlx::Type<DB> for #ident
where
@ -146,6 +146,16 @@ fn expand_derive_has_sql_type_weak_enum(
}
);
if cfg!(feature = "postgres") && !attributes.no_pg_array {
ts.extend(quote!(
impl ::sqlx::postgres::PgHasArrayType for #ident {
fn array_type_info() -> ::sqlx::postgres::PgTypeInfo {
<#ty as ::sqlx::postgres::PgHasArrayType>::array_type_info()
}
}
));
}
Ok(ts)
}
@ -184,6 +194,16 @@ fn expand_derive_has_sql_type_strong_enum(
}
}
));
if !attributes.no_pg_array {
tts.extend(quote!(
impl ::sqlx::postgres::PgHasArrayType for #ident {
fn array_type_info() -> ::sqlx::postgres::PgTypeInfo {
<#ty as ::sqlx::postgres::PgHasArrayType>::array_type_info()
}
}
));
}
}
if cfg!(feature = "sqlite") {

View File

@ -154,13 +154,15 @@ test_type!(transparent_array<TransparentArray>(Postgres,
test_type!(weak_enum<Weak>(Postgres,
"0::int4" == Weak::One,
"2::int4" == Weak::Two,
"4::int4" == Weak::Three
"4::int4" == Weak::Three,
"'{0, 2, 4}'::int4[]" == vec![Weak::One, Weak::Two, Weak::Three],
));
test_type!(strong_enum<Strong>(Postgres,
"'one'::text" == Strong::One,
"'two'::text" == Strong::Two,
"'four'::text" == Strong::Three
"'four'::text" == Strong::Three,
"'{'one', 'two', 'four'}'::text[]" == vec![Strong::One, Strong::Two, Strong::Three],
));
test_type!(floatrange<FloatRange>(Postgres,
@ -739,7 +741,8 @@ async fn test_enum_with_schema() -> anyhow::Result<()> {
let foo: Foo = sqlx::query_scalar("SELECT $1::foo.\"Foo\"")
.bind(Foo::Bar)
.fetch_one(&mut conn).await?;
.fetch_one(&mut conn)
.await?;
assert_eq!(foo, Foo::Bar);
@ -749,4 +752,12 @@ async fn test_enum_with_schema() -> anyhow::Result<()> {
.await?;
assert_eq!(foo, Foo::Baz);
}
let foos: Vec<Foo> = sqlx::query_scalar!("SELECT ARRAY($1::foo.\"Foo\", $2::foo.\"Foo\")")
.bind(Foo::Bar)
.bind(Foo::Baz)
.fetch_one(&mut conn)
.await?;
assert_eq!(foos, [Foo::Bar, Foo::Baz]);
}