我有一个 users
表,我正在尝试使用 Diesel 添加 role
字段:
#[derive(Debug, Clone, Queryable, Insertable)]
pub struct User {
// other fields
pub role: Role,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, AsExpression)]
#[sql_type = "diesel::sql_types::VarChar"]
pub enum Role {
User,
Admin,
}
/// manual impls for FromSql<VarChar, Pg>, ToSql<VarChar, Pg> and FromSqlRow<VarChar, Pg>
出于兼容性原因,我希望这些在数据库中表示为 varchar("user"
和 "admin"
),但希望使用Rust 方面的枚举可提供额外的类型安全性。
但是,根据我目前的设置,我得到:
error[E0277]: the trait bound `Role: Queryable<Text, Pg>` is not satisfied
--> src/state/database/users.rs:47:32
|
47 | self.exec(|conn| users.load(conn)).await
| ^^^^ the trait `Queryable<Text, Pg>` is not implemented for `Role`
|
= note: required because of the requirements on the impl of `Queryable<(diesel::sql_types::Uuid, Text, Text, diesel::sql_types::Timestamp, Text), Pg>` for `(model::types::UserId, model::types::Email, model::types::PasswordHash, NaiveDateTime, Role)`
= note: 1 redundant requirement hidden
= note: required because of the requirements on the impl of `Queryable<(diesel::sql_types::Uuid, Text, Text, diesel::sql_types::Timestamp, Text), Pg>` for `user::User`
= note: required because of the requirements on the impl of `LoadQuery<PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>, user::User>` for `schema::users::table`
据我了解,在柴油中,VarChar
和 Text
是相同的类型(即别名)。如果我将 impl 中的所有 VarChar
更改为 Text
,错误仍然存在。
我确信这不是其他字段/字段顺序,因为如果我将 Role
替换为普通的 String
,它就可以工作。
我觉得我一定错过了一些东西,这似乎是相当常见的行为。也许我还需要实现另一个特征?
FWIW,我的用户表架构如下所示:
table! {
users (id) {
id -> Uuid,
email -> Varchar,
password_hash -> Varchar,
created_at -> Timestamp,
role -> Varchar,
}
}
使用 postgres 14、rust 1.57、diesel 1.4.8
最佳答案
您需要导出FromSqlRow
以及。它将为您的类型生成必要的 FromSqlRow
和 Queryable
impl。
关于postgresql - 如何将类似 C 的枚举与柴油一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70589365/