gcp_bigquery_client/model/
query_response.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
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
use crate::error::BQError;
use crate::model::error_proto::ErrorProto;
use crate::model::get_query_results_response::GetQueryResultsResponse;
use crate::model::job_reference::JobReference;
use crate::model::table_row::TableRow;
use crate::model::table_schema::TableSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QueryResponse {
    /// Whether the query result was fetched from the query cache.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_hit: Option<bool>,
    /// [Output-only] The first errors or warnings encountered during the running of the job. The final message includes the number of errors that caused the process to stop. Errors here do not necessarily mean that the job has completed or was unsuccessful.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub errors: Option<Vec<ErrorProto>>,
    /// Whether the query has completed or not. If rows or totalRows are present, this will always be true. If this is false, totalRows will not be available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub job_complete: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub job_reference: Option<JobReference>,
    /// The resource type.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    /// [Output-only] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub num_dml_affected_rows: Option<String>,
    /// A token used for paging results.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_token: Option<String>,
    /// An object with as many results as can be contained within the maximum permitted reply size. To get any additional rows, you can call GetQueryResults and specify the jobReference returned above.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rows: Option<Vec<TableRow>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schema: Option<TableSchema>,
    /// The total number of bytes processed for this query. If this query was a dry run, this is the number of bytes that would be processed if the query were run.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_bytes_processed: Option<String>,
    /// The total number of rows in the complete query result set, which can be more than the number of rows in this single page of results.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_rows: Option<String>,
}

impl From<GetQueryResultsResponse> for QueryResponse {
    fn from(resp: GetQueryResultsResponse) -> Self {
        Self {
            cache_hit: resp.cache_hit,
            errors: resp.errors,
            job_complete: resp.job_complete,
            job_reference: resp.job_reference,
            kind: resp.kind,
            num_dml_affected_rows: resp.num_dml_affected_rows,
            page_token: resp.page_token,
            rows: resp.rows,
            schema: resp.schema,
            total_bytes_processed: resp.total_bytes_processed,
            total_rows: resp.total_rows,
        }
    }
}

/// Set of rows in response to a SQL query
#[derive(Debug)]
pub struct ResultSet {
    cursor: i64,
    row_count: i64,
    rows: Vec<TableRow>,
    fields: HashMap<String, usize>,
}

impl ResultSet {
    pub fn new_from_query_response(query_response: QueryResponse) -> Self {
        if query_response.job_complete.unwrap_or(false) && query_response.schema.is_some() {
            // rows and tables schema are only present for successfully completed jobs.
            let row_count = query_response.rows.as_ref().map_or(0, Vec::len) as i64;
            let table_schema = query_response.schema.as_ref().expect("Expecting a schema");
            let table_fields = table_schema
                .fields
                .as_ref()
                .expect("Expecting a non empty list of fields");
            let fields: HashMap<String, usize> = table_fields
                .iter()
                .enumerate()
                .map(|(pos, field)| (field.name.clone(), pos))
                .collect();
            let rows = query_response.rows.unwrap_or_default();
            Self {
                cursor: -1,
                row_count,
                rows,
                fields,
            }
        } else {
            Self {
                cursor: -1,
                row_count: 0,
                rows: vec![],
                fields: HashMap::new(),
            }
        }
    }

    pub fn new_from_get_query_results_response(get_query_results_response: GetQueryResultsResponse) -> Self {
        if get_query_results_response.job_complete.unwrap_or(false) && get_query_results_response.schema.is_some() {
            // rows and tables schema are only present for successfully completed jobs.
            let row_count = get_query_results_response.rows.as_ref().map_or(0, Vec::len) as i64;
            let table_schema = get_query_results_response.schema.as_ref().expect("Expecting a schema");
            let table_fields = table_schema
                .fields
                .as_ref()
                .expect("Expecting a non empty list of fields");
            let fields: HashMap<String, usize> = table_fields
                .iter()
                .enumerate()
                .map(|(pos, field)| (field.name.clone(), pos))
                .collect();
            let rows = get_query_results_response.rows.unwrap_or_default();
            Self {
                cursor: -1,
                row_count,
                rows,
                fields,
            }
        } else {
            Self {
                cursor: -1,
                row_count: 0,
                rows: vec![],
                fields: HashMap::new(),
            }
        }
    }

