summaryrefslogtreecommitdiff
path: root/src/mongo/db/update/object_replace_node.cpp
blob: f9c52c1d4feaeed311909cdd62983e5ce35b5ea2 (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

/**
 *    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/db/update/object_replace_node.h"

#include "mongo/base/data_view.h"
#include "mongo/db/bson/dotted_path_support.h"
#include "mongo/db/logical_clock.h"
#include "mongo/db/logical_time.h"
#include "mongo/db/service_context.h"
#include "mongo/db/update/storage_validation.h"

namespace mongo {

namespace {
constexpr StringData kIdFieldName = "_id"_sd;
}  // namespace

ObjectReplaceNode::ObjectReplaceNode(BSONObj val)
    : UpdateNode(Type::Replacement), _val(val.getOwned()), _containsId(false) {

    // Replace all zero-valued timestamps with the current time and check for the existence of _id.
    for (auto&& elem : _val) {

        // Do not change the _id field.
        if (elem.fieldNameStringData() == kIdFieldName) {
            _containsId = true;
            continue;
        }

        if (elem.type() == BSONType::bsonTimestamp) {
            auto timestampView = DataView(const_cast<char*>(elem.value()));

            // We don't need to do an endian-safe read here, because 0 is 0 either way.
            unsigned long long timestamp = timestampView.read<unsigned long long>();
            if (timestamp == 0) {
                ServiceContext* service = getGlobalServiceContext();
                auto ts = LogicalClock::get(service)->reserveTicks(1).asTimestamp();
                timestampView.write(tagLittleEndian(ts.asULL()));
            }
        }
    }
}

UpdateNode::ApplyResult ObjectReplaceNode::apply(ApplyParams applyParams) const {
    invariant(applyParams.pathToCreate->empty());
    invariant(applyParams.pathTaken->empty());

    auto original = applyParams.element.getDocument().getObject();

    // Check for noop.
    if (original.binaryEqual(_val)) {
        return ApplyResult::noopResult();
    }

    // Remove the contents of the provided document.
    auto current = applyParams.element.leftChild();
    while (current.ok()) {

        // Keep the _id if the replacement document does not have one.
        if (!_containsId && current.getFieldName() == kIdFieldName) {
            current = current.rightSibling();
            continue;
        }

        auto toRemove = current;
        current = current.rightSibling();
        invariant(toRemove.remove());
    }

    // Insert the provided contents instead.
    for (auto&& elem : _val) {
        invariant(applyParams.element.appendElement(elem));
    }

    // Validate for storage.
    if (applyParams.validateForStorage) {
        storage_validation::storageValid(applyParams.element.getDocument());
    }

    // Check immutable paths.
    for (auto path = applyParams.immutablePaths.begin(); path != applyParams.immutablePaths.end();
         ++path) {

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

        auto oldElem = dotted_path_support::extractElementAtPath(original, (*path)->dottedField());

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

    if (applyParams.logBuilder) {
        auto replacementObject = applyParams.logBuilder->getDocument().end();
        invariant(applyParams.logBuilder->getReplacementObject(&replacementObject));
        for (auto current = applyParams.element.leftChild(); current.ok();
             current = current.rightSibling()) {
            invariant(replacementObject.appendElement(current.getValue()));
        }
    }

    return ApplyResult();
}

}  // namespace mongo