/
explain.cpp
2400 lines (2073 loc) · 87.4 KB
/
explain.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) 2022-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/db/query/optimizer/explain.h"
#include "mongo/db/exec/sbe/values/bson.h"
#include "mongo/db/query/optimizer/cascades/memo.h"
#include "mongo/db/query/optimizer/node.h"
#include "mongo/util/assert_util.h"
namespace mongo::optimizer {
BSONObj ABTPrinter::explainBSON() const {
return ExplainGenerator::explainBSONObj(
_abtTree, true /*displayProperties*/, nullptr /*Memo*/, _nodeToPropsMap);
}
enum class ExplainVersion { V1, V2, V3, Vmax };
bool constexpr operator<(const ExplainVersion v1, const ExplainVersion v2) {
return static_cast<int>(v1) < static_cast<int>(v2);
}
bool constexpr operator<=(const ExplainVersion v1, const ExplainVersion v2) {
return static_cast<int>(v1) <= static_cast<int>(v2);
}
bool constexpr operator>(const ExplainVersion v1, const ExplainVersion v2) {
return static_cast<int>(v1) > static_cast<int>(v2);
}
bool constexpr operator>=(const ExplainVersion v1, const ExplainVersion v2) {
return static_cast<int>(v1) >= static_cast<int>(v2);
}
static constexpr ExplainVersion kDefaultExplainVersion = ExplainVersion::V1;
enum class CommandType { Indent, Unindent, AddLine };
struct CommandStruct {
CommandStruct() = default;
CommandStruct(const CommandType type, std::string str) : _type(type), _str(std::move(str)) {}
CommandType _type;
std::string _str;
};
using CommandVector = std::vector<CommandStruct>;
template <const ExplainVersion version = kDefaultExplainVersion>
class ExplainPrinterImpl {
public:
ExplainPrinterImpl()
: _cmd(),
_os(),
_osDirty(false),
_indentCount(0),
_childrenRemaining(0),
_cmdInsertPos(-1) {}
~ExplainPrinterImpl() {
uassert(6624003, "Unmatched indentations", _indentCount == 0);
uassert(6624004, "Incorrect child count mark", _childrenRemaining == 0);
}
ExplainPrinterImpl(const ExplainPrinterImpl& other) = delete;
ExplainPrinterImpl& operator=(const ExplainPrinterImpl& other) = delete;
explicit ExplainPrinterImpl(const std::string& initialStr) : ExplainPrinterImpl() {
print(initialStr);
}
ExplainPrinterImpl(ExplainPrinterImpl&& other) noexcept
: _cmd(std::move(other._cmd)),
_os(std::move(other._os)),
_osDirty(other._osDirty),
_indentCount(other._indentCount),
_childrenRemaining(other._childrenRemaining),
_cmdInsertPos(other._cmdInsertPos) {}
template <class T>
ExplainPrinterImpl& print(const T& t) {
_os << t;
_osDirty = true;
return *this;
}
/**
* Here and below: "other" printer(s) may be siphoned out.
*/
ExplainPrinterImpl& print(ExplainPrinterImpl& other) {
return print(other, false /*singleLevel*/);
}
template <class P>
ExplainPrinterImpl& printSingleLevel(P& other, const std::string& singleLevelSpacer = " ") {
return print(other, true /*singleLevel*/, singleLevelSpacer);
}
ExplainPrinterImpl& printAppend(ExplainPrinterImpl& other) {
// Ignore append
return print(other);
}
ExplainPrinterImpl& print(std::vector<ExplainPrinterImpl>& other) {
for (auto&& element : other) {
print(element);
}
return *this;
}
ExplainPrinterImpl& printAppend(std::vector<ExplainPrinterImpl>& other) {
// Ignore append.
return print(other);
}
ExplainPrinterImpl& setChildCount(const size_t childCount) {
if (version > ExplainVersion::V1) {
_childrenRemaining = childCount;
indent("");
for (int i = 0; i < _childrenRemaining - 1; i++) {
indent("|");
}
}
return *this;
}
ExplainPrinterImpl& maybeReverse() {
if (version > ExplainVersion::V1) {
_cmdInsertPos = _cmd.size();
}
return *this;
}
ExplainPrinterImpl& fieldName(const std::string& name,
const ExplainVersion minVersion = ExplainVersion::V1,
const ExplainVersion maxVersion = ExplainVersion::Vmax) {
if (minVersion <= version && maxVersion >= version) {
print(name);
print(": ");
}
return *this;
}
ExplainPrinterImpl& separator(const std::string& separator) {
return print(separator);
}
std::string str() {
newLine();
std::ostringstream os;
std::vector<std::string> linePrefix;
bool firstAddLine = true;
for (const auto& cmd : _cmd) {
switch (cmd._type) {
case CommandType::Indent:
linePrefix.push_back(cmd._str);
break;
case CommandType::Unindent: {
linePrefix.pop_back();
break;
}
case CommandType::AddLine: {
for (const std::string& element : linePrefix) {
if (!element.empty()) {
os << element << ((version == ExplainVersion::V1) ? " " : " ");
}
}
os << cmd._str << "\n";
firstAddLine = false;
break;
}
default: { MONGO_UNREACHABLE; }
}
}
return os.str();
}
void newLine() {
if (!_osDirty) {
return;
}
const std::string& str = _os.str();
_cmd.emplace_back(CommandType::AddLine, str);
_os.str("");
_os.clear();
_osDirty = false;
}
const CommandVector& getCommands() const {
return _cmd;
}
private:
template <class P>
ExplainPrinterImpl& print(P& other,
const bool singleLevel,
const std::string& singleLevelSpacer = " ") {
CommandVector toAppend;
if (_cmdInsertPos >= 0) {
toAppend = CommandVector(_cmd.cbegin() + _cmdInsertPos, _cmd.cend());
_cmd.resize(static_cast<size_t>(_cmdInsertPos));
}
const bool hadChildrenRemaining = _childrenRemaining > 0;
if (hadChildrenRemaining) {
_childrenRemaining--;
}
other.newLine();
if (singleLevel) {
uassert(6624071, "Unexpected dirty status", _osDirty);
bool first = true;
for (const auto& element : other.getCommands()) {
if (element._type == CommandType::AddLine) {
if (first) {
first = false;
} else {
_os << singleLevelSpacer;
}
_os << element._str;
}
}
} else {
newLine();
if (!hadChildrenRemaining) {
indent();
}
for (const auto& element : other.getCommands()) {
_cmd.push_back(element);
}
unIndent();
}
if (_cmdInsertPos >= 0) {
std::copy(toAppend.cbegin(), toAppend.cend(), std::back_inserter(_cmd));
}
return *this;
}
void indent(std::string s = " ") {
newLine();
_indentCount++;
_cmd.emplace_back(CommandType::Indent, std::move(s));
}
void unIndent() {
newLine();
_indentCount--;
_cmd.emplace_back(CommandType::Unindent, "");
}
CommandVector _cmd;
std::ostringstream _os;
bool _osDirty;
int _indentCount;
int _childrenRemaining;
int _cmdInsertPos;
};
template <>
class ExplainPrinterImpl<ExplainVersion::V3> {
static constexpr ExplainVersion version = ExplainVersion::V3;
public:
ExplainPrinterImpl() {
reset();
}
~ExplainPrinterImpl() {
if (_initialized) {
releaseValue(_tag, _val);
}
}
ExplainPrinterImpl(const ExplainPrinterImpl& other) = delete;
ExplainPrinterImpl& operator=(const ExplainPrinterImpl& other) = delete;
ExplainPrinterImpl(ExplainPrinterImpl&& other) noexcept {
_nextFieldName = std::move(other._nextFieldName);
_initialized = other._initialized;
_canAppend = other._canAppend;
_tag = other._tag;
_val = other._val;
_fieldNameSet = std::move(other._fieldNameSet);
other.reset();
}
explicit ExplainPrinterImpl(const std::string& nodeName) : ExplainPrinterImpl() {
fieldName("nodeType").print(nodeName);
}
auto moveValue() {
auto result = std::pair<sbe::value::TypeTags, sbe::value::Value>(_tag, _val);
reset();
return result;
}
ExplainPrinterImpl& print(const bool v) {
addValue(sbe::value::TypeTags::Boolean, v);
return *this;
}
ExplainPrinterImpl& print(const int64_t v) {
addValue(sbe::value::TypeTags::NumberInt64, sbe::value::bitcastFrom<int64_t>(v));
return *this;
}
ExplainPrinterImpl& print(const int32_t v) {
addValue(sbe::value::TypeTags::NumberInt32, sbe::value::bitcastFrom<int32_t>(v));
return *this;
}
ExplainPrinterImpl& print(const size_t v) {
addValue(sbe::value::TypeTags::NumberInt64, sbe::value::bitcastFrom<size_t>(v));
return *this;
}
ExplainPrinterImpl& print(const double v) {
addValue(sbe::value::TypeTags::NumberDouble, sbe::value::bitcastFrom<double>(v));
return *this;
}
ExplainPrinterImpl& print(const std::pair<sbe::value::TypeTags, sbe::value::Value> v) {
auto [tag, val] = sbe::value::copyValue(v.first, v.second);
addValue(tag, val);
return *this;
}
ExplainPrinterImpl& print(const std::string& s) {
auto [tag, val] = sbe::value::makeNewString(s);
addValue(tag, val);
return *this;
}
ExplainPrinterImpl& print(const char* s) {
return print(static_cast<std::string>(s));
}
/**
* Here and below: "other" printer(s) may be siphoned out.
*/
ExplainPrinterImpl& print(ExplainPrinterImpl& other) {
return print(other, false /*append*/);
}
ExplainPrinterImpl& printSingleLevel(ExplainPrinterImpl& other,
const std::string& /*singleLevelSpacer*/ = " ") {
// Ignore single level.
return print(other);
}
ExplainPrinterImpl& printAppend(ExplainPrinterImpl& other) {
return print(other, true /*append*/);
}
ExplainPrinterImpl& print(std::vector<ExplainPrinterImpl>& other) {
return print(other, false /*append*/);
}
ExplainPrinterImpl& printAppend(std::vector<ExplainPrinterImpl>& other) {
return print(other, true /*append*/);
}
ExplainPrinterImpl& setChildCount(const size_t /*childCount*/) {
// Ignored.
return *this;
}
ExplainPrinterImpl& maybeReverse() {
// Ignored.
return *this;
}
ExplainPrinterImpl& fieldName(const std::string& name,
const ExplainVersion minVersion = ExplainVersion::V1,
const ExplainVersion maxVersion = ExplainVersion::Vmax) {
if (minVersion <= version && maxVersion >= version) {
_nextFieldName = name;
}
return *this;
}
ExplainPrinterImpl& separator(const std::string& /*separator*/) {
// Ignored.
return *this;
}
private:
ExplainPrinterImpl& print(ExplainPrinterImpl& other, const bool append) {
auto [tag, val] = other.moveValue();
addValue(tag, val, append);
if (append) {
sbe::value::releaseValue(tag, val);
}
return *this;
}
ExplainPrinterImpl& print(std::vector<ExplainPrinterImpl>& other, const bool append) {
auto [tag, val] = sbe::value::makeNewArray();
sbe::value::Array* arr = sbe::value::getArrayView(val);
for (auto&& element : other) {
auto [tag1, val1] = element.moveValue();
arr->push_back(tag1, val1);
}
addValue(tag, val, append);
return *this;
}
void addValue(sbe::value::TypeTags tag, sbe::value::Value val, const bool append = false) {
if (!_initialized) {
_initialized = true;
_canAppend = !_nextFieldName.empty();
if (_canAppend) {
std::tie(_tag, _val) = sbe::value::makeNewObject();
} else {
_tag = tag;
_val = val;
return;
}
}
if (!_canAppend) {
uasserted(6624072, "Cannot append to scalar");
return;
}
if (append) {
uassert(6624073, "Field name is not empty", _nextFieldName.empty());
uassert(6624349,
"Other printer does not contain Object",
tag == sbe::value::TypeTags::Object);
sbe::value::Object* obj = sbe::value::getObjectView(val);
for (size_t i = 0; i < obj->size(); i++) {
const auto field = obj->getAt(i);
auto [fieldTag, fieldVal] = sbe::value::copyValue(field.first, field.second);
addField(obj->field(i), fieldTag, fieldVal);
}
} else {
addField(_nextFieldName, tag, val);
_nextFieldName.clear();
}
}
void addField(const std::string& fieldName, sbe::value::TypeTags tag, sbe::value::Value val) {
uassert(6624074, "Field name is empty", !fieldName.empty());
uassert(6624075, "Duplicate field name", _fieldNameSet.insert(fieldName).second);
sbe::value::getObjectView(_val)->push_back(fieldName, tag, val);
}
void reset() {
_nextFieldName.clear();
_initialized = false;
_canAppend = false;
_tag = sbe::value::TypeTags::Nothing;
_val = 0;
_fieldNameSet.clear();
}
std::string _nextFieldName;
bool _initialized;
bool _canAppend;
sbe::value::TypeTags _tag;
sbe::value::Value _val;
// For debugging.
opt::unordered_set<std::string> _fieldNameSet;
};
template <const ExplainVersion version = kDefaultExplainVersion>
class ExplainGeneratorTransporter {
public:
using ExplainPrinter = ExplainPrinterImpl<version>;
ExplainGeneratorTransporter(bool displayProperties = false,
const cascades::Memo* memo = nullptr,
const NodeToGroupPropsMap& nodeMap = {})
: _displayProperties(displayProperties), _memo(memo), _nodeMap(nodeMap) {
uassert(6624005,
"Memo must be provided in order to display properties.",
!_displayProperties || (_memo != nullptr || version == ExplainVersion::V3));
}
/**
* Helper function that appends the logical and physical properties of 'node' nested under a new
* field named 'properties'. Only applicable for BSON explain, for other versions this is a
* no-op.
*/
void maybePrintProps(ExplainPrinter& nodePrinter, const Node& node) {
if (!_displayProperties || version != ExplainVersion::V3 || _nodeMap.empty()) {
return;
}
auto it = _nodeMap.find(&node);
uassert(6624006, "Failed to find node properties", it != _nodeMap.end());
const NodeProps& props = it->second;
ExplainPrinter logPropPrinter = printLogicalProps("logical", props._logicalProps);
ExplainPrinter physPropPrinter = printPhysProps("physical", props._physicalProps);
ExplainPrinter propsPrinter;
propsPrinter.fieldName("cost")
.print(props._cost.getCost())
.fieldName("localCost")
.print(props._localCost.getCost())
.fieldName("adjustedCE")
.print(props._adjustedCE)
.fieldName("planNodeID")
.print(props._planNodeId)
.fieldName("logicalProperties")
.print(logPropPrinter)
.fieldName("physicalProperties")
.print(physPropPrinter);
ExplainPrinter res;
res.fieldName("properties").print(propsPrinter);
nodePrinter.printAppend(res);
}
static void printBooleanFlag(ExplainPrinter& printer,
const std::string& name,
const bool flag,
const bool addComma = true) {
if constexpr (version < ExplainVersion::V3) {
if (flag) {
if (addComma) {
printer.print(", ");
}
printer.print(name);
}
} else if constexpr (version == ExplainVersion::V3) {
printer.fieldName(name).print(flag);
} else {
static_assert("Unknown version");
}
}
static void printDirectToParentHelper(const bool directToParent,
ExplainPrinter& parent,
std::function<void(ExplainPrinter& printer)> fn) {
if (directToParent) {
fn(parent);
} else {
ExplainPrinter printer;
fn(printer);
parent.printAppend(printer);
}
}
/**
* Nodes
*/
ExplainPrinter transport(const References& references, std::vector<ExplainPrinter> inResults) {
ExplainPrinter printer;
printer.separator("RefBlock: ").printAppend(inResults);
return printer;
}
ExplainPrinter transport(const ExpressionBinder& binders,
std::vector<ExplainPrinter> inResults) {
std::map<std::string, ExplainPrinter> ordered;
for (size_t idx = 0; idx < inResults.size(); ++idx) {
ordered.emplace(binders.names()[idx], std::move(inResults[idx]));
}
ExplainPrinter printer;
printer.separator("BindBlock:");
for (auto& [name, child] : ordered) {
if constexpr (version < ExplainVersion::V3) {
ExplainPrinter local;
local.print("[").print(name).print("]").print(child);
printer.print(local);
} else if constexpr (version == ExplainVersion::V3) {
printer.separator(" ").fieldName(name).print(child);
} else {
static_assert("Unknown version");
}
}
return printer;
}
static void printFieldProjectionMap(ExplainPrinter& printer, const FieldProjectionMap& map) {
std::map<FieldNameType, ProjectionName> ordered;
if (!map._ridProjection.empty()) {
ordered["<rid>"] = map._ridProjection;
}
if (!map._rootProjection.empty()) {
ordered["<root>"] = map._rootProjection;
}
for (const auto& entry : map._fieldProjections) {
ordered.insert(entry);
}
if constexpr (version < ExplainVersion::V3) {
bool first = true;
for (const auto& [fieldName, projectionName] : ordered) {
if (first) {
first = false;
} else {
printer.print(", ");
}
printer.print("'").print(fieldName).print("': ").print(projectionName);
}
} else if constexpr (version == ExplainVersion::V3) {
ExplainPrinter local;
for (const auto& [fieldName, projectionName] : ordered) {
local.fieldName(fieldName).print(projectionName);
}
printer.fieldName("fieldProjectionMap").print(local);
} else {
static_assert("Unknown version");
}
}
ExplainPrinter transport(const ScanNode& node, ExplainPrinter bindResult) {
ExplainPrinter printer("Scan");
maybePrintProps(printer, node);
printer.separator(" [")
.fieldName("scanDefName", ExplainVersion::V3)
.print(node.getScanDefName())
.separator("]")
.fieldName("bindings", ExplainVersion::V3)
.print(bindResult);
return printer;
}
ExplainPrinter transport(const PhysicalScanNode& node, ExplainPrinter bindResult) {
ExplainPrinter printer("PhysicalScan");
maybePrintProps(printer, node);
printer.separator(" [{");
printFieldProjectionMap(printer, node.getFieldProjectionMap());
printer.separator("}, ")
.fieldName("scanDefName", ExplainVersion::V3)
.print(node.getScanDefName());
printBooleanFlag(printer, "parallel", node.useParallelScan());
printer.separator("]").fieldName("bindings", ExplainVersion::V3).print(bindResult);
return printer;
}
ExplainPrinter transport(const ValueScanNode& node, ExplainPrinter bindResult) {
ExplainPrinter valuePrinter = generate(node.getValueArray());
ExplainPrinter printer("ValueScan");
maybePrintProps(printer, node);
printer.separator(" [")
.fieldName("arraySize")
.print(node.getArraySize())
.separator("]")
.fieldName("values", ExplainVersion::V3)
.print(valuePrinter)
.fieldName("bindings", ExplainVersion::V3)
.print(bindResult);
return printer;
}
ExplainPrinter transport(const CoScanNode& node) {
ExplainPrinter printer("CoScan");
maybePrintProps(printer, node);
printer.separator(" []");
return printer;
}
void printInterval(ExplainPrinter& printer, const IntervalRequirement& interval) {
const BoundRequirement& lowBound = interval.getLowBound();
const BoundRequirement& highBound = interval.getHighBound();
if constexpr (version < ExplainVersion::V3) {
const auto printBoundFn = [](ExplainPrinter& printer, const ABT& bound) {
// Since we are printing on a single level, use V1 printer in order to avoid
// children being reversed.
ExplainGeneratorTransporter<ExplainVersion::V1> gen;
auto boundPrinter = gen.generate(bound);
printer.printSingleLevel(boundPrinter);
};
printer.print(lowBound.isInclusive() ? "[" : "(");
if (lowBound.isInfinite()) {
printer.print("-inf");
} else {
printBoundFn(printer, lowBound.getBound());
}
printer.print(", ");
if (highBound.isInfinite()) {
printer.print("+inf");
} else {
printBoundFn(printer, highBound.getBound());
}
printer.print(highBound.isInclusive() ? "]" : ")");
} else if constexpr (version == ExplainVersion::V3) {
ExplainPrinter lowBoundPrinter;
lowBoundPrinter.fieldName("inclusive")
.print(lowBound.isInclusive())
.fieldName("infinite")
.print(lowBound.isInfinite());
if (!lowBound.isInfinite()) {
ExplainPrinter boundPrinter = generate(lowBound.getBound());
lowBoundPrinter.fieldName("bound").print(boundPrinter);
}
ExplainPrinter highBoundPrinter;
highBoundPrinter.fieldName("inclusive")
.print(highBound.isInclusive())
.fieldName("infinite")
.print(highBound.isInfinite());
if (!highBound.isInfinite()) {
ExplainPrinter boundPrinter = generate(highBound.getBound());
highBoundPrinter.fieldName("bound").print(boundPrinter);
}
printer.fieldName("lowBound")
.print(lowBoundPrinter)
.fieldName("highBound")
.print(highBoundPrinter);
} else {
static_assert("Version not implemented");
}
}
std::string printInterval(const IntervalRequirement& interval) {
ExplainPrinter printer;
printInterval(printer, interval);
return printer.str();
}
ExplainPrinter printIntervalExpr(const IntervalReqExpr::Node& intervalExpr) {
IntervalPrinter<IntervalReqExpr> intervalPrinter(*this);
return intervalPrinter.print(intervalExpr);
}
void printInterval(ExplainPrinter& printer, const MultiKeyIntervalRequirement& interval) {
if constexpr (version < ExplainVersion::V3) {
bool first = true;
for (const auto& entry : interval) {
if (first) {
first = false;
} else {
printer.print(", ");
}
printInterval(printer, entry);
}
} else if constexpr (version == ExplainVersion::V3) {
std::vector<ExplainPrinter> printers;
for (const auto& entry : interval) {
ExplainPrinter local;
printInterval(local, entry);
printers.push_back(std::move(local));
}
printer.print(printers);
} else {
static_assert("Version not implemented");
}
}
template <class T>
class IntervalPrinter {
public:
IntervalPrinter(ExplainGeneratorTransporter& instance) : _instance(instance) {}
ExplainPrinter transport(const typename T::Atom& node) {
ExplainPrinter printer;
printer.separator("{");
_instance.printInterval(printer, node.getExpr());
printer.separator("}");
return printer;
}
template <bool isConjunction>
ExplainPrinter print(std::vector<ExplainPrinter> childResults) {
if constexpr (version < ExplainVersion::V3) {
ExplainPrinter printer;
printer.separator("{");
bool first = true;
for (ExplainPrinter& child : childResults) {
if (first) {
first = false;
} else if constexpr (isConjunction) {
printer.print(" ^ ");
} else {
printer.print(" U ");
}
printer.print(child);
}
printer.separator("}");
return printer;
} else if constexpr (version == ExplainVersion::V3) {
ExplainPrinter printer;
if constexpr (isConjunction) {
printer.fieldName("conjunction");
} else {
printer.fieldName("disjunction");
}
printer.print(childResults);
return printer;
} else {
static_assert("Version not implemented");
}
}
ExplainPrinter transport(const typename T::Conjunction& node,
std::vector<ExplainPrinter> childResults) {
return print<true /*isConjunction*/>(std::move(childResults));
}
ExplainPrinter transport(const typename T::Disjunction& node,
std::vector<ExplainPrinter> childResults) {
return print<false /*isConjunction*/>(std::move(childResults));
}
ExplainPrinter print(const typename T::Node& intervals) {
return algebra::transport<false>(intervals, *this);
}
private:
ExplainGeneratorTransporter& _instance;
};
ExplainPrinter transport(const IndexScanNode& node, ExplainPrinter bindResult) {
ExplainPrinter printer("IndexScan");
maybePrintProps(printer, node);
printer.separator(" [{");
printFieldProjectionMap(printer, node.getFieldProjectionMap());
printer.separator("}, ");
const auto& spec = node.getIndexSpecification();
printer.fieldName("scanDefName")
.print(spec.getScanDefName())
.separator(", ")
.fieldName("indexDefName")
.print(spec.getIndexDefName())
.separator(", ");
printer.fieldName("interval").separator("{");
printInterval(printer, spec.getInterval());
printer.separator("}");
printBooleanFlag(printer, "reversed", spec.isReverseOrder());
printer.separator("]").fieldName("bindings", ExplainVersion::V3).print(bindResult);
return printer;
}
ExplainPrinter transport(const SeekNode& node,
ExplainPrinter bindResult,
ExplainPrinter refsResult) {
ExplainPrinter printer("Seek");
maybePrintProps(printer, node);
printer.separator(" [")
.fieldName("ridProjection")
.print(node.getRIDProjectionName())
.separator(", {");
printFieldProjectionMap(printer, node.getFieldProjectionMap());
printer.separator("}, ")
.fieldName("scanDefName", ExplainVersion::V3)
.print(node.getScanDefName())
.separator("]")
.setChildCount(2)
.fieldName("bindings", ExplainVersion::V3)
.print(bindResult)
.fieldName("references", ExplainVersion::V3)
.print(refsResult);
return printer;
}
ExplainPrinter transport(const MemoLogicalDelegatorNode& node) {
ExplainPrinter printer("MemoLogicalDelegator");
maybePrintProps(printer, node);
printer.separator(" [").fieldName("groupId").print(node.getGroupId()).separator("]");
return printer;
}
ExplainPrinter transport(const MemoPhysicalDelegatorNode& node) {
const auto id = node.getNodeId();
if (_displayProperties) {
const auto& group = _memo->getGroup(id._groupId);
const auto& result = group._physicalNodes.at(id._index);
uassert(6624076,
"Physical delegator must be pointing to an optimized result.",
result._nodeInfo.has_value());
const auto& nodeInfo = *result._nodeInfo;
const ABT& n = nodeInfo._node;
ExplainPrinter nodePrinter = generate(n);
if (n.template is<MemoPhysicalDelegatorNode>()) {
// Handle delegation.
return nodePrinter;
}
ExplainPrinter logPropPrinter = printLogicalProps("Logical", group._logicalProperties);
ExplainPrinter physPropPrinter = printPhysProps("Physical", result._physProps);
ExplainPrinter printer("Properties");
printer.separator(" [")
.fieldName("cost")
.print(nodeInfo._cost.getCost())
.separator(", ")
.fieldName("localCost")
.print(nodeInfo._localCost.getCost())
.separator(", ")
.fieldName("adjustedCE")
.print(nodeInfo._adjustedCE)
.separator("]")
.setChildCount(3)
.fieldName("logicalProperties", ExplainVersion::V3)
.print(logPropPrinter)
.fieldName("physicalProperties", ExplainVersion::V3)
.print(physPropPrinter)
.fieldName("node", ExplainVersion::V3)
.print(nodePrinter);
return printer;
}
ExplainPrinter printer("MemoPhysicalDelegator");
printer.separator(" [")
.fieldName("groupId")
.print(id._groupId)
.separator(", ")
.fieldName("index")
.print(id._index)
.separator("]");
return printer;
}
ExplainPrinter transport(const FilterNode& node,
ExplainPrinter childResult,
ExplainPrinter filterResult) {
ExplainPrinter printer("Filter");
maybePrintProps(printer, node);
printer.separator(" []")
.setChildCount(2)
.fieldName("filter", ExplainVersion::V3)
.print(filterResult)
.fieldName("child", ExplainVersion::V3)
.print(childResult);
return printer;
}
ExplainPrinter transport(const EvaluationNode& node,
ExplainPrinter childResult,
ExplainPrinter projectionResult) {
ExplainPrinter printer("Evaluation");
maybePrintProps(printer, node);
printer.separator(" []")
.setChildCount(2)
.fieldName("projection", ExplainVersion::V3)
.print(projectionResult)
.fieldName("child", ExplainVersion::V3)
.print(childResult);
return printer;
}
void printPartialSchemaReqMap(ExplainPrinter& parent, const PartialSchemaRequirements& reqMap) {
std::vector<ExplainPrinter> printers;
for (const auto& [key, req] : reqMap) {