    /// Moves the cursor froward one row from its current position.
    /// A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the
    /// first row the current row; the second call makes the second row the current row, and so on.
    pub fn next_row(&mut self) -> bool {
        if self.cursor == (self.row_count - 1) {
            false
        } else {
            self.cursor += 1;
            true
        }
    }

    /// Total number of rows in this result set.
    pub fn row_count(&self) -> usize {
        self.row_count as usize
    }

    /// List of column names for this result set.
    pub fn column_names(&self) -> Vec<String> {
        self.fields.keys().cloned().collect()
    }

    /// Returns the index for a column name.
    pub fn column_index(&self, column_name: &str) -> Option<&usize> {
        self.fields.get(column_name)
    }

    pub fn get_i64(&self, col_index: usize) -> Result<Option<i64>, BQError> {
        let json_value = self.get_json_value(col_index)?;
        match &json_value {
            None => Ok(None),
            Some(json_value) => match json_value {
                serde_json::Value::Number(value) => Ok(value.as_i64()),
                serde_json::Value::String(value) => match (value.parse::<i64>(), value.parse::<f64>()) {
                    (Ok(v), _) => Ok(Some(v)),
                    (Err(_), Ok(v)) => Ok(Some(v as i64)),
                    _ => Err(BQError::InvalidColumnType {
                        col_index,
                        col_type: ResultSet::json_type(json_value),
                        type_requested: "I64".into(),
                    }),
                },
                _ => Err(BQError::InvalidColumnType {
                    col_index,
                    col_type: ResultSet::json_type(json_value),
                    type_requested: "I64".into(),
                }),
            },
        }
    }

    pub fn get_i64_by_name(&self, col_name: &str) -> Result<Option<i64>, BQError> {
        let col_index = self.fields.get(col_name);
        match col_index {
            None => Err(BQError::InvalidColumnName {
                col_name: col_name.into(),
            }),
            Some(col_index) => self.get_i64(*col_index),
        }
    }

    pub fn get_serde<T>(&self, col_index: usize) -> Result<Option<T>, BQError>
    where
        T: serde::de::DeserializeOwned,
    {
        let json_value = self.get_json_value(col_index)?;
        match json_value {
            None => Ok(None),
            Some(json_value) => match serde_json::from_value::<T>(json_value.clone()) {
                Ok(value) => Ok(Some(value)),
                Err(_) => Err(BQError::InvalidColumnType {
                    col_index,
                    col_type: ResultSet::json_type(&json_value),
                    type_requested: std::any::type_name::<T>().to_string(),
                }),
            },
        }
    }

    pub fn get_serde_by_name<T>(&self, col_name: &str) -> Result<Option<T>, BQError>
    where
        T: serde::de::DeserializeOwned,
    {
        let col_index = self.fields.get(col_name);
        match col_index {
            None => Err(BQError::InvalidColumnName {
                col_name: col_name.into(),
            }),
            Some(col_index) => self.get_serde(*col_index),
        }
    }

    pub fn get_f64(&self, col_index: usize) -> Result<Option<f64>, BQError> {
        let json_value = self.get_json_value(col_index)?;
        match &json_value {
            None => Ok(None),
            Some(json_value) => match json_value {
                serde_json::Value::Number(value) => Ok(value.as_f64()),
                serde_json::Value::String(value) => {
                    let value: Result<f64, _> = value.parse();
                    match &value {
                        Err(_) => Err(BQError::InvalidColumnType {
                            col_index,
                            col_type: ResultSet::json_type(json_value),
                            type_requested: "F64".into(),
                        }),
                        Ok(value) => Ok(Some(*value)),
                    }
                }
                _ => Err(BQError::InvalidColumnType {
                    col_index,
                    col_type: ResultSet::json_type(json_value),
                    type_requested: "F64".into(),
                }),
            },
        }
    }

