summaryrefslogtreecommitdiff
path: root/src/mongo/db/pipeline/document_source_replace_root_test.cpp
blob: 0397784b7ffafc14ca26337fcba45ff844df1778 (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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/**
 *    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 <boost/intrusive_ptr.hpp>

#include "mongo/bson/bsonmisc.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/db/exec/document_value/document.h"
#include "mongo/db/exec/document_value/document_value_test_util.h"
#include "mongo/db/pipeline/aggregation_context_fixture.h"
#include "mongo/db/pipeline/dependencies.h"
#include "mongo/db/pipeline/document_source_mock.h"
#include "mongo/db/pipeline/document_source_replace_root.h"
#include "mongo/unittest/unittest.h"

namespace mongo {
namespace {

using boost::intrusive_ptr;

class ReplaceRootBasics : public AggregationContextFixture {
protected:
    intrusive_ptr<DocumentSource> createReplaceRoot(const BSONObj& replaceRoot) {
        BSONObj spec = BSON(DocumentSourceReplaceRoot::kStageName << replaceRoot);
        BSONElement specElement = spec.firstElement();
        return DocumentSourceReplaceRoot::createFromBson(specElement, getExpCtx());
    }

    /**
     * Assert 'source' consistently reports it is exhausted.
     */
    void assertExhausted(const boost::intrusive_ptr<DocumentSource>& source) const {
        ASSERT(source->getNext().isEOF());
        ASSERT(source->getNext().isEOF());
        ASSERT(source->getNext().isEOF());
    }
};

// Verify that sending $newRoot a field path that contains an object in the document results
// in the replacement of the root with that object.
TEST_F(ReplaceRootBasics, FieldPathAsNewRootPromotesSubdocument) {
    auto replaceRoot = createReplaceRoot(BSON("newRoot"
                                              << "$a"));
    Document subdoc = Document{{"b", 1}, {"c", "hello"_sd}, {"d", Document{{"e", 2}}}};
    auto mock = DocumentSourceMock::createForTest(Document{{"a", subdoc}}, getExpCtx());
    replaceRoot->setSource(mock.get());

    auto next = replaceRoot->getNext();
    ASSERT_TRUE(next.isAdvanced());
    ASSERT_DOCUMENT_EQ(next.releaseDocument(), subdoc);
    assertExhausted(replaceRoot);
}

// Verify that sending $newRoot a dotted field path that contains an object in the document results
// in the replacement of the root with that object.
TEST_F(ReplaceRootBasics, DottedFieldPathAsNewRootPromotesSubdocument) {
    auto replaceRoot = createReplaceRoot(BSON("newRoot"
                                              << "$a.b"));
    // source document: {a: {b: {c: 3}}}
    Document subdoc = Document{{"c", 3}};
    auto mock =
        DocumentSourceMock::createForTest(Document{{"a", Document{{"b", subdoc}}}}, getExpCtx());
    replaceRoot->setSource(mock.get());

    auto next = replaceRoot->getNext();
    ASSERT_TRUE(next.isAdvanced());
    ASSERT_DOCUMENT_EQ(next.releaseDocument(), subdoc);
    assertExhausted(replaceRoot);
}

// Verify that sending $newRoot a dotted field path that contains an object in two different
// documents results in the replacement of the root with that object in both documents.
TEST_F(ReplaceRootBasics, FieldPathAsNewRootPromotesSubdocumentInMultipleDocuments) {
    auto replaceRoot = createReplaceRoot(BSON("newRoot"
                                              << "$a"));
    Document subdoc1 = Document{{"b", 1}, {"c", 2}};
    Document subdoc2 = Document{{"b", 3}, {"c", 4}};
    auto mock = DocumentSourceMock::createForTest(
        {Document{{"a", subdoc1}}, Document{{"a", subdoc2}}}, getExpCtx());
    replaceRoot->setSource(mock.get());

    // Verify that the first document that comes out is the first document we put in.
    auto next = replaceRoot->getNext();
    ASSERT_TRUE(next.isAdvanced());
    ASSERT_DOCUMENT_EQ(next.releaseDocument(), subdoc1);

    next = replaceRoot->getNext();
    ASSERT_TRUE(next.isAdvanced());
    ASSERT_DOCUMENT_EQ(next.releaseDocument(), subdoc2);

    assertExhausted(replaceRoot);
}

