bigquery 0.5.0

Library provides a simple API for Google BigQuery based on the gRPC Storage Read/Write and v2 APIs
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
425
426
427
428
429
430
//! Running a query and deciding where its rows come from.
//!
//! Every query goes through `JobService.Query` with an Arrow result format. A result that is
//! complete and whole in that first response is decoded from its inline Arrow. Anything else
//! is read from the job's destination table through the Storage Read API, since
//! `GetQueryResults` has no Arrow form and is used only to wait for the job.
//!
//! Job creation is optional unless the caller requires it, so a short query is answered
//! without a job. Whenever the first response leaves anything for a later call, BigQuery has
//! created a job for it, and that job is what the rest of the route reads.

use crate::errors::BigQueryError;
use crate::query::params::parameter_mode;
use crate::read::ArrowIpcDecoder;
use crate::{
    BigQueryDb, BigQueryDryRunResult, BigQueryJobCreation, BigQueryJobRef, BigQueryJobStats,
    BigQueryLocation, BigQueryQueryId, BigQueryQueryOutcome, BigQueryQueryParams,
    BigQueryReadCompression, BigQueryResult, BigQueryStatementType, BigQueryTableRef,
    BigQueryTableSchema,
};
use arrow_array::RecordBatch;
use gcloud_sdk::google::cloud::bigquery::v2::arrow_serialization_options::CompressionCodec;
use gcloud_sdk::google::cloud::bigquery::v2::query_request::{
    JobCreationMode, QueryResultsFormat, ResultsFormatSerializationOptions,
};
use gcloud_sdk::google::cloud::bigquery::v2::query_response::{Results, ResultsSchema};
use gcloud_sdk::google::cloud::bigquery::v2::{
    ArrowSerializationOptions, DataFormatOptions, DatasetReference, GetQueryResultsResponse, Job,
    PostQueryRequest, QueryRequest, QueryResponse,
};
use rand::RngExt;
use std::sync::atomic::{AtomicBool, Ordering};
use tracing::field::Empty;
use tracing::Span;

impl BigQueryQueryParams {
    /// The span of one query terminal call.
    pub(crate) fn span(&self) -> Span {
        tracing::debug_span!(
            "BigQuery Query",
            "/bigquery/sql_len" = self.sql.len(),
            "/bigquery/job_id" = Empty,
            "/bigquery/query_id" = Empty,
            "/bigquery/location" = Empty,
            "/bigquery/statement_type" = Empty,
            "/bigquery/bytes_processed" = Empty,
            "/bigquery/bytes_billed" = Empty,
            "/bigquery/slot_ms" = Empty,
            "/bigquery/cache_hit" = Empty,
            "/bigquery/dml_rows" = Empty,
            "/bigquery/total_rows" = Empty,
            "/bigquery/route" = Empty,
        )
    }
}

impl From<BigQueryReadCompression> for CompressionCodec {
    fn from(compression: BigQueryReadCompression) -> Self {
        match compression {
            BigQueryReadCompression::None => CompressionCodec::CompressionUnspecified,
            BigQueryReadCompression::Lz4 => CompressionCodec::Lz4Frame,
            BigQueryReadCompression::Zstd => CompressionCodec::Zstd,
        }
    }
}

impl From<BigQueryJobCreation> for JobCreationMode {
    fn from(mode: BigQueryJobCreation) -> Self {
        match mode {
            BigQueryJobCreation::Optional => Self::JobCreationOptional,
            BigQueryJobCreation::Required => Self::JobCreationRequired,
        }
    }
}

/// The figures of the `Query` response; a figure it leaves out is filled later from the
/// responses the query goes on to receive.
impl From<&QueryResponse> for BigQueryJobStats {
    fn from(response: &QueryResponse) -> Self {
        let job = response.job_reference.clone().map(|reference| {
            let mut job = BigQueryJobRef::from(reference);
            if job.location.is_none() {
                job.location = BigQueryLocation::reported(response.location.clone());
            }
            job
        });
        Self {
            job,
            query_id: Some(response.query_id.clone())
                .filter(|v| !v.is_empty())
                .map(BigQueryQueryId::reported),
            statement_type: Some(response.statement_type.clone())
                .filter(|v| !v.is_empty())
                .map(Into::into),
            total_rows: response.total_rows,
            total_bytes_processed: response.total_bytes_processed,
            total_bytes_billed: response.total_bytes_billed,
            total_slot_ms: response.total_slot_ms,
            cache_hit: response.cache_hit,
            num_dml_affected_rows: response.num_dml_affected_rows,
            dml_stats: response.dml_stats.map(Into::into),
        }
    }
}

