firestore 0.61.1

Library provides a simple API for Google Firestore and own Serde serializer based on efficient gRPC API
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
//! Builder for constructing Firestore list operations.
//!
//! This module provides a fluent API for listing documents within a collection
//! or listing collection IDs under a parent document (or the database root).
//! It supports pagination, ordering (for document listing), and projections.

use crate::select_order_builder::FirestoreQueryOrderBuilder;
use crate::{
    FirestoreListCollectionIdsParams, FirestoreListCollectionIdsResult, FirestoreListDocParams,
    FirestoreListDocResult, FirestoreListingSupport, FirestoreQueryOrder, FirestoreRequestOptions,
    FirestoreRequestTag, FirestoreResult,
};
use futures::stream::BoxStream;
use gcloud_sdk::google::firestore::v1::Document;
use serde::Deserialize;
use std::marker::PhantomData;

/// The initial builder for a Firestore list operation.
///
/// Created by calling [`FirestoreExprBuilder::list()`](crate::FirestoreExprBuilder::list).
/// From here, you can choose to list documents from a collection or list collection IDs.
#[derive(Clone, Debug)]
pub struct FirestoreListingInitialBuilder<'a, D>
where
    D: FirestoreListingSupport,
{
    db: &'a D,
    return_only_fields: Option<Vec<String>>,
}

impl<'a, D> FirestoreListingInitialBuilder<'a, D>
where
    D: FirestoreListingSupport,
{
    #[inline]
    pub(crate) fn new(db: &'a D) -> Self {
        Self {
            db,
            return_only_fields: None,
        }
    }

    /// Specifies which fields of the documents should be returned when listing documents.
    ///
    /// This is a projection. If not set, all fields are returned.
    /// This option is only applicable when listing documents, not collection IDs.
    #[inline]
    pub fn fields<I>(self, return_only_fields: I) -> Self
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        Self {
            return_only_fields: Some(
                return_only_fields
                    .into_iter()
                    .map(|field| field.as_ref().to_string())
                    .collect(),
            ),
            ..self
        }
    }

    /// Specifies that documents should be listed from the given collection.
    #[inline]
    pub fn from<S: AsRef<str>>(self, collection: S) -> FirestoreListingDocBuilder<'a, D> {
        let params: FirestoreListDocParams =
            FirestoreListDocParams::new(collection.as_ref().to_string())
                .opt_return_only_fields(self.return_only_fields);
        FirestoreListingDocBuilder::new(self.db, params)
    }

    /// Specifies that collection IDs should be listed.
    #[inline]
    pub fn collections(self) -> FirestoreListCollectionIdsBuilder<'a, D> {
        FirestoreListCollectionIdsBuilder::new(self.db)
    }
}

/// A builder for configuring and executing a document listing operation.
#[derive(Clone, Debug)]
pub struct FirestoreListingDocBuilder<'a, D>
where
    D: FirestoreListingSupport,
{
    db: &'a D,
    params: FirestoreListDocParams,
}

