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
//! Validated newtypes for BigQuery dataset and table IDs.
//!
//! Both types follow the same shape: [`new`](BigQueryDatasetId::new) and the `TryFrom`/`FromStr`
//! impls validate at run time, and `const fn from_static` validates a literal at compile time.
//! Both share one rule function. The project ID is not here: it is one value for every Google
//! Cloud product, and stays a plain `String`.
//!
//! The rule is deliberately narrow. It rejects only what would change how the crate builds a
//! resource path (`projects/{p}/datasets/{d}/tables/{t}`), a dotted reference (`p.ds.t`) or SQL
//! text from the ID. Everything else, Unicode and BigQuery's own naming rules included, is the
//! server's to accept or reject.

use crate::errors::BigQueryError;
use crate::{BigQueryResult, BigQueryTableRef};
use serde::{Deserialize, Serialize, Serializer};
use std::borrow::Cow;
use std::fmt::{Display, Formatter};
use std::str::FromStr;

/// The most a dataset ID or a table ID may hold, in UTF-8 bytes; BigQuery's own limit for both.
const MAX_ID_BYTES: usize = 1024;

/// The ASCII characters an ID may not contain besides control characters: quotes and the
/// backslash would end or escape a quoted SQL identifier or string, `.` and `/` separate the parts
/// of a dotted reference and a resource path, and `$` and `@` start BigQuery's partition and
/// snapshot decorators.
const FORBIDDEN_ASCII: &[u8] = b"`'\"\\./$@";

/// The one rule an ID fails, if any.
#[derive(Clone, Copy)]
enum IdViolation {
    Empty,
    TooLong {
        length: usize,
    },
    /// The character starting at byte `at` is not allowed.
    InvalidChar {
        at: usize,
    },
}

impl IdViolation {
    /// The rule as a phrase, the same for both callers.
    ///
    /// `from_static` panics with it bare: formatting is not `const` on stable Rust, and the
    /// failing `const` item already points `rustc` at the bad literal. The run-time path adds
    /// the field name and the offending part.
    const fn rule(self) -> &'static str {
        match self {
            Self::Empty => "must not be empty",
            Self::TooLong { .. } => "must be at most 1,024 UTF-8 bytes",
            Self::InvalidChar { .. } => {
                "must not contain control characters or any of ` ' \" \\ . / $ @"
            }
        }
    }

    /// The error for `id` under the field name `field`.
    fn into_error(self, field: &'static str, id: &str) -> BigQueryError {
        let rule = self.rule();
        let error = match self {
            Self::Empty => rule.to_string(),
            // The value is unbounded here, so the message gives its length, not the value.
            Self::TooLong { length } => format!("{rule}, was {length} bytes"),
            Self::InvalidChar { at } => {
                let ch = id[at..]
                    .chars()
                    .next()
                    .expect("`at` is the start of the character the check rejected");
                format!(
                    "{rule}; got {ch:?} at byte {at} of \"{}\"",
                    id.escape_debug()
                )
            }
        };
        BigQueryError::invalid_parameters(field, error)
    }
}

/// Checks a dataset or table ID: not empty, at most [`MAX_ID_BYTES`], and free of control
/// characters (as [`char::is_control`]) and of [`FORBIDDEN_ASCII`].
///
/// `str` methods are not `const fn`, so this walks the bytes by hand; that is what lets
/// `from_static` run at compile time. Every forbidden character but the C1 controls is ASCII. The
/// C1 controls, U+0080 to U+009F, are the only characters encoded as `0xC2` followed by
/// `0x80..=0x9F`; `id` is valid UTF-8, so a `0xC2` byte always starts a character and needs no
/// further decoding.
const fn check_id(id: &str) -> Result<(), IdViolation> {
    let bytes = id.as_bytes();
    let length = bytes.len();
    if length == 0 {
        return Err(IdViolation::Empty);
    }
    if length > MAX_ID_BYTES {
        return Err(IdViolation::TooLong { length });
    }
    let mut index = 0;
    while index < length {
        let byte = bytes[index];
        let c1_control = byte == 0xC2
            && index + 1 < length
            && bytes[index + 1] >= 0x80
            && bytes[index + 1] <= 0x9F;
        if byte.is_ascii_control() || c1_control || is_forbidden_ascii(byte) {
            return Err(IdViolation::InvalidChar { at: index });
        }
        index += 1;
    }
    Ok(())
}

