Rust/Diesel:如何查询并插入具有 uuid 的 postgres 表 [英] Rust/Diesel: How to query and insert into postgres tables which have uuid

查看:67
本文介绍了Rust/Diesel:如何查询并插入具有 uuid 的 postgres 表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下由 Diesel 生成的架构:

I have the following schema generated by 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()
    }
}

当我尝试编译它时出现错误,内容为:

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` 

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

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

推荐答案

struct 中的类型需要是 Rust 类型而不是 SQL 类型,特别是 Uuid 来自 uuid crate(在 Diesel 1.3 中,Diesel 仅支持 0.6 版).在问题的代码中,Uuid 扩展为 diesel::sql_types::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). 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,
}

这篇关于Rust/Diesel:如何查询并插入具有 uuid 的 postgres 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