forked from mysql/mysql-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccess_path.cc
1772 lines (1672 loc) · 73.8 KB
/
access_path.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) 2020, 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 */
#include "sql/join_optimizer/access_path.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <span>
#include <vector>
#include "mem_root_deque.h"
#include "my_base.h"
#include "my_dbug.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "prealloced_array.h"
#include "sql/field.h"
#include "sql/filesort.h"
#include "sql/handler.h"
#include "sql/item_cmpfunc.h"
#include "sql/item_func.h"
#include "sql/item_subselect.h"
#include "sql/iterators/basic_row_iterators.h"
#include "sql/iterators/bka_iterator.h"
#include "sql/iterators/composite_iterators.h"
#include "sql/iterators/delete_rows_iterator.h"
#include "sql/iterators/hash_join_iterator.h"
#include "sql/iterators/ref_row_iterators.h"
#include "sql/iterators/row_iterator.h"
#include "sql/iterators/sorting_iterator.h"
#include "sql/iterators/timing_iterator.h"
#include "sql/iterators/window_iterators.h"
#include "sql/join_optimizer/bit_utils.h"
#include "sql/join_optimizer/cost_model.h"
#include "sql/join_optimizer/estimate_selectivity.h"
#include "sql/join_optimizer/overflow_bitset.h"
#include "sql/join_optimizer/relational_expression.h"
#include "sql/join_optimizer/walk_access_paths.h"
#include "sql/mem_root_array.h"
#include "sql/pack_rows.h"
#include "sql/range_optimizer/geometry_index_range_scan.h"
#include "sql/range_optimizer/group_index_skip_scan.h"
#include "sql/range_optimizer/group_index_skip_scan_plan.h"
#include "sql/range_optimizer/index_merge.h"
#include "sql/range_optimizer/index_range_scan.h"
#include "sql/range_optimizer/index_skip_scan.h"
#include "sql/range_optimizer/index_skip_scan_plan.h"
#include "sql/range_optimizer/range_optimizer.h"
#include "sql/range_optimizer/reverse_index_range_scan.h"
#include "sql/range_optimizer/rowid_ordered_retrieval.h"
#include "sql/sql_array.h"
#include "sql/sql_const.h"
#include "sql/sql_executor.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_optimizer.h"
#include "sql/sql_update.h"
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/visible_fields.h"
#include "template_utils.h"
using pack_rows::TableCollection;
using std::all_of;
using std::vector;
AccessPath *NewSortAccessPath(THD *thd, AccessPath *child, Filesort *filesort,
ORDER *order, bool count_examined_rows) {
assert(child != nullptr);
assert(filesort != nullptr);
assert(order != nullptr);
AccessPath *path = new (thd->mem_root) AccessPath;
path->type = AccessPath::SORT;
path->count_examined_rows = count_examined_rows;
path->sort().child = child;
path->sort().filesort = filesort;
path->sort().order = order;
path->sort().remove_duplicates = filesort->m_remove_duplicates;
path->sort().unwrap_rollup = false;
path->sort().limit = filesort->limit;
path->sort().force_sort_rowids = !filesort->using_addon_fields();
if (filesort->using_addon_fields()) {
path->sort().tables_to_get_rowid_for = 0;
} else {
if (filesort->tables.size() == 1 &&
filesort->tables[0]->pos_in_table_list == nullptr) {
// This can happen if we sort a single temporary table
// which is not in the table list (e.g., one that was
// specifically created for us). Filesort has special-casing
// to always get the row ID in this case.
path->sort().tables_to_get_rowid_for = 0;
} else {
FindTablesToGetRowidFor(path);
}
}
path->has_group_skip_scan = child->has_group_skip_scan;
return path;
}
AccessPath *NewDeleteRowsAccessPath(THD *thd, AccessPath *child,
table_map delete_tables,
table_map immediate_tables) {
assert(IsSubset(immediate_tables, delete_tables));
AccessPath *path = new (thd->mem_root) AccessPath;
path->type = AccessPath::DELETE_ROWS;
path->delete_rows().child = child;
path->delete_rows().tables_to_delete_from = delete_tables;
path->delete_rows().immediate_tables = immediate_tables;
return path;
}
AccessPath *NewUpdateRowsAccessPath(THD *thd, AccessPath *child,
table_map update_tables,
table_map immediate_tables) {
assert(IsSubset(immediate_tables, update_tables));
AccessPath *path = new (thd->mem_root) AccessPath;
path->type = AccessPath::UPDATE_ROWS;
path->update_rows().child = child;
path->update_rows().tables_to_update = update_tables;
path->update_rows().immediate_tables = immediate_tables;
return path;
}
static Mem_root_array<Item_values_column *> *GetTableValueConstructorOutputRefs(
MEM_ROOT *mem_root, const JOIN *join) {
// If the table value constructor has a single row, the values are contained
// directly in join->fields, and there are no Item_values_column output refs.
if (join->query_block->row_value_list->size() == 1) {
return nullptr;
}
auto columns = new (mem_root) Mem_root_array<Item_values_column *>(mem_root);
if (columns == nullptr) return nullptr;
for (Item *column : VisibleFields(*join->fields)) {
if (columns->push_back(down_cast<Item_values_column *>(column))) {
return nullptr;
}
}
return columns;
}
AccessPath *NewTableValueConstructorAccessPath(const THD *thd,
const JOIN *join) {
AccessPath *path = new (thd->mem_root) AccessPath;
path->type = AccessPath::TABLE_VALUE_CONSTRUCTOR;
// The iterator keeps track of which row it is at in examined_rows,
// so we always need to give it the pointer.
path->count_examined_rows = true;
path->table_value_constructor().output_refs =
GetTableValueConstructorOutputRefs(thd->mem_root, join);
return path;
}
static AccessPath *FindSingleAccessPathOfType(AccessPath *path,
AccessPath::Type type) {
AccessPath *found_path = nullptr;
auto func = [type, &found_path](AccessPath *subpath, const JOIN *) {
#ifdef NDEBUG
constexpr bool fast_exit = true;
#else
constexpr bool fast_exit = false;
#endif
if (subpath->type == type) {
assert(found_path == nullptr);
found_path = subpath;
// If not in debug mode, stop as soon as we find the first one.
if (fast_exit) {
return true;
}
}
return false;
};
// Our users generally want to stop at STREAM or MATERIALIZE nodes,
// since they are table-oriented and those nodes have their own tables.
WalkAccessPaths(path, /*join=*/nullptr,
WalkAccessPathPolicy::STOP_AT_MATERIALIZATION, func);
return found_path;
}
static RowIterator *FindSingleIteratorOfType(AccessPath *path,
AccessPath::Type type) {
AccessPath *found_path = FindSingleAccessPathOfType(path, type);
if (found_path == nullptr) {
return nullptr;
} else {
return found_path->iterator->real_iterator();
}
}
TABLE *GetBasicTable(const AccessPath *path) {
switch (path->type) {
// Basic access paths (those with no children, at least nominally).
case AccessPath::TABLE_SCAN:
return path->table_scan().table;
case AccessPath::SAMPLE_SCAN:
return path->sample_scan().table;
case AccessPath::INDEX_SCAN:
return path->index_scan().table;
case AccessPath::INDEX_DISTANCE_SCAN:
return path->index_distance_scan().table;
case AccessPath::REF:
return path->ref().table;
case AccessPath::REF_OR_NULL:
return path->ref_or_null().table;
case AccessPath::EQ_REF:
return path->eq_ref().table;
case AccessPath::PUSHED_JOIN_REF:
return path->pushed_join_ref().table;
case AccessPath::FULL_TEXT_SEARCH:
return path->full_text_search().table;
case AccessPath::CONST_TABLE:
return path->const_table().table;
case AccessPath::MRR:
return path->mrr().table;
case AccessPath::FOLLOW_TAIL:
return path->follow_tail().table;
case AccessPath::INDEX_RANGE_SCAN:
return path->index_range_scan().used_key_part[0].field->table;
case AccessPath::INDEX_MERGE:
return path->index_merge().table;
case AccessPath::ROWID_INTERSECTION:
return path->rowid_intersection().table;
case AccessPath::ROWID_UNION:
return path->rowid_union().table;
case AccessPath::INDEX_SKIP_SCAN:
return path->index_skip_scan().table;
case AccessPath::GROUP_INDEX_SKIP_SCAN:
return path->group_index_skip_scan().table;
case AccessPath::DYNAMIC_INDEX_RANGE_SCAN:
return path->dynamic_index_range_scan().table;
// Basic access paths that don't correspond to a specific table.
case AccessPath::TABLE_VALUE_CONSTRUCTOR:
case AccessPath::FAKE_SINGLE_ROW:
case AccessPath::ZERO_ROWS:
case AccessPath::ZERO_ROWS_AGGREGATED:
case AccessPath::MATERIALIZED_TABLE_FUNCTION:
case AccessPath::UNQUALIFIED_COUNT:
// Note, some other AccessPaths may use its own temporary (derived) table.
// We intentionally do not return such TABLEs.
default:
return nullptr;
}
}
table_map GetUsedTableMap(const AccessPath *path, bool include_pruned_tables) {
table_map tmap = 0;
WalkTablesUnderAccessPath(
const_cast<AccessPath *>(path),
[&tmap](TABLE *table) {
if (table->pos_in_table_list == nullptr) {
// Materialization within a JOIN (e.g., for sorting). The table won't
// have a map, so the caller will need to find the table manually.
tmap |= RAND_TABLE_BIT;
} else {
tmap |= table->pos_in_table_list->map();
}
return false;
},
include_pruned_tables);
return tmap;
}
static Prealloced_array<TABLE *, 4> GetUsedTables(AccessPath *child,
bool include_pruned_tables) {
Prealloced_array<TABLE *, 4> tables{PSI_NOT_INSTRUMENTED};
WalkTablesUnderAccessPath(
child,
[&tables](TABLE *table) {
tables.push_back(table);
return false;
},
include_pruned_tables);
return tables;
}
Mem_root_array<TABLE *> CollectTables(THD *thd, AccessPath *root_path) {
Mem_root_array<TABLE *> tables(thd->mem_root);
WalkTablesUnderAccessPath(
root_path, [&tables](TABLE *table) { return tables.push_back(table); },
/*include_pruned_tables=*/true);
return tables;
}
namespace {
/**
Collect all the single-row index lookups that are located below the given path
with no intermediate materialization step in between, and which cache the
result of the index lookup.
These are used by iterators that may overwrite the contents of
table->record[0] in a way that disturbs EQRefIterator's cache, and which
therefore need to mark the cache as invalid to force the next read from the
EQRefIterator to read again from the index. Examples of iterators that may
disturb EQRefIterator's cache include AggregateIterator, SortingIterator,
HashJoinIterator and BKAIterator.
*/
std::span<AccessPath *> CollectSingleRowIndexLookups(THD *thd,
AccessPath *root) {
Mem_root_array<AccessPath *> lookups(thd->mem_root);
WalkAccessPaths(root, /*join=*/nullptr,
WalkAccessPathPolicy::STOP_AT_MATERIALIZATION,
[&lookups](AccessPath *path, const JOIN *) {
if (path->type == AccessPath::EQ_REF &&
!path->eq_ref().ref->disable_cache) {
return lookups.push_back(path);
}
return false;
});
return {lookups};
}
// Mirrors QEP_TAB::pfs_batch_update(), with one addition:
// If there is more than one table, batch mode will be handled by the join
// iterators on the probe side, so joins will return false.
bool ShouldEnableBatchMode(AccessPath *path) {
switch (path->type) {
case AccessPath::TABLE_SCAN:
case AccessPath::INDEX_SCAN:
case AccessPath::INDEX_DISTANCE_SCAN:
case AccessPath::REF:
case AccessPath::REF_OR_NULL:
case AccessPath::PUSHED_JOIN_REF:
case AccessPath::FULL_TEXT_SEARCH:
case AccessPath::DYNAMIC_INDEX_RANGE_SCAN:
return true;
case AccessPath::FILTER:
if (path->filter().condition->has_subquery()) {
return false;
} else {
return ShouldEnableBatchMode(path->filter().child);
}
case AccessPath::SORT:
return ShouldEnableBatchMode(path->sort().child);
case AccessPath::EQ_REF:
case AccessPath::CONST_TABLE:
// These can read only one row per scan, so batch mode will never be a
// win (fall through).
default:
// All others, in particular joins.
return false;
}
}
// Check if a subquery present in a condition has forced materialization.
bool IsForcedMaterialization(THD *thd, Item *cond) {
bool force_materialization = false;
WalkItem(cond, enum_walk::POSTFIX | enum_walk::SUBQUERY,
[&force_materialization, thd](Item *item) {
if (item->type() == Item::SUBQUERY_ITEM) {
if (!is_quantified_comp_predicate(item)) return false;
Item_in_subselect *item_subs =
down_cast<Item_in_subselect *>(item);
const Query_expression *query_expr = item_subs->query_expr();
Query_block *qb = query_expr->first_query_block();
// Sometimes a query block is marked for materialization
// during resolving. However, because of an always false
// condition detected elsewhere in the query during
// optimization, this query block may not be optimized.
// So, check that before forcing materialization.
if (query_expr->is_optimized() &&
qb->subquery_strategy(thd) ==
Subquery_strategy::SUBQ_MATERIALIZATION) {
force_materialization = true;
return true;
}
}
return false;
});
return force_materialization;
}
/**
If the path is a FILTER path marked that subqueries are to be materialized,
do so. If not, do nothing.
It is important that this is not called until the entire plan is ready;
not just when planning a single query block. The reason is that a query
block A with materializable subqueries may itself be part of a materializable
subquery B, so if one calls this when planning A, the subqueries in A will
irrevocably be materialized, even if that is not the optimal plan given B.
Thus, this is done when creating iterators.
*/
bool FinalizeMaterializedSubqueries(THD *thd, JOIN *join, AccessPath *path) {
if (path->type != AccessPath::FILTER ||
!(path->filter().materialize_subqueries ||
IsForcedMaterialization(thd, path->filter().condition))) {
return false;
}
return WalkItem(
path->filter().condition, enum_walk::POSTFIX | enum_walk::SUBQUERY,
[thd, join](Item *item) {
if (!is_quantified_comp_predicate(item)) {
return false;
}
Item_in_subselect *item_subs = down_cast<Item_in_subselect *>(item);
if (item_subs->strategy == Subquery_strategy::SUBQ_MATERIALIZATION) {
// This subquery is already set up for materialization.
return false;
}
const Query_expression *query_expr = item_subs->query_expr();
// The subquery is eliminated. Do not materialize.
if (!query_expr->is_optimized()) {
return false;
}
// If IN-TO-EXISTS is forced, don't materialize.
Query_block *qb = query_expr->first_query_block();
if (qb->subquery_strategy(thd) == Subquery_strategy::SUBQ_EXISTS) {
return false;
}
if (!item_subs->subquery_allows_materialization(thd, qb,
join->query_block)) {
return false;
}
if (item_subs->finalize_materialization_transform(thd, qb->join)) {
return true;
}
item_subs->create_iterators(thd);
return false;
});
}
struct IteratorToBeCreated {
AccessPath *path;
JOIN *join;
bool eligible_for_batch_mode;
unique_ptr_destroy_only<RowIterator> *destination;
Bounds_checked_array<unique_ptr_destroy_only<RowIterator>> children;
void AllocChildren(MEM_ROOT *mem_root, int num_children) {
children =
Bounds_checked_array<unique_ptr_destroy_only<RowIterator>>::Alloc(
mem_root, num_children);
}
};
void SetupJobsForChildren(MEM_ROOT *mem_root, AccessPath *child, JOIN *join,
bool eligible_for_batch_mode,
IteratorToBeCreated *job,
Mem_root_array<IteratorToBeCreated> *todo) {
// Make jobs for the child, and we'll return to this job later.
job->AllocChildren(mem_root, 1);
todo->push_back(*job);
todo->push_back(
{child, join, eligible_for_batch_mode, &job->children[0], {}});
}
void SetupJobsForChildren(MEM_ROOT *mem_root, AccessPath *outer,
AccessPath *inner, JOIN *join,
bool inner_eligible_for_batch_mode,
IteratorToBeCreated *job,
Mem_root_array<IteratorToBeCreated> *todo) {
// Make jobs for the children, and we'll return to this job later.
// Note that we push the inner before the outer job, so that we get
// left created before right (invalidators in materialization access paths,
// used in the old join optimizer, depend on this).
job->AllocChildren(mem_root, 2);
todo->push_back(*job);
todo->push_back(
{inner, join, inner_eligible_for_batch_mode, &job->children[1], {}});
todo->push_back({outer, join, false, &job->children[0], {}});
}
} // namespace
const Mem_root_array<Item *> *GetExtraHashJoinConditions(
MEM_ROOT *mem_root, bool using_hypergraph_optimizer,
const vector<HashJoinCondition> &equijoin_conditions,
const Mem_root_array<Item *> &other_conditions) {
if (!using_hypergraph_optimizer) {
// The old optimizer has already collected the necessary conditions in
// other_conditions or in a filter on top of the hash join.
return &other_conditions;
}
if (all_of(equijoin_conditions.begin(), equijoin_conditions.end(),
[](const HashJoinCondition &condition) {
return condition.store_full_sort_key();
})) {
// When we have no partially stored hash keys, there are no more conditions
// to add.
return &other_conditions;
}
// If we have at least one part of the hash key that cannot be stored fully in
// the hash join buffer, we need to add the corresponding equijoin condition
// as an extra condition to evaluate after the hash join. Append it to the
// non-equijoin predicates that we already have.
Mem_root_array<Item *> *extra_conditions =
new (mem_root) Mem_root_array<Item *>(mem_root, other_conditions);
if (extra_conditions == nullptr) return nullptr;
for (const HashJoinCondition &condition : equijoin_conditions) {
if (!condition.store_full_sort_key()) {
if (extra_conditions->push_back(condition.join_condition())) {
return nullptr;
}
}
}
return extra_conditions;
}
unique_ptr_destroy_only<RowIterator> CreateIteratorFromAccessPath(
THD *thd, MEM_ROOT *mem_root, AccessPath *top_path, JOIN *top_join,
bool top_eligible_for_batch_mode) {
assert(IteratorsAreNeeded(thd, top_path));
unique_ptr_destroy_only<RowIterator> ret;
Mem_root_array<IteratorToBeCreated> todo(mem_root);
todo.push_back({top_path, top_join, top_eligible_for_batch_mode, &ret, {}});
// The access path trees can be pretty deep, and the stack frames can be big
// on certain compilers/setups, so instead of explicit recursion, we push jobs
// onto a MEM_ROOT-backed stack. This uses a little more RAM (the MEM_ROOT
// typically lives to the end of the query), but reduces the stack usage
// greatly.
//
// The general rule is that if an iterator requires any children, it will push
// jobs for their access paths at the end of the stack and then re-push
// itself. When the children are instantiated and we get back to the original
// iterator, we'll actually instantiate it. (We distinguish between the two
// cases on basis of whether job.children has been allocated or not; the child
// iterator's destination will point into this array. The child list needs
// to be allocated in a way that doesn't move around if the TODO job list
// is reallocated, which we do by means of allocating it directly on the
// MEM_ROOT.)
while (!todo.empty()) {
IteratorToBeCreated job = todo.back();
todo.pop_back();
AccessPath *path = job.path;
JOIN *join = job.join;
bool eligible_for_batch_mode = job.eligible_for_batch_mode;
if (job.join != nullptr) {
assert(!job.join->needs_finalize);
}
unique_ptr_destroy_only<RowIterator> iterator;
ha_rows *examined_rows = nullptr;
if (path->count_examined_rows && join != nullptr) {
examined_rows = &join->examined_rows;
}
switch (path->type) {
case AccessPath::TABLE_SCAN: {
const auto ¶m = path->table_scan();
iterator = NewIterator<TableScanIterator>(
thd, mem_root, param.table, path->num_output_rows(), examined_rows);
break;
}
case AccessPath::INDEX_SCAN: {
const auto ¶m = path->index_scan();
if (param.reverse) {
iterator = NewIterator<IndexScanIterator<true>>(
thd, mem_root, param.table, param.idx, param.use_order,
path->num_output_rows(), examined_rows);
} else {
iterator = NewIterator<IndexScanIterator<false>>(
thd, mem_root, param.table, param.idx, param.use_order,
path->num_output_rows(), examined_rows);
}
break;
}
case AccessPath::INDEX_DISTANCE_SCAN: {
const auto ¶m = path->index_distance_scan();
iterator = NewIterator<IndexDistanceScanIterator>(
thd, mem_root, param.table, param.idx, param.range,
path->num_output_rows(), examined_rows);
break;
}
case AccessPath::REF: {
const auto ¶m = path->ref();
if (param.reverse) {
iterator = NewIterator<RefIterator<true>>(
thd, mem_root, param.table, param.ref, param.use_order,
path->num_output_rows(), examined_rows);
} else {
iterator = NewIterator<RefIterator<false>>(
thd, mem_root, param.table, param.ref, param.use_order,
path->num_output_rows(), examined_rows);
}
break;
}
case AccessPath::REF_OR_NULL: {
const auto ¶m = path->ref_or_null();
iterator = NewIterator<RefOrNullIterator>(
thd, mem_root, param.table, param.ref, param.use_order,
path->num_output_rows(), examined_rows);
break;
}
case AccessPath::EQ_REF: {
const auto ¶m = path->eq_ref();
iterator = NewIterator<EQRefIterator>(thd, mem_root, param.table,
param.ref, examined_rows);
break;
}
case AccessPath::PUSHED_JOIN_REF: {
const auto ¶m = path->pushed_join_ref();
iterator = NewIterator<PushedJoinRefIterator>(
thd, mem_root, param.table, param.ref, param.use_order,
param.is_unique, examined_rows);
break;
}
case AccessPath::FULL_TEXT_SEARCH: {
const auto ¶m = path->full_text_search();
iterator = NewIterator<FullTextSearchIterator>(
thd, mem_root, param.table, param.ref, param.ft_func,
param.use_order, param.use_limit, examined_rows);
break;
}
case AccessPath::CONST_TABLE: {
const auto ¶m = path->const_table();
iterator = NewIterator<ConstIterator>(thd, mem_root, param.table,
param.ref, examined_rows);
break;
}
case AccessPath::MRR: {
const auto ¶m = path->mrr();
const auto &bka_param = param.bka_path->bka_join();
iterator = NewIterator<MultiRangeRowIterator>(
thd, mem_root, param.table, param.ref, param.mrr_flags,
bka_param.join_type,
GetUsedTables(bka_param.outer, /*include_pruned_tables=*/true),
bka_param.store_rowids, bka_param.tables_to_get_rowid_for);
break;
}
case AccessPath::FOLLOW_TAIL: {
const auto ¶m = path->follow_tail();
iterator = NewIterator<FollowTailIterator>(
thd, mem_root, param.table, path->num_output_rows(), examined_rows);
break;
}
case AccessPath::INDEX_RANGE_SCAN: {
const auto ¶m = path->index_range_scan();
TABLE *table = param.used_key_part[0].field->table;
if (param.geometry) {
iterator = NewIterator<GeometryIndexRangeScanIterator>(
thd, mem_root, table, examined_rows, path->num_output_rows(),
param.index, param.need_rows_in_rowid_order, param.reuse_handler,
mem_root, param.mrr_flags, param.mrr_buf_size,
Bounds_checked_array{param.ranges, param.num_ranges});
} else if (param.reverse) {
iterator = NewIterator<ReverseIndexRangeScanIterator>(
thd, mem_root, table, examined_rows, path->num_output_rows(),
param.index, mem_root, param.mrr_flags,
Bounds_checked_array{param.ranges, param.num_ranges},
param.using_extended_key_parts);
} else {
iterator = NewIterator<IndexRangeScanIterator>(
thd, mem_root, table, examined_rows, path->num_output_rows(),
param.index, param.need_rows_in_rowid_order, param.reuse_handler,
mem_root, param.mrr_flags, param.mrr_buf_size,
Bounds_checked_array{param.ranges, param.num_ranges});
}
break;
}
case AccessPath::INDEX_MERGE: {
const auto ¶m = path->index_merge();
unique_ptr_destroy_only<RowIterator> pk_quick_select;
if (job.children.is_null()) {
job.AllocChildren(mem_root, param.children->size());
todo.push_back(job);
for (size_t child_idx = 0; child_idx < param.children->size();
++child_idx) {
todo.push_back({(*param.children)[child_idx],
join,
/*eligible_for_batch_mode=*/false,
&job.children[child_idx],
{}});
}
continue;
}
Mem_root_array<unique_ptr_destroy_only<RowIterator>> children(mem_root);
children.reserve(param.children->size());
for (size_t child_idx = 0; child_idx < param.children->size();
++child_idx) {
AccessPath *range_scan = (*param.children)[child_idx];
if (param.allow_clustered_primary_key_scan &&
param.table->file->primary_key_is_clustered() &&
range_scan->index_range_scan().index ==
param.table->s->primary_key) {
assert(pk_quick_select == nullptr);
pk_quick_select = std::move(job.children[child_idx]);
} else {
children.push_back(std::move(job.children[child_idx]));
}
}
iterator = NewIterator<IndexMergeIterator>(
thd, mem_root, mem_root, param.table, std::move(pk_quick_select),
std::move(children));
break;
}
case AccessPath::ROWID_INTERSECTION: {
const auto ¶m = path->rowid_intersection();
if (job.children.is_null()) {
job.AllocChildren(mem_root, param.children->size() +
(param.cpk_child != nullptr ? 1 : 0));
todo.push_back(job);
for (size_t child_idx = 0; child_idx < param.children->size();
++child_idx) {
todo.push_back({(*param.children)[child_idx],
join,
/*eligible_for_batch_mode=*/false,
&job.children[child_idx],
{}});
}
if (param.cpk_child != nullptr) {
todo.push_back({param.cpk_child,
join,
/*eligible_for_batch_mode=*/false,
&job.children[param.children->size()],
{}});
}
continue;
}
// TODO(sgunders): Consider just sending in the array here,
// changing types in the constructor.
Mem_root_array<unique_ptr_destroy_only<RowIterator>> children(mem_root);
children.reserve(param.children->size());
for (size_t child_idx = 0; child_idx < param.children->size();
++child_idx) {
children.push_back(std::move(job.children[child_idx]));
}
unique_ptr_destroy_only<RowIterator> cpk_child;
if (param.cpk_child != nullptr) {
cpk_child = std::move(job.children[param.children->size()]);
}
iterator = NewIterator<RowIDIntersectionIterator>(
thd, mem_root, mem_root, param.table, param.retrieve_full_rows,
param.need_rows_in_rowid_order, std::move(children),
std::move(cpk_child));
break;
}
case AccessPath::ROWID_UNION: {
const auto ¶m = path->rowid_union();
if (job.children.is_null()) {
job.AllocChildren(mem_root, param.children->size());
todo.push_back(job);
for (size_t child_idx = 0; child_idx < param.children->size();
++child_idx) {
todo.push_back({(*param.children)[child_idx],
join,
/*eligible_for_batch_mode=*/false,
&job.children[child_idx],
{}});
}
continue;
}
// TODO(sgunders): Consider just sending in the array here,
// changing types in the constructor.
Mem_root_array<unique_ptr_destroy_only<RowIterator>> children(mem_root);
children.reserve(param.children->size());
for (unique_ptr_destroy_only<RowIterator> &child : job.children) {
children.push_back(std::move(child));
}
iterator = NewIterator<RowIDUnionIterator>(
thd, mem_root, mem_root, param.table, std::move(children));
break;
}
case AccessPath::INDEX_SKIP_SCAN: {
const IndexSkipScanParameters *param = path->index_skip_scan().param;
iterator = NewIterator<IndexSkipScanIterator>(
thd, mem_root, path->index_skip_scan().table, param->index_info,
path->index_skip_scan().index, param->eq_prefix_len,
param->eq_prefix_key_parts, param->eq_prefixes,
path->index_skip_scan().num_used_key_parts, mem_root,
param->has_aggregate_function, param->min_range_key,
param->max_range_key, param->min_search_key, param->max_search_key,
param->range_cond_flag, param->range_key_len);
break;
}
case AccessPath::GROUP_INDEX_SKIP_SCAN: {
const GroupIndexSkipScanParameters *param =
path->group_index_skip_scan().param;
iterator = NewIterator<GroupIndexSkipScanIterator>(
thd, mem_root, path->group_index_skip_scan().table,
¶m->min_functions, ¶m->max_functions,
param->have_agg_distinct, param->min_max_arg_part,
param->group_prefix_len, param->group_key_parts,
param->real_key_parts, param->max_used_key_length,
param->index_info, path->group_index_skip_scan().index,
param->key_infix_len, mem_root, param->is_index_scan,
¶m->prefix_ranges, ¶m->key_infix_ranges,
¶m->min_max_ranges);
break;
}
case AccessPath::DYNAMIC_INDEX_RANGE_SCAN: {
const auto ¶m = path->dynamic_index_range_scan();
iterator = NewIterator<DynamicRangeIterator>(
thd, mem_root, param.table, param.qep_tab, examined_rows);
break;
}
case AccessPath::TABLE_VALUE_CONSTRUCTOR: {
assert(join != nullptr);
Query_block *query_block = join->query_block;
iterator = NewIterator<TableValueConstructorIterator>(
thd, mem_root, examined_rows, *query_block->row_value_list,
path->table_value_constructor().output_refs);
break;
}
case AccessPath::FAKE_SINGLE_ROW:
iterator =
NewIterator<FakeSingleRowIterator>(thd, mem_root, examined_rows);
break;
case AccessPath::ZERO_ROWS: {
iterator = NewIterator<ZeroRowsIterator>(thd, mem_root,
CollectTables(thd, path));
break;
}
case AccessPath::ZERO_ROWS_AGGREGATED:
iterator = NewIterator<ZeroRowsAggregatedIterator>(thd, mem_root, join,
examined_rows);
break;
case AccessPath::MATERIALIZED_TABLE_FUNCTION: {
const auto ¶m = path->materialized_table_function();
if (job.children.is_null()) {
SetupJobsForChildren(mem_root, param.table_path, join,
eligible_for_batch_mode, &job, &todo);
continue;
}
iterator = NewIterator<MaterializedTableFunctionIterator>(
thd, mem_root, param.table_function, param.table,
std::move(job.children[0]));
break;
}
case AccessPath::UNQUALIFIED_COUNT:
iterator = NewIterator<UnqualifiedCountIterator>(thd, mem_root, join);
break;
case AccessPath::NESTED_LOOP_JOIN: {
const auto ¶m = path->nested_loop_join();
if (job.children.is_null()) {
SetupJobsForChildren(mem_root, param.outer, param.inner, join,
eligible_for_batch_mode, &job, &todo);
continue;
}
iterator = NewIterator<NestedLoopIterator>(
thd, mem_root, std::move(job.children[0]),
std::move(job.children[1]), param.join_type, param.pfs_batch_mode);
break;
}
case AccessPath::NESTED_LOOP_SEMIJOIN_WITH_DUPLICATE_REMOVAL: {
const auto ¶m = path->nested_loop_semijoin_with_duplicate_removal();
if (job.children.is_null()) {
SetupJobsForChildren(mem_root, param.outer, param.inner, join,
eligible_for_batch_mode, &job, &todo);
continue;
}
iterator = NewIterator<NestedLoopSemiJoinWithDuplicateRemovalIterator>(
thd, mem_root, std::move(job.children[0]),
std::move(job.children[1]), param.table, param.key, param.key_len);
break;
}
case AccessPath::BKA_JOIN: {
const auto ¶m = path->bka_join();
AccessPath *mrr_path =
FindSingleAccessPathOfType(param.inner, AccessPath::MRR);
if (job.children.is_null()) {
mrr_path->mrr().bka_path = path;
SetupJobsForChildren(mem_root, param.outer, param.inner, join,
/*inner_eligible_for_batch_mode=*/false, &job,
&todo);
continue;
}
MultiRangeRowIterator *mrr_iterator =
down_cast<MultiRangeRowIterator *>(
mrr_path->iterator->real_iterator());
iterator = NewIterator<BKAIterator>(
thd, mem_root, std::move(job.children[0]),
GetUsedTables(param.outer, /*include_pruned_tables=*/true),
std::move(job.children[1]), thd->variables.join_buff_size,
param.mrr_length_per_rec, param.rec_per_key, param.store_rowids,
param.tables_to_get_rowid_for, mrr_iterator,
CollectSingleRowIndexLookups(thd, path), param.join_type);
break;
}
case AccessPath::HASH_JOIN: {
const auto ¶m = path->hash_join();
if (job.children.is_null()) {
SetupJobsForChildren(mem_root, param.outer, param.inner, join,
/*inner_eligible_for_batch_mode=*/true, &job,
&todo);
continue;
}
const JoinPredicate *join_predicate = param.join_predicate;
vector<HashJoinCondition> conditions;
conditions.reserve(join_predicate->expr->equijoin_conditions.size());
for (Item_eq_base *cond : join_predicate->expr->equijoin_conditions) {
conditions.emplace_back(cond, thd->mem_root);
}
const Mem_root_array<Item *> *extra_conditions =
GetExtraHashJoinConditions(
mem_root, thd->lex->using_hypergraph_optimizer(), conditions,
join_predicate->expr->join_conditions);
if (extra_conditions == nullptr) return nullptr;
const bool probe_input_batch_mode =
eligible_for_batch_mode && ShouldEnableBatchMode(param.outer);
double estimated_build_rows = param.inner->num_output_rows();
if (param.inner->num_output_rows() < 0.0) {
// Not all access paths may propagate their costs properly.
// Choose a fairly safe estimate (it's better to be too large
// than too small).
estimated_build_rows = 1048576.0;
}
JoinType join_type{JoinType::INNER};
switch (join_predicate->expr->type) {
case RelationalExpression::INNER_JOIN:
case RelationalExpression::STRAIGHT_INNER_JOIN:
join_type = JoinType::INNER;
break;
case RelationalExpression::LEFT_JOIN:
join_type = JoinType::OUTER;
break;
case RelationalExpression::ANTIJOIN:
join_type = JoinType::ANTI;
break;
case RelationalExpression::SEMIJOIN:
join_type =
param.rewrite_semi_to_inner ? JoinType::INNER : JoinType::SEMI;
break;
case RelationalExpression::TABLE:
default:
assert(false);
}
// See if we can allow the hash table to keep its contents across Init()
// calls.
//
// The old optimizer will sometimes push join conditions referring
// to outer tables (in the same query block) down in under the hash
// operation, so without analysis of each filter and join condition, we
// cannot say for sure, and thus have to turn it off. But the hypergraph
// optimizer sets parameter_tables properly, so we're safe if we just
// check that.
//
// Regardless of optimizer, we can push outer references down in under
// the hash, but join->hash_table_generation will increase whenever we
// need to recompute the query block (in JOIN::clear_hash_tables()).
//
// TODO(sgunders): The old optimizer had a concept of _when_ to clear
// derived tables (invalidators), and this is somehow similar. If it
// becomes a performance issue, consider reintroducing them.
//
// TODO(sgunders): Should this perhaps be set as a flag on the access
// path instead of being computed here? We do make the same checks in
// the cost model, so perhaps it should set the flag as well.
uint64_t *hash_table_generation =
(thd->lex->using_hypergraph_optimizer() &&
path->parameter_tables == 0)
? &join->hash_table_generation
: nullptr;
// If the probe (outer) input is empty, the join result will be empty,
// and we do not need to read the build input. For inner join and
// semijoin, the converse is also true. To benefit from this, we want to
// start with the input where the cost of reading the first row is
// lowest. (We only do this for Hypergraph, as the cost data for the
// traditional optimizer are incomplete, and since we are reluctant to
// change existing behavior.) Note that we always try the probe input
// first for left join and antijoin.
const HashJoinInput first_input =
(thd->lex->using_hypergraph_optimizer() &&
param.inner->first_row_cost() > param.outer->first_row_cost())
? HashJoinInput::kProbe
: HashJoinInput::kBuild;
iterator = NewIterator<HashJoinIterator>(