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
//! Builder for constructing Firestore delete operations.
//!
//! This module provides a fluent API to specify the document to be deleted,
//! optionally including a parent path for sub-collections and preconditions
//! for the delete operation.

use crate::{
    FirestoreBatch, FirestoreBatchWriter, FirestoreDeleteSupport, FirestoreResult,
    FirestoreTransactionOps, FirestoreWritePrecondition,
};
#[cfg(feature = "admin")]
use crate::{
    FirestoreBulkDeleteParams, FirestoreBulkDeleteResult, FirestoreBulkDeleteSupport,
    FirestoreCollectionId, FirestoreOperationWaitOptions,
};

/// The initial builder for a Firestore delete operation.
///
/// Created by calling [`FirestoreExprBuilder::delete()`](crate::FirestoreExprBuilder::delete).
#[derive(Clone, Debug)]
pub struct FirestoreDeleteInitialBuilder<'a, D>
where
    D: FirestoreDeleteSupport,
{
    db: &'a D,
}

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

    /// Specifies the collection ID from which to delete the document.
    #[inline]
    pub fn from<S: AsRef<str>>(self, collection_id: S) -> FirestoreDeleteDocIdBuilder<'a, D> {
        FirestoreDeleteDocIdBuilder::new(self.db, collection_id.as_ref().to_string())
    }
}

// A separate impl block, bounded only by `FirestoreBulkDeleteSupport`, so that this method never
// widens the bounds a plain single-document delete pays for.
#[cfg(feature = "admin")]
impl<'a, D> FirestoreDeleteInitialBuilder<'a, D>
where
    D: FirestoreDeleteSupport + FirestoreBulkDeleteSupport + Clone + Send + Sync + 'static,
{
    /// Switches to Google's `BulkDeleteDocuments` operation: every document in the named
    /// collection groups, at any depth, across the whole database, deleted in the background.
    /// Requires the `admin` feature.
    ///
    /// See <https://cloud.google.com/firestore/docs/manage-data/bulk-delete>. In particular:
    ///
    /// - it reaches every document in each named collection group at any depth, anywhere under
    ///   the database, not only documents under one parent - there is no `.parent()` on the
    ///   builder this returns, because the underlying API cannot express one;
    /// - it runs in the background and is not transactional;
    /// - documents written after the operation starts processing are not touched, so they
    ///   survive;
    /// - a collection with a different ID is never touched, even if nested under a deleted group.
    ///
    /// Continue with [`FirestoreBulkDeleteBuilder::collection_groups`].
    #[inline]
    pub fn bulk(self) -> FirestoreBulkDeleteBuilder<'a, D> {
        FirestoreBulkDeleteBuilder::new(self.db)
    }
}

/// A builder for specifying the document ID and options for a delete operation.
#[derive(Clone, Debug)]
pub struct FirestoreDeleteDocIdBuilder<'a, D>
where
    D: FirestoreDeleteSupport,
{
    db: &'a D,
    collection_id: String,
    parent: Option<String>,
    precondition: Option<FirestoreWritePrecondition>,
}

impl<'a, D> FirestoreDeleteDocIdBuilder<'a, D>
where
    D: FirestoreDeleteSupport,
{
    #[inline]
    pub(crate) fn new(db: &'a D, collection_id: String) -> Self {
        Self {
            db,
            collection_id,
            parent: None,
            precondition: None,
        }
    }

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

    /// Specifies a precondition for the delete operation.
    ///
    /// The delete will only be executed if the precondition is met.
    #[inline]
    pub fn precondition(self, precondition: FirestoreWritePrecondition) -> Self {
        Self {
            precondition: Some(precondition),
            ..self
        }
    }

    /// Specifies the ID of the document to delete.
    #[inline]
    pub fn document_id<S>(self, document_id: S) -> FirestoreDeleteExecuteBuilder<'a, D>
    where
        S: AsRef<str> + Send,
    {
        FirestoreDeleteExecuteBuilder::new(
            self.db,
            self.collection_id.to_string(),
            document_id.as_ref().to_string(),
            self.parent,
            self.precondition,
        )
    }
}

/// A builder for executing a Firestore delete operation or adding it to a batch/transaction.
#[derive(Clone, Debug)]
pub struct FirestoreDeleteExecuteBuilder<'a, D>
where
    D: FirestoreDeleteSupport,
{
    db: &'a D,
    collection_id: String,
    document_id: String,
    parent: Option<String>,
    precondition: Option<FirestoreWritePrecondition>,
}

