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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
//! A fake BigQuery for your tests.
//!
//! [`BigQueryFake`] runs a gRPC server on a loopback port and hands out a real [`BigQueryDb`]
//! pointed at it, so the code under test runs unchanged, through the same requests, codecs,
//! retries and errors as against BigQuery. A test scripts the fake in serde terms:
//!
//! - a query rule answers the statement it matches with rows of any `Serialize` type, DML
//!   counts, or a failure;
//! - a table holds rows, which reads serve and writes append to, and which the test reads
//!   back with [`rows`](BigQueryFake::rows);
//! - a fault makes one RPC fail with a gRPC status, a dropped connection or a call that never
//!   answers.
//!
//! There is no SQL engine: a query answers only as a rule scripts it. A call that nothing
//! answers fails with `Unimplemented`, which the client does not retry, and
//! [`verify`](BigQueryFake::verify), which runs when the fake is dropped, panics with every
//! such call and the rules that were there to answer it.
//!
//! The tests need an async runtime in your dev-dependencies:
//!
//! ```toml
//! [dev-dependencies]
//! tokio = { version = "1", features = ["macros", "rt"] }
//! ```
//!
//! # Examples
//!
//! The examples share a row type and the code under test:
//!
//! ```rust
//! use bigquery::*;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
//! struct Order {
//!     id: i64,
//!     customer: String,
//!     total: f64,
//! }
//!
//! const SHOP: BigQueryDatasetId = BigQueryDatasetId::from_static("shop");
//! const ORDERS: BigQueryTableId = BigQueryTableId::from_static("orders");
//! const ORDERS_OF: &str = "SELECT id, customer, total FROM shop.orders WHERE customer = @customer";
//!
//! async fn orders_of(db: &BigQueryDb, customer: &str) -> BigQueryResult<Vec<Order>> {
//!     db.fluent().query(ORDERS_OF).param("customer", customer).obj().query().await
//! }
//!
//! async fn save(db: &BigQueryDb, orders: &[Order]) -> BigQueryResult<BigQueryWriteSummary> {
//!     db.fluent().insert().into(SHOP.table(ORDERS)).objects(orders).execute().await
//! }
//! ```
//!
//! Each example below is the body of a `#[tokio::test] async fn ...() -> BigQueryResult<()>`.
//!
//! A query that returns rows:
//!
//! ```rust
//! # use bigquery::*;
//! # use serde::{Deserialize, Serialize};
//! # #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
//! # struct Order { id: i64, customer: String, total: f64 }
//! # const ORDERS_OF: &str = "SELECT id, customer, total FROM shop.orders WHERE customer = @customer";
//! # async fn orders_of(db: &BigQueryDb, customer: &str) -> BigQueryResult<Vec<Order>> {
//! #     db.fluent().query(ORDERS_OF).param("customer", customer).obj().query().await
//! # }
//! # #[tokio::main(flavor = "current_thread")]
//! # async fn main() -> BigQueryResult<()> {
//! use bigquery::testing::BigQueryFake;
//!
//! let fake = BigQueryFake::start().await?;
//! let alice = vec![Order { id: 1, customer: "Alice".into(), total: 120.0 }];
//! let rule = fake
//!     .when_query_match(ORDERS_OF)
//!     .param("customer", "Alice")
//!     .returns_rows(|columns| columns.from_type::<Order>(), &alice)?;
//!
//! assert_eq!(orders_of(fake.db(), "Alice").await?, alice);
//! assert_eq!(rule.calls(), 1);
//! # Ok(())
//! # }
//! ```
//!
//! A writer whose rows are captured:
//!
//! ```rust
//! # use bigquery::*;
//! # use serde::{Deserialize, Serialize};
//! # #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
//! # struct Order { id: i64, customer: String, total: f64 }
//! # const SHOP: BigQueryDatasetId = BigQueryDatasetId::from_static("shop");
//! # const ORDERS: BigQueryTableId = BigQueryTableId::from_static("orders");
//! # async fn save(db: &BigQueryDb, orders: &[Order]) -> BigQueryResult<BigQueryWriteSummary> {
//! #     db.fluent().insert().into(SHOP.table(ORDERS)).objects(orders).execute().await
//! # }
//! # #[tokio::main(flavor = "current_thread")]
//! # async fn main() -> BigQueryResult<()> {
//! use bigquery::testing::BigQueryFake;
//!
//! let fake = BigQueryFake::start().await?;
//! fake.table(SHOP.table(ORDERS), |columns| columns.from_type::<Order>())
//!     .create()?;
//! let orders = vec![
//!     Order { id: 1, customer: "Alice".into(), total: 120.0 },
//!     Order { id: 2, customer: "Bob".into(), total: 80.5 },
//! ];
//!
//! let summary = save(fake.db(), &orders).await?;
//!
//! assert_eq!(summary.rows_written, 2);
//! let written: Vec<Order> = fake.rows(SHOP.table(ORDERS))?;
//! assert_eq!(written, orders);
//! # Ok(())
//! # }
//! ```
//!
//! A failure a retry gets past, then an outage the client gives up on. Retries against the
//! fake wait no backoff:
//!
//! ```rust
//! # use bigquery::*;
//! # use serde::{Deserialize, Serialize};
//! # #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
//! # struct Order { id: i64, customer: String, total: f64 }
//! # const ORDERS_OF: &str = "SELECT id, customer, total FROM shop.orders WHERE customer = @customer";
//! # async fn orders_of(db: &BigQueryDb, customer: &str) -> BigQueryResult<Vec<Order>> {
//! #     db.fluent().query(ORDERS_OF).param("customer", customer).obj().query().await
//! # }
//! # #[tokio::main(flavor = "current_thread")]
//! # async fn main() -> BigQueryResult<()> {
//! use bigquery::testing::{BigQueryFake, BigQueryFakeCode, BigQueryFakeFault};
//!
//! let fake = BigQueryFake::start().await?;
//! let alice = vec![Order { id: 1, customer: "Alice".into(), total: 120.0 }];
//! let unavailable =
//!     || BigQueryFakeFault::status(BigQueryFakeCode::Unavailable, "backend went away");
//! let lost = fake.when_query_match(ORDERS_OF).times(1).fails(unavailable())?;
//! let answer = fake
//!     .when_query_match(ORDERS_OF)
//!     .param("customer", "Alice")
//!     .returns_rows(|columns| columns.from_type::<Order>(), &alice)?;
//! let outage = fake
//!     .when_query_match(ORDERS_OF)
//!     .param("customer", "Bob")
//!     .fails(unavailable())?;
//!
//! assert_eq!(orders_of(fake.db(), "Alice").await?, alice);
//! assert_eq!((lost.calls(), answer.calls()), (1, 1));
//!
//! let failed = orders_of(fake.db(), "Bob").await;
//! assert!(matches!(&failed, Err(err) if err.retry_possible()), "{failed:?}");
//! assert_eq!(outage.calls(), 4, "the first attempt and max_retries = 3 retries");
//! # Ok(())
//! # }
//! ```
//!
//! # Limits
//!
//! The fake binds its own port, so tests run in parallel. A call sees the rules registered
//! before it arrives. Tokio's paused time is not supported: a paused runtime jumps to its
//! next timer whenever it is idle, and waiting on the fake's loopback socket counts as idle.

