summaryrefslogtreecommitdiff
path: root/src/mongo/db/update/update_node.h
blob: be4a1b091551c233e04faf4bc143c170e4a9bf7f (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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/**
 *    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 <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "mongo/bson/bsonelement.h"
#include "mongo/bson/mutable/element.h"
#include "mongo/db/field_ref_set.h"
#include "mongo/db/update/log_builder.h"
#include "mongo/db/update/update_node_visitor.h"
#include "mongo/db/update_index_data.h"
#include "mongo/util/assert_util.h"

namespace mongo {

class CollatorInterface;
class FieldRef;

/**
 * Update modifier expressions are stored as a prefix tree of UpdateNodes, where two modifiers that
 * share a field path prefix share a path prefix in the tree. The prefix tree is used to enforce
 * that no update modifier's field path is a prefix of (or equal to) another update modifier's field
 * path. The root of the UpdateNode tree is always an UpdateObjectNode. The leaves are always
 * UpdateLeafNodes.
 *
 * Example: {$set: {'a.b': 5, c: 6}, $inc: {'a.c': 1}}
 *
 *                      UpdateObjectNode
 *                         a /    \ c
 *            UpdateObjectNode    SetNode: _val = 6
 *               b /    \ c
 * SetNode: _val = 5    IncNode: _val = 1
 */
class UpdateNode {
public:
    enum class Context { kAll, kInsertOnly };
    enum class Type { Object, Array, Leaf, Replacement };

    explicit UpdateNode(Type type, Context context = Context::kAll)
        : context(context), type(type) {}
    virtual ~UpdateNode() = default;

    virtual std::unique_ptr<UpdateNode> clone() const = 0;

    /**
     * Set the collation on the node and all descendants. This is a noop if no leaf nodes require a
     * collator. If setCollator() is called, it is required that the current collator of all leaf
     * nodes is the simple collator (nullptr). The collator must outlive the modifier interface.
     * This is used to override the collation after obtaining a collection lock if the update did
     * not specify a collation and the collection has a non-simple default collation.
     */
    virtual void setCollator(const CollatorInterface* collator) = 0;

    /**
     * The parameters required by UpdateNode::apply.
     */
    struct ApplyParams {
        ApplyParams(mutablebson::Element element, const FieldRefSet& immutablePaths)
            : element(element), immutablePaths(immutablePaths) {}

        // The element to update.
        mutablebson::Element element;

        // UpdateNode::apply uasserts if it modifies an immutable path.
        const FieldRefSet& immutablePaths;

        // The path taken through the UpdateNode tree beyond where the path existed in the document.
        // For example, if the update is {$set: {'a.b.c': 5}}, and the document is {a: {}}, then at
        // the leaf node, 'pathToCreate'="b.c".
        std::shared_ptr<FieldRef> pathToCreate = std::make_shared<FieldRef>();

        // The path through the root document to 'element', ending with the field name of 'element'.
        // For example, if the update is {$set: {'a.b.c': 5}}, and the document is {a: {}}, then at
        // the leaf node, 'pathTaken'="a".
        std::shared_ptr<FieldRef> pathTaken = std::make_shared<FieldRef>();

        // If there was a positional ($) element in the update expression, 'matchedField' is the
        // index of the array element that caused the query to match the document.
        StringData matchedField;

        // True if the update is being applied to a document to be inserted. $setOnInsert behaves as
        // a no-op when this flag is false.
        bool insert = false;

        // This is provided because some modifiers may ignore certain errors when the update is from
        // replication.
        bool fromOplogApplication = false;

        // If true, UpdateNode::apply ensures that modified elements do not violate depth or DBRef
        // constraints.
        bool validateForStorage = true;

        // Used to determine whether indexes are affected.
        const UpdateIndexData* indexData = nullptr;

        // If provided, UpdateNode::apply will log the update here.
        LogBuilder* logBuilder = nullptr;

        // If provided, UpdateNode::apply will populate this with a path to each modified field.
        FieldRefSetWithStorage* modifiedPaths = nullptr;
    };

    /**
     * The outputs of apply().
     */
    struct ApplyResult {
        static ApplyResult noopResult() {
            ApplyResult applyResult;
            applyResult.indexesAffected = false;
            applyResult.noop = true;
            return applyResult;
        }

        bool indexesAffected = true;
        bool noop = false;
    };

    /**
     * Applies the update node to 'applyParams.element', creating the fields in
     * 'applyParams.pathToCreate' if required by the leaves (i.e. the leaves are not all $unset).
     * Returns an ApplyResult specifying whether the operation was a no-op and whether indexes are
     * affected.
     */
    virtual ApplyResult apply(ApplyParams applyParams) const = 0;

    /**
     * Creates a new node by merging the contents of two input nodes. The semantics of the merge
     * operation depend on the types of the input nodes. When the nodes have the same type, this
     * function dispatches the merge to a createUpdateNodeByMerging implementation defined for that
     * subtype. Throws AssertionException with a ConflictingUpdateOperators code when the types of
     * the input nodes differ or when any of the child nodes fail to merge.
     */
    static std::unique_ptr<UpdateNode> createUpdateNodeByMerging(const UpdateNode& leftNode,
                                                                 const UpdateNode& rightNode,
                                                                 FieldRef* pathTaken);

    /**
     * Produces a map of serialization components for an update. The map is indexed according to
     * operator name. The value of each map entry is a vector of operator components. These two
     * components are an operator field, which is a string representing a path, and an operator
     * value, which is a BSONObj of the arguments to the operation. 'currentPath' keeps running
     * track of the full path to the current node. Note that, although produceSerializationMap()
     * mutates its 'currentPath' FieldRef for use in recursive calls, it always restores the
     * original value before the function returns so the caller will witness no change.
     */
    virtual void produceSerializationMap(
        FieldRef* currentPath,
        std::map<std::string, std::vector<std::pair<std::string, BSONObj>>>*
            operatorOrientedUpdates) const = 0;

    /**
     * This allows an arbitrary class to implement logic which gets dispatched to at runtime
     * depending on the type of the UpdateNode.
     */
    virtual void acceptVisitor(UpdateNodeVisitor* visitor) = 0;

public:
    const Context context;
    const Type type;
};

}  // namespace mongo