impl<'a, D> FirestoreDeleteExecuteBuilder<'a, D>
where
    D: FirestoreDeleteSupport,
{
    #[inline]
    pub(crate) fn new(
        db: &'a D,
        collection_id: String,
        document_id: String,
        parent: Option<String>,
        precondition: Option<FirestoreWritePrecondition>,
    ) -> Self {
        Self {
            db,
            collection_id,
            document_id,
            parent,
            precondition,
        }
    }

    /// Sets or overrides the parent document path.
    #[inline]
    pub fn parent<S>(self, parent: S) -> Self
    where
        S: AsRef<str>,
    {
        Self {
            parent: Some(parent.as_ref().to_string()),
            ..self
        }
    }

    /// Sets or overrides the precondition for the delete.
    #[inline]
    pub fn precondition(self, precondition: FirestoreWritePrecondition) -> Self {
        Self {
            precondition: Some(precondition),
            ..self
        }
    }

    /// Sends the delete to Firestore.
    ///
    /// Returns an error if the request fails, or if a precondition was set and does not hold.
    ///
    /// ```rust,no_run
    /// use firestore::FirestoreDb;
    ///
    /// # async fn example(db: FirestoreDb) -> Result<(), Box<dyn std::error::Error>> {
    /// db.fluent()
    ///     .delete()
    ///     .from("users")
    ///     .document_id("user-42")
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn execute(self) -> FirestoreResult<()> {
        if let Some(parent) = self.parent {
            self.db
                .delete_by_id_at(
                    parent.as_str(),
                    self.collection_id.as_str(),
                    self.document_id,
                    self.precondition,
                )
                .await
        } else {
            self.db
                .delete_by_id(
                    self.collection_id.as_str(),
                    self.document_id,
                    self.precondition,
                )
                .await
        }
    }

    /// Queues this delete on `transaction`, to be sent when the transaction commits.
    ///
    /// Returns an error if the delete cannot be added to the transaction.
    #[inline]
    pub fn add_to_transaction<'t, TO>(self, transaction: &'t mut TO) -> FirestoreResult<&'t mut TO>
    where
        TO: FirestoreTransactionOps,
    {
        if let Some(parent) = self.parent {
            transaction.delete_by_id_at(
                parent.as_str(),
                self.collection_id.as_str(),
                self.document_id,
                self.precondition,
            )
        } else {
            transaction.delete_by_id(
                self.collection_id.as_str(),
                self.document_id,
                self.precondition,
            )
        }
    }

    /// Queues this delete on `batch`, to be sent when the batch is written.
    ///
    /// Returns an error if the delete cannot be added to the batch.
    #[inline]
    pub fn add_to_batch<'t, W>(
        self,
        batch: &'a mut FirestoreBatch<'t, W>,
    ) -> FirestoreResult<&'a mut FirestoreBatch<'t, W>>
    where
        W: FirestoreBatchWriter,
    {
        if let Some(parent) = self.parent {
            batch.delete_by_id_at(
                parent.as_str(),
                self.collection_id.as_str(),
                self.document_id,
                self.precondition,
            )
        } else {
            batch.delete_by_id(
                self.collection_id.as_str(),
                self.document_id,
                self.precondition,
            )
        }
    }
}

/// The bulk-delete operation Google calls `BulkDeleteDocuments`: deletes every document in the
/// named collection groups, at any depth, across the whole database. Requires the `admin`
/// feature.
///
/// Reach this from [`FirestoreDeleteInitialBuilder::bulk`]. There is no `.parent()` or
/// `.document_id()` here: a parent-scoped bulk delete is not an operation Firestore offers.
#[cfg(feature = "admin")]
#[derive(Clone, Debug)]
pub struct FirestoreBulkDeleteBuilder<'a, D>
where
    D: FirestoreBulkDeleteSupport,
{
    db: &'a D,
    collection_groups: Vec<String>,
    wait: Option<FirestoreOperationWaitOptions>,
}

