forked from transact-rs/sqlx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.rs
More file actions
89 lines (70 loc) · 2.5 KB
/
Copy pathparse.rs
File metadata and controls
89 lines (70 loc) · 2.5 KB
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
use crate::PgConnectOptions;
use sqlx_core::error::Error;
use std::str::FromStr;
use url::Url;
impl FromStr for PgConnectOptions {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Error> {
let url: Url = s.parse().map_err(Error::configuration)?;
if !matches!(url.scheme(), "postgres" | "postgresql") {
return Err(Error::configuration_msg(format!(
"unsupported URI scheme {:?} for PostgreSQL",
url.scheme()
)));
}
let mut options = Self::default();
if let Some(host) = url.host_str() {
options = options.host(host);
}
if let Some(port) = url.port() {
options = options.port(port);
}
let username = url.username();
if !username.is_empty() {
options = options.username(username);
}
if let Some(password) = url.password() {
options = options.password(password);
}
let path = url.path().trim_start_matches('/');
if !path.is_empty() {
options = options.database(path);
}
for (key, value) in url.query_pairs().into_iter() {
match &*key {
"sslmode" | "ssl-mode" => {
options = options.ssl_mode(value.parse().map_err(Error::configuration)?);
}
"sslrootcert" | "ssl-root-cert" | "ssl-ca" => {
options = options.ssl_root_cert(&*value);
}
"statement-cache-capacity" => {
options = options
.statement_cache_capacity(value.parse().map_err(Error::configuration)?);
}
"host" => {
if value.starts_with("/") {
options = options.socket(&*value);
} else {
options = options.host(&*value);
}
}
_ => {}
}
}
Ok(options)
}
}
#[test]
fn it_parses_socket_correctly_from_parameter() {
let uri = "postgres:///?host=/var/run/postgres/";
let opts = PgConnectOptions::from_str(uri).unwrap();
assert_eq!(Some("/var/run/postgres/".into()), opts.socket);
}
#[test]
fn it_parses_host_correctly_from_parameter() {
let uri = "postgres:///?host=google.database.com";
let opts = PgConnectOptions::from_str(uri).unwrap();
assert_eq!(None, opts.socket);
assert_eq!("google.database.com", &opts.host);
}