how to use with deadpool?
Closed this issue · 2 comments
I think I want to use deadpool since I think my odbc driver doesn't support pooling and since connection with this driver are slow to establish, I would want the connections to be created at launch.
It seems that I need to set a lifetime to my struct but I'm not sure how to use it with deadpool. I tried type Type<'a> = Computer<'a>
but I think the trait didn't match anymore.
With this code:
use anyhow::Error;
use async_trait::async_trait;
use deadpool::managed;
use odbc_api::{Connection, ConnectionOptions, Environment};
struct Computer<'a> {
conn: Connection<'a>,
}
struct Manager {}
#[async_trait]
impl managed::Manager for Manager {
type Type = Computer<'static>;
type Error = Error;
async fn create(&self) -> Result<Self::Type, Error> {
let conn_str = "something".to_string();
let environment = Environment::new().unwrap();
let conn = environment
.connect_with_connection_string(&conn_str, ConnectionOptions::default())
.unwrap();
Ok(Computer { conn })
}
async fn recycle(
&self,
_: &mut Self::Type,
_: &managed::Metrics,
) -> managed::RecycleResult<Error> {
todo!();
}
}
fn main() {
todo!();
}
I get:
error[E0597]: `environment` does not live long enough
--> src/main.rs:21:20
|
17 | async fn create(&self) -> Result<Self::Type, Error> {
| ------------------------- type annotation requires that `environment` is borrowed for `'static`
...
20 | let environment = Environment::new().unwrap();
| ----------- binding `environment` declared here
21 | let conn = environment
| ____________________^
22 | | .connect_with_connection_string(&conn_str, ConnectionOptions::default())
| |____________________________________________________________________________________^ borrowed value does not live long enough
...
26 | }
| - `environment` dropped here while still borrowed
Hello @bbigras ,
Environment
must outlive any Connection
created with it. Most straigt forward way to implement ithis is to use at most one Environment
with static lifetime to create all connections, for the entirety of the application. To do that you can either use OnceCell
or LazyStatic
.
Best, Markus
It works with LazyStatic. Thanks!!