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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
|
/**
* Copyright (C) 2014 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/db/query/canonical_query.h"
#include "mongo/client/dbclientinterface.h"
#include "mongo/db/json.h"
#include "mongo/db/matcher/extensions_callback_disallow_extensions.h"
#include "mongo/db/matcher/extensions_callback_noop.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/query/collation/collator_interface_mock.h"
#include "mongo/db/query/index_tag.h"
#include "mongo/db/query/query_test_service_context.h"
#include "mongo/unittest/unittest.h"
namespace mongo {
namespace {
using std::string;
using std::unique_ptr;
using unittest::assertGet;
static const NamespaceString nss("testdb.testcoll");
/**
* Helper function to parse the given BSON object as a MatchExpression, checks the status,
* and return the MatchExpression*.
*/
MatchExpression* parseMatchExpression(const BSONObj& obj) {
const CollatorInterface* collator = nullptr;
StatusWithMatchExpression status =
MatchExpressionParser::parse(obj, ExtensionsCallbackNoop(), collator);
if (!status.isOK()) {
mongoutils::str::stream ss;
ss << "failed to parse query: " << obj.toString()
<< ". Reason: " << status.getStatus().toString();
FAIL(ss);
}
return status.getValue().release();
}
/**
* Helper function which parses and normalizes 'queryStr', and returns whether the given
* (expression tree, lite parsed query) tuple passes CanonicalQuery::isValid().
* Returns Status::OK() if the tuple is valid, else returns an error Status.
*/
Status isValid(const std::string& queryStr, const LiteParsedQuery& lpqRaw) {
BSONObj queryObj = fromjson(queryStr);
unique_ptr<MatchExpression> me(CanonicalQuery::normalizeTree(parseMatchExpression(queryObj)));
return CanonicalQuery::isValid(me.get(), lpqRaw);
}
void assertEquivalent(const char* queryStr,
const MatchExpression* expected,
const MatchExpression* actual) {
if (actual->equivalent(expected)) {
return;
}
mongoutils::str::stream ss;
ss << "Match expressions are not equivalent."
<< "\nOriginal query: " << queryStr << "\nExpected: " << expected->toString()
<< "\nActual: " << actual->toString();
FAIL(ss);
}
void assertNotEquivalent(const char* queryStr,
const MatchExpression* expected,
const MatchExpression* actual) {
if (!actual->equivalent(expected)) {
return;
}
mongoutils::str::stream ss;
ss << "Match expressions are equivalent."
<< "\nOriginal query: " << queryStr << "\nExpected: " << expected->toString()
<< "\nActual: " << actual->toString();
FAIL(ss);
}
TEST(CanonicalQueryTest, IsValidText) {
// Filter inside LiteParsedQuery is not used.
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
ASSERT_OK(lpq->validate());
// Valid: regular TEXT.
ASSERT_OK(isValid("{$text: {$search: 's'}}", *lpq));
// Valid: TEXT inside OR.
ASSERT_OK(
isValid("{$or: ["
" {$text: {$search: 's'}},"
" {a: 1}"
"]}",
*lpq));
// Valid: TEXT outside NOR.
ASSERT_OK(isValid("{$text: {$search: 's'}, $nor: [{a: 1}, {b: 1}]}", *lpq));
// Invalid: TEXT inside NOR.
ASSERT_NOT_OK(isValid("{$nor: [{$text: {$search: 's'}}, {a: 1}]}", *lpq));
// Invalid: TEXT inside NOR.
ASSERT_NOT_OK(
isValid("{$nor: ["
" {$or: ["
" {$text: {$search: 's'}},"
" {a: 1}"
" ]},"
" {a: 2}"
"]}",
*lpq));
// Invalid: >1 TEXT.
ASSERT_NOT_OK(
isValid("{$and: ["
" {$text: {$search: 's'}},"
" {$text: {$search: 't'}}"
"]}",
*lpq));
// Invalid: >1 TEXT.
ASSERT_NOT_OK(
isValid("{$and: ["
" {$or: ["
" {$text: {$search: 's'}},"
" {a: 1}"
" ]},"
" {$or: ["
" {$text: {$search: 't'}},"
" {b: 1}"
" ]}"
"]}",
*lpq));
}
TEST(CanonicalQueryTest, IsValidTextTailable) {
// Filter inside LiteParsedQuery is not used.
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
lpq->setTailable(true);
ASSERT_OK(lpq->validate());
// Invalid: TEXT and tailable.
ASSERT_NOT_OK(isValid("{$text: {$search: 's'}}", *lpq));
}
TEST(CanonicalQueryTest, IsValidGeo) {
// Filter inside LiteParsedQuery is not used.
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
ASSERT_OK(lpq->validate());
// Valid: regular GEO_NEAR.
ASSERT_OK(isValid("{a: {$near: [0, 0]}}", *lpq));
// Valid: GEO_NEAR inside nested AND.
ASSERT_OK(
isValid("{$and: ["
" {$and: ["
" {a: {$near: [0, 0]}},"
" {b: 1}"
" ]},"
" {c: 1}"
"]}",
*lpq));
// Invalid: >1 GEO_NEAR.
ASSERT_NOT_OK(
isValid("{$and: ["
" {a: {$near: [0, 0]}},"
" {b: {$near: [0, 0]}}"
"]}",
*lpq));
// Invalid: >1 GEO_NEAR.
ASSERT_NOT_OK(
isValid("{$and: ["
" {a: {$geoNear: [0, 0]}},"
" {b: {$near: [0, 0]}}"
"]}",
*lpq));
// Invalid: >1 GEO_NEAR.
ASSERT_NOT_OK(
isValid("{$and: ["
" {$and: ["
" {a: {$near: [0, 0]}},"
" {b: 1}"
" ]},"
" {$and: ["
" {c: {$near: [0, 0]}},"
" {d: 1}"
" ]}"
"]}",
*lpq));
// Invalid: GEO_NEAR inside NOR.
ASSERT_NOT_OK(
isValid("{$nor: ["
" {a: {$near: [0, 0]}},"
" {b: 1}"
"]}",
*lpq));
// Invalid: GEO_NEAR inside OR.
ASSERT_NOT_OK(
isValid("{$or: ["
" {a: {$near: [0, 0]}},"
" {b: 1}"
"]}",
*lpq));
}
TEST(CanonicalQueryTest, IsValidTextAndGeo) {
// Filter inside LiteParsedQuery is not used.
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
ASSERT_OK(lpq->validate());
// Invalid: TEXT and GEO_NEAR.
ASSERT_NOT_OK(isValid("{$text: {$search: 's'}, a: {$near: [0, 0]}}", *lpq));
// Invalid: TEXT and GEO_NEAR.
ASSERT_NOT_OK(isValid("{$text: {$search: 's'}, a: {$geoNear: [0, 0]}}", *lpq));
// Invalid: TEXT and GEO_NEAR.
ASSERT_NOT_OK(
isValid("{$or: ["
" {$text: {$search: 's'}},"
" {a: 1}"
" ],"
" b: {$near: [0, 0]}}",
*lpq));
}
TEST(CanonicalQueryTest, IsValidTextAndNaturalAscending) {
// Filter inside LiteParsedQuery is not used.
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
lpq->setSort(fromjson("{$natural: 1}"));
ASSERT_OK(lpq->validate());
// Invalid: TEXT and {$natural: 1} sort order.
ASSERT_NOT_OK(isValid("{$text: {$search: 's'}}", *lpq));
}
TEST(CanonicalQueryTest, IsValidTextAndNaturalDescending) {
// Filter inside LiteParsedQuery is not used.
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
lpq->setSort(fromjson("{$natural: -1}"));
ASSERT_OK(lpq->validate());
// Invalid: TEXT and {$natural: -1} sort order.
ASSERT_NOT_OK(isValid("{$text: {$search: 's'}}", *lpq));
}
TEST(CanonicalQueryTest, IsValidTextAndHint) {
// Filter inside LiteParsedQuery is not used.
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
lpq->setHint(fromjson("{a: 1}"));
ASSERT_OK(lpq->validate());
// Invalid: TEXT and {$natural: -1} sort order.
ASSERT_NOT_OK(isValid("{$text: {$search: 's'}}", *lpq));
}
// SERVER-14366
TEST(CanonicalQueryTest, IsValidGeoNearNaturalSort) {
// Filter inside LiteParsedQuery is not used.
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
lpq->setSort(fromjson("{$natural: 1}"));
ASSERT_OK(lpq->validate());
// Invalid: GEO_NEAR and {$natural: 1} sort order.
ASSERT_NOT_OK(isValid("{a: {$near: {$geometry: {type: 'Point', coordinates: [0, 0]}}}}", *lpq));
}
// SERVER-14366
TEST(CanonicalQueryTest, IsValidGeoNearNaturalHint) {
// Filter inside LiteParsedQuery is not used.
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
lpq->setHint(fromjson("{$natural: 1}"));
ASSERT_OK(lpq->validate());
// Invalid: GEO_NEAR and {$natural: 1} hint.
ASSERT_NOT_OK(isValid("{a: {$near: {$geometry: {type: 'Point', coordinates: [0, 0]}}}}", *lpq));
}
TEST(CanonicalQueryTest, IsValidTextAndSnapshot) {
// Filter inside LiteParsedQuery is not used.
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
lpq->setSnapshot(true);
ASSERT_OK(lpq->validate());
// Invalid: TEXT and snapshot.
ASSERT_NOT_OK(isValid("{$text: {$search: 's'}}", *lpq));
}
TEST(CanonicalQueryTest, IsValidSortKeyMetaProjection) {
QueryTestServiceContext serviceContext;
auto txn = serviceContext.makeOperationContext();
// Passing a sortKey meta-projection without a sort is an error.
{
const bool isExplain = false;
auto lpq = assertGet(LiteParsedQuery::makeFromFindCommand(
nss, fromjson("{find: 'testcoll', projection: {foo: {$meta: 'sortKey'}}}"), isExplain));
auto cq = CanonicalQuery::canonicalize(
txn.get(), std::move(lpq), ExtensionsCallbackDisallowExtensions());
ASSERT_NOT_OK(cq.getStatus());
}
// Should be able to successfully create a CQ when there is a sort.
{
const bool isExplain = false;
auto lpq = assertGet(LiteParsedQuery::makeFromFindCommand(
nss,
fromjson("{find: 'testcoll', projection: {foo: {$meta: 'sortKey'}}, sort: {bar: 1}}"),
isExplain));
auto cq = CanonicalQuery::canonicalize(
txn.get(), std::move(lpq), ExtensionsCallbackDisallowExtensions());
ASSERT_OK(cq.getStatus());
}
}
TEST(CanonicalQueryTest, IsValidNaturalSortIndexHint) {
const bool isExplain = false;
auto lpq = assertGet(LiteParsedQuery::makeFromFindCommand(
nss, fromjson("{find: 'testcoll', sort: {$natural: 1}, hint: {a: 1}}"), isExplain));
// Invalid: {$natural: 1} sort order and index hint.
ASSERT_NOT_OK(isValid("{}", *lpq));
}
TEST(CanonicalQueryTest, IsValidNaturalSortNaturalHint) {
const bool isExplain = false;
auto lpq = assertGet(LiteParsedQuery::makeFromFindCommand(
nss, fromjson("{find: 'testcoll', sort: {$natural: 1}, hint: {$natural: 1}}"), isExplain));
// Valid: {$natural: 1} sort order and {$natural: 1} hint.
ASSERT_OK(isValid("{}", *lpq));
}
TEST(CanonicalQueryTest, IsValidNaturalSortNaturalHintDifferentDirections) {
const bool isExplain = false;
auto lpq = assertGet(LiteParsedQuery::makeFromFindCommand(
nss, fromjson("{find: 'testcoll', sort: {$natural: 1}, hint: {$natural: -1}}"), isExplain));
// Invalid: {$natural: 1} sort order and {$natural: -1} hint.
ASSERT_NOT_OK(isValid("{}", *lpq));
}
//
// Tests for CanonicalQuery::sortTree
//
/**
* Helper function for testing CanonicalQuery::sortTree().
*
* Verifies that sorting the expression 'unsortedQueryStr' yields an expression equivalent to
* the expression 'sortedQueryStr'.
*/
void testSortTree(const char* unsortedQueryStr, const char* sortedQueryStr) {
BSONObj unsortedQueryObj = fromjson(unsortedQueryStr);
unique_ptr<MatchExpression> unsortedQueryExpr(parseMatchExpression(unsortedQueryObj));
BSONObj sortedQueryObj = fromjson(sortedQueryStr);
unique_ptr<MatchExpression> sortedQueryExpr(parseMatchExpression(sortedQueryObj));
// Sanity check that the unsorted expression is not equivalent to the sorted expression.
assertNotEquivalent(unsortedQueryStr, unsortedQueryExpr.get(), sortedQueryExpr.get());
// Sanity check that sorting the sorted expression is a no-op.
{
unique_ptr<MatchExpression> sortedQueryExprClone(parseMatchExpression(sortedQueryObj));
CanonicalQuery::sortTree(sortedQueryExprClone.get());
assertEquivalent(unsortedQueryStr, sortedQueryExpr.get(), sortedQueryExprClone.get());
}
// Test that sorting the unsorted expression yields the sorted expression.
CanonicalQuery::sortTree(unsortedQueryExpr.get());
assertEquivalent(unsortedQueryStr, unsortedQueryExpr.get(), sortedQueryExpr.get());
}
// Test that an EQ expression sorts before a GT expression.
TEST(CanonicalQueryTest, SortTreeMatchTypeComparison) {
testSortTree("{a: {$gt: 1}, a: 1}", "{a: 1, a: {$gt: 1}}");
}
// Test that an EQ expression on path "a" sorts before an EQ expression on path "b".
TEST(CanonicalQueryTest, SortTreePathComparison) {
testSortTree("{b: 1, a: 1}", "{a: 1, b: 1}");
testSortTree("{'a.b': 1, a: 1}", "{a: 1, 'a.b': 1}");
testSortTree("{'a.c': 1, 'a.b': 1}", "{'a.b': 1, 'a.c': 1}");
}
// Test that AND expressions sort according to their first differing child.
TEST(CanonicalQueryTest, SortTreeChildComparison) {
testSortTree("{$or: [{a: 1, c: 1}, {a: 1, b: 1}]}", "{$or: [{a: 1, b: 1}, {a: 1, c: 1}]}");
}
// Test that an AND with 2 children sorts before an AND with 3 children, if the first 2 children
// are equivalent in both.
TEST(CanonicalQueryTest, SortTreeNumChildrenComparison) {
testSortTree("{$or: [{a: 1, b: 1, c: 1}, {a: 1, b: 1}]}",
"{$or: [{a: 1, b: 1}, {a: 1, b: 1, c: 1}]}");
}
/**
* Utility function to create a CanonicalQuery
*/
unique_ptr<CanonicalQuery> canonicalize(const char* queryStr) {
QueryTestServiceContext serviceContext;
auto txn = serviceContext.makeOperationContext();
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
lpq->setFilter(fromjson(queryStr));
auto statusWithCQ = CanonicalQuery::canonicalize(
txn.get(), std::move(lpq), ExtensionsCallbackDisallowExtensions());
ASSERT_OK(statusWithCQ.getStatus());
return std::move(statusWithCQ.getValue());
}
std::unique_ptr<CanonicalQuery> canonicalize(const char* queryStr,
const char* sortStr,
const char* projStr) {
QueryTestServiceContext serviceContext;
auto txn = serviceContext.makeOperationContext();
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
lpq->setFilter(fromjson(queryStr));
lpq->setSort(fromjson(sortStr));
lpq->setProj(fromjson(projStr));
auto statusWithCQ = CanonicalQuery::canonicalize(
txn.get(), std::move(lpq), ExtensionsCallbackDisallowExtensions());
ASSERT_OK(statusWithCQ.getStatus());
return std::move(statusWithCQ.getValue());
}
/**
* Test that CanonicalQuery::isIsolated() returns correctly.
*/
TEST(CanonicalQueryTest, IsIsolatedReturnsTrueWithIsolated) {
unique_ptr<CanonicalQuery> cq = canonicalize("{$isolated: 1, x: 3}");
ASSERT_TRUE(cq->isIsolated());
}
TEST(CanonicalQueryTest, IsIsolatedReturnsTrueWithAtomic) {
unique_ptr<CanonicalQuery> cq = canonicalize("{$atomic: 1, x: 3}");
ASSERT_TRUE(cq->isIsolated());
}
TEST(CanonicalQueryTest, IsIsolatedReturnsFalseWithIsolated) {
unique_ptr<CanonicalQuery> cq = canonicalize("{$isolated: 0, x: 3}");
ASSERT_FALSE(cq->isIsolated());
}
TEST(CanonicalQueryTest, IsIsolatedReturnsFalseWithAtomic) {
unique_ptr<CanonicalQuery> cq = canonicalize("{$atomic: 0, x: 3}");
ASSERT_FALSE(cq->isIsolated());
}
/**
* Test function for CanonicalQuery::normalize.
*/
void testNormalizeQuery(const char* queryStr, const char* expectedExprStr) {
unique_ptr<CanonicalQuery> cq(canonicalize(queryStr));
MatchExpression* me = cq->root();
BSONObj expectedExprObj = fromjson(expectedExprStr);
unique_ptr<MatchExpression> expectedExpr(parseMatchExpression(expectedExprObj));
assertEquivalent(queryStr, expectedExpr.get(), me);
}
TEST(CanonicalQueryTest, NormalizeQuerySort) {
// Field names
testNormalizeQuery("{b: 1, a: 1}", "{a: 1, b: 1}");
// Operator types
testNormalizeQuery("{a: {$gt: 5}, a: {$lt: 10}}}", "{a: {$lt: 10}, a: {$gt: 5}}");
// Nested queries
testNormalizeQuery("{a: {$elemMatch: {c: 1, b:1}}}", "{a: {$elemMatch: {b: 1, c:1}}}");
}
TEST(CanonicalQueryTest, NormalizeQueryTree) {
// Single-child $or elimination.
testNormalizeQuery("{$or: [{b: 1}]}", "{b: 1}");
// Single-child $and elimination.
testNormalizeQuery("{$or: [{$and: [{a: 1}]}, {b: 1}]}", "{$or: [{a: 1}, {b: 1}]}");
// $or absorbs $or children.
testNormalizeQuery("{$or: [{a: 1}, {$or: [{b: 1}, {$or: [{c: 1}]}]}, {d: 1}]}",
"{$or: [{a: 1}, {b: 1}, {c: 1}, {d: 1}]}");
// $and absorbs $and children.
testNormalizeQuery("{$and: [{$and: [{a: 1}, {b: 1}]}, {c: 1}]}",
"{$and: [{a: 1}, {b: 1}, {c: 1}]}");
// $in with one argument is rewritten as an equality or regex predicate.
testNormalizeQuery("{a: {$in: [1]}}", "{a: {$eq: 1}}");
testNormalizeQuery("{a: {$in: [/./]}}", "{a: {$regex: '.'}}");
// $in with 0 or more than 1 argument is not modified.
testNormalizeQuery("{a: {$in: []}}", "{a: {$in: []}}");
testNormalizeQuery("{a: {$in: [/./, 3]}}", "{a: {$in: [/./, 3]}}");
}
TEST(CanonicalQueryTest, NormalizeWithInPreservesTags) {
BSONObj obj = fromjson("{x: {$in: [1]}}");
unique_ptr<MatchExpression> matchExpression(parseMatchExpression(obj));
matchExpression->setTag(new IndexTag(2U, 1U, false));
matchExpression.reset(CanonicalQuery::normalizeTree(matchExpression.release()));
IndexTag* tag = dynamic_cast<IndexTag*>(matchExpression->getTag());
ASSERT(tag);
ASSERT_EQ(2U, tag->index);
}
TEST(CanonicalQueryTest, NormalizeWithInAndRegexPreservesTags) {
BSONObj obj = fromjson("{x: {$in: [/a.b/]}}");
unique_ptr<MatchExpression> matchExpression(parseMatchExpression(obj));
matchExpression->setTag(new IndexTag(2U, 1U, false));
matchExpression.reset(CanonicalQuery::normalizeTree(matchExpression.release()));
IndexTag* tag = dynamic_cast<IndexTag*>(matchExpression->getTag());
ASSERT(tag);
ASSERT_EQ(2U, tag->index);
}
TEST(CanonicalQueryTest, NormalizeWithInPreservesCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
auto inMatchExpression = stdx::make_unique<InMatchExpression>(&collator);
BSONObj obj = fromjson("{'': 'string'}");
inMatchExpression->addEquality(obj.firstElement());
unique_ptr<MatchExpression> matchExpression(
CanonicalQuery::normalizeTree(inMatchExpression.release()));
ASSERT(matchExpression->matchType() == MatchExpression::MatchType::EQ);
EqualityMatchExpression* eqMatchExpression =
static_cast<EqualityMatchExpression*>(matchExpression.get());
ASSERT_EQ(eqMatchExpression->getCollator(), &collator);
}
TEST(CanonicalQueryTest, CanonicalizeFromBaseQuery) {
QueryTestServiceContext serviceContext;
auto txn = serviceContext.makeOperationContext();
const bool isExplain = true;
const std::string cmdStr =
"{find:'bogusns', filter:{$or:[{a:1,b:1},{a:1,c:1}]}, projection:{a:1}, sort:{b:1}}";
auto lpq = assertGet(LiteParsedQuery::makeFromFindCommand(nss, fromjson(cmdStr), isExplain));
auto baseCq = assertGet(CanonicalQuery::canonicalize(
txn.get(), std::move(lpq), ExtensionsCallbackDisallowExtensions()));
MatchExpression* firstClauseExpr = baseCq->root()->getChild(0);
auto childCq = assertGet(CanonicalQuery::canonicalize(
txn.get(), *baseCq, firstClauseExpr, ExtensionsCallbackDisallowExtensions()));
// Descriptive test. The childCq's filter should be the relevant $or clause, rather than the
// entire query predicate.
ASSERT_EQ(childCq->getParsed().getFilter(), baseCq->getParsed().getFilter());
ASSERT_EQ(childCq->getParsed().getProj(), baseCq->getParsed().getProj());
ASSERT_EQ(childCq->getParsed().getSort(), baseCq->getParsed().getSort());
ASSERT_TRUE(childCq->getParsed().isExplain());
}
TEST(CanonicalQueryTest, CanonicalQueryFromLPQWithNoCollation) {
QueryTestServiceContext serviceContext;
auto txn = serviceContext.makeOperationContext();
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
auto cq = assertGet(CanonicalQuery::canonicalize(
txn.get(), std::move(lpq), ExtensionsCallbackDisallowExtensions()));
ASSERT_TRUE(cq->getCollator() == nullptr);
}
TEST(CanonicalQueryTest, CanonicalQueryFromLPQWithCollation) {
QueryTestServiceContext serviceContext;
auto txn = serviceContext.makeOperationContext();
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
lpq->setCollation(BSON("locale"
<< "reverse"));
auto cq = assertGet(CanonicalQuery::canonicalize(
txn.get(), std::move(lpq), ExtensionsCallbackDisallowExtensions()));
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
ASSERT_TRUE(CollatorInterface::collatorsMatch(cq->getCollator(), &collator));
}
TEST(CanonicalQueryTest, CanonicalQueryFromBaseQueryWithNoCollation) {
QueryTestServiceContext serviceContext;
auto txn = serviceContext.makeOperationContext();
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
lpq->setFilter(fromjson("{$or:[{a:1,b:1},{a:1,c:1}]}"));
auto baseCq = assertGet(CanonicalQuery::canonicalize(
txn.get(), std::move(lpq), ExtensionsCallbackDisallowExtensions()));
MatchExpression* firstClauseExpr = baseCq->root()->getChild(0);
auto childCq = assertGet(CanonicalQuery::canonicalize(
txn.get(), *baseCq, firstClauseExpr, ExtensionsCallbackDisallowExtensions()));
ASSERT_TRUE(baseCq->getCollator() == nullptr);
ASSERT_TRUE(childCq->getCollator() == nullptr);
}
TEST(CanonicalQueryTest, CanonicalQueryFromBaseQueryWithCollation) {
QueryTestServiceContext serviceContext;
auto txn = serviceContext.makeOperationContext();
auto lpq = stdx::make_unique<LiteParsedQuery>(nss);
lpq->setFilter(fromjson("{$or:[{a:1,b:1},{a:1,c:1}]}"));
lpq->setCollation(BSON("locale"
<< "reverse"));
auto baseCq = assertGet(CanonicalQuery::canonicalize(
txn.get(), std::move(lpq), ExtensionsCallbackDisallowExtensions()));
MatchExpression* firstClauseExpr = baseCq->root()->getChild(0);
auto childCq = assertGet(CanonicalQuery::canonicalize(
txn.get(), *baseCq, firstClauseExpr, ExtensionsCallbackDisallowExtensions()));
ASSERT(baseCq->getCollator());
ASSERT(childCq->getCollator());
ASSERT_TRUE(*(childCq->getCollator()) == *(baseCq->getCollator()));
}
} // namespace
} // namespace mongo
|