Sqlx + postgres - how to insert a enum value

Can't figure out how to use enums, here's the code:

CREATE TYPE enm AS ENUM ('foo', 'bar');
CREATE TABLE tbl (e enm);
use sqlx::postgres::PgPool;

#[sqlx(rename = "enm", rename_all = "lowercase")]
enum Enm {

async fn main() {
    let db = PgPool::connect("postgres:///sqlx_enum").await.unwrap();
    // error: unsupported type enm for param #1
    sqlx::query!("INSERT INTO tbl VALUES ($1)", Enm::Foo)

Try sqlx::query!("INSERT INTO tbl VALUES ($1)", Enm::Foo as Enm).

For queries returning rows you'd do:

struct Row {
    e: Enm,

    r#"INSERT INTO tbl VALUES ($1) RETURNING e AS "e!: Enm""#,
    Enm::Foo as Enm

This is documented here: sqlx::query - Rust

Although I think the documentation could benefit from an explicit insertion example.

Thank you :slight_smile: Would you say a few words why these type overrides are needed? To my newbie eye they seem completely redundant.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.