impl BigQueryJobStats {
    /// Fills the figures still missing from the `GetQueryResults` that saw the job complete.
    fn merge_results(&mut self, results: &GetQueryResultsResponse) {
        self.total_rows = self.total_rows.or(results.total_rows);
        self.total_bytes_processed = self.total_bytes_processed.or(results.total_bytes_processed);
        self.cache_hit = self.cache_hit.or(results.cache_hit);
        self.num_dml_affected_rows = self.num_dml_affected_rows.or(results.num_dml_affected_rows);
    }

    /// Fills the figures still missing from the finished job's statistics, the query
    /// statistics before the job-wide ones.
    fn merge_job(&mut self, job: &Job) {
        let Some(statistics) = &job.statistics else {
            return;
        };
        if let Some(query) = &statistics.query {
            self.statement_type = self.statement_type.take().or_else(|| {
                Some(query.statement_type.clone())
                    .filter(|v| !v.is_empty())
                    .map(Into::into)
            });
            self.total_bytes_processed = self.total_bytes_processed.or(query.total_bytes_processed);
            self.total_bytes_billed = self.total_bytes_billed.or(query.total_bytes_billed);
            self.total_slot_ms = self.total_slot_ms.or(query.total_slot_ms);
            self.cache_hit = self.cache_hit.or(query.cache_hit);
            self.num_dml_affected_rows = self.num_dml_affected_rows.or(query.num_dml_affected_rows);
            self.dml_stats = self.dml_stats.or(query.dml_stats.map(Into::into));
        }
        self.total_bytes_processed = self
            .total_bytes_processed
            .or(statistics.total_bytes_processed);
        self.total_slot_ms = self.total_slot_ms.or(statistics.total_slot_ms);
    }

    /// The figures of the first `Query` response, recorded on the query's span. A query that
    /// ran without a job has its location only in the response, not in a job reference.
    fn first_response(response: &QueryResponse, span: &Span) -> Self {
        let stats = Self::from(response);
        stats.record(span);
        if stats.job.is_none() && !response.location.is_empty() {
            span.record("/bigquery/location", response.location.as_str());
        }
        stats
    }

    /// Records the figures known so far on the query's span.
    fn record(&self, span: &Span) {
        if let Some(query_id) = &self.query_id {
            span.record("/bigquery/query_id", query_id.as_str());
        }
        if let Some(job) = &self.job {
            span.record("/bigquery/job_id", job.job_id.as_str());
            if let Some(location) = &job.location {
                span.record("/bigquery/location", location.as_str());
            }
        }
        if let Some(statement_type) = &self.statement_type {
            span.record("/bigquery/statement_type", statement_type.as_str());
        }
        if let Some(bytes) = self.total_bytes_processed {
            span.record("/bigquery/bytes_processed", bytes);
        }
        if let Some(bytes) = self.total_bytes_billed {
            span.record("/bigquery/bytes_billed", bytes);
        }
        if let Some(slot_ms) = self.total_slot_ms {
            span.record("/bigquery/slot_ms", slot_ms);
        }
        if let Some(cache_hit) = self.cache_hit {
            span.record("/bigquery/cache_hit", cache_hit);
        }
        if let Some(rows) = self.num_dml_affected_rows {
            span.record("/bigquery/dml_rows", rows);
        }
        if let Some(rows) = self.total_rows {
            span.record("/bigquery/total_rows", rows);
        }
    }
}

/// What a terminal call asks of the `Query` request.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Purpose {
    /// The rows, inline when they fit.
    Rows,
    /// What the statement did, no rows.
    Execute,
    /// The cost estimate of a dry run.
    DryRun,
}