// Verify that when newRoot contains an expression object, the document is replaced with that
// object.
TEST_F(ReplaceRootBasics, ExpressionObjectForNewRootReplacesRootWithThatObject) {
    auto replaceRoot = createReplaceRoot(BSON("newRoot" << BSON("b" << 1)));
    auto mock = DocumentSourceMock::createForTest(Document{{"a", 2}}, getExpCtx());
    replaceRoot->setSource(mock.get());

    auto next = replaceRoot->getNext();
    ASSERT_TRUE(next.isAdvanced());
    ASSERT_DOCUMENT_EQ(next.releaseDocument(), (Document{{"b", 1}}));
    assertExhausted(replaceRoot);

    BSONObj newObject = BSON("a" << 1 << "b" << 2 << "arr" << BSON_ARRAY(3 << 4 << 5));
    replaceRoot = createReplaceRoot(BSON("newRoot" << newObject));
    mock = DocumentSourceMock::createForTest(Document{{"c", 2}}, getExpCtx());
    replaceRoot->setSource(mock.get());

    next = replaceRoot->getNext();
    ASSERT_TRUE(next.isAdvanced());
    ASSERT_DOCUMENT_EQ(next.releaseDocument(), Document(newObject));
    assertExhausted(replaceRoot);

    replaceRoot = createReplaceRoot(BSON("newRoot" << BSON("a" << BSON("b" << 1))));
    mock = DocumentSourceMock::createForTest(Document{{"c", 2}}, getExpCtx());
    replaceRoot->setSource(mock.get());

    next = replaceRoot->getNext();
    ASSERT_TRUE(next.isAdvanced());
    ASSERT_DOCUMENT_EQ(next.releaseDocument(), (Document{{"a", Document{{"b", 1}}}}));
    assertExhausted(replaceRoot);

    replaceRoot = createReplaceRoot(BSON("newRoot" << BSON("a" << 2)));
    mock = DocumentSourceMock::createForTest(Document{{"b", 2}}, getExpCtx());
    replaceRoot->setSource(mock.get());

    next = replaceRoot->getNext();
    ASSERT_TRUE(next.isAdvanced());
    ASSERT_DOCUMENT_EQ(next.releaseDocument(), (Document{{"a", 2}}));
    assertExhausted(replaceRoot);
}

// Verify that when newRoot contains a system variable, the document is replaced with the correct
// object corresponding to that system variable.
TEST_F(ReplaceRootBasics, SystemVariableForNewRootReplacesRootWithThatObject) {
    // System variables
    auto replaceRoot = createReplaceRoot(BSON("newRoot"
                                              << "$$CURRENT"));
    Document inputDoc = Document{{"b", 2}};
    auto mock = DocumentSourceMock::createForTest({inputDoc}, getExpCtx());
    replaceRoot->setSource(mock.get());

    auto next = replaceRoot->getNext();
    ASSERT_TRUE(next.isAdvanced());
    ASSERT_DOCUMENT_EQ(next.releaseDocument(), inputDoc);
    assertExhausted(replaceRoot);

    replaceRoot = createReplaceRoot(BSON("newRoot"
                                         << "$$ROOT"));
    mock = DocumentSourceMock::createForTest({inputDoc}, getExpCtx());
    replaceRoot->setSource(mock.get());

    next = replaceRoot->getNext();
    ASSERT_TRUE(next.isAdvanced());
    ASSERT_DOCUMENT_EQ(next.releaseDocument(), inputDoc);
    assertExhausted(replaceRoot);
}

