1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use qp::async_trait;
use qp::pool::Pool;
use qp::resource::Factory;
use tokio_postgres::tls::{MakeTlsConnect, TlsConnect};
use tokio_postgres::{Client, Config, Error, Socket};

pub use qp;
pub use tokio_postgres;

pub type PgPool<T> = Pool<PgConnFactory<T>>;

pub struct PgConnFactory<T>
where
    T: MakeTlsConnect<Socket> + Clone + Send + Sync,
    T::Stream: Send + Sync + 'static,
    T::TlsConnect: Send + Sync,
    <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
{
    config: Config,
    tls: T,
}

#[async_trait]
impl<T> Factory for PgConnFactory<T>
where
    T: MakeTlsConnect<Socket> + Clone + Send + Sync,
    T::Stream: Send + Sync + 'static,
    T::TlsConnect: Send + Sync,
    <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
{
    type Output = Client;
    type Error = Error;

    async fn try_create(&self) -> Result<Self::Output, Self::Error> {
        let (client, conn) = self.config.connect(self.tls.clone()).await?;
        tokio::spawn(conn);
        Ok(client)
    }

    async fn validate(&self, client: &Self::Output) -> bool {
        !client.is_closed()
    }
}

impl<T> PgConnFactory<T>
where
    T: MakeTlsConnect<Socket> + Clone + Send + Sync,
    T::Stream: Send + Sync + 'static,
    T::TlsConnect: Send + Sync,
    <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
{
    pub fn new(config: Config, tls: T) -> Self {
        Self { config, tls }
    }
}

pub fn connect<T>(config: Config, tls: T, pool_size: usize) -> PgPool<T>
where
    T: MakeTlsConnect<Socket> + Clone + Send + Sync,
    T::Stream: Send + Sync + 'static,
    T::TlsConnect: Send + Sync,
    <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
{
    Pool::new(PgConnFactory::new(config, tls), pool_size)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio_postgres::NoTls;

    #[tokio::test]
    async fn test_connect() {
        let config = "postgresql://postgres:postgres@localhost".parse().unwrap();
        let pool = connect(config, NoTls, 1);
        let client = pool.acquire().await.unwrap();
        let row = client.query_one("SELECT 1", &[]).await.unwrap();
        let value: i32 = row.get(0);
        assert_eq!(value, 1);
    }
}