我正在尝试使用柴油将 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;
// ...
错误依旧。
答案 0 :(得分:2)
根据 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
。)
答案 1 :(得分:0)
如果我没记错的话,应该是
#[get("/")]
fn index(connection: DbConnection) -> JsonValue {
json!(all_bicycles(&*connection))
}
对于路线和
fn all_bicycles(connection: &diesel::PgConnection) -> Vec<Bicycle> {
// ...
.get_result(connection)
.expect("Error saving bicycle")
// ...
}
用于查询数据库的实际方法。因此,直接传递实际的柴油连接作为参考(因为您的数据库抽象不一定了解火箭)。