/// Where the rows of a finished query are.
pub(crate) enum Rows {
    /// The whole result, from the first response.
    Inline(RecordBatch),
    /// The job's destination table, for the Storage Read API.
    Table(BigQueryTableRef),
    /// No rows: a statement with no result, such as DML or DDL, or an empty result.
    None,
}

/// A fresh idempotency key: 128 random bits in hex.
fn random_request_id() -> String {
    format!("{:032x}", rand::rng().random::<u128>())
}

impl BigQueryDb {
    fn query_request(
        &self,
        params: &BigQueryQueryParams,
        purpose: Purpose,
    ) -> BigQueryResult<PostQueryRequest> {
        let project_id = self.options().google_project_id.clone();
        let default_dataset = params.default_dataset.as_ref().map(|d| DatasetReference {
            project_id: d.project_or(&project_id).to_string(),
            dataset_id: d.dataset().to_string(),
        });
        let max_results = match purpose {
            Purpose::Rows => params.inline_rows_limit,
            Purpose::Execute => Some(0),
            Purpose::DryRun => None,
        };
        Ok(PostQueryRequest {
            project_id,
            query_request: Some(QueryRequest {
                query: params.sql.clone(),
                max_results,
                default_dataset,
                timeout_ms: Some(params.timeout_ms()?),
                job_timeout_ms: params.job_timeout_ms()?,
                dry_run: purpose == Purpose::DryRun,
                use_query_cache: params.use_query_cache,
                use_legacy_sql: Some(false),
                parameter_mode: parameter_mode(&params.query_parameters)?.to_string(),
                query_parameters: params.query_parameters.clone(),
                location: params
                    .location
                    .as_ref()
                    .or(self.options().location.as_ref())
                    .map(ToString::to_string)
                    .unwrap_or_default(),
                format_options: Some(DataFormatOptions {
                    use_int64_timestamp: true,
                    ..Default::default()
                }),
                labels: params.labels.clone().into_iter().collect(),
                maximum_bytes_billed: params.maximum_bytes_billed,
                job_creation_mode: JobCreationMode::from(params.job_creation).into(),
                request_id: params
                    .request_id
                    .as_ref()
                    .map_or_else(random_request_id, ToString::to_string),
                query_results_format: QueryResultsFormat::Arrow.into(),
                results_format_serialization_options: Some(
                    ResultsFormatSerializationOptions::ArrowSerializationOptions(
                        ArrowSerializationOptions {
                            buffer_compression: CompressionCodec::from(
                                params.read_options.compression,
                            )
                            .into(),
                            ..Default::default()
                        },
                    ),
                ),
                ..Default::default()
            }),
        })
    }

    /// Sends `Query`. Its retries are safe because every attempt repeats one `request_id`.
    ///
    /// A retry requires a job whatever the first attempt asked for: BigQuery answers a repeated
    /// `request_id` with the job the first attempt created only in that mode, and with
    /// `AlreadyExists` for that job in optional mode.
    async fn post_query(
        &self,
        params: &BigQueryQueryParams,
        purpose: Purpose,
        span: &Span,
    ) -> BigQueryResult<QueryResponse> {
        let request = self.query_request(params, purpose)?;
        let retrying = AtomicBool::new(false);
        self.retry(span, "run a query", &request, |mut r| {
            if retrying.swap(true, Ordering::Relaxed) {
                if let Some(query) = r.get_mut().query_request.as_mut() {
                    query.job_creation_mode = JobCreationMode::JobCreationRequired.into();
                }
            }
            let mut client = self.job_client();
            async move { client.query(r).await }
        })
        .await
    }