TEST_F(ReplaceRootBasics, ShouldPropagatePauses) {
    auto replaceRoot = createReplaceRoot(BSON("newRoot"
                                              << "$$ROOT"));
    auto mock =
        DocumentSourceMock::createForTest({Document(),
                                           DocumentSource::GetNextResult::makePauseExecution(),
                                           Document(),
                                           Document(),
                                           DocumentSource::GetNextResult::makePauseExecution(),
                                           DocumentSource::GetNextResult::makePauseExecution()},
                                          getExpCtx());
    replaceRoot->setSource(mock.get());

    ASSERT_TRUE(replaceRoot->getNext().isAdvanced());
    ASSERT_TRUE(replaceRoot->getNext().isPaused());
    ASSERT_TRUE(replaceRoot->getNext().isAdvanced());
    ASSERT_TRUE(replaceRoot->getNext().isAdvanced());
    ASSERT_TRUE(replaceRoot->getNext().isPaused());
    ASSERT_TRUE(replaceRoot->getNext().isPaused());

    assertExhausted(replaceRoot);
}

// Verify that when the expression at newRoot does not resolve to an object, as per the spec we
// throw a user assertion.
TEST_F(ReplaceRootBasics, ErrorsWhenNewRootDoesNotEvaluateToAnObject) {
    auto replaceRoot = createReplaceRoot(BSON("newRoot"
                                              << "$a"));

    // A string is not an object.
    auto mock = DocumentSourceMock::createForTest(Document{{"a", "hello"_sd}}, getExpCtx());
    replaceRoot->setSource(mock.get());
    ASSERT_THROWS_CODE(replaceRoot->getNext(), AssertionException, 40228);

    // An integer is not an object.
    mock = DocumentSourceMock::createForTest(Document{{"a", 5}}, getExpCtx());
    replaceRoot->setSource(mock.get());
    ASSERT_THROWS_CODE(replaceRoot->getNext(), AssertionException, 40228);

    // Literals are not objects.
    replaceRoot = createReplaceRoot(BSON("newRoot" << BSON("$literal" << 1)));
    mock = DocumentSourceMock::createForTest(Document(), getExpCtx());
    replaceRoot->setSource(mock.get());
    ASSERT_THROWS_CODE(replaceRoot->getNext(), AssertionException, 40228);
    assertExhausted(replaceRoot);

    // Most operator expressions do not resolve to objects.
    replaceRoot = createReplaceRoot(BSON("newRoot" << BSON("$and"
                                                           << "$a")));
    mock = DocumentSourceMock::createForTest(Document{{"a", true}}, getExpCtx());
    replaceRoot->setSource(mock.get());
    ASSERT_THROWS_CODE(replaceRoot->getNext(), AssertionException, 40228);
    assertExhausted(replaceRoot);
}

// Verify that when newRoot contains a field path and that field path doesn't exist, we throw a user
// error. This error happens whenever the expression evaluates to a "missing" Value.
TEST_F(ReplaceRootBasics, ErrorsIfNewRootFieldPathDoesNotExist) {
    auto replaceRoot = createReplaceRoot(BSON("newRoot"
                                              << "$a"));

    auto mock = DocumentSourceMock::createForTest(Document(), getExpCtx());
    replaceRoot->setSource(mock.get());
    ASSERT_THROWS_CODE(replaceRoot->getNext(), AssertionException, 40228);
    assertExhausted(replaceRoot);

    mock = DocumentSourceMock::createForTest(Document{{"e", Document{{"b", Document{{"c", 3}}}}}},
                                             getExpCtx());
    replaceRoot->setSource(mock.get());
    ASSERT_THROWS_CODE(replaceRoot->getNext(), AssertionException, 40228);
    assertExhausted(replaceRoot);
}

// Verify that the only dependent field is the root we are replacing with.
TEST_F(ReplaceRootBasics, OnlyDependentFieldIsNewRoot) {
    auto replaceRoot = createReplaceRoot(BSON("newRoot"
                                              << "$a.b"));
    DepsTracker dependencies;
    ASSERT_EQUALS(DepsTracker::State::EXHAUSTIVE_FIELDS,
                  replaceRoot->getDependencies(&dependencies));

    // Should only depend on field a.b
    ASSERT_EQUALS(1U, dependencies.fields.size());
    ASSERT_EQUALS(1U, dependencies.fields.count("a.b"));
    ASSERT_EQUALS(0U, dependencies.fields.count("a"));
    ASSERT_EQUALS(0U, dependencies.fields.count("b"));

    // Should not need any other fields.
    ASSERT_EQUALS(false, dependencies.needWholeDocument);
    ASSERT_EQUALS(false, dependencies.getNeedsMetadata(DocumentMetadataFields::kTextScore));
}

