forked from alibaba/AliSQL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake_join_hypergraph.cc
More file actions
3748 lines (3416 loc) · 151 KB
/
make_join_hypergraph.cc
File metadata and controls
3748 lines (3416 loc) · 151 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2020, 2025, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "sql/join_optimizer/make_join_hypergraph.h"
#include <assert.h>
#include <stddef.h>
#include <algorithm>
#include <array>
#include <iterator>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#include "limits.h"
#include "mem_root_deque.h"
#include "my_alloc.h"
#include "my_bit.h"
#include "my_inttypes.h"
#include "my_sys.h"
#include "my_table_map.h"
#include "mysqld_error.h"
#include "sql/current_thd.h"
#include "sql/item.h"
#include "sql/item_cmpfunc.h"
#include "sql/item_func.h"
#include "sql/join_optimizer/access_path.h"
#include "sql/join_optimizer/bit_utils.h"
#include "sql/join_optimizer/common_subexpression_elimination.h"
#include "sql/join_optimizer/cost_model.h"
#include "sql/join_optimizer/estimate_selectivity.h"
#include "sql/join_optimizer/find_contained_subqueries.h"
#include "sql/join_optimizer/hypergraph.h"
#include "sql/join_optimizer/print_utils.h"
#include "sql/join_optimizer/relational_expression.h"
#include "sql/join_optimizer/subgraph_enumeration.h"
#include "sql/nested_join.h"
#include "sql/sql_class.h"
#include "sql/sql_const.h"
#include "sql/sql_executor.h"
#include "sql/sql_lex.h"
#include "sql/sql_optimizer.h"
#include "sql/table.h"
#include "template_utils.h"
using hypergraph::Hyperedge;
using hypergraph::Hypergraph;
using hypergraph::NodeMap;
using std::array;
using std::max;
using std::min;
using std::string;
using std::swap;
using std::vector;
namespace {
RelationalExpression *MakeRelationalExpressionFromJoinList(
THD *thd, const mem_root_deque<Table_ref *> &join_list);
bool EarlyNormalizeConditions(THD *thd, RelationalExpression *join,
Mem_root_array<Item *> *conditions,
bool *always_false);
inline bool IsMultipleEquals(Item *cond) {
return cond->type() == Item::FUNC_ITEM &&
down_cast<Item_func *>(cond)->functype() == Item_func::MULT_EQUAL_FUNC;
}
Item_func_eq *MakeEqItem(Item *a, Item *b,
Item_equal *source_multiple_equality) {
Item_func_eq *eq_item = new Item_func_eq(a, b);
eq_item->set_cmp_func();
eq_item->update_used_tables();
eq_item->quick_fix_field();
eq_item->source_multiple_equality = source_multiple_equality;
return eq_item;
}
/**
Helper function for ReorderConditions(), which counts how many tables are
referenced by an equijoin condition. This enables ReorderConditions() to sort
the conditions on their complexity (referencing more tables == more complex).
Multiple equalities are considered simple, referencing two tables, regardless
of how many tables are actually referenced by them. This is because multiple
equalities will be split into one or more single equalities later, referencing
no more than two tables each.
*/
int CountTablesInEquiJoinCondition(Item *cond) {
assert(cond->type() == Item::FUNC_ITEM &&
down_cast<Item_func *>(cond)->contains_only_equi_join_condition());
if (IsMultipleEquals(cond)) {
// It's not a join condition if it has a constant argument.
assert(down_cast<Item_equal *>(cond)->const_arg() == nullptr);
return 2;
} else {
return PopulationCount(cond->used_tables());
}
}
/**
Reorders the predicates in such a way that equalities are placed ahead
of other types of predicates. These will be followed by predicates having
subqueries and the expensive predicates at the end.
This is used in the early stage of optimization. Predicates are not ordered
based on their selectivity yet. The call to optimize_cond() would have put
all the equalities at the end (because it tries to create multiple
equalities out of them). It is always better to see the equalties ahead of
other types of conditions when pushing join conditions down.
E.g:
(t1.f1 != t2.f1) and (t1.f2 = t3.f2 OR t4.f1 = t5.f3) and (3 = select #2) and
(t1.f3 = t3.f3) and multi_equal(t1.f2,t2.f3,t3.f4)
will be split in this order
(t1.f3 = t3.f3) and
multi_equal(t1.f2,t2.f3,t3.f4) and
(t1.f1 != t2.f1) and
(t1.f2 = t3.f2 OR t4.f1 = t5.f3) and
(3 = select #2)
Simple equijoin conditions (like t1.x=t2.x) are placed ahead of more complex
ones (like t1.x=t2.x+t3.x), so that we prefer making simple edges and avoid
hyperedges when we can.
*/
void ReorderConditions(Mem_root_array<Item *> *condition_parts) {
// First equijoin conditions, followed by other conditions, then
// subqueries (which can be expensive), then stored procedures
// (which are unknown, so potentially _very_ expensive).
const auto equi_cond_end = std::stable_partition(
condition_parts->begin(), condition_parts->end(), [](Item *item) {
return item->type() == Item::FUNC_ITEM &&
down_cast<Item_func *>(item)
->contains_only_equi_join_condition();
});
std::stable_sort(condition_parts->begin(), equi_cond_end,
[](Item *a, Item *b) {
return CountTablesInEquiJoinCondition(a) <
CountTablesInEquiJoinCondition(b);
});
std::stable_partition(condition_parts->begin(), condition_parts->end(),
[](Item *item) { return !item->has_subquery(); });
std::stable_partition(condition_parts->begin(), condition_parts->end(),
[](Item *item) { return !item->is_expensive(); });
}
/**
For a multiple equality, split out any conditions that refer to the
same table, without touching the multi-equality; e.g. for equal(t1.a, t2.a,
t2.b, t3.a), will return t2.a=t2.b AND (original item). This means that later
stages can ignore such duplicates, and also that we can push these parts
independently of the multiple equality as a whole.
*/
void ExpandSameTableFromMultipleEquals(Item_equal *equal,
table_map tables_in_subtree,
List<Item> *eq_items) {
// Look for pairs of items that touch the same table.
for (auto it1 = equal->get_fields().begin(); it1 != equal->get_fields().end();
++it1) {
if (!Overlaps(it1->used_tables(), tables_in_subtree)) {
continue;
}
for (auto it2 = std::next(it1); it2 != equal->get_fields().end(); ++it2) {
if (it1->field->table == it2->field->table) {
eq_items->push_back(MakeEqItem(&*it1, &*it2, equal));
// If there are more, i.e., *it2 = *it3, they will be dealt with
// in a future iteration of the outer loop; so stop now to avoid
// duplicates.
break;
}
}
}
}
/**
Expand multiple equalities that can (and should) be expanded before join
pushdown. These are the ones that touch at most two tables, or that
are against a constant. They can be expanded unambiguously; no matter the join
order, they will be the same. Fields on tables not in “tables_in_subtree” are
assumed to be irrelevant to the equality and ignored (see the comment on
PushDownCondition() for more details).
For multi-equalities that are kept, split out any conditions that refer to the
same table. See ExpandSameTableFromMultipleEquals().
The return value is an AND conjunction, so most likely, it needs to be split.
*/
Item *EarlyExpandMultipleEquals(Item *condition, table_map tables_in_subtree) {
return CompileItem(
condition, [](Item *) { return true; },
[tables_in_subtree](Item *item) -> Item * {
if (!IsMultipleEquals(item)) {
return item;
}
Item_equal *equal = down_cast<Item_equal *>(item);
List<Item> eq_items;
// If this condition is a constant, do the evaluation
// and add a "false" condition if needed.
// This cannot be skipped as optimize_cond() expects
// the value stored in "cond_false" to be checked for
// Item_equal before creating equalities from it.
// We do not need to check for the const item evaluating
// to be "true", as that could happen only when const table
// optimization is used (It is currently not done for
// hypergraph).
if (equal->const_item() && !equal->val_int()) {
eq_items.push_back(new Item_func_false);
} else if (equal->const_arg() != nullptr) {
// If there is a constant element, do a simple expansion.
for (Item_field &field : equal->get_fields()) {
if (IsSubset(field.used_tables(), tables_in_subtree)) {
eq_items.push_back(MakeEqItem(&field, equal->const_arg(), equal));
}
}
} else if (my_count_bits(equal->used_tables() & tables_in_subtree) >
2) {
// Only look at partial expansion.
ExpandSameTableFromMultipleEquals(equal, tables_in_subtree,
&eq_items);
eq_items.push_back(equal);
} else {
// Prioritize expanding equalities from the same table if possible;
// e.g., if we have t1.a = t2.a = t2.b, we want to have t2.a = t2.b
// included (ie., not t1.a = t2.a AND t1.a = t2.b). The primary reason
// for this is that such single-table equalities will be pushable
// as table filters, and not left on the joins. This means we avoid an
// issue where we have a hypergraph cycle where the edge we do not
// follow (and thus ignore) has more join conditions than we skip,
// causing us to wrongly “forget” constraining one degree of freedom.
//
// Thus, we first pick out every equality that touches only one table,
// and then link one equality from each table into an arbitrary one.
//
// It's not given that this will always give us the fastest possible
// plan; e.g. if there's a composite index on (t1.a, t1.b), it could
// be faster to use it for lookups against (t2.a, t2.b) instead of
// pushing t1.a = t1.b. But it doesn't seem worth it to try to keep
// multiple such variations around.
ExpandSameTableFromMultipleEquals(equal, tables_in_subtree,
&eq_items);
table_map included_tables = 0;
Item_field *base_item = nullptr;
for (Item_field &field : equal->get_fields()) {
assert(IsSingleBitSet(field.used_tables()));
if (!IsSubset(field.used_tables(), tables_in_subtree) ||
Overlaps(field.used_tables(), included_tables)) {
continue;
}
included_tables |= field.used_tables();
if (base_item == nullptr) {
base_item = &field;
continue;
}
eq_items.push_back(MakeEqItem(base_item, &field, equal));
// Since we have at most two tables, we can have only one link.
break;
}
}
assert(!eq_items.is_empty());
return CreateConjunction(&eq_items);
});
}
RelationalExpression *MakeRelationalExpression(THD *thd, const Table_ref *tl) {
if (tl->nested_join == nullptr) {
// A single table.
RelationalExpression *ret = new (thd->mem_root) RelationalExpression(thd);
ret->type = RelationalExpression::TABLE;
ret->table = tl;
ret->tables_in_subtree = tl->map();
ret->join_conditions_pushable_to_this.init(thd->mem_root);
return ret;
} else {
// A join or multijoin.
return MakeRelationalExpressionFromJoinList(thd, tl->nested_join->m_tables);
}
}
/**
Convert the Query_block's join lists into a RelationalExpression,
ie., a join tree with tables at the leaves.
*/
RelationalExpression *MakeRelationalExpressionFromJoinList(
THD *thd, const mem_root_deque<Table_ref *> &join_list) {
assert(!join_list.empty());
RelationalExpression *ret = nullptr;
for (auto it = join_list.rbegin(); it != join_list.rend();
++it) { // The list goes backwards.
const Table_ref *tl = *it;
if (ret == nullptr) {
// The first table in the list.
ret = MakeRelationalExpression(thd, tl);
continue;
}
RelationalExpression *join = new (thd->mem_root) RelationalExpression(thd);
join->left = ret;
if (tl->is_sj_or_aj_nest()) {
join->right =
MakeRelationalExpressionFromJoinList(thd, tl->nested_join->m_tables);
join->type = tl->is_sj_nest() ? RelationalExpression::SEMIJOIN
: RelationalExpression::ANTIJOIN;
} else {
join->right = MakeRelationalExpression(thd, tl);
if (tl->outer_join) {
join->type = RelationalExpression::LEFT_JOIN;
} else if (tl->straight) {
join->type = RelationalExpression::STRAIGHT_INNER_JOIN;
} else {
join->type = RelationalExpression::INNER_JOIN;
}
}
join->tables_in_subtree =
join->left->tables_in_subtree | join->right->tables_in_subtree;
if (tl->is_aj_nest()) {
assert(tl->join_cond_optim() != nullptr);
}
if (tl->join_cond_optim() != nullptr) {
Item *join_cond = EarlyExpandMultipleEquals(tl->join_cond_optim(),
join->tables_in_subtree);
ExtractConditions(join_cond, &join->join_conditions);
bool always_false = false;
EarlyNormalizeConditions(thd, join, &join->join_conditions,
&always_false);
ReorderConditions(&join->join_conditions);
}
ret = join;
}
return ret;
}
void ComputeCompanionSets(RelationalExpression *expr, int current_set,
int *num_companion_sets,
int table_num_to_companion_set[MAX_TABLES]) {
switch (expr->type) {
case RelationalExpression::TABLE:
expr->companion_set = current_set;
table_num_to_companion_set[expr->table->tableno()] = current_set;
return;
case RelationalExpression::STRAIGHT_INNER_JOIN:
case RelationalExpression::FULL_OUTER_JOIN:
ComputeCompanionSets(expr->left, /*current_set=*/-1, num_companion_sets,
table_num_to_companion_set);
ComputeCompanionSets(expr->right, /*current_set=*/-1, num_companion_sets,
table_num_to_companion_set);
break;
case RelationalExpression::INNER_JOIN:
if (current_set == -1) {
// Start a new set.
current_set = (*num_companion_sets)++;
}
ComputeCompanionSets(expr->left, current_set, num_companion_sets,
table_num_to_companion_set);
ComputeCompanionSets(expr->right, current_set, num_companion_sets,
table_num_to_companion_set);
break;
case RelationalExpression::LEFT_JOIN:
case RelationalExpression::SEMIJOIN:
case RelationalExpression::ANTIJOIN:
if (current_set == -1) {
// Start a new set.
current_set = (*num_companion_sets)++;
}
ComputeCompanionSets(expr->left, current_set, num_companion_sets,
table_num_to_companion_set);
ComputeCompanionSets(expr->right, /*current_set=*/-1, num_companion_sets,
table_num_to_companion_set);
break;
case RelationalExpression::MULTI_INNER_JOIN:
assert(false);
}
}
/**
Convert a multi-join into a simple inner join. expr must already have
the correct companion set filled out.
Only the top level will be converted, so there may still be a multi-join
below the modified node, e.g.:
MULTIJOIN(a, b) -> a JOIN b
MULTIJOIN(a, b, c, ...) -> a JOIN MULTIJOIN(b, c, ...)
If you want full unflattening, call UnflattenInnerJoins(), which calls this
function recursively.
*/
void CreateInnerJoinFromChildList(
Mem_root_array<RelationalExpression *> children,
RelationalExpression *expr) {
expr->type = RelationalExpression::INNER_JOIN;
expr->tables_in_subtree = 0;
expr->nodes_in_subtree = 0;
for (RelationalExpression *child : children) {
expr->tables_in_subtree |= child->tables_in_subtree;
expr->nodes_in_subtree |= child->nodes_in_subtree;
}
if (children.size() == 2) {
expr->left = children[0];
expr->right = children[1];
} else {
// Split arbitrarily.
expr->right = children.back();
children.pop_back();
RelationalExpression *left =
new (current_thd->mem_root) RelationalExpression(current_thd);
left->type = RelationalExpression::MULTI_INNER_JOIN;
left->tables_in_subtree = 0;
left->nodes_in_subtree = 0;
left->companion_set = expr->companion_set;
for (RelationalExpression *child : children) {
left->tables_in_subtree |= child->tables_in_subtree;
left->nodes_in_subtree |= child->nodes_in_subtree;
}
left->multi_children = std::move(children);
expr->left = left;
}
expr->multi_children.clear();
}
/**
Find all inner joins under “expr” without a join condition, and convert them
to a flattened join (MULTI_INNER_JOIN). We do this even for the joins that
have only two children, as it makes it easier to absorb them into higher
multi-joins.
The primary motivation for flattening is more flexible pushdown; when there is
a large multi-way join, we can push pretty much any equality condition down
to it, no matter how the join tree was written by the user.
See PartiallyUnflattenJoinForCondition() for details.
Note that this (currently) does not do any rewrites to flatten even more.
E.g., for the tree (a JOIN (b LEFT JOIN c)), it would be beneficial to use
associativity to rewrite into (a JOIN b) LEFT JOIN c (assuming a and b
could be combined further with other joins). This also means that there may
be items in the companion set that are not part of the same multi-join.
*/
void FlattenInnerJoins(RelationalExpression *expr) {
if (expr->type == RelationalExpression::MULTI_INNER_JOIN) {
// Already flattened, but grandchildren might need re-flattening.
for (RelationalExpression *child : expr->multi_children) {
FlattenInnerJoins(child);
assert(child->type != RelationalExpression::MULTI_INNER_JOIN);
}
return;
}
if (expr->type != RelationalExpression::TABLE) {
FlattenInnerJoins(expr->left);
FlattenInnerJoins(expr->right);
}
assert(expr->equijoin_conditions
.empty()); // MakeHashJoinConditions() has not run yet.
if (expr->type == RelationalExpression::INNER_JOIN &&
expr->join_conditions.empty()) {
// Collect and flatten children.
assert(expr->multi_children.empty());
expr->type = RelationalExpression::MULTI_INNER_JOIN;
if (expr->left->type == RelationalExpression::MULTI_INNER_JOIN) {
for (RelationalExpression *child : expr->left->multi_children) {
expr->multi_children.push_back(child);
}
} else {
expr->multi_children.push_back(expr->left);
}
if (expr->right->type == RelationalExpression::MULTI_INNER_JOIN) {
for (RelationalExpression *child : expr->right->multi_children) {
expr->multi_children.push_back(child);
}
} else {
expr->multi_children.push_back(expr->right);
}
expr->left = nullptr;
expr->right = nullptr;
}
}
/**
The opposite of FlattenInnerJoins(); converts all flattened joins to
a series of (right-deep) binary joins.
*/
void UnflattenInnerJoins(RelationalExpression *expr) {
if (expr->type == RelationalExpression::TABLE) {
return;
}
if (expr->type == RelationalExpression::MULTI_INNER_JOIN) {
// Peel off one table, then recurse. We could probably be
// somewhat more efficient than this if it's important.
CreateInnerJoinFromChildList(std::move(expr->multi_children), expr);
}
UnflattenInnerJoins(expr->left);
UnflattenInnerJoins(expr->right);
}
/**
For the given flattened join (multi-join), pull out (only) the parts we need
to push the given condition, and make a binary join for it. For instance,
if we have
MULTIJOIN(t1, t2, t3, t4 LJ t5)
and we have a condition t2.x = t5.x, we need to pull out the parts referring
to t2 and t5, partially exploding the multi-join:
MULTIJOIN(t1, t3, t2 JOIN (t4 LJ t5))
The newly created child will be returned, and the condition can be pushed
onto it. Note that there may be flattened joins under it; it is only the
returned node itself that is guaranteed to be a binary join.
If the condition touches all tables in the flattened join, the newly created
binary node will completely replace the former. (The simplest case of this is
a multi-join with only two nodes, and a condition referring to both of them.)
For instance, given
MULTIJOIN(t1, t2, t3)
and a condition t1.x = t2.x + t3.x, the entire node will be replaced by
t1 JOIN MULTIJOIN(t2, t3)
on which it is possible to push the condition. Which node is pulled out to
the left side is undefined.
See also CreateInnerJoinFromChildList().
*/
RelationalExpression *PartiallyUnflattenJoinForCondition(
table_map used_tables, RelationalExpression *expr) {
Mem_root_array<RelationalExpression *> affected_children(
current_thd->mem_root);
for (RelationalExpression *child : expr->multi_children) {
if (Overlaps(used_tables, child->tables_in_subtree) ||
Overlaps(used_tables, RAND_TABLE_BIT)) {
affected_children.push_back(child);
}
}
assert(affected_children.size() > 1);
if (affected_children.size() == expr->multi_children.size()) {
// We need all of the nodes, so replace ourself entirely.
CreateInnerJoinFromChildList(std::move(affected_children), expr);
return expr;
}
RelationalExpression *new_expr =
new (current_thd->mem_root) RelationalExpression(current_thd);
new_expr->companion_set = expr->companion_set;
CreateInnerJoinFromChildList(std::move(affected_children), new_expr);
// Insert the new node as one of the children, and take out
// the ones we've moved down into it.
auto new_end =
std::remove_if(expr->multi_children.begin(), expr->multi_children.end(),
[used_tables](const RelationalExpression *child) {
return Overlaps(used_tables, child->tables_in_subtree) ||
Overlaps(used_tables, RAND_TABLE_BIT);
});
expr->multi_children.erase(new_end, expr->multi_children.end());
expr->multi_children.push_back(new_expr);
return new_expr;
}
string PrintRelationalExpression(RelationalExpression *expr, int level) {
string result;
for (int i = 0; i < level * 2; ++i) result += ' ';
switch (expr->type) {
case RelationalExpression::TABLE:
if (expr->companion_set != -1) {
result += StringPrintf("* %s [companion set %d]\n", expr->table->alias,
expr->companion_set);
} else {
result += StringPrintf("* %s\n", expr->table->alias);
}
// Do not try to descend further.
return result;
case RelationalExpression::INNER_JOIN:
case RelationalExpression::MULTI_INNER_JOIN:
result += "* Inner join";
break;
case RelationalExpression::STRAIGHT_INNER_JOIN:
result += "* Inner join [forced noncommutative]";
break;
case RelationalExpression::LEFT_JOIN:
result += "* Left join";
break;
case RelationalExpression::SEMIJOIN:
result += "* Semijoin";
break;
case RelationalExpression::ANTIJOIN:
result += "* Antijoin";
break;
case RelationalExpression::FULL_OUTER_JOIN:
result += "* Full outer join";
break;
}
if (expr->type == RelationalExpression::MULTI_INNER_JOIN) {
// Should only exist before pushdown.
assert(expr->equijoin_conditions.empty() && expr->join_conditions.empty());
result += " (flattened)\n";
for (RelationalExpression *child : expr->multi_children) {
result += PrintRelationalExpression(child, level + 1);
}
return result;
}
if (!expr->equijoin_conditions.empty() && !expr->join_conditions.empty()) {
result += StringPrintf(" (equijoin condition = %s, extra = %s)",
ItemsToString(expr->equijoin_conditions).c_str(),
ItemsToString(expr->join_conditions).c_str());
} else if (!expr->equijoin_conditions.empty()) {
result += StringPrintf(" (equijoin condition = %s)",
ItemsToString(expr->equijoin_conditions).c_str());
} else if (!expr->join_conditions.empty()) {
result += StringPrintf(" (extra join condition = %s)",
ItemsToString(expr->join_conditions).c_str());
} else {
result += " (no join conditions)";
}
result += '\n';
result += PrintRelationalExpression(expr->left, level + 1);
result += PrintRelationalExpression(expr->right, level + 1);
return result;
}
// Returns whether the join condition for “expr” is null-rejecting (also known
// as strong or strict) on the given relations; that is, if it is guaranteed to
// return FALSE or NULL if _all_ tables in “tables” consist only of NULL values.
// (This means that adding tables in “tables” which are not part of any of the
// predicates is legal, and has no effect on the result.)
//
// A typical example of a null-rejecting condition would be a simple equality,
// e.g. t1.x = t2.x, which would reject NULLs on t1 and t2.
bool IsNullRejecting(const RelationalExpression &expr, table_map tables) {
for (Item *cond : expr.join_conditions) {
if (Overlaps(tables, cond->not_null_tables())) {
return true;
}
}
for (Item *cond : expr.equijoin_conditions) {
if (Overlaps(tables, cond->not_null_tables())) {
return true;
}
}
return false;
}
bool IsInnerJoin(RelationalExpression::Type type) {
return type == RelationalExpression::INNER_JOIN ||
type == RelationalExpression::STRAIGHT_INNER_JOIN ||
type == RelationalExpression::MULTI_INNER_JOIN;
}
// Returns true if (t1 <a> t2) <b> t3 === t1 <a> (t2 <b> t3).
//
// Note that this is not symmetric; e.g.
//
// (t1 JOIN t2) LEFT JOIN t3 === t1 JOIN (t2 LEFT JOIN t3)
//
// but
//
// (t1 LEFT JOIN t2) JOIN t3 != t1 LEFT JOIN (t2 JOIN t3)
//
// Note that this does not check that the rewrite would be _syntatically_ valid,
// i.e., that <b> does not refer to tables from t1. That is the job of the SES
// (syntactic eligibility set), which forms the base of the hyperedge
// representing the join, and not conflict rules -- if <b> refers to t1, the
// edge will include t1 no matter what we return here. This also goes for
// l-asscom and r-asscom below.
//
// When generating conflict rules, we call this function in a generalized sense:
//
// 1. t1, t2 and t3 could be join expressions, not just single tables.
// 2. <a> may not be a direct descendant of <b>, but further down the tree.
// 3. <b> may be below <a> in the tree, instead of the other way round.
//
// Due to #1 and #2, we need to take care when checking for null-rejecting
// conditions. Specifically, when the tables say we should check whether a
// condition mentioning (t2,t3) is null-rejecting on t2, we need to check the
// left arm of <b> instead of the right arm of <a>, as the condition might
// refer to a table that is not even part of <a> (ie., the “t2” in the condition
// is not the same “t2” as is under <a>). Otherwise, we might be rejecting
// valid plans. An example (where LJmn is LEFT JOIN with a null-rejecting
// predicate between tables m and n):
//
// ((t1 LJ12 t2) LJ23 t3) LJ34 t4
//
// At some point, we will be called with <a> = LJ12 and <b> = LJ34.
// If we check whether LJ34 is null-rejecting on t2 (a.right), instead of
// checking wheher it is null-rejecting on {t1,t2,t3} (b.left), we will
// erroneously create a conflict rule {t2} → {t1}, since we believe the
// LJ34 predicate is not null-rejecting on its left side.
//
// A special note on semijoins not covered in [Moe13]: If the inner side
// is known to be free of duplicates on the key (e.g. because we removed
// them), semijoin is equivalent to inner join and is both commutative
// and associative. (We use this in the join optimizer.) However, we don't
// actually need to care about this here, because the way semijoin is
// defined, it is impossible to do an associate rewrite without there being
// degenerate join predicates, and we already accept missing some rewrites
// for them. Ie., for associativity to matter, one would need to have a
// rewrite like
//
// (t1 SJ12 t2) J23 t3 === t1 SJ12 (t2 J23 t3)
//
// but there's no way we could have a condition J23 on the left side
// to begin with; semijoin in SQL comes from IN or EXISTS, which makes
// the attributes from t2 inaccessible after the join. Thus, J23 would
// have to be J3 (degenerate). The same argument explains why we don't
// need to worry about r-asscom, and semijoins are already l-asscom.
bool OperatorsAreAssociative(const RelationalExpression &a,
const RelationalExpression &b) {
// Table 2 from [Moe13]; which operator pairs are associative.
if ((a.type == RelationalExpression::LEFT_JOIN ||
a.type == RelationalExpression::FULL_OUTER_JOIN) &&
b.type == RelationalExpression::LEFT_JOIN) {
// True if and only if the second join predicate rejects NULLs
// on all tables in e2.
return IsNullRejecting(b, b.left->tables_in_subtree);
}
if (a.type == RelationalExpression::FULL_OUTER_JOIN &&
b.type == RelationalExpression::FULL_OUTER_JOIN) {
// True if and only if both join predicates rejects NULLs
// on all tables in e2.
return IsNullRejecting(a, a.right->tables_in_subtree) &&
IsNullRejecting(b, b.left->tables_in_subtree);
}
// Secondary engine does not want us to treat STRAIGHT_JOINs as
// associative.
if ((current_thd->secondary_engine_optimization() ==
Secondary_engine_optimization::SECONDARY) &&
(a.type == RelationalExpression::STRAIGHT_INNER_JOIN ||
b.type == RelationalExpression::STRAIGHT_INNER_JOIN)) {
return false;
}
// For the operations we support, it can be collapsed into this simple
// condition. (Cartesian products and inner joins are treated the same.)
return IsInnerJoin(a.type) && b.type != RelationalExpression::FULL_OUTER_JOIN;
}
// Returns true if (t1 <a> t2) <b> t3 === (t1 <b> t3) <a> t2,
// ie., the order of right-applying <a> and <b> don't matter.
//
// This is a symmetric property. The name comes from the fact that
// associativity and commutativity together would imply l-asscom;
// however, the converse is not true, so this is a more lenient property.
//
// See comments on OperatorsAreAssociative().
bool OperatorsAreLeftAsscom(const RelationalExpression &a,
const RelationalExpression &b) {
// Associative and asscom implies commutativity, and since STRAIGHT_JOIN
// is associative and we don't want it to be commutative, we can't make it
// asscom. As an example, a user writing
//
// (t1 STRAIGHT_JOIN t2) STRAIGHT_JOIN t3
//
// would never expect it to be rewritten to
//
// (t1 STRAIGHT_JOIN t3) STRAIGHT_JOIN t2
//
// since that would effectively switch the order of t2 and t3.
// It's possible we could be slightly more lenient here for some cases
// (e.g. if t1/t2 were a regular inner join), but presumably, people
// write STRAIGHT_JOIN to get _less_ leniency, so we just block them
// off entirely.
if (a.type == RelationalExpression::STRAIGHT_INNER_JOIN ||
b.type == RelationalExpression::STRAIGHT_INNER_JOIN) {
return false;
}
// Table 3 from [Moe13]; which operator pairs are l-asscom.
// (Cartesian products and inner joins are treated the same.)
if (a.type == RelationalExpression::LEFT_JOIN) {
if (b.type == RelationalExpression::FULL_OUTER_JOIN) {
return IsNullRejecting(a, a.left->tables_in_subtree);
} else {
return true;
}
}
if (a.type == RelationalExpression::FULL_OUTER_JOIN) {
if (b.type == RelationalExpression::LEFT_JOIN) {
return IsNullRejecting(b, b.right->tables_in_subtree);
}
if (b.type == RelationalExpression::FULL_OUTER_JOIN) {
return IsNullRejecting(a, a.left->tables_in_subtree) &&
IsNullRejecting(b, b.left->tables_in_subtree);
}
return false;
}
return b.type != RelationalExpression::FULL_OUTER_JOIN;
}
// Returns true if e1 <a> (e2 <b> e3) === e2 <b> (e1 <a> e3),
// ie., the order of left-applying <a> and <b> don't matter.
// Similar to OperatorsAreLeftAsscom().
bool OperatorsAreRightAsscom(const RelationalExpression &a,
const RelationalExpression &b) {
// Table 3 from [Moe13]; which operator pairs are r-asscom.
// (Cartesian products and inner joins are treated the same.)
if (a.type == RelationalExpression::FULL_OUTER_JOIN &&
b.type == RelationalExpression::FULL_OUTER_JOIN) {
return IsNullRejecting(a, a.right->tables_in_subtree) &&
IsNullRejecting(b, b.right->tables_in_subtree);
}
// See OperatorsAreLeftAsscom() for why we don't accept STRAIGHT_INNER_JOIN.
return a.type == RelationalExpression::INNER_JOIN &&
b.type == RelationalExpression::INNER_JOIN;
}
enum class AssociativeRewritesAllowed { ANY, RIGHT_ONLY, LEFT_ONLY };
/**
Find a bitmap of used tables for all conditions on \<expr\>.
Note that after all conditions have been pushed, you can check
expr.conditions_used_tables instead (see FindConditionsUsedTables()).
NOTE: The map might be wider than expr.tables_in_subtree due to
multiple equalities; you should normally just ignore those bits.
*/
table_map UsedTablesForCondition(const RelationalExpression &expr) {
assert(expr.equijoin_conditions
.empty()); // MakeHashJoinConditions() has not run yet.
table_map used_tables = 0;
for (Item *cond : expr.join_conditions) {
used_tables |= cond->used_tables();
}
return used_tables;
}
/**
Like UsedTablesForCondition(), but multiple equalities set no bits unless
they're certain, i.e., cannot be avoided no matter how we break up the
multiple equality. This is the case for tables that are the only ones on
their side of the join. E.g.: For a multiple equality {A,C,D} on a join
(A,B) JOIN (C,D), A is certain; either A=C or A=D has to be included
no matter what.
*/
table_map CertainlyUsedTablesForCondition(const RelationalExpression &expr) {
assert(expr.equijoin_conditions
.empty()); // MakeHashJoinConditions() has not run yet.
table_map used_tables = 0;
for (Item *cond : expr.join_conditions) {
table_map this_used_tables = cond->used_tables();
if (IsMultipleEquals(cond)) {
table_map left_bits = this_used_tables & GetVisibleTables(expr.left);
table_map right_bits = this_used_tables & GetVisibleTables(expr.right);
if (IsSingleBitSet(left_bits)) {
used_tables |= left_bits;
}
if (IsSingleBitSet(right_bits)) {
used_tables |= right_bits;
}
} else {
used_tables |= this_used_tables;
}
}
return used_tables;
}
/**
For a given set of tables, find the companion set they are part of (see
RelationalExpression::companion_set for an explanation of companion sets).
Returns -1 if the tables are in different (ie., incompatible) companion sets;
if so, a condition using this set of tables can _not_ induce a new (cycle)
edge in the hypergraph, as there are non-inner joins in the way.
*/
int CompanionSetUsedByCondition(
table_map tables, const int table_num_to_companion_set[MAX_TABLES]) {
assert(tables != 0);
int ret = -1;
for (int table_num : BitsSetIn(tables)) {
if (table_num >= int{MAX_TABLES} ||
table_num_to_companion_set[table_num] == -1) {
// This table is not part of a companion set.
return -1;
}
if (ret == -1) {
// First table.
ret = table_num_to_companion_set[table_num];
} else if (ret != table_num_to_companion_set[table_num]) {
// Incompatible sets.
return -1;
}
}
return ret;
}
/**
Check whether we are allowed to make an extra join edge with the given
condition, instead of pushing the condition onto the given point in the
join tree (which we have presumably found out that we don't want).
*/
bool IsCandidateForCycle(RelationalExpression *expr, Item *cond,
const int table_num_to_companion_set[MAX_TABLES]) {
if (cond->type() != Item::FUNC_ITEM) {
return false;
}
if (Overlaps(cond->used_tables(), PSEUDO_TABLE_BITS)) {
return false;
}
Item_func *func_item = down_cast<Item_func *>(cond);
if (!IsMultipleEquals(func_item)) {
// Don't try to make cycle edges out of hyperpredicates, at least for now;
// simple equalities and multi-equalities only.
if (!func_item->contains_only_equi_join_condition()) {
return false;
}
if (my_count_bits(cond->used_tables()) != 2) {
return false;
}
}
// Check that we are not combining together anything that is not part of
// the same companion set (either by means of the condition, or by making
// a cycle through an already-existing condition).
table_map used_tables = cond->used_tables();
assert(expr->equijoin_conditions
.empty()); // MakeHashJoinConditions() has not run yet.
for (Item *other_cond : expr->join_conditions) {
used_tables |= other_cond->used_tables();
}
return CompanionSetUsedByCondition(used_tables & expr->tables_in_subtree,
table_num_to_companion_set) != -1;
}
bool ComesFromMultipleEquality(Item *item, Item_equal *equal) {
return is_function_of_type(item, Item_func::EQ_FUNC) &&
down_cast<Item_func_eq *>(item)->source_multiple_equality == equal;
}
int FindSourceMultipleEquality(Item *item,
const Mem_root_array<Item_equal *> &equals) {
if (!is_function_of_type(item, Item_func::EQ_FUNC)) {
return -1;
}
Item_func_eq *eq = down_cast<Item_func_eq *>(item);
for (size_t equals_idx = 0; equals_idx < equals.size(); ++equals_idx) {
if (eq->source_multiple_equality == equals[equals_idx]) {
return static_cast<int>(equals_idx);
}
}
return -1;
}
bool MultipleEqualityAlreadyExistsOnJoin(Item_equal *equal,
const RelationalExpression &expr) {
// Could be called both before and after MakeHashJoinConditions(),
// so check for join_conditions and equijoin_conditions.
for (Item *item : expr.join_conditions) {
if (ComesFromMultipleEquality(item, equal)) {
return true;
}
}
for (Item_eq_base *item : expr.equijoin_conditions) {
if (item->source_multiple_equality == equal) {
return true;
}
}
return false;
}
bool AlreadyExistsOnJoin(Item *cond, const RelationalExpression &expr) {
assert(expr.equijoin_conditions
.empty()); // MakeHashJoinConditions() has not run yet.
constexpr bool binary_cmp = true;
for (Item *item : expr.join_conditions) {
if (cond->eq(item, binary_cmp)) {
return true;
}
}