impl<'a, D> FirestoreListingDocBuilder<'a, D>
where
    D: FirestoreListingSupport,
{
    #[inline]
    pub(crate) fn new(db: &'a D, params: FirestoreListDocParams) -> Self {
        Self { db, params }
    }

    /// Specifies that the listed documents should be deserialized into a specific Rust type `T`.
    #[inline]
    pub fn obj<T>(self) -> FirestoreListingObjBuilder<'a, D, T>
    where
        T: Send,
        for<'de> T: Deserialize<'de>,
    {
        FirestoreListingObjBuilder::new(self.db, self.params)
    }

    /// Specifies the parent document path for listing documents in a sub-collection.
    #[inline]
    pub fn parent<S>(self, parent: S) -> Self
    where
        S: AsRef<str>,
    {
        Self {
            params: self.params.with_parent(parent.as_ref().to_string()),
            ..self
        }
    }

    /// Sets the maximum number of documents to return in a single page.
    #[inline]
    pub fn page_size(self, value: usize) -> Self {
        Self {
            params: self.params.with_page_size(value),
            ..self
        }
    }

    /// Sets the page token for pagination.
    #[inline]
    pub fn page_token(self, value: String) -> Self {
        Self {
            params: self.params.with_page_token(value),
            ..self
        }
    }

    /// Specifies the order in which to sort the documents.
    ///
    /// Each call replaces any ordering set by a previous call; it does not add to it.
    #[deprecated(
        since = "0.55.0",
        note = "Superseded by `.order()`, which takes a closure builder: \
                `.order(|o| o.fields([o.field(path!(T::some_num)).desc()]))`. \
                This method keeps working and will not be removed in 0.x."
    )]
    #[inline]
    pub fn order_by<I>(self, fields: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<FirestoreQueryOrder>,
    {
        Self {
            params: self
                .params
                .with_order_by(fields.into_iter().map(|field| field.into()).collect()),
            ..self
        }
    }

    /// Specifies the order in which to sort the documents.
    ///
    /// The `order` argument is a closure that receives a [`FirestoreQueryOrderBuilder`] and
    /// should return a `Vec<FirestoreQueryOrder>`, typically built with
    /// [`FirestoreQueryOrderBuilder::fields`]. Each call replaces any ordering set by a previous
    /// call; it does not add to it.
    #[inline]
    pub fn order<FN>(self, order: FN) -> Self
    where
        FN: Fn(FirestoreQueryOrderBuilder) -> Vec<FirestoreQueryOrder>,
    {
        let orders = order(FirestoreQueryOrderBuilder::new());

        // An ordering whose entries were all conditional and all absent must clear the field
        // rather than store an empty vec: a listing is only served from the cache while
        // `order_by` is None, so an empty vec would silently force every such listing remote.
        Self {
            params: self.params.opt_order_by(if orders.is_empty() {
                None
            } else {
                Some(orders)
            }),
            ..self
        }
    }

    /// Attaches request tags to this listing operation.
    ///
    /// They override any session wide default configured with
    /// [`FirestoreDb::clone_with_request_tags()`](crate::FirestoreDb::clone_with_request_tags).
    #[inline]
    pub fn request_tags<I>(self, request_tags: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<FirestoreRequestTag>,
    {
        self.request_options(FirestoreRequestOptions::from_tags(request_tags))
    }

    /// Attaches request options to this listing operation.
    #[inline]
    pub fn request_options(self, options: FirestoreRequestOptions) -> Self {
        Self {
            params: self.params.with_request_options(options),
            ..self
        }
    }

    /// Fetches one page of documents, with a token for the next page when more remain.
    ///
    /// Returns an error if the request to Firestore fails.
    pub async fn get_page(self) -> FirestoreResult<FirestoreListDocResult> {
        self.db.list_doc(self.params).await
    }

    /// Streams every document, sending further requests to Firestore as needed to page through
    /// the full result.
    ///
    /// An error while streaming terminates the stream early.
    ///
    /// ```rust,no_run
    /// use firestore::FirestoreDb;
    /// use futures::stream::BoxStream;
    /// use futures::StreamExt;
    ///
    /// # async fn example(db: FirestoreDb) -> Result<(), Box<dyn std::error::Error>> {
    /// let mut documents: BoxStream<_> = db.fluent().list().from("users").stream_all().await?;
    /// while let Some(document) = documents.next().await {
    ///     let _ = document;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn stream_all<'b>(self) -> FirestoreResult<BoxStream<'b, Document>> {
        self.db.stream_list_doc(self.params).await
    }

    /// Streams a `FirestoreResult<Document>` per document, paging through the full result, so
    /// one failed request does not end the stream.
    pub async fn stream_all_with_errors<'b>(
        self,
    ) -> FirestoreResult<BoxStream<'b, FirestoreResult<Document>>> {
        self.db.stream_list_doc_with_errors(self.params).await
    }
}

/// A builder for streaming listed documents deserialized into a Rust type `T`.
#[derive(Clone, Debug)]
pub struct FirestoreListingObjBuilder<'a, D, T>
where
    D: FirestoreListingSupport,
    T: Send,
    for<'de> T: Deserialize<'de>,
{
    db: &'a D,
    params: FirestoreListDocParams,
    _pd: PhantomData<T>,
}

impl<'a, D, T> FirestoreListingObjBuilder<'a, D, T>
where
    D: FirestoreListingSupport,
    T: Send,
    for<'de> T: Deserialize<'de>,
{
    pub(crate) fn new(
        db: &'a D,
        params: FirestoreListDocParams,
    ) -> FirestoreListingObjBuilder<'a, D, T> {
        Self {
            db,
            params,
            _pd: PhantomData,
        }
    }

    /// Attaches request tags to this listing operation.
    ///
    /// They override any session wide default configured with
    /// [`FirestoreDb::clone_with_request_tags()`](crate::FirestoreDb::clone_with_request_tags).
    #[inline]
    pub fn request_tags<I>(self, request_tags: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<FirestoreRequestTag>,
    {
        self.request_options(FirestoreRequestOptions::from_tags(request_tags))
    }

    /// Attaches request options to this listing operation.
    #[inline]
    pub fn request_options(self, options: FirestoreRequestOptions) -> Self {
        Self {
            params: self.params.with_request_options(options),
            ..self
        }
    }

    /// Streams every document deserialized into `T`, paging through the full result.
    ///
    /// An error while streaming or deserializing terminates the stream early.
    pub async fn stream_all<'b>(self) -> FirestoreResult<BoxStream<'b, T>>
    where
        T: 'b,
    {
        self.db.stream_list_obj(self.params).await
    }

    /// Streams a `FirestoreResult<T>` per document, paging through the full result, so one
    /// failed fetch or deserialization does not end the stream.
    pub async fn stream_all_with_errors<'b>(
        self,
    ) -> FirestoreResult<BoxStream<'b, FirestoreResult<T>>>
    where
        T: 'b,
    {
        self.db.stream_list_obj_with_errors(self.params).await
    }
}

/// A builder for configuring and executing a collection ID listing operation.
#[derive(Clone, Debug)]
pub struct FirestoreListCollectionIdsBuilder<'a, D>
where
    D: FirestoreListingSupport,
{
    db: &'a D,
    params: FirestoreListCollectionIdsParams,
}