mod admin;
mod matcher;
mod query;
mod read;
mod rows;
mod rules;
mod schema;
mod server;
mod state;
mod write;

pub use matcher::BigQueryFakeQuery;
pub use rules::{
    BigQueryFakeCode, BigQueryFakeFault, BigQueryFakeJobFailure, BigQueryFakeRpc, BigQueryFakeRule,
};

use crate::db::fake::FakeServer;
use crate::errors::BigQueryError;
use crate::query::{parameter_mode, ParamList};
use crate::read::BigQueryBatchRows;
use crate::testing::rows::ProtoBatchBuilder;
use crate::testing::rules::{
    FaultRule, QueryAnswer, QueryMatcher, QueryReply, QueryRule, ReadRule, RejectRule,
    ShownParameters,
};
use crate::testing::server::FakeShared;
use crate::testing::state::{DatasetKey, FakeTable, TableKey};
use crate::{
    BigQueryChange, BigQueryDatasetRef, BigQueryDb, BigQueryDmlStats, BigQueryParamType,
    BigQueryResult, BigQuerySchemaColumns, BigQuerySchemaColumnsBuilder, BigQuerySql,
    BigQueryStatementType, BigQueryTableRef, BigQueryTableSchema,
};
use arrow_array::RecordBatch;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::fmt::{Debug, Formatter};
use std::num::NonZeroUsize;
use std::sync::Arc;

/// A fake BigQuery on a loopback port, and a client for it.
///
/// Start one per test with [`start`](Self::start), script it, run the code under test against
/// [`db`](Self::db), then assert on what the code returned and on what the fake recorded. The
/// fake is `Send + Sync`, so a test can share it with the tasks it spawns.
///
/// Dropping it stops the server and calls [`verify`](Self::verify).
pub struct BigQueryFake {
    db: BigQueryDb,
    shared: Arc<FakeShared>,
    /// Held for its `Drop`, which stops the server.
    _server: FakeServer,
}

impl Debug for BigQueryFake {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BigQueryFake")
            .field("db", &self.db)
            .finish_non_exhaustive()
    }
}

impl BigQueryFake {
    /// The client for this fake, as the code under test takes it. Clones share the fake.
    pub fn db(&self) -> &BigQueryDb {
        &self.db
    }

