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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
use std::time::Duration;

use bson::serde_helpers;
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
use serde_with::skip_serializing_none;
use typed_builder::TypedBuilder;

use crate::{
    bson::{doc, Bson, Document},
    bson_util,
    concern::{ReadConcern, WriteConcern},
    options::Collation,
    selection_criteria::SelectionCriteria,
};

/// These are the valid options for creating a [`Collection`](../struct.Collection.html) with
/// [`Database::collection_with_options`](../struct.Database.html#method.collection_with_options).
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CollectionOptions {
    /// The default read preference for operations.
    pub selection_criteria: Option<SelectionCriteria>,

    /// The default read concern for operations.
    pub read_concern: Option<ReadConcern>,

    /// The default write concern for operations.
    pub write_concern: Option<WriteConcern>,
}

/// Specifies whether a
/// [`Collection::find_one_and_replace`](../struct.Collection.html#method.find_one_and_replace) and
/// [`Collection::find_one_and_update`](../struct.Collection.html#method.find_one_and_update)
/// operation should return the document before or after modification.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ReturnDocument {
    /// Return the document after modification.
    After,
    /// Return the document before modification.
    Before,
}

impl<'de> Deserialize<'de> for ReturnDocument {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        match s.to_lowercase().as_str() {
            "after" => Ok(ReturnDocument::After),
            "before" => Ok(ReturnDocument::Before),
            other => Err(D::Error::custom(format!(
                "Unknown return document value: {}",
                other
            ))),
        }
    }
}

/// Specifies the index to use for an operation.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum Hint {
    /// Specifies the keys of the index to use.
    Keys(Document),
    /// Specifies the name of the index to use.
    Name(String),
}

impl Hint {
    pub(crate) fn to_bson(&self) -> Bson {
        match self {
            Hint::Keys(ref d) => Bson::Document(d.clone()),
            Hint::Name(ref s) => Bson::String(s.clone()),
        }
    }
}

/// Specifies the type of cursor to return from a find operation.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum CursorType {
    /// Default; close the cursor after the last document is received from the server.
    NonTailable,

    /// Do not close the cursor after the last document is received from the server. If more
    /// results become available later, the cursor will return them.
    Tailable,

    /// Similar to `Tailable`, except that the cursor should block on receiving more results if
    /// none are available.
    TailableAwait,
}

/// Specifies the options to a
/// [`Collection::insert_one`](../struct.Collection.html#method.insert_one) operation.
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct InsertOneOptions {
    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,
}

/// Specifies the options to a
/// [`Collection::insert_many`](../struct.Collection.html#method.insert_many) operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, TypedBuilder, Serialize, Deserialize)]
#[builder(field_defaults(default, setter(into)))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct InsertManyOptions {
    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// If true, when an insert fails, return without performing the remaining writes. If false,
    /// when a write fails, continue with the remaining writes, if any.
    ///
    /// Defaults to true.
    pub ordered: Option<bool>,

    /// The write concern for the operation.
    #[serde(skip_deserializing)]
    pub write_concern: Option<WriteConcern>,
}

impl InsertManyOptions {
    pub(crate) fn from_insert_one_options(options: InsertOneOptions) -> Self {
        Self {
            bypass_document_validation: options.bypass_document_validation,
            ordered: None,
            write_concern: options.write_concern,
        }
    }
}

/// Enum modeling the modifications to apply during an update.
/// For details, see the official MongoDB
/// [documentation](https://docs.mongodb.com/manual/reference/command/update/#update-command-behaviors)
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum UpdateModifications {
    /// A document that contains only update operator expressions.
    Document(Document),

    /// An aggregation pipeline.
    /// Only available in MongoDB 4.2+.
    Pipeline(Vec<Document>),
}

impl UpdateModifications {
    pub(crate) fn to_bson(&self) -> Bson {
        match self {
            UpdateModifications::Document(ref d) => Bson::Document(d.clone()),
            UpdateModifications::Pipeline(ref p) => {
                Bson::Array(p.iter().map(|d| Bson::Document(d.clone())).collect())
            }
        }
    }
}