#[cfg(feature = "admin")]
impl<'a, D> FirestoreBulkDeleteBuilder<'a, D>
where
    D: FirestoreBulkDeleteSupport + Clone + Send + Sync + 'static,
{
    #[inline]
    pub(crate) fn new(db: &'a D) -> Self {
        Self {
            db,
            collection_groups: Vec::new(),
            wait: None,
        }
    }

    /// Names the collection groups to delete. Every document in each group, at any depth across
    /// the whole database, is removed - see [`FirestoreDeleteInitialBuilder::bulk`] for the full
    /// semantics. Each call replaces any groups set by a previous call.
    ///
    /// Validated into [`FirestoreCollectionId`]s at [`execute`](Self::execute): an empty list, or
    /// a group named twice, is rejected there rather than sent, since Firestore reads an empty
    /// `collection_ids` as "the whole database".
    #[inline]
    pub fn collection_groups<I>(self, collection_groups: I) -> Self
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        Self {
            collection_groups: collection_groups
                .into_iter()
                .map(|group| group.as_ref().to_string())
                .collect(),
            ..self
        }
    }

    /// Waits for the bulk delete to reach a terminal state before [`execute`](Self::execute)
    /// returns, up to `timeout` (see [`FirestoreOperationWaitOptions`] for exactly how it is
    /// applied), polling at the default interval. Without this, `execute` returns once the
    /// operation is requested.
    #[inline]
    pub fn wait_until_done(self, timeout: std::time::Duration) -> Self {
        self.wait_until_done_with_options(FirestoreOperationWaitOptions::new(timeout))
    }

    /// Waits for the bulk delete to reach a terminal state before [`execute`](Self::execute)
    /// returns, per `options`. Without this, `execute` returns once the operation is requested.
    #[inline]
    pub fn wait_until_done_with_options(self, options: FirestoreOperationWaitOptions) -> Self {
        Self {
            wait: Some(options),
            ..self
        }
    }

    /// Sends the bulk delete to Firestore.
    ///
    /// When waiting was requested and the wait fails, the error is returned and the result known
    /// so far (the operation name and the last reported progress) is logged at `warn` just
    /// before: the delete keeps running on the server either way.
    ///
    /// Returns [`FirestoreError::InvalidParametersError`](crate::errors::FirestoreError::InvalidParametersError)
    /// if no collection groups were named, or the same group was named twice: an empty list is
    /// never sent, since Firestore reads it as "delete the whole database".
    pub async fn execute(self) -> FirestoreResult<FirestoreBulkDeleteResult> {
        let collection_groups = self
            .collection_groups
            .into_iter()
            .map(FirestoreCollectionId::new)
            .collect::<FirestoreResult<Vec<_>>>()?;
        let params = FirestoreBulkDeleteParams::new(collection_groups).opt_wait(self.wait);
        crate::validate_bulk_delete_params(&params)?;
        self.db.bulk_delete_documents(params).await
    }
}

#[cfg(all(test, feature = "admin"))]
mod tests {
    use super::FirestoreDeleteInitialBuilder;
    use crate::fluent_api::tests::mockdb::MockBulkDeleteDatabase;
    use crate::{FirestoreCollectionId, FirestoreOperationWaitOptions};
    use std::time::Duration;

    #[tokio::test]
    async fn bulk_chain_produces_the_expected_params() {
        let mock = MockBulkDeleteDatabase::default();
        FirestoreDeleteInitialBuilder::new(&mock)
            .bulk()
            .collection_groups(["users", "orders"])
            .wait_until_done(Duration::from_secs(600))
            .execute()
            .await
            .expect("capturing mock always succeeds");

        let params = mock.captured().expect("bulk_delete_documents was called");
        assert_eq!(
            params.collection_groups,
            vec![
                FirestoreCollectionId::new("users").unwrap(),
                FirestoreCollectionId::new("orders").unwrap(),
            ]
        );
        assert_eq!(
            params.wait,
            Some(FirestoreOperationWaitOptions::new(Duration::from_secs(600)))
        );
    }

    #[tokio::test]
    async fn without_wait_defaults_to_no_wait() {
        let mock = MockBulkDeleteDatabase::default();
        FirestoreDeleteInitialBuilder::new(&mock)
            .bulk()
            .collection_groups(["users"])
            .execute()
            .await
            .unwrap();

        let params = mock.captured().unwrap();
        assert!(params.wait.is_none());
    }

    #[tokio::test]
    async fn empty_collection_groups_is_rejected_before_the_call() {
        let mock = MockBulkDeleteDatabase::default();
        let err = FirestoreDeleteInitialBuilder::new(&mock)
            .bulk()
            .execute()
            .await
            .unwrap_err();
        assert!(err.to_string().contains("collection_groups"));
        assert!(mock.captured().is_none());
    }

    #[tokio::test]
    async fn duplicate_collection_group_is_rejected_before_the_call() {
        let mock = MockBulkDeleteDatabase::default();
        let err = FirestoreDeleteInitialBuilder::new(&mock)
            .bulk()
            .collection_groups(["users", "users"])
            .execute()
            .await
            .unwrap_err();
        assert!(err.to_string().contains("more than once"));
        assert!(mock.captured().is_none());
    }

    #[tokio::test]
    async fn invalid_collection_group_is_rejected_before_the_call() {
        let mock = MockBulkDeleteDatabase::default();
        let err = FirestoreDeleteInitialBuilder::new(&mock)
            .bulk()
            .collection_groups(["a/b"])
            .execute()
            .await
            .unwrap_err();
        assert!(err.to_string().contains("collection_id"));
        assert!(mock.captured().is_none());
    }
}