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

做~自己de王妃 提交于 2020-05-12 11:59:12

问题


I have the following schema generated by 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.

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

回答1:


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). In the code from the question, the Uuid is expanded to a diesel::sql_types::Uuid

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


来源:https://stackoverflow.com/questions/53326887/rust-diesel-how-to-query-and-insert-into-postgres-tables-which-have-uuid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!