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
//! Manage BigQuery table
use log::warn;
use reqwest::Client;

use crate::auth::ServiceAccountAuthenticator;
use crate::error::BQError;
use crate::model::get_iam_policy_request::GetIamPolicyRequest;
use crate::model::policy::Policy;
use crate::model::set_iam_policy_request::SetIamPolicyRequest;
use crate::model::table::Table;
use crate::model::table_list::TableList;
use crate::model::test_iam_permissions_request::TestIamPermissionsRequest;
use crate::model::test_iam_permissions_response::TestIamPermissionsResponse;
use crate::{process_response, urlencode};

/// A table API handler.
#[derive(Clone)]
pub struct TableApi {
    client: Client,
    sa_auth: ServiceAccountAuthenticator,
}

impl TableApi {
    pub(crate) fn new(client: Client, sa_auth: ServiceAccountAuthenticator) -> Self {
        Self { client, sa_auth }
    }

    /// Creates a new, empty table in the dataset.
    /// # Arguments
    /// * table - The request body contains an instance of Table.
    pub async fn create(&self, table: Table) -> Result<Table, BQError> {
        let req_url = &format!(
            "https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}/tables",
            project_id = urlencode(&table.table_reference.project_id),
            dataset_id = urlencode(&table.table_reference.dataset_id)
        );

        let access_token = self.sa_auth.access_token().await?;

        let request = self
            .client
            .post(req_url.as_str())
            .bearer_auth(access_token)
            .json(&table)
            .build()?;

        let response = self.client.execute(request).await?;

        process_response(response).await
    }

    /// Deletes the table specified by tableId from the dataset. If the table contains data, all the data will be deleted.
    /// # Arguments
    /// * project_id - Project ID of the table to delete
    /// * dataset_id - Dataset ID of the table to delete
    /// * table_id - Table ID of the table to delete
    pub async fn delete(&self, project_id: &str, dataset_id: &str, table_id: &str) -> Result<(), BQError> {
        let req_url = &format!(
            "https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}/tables/{table_id}",
            project_id = urlencode(project_id),
            dataset_id = urlencode(dataset_id),
            table_id = urlencode(table_id)
        );

        let access_token = self.sa_auth.access_token().await?;

        let request = self.client.delete(req_url.as_str()).bearer_auth(access_token).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, table_id: &str) -> bool {
        match self.delete(project_id, dataset_id, table_id).await {
            Err(BQError::ResponseError { error }) => {
                if error.error.code != 404 {
                    warn!("table.delete_if_exists: unexpected error: {:?}", error);
                }
                false
            }
            Err(err) => {
                warn!("table.delete_if_exists: unexpected error: {:?}", err);
                false
            }
            Ok(_) => true,
        }
    }

    /// Gets the specified table resource by table ID. This method does not return the data in the table, it only
    /// returns the table resource, which describes the structure of this table.
    /// # Arguments
    /// * project_id - Project ID of the table to delete
    /// * dataset_id - Dataset ID of the table to delete
    /// * table_id - Table ID of the table to delete
    /// * selected_fields - tabledata.list of table schema fields to return (comma-separated). If unspecified, all
    /// fields are returned. A fieldMask cannot be used here because the fields will automatically be converted from
    /// camelCase to snake_case and the conversion will fail if there are underscores. Since these are fields in
    /// BigQuery table schemas, underscores are allowed.
    pub async fn get(
        &self,
        project_id: &str,
        dataset_id: &str,
        table_id: &str,
        selected_fields: Option<Vec<&str>>,
    ) -> Result<Table, BQError> {
        let req_url = &format!(
            "https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}/tables/{table_id}",
            project_id = urlencode(project_id),
            dataset_id = urlencode(dataset_id),
            table_id = urlencode(table_id)
        );

        let access_token = self.sa_auth.access_token().await?;

        let mut request_builder = self.client.get(req_url.as_str()).bearer_auth(access_token);
        if let Some(selected_fields) = selected_fields {
            let selected_fields = selected_fields.join(",");
            request_builder = request_builder.query(&[("selectedFields", selected_fields)]);
        }

        let request = request_builder.build()?;

        let response = self.client.execute(request).await?;

        process_response(response).await
    }

    /// Lists all tables in the specified dataset. Requires the READER dataset role.
    /// # Arguments
    /// * project_id - Project ID of the table to delete
    /// * dataset_id - Dataset ID of the table to delete
    /// * options - Options
    pub async fn list(&self, project_id: &str, dataset_id: &str, options: ListOptions) -> Result<TableList, BQError> {
        let req_url = &format!(
            "https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}/tables",
            project_id = urlencode(project_id),
            dataset_id = urlencode(dataset_id)
        );

        let access_token = self.sa_auth.access_token().await?;

        let mut request = self.client.get(req_url).bearer_auth(access_token);

        // process options
        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)]);
        }

        let request = request.build()?;
        let response = self.client.execute(request).await?;

        process_response(response).await
    }

    /// Updates information in an existing table. The update method replaces the entire table resource, whereas the
    /// patch method only replaces fields that are provided in the submitted table resource. This method supports
    /// RFC5789 patch semantics.
    /// # Arguments
    /// * project_id - Project ID of the table to delete
    /// * dataset_id - Dataset ID of the table to delete
    /// * table_id - Table ID of the table to delete
    /// * table - Table to patch
    pub async fn patch(
        &self,
        project_id: &str,
        dataset_id: &str,
        table_id: &str,
        table: Table,
    ) -> Result<Table, BQError> {
        let req_url = &format!(
            "https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}/tables/{table_id}",
            project_id = urlencode(project_id),
            dataset_id = urlencode(dataset_id),
            table_id = urlencode(table_id)
        );

        let access_token = self.sa_auth.access_token().await?;

        let request = self
            .client
            .patch(req_url)
            .bearer_auth(access_token)
            .json(&table)
            .build()?;
        let response = self.client.execute(request).await?;

        process_response(response).await
    }

    /// Updates information in an existing table. The update method replaces the entire Table resource, whereas the
    /// patch method only replaces fields that are provided in the submitted Table resource.
    /// # Arguments
    /// * project_id - Project ID of the table to delete
    /// * dataset_id - Dataset ID of the table to delete
    /// * table_id - Table ID of the table to delete
    /// * table - Table to update
    pub async fn update(
        &self,
        project_id: &str,
        dataset_id: &str,
        table_id: &str,
        table: Table,
    ) -> Result<Table, BQError> {
        let req_url = &format!(
            "https://bigquery.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}/tables/{table_id}",
            project_id = urlencode(project_id),
            dataset_id = urlencode(dataset_id),
            table_id = urlencode(table_id)
        );

        let access_token = self.sa_auth.access_token().await?;

        let request = self
            .client
            .put(req_url)
            .bearer_auth(access_token)
            .json(&table)
            .build()?;
        let response = self.client.execute(request).await?;

        process_response(response).await
    }

    /// Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have
    /// a policy set.
    /// # Argument
    /// * `resource` - The resource for which the policy is being requested. See the operation documentation for the
    /// appropriate value for this field.
    pub async fn get_iam_policy(
        &self,
        resource: &str,
        get_iam_policy_request: GetIamPolicyRequest,
    ) -> Result<Policy, BQError> {
        let req_url = &format!(
            "https://bigquery.googleapis.com/bigquery/v2/projects/{resource}/:getIamPolicy",
            resource = urlencode(resource)
        );

        let access_token = self.sa_auth.access_token().await?;

        let request = self
            .client
            .post(req_url.as_str())
            .bearer_auth(access_token)
            .json(&get_iam_policy_request)
            .build()?;

        let response = self.client.execute(request).await?;

        process_response(response).await
    }

    /// Sets the access control policy on the specified resource. Replaces any existing policy. Can return `NOT_FOUND`,
    /// `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
    /// # Argument
    /// * `resource` - The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
    pub async fn set_iam_policy(
        &self,
        resource: &str,
        set_iam_policy_request: SetIamPolicyRequest,
    ) -> Result<Policy, BQError> {
        let req_url = &format!(
            "https://bigquery.googleapis.com/bigquery/v2/projects/{resource}/:setIamPolicy",
            resource = urlencode(resource)
        );

        let access_token = self.sa_auth.access_token().await?;

        let request = self
            .client
            .post(req_url.as_str())
            .bearer_auth(access_token)
            .json(&set_iam_policy_request)
            .build()?;

        let response = self.client.execute(request).await?;

        process_response(response).await
    }

    /// Returns permissions that a caller has on the specified resource. If the resource does not exist, this will
    /// return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is designed to be used for
    /// building permission-aware UIs and command-line tools, not for authorization checking. This operation may
    /// \"fail open\" without warning.
    /// # Argument
    /// * `resource` - The resource for which the policy detail is being requested. See the operation documentation for
    /// the appropriate value for this field.
    pub async fn test_iam_permissions(
        &self,
        resource: &str,
        test_iam_permissions_request: TestIamPermissionsRequest,
    ) -> Result<TestIamPermissionsResponse, BQError> {
        let req_url = &format!(
            "https://bigquery.googleapis.com/bigquery/v2/projects/{resource}/:testIamPermissions",
            resource = urlencode(resource)
        );

        let access_token = self.sa_auth.access_token().await?;

        let request = self
            .client
            .post(req_url.as_str())
            .bearer_auth(access_token)
            .json(&test_iam_permissions_request)
            .build()?;

        let response = self.client.execute(request).await?;

        process_response(response).await
    }
}

/// A list of options to use with the table API handler.
#[derive(Default)]
pub struct ListOptions {
    max_results: Option<u64>,
    page_token: Option<String>,
}

impl ListOptions {
    /// The maximum number of results to return in a single response page. Leverage the page tokens to iterate
    /// through the entire collection.
    pub fn max_results(mut self, value: u64) -> Self {
        self.max_results = Some(value);
        self
    }

    /// Page token, returned by a previous call, to request the next page of results
    pub fn page_token(mut self, value: String) -> Self {
        self.page_token = Some(value);
        self
    }
}

#[cfg(test)]
mod test {
    use crate::error::BQError;
    use crate::model::dataset::Dataset;
    use crate::model::field_type::FieldType;
    use crate::model::table::Table;
    use crate::model::table_field_schema::TableFieldSchema;
    use crate::model::table_schema::TableSchema;
    use crate::table::ListOptions;
    use crate::{env_vars, Client};
    use std::time::{Duration, SystemTime};

    #[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!("{}_table", dataset_id);

        let client = Client::from_service_account_key_file(sa_key).await;

        // Delete the dataset if needed
        client.dataset().delete_if_exists(project_id, dataset_id, true).await;

        // Create dataset
        let created_dataset = client.dataset().create(Dataset::new(project_id, dataset_id)).await?;
        assert_eq!(created_dataset.id, Some(format!("{}:{}", project_id, dataset_id)));

        // Create table
        let table = Table::new(
            project_id,
            dataset_id,
            table_id,
            TableSchema::new(vec![
                TableFieldSchema::new("col1", FieldType::String),
                TableFieldSchema::new("col2", FieldType::Int64),
                TableFieldSchema::new("col3", FieldType::Boolean),
                TableFieldSchema::new("col4", FieldType::Datetime),
            ]),
        );
        let created_table = client
            .table()
            .create(
                table
                    .description("A table used for unit tests")
                    .label("owner", "me")
                    .label("env", "prod")
                    .expiration_time(SystemTime::now() + Duration::from_secs(3600)),
            )
            .await?;
        assert_eq!(created_table.table_reference.table_id, table_id.to_string());

        let table = client.table().get(project_id, dataset_id, table_id, None).await?;
        assert_eq!(table.table_reference.table_id, table_id.to_string());

        let table = client.table().update(project_id, dataset_id, table_id, table).await?;
        assert_eq!(table.table_reference.table_id, table_id.to_string());

        let table = client.table().patch(project_id, dataset_id, table_id, table).await?;
        assert_eq!(table.table_reference.table_id, table_id.to_string());

        // List tables
        let tables = client
            .table()
            .list(project_id, dataset_id, ListOptions::default())
            .await?;
        let mut created_table_found = false;
        for table_list_tables in tables.tables.unwrap().iter() {
            if &table_list_tables.table_reference.dataset_id == dataset_id {
                created_table_found = true;
            }
        }
        assert!(created_table_found);

        client.table().delete(project_id, dataset_id, table_id).await?;

        // Delete dataset
        client.dataset().delete(project_id, dataset_id, true).await?;

        Ok(())
    }
}