nu_plugin_bigquery 0.2.0

A Nushell plugin for querying Google BigQuery
Documentation
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
#![allow(dead_code)] // API response fields are deserialized from JSON; not all are read directly

use google_cloud_auth::credentials::AccessTokenCredentials;
use nu_protocol::LabeledError;
use reqwest::Client;
use serde::{Deserialize, Serialize};

use crate::auth;

const BQ_BASE_URL: &str = "https://bigquery.googleapis.com/bigquery/v2";

/// BigQuery REST API client.
pub struct BigQueryClient {
    http: Client,
    provider: AccessTokenCredentials,
    project: String,
}

impl BigQueryClient {
    pub fn new(provider: AccessTokenCredentials, project: String) -> Self {
        let http = Client::builder()
            .connect_timeout(std::time::Duration::from_secs(30))
            .timeout(std::time::Duration::from_secs(300))
            .build()
            .unwrap_or_else(|_| Client::new());
        Self {
            http,
            provider,
            project,
        }
    }

    pub fn project(&self) -> &str {
        &self.project
    }

    async fn bearer_token(&self) -> Result<String, LabeledError> {
        auth::get_token(&self.provider).await
    }

    /// Execute a SQL query and return the full response including schema.
    pub async fn query(
        &self,
        sql: &str,
        location: Option<&str>,
        max_results: Option<u64>,
        dry_run: bool,
        timeout_ms: Option<u64>,
    ) -> Result<QueryResponse, LabeledError> {
        let token = self.bearer_token().await?;
        let url = format!("{}/projects/{}/queries", BQ_BASE_URL, self.project);

        let request = QueryRequest {
            query: sql.to_string(),
            use_legacy_sql: false,
            location: location.map(String::from),
            max_results,
            dry_run: if dry_run { Some(true) } else { None },
            timeout_ms,
        };

        let resp = self
            .http
            .post(&url)
            .bearer_auth(&token)
            .json(&request)
            .send()
            .await
            .map_err(|e| {
                LabeledError::new("BigQuery request failed").with_help(format!("HTTP error: {e}"))
            })?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(parse_bq_error(status.as_u16(), &body));
        }

        resp.json::<QueryResponse>().await.map_err(|e| {
            LabeledError::new("Failed to parse BigQuery response")
                .with_help(format!("JSON parse error: {e}"))
        })
    }

    /// Get remaining results for a query job (pagination).
    pub async fn get_query_results(
        &self,
        job_id: &str,
        location: Option<&str>,
        page_token: Option<&str>,
        max_results: Option<u64>,
    ) -> Result<GetQueryResultsResponse, LabeledError> {
        let token = self.bearer_token().await?;
        let url = format!(
            "{}/projects/{}/queries/{}",
            BQ_BASE_URL, self.project, job_id
        );

        let mut params: Vec<(&str, String)> = Vec::new();
        if let Some(loc) = location {
            params.push(("location", loc.to_string()));
        }
        if let Some(pt) = page_token {
            params.push(("pageToken", pt.to_string()));
        }
        if let Some(mr) = max_results {
            params.push(("maxResults", mr.to_string()));
        }

        let resp = self
            .http
            .get(&url)
            .bearer_auth(&token)
            .query(&params)
            .send()
            .await
            .map_err(|e| {
                LabeledError::new("BigQuery request failed").with_help(format!("HTTP error: {e}"))
            })?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(parse_bq_error(status.as_u16(), &body));
        }

        resp.json::<GetQueryResultsResponse>().await.map_err(|e| {
            LabeledError::new("Failed to parse BigQuery response")
                .with_help(format!("JSON parse error: {e}"))
        })
    }

    /// List datasets in the project.
    pub async fn list_datasets(&self) -> Result<DatasetListResponse, LabeledError> {
        let token = self.bearer_token().await?;
        let url = format!("{}/projects/{}/datasets", BQ_BASE_URL, self.project);

        let resp = self
            .http
            .get(&url)
            .bearer_auth(&token)
            .send()
            .await
            .map_err(|e| {
                LabeledError::new("BigQuery request failed").with_help(format!("HTTP error: {e}"))
            })?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(parse_bq_error(status.as_u16(), &body));
        }

        resp.json::<DatasetListResponse>().await.map_err(|e| {
            LabeledError::new("Failed to parse BigQuery response")
                .with_help(format!("JSON parse error: {e}"))
        })
    }

    /// List tables in a dataset.
    pub async fn list_tables(&self, dataset_id: &str) -> Result<TableListResponse, LabeledError> {
        let token = self.bearer_token().await?;
        let url = format!(
            "{}/projects/{}/datasets/{}/tables",
            BQ_BASE_URL, self.project, dataset_id
        );

        let resp = self
            .http
            .get(&url)
            .bearer_auth(&token)
            .send()
            .await
            .map_err(|e| {
                LabeledError::new("BigQuery request failed").with_help(format!("HTTP error: {e}"))
            })?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(parse_bq_error(status.as_u16(), &body));
        }

        resp.json::<TableListResponse>().await.map_err(|e| {
            LabeledError::new("Failed to parse BigQuery response")
                .with_help(format!("JSON parse error: {e}"))
        })
    }

    /// Get table metadata (including schema).
    pub async fn get_table(
        &self,
        dataset_id: &str,
        table_id: &str,
    ) -> Result<TableResource, LabeledError> {
        let token = self.bearer_token().await?;
        let url = format!(
            "{}/projects/{}/datasets/{}/tables/{}",
            BQ_BASE_URL, self.project, dataset_id, table_id
        );

        let resp = self
            .http
            .get(&url)
            .bearer_auth(&token)
            .send()
            .await
            .map_err(|e| {
                LabeledError::new("BigQuery request failed").with_help(format!("HTTP error: {e}"))
            })?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(parse_bq_error(status.as_u16(), &body));
        }

        resp.json::<TableResource>().await.map_err(|e| {
            LabeledError::new("Failed to parse BigQuery response")
                .with_help(format!("JSON parse error: {e}"))
        })
    }
}

