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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! The plan as a pure function of a declaration and the table `GetTable` returned, and the
//! request bodies that carry it out.
//!
//! Nothing here performs I/O, so every class of change BigQuery was measured on is a unit
//! test.

use crate::db::proto::millis;
use crate::schema::declaration::DeclaredColumn;
use crate::schema::existing::ExistingTable;
use crate::schema::plan::ChangeStep;
use crate::sql::dotted_path;
use crate::BigQueryLabels;
use crate::{
    BigQueryDecimalParams, BigQueryFieldMode, BigQueryFieldSchema, BigQueryFieldType,
    BigQueryRecreate, BigQueryRecreateMethod, BigQueryRecreatePolicy, BigQueryRefusal,
    BigQueryResult, BigQuerySchemaChange, BigQueryTableDeclaration, BigQueryTablePlan,
    BigQueryTableRef, BigQueryTableTarget, BigQueryWithheldChange, BigQueryWithheldReason,
};
use gcloud_sdk::google::cloud::bigquery::v2;
use std::collections::HashSet;

impl BigQueryTableDeclaration {
    /// What `.sync()` would do to `table`, declared as `declaration`, given its current state;
    /// `None` when it does not exist. `row_access_policies` of a recreate are left empty for the
    /// caller to list.
    pub(crate) fn plan(
        &self,
        table: BigQueryTableRef,
        existing: Option<&ExistingTable>,
    ) -> BigQueryTablePlan {
        let mut plan = BigQueryTablePlan {
            table,
            create: None,
            changes: Vec::new(),
            withheld: Vec::new(),
            recreate: None,
            impossible: Vec::new(),
            refusal: None,
        };
        let Some(existing) = existing else {
            plan.create = Some(self.target(None));
            return plan;
        };

        let mut diff = Diff {
            declaration: self,
            changes: Vec::new(),
            withheld: Vec::new(),
            impossible: Vec::new(),
        };
        diff.columns(&existing.schema.fields);
        diff.settings(existing);
        // A stable sort keeps the column changes ahead of the table settings within a step.
        diff.changes.sort_by_key(BigQuerySchemaChange::step);
        plan.withheld = diff.withheld;

        if diff.impossible.is_empty() {
            plan.changes = diff.changes;
            return plan;
        }
        let dangerous = match self.recreate {
            Some(BigQueryRecreatePolicy::DangerouslyWithDataLoss) => true,
            Some(BigQueryRecreatePolicy::IfEmpty) if existing.num_rows == Some(0) => false,
            Some(BigQueryRecreatePolicy::IfEmpty) => {
                plan.changes = diff.changes;
                plan.impossible = diff.impossible;
                plan.refusal = Some(BigQueryRefusal::NotEmpty {
                    num_rows: existing.num_rows,
                });
                return plan;
            }
            None => {
                plan.changes = diff.changes;
                plan.impossible = diff.impossible;
                plan.refusal = Some(BigQueryRefusal::NoRecreateOptIn);
                return plan;
            }
        };
        let target = self.target(Some(existing));
        let same_partitioning = match (&target.partitioning, &existing.partitioning) {
            (Some(a), Some(b)) => a.same_as(b),
            (None, None) => true,
            _ => false,
        };
        // `CREATE OR REPLACE` must restate the partitioning and clustering exactly.
        let method = if same_partitioning && same_columns(&target.clustering, &existing.clustering)
        {
            BigQueryRecreateMethod::CreateOrReplace
        } else {
            BigQueryRecreateMethod::DropAndCreate
        };
        plan.recreate = Some(BigQueryRecreate {
            method,
            reasons: diff.impossible,
            target,
            num_rows: existing.num_rows,
            num_bytes: existing.num_bytes,
            row_access_policies: Vec::new(),
            dangerous,
            snapshot_first: self.snapshot_first,
        });
        plan
    }
}

/// Column names compare as BigQuery compares them, ignoring case.
fn same_name(left: &str, right: &str) -> bool {
    left.eq_ignore_ascii_case(right)
}