    /// Starts a rule for the statement whose SQL equals `sql` exactly: no whitespace or case
    /// folding, so the rule matches only the text the code under test sends. A statement from
    /// [`sql_file!`](crate::sql_file!) matches by its file's text.
    pub fn when_query_match(&self, sql: impl Into<BigQuerySql>) -> BigQueryFakeQueryBuilder<'_> {
        let (sql, _) = sql.into().into_parts();
        BigQueryFakeQueryBuilder::new(self, QueryMatcher::Exact(sql))
    }

    /// Starts a rule for every call `matcher` accepts, given the call's SQL and its parameters
    /// as a [`BigQueryFakeQuery`].
    ///
    /// The matcher runs for each query and job call that reaches its rule, while the fake holds
    /// its rules, so a matcher that blocks holds up every other call. A matcher that panics
    /// fails the call with `Internal` and fails [`verify`](Self::verify).
    pub fn when_query<F>(&self, matcher: F) -> BigQueryFakeQueryBuilder<'_>
    where
        F: Fn(&BigQueryFakeQuery<'_>) -> bool + Send + Sync + 'static,
    {
        BigQueryFakeQueryBuilder::new(self, QueryMatcher::Matching(Box::new(matcher)))
    }

    /// Creates the dataset. A dataset without a project is in the client's.
    ///
    /// # Errors
    /// [`BigQueryError::DataConflictError`] if the dataset exists.
    pub fn create_dataset(&self, dataset: impl Into<BigQueryDatasetRef>) -> BigQueryResult<()> {
        let key = DatasetKey::resolve(&dataset.into(), self.shared.project());
        self.shared.state().create_dataset(key)?;
        Ok(())
    }

    /// Starts a table with the columns `columns` declares, as
    /// [`BigQueryTableSchemaBuilder::columns`](crate::BigQueryTableSchemaBuilder::columns)
    /// takes them. [`create`](BigQueryFakeTableBuilder::create) creates it, and its dataset if
    /// that is missing.
    pub fn table<F, R>(
        &self,
        table: impl Into<BigQueryTableRef>,
        columns: F,
    ) -> BigQueryFakeTableBuilder<'_>
    where
        F: FnOnce(BigQuerySchemaColumnsBuilder) -> R,
        R: Into<BigQuerySchemaColumns>,
    {
        let contents = columns(BigQuerySchemaColumnsBuilder)
            .into()
            .table_schema()
            .map(|schema| FakeTableContents {
                schema,
                batches: Vec::new(),
                rows: 0,
            });
        BigQueryFakeTableBuilder {
            fake: self,
            table: table.into(),
            contents,
            read_streams: 1,
        }
    }

    /// Starts a rule for the read sessions of an existing table. A session without a row
    /// restriction is served the table's rows when no rule answers it; one with a row
    /// restriction needs a rule, since the fake does not evaluate filters.
    pub fn when_read(&self, table: impl Into<BigQueryTableRef>) -> BigQueryFakeReadBuilder<'_> {
        BigQueryFakeReadBuilder {
            fake: self,
            table: table.into(),
            row_restriction: None,
            times: None,
        }
    }

    /// Starts a fault for the calls of `rpc`. Faults answer before every other rule and before
    /// the tables.
    pub fn when_fault(&self, rpc: BigQueryFakeRpc) -> BigQueryFakeFaultBuilder<'_> {
        BigQueryFakeFaultBuilder {
            fake: self,
            rpc,
            table: None,
            times: None,
        }
    }

    /// Fails each append request to `table` that has a row `rejects` accepts, with one row
    /// error per such row, each carrying `reason`. As in BigQuery, nothing in that request is
    /// written.
    ///
    /// The rows are read as `T`, as [`rows`](Self::rows) reads them, before `rejects` sees
    /// them.
    pub fn when_rows_rejected<T, F>(
        &self,
        table: impl Into<BigQueryTableRef>,
        reason: impl Into<String>,
        rejects: F,
    ) -> BigQueryFakeRule
    where
        T: DeserializeOwned + 'static,
        F: Fn(&T) -> bool + Send + Sync + 'static,
    {
        let table = TableKey::resolve(&table.into(), self.shared.project());
        let reason = reason.into();
        let rule =
            BigQueryFakeRule::unlimited(format!("when_rows_rejected on {table}: {reason:?}"));
        self.shared.rules().add_rejection(RejectRule {
            table,
            reason,
            rejects: Box::new(move |batch: &RecordBatch| {
                let mut rejected = Vec::new();
                for (index, row) in BigQueryBatchRows::<T>::new(batch).enumerate() {
                    if rejects(&row?) {
                        rejected.push(index);
                    }
                }
                Ok(rejected)
            }),
            rule: rule.clone(),
        });
        rule
    }

    /// The visible rows of `table`, in the order they were acknowledged, read as `T` the way a
    /// read session's rows are.
    ///
    /// # Errors
    /// [`BigQueryError::DataNotFoundError`] if the table does not exist, and
    /// [`BigQueryError::DeserializeError`] for a row that does not read as `T`.
    pub fn rows<T: DeserializeOwned>(
        &self,
        table: impl Into<BigQueryTableRef>,
    ) -> BigQueryResult<Vec<T>> {
        let key = TableKey::resolve(&table.into(), self.shared.project());
        let batches = self.shared.state().table(&key)?.batches.clone();
        let mut rows = Vec::new();
        let mut first_row = 0;
        for batch in &batches {
            for row in BigQueryBatchRows::<T>::numbered_from(batch, first_row) {
                rows.push(row?);
            }
            first_row += batch.num_rows() as u64;
        }
        Ok(rows)
    }

    /// The CDC changes written to `table`, in the order they were acknowledged, each row read
    /// as `T`. The fake records changes and does not apply them to the table's rows.
    ///
    /// # Errors
    /// [`BigQueryError::DataNotFoundError`] if the table does not exist, and
    /// [`BigQueryError::DeserializeError`] for a row that does not read as `T`.
    pub fn changes<T: DeserializeOwned>(
        &self,
        table: impl Into<BigQueryTableRef>,
    ) -> BigQueryResult<Vec<BigQueryChange<T>>> {
        let key = TableKey::resolve(&table.into(), self.shared.project());
        let written = self.shared.state().table(&key)?.changes.clone();
        let mut changes = Vec::new();
        let mut first_row = 0;
        for batch in &written {
            let rows = BigQueryBatchRows::<T>::numbered_from(&batch.rows, first_row);
            for (row, change) in rows.zip(&batch.changes) {
                changes.push(BigQueryChange {
                    change_type: change.change_type,
                    sequence_number: change.sequence_number.clone(),
                    row: row?,
                });
            }
            first_row += batch.rows.num_rows() as u64;
        }
        Ok(changes)
    }
}