TEST_F(ReplaceRootBasics, ReplaceRootModifiesAllFields) {
    auto replaceRoot = createReplaceRoot(BSON("newRoot"
                                              << "$a"));
    auto modifiedPaths = replaceRoot->getModifiedPaths();
    ASSERT(modifiedPaths.type == DocumentSource::GetModPathsReturn::Type::kAllPaths);
    ASSERT_EQUALS(0U, modifiedPaths.paths.size());
}

TEST_F(ReplaceRootBasics, ReplaceRootWithRemoveSystemVariableThrows) {
    auto replaceRoot = createReplaceRoot(BSON("newRoot"
                                              << "$$REMOVE"));
    Document inputDoc = Document{{"b", 2}};
    auto mock = DocumentSourceMock::createForTest({inputDoc}, getExpCtx());
    replaceRoot->setSource(mock.get());

    ASSERT_THROWS_CODE(replaceRoot->getNext(), AssertionException, 40228);
}

/**
 * Fixture to test error cases of initializing the $replaceRoot stage.
 */
class ReplaceRootSpec : public AggregationContextFixture {
public:
    intrusive_ptr<DocumentSource> createReplaceRoot(const BSONObj& replaceRootSpec) {
        return DocumentSourceReplaceRoot::createFromBson(replaceRootSpec.firstElement(),
                                                         getExpCtx());
    }

    intrusive_ptr<DocumentSource> createReplaceWith(std::string fieldPath) {
        BSONObj spec = BSON(DocumentSourceReplaceRoot::kAliasNameReplaceWith << fieldPath);
        return DocumentSourceReplaceRoot::createFromBson(spec.firstElement(), getExpCtx());
    }

    intrusive_ptr<DocumentSource> createReplaceWith(BSONObj expression) {
        BSONObj spec = BSON(DocumentSourceReplaceRoot::kAliasNameReplaceWith << expression);
        return DocumentSourceReplaceRoot::createFromBson(spec.firstElement(), getExpCtx());
    }


    BSONObj createSpec(BSONObj spec) {
        return BSON("$replaceRoot" << spec);
    }

    BSONObj createFullSpec(BSONObj spec) {
        return BSON("$replaceRoot" << BSON("newRoot" << spec));
    }
};

// Verify that the creation of a $replaceRoot stage requires an object specification
TEST_F(ReplaceRootSpec, CreationRequiresObjectSpecification) {
    ASSERT_THROWS_CODE(createReplaceRoot(BSON("$replaceRoot" << 1)), AssertionException, 40229);
    ASSERT_THROWS_CODE(createReplaceRoot(BSON("$replaceRoot"
                                              << "string")),
                       AssertionException,
                       40229);
}

// Verify that the only valid option for the $replaceRoot object specification is newRoot.
TEST_F(ReplaceRootSpec, OnlyValidOptionInObjectSpecIsNewRoot) {
    ASSERT_THROWS_CODE(createReplaceRoot(createSpec(BSON("newRoot"
                                                         << "$a"
                                                         << "root" << 2))),
                       AssertionException,
                       40415);
    ASSERT_THROWS_CODE(createReplaceRoot(createSpec(BSON("newRoot"
                                                         << "$a"
                                                         << "path" << 2))),
                       AssertionException,
                       40415);
    ASSERT_THROWS_CODE(createReplaceRoot(createSpec(BSON("path"
                                                         << "$a"))),
                       AssertionException,
                       40415);
}

// Verify that $replaceRoot requires a valid expression as input to the newRoot option.
TEST_F(ReplaceRootSpec, RequiresExpressionForNewRootOption) {
    ASSERT_THROWS_CODE(createReplaceRoot(createSpec(BSONObj())), AssertionException, 40414);
    ASSERT_THROWS(createReplaceRoot(createSpec(BSON("newRoot"
                                                    << "$$$a"))),
                  AssertionException);
    ASSERT_THROWS(createReplaceRoot(createSpec(BSON("newRoot"
                                                    << "$$a"))),
                  AssertionException);
    ASSERT_THROWS(createReplaceRoot(createFullSpec(BSON("$map" << BSON("a" << 1)))),
                  AssertionException);
}

