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
#![warn(missing_debug_implementations)]
use std::fmt;
use std::time::Duration;
use reqwest::{IntoUrl, Url};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
#[derive(Debug)]
pub struct Client {
inner: reqwest::Client,
url: Url,
session_id: Option<String>,
}
impl Client {
pub fn new<U>(url: U) -> Result<Self, Error>
where
U: IntoUrl,
{
let mut url = url.into_url()?;
if url.path() != "/" {
return Err(Error::InvalidUrl("base URL cannot have path".into()));
}
assert!(!url.cannot_be_a_base());
url.path_segments_mut()
.expect("cannot-be-a-base checked to be false")
.push("api");
Ok(Client {
inner: reqwest::Client::new(),
url,
session_id: None,
})
}
pub fn set_session_id(&mut self, session_id: String) {
self.session_id = Some(session_id);
}
pub async fn session_properties(&self) -> Result<SessionPropertiesResponse, reqwest::Error> {
let url = self.api_url(&["session", "properties"]);
self.send_request(self.inner.get(url)).await
}
pub async fn login(&self, request: &LoginRequest) -> Result<LoginResponse, reqwest::Error> {
let url = self.api_url(&["session"]);
self.send_request(self.inner.post(url).json(request)).await
}
pub async fn setup(&self, request: &SetupRequest) -> Result<LoginResponse, reqwest::Error> {
let url = self.api_url(&["setup"]);
self.send_request(self.inner.post(url).json(request)).await
}
pub async fn databases(&self) -> Result<Vec<Database>, reqwest::Error> {
let url = self.api_url(&["database"]);
let res: ListWrapper<_> = self.send_request(self.inner.get(url)).await?;
Ok(res.data)
}
pub async fn database_metadata(&self, id: usize) -> Result<DatabaseMetadata, reqwest::Error> {
let url = self.api_url(&["database", &id.to_string(), "metadata"]);
self.send_request(self.inner.get(url)).await
}
fn api_url(&self, endpoint: &[&str]) -> Url {
let mut url = self.url.clone();
url.path_segments_mut()
.expect("url validated on construction")
.extend(endpoint);
url
}
async fn send_request<T>(&self, mut req: reqwest::RequestBuilder) -> Result<T, reqwest::Error>
where
T: DeserializeOwned,
{
req = req.timeout(Duration::from_secs(5));
if let Some(session_id) = &self.session_id {
req = req.header("X-Metabase-Session", session_id);
}
let res = req.send().await?.error_for_status()?;
res.json().await
}
}
#[derive(Debug)]
pub enum Error {
InvalidUrl(String),
Transport(reqwest::Error),
}
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Error {
Error::Transport(e)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::InvalidUrl(_) => None,
Error::Transport(e) => Some(e),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::InvalidUrl(msg) => write!(f, "invalid url: {}", msg),
Error::Transport(e) => write!(f, "transport: {}", e),
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
struct ListWrapper<T> {
data: Vec<T>,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub struct SessionPropertiesResponse {
pub setup_token: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct SetupRequest {
pub allow_tracking: bool,
pub database: SetupDatabase,
pub token: String,
pub prefs: SetupPrefs,
pub user: SetupUser,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct SetupDatabase {
pub engine: String,
pub name: String,
pub details: SetupDatabaseDetails,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct SetupDatabaseDetails {
pub host: String,
pub port: usize,
pub dbname: String,
pub user: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct SetupPrefs {
pub site_name: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct SetupUser {
pub email: String,
pub first_name: String,
pub last_name: String,
pub password: String,
pub site_name: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct LoginRequest {
pub username: String,
pub password: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct LoginResponse {
pub id: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct Database {
pub name: String,
pub id: usize,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct DatabaseMetadata {
pub tables: Vec<Table>,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct Table {
pub name: String,
pub schema: String,
pub fields: Vec<TableField>,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct TableField {
pub name: String,
pub database_type: String,
pub base_type: String,
pub special_type: Option<String>,
}