/
expression.cpp
6112 lines (5177 loc) · 233 KB
/
expression.cpp
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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/pipeline/expression.h"
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <cstdio>
#include <pcrecpp.h>
#include <utility>
#include <vector>
#include "mongo/db/commands/feature_compatibility_version_documentation.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/pipeline/document.h"
#include "mongo/db/pipeline/expression_context.h"
#include "mongo/db/pipeline/value.h"
#include "mongo/db/query/datetime/date_time_support.h"
#include "mongo/platform/bits.h"
#include "mongo/platform/decimal128.h"
#include "mongo/util/regex_util.h"
#include "mongo/util/str.h"
#include "mongo/util/string_map.h"
#include "mongo/util/summation.h"
namespace mongo {
using Parser = Expression::Parser;
using boost::intrusive_ptr;
using std::map;
using std::move;
using std::pair;
using std::set;
using std::string;
using std::vector;
/// Helper function to easily wrap constants with $const.
static Value serializeConstant(Value val) {
if (val.missing()) {
return Value("$$REMOVE"_sd);
}
return Value(DOC("$const" << val));
}
/* --------------------------- Expression ------------------------------ */
string Expression::removeFieldPrefix(const string& prefixedField) {
uassert(16419,
str::stream() << "field path must not contain embedded null characters",
prefixedField.find('\0') == string::npos);
const char* pPrefixedField = prefixedField.c_str();
uassert(15982,
str::stream() << "field path references must be prefixed with a '$' ('" << prefixedField
<< "'",
pPrefixedField[0] == '$');
return string(pPrefixedField + 1);
}
intrusive_ptr<Expression> Expression::parseObject(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONObj obj,
const VariablesParseState& vps) {
if (obj.isEmpty()) {
return ExpressionObject::create(expCtx, {}, {});
}
if (obj.firstElementFieldName()[0] == '$') {
// Assume this is an expression like {$add: [...]}.
return parseExpression(expCtx, obj, vps);
}
return ExpressionObject::parse(expCtx, obj, vps);
}
namespace {
struct ParserRegistration {
Parser parser;
boost::optional<ServerGlobalParams::FeatureCompatibility::Version> requiredMinVersion;
};
StringMap<ParserRegistration> parserMap;
} // namespace
void Expression::registerExpression(
string key,
Parser parser,
boost::optional<ServerGlobalParams::FeatureCompatibility::Version> requiredMinVersion) {
auto op = parserMap.find(key);
massert(17064,
str::stream() << "Duplicate expression (" << key << ") registered.",
op == parserMap.end());
parserMap[key] = {parser, requiredMinVersion};
}
intrusive_ptr<Expression> Expression::parseExpression(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONObj obj,
const VariablesParseState& vps) {
uassert(15983,
str::stream() << "An object representing an expression must have exactly one "
"field: "
<< obj.toString(),
obj.nFields() == 1);
// Look up the parser associated with the expression name.
const char* opName = obj.firstElementFieldName();
auto it = parserMap.find(opName);
uassert(ErrorCodes::InvalidPipelineOperator,
str::stream() << "Unrecognized expression '" << opName << "'",
it != parserMap.end());
// Make sure we are allowed to use this expression under the current feature compatibility
// version.
auto& entry = it->second;
uassert(ErrorCodes::QueryFeatureNotAllowed,
// TODO SERVER-31968 we would like to include the current version and the required
// minimum version in this error message, but using
// FeatureCompatibilityVersion::toString() would introduce a dependency cycle.
str::stream() << opName
<< " is not allowed in the current feature compatibility version. See "
<< feature_compatibility_version_documentation::kCompatibilityLink
<< " for more information.",
!expCtx->maxFeatureCompatibilityVersion || !entry.requiredMinVersion ||
(*entry.requiredMinVersion <= *expCtx->maxFeatureCompatibilityVersion));
return entry.parser(expCtx, obj.firstElement(), vps);
}
Expression::ExpressionVector ExpressionNary::parseArguments(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement exprElement,
const VariablesParseState& vps) {
ExpressionVector out;
if (exprElement.type() == Array) {
BSONForEach(elem, exprElement.Obj()) {
out.push_back(Expression::parseOperand(expCtx, elem, vps));
}
} else { // Assume it's an operand that accepts a single argument.
out.push_back(Expression::parseOperand(expCtx, exprElement, vps));
}
return out;
}
intrusive_ptr<Expression> Expression::parseOperand(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement exprElement,
const VariablesParseState& vps) {
BSONType type = exprElement.type();
if (type == String && exprElement.valuestr()[0] == '$') {
/* if we got here, this is a field path expression */
return ExpressionFieldPath::parse(expCtx, exprElement.str(), vps);
} else if (type == Object) {
return Expression::parseObject(expCtx, exprElement.Obj(), vps);
} else if (type == Array) {
return ExpressionArray::parse(expCtx, exprElement, vps);
} else {
return ExpressionConstant::parse(expCtx, exprElement, vps);
}
}
namespace {
/**
* UTF-8 multi-byte code points consist of one leading byte of the form 11xxxxxx, and potentially
* many continuation bytes of the form 10xxxxxx. This method checks whether 'charByte' is a leading
* byte.
*/
bool isLeadingByte(char charByte) {
return (charByte & 0xc0) == 0xc0;
}
/**
* UTF-8 single-byte code points are of the form 0xxxxxxx. This method checks whether 'charByte' is
* a single-byte code point.
*/
bool isSingleByte(char charByte) {
return (charByte & 0x80) == 0x0;
}
size_t getCodePointLength(char charByte) {
if (isSingleByte(charByte)) {
return 1;
}
invariant(isLeadingByte(charByte));
// In UTF-8, the number of leading ones is the number of bytes the code point takes up.
return countLeadingZeros64(~(uint64_t(charByte) << (64 - 8)));
}
} // namespace
/* ------------------------- Register Date Expressions ----------------------------- */
REGISTER_EXPRESSION(dayOfMonth, ExpressionDayOfMonth::parse);
REGISTER_EXPRESSION(dayOfWeek, ExpressionDayOfWeek::parse);
REGISTER_EXPRESSION(dayOfYear, ExpressionDayOfYear::parse);
REGISTER_EXPRESSION(hour, ExpressionHour::parse);
REGISTER_EXPRESSION(isoDayOfWeek, ExpressionIsoDayOfWeek::parse);
REGISTER_EXPRESSION(isoWeek, ExpressionIsoWeek::parse);
REGISTER_EXPRESSION(isoWeekYear, ExpressionIsoWeekYear::parse);
REGISTER_EXPRESSION(millisecond, ExpressionMillisecond::parse);
REGISTER_EXPRESSION(minute, ExpressionMinute::parse);
REGISTER_EXPRESSION(month, ExpressionMonth::parse);
REGISTER_EXPRESSION(second, ExpressionSecond::parse);
REGISTER_EXPRESSION(week, ExpressionWeek::parse);
REGISTER_EXPRESSION(year, ExpressionYear::parse);
/* ----------------------- ExpressionAbs ---------------------------- */
Value ExpressionAbs::evaluateNumericArg(const Value& numericArg) const {
BSONType type = numericArg.getType();
if (type == NumberDouble) {
return Value(std::abs(numericArg.getDouble()));
} else if (type == NumberDecimal) {
return Value(numericArg.getDecimal().toAbs());
} else {
long long num = numericArg.getLong();
uassert(28680,
"can't take $abs of long long min",
num != std::numeric_limits<long long>::min());
long long absVal = std::abs(num);
return type == NumberLong ? Value(absVal) : Value::createIntOrLong(absVal);
}
}
REGISTER_EXPRESSION(abs, ExpressionAbs::parse);
const char* ExpressionAbs::getOpName() const {
return "$abs";
}
/* ------------------------- ExpressionAdd ----------------------------- */
Value ExpressionAdd::evaluate(const Document& root, Variables* variables) const {
// We'll try to return the narrowest possible result value while avoiding overflow, loss
// of precision due to intermediate rounding or implicit use of decimal types. To do that,
// compute a compensated sum for non-decimal values and a separate decimal sum for decimal
// values, and track the current narrowest type.
DoubleDoubleSummation nonDecimalTotal;
Decimal128 decimalTotal;
BSONType totalType = NumberInt;
bool haveDate = false;
const size_t n = _children.size();
for (size_t i = 0; i < n; ++i) {
Value val = _children[i]->evaluate(root, variables);
switch (val.getType()) {
case NumberDecimal:
decimalTotal = decimalTotal.add(val.getDecimal());
totalType = NumberDecimal;
break;
case NumberDouble:
nonDecimalTotal.addDouble(val.getDouble());
if (totalType != NumberDecimal)
totalType = NumberDouble;
break;
case NumberLong:
nonDecimalTotal.addLong(val.getLong());
if (totalType == NumberInt)
totalType = NumberLong;
break;
case NumberInt:
nonDecimalTotal.addDouble(val.getInt());
break;
case Date:
uassert(16612, "only one date allowed in an $add expression", !haveDate);
haveDate = true;
nonDecimalTotal.addLong(val.getDate().toMillisSinceEpoch());
break;
default:
uassert(16554,
str::stream() << "$add only supports numeric or date types, not "
<< typeName(val.getType()),
val.nullish());
return Value(BSONNULL);
}
}
if (haveDate) {
int64_t longTotal;
if (totalType == NumberDecimal) {
longTotal = decimalTotal.add(nonDecimalTotal.getDecimal()).toLong();
} else {
uassert(ErrorCodes::Overflow, "date overflow in $add", nonDecimalTotal.fitsLong());
longTotal = nonDecimalTotal.getLong();
}
return Value(Date_t::fromMillisSinceEpoch(longTotal));
}
switch (totalType) {
case NumberDecimal:
return Value(decimalTotal.add(nonDecimalTotal.getDecimal()));
case NumberLong:
dassert(nonDecimalTotal.isInteger());
if (nonDecimalTotal.fitsLong())
return Value(nonDecimalTotal.getLong());
// Fallthrough.
case NumberInt:
if (nonDecimalTotal.fitsLong())
return Value::createIntOrLong(nonDecimalTotal.getLong());
// Fallthrough.
case NumberDouble:
return Value(nonDecimalTotal.getDouble());
default:
massert(16417, "$add resulted in a non-numeric type", false);
}
}
REGISTER_EXPRESSION(add, ExpressionAdd::parse);
const char* ExpressionAdd::getOpName() const {
return "$add";
}
/* ------------------------- ExpressionAllElementsTrue -------------------------- */
Value ExpressionAllElementsTrue::evaluate(const Document& root, Variables* variables) const {
const Value arr = _children[0]->evaluate(root, variables);
uassert(17040,
str::stream() << getOpName() << "'s argument must be an array, but is "
<< typeName(arr.getType()),
arr.isArray());
const vector<Value>& array = arr.getArray();
for (vector<Value>::const_iterator it = array.begin(); it != array.end(); ++it) {
if (!it->coerceToBool()) {
return Value(false);
}
}
return Value(true);
}
REGISTER_EXPRESSION(allElementsTrue, ExpressionAllElementsTrue::parse);
const char* ExpressionAllElementsTrue::getOpName() const {
return "$allElementsTrue";
}
/* ------------------------- ExpressionAnd ----------------------------- */
intrusive_ptr<Expression> ExpressionAnd::optimize() {
/* optimize the conjunction as much as possible */
intrusive_ptr<Expression> pE(ExpressionNary::optimize());
/* if the result isn't a conjunction, we can't do anything */
ExpressionAnd* pAnd = dynamic_cast<ExpressionAnd*>(pE.get());
if (!pAnd)
return pE;
/*
Check the last argument on the result; if it's not constant (as
promised by ExpressionNary::optimize(),) then there's nothing
we can do.
*/
const size_t n = pAnd->_children.size();
// ExpressionNary::optimize() generates an ExpressionConstant for {$and:[]}.
verify(n > 0);
intrusive_ptr<Expression> pLast(pAnd->_children[n - 1]);
const ExpressionConstant* pConst = dynamic_cast<ExpressionConstant*>(pLast.get());
if (!pConst)
return pE;
/*
Evaluate and coerce the last argument to a boolean. If it's false,
then we can replace this entire expression.
*/
bool last = pConst->getValue().coerceToBool();
if (!last) {
intrusive_ptr<ExpressionConstant> pFinal(
ExpressionConstant::create(getExpressionContext(), Value(false)));
return pFinal;
}
/*
If we got here, the final operand was true, so we don't need it
anymore. If there was only one other operand, we don't need the
conjunction either. Note we still need to keep the promise that
the result will be a boolean.
*/
if (n == 2) {
intrusive_ptr<Expression> pFinal(
ExpressionCoerceToBool::create(getExpressionContext(), std::move(pAnd->_children[0])));
return pFinal;
}
/*
Remove the final "true" value, and return the new expression.
CW TODO:
Note that because of any implicit conversions, we may need to
apply an implicit boolean conversion.
*/
pAnd->_children.resize(n - 1);
return pE;
}
Value ExpressionAnd::evaluate(const Document& root, Variables* variables) const {
const size_t n = _children.size();
for (size_t i = 0; i < n; ++i) {
Value pValue(_children[i]->evaluate(root, variables));
if (!pValue.coerceToBool())
return Value(false);
}
return Value(true);
}
REGISTER_EXPRESSION(and, ExpressionAnd::parse);
const char* ExpressionAnd::getOpName() const {
return "$and";
}
/* ------------------------- ExpressionAnyElementTrue -------------------------- */
Value ExpressionAnyElementTrue::evaluate(const Document& root, Variables* variables) const {
const Value arr = _children[0]->evaluate(root, variables);
uassert(17041,
str::stream() << getOpName() << "'s argument must be an array, but is "
<< typeName(arr.getType()),
arr.isArray());
const vector<Value>& array = arr.getArray();
for (vector<Value>::const_iterator it = array.begin(); it != array.end(); ++it) {
if (it->coerceToBool()) {
return Value(true);
}
}
return Value(false);
}
REGISTER_EXPRESSION(anyElementTrue, ExpressionAnyElementTrue::parse);
const char* ExpressionAnyElementTrue::getOpName() const {
return "$anyElementTrue";
}
/* ---------------------- ExpressionArray --------------------------- */
Value ExpressionArray::evaluate(const Document& root, Variables* variables) const {
vector<Value> values;
values.reserve(_children.size());
for (auto&& expr : _children) {
Value elemVal = expr->evaluate(root, variables);
values.push_back(elemVal.missing() ? Value(BSONNULL) : std::move(elemVal));
}
return Value(std::move(values));
}
Value ExpressionArray::serialize(bool explain) const {
vector<Value> expressions;
expressions.reserve(_children.size());
for (auto&& expr : _children) {
expressions.push_back(expr->serialize(explain));
}
return Value(std::move(expressions));
}
intrusive_ptr<Expression> ExpressionArray::optimize() {
bool allValuesConstant = true;
for (auto&& expr : _children) {
expr = expr->optimize();
if (!dynamic_cast<ExpressionConstant*>(expr.get())) {
allValuesConstant = false;
}
}
// If all values in ExpressionArray are constant evaluate to ExpressionConstant.
if (allValuesConstant) {
return ExpressionConstant::create(
getExpressionContext(), evaluate(Document(), &(getExpressionContext()->variables)));
}
return this;
}
const char* ExpressionArray::getOpName() const {
// This should never be called, but is needed to inherit from ExpressionNary.
return "$array";
}
/* ------------------------- ExpressionArrayElemAt -------------------------- */
Value ExpressionArrayElemAt::evaluate(const Document& root, Variables* variables) const {
const Value array = _children[0]->evaluate(root, variables);
const Value indexArg = _children[1]->evaluate(root, variables);
if (array.nullish() || indexArg.nullish()) {
return Value(BSONNULL);
}
uassert(28689,
str::stream() << getOpName() << "'s first argument must be an array, but is "
<< typeName(array.getType()),
array.isArray());
uassert(28690,
str::stream() << getOpName() << "'s second argument must be a numeric value,"
<< " but is " << typeName(indexArg.getType()),
indexArg.numeric());
uassert(28691,
str::stream() << getOpName() << "'s second argument must be representable as"
<< " a 32-bit integer: " << indexArg.coerceToDouble(),
indexArg.integral());
long long i = indexArg.coerceToLong();
if (i < 0 && static_cast<size_t>(std::abs(i)) > array.getArrayLength()) {
// Positive indices that are too large are handled automatically by Value.
return Value();
} else if (i < 0) {
// Index from the back of the array.
i = array.getArrayLength() + i;
}
const size_t index = static_cast<size_t>(i);
return array[index];
}
REGISTER_EXPRESSION(arrayElemAt, ExpressionArrayElemAt::parse);
const char* ExpressionArrayElemAt::getOpName() const {
return "$arrayElemAt";
}
/* ------------------------- ExpressionObjectToArray -------------------------- */
Value ExpressionObjectToArray::evaluate(const Document& root, Variables* variables) const {
const Value targetVal = _children[0]->evaluate(root, variables);
if (targetVal.nullish()) {
return Value(BSONNULL);
}
uassert(40390,
str::stream() << "$objectToArray requires a document input, found: "
<< typeName(targetVal.getType()),
(targetVal.getType() == BSONType::Object));
vector<Value> output;
FieldIterator iter = targetVal.getDocument().fieldIterator();
while (iter.more()) {
Document::FieldPair pair = iter.next();
MutableDocument keyvalue;
keyvalue.addField("k", Value(pair.first));
keyvalue.addField("v", pair.second);
output.push_back(keyvalue.freezeToValue());
}
return Value(output);
}
REGISTER_EXPRESSION(objectToArray, ExpressionObjectToArray::parse);
const char* ExpressionObjectToArray::getOpName() const {
return "$objectToArray";
}
/* ------------------------- ExpressionArrayToObject -------------------------- */
Value ExpressionArrayToObject::evaluate(const Document& root, Variables* variables) const {
const Value input = _children[0]->evaluate(root, variables);
if (input.nullish()) {
return Value(BSONNULL);
}
uassert(40386,
str::stream() << "$arrayToObject requires an array input, found: "
<< typeName(input.getType()),
input.isArray());
MutableDocument output;
const vector<Value>& array = input.getArray();
if (array.empty()) {
return output.freezeToValue();
}
// There are two accepted input formats in an array: [ [key, val] ] or [ {k:key, v:val} ]. The
// first array element determines the format for the rest of the array. Mixing input formats is
// not allowed.
bool inputArrayFormat;
if (array[0].isArray()) {
inputArrayFormat = true;
} else if (array[0].getType() == BSONType::Object) {
inputArrayFormat = false;
} else {
uasserted(40398,
str::stream() << "Unrecognised input type format for $arrayToObject: "
<< typeName(array[0].getType()));
}
for (auto&& elem : array) {
if (inputArrayFormat == true) {
uassert(
40396,
str::stream() << "$arrayToObject requires a consistent input format. Elements must"
"all be arrays or all be objects. Array was detected, now found: "
<< typeName(elem.getType()),
elem.isArray());
const vector<Value>& valArray = elem.getArray();
uassert(40397,
str::stream() << "$arrayToObject requires an array of size 2 arrays,"
"found array of size: "
<< valArray.size(),
(valArray.size() == 2));
uassert(40395,
str::stream() << "$arrayToObject requires an array of key-value pairs, where "
"the key must be of type string. Found key type: "
<< typeName(valArray[0].getType()),
(valArray[0].getType() == BSONType::String));
output[valArray[0].getString()] = valArray[1];
} else {
uassert(
40391,
str::stream() << "$arrayToObject requires a consistent input format. Elements must"
"all be arrays or all be objects. Object was detected, now found: "
<< typeName(elem.getType()),
(elem.getType() == BSONType::Object));
uassert(40392,
str::stream() << "$arrayToObject requires an object keys of 'k' and 'v'. "
"Found incorrect number of keys:"
<< elem.getDocument().size(),
(elem.getDocument().size() == 2));
Value key = elem.getDocument().getField("k");
Value value = elem.getDocument().getField("v");
uassert(40393,
str::stream() << "$arrayToObject requires an object with keys 'k' and 'v'. "
"Missing either or both keys from: "
<< elem.toString(),
(!key.missing() && !value.missing()));
uassert(
40394,
str::stream() << "$arrayToObject requires an object with keys 'k' and 'v', where "
"the value of 'k' must be of type string. Found type: "
<< typeName(key.getType()),
(key.getType() == BSONType::String));
output[key.getString()] = value;
}
}
return output.freezeToValue();
}
REGISTER_EXPRESSION(arrayToObject, ExpressionArrayToObject::parse);
const char* ExpressionArrayToObject::getOpName() const {
return "$arrayToObject";
}
/* ------------------------- ExpressionCeil -------------------------- */
Value ExpressionCeil::evaluateNumericArg(const Value& numericArg) const {
// There's no point in taking the ceiling of integers or longs, it will have no effect.
switch (numericArg.getType()) {
case NumberDouble:
return Value(std::ceil(numericArg.getDouble()));
case NumberDecimal:
// Round toward the nearest decimal with a zero exponent in the positive direction.
return Value(numericArg.getDecimal().quantize(Decimal128::kNormalizedZero,
Decimal128::kRoundTowardPositive));
default:
return numericArg;
}
}
REGISTER_EXPRESSION(ceil, ExpressionCeil::parse);
const char* ExpressionCeil::getOpName() const {
return "$ceil";
}
/* -------------------- ExpressionCoerceToBool ------------------------- */
intrusive_ptr<ExpressionCoerceToBool> ExpressionCoerceToBool::create(
const intrusive_ptr<ExpressionContext>& expCtx, intrusive_ptr<Expression> pExpression) {
return new ExpressionCoerceToBool(expCtx, std::move(pExpression));
}
ExpressionCoerceToBool::ExpressionCoerceToBool(const intrusive_ptr<ExpressionContext>& expCtx,
intrusive_ptr<Expression> pExpression)
: Expression(expCtx, {std::move(pExpression)}), pExpression(_children[0]) {}
intrusive_ptr<Expression> ExpressionCoerceToBool::optimize() {
/* optimize the operand */
pExpression = pExpression->optimize();
/* if the operand already produces a boolean, then we don't need this */
/* LATER - Expression to support a "typeof" query? */
Expression* pE = pExpression.get();
if (dynamic_cast<ExpressionAnd*>(pE) || dynamic_cast<ExpressionOr*>(pE) ||
dynamic_cast<ExpressionNot*>(pE) || dynamic_cast<ExpressionCoerceToBool*>(pE))
return pExpression;
return intrusive_ptr<Expression>(this);
}
void ExpressionCoerceToBool::_doAddDependencies(DepsTracker* deps) const {
pExpression->addDependencies(deps);
}
Value ExpressionCoerceToBool::evaluate(const Document& root, Variables* variables) const {
Value pResult(pExpression->evaluate(root, variables));
bool b = pResult.coerceToBool();
if (b)
return Value(true);
return Value(false);
}
Value ExpressionCoerceToBool::serialize(bool explain) const {
// When not explaining, serialize to an $and expression. When parsed, the $and expression
// will be optimized back into a ExpressionCoerceToBool.
const char* name = explain ? "$coerceToBool" : "$and";
return Value(DOC(name << DOC_ARRAY(pExpression->serialize(explain))));
}
/* ----------------------- ExpressionCompare --------------------------- */
namespace {
struct BoundOp {
ExpressionCompare::CmpOp op;
auto operator()(const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement bsonExpr,
const VariablesParseState& vps) const {
return ExpressionCompare::parse(expCtx, std::move(bsonExpr), vps, op);
}
};
} // namespace
REGISTER_EXPRESSION(cmp, BoundOp{ExpressionCompare::CMP});
REGISTER_EXPRESSION(eq, BoundOp{ExpressionCompare::EQ});
REGISTER_EXPRESSION(gt, BoundOp{ExpressionCompare::GT});
REGISTER_EXPRESSION(gte, BoundOp{ExpressionCompare::GTE});
REGISTER_EXPRESSION(lt, BoundOp{ExpressionCompare::LT});
REGISTER_EXPRESSION(lte, BoundOp{ExpressionCompare::LTE});
REGISTER_EXPRESSION(ne, BoundOp{ExpressionCompare::NE});
intrusive_ptr<Expression> ExpressionCompare::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement bsonExpr,
const VariablesParseState& vps,
CmpOp op) {
intrusive_ptr<ExpressionCompare> expr = new ExpressionCompare(expCtx, op);
ExpressionVector args = parseArguments(expCtx, bsonExpr, vps);
expr->validateArguments(args);
expr->_children = args;
return expr;
}
boost::intrusive_ptr<ExpressionCompare> ExpressionCompare::create(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
CmpOp cmpOp,
const boost::intrusive_ptr<Expression>& exprLeft,
const boost::intrusive_ptr<Expression>& exprRight) {
boost::intrusive_ptr<ExpressionCompare> expr = new ExpressionCompare(expCtx, cmpOp);
expr->_children = {exprLeft, exprRight};
return expr;
}
namespace {
// Lookup table for truth value returns
struct CmpLookup {
const bool truthValue[3]; // truth value for -1, 0, 1
const ExpressionCompare::CmpOp reverse; // reverse(b,a) returns the same as op(a,b)
const char name[5]; // string name with trailing '\0'
};
static const CmpLookup cmpLookup[7] = {
/* -1 0 1 reverse name */
/* EQ */ {{false, true, false}, ExpressionCompare::EQ, "$eq"},
/* NE */ {{true, false, true}, ExpressionCompare::NE, "$ne"},
/* GT */ {{false, false, true}, ExpressionCompare::LT, "$gt"},
/* GTE */ {{false, true, true}, ExpressionCompare::LTE, "$gte"},
/* LT */ {{true, false, false}, ExpressionCompare::GT, "$lt"},
/* LTE */ {{true, true, false}, ExpressionCompare::GTE, "$lte"},
// CMP is special. Only name is used.
/* CMP */ {{false, false, false}, ExpressionCompare::CMP, "$cmp"},
};
} // namespace
Value ExpressionCompare::evaluate(const Document& root, Variables* variables) const {
Value pLeft(_children[0]->evaluate(root, variables));
Value pRight(_children[1]->evaluate(root, variables));
int cmp = getExpressionContext()->getValueComparator().compare(pLeft, pRight);
// Make cmp one of 1, 0, or -1.
if (cmp == 0) {
// leave as 0
} else if (cmp < 0) {
cmp = -1;
} else if (cmp > 0) {
cmp = 1;
}
if (cmpOp == CMP)
return Value(cmp);
bool returnValue = cmpLookup[cmpOp].truthValue[cmp + 1];
return Value(returnValue);
}
const char* ExpressionCompare::getOpName() const {
return cmpLookup[cmpOp].name;
}
/* ------------------------- ExpressionConcat ----------------------------- */
Value ExpressionConcat::evaluate(const Document& root, Variables* variables) const {
const size_t n = _children.size();
StringBuilder result;
for (size_t i = 0; i < n; ++i) {
Value val = _children[i]->evaluate(root, variables);
if (val.nullish())
return Value(BSONNULL);
uassert(16702,
str::stream() << "$concat only supports strings, not " << typeName(val.getType()),
val.getType() == String);
result << val.coerceToString();
}
return Value(result.str());
}
REGISTER_EXPRESSION(concat, ExpressionConcat::parse);
const char* ExpressionConcat::getOpName() const {
return "$concat";
}
/* ------------------------- ExpressionConcatArrays ----------------------------- */
Value ExpressionConcatArrays::evaluate(const Document& root, Variables* variables) const {
const size_t n = _children.size();
vector<Value> values;
for (size_t i = 0; i < n; ++i) {
Value val = _children[i]->evaluate(root, variables);
if (val.nullish()) {
return Value(BSONNULL);
}
uassert(28664,
str::stream() << "$concatArrays only supports arrays, not "
<< typeName(val.getType()),
val.isArray());
const auto& subValues = val.getArray();
values.insert(values.end(), subValues.begin(), subValues.end());
}
return Value(std::move(values));
}
REGISTER_EXPRESSION(concatArrays, ExpressionConcatArrays::parse);
const char* ExpressionConcatArrays::getOpName() const {
return "$concatArrays";
}
/* ----------------------- ExpressionCond ------------------------------ */
Value ExpressionCond::evaluate(const Document& root, Variables* variables) const {
Value pCond(_children[0]->evaluate(root, variables));
int idx = pCond.coerceToBool() ? 1 : 2;
return _children[idx]->evaluate(root, variables);
}
intrusive_ptr<Expression> ExpressionCond::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vps) {
if (expr.type() != Object) {
return Base::parse(expCtx, expr, vps);
}
verify(expr.fieldNameStringData() == "$cond");
intrusive_ptr<ExpressionCond> ret = new ExpressionCond(expCtx);
ret->_children.resize(3);
const BSONObj args = expr.embeddedObject();
BSONForEach(arg, args) {
if (arg.fieldNameStringData() == "if") {
ret->_children[0] = parseOperand(expCtx, arg, vps);
} else if (arg.fieldNameStringData() == "then") {
ret->_children[1] = parseOperand(expCtx, arg, vps);
} else if (arg.fieldNameStringData() == "else") {
ret->_children[2] = parseOperand(expCtx, arg, vps);
} else {
uasserted(17083,
str::stream() << "Unrecognized parameter to $cond: " << arg.fieldName());
}
}
uassert(17080, "Missing 'if' parameter to $cond", ret->_children[0]);
uassert(17081, "Missing 'then' parameter to $cond", ret->_children[1]);
uassert(17082, "Missing 'else' parameter to $cond", ret->_children[2]);
return ret;
}
REGISTER_EXPRESSION(cond, ExpressionCond::parse);
const char* ExpressionCond::getOpName() const {
return "$cond";
}
/* ---------------------- ExpressionConstant --------------------------- */
intrusive_ptr<Expression> ExpressionConstant::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement exprElement,
const VariablesParseState& vps) {
return new ExpressionConstant(expCtx, Value(exprElement));
}
intrusive_ptr<ExpressionConstant> ExpressionConstant::create(
const intrusive_ptr<ExpressionContext>& expCtx, const Value& value) {
intrusive_ptr<ExpressionConstant> pEC(new ExpressionConstant(expCtx, value));
return pEC;
}
ExpressionConstant::ExpressionConstant(const boost::intrusive_ptr<ExpressionContext>& expCtx,
const Value& value)
: Expression(expCtx), _value(value) {}
intrusive_ptr<Expression> ExpressionConstant::optimize() {
/* nothing to do */
return intrusive_ptr<Expression>(this);
}
void ExpressionConstant::_doAddDependencies(DepsTracker* deps) const {
/* nothing to do */
}
Value ExpressionConstant::evaluate(const Document& root, Variables* variables) const {
return _value;
}
Value ExpressionConstant::serialize(bool explain) const {
return serializeConstant(_value);
}
REGISTER_EXPRESSION(const, ExpressionConstant::parse);
REGISTER_EXPRESSION(literal, ExpressionConstant::parse); // alias
const char* ExpressionConstant::getOpName() const {
return "$const";
}
/* ---------------------- ExpressionDateFromParts ----------------------- */
/* Helper functions also shared with ExpressionDateToParts */
namespace {
boost::optional<TimeZone> makeTimeZone(const TimeZoneDatabase* tzdb,
const Document& root,
const Expression* timeZone,
Variables* variables) {
invariant(tzdb);
if (!timeZone) {
return mongo::TimeZoneDatabase::utcZone();
}
auto timeZoneId = timeZone->evaluate(root, variables);
if (timeZoneId.nullish()) {
return boost::none;
}