fn same_columns(left: &[String], right: &[String]) -> bool {
    left.len() == right.len()
        && left
            .iter()
            .zip(right)
            .all(|(left, right)| same_name(left, right))
}

fn find<'f>(fields: &'f [BigQueryFieldSchema], name: &str) -> Option<&'f BigQueryFieldSchema> {
    fields.iter().find(|field| same_name(&field.name, name))
}

impl DeclaredColumn {
    /// The existing column a declared top-level column matches: the one with its name, or else the
    /// one it is renamed from.
    fn matched<'f>(&self, existing: &'f [BigQueryFieldSchema]) -> Option<&'f BigQueryFieldSchema> {
        find(existing, &self.field.name).or_else(|| {
            self.renamed_from
                .as_deref()
                .and_then(|old| find(existing, old))
        })
    }
}

impl BigQueryDecimalParams {
    /// Whether a column with these parameters takes the parameters `to`, `None` being the
    /// unparameterized type: every value fits in at least as many integer and fractional digits.
    fn widens_to(self, to: Option<BigQueryDecimalParams>) -> bool {
        match to {
            None => true,
            Some(to) => {
                to.scale >= self.scale
                    && i32::from(to.precision) - i32::from(to.scale)
                        >= i32::from(self.precision) - i32::from(self.scale)
            }
        }
    }
}

/// Whether a `STRING(n)` or `BYTES(n)` column of length `from` takes the length `to`, `None`
/// being no limit.
fn length_widens(from: Option<u64>, to: Option<u64>) -> bool {
    match (from, to) {
        (Some(_), None) => true,
        (Some(from), Some(to)) => to > from,
        (None, _) => false,
    }
}

impl BigQueryFieldType {
    /// Whether `ALTER COLUMN SET DATA TYPE` takes this type to `to`.
    ///
    /// BigQuery takes INT64 to NUMERIC and a longer `STRING(n)`, and refuses INT64 to
    /// FLOAT64, so FLOAT64 is never a widening target here. The other pairs follow
    /// GoogleSQL's assignability of the exact numeric types and of type parameters.
    fn widens_to(&self, to: &BigQueryFieldType) -> bool {
        use BigQueryFieldType::*;
        match (self, to) {
            (Int64, Numeric(None) | BigNumeric(None)) => true,
            (Numeric(None), BigNumeric(None)) => true,
            (Numeric(from), Numeric(to)) | (BigNumeric(from), BigNumeric(to)) => {
                from.is_some_and(|from| from.widens_to(*to))
            }
            (String { max_length: from }, String { max_length: to })
            | (Bytes { max_length: from }, Bytes { max_length: to }) => length_widens(*from, *to),
            _ => false,
        }
    }
}

struct Diff<'a> {
    declaration: &'a BigQueryTableDeclaration,
    changes: Vec<BigQuerySchemaChange>,
    withheld: Vec<BigQueryWithheldChange>,
    impossible: Vec<BigQuerySchemaChange>,
}