/// A query rule being built, from [`BigQueryFake::when_query_match`] or
/// [`BigQueryFake::when_query`]: add the parameters it expects, then pick what it answers
/// with.
///
/// The builder methods never fail. A parameter that cannot be encoded, or a
/// [`times`](Self::times) of 0, is kept, and the terminal returns the error without
/// registering the rule.
#[derive(Debug)]
#[must_use]
pub struct BigQueryFakeQueryBuilder<'a> {
    fake: &'a BigQueryFake,
    matcher: QueryMatcher,
    parameters: ParamList,
    times: Option<usize>,
    bytes_processed: Option<i64>,
}

impl<'a> BigQueryFakeQueryBuilder<'a> {
    fn new(fake: &'a BigQueryFake, matcher: QueryMatcher) -> Self {
        Self {
            fake,
            matcher,
            parameters: ParamList::default(),
            times: None,
            bytes_processed: None,
        }
    }
}

impl BigQueryFakeQueryBuilder<'_> {
    /// Expects the named parameter `@name`, encoded as
    /// [`BigQueryQueryBuilder::param`](crate::BigQueryQueryBuilder::param) encodes it.
    ///
    /// A rule without parameters answers a call whatever its parameters. Once it expects any,
    /// a call's named parameters must equal them as a set, and its positional ones in order.
    pub fn param<N: Into<String>, V: Serialize>(mut self, name: N, value: V) -> Self {
        self.parameters.named(&name.into(), &value);
        self
    }

    /// Expects the named parameter `@name` of type `ty`, as
    /// [`BigQueryQueryBuilder::param_as`](crate::BigQueryQueryBuilder::param_as) encodes it.
    pub fn param_as<N: Into<String>, V: Serialize>(
        mut self,
        name: N,
        ty: impl Into<BigQueryParamType>,
        value: V,
    ) -> Self {
        self.parameters.named_as(&name.into(), &ty.into(), &value);
        self
    }

    /// Expects every top-level field of a struct or string-keyed map as a named parameter, as
    /// [`BigQueryQueryBuilder::params`](crate::BigQueryQueryBuilder::params) encodes them.
    pub fn params<P: Serialize + ?Sized>(mut self, params: &P) -> Self {
        self.parameters.fields(params);
        self
    }

    /// Expects the next positional parameter `?`, as
    /// [`BigQueryQueryBuilder::positional_param`](crate::BigQueryQueryBuilder::positional_param)
    /// encodes it.
    pub fn positional_param<V: Serialize>(mut self, value: V) -> Self {
        self.parameters.positional(&value);
        self
    }

    /// Expects the next positional parameter `?` of type `ty`, as
    /// [`BigQueryQueryBuilder::positional_param_as`](crate::BigQueryQueryBuilder::positional_param_as)
    /// encodes it.
    pub fn positional_param_as<V: Serialize>(
        mut self,
        ty: impl Into<BigQueryParamType>,
        value: V,
    ) -> Self {
        self.parameters.positional_as(&ty.into(), &value);
        self
    }

    /// Answers exactly `calls` calls, retries included, and then no more, so that a later rule
    /// answers the calls after them. [`verify`](BigQueryFake::verify) fails unless the rule
    /// answered all of them. The terminal refuses 0.
    pub fn times(mut self, calls: usize) -> Self {
        self.times = Some(calls);
        self
    }

    /// The bytes the statement reports processed, in its stats and in a dry run.
    pub fn bytes_processed(mut self, bytes: i64) -> Self {
        self.bytes_processed = Some(bytes);
        self
    }

    /// Answers with `rows`, a result whose columns `columns` declares as
    /// [`BigQueryFake::table`] takes them. The same rule answers every purpose of a call: the
    /// rows for a query, the stats for `execute()`, and the schema for a dry run.
    ///
    /// # Errors
    /// The parameter or `times` error the builder kept,
    /// [`BigQueryError::SchemaInferenceError`] or
    /// [`BigQueryError::InvalidParametersError`] for columns `.plan()` would refuse, and
    /// [`BigQueryError::SerializeError`] naming the row and field of a row that does not
    /// encode as the columns say.
    pub fn returns_rows<F, R, T, I>(self, columns: F, rows: I) -> BigQueryResult<BigQueryFakeRule>
    where
        F: FnOnce(BigQuerySchemaColumnsBuilder) -> R,
        R: Into<BigQuerySchemaColumns>,
        I: IntoIterator<Item = T>,
        T: Serialize,
    {
        let schema = columns(BigQuerySchemaColumnsBuilder)
            .into()
            .table_schema()?;
        let rows = ProtoBatchBuilder::encode(&schema, rows, 0)?;
        self.register(QueryAnswer::Rows { schema, rows })
    }

    /// Answers as a DML statement of `statement_type` that changed the rows `stats` counts.
    ///
    /// # Errors
    /// The parameter or `times` error the builder kept.
    pub fn returns_dml(
        self,
        statement_type: BigQueryStatementType,
        stats: BigQueryDmlStats,
    ) -> BigQueryResult<BigQueryFakeRule> {
        self.register(QueryAnswer::Dml {
            statement_type,
            stats,
        })
    }

    /// Answers as a statement of `statement_type` with no rows and no DML counts, such as DDL.
    ///
    /// # Errors
    /// The parameter or `times` error the builder kept.
    pub fn returns_statement(
        self,
        statement_type: BigQueryStatementType,
    ) -> BigQueryResult<BigQueryFakeRule> {
        self.register(QueryAnswer::Statement(statement_type))
    }

    /// Refuses the call with `fault`.
    ///
    /// # Errors
    /// The parameter or `times` error the builder kept.
    pub fn fails(self, fault: BigQueryFakeFault) -> BigQueryResult<BigQueryFakeRule> {
        self.register(QueryAnswer::Fault(fault))
    }

    /// Runs the statement as a job that fails with `failure`: the first response says the job
    /// is still running, and the job reports the failure once it is done, which the client
    /// returns as [`BigQueryError::JobError`].
    ///
    /// A statement BigQuery refuses at validation, such as one with a syntax error, never runs
    /// as a job. Script it with
    /// [`fails`](Self::fails)`(BigQueryFakeFault::status(BigQueryFakeCode::InvalidArgument, ..))`,
    /// which fails `dry_run()` as well.
    ///
    /// # Errors
    /// The parameter or `times` error the builder kept.
    pub fn fails_job(self, failure: BigQueryFakeJobFailure) -> BigQueryResult<BigQueryFakeRule> {
        self.register(QueryAnswer::JobFailure(failure))
    }

    fn register(self, answer: QueryAnswer) -> BigQueryResult<BigQueryFakeRule> {
        let parameters = self.parameters.into_parameters()?;
        parameter_mode(&parameters)?;
        let mut description = self.matcher.to_string();
        if !parameters.is_empty() {
            description.push_str(&format!(" with {}", ShownParameters(&parameters)));
        }
        let rule = BigQueryFakeRule::limited(description, self.times)?;
        self.fake.shared.rules().add_query(QueryRule {
            matcher: self.matcher,
            parameters: (!parameters.is_empty()).then_some(parameters),
            reply: Arc::new(QueryReply {
                answer,
                bytes_processed: self.bytes_processed,
            }),
            rule: rule.clone(),
        });
        Ok(rule)
    }
}