    pub fn get_f64_by_name(&self, col_name: &str) -> Result<Option<f64>, BQError> {
        let col_index = self.fields.get(col_name);
        match col_index {
            None => Err(BQError::InvalidColumnName {
                col_name: col_name.into(),
            }),
            Some(col_index) => self.get_f64(*col_index),
        }
    }

    pub fn get_bool(&self, col_index: usize) -> Result<Option<bool>, BQError> {
        let json_value = self.get_json_value(col_index)?;
        match &json_value {
            None => Ok(None),
            Some(json_value) => match json_value {
                serde_json::Value::Bool(value) => Ok(Some(*value)),
                serde_json::Value::String(value) => {
                    let value: Result<bool, _> = value.parse();
                    match &value {
                        Err(_) => Err(BQError::InvalidColumnType {
                            col_index,
                            col_type: ResultSet::json_type(json_value),
                            type_requested: "Bool".into(),
                        }),
                        Ok(value) => Ok(Some(*value)),
                    }
                }
                _ => Err(BQError::InvalidColumnType {
                    col_index,
                    col_type: ResultSet::json_type(json_value),
                    type_requested: "Bool".into(),
                }),
            },
        }
    }

    pub fn get_bool_by_name(&self, col_name: &str) -> Result<Option<bool>, BQError> {
        let col_index = self.fields.get(col_name);
        match col_index {
            None => Err(BQError::InvalidColumnName {
                col_name: col_name.into(),
            }),
            Some(col_index) => self.get_bool(*col_index),
        }
    }

    pub fn get_string(&self, col_index: usize) -> Result<Option<String>, BQError> {
        let json_value = self.get_json_value(col_index)?;
        match json_value {
            None => Ok(None),
            Some(json_value) => match json_value {
                serde_json::Value::String(value) => Ok(Some(value)),
                serde_json::Value::Number(value) => Ok(Some(value.to_string())),
                serde_json::Value::Bool(value) => Ok(Some(value.to_string())),
                _ => Err(BQError::InvalidColumnType {
                    col_index,
                    col_type: ResultSet::json_type(&json_value),
                    type_requested: "String".into(),
                }),
            },
        }
    }

    pub fn get_string_by_name(&self, col_name: &str) -> Result<Option<String>, BQError> {
        let col_index = self.fields.get(col_name);
        match col_index {
            None => Err(BQError::InvalidColumnName {
                col_name: col_name.into(),
            }),
            Some(col_index) => self.get_string(*col_index),
        }
    }

    pub fn get_json_value(&self, col_index: usize) -> Result<Option<serde_json::Value>, BQError> {
        if self.cursor < 0 || self.cursor == self.row_count {
            return Err(BQError::NoDataAvailable);
        }
        if col_index >= self.fields.len() {
            return Err(BQError::InvalidColumnIndex { col_index });
        }

        Ok(self
            .rows
            .get(self.cursor as usize)
            .and_then(|row| row.columns.as_ref())
            .and_then(|cols| cols.get(col_index))
            .and_then(|col| col.value.clone()))
    }

    pub fn get_json_value_by_name(&self, col_name: &str) -> Result<Option<serde_json::Value>, BQError> {
        let col_pos = self.fields.get(col_name);
        match col_pos {
            None => Err(BQError::InvalidColumnName {
                col_name: col_name.into(),
            }),
            Some(col_pos) => self.get_json_value(*col_pos),
        }
    }

    fn json_type(json_value: &serde_json::Value) -> String {
        match json_value {
            Value::Null => "Null".into(),
            Value::Bool(_) => "Bool".into(),
            Value::Number(_) => "Number".into(),
            Value::String(_) => "String".into(),
            Value::Array(_) => "Array".into(),
            Value::Object(_) => "Object".into(),
        }
    }
}