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
use reqwest::{Client as ReqwestClient, StatusCode, Url};
use serde::{de::DeserializeOwned, Deserialize};
use serde_json;
use crate::{Client, Error, Query, ReadQuery};
#[derive(Deserialize)]
#[doc(hidden)]
struct _DatabaseError {
error: String,
}
#[derive(Deserialize, Debug)]
#[doc(hidden)]
pub struct DatabaseQueryResult {
pub results: Vec<serde_json::Value>,
}
impl DatabaseQueryResult {
pub fn deserialize_next<T: 'static>(&mut self) -> Result<Return<T>, Error>
where
T: DeserializeOwned + Send,
{
serde_json::from_value::<Return<T>>(self.results.remove(0)).map_err(|err| {
Error::DeserializationError {
error: format!("could not deserialize: {}", err),
}
})
}
}
#[derive(Deserialize, Debug)]
#[doc(hidden)]
pub struct Return<T> {
pub series: Vec<Series<T>>,
}
#[derive(Deserialize, Debug)]
pub struct Series<T> {
pub name: String,
pub values: Vec<T>,
}
impl Client {
pub async fn json_query(&self, q: ReadQuery) -> Result<DatabaseQueryResult, Error> {
let query = q.build().unwrap();
let basic_parameters: Vec<(String, String)> = self.into();
let client = {
let read_query = query.get();
let mut url = match Url::parse_with_params(
format!("{url}/query", url = self.database_url()).as_str(),
basic_parameters,
) {
Ok(url) => url,
Err(err) => {
let error = Error::UrlConstructionError {
error: format!("{}", err),
};
return Err(error);
}
};
url.query_pairs_mut().append_pair("q", &read_query.clone());
if !read_query.contains("SELECT") && !read_query.contains("SHOW") {
let error = Error::InvalidQueryError {
error: String::from(
"Only SELECT and SHOW queries supported with JSON deserialization",
),
};
return Err(error);
}
ReqwestClient::new().get(url.as_str())
};
let res = client
.send()
.await
.map_err(|err| Error::ConnectionError { error: err })?;
match res.status() {
StatusCode::UNAUTHORIZED => return Err(Error::AuthorizationError),
StatusCode::FORBIDDEN => return Err(Error::AuthenticationError),
_ => {}
}
let body = res.bytes().await.map_err(|err| Error::ProtocolError {
error: format!("{}", err),
})?;
if let Ok(error) = serde_json::from_slice::<_DatabaseError>(&body) {
return Err(Error::DatabaseError { error: error.error });
}
serde_json::from_slice::<DatabaseQueryResult>(&body).map_err(|err| {
Error::DeserializationError {
error: format!("serde error: {}", err),
}
})
}
}