/// The schema of a table being built and the rows encoded for it so far.
#[derive(Debug)]
struct FakeTableContents {
    schema: BigQueryTableSchema,
    batches: Vec<RecordBatch>,
    rows: u64,
}

/// A table being built, from [`BigQueryFake::table`].
///
/// The builder methods never fail. Columns `.plan()` would refuse and rows that do not encode
/// are kept, and [`create`](Self::create) returns the first such error without creating the
/// table.
#[derive(Debug)]
#[must_use]
pub struct BigQueryFakeTableBuilder<'a> {
    fake: &'a BigQueryFake,
    table: BigQueryTableRef,
    contents: BigQueryResult<FakeTableContents>,
    read_streams: usize,
}

impl BigQueryFakeTableBuilder<'_> {
    /// Adds `rows` after the rows added so far, encoded as a write would encode them.
    pub fn rows<T: Serialize, I: IntoIterator<Item = T>>(mut self, rows: I) -> Self {
        if let Ok(contents) = &mut self.contents {
            match ProtoBatchBuilder::encode(&contents.schema, rows, contents.rows) {
                Ok(batch) => {
                    contents.rows += batch.num_rows() as u64;
                    contents.batches.push(batch);
                }
                Err(failure) => self.contents = Err(failure),
            }
        }
        self
    }

    /// The number of streams a read session of the table has, 1 by default. The rows are
    /// spread over them. [`create`](Self::create) refuses 0.
    pub fn read_streams(mut self, streams: usize) -> Self {
        self.read_streams = streams;
        self
    }

    /// Creates the table, and its dataset if that is missing.
    ///
    /// # Errors
    /// The error the builder kept, [`BigQueryError::InvalidParametersError`] for
    /// `read_streams(0)`, and [`BigQueryError::DataConflictError`] if the table exists.
    pub fn create(self) -> BigQueryResult<()> {
        let contents = self.contents?;
        let read_streams = NonZeroUsize::new(self.read_streams).ok_or_else(|| {
            BigQueryError::invalid_parameters(
                "read_streams",
                format!("{} would have no read stream; pass 1 or more", self.table),
            )
        })?;
        let key = TableKey::resolve(&self.table, self.fake.shared.project());
        let mut state = self.fake.shared.state();
        let generation = state.next_generation();
        let table = FakeTable::new(contents.schema, contents.batches, read_streams, generation);
        state.create_table(key, table)
    }
}

/// A rule for the read sessions of one table, from [`BigQueryFake::when_read`].
#[derive(Debug)]
#[must_use]
pub struct BigQueryFakeReadBuilder<'a> {
    fake: &'a BigQueryFake,
    table: BigQueryTableRef,
    row_restriction: Option<String>,
    times: Option<usize>,
}