/// Whether `byte` is in [`FORBIDDEN_ASCII`]; a loop because slice methods are not `const fn`.
const fn is_forbidden_ascii(byte: u8) -> bool {
    let mut index = 0;
    while index < FORBIDDEN_ASCII.len() {
        if FORBIDDEN_ASCII[index] == byte {
            return true;
        }
        index += 1;
    }
    false
}

/// A BigQuery dataset ID, checked only for what would let it reshape a path or a query.
///
/// An ID is rejected when it is empty, longer than 1,024 UTF-8 bytes, or holds a control
/// character or any of `` ` ``, `'`, `"`, `\`, `.`, `/`, `$` and `@`. Quotes and the backslash
/// would end or escape a quoted identifier in SQL text, `.` and `/` separate the parts of
/// `p.ds.t` and `projects/{p}/datasets/{d}`, and `$` and `@` start BigQuery's partition and
/// snapshot decorators. The full naming rules are BigQuery's to enforce: an ID that passes here
/// can still be refused by the server, at the call that sends it.
///
/// Declare the datasets an application knows up front as constants, and build tables in them
/// with [`table`](Self::table):
///
/// ```rust
/// use bigquery::{BigQueryDatasetId, BigQueryTableId};
///
/// const SHOP: BigQueryDatasetId = BigQueryDatasetId::from_static("shop");
/// const ORDERS: BigQueryTableId = BigQueryTableId::from_static("orders");
///
/// let orders = SHOP.table(ORDERS);
/// assert_eq!(orders.to_string(), "shop.orders");
/// ```
///
/// A name that arrives at run time goes through [`new`](Self::new), `parse()` or `try_into()`;
/// deserializing validates the same way:
///
/// ```rust
/// use bigquery::BigQueryDatasetId;
///
/// let shop = BigQueryDatasetId::new("shop_eu")?;
/// assert_eq!(shop.to_string(), "shop_eu");
///
/// assert!(BigQueryDatasetId::new("shop.eu").is_err());
/// # Ok::<(), bigquery::errors::BigQueryError>(())
/// ```
///
/// Dataset IDs are case-sensitive, and one that starts with `_` is a hidden dataset.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize)]
#[serde(try_from = "String")]
pub struct BigQueryDatasetId(Cow<'static, str>);

impl BigQueryDatasetId {
    /// Validates `id` and wraps it.
    ///
    /// # Errors
    /// [`BigQueryError::InvalidParametersError`] for the field `dataset_id` if `id` breaks the
    /// rule in the [type docs](Self); the message names the first rejected character and its
    /// byte offset.
    pub fn new(id: impl Into<String>) -> BigQueryResult<Self> {
        let id = id.into();
        match check_id(&id) {
            Ok(()) => Ok(Self(Cow::Owned(id))),
            Err(violation) => Err(violation.into_error("dataset_id", &id)),
        }
    }

    /// Validates `id` at compile time and wraps it without allocating.
    ///
    /// In a `const` or `static` item an invalid literal fails the build:
    ///
    /// ```compile_fail
    /// use bigquery::BigQueryDatasetId;
    /// const BAD: BigQueryDatasetId = BigQueryDatasetId::from_static("shop.eu");
    /// ```
    ///
    /// # Panics
    /// On an invalid `id` when called at run time, under the same rules as [`new`](Self::new).
    pub const fn from_static(id: &'static str) -> Self {
        match check_id(id) {
            Ok(()) => Self(Cow::Borrowed(id)),
            Err(violation) => panic!("{}", violation.rule()),
        }
    }

    /// The table `table` in this dataset, in the client's project.
    pub fn table(&self, table: BigQueryTableId) -> BigQueryTableRef {
        BigQueryTableRef::new(None, self.clone(), table)
    }

    /// The ID, for the crate's wire encoding.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Display for BigQueryDatasetId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Display::fmt(self.0.as_ref(), f)
    }
}

