-
Notifications
You must be signed in to change notification settings - Fork 1
/
pg.rs
167 lines (153 loc) · 5.04 KB
/
pg.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
use crate::common::{DbError, DbErrorLifetime, DbErrorType, Opts};
use native_tls::TlsConnector;
use postgres::Client;
use postgres_native_tls::MakeTlsConnector;
use regex::Regex;
use std::collections::HashMap;
use std::error::Error;
impl From<&postgres::error::DbError> for DbError {
fn from(e: &postgres::error::DbError) -> Self {
let kind = if *e.code() == postgres::error::SqlState::SYNTAX_ERROR {
DbErrorLifetime::Permanent
} else {
DbErrorLifetime::Temporary
};
DbError {
kind,
error: DbErrorType::PostgresError {
error: Box::new(e.clone()),
},
}
}
}
impl From<postgres::error::Error> for DbError {
#[rustfmt::skip]
fn from(e: postgres::error::Error) -> Self {
if let Some(error) = e.source() {
if let Some(dberror) = error.downcast_ref::<postgres::error::DbError>() {
return dberror.into();
}
}
// FIXME: Hack because https://github.com/sfackler/rust-postgres/issues/583
let dump = format!("{:?}", e);
let kind_re = Regex::new(r"kind: ([A-Za-z]+)").unwrap();
let lifetime = if let Some(captures) = kind_re.captures(&dump) {
match &captures[1] {
"ConfigParse" => DbErrorLifetime::Permanent,
_ => DbErrorLifetime::Temporary
}
} else {
DbErrorLifetime::Temporary
};
DbError {
kind: lifetime,
error: DbErrorType::PostgresError { error: Box::new(e) },
}
}
}
pub fn connect(opts: &Opts) -> std::result::Result<Vec<HashMap<String, String>>, DbError> {
let tls_connector = TlsConnector::builder()
.danger_accept_invalid_certs(true)
.build()
.unwrap();
let connector = MakeTlsConnector::new(tls_connector);
let mut conn = Client::connect(opts.connection_string.as_str(), connector)?;
if let Some(ref sql_query) = opts.sql_query {
execute_statement(&mut conn, sql_query)
} else {
Ok(Vec::new())
}
}
fn execute_statement(
conn: &mut postgres::Client,
sql_query: &str,
) -> Result<Vec<HashMap<String, String>>, DbError> {
let mut results: Vec<HashMap<String, String>> = Vec::new();
let rows = conn.query(sql_query, &[])?;
for row in rows.iter() {
let mut result: HashMap<String, String> = HashMap::new();
let cols = row.columns();
for (i, col) in cols.iter().enumerate() {
let val = row
.try_get::<usize, String>(i)
.unwrap_or_else(|_| "".to_string());
result.insert(col.name().to_string(), val);
}
results.push(result);
}
Ok(results)
}
// only for tests
#[doc(hidden)]
pub fn postgres_connect(sslmode: &str) -> String {
format!(
"postgresql://{}:{}@{}:{}?sslmode={}",
std::env::var("POSTGRES_USERNAME").unwrap(),
std::env::var("POSTGRES_PASSWORD").unwrap(),
std::env::var("POSTGRES_SERVER").unwrap(),
std::env::var("POSTGRES_PORT").unwrap(),
sslmode
)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_postgres_with_no_server() {
let err = connect(&Opts::new().connection_string("postgresql://")).unwrap_err();
assert_eq!(err.kind, DbErrorLifetime::Temporary, "{:?}", err);
if let DbErrorType::OdbcError { error } = err.error {
let desc = format!("{}", error);
assert!(
desc.contains("could not connect to server: No such file or directory"),
"{}",
desc
);
}
}
#[test]
fn test_postgres_with_bad_url() {
let err = connect(&Opts::new().connection_string("postgresql://test:test@localhost:port"))
.unwrap_err();
assert_eq!(err.kind, DbErrorLifetime::Permanent, "{:?}", err);
}
#[test]
#[cfg_attr(postgres_driver = "", ignore)]
fn test_postgres_with_server() {
connect(
&Opts::new()
.connection_string(postgres_connect("disable"))
.sql_query("SHOW IS_SUPERUSER"),
)
.unwrap();
}
#[test]
#[cfg_attr(postgres_driver = "", ignore)]
fn test_postgres_with_secure_server() {
connect(
&Opts::new()
.connection_string(postgres_connect("require"))
.sql_query("SHOW IS_SUPERUSER"),
)
.unwrap();
}
#[test]
#[cfg_attr(postgres_driver = "", ignore)]
fn test_postgres_with_bad_query() {
let err = connect(
&Opts::new()
.connection_string(postgres_connect("disable"))
.sql_query("foobar"),
)
.unwrap_err();
assert_eq!(err.kind, DbErrorLifetime::Permanent, "{:?}", err);
if let DbErrorType::OdbcError { error } = err.error {
let desc = format!("{}", error);
assert!(
desc.contains("ERROR: syntax error at or near \"foobar\""),
"{}",
desc
);
}
}
}