db_pool/async/backend/common/pool/tokio_postgres/
deadpool.rs

1use std::ops::{Deref, DerefMut};
2
3use async_trait::async_trait;
4use deadpool::managed::{BuildError, Object, Pool, PoolBuilder, PoolError};
5use deadpool_postgres::Manager;
6use tokio_postgres::{Client, Config, Error};
7
8use crate::r#async::backend::{
9    common::error::tokio_postgres::{ConnectionError, QueryError},
10    error::Error as BackendError,
11};
12
13use super::r#trait::TokioPostgresPoolAssociation;
14
15/// [`tokio-postgres deadpool`](https://docs.rs/deadpool-postgres/0.14.1/deadpool_postgres/) association
16pub struct TokioPostgresDeadpool;
17
18#[async_trait]
19impl TokioPostgresPoolAssociation for TokioPostgresDeadpool {
20    type PooledConnection<'pool> = PooledConnection;
21
22    type Builder = PoolBuilder<Manager>;
23    type Pool = Pool<Manager>;
24
25    type BuildError = BuildError;
26    type PoolError = PoolError<Error>;
27
28    async fn build_pool(
29        builder: PoolBuilder<Manager>,
30        _config: Config,
31    ) -> Result<Self::Pool, Self::BuildError> {
32        builder.build()
33    }
34
35    async fn get_connection<'pool>(
36        pool: &'pool Pool<Manager>,
37    ) -> Result<Self::PooledConnection<'pool>, Self::PoolError> {
38        pool.get().await.map(Into::into)
39    }
40}
41
42pub struct PooledConnection(Object<Manager>);
43
44impl From<Object<Manager>> for PooledConnection {
45    fn from(value: Object<Manager>) -> Self {
46        Self(value)
47    }
48}
49
50impl Deref for PooledConnection {
51    type Target = Client;
52
53    fn deref(&self) -> &Self::Target {
54        &self.0
55    }
56}
57
58impl DerefMut for PooledConnection {
59    fn deref_mut(&mut self) -> &mut Self::Target {
60        &mut self.0
61    }
62}
63
64impl From<BuildError> for BackendError<BuildError, PoolError<Error>, ConnectionError, QueryError> {
65    fn from(value: BuildError) -> Self {
66        Self::Build(value)
67    }
68}
69
70impl From<PoolError<Error>>
71    for BackendError<BuildError, PoolError<Error>, ConnectionError, QueryError>
72{
73    fn from(value: PoolError<Error>) -> Self {
74        Self::Pool(value)
75    }
76}