【发布时间】:2016-10-25 21:48:35
【问题描述】:
在编写我的测试时,我希望能够将连接注入到请求中,以便我可以将整个测试用例包装在一个事务中(即使测试用例中有多个请求)。
我尝试使用 BeforeMiddleware 来执行此操作,我可以在我的测试用例中链接它以插入连接,例如:
pub type DatabaseConnection = PooledConnection<ConnectionManager<PgConnection>>;
pub struct DatabaseOverride {
conn: DatabaseConnection,
}
impl BeforeMiddleware for DatabaseOverride {
fn before(&self, req: &mut Request) -> IronResult<()> {
req.extensions_mut().entry::<DatabaseOverride>().or_insert(self.conn);
Ok(())
}
}
但是,我在尝试执行此操作时遇到编译错误:
error: the trait bound `std::rc::Rc<diesel::pg::connection::raw::RawConnection>: std::marker::Sync` is not satisfied [E0277]
impl BeforeMiddleware for DatabaseOverride {
^~~~~~~~~~~~~~~~
help: run `rustc --explain E0277` to see a detailed explanation
note: `std::rc::Rc<diesel::pg::connection::raw::RawConnection>` cannot be shared between threads safely
note: required because it appears within the type `diesel::pg::PgConnection`
note: required because it appears within the type `r2d2::Conn<diesel::pg::PgConnection>`
note: required because it appears within the type `std::option::Option<r2d2::Conn<diesel::pg::PgConnection>>`
note: required because it appears within the type `r2d2::PooledConnection<r2d2_diesel::ConnectionManager<diesel::pg::PgConnection>>`
note: required because it appears within the type `utility::db::DatabaseOverride`
note: required by `iron::BeforeMiddleware`
error: the trait bound `std::cell::Cell<i32>: std::marker::Sync` is not satisfied [E0277]
impl BeforeMiddleware for DatabaseOverride {
^~~~~~~~~~~~~~~~
help: run `rustc --explain E0277` to see a detailed explanation
note: `std::cell::Cell<i32>` cannot be shared between threads safely
note: required because it appears within the type `diesel::pg::PgConnection`
note: required because it appears within the type `r2d2::Conn<diesel::pg::PgConnection>`
note: required because it appears within the type `std::option::Option<r2d2::Conn<diesel::pg::PgConnection>>`
note: required because it appears within the type `r2d2::PooledConnection<r2d2_diesel::ConnectionManager<diesel::pg::PgConnection>>`
note: required because it appears within the type `utility::db::DatabaseOverride`
note: required by `iron::BeforeMiddleware`
有没有办法通过柴油机的连接来解决这个问题?我在 Github 上找到了几个使用 pg crate 的示例,但我想继续使用柴油。
【问题讨论】:
-
我可能是错的(我不在我的 Rust 环境 atm 附近)但你不必实现
typemap特征或类似的东西才能将其存储在请求扩展中吗? -
是的,我已经实现了一个(为简洁起见,我没有在这里发布)。这里的问题是我不能用
diesel::pg::PgConnection初始化BeforeMiddleware,因为PgConnection没有实现Sync。我希望有人知道解决此限制的方法。 -
我自己没有使用过
diesel,我不确定。然而,它使用任何Cell类型,甚至是像Rc这样的不同步智能指针,都会导致它自动无法实现Sync。
标签: rust iron rust-diesel