postgresql - 如何将类似 C 的枚举与柴油一起使用

标签 postgresql rust enums rust-diesel

我有一个 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`

据我了解,在柴油中,VarCharText 是相同的类型(即别名)。如果我将 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以及。它将为您的类型生成必要的 FromSqlRowQueryable impl。

关于postgresql - 如何将类似 C 的枚举与柴油一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70589365/

相关文章:

PostgreSQL 检查约束

sql - Postgres : get average for all values of a column for each distinct from another column

vector - "std::vec"与 "collections::vec"

c# - 获取只有字符串的嵌套枚举类型?

sql - PostgreSQL:给定特定时间间隔的一周中每一天的记录计数

postgresql - Npgsql 在 PostgreSQL 数据库中插入地球数据

arrays - 具有包含引用的可能变体的枚举数组

collections - 从 Vec<Vec<char>> 创建一个 Vec<BTreeSet<char>>

c - 枚举数中 'four' 的值是多少?

c++ - 在声明后定义一个枚举变量