-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathsql_optimizer.cc
11815 lines (10474 loc) · 452 KB
/
sql_optimizer.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) 2000, 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
@brief Optimize query expressions: Make optimal table join order, select
optimal access methods per table, apply grouping, sorting and
limit processing.
@defgroup Query_Optimizer Query Optimizer
@{
*/
#include "sql/sql_optimizer.h"
#include "my_base.h"
#include "sql/sql_optimizer_internal.h"
#include <limits.h>
#include <algorithm>
#include <atomic>
#include <bit>
#include <cmath>
#include <deque>
#include <limits>
#include <new>
#include <string>
#include <utility>
#include <vector>
#include "field_types.h" // enum_field_types
#include "ft_global.h"
#include "mem_root_deque.h"
#include "memory_debugging.h"
#include "my_bitmap.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "mysql/strings/m_ctype.h"
#include "mysql/udf_registration_types.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "scope_guard.h"
#include "sql/check_stack.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/error_handler.h" // Functional_index_error_handler
#include "sql/field.h"
#include "sql/handler.h"
#include "sql/item.h"
#include "sql/item_cmpfunc.h"
#include "sql/item_func.h"
#include "sql/item_row.h"
#include "sql/item_subselect.h"
#include "sql/item_sum.h" // Item_sum
#include "sql/iterators/basic_row_iterators.h"
#include "sql/iterators/timing_iterator.h"
#include "sql/join_optimizer/access_path.h"
#include "sql/join_optimizer/bit_utils.h"
#include "sql/join_optimizer/join_optimizer.h"
#include "sql/join_optimizer/optimizer_trace.h"
#include "sql/join_optimizer/relational_expression.h"
#include "sql/join_optimizer/walk_access_paths.h"
#include "sql/key.h"
#include "sql/key_spec.h"
#include "sql/lock.h" // mysql_unlock_some_tables
#include "sql/mysqld.h" // stage_optimizing
#include "sql/nested_join.h"
#include "sql/opt_costmodel.h"
#include "sql/opt_explain.h" // join_type_str
#include "sql/opt_hints.h" // hint_table_state
#include "sql/opt_trace.h" // Opt_trace_object
#include "sql/opt_trace_context.h"
#include "sql/parse_tree_node_base.h"
#include "sql/parser_yystype.h"
#include "sql/query_options.h"
#include "sql/query_result.h"
#include "sql/range_optimizer/partition_pruning.h"
#include "sql/range_optimizer/path_helpers.h"
#include "sql/range_optimizer/range_optimizer.h"
#include "sql/sql_base.h" // init_ftfuncs
#include "sql/sql_bitmap.h"
#include "sql/sql_class.h"
#include "sql/sql_const.h"
#include "sql/sql_const_folding.h"
#include "sql/sql_error.h"
#include "sql/sql_join_buffer.h" // JOIN_CACHE
#include "sql/sql_list.h" // List_iterator_fast
#include "sql/sql_planner.h" // calculate_condition_filter
#include "sql/sql_test.h" // print_where
#include "sql/sql_tmp_table.h"
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/thd_raii.h"
#include "sql/window.h"
#include "sql_string.h"
#include "template_utils.h"
using std::ceil;
using std::max;
using std::min;
const char *antijoin_null_cond = "<ANTIJOIN-NULL>";
static bool optimize_semijoin_nests_for_materialization(JOIN *join);
static void calculate_materialization_costs(JOIN *join, Table_ref *sj_nest,
uint n_tables,
Semijoin_mat_optimize *sjm);
static bool make_join_query_block(JOIN *join, Item *item);
static bool list_contains_unique_index(JOIN_TAB *tab,
bool (*find_func)(Field *, void *),
void *data);
static bool find_field_in_item_list(Field *field, void *data);
static bool find_field_in_order_list(Field *field, void *data);
static TABLE *get_sort_by_table(ORDER *a, ORDER *b, Table_ref *tables);
static void trace_table_dependencies(Opt_trace_context *trace,
JOIN_TAB *join_tabs, uint table_count);
static bool update_ref_and_keys(THD *thd, Key_use_array *keyuse,
JOIN_TAB *join_tab, uint tables, Item *cond,
table_map normal_tables,
Query_block *query_block,
SARGABLE_PARAM **sargables);
static bool pull_out_semijoin_tables(JOIN *join);
static void add_loose_index_scan_and_skip_scan_keys(JOIN *join,
JOIN_TAB *join_tab);
static ha_rows get_quick_record_count(THD *thd, JOIN_TAB *tab, ha_rows limit,
Item *condition);
static bool only_eq_ref_tables(JOIN *join, ORDER *order, table_map tables,
table_map *cached_eq_ref_tables,
table_map *eq_ref_tables);
static bool setup_join_buffering(JOIN_TAB *tab, JOIN *join, uint no_jbuf_after);
static bool test_if_skip_sort_order(JOIN_TAB *tab, ORDER_with_src &order,
ha_rows select_limit, const bool no_changes,
const Key_map *map, int *best_idx);
static Item_func_match *test_if_ft_index_order(ORDER *order);
static uint32 get_key_length_tmp_table(Item *item);
static bool can_switch_from_ref_to_range(THD *thd, JOIN_TAB *tab,
enum_order ordering,
bool recheck_range);
static bool has_not_null_predicate(Item *cond, Item_field *not_null_item);
JOIN::JOIN(THD *thd_arg, Query_block *select)
: query_block(select),
thd(thd_arg),
// @todo Can this be substituted with select->is_explicitly_grouped()?
grouped(select->is_explicitly_grouped()),
// Inner tables may always be considered to be constant:
const_table_map(INNER_TABLE_BIT),
found_const_table_map(INNER_TABLE_BIT),
// Needed in case optimizer short-cuts, set properly in
// make_tmp_tables_info()
fields(&select->fields),
tmp_table_param(thd_arg->mem_root),
lock(thd->lock),
// @todo Can this be substituted with select->is_implicitly_grouped()?
implicit_grouping(select->is_implicitly_grouped()),
select_distinct(select->is_distinct()),
keyuse_array(thd->mem_root),
order(select->order_list.first, ESC_ORDER_BY),
group_list(select->group_list.first, ESC_GROUP_BY),
m_windows(select->m_windows),
/*
Those four members are meaningless before JOIN::optimize(), so force a
crash if they are used before that.
*/
where_cond(reinterpret_cast<Item *>(1)),
having_cond(reinterpret_cast<Item *>(1)),
having_for_explain(reinterpret_cast<Item *>(1)),
tables_list(reinterpret_cast<Table_ref *>(1)),
current_ref_item_slice(REF_SLICE_SAVED_BASE),
with_json_agg(select->json_agg_func_used()) {
rollup_state = RollupState::NONE;
if (select->order_list.first) explain_flags.set(ESC_ORDER_BY, ESP_EXISTS);
if (select->group_list.first) explain_flags.set(ESC_GROUP_BY, ESP_EXISTS);
if (select->is_distinct()) explain_flags.set(ESC_DISTINCT, ESP_EXISTS);
if (m_windows.elements > 0) explain_flags.set(ESC_WINDOWING, ESP_EXISTS);
// Calculate the number of groups
for (ORDER *group = group_list.order; group; group = group->next)
send_group_parts++;
}
bool JOIN::alloc_ref_item_slice(THD *thd_arg, int sliceno) {
assert(sliceno > 0);
assert(ref_items[sliceno].is_null());
size_t count = ref_items[0].size();
Item **slice = thd_arg->mem_root->ArrayAlloc<Item *>(count);
if (slice == nullptr) return true;
ref_items[sliceno] = Ref_item_array(slice, count);
return false;
}
bool JOIN::alloc_indirection_slices() {
const int num_slices = REF_SLICE_WIN_1 + m_windows.elements;
assert(ref_items == nullptr);
ref_items = (*THR_MALLOC)->ArrayAlloc<Ref_item_array>(num_slices);
if (ref_items == nullptr) return true;
tmp_fields =
(*THR_MALLOC)
->ArrayAlloc<mem_root_deque<Item *>>(num_slices, *THR_MALLOC);
if (tmp_fields == nullptr) return true;
return false;
}
/**
The List<Item_multi_eq> in COND_EQUAL partially overlaps with the argument
list in various Item_cond via C-style casts. However, the hypergraph optimizer
can modify the lists in Item_cond (by calling compile()), causing an
Item_multi_eq to be replaced with Item_func_eq, and this can cause a
List<Item_multi_eq> not to contain Item_multi_eq pointers anymore. This is is
obviously bad if anybody wants to actually look into these lists after
optimization (in particular, NDB wants this).
Since untangling this spaghetti seems very hard, we solve it by brute force:
Make a copy of all the COND_EQUAL lists, so that they no longer reach into the
Item_cond. This allows us to modify the Item_cond at will.
*/
static void SaveCondEqualLists(COND_EQUAL *cond_equal) {
if (cond_equal == nullptr) {
return;
}
List<Item_multi_eq> copy;
for (Item_multi_eq &item : cond_equal->current_level) {
copy.push_back(&item);
}
cond_equal->current_level = std::move(copy);
SaveCondEqualLists(cond_equal->upper_levels);
}
bool JOIN::check_access_path_with_fts() const {
// Only relevant to the old optimizer.
assert(!thd->lex->using_hypergraph_optimizer());
assert(query_block->has_ft_funcs());
assert(rollup_state != RollupState::NONE);
// Find all tables referenced from non-aggregated MATCH calls in the SELECT
// list or in any hidden items lifted to the SELECT list from other clauses.
table_map fulltext_tables = 0;
for (Item *field : *fields) {
WalkItem(field, enum_walk::PREFIX | enum_walk::POSTFIX,
NonAggregatedFullTextSearchVisitor(
[&fulltext_tables](Item_func_match *item) {
fulltext_tables |= item->used_tables();
return false;
}));
}
if (fulltext_tables == 0) return false;
// See if any of those tables is accessed without materialization between the
// table access path and the aggregate access path.
bool found = false;
WalkAccessPaths(
root_access_path(), this, WalkAccessPathPolicy::ENTIRE_QUERY_BLOCK,
[fulltext_tables, &found](const AccessPath *path, const JOIN *) {
if (path->type == AccessPath::AGGREGATE) {
// Does the aggregate path access any of "fulltext_tables" without an
// intermediate materialization step? GetUsedTableMap() does not see
// through materialization and returns RAND_TABLE_BIT instead of the
// actual tables if "path" reads materialized results.
found |=
Overlaps(fulltext_tables,
GetUsedTableMap(path, /*include_pruned_tables=*/true));
}
return found;
});
if (found) {
my_error(ER_NOT_SUPPORTED_YET, MYF(0),
"reading non-aggregated results of the MATCH full-text search "
"function after GROUP BY WITH ROLLUP");
return true;
}
return false;
}
/**
Optimizes one query block into a query execution plan (QEP.)
This is the entry point to the query optimization phase. This phase
applies both logical (equivalent) query rewrites, cost-based join
optimization, and rule-based access path selection. Once an optimal
plan is found, the member function creates/initializes all
structures needed for query execution. The main optimization phases
are outlined below:
-# Logical transformations:
- Outer to inner joins transformation.
- Equality/constant propagation.
- Partition pruning.
- COUNT(*), MIN(), MAX() constant substitution in case of
implicit grouping.
- ORDER BY optimization.
-# Perform cost-based optimization of table order and access path
selection. See JOIN::make_join_plan()
-# Post-join order optimization:
- Create optimal table conditions from the where clause and the
join conditions.
- Inject outer-join guarding conditions.
- Adjust data access methods after determining table condition
(several times.)
- Optimize ORDER BY/DISTINCT.
-# Code generation
- Set data access functions.
- Try to optimize away sorting/distinct.
- Setup temporary table usage for grouping and/or sorting.
@retval false Success.
@retval true Error, error code saved in member JOIN::error.
*/
bool JOIN::optimize(bool finalize_access_paths) {
DBUG_TRACE;
uint no_jbuf_after = UINT_MAX;
Query_block *const set_operand_block =
query_expression()->non_simple_result_query_block();
assert(query_block->leaf_table_count == 0 ||
thd->lex->is_query_tables_locked() ||
query_block == set_operand_block);
assert(tables == 0 && primary_tables == 0 && tables_list == (Table_ref *)1);
// to prevent double initialization on EXPLAIN
if (optimized) return false;
DEBUG_SYNC(thd, "before_join_optimize");
THD_STAGE_INFO(thd, stage_optimizing);
Opt_trace_context *const trace = &thd->opt_trace;
const Opt_trace_object trace_wrapper(trace);
Opt_trace_object trace_optimize(trace, "join_optimization");
trace_optimize.add_select_number(query_block->select_number);
Opt_trace_array trace_steps(trace, "steps");
count_field_types(query_block, &tmp_table_param, *fields, false, false);
assert(tmp_table_param.sum_func_count == 0 || !group_list.empty() ||
implicit_grouping);
const bool has_windows = m_windows.elements != 0;
if (has_windows && Window::setup_windows2(thd, &m_windows))
return true; /* purecov: inspected */
if (query_block->olap == ROLLUP_TYPE && optimize_rollup())
return true; /* purecov: inspected */
if (alloc_func_list()) return true; /* purecov: inspected */
if (query_block->get_optimizable_conditions(thd, &where_cond, &having_cond))
return true;
for (Item_rollup_group_item *item : query_block->rollup_group_items) {
rollup_group_items.push_back(item);
}
for (Item_rollup_sum_switcher *item : query_block->rollup_sums) {
rollup_sums.push_back(item);
}
set_optimized();
tables_list = query_block->leaf_tables;
if (alloc_indirection_slices()) return true;
// The base ref items from query block are assigned as JOIN's ref items
ref_items[REF_SLICE_ACTIVE] = query_block->base_ref_items;
/* dump_TABLE_LIST_graph(query_block, query_block->leaf_tables); */
/*
Run optimize phase for all derived tables/views used in this SELECT,
including those in semi-joins.
*/
// if (query_block->materialized_derived_table_count) {
{ // WL#6570
for (Table_ref *tl = query_block->leaf_tables; tl; tl = tl->next_leaf) {
tl->ClearMaterializedPathCache();
if (tl->is_view_or_derived()) {
if (tl->optimize_derived(thd)) return true;
} else if (tl->is_table_function()) {
TABLE *const table = tl->table;
if (!table->has_storage_handler()) {
if (setup_tmp_table_handler(
thd, table,
query_block->active_options() | TMP_TABLE_ALL_COLUMNS))
return true; /* purecov: inspected */
}
table->file->stats.records = 2;
}
}
}
if (thd->lex->using_hypergraph_optimizer()) {
// The hypergraph optimizer also wants all subselect items to be optimized,
// so that it has cost information to attach to filter nodes.
for (Query_expression *unit = query_block->first_inner_query_expression();
unit; unit = unit->next_query_expression()) {
// Derived tables and const subqueries are already optimized
if (!unit->is_optimized() &&
unit->optimize(thd, /*materialize_destination=*/nullptr,
/*finalize_access_paths=*/false))
return true;
}
// The hypergraph optimizer does not do const tables,
// nor does it evaluate subqueries during optimization.
query_block->add_active_options(OPTION_NO_CONST_TABLES |
OPTION_NO_SUBQUERY_DURING_OPTIMIZATION);
}
has_lateral = false;
/* dump_TABLE_LIST_graph(query_block, query_block->leaf_tables); */
row_limit = ((select_distinct || !order.empty() || !group_list.empty())
? HA_POS_ERROR
: query_expression()->select_limit_cnt);
// m_select_limit is used to decide if we are likely to scan the whole table.
m_select_limit = query_expression()->select_limit_cnt;
if (query_expression()->first_query_block()->active_options() &
OPTION_FOUND_ROWS) {
/*
Calculate found rows (ie., keep counting rows even after we hit LIMIT) if
- LIMIT is set, and
- This is the outermost query block (for a UNION query, this is the
block that contains the limit applied on the final UNION
evaluation, cf query_term.h for explanation).
*/
calc_found_rows = m_select_limit != HA_POS_ERROR &&
(!query_expression()->is_set_operation() ||
query_block == set_operand_block);
}
if (having_cond || calc_found_rows) m_select_limit = HA_POS_ERROR;
if (query_expression()->select_limit_cnt == 0 && !calc_found_rows) {
zero_result_cause = "Zero limit";
best_rowcount = 0;
set_root_access_path(create_access_paths_for_zero_rows());
goto setup_subq_exit;
}
if (where_cond || query_block->outer_join) {
if (optimize_cond(thd, &where_cond, &cond_equal, &query_block->m_table_nest,
&query_block->cond_value)) {
error = 1;
DBUG_PRINT("error", ("Error from optimize_cond"));
return true;
}
if (query_block->cond_value == Item::COND_FALSE) {
zero_result_cause = "Impossible WHERE";
best_rowcount = 0;
set_root_access_path(create_access_paths_for_zero_rows());
goto setup_subq_exit;
}
}
if (having_cond) {
if (optimize_cond(thd, &having_cond, &cond_equal, nullptr,
&query_block->having_value)) {
error = 1;
DBUG_PRINT("error", ("Error from optimize_cond"));
return true;
}
if (query_block->having_value == Item::COND_FALSE) {
zero_result_cause = "Impossible HAVING";
best_rowcount = 0;
set_root_access_path(create_access_paths_for_zero_rows());
goto setup_subq_exit;
}
}
if (query_block->partitioned_table_count && prune_table_partitions()) {
error = 1;
DBUG_PRINT("error", ("Error from prune_partitions"));
return true;
}
/*
Try to optimize count(*), min() and max() to const fields if
there is implicit grouping (aggregate functions but no
group_list). In this case, the result set shall only contain one
row.
*/
if (tables_list && implicit_grouping &&
!(query_block->active_options() & OPTION_NO_CONST_TABLES)) {
aggregate_evaluated outcome;
if (optimize_aggregated_query(thd, query_block, *fields, where_cond,
&outcome)) {
error = 1;
DBUG_PRINT("error", ("Error from optimize_aggregated_query"));
return true;
}
switch (outcome) {
case AGGR_REGULAR:
// Query was not (fully) evaluated. Revert to regular optimization.
break;
case AGGR_DELAYED:
// Query was not (fully) evaluated. Revert to regular optimization,
// but indicate that storage engine supports HA_COUNT_ROWS_INSTANT.
select_count = true;
break;
case AGGR_COMPLETE: {
// All SELECT expressions are fully evaluated
DBUG_PRINT("info", ("Select tables optimized away"));
zero_result_cause = "Select tables optimized away";
tables_list = nullptr; // All tables resolved
best_rowcount = 1;
const_tables = tables = primary_tables = query_block->leaf_table_count;
AccessPath *path =
NewFakeSingleRowAccessPath(thd, /*count_examined_rows=*/true);
path = attach_access_paths_for_having_qualify_limit(path);
m_root_access_path = path;
/*
There are no relevant conditions left from the WHERE;
optimize_aggregated_query() will not return AGGR_COMPLETE if there are
any table-independent conditions, and all other conditions have been
optimized away by it. Thus, remove the condition, unless we have
EXPLAIN (in which case we will keep it for printing).
*/
if (!thd->lex->is_explain()) {
#ifndef NDEBUG
// Verify, to be sure.
if (where_cond != nullptr) {
Item *table_independent_conds = make_cond_for_table(
thd, where_cond, PSEUDO_TABLE_BITS, table_map(0),
/*exclude_expensive_cond=*/true);
assert(table_independent_conds == nullptr);
}
#endif
where_cond = nullptr;
}
goto setup_subq_exit;
}
case AGGR_EMPTY:
// It was detected that the result tables are empty
DBUG_PRINT("info", ("No matching min/max row"));
zero_result_cause = "No matching min/max row";
set_root_access_path(create_access_paths_for_zero_rows());
goto setup_subq_exit;
}
}
if (thd->lex->using_hypergraph_optimizer() &&
query_block->is_table_value_constructor) {
// Let the hypergraph optimizer handle table value constructors, even though
// they are table-less queries.
} else if (tables_list == nullptr) {
DBUG_PRINT("info", ("No tables"));
best_rowcount = 1;
error = 0;
if (make_tmp_tables_info()) return true;
count_field_types(query_block, &tmp_table_param, *fields, false, false);
// Make plan visible for EXPLAIN
set_plan_state(NO_TABLES);
create_access_paths();
return false;
}
error = -1; // Error is sent to client
{
m_windowing_steps = false; // initialization
m_windows_sort = false;
List_iterator<Window> li(m_windows);
Window *w;
while ((w = li++))
if (w->needs_sorting()) {
m_windows_sort = true;
break;
}
}
if (!thd->lex->using_hypergraph_optimizer()) {
sort_by_table = get_sort_by_table(order.order, group_list.order,
query_block->leaf_tables);
}
if ((where_cond || !group_list.empty() || !order.empty()) &&
substitute_gc(thd, query_block, where_cond, group_list.order,
order.order)) {
// We added hidden fields to the all_fields list, count them.
count_field_types(query_block, &tmp_table_param, query_block->fields, false,
false);
}
// Ensure there are no errors prior making query plan
if (thd->is_error()) return true;
if (thd->lex->using_hypergraph_optimizer()) {
// Get the WHERE and HAVING clauses with the IN-to-EXISTS predicates
// removed, so that we can plan both with and without the IN-to-EXISTS
// conversion.
Item *where_cond_no_in2exists = remove_in2exists_conds(where_cond);
Item *having_cond_no_in2exists = remove_in2exists_conds(having_cond);
// Cap the trace size at 2^63-1 bytes, since UnstructuredTrace uses
// int64_t.
const int64_t max_trace_bytes{static_cast<int64_t>(
std::min<uintmax_t>(std::numeric_limits<int64_t>::max(),
thd->variables.optimizer_trace_max_mem_size))};
UnstructuredTrace unstructured_trace{max_trace_bytes};
if (thd->opt_trace.is_started()) {
thd->opt_trace.set_unstructured_trace(&unstructured_trace);
}
// Add the contents of unstructured_trace to the JSON tree when we exit
// this scope.
const auto copy_trace = create_scope_guard([&]() {
if (thd->opt_trace.is_started()) {
thd->opt_trace.ConsumeUnstructuredTrace(thd);
thd->opt_trace.set_unstructured_trace(nullptr);
}
});
SaveCondEqualLists(cond_equal);
m_root_access_path = FindBestQueryPlan(thd, query_block);
if (finalize_access_paths && m_root_access_path != nullptr) {
if (FinalizePlanForQueryBlock(thd, query_block)) {
return true;
}
}
// If this query block was modified by IN-to-EXISTS conversion,
// the outer query block may want to undo that conversion and materialize
// us instead, depending on cost. (Materialization has high initial cost,
// but looking up in the materialized table is typically cheaper than
// running the entire query.) If so, we will need to plan the query again,
// but with all extra conditions added by IN-to-EXISTS removed, as those
// are specific to the values referred to by the outer query.
//
// Thus, we detect this here, and plan a second query plan. There are
// computations that could be shared between the two plans (e.g. join order
// between tables for which there is no IN-to-EXISTS-related condition),
// so it is somewhat wasteful, but experiments have shown that planning
// both at the same time quickly clutters the code with such handling;
// there are so many places such filters could be added (base table filters,
// filters after various types of joins, join conditions, post-join filters,
// HAVING, possibly others) that trying to plan paths both with and without
// them incurs complexity that is not justified by the small computational
// gain it would bring.
if (where_cond != where_cond_no_in2exists ||
having_cond != having_cond_no_in2exists) {
if (TraceStarted(thd)) {
Trace(thd)
<< "\nPlanning an alternative with in2exists conditions removed:\n";
}
where_cond = where_cond_no_in2exists;
having_cond = having_cond_no_in2exists;
assert(!finalize_access_paths);
m_root_access_path_no_in2exists = FindBestQueryPlan(thd, query_block);
} else {
m_root_access_path_no_in2exists = nullptr;
}
if (m_root_access_path == nullptr) {
return true;
}
set_plan_state(PLAN_READY);
DEBUG_SYNC(thd, "after_join_optimize");
return false;
}
// ----------------------------------------------------------------------------
// All of this is never called for the hypergraph join optimizer!
// ----------------------------------------------------------------------------
assert(!thd->lex->using_hypergraph_optimizer());
// Don't expect to get here if the hypergraph optimizer is enabled via an
// optimizer switch. The "is_regular()" case is necessary for SET statements.
assert(!thd->optimizer_switch_flag(OPTIMIZER_SWITCH_HYPERGRAPH_OPTIMIZER) ||
!thd->stmt_arena->is_regular());
// Set up join order and initial access paths
THD_STAGE_INFO(thd, stage_statistics);
if (make_join_plan()) {
if (thd->killed) thd->send_kill_message();
DBUG_PRINT("error", ("Error: JOIN::make_join_plan() failed"));
return true;
}
// At this stage, join_tab==NULL, JOIN_TABs are listed in order by best_ref.
ASSERT_BEST_REF_IN_JOIN_ORDER(this);
if (zero_result_cause != nullptr) { // Can be set by make_join_plan().
set_root_access_path(create_access_paths_for_zero_rows());
goto setup_subq_exit;
}
if (!query_block->is_non_primitive_grouped()) {
/* Remove distinct if only const tables */
select_distinct &= !plan_is_const();
}
if (const_tables && !thd->locked_tables_mode &&
!(query_block->active_options() & SELECT_NO_UNLOCK)) {
TABLE *ct[MAX_TABLES];
for (uint i = 0; i < const_tables; i++) {
ct[i] = best_ref[i]->table();
ct[i]->file->ha_index_or_rnd_end();
}
mysql_unlock_some_tables(thd, ct, const_tables);
}
if (!where_cond && query_block->outer_join) {
/* Handle the case where we have an OUTER JOIN without a WHERE */
where_cond = new Item_func_true(); // Always true
}
error = 0;
/*
Among the equal fields belonging to the same multiple equality
choose the one that is to be retrieved first and substitute
all references to these in where condition for a reference for
the selected field.
*/
if (where_cond) {
where_cond =
substitute_for_best_equal_field(thd, where_cond, cond_equal, map2table);
if (thd->is_error()) {
error = 1;
DBUG_PRINT("error", ("Error from substitute_for_best_equal"));
return true;
}
where_cond->update_used_tables();
DBUG_EXECUTE("where",
print_where(thd, where_cond, "after substitute_best_equal",
QT_ORDINARY););
}
/*
Perform the same optimization on field evaluation for all join conditions.
*/
for (uint i = const_tables; i < tables; ++i) {
JOIN_TAB *const tab = best_ref[i];
if (tab->position() != nullptr && tab->join_cond() != nullptr) {
tab->set_join_cond(substitute_for_best_equal_field(
thd, tab->join_cond(), tab->cond_equal, map2table));
if (thd->is_error()) {
error = 1;
DBUG_PRINT("error", ("Error from substitute_for_best_equal"));
return true;
}
tab->join_cond()->update_used_tables();
if (tab->join_cond()->walk(&Item::cast_incompatible_args,
enum_walk::POSTFIX, nullptr)) {
return true;
}
}
}
if (init_ref_access()) {
error = 1;
DBUG_PRINT("error", ("Error from init_ref_access"));
return true;
}
// Update table dependencies after assigning ref access fields
update_depend_map();
THD_STAGE_INFO(thd, stage_preparing);
if (make_join_query_block(this, where_cond)) {
if (thd->is_error()) return true;
zero_result_cause = "Impossible WHERE noticed after reading const tables";
set_root_access_path(create_access_paths_for_zero_rows());
goto setup_subq_exit;
}
// Inject cast nodes into the WHERE conditions
if (where_cond != nullptr && where_cond->walk(&Item::cast_incompatible_args,
enum_walk::POSTFIX, nullptr)) {
return true;
}
error = -1; /* if goto err */
if (optimize_distinct_group_order()) return true;
if ((query_block->active_options() & SELECT_NO_JOIN_CACHE) ||
query_block->ftfunc_list->elements)
no_jbuf_after = 0;
/* Perform FULLTEXT search before all regular searches */
if (query_block->has_ft_funcs() && optimize_fts_query()) return true;
/*
By setting child_subquery_can_materialize so late we gain the following:
JOIN::compare_costs_of_subquery_strategies() can test this variable to
know if we are have finished evaluating constant conditions, which itself
helps determining fanouts.
*/
child_subquery_can_materialize = true;
/*
It's necessary to check const part of HAVING cond as
there is a chance that some cond parts may become
const items after make_join_plan() (for example
when Item is a reference to const table field from
outer join).
This check is performed only for those conditions
which do not use aggregate functions. In such case
temporary table may not be used and const condition
elements may be lost during further having
condition transformation in JOIN::exec.
*/
if (having_cond && !having_cond->has_aggregation() && (const_tables > 0)) {
having_cond->update_used_tables();
if (remove_eq_conds(thd, having_cond, &having_cond,
&query_block->having_value)) {
error = 1;
DBUG_PRINT("error", ("Error from remove_eq_conds"));
return true;
}
if (query_block->having_value == Item::COND_FALSE) {
having_cond = new Item_func_false();
zero_result_cause =
"Impossible HAVING noticed after reading const tables";
set_root_access_path(create_access_paths_for_zero_rows());
goto setup_subq_exit;
}
}
// Inject cast nodes into the HAVING conditions
if (having_cond != nullptr &&
having_cond->walk(&Item::cast_incompatible_args, enum_walk::POSTFIX,
nullptr)) {
return true;
}
// Traverse the expressions and inject cast nodes to compatible data types,
// if needed.
for (Item *item : *fields) {
if (item->walk(&Item::cast_incompatible_args, enum_walk::POSTFIX,
nullptr)) {
return true;
}
}
// Also GROUP BY expressions, so that find_in_group_list() doesn't
// inadvertently fail because the SELECT list has casts that GROUP BY doesn't.
for (ORDER *ord = group_list.order; ord != nullptr; ord = ord->next) {
if ((*ord->item)
->walk(&Item::cast_incompatible_args, enum_walk::POSTFIX,
nullptr)) {
return true;
}
}
// See if this subquery can be evaluated with subselect_indexsubquery_engine
if (const int ret = replace_index_subquery()) {
if (ret == -1) {
// Error (e.g. allocation failed, or some condition was attempted
// evaluated statically and failed).
return true;
}
create_access_paths_for_index_subquery();
set_plan_state(PLAN_READY);
/*
We leave optimize() because the rest of it is only about order/group
which those subqueries don't have and about setting up plan which
we're not going to use due to different execution method.
*/
return false;
}
{
/*
If the hint FORCE INDEX FOR ORDER BY/GROUP BY is used for the first
table (it does not make sense for other tables) then we cannot do join
buffering.
*/
if (!plan_is_const()) {
const TABLE *const first = best_ref[const_tables]->table();
if ((first->force_index_order && !order.empty()) ||
(first->force_index_group && !group_list.empty()))
no_jbuf_after = 0;
}
bool simple_sort = true;
const Table_map_restorer deps_lateral(
&deps_of_remaining_lateral_derived_tables);
// Check whether join cache could be used
for (uint i = const_tables; i < tables; i++) {
JOIN_TAB *const tab = best_ref[i];
if (!tab->position()) continue;
if (setup_join_buffering(tab, this, no_jbuf_after)) return true;
if (tab->use_join_cache() != JOIN_CACHE::ALG_NONE) simple_sort = false;
assert(tab->type() != JT_FT ||
tab->use_join_cache() == JOIN_CACHE::ALG_NONE);
if (has_lateral && get_lateral_deps(*best_ref[i]) != 0) {
deps_of_remaining_lateral_derived_tables =
calculate_deps_of_remaining_lateral_derived_tables(all_table_map,
i + 1);
}
}
if (!simple_sort) {
/*
A join buffer is used for this table. We here inform the optimizer
that it should not rely on rows of the first non-const table being in
order thanks to an index scan; indeed join buffering of the present
table subsequently changes the order of rows.
*/
simple_order = simple_group = false;
}
}
if (!plan_is_const() && !order.empty()) {
/*
Force using of tmp table if sorting by a SP or UDF function due to
their expensive and probably non-deterministic nature.
*/
for (ORDER *tmp_order = order.order; tmp_order;
tmp_order = tmp_order->next) {
Item *item = *tmp_order->item;
if (item->cost().IsExpensive()) {
/* Force tmp table without sort */
simple_order = simple_group = false;
break;
}
}
}
/*
Check if we need to create a temporary table prior to any windowing.
(1) If there is ROLLUP, which happens before DISTINCT, windowing and ORDER
BY, any of those clauses needs the result of ROLLUP in a tmp table.
Rows which ROLLUP adds to the result are visible only to DISTINCT,
windowing and ORDER BY which we handled above. So for the rest of
conditions ((2), etc), we can do as if there were no ROLLUP.
(2) If all tables are constant, the query's result is guaranteed to have 0
or 1 row only, so all SQL clauses discussed below (DISTINCT, ORDER BY,
GROUP BY, windowing, SQL_BUFFER_RESULT) are useless and need no tmp
table.
(3) If there is GROUP BY which isn't resolved by using an index or sorting
the first table, we need a tmp table to compute the grouped rows.
GROUP BY happens before windowing; so it is a pre-windowing tmp
table.
(4) (5) If there is DISTINCT, or ORDER BY which isn't resolved by using an
index or sorting the first table, those clauses need an input tmp table.
If we have windowing, as those clauses are used after windowing, they can
use the last window's tmp table.
(6) If there are different ORDER BY and GROUP BY orders, ORDER BY needs an
input tmp table, so it's like (5).
(7) If the user wants us to buffer the result, we need a tmp table. But
windowing creates one anyway, and so does the materialization of a derived
table.
See also the computation of Window::m_short_circuit,
where we make sure to create a tmp table if the clauses above want one.
(8) If the first windowing step needs sorting, filesort() will be used; it
can sort one table but not a join of tables, so we need a tmp table
then. If GROUP BY was optimized away, the pre-windowing result is 0 or 1
row so doesn't need sorting.
*/
if (rollup_state != RollupState::NONE && // (1)
(select_distinct || has_windows || !order.empty()))
need_tmp_before_win = true;