use std::future::Future;
use std::ops::Deref;
use std::sync::Arc;
use tokio_postgres::Client;
use crate::Error;
pub trait ConnectionProvider: Clone + Send + Sync + 'static {
type Guard<'a>: Deref<Target = Client> + Send
where
Self: 'a;
fn get(&self) -> impl Future<Output = Result<Self::Guard<'_>, Error>> + Send;
}
impl ConnectionProvider for Arc<Client> {
type Guard<'a> = Arc<Client>;
async fn get(&self) -> Result<Self::Guard<'_>, Error> {
Ok(self.clone())
}
}
pub struct PooledConnection(deadpool_postgres::Object);
impl Deref for PooledConnection {
type Target = Client;
fn deref(&self) -> &Client {
&self.0
}
}
impl ConnectionProvider for deadpool_postgres::Pool {
type Guard<'a> = PooledConnection;
async fn get(&self) -> Result<Self::Guard<'_>, Error> {
self.get()
.await
.map(PooledConnection)
.map_err(|e| Error::Pool(e.to_string()))
}
}