fn parse_bq_error(status: u16, body: &str) -> LabeledError {
    if let Ok(err_resp) = serde_json::from_str::<ErrorResponse>(body)
        && let Some(err) = err_resp.error
    {
        let msg = format!("BigQuery API error ({}): {}", err.code, err.message);
        let mut labeled = LabeledError::new(msg);
        if let Some(errors) = err.errors {
            let details: Vec<String> = errors
                .iter()
                .map(|e| {
                    format!(
                        "- {}: {}",
                        e.reason.as_deref().unwrap_or("unknown"),
                        e.message.as_deref().unwrap_or("")
                    )
                })
                .collect();
            if !details.is_empty() {
                labeled = labeled.with_help(details.join("\n"));
            }
        }
        return labeled;
    }
    LabeledError::new(format!("BigQuery API error (HTTP {status})"))
        .with_help(body.chars().take(500).collect::<String>())
}

// --- API request/response types ---

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct QueryRequest {
    query: String,
    use_legacy_sql: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    location: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_results: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    dry_run: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    timeout_ms: Option<u64>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct QueryResponse {
    pub schema: Option<TableSchema>,
    pub rows: Option<Vec<TableRow>>,
    pub total_rows: Option<String>,
    pub total_bytes_processed: Option<String>,
    pub job_complete: Option<bool>,
    pub job_reference: Option<JobReference>,
    pub page_token: Option<String>,
    pub cache_hit: Option<bool>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GetQueryResultsResponse {
    pub schema: Option<TableSchema>,
    pub rows: Option<Vec<TableRow>>,
    pub total_rows: Option<String>,
    pub page_token: Option<String>,
    pub job_complete: Option<bool>,
}

#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct TableSchema {
    pub fields: Option<Vec<TableFieldSchema>>,
}

#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct TableFieldSchema {
    pub name: Option<String>,
    pub r#type: Option<String>,
    pub mode: Option<String>,
    pub description: Option<String>,
    pub fields: Option<Vec<TableFieldSchema>>,
}

#[derive(Deserialize, Debug)]
pub struct TableRow {
    pub f: Option<Vec<TableCell>>,
}

#[derive(Deserialize, Debug)]
pub struct TableCell {
    pub v: Option<serde_json::Value>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct JobReference {
    pub project_id: Option<String>,
    pub job_id: Option<String>,
    pub location: Option<String>,
}

// --- Dataset list types ---

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DatasetListResponse {
    pub datasets: Option<Vec<DatasetListItem>>,
    pub next_page_token: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DatasetListItem {
    pub dataset_reference: Option<DatasetReference>,
    pub friendly_name: Option<String>,
    pub id: Option<String>,
    pub location: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DatasetReference {
    pub dataset_id: Option<String>,
    pub project_id: Option<String>,
}

// --- Table list types ---

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct TableListResponse {
    pub tables: Option<Vec<TableListItem>>,
    pub next_page_token: Option<String>,
    pub total_items: Option<i64>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct TableListItem {
    pub table_reference: Option<TableReference>,
    pub friendly_name: Option<String>,
    pub id: Option<String>,
    pub r#type: Option<String>,
    pub creation_time: Option<String>,
    pub expiration_time: Option<String>,
    // Note: tables.list returns row/byte counts in a nested "view" in some API versions,
    // but the standard response doesn't include them directly. We fetch via get_table if needed.
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct TableReference {
    pub project_id: Option<String>,
    pub dataset_id: Option<String>,
    pub table_id: Option<String>,
}

// --- Table resource (for schema) ---

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct TableResource {
    pub table_reference: Option<TableReference>,
    pub schema: Option<TableSchema>,
    pub num_rows: Option<String>,
    pub num_bytes: Option<String>,
    pub creation_time: Option<String>,
    pub last_modified_time: Option<String>,
    pub r#type: Option<String>,
    pub description: Option<String>,
}

// --- Error response ---

#[derive(Deserialize)]
struct ErrorResponse {
    error: Option<BqApiError>,
}

#[derive(Deserialize)]
struct BqApiError {
    code: u16,
    message: String,
    errors: Option<Vec<BqApiErrorDetail>>,
}

#[derive(Deserialize)]
struct BqApiErrorDetail {
    reason: Option<String>,
    message: Option<String>,
}

impl BigQueryClient {
    pub async fn create_storage_client(
        &self,
    ) -> Result<crate::grpc_client::StorageClient, LabeledError> {
        let token = self.bearer_token().await?;
        crate::grpc_client::create_storage_client(token).await
    }
}