forked from alibaba/AliSQL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexplain_access_path.cc
More file actions
2107 lines (1913 loc) · 82.7 KB
/
explain_access_path.cc
File metadata and controls
2107 lines (1913 loc) · 82.7 KB
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) 2020, 2025, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "sql/join_optimizer/explain_access_path.h"
#include <functional>
#include <regex>
#include <string>
#include <vector>
#include <openssl/sha.h>
#include "my_base.h"
#include "sha2.h"
#include "sql-common/json_dom.h"
#include "sql/filesort.h"
#include "sql/item_cmpfunc.h"
#include "sql/item_sum.h"
#include "sql/iterators/basic_row_iterators.h"
#include "sql/iterators/bka_iterator.h"
#include "sql/iterators/composite_iterators.h"
#include "sql/iterators/hash_join_iterator.h"
#include "sql/iterators/ref_row_iterators.h"
#include "sql/iterators/sorting_iterator.h"
#include "sql/iterators/timing_iterator.h"
#include "sql/join_optimizer/access_path.h"
#include "sql/join_optimizer/cost_model.h"
#include "sql/join_optimizer/print_utils.h"
#include "sql/join_optimizer/relational_expression.h"
#include "sql/opt_explain.h"
#include "sql/opt_explain_traditional.h"
#include "sql/query_result.h"
#include "sql/range_optimizer/group_index_skip_scan_plan.h"
#include "sql/range_optimizer/index_skip_scan_plan.h"
#include "sql/range_optimizer/internal.h"
#include "sql/range_optimizer/range_optimizer.h"
#include "sql/sql_optimizer.h"
#include "sql/table.h"
#include "template_utils.h"
using std::string;
using std::vector;
/// This structure encapsulates the information needed to create a Json object
/// for a child access path.
struct ExplainChild {
AccessPath *path;
// Normally blank. If not blank, a heading for this iterator
// saying what kind of role it has to the parent if it is not
// obvious. E.g., FilterIterator can print iterators that are
// children because they come out of subselect conditions.
std::string description = "";
// If this child is the root of a new JOIN, it is contained here.
JOIN *join = nullptr;
// If it's convenient to assign json fields for this child while creating this
// structure, then a json object can be allocated and set here.
Json_object *obj = nullptr;
};
/// Convenience function to add a json field.
template <class T, class... Args>
static bool AddMemberToObject(Json_object *obj, const char *alias,
Args &&...ctor_args) {
return obj->add_alias(
alias, create_dom_ptr<T, Args...>(std::forward<Args>(ctor_args)...));
}
template <class T, class... Args>
static bool AddElementToArray(const std::unique_ptr<Json_array> &array,
Args &&...ctor_args) {
return array->append_alias(
create_dom_ptr<T, Args...>(std::forward<Args>(ctor_args)...));
}
static bool PrintRanges(const QUICK_RANGE *const *ranges, unsigned num_ranges,
const KEY_PART_INFO *key_part, bool single_part_only,
const std::unique_ptr<Json_array> &range_array,
string *ranges_out);
static std::unique_ptr<Json_object> ExplainAccessPath(
const AccessPath *path, const AccessPath *materialized_path, JOIN *join,
bool is_root_of_join, Json_object *input_obj = nullptr);
static std::unique_ptr<Json_object> AssignParentPath(
AccessPath *parent_path, const AccessPath *materialized_path,
std::unique_ptr<Json_object> obj, JOIN *join);
inline static double GetJSONDouble(const Json_object *obj, const char *key) {
return down_cast<const Json_double *>(obj->get(key))->value();
}
/*
The index information is displayed like this :
[<Prefix>] [COVERING] INDEX <index_operation>
ON table_alias USING index_name [ (<lookup_condition>) ]
[ OVER <range> [, <range>, ...] ]
[ (REVERSE) ]
[ WITH INDEX CONDITION: <pushed_idx_cond> ]
where <index_operation> =
{scan|skip scan|range scan|lookup|search|
skip scan for grouping|skip scan for deduplication}
where <Prefix> = {Single-row|Multi-range}
Return obj. Not necessary, but for the sake of AddMemberToObject() returning
NULL in case of failure, we need to return something non-NULL to indicate
success.
*/
static bool SetIndexInfoInObject(
string *str, const char *json_index_access_type, const char *prefix,
TABLE *table, const KEY *key, const char *index_access_type,
const string lookup_condition, const string *ranges_text,
std::unique_ptr<Json_array> range_arr, bool reverse, Item *pushed_idx_cond,
Json_object *obj) {
string idx_cond_str = pushed_idx_cond ? ItemToString(pushed_idx_cond) : "";
string covering_index =
string(table->key_read ? "Covering index " : "Index ");
bool error = false;
if (prefix) covering_index[0] = tolower(covering_index[0]);
*str += (prefix ? string(prefix) + " " : "") + covering_index +
index_access_type + // lookup/scan/search
" on " + table->alias + " using " + key->name +
(!lookup_condition.empty() ? " (" + lookup_condition + ")" : "") +
(ranges_text != nullptr ? " over " + *ranges_text : "") +
(reverse ? " (reverse)" : "") +
(pushed_idx_cond ? ", with index condition: " + idx_cond_str : "");
*str += table->file->explain_extra();
error |= AddMemberToObject<Json_string>(obj, "access_type", "index");
error |= AddMemberToObject<Json_string>(obj, "index_access_type",
json_index_access_type);
error |= AddMemberToObject<Json_boolean>(obj, "covering", table->key_read);
error |= AddMemberToObject<Json_string>(obj, "table_name", table->alias);
error |= AddMemberToObject<Json_string>(obj, "index_name", key->name);
if (!lookup_condition.empty())
error |= AddMemberToObject<Json_string>(obj, "lookup_condition",
lookup_condition);
if (range_arr) error |= obj->add_alias("ranges", std::move(range_arr));
if (reverse) error |= AddMemberToObject<Json_boolean>(obj, "reverse", true);
if (pushed_idx_cond)
error |= AddMemberToObject<Json_string>(obj, "pushed_index_condition",
idx_cond_str);
if (!table->file->explain_extra().empty())
error |= AddMemberToObject<Json_string>(obj, "message",
table->file->explain_extra());
return error;
}
string JoinTypeToString(JoinType join_type) {
switch (join_type) {
case JoinType::INNER:
return "inner join";
case JoinType::OUTER:
return "left join";
case JoinType::ANTI:
return "antijoin";
case JoinType::SEMI:
return "semijoin";
default:
assert(false);
return "<error>";
}
}
string HashJoinTypeToString(RelationalExpression::Type join_type,
string *explain_json_value) {
switch (join_type) {
case RelationalExpression::INNER_JOIN:
case RelationalExpression::STRAIGHT_INNER_JOIN:
if (explain_json_value)
*explain_json_value = JoinTypeToString(JoinType::INNER);
return "Inner hash join";
case RelationalExpression::LEFT_JOIN:
if (explain_json_value)
*explain_json_value = JoinTypeToString(JoinType::OUTER);
return "Left hash join";
case RelationalExpression::ANTIJOIN:
if (explain_json_value)
*explain_json_value = JoinTypeToString(JoinType::ANTI);
return "Hash antijoin";
case RelationalExpression::SEMIJOIN:
if (explain_json_value)
*explain_json_value = JoinTypeToString(JoinType::SEMI);
return "Hash semijoin";
default:
assert(false);
return "<error>";
}
}
static bool GetAccessPathsFromItem(Item *item_arg, const char *source_text,
vector<ExplainChild> *children) {
return WalkItem(
item_arg, enum_walk::POSTFIX, [children, source_text](Item *item) {
if (item->type() != Item::SUBSELECT_ITEM) {
return false;
}
Item_subselect *subselect = down_cast<Item_subselect *>(item);
Query_block *query_block = subselect->unit->first_query_block();
char description[256];
if (query_block->is_dependent()) {
snprintf(description, sizeof(description),
"Select #%d (subquery in %s; dependent)",
query_block->select_number, source_text);
} else if (!query_block->is_cacheable()) {
snprintf(description, sizeof(description),
"Select #%d (subquery in %s; uncacheable)",
query_block->select_number, source_text);
} else {
snprintf(description, sizeof(description),
"Select #%d (subquery in %s; run only once)",
query_block->select_number, source_text);
}
subselect->unit->finalize(current_thd);
AccessPath *path;
if (subselect->unit->root_access_path() != nullptr) {
path = subselect->unit->root_access_path();
} else {
path = subselect->unit->item->root_access_path();
}
Json_object *child_obj = new (std::nothrow) Json_object();
if (child_obj == nullptr) return true;
// Populate the subquery-specific json fields.
bool error = false;
error |= AddMemberToObject<Json_boolean>(child_obj, "subquery", true);
error |= AddMemberToObject<Json_string>(child_obj, "subquery_location",
source_text);
if (query_block->is_dependent())
error |=
AddMemberToObject<Json_boolean>(child_obj, "dependent", true);
if (query_block->is_cacheable())
error |=
AddMemberToObject<Json_boolean>(child_obj, "cacheable", true);
children->push_back({path, description, query_block->join, child_obj});
return error != 0;
});
}
static bool GetAccessPathsFromSelectList(JOIN *join,
vector<ExplainChild> *children) {
if (join == nullptr) {
return false;
}
// Look for any Items in the projection list itself.
for (Item *item : *join->get_current_fields()) {
if (GetAccessPathsFromItem(item, "projection", children)) return true;
}
// Look for any Items that were materialized into fields during execution.
for (uint table_idx = join->primary_tables; table_idx < join->tables;
++table_idx) {
QEP_TAB *qep_tab = &join->qep_tab[table_idx];
if (qep_tab != nullptr && qep_tab->tmp_table_param != nullptr) {
for (Func_ptr &func : *qep_tab->tmp_table_param->items_to_copy) {
if (GetAccessPathsFromItem(func.func(), "projection", children))
return true;
}
}
}
return false;
}
static std::unique_ptr<Json_object> ExplainMaterializeAccessPath(
const AccessPath *path, JOIN *join, std::unique_ptr<Json_object> ret_obj,
vector<ExplainChild> *children, bool explain_analyze) {
Json_object *obj = ret_obj.get();
bool error = false;
MaterializePathParameters *param = path->materialize().param;
/*
There may be multiple references to a CTE, but we should only print the
plan once.
*/
const bool explain_cte_now = param->cte != nullptr && [&]() {
if (explain_analyze) {
/*
Find the temporary table for which the CTE was materialized, if there
is one.
*/
if (path->iterator == nullptr ||
path->iterator->GetProfiler()->GetNumInitCalls() == 0) {
// If the CTE was never materialized, print it at the first reference.
return param->table == param->cte->tmp_tables[0]->table &&
std::none_of(param->cte->tmp_tables.cbegin(),
param->cte->tmp_tables.cend(),
[](const Table_ref *tab) {
return tab->table->materialized;
});
} else {
// The CTE was materialized here, print it now with cost data.
return true;
}
} else {
// If we do not want cost data, print the plan at the first reference.
return param->table == param->cte->tmp_tables[0]->table;
}
}();
const bool is_set_operation = param->query_blocks.size() > 1;
string str;
const bool doing_dedup = MaterializeIsDoingDeduplication(param->table);
if (param->cte != nullptr) {
error |= AddMemberToObject<Json_boolean>(obj, "cte", true);
if (param->cte->recursive) {
error |= AddMemberToObject<Json_boolean>(obj, "recursive", true);
str = "Materialize recursive CTE " + to_string(param->cte->name);
} else {
if (is_set_operation) {
str = "Materialize union CTE " + to_string(param->cte->name);
error |= AddMemberToObject<Json_boolean>(obj, "union", true);
} else {
str = "Materialize CTE " + to_string(param->cte->name);
}
if (param->cte->tmp_tables.size() > 1) {
str += " if needed";
if (!explain_cte_now) {
// See children().
str += " (query plan printed elsewhere)";
}
}
}
} else if (is_set_operation) {
if (param->table->is_union_or_table()) {
if (doing_dedup) {
str = "Union materialize";
} else {
str = "Union all materialize";
}
error |= AddMemberToObject<Json_boolean>(obj, "union", true);
} else {
if (param->table->is_except()) {
if (param->table->is_distinct()) {
str = "Except materialize";
} else {
str = "Except all materialize";
}
error |= AddMemberToObject<Json_boolean>(obj, "except", true);
} else {
if (param->table->is_distinct()) {
str = "Intersect materialize";
} else {
str = "Intersect all materialize";
}
error |= AddMemberToObject<Json_boolean>(obj, "intersect", true);
}
}
} else if (param->rematerialize) {
error |= AddMemberToObject<Json_boolean>(obj, "temp_table", true);
str = "Temporary table";
} else {
str = "Materialize";
}
const bool union_dedup = param->table->is_union_or_table() && doing_dedup;
if (union_dedup ||
(!param->table->is_union_or_table() && param->table->is_distinct())) {
error |= AddMemberToObject<Json_boolean>(obj, "deduplication", true);
str += " with deduplication";
} // else: do not print deduplication for intersect, except
if (param->invalidators != nullptr) {
std::unique_ptr<Json_array> cache_invalidators(new (std::nothrow)
Json_array());
if (cache_invalidators == nullptr) return nullptr;
bool first = true;
str += " (invalidate on row from ";
for (const AccessPath *invalidator : *param->invalidators) {
if (!first) {
str += "; ";
}
first = false;
str += invalidator->cache_invalidator().name;
error |= AddElementToArray<Json_string>(
cache_invalidators, invalidator->cache_invalidator().name);
}
str += ")";
error |=
obj->add_alias("cache_invalidators", std::move(cache_invalidators));
}
error |= AddMemberToObject<Json_string>(obj, "operation", str);
/* Move the Materialize to the bottom of its table path, and return a new
* object for this table path.
*/
ret_obj = AssignParentPath(path->materialize().table_path, path,
std::move(ret_obj), join);
// Children.
// If a CTE is referenced multiple times, only bother printing its query plan
// once, instead of repeating it over and over again.
//
// TODO(sgunders): Consider printing CTE query plans on the top level of the
// query block instead?
if (param->cte != nullptr && !explain_cte_now) {
return (error ? nullptr : std::move(ret_obj));
}
char heading[256] = "";
if (param->limit_rows != HA_POS_ERROR) {
// We call this “Limit table size” as opposed to “Limit”, to be able
// to distinguish between the two in EXPLAIN when debugging.
if (MaterializeIsDoingDeduplication(param->table)) {
snprintf(heading, sizeof(heading), "Limit table size: %llu unique row(s)",
param->limit_rows);
} else {
snprintf(heading, sizeof(heading), "Limit table size: %llu row(s)",
param->limit_rows);
}
}
// We don't list the table iterator as an explicit child; we mark it in
// our description instead. (Anything else would look confusingly much
// like a join.)
for (const MaterializePathParameters::QueryBlock &query_block :
param->query_blocks) {
string this_heading = heading;
if (query_block.disable_deduplication_by_hash_field) {
if (this_heading.empty()) {
this_heading = "Disable deduplication";
} else {
this_heading += ", disable deduplication";
}
}
if (!param->table->is_union_or_table() &&
(param->table->is_except() && param->table->is_distinct()) &&
query_block.m_operand_idx > 0 &&
(query_block.m_operand_idx < query_block.m_first_distinct)) {
if (this_heading.empty()) {
this_heading = "Disable deduplication";
} else {
this_heading += ", disable deduplication";
}
}
if (query_block.is_recursive_reference) {
if (this_heading.empty()) {
this_heading = "Repeat until convergence";
} else {
this_heading += ", repeat until convergence";
}
}
children->push_back(
{query_block.subquery_path, this_heading, query_block.join});
}
return (error ? nullptr : std::move(ret_obj));
}
/**
AccessPath objects of type TEMPTABLE_AGGREGATE, MATERIALIZE, and
MATERIALIZE_INFORMATION_SCHEMA_TABLE represent a materialized
set of rows. These materialized AccessPaths have a another path member
(called table_path) that iterates over the materialized rows.
So codewise, table_path is a child of the materialized path, even if it
is logically the parent, as it consumes the results from the materialized
path. For that reason, we present table_path above the materialized path in
'explain' output (@see AddPathCost for details).
This function therefore sets the JSON object for the materialized
path to be the leaf descendant of the table_path JSON
object. (Note that in some cases table_path does not operate
directly on materialized_path. Instead, table_path is the first in
a chain of paths where the final path is typically a TABLE_SCAN of
REF access path that the iterates over the materialized rows.)
@param table_path the head of the chain of paths that iterates over the
materialized rows.
@param materialized_path if (the leaf descendant of) table_path iterates
over the rows from a MATERIALIZE path, then 'materialized_path'
is that path. Otherwise it is nullptr.
@param materialized_obj the JSON object describing the materialized path.
@param join the JOIN to which 'table_path' belongs.
@returns the JSON object describing table_path.
*/
static std::unique_ptr<Json_object> AssignParentPath(
AccessPath *table_path, const AccessPath *materialized_path,
std::unique_ptr<Json_object> materialized_obj, JOIN *join) {
// We don't want to include the SELECT subquery list in the parent path;
// Let them get printed in the actual root node. So is_root_of_join=false.
std::unique_ptr<Json_object> table_obj = ExplainAccessPath(
table_path, materialized_path, join, /*is_root_of_join=*/false);
if (table_obj == nullptr) return nullptr;
/* Get the bottommost object from the new object tree. */
Json_object *bottom_obj = table_obj.get();
while (bottom_obj->get("inputs") != nullptr) {
Json_dom *children = bottom_obj->get("inputs");
assert(children->json_type() == enum_json_type::J_ARRAY);
Json_array *children_array = down_cast<Json_array *>(children);
bottom_obj = down_cast<Json_object *>((*children_array)[0]);
}
/* Place the input object as a child of the bottom-most object */
std::unique_ptr<Json_array> children(new (std::nothrow) Json_array());
if (children == nullptr ||
children->append_alias(std::move(materialized_obj)))
return nullptr;
if (bottom_obj->add_alias("inputs", std::move(children))) return nullptr;
return table_obj;
}
static bool ExplainIndexSkipScanAccessPath(Json_object *obj,
const AccessPath *path,
JOIN *join [[maybe_unused]],
string *description) {
TABLE *table = path->index_skip_scan().table;
KEY *key_info = table->key_info + path->index_skip_scan().index;
string ranges;
IndexSkipScanParameters *param = path->index_skip_scan().param;
// Print out any equality ranges.
bool first = true;
std::unique_ptr<Json_array> range_arr(new (std::nothrow) Json_array());
if (range_arr == nullptr) return true;
for (unsigned key_part_idx = 0; key_part_idx < param->eq_prefix_key_parts;
++key_part_idx) {
if (!first) {
ranges += ", ";
}
first = false;
string range = param->index_info->key_part[key_part_idx].field->field_name;
string range_short_text;
Bounds_checked_array<unsigned char *> prefixes =
param->eq_prefixes[key_part_idx].eq_key_prefixes;
if (prefixes.size() == 1) {
range += " = ";
String out;
print_key_value(&out, ¶m->index_info->key_part[key_part_idx],
prefixes[0]);
range += to_string(out);
} else {
range += " IN (";
for (unsigned i = 0; i < prefixes.size(); ++i) {
if (i == 2 && prefixes.size() > 3) {
range_short_text =
range + StringPrintf(", (%zu more))", prefixes.size() - 2);
}
if (i != 0) {
range += ", ";
}
String out;
print_key_value(&out, ¶m->index_info->key_part[key_part_idx],
prefixes[i]);
range += to_string(out);
}
range += ")";
}
if (AddElementToArray<Json_string>(range_arr, range)) return true;
// For IN clause above, we have made range_short_text; so use that if it's
// available, rather than the full string stored in 'range'.
ranges += (range_short_text.empty() ? range : range_short_text);
}
// Then the ranges.
if (!first) {
ranges += ", ";
}
String out;
append_range(&out, param->range_key_part, param->min_range_key,
param->max_range_key, param->range_cond_flag);
ranges += to_string(out);
if (AddElementToArray<Json_string>(range_arr, to_string(out))) return true;
// NOTE: Currently, index skip scan is always covering, but there's no
// good reason why we cannot fix this limitation in the future.
return SetIndexInfoInObject(
description, "index_skip_scan", nullptr, table, key_info, "skip scan",
/*lookup condition*/ "", &ranges, std::move(range_arr), /*reverse*/ false,
/*push_condition*/ nullptr, obj);
}
static bool ExplainGroupIndexSkipScanAccessPath(Json_object *obj,
const AccessPath *path,
JOIN *join [[maybe_unused]],
string *description) {
TABLE *table = path->group_index_skip_scan().table;
KEY *key_info = table->key_info + path->group_index_skip_scan().index;
GroupIndexSkipScanParameters *param = path->group_index_skip_scan().param;
string ranges;
bool error = false;
std::unique_ptr<Json_array> range_arr(new (std::nothrow) Json_array());
if (range_arr == nullptr) return true;
// Print out prefix ranges, if any.
if (!param->prefix_ranges.empty()) {
error |= PrintRanges(param->prefix_ranges.data(),
param->prefix_ranges.size(), key_info->key_part,
/*single_part_only=*/false, range_arr, &ranges);
}
// Print out the ranges on the MIN/MAX keypart, if we have them.
// (We don't print infix ranges, because they seem to be in an unusual
// format.)
if (!param->min_max_ranges.empty()) {
if (!param->prefix_ranges.empty()) {
ranges += ", ";
}
error |= PrintRanges(param->min_max_ranges.data(),
param->min_max_ranges.size(), param->min_max_arg_part,
/*single_part_only=*/true, range_arr, &ranges);
}
// NOTE: Currently, group index skip scan is always covering, but there's no
// good reason why we cannot fix this limitation in the future.
error |= SetIndexInfoInObject(
description, "group_index_skip_scan", nullptr, table, key_info,
(param->min_max_arg_part ? "skip scan for grouping"
: "skip scan for deduplication"),
/*lookup condition*/ "", (!ranges.empty() ? &ranges : nullptr),
std::move(range_arr),
/*reverse*/ false, /*push_condition*/ nullptr, obj);
return error;
}
static bool AddChildrenFromPushedCondition(const TABLE *table,
vector<ExplainChild> *children) {
/*
A table access path is normally a leaf node in the set of paths.
The exception is if a subquery was included as part of an
'engine_condition_pushdown'. In such cases the subquery has
been evaluated prior to accessing this table, and the result(s)
from the subquery materialized into the pushed condition.
Report such subqueries as children of this table.
*/
Item *pushed_cond = const_cast<Item *>(table->file->pushed_cond);
if (pushed_cond != nullptr) {
if (GetAccessPathsFromItem(pushed_cond, "pushed condition", children))
return true;
}
return false;
}
/*
Returns the range through the return value (to be used in TREE format
synopsis), and also appends the range to the range_array (to be used for
JSON format field). The only reason the return value cannot be used for JSON
format is because we truncate it when there are too many ranges; we do
want to keep the full range for JSON format.
*/
static bool PrintRanges(const QUICK_RANGE *const *ranges, unsigned num_ranges,
const KEY_PART_INFO *key_part, bool single_part_only,
const std::unique_ptr<Json_array> &range_array,
string *ranges_out) {
string range, shortened_range;
for (unsigned range_idx = 0; range_idx < num_ranges; ++range_idx) {
if (range_idx == 2 && num_ranges > 3) {
char str[256];
snprintf(str, sizeof(str), " OR (%u more)", num_ranges - 2);
// Save the shortened version for TREE format.
shortened_range = range + str;
}
if (range_idx > 0) range += " OR ";
String str;
if (single_part_only) {
// key_part is the part we are printing on,
// and we have to ignore min_keypart_map / max_keypart_map,
// so we cannot use append_range_to_string().
append_range(&str, key_part, ranges[range_idx]->min_key,
ranges[range_idx]->max_key, ranges[range_idx]->flag);
} else {
// NOTE: key_part is the first keypart in the key.
append_range_to_string(ranges[range_idx], key_part, &str);
}
range += "(" + to_string(str) + ")";
}
if (AddElementToArray<Json_string>(range_array, range)) return true;
*ranges_out = (shortened_range.empty() ? range : shortened_range);
return false;
}
static bool AddChildrenToObject(Json_object *obj,
const vector<ExplainChild> &children,
JOIN *parent_join, bool parent_is_root_of_join,
string alias) {
if (children.empty()) return false;
std::unique_ptr<Json_array> children_json(new (std::nothrow) Json_array());
if (children_json == nullptr) return true;
for (const ExplainChild &child : children) {
JOIN *subjoin = child.join != nullptr ? child.join : parent_join;
bool child_is_root_of_join =
subjoin != parent_join || parent_is_root_of_join;
std::unique_ptr<Json_object> child_obj = ExplainAccessPath(
child.path, nullptr, subjoin, child_is_root_of_join, child.obj);
if (child_obj == nullptr) return true;
if (!child.description.empty()) {
if (AddMemberToObject<Json_string>(child_obj.get(), "heading",
child.description))
return true;
}
if (children_json->append_alias(std::move(child_obj))) return true;
}
return obj->add_alias(alias, std::move(children_json));
}
static std::unique_ptr<Json_object> ExplainQueryPlan(
const AccessPath *path, THD::Query_plan const *query_plan, JOIN *join,
bool is_root_of_join) {
string dml_desc;
std::unique_ptr<Json_object> obj = nullptr;
/* Create a Json object for the SELECT path */
if (path != nullptr) {
obj = ExplainAccessPath(path, nullptr, join, is_root_of_join);
if (obj == nullptr) return nullptr;
}
if (query_plan != nullptr) {
switch (query_plan->get_command()) {
case SQLCOM_INSERT_SELECT:
case SQLCOM_INSERT:
dml_desc = string("Insert into ") +
query_plan->get_lex()->insert_table_leaf->table->alias;
break;
case SQLCOM_REPLACE_SELECT:
case SQLCOM_REPLACE:
dml_desc = string("Replace into ") +
query_plan->get_lex()->insert_table_leaf->table->alias;
break;
default:
// SELECTs have no top-level node.
break;
}
}
/* If there is a DML node, add it on top of the SELECT plan */
if (!dml_desc.empty()) {
std::unique_ptr<Json_object> dml_obj(new (std::nothrow) Json_object());
if (dml_obj == nullptr) return nullptr;
if (AddMemberToObject<Json_string>(dml_obj.get(), "operation", dml_desc))
return nullptr;
/* There might not be a select plan. E.g. INSERT ... VALUES() */
if (obj != nullptr) {
std::unique_ptr<Json_array> children(new (std::nothrow) Json_array());
if (children == nullptr || children->append_alias(std::move(obj)))
return nullptr;
if (dml_obj->add_alias("inputs", std::move(children))) return nullptr;
}
obj = std::move(dml_obj);
}
return obj;
}
/** Append the various costs.
@param path the path that we add costs for.
@param materialized_path the MATERIALIZE path for which 'path' is the
table_path, or nullptr 'path' is not a table_path.
@param obj the JSON object describing 'path'.
@param explain_analyze true if we run an 'eaxplain analyze' command.
@returns true iff there was an error.
*/
static bool AddPathCosts(const AccessPath *path,
const AccessPath *materialized_path, Json_object *obj,
bool explain_analyze) {
const AccessPath *const table_path = path->type == AccessPath::MATERIALIZE
? path->materialize().table_path
: nullptr;
double cost;
/*
A MATERIALIZE AccessPath has a child path (called table_path)
that iterates over the materialized rows.
So codewise, table_path is a child of materialized_path, even if it is
logically the parent, as it consumes the results from materialized_path.
For that reason, we present table_path above materialized_path in
'explain' output, e.g.:
.-> Sort: i (cost=8.45..8.45 rows=10)
. -> Table scan on <union temporary> (cost=1.76..4.12 rows=10)
. -> Union materialize with deduplication (cost=1.50..1.50 rows=10)
. -> Table scan on t1 (cost=0.05..0.25 rows=5)
. -> Table scan on t2 (cost=0.05..0.25 rows=5)
The cost of an access path includes the cost all of its descendants.
Since table_path is codewise a child of materialized_path, this means that:
- The cost of table_path is the cost of accessing the materialized
structure plus the cost of the descendants (inputs) of materialized_path.
- The cost of materialized_path is the cost of materialization plus
the cost of table_path.
When we wish to display table_path as the parent of materialized_path,
we need to compensate for this:
- For table_path, we show the cost of materialized_path, as this includes
the cost of materialization, iteration and the descendants.
- For the MATERIALIZE AccessPath we show the cost of the descendants plus
the cost of materialization.
*/
if (materialized_path == nullptr) {
if (table_path == nullptr) {
cost = std::max(0.0, path->cost);
} else {
assert(path->materialize().subquery_cost >= 0.0);
cost = path->materialize().subquery_cost +
kMaterializeOneRowCost * path->num_output_rows();
}
} else {
assert(materialized_path->cost >= 0.0);
cost = materialized_path->cost;
}
bool error = false;
if (path->num_output_rows() >= 0.0) {
// Calculate first row cost
double init_cost;
if (materialized_path == nullptr) {
if (table_path == nullptr) {
init_cost = path->init_cost;
} else {
init_cost = cost;
}
} else {
init_cost = materialized_path->init_cost;
}
if (init_cost >= 0.0) {
double first_row_cost;
if (path->num_output_rows() <= 1.0) {
first_row_cost = cost;
} else {
first_row_cost =
init_cost + (cost - init_cost) / path->num_output_rows();
}
error |= AddMemberToObject<Json_double>(obj, "estimated_first_row_cost",
first_row_cost);
}
error |= AddMemberToObject<Json_double>(obj, "estimated_total_cost", cost);
error |= AddMemberToObject<Json_double>(obj, "estimated_rows",
path->num_output_rows());
} /* if (path->num_output_rows() >= 0.0) */
/* Add analyze figures */
if (explain_analyze) {
int num_init_calls = 0;
if (path->iterator != nullptr) {
const IteratorProfiler *const profiler = path->iterator->GetProfiler();
if ((num_init_calls = profiler->GetNumInitCalls()) != 0) {
error |= AddMemberToObject<Json_double>(
obj, "actual_first_row_ms",
profiler->GetFirstRowMs() / profiler->GetNumInitCalls());
error |= AddMemberToObject<Json_double>(
obj, "actual_last_row_ms",
profiler->GetLastRowMs() / profiler->GetNumInitCalls());
error |= AddMemberToObject<Json_double>(
obj, "actual_rows",
static_cast<double>(profiler->GetNumRows()) / num_init_calls);
error |=
AddMemberToObject<Json_int>(obj, "actual_loops", num_init_calls);
}
}
if (num_init_calls == 0) {
error |= AddMemberToObject<Json_null>(obj, "actual_first_row_ms");
error |= AddMemberToObject<Json_null>(obj, "actual_last_row_ms");
error |= AddMemberToObject<Json_null>(obj, "actual_rows");
error |= AddMemberToObject<Json_null>(obj, "actual_loops");
}
}
return error;
}
/**
Given a json object, update it's appropriate json fields according to the
input path. Also update the 'children' with a flat list of direct children
of the passed object. In most of cases, the returned object is same as the
input object, but for some paths it can be different. So callers should use
the returned object.
Note: This function has shown to consume excessive stack space, particularly
in debug builds. Hence make sure this function does not directly or
indirectly create any json children objects recursively. It may cause stack
overflow. Hence json children are created only after this function returns
in function ExplainAccessPath().
@param ret_obj The JSON object describing 'path'.
@param path the path to describe.
@param materialized_path if 'path' is the table_path of a MATERIALIZE path,
then materialized_path is that path. Otherwise it is nullptr.
@param join the JOIN to which 'path' belongs.
@param children the paths that are the children of the path that the
returned JSON object represents (i.e. the next paths to be explained).
@returns either ret_obj or a new JSON object with ret_obj as a descendant.
*/
static std::unique_ptr<Json_object> SetObjectMembers(
std::unique_ptr<Json_object> ret_obj, const AccessPath *path,
const AccessPath *materialized_path, JOIN *join,
vector<ExplainChild> *children) {
bool error = false;
string description;
// The obj to be returned might get changed when processing some of the
// paths. So keep a handle to the original object, in case we later add any
// more fields.
Json_object *obj = ret_obj.get();
/* Get path-specific info, including the description string */
switch (path->type) {
case AccessPath::TABLE_SCAN: {
TABLE *table = path->table_scan().table;
description += string("Table scan on ") + table->alias;
if (table->s->is_secondary_engine()) {
error |= AddMemberToObject<Json_string>(obj, "secondary_engine",
table->file->table_type());
description +=
string(" in secondary engine ") + table->file->table_type();
}
description += table->file->explain_extra();
error |= AddMemberToObject<Json_string>(obj, "table_name", table->alias);
error |= AddMemberToObject<Json_string>(obj, "access_type", "table");
if (!table->file->explain_extra().empty())
error |= AddMemberToObject<Json_string>(obj, "message",
table->file->explain_extra());
error |= AddChildrenFromPushedCondition(table, children);
break;
}
case AccessPath::INDEX_SCAN: {
TABLE *table = path->index_scan().table;
assert(table->file->pushed_idx_cond == nullptr);
const KEY *key = &table->key_info[path->index_scan().idx];
error |= SetIndexInfoInObject(&description, "index_scan", nullptr, table,
key, "scan",
/*lookup condition*/ "", /*range*/ nullptr,
nullptr, path->index_scan().reverse,
/*push_condition*/ nullptr, obj);
error |= AddChildrenFromPushedCondition(table, children);
break;
}
case AccessPath::REF: {
TABLE *table = path->ref().table;
const KEY *key = &table->key_info[path->ref().ref->key];
error |= SetIndexInfoInObject(
&description, "index_lookup", nullptr, table, key, "lookup",
RefToString(*path->ref().ref, key, /*include_nulls=*/false),
/*ranges=*/nullptr, nullptr, path->ref().reverse,
table->file->pushed_idx_cond, obj);
error |= AddChildrenFromPushedCondition(table, children);
break;
}
case AccessPath::REF_OR_NULL: {
TABLE *table = path->ref_or_null().table;
const KEY *key = &table->key_info[path->ref_or_null().ref->key];
error |= SetIndexInfoInObject(
&description, "index_lookup", nullptr, table, key, "lookup",
RefToString(*path->ref_or_null().ref, key, /*include_nulls=*/true),
/*ranges=*/nullptr, nullptr, false, table->file->pushed_idx_cond,
obj);
error |= AddChildrenFromPushedCondition(table, children);
break;