gpt4 book ai didi

postgresql - 特征 `diesel::Connection` 未针对 `DbConnection` 实现

转载 作者:行者123 更新时间:2023-12-03 11:38:13 24 4
gpt4 key购买 nike

我正在尝试将 postgres 数据库添加到使用柴油的火箭应用程序中。我的 main.rs文件看起来像这样,但在 diesel::Connection 处给出错误“未为 DbConnection 实现特征 .get_result(connection)

#[macro_use] extern crate diesel;
extern crate dotenv;
#[macro_use] extern crate rocket;
#[macro_use] extern crate rocket_contrib;

use diesel::prelude::*;
use rocket_contrib::database;
use rocket_contrib::json::JsonValue;

mod models;
mod schema;

use self::models::*;
use self::schema::*;

#[database("my_db")]
struct DbConnection(diesel::PgConnection);

#[get("/")]
fn index(connection: DbConnection) -> JsonValue {
json!(all_bicycles(&connection))
}

fn create_bicycle<'a>(connection: &DbConnection, make: &'a str, model: &'a str, rider_type: &'a str, size: &'a str) -> Bicycle {
let new_bicycle = NewBicycle {
make,
model,
rider_type,
size
};

diesel::insert_into(bicycles::table)
.values(new_bicycle)
// the error is on the following line, on `connection`
.get_result(connection)
.expect("Error saving bicycle")
}

fn main() {
rocket::ignite()
.attach(DbConnection::fairing())
.mount("/", routes![index])
.launch();
}

我的 Cargo.toml (相关部分)
[dependencies]
diesel = { version = "1.4.4", features = ["postgres"] }
dotenv = "0.15.0"
rocket = { git = "https://github.com/SergioBenitez/Rocket" }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

[dependencies.rocket_contrib]
git = "https://github.com/SergioBenitez/Rocket"
default-features = false
features = ["json", "diesel_postgres_pool"]

和我的 Rocket.toml :
[global.databases]
my_db = { url = "postgres://postgres:@localhost/bikes" }

展开后的错误如下所示:
&DbConnection
the trait bound `DbConnection: diesel::Connection` is not satisfied

the trait `diesel::Connection` is not implemented for `DbConnection`
我已经设法建立到数据库的连接,并且 diesel setup那是成功的。我还可以添加迁移——尽管我认为它们对于这个问题是不必要的。
我在这里做错了什么?
编辑
我再次阅读 Rocket 文档并意识到我错过了 use rocket_contrib::databases::diesel; 行。 ,与 extern crate diesel; 冲突,所以我将数据库逻辑移到了一个新模块中 - database.rs .什么都没有真正改变,但新模块如下所示:
use rocket_contrib::database;
use rocket_contrib::databases::diesel;

#[database("my_db")]
pub struct DbConnection(diesel::PgConnection);
它的使用方式如下: main.rs
// ...
mod database;
use self::database::DbConnection;
// ...
错误保持不变。

最佳答案

根据rocket您需要将连接类型取消引用为实现 diesel::connection::Connection 的某种类型的文档因为包装器类型没有实现必要的特征。因此,您需要将代码更改为以下内容:

    diesel::insert_into(bicycles::table)
.values(new_bicycle)
// the error is on the following line, on `connection`
.get_result(&*connection)
.expect("Error saving bicycle")
(在将连接传递给 &* 函数之前,请注意额外的 get_result。)

关于postgresql - 特征 `diesel::Connection` 未针对 `DbConnection` 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65818709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com