impl From<Document> for UpdateModifications {
    fn from(item: Document) -> Self {
        UpdateModifications::Document(item)
    }
}

impl From<Vec<Document>> for UpdateModifications {
    fn from(item: Vec<Document>) -> Self {
        UpdateModifications::Pipeline(item)
    }
}

/// Specifies the options to a
/// [`Collection::update_one`](../struct.Collection.html#method.update_one) or
/// [`Collection::update_many`](../struct.Collection.html#method.update_many) operation.
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct UpdateOptions {
    /// A set of filters specifying to which array elements an update should apply.
    ///
    /// See the documentation [here](https://docs.mongodb.com/manual/reference/command/update/) for
    /// more information on array filters.
    pub array_filters: Option<Vec<Document>>,

    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// If true, insert a document if no matching document is found.
    pub upsert: Option<bool>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// A document or string that specifies the index to use to support the query predicate.
    ///
    /// Only available in MongoDB 4.2+. See the official MongoDB
    /// [documentation](https://docs.mongodb.com/manual/reference/command/update/#ex-update-command-hint) for examples.
    pub hint: Option<Hint>,

    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,
}

impl UpdateOptions {
    pub(crate) fn from_replace_options(options: ReplaceOptions) -> Self {
        Self {
            bypass_document_validation: options.bypass_document_validation,
            upsert: options.upsert,
            hint: options.hint,
            write_concern: options.write_concern,
            collation: options.collation,
            ..Default::default()
        }
    }
}

/// Specifies the options to a
/// [`Collection::replace_one`](../struct.Collection.html#method.replace_one) operation.
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct ReplaceOptions {
    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// If true, insert a document if no matching document is found.
    pub upsert: Option<bool>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// A document or string that specifies the index to use to support the query predicate.
    ///
    /// Only available in MongoDB 4.2+. See the official MongoDB
    /// [documentation](https://docs.mongodb.com/manual/reference/command/update/#ex-update-command-hint) for examples.
    pub hint: Option<Hint>,

    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,
}

/// Specifies the options to a
/// [`Collection::delete_one`](../struct.Collection.html#method.delete_one) or
/// [`Collection::delete_many`](../struct.Collection.html#method.delete_many) operation.
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct DeleteOptions {
    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,

    /// The index to use for the operation.
    /// Only available in MongoDB 4.4+.
    pub hint: Option<Hint>,
}

/// Specifies the options to a
/// [`Collection::find_one_and_delete`](../struct.Collection.html#method.find_one_and_delete)
/// operation.
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct FindOneAndDeleteOptions {
    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    pub max_time: Option<Duration>,

    /// Limits the fields of the document being returned.
    pub projection: Option<Document>,

    /// The order of the documents for the purposes of the operation.
    pub sort: Option<Document>,

    /// The level of the write concern
    pub write_concern: Option<WriteConcern>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// The index to use for the operation.
    /// Only available in MongoDB 4.4+.
    pub hint: Option<Hint>,
}

/// Specifies the options to a
/// [`Collection::find_one_and_replace`](../struct.Collection.html#method.find_one_and_replace)
/// operation.
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct FindOneAndReplaceOptions {
    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    pub max_time: Option<Duration>,

    /// Limits the fields of the document being returned.
    pub projection: Option<Document>,

    /// Whether the operation should return the document before or after modification.
    pub return_document: Option<ReturnDocument>,

    /// The order of the documents for the purposes of the operation.
    pub sort: Option<Document>,

    /// If true, insert a document if no matching document is found.
    pub upsert: Option<bool>,

    /// The level of the write concern
    pub write_concern: Option<WriteConcern>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// The index to use for the operation.
    /// Only available in MongoDB 4.4+.
    pub hint: Option<Hint>,
}