    /// Runs the query and finds its rows, with the figures of every response it received.
    pub(crate) async fn query_rows(
        &self,
        params: &BigQueryQueryParams,
        span: &Span,
    ) -> BigQueryResult<(Rows, BigQueryJobStats)> {
        let response = self.post_query(params, Purpose::Rows, span).await?;
        let mut stats = BigQueryJobStats::first_response(&response, span);
        let complete = response.job_complete == Some(true);
        if complete && response.page_token.is_empty() {
            let batch = inline_batch(&response)?;
            let inline_rows = batch.as_ref().map_or(0, |b| b.num_rows() as u64);
            // DML and DDL report no total; a SELECT reports one, and the inline page is the
            // whole result only when it holds that many rows.
            if response.total_rows.is_none_or(|total| total == inline_rows) {
                span.record("/bigquery/route", "inline");
                return Ok((batch.map_or(Rows::None, Rows::Inline), stats));
            }
        }
        let (job, details) = self.finish_job(&mut stats, !complete, params, span).await?;
        let destination = details
            .configuration
            .as_ref()
            .and_then(|c| c.query.as_ref())
            .and_then(|q| q.destination_table.clone());
        match destination {
            Some(table) => {
                span.record("/bigquery/route", "storage_read");
                let table = BigQueryTableRef::try_from(table).map_err(|err| {
                    BigQueryError::system(
                        "INVALID_DESTINATION_TABLE",
                        format!(
                        "The query job {} names a destination table this crate cannot read: {err}",
                        job.job_id
                    ),
                    )
                })?;
                Ok((Rows::Table(table), stats))
            }
            None if stats.statement_type == Some(BigQueryStatementType::Select) => {
                Err(BigQueryError::system(
                    "NO_DESTINATION_TABLE",
                    format!(
                    "The query job {} returned rows but has no destination table to read them from",
                    job.job_id
                ),
                ))
            }
            None => {
                span.record("/bigquery/route", "none");
                Ok((Rows::None, stats))
            }
        }
    }

    /// Runs the statement, waits for it, and reports what it did.
    pub(crate) async fn execute_statement(
        &self,
        params: &BigQueryQueryParams,
        span: &Span,
    ) -> BigQueryResult<BigQueryQueryOutcome> {
        let response = self.post_query(params, Purpose::Execute, span).await?;
        let mut stats = BigQueryJobStats::first_response(&response, span);
        if response.job_complete == Some(true) {
            return Ok(stats);
        }
        self.finish_job(&mut stats, true, params, span).await?;
        Ok(stats)
    }

    /// Waits for the query's job when `wait`, reads the finished job, and fills `stats` from
    /// both. Returns the job and what `GetJob` said of it.
    async fn finish_job(
        &self,
        stats: &mut BigQueryJobStats,
        wait: bool,
        params: &BigQueryQueryParams,
        span: &Span,
    ) -> BigQueryResult<(BigQueryJobRef, Job)> {
        let job = stats
            .job
            .clone()
            .ok_or_else(|| BigQueryError::system("NO_JOB_REFERENCE", MISSING_JOB))?;
        if wait {
            let results = self.wait_for_job(&job, params.timeout_ms()?, span).await?;
            stats.merge_results(&results);
        }
        let details = self.get_query_job(&job, span).await?;
        stats.merge_job(&details);
        stats.record(span);
        Ok((job, details))
    }

    /// Validates the statement and reports its cost without running it.
    pub(crate) async fn dry_run_statement(
        &self,
        params: &BigQueryQueryParams,
        span: &Span,
    ) -> BigQueryResult<BigQueryDryRunResult> {
        let response = self.post_query(params, Purpose::DryRun, span).await?;
        Ok(BigQueryDryRunResult {
            total_bytes_processed: response.total_bytes_processed,
            schema: response
                .schema
                .as_ref()
                .map(BigQueryTableSchema::try_from)
                .transpose()?,
        })
    }
}

/// BigQuery creates a job for any query it cannot answer whole in the first response, so a
/// response that leaves rows or the job's completion to a later call names that job.
const MISSING_JOB: &str = "BigQuery answered a query that is unfinished or only partly inline \
                           without a job reference to read the rest from";

/// The inline Arrow result of a `Query` response, if it carries one.
fn inline_batch(response: &QueryResponse) -> BigQueryResult<Option<RecordBatch>> {
    let (Some(ResultsSchema::ArrowSchema(schema)), Some(Results::ArrowRecordBatch(batch))) =
        (&response.results_schema, &response.results)
    else {
        return Ok(None);
    };
    // A result with no rows comes as the schema and a record batch message of zero bytes.
    if batch.serialized_record_batch.is_empty() {
        return Ok(None);
    }
    ArrowIpcDecoder::new(&schema.serialized_schema)?
        .decode(&batch.serialized_record_batch)
        .map(Some)
}