// Verify that newRoot accepts all types of expressions.
TEST_F(ReplaceRootSpec, NewRootAcceptsAllTypesOfExpressions) {
    // Field Path and system variables
    ASSERT_TRUE(createReplaceRoot(createSpec(BSON("newRoot"
                                                  << "$a.b.c.d.e"))));
    ASSERT_TRUE(createReplaceRoot(createSpec(BSON("newRoot"
                                                  << "$$CURRENT"))));

    // Literals
    ASSERT_TRUE(createReplaceRoot(createFullSpec(BSON("$literal" << 1))));

    // Expression Objects
    ASSERT_TRUE(createReplaceRoot(createFullSpec(BSON("a" << BSON("b" << 1)))));

    // Operator Expressions
    ASSERT_TRUE(createReplaceRoot(createFullSpec(BSON("$and"
                                                      << "$a"))));
    ASSERT_TRUE(createReplaceRoot(createFullSpec(BSON("$gt" << BSON_ARRAY("$a" << 1)))));
    ASSERT_TRUE(createReplaceRoot(createFullSpec(BSON("$sqrt"
                                                      << "$a"))));

    // Accumulators
    ASSERT_TRUE(createReplaceRoot(createFullSpec(BSON("$sum"
                                                      << "$a"))));
}

TEST_F(ReplaceRootSpec, ReplaceWithAcceptsAllTypesOfExpressions) {
    // Field Path and system variables
    ASSERT_TRUE(createReplaceWith("$a.b.c.d.e"));
    ASSERT_TRUE(createReplaceWith("$$CURRENT"));

    // Literals
    ASSERT_TRUE(createReplaceWith(BSON("$literal" << 1)));

    // Expression Objects
    ASSERT_TRUE(createReplaceWith(BSON("a" << BSON("b" << 1))));

    // Operator Expressions
    ASSERT_TRUE(createReplaceWith(BSON("$and"
                                       << "$a")));
    ASSERT_TRUE(createReplaceWith(BSON("$gt" << BSON_ARRAY("$a" << 1))));
    ASSERT_TRUE(createReplaceWith(BSON("$sqrt"
                                       << "$a")));

    // Accumulators
    ASSERT_TRUE(createReplaceWith(BSON("$sum"
                                       << "$a")));
}

// Verify that $replaceRoot round trips through serialization.
TEST_F(ReplaceRootSpec, ReplaceRootRoundTrips) {
    auto replaceRoot = createReplaceRoot(createSpec(BSON("newRoot"
                                                         << "$a.b.c.d.e")));
    ASSERT_EQ(replaceRoot->getSourceName(), DocumentSourceReplaceRoot::kStageName);
    std::vector<Value> serialization;
    replaceRoot->serializeToArray(serialization);
    replaceRoot = createReplaceRoot(serialization[0].getDocument().toBson());
    ASSERT_EQ(replaceRoot->getSourceName(), DocumentSourceReplaceRoot::kStageName);
}

// Verify that $replaceWith round trips through serialization.
TEST_F(ReplaceRootSpec, ReplaceWithRoundTrips) {
    auto replaceWith = createReplaceWith("$newRoot");
    // We should always create a stage with the name '$replaceRoot' internally, even if the alias is
    // used.
    ASSERT_EQ(replaceWith->getSourceName(), DocumentSourceReplaceRoot::kStageName);

    std::vector<Value> serialization;
    replaceWith->serializeToArray(serialization);
    replaceWith = createReplaceRoot(serialization[0].getDocument().toBson());
    // While the stage that has round-tripped through serialization should mean the same thing, it
    // will have a different name since it always serializes to the full $replaceRoot syntax.
    ASSERT_EQ(replaceWith->getSourceName(), DocumentSourceReplaceRoot::kStageName);
}

}  // namespace
}  // namespace mongo