impl Diff<'_> {
    /// An undeclared item: removed with `prune_undeclared()`, kept and reported without.
    fn undeclared(&mut self, change: BigQuerySchemaChange) {
        if !self.declaration.prune {
            self.withheld.push(BigQueryWithheldChange {
                change,
                reason: BigQueryWithheldReason::PruneUndeclared,
            });
        } else if change.step() == ChangeStep::Impossible {
            self.impossible.push(change);
        } else {
            self.changes.push(change);
        }
    }

    fn add(&mut self, path: String, field: &BigQueryFieldSchema) {
        let field = field.clone();
        if field.mode == BigQueryFieldMode::Required {
            self.impossible
                .push(BigQuerySchemaChange::AddRequiredColumn { path, field });
        } else {
            self.changes
                .push(BigQuerySchemaChange::AddColumn { path, field });
        }
    }

    fn columns(&mut self, existing: &[BigQueryFieldSchema]) {
        let declaration = self.declaration;
        let mut matched_names = HashSet::new();
        for column in &declaration.columns {
            let Some(current) = column.matched(existing) else {
                self.add(column.field.name.clone(), &column.field);
                continue;
            };
            matched_names.insert(current.name.to_ascii_lowercase());
            if !same_name(&current.name, &column.field.name) {
                self.changes.push(BigQuerySchemaChange::RenameColumn {
                    from: current.name.clone(),
                    to: column.field.name.clone(),
                });
            }
            self.compare(
                &current.name,
                Some(&column.field.name),
                &column.field,
                current,
            );
        }
        for current in existing {
            if !matched_names.contains(&current.name.to_ascii_lowercase()) {
                self.undeclared(BigQuerySchemaChange::DropColumn {
                    column: current.name.clone(),
                    field_type: current.field_type.clone(),
                });
            }
        }
    }

    /// Compares one declared column or field with the existing one at `path`. `ddl_name` is the
    /// top-level column's name after any rename, `None` for a nested field, which no DDL can
    /// alter.
    fn compare(
        &mut self,
        path: &str,
        ddl_name: Option<&str>,
        declared: &BigQueryFieldSchema,
        current: &BigQueryFieldSchema,
    ) {
        match (&declared.field_type, &current.field_type) {
            (
                BigQueryFieldType::Struct(declared_fields),
                BigQueryFieldType::Struct(live_fields),
            ) => self.nested(path, declared_fields, live_fields),
            (to, from) if to == from => {}
            (to, from) if ddl_name.is_some() && from.widens_to(to) => {
                let change = BigQuerySchemaChange::WidenColumn {
                    column: ddl_name.unwrap_or(path).to_string(),
                    from: from.clone(),
                    to: to.clone(),
                };
                if self.declaration.allow_widening {
                    self.changes.push(change);
                } else {
                    self.withheld.push(BigQueryWithheldChange {
                        change,
                        reason: BigQueryWithheldReason::AllowWidening,
                    });
                }
            }
            (to, from) => self
                .impossible
                .push(BigQuerySchemaChange::ChangeColumnType {
                    path: path.to_string(),
                    from: from.clone(),
                    to: to.clone(),
                }),
        }
        match (declared.mode, current.mode) {
            (to, from) if to == from => {}
            (BigQueryFieldMode::Nullable, BigQueryFieldMode::Required) => {
                self.changes.push(BigQuerySchemaChange::RelaxColumn {
                    path: path.to_string(),
                })
            }
            (to, from) => self
                .impossible
                .push(BigQuerySchemaChange::ChangeColumnMode {
                    path: path.to_string(),
                    from,
                    to,
                }),
        }
        if let Some(to) = &declared.description {
            if current.description.as_deref().unwrap_or("") != to {
                self.changes
                    .push(BigQuerySchemaChange::SetColumnDescription {
                        path: path.to_string(),
                        from: current.description.clone(),
                        to: to.clone(),
                    });
            }
        }
        if let Some(to) = &declared.default_value_expression {
            if current.default_value_expression.as_ref() != Some(to) {
                self.changes.push(BigQuerySchemaChange::SetColumnDefault {
                    path: path.to_string(),
                    from: current.default_value_expression.clone(),
                    to: to.clone(),
                });
            }
        }
    }

    fn nested(
        &mut self,
        prefix: &str,
        declared: &[BigQueryFieldSchema],
        existing: &[BigQueryFieldSchema],
    ) {
        for field in declared {
            let path = dotted_path(prefix, &field.name);
            match find(existing, &field.name) {
                Some(current) => self.compare(&path, None, field, current),
                None => self.add(path, field),
            }
        }
        for current in existing {
            if find(declared, &current.name).is_none() {
                self.undeclared(BigQuerySchemaChange::DropNestedField {
                    path: dotted_path(prefix, &current.name),
                    field_type: current.field_type.clone(),
                });
            }
        }
    }

    fn settings(&mut self, existing: &ExistingTable) {
        let declaration = self.declaration;
        if let Some(to) = &declaration.description {
            if existing.description.as_deref().unwrap_or("") != to {
                self.changes.push(BigQuerySchemaChange::SetDescription {
                    from: existing.description.clone(),
                    to: to.clone(),
                });
            }
        }
        for (key, to) in declaration.labels.iter() {
            let from = existing.labels.get(key);
            if from != Some(to) {
                self.changes.push(BigQuerySchemaChange::SetLabel {
                    key: key.to_string(),
                    from: from.map(str::to_string),
                    to: to.to_string(),
                });
            }
        }
        for (key, value) in existing.labels.iter() {
            if declaration.labels.get(key).is_none() {
                self.undeclared(BigQuerySchemaChange::RemoveLabel {
                    key: key.to_string(),
                    value: value.to_string(),
                });
            }
        }
        if let Some(to) = declaration.expiration {
            if existing.expiration != Some(to) {
                self.changes.push(BigQuerySchemaChange::SetExpiration {
                    from: existing.expiration,
                    to,
                });
            }
        }
        match (&declaration.partitioning, &existing.partitioning) {
            (Some(declared), Some(current)) if declared.same_as(current) => {
                if let Some(to) = declaration.partition_expiration {
                    if existing.partition_expiration != Some(to) {
                        self.changes
                            .push(BigQuerySchemaChange::SetPartitionExpiration {
                                from: existing.partition_expiration,
                                to,
                            });
                    }
                }
            }
            (Some(declared), current) => {
                self.impossible
                    .push(BigQuerySchemaChange::ChangePartitioning {
                        from: current.clone(),
                        to: Some(declared.clone()),
                    })
            }
            (None, Some(current)) => self.undeclared(BigQuerySchemaChange::ChangePartitioning {
                from: Some(current.clone()),
                to: None,
            }),
            (None, None) => {}
        }
        match &declaration.clustering {
            Some(to) if !same_columns(to, &existing.clustering) => {
                self.changes.push(BigQuerySchemaChange::SetClustering {
                    from: existing.clustering.clone(),
                    to: to.clone(),
                })
            }
            Some(_) => {}
            None if !existing.clustering.is_empty() => {
                self.undeclared(BigQuerySchemaChange::RemoveClustering {
                    from: existing.clustering.clone(),
                })
            }
            None => {}
        }
        match (&declaration.primary_key, &existing.primary_key) {
            (Some(to), current)
                if current
                    .as_ref()
                    .is_none_or(|current| !same_columns(to, current)) =>
            {
                self.changes.push(BigQuerySchemaChange::SetPrimaryKey {
                    from: current.clone(),
                    to: to.clone(),
                })
            }
            (None, Some(current)) => self.undeclared(BigQuerySchemaChange::RemovePrimaryKey {
                from: current.clone(),
            }),
            _ => {}
        }
    }
}

