1

I'm trying to select on a subset of enum variants, but getting the trait PgHasArrayType is not implemented. Any suggestions?

use sqlx::Row;

#[derive(Debug, sqlx::Type)]
#[sqlx(type_name = "color")]
#[sqlx(rename_all = "lowercase")]
enum Color {
    Red,
    Green,
    Blue,
}

#[tokio::main]
async fn main() -> sqlx::Result<()> {
    dotenv::dotenv().ok();
    let db = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()).await?;
    let mut tnx = db.begin().await?;

    sqlx::query("CREATE TYPE color AS ENUM ('red', 'green', 'blue')")
        .execute(&mut tnx)
        .await?;
    sqlx::query("CREATE TABLE colors (color color)")
        .execute(&mut tnx)
        .await?;
    sqlx::query("INSERT INTO colors VALUES ('red'), ('green')")
        .execute(&mut tnx)
        .await?;

    /// Querying by a single enum works
    assert_eq!(
        sqlx::query("SELECT color FROM colors WHERE color = $1")
            .bind(Color::Red)
            .fetch_one(&mut tnx)
            .await?
            .get::<Color, &str>("color"),
        Color::Red
    );

    /// Error: the trait `PgHasArrayType` is not implemented for `Color`
    sqlx::query("SELECT color FROM colors WHERE color = ANY($1)")
        .bind(&[Color::Blue, Color::Red])
        .fetch_one(&mut tnx)
        .await?
        .get::<Color, &str>("color");

    tnx.rollback().await?;
    Ok(())
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
imbolc
  • 1,620
  • 1
  • 19
  • 32

0 Answers0