/// Specifies the options to a
/// [`Collection::find_one_and_update`](../struct.Collection.html#method.find_one_and_update)
/// operation.
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct FindOneAndUpdateOptions {
    /// A set of filters specifying to which array elements an update should apply.
    ///
    /// See the documentation [here](https://docs.mongodb.com/manual/reference/command/update/) for
    /// more information on array filters.
    pub array_filters: Option<Vec<Document>>,

    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    pub max_time: Option<Duration>,

    /// Limits the fields of the document being returned.
    pub projection: Option<Document>,

    /// Whether the operation should return the document before or after modification.
    pub return_document: Option<ReturnDocument>,

    /// The order of the documents for the purposes of the operation.
    pub sort: Option<Document>,

    /// If true, insert a document if no matching document is found.
    pub upsert: Option<bool>,

    /// The level of the write concern
    pub write_concern: Option<WriteConcern>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// The index to use for the operation.
    /// Only available in MongoDB 4.4+.
    pub hint: Option<Hint>,
}

/// Specifies the options to a [`Collection::aggregate`](../struct.Collection.html#method.aggregate)
/// operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct AggregateOptions {
    /// Enables writing to temporary files. When set to true, aggregation stages can write data to
    /// the _tmp subdirectory in the dbPath directory.
    pub allow_disk_use: Option<bool>,

    /// The number of documents the server should return per cursor batch.
    ///
    /// Note that this does not have any affect on the documents that are returned by a cursor,
    /// only the number of documents kept in memory at a given time (and by extension, the
    /// number of round trips needed to return the entire set of documents returned by the
    /// query).
    #[serde(
        serialize_with = "bson_util::serialize_u32_option_as_batch_size",
        rename(serialize = "cursor")
    )]
    pub batch_size: Option<u32>,

    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// Tags the query with an arbitrary string to help trace the operation through the database
    /// profiler, currentOp and logs.
    pub comment: Option<String>,

    /// The index to use for the operation.
    pub hint: Option<Hint>,

    /// The maximum amount of time for the server to wait on new documents to satisfy a tailable
    /// await cursor query.
    ///
    /// This option will have no effect on non-tailable cursors that result from this operation.
    #[serde(
        skip_serializing,
        deserialize_with = "bson_util::deserialize_duration_option_from_u64_millis",
        default
    )]
    pub max_await_time: Option<Duration>,

    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        serialize_with = "bson_util::serialize_duration_option_as_int_millis",
        rename = "maxTimeMS",
        deserialize_with = "bson_util::deserialize_duration_option_from_u64_millis",
        default
    )]
    pub max_time: Option<Duration>,

    /// The read concern to use for the operation.
    ///
    /// If none is specified, the read concern defined on the object executing this operation will
    /// be used.
    #[serde(skip_serializing)]
    pub read_concern: Option<ReadConcern>,

    /// The criteria used to select a server for this operation.
    ///
    /// If none is specified, the selection criteria defined on the object executing this operation
    /// will be used.
    #[serde(skip_serializing)]
    #[serde(rename = "readPreference")]
    pub selection_criteria: Option<SelectionCriteria>,

    /// The write concern to use for the operation.
    ///
    /// If none is specified, the write concern defined on the object executing this operation will
    /// be used.
    pub write_concern: Option<WriteConcern>,

    /// A document with any amount of parameter names, each followed by definitions of constants in
    /// the MQL Aggregate Expression language.  Each parameter name is then usable to access the
    /// value of the corresponding MQL Expression with the "$$" syntax within Aggregate Expression
    /// contexts.
    ///
    /// This feature is only available on server versions 5.0 and above.
    #[serde(rename = "let")]
    pub let_vars: Option<Document>,
}

/// Specifies the options to a
/// [`Collection::count_documents`](../struct.Collection.html#method.count_documents) operation.
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct CountOptions {
    /// The index to use for the operation.
    pub hint: Option<Hint>,

    /// The maximum number of documents to count.
    pub limit: Option<u64>,

    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        default,
        deserialize_with = "bson_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The number of documents to skip before counting.
    pub skip: Option<u64>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// The criteria used to select a server for this operation.
    ///
    /// If none specified, the default set on the collection will be used.
    pub selection_criteria: Option<SelectionCriteria>,

    /// The level of the read concern.
    #[serde(skip_serializing)]
    pub read_concern: Option<ReadConcern>,
}

