SQLX: cannot put vector of enum into db

70 Views Asked by At

I have a table

CREATE TYPE WEEKDAY AS ENUM (
    'sunday',
    'monday',
    'tuesday',
    'wednesday',
    'thursday',
    'friday',
    'saturday'
    );


CREATE TABLE tasks
(
    weekday       WEEKDAY ARRAY
);

Following the documentation and other SO questions, I'd expect the following to work

#[derive(sqlx::Type)]
#[sqlx(type_name = "weekday", rename_all = "lowercase")]
enum Weekday {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
}


    let weekday: Vec<Weekday> = Vec::new();
    sqlx::query!(
        r##"
        INSERT INTO tasks (weekday)
        VALUES ($1);
    "##,
        weekday
    )
    .execute(&mut **db)
    .await
    .expect("db failure");

but I get error error: unsupported type _weekday for param #1. I've tried to put as "weekday: weekday" in various places (as suggested in other threads), but always was responded with syntax error. How can I make it work?

1

There are 1 best solutions below

0
Dekakaruk On

Argh, after some digging I found the ugly answer.

  1. I need to explicitly set type of vector in the binding (weekday as Vec<Weekday>)
  2. I need to manualy implement trait PgHasArrayType - should be derivable by sqlx::Type, but enums are not supported at this moment

so in summary the code is

#[derive(sqlx::Type)]
#[sqlx(type_name = "weekday", rename_all = "lowercase")]
enum Weekday {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
}

impl PgHasArrayType for Weekday {
    fn array_type_info() -> PgTypeInfo {
        PgTypeInfo::with_name("weekday[]")
    }
}

    let weekday: Vec<Weekday> = Vec::new();
    sqlx::query!(
        r##"
        INSERT INTO tasks (weekday)
        VALUES ($1);
    "##,
        weekday as Vec<Weekday>
    )
    .execute(&mut **db)
    .await
    .expect("db failure");