/
get_executor.cpp
1456 lines (1254 loc) · 61.1 KB
/
get_executor.cpp
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
/**
* Copyright (C) 2013-2014 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* 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 GNU Affero General 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.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kQuery
#include "mongo/platform/basic.h"
#include "mongo/db/query/get_executor.h"
#include <limits>
#include <memory>
#include "mongo/base/error_codes.h"
#include "mongo/base/parse_number.h"
#include "mongo/client/dbclientinterface.h"
#include "mongo/db/exec/cached_plan.h"
#include "mongo/db/exec/count.h"
#include "mongo/db/exec/delete.h"
#include "mongo/db/exec/eof.h"
#include "mongo/db/exec/group.h"
#include "mongo/db/exec/idhack.h"
#include "mongo/db/exec/multi_plan.h"
#include "mongo/db/exec/oplogstart.h"
#include "mongo/db/exec/projection.h"
#include "mongo/db/exec/shard_filter.h"
#include "mongo/db/exec/sort_key_generator.h"
#include "mongo/db/exec/subplan.h"
#include "mongo/db/exec/update.h"
#include "mongo/db/index_names.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/matcher/extensions_callback_disallow_extensions.h"
#include "mongo/db/matcher/extensions_callback_noop.h"
#include "mongo/db/matcher/extensions_callback_real.h"
#include "mongo/db/ops/update_lifecycle.h"
#include "mongo/db/query/canonical_query.h"
#include "mongo/db/query/explain.h"
#include "mongo/db/query/index_bounds_builder.h"
#include "mongo/db/query/internal_plans.h"
#include "mongo/db/query/plan_cache.h"
#include "mongo/db/query/plan_executor.h"
#include "mongo/db/query/planner_access.h"
#include "mongo/db/query/planner_analysis.h"
#include "mongo/db/query/query_knobs.h"
#include "mongo/db/query/query_planner.h"
#include "mongo/db/query/query_planner_common.h"
#include "mongo/db/query/query_settings.h"
#include "mongo/db/query/stage_builder.h"
#include "mongo/db/repl/replication_coordinator_global.h"
#include "mongo/db/server_options.h"
#include "mongo/db/server_parameters.h"
#include "mongo/db/service_context.h"
#include "mongo/db/s/collection_metadata.h"
#include "mongo/db/s/collection_sharding_state.h"
#include "mongo/db/s/sharding_state.h"
#include "mongo/db/storage/storage_options.h"
#include "mongo/db/storage/oplog_hack.h"
#include "mongo/scripting/engine.h"
#include "mongo/stdx/memory.h"
#include "mongo/util/log.h"
namespace mongo {
using std::unique_ptr;
using std::string;
using std::vector;
using stdx::make_unique;
// static
void filterAllowedIndexEntries(const AllowedIndices& allowedIndices,
std::vector<IndexEntry>* indexEntries) {
invariant(indexEntries);
// Filter index entries
// Check BSON objects in AllowedIndices::_indexKeyPatterns against IndexEntry::keyPattern.
// Removes IndexEntrys that do not match _indexKeyPatterns.
std::vector<IndexEntry> temp;
for (std::vector<IndexEntry>::const_iterator i = indexEntries->begin();
i != indexEntries->end();
++i) {
const IndexEntry& indexEntry = *i;
for (std::vector<BSONObj>::const_iterator j = allowedIndices.indexKeyPatterns.begin();
j != allowedIndices.indexKeyPatterns.end();
++j) {
const BSONObj& index = *j;
// Copy index entry to temp vector if found in query settings.
if (0 == indexEntry.keyPattern.woCompare(index)) {
temp.push_back(indexEntry);
break;
}
}
}
// Update results.
temp.swap(*indexEntries);
}
namespace {
// The body is below in the "count hack" section but getExecutor calls it.
bool turnIxscanIntoCount(QuerySolution* soln);
} // namespace
void fillOutPlannerParams(OperationContext* txn,
Collection* collection,
CanonicalQuery* canonicalQuery,
QueryPlannerParams* plannerParams) {
// If it's not NULL, we may have indices. Access the catalog and fill out IndexEntry(s)
IndexCatalog::IndexIterator ii = collection->getIndexCatalog()->getIndexIterator(txn, false);
while (ii.more()) {
const IndexDescriptor* desc = ii.next();
IndexCatalogEntry* ice = ii.catalogEntry(desc);
plannerParams->indices.push_back(IndexEntry(desc->keyPattern(),
desc->getAccessMethodName(),
desc->isMultikey(txn),
desc->isSparse(),
desc->unique(),
desc->indexName(),
ice->getFilterExpression(),
desc->infoObj()));
}
// If query supports index filters, filter params.indices by indices in query settings.
QuerySettings* querySettings = collection->infoCache()->getQuerySettings();
AllowedIndices* allowedIndicesRaw;
PlanCacheKey planCacheKey =
collection->infoCache()->getPlanCache()->computeKey(*canonicalQuery);
// Filter index catalog if index filters are specified for query.
// Also, signal to planner that application hint should be ignored.
if (querySettings->getAllowedIndices(planCacheKey, &allowedIndicesRaw)) {
unique_ptr<AllowedIndices> allowedIndices(allowedIndicesRaw);
filterAllowedIndexEntries(*allowedIndices, &plannerParams->indices);
plannerParams->indexFiltersApplied = true;
}
// We will not output collection scans unless there are no indexed solutions. NO_TABLE_SCAN
// overrides this behavior by not outputting a collscan even if there are no indexed
// solutions.
if (storageGlobalParams.noTableScan) {
const string& ns = canonicalQuery->ns();
// There are certain cases where we ignore this restriction:
bool ignore = canonicalQuery->getQueryObj().isEmpty() ||
(string::npos != ns.find(".system.")) || (0 == ns.find("local."));
if (!ignore) {
plannerParams->options |= QueryPlannerParams::NO_TABLE_SCAN;
}
}
// If the caller wants a shard filter, make sure we're actually sharded.
if (plannerParams->options & QueryPlannerParams::INCLUDE_SHARD_FILTER) {
std::shared_ptr<CollectionMetadata> collMetadata =
CollectionShardingState::get(txn, canonicalQuery->nss())->getMetadata();
if (collMetadata) {
plannerParams->shardKey = collMetadata->getKeyPattern();
} else {
// If there's no metadata don't bother w/the shard filter since we won't know what
// the key pattern is anyway...
plannerParams->options &= ~QueryPlannerParams::INCLUDE_SHARD_FILTER;
}
}
if (internalQueryPlannerEnableIndexIntersection) {
plannerParams->options |= QueryPlannerParams::INDEX_INTERSECTION;
}
plannerParams->options |= QueryPlannerParams::SPLIT_LIMITED_SORT;
// Doc-level locking storage engines cannot answer predicates implicitly via exact index
// bounds for index intersection plans, as this can lead to spurious matches.
//
// Such storage engines do not use the invalidation framework, and therefore
// have no need for KEEP_MUTATIONS.
if (supportsDocLocking()) {
plannerParams->options |= QueryPlannerParams::CANNOT_TRIM_IXISECT;
} else {
plannerParams->options |= QueryPlannerParams::KEEP_MUTATIONS;
}
// MMAPv1 storage engine should have snapshot() perform an index scan on _id rather than a
// collection scan since a collection scan on the MMAP storage engine can return duplicates
// or miss documents.
if (isMMAPV1()) {
plannerParams->options |= QueryPlannerParams::SNAPSHOT_USE_ID;
}
}
namespace {
/**
* Build an execution tree for the query described in 'canonicalQuery'. Does not take
* ownership of arguments.
*
* If an execution tree could be created, then returns Status::OK() and sets 'rootOut' to
* the root of the constructed execution tree, and sets 'querySolutionOut' to the associated
* query solution (if applicable) or NULL.
*
* If an execution tree could not be created, returns a Status indicating why and sets both
* 'rootOut' and 'querySolutionOut' to NULL.
*/
Status prepareExecution(OperationContext* opCtx,
Collection* collection,
WorkingSet* ws,
CanonicalQuery* canonicalQuery,
size_t plannerOptions,
PlanStage** rootOut,
QuerySolution** querySolutionOut) {
invariant(canonicalQuery);
*rootOut = NULL;
*querySolutionOut = NULL;
// This can happen as we're called by internal clients as well.
if (NULL == collection) {
const string& ns = canonicalQuery->ns();
LOG(2) << "Collection " << ns << " does not exist."
<< " Using EOF plan: " << canonicalQuery->toStringShort();
*rootOut = new EOFStage(opCtx);
return Status::OK();
}
// Fill out the planning params. We use these for both cached solutions and non-cached.
QueryPlannerParams plannerParams;
plannerParams.options = plannerOptions;
fillOutPlannerParams(opCtx, collection, canonicalQuery, &plannerParams);
const IndexDescriptor* descriptor = collection->getIndexCatalog()->findIdIndex(opCtx);
// If we have an _id index we can use an idhack plan.
if (descriptor && IDHackStage::supportsQuery(*canonicalQuery)) {
LOG(2) << "Using idhack: " << canonicalQuery->toStringShort();
*rootOut = new IDHackStage(opCtx, collection, canonicalQuery, ws, descriptor);
// Might have to filter out orphaned docs.
if (plannerParams.options & QueryPlannerParams::INCLUDE_SHARD_FILTER) {
*rootOut = new ShardFilterStage(
opCtx,
CollectionShardingState::get(opCtx, canonicalQuery->nss())->getMetadata(),
ws,
*rootOut);
}
// There might be a projection. The idhack stage will always fetch the full
// document, so we don't support covered projections. However, we might use the
// simple inclusion fast path.
if (NULL != canonicalQuery->getProj()) {
ProjectionStageParams params(ExtensionsCallbackReal(opCtx, &collection->ns()));
params.projObj = canonicalQuery->getProj()->getProjObj();
// Add a SortKeyGeneratorStage if there is a $meta sortKey projection.
if (canonicalQuery->getProj()->wantSortKey()) {
*rootOut = new SortKeyGeneratorStage(opCtx,
*rootOut,
ws,
canonicalQuery->getParsed().getSort(),
canonicalQuery->getParsed().getFilter());
}
// Stuff the right data into the params depending on what proj impl we use.
if (canonicalQuery->getProj()->requiresDocument() ||
canonicalQuery->getProj()->wantIndexKey() ||
canonicalQuery->getProj()->wantSortKey()) {
params.fullExpression = canonicalQuery->root();
params.projImpl = ProjectionStageParams::NO_FAST_PATH;
} else {
params.projImpl = ProjectionStageParams::SIMPLE_DOC;
}
*rootOut = new ProjectionStage(opCtx, params, ws, *rootOut);
}
return Status::OK();
}
// Tailable: If the query requests tailable the collection must be capped.
if (canonicalQuery->getParsed().isTailable()) {
if (!collection->isCapped()) {
return Status(ErrorCodes::BadValue,
"error processing query: " + canonicalQuery->toString() +
" tailable cursor requested on non capped collection");
}
}
// Try to look up a cached solution for the query.
CachedSolution* rawCS;
if (PlanCache::shouldCacheQuery(*canonicalQuery) &&
collection->infoCache()->getPlanCache()->get(*canonicalQuery, &rawCS).isOK()) {
// We have a CachedSolution. Have the planner turn it into a QuerySolution.
unique_ptr<CachedSolution> cs(rawCS);
QuerySolution* qs;
Status status = QueryPlanner::planFromCache(*canonicalQuery, plannerParams, *cs, &qs);
if (status.isOK()) {
if ((plannerParams.options & QueryPlannerParams::IS_COUNT) && turnIxscanIntoCount(qs)) {
LOG(2) << "Using fast count: " << canonicalQuery->toStringShort();
}
verify(StageBuilder::build(opCtx, collection, *canonicalQuery, *qs, ws, rootOut));
// Add a CachedPlanStage on top of the previous root.
//
// 'decisionWorks' is used to determine whether the existing cache entry should
// be evicted, and the query replanned.
//
// Takes ownership of '*rootOut'.
*rootOut = new CachedPlanStage(
opCtx, collection, ws, canonicalQuery, plannerParams, cs->decisionWorks, *rootOut);
*querySolutionOut = qs;
return Status::OK();
}
}
if (internalQueryPlanOrChildrenIndependently &&
SubplanStage::canUseSubplanning(*canonicalQuery)) {
LOG(2) << "Running query as sub-queries: " << canonicalQuery->toStringShort();
*rootOut = new SubplanStage(opCtx, collection, ws, plannerParams, canonicalQuery);
return Status::OK();
}
vector<QuerySolution*> solutions;
Status status = QueryPlanner::plan(*canonicalQuery, plannerParams, &solutions);
if (!status.isOK()) {
return Status(ErrorCodes::BadValue,
"error processing query: " + canonicalQuery->toString() +
" planner returned error: " + status.reason());
}
// We cannot figure out how to answer the query. Perhaps it requires an index
// we do not have?
if (0 == solutions.size()) {
return Status(ErrorCodes::BadValue,
str::stream() << "error processing query: " << canonicalQuery->toString()
<< " No query solutions");
}
// See if one of our solutions is a fast count hack in disguise.
if (plannerParams.options & QueryPlannerParams::IS_COUNT) {
for (size_t i = 0; i < solutions.size(); ++i) {
if (turnIxscanIntoCount(solutions[i])) {
// Great, we can use solutions[i]. Clean up the other QuerySolution(s).
for (size_t j = 0; j < solutions.size(); ++j) {
if (j != i) {
delete solutions[j];
}
}
// We're not going to cache anything that's fast count.
verify(StageBuilder::build(
opCtx, collection, *canonicalQuery, *solutions[i], ws, rootOut));
LOG(2) << "Using fast count: " << canonicalQuery->toStringShort()
<< ", planSummary: " << Explain::getPlanSummary(*rootOut);
*querySolutionOut = solutions[i];
return Status::OK();
}
}
}
if (1 == solutions.size()) {
// Only one possible plan. Run it. Build the stages from the solution.
verify(StageBuilder::build(opCtx, collection, *canonicalQuery, *solutions[0], ws, rootOut));
LOG(2) << "Only one plan is available; it will be run but will not be cached. "
<< canonicalQuery->toStringShort()
<< ", planSummary: " << Explain::getPlanSummary(*rootOut);
*querySolutionOut = solutions[0];
return Status::OK();
} else {
// Many solutions. Create a MultiPlanStage to pick the best, update the cache,
// and so on. The working set will be shared by all candidate plans.
MultiPlanStage* multiPlanStage = new MultiPlanStage(opCtx, collection, canonicalQuery);
for (size_t ix = 0; ix < solutions.size(); ++ix) {
if (solutions[ix]->cacheData.get()) {
solutions[ix]->cacheData->indexFilterApplied = plannerParams.indexFiltersApplied;
}
// version of StageBuild::build when WorkingSet is shared
PlanStage* nextPlanRoot;
verify(StageBuilder::build(
opCtx, collection, *canonicalQuery, *solutions[ix], ws, &nextPlanRoot));
// Owns none of the arguments
multiPlanStage->addPlan(solutions[ix], nextPlanRoot, ws);
}
*rootOut = multiPlanStage;
return Status::OK();
}
}
} // namespace
StatusWith<unique_ptr<PlanExecutor>> getExecutor(OperationContext* txn,
Collection* collection,
unique_ptr<CanonicalQuery> canonicalQuery,
PlanExecutor::YieldPolicy yieldPolicy,
size_t plannerOptions) {
unique_ptr<WorkingSet> ws = make_unique<WorkingSet>();
PlanStage* rawRoot;
QuerySolution* rawQuerySolution;
Status status = prepareExecution(txn,
collection,
ws.get(),
canonicalQuery.get(),
plannerOptions,
&rawRoot,
&rawQuerySolution);
if (!status.isOK()) {
return status;
}
invariant(rawRoot);
unique_ptr<PlanStage> root(rawRoot);
unique_ptr<QuerySolution> querySolution(rawQuerySolution);
// We must have a tree of stages in order to have a valid plan executor, but the query
// solution may be null.
return PlanExecutor::make(txn,
std::move(ws),
std::move(root),
std::move(querySolution),
std::move(canonicalQuery),
collection,
yieldPolicy);
}
//
// Find
//
namespace {
/**
* Returns true if 'me' is a GTE or GE predicate over the "ts" field.
* Such predicates can be used for the oplog start hack.
*/
bool isOplogTsPred(const mongo::MatchExpression* me) {
if (mongo::MatchExpression::GT != me->matchType() &&
mongo::MatchExpression::GTE != me->matchType()) {
return false;
}
return mongoutils::str::equals(me->path().rawData(), "ts");
}
mongo::BSONElement extractOplogTsOptime(const mongo::MatchExpression* me) {
invariant(isOplogTsPred(me));
return static_cast<const mongo::ComparisonMatchExpression*>(me)->getData();
}
StatusWith<unique_ptr<PlanExecutor>> getOplogStartHack(OperationContext* txn,
Collection* collection,
unique_ptr<CanonicalQuery> cq) {
invariant(collection);
invariant(cq.get());
if (!collection->isCapped()) {
return Status(ErrorCodes::BadValue,
"OplogReplay cursor requested on non-capped collection");
}
// A query can only do oplog start finding if it has a top-level $gt or $gte predicate over
// the "ts" field (the operation's timestamp). Find that predicate and pass it to
// the OplogStart stage.
MatchExpression* tsExpr = NULL;
if (MatchExpression::AND == cq->root()->matchType()) {
// The query has an AND at the top-level. See if any of the children
// of the AND are $gt or $gte predicates over 'ts'.
for (size_t i = 0; i < cq->root()->numChildren(); ++i) {
MatchExpression* me = cq->root()->getChild(i);
if (isOplogTsPred(me)) {
tsExpr = me;
break;
}
}
} else if (isOplogTsPred(cq->root())) {
// The root of the tree is a $gt or $gte predicate over 'ts'.
tsExpr = cq->root();
}
if (NULL == tsExpr) {
return Status(ErrorCodes::OplogOperationUnsupported,
"OplogReplay query does not contain top-level "
"$gt or $gte over the 'ts' field.");
}
boost::optional<RecordId> startLoc = boost::none;
// See if the RecordStore supports the oplogStartHack
const BSONElement tsElem = extractOplogTsOptime(tsExpr);
if (tsElem.type() == bsonTimestamp) {
StatusWith<RecordId> goal = oploghack::keyForOptime(tsElem.timestamp());
if (goal.isOK()) {
startLoc = collection->getRecordStore()->oplogStartHack(txn, goal.getValue());
}
}
if (startLoc) {
LOG(3) << "Using direct oplog seek";
} else {
LOG(3) << "Using OplogStart stage";
// Fallback to trying the OplogStart stage.
unique_ptr<WorkingSet> oplogws = make_unique<WorkingSet>();
unique_ptr<OplogStart> stage =
make_unique<OplogStart>(txn, collection, tsExpr, oplogws.get());
// Takes ownership of oplogws and stage.
auto statusWithPlanExecutor = PlanExecutor::make(
txn, std::move(oplogws), std::move(stage), collection, PlanExecutor::YIELD_AUTO);
invariant(statusWithPlanExecutor.isOK());
unique_ptr<PlanExecutor> exec = std::move(statusWithPlanExecutor.getValue());
// The stage returns a RecordId of where to start.
startLoc = RecordId();
PlanExecutor::ExecState state = exec->getNext(NULL, startLoc.get_ptr());
// This is normal. The start of the oplog is the beginning of the collection.
if (PlanExecutor::IS_EOF == state) {
return getExecutor(txn, collection, std::move(cq), PlanExecutor::YIELD_AUTO);
}
// This is not normal. An error was encountered.
if (PlanExecutor::ADVANCED != state) {
return Status(ErrorCodes::InternalError, "quick oplog start location had error...?");
}
}
// Build our collection scan...
CollectionScanParams params;
params.collection = collection;
params.start = *startLoc;
params.direction = CollectionScanParams::FORWARD;
params.tailable = cq->getParsed().isTailable();
unique_ptr<WorkingSet> ws = make_unique<WorkingSet>();
unique_ptr<CollectionScan> cs = make_unique<CollectionScan>(txn, params, ws.get(), cq->root());
// Takes ownership of 'ws', 'cs', and 'cq'.
return PlanExecutor::make(
txn, std::move(ws), std::move(cs), std::move(cq), collection, PlanExecutor::YIELD_AUTO);
}
} // namespace
StatusWith<unique_ptr<PlanExecutor>> getExecutorFind(OperationContext* txn,
Collection* collection,
const NamespaceString& nss,
unique_ptr<CanonicalQuery> canonicalQuery,
PlanExecutor::YieldPolicy yieldPolicy) {
if (NULL != collection && canonicalQuery->getParsed().isOplogReplay()) {
return getOplogStartHack(txn, collection, std::move(canonicalQuery));
}
size_t options = QueryPlannerParams::DEFAULT;
if (ShardingState::get(txn)->needCollectionMetadata(txn, nss.ns())) {
options |= QueryPlannerParams::INCLUDE_SHARD_FILTER;
}
return getExecutor(
txn, collection, std::move(canonicalQuery), PlanExecutor::YIELD_AUTO, options);
}
namespace {
/**
* Wrap the specified 'root' plan stage in a ProjectionStage. Does not take ownership of any
* arguments other than root.
*
* If the projection was valid, then return Status::OK() with a pointer to the newly created
* ProjectionStage. Otherwise, return a status indicating the error reason.
*/
StatusWith<unique_ptr<PlanStage>> applyProjection(OperationContext* txn,
const NamespaceString& nsString,
CanonicalQuery* cq,
const BSONObj& proj,
bool allowPositional,
WorkingSet* ws,
unique_ptr<PlanStage> root) {
invariant(!proj.isEmpty());
ParsedProjection* rawParsedProj;
Status ppStatus = ParsedProjection::make(
proj.getOwned(), cq->root(), &rawParsedProj, ExtensionsCallbackDisallowExtensions());
if (!ppStatus.isOK()) {
return ppStatus;
}
unique_ptr<ParsedProjection> pp(rawParsedProj);
// ProjectionExec requires the MatchDetails from the query expression when the projection
// uses the positional operator. Since the query may no longer match the newly-updated
// document, we forbid this case.
if (!allowPositional && pp->requiresMatchDetails()) {
return {ErrorCodes::BadValue,
"cannot use a positional projection and return the new document"};
}
// $meta sortKey is not allowed to be projected in findAndModify commands.
if (pp->wantSortKey()) {
return {ErrorCodes::BadValue,
"Cannot use a $meta sortKey projection in findAndModify commands."};
}
ProjectionStageParams params(ExtensionsCallbackReal(txn, &nsString));
params.projObj = proj;
params.fullExpression = cq->root();
return {make_unique<ProjectionStage>(txn, params, ws, root.release())};
}
} // namespace
//
// Delete
//
StatusWith<unique_ptr<PlanExecutor>> getExecutorDelete(OperationContext* txn,
Collection* collection,
ParsedDelete* parsedDelete) {
const DeleteRequest* request = parsedDelete->getRequest();
const NamespaceString& nss(request->getNamespaceString());
if (!request->isGod()) {
if (nss.isSystem()) {
uassert(
12050, "cannot delete from system namespace", legalClientSystemNS(nss.ns(), true));
}
if (nss.ns().find('$') != string::npos) {
log() << "cannot delete from collection with reserved $ in name: " << nss;
uasserted(10100, "cannot delete from collection with reserved $ in name");
}
}
if (collection && collection->isCapped()) {
return Status(ErrorCodes::IllegalOperation,
str::stream() << "cannot remove from a capped collection: " << nss.ns());
}
bool userInitiatedWritesAndNotPrimary = txn->writesAreReplicated() &&
!repl::getGlobalReplicationCoordinator()->canAcceptWritesFor(nss);
if (userInitiatedWritesAndNotPrimary) {
return Status(ErrorCodes::NotMaster,
str::stream() << "Not primary while removing from " << nss.ns());
}
DeleteStageParams deleteStageParams;
deleteStageParams.isMulti = request->isMulti();
deleteStageParams.fromMigrate = request->isFromMigrate();
deleteStageParams.isExplain = request->isExplain();
deleteStageParams.returnDeleted = request->shouldReturnDeleted();
deleteStageParams.sort = request->getSort();
unique_ptr<WorkingSet> ws = make_unique<WorkingSet>();
PlanExecutor::YieldPolicy policy =
parsedDelete->canYield() ? PlanExecutor::YIELD_AUTO : PlanExecutor::YIELD_MANUAL;
if (!parsedDelete->hasParsedQuery()) {
// This is the idhack fast-path for getting a PlanExecutor without doing the work
// to create a CanonicalQuery.
const BSONObj& unparsedQuery = request->getQuery();
if (!collection) {
// Treat collections that do not exist as empty collections. Note that the explain
// reporting machinery always assumes that the root stage for a delete operation is
// a DeleteStage, so in this case we put a DeleteStage on top of an EOFStage.
LOG(2) << "Collection " << nss.ns() << " does not exist."
<< " Using EOF stage: " << unparsedQuery.toString();
auto deleteStage = make_unique<DeleteStage>(
txn, deleteStageParams, ws.get(), nullptr, new EOFStage(txn));
return PlanExecutor::make(txn, std::move(ws), std::move(deleteStage), nss.ns(), policy);
}
const IndexDescriptor* descriptor = collection->getIndexCatalog()->findIdIndex(txn);
if (descriptor && CanonicalQuery::isSimpleIdQuery(unparsedQuery) &&
request->getProj().isEmpty()) {
LOG(2) << "Using idhack: " << unparsedQuery.toString();
PlanStage* idHackStage =
new IDHackStage(txn, collection, unparsedQuery["_id"].wrap(), ws.get(), descriptor);
unique_ptr<DeleteStage> root =
make_unique<DeleteStage>(txn, deleteStageParams, ws.get(), collection, idHackStage);
return PlanExecutor::make(txn, std::move(ws), std::move(root), collection, policy);
}
// If we're here then we don't have a parsed query, but we're also not eligible for
// the idhack fast path. We need to force canonicalization now.
Status cqStatus = parsedDelete->parseQueryToCQ();
if (!cqStatus.isOK()) {
return cqStatus;
}
}
// This is the regular path for when we have a CanonicalQuery.
unique_ptr<CanonicalQuery> cq(parsedDelete->releaseParsedQuery());
PlanStage* rawRoot;
QuerySolution* rawQuerySolution;
const size_t defaultPlannerOptions = 0;
Status status = prepareExecution(
txn, collection, ws.get(), cq.get(), defaultPlannerOptions, &rawRoot, &rawQuerySolution);
if (!status.isOK()) {
return status;
}
invariant(rawRoot);
unique_ptr<QuerySolution> querySolution(rawQuerySolution);
deleteStageParams.canonicalQuery = cq.get();
rawRoot = new DeleteStage(txn, deleteStageParams, ws.get(), collection, rawRoot);
unique_ptr<PlanStage> root(rawRoot);
if (!request->getProj().isEmpty()) {
invariant(request->shouldReturnDeleted());
const bool allowPositional = true;
StatusWith<unique_ptr<PlanStage>> projStatus = applyProjection(
txn, nss, cq.get(), request->getProj(), allowPositional, ws.get(), std::move(root));
if (!projStatus.isOK()) {
return projStatus.getStatus();
}
root = std::move(projStatus.getValue());
}
// We must have a tree of stages in order to have a valid plan executor, but the query
// solution may be null.
return PlanExecutor::make(txn,
std::move(ws),
std::move(root),
std::move(querySolution),
std::move(cq),
collection,
policy);
}
//
// Update
//
namespace {
// TODO: Make this a function on NamespaceString, or make it cleaner.
inline void validateUpdate(const char* ns, const BSONObj& updateobj, const BSONObj& patternOrig) {
uassert(10155, "cannot update reserved $ collection", strchr(ns, '$') == 0);
if (strstr(ns, ".system.")) {
/* dm: it's very important that system.indexes is never updated as IndexDetails
has pointers into it */
uassert(10156,
str::stream() << "cannot update system collection: " << ns << " q: " << patternOrig
<< " u: " << updateobj,
legalClientSystemNS(ns, true));
}
}
} // namespace
StatusWith<unique_ptr<PlanExecutor>> getExecutorUpdate(OperationContext* txn,
Collection* collection,
ParsedUpdate* parsedUpdate,
OpDebug* opDebug) {
const UpdateRequest* request = parsedUpdate->getRequest();
UpdateDriver* driver = parsedUpdate->getDriver();
const NamespaceString& nsString = request->getNamespaceString();
UpdateLifecycle* lifecycle = request->getLifecycle();
validateUpdate(nsString.ns().c_str(), request->getUpdates(), request->getQuery());
// If there is no collection and this is an upsert, callers are supposed to create
// the collection prior to calling this method. Explain, however, will never do
// collection or database creation.
if (!collection && request->isUpsert()) {
invariant(request->isExplain());
}
// TODO: This seems a bit circuitious.
opDebug->updateobj = request->getUpdates();
// If this is a user-issued update, then we want to return an error: you cannot perform
// writes on a secondary. If this is an update to a secondary from the replication system,
// however, then we make an exception and let the write proceed.
bool userInitiatedWritesAndNotPrimary = txn->writesAreReplicated() &&
!repl::getGlobalReplicationCoordinator()->canAcceptWritesFor(nsString);
if (userInitiatedWritesAndNotPrimary) {
return Status(ErrorCodes::NotMaster,
str::stream() << "Not primary while performing update on " << nsString.ns());
}
if (lifecycle) {
lifecycle->setCollection(collection);
driver->refreshIndexKeys(lifecycle->getIndexKeys(txn));
}
PlanExecutor::YieldPolicy policy =
parsedUpdate->canYield() ? PlanExecutor::YIELD_AUTO : PlanExecutor::YIELD_MANUAL;
unique_ptr<WorkingSet> ws = make_unique<WorkingSet>();
UpdateStageParams updateStageParams(request, driver, opDebug);
if (!parsedUpdate->hasParsedQuery()) {
// This is the idhack fast-path for getting a PlanExecutor without doing the work
// to create a CanonicalQuery.
const BSONObj& unparsedQuery = request->getQuery();
if (!collection) {
// Treat collections that do not exist as empty collections. Note that the explain
// reporting machinery always assumes that the root stage for an update operation is
// an UpdateStage, so in this case we put an UpdateStage on top of an EOFStage.
LOG(2) << "Collection " << nsString.ns() << " does not exist."
<< " Using EOF stage: " << unparsedQuery.toString();
auto updateStage = make_unique<UpdateStage>(
txn, updateStageParams, ws.get(), collection, new EOFStage(txn));
return PlanExecutor::make(
txn, std::move(ws), std::move(updateStage), nsString.ns(), policy);
}
const IndexDescriptor* descriptor = collection->getIndexCatalog()->findIdIndex(txn);
if (descriptor && CanonicalQuery::isSimpleIdQuery(unparsedQuery) &&
request->getProj().isEmpty()) {
LOG(2) << "Using idhack: " << unparsedQuery.toString();
PlanStage* idHackStage =
new IDHackStage(txn, collection, unparsedQuery["_id"].wrap(), ws.get(), descriptor);
unique_ptr<UpdateStage> root =
make_unique<UpdateStage>(txn, updateStageParams, ws.get(), collection, idHackStage);
return PlanExecutor::make(txn, std::move(ws), std::move(root), collection, policy);
}
// If we're here then we don't have a parsed query, but we're also not eligible for
// the idhack fast path. We need to force canonicalization now.
Status cqStatus = parsedUpdate->parseQueryToCQ();
if (!cqStatus.isOK()) {
return cqStatus;
}
}
// This is the regular path for when we have a CanonicalQuery.
unique_ptr<CanonicalQuery> cq(parsedUpdate->releaseParsedQuery());
PlanStage* rawRoot;
QuerySolution* rawQuerySolution;
const size_t defaultPlannerOptions = 0;
Status status = prepareExecution(
txn, collection, ws.get(), cq.get(), defaultPlannerOptions, &rawRoot, &rawQuerySolution);
if (!status.isOK()) {
return status;
}
invariant(rawRoot);
unique_ptr<QuerySolution> querySolution(rawQuerySolution);
updateStageParams.canonicalQuery = cq.get();
rawRoot = new UpdateStage(txn, updateStageParams, ws.get(), collection, rawRoot);
unique_ptr<PlanStage> root(rawRoot);
if (!request->getProj().isEmpty()) {
invariant(request->shouldReturnAnyDocs());
// If the plan stage is to return the newly-updated version of the documents, then it
// is invalid to use a positional projection because the query expression need not
// match the array element after the update has been applied.
const bool allowPositional = request->shouldReturnOldDocs();
StatusWith<unique_ptr<PlanStage>> projStatus = applyProjection(txn,
nsString,
cq.get(),
request->getProj(),
allowPositional,
ws.get(),
std::move(root));
if (!projStatus.isOK()) {
return projStatus.getStatus();
}
root = std::move(projStatus.getValue());
}
// We must have a tree of stages in order to have a valid plan executor, but the query
// solution may be null. Takes ownership of all args other than 'collection' and 'txn'
return PlanExecutor::make(txn,
std::move(ws),
std::move(root),
std::move(querySolution),
std::move(cq),
collection,
policy);
}
//
// Group
//
StatusWith<unique_ptr<PlanExecutor>> getExecutorGroup(OperationContext* txn,
Collection* collection,
const GroupRequest& request,
PlanExecutor::YieldPolicy yieldPolicy) {
if (!globalScriptEngine) {
return Status(ErrorCodes::BadValue, "server-side JavaScript execution is disabled");
}
unique_ptr<WorkingSet> ws = make_unique<WorkingSet>();
if (!collection) {
// Treat collections that do not exist as empty collections. Note that the explain
// reporting machinery always assumes that the root stage for a group operation is a
// GroupStage, so in this case we put a GroupStage on top of an EOFStage.
unique_ptr<PlanStage> root =
make_unique<GroupStage>(txn, request, ws.get(), new EOFStage(txn));
return PlanExecutor::make(txn, std::move(ws), std::move(root), request.ns, yieldPolicy);
}
const NamespaceString nss(request.ns);
const ExtensionsCallbackReal extensionsCallback(txn, &nss);
auto statusWithCQ =
CanonicalQuery::canonicalize(nss, request.query, request.explain, extensionsCallback);
if (!statusWithCQ.isOK()) {
return statusWithCQ.getStatus();
}
unique_ptr<CanonicalQuery> canonicalQuery = std::move(statusWithCQ.getValue());
const size_t defaultPlannerOptions = 0;
PlanStage* child;
QuerySolution* rawQuerySolution;
Status status = prepareExecution(txn,
collection,
ws.get(),
canonicalQuery.get(),
defaultPlannerOptions,
&child,
&rawQuerySolution);
if (!status.isOK()) {
return status;
}
invariant(child);
unique_ptr<PlanStage> root = make_unique<GroupStage>(txn, request, ws.get(), child);
unique_ptr<QuerySolution> querySolution(rawQuerySolution);
// We must have a tree of stages in order to have a valid plan executor, but the query
// solution may be null. Takes ownership of all args other than 'collection'.
return PlanExecutor::make(txn,
std::move(ws),
std::move(root),
std::move(querySolution),
std::move(canonicalQuery),
collection,
yieldPolicy);
}
//
// Count hack
//
namespace {
/**
* Returns 'true' if the provided solution 'soln' can be rewritten to use
* a fast counting stage. Mutates the tree in 'soln->root'.
*
* Otherwise, returns 'false'.
*/
bool turnIxscanIntoCount(QuerySolution* soln) {
QuerySolutionNode* root = soln->root.get();
// Root should be a fetch w/o any filters.
if (STAGE_FETCH != root->getType()) {
return false;
}
if (NULL != root->filter.get()) {
return false;
}
// Child should be an ixscan.
if (STAGE_IXSCAN != root->children[0]->getType()) {
return false;
}