impl<'a, D> FirestoreListCollectionIdsBuilder<'a, D>
where
    D: FirestoreListingSupport,
{
    #[inline]
    pub(crate) fn new(db: &'a D) -> Self {
        Self {
            db,
            params: FirestoreListCollectionIdsParams::new(),
        }
    }

    /// Specifies the parent document path under which to list collection IDs.
    ///
    /// If not specified, collection IDs directly under the database root are listed.
    #[inline]
    pub fn parent<S>(self, parent: S) -> Self
    where
        S: AsRef<str>,
    {
        Self {
            params: self.params.with_parent(parent.as_ref().to_string()),
            ..self
        }
    }

    /// Sets the maximum number of collection IDs to return in a single page.
    #[inline]
    pub fn page_size(self, value: usize) -> Self {
        Self {
            params: self.params.with_page_size(value),
            ..self
        }
    }

    /// Attaches request tags to this listing operation.
    ///
    /// They override any session wide default configured with
    /// [`FirestoreDb::clone_with_request_tags()`](crate::FirestoreDb::clone_with_request_tags).
    #[inline]
    pub fn request_tags<I>(self, request_tags: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<FirestoreRequestTag>,
    {
        self.request_options(FirestoreRequestOptions::from_tags(request_tags))
    }

    /// Attaches request options to this listing operation.
    #[inline]
    pub fn request_options(self, options: FirestoreRequestOptions) -> Self {
        Self {
            params: self.params.with_request_options(options),
            ..self
        }
    }

    /// Fetches one page of collection IDs, with a token for the next page when more remain.
    ///
    /// Returns an error if the request to Firestore fails.
    pub async fn get_page(self) -> FirestoreResult<FirestoreListCollectionIdsResult> {
        self.db.list_collection_ids(self.params).await
    }

    /// Streams every collection ID, paging through the full result.
    ///
    /// An error while streaming terminates the stream early.
    pub async fn stream_all(self) -> FirestoreResult<BoxStream<'a, String>> {
        self.db.stream_list_collection_ids(self.params).await
    }

    /// Streams a `FirestoreResult<String>` per collection ID, paging through the full result, so
    /// one failed request does not end the stream.
    pub async fn stream_all_with_errors(
        self,
    ) -> FirestoreResult<BoxStream<'a, FirestoreResult<String>>> {
        self.db
            .stream_list_collection_ids_with_errors(self.params)
            .await
    }
}

#[cfg(test)]
mod tests {
    use crate::fluent_api::tests::*;
    use crate::fluent_api::FirestoreExprBuilder;
    use crate::{path, FirestoreQueryDirection, FirestoreQueryOrder, FirestoreRequestOptions};

    #[test]
    fn list_doc_builder_request_tags() {
        let builder = FirestoreExprBuilder::new(&mockdb::MockDatabase {})
            .list()
            .from("test")
            .request_tags(["tag-1", "tag-2"]);

        assert_eq!(
            builder.params.request_options,
            Some(FirestoreRequestOptions::from_tags(["tag-1", "tag-2"]))
        )
    }

    #[test]
    fn list_collection_ids_builder_request_tags() {
        let builder = FirestoreExprBuilder::new(&mockdb::MockDatabase {})
            .list()
            .collections()
            .request_tags(["tag-1"]);

        assert_eq!(
            builder.params.request_options,
            Some(FirestoreRequestOptions::from_tags(["tag-1"]))
        )
    }

    #[test]
    fn list_doc_builder_order() {
        let builder = FirestoreExprBuilder::new(&mockdb::MockDatabase {})
            .list()
            .from("test")
            .order(|o| {
                o.fields([
                    o.field(path!(TestStructure::some_num)).desc(),
                    o.field(path!(TestStructure::some_id)).asc(),
                ])
            });

        assert_eq!(
            builder.params.order_by,
            Some(vec![
                FirestoreQueryOrder::new(
                    path!(TestStructure::some_num),
                    FirestoreQueryDirection::Descending
                ),
                FirestoreQueryOrder::new(
                    path!(TestStructure::some_id),
                    FirestoreQueryDirection::Ascending
                ),
            ])
        )
    }

    #[test]
    fn list_doc_builder_order_empty_is_none() {
        let builder = FirestoreExprBuilder::new(&mockdb::MockDatabase {})
            .list()
            .from("test")
            .order(|o| o.fields(Vec::<FirestoreQueryOrder>::new()));

        assert_eq!(builder.params.order_by, None)
    }

    #[test]
    #[allow(deprecated)]
    fn list_doc_builder_order_by_tuples_are_still_accepted() {
        let tuple_builder = FirestoreExprBuilder::new(&mockdb::MockDatabase {})
            .list()
            .from("test")
            .order_by([(
                path!(TestStructure::some_num),
                FirestoreQueryDirection::Descending,
            )]);

        let closure_builder = FirestoreExprBuilder::new(&mockdb::MockDatabase {})
            .list()
            .from("test")
            .order(|o| o.fields([o.field(path!(TestStructure::some_num)).desc()]));

        assert_eq!(tuple_builder.params, closure_builder.params);
    }
}