impl TryFrom<&str> for BigQueryDatasetId {
    type Error = BigQueryError;

    fn try_from(id: &str) -> Result<Self, Self::Error> {
        Self::new(id)
    }
}

impl TryFrom<String> for BigQueryDatasetId {
    type Error = BigQueryError;

    fn try_from(id: String) -> Result<Self, Self::Error> {
        Self::new(id)
    }
}

impl FromStr for BigQueryDatasetId {
    type Err = BigQueryError;

    fn from_str(id: &str) -> Result<Self, Self::Err> {
        Self::new(id)
    }
}

impl Serialize for BigQueryDatasetId {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

/// A BigQuery table ID, checked only for what would let it reshape a path or a query.
///
/// The rule is the one [`BigQueryDatasetId`] applies: an ID is rejected when it is empty, longer
/// than 1,024 UTF-8 bytes, or holds a control character or any of `` ` ``, `'`, `"`, `\`, `.`,
/// `/`, `$` and `@`. Rejecting `$` and `@` keeps a plain table ID from silently becoming a
/// partition decorator such as `orders$20250101` or a snapshot decorator such as
/// `orders@1700000000000`. Unicode, spaces and dashes pass; the full naming rules are BigQuery's
/// to enforce, and an ID it refuses fails at the call that sends it.
///
/// ```rust
/// use bigquery::BigQueryTableId;
///
/// const ORDERS: BigQueryTableId = BigQueryTableId::from_static("orders");
/// assert_eq!(ORDERS.to_string(), "orders");
///
/// assert!(BigQueryTableId::new("étudiant-01").is_ok());
/// assert!(BigQueryTableId::new("table 01").is_ok());
///
/// assert!(BigQueryTableId::new("orders`; DROP").is_err());
/// ```
///
/// Table IDs are case-sensitive.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize)]
#[serde(try_from = "String")]
pub struct BigQueryTableId(Cow<'static, str>);

impl BigQueryTableId {
    /// Validates `id` and wraps it.
    ///
    /// # Errors
    /// [`BigQueryError::InvalidParametersError`] for the field `table_id` if `id` breaks the
    /// rule in the [type docs](Self); the message names the first rejected character and its
    /// byte offset.
    pub fn new(id: impl Into<String>) -> BigQueryResult<Self> {
        let id = id.into();
        match check_id(&id) {
            Ok(()) => Ok(Self(Cow::Owned(id))),
            Err(violation) => Err(violation.into_error("table_id", &id)),
        }
    }

    /// Validates `id` at compile time and wraps it without allocating.
    ///
    /// In a `const` or `static` item an invalid literal fails the build:
    ///
    /// ```compile_fail
    /// use bigquery::BigQueryTableId;
    /// const BAD: BigQueryTableId = BigQueryTableId::from_static("shop.orders");
    /// ```
    ///
    /// # Panics
    /// On an invalid `id` when called at run time, under the same rules as [`new`](Self::new).
    pub const fn from_static(id: &'static str) -> Self {
        match check_id(id) {
            Ok(()) => Self(Cow::Borrowed(id)),
            Err(violation) => panic!("{}", violation.rule()),
        }
    }

    /// The ID, for the crate's wire encoding.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Display for BigQueryTableId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Display::fmt(self.0.as_ref(), f)
    }
}

impl TryFrom<&str> for BigQueryTableId {
    type Error = BigQueryError;

    fn try_from(id: &str) -> Result<Self, Self::Error> {
        Self::new(id)
    }
}

impl TryFrom<String> for BigQueryTableId {
    type Error = BigQueryError;

    fn try_from(id: String) -> Result<Self, Self::Error> {
        Self::new(id)
    }
}

impl FromStr for BigQueryTableId {
    type Err = BigQueryError;

    fn from_str(id: &str) -> Result<Self, Self::Err> {
        Self::new(id)
    }
}

impl Serialize for BigQueryTableId {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::errors::BigQueryInvalidParametersError;
    use proptest::prelude::*;

    /// The field and the message of an invalid-parameters error.
    fn invalid<T: std::fmt::Debug>(result: BigQueryResult<T>) -> (String, String) {
        match result {
            Err(BigQueryError::InvalidParametersError(BigQueryInvalidParametersError {
                public,
            })) => (public.field, public.error),
            other => panic!("expected an invalid-parameters error, got {other:?}"),
        }
    }

