sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

error[E0277]: the trait bound `Struct: std::convert::From<()>` is not satisfied

Open FrenchGithubUser opened this issue 7 months ago • 3 comments

I have found these related issues/pull requests

none

Description

Here is my rust code:

#[derive(Debug, Deserialize, Serialize, sqlx::Type, ToSchema)]
#[sqlx(type_name = "user_class_enum")]
pub enum UserClass {
    #[sqlx(rename = "newbie")]
    #[serde(rename = "newbie")]
    Newbie,
    #[sqlx(rename = "staff")]
    #[serde(rename = "staff")]
    Staff,
}

#[derive(Debug, Serialize, Deserialize, FromRow, ToSchema)]
pub struct User {
    pub id: i64,
    pub class: UserClass
}

    sqlx::query_as!(
        User,
        r#"
            SELECT * FROM users
            WHERE id = $1
        "#,
        id
    )
    .fetch_one(pool)
    .await
    .map_err(|_| Error::WrongUsernameOrPassword)

Here is the SQL (pgsql db):

CREATE TYPE user_class_enum AS ENUM (
    'newbie',
    'staff'
);

CREATE TABLE users (
    id BIGSERIAL PRIMARY KEY,
    class user_class_enum NOT NULL DEFAULT 'newbie'
);

I am getting this compiler error: error[E0277]: the trait bound UserClass: std::convert::From<()> is not satisfied

Reproduction steps

run the code from above

SQLx version

0.8

Enabled SQLx features

"runtime-async-std", "postgres", "chrono", "ipnetwork",

Database server and version

Postgresql 17.4 (running in docker)

Operating system

Asahi Linux

Rust version

1.86.0

FrenchGithubUser avatar May 19 '25 15:05 FrenchGithubUser

The macro's don't know about your custom enum UserClass, you can override the inferred type with the type override syntax. E.g. SELECT id, class as "class: UserClass" FROM ...

joeydewaal avatar May 19 '25 17:05 joeydewaal

The macro's don't know about your custom enum UserClass, you can override the inferred type with the type override syntax. E.g. SELECT id, class as "class: UserClass" FROM ...

I feel like sqlx should know with the annotation matching the SQL enum. Or what is the annotation for then ?

FrenchGithubUser avatar May 19 '25 17:05 FrenchGithubUser

The #[derive(sqlx::Type)] just implements the Type, Encode and Decode traits for your enum. This makes it possible to decode/encode the enum but the macro's still don't know about it.

joeydewaal avatar May 26 '25 09:05 joeydewaal