【发布时间】:2021-04-25 08:37:04
【问题描述】:
我正在尝试将 postgres 数据库添加到使用柴油的火箭应用程序中。我的main.rs 文件看起来像这样,但在.get_result(connection) 处给出错误“diesel::Connection 的特征未针对DbConnection 实现”
#[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;
// ...
错误依旧。
【问题讨论】:
-
解决了吗?面对与火箭 0.5-rc1 完全相同的问题,我并没有得到它想要的错误
标签: postgresql rust rust-diesel rust-rocket