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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use log::warn;
use reqwest::Client;
use crate::auth::ServiceAccountAuthenticator;
use crate::error::BQError;
use crate::model::dataset::Dataset;
use crate::model::datasets::Datasets;
use crate::model::information_schema::schemata::Schemata;
use crate::model::query_request::QueryRequest;
use crate::model::query_response::{QueryResponse, ResultSet};
use crate::{process_response, urlencode};
#[derive(Clone)]
pub struct DatasetApi {
client: Client,
sa_auth: ServiceAccountAuthenticator,
}
impl DatasetApi {
pub(crate) fn new(client: Client, sa_auth: ServiceAccountAuthenticator) -> Self {
Self { client, sa_auth }
}
pub async fn create(&self, dataset: Dataset) -> Result<Dataset, BQError> {
let req_url = &format!(
"https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/datasets",
project_id = urlencode(&dataset.dataset_reference.project_id)
);
let access_token = self.sa_auth.access_token().await?;
let request = self
.client
.post(req_url.as_str())
.bearer_auth(access_token)
.json(&dataset)
.build()?;
let response = self.client.execute(request).await?;
process_response(response).await
}
pub async fn list(&self, project_id: &str, options: ListOptions) -> Result<Datasets, BQError> {
let req_url = &format!(
"https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/datasets",
project_id = urlencode(project_id)
);
let access_token = self.sa_auth.access_token().await?;
let mut request = self.client.get(req_url).bearer_auth(access_token);
if let Some(max_results) = options.max_results {
request = request.query(&[("maxResults", max_results.to_string())]);
}
if let Some(page_token) = options.page_token {
request = request.query(&[("pageToken", page_token)]);
}
if let Some(all) = options.all {
request = request.query(&[("all", all.to_string())]);
}
if let Some(filter) = options.filter {
request = request.query(&[("filter", filter)]);
}
let request = request.build()?;
let response = self.client.execute(request).await?;
process_response(response).await
}
pub async fn delete(&self, project_id: &str, dataset_id: &str, delete_contents: bool) -> Result<(), BQError> {
let req_url = &format!(
"https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}",
project_id = urlencode(project_id),
dataset_id = urlencode(dataset_id)
);
let access_token = self.sa_auth.access_token().await?;
let request = self
.client
.delete(req_url)
.bearer_auth(access_token)
.query(&[("deleteContents", delete_contents.to_string())])
.build()?;
let response = self.client.execute(request).await?;
if response.status().is_success() {
Ok(())
} else {
Err(BQError::ResponseError {
error: response.json().await?,
})
}
}
pub async fn delete_if_exists(&self, project_id: &str, dataset_id: &str, delete_contents: bool) -> bool {
match self.delete(project_id, dataset_id, delete_contents).await {
Err(BQError::ResponseError { error }) => {
if error.error.code != 404 {
warn!("dataset.delete_if_exists: unexpected error: {:?}", error);
}
false
}
Err(err) => {
warn!("dataset.delete_if_exists: unexpected error: {:?}", err);
false
}
Ok(_) => true,
}
}
pub async fn get(&self, project_id: &str, dataset_id: &str) -> Result<Dataset, BQError> {
let req_url = &format!(
"https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}",
project_id = urlencode(project_id),
dataset_id = urlencode(dataset_id)
);
let access_token = self.sa_auth.access_token().await?;
let request = self.client.get(req_url).bearer_auth(access_token).build()?;
let response = self.client.execute(request).await?;
process_response(response).await
}
pub async fn patch(&self, project_id: &str, dataset_id: &str, dataset: Dataset) -> Result<Dataset, BQError> {
let req_url = &format!(
"https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}",
project_id = urlencode(project_id),
dataset_id = urlencode(dataset_id)
);
let access_token = self.sa_auth.access_token().await?;
let request = self
.client
.patch(req_url)
.bearer_auth(access_token)
.json(&dataset)
.build()?;
let response = self.client.execute(request).await?;
process_response(response).await
}
pub async fn update(&self, project_id: &str, dataset_id: &str, dataset: Dataset) -> Result<Dataset, BQError> {
let req_url = &format!(
"https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}",
project_id = urlencode(project_id),
dataset_id = urlencode(dataset_id)
);
let access_token = self.sa_auth.access_token().await?;
let request = self
.client
.put(req_url)
.bearer_auth(access_token)
.json(&dataset)
.build()?;
let response = self.client.execute(request).await?;
process_response(response).await
}
pub async fn information_schema_schemata(&self, project_id: &str, region: &str) -> Result<Vec<Schemata>, BQError> {
let req_url = format!(
"https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/queries",
project_id = urlencode(project_id)
);
let access_token = self.sa_auth.access_token().await?;
let query_request = QueryRequest::new(format!("SELECT * FROM {}.INFORMATION_SCHEMA.SCHEMATA", region));
let request = self
.client
.post(req_url.as_str())
.bearer_auth(access_token)
.json(&query_request)
.build()?;
let resp = self.client.execute(request).await?;
let query_response: QueryResponse = process_response(resp).await?;
let mut rs = ResultSet::new(query_response);
let mut result = vec![];
let catalog_name_pos = *rs
.column_index("catalog_name")
.expect("The catalog_name column is expected");
let schema_name_pos = *rs
.column_index("schema_name")
.expect("The schema_name column is expected");
let schema_owner_pos = *rs
.column_index("schema_owner")
.expect("The schema_owner column is expected");
let creation_time_pos = *rs
.column_index("creation_time")
.expect("The creation_time column is expected");
let last_modified_time_pos = *rs
.column_index("last_modified_time")
.expect("The last_modified_time column is expected");
let location_pos = *rs.column_index("location").expect("The location column is expected");
while rs.next_row() {
result.push(Schemata {
catalog_name: rs.get_string(catalog_name_pos)?.expect("A catalog name is expected"),
schema_name: rs.get_string(schema_name_pos)?.expect("A schema_name is expected"),
schema_owner: rs.get_string(schema_owner_pos)?,
creation_time: rs.get_string(creation_time_pos)?.expect("A creation_time is expected"),
last_modified_time: rs
.get_string(last_modified_time_pos)?
.expect("A last_modified_time is expected"),
location: rs.get_string(location_pos)?.expect("A location is expected"),
});
}
Ok(result)
}
}
#[derive(Default)]
pub struct ListOptions {
max_results: Option<u64>,
page_token: Option<String>,
all: Option<bool>,
filter: Option<String>,
}
impl ListOptions {
pub fn max_results(mut self, value: u64) -> Self {
self.max_results = Some(value);
self
}
pub fn page_token(mut self, value: String) -> Self {
self.page_token = Some(value);
self
}
pub fn all(mut self, value: bool) -> Self {
self.all = Some(value);
self
}
pub fn filter(mut self, value: String) -> Self {
self.filter = Some(value);
self
}
}
#[cfg(test)]
mod test {
use crate::dataset::ListOptions;
use crate::error::BQError;
use crate::model::dataset::Dataset;
use crate::{env_vars, Client};
#[tokio::test]
async fn test() -> Result<(), BQError> {
let (ref project_id, ref dataset_id, ref _table_id, ref sa_key) = env_vars();
let dataset_id = &format!("{}_dataset", dataset_id);
let client = Client::from_service_account_key_file(sa_key).await;
let result = client.dataset().delete(project_id, dataset_id, true).await;
if let Ok(_) = result {
println!("Removed previous dataset '{}'", dataset_id);
}
let created_dataset = client
.dataset()
.create(
Dataset::new(project_id, dataset_id)
.friendly_name("A dataset used for unit tests")
.location("US")
.label("owner", "me")
.label("env", "prod"),
)
.await?;
assert_eq!(created_dataset.id, Some(format!("{}:{}", project_id, dataset_id)));
let dataset = client.dataset().get(project_id, dataset_id).await?;
assert_eq!(dataset.id, Some(format!("{}:{}", project_id, dataset_id)));
let dataset = client.dataset().patch(project_id, dataset_id, dataset).await?;
assert_eq!(dataset.id, Some(format!("{}:{}", project_id, dataset_id)));
let dataset = client.dataset().update(project_id, dataset_id, dataset).await?;
assert_eq!(dataset.id, Some(format!("{}:{}", project_id, dataset_id)));
let datasets = client
.dataset()
.list(project_id, ListOptions::default().all(true))
.await?;
let mut created_dataset_found = false;
for dataset in datasets.datasets.iter() {
if dataset.dataset_reference.dataset_id == *dataset_id {
created_dataset_found = true;
}
}
assert!(created_dataset_found);
client.dataset().delete(project_id, dataset_id, true).await?;
Ok(())
}
#[tokio::test]
async fn test_information_schema() -> Result<(), BQError> {
let (ref project_id, ref _dataset_id, ref _table_id, ref sa_key) = env_vars();
let client = Client::from_service_account_key_file(sa_key).await;
let result = client
.dataset()
.information_schema_schemata(project_id, "region-us")
.await?;
dbg!(result);
Ok(())
}
}