-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
bsoncolumn_test.cpp
7994 lines (6657 loc) · 296 KB
/
bsoncolumn_test.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) 2021-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/bson/bsonelement.h"
#include "mongo/bson/util/bsoncolumn.h"
#include <absl/numeric/int128.h>
#include <boost/cstdint.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/none.hpp>
#include <boost/optional/optional.hpp>
// IWYU pragma: no_include "ext/alloc_traits.h"
#include <array>
#include <cstdint>
#include <cstring>
#include <forward_list>
#include <limits>
#include <string>
#include "mongo/base/error_codes.h"
#include "mongo/bson/bsonmisc.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/bson/bsontypes_util.h"
#include "mongo/bson/oid.h"
#include "mongo/bson/timestamp.h"
#include "mongo/bson/util/bsoncolumnbuilder.h"
#include "mongo/bson/util/builder.h"
#include "mongo/bson/util/simple8b_builder.h"
#include "mongo/db/exec/sbe/values/bsoncolumn_materializer.h"
#include "mongo/platform/decimal128.h"
#include "mongo/unittest/assert.h"
#include "mongo/unittest/framework.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/base64.h"
#include "mongo/util/time_support.h"
using namespace mongo::bsoncolumn;
namespace mongo {
namespace {
void assertBinaryEqual(BSONBinData finalizedColumn, const BufBuilder& buffer) {
ASSERT_EQ(finalizedColumn.type, BinDataType::Column);
ASSERT_EQ(finalizedColumn.length, buffer.len());
ASSERT_EQ(memcmp(finalizedColumn.data, buffer.buf(), finalizedColumn.length), 0);
}
class BSONColumnTest : public unittest::Test {
public:
BSONElement createBSONColumn(const char* buffer, int size) {
BSONObjBuilder ob;
ob.appendBinData(""_sd, size, BinDataType::Column, buffer);
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
template <typename T>
BSONElement _createElement(T val) {
BSONObjBuilder ob;
ob.append("0"_sd, val);
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
BSONElement createElementDouble(double val) {
BSONObjBuilder ob;
ob.append("0"_sd, val);
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
BSONElement createObjectId(OID val) {
return _createElement(val);
}
BSONElement createTimestamp(Timestamp val) {
return _createElement(val);
}
BSONElement createElementInt64(int64_t val) {
return _createElement(val);
}
BSONElement createElementInt32(int32_t val) {
return _createElement(val);
}
BSONElement createElementDecimal128(Decimal128 val) {
return _createElement(val);
}
BSONElement createDate(Date_t dt) {
return _createElement(dt);
}
BSONElement createBool(bool b) {
return _createElement(b);
}
BSONElement createElementMinKey() {
BSONObjBuilder ob;
ob.appendMinKey("0"_sd);
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
BSONElement createElementMaxKey() {
BSONObjBuilder ob;
ob.appendMaxKey("0"_sd);
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
BSONElement createNull() {
BSONObjBuilder ob;
ob.appendNull("0"_sd);
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
BSONElement createUndefined() {
BSONObjBuilder ob;
ob.appendUndefined("0"_sd);
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
BSONElement createRegex(StringData options = "") {
BSONObjBuilder ob;
ob.appendRegex("0"_sd, options);
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
BSONElement createDBRef(StringData ns, const OID& oid) {
BSONObjBuilder ob;
ob.appendDBRef("0"_sd, ns, oid);
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
BSONElement createElementCode(StringData code) {
BSONObjBuilder ob;
ob.appendCode("0"_sd, code);
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
BSONElement createCodeWScope(StringData code, const BSONObj& scope) {
BSONObjBuilder ob;
ob.appendCodeWScope("0"_sd, code, scope);
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
BSONElement createSymbol(StringData symbol) {
BSONObjBuilder ob;
ob.appendSymbol("0"_sd, symbol);
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
BSONElement createElementBinData(BinDataType binDataType, const std::vector<uint8_t>& val) {
BSONObjBuilder ob;
ob.appendBinData("f", val.size(), binDataType, val.data());
_elementMemory.emplace_front(ob.obj());
return _elementMemory.front().firstElement();
}
BSONElement createElementString(StringData val) {
return _createElement(val);
}
BSONElement createElementObj(BSONObj obj) {
return _createElement(obj);
}
BSONElement createElementArray(BSONArray arr) {
return _createElement(arr);
}
BSONElement createElementArrayAsObject(BSONArray arr) {
return _createElement(*static_cast<BSONObj*>(&arr));
}
static boost::optional<uint128_t> deltaBinData(BSONElement val, BSONElement prev) {
if (val.binaryEqualValues(prev)) {
return uint128_t(0);
}
int valSize;
int prevSize;
const char* valBinary = val.binData(valSize);
const char* prevBinary = prev.binData(prevSize);
if (valSize != prevSize || valSize > 16) {
return boost::none;
}
return Simple8bTypeUtil::encodeInt128(
*Simple8bTypeUtil::encodeBinary(valBinary, valSize) -
*Simple8bTypeUtil::encodeBinary(prevBinary, prevSize));
}
static uint128_t deltaString(BSONElement val, BSONElement prev) {
return Simple8bTypeUtil::encodeInt128(
*Simple8bTypeUtil::encodeString(val.valueStringData()) -
*Simple8bTypeUtil::encodeString(prev.valueStringData()));
}
static uint64_t deltaInt32(BSONElement val, BSONElement prev) {
return Simple8bTypeUtil::encodeInt64(val.Int() - prev.Int());
}
static uint64_t deltaInt64(BSONElement val, BSONElement prev) {
return Simple8bTypeUtil::encodeInt64(val.Long() - prev.Long());
}
static uint64_t deltaDouble(BSONElement val, BSONElement prev, double scaleFactor) {
uint8_t scaleIndex = 0;
for (; scaleIndex < Simple8bTypeUtil::kScaleMultiplier.size(); ++scaleIndex) {
if (Simple8bTypeUtil::kScaleMultiplier[scaleIndex] == scaleFactor)
break;
}
return Simple8bTypeUtil::encodeInt64(
*Simple8bTypeUtil::encodeDouble(val.Double(), scaleIndex) -
*Simple8bTypeUtil::encodeDouble(prev.Double(), scaleIndex));
}
static uint64_t deltaDoubleMemory(BSONElement val, BSONElement prev) {
return Simple8bTypeUtil::encodeInt64(
static_cast<int64_t>(static_cast<uint64_t>(*Simple8bTypeUtil::encodeDouble(
val.Double(), Simple8bTypeUtil::kMemoryAsInteger)) -
static_cast<uint64_t>(*Simple8bTypeUtil::encodeDouble(
prev.Double(), Simple8bTypeUtil::kMemoryAsInteger))));
}
static bool simple8bPossible(uint64_t val) {
Simple8bBuilder<uint64_t> b;
return b.append(val, [](uint64_t block) {});
}
static uint64_t deltaOfDelta(int64_t delta, int64_t prevDelta) {
return Simple8bTypeUtil::encodeInt64(delta - prevDelta);
}
static uint64_t deltaOfDeltaObjectId(BSONElement val, BSONElement prev, BSONElement prevprev) {
ASSERT_EQ(memcmp(val.OID().getInstanceUnique().bytes,
prev.OID().getInstanceUnique().bytes,
OID::kInstanceUniqueSize),
0);
ASSERT_EQ(memcmp(prevprev.OID().getInstanceUnique().bytes,
prev.OID().getInstanceUnique().bytes,
OID::kInstanceUniqueSize),
0);
int64_t delta = Simple8bTypeUtil::encodeObjectId(val.OID()) -
Simple8bTypeUtil::encodeObjectId(prev.OID());
int64_t prevDelta = Simple8bTypeUtil::encodeObjectId(prev.OID()) -
Simple8bTypeUtil::encodeObjectId(prevprev.OID());
return deltaOfDelta(delta, prevDelta);
}
static uint128_t deltaDecimal128(BSONElement val, BSONElement prev) {
return Simple8bTypeUtil::encodeInt128(Simple8bTypeUtil::encodeDecimal128(val.Decimal()) -
Simple8bTypeUtil::encodeDecimal128(prev.Decimal()));
}
uint64_t deltaOfDeltaTimestamp(BSONElement val, BSONElement prev) {
return Simple8bTypeUtil::encodeInt64(val.timestamp().asULL() - prev.timestamp().asULL());
}
static uint64_t deltaOfDeltaTimestamp(BSONElement val, BSONElement prev, BSONElement prevprev) {
int64_t prevTimestampDelta = prev.timestamp().asULL() - prevprev.timestamp().asULL();
int64_t currTimestampDelta = val.timestamp().asULL() - prev.timestamp().asULL();
return deltaOfDelta(currTimestampDelta, prevTimestampDelta);
}
template <typename It>
static std::vector<boost::optional<uint64_t>> deltaInt64(It begin, It end, BSONElement prev) {
std::vector<boost::optional<uint64_t>> deltas;
for (; begin != end; ++begin) {
deltas.push_back(deltaInt64(*begin, prev));
prev = *begin;
}
return deltas;
}
template <typename It>
static std::vector<boost::optional<uint64_t>> deltaDouble(It begin,
It end,
BSONElement prev,
double scaleFactor) {
std::vector<boost::optional<uint64_t>> deltas;
for (; begin != end; ++begin) {
if (!begin->eoo()) {
deltas.push_back(deltaDouble(*begin, prev, scaleFactor));
prev = *begin;
} else {
deltas.push_back(boost::none);
}
}
return deltas;
}
template <typename It>
static std::vector<boost::optional<uint128_t>> deltaString(It begin, It end, BSONElement prev) {
std::vector<boost::optional<uint128_t>> deltas;
for (; begin != end; ++begin) {
deltas.push_back(deltaString(*begin, prev));
prev = *begin;
}
return deltas;
}
static uint64_t deltaBool(BSONElement val, BSONElement prev) {
return Simple8bTypeUtil::encodeInt64(val.Bool() - prev.Bool());
}
static uint64_t deltaOfDeltaDate(BSONElement val, BSONElement prev, BSONElement prevprev) {
int64_t delta = val.Date().toMillisSinceEpoch() - prev.Date().toMillisSinceEpoch();
int64_t prevDelta = prev.Date().toMillisSinceEpoch() - prevprev.Date().toMillisSinceEpoch();
return deltaOfDelta(delta, prevDelta);
}
template <typename It>
static std::vector<boost::optional<uint64_t>> deltaOfDeltaDates(It begin,
It end,
BSONElement prev,
BSONElement prevprev) {
std::vector<boost::optional<uint64_t>> deltas;
for (; begin != end; ++begin) {
deltas.push_back(deltaOfDeltaDate(*begin, prev, prevprev));
prevprev = prev;
prev = *begin;
}
return deltas;
}
static void appendLiteral(BufBuilder& builder, BSONElement elem) {
// BSON Type byte
builder.appendChar(elem.type());
// Null terminator for field name
builder.appendChar('\0');
// Element value
builder.appendBuf(elem.value(), elem.valuesize());
}
static void appendSimple8bControl(BufBuilder& builder, uint8_t control, uint8_t count) {
builder.appendChar(control << 4 | count);
}
static void appendInterleavedStartLegacy(BufBuilder& builder, BSONObj reference) {
builder.appendChar((char)0xF0);
builder.appendBuf(reference.objdata(), reference.objsize());
}
static void appendInterleavedStart(BufBuilder& builder, BSONObj reference) {
builder.appendChar((char)0xF1);
builder.appendBuf(reference.objdata(), reference.objsize());
}
static void appendInterleavedStartArrayRoot(BufBuilder& builder, BSONObj reference) {
builder.appendChar((char)0xF2);
builder.appendBuf(reference.objdata(), reference.objsize());
}
template <typename T>
static void _appendSimple8bBlock(BufBuilder& builder, boost::optional<T> val) {
auto prev = builder.len();
auto writeFn = [&builder](uint64_t block) {
builder.appendNum(block);
return true;
};
Simple8bBuilder<T> s8bBuilder;
if (val) {
s8bBuilder.append(*val, writeFn);
} else {
s8bBuilder.skip(writeFn);
}
s8bBuilder.flush(writeFn);
ASSERT_EQ(builder.len() - prev, sizeof(uint64_t));
}
static void appendSimple8bBlock64(BufBuilder& builder, boost::optional<uint64_t> val) {
_appendSimple8bBlock<uint64_t>(builder, val);
}
static void appendSimple8bBlock128(BufBuilder& builder, boost::optional<uint128_t> val) {
_appendSimple8bBlock<uint128_t>(builder, val);
}
template <typename T>
static void _appendSimple8bBlocks(BufBuilder& builder,
const std::vector<boost::optional<T>>& vals,
uint32_t expectedNum) {
auto prev = builder.len();
auto writeFn = [&builder](uint64_t block) {
builder.appendNum(block);
return true;
};
Simple8bBuilder<T> s8bBuilder;
for (auto val : vals) {
if (val) {
s8bBuilder.append(*val, writeFn);
} else {
s8bBuilder.skip(writeFn);
}
}
s8bBuilder.flush(writeFn);
ASSERT_EQ((builder.len() - prev) / sizeof(uint64_t), expectedNum);
}
static void appendSimple8bBlocks64(BufBuilder& builder,
const std::vector<boost::optional<uint64_t>>& vals,
uint32_t expectedNum) {
_appendSimple8bBlocks<uint64_t>(builder, vals, expectedNum);
}
static void appendSimple8bBlocks128(BufBuilder& builder,
const std::vector<boost::optional<uint128_t>> vals,
uint32_t expectedNum) {
_appendSimple8bBlocks<uint128_t>(builder, vals, expectedNum);
}
static void appendSimple8bRLE(BufBuilder& builder, int elemCount) {
ASSERT(elemCount % 120 == 0);
ASSERT(elemCount / 120 <= 16);
uint64_t block = (elemCount / 120) - 1;
builder.appendNum(block << 4 | simple8b_internal::kRleSelector);
}
static void appendEOO(BufBuilder& builder) {
builder.appendChar(EOO);
}
static void assertSbeValueEquals(sbe::bsoncolumn::SBEColumnMaterializer::Element& actual,
sbe::bsoncolumn::SBEColumnMaterializer::Element& expected) {
// We should have already have checked the tags are equal or are expected values. Tags for
// strings can differ based on how the SBE element is created, and thus should be verified
// before.
using namespace sbe::value;
switch (actual.first) {
// Values that are stored in 'Value' can be compared directly.
case TypeTags::Nothing:
case TypeTags::NumberInt32:
case TypeTags::NumberInt64:
case TypeTags::NumberDouble:
case TypeTags::Boolean:
case TypeTags::Null:
case TypeTags::bsonUndefined:
case TypeTags::MinKey:
case TypeTags::MaxKey:
case TypeTags::Date:
case TypeTags::Timestamp:
ASSERT_EQ(actual.second, expected.second);
break;
// The following types store pointers in 'Value'.
case TypeTags::NumberDecimal:
ASSERT_EQ(bitcastTo<Decimal128>(actual.second),
bitcastTo<Decimal128>(expected.second));
break;
case TypeTags::bsonObjectId:
ASSERT_EQ(memcmp(bitcastTo<uint8_t*>(actual.second),
bitcastTo<uint8_t*>(expected.second),
sizeof(ObjectIdType)),
0);
break;
// For strings we can retrieve the strings and compare them directly.
case TypeTags::bsonJavascript: {
ASSERT_EQ(getBsonJavascriptView(actual.second),
getBsonJavascriptView(expected.second));
break;
}
case TypeTags::StringSmall:
case TypeTags::bsonString:
// Generic conversion won't produce StringSmall from BSONElements, but the
// SBEColumnMaterializer will. So we can't compare the raw pointers since they are
// different lengths, but we can compare the string values.
ASSERT_EQ(getStringView(actual.first, actual.second),
getStringView(expected.first, expected.second));
break;
// We can read the raw pointer for these types, since the 32-bit 'length' at the
// beginning of pointer holds the full length of the value.
case TypeTags::bsonCodeWScope:
case TypeTags::bsonSymbol:
case TypeTags::bsonObject:
case TypeTags::bsonArray: {
auto actualPtr = getRawPointerView(actual.second);
auto expectedPtr = getRawPointerView(expected.second);
auto actSize = ConstDataView(actualPtr).read<LittleEndian<uint32_t>>();
ASSERT_EQ(actSize, ConstDataView(expectedPtr).read<LittleEndian<uint32_t>>());
ASSERT_EQ(memcmp(actualPtr, expectedPtr, actSize), 0);
break;
}
// For these types we must find the correct number of bytes to read.
case TypeTags::bsonRegex: {
auto actualPtr = getRawPointerView(actual.second);
auto expectedPtr = getRawPointerView(expected.second);
auto numBytes = BsonRegex(actualPtr).byteSize();
ASSERT_EQ(BsonRegex(expectedPtr).byteSize(), numBytes);
ASSERT_EQ(memcmp(actualPtr, expectedPtr, numBytes), 0);
break;
}
case TypeTags::bsonBinData: {
// The 32-bit 'length' at the beginning of a BinData does _not_ account for the
// 'length' field itself or the 'subtype' field.
auto actualSize = getBSONBinDataSize(actual.first, actual.second);
auto expectedSize = getBSONBinDataSize(expected.first, expected.second);
ASSERT_EQ(actualSize, expectedSize);
// We add 1 to compare the subtype and binData payload in one pass.
ASSERT_EQ(memcmp(getRawPointerView(actual.second),
getRawPointerView(expected.second),
actualSize + 1),
0);
break;
}
case TypeTags::bsonDBPointer: {
auto actualPtr = getRawPointerView(actual.second);
auto expectedPtr = getRawPointerView(expected.second);
auto numBytes = BsonDBPointer(actualPtr).byteSize();
ASSERT_EQ(BsonDBPointer(expectedPtr).byteSize(), numBytes);
ASSERT_EQ(memcmp(actualPtr, expectedPtr, numBytes), 0);
break;
}
default:
FAIL(str::stream()
<< "Hit unreachable case in the SBEColumnMaterializer. Expected: " << expected
<< "Actual: " << actual);
break;
}
}
static void convertAndAssertSBEEquals(sbe::bsoncolumn::SBEColumnMaterializer::Element& actual,
const BSONElement& expected) {
auto expectedSBE = sbe::bson::convertFrom<true>(expected);
if (actual.first == sbe::value::TypeTags::StringSmall) {
// Generic conversion won't produce StringSmall from BSONElements, but
// SBEColumnMaterializer will, don't compare the type tag for that case.
ASSERT_EQ(expectedSBE.first, sbe::value::TypeTags::bsonString);
} else {
ASSERT_EQ(actual.first, expectedSBE.first);
}
assertSbeValueEquals(actual, expectedSBE);
}
static void verifyColumnReopenFromBinary(const char* buffer, size_t size) {
BSONColumn column(buffer, size);
BSONColumnBuilder reference;
for (auto&& elem : column) {
reference.append(elem);
}
BSONColumnBuilder reopen(buffer, size);
[[maybe_unused]] auto diff = reference.intermediate();
// Verify that the internal state is identical to the reference builder
invariant(reopen.isInternalStateIdentical(reference));
}
static void verifyBinary(BSONBinData columnBinary,
const BufBuilder& expected,
bool testReopen = true) {
ASSERT_EQ(columnBinary.type, BinDataType::Column);
auto buf = expected.buf();
ASSERT_EQ(columnBinary.length, expected.len());
for (int i = 0; i < columnBinary.length; ++i) {
ASSERT_EQ(*(reinterpret_cast<const char*>(columnBinary.data) + i), buf[i]);
}
ASSERT_EQ(memcmp(columnBinary.data, buf, columnBinary.length), 0);
// Verify BSONColumnBuilder::last
{
BSONColumnBuilder cb;
// Initial state returns eoo
ASSERT_TRUE(cb.last().eoo());
BSONColumn column(columnBinary);
BSONElement last;
for (auto&& elem : column) {
cb.append(elem);
// Last does not consider skip
if (!elem.eoo()) {
last = elem;
}
if (last.eoo()) {
// Only skips have been encountered, last() should continue to return EOO
ASSERT_TRUE(cb.last().eoo());
} else if (last.type() != Object && last.type() != Array) {
// Empty objects and arrays _may_ be encoded as scalar depending on what else
// has been added to the builder. This makes this case difficult to test and we
// just test the scalar types instead.
ASSERT_FALSE(cb.last().eoo());
ASSERT_TRUE(last.binaryEqualValues(cb.last()));
}
}
}
// Verify BSONColumnBuilder::intermediate
{
// Test intermediate when called between every append to ensure we get the same binary
// compared to when no intermediate was used.
{
BufBuilder buffer;
BSONColumnBuilder cb;
BSONColumnBuilder reference;
BSONColumn c(columnBinary);
bool empty = true;
for (auto&& elem : c) {
cb.append(elem);
reference.append(elem);
auto diff = cb.intermediate();
ASSERT_GTE(buffer.len(), diff.offset());
buffer.setlen(diff.offset());
buffer.appendBuf(diff.data(), diff.size());
empty = false;
}
// If there was nothing in the column, we need to make sure at least one
// intermediate was called
if (empty) {
auto diff = cb.intermediate();
ASSERT_EQ(diff.offset(), 0);
buffer.appendBuf(diff.data(), diff.size());
}
// Compare the binary with one obtained using finalize
assertBinaryEqual(reference.finalize(), buffer);
}
// Test intermediate when called between every other append to ensure we get the same
// binary compared to when no intermediate was used.
{
BufBuilder buffer;
BSONColumnBuilder cb;
BSONColumnBuilder reference;
BSONColumn c(columnBinary);
int num = 0;
for (auto it = c.begin(); it != c.end(); ++it, ++num) {
cb.append(*it);
reference.append(*it);
if (num % 2 == 1)
continue;
auto diff = cb.intermediate();
ASSERT_GTE(buffer.len(), diff.offset());
buffer.setlen(diff.offset());
buffer.appendBuf(diff.data(), diff.size());
}
// One last intermediate to ensure all data is put into binary
auto diff = cb.intermediate();
ASSERT_GTE(buffer.len(), diff.offset());
buffer.setlen(diff.offset());
buffer.appendBuf(diff.data(), diff.size());
// Compare the binary with one obtained using finalize
assertBinaryEqual(reference.finalize(), buffer);
}
// Divide the range into two blocks where intermediate is called in between. We do all
// combinations of dividing the ranges so this test has quadratic complexity. Limit it
// to binaries with a limited number of elements.
size_t num = BSONColumn(columnBinary).size();
if (num > 0 && num < 1000) {
// Iterate over all elements and validate intermediate in all combinations
for (size_t i = 1; i <= num; ++i) {
BufBuilder buffer;
BSONColumnBuilder cb;
BSONColumnBuilder reference;
// Append initial data to our builder
BSONColumn c(columnBinary);
auto it = c.begin();
for (size_t j = 0; j < i; ++j, ++it) {
cb.append(*it);
reference.append(*it);
}
// Call intermediate to obtain the initial binary
auto diff = cb.intermediate();
ASSERT_EQ(diff.offset(), 0);
buffer.appendBuf(diff.data(), diff.size());
// Append the rest of the data
BufBuilder buffer2;
for (size_t j = i; j < num; ++j, ++it) {
cb.append(*it);
reference.append(*it);
}
// Call intermediate to obtain rest of the binary
diff = cb.intermediate();
// Start writing at the provided offset
ASSERT_GTE(buffer.len(), diff.offset());
buffer.setlen(diff.offset());
buffer.appendBuf(diff.data(), diff.size());
// We should now have added all our data.
ASSERT(it == c.end());
// Compare the binary with one obtained using finalize
assertBinaryEqual(reference.finalize(), buffer);
}
}
}
if (testReopen) {
BSONColumn c(columnBinary);
size_t num = c.size();
// Validate the BSONColumnBuilder constructor that initializes from a compressed binary.
// Its state should be identical to a builder that never called finalize() for these
// elements.
for (size_t i = 0; i <= num; ++i) {
BSONColumnBuilder before;
auto it = c.begin();
for (size_t j = 0; j < i; ++j, ++it) {
before.append(*it);
}
auto intermediate = before.finalize();
verifyColumnReopenFromBinary(reinterpret_cast<const char*>(intermediate.data),
intermediate.length);
}
}
}
// testBlockBased is a temporary option; it will be removed once all
// functionality for block based decompression is in place and all
// relevant tests are onboarded
static void verifyDecompression(const BufBuilder& columnBinary,
const std::vector<BSONElement>& expected,
bool testBlockBased = false) {
BSONBinData bsonBinData;
bsonBinData.data = columnBinary.buf();
bsonBinData.length = columnBinary.len();
bsonBinData.type = Column;
verifyDecompression(bsonBinData, expected, testBlockBased);
}
static void verifyDecompression(BSONBinData columnBinary,
const std::vector<BSONElement>& expected,
bool testBlockBased = false) {
BSONObjBuilder obj;
obj.append(""_sd, columnBinary);
BSONElement columnElement = obj.done().firstElement();
// Verify that we can traverse BSONColumn twice and extract values on the second pass
{
BSONColumn col(columnElement);
ASSERT_EQ(col.size(), expected.size());
ASSERT_EQ(std::distance(col.begin(), col.end()), expected.size());
ASSERT_EQ(col.size(), expected.size());
auto it = col.begin();
for (auto elem : expected) {
BSONElement other = *it;
ASSERT(elem.binaryEqualValues(other));
ASSERT_TRUE(it.more());
++it;
}
ASSERT_FALSE(it.more());
}
// Verify that we can traverse BSONColumn and extract values on the first pass
{
BSONColumn col(columnElement);
auto it = col.begin();
for (auto elem : expected) {
BSONElement other = *it;
ASSERT(elem.binaryEqualValues(other));
++it;
}
}
// Verify operator[] when accessing in order
{
BSONColumn col(columnElement);
for (size_t i = 0; i < expected.size(); ++i) {
ASSERT(expected[i].binaryEqualValues(*col[i]));
}
}
// Verify operator[] when accessing in reverse order
{
BSONColumn col(columnElement);
for (int i = (int)expected.size() - 1; i >= 0; --i) {
ASSERT(expected[i].binaryEqualValues(*col[i]));
}
}
// Verify that we can continue traverse with new iterators when we stop before end
{
BSONColumn col(columnElement);
for (size_t e = 0; e < expected.size(); ++e) {
auto it = col.begin();
for (size_t i = 0; i < e; ++i, ++it) {
ASSERT(expected[i].binaryEqualValues(*it));
}
ASSERT_EQ(col.size(), expected.size());
}
}
// Verify that we can have multiple iterators on the same thread
{
BSONColumn col(columnElement);
auto it1 = col.begin();
auto it2 = col.begin();
auto itEnd = col.end();
for (; it1 != itEnd && it2 != itEnd; ++it1, ++it2) {
ASSERT(it1->binaryEqualValues(*it2));
}
ASSERT(it1 == it2);
}
// Verify iterator equality operator
{
BSONColumn col(columnElement);
auto iIt = col.begin();
for (size_t i = 0; i < expected.size(); ++i, ++iIt) {
auto jIt = col.begin();
for (size_t j = 0; j < expected.size(); ++j, ++jIt) {
if (i == j) {
ASSERT(iIt == jIt);
} else {
ASSERT(iIt != jIt);
}
}
}
}
// Verify we can decompress the entire column using the block-based API using the
// BSONElementMaterializer.
{
bsoncolumn::BSONColumnBlockBased col(columnBinary);
boost::intrusive_ptr<ElementStorage> allocator = new ElementStorage();
std::vector<BSONElement> container;
col.decompressIterative<BSONElementMaterializer>(container, allocator);
ASSERT_EQ(container.size(), expected.size());
auto actual = container.begin();
for (auto&& elem : expected) {
elem.binaryEqualValues(*actual);
++actual;
}
}
// Verify we can decompress the entire column using the block-based API using the
// SBEColumnMaterializer.
{
using SBEMaterializer = sbe::bsoncolumn::SBEColumnMaterializer;
bsoncolumn::BSONColumnBlockBased col(columnBinary);
boost::intrusive_ptr<ElementStorage> allocator = new ElementStorage();
std::vector<SBEMaterializer::Element> container;
col.decompressIterative<SBEMaterializer>(container, allocator);
ASSERT_EQ(container.size(), expected.size());
auto actual = container.begin();
for (auto&& elem : expected) {
convertAndAssertSBEEquals(*actual, elem);
++actual;
}
}
// This gate will be removed once all types are onboarded to decompress all interface
if (testBlockBased) {
boost::intrusive_ptr<ElementStorage> allocator = new ElementStorage();
std::vector<BSONElement> collection;
BSONColumnBlockBased c((const char*)columnBinary.data, columnBinary.length);
c.decompress<BSONElementMaterializer, std::vector<BSONElement>>(collection, allocator);
ASSERT_EQ(collection.size(), expected.size());
for (size_t i = 0; i < collection.size(); ++i) {
ASSERT(expected[i].binaryEqualValues(collection[i]));
}
}
}
/**
* Constructs a BSON Column encoding with a non-zero delta after the specified element, and
* expects error 6785500 to be thrown.
*/
void testInvalidDelta(BSONElement elem) {
BufBuilder expected;
appendLiteral(expected, elem);
appendSimple8bControl(expected, 0b1000, 0b0000);
appendSimple8bBlock64(expected, Simple8bTypeUtil::encodeInt64(1));
appendEOO(expected);
BSONColumn col(createBSONColumn(expected.buf(), expected.len()));
ASSERT_THROWS_CODE(std::distance(col.begin(), col.end()), DBException, 6785500);
}
const boost::optional<uint64_t> kDeltaForBinaryEqualValues = Simple8bTypeUtil::encodeInt64(0);
const boost::optional<uint128_t> kDeltaForBinaryEqualValues128 =
Simple8bTypeUtil::encodeInt128(0);
private:
std::forward_list<BSONObj> _elementMemory;
};
TEST_F(BSONColumnTest, Empty) {
BSONColumnBuilder cb;
BufBuilder expected;
appendEOO(expected);
auto binData = cb.finalize();
verifyBinary(binData, expected);
verifyDecompression(binData, {}, true);
}
TEST_F(BSONColumnTest, ContainsScalarInt32SimpleCompressed) {
BSONColumnBuilder cb;
// Column should have several scalar values of same type
// -> 32-bit Ints
auto elemInt32_0 = createElementInt32(100);
auto elemInt32_1 = createElementInt32(101);
cb.append(elemInt32_0);
cb.append(elemInt32_0);
cb.append(elemInt32_1);
auto binData = cb.finalize();
// Recreate cb "manually" to create the BSONColumn class, so as to
// test BSONColumn::contains_forTest
BufBuilder colBuf;
appendLiteral(colBuf, elemInt32_0);
appendSimple8bControl(colBuf, 0b1000, 0b0000); // Control = 1, CountOfSimple8b's = 0+1
std::vector<boost::optional<uint64_t>> v{deltaInt32(elemInt32_0, elemInt32_0),
deltaInt32(elemInt32_1, elemInt32_0)};
appendSimple8bBlocks64(colBuf, v, 1);
appendEOO(colBuf);
BSONColumn col(createBSONColumn(colBuf.buf(), colBuf.len()));
ASSERT_EQ(col.contains_forTest(BSONType::NumberInt), true);
ASSERT_EQ(col.contains_forTest(BSONType::NumberLong), false);
ASSERT_EQ(col.contains_forTest(BSONType::NumberDouble), false);
ASSERT_EQ(col.contains_forTest(BSONType::Array), false);
ASSERT_EQ(col.contains_forTest(BSONType::bsonTimestamp), false);
ASSERT_EQ(col.contains_forTest(BSONType::String), false);
ASSERT_EQ(col.contains_forTest(BSONType::Object), false);
ASSERT_EQ(col.contains_forTest(BSONType::jstOID), false);
ASSERT_EQ(col.contains_forTest(BSONType::Bool), false);
verifyBinary(binData, colBuf);
}
TEST_F(BSONColumnTest, ContainsScalarInt64SimpleCompressed) {
BSONColumnBuilder cb;
// Column should have several scalar values of same type