summaryrefslogtreecommitdiff
path: root/src/mongo/db/query/query_planner_common.cpp
blob: b6c3253fd2822762fea54ca54e516ebb703efbbe (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
/**
 *    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/base/exact_cast.h"
#include "mongo/db/query/projection_ast_path_tracking_visitor.h"
#include "mongo/db/query/query_planner_common.h"
#include "mongo/db/query/query_solution.h"
#include "mongo/db/query/stage_types.h"
#include "mongo/db/query/tree_walker.h"
#include "mongo/logv2/log.h"
#include "mongo/logv2/redaction.h"
#include "mongo/util/assert_util.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kQuery


namespace mongo {

bool QueryPlannerCommon::scanDirectionsEqual(QuerySolutionNode* node, int direction) {
    StageType type = node->getType();

    boost::optional<int> scanDir;
    if (STAGE_IXSCAN == type) {
        IndexScanNode* isn = static_cast<IndexScanNode*>(node);
        scanDir = isn->direction;
    } else if (STAGE_DISTINCT_SCAN == type) {
        DistinctNode* dn = static_cast<DistinctNode*>(node);
        scanDir = dn->direction;
    } else if (STAGE_COLLSCAN == type) {
        CollectionScanNode* collScan = static_cast<CollectionScanNode*>(node);
        scanDir = collScan->direction;
    } else {
        // We shouldn't encounter a sort stage.
        invariant(!isSortStageType(type));
    }

    // If we found something with a direction, and the direction doesn't match, we return false.
    if (scanDir && scanDir != direction) {
        return false;
    }

    for (size_t i = 0; i < node->children.size(); ++i) {
        if (!scanDirectionsEqual(node->children[i].get(), direction)) {
            return false;
        }
    }
    return true;
}

void QueryPlannerCommon::reverseScans(QuerySolutionNode* node, bool reverseCollScans) {
    StageType type = node->getType();

    if (STAGE_IXSCAN == type) {
        IndexScanNode* isn = static_cast<IndexScanNode*>(node);
        isn->direction *= -1;

        isn->bounds = isn->bounds.reverse();

        invariant(isn->bounds.isValidFor(isn->index.keyPattern, isn->direction),
                  str::stream() << "Invalid bounds: "
                                << redact(isn->bounds.toString(isn->index.collator != nullptr)));

        // TODO: we can just negate every value in the already computed properties.
        isn->computeProperties();
    } else if (STAGE_DISTINCT_SCAN == type) {
        DistinctNode* dn = static_cast<DistinctNode*>(node);
        dn->direction *= -1;

        dn->bounds = dn->bounds.reverse();

        invariant(dn->bounds.isValidFor(dn->index.keyPattern, dn->direction),
                  str::stream() << "Invalid bounds: "
                                << redact(dn->bounds.toString(dn->index.collator != nullptr)));

        dn->computeProperties();
    } else if (STAGE_SORT_MERGE == type) {
        // reverse direction of comparison for merge
        MergeSortNode* msn = static_cast<MergeSortNode*>(node);
        msn->sort = reverseSortObj(msn->sort);
    } else if (reverseCollScans && STAGE_COLLSCAN == type) {
        CollectionScanNode* collScan = static_cast<CollectionScanNode*>(node);
        collScan->direction *= -1;
    } else {
        // Reversing scans is done in order to determine whether or not we need to add an explicit
        // SORT stage. There shouldn't already be one present in the plan.
        invariant(!isSortStageType(type));
    }

    for (size_t i = 0; i < node->children.size(); ++i) {
        reverseScans(node->children[i].get(), reverseCollScans);
    }
}

namespace {

struct MetaFieldData {
    std::vector<FieldPath> metaPaths;
};

using MetaFieldVisitorContext = projection_ast::PathTrackingVisitorContext<MetaFieldData>;

/**
 * Visitor which produces a list of paths where $meta expressions are.
 */
class MetaFieldVisitor final : public projection_ast::ProjectionASTConstVisitor {
public:
    MetaFieldVisitor(MetaFieldVisitorContext* context) : _context(context) {}


    void visit(const projection_ast::ExpressionASTNode* node) final {
        const auto* metaExpr = exact_pointer_cast<const ExpressionMeta*>(node->expressionRaw());
        if (!metaExpr || metaExpr->getMetaType() != DocumentMetadataFields::MetaType::kSortKey) {
            return;
        }

        _context->data().metaPaths.push_back(_context->fullPath());
    }

    void visit(const projection_ast::ProjectionPositionalASTNode* node) final {}
    void visit(const projection_ast::ProjectionSliceASTNode* node) final {}
    void visit(const projection_ast::ProjectionElemMatchASTNode* node) final {}
    void visit(const projection_ast::BooleanConstantASTNode* node) final {}
    void visit(const projection_ast::ProjectionPathASTNode* node) final {}
    void visit(const projection_ast::MatchExpressionASTNode* node) final {}

private:
    MetaFieldVisitorContext* _context;
};
}  // namespace

std::vector<FieldPath> QueryPlannerCommon::extractSortKeyMetaFieldsFromProjection(
    const projection_ast::Projection& proj) {

    MetaFieldVisitorContext ctx;
    MetaFieldVisitor visitor(&ctx);
    projection_ast::PathTrackingConstWalker<MetaFieldData> walker{&ctx, {&visitor}, {}};
    tree_walker::walk<true, projection_ast::ASTNode>(proj.root(), &walker);

    return std::move(ctx.data().metaPaths);
}
}  // namespace mongo