// rustfmt tries to split the link up when it's all on one line, which breaks the link, so we wrap
// the link contents in whitespace to get it to render correctly.
//
/// Specifies the options to a
/// [
///  `Collection::estimated_document_count`
/// ](../struct.Collection.html#method.estimated_document_count) operation.
#[serde_with::skip_serializing_none]
#[derive(Debug, Default, Deserialize, TypedBuilder, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct EstimatedDocumentCountOptions {
    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        default,
        serialize_with = "bson_util::serialize_duration_option_as_int_millis",
        rename = "maxTimeMS",
        deserialize_with = "bson_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The criteria used to select a server for this operation.
    ///
    /// If none specified, the default set on the collection will be used.
    #[serde(skip_serializing)]
    pub selection_criteria: Option<SelectionCriteria>,

    /// The level of the read concern.
    #[serde(skip_serializing)]
    pub read_concern: Option<ReadConcern>,
}

/// Specifies the options to a [`Collection::distinct`](../struct.Collection.html#method.distinct)
/// operation.
#[serde_with::skip_serializing_none]
#[derive(Debug, Default, Deserialize, TypedBuilder, Serialize, Clone)]
#[builder(field_defaults(default, setter(into)))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DistinctOptions {
    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        default,
        serialize_with = "bson_util::serialize_duration_option_as_int_millis",
        rename = "maxTimeMS",
        deserialize_with = "bson_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The criteria used to select a server for this operation.
    ///
    /// If none specified, the default set on the collection will be used.
    #[serde(skip_serializing)]
    pub selection_criteria: Option<SelectionCriteria>,

    /// The level of the read concern.
    #[serde(skip_serializing)]
    pub read_concern: Option<ReadConcern>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,
}

/// Specifies the options to a [`Collection::find`](../struct.Collection.html#method.find)
/// operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
#[builder(field_defaults(default, setter(into)))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct FindOptions {
    /// Enables writing to temporary files by the server. When set to true, the find operation can
    /// write data to the _tmp subdirectory in the dbPath directory. Only supported in server
    /// versions 4.4+.
    pub allow_disk_use: Option<bool>,

    /// If true, partial results will be returned from a mongos rather than an error being
    /// returned if one or more shards is down.
    pub allow_partial_results: Option<bool>,

    /// The number of documents the server should return per cursor batch.
    ///
    /// Note that this does not have any affect on the documents that are returned by a cursor,
    /// only the number of documents kept in memory at a given time (and by extension, the
    /// number of round trips needed to return the entire set of documents returned by the
    /// query.
    #[serde(serialize_with = "bson_util::serialize_u32_option_as_i32")]
    pub batch_size: Option<u32>,

    /// Tags the query with an arbitrary string to help trace the operation through the database
    /// profiler, currentOp and logs.
    pub comment: Option<String>,

    /// The type of cursor to return.
    #[serde(skip)]
    pub cursor_type: Option<CursorType>,

    /// The index to use for the operation.
    pub hint: Option<Hint>,

    /// The maximum number of documents to query.
    /// If a negative number is specified, the documents will be returned in a single batch limited
    /// in number by the positive value of the specified limit.
    #[serde(serialize_with = "serialize_absolute_value")]
    pub limit: Option<i64>,

    /// The exclusive upper bound for a specific index.
    pub max: Option<Document>,

    /// The maximum amount of time for the server to wait on new documents to satisfy a tailable
    /// cursor query. If the cursor is not tailable, this option is ignored.
    #[serde(skip)]
    pub max_await_time: Option<Duration>,

    /// Maximum number of documents or index keys to scan when executing the query.
    ///
    /// Note: this option is deprecated starting in MongoDB version 4.0 and removed in MongoDB 4.2.
    /// Use the maxTimeMS option instead.
    #[serde(serialize_with = "bson_util::serialize_u64_option_as_i64")]
    pub max_scan: Option<u64>,

    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        rename = "maxTimeMS",
        serialize_with = "bson_util::serialize_duration_option_as_int_millis"
    )]
    pub max_time: Option<Duration>,

    /// The inclusive lower bound for a specific index.
    pub min: Option<Document>,

    /// Whether the server should close the cursor after a period of inactivity.
    pub no_cursor_timeout: Option<bool>,

    /// Limits the fields of the document being returned.
    pub projection: Option<Document>,

    /// The read concern to use for this find query.
    ///
    /// If none specified, the default set on the collection will be used.
    #[serde(skip_serializing)]
    pub read_concern: Option<ReadConcern>,

    /// Whether to return only the index keys in the documents.
    pub return_key: Option<bool>,

    /// The criteria used to select a server for this find query.
    ///
    /// If none specified, the default set on the collection will be used.
    #[serde(skip)]
    pub selection_criteria: Option<SelectionCriteria>,

    /// Whether to return the record identifier for each document.
    pub show_record_id: Option<bool>,

    /// The number of documents to skip before counting.
    #[serde(serialize_with = "bson_util::serialize_u64_option_as_i64")]
    pub skip: Option<u64>,

    /// The order of the documents for the purposes of the operation.
    pub sort: Option<Document>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,
}

