【问题标题】:Rust/Diesel: How to query and insert into postgres tables which have uuidRust/Diesel:如何查询并插入具有 uuid 的 postgres 表
【发布时间】:2019-04-18 23:52:12
【问题描述】:

我有以下 Diesel 生成的架构:

table! {
user (id) {
    id -> Uuid,
    name -> Text
}

和相关的模型

use diesel::{
    self,
    Queryable,
    Insertable,
};
use diesel::prelude::*;
use diesel::sql_types::Uuid;
use super::schema::user;

#[derive(Queryable)]
pub struct User {
    pub id: Uuid,
    pub name: String,
}

impl User {

    pub fn get(id: i32, connection: &PgConnection) -> Vec<User> {
        user::table.load::<User>(connection).unwrap()
    }
}

当我尝试编译时出现错误:

21 |         user::table.load::<User>(connection).unwrap()                                                                                                                              
   |                         ^^^^ the trait `diesel::Queryable<diesel::sql_types::Uuid, diesel::pg::Pg>` is not implemented for `diesel::sql_types::Uuid` 

如果我尝试插入,我会收到类似的错误,指出 Expression 未实现。

这可能是我的依赖项有问题,还是我可能忘记添加到模型中?

[dependencies]
rocket = "0.4.0-rc.1"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
diesel = { version = "1.0.0", features = ["postgres", "uuid"] }
r2d2 = "*"
r2d2-diesel = "*"

[dependencies.rocket_contrib]
version = "0.4.0-rc.1"
default-features = false
features = ["json", "diesel_postgres_pool", "uuid"]

【问题讨论】:

    标签: rust rust-diesel


    【解决方案1】:

    结构中的类型需要是 Rust 类型而不是 SQL 类型,特别是 uuid crate 中的 Uuid(在 Diesel 1.3 中,Diesel 仅支持 0.6 版本)。在问题的代码中,Uuid 扩展为 diesel::sql_types::Uuid

    #[derive(Queryable)]
    pub struct User {
        pub id: uuid::Uuid,
        pub name: String,
    }
    

    【讨论】:

    • 在阅读了我能在网上找到的所有内容之后,这个问题终于通过将uuid 修复到版本 0.6 为我解决了。感谢您指出这一点,这在其他地方并不明显。
    • 就我而言,我只是将柴油机功能从 uuid 更改为 uuidv07
    【解决方案2】:

    刚刚也花了很多时间来解决这个问题。从 Diesel 1.4.5 开始,您可以添加最新版本的 uuid,但您必须在 Diesel 上指定 uuidv07 功能。

    您的Cargo.toml 应该如下所示:

    uuid = { version = "0.8.2", features = ["serde", "v4"] }
    diesel = { version = "1.4.5", features = ["chrono", "postgres", "r2d2", "uuidv07"] }
    

    来源:https://github.com/diesel-rs/diesel/issues/2348

    注意:另外,就像@canab 所说,结构上的Uuid 类型应该来自uuid 库,而不是Diesel SQL 类型。

    【讨论】:

      猜你喜欢
      • 2016-02-06
      • 2021-10-31
      • 2022-09-23
      • 2019-07-07
      • 1970-01-01
      • 2020-11-22
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多