gpt4 book ai didi

rust - 将 Diesel 连接注入(inject) Iron 中间件

转载 作者:行者123 更新时间:2023-11-29 08:20:50 25 4
gpt4 key购买 nike

在编写我的测试时,我希望能够在请求中注入(inject)一个连接,这样我就可以将整个测试用例包装在一个事务中(即使测试用例中有多个请求)。

我尝试使用 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 执行此操作的示例,但我想继续使用 diesel。

最佳答案

This answer肯定会解决问题,但这不是最佳选择。如前所述,您不能共享单个连接,因为它不是线程安全的。然而,虽然将其包装在 Mutex 中使其成为线程安全的,但它会强制所有服务器线程使用单个 连接。相反,您想使用连接池。

您可以使用 r2d2 来完成此操作和 r2d2-diesel crate 。这将根据需要建立多个连接,并在可能的情况下以线程安全的方式重用它们。

关于rust - 将 Diesel 连接注入(inject) Iron 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48710477/

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