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
use std::{borrow::Borrow, time::Duration};

use bson::{Bson, Document, RawDocumentBuf};
use serde::{de::DeserializeOwned, Serialize};

use crate::{
    coll::options::{
        FindOneAndDeleteOptions,
        FindOneAndReplaceOptions,
        FindOneAndUpdateOptions,
        Hint,
        ReturnDocument,
        UpdateModifications,
    },
    collation::Collation,
    error::Result,
    operation::{
        find_and_modify::options::{FindAndModifyOptions, Modification},
        FindAndModify as Op,
        UpdateOrReplace,
    },
    options::WriteConcern,
    ClientSession,
    Collection,
};

use super::{action_impl, deeplink, option_setters};

impl<T: DeserializeOwned + Send + Sync> Collection<T> {
    async fn find_and_modify<'a>(
        &self,
        filter: Document,
        modification: Modification,
        mut options: Option<FindAndModifyOptions>,
        session: Option<&'a mut ClientSession>,
    ) -> Result<Option<T>> {
        resolve_write_concern_with_session!(self, options, session.as_ref())?;

        let op = Op::<T>::with_modification(self.namespace(), filter, modification, options)?;
        self.client().execute_operation(op, session).await
    }

    /// Atomically finds up to one document in the collection matching `filter` and deletes it.
    ///
    /// This operation will retry once upon failure if the connection and encountered error support
    /// retryability. See the documentation
    /// [here](https://www.mongodb.com/docs/manual/core/retryable-writes/) for more information on
    /// retryable writes.
    ///
    /// `await` will return d[`Result<Option<T>>`].
    #[deeplink]
    pub fn find_one_and_delete(&self, filter: Document) -> FindOneAndDelete<'_, T> {
        FindOneAndDelete {
            coll: self,
            filter,
            options: None,
            session: None,
        }
    }

    /// Atomically finds up to one document in the collection matching `filter` and updates it.
    /// Both `Document` and `Vec<Document>` implement `Into<UpdateModifications>`, so either can be
    /// passed in place of constructing the enum case. Note: pipeline updates are only supported
    /// in MongoDB 4.2+.
    ///
    /// This operation will retry once upon failure if the connection and encountered error support
    /// retryability. See the documentation
    /// [here](https://www.mongodb.com/docs/manual/core/retryable-writes/) for more information on
    /// retryable writes.
    ///
    /// `await` will return d[`Result<Option<T>>`].
    #[deeplink]
    pub fn find_one_and_update(
        &self,
        filter: Document,
        update: impl Into<UpdateModifications>,
    ) -> FindOneAndUpdate<'_, T> {
        FindOneAndUpdate {
            coll: self,
            filter,
            update: update.into(),
            options: None,
            session: None,
        }
    }
}

impl<T: Serialize + DeserializeOwned + Send + Sync> Collection<T> {
    /// Atomically finds up to one document in the collection matching `filter` and replaces it with
    /// `replacement`.
    ///
    /// This operation will retry once upon failure if the connection and encountered error support
    /// retryability. See the documentation
    /// [here](https://www.mongodb.com/docs/manual/core/retryable-writes/) for more information on
    /// retryable writes.
    ///
    /// `await` will return d[`Result<Option<T>>`].
    #[deeplink]
    pub fn find_one_and_replace(
        &self,
        filter: Document,
        replacement: impl Borrow<T>,
    ) -> FindOneAndReplace<'_, T> {
        FindOneAndReplace {
            coll: self,
            filter,
            replacement: bson::to_raw_document_buf(replacement.borrow()).map_err(Into::into),
            options: None,
            session: None,
        }
    }
}

#[cfg(feature = "sync")]
impl<T: DeserializeOwned + Send + Sync> crate::sync::Collection<T> {
    /// Atomically finds up to one document in the collection matching `filter` and deletes it.
    ///
    /// This operation will retry once upon failure if the connection and encountered error support
    /// retryability. See the documentation
    /// [here](https://www.mongodb.com/docs/manual/core/retryable-writes/) for more information on
    /// retryable writes.
    ///
    /// [`run`](FindOneAndDelete::run) will return d[`Result<Option<T>>`].
    #[deeplink]
    pub fn find_one_and_delete(&self, filter: Document) -> FindOneAndDelete<'_, T> {
        self.async_collection.find_one_and_delete(filter)
    }

    /// Atomically finds up to one document in the collection matching `filter` and updates it.
    /// Both `Document` and `Vec<Document>` implement `Into<UpdateModifications>`, so either can be
    /// passed in place of constructing the enum case. Note: pipeline updates are only supported
    /// in MongoDB 4.2+.
    ///
    /// This operation will retry once upon failure if the connection and encountered error support
    /// retryability. See the documentation
    /// [here](https://www.mongodb.com/docs/manual/core/retryable-writes/) for more information on
    /// retryable writes.
    ///
    /// [`run`](FindOneAndDelete::run) will return d[`Result<Option<T>>`].
    #[deeplink]
    pub fn find_one_and_update(
        &self,
        filter: Document,
        update: impl Into<UpdateModifications>,
    ) -> FindOneAndUpdate<'_, T> {
        self.async_collection.find_one_and_update(filter, update)
    }
}