impl From<FindOneOptions> for FindOptions {
    fn from(options: FindOneOptions) -> Self {
        FindOptions {
            allow_disk_use: None,
            allow_partial_results: options.allow_partial_results,
            collation: options.collation,
            comment: options.comment,
            hint: options.hint,
            max: options.max,
            max_scan: options.max_scan,
            max_time: options.max_time,
            min: options.min,
            projection: options.projection,
            read_concern: options.read_concern,
            return_key: options.return_key,
            selection_criteria: options.selection_criteria,
            show_record_id: options.show_record_id,
            skip: options.skip,
            batch_size: None,
            cursor_type: None,
            limit: Some(-1),
            max_await_time: None,
            no_cursor_timeout: None,
            sort: options.sort,
        }
    }
}

/// Custom serializer used to serialize limit as its absolute value.
fn serialize_absolute_value<S>(
    val: &Option<i64>,
    serializer: S,
) -> std::result::Result<S::Ok, S::Error>
where
    S: Serializer,
{
    match val {
        Some(v) => serializer.serialize_i64(v.abs()),
        None => serializer.serialize_none(),
    }
}

/// Specifies the options to a [`Collection::find_one`](../struct.Collection.html#method.find_one)
/// operation.
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct FindOneOptions {
    /// If true, partial results will be returned from a mongos rather than an error being
    /// returned if one or more shards is down.
    pub allow_partial_results: Option<bool>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// Tags the query with an arbitrary string to help trace the operation through the database
    /// profiler, currentOp and logs.
    pub comment: Option<String>,

    /// The index to use for the operation.
    pub hint: Option<Hint>,

    /// The exclusive upper bound for a specific index.
    pub max: Option<Document>,

    /// Maximum number of documents or index keys to scan when executing the query.
    ///
    /// Note: this option is deprecated starting in MongoDB version 4.0 and removed in MongoDB 4.2.
    /// Use the maxTimeMS option instead.
    #[serde(serialize_with = "bson_util::serialize_u64_option_as_i64")]
    pub max_scan: Option<u64>,

    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(deserialize_with = "bson_util::deserialize_duration_option_from_u64_millis")]
    pub max_time: Option<Duration>,

    /// The inclusive lower bound for a specific index.
    pub min: Option<Document>,

    /// Limits the fields of the document being returned.
    pub projection: Option<Document>,

    /// The read concern to use for this find query.
    ///
    /// If none specified, the default set on the collection will be used.
    #[serde(skip_serializing)]
    pub read_concern: Option<ReadConcern>,

    /// Whether to return only the index keys in the documents.
    pub return_key: Option<bool>,

    /// The criteria used to select a server for this find query.
    ///
    /// If none specified, the default set on the collection will be used.
    pub selection_criteria: Option<SelectionCriteria>,

    /// Whether to return the record identifier for each document.
    pub show_record_id: Option<bool>,

    /// The number of documents to skip before counting.
    #[serde(serialize_with = "bson_util::serialize_u64_option_as_i64")]
    pub skip: Option<u64>,

    /// The order of the documents for the purposes of the operation.
    pub sort: Option<Document>,
}

