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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#![doc(html_root_url="https://sfackler.github.io/r2d2-postgres/doc/v0.11.0")]
#![warn(missing_docs)]
pub extern crate r2d2;
pub extern crate postgres;
use std::error;
use std::error::Error as _StdError;
use std::fmt;
use postgres::params::{ConnectParams, IntoConnectParams};
use postgres::tls::TlsHandshake;
#[derive(Debug)]
pub enum TlsMode {
None,
Prefer(Box<TlsHandshake + Sync + Send>),
Require(Box<TlsHandshake + Sync + Send>),
}
#[derive(Debug)]
pub enum Error {
Connect(postgres::error::ConnectError),
Other(postgres::error::Error),
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}: {}", self.description(), self.cause().unwrap())
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Connect(_) => "Error opening a connection",
Error::Other(_) => "Error communicating with server",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::Connect(ref err) => Some(err as &error::Error),
Error::Other(ref err) => Some(err as &error::Error),
}
}
}
#[derive(Debug)]
pub struct PostgresConnectionManager {
params: ConnectParams,
ssl_mode: TlsMode,
}
impl PostgresConnectionManager {
pub fn new<T>(params: T,
ssl_mode: TlsMode)
-> Result<PostgresConnectionManager, postgres::error::ConnectError>
where T: IntoConnectParams
{
let params = match params.into_connect_params() {
Ok(params) => params,
Err(err) => return Err(postgres::error::ConnectError::ConnectParams(err)),
};
Ok(PostgresConnectionManager {
params: params,
ssl_mode: ssl_mode,
})
}
}
impl r2d2::ManageConnection for PostgresConnectionManager {
type Connection = postgres::Connection;
type Error = Error;
fn connect(&self) -> Result<postgres::Connection, Error> {
let mode = match self.ssl_mode {
TlsMode::None => postgres::TlsMode::None,
TlsMode::Prefer(ref n) => postgres::TlsMode::Prefer(&**n),
TlsMode::Require(ref n) => postgres::TlsMode::Require(&**n),
};
postgres::Connection::connect(self.params.clone(), mode).map_err(Error::Connect)
}
fn is_valid(&self, conn: &mut postgres::Connection) -> Result<(), Error> {
conn.batch_execute("").map_err(Error::Other)
}
fn has_broken(&self, conn: &mut postgres::Connection) -> bool {
conn.is_desynchronized()
}
}