bigquery 0.10.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! 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.
//!
//! A query with a caller's destination table cannot go through `Query`, whose request has no
//! destination. It is inserted as a job with `InsertJob`, waited for like any other job, and
//! its rows are always read from that table through the Storage Read API.

use crate::errors::BigQueryError;
use crate::query::params::parameter_mode;
use crate::read::ArrowIpcDecoder;
use crate::{
    BigQueryDb, BigQueryDryRunResult, BigQueryJobCreation, BigQueryJobId, BigQueryJobRef,
    BigQueryJobStats, BigQueryLocation, BigQueryQueryDestination, 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,
    InsertJobRequest, Job, JobConfiguration, JobConfigurationQuery, JobReference, PostQueryRequest,
    QueryRequest, QueryResponse,
};
use gcloud_sdk::tonic::{Code, Response};
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 BigQueryQueryParams {
    /// The dataset unqualified table names resolve in, with `project_id` for an unset project.
    fn default_dataset_reference(&self, project_id: &str) -> Option<DatasetReference> {
        self.default_dataset.as_ref().map(|d| DatasetReference {
            project_id: d.project_or(project_id).to_string(),
            dataset_id: d.dataset().to_string(),
        })
    }
}

impl BigQueryDb {
    /// Where the query's job runs: its own location, else the client's, else BigQuery's
    /// choice.
    fn query_location(&self, params: &BigQueryQueryParams) -> Option<String> {
        params
            .location
            .as_ref()
            .or(self.options().location.as_ref())
            .map(ToString::to_string)
    }

    /// The `InsertJob` request of a query that writes into `destination`, with a fresh job ID.
    fn query_job_request(
        &self,
        params: &BigQueryQueryParams,
        destination: &BigQueryQueryDestination,
        dry_run: bool,
    ) -> BigQueryResult<InsertJobRequest> {
        let project_id = self.options().google_project_id.clone();
        let query = JobConfigurationQuery {
            query: params.sql.clone(),
            destination_table: Some(destination.table.table_reference(&project_id)),
            create_disposition: "CREATE_IF_NEEDED".to_string(),
            write_disposition: destination.write.disposition().to_string(),
            default_dataset: params.default_dataset_reference(&project_id),
            use_query_cache: params.use_query_cache,
            maximum_bytes_billed: params.maximum_bytes_billed,
            use_legacy_sql: Some(false),
            parameter_mode: parameter_mode(&params.query_parameters)?.to_string(),
            query_parameters: params.query_parameters.clone(),
            ..Default::default()
        };
        Ok(InsertJobRequest {
            project_id: project_id.clone(),
            job: Some(Job {
                job_reference: Some(JobReference {
                    project_id,
                    job_id: BigQueryJobId::random().to_string(),
                    location: self.query_location(params),
                }),
                configuration: Some(JobConfiguration {
                    query: Some(query),
                    dry_run: Some(dry_run),
                    job_timeout_ms: params.job_timeout_ms()?,
                    labels: params.labels.clone().into_iter().collect(),
                    ..Default::default()
                }),
                ..Default::default()
            }),
        })
    }

    /// Sends `InsertJob` for a query into `destination`. Every retry repeats the job ID, so
    /// `AlreadyExists` for that job on a retry means an earlier attempt created it, and that
    /// job is the one returned.
    async fn insert_query_job(
        &self,
        params: &BigQueryQueryParams,
        destination: &BigQueryQueryDestination,
        dry_run: bool,
        span: &Span,
    ) -> BigQueryResult<Job> {
        let request = self.query_job_request(params, destination, dry_run)?;
        let sent = request
            .job
            .as_ref()
            .and_then(|job| job.job_reference.clone());
        let retrying = AtomicBool::new(false);
        self.retry(span, "insert a query job", &request, |r| {
            let retry = retrying.swap(true, Ordering::Relaxed);
            let sent = sent.clone();
            let mut client = self.job_client();
            async move {
                match client.insert_job(r).await {
                    Err(status) if retry && status.code() == Code::AlreadyExists => {
                        match sent.and_then(|job| earlier_attempt_job(job, status.message())) {
                            Some(job) => Ok(Response::new(Job {
                                job_reference: Some(job),
                                ..Default::default()
                            })),
                            None => Err(status),
                        }
                    }
                    other => other,
                }
            }
        })
        .await
    }

    /// Inserts the job of a query into `destination` and waits for it to finish.
    async fn run_query_job(
        &self,
        params: &BigQueryQueryParams,
        destination: &BigQueryQueryDestination,
        span: &Span,
    ) -> BigQueryResult<(BigQueryJobStats, BigQueryJobRef, Job)> {
        let inserted = self
            .insert_query_job(params, destination, false, span)
            .await?;
        let mut stats = BigQueryJobStats {
            job: inserted.job_reference.map(BigQueryJobRef::from),
            ..Default::default()
        };
        stats.record(span);
        let (job, details) = self.finish_job(&mut stats, true, params, span).await?;
        Ok((stats, job, details))
    }

    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_reference(&project_id);
        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: self.query_location(params).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)> {
        if let Some(destination) = &params.destination {
            let (stats, job, details) = self.run_query_job(params, destination, span).await?;
            return Self::job_rows(stats, &job, &details, span);
        }
        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?;
        Self::job_rows(stats, &job, &details, span)
    }

    /// Where the rows of the finished `job` are: its destination table, or none for a
    /// statement without rows.
    fn job_rows(
        stats: BigQueryJobStats,
        job: &BigQueryJobRef,
        details: &Job,
        span: &Span,
    ) -> BigQueryResult<(Rows, BigQueryJobStats)> {
        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> {
        if let Some(destination) = &params.destination {
            return Ok(self.run_query_job(params, destination, span).await?.0);
        }
        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> {
        if let Some(destination) = &params.destination {
            let job = self
                .insert_query_job(params, destination, true, span)
                .await?;
            return BigQueryDryRunResult::try_from(&job);
        }
        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()?,
        })
    }
}

/// The job an earlier attempt of a retried `InsertJob` created, when `already_exists`, the
/// message of an `AlreadyExists` status, names `sent`'s job ID as `project:LOCATION.job_id`.
/// The location is taken from the message, since `sent` has none unless the caller set one,
/// and the later job calls need it for a job outside the `US` and `EU` multi-regions.
fn earlier_attempt_job(sent: JobReference, already_exists: &str) -> Option<JobReference> {
    let qualified_id = format!(".{}", sent.job_id);
    let named = already_exists
        .split_whitespace()
        .find(|word| word.ends_with(&qualified_id))?;
    let location = named
        .strip_suffix(&qualified_id)?
        .rsplit_once(':')
        .map(|(_, location)| location.to_string())
        .filter(|location| !location.is_empty());
    Some(JobReference {
        location: location.or(sent.location),
        ..sent
    })
}

/// What a dry-run job reports: the bytes and the result schema of its query statistics, else
/// the bytes of its job statistics.
impl TryFrom<&Job> for BigQueryDryRunResult {
    type Error = BigQueryError;

    fn try_from(job: &Job) -> Result<Self, Self::Error> {
        let statistics = job.statistics.as_ref();
        let query = statistics.and_then(|statistics| statistics.query.as_ref());
        Ok(Self {
            total_bytes_processed: query
                .and_then(|query| query.total_bytes_processed)
                .or(statistics.and_then(|statistics| statistics.total_bytes_processed)),
            schema: query
                .and_then(|query| query.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)
}