summaryrefslogtreecommitdiff
path: root/src/mongo/db/exec/projection_executor.h
blob: 0188c17f69548ccb3b01ee97350d9c593cdd4dd9 (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
/**
 *    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.
 */

#pragma once

#include "mongo/platform/basic.h"

#include <boost/intrusive_ptr.hpp>
#include <memory>

#include "mongo/bson/bsonelement.h"
#include "mongo/db/pipeline/expression_context.h"
#include "mongo/db/pipeline/field_path.h"
#include "mongo/db/pipeline/transformer_interface.h"
#include "mongo/db/query/projection_policies.h"

namespace mongo::projection_executor {
/**
 * A ProjectionExecutor is responsible for parsing and executing a $project. It represents either an
 * inclusion or exclusion projection. This is the common interface between the two types of
 * projections.
 */
class ProjectionExecutor : public TransformerInterface {
public:
    /**
     * The name of an internal variable to bind a projection post image to, which is used by the
     * '_rootReplacementExpression' to replace the content of the transformed document.
     */
    static constexpr StringData kProjectionPostImageVarName{"INTERNAL_PROJ_POST_IMAGE"_sd};

    /**
     * Optimize any expressions contained within this projection.
     */
    void optimize() override {
        if (_rootReplacementExpression) {
            _rootReplacementExpression->optimize();
        }
    }

    /**
     * Add any dependencies needed by this projection or any sub-expressions to 'deps'.
     */
    DepsTracker::State addDependencies(DepsTracker* deps) const override {
        return DepsTracker::State::NOT_SUPPORTED;
    }

    /**
     * Apply the projection transformation.
     */
    Document applyTransformation(const Document& input) override {
        auto output = applyProjection(input);
        if (_rootReplacementExpression) {
            return _applyRootReplacementExpression(input, output);
        }
        return output;
    }

    /**
     * Sets 'expr' as a root-replacement expression to this tree. A root-replacement expression,
     * once evaluated, will replace an entire output document. A projection post image document
     * will be accessible via the special variable, whose name is stored in
     * 'kProjectionPostImageVarName', if this expression needs access to it.
     */
    void setRootReplacementExpression(boost::intrusive_ptr<Expression> expr) {
        _rootReplacementExpression = expr;
    }

    /**
     * Returns the root-replacement expression to this tree. Can return nullptr if this tree does
     * not have a root replacing expression.
     */
    boost::intrusive_ptr<Expression> rootReplacementExpression() const {
        return _rootReplacementExpression;
    }

    /**
     * Returns the exhaustive set of all paths that will be preserved by this projection, or
     * boost::none if the exhaustive set cannot be determined.
     */
    virtual boost::optional<std::set<FieldRef>> extractExhaustivePaths() const = 0;

    /**
     * The query shape is made by serializing the first parsed representation of the query, which in
     * the case of $project queries is a projection_ast::Projection. The ProjectionExecutor, holds
     * onto the root node of the AST for only $project queries, so that the first parsed
     * representation is accessible at serialization.
     */
    boost::optional<projection_ast::ProjectionPathASTNode> projection = boost::none;

protected:
    ProjectionExecutor(const boost::intrusive_ptr<ExpressionContext>& expCtx,
                       ProjectionPolicies policies,
                       boost::optional<projection_ast::ProjectionPathASTNode> proj = boost::none)
        : projection(proj),
          _expCtx(expCtx),
          _policies(policies),
          _projectionPostImageVarId{
              _expCtx->variablesParseState.defineVariable(kProjectionPostImageVarName)} {}

    /**
     * Apply the projection to 'input'.
     */
    virtual Document applyProjection(const Document& input) const = 0;

    boost::intrusive_ptr<ExpressionContext> _expCtx;

    ProjectionPolicies _policies;

    boost::intrusive_ptr<Expression> _rootReplacementExpression;

private:
    Document _applyRootReplacementExpression(const Document& input, const Document& output) {
        using namespace fmt::literals;

        _expCtx->variables.setValue(_projectionPostImageVarId, Value{output});
        auto val = _rootReplacementExpression->evaluate(input, &_expCtx->variables);
        uassert(51254,
                "Root-replacement expression must return a document, but got {}"_format(
                    typeName(val.getType())),
                val.getType() == BSONType::Object);
        return val.getDocument();
    }

    // This variable id is used to bind a projection post-image so that it can be accessed by
    // root-replacement expressions which apply projection to the entire post-image document, rather
    // than to a specific field.
    Variables::Id _projectionPostImageVarId;
};
}  // namespace mongo::projection_executor