简体   繁体   English

Rust/Diesel:如何查询并插入具有 uuid 的 postgres 表

[英]Rust/Diesel: How to query and insert into postgres tables which have uuid

I have the following schema generated by Diesel:我有以下由 Diesel 生成的架构:

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

and the associated model和相关的模型

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()
    }
}

I get an error when I try to compile this which says:当我尝试编译它时出现错误,它说:

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` 

If I try to insert I get a similar error saying that Expression is not implemented.如果我尝试插入,我会收到类似的错误,指出未实现Expression

Could this be a problem with my dependencies or something I may have forgotten to add to the model?这可能是我的依赖项的问题还是我可能忘记添加到模型中的问题?

[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"]

The type in the struct needs to be a Rust type rather than a SQL type, specifically Uuid from the uuid crate (in Diesel 1.3, only version 0.6 is supported by Diesel). struct 中的类型需要是 Rust 类型而不是 SQL 类型,特别是来自uuid crate 的Uuid (在 Diesel 1.3 中,Diesel 仅支持 0.6 版)。 In the code from the question, the Uuid is expanded to a diesel::sql_types::Uuid在问题的代码中, Uuid被扩展为一个diesel::sql_types::Uuid

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

Just spent a lot of time with this problem as well.刚刚也花了很多时间解决这个问题。 It looks like as of Diesel 1.4.5, you can add the latest version of uuid , but you have to specify the uuidv07 feature on Diesel.从 Diesel 1.4.5 开始,您可以添加最新版本的uuid ,但您必须在 Diesel 上指定uuidv07功能。

Your Cargo.toml should look something like this:您的Cargo.toml应如下所示:

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

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

Note: Also, like @canab said, the Uuid type on the struct should be from the uuid library, not the Diesel SQL type.注意:另外,就像@canab 所说的,结构上的Uuid类型应该来自uuid库,而不是 Diesel SQL 类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM