gcp_bigquery_client/
routine.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
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
//! Manage BigQuery user-defined function or a stored procedure.
use std::sync::Arc;

use reqwest::Client;

use crate::auth::Authenticator;
use crate::error::BQError;
use crate::model::list_routines_response::ListRoutinesResponse;
use crate::model::routine::Routine;
use crate::{process_response, urlencode, BIG_QUERY_V2_URL};

/// A routine API handler.
#[derive(Clone)]
pub struct RoutineApi {
    client: Client,
    auth: Arc<dyn Authenticator>,
    base_url: String,
}

impl RoutineApi {
    pub(crate) fn new(client: Client, auth: Arc<dyn Authenticator>) -> Self {
        Self {
            client,
            auth,
            base_url: BIG_QUERY_V2_URL.to_string(),
        }
    }

    pub(crate) fn with_base_url(&mut self, base_url: String) -> &mut Self {
        self.base_url = base_url;
        self
    }

    /// Creates a new routine in the dataset.
    /// # Arguments
    /// * `project_id` - Project ID of the new routine.
    /// * `dataset_id` - Dataset ID of the new routine.
    /// * `routine` - The request body contains an instance of Routine.
    pub async fn insert(&self, project_id: &str, dataset_id: &str, routine: Routine) -> Result<Routine, BQError> {
        let req_url = format!(
            "{base_url}/projects/{project_id}/datasets/{dataset_id}/routines",
            base_url = self.base_url,
            project_id = urlencode(project_id),
            dataset_id = urlencode(dataset_id),
        );

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

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

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

        process_response(resp).await
    }

    /// Lists all routines in the specified dataset. Requires the READER dataset role.
    /// # Arguments
    /// * `project_id` - Project ID of the routines to list.
    /// * `dataset_id` - Dataset ID of the routines to list.
    pub async fn list(
        &self,
        project_id: &str,
        dataset_id: &str,
        options: ListOptions,
    ) -> Result<ListRoutinesResponse, BQError> {
        let req_url = format!(
            "{base_url}/projects/{project_id}/datasets/{dataset_id}/routines",
            base_url = self.base_url,
            project_id = urlencode(project_id),
            dataset_id = urlencode(dataset_id),
        );

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

        let request = self
            .client
            .get(req_url.as_str())
            .bearer_auth(access_token)
            .query(&options)
            .build()?;

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

        process_response(resp).await
    }

    /// Deletes the routine specified by routineId from the dataset.
    /// # Arguments
    /// * `project_id`- Project ID of the routine to delete
    /// * `dataset_id` - Dataset ID of the routine to delete
    /// * `routine_id` - Routine ID of the routine to delete
    pub async fn delete(&self, project_id: &str, dataset_id: &str, routine_id: &str) -> Result<(), BQError> {
        let req_url = &format!(
            "{base_url}/projects/{project_id}/datasets/{dataset_id}/routines/{routine_id}",
            base_url = self.base_url,
            project_id = urlencode(project_id),
            dataset_id = urlencode(dataset_id),
            routine_id = urlencode(routine_id),
        );

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

        let request = self.client.delete(req_url).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?,
            })
        }
    }

    /// Gets the specified routine resource by routine ID.
    /// # Arguments
    /// * `project_id`- Project ID of the requested routine
    /// * `dataset_id` - Dataset ID of the requested routine
    /// * `routine_id` - Routine ID of the requested routine
    pub async fn get(&self, project_id: &str, dataset_id: &str, routine_id: &str) -> Result<Routine, BQError> {
        let req_url = &format!(
            "{base_url}/projects/{project_id}/datasets/{dataset_id}/routines/{routine_id}",
            base_url = self.base_url,
            project_id = urlencode(project_id),
            dataset_id = urlencode(dataset_id),
            routine_id = urlencode(routine_id),
        );

        let access_token = self.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
    }

    /// Updates information in an existing routine. The update method replaces the entire Routine
    /// resource.
    /// # Arguments
    /// * `project_id`- Project ID of the routine to update
    /// * `dataset_id` - Dataset ID of the routine to update
    /// * `routine_id` - Routine ID of the routine to update
    /// * `routine` - Routine to update
    pub async fn update(
        &self,
        project_id: &str,
        dataset_id: &str,
        routine_id: &str,
        routine: Routine,
    ) -> Result<Routine, BQError> {
        let req_url = &format!(
            "{base_url}/projects/{project_id}/datasets/{dataset_id}/routines/{routine_id}",
            base_url = self.base_url,
            project_id = urlencode(project_id),
            dataset_id = urlencode(dataset_id),
            routine_id = urlencode(routine_id),
        );

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

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

        process_response(response).await
    }
}

#[derive(Debug, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ListOptions {
    max_results: Option<u64>,
    page_token: Option<String>,
    read_mask: Option<String>,
    filter: 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
    }

    /// If set, then only the Routine fields in the field mask, as well as projectId, datasetId and
    /// routineId, are returned in the response. If unset, then the following Routine fields are
    /// returned: etag, projectId, datasetId, routineId, routineType, creationTime,
    /// lastModifiedTime, and language.
    ///
    /// A comma-separated list of fully qualified names of fields. Example: "user.displayName,photo".
    pub fn read_mask(mut self, value: String) -> Self {
        self.read_mask = Some(value);
        self
    }

    /// If set, then only the Routines matching this filter are returned. The current supported form
    /// is either "routineType:" or "routineType:", where is a RoutineType enum.
    /// Example: "routineType:SCALAR_FUNCTION".
    pub fn filter(mut self, value: String) -> Self {
        self.filter = Some(value);
        self
    }
}