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

use*_*090 8 rust rust-diesel

我有Diesel生成的以下架构:

table! {
user (id) {
    id -> Uuid,
    name -> Text
}
Run Code Online (Sandbox Code Playgroud)

和相关的模型

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

尝试编译此错误时显示错误:

table! {
user (id) {
    id -> Uuid,
    name -> Text
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试插入,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"]
Run Code Online (Sandbox Code Playgroud)

小智 9

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,
}
Run Code Online (Sandbox Code Playgroud)

  • 在阅读了我可以在网上找到的几乎所有内容后,我最终通过将 `uuid` 修复到 0.6 版解决了这个问题。感谢您指出这一点,在其他任何地方都不明显。 (5认同)

dan*_*rod 6

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

Cargo.toml应该看起来像这样:

uuid = { version = "0.8.2", features = ["serde", "v4"] }
diesel = { version = "1.4.5", features = ["chrono", "postgres", "r2d2", "uuidv07"] }
Run Code Online (Sandbox Code Playgroud)

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

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