firestore 0.51.0

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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! 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::{
    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,
{
    /// Creates a new `FirestoreListingInitialBuilder`.
    #[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.
    ///
    /// # Arguments
    /// * `return_only_fields`: An iterator of field paths to return.
    ///
    /// # Returns
    /// The builder instance with the projection mask set.
    #[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.
    ///
    /// # Arguments
    /// * `collection`: The ID of the collection to list documents from.
    ///
    /// # Returns
    /// A [`FirestoreListingDocBuilder`] to further configure and execute the document listing.
    #[inline]
    pub fn from(self, collection: &str) -> FirestoreListingDocBuilder<'a, D> {
        let params: FirestoreListDocParams = FirestoreListDocParams::new(collection.to_string())
            .opt_return_only_fields(self.return_only_fields);
        FirestoreListingDocBuilder::new(self.db, params)
    }

    /// Specifies that collection IDs should be listed.
    ///
    /// # Returns
    /// A [`FirestoreListCollectionIdsBuilder`] to configure and execute the collection ID listing.
    #[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,
{
    /// Creates a new `FirestoreListingDocBuilder`.
    #[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`.
    ///
    /// # Type Parameters
    /// * `T`: The type to deserialize documents into. Must implement `serde::Deserialize`.
    ///
    /// # Returns
    /// A [`FirestoreListingObjBuilder`] for streaming deserialized objects.
    #[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.
    ///
    /// # Arguments
    /// * `parent`: The full path to the parent document.
    ///
    /// # Returns
    /// The builder instance with the parent path set.
    #[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.
    ///
    /// # Arguments
    /// * `value`: The page size.
    ///
    /// # Returns
    /// The builder instance with the page size set.
    #[inline]
    pub fn page_size(self, value: usize) -> Self {
        Self {
            params: self.params.with_page_size(value),
            ..self
        }
    }

    /// Sets the page token for pagination.
    ///
    /// # Arguments
    /// * `value`: The page token from a previous listing operation.
    ///
    /// # Returns
    /// The builder instance with the page token set.
    #[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.
    ///
    /// # Arguments
    /// * `fields`: An iterator of [`FirestoreQueryOrder`] specifying the fields and directions to sort by.
    ///
    /// # Returns
    /// The builder instance with the ordering set.
    #[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
        }
    }

    /// 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).
    ///
    /// # Arguments
    /// * `request_tags`: An iterator of tags to attach.
    ///
    /// # Returns
    /// The builder instance with the request tags set.
    #[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.
    ///
    /// # Arguments
    /// * `options`: The [`FirestoreRequestOptions`] to attach.
    ///
    /// # Returns
    /// The builder instance with the request options set.
    #[inline]
    pub fn request_options(self, options: FirestoreRequestOptions) -> Self {
        Self {
            params: self.params.with_request_options(options),
            ..self
        }
    }

    /// Retrieves a single page of documents.
    ///
    /// # Returns
    /// A `FirestoreResult` containing a [`FirestoreListDocResult`], which includes the documents
    /// for the current page and a potential next page token.
    pub async fn get_page(self) -> FirestoreResult<FirestoreListDocResult> {
        self.db.list_doc(self.params).await
    }

    /// Streams all documents matching the configuration, handling pagination automatically.
    ///
    /// Errors encountered during streaming will terminate the stream.
    ///
    /// # Returns
    /// A `FirestoreResult` containing a `BoxStream` of [`Document`]s.
    pub async fn stream_all<'b>(self) -> FirestoreResult<BoxStream<'b, Document>> {
        self.db.stream_list_doc(self.params).await
    }

    /// Streams all documents matching the configuration, handling pagination automatically.
    ///
    /// Errors encountered during streaming are yielded as `Err` items in the stream,
    /// allowing the caller to handle them without terminating the entire stream.
    ///
    /// # Returns
    /// A `FirestoreResult` containing a `BoxStream` of `FirestoreResult<Document>`.
    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>,
{
    /// Creates a new `FirestoreListingObjBuilder`.
    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).
    ///
    /// # Arguments
    /// * `request_tags`: An iterator of tags to attach.
    ///
    /// # Returns
    /// The builder instance with the request tags set.
    #[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.
    ///
    /// # Arguments
    /// * `options`: The [`FirestoreRequestOptions`] to attach.
    ///
    /// # Returns
    /// The builder instance with the request options set.
    #[inline]
    pub fn request_options(self, options: FirestoreRequestOptions) -> Self {
        Self {
            params: self.params.with_request_options(options),
            ..self
        }
    }

    /// Streams all documents matching the configuration, deserializing them into type `T`
    /// and handling pagination automatically.
    ///
    /// Errors encountered during streaming or deserialization will terminate the stream.
    ///
    /// # Returns
    /// A `FirestoreResult` containing a `BoxStream` of deserialized objects `T`.
    pub async fn stream_all<'b>(self) -> FirestoreResult<BoxStream<'b, T>>
    where
        T: 'b,
    {
        self.db.stream_list_obj(self.params).await
    }

    /// Streams all documents matching the configuration, deserializing them into type `T`
    /// and handling pagination automatically.
    ///
    /// Errors encountered during streaming or deserialization are yielded as `Err` items
    /// in the stream.
    ///
    /// # Returns
    /// A `FirestoreResult` containing a `BoxStream` of `FirestoreResult<T>`.
    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,
{
    /// Creates a new `FirestoreListCollectionIdsBuilder`.
    #[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.
    ///
    /// # Arguments
    /// * `parent`: The full path to the parent document.
    ///
    /// # Returns
    /// The builder instance with the parent path set.
    #[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.
    ///
    /// # Arguments
    /// * `value`: The page size.
    ///
    /// # Returns
    /// The builder instance with the page size set.
    #[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).
    ///
    /// # Arguments
    /// * `request_tags`: An iterator of tags to attach.
    ///
    /// # Returns
    /// The builder instance with the request tags set.
    #[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.
    ///
    /// # Arguments
    /// * `options`: The [`FirestoreRequestOptions`] to attach.
    ///
    /// # Returns
    /// The builder instance with the request options set.
    #[inline]
    pub fn request_options(self, options: FirestoreRequestOptions) -> Self {
        Self {
            params: self.params.with_request_options(options),
            ..self
        }
    }

    /// Retrieves a single page of collection IDs.
    ///
    /// # Returns
    /// A `FirestoreResult` containing a [`FirestoreListCollectionIdsResult`], which includes
    /// the collection IDs for the current page and a potential next page token.
    pub async fn get_page(self) -> FirestoreResult<FirestoreListCollectionIdsResult> {
        self.db.list_collection_ids(self.params).await
    }

    /// Streams all collection IDs matching the configuration, handling pagination automatically.
    ///
    /// Errors encountered during streaming will terminate the stream.
    ///
    /// # Returns
    /// A `FirestoreResult` containing a `BoxStream` of `String` (collection IDs).
    pub async fn stream_all(self) -> FirestoreResult<BoxStream<'a, String>> {
        self.db.stream_list_collection_ids(self.params).await
    }

    /// Streams all collection IDs matching the configuration, handling pagination automatically.
    ///
    /// Errors encountered during streaming are yielded as `Err` items in the stream.
    ///
    /// # Returns
    /// A `FirestoreResult` containing a `BoxStream` of `FirestoreResult<String>`.
    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::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"]))
        )
    }
}