/// Specifies the options to a
/// [`Collection::create_index`](../struct.Collection.html#method.create_index) or [`Collection::
/// create_indexes`](../struct.Collection.html#method.create_indexes) operation.
///
/// For more information, see [`createIndexes`](https://docs.mongodb.com/manual/reference/command/createIndexes/).
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, TypedBuilder, Serialize)]
#[builder(field_defaults(default, setter(into)))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[non_exhaustive]
pub struct CreateIndexOptions {
    /// Specify the commit quorum needed to mark an `index` as ready.
    pub commit_quorum: Option<CommitQuorum>,

    /// The maximum amount of time to allow the index to build.
    ///
    /// This option maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        rename = "maxTimeMS",
        default,
        serialize_with = "bson_util::serialize_duration_option_as_int_millis",
        deserialize_with = "bson_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,
}

/// Specifies the options to a [`Collection::drop`](../struct.Collection.html#method.drop)
/// operation.
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct DropCollectionOptions {
    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,
}

/// Specifies the options to a
/// [`Collection::drop_index`](../struct.Collection.html#method.drop_index) or
/// [`Collection::drop_indexes`](../struct.Collection.html#method.drop_indexes) operation.
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct DropIndexOptions {
    /// The maximum amount of time to allow the index to drop.
    ///
    /// This option maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        rename = "maxTimeMS",
        default,
        serialize_with = "bson_util::serialize_duration_option_as_int_millis",
        deserialize_with = "bson_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,
}

/// Specifies the options to a
/// [`Collection::list_indexes`](../struct.Collection.html#method.list_indexes) operation.
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct ListIndexesOptions {
    /// The maximum amount of time to search for the index.
    ///
    /// This option maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        rename = "maxTimeMS",
        default,
        serialize_with = "bson_util::serialize_duration_option_as_int_millis",
        deserialize_with = "bson_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The number of indexes the server should return per cursor batch.
    #[serde(default, skip_serializing)]
    pub batch_size: Option<u32>,
}

/// The minimum number of data-bearing voting replica set members (i.e. commit quorum), including
/// the primary, that must report a successful index build before the primary marks the indexes as
/// ready.
///
/// For more information, see the [documentation](https://docs.mongodb.com/manual/reference/command/createIndexes/#definition)
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum CommitQuorum {
    /// A specific number of voting replica set members. When set to 0, disables quorum voting.
    Nodes(u32),

    /// All data-bearing voting replica set members (default).
    VotingMembers,

    /// A simple majority of voting members.
    Majority,

    /// A replica set tag name.
    Custom(String),
}

impl Serialize for CommitQuorum {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            CommitQuorum::Nodes(n) => serde_helpers::serialize_u32_as_i32(n, serializer),
            CommitQuorum::VotingMembers => serializer.serialize_str("votingMembers"),
            CommitQuorum::Majority => serializer.serialize_str("majority"),
            CommitQuorum::Custom(s) => serializer.serialize_str(s),
        }
    }
}

impl<'de> Deserialize<'de> for CommitQuorum {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum IntOrString {
            Int(u32),
            String(String),
        }
        match IntOrString::deserialize(deserializer)? {
            IntOrString::String(s) => {
                if s == "votingMembers" {
                    Ok(CommitQuorum::VotingMembers)
                } else if s == "majority" {
                    Ok(CommitQuorum::Majority)
                } else {
                    Ok(CommitQuorum::Custom(s))
                }
            }
            IntOrString::Int(i) => Ok(CommitQuorum::Nodes(i)),
        }
    }
}