summaryrefslogtreecommitdiff
path: root/src/mongo/db/update/path_creating_node.cpp
blob: 155f41029cd06c0e2d0e342283cb62d8d33f995d (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
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
/**
 * Copyright (C) 2017 MongoDB 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/>.
 *
 * 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 GNU Affero General 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/db/update/path_creating_node.h"

#include "mongo/db/bson/dotted_path_support.h"
#include "mongo/db/update/path_support.h"
#include "mongo/db/update/storage_validation.h"

namespace mongo {

namespace {

/**
 * Checks that no immutable paths were modified in the case where we are modifying an existing path
 * in the document. 'element' should be the modified element. 'pathTaken' is the path to the
 * modified element. If 'pathTaken' is a strict prefix of any immutable path, 'original' should be
 * provided as the preimage of the whole document. We assume that we have already checked the update
 * is not a noop.
 */
void checkImmutablePathsNotModified(mutablebson::Element element,
                                    FieldRef* pathTaken,
                                    const FieldRefSet& immutablePaths,
                                    BSONObj original) {
    for (auto immutablePath = immutablePaths.begin(); immutablePath != immutablePaths.end();
         ++immutablePath) {
        auto prefixSize = pathTaken->commonPrefixSize(**immutablePath);

        // If 'immutablePath' is a (strict or non-strict) prefix of 'pathTaken', and the update is
        // not a noop, then we have modified 'immutablePath', which is immutable.
        if (prefixSize == (*immutablePath)->numParts()) {
            uasserted(ErrorCodes::ImmutableField,
                      str::stream() << "Updating the path '" << pathTaken->dottedField() << "' to "
                                    << element.toString()
                                    << " would modify the immutable field '"
                                    << (*immutablePath)->dottedField()
                                    << "'");
        }

        // If 'pathTaken' is a strict prefix of 'immutablePath', then we may have modified
        // 'immutablePath'. We already know that 'pathTaken' is not equal to 'immutablePath', or we
        // would have uasserted.
        if (prefixSize == pathTaken->numParts()) {
            auto oldElem = dotted_path_support::extractElementAtPath(
                original, (*immutablePath)->dottedField());

            // We are allowed to modify immutable paths that do not yet exist.
            if (!oldElem.ok()) {
                continue;
            }

            auto newElem = element;
            for (size_t i = pathTaken->numParts(); i < (*immutablePath)->numParts(); ++i) {
                uassert(ErrorCodes::NotSingleValueField,
                        str::stream()
                            << "After applying the update to the document, the immutable field '"
                            << (*immutablePath)->dottedField()
                            << "' was found to be an array or array descendant.",
                        newElem.getType() != BSONType::Array);
                newElem = newElem[(*immutablePath)->getPart(i)];
                if (!newElem.ok()) {
                    break;
                }
            }

            uassert(ErrorCodes::ImmutableField,
                    str::stream() << "After applying the update, the immutable field '"
                                  << (*immutablePath)->dottedField()
                                  << "' was found to have been removed.",
                    newElem.ok());
            uassert(ErrorCodes::ImmutableField,
                    str::stream() << "After applying the update, the immutable field '"
                                  << (*immutablePath)->dottedField()
                                  << "' was found to have been altered to "
                                  << newElem.toString(),
                    newElem.compareWithBSONElement(oldElem, nullptr, false) == 0);
        }
    }
}

}  // namespace

