[英]Rust/Diesel: How to query and insert into postgres tables which have uuid
我有以下由 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"]
struct 中的類型需要是 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,
}
剛剛也花了很多時間解決這個問題。 從 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 類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.