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
//! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use client::{CDRS, Session, QueryBuilder};
use error::{Error as CError};
use authenticators::Authenticator;
use compression::Compression;
use r2d2;

#[cfg(not(feature = "ssl"))]
use transport::Transport;
#[cfg(feature = "ssl")]
use transport_ssl::Transport;

/// [r2d2](https://github.com/sfackler/r2d2) `ManageConnection`.
pub struct ConnectionManager<T> {
    transport: Transport,
    authenticator: T,
    compression: Compression
}

impl<T: Authenticator + Send + Sync + 'static> ConnectionManager<T> {
    /// Creates a new instance of `ConnectionManager`.
    /// It requires transport, authenticator and compression as inputs.
    pub fn new(transport: Transport, authenticator: T, compression: Compression)
        -> ConnectionManager<T> {
        ConnectionManager {
            transport: transport,
            authenticator: authenticator,
            compression: compression
        }
    }
}

impl<T: Authenticator + Send + Sync + 'static> r2d2::ManageConnection for ConnectionManager<T> {
    type Connection = Session<T>;
    type Error = CError;

    fn connect(&self) -> Result<Self::Connection, Self::Error> {
        let transport = try!(self.transport.try_clone());
        let compression = self.compression.clone();
        let cdrs = CDRS::new(transport, self.authenticator.clone());

        cdrs.start(compression)
    }

    fn is_valid(&self, connection: &mut Self::Connection) -> Result<(), Self::Error> {
        let query = QueryBuilder::new("SELECT * FROM system.peers;").finalize();

        connection.query(query, false, false).map(|_| (()))
    }

    fn has_broken(&self, _connection: &mut Self::Connection) -> bool {
        false
    }
}