summaryrefslogtreecommitdiff
path: root/src/mongo/db/exec/sort.cpp
blob: 95ce1d88cb556de1fafeca6340e1b4a85e08fbc8 (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
/**
 *    Copyright (C) 2013 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/db/exec/sort.h"

#include <algorithm>

#include "mongo/db/exec/working_set.h"
#include "mongo/db/exec/working_set_common.h"

namespace mongo {

    // Used in STL sort.
    struct WorkingSetComparison {
        WorkingSetComparison(WorkingSet* ws, BSONObj pattern) : _ws(ws), _pattern(pattern) { }

        bool operator()(const WorkingSetID& lhs, const WorkingSetID& rhs) const {
            WorkingSetMember* lhsMember = _ws->get(lhs);
            WorkingSetMember* rhsMember = _ws->get(rhs);

            BSONObjIterator it(_pattern);
            while (it.more()) {
                BSONElement patternElt = it.next();
                string fn = patternElt.fieldName();

                BSONElement lhsElt;
                verify(lhsMember->getFieldDotted(fn, &lhsElt));

                BSONElement rhsElt;
                verify(rhsMember->getFieldDotted(fn, &rhsElt));

                // false means don't compare field name.
                int x = lhsElt.woCompare(rhsElt, false);
                if (-1 == patternElt.number()) { x = -x; }
                if (x != 0) { return x < 0; }
            }

            // A comparator for use with sort is required to model a strict weak ordering, so
            // to satisfy irreflexivity we must return 'false' for elements that we consider
            // equivalent under the pattern.
            return false;
        }

        WorkingSet* _ws;
        BSONObj _pattern;
    };

    SortStage::SortStage(const SortStageParams& params, WorkingSet* ws, PlanStage* child)
        : _ws(ws), _child(child), _pattern(params.pattern), _sorted(false),
          _resultIterator(_data.end()) { }

    SortStage::~SortStage() { }

    bool SortStage::isEOF() {
        // We're done when our child has no more results, we've sorted the child's results, and
        // we've returned all sorted results.
        return _child->isEOF() && _sorted && (_data.end() == _resultIterator);
    }

    PlanStage::StageState SortStage::work(WorkingSetID* out) {
        ++_commonStats.works;

        if (isEOF()) { return PlanStage::IS_EOF; }

        // Still reading in results to sort.
        if (!_sorted) {
            WorkingSetID id;
            StageState code = _child->work(&id);

            if (PlanStage::ADVANCED == code) {
                // We let the data stay in the WorkingSet and sort using the IDs.
                _data.push_back(id);

                // Add it into the map for quick invalidation if it has a valid DiskLoc.
                // A DiskLoc may be invalidated at any time (during a yield).  We need to get into
                // the WorkingSet as quickly as possible to handle it.
                WorkingSetMember* member = _ws->get(id);
                if (member->hasLoc()) {
                    _wsidByDiskLoc[member->loc] = id;
                }

                ++_commonStats.needTime;
                return PlanStage::NEED_TIME;
            }
            else if (PlanStage::IS_EOF == code) {
                // TODO: We don't need the lock for this.  We could ask for a yield and do this work
                // unlocked.  Also, this is performing a lot of work for one call to work(...)
                std::sort(_data.begin(), _data.end(), WorkingSetComparison(_ws, _pattern));
                _resultIterator = _data.begin();
                _sorted = true;
                ++_commonStats.needTime;
                return PlanStage::NEED_TIME;
            }
            else {
                if (PlanStage::NEED_FETCH == code) {
                    ++_commonStats.needFetch;
                }
                else if (PlanStage::NEED_TIME == code) {
                    ++_commonStats.needTime;
                }
                return code;
            }
        }

        // Returning results.
        verify(_resultIterator != _data.end());
        verify(_sorted);
        *out = *_resultIterator++;
        ++_commonStats.advanced;
        return PlanStage::ADVANCED;
    }

    void SortStage::prepareToYield() {
        ++_commonStats.yields;
        _child->prepareToYield();
    }

    void SortStage::recoverFromYield() {
        ++_commonStats.unyields;
        _child->recoverFromYield();
    }

    void SortStage::invalidate(const DiskLoc& dl) {
        ++_commonStats.invalidates;
        _child->invalidate(dl);

        // _data contains indices into the WorkingSet, not actual data.  If a WorkingSetMember in
        // the WorkingSet needs to change state as a result of a DiskLoc invalidation, it will still
        // be at the same spot in the WorkingSet.  As such, we don't need to modify _data.

        DataMap::iterator it = _wsidByDiskLoc.find(dl);

        // If we're holding on to data that's got the DiskLoc we're invalidating...
        if (_wsidByDiskLoc.end() != it) {
            WorkingSetMember* member = _ws->get(it->second);
            WorkingSetCommon::fetchAndInvalidateLoc(member);
            _wsidByDiskLoc.erase(it);
            ++_specificStats.forcedFetches;
        }
    }

    PlanStageStats* SortStage::getStats() {
        _commonStats.isEOF = isEOF();

        auto_ptr<PlanStageStats> ret(new PlanStageStats(_commonStats));
        ret->setSpecific<SortStats>(_specificStats);
        ret->children.push_back(_child->getStats());
        return ret.release();
    }

}  // namespace mongo