impl BigQueryFieldSchema {
    /// This declared field with what it leaves undeclared taken from `current`: descriptions, defaults and,
    /// unless pruning, nested fields.
    fn merged_with(
        &self,
        current: Option<&BigQueryFieldSchema>,
        prune: bool,
    ) -> BigQueryFieldSchema {
        let mut field = self.clone();
        let Some(current) = current else {
            return field;
        };
        if field.description.is_none() {
            field.description.clone_from(&current.description);
        }
        if field.default_value_expression.is_none() {
            field
                .default_value_expression
                .clone_from(&current.default_value_expression);
        }
        if let (
            BigQueryFieldType::Struct(declared_fields),
            BigQueryFieldType::Struct(live_fields),
        ) = (&self.field_type, &current.field_type)
        {
            let mut fields: Vec<BigQueryFieldSchema> = declared_fields
                .iter()
                .map(|f| f.merged_with(find(live_fields, &f.name), prune))
                .collect();
            if !prune {
                fields.extend(
                    live_fields
                        .iter()
                        .filter(|f| find(declared_fields, &f.name).is_none())
                        .cloned(),
                );
            }
            field.field_type = BigQueryFieldType::Struct(fields);
        }
        field
    }
}

impl BigQueryTableDeclaration {
    /// The whole table as `.sync()` creates or recreates it: the declaration, plus what it leaves
    /// undeclared and does not prune.
    fn target(&self, existing: Option<&ExistingTable>) -> BigQueryTableTarget {
        let prune = self.prune;
        let live_fields = existing.map_or(&[][..], |l| &l.schema.fields[..]);
        let mut columns: Vec<BigQueryFieldSchema> = self
            .columns
            .iter()
            .map(|c| c.field.merged_with(c.matched(live_fields), prune))
            .collect();
        let mut labels = BigQueryLabels::new();
        let mut target = BigQueryTableTarget {
            columns: Vec::new(),
            primary_key: self.primary_key.clone(),
            partitioning: self.partitioning.clone(),
            partition_expiration: self.partition_expiration,
            clustering: self.clustering.clone().unwrap_or_default(),
            description: self.description.clone(),
            labels: BigQueryLabels::new(),
            expiration: self.expiration,
        };
        if let Some(existing) = existing {
            if !prune {
                let declared_live: HashSet<String> = self
                    .columns
                    .iter()
                    .filter_map(|c| c.matched(live_fields))
                    .map(|f| f.name.to_ascii_lowercase())
                    .collect();
                columns.extend(
                    live_fields
                        .iter()
                        .filter(|f| !declared_live.contains(&f.name.to_ascii_lowercase()))
                        .cloned(),
                );
                labels.clone_from(&existing.labels);
                if target.primary_key.is_none() {
                    target.primary_key.clone_from(&existing.primary_key);
                }
                if target.partitioning.is_none() {
                    target.partitioning.clone_from(&existing.partitioning);
                }
                if self.clustering.is_none() {
                    target.clustering.clone_from(&existing.clustering);
                }
            }
            let same_partitioning = match (&target.partitioning, &existing.partitioning) {
                (Some(a), Some(b)) => a.same_as(b),
                _ => false,
            };
            if target.partition_expiration.is_none() && same_partitioning {
                target.partition_expiration = existing.partition_expiration;
            }
            if target.description.is_none() {
                target.description.clone_from(&existing.description);
            }
            if target.expiration.is_none() {
                target.expiration = existing.expiration;
            }
        }
        for (key, value) in self.labels.iter() {
            labels.insert(key, value);
        }
        target.columns = columns;
        target.labels = labels;
        target
    }
}

