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
use std::error::Error;
use std::path::PathBuf;
use url::{self, Url};
#[derive(Clone, Debug)]
pub enum ConnectTarget {
Tcp(String),
Unix(PathBuf),
}
#[derive(Clone, Debug)]
pub struct UserInfo {
pub user: String,
pub password: Option<String>,
}
#[derive(Clone, Debug)]
pub struct ConnectParams {
pub target: ConnectTarget,
pub port: Option<u16>,
pub user: Option<UserInfo>,
pub database: Option<String>,
pub options: Vec<(String, String)>,
}
pub trait IntoConnectParams {
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 { mut path, query: options, .. }, .. } = self;
let maybe_path = try!(url::decode_component(&host));
let target = if maybe_path.starts_with('/') {
ConnectTarget::Unix(PathBuf::from(maybe_path))
} else {
ConnectTarget::Tcp(host)
};
let user = user.map(|url::UserInfo { user, pass }| {
UserInfo {
user: user,
password: pass,
}
});
let database = if path.is_empty() {
None
} else {
path.remove(0);
Some(path)
};
Ok(ConnectParams {
target: target,
port: port,
user: user,
database: database,
options: options,
})
}
}