I really struggled with sqlx and a custom enum type: I ended up adding strum to generate the &str values to make the query with the enum as parameter work:
#[derive(Debug, sqlx::Type, AsRefStr)]
#[sqlx(type_name = "category_type", rename_all = "lowercase")]
pub enum CategoryType {
#[strum(serialize = "music")]
Music,
#[strum(serialize = "audiobook")]
Audiobook,
}
#[derive(Debug, sqlx::FromRow)]
pub struct Category {
pub id: sqlx::types::Uuid,
pub name: String,
pub category_type: CategoryType,
}
async fn list(db: &PgPool, category_type: CategoryType) -> Result<Vec<Category>, errors::AppError> {
let result = sqlx::query_as!(
Category,
r#"
SELECT
id, name, category_type AS "category_type!: CategoryType"
FROM categories
WHERE category_type = ($1::text)::category_type
"#,
category_type.as_ref()
)
.fetch_all(db)
.await?;
Ok(result)
}
This fells quite complicated, but I think its the right way? what do you think?