UpdateNode::ApplyResult PathCreatingNode::apply(ApplyParams applyParams) const {
    if (context == Context::kInsertOnly && !applyParams.insert) {
        return ApplyResult::noopResult();
    }

    // The value in this Element gets used to create a logging entry (if we have a LogBuilder).
    mutablebson::Element valueToLog = applyParams.element.getDocument().end();

    if (applyParams.pathToCreate->empty()) {

        // If 'pathTaken' is a strict prefix of any immutable path, store the original document to
        // ensure the immutable path does not change.
        BSONObj original;
        for (auto immutablePath = applyParams.immutablePaths.begin();
             immutablePath != applyParams.immutablePaths.end();
             ++immutablePath) {
            if (applyParams.pathTaken->isPrefixOf(**immutablePath)) {
                original = applyParams.element.getDocument().getObject();
                break;
            }
        }

        // We found an existing element at the update path.
        auto updateResult = updateExistingElement(
            &applyParams.element, applyParams.pathTaken, applyParams.logBuilder);
        if (updateResult == UpdateExistingElementResult::kNoOp) {
            return ApplyResult::noopResult();  // Successful no-op update.
        }

        if (applyParams.validateForStorage) {
            const bool doRecursiveCheck = true;
            const uint32_t recursionLevel = applyParams.pathTaken->numParts();
            storage_validation::storageValid(applyParams.element, doRecursiveCheck, recursionLevel);
        }

        checkImmutablePathsNotModified(
            applyParams.element, applyParams.pathTaken.get(), applyParams.immutablePaths, original);

        if (updateResult == UpdateExistingElementResult::kUpdated) {
            valueToLog = applyParams.element;
        } else {
            // updateExistingElement() has already performed logging, so we don't set a log value.
        }
    } else {
        // We did not find an element at the update path. Create one.
        auto newElementFieldName =
            applyParams.pathToCreate->getPart(applyParams.pathToCreate->numParts() - 1);
        auto newElement = applyParams.element.getDocument().makeElementNull(newElementFieldName);
        setValueForNewElement(&newElement);

        invariant(newElement.ok());
        auto statusWithFirstCreatedElem = pathsupport::createPathAt(
            *(applyParams.pathToCreate), 0, applyParams.element, newElement);
        if (!statusWithFirstCreatedElem.isOK()) {
            // $sets on non-viable paths are ignored when the update came from replication. We do
            // not error because idempotency requires that any other update modifiers must still be
            // applied. For example, consider applying the following updates twice to an initially
            // empty document:
            // {$set: {c: 0}}
            // {$set: {'a.b': 0, c: 1}}
            // {$set: {a: 0}}
            // Setting 'a.b' will fail the second time, but we must still set 'c'.
            // (There are modifiers besides $set that use this code path, but they are not used for
            // replication, so we are not concerned with their behavior when "fromReplication" is
            // true.)
            if (statusWithFirstCreatedElem.getStatus().code() == ErrorCodes::PathNotViable &&
                applyParams.fromReplication) {
                return ApplyResult::noopResult();
            }
            uassertStatusOK(statusWithFirstCreatedElem);
            MONGO_UNREACHABLE;  // The previous uassertStatusOK should always throw.
        }

        if (applyParams.validateForStorage) {
            const bool doRecursiveCheck = true;
            const uint32_t recursionLevel = applyParams.pathTaken->numParts() + 1;
            storage_validation::storageValid(
                statusWithFirstCreatedElem.getValue(), doRecursiveCheck, recursionLevel);
        }

        for (auto immutablePath = applyParams.immutablePaths.begin();
             immutablePath != applyParams.immutablePaths.end();
             ++immutablePath) {

            // If 'immutablePath' is a (strict or non-strict) prefix of 'pathTaken', then we are
            // modifying 'immutablePath'. For example, adding '_id.x' will illegally modify '_id'.
            uassert(ErrorCodes::ImmutableField,
                    str::stream() << "Updating the path '" << applyParams.pathTaken->dottedField()
                                  << "' to "
                                  << applyParams.element.toString()
                                  << " would modify the immutable field '"
                                  << (*immutablePath)->dottedField()
                                  << "'",
                    applyParams.pathTaken->commonPrefixSize(**immutablePath) !=
                        (*immutablePath)->numParts());
        }

        valueToLog = newElement;
    }

    // Create full field path of set element.
    StringBuilder builder;
    builder << applyParams.pathTaken->dottedField();
    if (!applyParams.pathTaken->empty() && !applyParams.pathToCreate->empty()) {
        builder << ".";
    }
    builder << applyParams.pathToCreate->dottedField();
    auto fullPath = builder.str();

    ApplyResult applyResult;

    // Determine if indexes are affected.
    if (!applyParams.indexData || !applyParams.indexData->mightBeIndexed(fullPath)) {
        applyResult.indexesAffected = false;
    }

    // Log the operation.
    if (applyParams.logBuilder && valueToLog.ok()) {
        auto logElement =
            applyParams.logBuilder->getDocument().makeElementWithNewFieldName(fullPath, valueToLog);
        invariant(logElement.ok());
        uassertStatusOK(applyParams.logBuilder->addToSets(logElement));
    }

    return applyResult;
}
}  // namespace mongo