-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathopt_explain.cc
2660 lines (2301 loc) · 91.8 KB
/
opt_explain.cc
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) 2011, 2024, 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 */
/**
@file sql/opt_explain.cc
"EXPLAIN <command>" implementation.
*/
#include "sql/opt_explain.h"
#include <sys/types.h>
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <functional>
#include <string>
#include <vector>
#include "ft_global.h"
#include "lex_string.h"
#include "m_string.h"
#include "mem_root_deque.h"
#include "my_alloc.h"
#include "my_base.h"
#include "my_bitmap.h"
#include "my_dbug.h"
#include "my_double2ulonglong.h"
#include "my_inttypes.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "my_thread_local.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysql/strings/int2str.h"
#include "mysql/strings/m_ctype.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "sql/auth/auth_acls.h"
#include "sql/auth/sql_security_ctx.h"
#include "sql/current_thd.h"
#include "sql/debug_sync.h" // DEBUG_SYNC
#include "sql/derror.h" // ER_THD
#include "sql/enum_query_type.h"
#include "sql/field.h"
#include "sql/handler.h"
#include "sql/item.h"
#include "sql/item_func.h"
#include "sql/item_subselect.h"
#include "sql/join_optimizer/access_path.h"
#include "sql/join_optimizer/bit_utils.h"
#include "sql/join_optimizer/explain_access_path.h"
#include "sql/key.h"
#include "sql/mysqld.h" // stage_explaining
#include "sql/mysqld_thd_manager.h" // Global_THD_manager
#include "sql/opt_costmodel.h"
#include "sql/opt_explain_format.h"
#include "sql/opt_trace.h" // Opt_trace_*
#include "sql/parse_tree_node_base.h"
#include "sql/protocol.h"
#include "sql/query_term.h"
#include "sql/range_optimizer/group_index_skip_scan_plan.h"
#include "sql/range_optimizer/path_helpers.h"
#include "sql/sql_bitmap.h"
#include "sql/sql_class.h"
#include "sql/sql_cmd.h"
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_executor.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_opt_exec_shared.h"
#include "sql/sql_optimizer.h" // JOIN
#include "sql/sql_parse.h" // is_explainable_query
#include "sql/sql_partition.h" // for make_used_partitions_str()
#include "sql/sql_select.h"
#include "sql/table.h"
#include "sql/table_function.h" // Table_function
#include "sql/visible_fields.h"
#include "sql_string.h"
#include "string_with_len.h"
#include "template_utils.h"
class Opt_trace_context;
using std::function;
using std::string;
using std::vector;
typedef qep_row::extra extra;
static bool mysql_explain_query_expression(THD *explain_thd,
const THD *query_thd,
Query_expression *unit);
const char *join_type_str[] = {
"UNKNOWN", "system", "const", "eq_ref", "ref", "ALL",
"range", "index", "fulltext", "ref_or_null", "index_merge"};
static const enum_query_type cond_print_flags =
enum_query_type(QT_ORDINARY | QT_SHOW_SELECT_NUMBER);
/// First string: for regular EXPLAIN; second: for EXPLAIN CONNECTION
static const char *plan_not_ready[] = {"Not optimized, outer query is empty",
"Plan isn't ready yet"};
static bool ExplainIterator(THD *ethd, const THD *query_thd,
Query_expression *unit);
namespace {
/**
A base for all Explain_* classes
Explain_* classes collect and output EXPLAIN data.
This class hierarchy is a successor of the old select_describe() function
of 5.5.
*/
class Explain {
protected:
THD *const explain_thd; ///< cached THD which runs the EXPLAIN command
const THD *query_thd; ///< THD which runs the query to be explained
const CHARSET_INFO *const cs; ///< cached pointer to system_charset_info
/**
Cached Query_block of the explained query. Used for all explained stmts,
including single-table UPDATE (provides way to access ORDER BY of
UPDATE).
*/
Query_block *const query_block;
Explain_format *const fmt; ///< shortcut for thd->lex->explain_format
enum_parsing_context context_type; ///< associated value for struct. explain
bool order_list; ///< if query block has ORDER BY
const bool explain_other; ///< if we explain other thread than us
protected:
class Lazy_condition : public Lazy {
Item *const condition;
public:
Lazy_condition(Item *condition_arg) : condition(condition_arg) {}
bool eval(String *ret) override {
ret->length(0);
if (condition) condition->print(current_thd, ret, cond_print_flags);
return false;
}
};
explicit Explain(enum_parsing_context context_type_arg, THD *explain_thd_arg,
const THD *query_thd_arg, Query_block *query_block_arg)
: explain_thd(explain_thd_arg),
query_thd(query_thd_arg),
cs(system_charset_info),
query_block(query_block_arg),
fmt(explain_thd->lex->explain_format),
context_type(context_type_arg),
order_list(false),
explain_other(explain_thd != query_thd) {
if (explain_other) query_thd->query_plan.assert_plan_is_locked_if_other();
}
public:
virtual ~Explain() = default;
bool send();
/**
Tells if it is allowed to print the WHERE / GROUP BY / etc
clauses.
*/
bool can_print_clauses() const {
/*
Certain implementations of Item::print() modify the item, so cannot be
called by another thread which does not own the item. Moreover, the
owning thread may be modifying the item at this moment (example:
Item_in_subselect::finalize_materialization_transform() is done
at first execution of the subquery, which happens after the parent query
has a plan, and affects how the parent query would be printed).
*/
return !explain_other;
}
protected:
/**
Explain everything but subqueries
*/
virtual bool shallow_explain();
/**
Explain the rest of things after the @c shallow_explain() call
*/
bool explain_subqueries();
bool mark_subqueries(Item *item, qep_row *destination);
bool prepare_columns();
/**
Push a part of the "extra" column into formatter
Traditional formatter outputs traditional_extra_tags[tag] as is.
Hierarchical formatter outputs a property with the json_extra_tags[tag] name
and a boolean value of true.
@param tag type of the "extra" part
@retval false Ok
@retval true Error (OOM)
*/
bool push_extra(Extra_tag tag) {
extra *e = new (explain_thd->mem_root) extra(tag);
return e == nullptr || fmt->entry()->col_extra.push_back(e);
}
/**
Push a part of the "extra" column into formatter
@param tag type of the "extra" part
@param arg for traditional formatter: rest of the part text,
for hierarchical format: string value of the property
@retval false Ok
@retval true Error (OOM)
*/
bool push_extra(Extra_tag tag, const String &arg) {
if (arg.is_empty()) return push_extra(tag);
extra *e =
new (explain_thd->mem_root) extra(tag, arg.dup(explain_thd->mem_root));
return !e || !e->data || fmt->entry()->col_extra.push_back(e);
}
/**
Push a part of the "extra" column into formatter
@param tag type of the "extra" part
@param arg for traditional formatter: rest of the part text,
for hierarchical format: string value of the property
NOTE: arg must be a long-living string constant.
@retval false Ok
@retval true Error (OOM)
*/
bool push_extra(Extra_tag tag, const char *arg) {
extra *e = new (explain_thd->mem_root) extra(tag, arg);
return !e || fmt->entry()->col_extra.push_back(e);
}
/*
Rest of the functions are overloadable functions, those calculate and fill
"col_*" fields with Items for further sending as EXPLAIN columns.
"explain_*" functions return false on success and true on error (usually
OOM).
*/
virtual bool explain_id();
virtual bool explain_select_type();
virtual bool explain_table_name() { return false; }
virtual bool explain_partitions() { return false; }
virtual bool explain_join_type() { return false; }
virtual bool explain_possible_keys() { return false; }
/** fill col_key and and col_key_len fields together */
virtual bool explain_key_and_len() { return false; }
virtual bool explain_ref() { return false; }
/** fill col_rows and col_filtered fields together */
virtual bool explain_rows_and_filtered() { return false; }
virtual bool explain_extra() { return false; }
virtual bool explain_modify_flags() { return false; }
protected:
/**
Returns true if the WHERE, ORDER BY, GROUP BY, etc clauses can safely be
traversed: it means that we can iterate through them (no element is
added/removed/replaced); the internal details of an element can change
though (in particular if that element is an Item_subselect).
By default, if we are explaining another connection, this is not safe.
*/
virtual bool can_walk_clauses() { return !explain_other; }
virtual enum_parsing_context get_subquery_context(
Query_expression *unit) const;
private:
/**
Returns true if EXPLAIN should not produce any information about subqueries.
*/
virtual bool skip_subqueries() const { return false; }
};
enum_parsing_context Explain::get_subquery_context(
Query_expression *unit) const {
return unit->get_explain_marker(query_thd);
}
/**
Explain_no_table class outputs a trivial EXPLAIN row with "extra" column
This class is intended for simple cases to produce EXPLAIN output
with "No tables used", "No matching records" etc.
Optionally it can output number of estimated rows in the "row"
column.
@note This class also produces EXPLAIN rows for inner units (if any).
*/
class Explain_no_table : public Explain {
private:
const char *message; ///< cached "message" argument
const ha_rows rows; ///< HA_POS_ERROR or cached "rows" argument
public:
Explain_no_table(THD *explain_thd_arg, const THD *query_thd_arg,
Query_block *query_block_arg, const char *message_arg,
enum_parsing_context context_type_arg = CTX_JOIN,
ha_rows rows_arg = HA_POS_ERROR)
: Explain(context_type_arg, explain_thd_arg, query_thd_arg,
query_block_arg),
message(message_arg),
rows(rows_arg) {
if (can_walk_clauses())
order_list = (query_block_arg->order_list.elements != 0);
}
protected:
bool shallow_explain() override;
bool explain_rows_and_filtered() override;
bool explain_extra() override;
bool explain_modify_flags() override;
private:
enum_parsing_context get_subquery_context(
Query_expression *unit) const override;
};
/**
Explain_union_result class outputs EXPLAIN row for UNION
*/
class Explain_setop_result : public Explain {
public:
Explain_setop_result(THD *explain_thd_arg, const THD *query_thd_arg,
Query_block *query_block_arg, Query_term *qt,
enum_parsing_context ctx)
: Explain(ctx, explain_thd_arg, query_thd_arg, query_block_arg),
m_query_term(down_cast<Query_term_set_op *>(qt)) {
assert(m_query_term->term_type() != QT_QUERY_BLOCK);
// Use optimized values from block's join
order_list = !query_block_arg->join->order.empty();
// A plan exists so the reads above are safe:
assert(query_block_arg->join->get_plan_state() != JOIN::NO_PLAN);
}
protected:
bool explain_id() override;
bool explain_table_name() override;
bool explain_join_type() override;
bool explain_extra() override;
/* purecov: begin deadcode */
bool can_walk_clauses() override {
assert(0); // UNION result can't have conditions
return true; // Because we know that we have a plan
}
/* purecov: end */
Query_term_set_op *m_query_term;
};
/**
Common base class for Explain_join and Explain_table
*/
class Explain_table_base : public Explain {
protected:
/**
The QEP_TAB which we are currently explaining. It is NULL for the
inserted table in INSERT/REPLACE SELECT, and single-table UPDATE/DELETE.
@note that you should never read quick() or condition() even for SELECT,
they may change under your feet without holding the mutex;
read quick and condition in this class instead.
*/
QEP_TAB *tab{nullptr};
const TABLE *table{nullptr};
join_type type{JT_UNKNOWN};
AccessPath *range_scan_path{nullptr};
Item *condition{nullptr};
bool dynamic_range{false};
Table_ref *table_ref{nullptr};
bool skip_records_in_range{false};
bool reversed_access{false};
Key_map usable_keys;
Explain_table_base(enum_parsing_context context_type_arg,
THD *const explain_thd_arg, const THD *query_thd_arg,
Query_block *query_block_arg = nullptr,
TABLE *const table_arg = nullptr)
: Explain(context_type_arg, explain_thd_arg, query_thd_arg,
query_block_arg),
table(table_arg) {}
bool explain_partitions() override;
bool explain_possible_keys() override;
bool explain_key_parts(int key, uint key_parts);
bool explain_key_and_len_quick(AccessPath *range_scan);
bool explain_key_and_len_index(int key);
bool explain_key_and_len_index(int key, uint key_length, uint key_parts);
bool explain_extra_common(int range_scan_type, uint keyno);
bool explain_tmptable_and_filesort(bool need_tmp_table_arg,
bool need_sort_arg);
};
/**
Explain_join class produces EXPLAIN output for JOINs
*/
class Explain_join : public Explain_table_base {
private:
bool need_tmp_table; ///< add "Using temporary" to "extra" if true
bool need_order; ///< add "Using filesort"" to "extra" if true
const bool distinct; ///< add "Distinct" string to "extra" column if true
JOIN *join; ///< current JOIN
int range_scan_type; ///< current range scan type, really an AccessPath::Type
public:
Explain_join(THD *explain_thd_arg, const THD *query_thd_arg,
Query_block *query_block_arg, bool need_tmp_table_arg,
bool need_order_arg, bool distinct_arg)
: Explain_table_base(CTX_JOIN, explain_thd_arg, query_thd_arg,
query_block_arg),
need_tmp_table(need_tmp_table_arg),
need_order(need_order_arg),
distinct(distinct_arg),
join(query_block_arg->join) {
assert(join->get_plan_state() == JOIN::PLAN_READY);
order_list = !join->order.empty();
}
private:
// Next 4 functions begin and end context for GROUP BY, ORDER BY and DISTINC
bool begin_sort_context(Explain_sort_clause clause, enum_parsing_context ctx);
bool end_sort_context(Explain_sort_clause clause, enum_parsing_context ctx);
bool begin_simple_sort_context(Explain_sort_clause clause,
enum_parsing_context ctx);
bool end_simple_sort_context(Explain_sort_clause clause,
enum_parsing_context ctx);
bool explain_qep_tab(size_t tab_num);
protected:
bool shallow_explain() override;
bool explain_table_name() override;
bool explain_join_type() override;
bool explain_key_and_len() override;
bool explain_ref() override;
bool explain_rows_and_filtered() override;
bool explain_extra() override;
bool explain_select_type() override;
bool explain_id() override;
bool explain_modify_flags() override;
bool can_walk_clauses() override {
return true; // Because we know that we have a plan
}
};
/**
Explain_table class produce EXPLAIN output for queries without top-level JOIN
This class is a simplified version of the Explain_join class. It works in the
context of queries which implementation lacks top-level JOIN object (EXPLAIN
single-table UPDATE and DELETE).
*/
class Explain_table : public Explain_table_base {
private:
const uint key; ///< cached "key" number argument
const ha_rows limit; ///< HA_POS_ERROR or cached "limit" argument
const bool need_tmp_table; ///< cached need_tmp_table argument
const bool need_sort; ///< cached need_sort argument
const enum_mod_type mod_type; ///< Table modification type
const bool used_key_is_modified; ///< UPDATE command updates used key
const char *message; ///< cached "message" argument
public:
Explain_table(THD *const explain_thd_arg, const THD *query_thd_arg,
Query_block *query_block_arg, TABLE *const table_arg,
enum join_type type_arg, AccessPath *range_scan_arg,
Item *condition_arg, uint key_arg, ha_rows limit_arg,
bool need_tmp_table_arg, bool need_sort_arg,
enum_mod_type mod_type_arg, bool used_key_is_modified_arg,
const char *msg)
: Explain_table_base(CTX_JOIN, explain_thd_arg, query_thd_arg,
query_block_arg, table_arg),
key(key_arg),
limit(limit_arg),
need_tmp_table(need_tmp_table_arg),
need_sort(need_sort_arg),
mod_type(mod_type_arg),
used_key_is_modified(used_key_is_modified_arg),
message(msg) {
type = type_arg;
range_scan_path = range_scan_arg;
condition = condition_arg;
usable_keys = table->possible_quick_keys;
if (can_walk_clauses())
order_list = (query_block_arg->order_list.elements != 0);
}
bool explain_modify_flags() override;
private:
virtual bool explain_tmptable_and_filesort(bool need_tmp_table_arg,
bool need_sort_arg);
bool shallow_explain() override;
bool explain_ref() override;
bool explain_table_name() override;
bool explain_join_type() override;
bool explain_key_and_len() override;
bool explain_rows_and_filtered() override;
bool explain_extra() override;
bool can_walk_clauses() override {
return true; // Because we know that we have a plan
}
};
/**
This class outputs an empty plan for queries that use a secondary engine. It
is only used with the hypergraph optimizer, and only when the traditional
format is specified. The traditional format is not supported by the hypergraph
optimizer, so only an empty plan is shown, with extra information showing a
secondary engine is used.
*/
class Explain_secondary_engine final : public Explain {
public:
Explain_secondary_engine(THD *explain_thd_arg, const THD *query_thd_arg,
Query_block *query_block_arg)
: Explain(CTX_JOIN, explain_thd_arg, query_thd_arg, query_block_arg) {}
protected:
bool explain_select_type() override {
fmt->entry()->col_select_type.set(enum_explain_type::EXPLAIN_NONE);
return false;
}
bool explain_extra() override {
StringBuffer<STRING_BUFFER_USUAL_SIZE> buffer;
bool error = false;
error |= buffer.append(STRING_WITH_LEN("Using secondary engine "));
error |= buffer.append(
ha_resolve_storage_engine_name(SecondaryEngineHandlerton(query_thd)));
error |= buffer.append(
STRING_WITH_LEN(". Use EXPLAIN FORMAT=TREE to show the plan."));
if (error) return error;
return fmt->entry()->col_message.set(buffer);
}
private:
bool skip_subqueries() const override { return true; }
};
} // namespace
/* Explain class functions ****************************************************/
bool Explain::shallow_explain() {
return prepare_columns() || fmt->flush_entry();
}
/**
Qualify subqueries with WHERE/HAVING/ORDER BY/GROUP BY clause type marker
@param item Item tree to find subqueries
@param destination For WHERE clauses
@note WHERE clause belongs to TABLE or QEP_TAB. The @c destination parameter
provides a pointer to QEP data for such a table to associate a future
subquery EXPLAIN output with table QEP provided.
@retval false OK
@retval true Error
*/
bool Explain::mark_subqueries(Item *item, qep_row *destination) {
if (skip_subqueries() || item == nullptr || !fmt->is_hierarchical())
return false;
item->compile(&Item::explain_subquery_checker,
reinterpret_cast<uchar **>(&destination),
&Item::explain_subquery_propagator, nullptr);
return false;
}
static bool explain_ref_key(Explain_format *fmt, uint key_parts,
store_key *key_copy[]) {
if (key_parts == 0) return false;
for (uint part_no = 0; part_no < key_parts; part_no++) {
const store_key *const s_key = key_copy[part_no];
if (s_key == nullptr) {
// Const keys don't need to be copied
if (fmt->entry()->col_ref.push_back(STORE_KEY_CONST_NAME))
return true; /* purecov: inspected */
} else if (fmt->entry()->col_ref.push_back(s_key->name()))
return true; /* purecov: inspected */
}
return false;
}
enum_parsing_context Explain_no_table::get_subquery_context(
Query_expression *unit) const {
const enum_parsing_context context = Explain::get_subquery_context(unit);
if (context == CTX_OPTIMIZED_AWAY_SUBQUERY) return context;
if (context == CTX_DERIVED)
return context;
else if (message != plan_not_ready[explain_other])
/*
When zero result is given all subqueries are considered as optimized
away.
*/
return CTX_OPTIMIZED_AWAY_SUBQUERY;
return context;
}
/**
Traverses SQL clauses of this query specification to identify children
subqueries, marks each of them with the clause they belong to.
Then goes though all children subqueries and produces their EXPLAIN
output, attached to the proper clause's context.
@retval false Ok
@retval true Error (OOM)
*/
bool Explain::explain_subqueries() {
if (skip_subqueries()) return false;
/*
Subqueries in empty queries are neither optimized nor executed. They are
therefore not to be included in the explain output.
*/
if (query_block->is_empty_query()) return false;
for (Query_expression *unit = query_block->first_inner_query_expression();
unit; unit = unit->next_query_expression()) {
Query_block *sl = unit->first_query_block();
enum_parsing_context context = get_subquery_context(unit);
if (context == CTX_NONE) context = CTX_OPTIMIZED_AWAY_SUBQUERY;
uint derived_clone_id = 0;
bool is_derived_clone = false;
if (context == CTX_DERIVED) {
Table_ref *tl = unit->derived_table;
derived_clone_id = tl->query_block_id_for_explain();
assert(derived_clone_id);
is_derived_clone = derived_clone_id != tl->query_block_id();
if (is_derived_clone && !fmt->is_hierarchical()) {
// Don't show underlying tables of derived table clone
continue;
}
}
if (fmt->begin_context(context, unit)) return true;
if (is_derived_clone) fmt->entry()->derived_clone_id = derived_clone_id;
if (mysql_explain_query_expression(explain_thd, query_thd, unit))
return true;
/*
This must be after mysql_explain_query_expression() so that
JOIN::optimize() has run and had a chance to choose materialization.
*/
if (fmt->is_hierarchical() &&
(context == CTX_WHERE || context == CTX_HAVING ||
context == CTX_QUALIFY || context == CTX_SELECT_LIST ||
context == CTX_GROUP_BY_SQ || context == CTX_ORDER_BY_SQ) &&
(!explain_other ||
(sl->join && sl->join->get_plan_state() != JOIN::NO_PLAN)) &&
// Check below requires complete plan
unit->item &&
(unit->item->engine_type() == Item_subselect::HASH_SJ_ENGINE)) {
fmt->entry()->is_materialized_from_subquery = true;
fmt->entry()->col_table_name.set_const("<materialized_subquery>");
fmt->entry()->using_temporary = true;
fmt->entry()->col_join_type.set_const(
join_type_str[unit->item->get_join_type()]);
fmt->entry()->col_key.set_const("<auto_key>");
char buff_key_len[24];
fmt->entry()->col_key_len.set(
buff_key_len,
longlong10_to_str(unit->item->get_table()->key_info[0].key_length,
buff_key_len, 10) -
buff_key_len);
const Index_lookup &ref = unit->item->index_lookup();
if (explain_ref_key(fmt, ref.key_parts, ref.key_copy)) return true;
fmt->entry()->col_rows.set(1);
/*
The value to look up depends on the outer value, so the materialized
subquery is dependent and not cacheable:
*/
fmt->entry()->is_dependent = true;
fmt->entry()->is_cacheable = false;
}
if (fmt->end_context(context)) return true;
}
return false;
}
/**
Pre-calculate table property values for further EXPLAIN output
*/
bool Explain::prepare_columns() {
return explain_id() || explain_select_type() || explain_table_name() ||
explain_partitions() || explain_join_type() ||
explain_possible_keys() || explain_key_and_len() || explain_ref() ||
explain_modify_flags() || explain_rows_and_filtered() ||
explain_extra();
}
/**
Explain class main function
This function:
a) allocates a Query_result_send object (if no one pre-allocated available),
b) calculates and sends whole EXPLAIN data.
@return false if success, true if error
*/
bool Explain::send() {
DBUG_TRACE;
if (fmt->begin_context(context_type, nullptr)) return true;
/* Don't log this into the slow query log */
explain_thd->server_status &=
~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
bool ret = shallow_explain() || explain_subqueries();
if (!ret) ret = fmt->end_context(context_type);
return ret;
}
bool Explain::explain_id() {
fmt->entry()->col_id.set(query_block->select_number);
return false;
}
bool Explain::explain_select_type() {
// ignore top-level Query_blockes
// Elaborate only when plan is ready
if (query_block->master_query_expression()->outer_query_block() &&
query_block->join &&
query_block->join->get_plan_state() != JOIN::NO_PLAN) {
fmt->entry()->is_dependent = query_block->is_dependent();
if (query_block->type() != enum_explain_type::EXPLAIN_DERIVED)
fmt->entry()->is_cacheable = query_block->is_cacheable();
}
fmt->entry()->col_select_type.set(query_block->type());
return false;
}
/* Explain_no_table class functions *******************************************/
bool Explain_no_table::shallow_explain() {
return (fmt->begin_context(CTX_MESSAGE) || Explain::shallow_explain() ||
(can_walk_clauses() &&
mark_subqueries(query_block->where_cond(), fmt->entry())) ||
fmt->end_context(CTX_MESSAGE));
}
bool Explain_no_table::explain_rows_and_filtered() {
/* Don't print estimated # of rows in table for INSERT/REPLACE. */
if (rows == HA_POS_ERROR || fmt->entry()->mod_type == MT_INSERT ||
fmt->entry()->mod_type == MT_REPLACE)
return false;
fmt->entry()->col_rows.set(rows);
return false;
}
bool Explain_no_table::explain_extra() {
return fmt->entry()->col_message.set(message);
}
bool Explain_no_table::explain_modify_flags() {
switch (query_thd->query_plan.get_command()) {
case SQLCOM_UPDATE_MULTI:
case SQLCOM_UPDATE:
fmt->entry()->mod_type = MT_UPDATE;
break;
case SQLCOM_DELETE_MULTI:
case SQLCOM_DELETE:
fmt->entry()->mod_type = MT_DELETE;
break;
case SQLCOM_INSERT_SELECT:
case SQLCOM_INSERT:
fmt->entry()->mod_type = MT_INSERT;
break;
case SQLCOM_REPLACE_SELECT:
case SQLCOM_REPLACE:
fmt->entry()->mod_type = MT_REPLACE;
break;
default:;
}
return false;
}
/* Explain_union_result class functions
* ****************************************/
bool Explain_setop_result::explain_id() { return Explain::explain_id(); }
bool Explain_setop_result::explain_table_name() {
// Get the last of UNION's selects
Query_block *last_query_block =
m_query_term->child(m_query_term->child_count() - 1)->query_block();
;
// # characters needed to print select_number of last select
const int last_length =
(int)log10((double)last_query_block->select_number) + 1;
char table_name_buffer[NAME_LEN];
const char *op_type;
if (context_type == CTX_UNION_RESULT) {
op_type = "<union";
} else if (context_type == CTX_INTERSECT_RESULT) {
op_type = "<intersect";
} else if (context_type == CTX_EXCEPT_RESULT) {
op_type = "<except";
} else {
if (order_list) {
if (query_block->select_limit != nullptr) {
op_type = "<ordered/limited";
} else {
op_type = "<ordered";
}
} else if (query_block->select_limit != nullptr) {
op_type = "<limited";
} else {
op_type = "<ordered";
}
}
const size_t op_type_len = strlen(op_type);
size_t lastop = 0;
size_t len = op_type_len;
memcpy(table_name_buffer, op_type, op_type_len);
/*
- len + lastop: current position in table_name_buffer
- 6 + last_length: the number of characters needed to print
'...,'<last_query_block->select_number>'>\0'
*/
bool overflow = false;
for (size_t idx = 0; idx < m_query_term->child_count(); ++idx) {
if (len + lastop + op_type_len + last_length >= NAME_CHAR_LEN) {
overflow = true;
break;
}
len += lastop;
lastop = snprintf(table_name_buffer + len, NAME_CHAR_LEN - len, "%u,",
m_query_term->child(idx)->query_block()->select_number);
}
if (overflow || len + lastop >= NAME_CHAR_LEN) {
memcpy(table_name_buffer + len, STRING_WITH_LEN("...,"));
len += 4;
lastop = snprintf(table_name_buffer + len, NAME_CHAR_LEN - len, "%u,",
last_query_block->select_number);
}
len += lastop;
table_name_buffer[len - 1] = '>'; // change ',' to '>'
return fmt->entry()->col_table_name.set(table_name_buffer, len);
}
bool Explain_setop_result::explain_join_type() {
fmt->entry()->col_join_type.set_const(join_type_str[JT_ALL]);
return false;
}
bool Explain_setop_result::explain_extra() {
if (!fmt->is_hierarchical()) {
/*
Currently we always use temporary table for UNION result
*/
if (push_extra(ET_USING_TEMPORARY)) return true;
}
/*
here we assume that the query will return at least two rows, so we
show "filesort" in EXPLAIN. Of course, sometimes we'll be wrong
and no filesort will be actually done, but executing all selects in
the UNION to provide precise EXPLAIN information will hardly be
appreciated :)
*/
if (order_list) {
return push_extra(ET_USING_FILESORT);
}
return Explain::explain_extra();
}
/* Explain_table_base class functions *****************************************/
bool Explain_table_base::explain_partitions() {
if (table->part_info)
return make_used_partitions_str(table->part_info,
&fmt->entry()->col_partitions);
return false;
}
bool Explain_table_base::explain_possible_keys() {
if (usable_keys.is_clear_all()) return false;
if ((table->file->ha_table_flags() & HA_NO_INDEX_ACCESS) != 0) return false;
for (uint j = 0; j < table->s->keys; j++) {
if (usable_keys.is_set(j) &&
fmt->entry()->col_possible_keys.push_back(table->key_info[j].name))
return true;
}
return false;
}
bool Explain_table_base::explain_key_parts(int key, uint key_parts) {
KEY_PART_INFO *kp = table->key_info[key].key_part;
for (uint i = 0; i < key_parts; i++, kp++)
if (fmt->entry()->col_key_parts.push_back(
get_field_name_or_expression(explain_thd, kp->field)))
return true;
return false;
}
bool Explain_table_base::explain_key_and_len_quick(AccessPath *path) {
bool ret = false;
StringBuffer<512> str_key(cs);
StringBuffer<512> str_key_len(cs);
if (used_index(path) != MAX_KEY)
ret = explain_key_parts(used_index(range_scan_path),
get_used_key_parts(path));
add_keys_and_lengths(path, &str_key, &str_key_len);
return (ret || fmt->entry()->col_key.set(str_key) ||
fmt->entry()->col_key_len.set(str_key_len));
}
bool Explain_table_base::explain_key_and_len_index(int key) {
assert(key != MAX_KEY);
return explain_key_and_len_index(key, table->key_info[key].key_length,
table->key_info[key].user_defined_key_parts);
}
bool Explain_table_base::explain_key_and_len_index(int key, uint key_length,
uint key_parts) {
assert(key != MAX_KEY);
char buff_key_len[24];
const KEY *key_info = table->key_info + key;
const size_t length =
longlong10_to_str(key_length, buff_key_len, 10) - buff_key_len;
const bool ret = explain_key_parts(key, key_parts);
return (ret || fmt->entry()->col_key.set(key_info->name) ||
fmt->entry()->col_key_len.set(buff_key_len, length));
}
bool Explain_table_base::explain_extra_common(int range_scan_type, uint keyno) {
if (keyno != MAX_KEY && keyno == table->file->pushed_idx_cond_keyno &&
table->file->pushed_idx_cond) {
StringBuffer<160> buff(cs);
if (fmt->is_hierarchical() && can_print_clauses()) {