/
queryoptimizer.cpp
2040 lines (1802 loc) · 77.1 KB
/
queryoptimizer.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
// @file queryoptimizer.cpp
/**
* Copyright (C) 2008 10gen 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/>.
*/
#include "mongo/pch.h"
#include "mongo/db/queryoptimizer.h"
#include "mongo/client/dbclientinterface.h"
#include "mongo/db/btreecursor.h"
#include "mongo/db/cmdline.h"
#include "mongo/db/db.h"
#include "mongo/db/intervalbtreecursor.h"
#include "mongo/db/pagefault.h"
#include "mongo/server.h"
//#define DEBUGQO(x) cout << x << endl;
#define DEBUGQO(x)
namespace mongo {
QueryPlanSummary QueryPlan::summary() const { return QueryPlanSummary( *this ); }
double elementDirection( const BSONElement &e ) {
if ( e.isNumber() )
return e.number();
return 1;
}
// returns an IndexDetails * for a hint, 0 if hint is $natural.
// hint must not be eoo()
IndexDetails *parseHint( const BSONElement &hint, NamespaceDetails *d ) {
massert( 13292, "hint eoo", !hint.eoo() );
if( hint.type() == String ) {
string hintstr = hint.valuestr();
NamespaceDetails::IndexIterator i = d->ii();
while( i.more() ) {
IndexDetails& ii = i.next();
if ( ii.indexName() == hintstr ) {
return ⅈ
}
}
}
else if( hint.type() == Object ) {
BSONObj hintobj = hint.embeddedObject();
uassert( 10112 , "bad hint", !hintobj.isEmpty() );
if ( !strcmp( hintobj.firstElementFieldName(), "$natural" ) ) {
return 0;
}
NamespaceDetails::IndexIterator i = d->ii();
while( i.more() ) {
IndexDetails& ii = i.next();
if( ii.keyPattern().woCompare(hintobj) == 0 ) {
return ⅈ
}
}
}
uassert( 10113 , "bad hint", false );
return 0;
}
QueryPlan *QueryPlan::make( NamespaceDetails *d,
int idxNo,
const FieldRangeSetPair &frsp,
const FieldRangeSetPair *originalFrsp,
const BSONObj &originalQuery,
const BSONObj &order,
const shared_ptr<const ParsedQuery> &parsedQuery,
const BSONObj &startKey,
const BSONObj &endKey,
const std::string& special ) {
auto_ptr<QueryPlan> ret( new QueryPlan( d, idxNo, frsp, originalQuery, order, parsedQuery,
special ) );
ret->init( originalFrsp, startKey, endKey );
return ret.release();
}
QueryPlan::QueryPlan( NamespaceDetails *d,
int idxNo,
const FieldRangeSetPair &frsp,
const BSONObj &originalQuery,
const BSONObj &order,
const shared_ptr<const ParsedQuery> &parsedQuery,
const std::string& special ) :
_d(d),
_idxNo(idxNo),
_frs( frsp.frsForIndex( _d, _idxNo ) ),
_frsMulti( frsp.frsForIndex( _d, -1 ) ),
_originalQuery( originalQuery ),
_order( order ),
_parsedQuery( parsedQuery ),
_index( 0 ),
_scanAndOrderRequired( true ),
_matcherNecessary( true ),
_direction( 0 ),
_endKeyInclusive(),
_utility( Helpful ),
_special( special ),
_type(0),
_startOrEndSpec() {
}
void QueryPlan::init( const FieldRangeSetPair *originalFrsp,
const BSONObj &startKey,
const BSONObj &endKey ) {
_endKeyInclusive = endKey.isEmpty();
_startOrEndSpec = !startKey.isEmpty() || !endKey.isEmpty();
BSONObj idxKey = _idxNo < 0 ? BSONObj() : _d->idx( _idxNo ).keyPattern();
if ( !_frs.matchPossibleForIndex( idxKey ) ) {
_utility = Impossible;
_scanAndOrderRequired = false;
return;
}
if ( willScanTable() ) {
if ( _order.isEmpty() || !strcmp( _order.firstElementFieldName(), "$natural" ) )
_scanAndOrderRequired = false;
return;
}
_index = &_d->idx(_idxNo);
// If the parsing or index indicates this is a special query, don't continue the processing
if ( _special.size() ||
( _index->getSpec().getType() &&
_index->getSpec().getType()->suitability( _originalQuery, _order ) != USELESS ) ) {
_type = _index->getSpec().getType();
if( !_special.size() ) _special = _index->getSpec().getType()->getPlugin()->getName();
massert( 13040 , (string)"no type for special: " + _special , _type );
// hopefully safe to use original query in these contexts;
// don't think we can mix special with $or clause separation yet
_scanAndOrderRequired = _type->scanAndOrderRequired( _originalQuery , _order );
return;
}
const IndexSpec &idxSpec = _index->getSpec();
BSONObjIterator o( _order );
BSONObjIterator k( idxKey );
if ( !o.moreWithEOO() )
_scanAndOrderRequired = false;
while( o.moreWithEOO() ) {
BSONElement oe = o.next();
if ( oe.eoo() ) {
_scanAndOrderRequired = false;
break;
}
if ( !k.moreWithEOO() )
break;
BSONElement ke;
while( 1 ) {
ke = k.next();
if ( ke.eoo() )
goto doneCheckOrder;
if ( strcmp( oe.fieldName(), ke.fieldName() ) == 0 )
break;
if ( !_frs.range( ke.fieldName() ).equality() )
goto doneCheckOrder;
}
int d = elementDirection( oe ) == elementDirection( ke ) ? 1 : -1;
if ( _direction == 0 )
_direction = d;
else if ( _direction != d )
break;
}
doneCheckOrder:
if ( _scanAndOrderRequired )
_direction = 0;
BSONObjIterator i( idxKey );
int exactIndexedQueryCount = 0;
int optimalIndexedQueryCount = 0;
bool awaitingLastOptimalField = true;
set<string> orderFieldsUnindexed;
_order.getFieldNames( orderFieldsUnindexed );
while( i.moreWithEOO() ) {
BSONElement e = i.next();
if ( e.eoo() )
break;
const FieldRange &fr = _frs.range( e.fieldName() );
if ( awaitingLastOptimalField ) {
if ( !fr.universal() )
++optimalIndexedQueryCount;
if ( !fr.equality() )
awaitingLastOptimalField = false;
}
else {
if ( !fr.universal() )
optimalIndexedQueryCount = -1;
}
if ( fr.equality() ) {
BSONElement e = fr.max();
if ( !e.isNumber() && !e.mayEncapsulate() && e.type() != RegEx )
++exactIndexedQueryCount;
}
orderFieldsUnindexed.erase( e.fieldName() );
}
if ( !_scanAndOrderRequired &&
( optimalIndexedQueryCount == _frs.numNonUniversalRanges() ) )
_utility = Optimal;
_frv.reset( new FieldRangeVector( _frs, idxSpec, _direction ) );
if ( // If all field range constraints are on indexed fields and ...
_utility == Optimal &&
// ... the field ranges exactly represent the query and ...
_frs.mustBeExactMatchRepresentation() &&
// ... all indexed ranges are represented in the field range vector ...
_frv->hasAllIndexedRanges() ) {
// ... then the field range vector is sufficient to perform query matching against index
// keys. No matcher is required.
_matcherNecessary = false;
}
if ( originalFrsp ) {
_originalFrv.reset( new FieldRangeVector( originalFrsp->frsForIndex( _d, _idxNo ),
idxSpec, _direction ) );
}
else {
_originalFrv = _frv;
}
if ( _startOrEndSpec ) {
BSONObj newStart, newEnd;
if ( !startKey.isEmpty() )
_startKey = startKey;
else
_startKey = _frv->startKey();
if ( !endKey.isEmpty() )
_endKey = endKey;
else
_endKey = _frv->endKey();
}
if ( ( _scanAndOrderRequired || _order.isEmpty() ) &&
_frs.range( idxKey.firstElementFieldName() ).universal() ) { // NOTE SERVER-2140
_utility = Unhelpful;
}
if ( idxSpec.isSparse() && hasPossibleExistsFalsePredicate() ) {
_utility = Disallowed;
}
if ( _parsedQuery && _parsedQuery->getFields() && !_d->isMultikey( _idxNo ) ) { // Does not check modifiedKeys()
_keyFieldsOnly.reset( _parsedQuery->getFields()->checkKey( _index->keyPattern() ) );
}
}
shared_ptr<Cursor> QueryPlan::newCursor( const DiskLoc& startLoc,
bool requestIntervalCursor ) const {
if ( _type ) {
// hopefully safe to use original query in these contexts - don't think we can mix type with $or clause separation yet
int numWanted = 0;
if ( _parsedQuery ) {
// SERVER-5390
numWanted = _parsedQuery->getSkip() + _parsedQuery->getNumToReturn();
}
return _type->newCursor( _originalQuery , _order , numWanted );
}
if ( _utility == Impossible ) {
// Dummy table scan cursor returning no results. Allowed in --notablescan mode.
return shared_ptr<Cursor>( new BasicCursor( DiskLoc() ) );
}
if ( willScanTable() ) {
checkTableScanAllowed();
return findTableScan( _frs.ns(), _order, startLoc );
}
massert( 10363 , "newCursor() with start location not implemented for indexed plans", startLoc.isNull() );
if ( _startOrEndSpec ) {
// we are sure to spec _endKeyInclusive
return shared_ptr<Cursor>( BtreeCursor::make( _d,
*_index,
_startKey,
_endKey,
_endKeyInclusive,
_direction >= 0 ? 1 : -1 ) );
}
if ( _index->getSpec().getType() ) {
return shared_ptr<Cursor>( BtreeCursor::make( _d,
*_index,
_frv->startKey(),
_frv->endKey(),
true,
_direction >= 0 ? 1 : -1 ) );
}
// An IntervalBtreeCursor is returned if explicitly requested AND _frv is exactly
// represented by a single interval within the btree.
if ( // If an interval cursor is requested and ...
requestIntervalCursor &&
// ... equalities come before ranges (a requirement of Optimal) and ...
_utility == Optimal &&
// ... the field range vector exactly represents a single interval ...
_frv->isSingleInterval() ) {
// ... and an interval cursor can be created ...
shared_ptr<Cursor> ret( IntervalBtreeCursor::make( _d,
*_index,
_frv->startKey(),
_frv->startKeyInclusive(),
_frv->endKey(),
_frv->endKeyInclusive() ) );
if ( ret ) {
// ... then return the interval cursor.
return ret;
}
}
return shared_ptr<Cursor>( BtreeCursor::make( _d,
*_index,
_frv,
independentRangesSingleIntervalLimit(),
_direction >= 0 ? 1 : -1 ) );
}
shared_ptr<Cursor> QueryPlan::newReverseCursor() const {
if ( willScanTable() ) {
int orderSpec = _order.getIntField( "$natural" );
if ( orderSpec == INT_MIN )
orderSpec = 1;
return findTableScan( _frs.ns(), BSON( "$natural" << -orderSpec ) );
}
massert( 10364 , "newReverseCursor() not implemented for indexed plans", false );
return shared_ptr<Cursor>();
}
BSONObj QueryPlan::indexKey() const {
if ( !_index )
return BSON( "$natural" << 1 );
return _index->keyPattern();
}
void QueryPlan::registerSelf( long long nScanned,
CandidatePlanCharacter candidatePlans ) const {
// Impossible query constraints can be detected before scanning and historically could not
// generate a QueryPattern.
if ( _utility == Impossible ) {
return;
}
SimpleMutex::scoped_lock lk(NamespaceDetailsTransient::_qcMutex);
QueryPattern queryPattern = _frs.pattern( _order );
CachedQueryPlan queryPlanToCache( indexKey(), nScanned, candidatePlans );
NamespaceDetailsTransient &nsdt = NamespaceDetailsTransient::get_inlock( ns() );
nsdt.registerCachedQueryPlanForPattern( queryPattern, queryPlanToCache );
}
void QueryPlan::checkTableScanAllowed() const {
if ( likely( !cmdLine.noTableScan ) )
return;
// TODO - is this desirable? See SERVER-2222.
if ( _frs.numNonUniversalRanges() == 0 )
return;
if ( strstr( ns() , ".system." ) )
return;
if( str::startsWith(ns(), "local.") )
return;
if ( ! nsdetails( ns() ) )
return;
uassert( 10111 , (string)"table scans not allowed:" + ns() , ! cmdLine.noTableScan );
}
int QueryPlan::independentRangesSingleIntervalLimit() const {
if ( _scanAndOrderRequired &&
_parsedQuery &&
!_parsedQuery->wantMore() &&
!isMultiKey() &&
queryBoundsExactOrderSuffix() ) {
verify( _direction == 0 );
// Limit the results for each compound interval. SERVER-5063
return _parsedQuery->getSkip() + _parsedQuery->getNumToReturn();
}
return 0;
}
/**
* Detects $exists:false predicates in a matcher. All $exists:false predicates will be
* detected. Some $exists:true predicates may be incorrectly reported as $exists:false due to
* the approximate nature of the implementation.
*/
class ExistsFalseDetector : public MatcherVisitor {
public:
ExistsFalseDetector( const Matcher& originalMatcher );
bool hasFoundExistsFalse() const { return _foundExistsFalse; }
void visitMatcher( const Matcher& matcher ) { _currentMatcher = &matcher; }
void visitElementMatcher( const ElementMatcher& elementMatcher );
private:
const Matcher* _originalMatcher;
const Matcher* _currentMatcher;
bool _foundExistsFalse;
};
ExistsFalseDetector::ExistsFalseDetector( const Matcher& originalMatcher ) :
_originalMatcher( &originalMatcher ),
_currentMatcher( 0 ),
_foundExistsFalse() {
}
/** Matches $exists:false and $not:{$exists:true} exactly. */
static bool isExistsFalsePredicate( const ElementMatcher& elementMatcher ) {
bool hasTrueValue = elementMatcher._toMatch.trueValue();
bool hasNotModifier = elementMatcher._isNot;
return hasNotModifier ? hasTrueValue : !hasTrueValue;
}
void ExistsFalseDetector::visitElementMatcher( const ElementMatcher& elementMatcher ) {
if ( elementMatcher._compareOp != BSONObj::opEXISTS ) {
// Only consider $exists predicates.
return;
}
if ( _currentMatcher != _originalMatcher ) {
// Treat all $exists predicates nested below the original matcher as $exists:false.
// This approximation is used because a nesting operator may change the matching
// semantics of $exists:true.
_foundExistsFalse = true;
return;
}
if ( isExistsFalsePredicate( elementMatcher ) ) {
// Top level $exists operators are matched exactly.
_foundExistsFalse = true;
}
}
bool QueryPlan::hasPossibleExistsFalsePredicate() const {
ExistsFalseDetector detector( matcher()->docMatcher() );
matcher()->docMatcher().visit( detector );
return detector.hasFoundExistsFalse();
}
bool QueryPlan::queryBoundsExactOrderSuffix() const {
if ( !indexed() ||
!_frs.matchPossible() ||
!_frs.mustBeExactMatchRepresentation() ) {
return false;
}
BSONObj idxKey = indexKey();
BSONObjIterator index( idxKey );
BSONObjIterator order( _order );
int coveredNonUniversalRanges = 0;
while( index.more() ) {
const FieldRange& indexFieldRange = _frs.range( (*index).fieldName() );
if ( !indexFieldRange.isPointIntervalSet() ) {
if ( !indexFieldRange.universal() ) {
// The last indexed range may be a non point set containing a single interval.
// SERVER-5777
if ( indexFieldRange.intervals().size() > 1 ) {
return false;
}
++coveredNonUniversalRanges;
}
break;
}
++coveredNonUniversalRanges;
if ( order.more() && str::equals( (*index).fieldName(), (*order).fieldName() ) ) {
++order;
}
++index;
}
if ( coveredNonUniversalRanges != _frs.numNonUniversalRanges() ) {
return false;
}
while( index.more() && order.more() ) {
if ( !str::equals( (*index).fieldName(), (*order).fieldName() ) ) {
return false;
}
if ( ( elementDirection( *index ) < 0 ) != ( elementDirection( *order ) < 0 ) ) {
return false;
}
++order;
++index;
}
return !order.more();
}
string QueryPlan::toString() const {
return BSON(
"index" << indexKey() <<
"frv" << ( _frv ? _frv->toString() : "" ) <<
"order" << _order
).jsonString();
}
shared_ptr<CoveredIndexMatcher> QueryPlan::matcher() const {
if ( !_matcher ) {
_matcher.reset( new CoveredIndexMatcher( originalQuery(), indexKey() ) );
}
return _matcher;
}
bool QueryPlan::isMultiKey() const {
if ( _idxNo < 0 )
return false;
return _d->isMultikey( _idxNo );
}
std::ostream &operator<< ( std::ostream &out, const QueryPlan::Utility &utility ) {
out << "QueryPlan::";
switch( utility ) {
case QueryPlan::Impossible: return out << "Impossible";
case QueryPlan::Optimal: return out << "Optimal";
case QueryPlan::Helpful: return out << "Helpful";
case QueryPlan::Unhelpful: return out << "Unhelpful";
case QueryPlan::Disallowed: return out << "Disallowed";
default:
return out << "UNKNOWN(" << utility << ")";
}
}
CachedMatchCounter::CachedMatchCounter( long long& aggregateNscanned,
int cumulativeCount ) :
_aggregateNscanned( aggregateNscanned ),
_nscanned(),
_cumulativeCount( cumulativeCount ),
_count(),
_checkDups(),
_match( Unknown ),
_counted() {
}
void CachedMatchCounter::resetMatch() {
_match = Unknown;
_counted = false;
}
bool CachedMatchCounter::setMatch( bool match ) {
MatchState oldMatch = _match;
_match = match ? True : False;
return _match == True && oldMatch != True;
}
void CachedMatchCounter::incMatch( const DiskLoc& loc ) {
if ( !_counted && _match == True && !getsetdup( loc ) ) {
++_cumulativeCount;
++_count;
_counted = true;
}
}
bool CachedMatchCounter::wouldIncMatch( const DiskLoc& loc ) const {
return !_counted && _match == True && !getdup( loc );
}
bool CachedMatchCounter::enoughCumulativeMatchesToChooseAPlan() const {
// This is equivalent to the default condition for switching from
// a query to a getMore, which was the historical default match count for
// choosing a plan.
return _cumulativeCount >= 101;
}
bool CachedMatchCounter::enoughMatchesToRecordPlan() const {
// Recording after 50 matches is a historical default (101 default limit / 2).
return _count > 50;
}
void CachedMatchCounter::updateNscanned( long long nscanned ) {
_aggregateNscanned += ( nscanned - _nscanned );
_nscanned = nscanned;
}
bool CachedMatchCounter::getsetdup( const DiskLoc& loc ) {
if ( !_checkDups ) {
return false;
}
pair<set<DiskLoc>::iterator, bool> p = _dups.insert( loc );
return !p.second;
}
bool CachedMatchCounter::getdup( const DiskLoc& loc ) const {
if ( !_checkDups ) {
return false;
}
return _dups.find( loc ) != _dups.end();
}
QueryPlanRunner::QueryPlanRunner( long long& aggregateNscanned,
const QueryPlanSelectionPolicy& selectionPolicy,
const bool& requireOrder,
bool alwaysCountMatches,
int cumulativeCount ) :
_complete(),
_stopRequested(),
_queryPlan(),
_error(),
_matchCounter( aggregateNscanned, cumulativeCount ),
_countingMatches(),
_mustAdvance(),
_capped(),
_selectionPolicy( selectionPolicy ),
_requireOrder( requireOrder ),
_alwaysCountMatches( alwaysCountMatches ) {
}
void QueryPlanRunner::next() {
checkCursorOrdering();
mayAdvance();
if ( countMatches() && _matchCounter.enoughCumulativeMatchesToChooseAPlan() ) {
setStop();
if ( _explainPlanInfo ) _explainPlanInfo->notePicked();
return;
}
if ( !_c || !_c->ok() ) {
if ( _explainPlanInfo && _c ) _explainPlanInfo->noteDone( *_c );
setComplete();
return;
}
_mustAdvance = true;
}
long long QueryPlanRunner::nscanned() const {
return _c ? _c->nscanned() : _matchCounter.nscanned();
}
void QueryPlanRunner::prepareToYield() {
if ( _c && !_cc ) {
_cc.reset( new ClientCursor( QueryOption_NoCursorTimeout, _c, queryPlan().ns() ) );
// Set 'doing deletes' as deletes may occur; if there are no deletes this has no
// effect.
_cc->setDoingDeletes( true );
}
if ( _cc ) {
recordCursorLocation();
_cc->prepareToYield( _yieldData );
}
}
void QueryPlanRunner::recoverFromYield() {
if ( _cc && !ClientCursor::recoverFromYield( _yieldData ) ) {
// !!! The collection may be gone, and any namespace or index specific memory may
// have become invalid.
_c.reset();
_cc.reset();
if ( _capped ) {
msgassertedNoTrace( 13338,
str::stream() << "capped cursor overrun: "
<< queryPlan().ns() );
}
msgassertedNoTrace( 15892,
str::stream() <<
"QueryPlanRunner::recoverFromYield() failed to recover" );
}
else {
checkCursorAdvanced();
}
}
void QueryPlanRunner::prepareToTouchEarlierIterate() {
recordCursorLocation();
if ( _c ) {
_c->prepareToTouchEarlierIterate();
}
}
void QueryPlanRunner::recoverFromTouchingEarlierIterate() {
if ( _c ) {
_c->recoverFromTouchingEarlierIterate();
}
checkCursorAdvanced();
}
bool QueryPlanRunner::currentMatches( MatchDetails* details ) {
if ( !_c || !_c->ok() ) {
_matchCounter.setMatch( false );
return false;
}
MatchDetails myDetails;
if ( !details && _explainPlanInfo ) {
details = &myDetails;
}
bool match = queryPlan().matcher()->matchesCurrent( _c.get(), details );
// Cache the match, so we can count it in mayAdvance().
bool newMatch = _matchCounter.setMatch( match );
if ( _explainPlanInfo ) {
// Note iterate results as if this is the only query plan running. But do not account
// for query parameters that may be appled to the whole result set (results from
// interleaved plans), for example the 'skip' parameter.
bool countableMatch = newMatch && _matchCounter.wouldIncMatch( _c->currLoc() );
bool matchWouldBeLoadedForReturn = countableMatch && hasDocumentLoadingQueryPlan();
_explainPlanInfo->noteIterate( countableMatch,
details->hasLoadedRecord() ||
matchWouldBeLoadedForReturn,
*_c );
}
return match;
}
bool QueryPlanRunner::mayRecordPlan() const {
return complete() && ( !stopRequested() || _matchCounter.enoughMatchesToRecordPlan() );
}
QueryPlanRunner* QueryPlanRunner::createChild() const {
return new QueryPlanRunner( _matchCounter.aggregateNscanned(),
_selectionPolicy,
_requireOrder,
_alwaysCountMatches,
_matchCounter.cumulativeCount() );
}
void QueryPlanRunner::setQueryPlan( const QueryPlan* queryPlan ) {
_queryPlan = queryPlan;
verify( _queryPlan != NULL );
}
void QueryPlanRunner::init() {
checkCursorOrdering();
if ( !_selectionPolicy.permitPlan( queryPlan() ) ) {
throw MsgAssertionException( 9011,
str::stream()
<< "Plan not permitted by query plan selection policy '"
<< _selectionPolicy.name()
<< "'" );
}
_c = queryPlan().newCursor();
// The basic and btree cursors used by this implementation do not supply their own
// matchers, and a matcher from a query plan will be used instead.
verify( !_c->matcher() );
// Such cursors all support deduplication.
verify( _c->autoDedup() );
// The query plan must have a matcher. The matcher's constructor performs some aspects
// of query validation that should occur as part of this class's init() if not handled
// already.
fassert( 16249, queryPlan().matcher() );
// All candidate cursors must support yields for QueryOptimizerCursorImpl's
// prepareToYield() and prepareToTouchEarlierIterate() to work.
verify( _c->supportYields() );
_capped = _c->capped();
// TODO This violates the current Cursor interface abstraction, but for now it's simpler to keep our own set of
// dups rather than avoid poisoning the cursor's dup set with unreturned documents. Deduping documents
// matched in this QueryOptimizerCursorOp will run against the takeover cursor.
_matchCounter.setCheckDups( countMatches() && _c->isMultiKey() );
// TODO ok if cursor becomes multikey later?
_matchCounter.updateNscanned( _c->nscanned() );
}
void QueryPlanRunner::setException( const DBException &e ) {
_error = true;
_exception = e.getInfo();
}
shared_ptr<ExplainPlanInfo> QueryPlanRunner::generateExplainInfo() {
if ( !_c ) {
return shared_ptr<ExplainPlanInfo>( new ExplainPlanInfo() );
}
_explainPlanInfo.reset( new ExplainPlanInfo() );
_explainPlanInfo->notePlan( *_c, queryPlan().scanAndOrderRequired(),
queryPlan().keyFieldsOnly() );
return _explainPlanInfo;
}
void QueryPlanRunner::mayAdvance() {
if ( !_c ) {
return;
}
if ( countingMatches() ) {
// Check match if not yet known.
if ( !_matchCounter.knowMatch() ) {
currentMatches( 0 );
}
_matchCounter.incMatch( currLoc() );
}
if ( _mustAdvance ) {
_c->advance();
handleCursorAdvanced();
}
_matchCounter.updateNscanned( _c->nscanned() );
}
bool QueryPlanRunner::countingMatches() {
if ( _countingMatches ) {
return true;
}
if ( countMatches() ) {
// Only count matches after the first call to next(), which occurs before the first
// result is returned.
_countingMatches = true;
}
return false;
}
bool QueryPlanRunner::countMatches() const {
return _alwaysCountMatches || !queryPlan().scanAndOrderRequired();
}
bool QueryPlanRunner::hasDocumentLoadingQueryPlan() const {
if ( queryPlan().parsedQuery() && queryPlan().parsedQuery()->returnKey() ) {
// Index keys will be returned using $returnKey.
return false;
}
if ( queryPlan().scanAndOrderRequired() ) {
// The in memory sort implementation operates on full documents.
return true;
}
if ( keyFieldsOnly() ) {
// A covered index projection will be used.
return false;
}
// Documents will be loaded for a standard query.
return true;
}
void QueryPlanRunner::recordCursorLocation() {
_posBeforeYield = currLoc();
}
void QueryPlanRunner::checkCursorAdvanced() {
// This check will not correctly determine if we are looking at a different document in
// all cases, but it is adequate for updating the query plan's match count (just used to pick
// plans, not returned to the client) and adjust iteration via _mustAdvance.
if ( _posBeforeYield != currLoc() ) {
// If the yield advanced our position, the next next() will be a no op.
handleCursorAdvanced();
}
}
void QueryPlanRunner::handleCursorAdvanced() {
_mustAdvance = false;
_matchCounter.resetMatch();
}
void QueryPlanRunner::checkCursorOrdering() {
if ( _requireOrder && queryPlan().scanAndOrderRequired() ) {
throw MsgAssertionException( OutOfOrderDocumentsAssertionCode, "order spec cannot be satisfied with index" );
}
}
QueryPlanGenerator::QueryPlanGenerator( QueryPlanSet &qps,
auto_ptr<FieldRangeSetPair> originalFrsp,
const shared_ptr<const ParsedQuery> &parsedQuery,
const BSONObj &hint,
RecordedPlanPolicy recordedPlanPolicy,
const BSONObj &min,
const BSONObj &max,
bool allowSpecial ) :
_qps( qps ),
_originalFrsp( originalFrsp ),
_parsedQuery( parsedQuery ),
_hint( hint.getOwned() ),
_recordedPlanPolicy( recordedPlanPolicy ),
_min( min.getOwned() ),
_max( max.getOwned() ),
_allowSpecial( allowSpecial ) {
}
void QueryPlanGenerator::addInitialPlans() {
const char *ns = _qps.frsp().ns();
NamespaceDetails *d = nsdetails( ns );
if ( addShortCircuitPlan( d ) ) {
return;
}
addStandardPlans( d );
warnOnCappedIdTableScan();
}
void QueryPlanGenerator::addFallbackPlans() {
const char *ns = _qps.frsp().ns();
NamespaceDetails *d = nsdetails( ns );
verify( d );
vector<shared_ptr<QueryPlan> > plans;
shared_ptr<QueryPlan> optimalPlan;
shared_ptr<QueryPlan> specialPlan;
for( int i = 0; i < d->nIndexes; ++i ) {
if ( !QueryUtilIndexed::indexUseful( _qps.frsp(), d, i, _qps.order() ) ) {
continue;
}
shared_ptr<QueryPlan> p = newPlan( d, i );
switch( p->utility() ) {
case QueryPlan::Impossible:
_qps.setSinglePlan( p );
return;
case QueryPlan::Optimal:
if ( !optimalPlan ) {
optimalPlan = p;
}
break;
case QueryPlan::Helpful:
if ( p->special().empty() ) {
// Not a 'special' plan.
plans.push_back( p );
}
else if ( _allowSpecial ) {
specialPlan = p;
}
break;
default:
break;
}
}
if ( optimalPlan ) {
_qps.setSinglePlan( optimalPlan );
// Record an optimal plan in the query cache immediately, with a small nscanned value
// that will be ignored.
optimalPlan->registerSelf
( 0, CandidatePlanCharacter( !optimalPlan->scanAndOrderRequired(),
optimalPlan->scanAndOrderRequired() ) );
return;
}
// Only add a special plan if no standard btree plans have been added. SERVER-4531
if ( plans.empty() && specialPlan ) {
_qps.setSinglePlan( specialPlan );
return;
}
for( vector<shared_ptr<QueryPlan> >::const_iterator i = plans.begin(); i != plans.end();
++i ) {
_qps.addCandidatePlan( *i );
}
_qps.addCandidatePlan( newPlan( d, -1 ) );
}
bool QueryPlanGenerator::addShortCircuitPlan( NamespaceDetails *d ) {
return
// The collection is missing.
setUnindexedPlanIf( !d, d ) ||
// No match is possible.
setUnindexedPlanIf( !_qps.frsp().matchPossible(), d ) ||
// The hint, min, or max parameters are specified.
addHintPlan( d ) ||
// A special index operation is requested.
addSpecialPlan( d ) ||
// No indexable ranges or ordering are specified.
setUnindexedPlanIf( _qps.frsp().noNonUniversalRanges() && _qps.order().isEmpty(), d ) ||
// $natural sort is requested.
setUnindexedPlanIf( !_qps.order().isEmpty() &&
str::equals( _qps.order().firstElementFieldName(), "$natural" ), d );
}
bool QueryPlanGenerator::addHintPlan( NamespaceDetails *d ) {
BSONElement hint = _hint.firstElement();
if ( !hint.eoo() ) {
IndexDetails *id = parseHint( hint, d );
if ( id ) {
setHintedPlanForIndex( *id );
}
else {
uassert( 10366, "natural order cannot be specified with $min/$max",
_min.isEmpty() && _max.isEmpty() );
setSingleUnindexedPlan( d );
}
return true;
}
if ( !_min.isEmpty() || !_max.isEmpty() ) {
string errmsg;
BSONObj keyPattern;
IndexDetails *idx = indexDetailsForRange( _qps.frsp().ns(), errmsg, _min, _max,
keyPattern );
uassert( 10367 , errmsg, idx );
validateAndSetHintedPlan( newPlan( d, d->idxNo( *idx ), _min, _max ) );
return true;
}
return false;
}
bool QueryPlanGenerator::addSpecialPlan( NamespaceDetails *d ) {