forked from sfackler/rust-postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
285 lines (247 loc) · 7.46 KB
/
mod.rs
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
//! Connection parameters
use std::error::Error;
use std::mem;
use std::path::PathBuf;
use std::time::Duration;
use params::url::Url;
mod url;
/// The host.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Host {
/// A TCP hostname.
Tcp(String),
/// The path to a directory containing the server's Unix socket.
Unix(PathBuf),
}
/// Authentication information.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct User {
name: String,
password: Option<String>,
}
impl User {
/// The username.
pub fn name(&self) -> &str {
&self.name
}
/// An optional password.
pub fn password(&self) -> Option<&str> {
self.password.as_ref().map(|p| &**p)
}
}
/// Information necessary to open a new connection to a Postgres server.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ConnectParams {
host: Host,
port: u16,
user: Option<User>,
database: Option<String>,
options: Vec<(String, String)>,
connect_timeout: Option<Duration>,
keepalive: Option<Duration>,
}
impl ConnectParams {
/// Returns a new builder.
pub fn builder() -> Builder {
Builder::new()
}
/// The target host.
pub fn host(&self) -> &Host {
&self.host
}
/// The target port.
///
/// Defaults to 5432.
pub fn port(&self) -> u16 {
self.port
}
/// The user to log in as.
///
/// A user is required to open a new connection but not to cancel a query.
pub fn user(&self) -> Option<&User> {
self.user.as_ref()
}
/// The database to connect to.
pub fn database(&self) -> Option<&str> {
self.database.as_ref().map(|d| &**d)
}
/// Runtime parameters to be passed to the Postgres backend.
pub fn options(&self) -> &[(String, String)] {
&self.options
}
/// A timeout to apply to each socket-level connection attempt.
pub fn connect_timeout(&self) -> Option<Duration> {
self.connect_timeout
}
/// The interval at which TCP keepalive messages are sent on the socket.
///
/// This is ignored for Unix sockets.
pub fn keepalive(&self) -> Option<Duration> {
self.keepalive
}
}
/// A builder for `ConnectParams`.
pub struct Builder {
port: u16,
user: Option<User>,
database: Option<String>,
options: Vec<(String, String)>,
connect_timeout: Option<Duration>,
keepalive: Option<Duration>,
}
impl Builder {
/// Creates a new builder.
pub fn new() -> Builder {
Builder {
port: 5432,
user: None,
database: None,
options: vec![],
connect_timeout: None,
keepalive: None,
}
}
/// Sets the port.
pub fn port(&mut self, port: u16) -> &mut Builder {
self.port = port;
self
}
/// Sets the user.
pub fn user(&mut self, name: &str, password: Option<&str>) -> &mut Builder {
self.user = Some(User {
name: name.to_string(),
password: password.map(ToString::to_string),
});
self
}
/// Sets the database.
pub fn database(&mut self, database: &str) -> &mut Builder {
self.database = Some(database.to_string());
self
}
/// Adds a runtime parameter.
pub fn option(&mut self, name: &str, value: &str) -> &mut Builder {
self.options.push((name.to_string(), value.to_string()));
self
}
/// Sets the connection timeout.
pub fn connect_timeout(&mut self, connect_timeout: Option<Duration>) -> &mut Builder {
self.connect_timeout = connect_timeout;
self
}
/// Sets the keepalive interval.
pub fn keepalive(&mut self, keepalive: Option<Duration>) -> &mut Builder {
self.keepalive = keepalive;
self
}
/// Constructs a `ConnectParams` from the builder.
pub fn build(&mut self, host: Host) -> ConnectParams {
ConnectParams {
host: host,
port: self.port,
user: self.user.take(),
database: self.database.take(),
options: mem::replace(&mut self.options, vec![]),
connect_timeout: self.connect_timeout,
keepalive: self.keepalive,
}
}
}
/// A trait implemented by types that can be converted into a `ConnectParams`.
pub trait IntoConnectParams {
/// Converts the value of `self` into a `ConnectParams`.
fn into_connect_params(self) -> Result<ConnectParams, Box<Error + Sync + Send>>;
}
impl IntoConnectParams for ConnectParams {
fn into_connect_params(self) -> Result<ConnectParams, Box<Error + Sync + Send>> {
Ok(self)
}
}
impl<'a> IntoConnectParams for &'a str {
fn into_connect_params(self) -> Result<ConnectParams, Box<Error + Sync + Send>> {
match Url::parse(self) {
Ok(url) => url.into_connect_params(),
Err(err) => Err(err.into()),
}
}
}
impl IntoConnectParams for String {
fn into_connect_params(self) -> Result<ConnectParams, Box<Error + Sync + Send>> {
self.as_str().into_connect_params()
}
}
impl IntoConnectParams for Url {
fn into_connect_params(self) -> Result<ConnectParams, Box<Error + Sync + Send>> {
let Url {
host,
port,
user,
path:
url::Path {
path,
query: options,
..
},
..
} = self;
let mut builder = ConnectParams::builder();
if let Some(port) = port {
builder.port(port);
}
if let Some(info) = user {
builder.user(&info.user, info.pass.as_ref().map(|p| &**p));
}
if !path.is_empty() {
// path contains the leading /
builder.database(&path[1..]);
}
for (name, value) in options {
match &*name {
"connect_timeout" => {
let timeout = value.parse().map_err(|_| "invalid connect_timeout")?;
let timeout = Duration::from_secs(timeout);
builder.connect_timeout(Some(timeout));
}
"keepalive" => {
let keepalive = value.parse().map_err(|_| "invalid keepalive")?;
let keepalive = Duration::from_secs(keepalive);
builder.keepalive(Some(keepalive));
}
_ => {
builder.option(&name, &value);
}
}
}
let maybe_path = url::decode_component(&host)?;
let host = if maybe_path.starts_with('/') {
Host::Unix(maybe_path.into())
} else {
Host::Tcp(maybe_path)
};
Ok(builder.build(host))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn parse_url() {
let params = "postgres://user@host:44/dbname?connect_timeout=10&application_name=foo";
let params = params.into_connect_params().unwrap();
assert_eq!(
params.user(),
Some(&User {
name: "user".to_string(),
password: None,
})
);
assert_eq!(params.host(), &Host::Tcp("host".to_string()));
assert_eq!(params.port(), 44);
assert_eq!(params.database(), Some("dbname"));
assert_eq!(
params.options(),
&[("application_name".to_string(), "foo".to_string())][..]
);
assert_eq!(params.connect_timeout(), Some(Duration::from_secs(10)));
}
}