#[cfg(feature = "sync")]
impl<T: Serialize + DeserializeOwned + Send + Sync> crate::sync::Collection<T> {
    /// Atomically finds up to one document in the collection matching `filter` and replaces it with
    /// `replacement`.
    ///
    /// This operation will retry once upon failure if the connection and encountered error support
    /// retryability. See the documentation
    /// [here](https://www.mongodb.com/docs/manual/core/retryable-writes/) for more information on
    /// retryable writes.
    ///
    /// [`run`](FindOneAndReplace::run) will return d[`Result<Option<T>>`].
    #[deeplink]
    pub fn find_one_and_replace(
        &self,
        filter: Document,
        replacement: impl Borrow<T>,
    ) -> FindOneAndReplace<'_, T> {
        self.async_collection
            .find_one_and_replace(filter, replacement)
    }
}

/// Atomically finds up to one document in the collection matching a filter and deletes it.
/// Construct with [`Collection::find_one_and_delete`].
#[must_use]
pub struct FindOneAndDelete<'a, T: Send + Sync> {
    coll: &'a Collection<T>,
    filter: Document,
    options: Option<FindOneAndDeleteOptions>,
    session: Option<&'a mut ClientSession>,
}

impl<'a, T: Send + Sync> FindOneAndDelete<'a, T> {
    option_setters! { options: FindOneAndDeleteOptions;
        max_time: Duration,
        projection: Document,
        sort: Document,
        write_concern: WriteConcern,
        collation: Collation,
        hint: Hint,
        let_vars: Document,
        comment: Bson,
    }

    /// Use the provided session when running the operation.
    pub fn session(mut self, value: impl Into<&'a mut ClientSession>) -> Self {
        self.session = Some(value.into());
        self
    }
}

#[action_impl]
impl<'a, T: DeserializeOwned + Send + Sync> Action for FindOneAndDelete<'a, T> {
    type Future = FindOneAndDeleteFuture;

    async fn execute(self) -> Result<Option<T>> {
        self.coll
            .find_and_modify(
                self.filter,
                Modification::Delete,
                self.options.map(FindAndModifyOptions::from),
                self.session,
            )
            .await
    }
}

/// Atomically finds up to one document in the collection matching a filter and updates it.
/// Construct with [`Collection::find_one_and_update`].
#[must_use]
pub struct FindOneAndUpdate<'a, T: Send + Sync> {
    coll: &'a Collection<T>,
    filter: Document,
    update: UpdateModifications,
    options: Option<FindOneAndUpdateOptions>,
    session: Option<&'a mut ClientSession>,
}

impl<'a, T: Send + Sync> FindOneAndUpdate<'a, T> {
    option_setters! { options: FindOneAndUpdateOptions;
        array_filters: Vec<Document>,
        bypass_document_validation: bool,
        max_time: Duration,
        projection: Document,
        return_document: ReturnDocument,
        sort: Document,
        upsert: bool,
        write_concern: WriteConcern,
        collation: Collation,
        hint: Hint,
        let_vars: Document,
        comment: Bson,
    }

    /// Use the provided session when running the operation.
    pub fn session(mut self, value: impl Into<&'a mut ClientSession>) -> Self {
        self.session = Some(value.into());
        self
    }
}

#[action_impl]
impl<'a, T: DeserializeOwned + Send + Sync> Action for FindOneAndUpdate<'a, T> {
    type Future = FindOneAndUpdateFuture;

    async fn execute(self) -> Result<Option<T>> {
        self.coll
            .find_and_modify(
                self.filter,
                Modification::Update(self.update.into()),
                self.options.map(FindAndModifyOptions::from),
                self.session,
            )
            .await
    }
}

/// Atomically finds up to one document in the collection matching a filter and replaces it.
/// Construct with [`Collection::find_one_and_replace`].
#[must_use]
pub struct FindOneAndReplace<'a, T: Send + Sync> {
    coll: &'a Collection<T>,
    filter: Document,
    replacement: Result<RawDocumentBuf>,
    options: Option<FindOneAndReplaceOptions>,
    session: Option<&'a mut ClientSession>,
}

impl<'a, T: Send + Sync> FindOneAndReplace<'a, T> {
    option_setters! { options: FindOneAndReplaceOptions;
        bypass_document_validation: bool,
        max_time: Duration,
        projection: Document,
        return_document: ReturnDocument,
        sort: Document,
        upsert: bool,
        write_concern: WriteConcern,
        collation: Collation,
        hint: Hint,
        let_vars: Document,
        comment: Bson,
    }

    /// Use the provided session when running the operation.
    pub fn session(mut self, value: impl Into<&'a mut ClientSession>) -> Self {
        self.session = Some(value.into());
        self
    }
}

#[action_impl]
impl<'a, T: DeserializeOwned + Send + Sync> Action for FindOneAndReplace<'a, T> {
    type Future = FindOneAndReplaceFuture;

    async fn execute(self) -> Result<Option<T>> {
        self.coll
            .find_and_modify(
                self.filter,
                Modification::Update(UpdateOrReplace::Replacement(self.replacement?)),
                self.options.map(FindAndModifyOptions::from),
                self.session,
            )
            .await
    }
}