【问题标题】:Cannot use UUID as a primary key: Uuid: diesel::Expression is not satisfied [duplicate]不能将 UUID 用作主键:Uuid:diesel::Expression 不满足 [重复]
【发布时间】:2020-06-11 23:02:48
【问题描述】:

我想将 UUID 字段作为 Postgres 表中的主字段,但出现以下错误:

error[E0277]: the trait bound `uuid::Uuid: diesel::Expression` is not satisfied
 --> database/src/models.rs:3:35
  |
3 | #[derive(Debug, Clone, Queryable, Insertable)]
  |                                   ^^^^^^^^^^ the trait `diesel::Expression` is not implemented for `uuid::Uuid`
  |
  = note: required because of the requirements on the impl of `diesel::expression::AsExpression<diesel::sql_types::Uuid>` for `uuid::Uuid`

有一些关于柴油 UUID 的较早问题,但没有一个是可插入的,我特别收到了错误。我正在使用带有 actix web 的柴油。

这是我的模型:

use crate::schema::users;

#[derive(Debug, Clone, Queryable, Insertable)]
#[table_name="users"]
pub struct User {
    pub id: uuid::Uuid,
    pub phone: String,
    pub name: String,
    pub password: String,
}

还有我的表架构

table! {
    users (id) {
        id -> Uuid,
        name -> Text,
        phone -> Text,
        password -> Text,
    }
}

我发现一些旧帖子表明该字段可能可以为空,但 id 是我的表 up.sql 中的 PRIMARY KEY,因此它不能为空。

表格是从diesel-cli生成的,那里似乎没有问题。

这是我的 Cargo.toml

diesel = { version = "1.0.0", features = ["postgres", "r2d2", "uuid"] }
uuid = { version = "0.8", features = ["v4"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

【问题讨论】:

  • 您能否补充一些有关您使用的dieseluuid 版本的更多信息?还为diesel 启用了哪些功能标志?这很可能是缺少功能标志或内部使用的uuid 版本diesel 与您的uuid 版本之间的版本不匹配。
  • Diesel 目前最新发布的版本不支持uuid 0.8 版,仅支持0.7 及以下版本。此外,您需要使用 uuidv07 功能来支持 0.7 版。这将随着下一个柴油版本而改变。

标签: postgresql rust rust-diesel actix-web


【解决方案1】:

查看Cargo.lock 文件中的内容并查看是否指向包依赖项总是很好。

[[package]]
name = "diesel"
version = "1.4.4"
...
 "uuid 0.6.5", <-- It was older version even I've installed newest version of uuid
]

只要将功能更改为uuidv07 并运行cargo update,Cargo.lock 文件也会更改。如果您想检查柴油应用了哪个Uuid。可以通过查看diesel::sql_types::Uuid 的来源来检查它,以确保它们使用与uuid::Uuid 相同的版本。

P.S:@weiznich 在问题帖子中评论了答案,只是添加了一些详细信息,并作为答案帖子谁,谁不阅读 cmets 并且只寻找答案

【讨论】:

  • 我是初学者,我猜柴油里面的uuid是对等依赖的,但是为什么会导致这个,因为它与主要的cargo.toml不同
猜你喜欢
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2023-02-21
  • 1970-01-01
  • 2022-12-11
相关资源
最近更新 更多