summaryrefslogtreecommitdiff
path: root/src/mongo/db/query/query_request.cpp
blob: d50d8a10f4db7d200b511094f2211539583f4dee (plain)
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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include "mongo/db/query/query_request.h"

#include <memory>

#include "mongo/base/status.h"
#include "mongo/base/status_with.h"
#include "mongo/bson/simple_bsonobj_comparator.h"
#include "mongo/db/catalog/collection_catalog.h"
#include "mongo/db/command_generic_argument.h"
#include "mongo/db/commands.h"
#include "mongo/db/dbmessage.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/repl/read_concern_args.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/str.h"

namespace mongo {

using std::string;
using std::unique_ptr;

const std::string QueryRequest::kUnwrappedReadPrefField("$queryOptions");
const std::string QueryRequest::kWrappedReadPrefField("$readPreference");

const char QueryRequest::cmdOptionMaxTimeMS[] = "maxTimeMS";
const char QueryRequest::queryOptionMaxTimeMS[] = "$maxTimeMS";

const string QueryRequest::metaGeoNearDistance("geoNearDistance");
const string QueryRequest::metaGeoNearPoint("geoNearPoint");
const string QueryRequest::metaRecordId("recordId");
const string QueryRequest::metaSortKey("sortKey");
const string QueryRequest::metaTextScore("textScore");

const string QueryRequest::kAllowDiskUseField("allowDiskUse");

const long long QueryRequest::kDefaultBatchSize = 101;

namespace {

Status checkFieldType(const BSONElement& el, BSONType type) {
    if (type != el.type()) {
        str::stream ss;
        ss << "Failed to parse: " << el.toString() << ". "
           << "'" << el.fieldName() << "' field must be of BSON type " << typeName(type) << ".";
        return Status(ErrorCodes::FailedToParse, ss);
    }

    return Status::OK();
}

// Find command field names.
const char kFilterField[] = "filter";
const char kProjectionField[] = "projection";
const char kSortField[] = "sort";
const char kHintField[] = "hint";
const char kCollationField[] = "collation";
const char kSkipField[] = "skip";
const char kLimitField[] = "limit";
const char kBatchSizeField[] = "batchSize";
const char kNToReturnField[] = "ntoreturn";
const char kSingleBatchField[] = "singleBatch";
const char kMaxField[] = "max";
const char kMinField[] = "min";
const char kReturnKeyField[] = "returnKey";
const char kShowRecordIdField[] = "showRecordId";
const char kTailableField[] = "tailable";
const char kOplogReplayField[] = "oplogReplay";
const char kNoCursorTimeoutField[] = "noCursorTimeout";
const char kAwaitDataField[] = "awaitData";
const char kPartialResultsField[] = "allowPartialResults";
const char kRuntimeConstantsField[] = "runtimeConstants";
const char kTermField[] = "term";
const char kOptionsField[] = "options";
const char kReadOnceField[] = "readOnce";
const char kAllowSpeculativeMajorityReadField[] = "allowSpeculativeMajorityRead";
const char kInternalReadAtClusterTimeField[] = "$_internalReadAtClusterTime";

// Field names for sorting options.
const char kNaturalSortField[] = "$natural";

}  // namespace

const char QueryRequest::kFindCommandName[] = "find";
const char QueryRequest::kShardVersionField[] = "shardVersion";

QueryRequest::QueryRequest(NamespaceStringOrUUID nssOrUuid)
    : _nss(nssOrUuid.nss() ? *nssOrUuid.nss() : NamespaceString()), _uuid(nssOrUuid.uuid()) {}

void QueryRequest::refreshNSS(OperationContext* opCtx) {
    if (_uuid) {
        const CollectionCatalog& catalog = CollectionCatalog::get(opCtx);
        auto foundColl = catalog.lookupCollectionByUUID(_uuid.get());
        uassert(ErrorCodes::NamespaceNotFound,
                str::stream() << "UUID " << _uuid.get() << " specified in query request not found",
                foundColl);
        dassert(opCtx->lockState()->isDbLockedForMode(foundColl->ns().db(), MODE_IS));
        _nss = foundColl->ns();
    }
    invariant(!_nss.isEmpty());
}

// static
StatusWith<unique_ptr<QueryRequest>> QueryRequest::parseFromFindCommand(unique_ptr<QueryRequest> qr,
                                                                        const BSONObj& cmdObj,
                                                                        bool isExplain) {
    qr->_explain = isExplain;
    bool tailable = false;
    bool awaitData = false;

    // Parse the command BSON by looping through one element at a time.
    BSONObjIterator it(cmdObj);
    while (it.more()) {
        BSONElement el = it.next();
        const auto fieldName = el.fieldNameStringData();
        if (fieldName == kFindCommandName) {
            // Check both UUID and String types for "find" field.
            Status status = checkFieldType(el, BinData);
            if (!status.isOK()) {
                status = checkFieldType(el, String);
            }
            if (!status.isOK()) {
                return status;
            }
        } else if (fieldName == kFilterField) {
            Status status = checkFieldType(el, Object);
            if (!status.isOK()) {
                return status;
            }

            qr->_filter = el.Obj().getOwned();
        } else if (fieldName == kProjectionField) {
            Status status = checkFieldType(el, Object);
            if (!status.isOK()) {
                return status;
            }

            qr->_proj = el.Obj().getOwned();
        } else if (fieldName == kSortField) {
            Status status = checkFieldType(el, Object);
            if (!status.isOK()) {
                return status;
            }

            qr->_sort = el.Obj().getOwned();
        } else if (fieldName == kHintField) {
            BSONObj hintObj;
            if (Object == el.type()) {
                hintObj = cmdObj["hint"].Obj().getOwned();
            } else if (String == el.type()) {
                hintObj = el.wrap("$hint");
            } else {
                return Status(ErrorCodes::FailedToParse,
                              "hint must be either a string or nested object");
            }

            qr->_hint = hintObj;
        } else if (fieldName == repl::ReadConcernArgs::kReadConcernFieldName) {
            // Read concern parsing is handled elsewhere, but we store a copy here.
            Status status = checkFieldType(el, Object);
            if (!status.isOK()) {
                return status;
            }

            qr->_readConcern = el.Obj().getOwned();
        } else if (fieldName == QueryRequest::kUnwrappedReadPrefField) {
            // Read preference parsing is handled elsewhere, but we store a copy here.
            Status status = checkFieldType(el, Object);
            if (!status.isOK()) {
                return status;
            }

            qr->setUnwrappedReadPref(el.Obj());
        } else if (fieldName == kCollationField) {
            // Collation parsing is handled elsewhere, but we store a copy here.
            Status status = checkFieldType(el, Object);
            if (!status.isOK()) {
                return status;
            }

            qr->_collation = el.Obj().getOwned();
        } else if (fieldName == kSkipField) {
            if (!el.isNumber()) {
                str::stream ss;
                ss << "Failed to parse: " << cmdObj.toString() << ". "
                   << "'skip' field must be numeric.";
                return Status(ErrorCodes::FailedToParse, ss);
            }

            long long skip = el.numberLong();

            // A skip value of 0 means that there is no skip.
            if (skip) {
                qr->_skip = skip;
            }
        } else if (fieldName == kLimitField) {
            if (!el.isNumber()) {
                str::stream ss;
                ss << "Failed to parse: " << cmdObj.toString() << ". "
                   << "'limit' field must be numeric.";
                return Status(ErrorCodes::FailedToParse, ss);
            }

            long long limit = el.numberLong();

            // A limit value of 0 means that there is no limit.
            if (limit) {
                qr->_limit = limit;
            }
        } else if (fieldName == kBatchSizeField) {
            if (!el.isNumber()) {
                str::stream ss;
                ss << "Failed to parse: " << cmdObj.toString() << ". "
                   << "'batchSize' field must be numeric.";
                return Status(ErrorCodes::FailedToParse, ss);
            }

            qr->_batchSize = el.numberLong();
        } else if (fieldName == kNToReturnField) {
            if (!el.isNumber()) {
                str::stream ss;
                ss << "Failed to parse: " << cmdObj.toString() << ". "
                   << "'ntoreturn' field must be numeric.";
                return Status(ErrorCodes::FailedToParse, ss);
            }

            qr->_ntoreturn = el.numberLong();
        } else if (fieldName == kSingleBatchField) {
            Status status = checkFieldType(el, Bool);
            if (!status.isOK()) {
                return status;
            }

            qr->_wantMore = !el.boolean();
        } else if (fieldName == kAllowDiskUseField) {
            Status status = checkFieldType(el, Bool);
            if (!status.isOK()) {
                return status;
            }

            qr->_allowDiskUse = el.boolean();
        } else if (fieldName == cmdOptionMaxTimeMS) {
            StatusWith<int> maxTimeMS = parseMaxTimeMS(el);
            if (!maxTimeMS.isOK()) {
                return maxTimeMS.getStatus();
            }

            qr->_maxTimeMS = maxTimeMS.getValue();
        } else if (fieldName == kMinField) {
            Status status = checkFieldType(el, Object);
            if (!status.isOK()) {
                return status;
            }

            qr->_min = el.Obj().getOwned();
        } else if (fieldName == kMaxField) {
            Status status = checkFieldType(el, Object);
            if (!status.isOK()) {
                return status;
            }

            qr->_max = el.Obj().getOwned();
        } else if (fieldName == kReturnKeyField) {
            Status status = checkFieldType(el, Bool);
            if (!status.isOK()) {
                return status;
            }

            qr->_returnKey = el.boolean();
        } else if (fieldName == kShowRecordIdField) {
            Status status = checkFieldType(el, Bool);
            if (!status.isOK()) {
                return status;
            }

            qr->_showRecordId = el.boolean();
        } else if (fieldName == kTailableField) {
            Status status = checkFieldType(el, Bool);
            if (!status.isOK()) {
                return status;
            }

            tailable = el.boolean();
        } else if (fieldName == kOplogReplayField) {
            Status status = checkFieldType(el, Bool);
            if (!status.isOK()) {
                return status;
            }

            qr->_oplogReplay = el.boolean();
        } else if (fieldName == kNoCursorTimeoutField) {
            Status status = checkFieldType(el, Bool);
            if (!status.isOK()) {
                return status;
            }

            qr->_noCursorTimeout = el.boolean();
        } else if (fieldName == kAwaitDataField) {
            Status status = checkFieldType(el, Bool);
            if (!status.isOK()) {
                return status;
            }

            awaitData = el.boolean();
        } else if (fieldName == kPartialResultsField) {
            Status status = checkFieldType(el, Bool);
            if (!status.isOK()) {
                return status;
            }

            qr->_allowPartialResults = el.boolean();
        } else if (fieldName == kRuntimeConstantsField) {
            Status status = checkFieldType(el, Object);
            if (!status.isOK()) {
                return status;
            }
            qr->_runtimeConstants =
                RuntimeConstants::parse(IDLParserErrorContext(kRuntimeConstantsField),
                                        cmdObj.getObjectField(kRuntimeConstantsField));
        } else if (fieldName == kOptionsField) {
            // 3.0.x versions of the shell may generate an explain of a find command with an
            // 'options' field. We accept this only if the 'options' field is empty so that
            // the shell's explain implementation is forwards compatible.
            //
            // TODO: Remove for 3.4.
            if (!qr->isExplain()) {
                return Status(ErrorCodes::FailedToParse,
                              str::stream() << "Field '" << kOptionsField
                                            << "' is only allowed for explain.");
            }

            Status status = checkFieldType(el, Object);
            if (!status.isOK()) {
                return status;
            }

            BSONObj optionsObj = el.Obj();
            if (!optionsObj.isEmpty()) {
                return Status(ErrorCodes::FailedToParse,
                              str::stream() << "Failed to parse options: " << optionsObj.toString()
                                            << ". You may need to update your shell or driver.");
            }
        } else if (fieldName == kShardVersionField) {
            // Shard version parsing is handled elsewhere.
        } else if (fieldName == kTermField) {
            Status status = checkFieldType(el, NumberLong);
            if (!status.isOK()) {
                return status;
            }
            qr->_replicationTerm = el._numberLong();
        } else if (fieldName == kReadOnceField) {
            Status status = checkFieldType(el, Bool);
            if (!status.isOK()) {
                return status;
            }

            qr->_readOnce = el.boolean();
        } else if (fieldName == kAllowSpeculativeMajorityReadField) {
            Status status = checkFieldType(el, Bool);
            if (!status.isOK()) {
                return status;
            }
            qr->_allowSpeculativeMajorityRead = el.boolean();
        } else if (fieldName == kInternalReadAtClusterTimeField) {
            Status status = checkFieldType(el, BSONType::bsonTimestamp);
            if (!status.isOK()) {
                return status;
            }
            qr->_internalReadAtClusterTime = el.timestamp();
        } else if (!isGenericArgument(fieldName)) {
            return Status(ErrorCodes::FailedToParse,
                          str::stream() << "Failed to parse: " << cmdObj.toString() << ". "
                                        << "Unrecognized field '" << fieldName << "'.");
        }
    }

    auto tailableMode = tailableModeFromBools(tailable, awaitData);
    if (!tailableMode.isOK()) {
        return tailableMode.getStatus();
    }
    qr->_tailableMode = tailableMode.getValue();
    qr->addMetaProjection();

    Status validateStatus = qr->validate();
    if (!validateStatus.isOK()) {
        return validateStatus;
    }

    return std::move(qr);
}

StatusWith<unique_ptr<QueryRequest>> QueryRequest::makeFromFindCommand(NamespaceString nss,
                                                                       const BSONObj& cmdObj,
                                                                       bool isExplain) {
    BSONElement first = cmdObj.firstElement();
    if (first.type() == BinData && first.binDataType() == BinDataType::newUUID) {
        auto uuid = uassertStatusOK(UUID::parse(first));
        auto qr = std::make_unique<QueryRequest>(NamespaceStringOrUUID(nss.db().toString(), uuid));
        return parseFromFindCommand(std::move(qr), cmdObj, isExplain);
    } else {
        auto qr = std::make_unique<QueryRequest>(nss);
        return parseFromFindCommand(std::move(qr), cmdObj, isExplain);
    }
}

BSONObj QueryRequest::asFindCommand() const {
    BSONObjBuilder bob;
    asFindCommand(&bob);
    return bob.obj();
}

BSONObj QueryRequest::asFindCommandWithUuid() const {
    BSONObjBuilder bob;
    asFindCommandWithUuid(&bob);
    return bob.obj();
}

void QueryRequest::asFindCommand(BSONObjBuilder* cmdBuilder) const {
    cmdBuilder->append(kFindCommandName, _nss.coll());
    asFindCommandInternal(cmdBuilder);
}

void QueryRequest::asFindCommandWithUuid(BSONObjBuilder* cmdBuilder) const {
    invariant(_uuid);
    _uuid->appendToBuilder(cmdBuilder, kFindCommandName);
    asFindCommandInternal(cmdBuilder);
}

void QueryRequest::asFindCommandInternal(BSONObjBuilder* cmdBuilder) const {
    if (!_filter.isEmpty()) {
        cmdBuilder->append(kFilterField, _filter);
    }

    if (!_proj.isEmpty()) {
        cmdBuilder->append(kProjectionField, _proj);
    }

    if (!_sort.isEmpty()) {
        cmdBuilder->append(kSortField, _sort);
    }

    if (!_hint.isEmpty()) {
        cmdBuilder->append(kHintField, _hint);
    }

    if (!_readConcern.isEmpty()) {
        cmdBuilder->append(repl::ReadConcernArgs::kReadConcernFieldName, _readConcern);
    }

    if (!_collation.isEmpty()) {
        cmdBuilder->append(kCollationField, _collation);
    }

    if (_skip) {
        cmdBuilder->append(kSkipField, *_skip);
    }

    if (_ntoreturn) {
        cmdBuilder->append(kNToReturnField, *_ntoreturn);
    }

    if (_limit) {
        cmdBuilder->append(kLimitField, *_limit);
    }

    if (_allowDiskUse) {
        cmdBuilder->append(kAllowDiskUseField, true);
    }

    if (_batchSize) {
        cmdBuilder->append(kBatchSizeField, *_batchSize);
    }

    if (!_wantMore) {
        cmdBuilder->append(kSingleBatchField, true);
    }

    if (_maxTimeMS > 0) {
        cmdBuilder->append(cmdOptionMaxTimeMS, _maxTimeMS);
    }

    if (!_max.isEmpty()) {
        cmdBuilder->append(kMaxField, _max);
    }

    if (!_min.isEmpty()) {
        cmdBuilder->append(kMinField, _min);
    }

    if (_returnKey) {
        cmdBuilder->append(kReturnKeyField, true);
    }

    if (_showRecordId) {
        cmdBuilder->append(kShowRecordIdField, true);
    }

    switch (_tailableMode) {
        case TailableModeEnum::kTailable: {
            cmdBuilder->append(kTailableField, true);
            break;
        }
        case TailableModeEnum::kTailableAndAwaitData: {
            cmdBuilder->append(kTailableField, true);
            cmdBuilder->append(kAwaitDataField, true);
            break;
        }
        case TailableModeEnum::kNormal: {
            break;
        }
    }

    if (_oplogReplay) {
        cmdBuilder->append(kOplogReplayField, true);
    }

    if (_noCursorTimeout) {
        cmdBuilder->append(kNoCursorTimeoutField, true);
    }

    if (_allowPartialResults) {
        cmdBuilder->append(kPartialResultsField, true);
    }

    if (_runtimeConstants) {
        BSONObjBuilder rtcBuilder(cmdBuilder->subobjStart(kRuntimeConstantsField));
        _runtimeConstants->serialize(&rtcBuilder);
        rtcBuilder.doneFast();
    }

    if (_replicationTerm) {
        cmdBuilder->append(kTermField, *_replicationTerm);
    }

    if (_readOnce) {
        cmdBuilder->append(kReadOnceField, true);
    }

    if (_allowSpeculativeMajorityRead) {
        cmdBuilder->append(kAllowSpeculativeMajorityReadField, true);
    }

    if (_internalReadAtClusterTime) {
        cmdBuilder->append(kInternalReadAtClusterTimeField, *_internalReadAtClusterTime);
    }
}

void QueryRequest::addShowRecordIdMetaProj() {
    if (_proj["$recordId"]) {
        // There's already some projection on $recordId. Don't overwrite it.
        return;
    }

    BSONObjBuilder projBob;
    projBob.appendElements(_proj);
    BSONObj metaRecordId = BSON("$recordId" << BSON("$meta" << QueryRequest::metaRecordId));
    projBob.append(metaRecordId.firstElement());
    _proj = projBob.obj();
}

Status QueryRequest::validate() const {
    // Min and Max objects must have the same fields.
    if (!_min.isEmpty() && !_max.isEmpty()) {
        if (!_min.isFieldNamePrefixOf(_max) || (_min.nFields() != _max.nFields())) {
            return Status(ErrorCodes::Error(51176), "min and max must have the same field names");
        }
    }

    // Can't combine a normal sort and a $meta projection on the same field.
    BSONObjIterator projIt(_proj);
    while (projIt.more()) {
        BSONElement projElt = projIt.next();
        if (isTextScoreMeta(projElt)) {
            BSONElement sortElt = _sort[projElt.fieldName()];
            if (!sortElt.eoo() && !isTextScoreMeta(sortElt)) {
                return Status(ErrorCodes::BadValue,
                              "can't have a non-$meta sort on a $meta projection");
            }
        }
    }

    if (!isValidSortOrder(_sort)) {
        return Status(ErrorCodes::BadValue, "bad sort specification");
    }

    // All fields with a $meta sort must have a corresponding $meta projection.
    BSONObjIterator sortIt(_sort);
    while (sortIt.more()) {
        BSONElement sortElt = sortIt.next();
        if (isTextScoreMeta(sortElt)) {
            BSONElement projElt = _proj[sortElt.fieldName()];
            if (projElt.eoo() || !isTextScoreMeta(projElt)) {
                return Status(ErrorCodes::BadValue,
                              "must have $meta projection for all $meta sort keys");
            }
        }
    }

    if ((_limit || _batchSize) && _ntoreturn) {
        return Status(ErrorCodes::BadValue,
                      "'limit' or 'batchSize' fields can not be set with 'ntoreturn' field.");
    }


    if (_skip && *_skip < 0) {
        return Status(ErrorCodes::BadValue,
                      str::stream() << "Skip value must be non-negative, but received: " << *_skip);
    }

    if (_limit && *_limit < 0) {
        return Status(ErrorCodes::BadValue,
                      str::stream()
                          << "Limit value must be non-negative, but received: " << *_limit);
    }

    if (_batchSize && *_batchSize < 0) {
        return Status(ErrorCodes::BadValue,
                      str::stream()
                          << "BatchSize value must be non-negative, but received: " << *_batchSize);
    }

    if (_ntoreturn && *_ntoreturn < 0) {
        return Status(ErrorCodes::BadValue,
                      str::stream()
                          << "NToReturn value must be non-negative, but received: " << *_ntoreturn);
    }

    if (_maxTimeMS < 0) {
        return Status(ErrorCodes::BadValue,
                      str::stream()
                          << "MaxTimeMS value must be non-negative, but received: " << _maxTimeMS);
    }

    if (_tailableMode != TailableModeEnum::kNormal) {
        // Tailable cursors cannot have any sort other than {$natural: 1}.
        const BSONObj expectedSort = BSON(kNaturalSortField << 1);
        if (!_sort.isEmpty() &&
            SimpleBSONObjComparator::kInstance.evaluate(_sort != expectedSort)) {
            return Status(ErrorCodes::BadValue,
                          "cannot use tailable option with a sort other than {$natural: 1}");
        }

        // Cannot indicate that you want a 'singleBatch' if the cursor is tailable.
        if (!_wantMore) {
            return Status(ErrorCodes::BadValue,
                          "cannot use tailable option with the 'singleBatch' option");
        }
    }

    return Status::OK();
}

// static
StatusWith<int> QueryRequest::parseMaxTimeMS(BSONElement maxTimeMSElt) {
    if (!maxTimeMSElt.eoo() && !maxTimeMSElt.isNumber()) {
        return StatusWith<int>(
            ErrorCodes::BadValue,
            (StringBuilder() << maxTimeMSElt.fieldNameStringData() << " must be a number").str());
    }
    long long maxTimeMSLongLong = maxTimeMSElt.safeNumberLong();  // returns 0 on EOO
    if (maxTimeMSLongLong < 0 || maxTimeMSLongLong > INT_MAX) {
        return StatusWith<int>(
            ErrorCodes::BadValue,
            (StringBuilder() << maxTimeMSElt.fieldNameStringData() << " is out of range").str());
    }
    double maxTimeMSDouble = maxTimeMSElt.numberDouble();
    if (maxTimeMSElt.type() == mongo::NumberDouble && floor(maxTimeMSDouble) != maxTimeMSDouble) {
        return StatusWith<int>(
            ErrorCodes::BadValue,
            (StringBuilder() << maxTimeMSElt.fieldNameStringData() << " has non-integral value")
                .str());
    }
    return StatusWith<int>(static_cast<int>(maxTimeMSLongLong));
}

// static
bool QueryRequest::isTextScoreMeta(BSONElement elt) {
    // elt must be foo: {$meta: "textScore"}
    if (mongo::Object != elt.type()) {
        return false;
    }
    BSONObj metaObj = elt.Obj();
    BSONObjIterator metaIt(metaObj);
    // must have exactly 1 element
    if (!metaIt.more()) {
        return false;
    }
    BSONElement metaElt = metaIt.next();
    if (metaElt.fieldNameStringData() != "$meta") {
        return false;
    }
    if (mongo::String != metaElt.type()) {
        return false;
    }
    if (QueryRequest::metaTextScore != metaElt.valuestr()) {
        return false;
    }
    // must have exactly 1 element
    if (metaIt.more()) {
        return false;
    }
    return true;
}

// static
bool QueryRequest::isValidSortOrder(const BSONObj& sortObj) {
    BSONObjIterator i(sortObj);
    while (i.more()) {
        BSONElement e = i.next();
        // fieldNameSize() includes NULL terminator. For empty field name,
        // we should be checking for 1 instead of 0.
        if (1 == e.fieldNameSize()) {
            return false;
        }
        if (isTextScoreMeta(e)) {
            continue;
        }
        long long n = e.safeNumberLong();
        if (!(e.isNumber() && (n == -1LL || n == 1LL))) {
            return false;
        }
    }
    return true;
}

//
// Old QueryRequest parsing code: SOON TO BE DEPRECATED.
//

// static
StatusWith<unique_ptr<QueryRequest>> QueryRequest::fromLegacyQueryMessage(const QueryMessage& qm) {
    auto qr = std::make_unique<QueryRequest>(NamespaceString(qm.ns));

    Status status = qr->init(qm.ntoskip, qm.ntoreturn, qm.queryOptions, qm.query, qm.fields, true);
    if (!status.isOK()) {
        return status;
    }

    return std::move(qr);
}

StatusWith<unique_ptr<QueryRequest>> QueryRequest::fromLegacyQuery(NamespaceStringOrUUID nsOrUuid,
                                                                   const BSONObj& queryObj,
                                                                   const BSONObj& proj,
                                                                   int ntoskip,
                                                                   int ntoreturn,
                                                                   int queryOptions) {
    auto qr = std::make_unique<QueryRequest>(nsOrUuid);

    Status status = qr->init(ntoskip, ntoreturn, queryOptions, queryObj, proj, true);
    if (!status.isOK()) {
        return status;
    }

    return std::move(qr);
}

Status QueryRequest::init(int ntoskip,
                          int ntoreturn,
                          int queryOptions,
                          const BSONObj& queryObj,
                          const BSONObj& proj,
                          bool fromQueryMessage) {
    _proj = proj.getOwned();

    if (ntoskip) {
        _skip = ntoskip;
    }

    if (ntoreturn) {
        if (ntoreturn < 0) {
            if (ntoreturn == std::numeric_limits<int>::min()) {
                // ntoreturn is negative but can't be negated.
                return Status(ErrorCodes::BadValue, "bad ntoreturn value in query");
            }
            _ntoreturn = -ntoreturn;
            _wantMore = false;
        } else {
            _ntoreturn = ntoreturn;
        }
    }

    // An ntoreturn of 1 is special because it also means to return at most one batch.
    if (_ntoreturn.value_or(0) == 1) {
        _wantMore = false;
    }

    // Initialize flags passed as 'queryOptions' bit vector.
    initFromInt(queryOptions);

    if (fromQueryMessage) {
        BSONElement queryField = queryObj["query"];
        if (!queryField.isABSONObj()) {
            queryField = queryObj["$query"];
        }
        if (queryField.isABSONObj()) {
            _filter = queryField.embeddedObject().getOwned();
            Status status = initFullQuery(queryObj);
            if (!status.isOK()) {
                return status;
            }
        } else {
            _filter = queryObj.getOwned();
        }
    } else {
        // This is the debugging code path.
        _filter = queryObj.getOwned();
    }

    _hasReadPref = queryObj.hasField("$readPreference");

    return validate();
}

Status QueryRequest::initFullQuery(const BSONObj& top) {
    BSONObjIterator i(top);

    while (i.more()) {
        BSONElement e = i.next();
        StringData name = e.fieldNameStringData();

        if (name == "$orderby" || name == "orderby") {
            if (Object == e.type()) {
                _sort = e.embeddedObject().getOwned();
            } else if (Array == e.type()) {
                _sort = e.embeddedObject();

                // TODO: Is this ever used?  I don't think so.
                // Quote:
                // This is for languages whose "objects" are not well ordered (JSON is well
                // ordered).
                // [ { a : ... } , { b : ... } ] -> { a : ..., b : ... }
                // note: this is slow, but that is ok as order will have very few pieces
                BSONObjBuilder b;
                char p[2] = "0";

                while (1) {
                    BSONObj j = _sort.getObjectField(p);
                    if (j.isEmpty()) {
                        break;
                    }
                    BSONElement e = j.firstElement();
                    if (e.eoo()) {
                        return Status(ErrorCodes::BadValue, "bad order array");
                    }
                    if (!e.isNumber()) {
                        return Status(ErrorCodes::BadValue, "bad order array [2]");
                    }
                    b.append(e);
                    (*p)++;
                    if (!(*p <= '9')) {
                        return Status(ErrorCodes::BadValue, "too many ordering elements");
                    }
                }

                _sort = b.obj();
            } else {
                return Status(ErrorCodes::BadValue, "sort must be object or array");
            }
        } else if (name.startsWith("$")) {
            name = name.substr(1);  // chop first char
            if (name == "explain") {
                // Won't throw.
                _explain = e.trueValue();
            } else if (name == "min") {
                if (!e.isABSONObj()) {
                    return Status(ErrorCodes::BadValue, "$min must be a BSONObj");
                }
                _min = e.embeddedObject().getOwned();
            } else if (name == "max") {
                if (!e.isABSONObj()) {
                    return Status(ErrorCodes::BadValue, "$max must be a BSONObj");
                }
                _max = e.embeddedObject().getOwned();
            } else if (name == "hint") {
                if (e.isABSONObj()) {
                    _hint = e.embeddedObject().getOwned();
                } else if (String == e.type()) {
                    _hint = e.wrap();
                } else {
                    return Status(ErrorCodes::BadValue,
                                  "$hint must be either a string or nested object");
                }
            } else if (name == "returnKey") {
                // Won't throw.
                if (e.trueValue()) {
                    _returnKey = true;
                }
            } else if (name == "showDiskLoc") {
                // Won't throw.
                if (e.trueValue()) {
                    _showRecordId = true;
                    addShowRecordIdMetaProj();
                }
            } else if (name == "maxTimeMS") {
                StatusWith<int> maxTimeMS = parseMaxTimeMS(e);
                if (!maxTimeMS.isOK()) {
                    return maxTimeMS.getStatus();
                }
                _maxTimeMS = maxTimeMS.getValue();
            }
        }
    }

    return Status::OK();
}

int QueryRequest::getOptions() const {
    int options = 0;
    if (_tailableMode == TailableModeEnum::kTailable) {
        options |= QueryOption_CursorTailable;
    } else if (_tailableMode == TailableModeEnum::kTailableAndAwaitData) {
        options |= QueryOption_CursorTailable;
        options |= QueryOption_AwaitData;
    }
    if (_slaveOk) {
        options |= QueryOption_SlaveOk;
    }
    if (_oplogReplay) {
        options |= QueryOption_OplogReplay;
    }
    if (_noCursorTimeout) {
        options |= QueryOption_NoCursorTimeout;
    }
    if (_exhaust) {
        options |= QueryOption_Exhaust;
    }
    if (_allowPartialResults) {
        options |= QueryOption_PartialResults;
    }
    return options;
}

void QueryRequest::initFromInt(int options) {
    bool tailable = (options & QueryOption_CursorTailable) != 0;
    bool awaitData = (options & QueryOption_AwaitData) != 0;
    _tailableMode = uassertStatusOK(tailableModeFromBools(tailable, awaitData));
    _slaveOk = (options & QueryOption_SlaveOk) != 0;
    _oplogReplay = (options & QueryOption_OplogReplay) != 0;
    _noCursorTimeout = (options & QueryOption_NoCursorTimeout) != 0;
    _exhaust = (options & QueryOption_Exhaust) != 0;
    _allowPartialResults = (options & QueryOption_PartialResults) != 0;
}

void QueryRequest::addMetaProjection() {
    if (showRecordId()) {
        addShowRecordIdMetaProj();
    }
}

boost::optional<long long> QueryRequest::getEffectiveBatchSize() const {
    return _batchSize ? _batchSize : _ntoreturn;
}

StatusWith<BSONObj> QueryRequest::asAggregationCommand() const {
    BSONObjBuilder aggregationBuilder;

    // First, check if this query has options that are not supported in aggregation.
    if (!_min.isEmpty()) {
        return {ErrorCodes::InvalidPipelineOperator,
                str::stream() << "Option " << kMinField << " not supported in aggregation."};
    }
    if (!_max.isEmpty()) {
        return {ErrorCodes::InvalidPipelineOperator,
                str::stream() << "Option " << kMaxField << " not supported in aggregation."};
    }
    if (_returnKey) {
        return {ErrorCodes::InvalidPipelineOperator,
                str::stream() << "Option " << kReturnKeyField << " not supported in aggregation."};
    }
    if (_showRecordId) {
        return {ErrorCodes::InvalidPipelineOperator,
                str::stream() << "Option " << kShowRecordIdField
                              << " not supported in aggregation."};
    }
    if (isTailable()) {
        return {ErrorCodes::InvalidPipelineOperator,
                "Tailable cursors are not supported in aggregation."};
    }
    if (_oplogReplay) {
        return {ErrorCodes::InvalidPipelineOperator,
                str::stream() << "Option " << kOplogReplayField
                              << " not supported in aggregation."};
    }
    if (_noCursorTimeout) {
        return {ErrorCodes::InvalidPipelineOperator,
                str::stream() << "Option " << kNoCursorTimeoutField
                              << " not supported in aggregation."};
    }
    if (_allowPartialResults) {
        return {ErrorCodes::InvalidPipelineOperator,
                str::stream() << "Option " << kPartialResultsField
                              << " not supported in aggregation."};
    }
    if (_ntoreturn) {
        return {ErrorCodes::BadValue,
                str::stream() << "Cannot convert to an aggregation if ntoreturn is set."};
    }
    if (_sort[kNaturalSortField]) {
        return {ErrorCodes::InvalidPipelineOperator,
                str::stream() << "Sort option " << kNaturalSortField
                              << " not supported in aggregation."};
    }
    // The aggregation command normally does not support the 'singleBatch' option, but we make a
    // special exception if 'limit' is set to 1.
    if (!_wantMore && _limit.value_or(0) != 1LL) {
        return {ErrorCodes::InvalidPipelineOperator,
                str::stream() << "Option " << kSingleBatchField
                              << " not supported in aggregation."};
    }
    if (_readOnce) {
        return {ErrorCodes::InvalidPipelineOperator,
                str::stream() << "Option " << kReadOnceField << " not supported in aggregation."};
    }

    if (_allowSpeculativeMajorityRead) {
        return {ErrorCodes::InvalidPipelineOperator,
                str::stream() << "Option " << kAllowSpeculativeMajorityReadField
                              << " not supported in aggregation."};
    }

    if (_internalReadAtClusterTime) {
        return {ErrorCodes::InvalidPipelineOperator,
                str::stream() << "Option " << kInternalReadAtClusterTimeField
                              << " not supported in aggregation."};
    }

    // Now that we've successfully validated this QR, begin building the aggregation command.
    aggregationBuilder.append("aggregate", _nss.coll());

    // Construct an aggregation pipeline that finds the equivalent documents to this query request.
    BSONArrayBuilder pipelineBuilder(aggregationBuilder.subarrayStart("pipeline"));
    if (!_filter.isEmpty()) {
        BSONObjBuilder matchBuilder(pipelineBuilder.subobjStart());
        matchBuilder.append("$match", _filter);
        matchBuilder.doneFast();
    }
    if (!_sort.isEmpty()) {
        BSONObjBuilder sortBuilder(pipelineBuilder.subobjStart());
        sortBuilder.append("$sort", _sort);
        sortBuilder.doneFast();
    }
    if (_skip) {
        BSONObjBuilder skipBuilder(pipelineBuilder.subobjStart());
        skipBuilder.append("$skip", *_skip);
        skipBuilder.doneFast();
    }
    if (_limit) {
        BSONObjBuilder limitBuilder(pipelineBuilder.subobjStart());
        limitBuilder.append("$limit", *_limit);
        limitBuilder.doneFast();
    }
    if (!_proj.isEmpty()) {
        BSONObjBuilder projectBuilder(pipelineBuilder.subobjStart());
        projectBuilder.append("$project", _proj);
        projectBuilder.doneFast();
    }
    pipelineBuilder.doneFast();

    // The aggregation 'cursor' option is always set, regardless of the presence of batchSize.
    BSONObjBuilder batchSizeBuilder(aggregationBuilder.subobjStart("cursor"));
    if (_batchSize) {
        batchSizeBuilder.append(kBatchSizeField, *_batchSize);
    }
    batchSizeBuilder.doneFast();

    // Other options.
    aggregationBuilder.append("collation", _collation);
    if (_maxTimeMS > 0) {
        aggregationBuilder.append(cmdOptionMaxTimeMS, _maxTimeMS);
    }
    if (!_hint.isEmpty()) {
        aggregationBuilder.append("hint", _hint);
    }
    if (!_readConcern.isEmpty()) {
        aggregationBuilder.append("readConcern", _readConcern);
    }
    if (!_unwrappedReadPref.isEmpty()) {
        aggregationBuilder.append(QueryRequest::kUnwrappedReadPrefField, _unwrappedReadPref);
    }
    if (_allowDiskUse) {
        aggregationBuilder.append(QueryRequest::kAllowDiskUseField, _allowDiskUse);
    }
    if (_runtimeConstants) {
        BSONObjBuilder rtcBuilder(aggregationBuilder.subobjStart(kRuntimeConstantsField));
        _runtimeConstants->serialize(&rtcBuilder);
        rtcBuilder.doneFast();
    }
    return StatusWith<BSONObj>(aggregationBuilder.obj());
}
}  // namespace mongo