/// The field at the dotted `path`, matched ignoring case as the diff matched it.
fn field_at<'f>(
    fields: &'f mut [v2::TableFieldSchema],
    path: &str,
) -> Option<&'f mut v2::TableFieldSchema> {
    let (head, rest) = match path.split_once('.') {
        Some((head, rest)) => (head, Some(rest)),
        None => (path, None),
    };
    let field = fields.iter_mut().find(|f| same_name(&f.name, head))?;
    match rest {
        Some(rest) => field_at(&mut field.fields, rest),
        None => Some(field),
    }
}

/// Appends `field` at `path`, inside the record its parent path names.
fn add_field(schema: &mut v2::TableSchema, path: &str, field: v2::TableFieldSchema) {
    match path.rsplit_once('.') {
        Some((parent, _)) => {
            if let Some(parent) = field_at(&mut schema.fields, parent) {
                parent.fields.push(field);
            }
        }
        None => schema.fields.push(field),
    }
}

impl BigQueryTablePlan {
    /// The first `PatchTable` body: every `[patch]` change, with new columns added without their
    /// default value, which BigQuery refuses in the same step.
    ///
    /// A schema in the body replaces the whole schema, so it is the existing one with the changes
    /// edited in, every column and description included, and everything the crate does
    /// not model, such as policy tags, carried back as it was.
    ///
    /// # Errors
    /// [`BigQueryError::InvalidParametersError`] for a partition expiration whose milliseconds do
    /// not fit the request field.
    pub(crate) fn patch_body(&self, existing: &v2::Table) -> BigQueryResult<Option<v2::Table>> {
        let changes = &self.changes;
        let mut body = v2::Table::default();
        let mut schema = existing.schema.clone().unwrap_or_default();
        let mut schema_edited = false;
        let mut any = false;
        let foreign_keys = || {
            existing
                .table_constraints
                .as_ref()
                .map(|c| c.foreign_keys.clone())
                .unwrap_or_default()
        };
        for change in changes.iter().filter(|c| c.step() == ChangeStep::Patch) {
            any = true;
            if matches!(
                change,
                BigQuerySchemaChange::AddColumn { .. }
                    | BigQuerySchemaChange::RelaxColumn { .. }
                    | BigQuerySchemaChange::SetColumnDescription { .. }
                    | BigQuerySchemaChange::SetColumnDefault { .. }
            ) {
                schema_edited = true;
            }
            match change {
                BigQuerySchemaChange::AddColumn { path, field } => {
                    let mut field = v2::TableFieldSchema::from(field);
                    field.default_value_expression = None;
                    add_field(&mut schema, path, field);
                }
                BigQuerySchemaChange::RelaxColumn { path } => {
                    if let Some(field) = field_at(&mut schema.fields, path) {
                        field.mode = "NULLABLE".into();
                    }
                }
                BigQuerySchemaChange::SetColumnDescription { path, to, .. } => {
                    if let Some(field) = field_at(&mut schema.fields, path) {
                        field.description = Some(to.clone());
                    }
                }
                BigQuerySchemaChange::SetColumnDefault { path, to, .. } => {
                    if let Some(field) = field_at(&mut schema.fields, path) {
                        field.default_value_expression = Some(to.clone());
                    }
                }
                BigQuerySchemaChange::SetDescription { to, .. } => {
                    body.description = Some(to.clone())
                }
                BigQuerySchemaChange::SetLabel { key, to, .. } => {
                    body.labels.insert(key.clone(), to.clone());
                }
                BigQuerySchemaChange::SetExpiration { to, .. } => {
                    body.expiration_time = Some(to.as_millisecond());
                }
                BigQuerySchemaChange::SetPartitionExpiration { to, .. } => {
                    body.time_partitioning = Some(v2::TimePartitioning {
                        expiration_ms: Some(millis("partition_expiration", *to)?),
                        ..existing.time_partitioning.clone().unwrap_or_default()
                    });
                }
                BigQuerySchemaChange::SetClustering { to, .. } => {
                    body.clustering = Some(v2::Clustering { fields: to.clone() });
                }
                BigQuerySchemaChange::SetPrimaryKey { to, .. } => {
                    body.table_constraints = Some(v2::TableConstraints {
                        primary_key: Some(v2::PrimaryKey {
                            columns: to.clone(),
                        }),
                        foreign_keys: foreign_keys(),
                    });
                }
                BigQuerySchemaChange::RemovePrimaryKey { .. } => {
                    body.table_constraints = Some(v2::TableConstraints {
                        primary_key: None,
                        foreign_keys: foreign_keys(),
                    });
                }
                _ => {}
            }
        }
        body.schema = schema_edited.then_some(schema);
        Ok(any.then_some(body))
    }