impl BigQueryFakeReadBuilder<'_> {
    /// Matches sessions with exactly this `row_restriction`, as the code under test sends it.
    /// Unset, the rule matches sessions without one.
    pub fn row_restriction(mut self, restriction: impl Into<String>) -> Self {
        self.row_restriction = Some(restriction.into());
        self
    }

    /// Answers exactly `calls` sessions, as [`BigQueryFakeQueryBuilder::times`] does.
    pub fn times(mut self, calls: usize) -> Self {
        self.times = Some(calls);
        self
    }

    /// Answers the session with `rows` instead of the table's own, encoded as the table's
    /// columns say.
    ///
    /// # Errors
    /// [`BigQueryError::DataNotFoundError`] if the table does not exist, the `times` error the
    /// builder kept, and [`BigQueryError::SerializeError`] naming the row and field of a row
    /// that does not encode.
    pub fn returns_rows<T: Serialize, I: IntoIterator<Item = T>>(
        self,
        rows: I,
    ) -> BigQueryResult<BigQueryFakeRule> {
        let table = TableKey::resolve(&self.table, self.fake.shared.project());
        let schema = self.fake.shared.state().table(&table)?.schema.clone();
        let rows = ProtoBatchBuilder::encode(&schema, rows, 0)?;
        let description = match &self.row_restriction {
            Some(restriction) => format!("read of {table} where {restriction:?}"),
            None => format!("read of {table}"),
        };
        let rule = BigQueryFakeRule::limited(description, self.times)?;
        self.fake.shared.rules().add_read(ReadRule {
            table,
            row_restriction: self.row_restriction,
            rows,
            rule: rule.clone(),
        });
        Ok(rule)
    }
}

/// A fault being built, from [`BigQueryFake::when_fault`].
#[derive(Debug)]
#[must_use]
pub struct BigQueryFakeFaultBuilder<'a> {
    fake: &'a BigQueryFake,
    rpc: BigQueryFakeRpc,
    table: Option<BigQueryTableRef>,
    times: Option<usize>,
}

