1 
2 /**
3  *    Copyright (C) 2018-present MongoDB, Inc.
4  *
5  *    This program is free software: you can redistribute it and/or modify
6  *    it under the terms of the Server Side Public License, version 1,
7  *    as published by MongoDB, Inc.
8  *
9  *    This program is distributed in the hope that it will be useful,
10  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *    Server Side Public License for more details.
13  *
14  *    You should have received a copy of the Server Side Public License
15  *    along with this program. If not, see
16  *    <http://www.mongodb.com/licensing/server-side-public-license>.
17  *
18  *    As a special exception, the copyright holders give permission to link the
19  *    code of portions of this program with the OpenSSL library under certain
20  *    conditions as described in each individual source file and distribute
21  *    linked combinations including the program with the OpenSSL library. You
22  *    must comply with the Server Side Public License in all respects for
23  *    all of the code used other than as permitted herein. If you modify file(s)
24  *    with this exception, you may extend this exception to your version of the
25  *    file(s), but you are not obligated to do so. If you do not wish to do so,
26  *    delete this exception statement from your version. If you delete this
27  *    exception statement from all source files in the program, then also delete
28  *    it in the license file.
29  */
30 
31 #include "mongo/db/ops/modifier_unset.h"
32 
33 #include "mongo/base/error_codes.h"
34 #include "mongo/bson/mutable/document.h"
35 #include "mongo/db/update/field_checker.h"
36 #include "mongo/db/update/log_builder.h"
37 #include "mongo/db/update/path_support.h"
38 #include "mongo/util/mongoutils/str.h"
39 
40 namespace mongo {
41 
42 namespace str = mongoutils::str;
43 
44 struct ModifierUnset::PreparedState {
PreparedStatemongo::ModifierUnset::PreparedState45     PreparedState(mutablebson::Document* targetDoc)
46         : doc(*targetDoc), idxFound(0), elemFound(doc.end()), noOp(false) {}
47 
48     // Document that is going to be changed.
49     mutablebson::Document& doc;
50 
51     // Index in _fieldRef for which an Element exist in the document.
52     size_t idxFound;
53 
54     // Element corresponding to _fieldRef[0.._idxFound].
55     mutablebson::Element elemFound;
56 
57     // This $set is a no-op?
58     bool noOp;
59 };
60 
ModifierUnset()61 ModifierUnset::ModifierUnset() : _fieldRef(), _posDollar(0), _val() {}
62 
~ModifierUnset()63 ModifierUnset::~ModifierUnset() {}
64 
init(const BSONElement & modExpr,const Options & opts,bool * positional)65 Status ModifierUnset::init(const BSONElement& modExpr, const Options& opts, bool* positional) {
66     //
67     // field name analysis
68     //
69 
70     // Perform standard field name and updateable checks.
71     _fieldRef.parse(modExpr.fieldName());
72     Status status = fieldchecker::isUpdatable(_fieldRef);
73     if (!status.isOK()) {
74         return status;
75     }
76 
77     // If a $-positional operator was used, get the index in which it occurred
78     // and ensure only one occurrence.
79     size_t foundCount;
80     bool foundDollar = fieldchecker::isPositional(_fieldRef, &_posDollar, &foundCount);
81 
82     if (positional)
83         *positional = foundDollar;
84 
85     if (foundDollar && foundCount > 1) {
86         return Status(ErrorCodes::BadValue,
87                       str::stream() << "Too many positional (i.e. '$') elements found in path '"
88                                     << _fieldRef.dottedField()
89                                     << "'");
90     }
91 
92 
93     //
94     // value analysis
95     //
96 
97     // Unset takes any value, since there is no semantics attached to such value.
98     _val = modExpr;
99 
100     return Status::OK();
101 }
102 
prepare(mutablebson::Element root,StringData matchedField,ExecInfo * execInfo)103 Status ModifierUnset::prepare(mutablebson::Element root,
104                               StringData matchedField,
105                               ExecInfo* execInfo) {
106     _preparedState.reset(new PreparedState(&root.getDocument()));
107 
108     // If we have a $-positional field, it is time to bind it to an actual field part.
109     if (_posDollar) {
110         if (matchedField.empty()) {
111             return Status(ErrorCodes::BadValue,
112                           str::stream() << "The positional operator did not find the match "
113                                            "needed from the query. Unexpanded update: "
114                                         << _fieldRef.dottedField());
115         }
116         _fieldRef.setPart(_posDollar, matchedField);
117     }
118 
119 
120     // Locate the field name in 'root'. Note that if we don't have the full path in the
121     // doc, there isn't anything to unset, really.
122     Status status = pathsupport::findLongestPrefix(
123         _fieldRef, root, &_preparedState->idxFound, &_preparedState->elemFound);
124     if (!status.isOK() || _preparedState->idxFound != (_fieldRef.numParts() - 1)) {
125         execInfo->noOp = _preparedState->noOp = true;
126         execInfo->fieldRef[0] = &_fieldRef;
127 
128         return Status::OK();
129     }
130 
131     // If there is indeed something to unset, we register so, along with the interest in
132     // the field name. The driver needs this info to sort out if there is any conflict
133     // among mods.
134     execInfo->fieldRef[0] = &_fieldRef;
135 
136     // The only way for an $unset to be inplace is for its target field to be the last one
137     // of the object. That is, it is always the right child on its paths. The current
138     // rationale is that there should be no holes in a BSONObj and, to be in place, no
139     // field boundaries must change.
140     //
141     // TODO:
142     // mutablebson::Element curr = _preparedState->elemFound;
143     // while (curr.ok()) {
144     //     if (curr.rightSibling().ok()) {
145     //     }
146     //     curr = curr.parent();
147     // }
148 
149     return Status::OK();
150 }
151 
apply() const152 Status ModifierUnset::apply() const {
153     dassert(!_preparedState->noOp);
154 
155     // Our semantics says that, if we're unseting an element of an array, we swap that
156     // value to null. The rationale is that we don't want other array elements to change
157     // indices. (That could be achieved with $pull-ing element from it.)
158     if (_preparedState->elemFound.parent().ok() &&
159         _preparedState->elemFound.parent().getType() == Array) {
160         return _preparedState->elemFound.setValueNull();
161     } else {
162         return _preparedState->elemFound.remove();
163     }
164 }
165 
log(LogBuilder * logBuilder) const166 Status ModifierUnset::log(LogBuilder* logBuilder) const {
167     return logBuilder->addToUnsets(_fieldRef.dottedField());
168 }
169 
170 }  // namespace mongo
171