    /// The second `PatchTable` body, setting the defaults of the columns the first one added; built
    /// from the table the first patch returned. `None` when no added column has a default.
    pub(crate) fn defaults_body(&self, latest: &v2::Table) -> Option<v2::Table> {
        let changes = &self.changes;
        let mut schema = latest.schema.clone().unwrap_or_default();
        let mut any = false;
        for change in changes {
            if let BigQuerySchemaChange::AddColumn { path, field } = change {
                if let Some(default) = &field.default_value_expression {
                    if let Some(field) = field_at(&mut schema.fields, path) {
                        field.default_value_expression = Some(default.clone());
                        any = true;
                    }
                }
            }
        }
        any.then(|| v2::Table {
            schema: Some(schema),
            ..Default::default()
        })
    }

    /// The `UpdateTable` body: the whole of `latest`, which must be the table as it is now, without
    /// the removed labels and clustering. Update clears whatever its body leaves out.
    pub(crate) fn update_body(&self, latest: &v2::Table) -> Option<v2::Table> {
        let changes = &self.changes;
        let mut body = latest.clone();
        let mut any = false;
        for change in changes {
            match change {
                BigQuerySchemaChange::RemoveLabel { key, .. } => {
                    body.labels.remove(key);
                    any = true;
                }
                BigQuerySchemaChange::RemoveClustering { .. } => {
                    body.clustering = None;
                    any = true;
                }
                _ => {}
            }
        }
        any.then_some(body)
    }
}

#[cfg(test)]
mod tests;