impl BigQueryFakeFaultBuilder<'_> {
    /// Narrows the fault to the calls on `table`. [`fails`](Self::fails) refuses it for an
    /// RPC whose calls name no table, such as `GetJob` or the dataset RPCs.
    pub fn on_table(mut self, table: impl Into<BigQueryTableRef>) -> Self {
        self.table = Some(table.into());
        self
    }

    /// Answers exactly `calls` calls, as [`BigQueryFakeQueryBuilder::times`] does.
    pub fn times(mut self, calls: usize) -> Self {
        self.times = Some(calls);
        self
    }

    /// Fails the calls with `fault`.
    ///
    /// # Errors
    /// [`BigQueryError::InvalidParametersError`] for the field `on_table` when the RPC names
    /// no table, and the `times` error the builder kept.
    pub fn fails(self, fault: BigQueryFakeFault) -> BigQueryResult<BigQueryFakeRule> {
        let rpc = self.rpc;
        let table = self
            .table
            .map(|table| TableKey::resolve(&table, self.fake.shared.project()));
        if table.is_some() && !rpc.names_a_table() {
            return Err(BigQueryError::invalid_parameters(
                "on_table",
                format!("{rpc:?} calls name no table"),
            ));
        }
        let description = match &table {
            Some(table) => format!("fault on {rpc:?} of {table}"),
            None => format!("fault on {rpc:?}"),
        };
        let rule = BigQueryFakeRule::limited(description, self.times)?;
        self.fake.shared.rules().add_fault(FaultRule {
            rpc,
            table,
            fault,
            rule: rule.clone(),
        });
        Ok(rule)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::BigQueryDatasetId;
    use serde::Deserialize;
    use std::panic::{catch_unwind, AssertUnwindSafe};

    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
    struct Order {
        id: i64,
        customer: String,
        total: f64,
        paid: bool,
        receipt: Option<Vec<u8>>,
    }

    const ORDERS_OF: &str =
        "SELECT id, customer, total, paid, receipt FROM shop.orders WHERE customer = @customer";

    fn paid(id: i64, customer: &str, total: f64, receipt: &[u8]) -> Order {
        Order {
            id,
            customer: customer.to_string(),
            total,
            paid: true,
            receipt: Some(receipt.to_vec()),
        }
    }

    fn unpaid(id: i64, customer: &str, total: f64) -> Order {
        Order {
            id,
            customer: customer.to_string(),
            total,
            paid: false,
            receipt: None,
        }
    }

    async fn orders_of(db: &BigQueryDb, customer: &str) -> BigQueryResult<Vec<Order>> {
        db.fluent()
            .query(ORDERS_OF)
            .param("customer", customer)
            .obj()
            .query()
            .await
    }

    /// Whether dropping `fake`, which verifies it, panics.
    fn drop_panics(fake: BigQueryFake) -> bool {
        catch_unwind(AssertUnwindSafe(move || drop(fake))).is_err()
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn spawned_tasks_share_one_fake() -> BigQueryResult<()> {
        let fake = Arc::new(BigQueryFake::start().await?);
        let orders = vec![unpaid(1, "Alice", 12.0)];
        let rule = fake
            .when_query_match(ORDERS_OF)
            .returns_rows(|columns| columns.from_type::<Order>(), &orders)?;

        let spawned = tokio::spawn({
            let fake = Arc::clone(&fake);
            async move {
                fake.db()
                    .fluent()
                    .query(ORDERS_OF)
                    .param("customer", "Alice")
                    .obj::<Order>()
                    .query()
                    .await
            }
        });

        assert_eq!(spawned.await.expect("the task panicked")?, orders);
        assert_eq!(rule.calls(), 1);
        Ok(())
    }

    #[tokio::test]
    async fn a_rule_answers_its_query_inline() -> BigQueryResult<()> {
        let fake = BigQueryFake::start().await?;
        let orders = vec![
            paid(1, "Alice", 120.0, &[0, 159, 255]),
            unpaid(2, "Alice", -0.5),
        ];
        let rule = fake
            .when_query_match(ORDERS_OF)
            .returns_rows(|columns| columns.from_type::<Order>(), &orders)?;

        let (rows, stats) = fake
            .db()
            .fluent()
            .query(ORDERS_OF)
            .param("customer", "Alice")
            .obj::<Order>()
            .query_with_stats()
            .await?;

        assert_eq!(rows, orders);
        assert_eq!(stats.total_rows, Some(2));
        assert_eq!(stats.statement_type, Some(BigQueryStatementType::Select));
        assert_eq!(rule.calls(), 1);
        Ok(())
    }

    #[tokio::test]
    async fn an_unmatched_query_fails_verify() -> BigQueryResult<()> {
        let fake = BigQueryFake::start().await?;
        fake.when_query_match("SELECT 1")
            .returns_rows(|columns| columns.from_type::<Order>(), Vec::<Order>::new())?;

        let unmatched = orders_of(fake.db(), "Alice").await;

        match &unmatched {
            Err(BigQueryError::DatabaseError(err)) => {
                assert_eq!(err.public.code, "Unimplemented");
                assert!(!err.retry_possible);
            }
            other => panic!("expected the unmatched call to fail, got {other:?}"),
        }
        assert!(catch_unwind(AssertUnwindSafe(|| fake.verify())).is_err());
        assert!(drop_panics(fake));
        Ok(())
    }

    #[tokio::test]
    async fn a_times_rule_not_used_up_fails_verify() -> BigQueryResult<()> {
        let fake = BigQueryFake::start().await?;
        let orders = vec![unpaid(1, "Alice", 120.0)];
        let rule = fake
            .when_query_match(ORDERS_OF)
            .times(2)
            .returns_rows(|columns| columns.from_type::<Order>(), &orders)?;

        assert_eq!(orders_of(fake.db(), "Alice").await?, orders);

        assert_eq!(rule.calls(), 1);
        assert!(drop_panics(fake));
        Ok(())
    }

    #[tokio::test]
    async fn params_must_match_once_declared() -> BigQueryResult<()> {
        let fake = BigQueryFake::start().await?;
        let alice = vec![unpaid(1, "Alice", 120.0)];
        let anyone = vec![paid(2, "Bob", 80.5, b"r-2"), unpaid(3, "Carol", 7.0)];
        let for_alice = fake
            .when_query_match(ORDERS_OF)
            .param("customer", "Alice")
            .returns_rows(|columns| columns.from_type::<Order>(), &alice)?;
        let for_anyone = fake
            .when_query_match(ORDERS_OF)
            .returns_rows(|columns| columns.from_type::<Order>(), &anyone)?;

        assert_eq!(orders_of(fake.db(), "Bob").await?, anyone);
        assert_eq!(orders_of(fake.db(), "Alice").await?, alice);

        assert_eq!((for_alice.calls(), for_anyone.calls()), (1, 1));
        Ok(())
    }

    #[tokio::test]
    async fn creating_a_dataset_that_exists_is_a_data_conflict() -> BigQueryResult<()> {
        let fake = BigQueryFake::start().await?;
        const SHOP: BigQueryDatasetId = BigQueryDatasetId::from_static("shop");
        fake.create_dataset(SHOP)?;

        let again = fake.create_dataset(SHOP);

        assert!(
            matches!(again, Err(BigQueryError::DataConflictError(_))),
            "{again:?}"
        );
        Ok(())
    }

    #[tokio::test]
    async fn a_rule_mixing_named_and_positional_parameters_is_refused() -> BigQueryResult<()> {
        let fake = BigQueryFake::start().await?;

        let registered = fake
            .when_query_match(ORDERS_OF)
            .param("customer", "Alice")
            .positional_param(1)
            .returns_rows(|columns| columns.from_type::<Order>(), Vec::<Order>::new());

        match registered {
            Err(BigQueryError::InvalidParametersError(err)) => {
                assert_eq!(err.public.field, "query_parameters");
            }
            other => panic!("expected the rule to be refused, got {other:?}"),
        }
        Ok(())
    }

    #[tokio::test]
    async fn named_parameters_must_equal_the_rule_as_a_set() -> BigQueryResult<()> {
        let fake = BigQueryFake::start().await?;
        fake.when_query_match(ORDERS_OF)
            .param("customer", "Alice")
            .param("customer", "Alice")
            .returns_rows(|columns| columns.from_type::<Order>(), Vec::<Order>::new())?;

        let unmatched: BigQueryResult<Vec<Order>> = fake
            .db()
            .fluent()
            .query(ORDERS_OF)
            .param("customer", "Alice")
            .param("since", 2020)
            .obj()
            .query()
            .await;

        match &unmatched {
            Err(BigQueryError::DatabaseError(err)) => assert_eq!(err.public.code, "Unimplemented"),
            other => panic!("expected the call to go unmatched, got {other:?}"),
        }
        assert!(drop_panics(fake));
        Ok(())
    }

    fn assert_unmatched<T: Debug>(call: &BigQueryResult<T>) {
        match call {
            Err(BigQueryError::DatabaseError(err)) => assert_eq!(err.public.code, "Unimplemented"),
            other => panic!("expected the call to go unmatched, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn a_when_query_matcher_sees_the_sql_and_a_named_param() -> BigQueryResult<()> {
        let fake = BigQueryFake::start().await?;
        let alice = vec![unpaid(1, "Alice", 120.0)];
        let rule = fake
            .when_query(|query| {
                query.sql() == ORDERS_OF
                    && query.param::<String>("customer").as_deref() == Some("Alice")
            })
            .returns_rows(|columns| columns.from_type::<Order>(), &alice)?;

        assert_eq!(orders_of(fake.db(), "Alice").await?, alice);
        assert_unmatched(&orders_of(fake.db(), "Bob").await);

        assert_eq!(rule.calls(), 1);
        assert!(drop_panics(fake));
        Ok(())
    }

    #[tokio::test]
    async fn a_when_query_matcher_reads_param_names_ignoring_case() -> BigQueryResult<()> {
        let fake = BigQueryFake::start().await?;
        let alice = vec![unpaid(1, "Alice", 120.0)];
        let rule = fake
            .when_query(|query| query.param::<String>("CUSTOMER").as_deref() == Some("Alice"))
            .returns_rows(|columns| columns.from_type::<Order>(), &alice)?;

        assert_eq!(orders_of(fake.db(), "Alice").await?, alice);

        assert_eq!(rule.calls(), 1);
        Ok(())
    }

    #[tokio::test]
    async fn a_when_query_matcher_sees_a_positional_param() -> BigQueryResult<()> {
        const ORDER_BY_ID: &str =
            "SELECT id, customer, total, paid, receipt FROM shop.orders WHERE id = ?";
        let fake = BigQueryFake::start().await?;
        let second = vec![unpaid(2, "Bob", 80.5)];
        let rule = fake
            .when_query(|query| query.positional_param::<i64>(0) == Some(2))
            .returns_rows(|columns| columns.from_type::<Order>(), &second)?;
        let order_by_id = |id: i64| {
            fake.db()
                .fluent()
                .query(ORDER_BY_ID)
                .positional_param(id)
                .obj::<Order>()
                .query()
        };

        assert_eq!(order_by_id(2).await?, second);
        assert_unmatched(&order_by_id(3).await);

        assert_eq!(rule.calls(), 1);
        assert!(drop_panics(fake));
        Ok(())
    }

    #[tokio::test]
    async fn a_named_param_that_does_not_decode_as_t_is_none() -> BigQueryResult<()> {
        let fake = BigQueryFake::start().await?;
        let rule = fake
            .when_query(|query| query.param::<i64>("customer").is_some())
            .returns_rows(|columns| columns.from_type::<Order>(), Vec::<Order>::new())?;

        assert_unmatched(&orders_of(fake.db(), "Alice").await);

        assert_eq!(rule.calls(), 0);
        assert!(drop_panics(fake));
        Ok(())
    }

    #[tokio::test]
    async fn param_decodes_array_struct_and_range_values() -> BigQueryResult<()> {
        use crate::{BigQueryDate, BigQueryRange};
        use std::sync::Mutex;

        #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
        struct Filter {
            customer: String,
            since: BigQueryDate,
            tags: Vec<String>,
        }

        const FILTERED: &str = "SELECT id FROM shop.orders \
            WHERE id IN UNNEST(@ids) AND customer = @filter.customer AND day <@ @days";
        let day = |day: i8| BigQueryDate(jiff::civil::date(2024, 3, day));
        let ids = vec![1_i64, 2, 3];
        let filter = Filter {
            customer: "Alice".into(),
            since: day(1),
            tags: vec!["vip".into(), "eu".into()],
        };
        let days = BigQueryRange {
            start: Some(day(1)),
            end: None,
        };

        type Seen = (
            Option<Vec<i64>>,
            Option<Filter>,
            Option<BigQueryRange<BigQueryDate>>,
        );
        let fake = BigQueryFake::start().await?;
        let seen: Arc<Mutex<Option<Seen>>> = Arc::default();
        let recorded = seen.clone();
        fake.when_query(move |query| {
            *recorded.lock().expect("no test thread panics holding it") = Some((
                query.param("ids"),
                query.param("filter"),
                query.param("days"),
            ));
            true
        })
        .returns_statement(BigQueryStatementType::Select)?;

        fake.db()
            .fluent()
            .query(FILTERED)
            .param("ids", &ids)
            .param("filter", &filter)
            .param("days", days)
            .execute()
            .await?;

        let seen = seen
            .lock()
            .expect("no test thread panics holding it")
            .take();
        assert_eq!(seen, Some((Some(ids), Some(filter), Some(days))));
        Ok(())
    }

    #[tokio::test]
    async fn param_narrows_a_when_query_matcher() -> BigQueryResult<()> {
        let fake = BigQueryFake::start().await?;
        let alice = vec![unpaid(1, "Alice", 120.0)];
        let rule = fake
            .when_query(|query| query.sql().starts_with("SELECT"))
            .param("customer", "Alice")
            .returns_rows(|columns| columns.from_type::<Order>(), &alice)?;

        assert_eq!(orders_of(fake.db(), "Alice").await?, alice);
        assert_unmatched(&orders_of(fake.db(), "Bob").await);

        assert_eq!(rule.calls(), 1);
        assert!(drop_panics(fake));
        Ok(())
    }
}