如何在 Rust SQLx 中创建自定义 Postgres 枚举类型?

Kan*_*rix 5 postgresql rust rust-sqlx

我正在尝试在 Postgres 中创建自定义枚举类型并已成功完成。我的迁移看起来像这样:

CREATE TYPE role AS ENUM ('admin', 'user');

ALTER TABLE users
ADD role role DEFAULT 'user';
Run Code Online (Sandbox Code Playgroud)

然后我在 Rust 中创建了枚举类型,如下所示:

#[derive(Serialize, Deserialize, Debug, sqlx::Type)]
#[sqlx(type_name = "role", rename_all = "lowercase")] 
pub enum Role {
    ADMIN,
    USER
}
Run Code Online (Sandbox Code Playgroud)

我也改变了用户模型:

#[derive(sqlx::FromRow, Debug)]
pub struct User {
    pub id: i32,
    pub email: String,
    pub username: String,
    pub password: String,
    pub role: Role,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}
Run Code Online (Sandbox Code Playgroud)

但现在当我尝试像这样查询数据库时:

let user = match sqlx::query_as!(
    User,
    "SELECT * FROM users WHERE email = $1 AND password = $2",
    &email,
    &password,
)
Run Code Online (Sandbox Code Playgroud)

我收到此错误:unsupported type role of column #7 ("role")

我究竟做错了什么?

我尝试过使用宏观部分

#[sqlx(type_name = "role", rename_all = "lowercase")],

但这似乎没有帮助。

这是完整的错误cargo check

error: unsupported type role of column #7 ("role")
   --> src/routes/auth/mod.rs:140:20
    |
140 |           let user = match sqlx::query_as!(
    |  __________________________^
141 | |             User,
142 | |             "SELECT * FROM users WHERE email = $1 AND password = $2",
143 | |             &payload.email,
144 | |             &hash,
145 | |         )
    | |_________^
    |
    = note: this error originates in the macro `$crate::sqlx_macros::expand_query` which comes from the expansion of the macro `sqlx::query_as` (in Nightly builds, run with -Z macro-backtrace for more info)

error: could not compile `rust-api-example` (bin "rust-api-example") due to previous error
Run Code Online (Sandbox Code Playgroud)

Kan*_*rix 0

我最终像这样修复:

let user = sqlx::query_as!(
    model::User,
    "SELECT
    id,
    email,
    username,
    password,
    role AS \"role: model::Role\",
    created_at,
    updated_at
    FROM users WHERE id = $1",
    user_id
)
.fetch_one(&pool)
.await
.unwrap();
Run Code Online (Sandbox Code Playgroud)