    /// Each class of ID the crate rejects, for both ID types: the ones that would change how a
    /// resource path or SQL text is built from the ID.
    #[test]
    fn ids_that_could_reshape_a_path_or_sql_are_rejected() {
        let over_limit = "é".repeat(513);
        let cases = [
            ("", "empty"),
            (over_limit.as_str(), "over 1,024 bytes"),
            ("ord\0ers", "NUL"),
            ("ord\ners", "newline"),
            ("ord\rers", "carriage return"),
            ("ord\ters", "tab"),
            ("ord\u{7f}ers", "DEL"),
            ("ord\u{85}ers", "C1 control"),
            ("ord`ers", "backtick"),
            ("ord'ers", "single quote"),
            ("ord\"ers", "double quote"),
            ("ord\\ers", "backslash"),
            ("shop.orders", "part separator"),
            ("shop/orders", "path separator"),
            ("orders$20250101", "partition decorator"),
            ("orders@1700000000000", "snapshot decorator"),
        ];
        for (id, class) in cases {
            assert_eq!(
                invalid(BigQueryDatasetId::new(id)).0,
                "dataset_id",
                "{class}: {id:?}"
            );
            assert_eq!(
                invalid(BigQueryTableId::new(id)).0,
                "table_id",
                "{class}: {id:?}"
            );
        }
    }

    /// Anything else is BigQuery's to accept or reject, so the crate lets it through.
    #[test]
    fn other_ids_are_left_to_bigquery() {
        let at_limit = "é".repeat(512);
        for id in [
            "orders",
            "shop-eu",
            "table 01",
            "étudiant-01",
            "00_お客様",
            "ord😀ers",
            "a+b;c",
            at_limit.as_str(),
        ] {
            assert!(BigQueryDatasetId::new(id).is_ok(), "{id:?}");
            assert!(BigQueryTableId::new(id).is_ok(), "{id:?}");
        }
    }

    #[test]
    fn an_invalid_character_error_carries_no_raw_control_character() {
        let (_, message) = invalid(BigQueryDatasetId::new("sh\nop"));
        assert!(!message.contains('\n'), "{message:?}");
    }

    #[test]
    fn an_oversized_id_error_leaves_the_value_out() {
        let (_, message) = invalid(BigQueryTableId::new("x".repeat(10_000)));
        assert!(!message.contains(&"x".repeat(10)), "{message}");
    }

    const SHOP: BigQueryDatasetId = BigQueryDatasetId::from_static("shop");
    static ORDERS: BigQueryTableId = BigQueryTableId::from_static("orders");

    #[test]
    fn from_static_agrees_with_new() {
        assert_eq!(
            SHOP,
            BigQueryDatasetId::new("shop").expect("valid test input")
        );
        assert_eq!(
            ORDERS,
            BigQueryTableId::new("orders").expect("valid test input")
        );
    }

    #[test]
    #[should_panic]
    fn from_static_panics_at_run_time_on_a_bad_literal() {
        let _ = BigQueryDatasetId::from_static("shop.eu");
    }

    #[test]
    fn deserializing_validates() {
        let shop: BigQueryDatasetId = serde_json::from_str("\"shop\"").expect("valid test input");
        assert_eq!(shop, BigQueryDatasetId::from_static("shop"));
        assert!(serde_json::from_str::<BigQueryDatasetId>("\"shop.eu\"").is_err());
        assert!(serde_json::from_str::<BigQueryTableId>("\"a.b\"").is_err());
        assert_eq!(
            serde_json::to_string(&ORDERS).expect("valid test input"),
            "\"orders\""
        );
    }

    proptest! {
        /// The byte walk in the const check rejects exactly the characters `char` names.
        #[test]
        fn the_id_check_agrees_with_char(id in any::<String>()) {
            let expected = !id.is_empty()
                && id.len() <= 1024
                && !id.chars().any(|c| c.is_control() || "`'\"\\./$@".contains(c));
            prop_assert_eq!(check_id(&id).is_ok(), expected);
        }
    }
}