forked from alibaba/AliSQL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteresting_orders.cc
More file actions
2319 lines (2072 loc) · 85.7 KB
/
interesting_orders.cc
File metadata and controls
2319 lines (2072 loc) · 85.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2021, 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/interesting_orders.h"
#include <algorithm>
#include <cstddef>
#include <functional>
#include <type_traits>
#include "map_helpers.h"
#include "my_hash_combine.h"
#include "my_pointer_arithmetic.h"
#include "sql/item.h"
#include "sql/item_func.h"
#include "sql/item_sum.h"
#include "sql/join_optimizer/bit_utils.h"
#include "sql/join_optimizer/print_utils.h"
#include "sql/mem_root_array.h"
#include "sql/parse_tree_nodes.h"
#include "sql/sql_array.h"
#include "sql/sql_class.h"
#include "sql/sql_executor.h"
using std::all_of;
using std::bind;
using std::distance;
using std::equal;
using std::fill;
using std::lower_bound;
using std::make_pair;
using std::max;
using std::none_of;
using std::pair;
using std::sort;
using std::string;
using std::swap;
using std::unique;
using std::upper_bound;
/**
A scope-guard class for allocating an Ordering::Elements instance
which is automatically returned to the pool when we exit the scope of
the OrderingElementsGuard instance.
*/
class OrderingElementsGuard final {
public:
/**
@param context The object containing the pool.
@param mem_root For allocating additional Ordering::Elements instances if
needed.
*/
OrderingElementsGuard(LogicalOrderings *context, MEM_ROOT *mem_root)
: m_context{context} {
m_elements = context->RetrieveElements(mem_root);
}
// No copying of this class.
OrderingElementsGuard(const OrderingElementsGuard &) = delete;
OrderingElementsGuard &operator=(const OrderingElementsGuard &) = delete;
~OrderingElementsGuard() { m_context->ReturnElements(m_elements); }
Ordering::Elements &Get() { return m_elements; }
private:
/// The object containing the pool.
LogicalOrderings *m_context;
/// The instance fetched from the pool.
Ordering::Elements m_elements;
};
namespace {
// Set some maximum limits on the size of the FSMs, in order to prevent runaway
// computation on pathological queries. As rough reference: As of 8.0.26,
// there is a single query in the test suite hitting these limits (it wants 8821
// NFSM states and an estimated 2^50 DFSM states). Excluding that query, the
// test suite contains the following largest FSMs:
//
// - Largest NFSM: 63 NFSM states => 2 DFSM states
// - Largest DFSM: 37 NFSM states => 152 DFSM states
//
// And for DBT-3:
//
// - Largest NFSM: 43 NFSM states => 3 DFSM states
// - Largest DFSM: 8 NFSM states => 8 DFSM states
//
// We could make system variables out of these if needed, but they would
// probably have to be settable by superusers only, in order to prevent runaway
// unabortable queries from taking down the server. Having them as fixed limits
// is good enough for now.
constexpr int kMaxNFSMStates = 200;
constexpr int kMaxDFSMStates = 2000;
/**
Check if 'elements' contains 'item'.
*/
bool Contains(Ordering::Elements elements, int item) {
return std::any_of(elements.cbegin(), elements.cend(),
[item](OrderElement elem) { return elem.item == item; });
}
// Calculates the hash for a DFSM state given by an index into
// LogicalOrderings::m_dfsm_states. The hash is based on the set of NFSM states
// the DFSM state corresponds to.
template <typename DFSMState>
struct DFSMStateHash {
const Mem_root_array<DFSMState> *dfsm_states;
size_t operator()(int idx) const {
size_t hash = 0;
for (int nfsm_state : (*dfsm_states)[idx].nfsm_states) {
my_hash_combine<size_t>(hash, nfsm_state);
}
return hash;
}
};
// Checks if two DFSM states represent the same set of NFSM states.
template <typename DFSMState>
struct DFSMStateEqual {
const Mem_root_array<DFSMState> *dfsm_states;
bool operator()(int idx1, int idx2) const {
return equal((*dfsm_states)[idx1].nfsm_states.begin(),
(*dfsm_states)[idx1].nfsm_states.end(),
(*dfsm_states)[idx2].nfsm_states.begin(),
(*dfsm_states)[idx2].nfsm_states.end());
}
};
} // namespace
void Ordering::Deduplicate() {
assert(Valid());
size_t length = 0;
for (size_t i = 0; i < m_elements.size(); ++i) {
if (!Contains(m_elements.prefix(length), m_elements[i].item)) {
m_elements[length++] = m_elements[i];
}
}
m_elements.resize(length);
}
bool Ordering::Valid() const {
switch (m_kind) {
case Kind::kEmpty:
return m_elements.empty();
case Kind::kOrder:
return !m_elements.empty() &&
std::all_of(m_elements.cbegin(), m_elements.cend(),
[](OrderElement e) {
return e.direction != ORDER_NOT_RELEVANT;
});
case Kind::kRollup:
case Kind::kGroup:
return !m_elements.empty() &&
std::all_of(m_elements.cbegin(), m_elements.cend(),
[](OrderElement e) {
return e.direction == ORDER_NOT_RELEVANT;
});
}
assert(false);
return false;
}
LogicalOrderings::LogicalOrderings(THD *thd)
: m_items(thd->mem_root),
m_orderings(thd->mem_root),
m_fds(thd->mem_root),
m_states(thd->mem_root),
m_dfsm_states(thd->mem_root),
m_dfsm_edges(thd->mem_root),
m_elements_pool(thd->mem_root) {
GetHandle(nullptr); // Always has the zero handle.
// Add the empty ordering/grouping.
m_orderings.push_back(OrderingWithInfo{Ordering(),
OrderingWithInfo::UNINTERESTING,
/*used_at_end=*/true});
FunctionalDependency decay_fd;
decay_fd.type = FunctionalDependency::DECAY;
decay_fd.tail = 0;
decay_fd.always_active = true;
m_fds.push_back(decay_fd);
}
int LogicalOrderings::AddOrderingInternal(THD *thd, Ordering order,
OrderingWithInfo::Type type,
bool used_at_end,
table_map homogenize_tables) {
assert(!m_built);
#ifndef NDEBUG
if (order.GetKind() == Ordering::Kind::kGroup) {
Ordering::Elements elements = order.GetElements();
// Verify that the grouping is sorted and deduplicated.
for (size_t i = 1; i < elements.size(); ++i) {
assert(elements[i].item > elements[i - 1].item);
assert(elements[i].direction == ORDER_NOT_RELEVANT);
}
// Verify that none of the items are of ROW_RESULT,
// as RemoveDuplicatesIterator cannot handle them.
// (They would theoretically be fine for orderings.)
for (size_t i = 0; i < elements.size(); ++i) {
assert(m_items[elements[i].item].item->result_type() != ROW_RESULT);
}
}
#endif
if (type != OrderingWithInfo::UNINTERESTING) {
for (OrderElement element : order.GetElements()) {
if (element.direction == ORDER_ASC) {
m_items[element.item].used_asc = true;
}
if (element.direction == ORDER_DESC) {
m_items[element.item].used_desc = true;
}
if (element.direction == ORDER_NOT_RELEVANT) {
m_items[element.item].used_in_grouping = true;
}
}
}
// Deduplicate against all the existing ones.
for (size_t i = 0; i < m_orderings.size(); ++i) {
if (m_orderings[i].ordering == order) {
// Potentially promote the existing one.
m_orderings[i].type = std::max(m_orderings[i].type, type);
m_orderings[i].homogenize_tables |= homogenize_tables;
return i;
}
}
m_orderings.push_back(OrderingWithInfo{order.Clone(thd->mem_root), type,
used_at_end, homogenize_tables});
m_longest_ordering = std::max<int>(m_longest_ordering, order.size());
return m_orderings.size() - 1;
}
int LogicalOrderings::AddFunctionalDependency(THD *thd,
FunctionalDependency fd) {
assert(!m_built);
// Deduplicate against all the existing ones.
for (size_t i = 0; i < m_fds.size(); ++i) {
if (m_fds[i].type != fd.type) {
continue;
}
if (fd.type == FunctionalDependency::EQUIVALENCE) {
// Equivalences are symmetric.
if (m_fds[i].head[0] == fd.head[0] && m_fds[i].tail == fd.tail) {
return i;
}
if (m_fds[i].tail == fd.head[0] && m_fds[i].head[0] == fd.tail) {
return i;
}
} else {
if (m_fds[i].tail == fd.tail &&
equal(m_fds[i].head.begin(), m_fds[i].head.end(), fd.head.begin(),
fd.head.end())) {
return i;
}
}
}
fd.head = fd.head.Clone(thd->mem_root);
m_fds.push_back(fd);
return m_fds.size() - 1;
}
void LogicalOrderings::Build(THD *thd, string *trace) {
// If we have no interesting orderings or groupings, just create a DFSM
// directly with a single state for the empty ordering.
if (m_orderings.size() == 1) {
m_dfsm_states.reserve(1);
m_dfsm_states.emplace_back();
DFSMState &initial = m_dfsm_states.back();
initial.nfsm_states.init(thd->mem_root);
initial.nfsm_states.reserve(1);
initial.nfsm_states.push_back(0);
initial.next_state =
Bounds_checked_array<int>::Alloc(thd->mem_root, m_fds.size());
m_optimized_ordering_mapping =
Bounds_checked_array<int>::Alloc(thd->mem_root, 1);
m_built = true;
return;
}
BuildEquivalenceClasses();
RecanonicalizeGroupings();
AddFDsFromComputedItems(thd);
AddFDsFromConstItems(thd);
AddFDsFromAggregateItems(thd);
PreReduceOrderings(thd);
CreateOrderingsFromGroupings(thd);
CreateHomogenizedOrderings(thd);
PruneFDs(thd);
if (trace != nullptr) {
PrintFunctionalDependencies(trace);
}
FindElementsThatCanBeAddedByFDs();
PruneUninterestingOrders(thd);
if (trace != nullptr) {
PrintInterestingOrders(trace);
}
BuildNFSM(thd);
if (trace != nullptr) {
*trace += "NFSM for interesting orders, before pruning:\n";
PrintNFSMDottyGraph(trace);
if (m_states.size() >= kMaxNFSMStates) {
*trace += "NOTE: NFSM is incomplete, because it became too big.\n";
}
}
PruneNFSM(thd);
if (trace != nullptr) {
*trace += "\nNFSM for interesting orders, after pruning:\n";
PrintNFSMDottyGraph(trace);
}
ConvertNFSMToDFSM(thd);
if (trace != nullptr) {
*trace += "\nDFSM for interesting orders:\n";
PrintDFSMDottyGraph(trace);
if (m_dfsm_states.size() >= kMaxDFSMStates) {
*trace +=
"NOTE: DFSM does not contain all NFSM states, because it became too "
"big.\n";
}
}
FindInitialStatesForOrdering();
m_built = true;
}
LogicalOrderings::StateIndex LogicalOrderings::ApplyFDs(
LogicalOrderings::StateIndex state_idx, FunctionalDependencySet fds) const {
for (;;) { // Termination condition within loop.
FunctionalDependencySet relevant_fds =
m_dfsm_states[state_idx].can_use_fd & fds;
if (relevant_fds.none()) {
return state_idx;
}
// Pick an arbitrary one and follow it. Note that this part assumes
// kMaxSupportedFDs <= 64.
static_assert(kMaxSupportedFDs <= sizeof(unsigned long long) * CHAR_BIT);
int fd_idx = FindLowestBitSet(relevant_fds.to_ullong()) + 1;
state_idx = m_dfsm_states[state_idx].next_state[fd_idx];
// Now continue for as long as we have anything to follow;
// we'll converge on the right answer eventually. Typically,
// there will be one or two edges to follow, but in extreme cases,
// there could be O(k²) in the number of FDs.
}
}
/**
Try to get rid of uninteresting orders, possibly by discarding irrelevant
suffixes and merging them with others. In a typical query, this removes a
large amount of index-created orderings that will never get to something
interesting, reducing the end FSM size (and thus, reducing the number of
different access paths we have to keep around).
This step is the only one that can move orderings around, and thus also
populates m_optimized_ordering_mapping.
*/
void LogicalOrderings::PruneUninterestingOrders(THD *thd) {
m_optimized_ordering_mapping =
Bounds_checked_array<int>::Alloc(thd->mem_root, m_orderings.size());
int new_length = 0;
for (size_t ordering_idx = 0; ordering_idx < m_orderings.size();
++ordering_idx) {
if (m_orderings[ordering_idx].type == OrderingWithInfo::UNINTERESTING) {
Ordering &ordering = m_orderings[ordering_idx].ordering;
// We are not prepared for uninteresting groupings yet.
assert(ordering.GetKind() != Ordering::Kind::kGroup);
// Find the longest prefix that contains only elements that are used in
// interesting groupings. We will never shorten the uninteresting ordering
// below this; it is overconservative in some cases, but it makes sure
// we never miss a path to an interesting grouping.
size_t minimum_prefix_len = 0;
const Ordering::Elements &elements = ordering.GetElements();
while (elements.size() > minimum_prefix_len &&
m_items[m_items[elements[minimum_prefix_len].item].canonical_item]
.used_in_grouping) {
++minimum_prefix_len;
}
// Shorten this ordering one by one element, until it can (heuristically)
// become an interesting ordering with the FDs we have. Note that it might
// become the empty ordering, and if so, it will be deleted entirely
// in the step below.
while (elements.size() > minimum_prefix_len &&
!CouldBecomeInterestingOrdering(ordering)) {
if (elements.size() > 1) {
ordering = Ordering(elements.without_back(), ordering.GetKind());
} else {
ordering = Ordering();
}
}
}
// Since some orderings may have changed, we need to re-deduplicate.
// Note that at this point, we no longer care about used_at_end;
// it was only used for reducing orderings in homogenization.
m_optimized_ordering_mapping[ordering_idx] = new_length;
for (int i = 0; i < new_length; ++i) {
if (m_orderings[i].ordering == m_orderings[ordering_idx].ordering) {
m_optimized_ordering_mapping[ordering_idx] = i;
m_orderings[i].type =
std::max(m_orderings[i].type, m_orderings[ordering_idx].type);
break;
}
}
if (m_optimized_ordering_mapping[ordering_idx] == new_length) {
// Not a duplicate of anything earlier, so keep it.
m_orderings[new_length++] = m_orderings[ordering_idx];
}
}
m_orderings.resize(new_length);
}
void LogicalOrderings::PruneFDs(THD *thd) {
// The definition of prunable FDs in the papers seems to be very abstract
// and not practically realizable, so we use a simple heuristic instead:
// A FD is useful iff it produces an item that is part of some ordering.
// Discard all useless FDs. (Items not part of some ordering will cause
// the new proposed ordering to immediately be pruned away, so this is
// safe. See also the comment in the .h file about transitive dependencies.)
//
// Note that this will sometimes leave useless FDs; if we have e.g. a → b
// and b is useful, we will mark the FD as useful even if nothing can
// produce a. However, such FDs don't induce more NFSM states (which is
// the main point of the pruning), it just slows the NFSM down slightly,
// and by far the dominant FDs to prune in our cases are the ones
// induced by keys, e.g. S → k where S is always the same and k
// is useless. These are caught by this heuristic.
m_optimized_fd_mapping =
Bounds_checked_array<int>::Alloc(thd->mem_root, m_fds.size());
size_t old_length = m_fds.size();
// We always need to keep the decay FD, so start at 1.
m_optimized_fd_mapping[0] = 0;
int new_length = 1;
for (size_t fd_idx = 1; fd_idx < old_length; ++fd_idx) {
const FunctionalDependency &fd = m_fds[fd_idx];
// See if we this FDs is useful, ie., can produce an item used in an
// ordering.
bool used_fd = false;
ItemHandle tail = m_items[fd.tail].canonical_item;
if (m_items[tail].used_asc || m_items[tail].used_desc ||
m_items[tail].used_in_grouping) {
used_fd = true;
} else if (fd.type == FunctionalDependency::EQUIVALENCE) {
ItemHandle head = m_items[fd.head[0]].canonical_item;
if (m_items[head].used_asc || m_items[head].used_desc ||
m_items[head].used_in_grouping) {
used_fd = true;
}
}
if (!used_fd) {
m_optimized_fd_mapping[fd_idx] = -1;
continue;
}
if (m_fds[fd_idx].always_active) {
// Defer these for now, by moving them to the end. We will need to keep
// them in the array so that we can apply them under FSM construction,
// but they should not get a FD bitmap, and thus also not priority for
// the lowest index. We could have used a separate array, but the m_fds
// array probably already has the memory.
m_optimized_fd_mapping[fd_idx] = -1;
m_fds.push_back(m_fds[fd_idx]);
} else {
m_optimized_fd_mapping[fd_idx] = new_length;
m_fds[new_length++] = m_fds[fd_idx];
}
}
// Now include the always-on FDs we deferred earlier.
for (size_t fd_idx = old_length; fd_idx < m_fds.size(); ++fd_idx) {
m_fds[new_length++] = m_fds[fd_idx];
}
m_fds.resize(new_length);
}
void LogicalOrderings::BuildEquivalenceClasses() {
for (size_t i = 0; i < m_items.size(); ++i) {
m_items[i].canonical_item = i;
}
// In the worst case, for n items, all equal, m FDs ordered optimally bad,
// this algorithm is O(nm) (all items shifted one step down each loop).
// In practice, it should be much better.
bool done_anything;
do {
done_anything = false;
for (const FunctionalDependency &fd : m_fds) {
if (fd.type != FunctionalDependency::EQUIVALENCE) {
continue;
}
ItemHandle left_item = fd.head[0];
ItemHandle right_item = fd.tail;
if (m_items[left_item].canonical_item ==
m_items[right_item].canonical_item) {
// Already fully applied.
continue;
}
// Merge the classes so that the lowest index always is the canonical one
// of its equivalence class.
ItemHandle canonical_item, duplicate_item;
if (m_items[right_item].canonical_item <
m_items[left_item].canonical_item) {
canonical_item = m_items[right_item].canonical_item;
duplicate_item = left_item;
} else {
canonical_item = m_items[left_item].canonical_item;
duplicate_item = right_item;
}
m_items[duplicate_item].canonical_item = canonical_item;
m_items[canonical_item].used_asc |= m_items[duplicate_item].used_asc;
m_items[canonical_item].used_desc |= m_items[duplicate_item].used_desc;
m_items[canonical_item].used_in_grouping |=
m_items[duplicate_item].used_in_grouping;
done_anything = true;
}
} while (done_anything);
}
// Put all groupings into a canonical form that we can compare them
// as orderings without further logic. (It needs to be on a form that
// does not change markedly after applying equivalences, and it needs
// to be deterministic, but apart from that, the order is pretty arbitrary.)
// We can only do this after BuildEquivalenceClasses().
void LogicalOrderings::RecanonicalizeGroupings() {
for (OrderingWithInfo &ordering : m_orderings) {
if (ordering.ordering.GetKind() == Ordering::Kind::kGroup) {
SortElements(ordering.ordering.GetElements());
}
}
}
// Window functions depend on both the function argument and on the PARTITION BY
// clause, so we need to add both to the functional dependency's head.
// The order of elements is arbitrary.
Bounds_checked_array<ItemHandle>
LogicalOrderings::CollectHeadForStaticWindowFunction(THD *thd,
ItemHandle argument_item,
Window *window) {
const PT_order_list *partition_by = window->effective_partition_by();
int partition_len = 0;
if (partition_by != nullptr) {
for (ORDER *order = partition_by->value.first; order != nullptr;
order = order->next) {
++partition_len;
}
}
auto head =
Bounds_checked_array<ItemHandle>::Alloc(thd->mem_root, partition_len + 1);
if (partition_by != nullptr) {
for (ORDER *order = partition_by->value.first; order != nullptr;
order = order->next) {
head[partition_len--] = GetHandle(*order->item);
}
}
head[0] = argument_item;
return head;
}
/**
Try to add new FDs from items that are not base items; e.g., if we have
an item (a + 1), we add {a} → (a + 1) (since addition is deterministic).
This can help reducing orderings that are on such derived items.
For simplicity, we only bother doing this for items that derive from a
single base field; i.e., from (a + b), we don't add {a,b} → (a + b)
even though we could. Also note that these are functional dependencies,
not equivalences; even though ORDER BY (a + 1) could be satisfied by an
ordering on (a) (barring overflow issues), this does not hold in general,
e.g. ORDER BY (-a) is _not_ satisfied by an ordering on (a), not to mention
ORDER BY (a*a). We do not have the framework in Item to understand which
functions are monotonous, so we do not attempt to create equivalences.
This is really the only the case where we can get transitive FDs that are not
equivalences. Since our approach does not apply FDs transitively without
adding the intermediate item (e.g., for {a} → b and {b} → c, we won't extend
(a) to (ac), only to (abc)), we extend any existing FDs here when needed.
*/
void LogicalOrderings::AddFDsFromComputedItems(THD *thd) {
int num_original_items = m_items.size();
int num_original_fds = m_fds.size();
for (int item_idx = 0; item_idx < num_original_items; ++item_idx) {
// We only care about items that are used in some ordering,
// not any used as base in FDs or the likes.
const ItemHandle canonical_idx = m_items[item_idx].canonical_item;
if (!m_items[canonical_idx].used_asc && !m_items[canonical_idx].used_desc &&
!m_items[canonical_idx].used_in_grouping) {
continue;
}
// We only want to look at items that are not already Item_field
// or aggregate functions (the latter are handled in
// AddFDsFromAggregateItems()), and that are generated from a single field.
// Some quick heuristics will eliminate most of these for us.
Item *item = m_items[item_idx].item;
const table_map used_tables = item->used_tables();
if (item->type() == Item::FIELD_ITEM || item->has_aggregation() ||
Overlaps(used_tables, PSEUDO_TABLE_BITS) ||
!IsSingleBitSet(used_tables)) {
continue;
}
// Window functions have much more state than just the parameter,
// so we cannot say that e.g. {a} → SUM(a) OVER (...), unless we
// know that the function is over the entire frame (unbounded).
//
// TODO(sgunders): We could also add FDs for window functions
// where could guarantee that the partition is only one row.
bool is_static_wf = false;
if (item->has_wf()) {
if (item->m_is_window_function &&
down_cast<Item_sum *>(item)->framing() &&
down_cast<Item_sum *>(item)->window()->static_aggregates()) {
is_static_wf = true;
} else {
continue;
}
}
Item_field *base_field = nullptr;
bool error =
WalkItem(item, enum_walk::POSTFIX, [&base_field](Item *sub_item) {
if (sub_item->type() == Item::FUNC_ITEM &&
down_cast<Item_func *>(sub_item)->functype() ==
Item_func::ROLLUP_GROUP_ITEM_FUNC) {
// Rollup items are nondeterministic, yet don't always set
// RAND_TABLE_BIT.
return true;
}
if (sub_item->type() == Item::FIELD_ITEM) {
if (base_field != nullptr &&
!base_field->eq(sub_item, /*binary_cmp=*/true)) {
// More than one field in use.
return true;
}
base_field = down_cast<Item_field *>(sub_item);
}
return false;
});
if (error || base_field == nullptr) {
// More than one field in use, or no fields in use
// (can happen even when used_tables is set, e.g. for
// an Item_view_ref to a constant).
continue;
}
if (!base_field->field->binary()) {
// Fields with collations can have equality (with no tiebreaker)
// even with fields that contain differing binary data.
// Thus, functions do not always preserve equality; a == b
// does not mean f(a) == f(b), and thus, the FD does not
// hold either.
continue;
}
ItemHandle head_item = GetHandle(base_field);
FunctionalDependency fd;
fd.type = FunctionalDependency::FD;
if (is_static_wf) {
fd.head = CollectHeadForStaticWindowFunction(
thd, head_item, down_cast<Item_sum *>(item)->window());
} else {
fd.head = Bounds_checked_array<ItemHandle>(&head_item, 1);
}
fd.tail = item_idx;
fd.always_active = true;
AddFunctionalDependency(thd, fd);
if (fd.head.size() == 1) {
// Extend existing FDs transitively (see function comment).
// E.g. if we have S → base, also add S → item.
for (int fd_idx = 0; fd_idx < num_original_fds; ++fd_idx) {
if (m_fds[fd_idx].type == FunctionalDependency::FD &&
m_fds[fd_idx].tail == head_item && m_fds[fd_idx].always_active) {
fd = m_fds[fd_idx];
fd.tail = item_idx;
AddFunctionalDependency(thd, fd);
}
}
}
}
}
/**
Try to add FDs from items that are constant by themselves, e.g. if someone
does ORDER BY 'x', add a new FD {} → 'x' so that the ORDER BY can be elided.
TODO(sgunders): This can potentially remove subqueries or other functions
that would throw errors if actually executed, potentially modifying
semantics. See if that is illegal, and thus, if we need to test-execute them
at least once somehow (ideally not during optimization).
*/
void LogicalOrderings::AddFDsFromConstItems(THD *thd) {
int num_original_items = m_items.size();
for (int item_idx = 0; item_idx < num_original_items; ++item_idx) {
// We only care about items that are used in some ordering,
// not any used as base in FDs or the likes.
const ItemHandle canonical_idx = m_items[item_idx].canonical_item;
if (!m_items[canonical_idx].used_asc && !m_items[canonical_idx].used_desc &&
!m_items[canonical_idx].used_in_grouping) {
continue;
}
if (m_items[item_idx].item->const_for_execution()) {
// Add {} → item.
FunctionalDependency fd;
fd.type = FunctionalDependency::FD;
fd.head = Bounds_checked_array<ItemHandle>();
fd.tail = item_idx;
fd.always_active = true;
AddFunctionalDependency(thd, fd);
}
}
}
void LogicalOrderings::AddFDsFromAggregateItems(THD *thd) {
// If ROLLUP is active, and we have nullable GROUP BY expressions, we could
// get two different NULL groups with different aggregates; one for the actual
// NULL value, and one for the rollup group. If so, these FDs no longer hold,
// and we cannot add them.
if (m_rollup) {
for (ItemHandle item : m_aggregate_head) {
if (m_items[item].item->is_nullable()) {
return;
}
}
}
int num_original_items = m_items.size();
for (int item_idx = 0; item_idx < num_original_items; ++item_idx) {
// We only care about items that are used in some ordering,
// not any used as base in FDs or the likes.
const ItemHandle canonical_idx = m_items[item_idx].canonical_item;
if (!m_items[canonical_idx].used_asc && !m_items[canonical_idx].used_desc &&
!m_items[canonical_idx].used_in_grouping) {
continue;
}
if (m_items[item_idx].item->has_aggregation() &&
!m_items[item_idx].item->has_wf()) {
// Add {all GROUP BY items} → item.
// Note that the head might be empty, for implicit grouping,
// which means all aggregate items are constant (there is only one row).
FunctionalDependency fd;
fd.type = FunctionalDependency::FD;
fd.head = m_aggregate_head;
fd.tail = item_idx;
fd.always_active = true;
AddFunctionalDependency(thd, fd);
}
}
}
void LogicalOrderings::FindElementsThatCanBeAddedByFDs() {
for (const FunctionalDependency &fd : m_fds) {
m_items[m_items[fd.tail].canonical_item].can_be_added_by_fd = true;
if (fd.type == FunctionalDependency::EQUIVALENCE) {
m_items[m_items[fd.head[0]].canonical_item].can_be_added_by_fd = true;
}
}
}
/**
Checks whether the given item is redundant given previous elements in
the ordering; ie., whether adding it will never change the ordering.
This could either be because it's a duplicate, or because it is implied
by functional dependencies. When this is applied to all elements in turn,
it is called “reducing” the ordering. [Neu04] claims that this operation
is not confluent, which is erroneous (their example is faulty, ignoring
that Simmen reduces from the back). [Neu04b] has modified the claim to
be that it is not confluent for _groupings_, which is correct.
We make no attempt at optimality.
If all_fds is true, we consider all functional dependencies, including those
that may not always be active; e.g. a FD a=b may come from a join, and thus
does not hold before the join is actually done, but we assume it holds anyway.
This is OK from order homogenization, which is concerned with making orderings
that will turn into the desired interesting ordering (e.g. for ORDER BY) only
after all joins have been done. It would not be OK if we were to use it for
merge joins somehow.
*/
bool LogicalOrderings::ImpliedByEarlierElements(ItemHandle item,
Ordering::Elements prefix,
bool all_fds) const {
// First, search for straight-up duplicates (ignoring ASC/DESC).
if (Contains(prefix, item)) {
return true;
}
// Check if this item is implied by any of the functional dependencies.
for (size_t fd_idx = 1; fd_idx < m_fds.size(); ++fd_idx) {
const FunctionalDependency &fd = m_fds[fd_idx];
if (!all_fds && !fd.always_active) {
continue;
}
if (fd.type == FunctionalDependency::FD) {
if (fd.tail != item) {
continue;
}
// Check if we have all the required head items.
bool all_found = true;
for (ItemHandle other_item : fd.head) {
if (!Contains(prefix, other_item)) {
all_found = false;
break;
}
}
if (all_found) {
return true;
}
} else {
// a = b implies that a → b and b → a, so we check for both of those.
assert(fd.type == FunctionalDependency::EQUIVALENCE);
assert(fd.head.size() == 1);
if (fd.tail == item && Contains(prefix, fd.head[0])) {
return true;
}
if (fd.head[0] == item && Contains(prefix, fd.tail)) {
return true;
}
}
}
return false;
}
/**
Do safe reduction on all orderings (some of them may get merged by
PruneUninterestingOrders() later), ie., remove all items that may be removed
using only FDs that always are active.
There's a problem in [Neu04] that is never adequately addressed; orderings are
only ever expanded, and then eventually compared against interesting orders.
But the interesting order itself is not necessarily extended, due to pruning.
For instance, if an index could yield (x,y) and we have {} → x, there's no way
we could get it to match the interesting order (y) even though they are
logically equivalent. For an even trickier case, imagine an index (x,y) and
an interesting order (y,z), with {} → x and y → z. For this to match, we'd
need to have a “super-order” (x,y,z) and infer that from both orderings.
Instead, we do a pre-step related to Simmen's “Test Ordering” procedure;
we reduce the orderings. In the example above, both will be reduced to (y),
and then match. This is mostly a band-aid around the problem; for instance,
it cannot deal with FDs that are not always active, and it does not deal
adequately with groupings (since reduction does not).
Note that this could make the empty ordering interesting after merging.
*/
void LogicalOrderings::PreReduceOrderings(THD *thd) {
for (OrderingWithInfo &ordering : m_orderings) {
OrderingElementsGuard tmp_guard(this, thd->mem_root);
Ordering reduced_ordering =
ReduceOrdering(ordering.ordering,
/*all_fds=*/false, tmp_guard.Get());
if (reduced_ordering.size() < ordering.ordering.size()) {
ordering.ordering = reduced_ordering.Clone(thd->mem_root);
}
}
}
/**
We don't currently have any operators that only group and do not sort
(e.g. hash grouping), so we always implement grouping by sorting.
This function makes that representation explicit -- for each grouping,
it will make sure there is at least one ordering representing that
grouping. This means we never need to “sort by a grouping”, which
would destroy ordering information that could be useful later.
As an example, take SELECT ... GROUP BY a, b ORDER BY a. This needs to
group first by {a,b} (assume we're using filesort, not an index),
then sort by (a). If we just represent the sort we're doing as going
directly to {a,b}, we can't elide the sort on (a). Instead, we create
a sort (a,b) (implicitly convertible to {a,b}), which makes the FSM
understand that we're _both_ sorted on (a,b) and grouped on {a,b},
and then also sorted on (a).
Any given grouping would be satisfied by lots of different orderings:
{a,b} could be (a,b), (b,a), (a DESC, b) etc.. We look through all
interesting orders that are a subset of our grouping, and if they are,
we extend them arbitrarily to complete the grouping. E.g., if our
grouping is {a,b,c,d} and the ordering (c DESC, b) is interesting,
we make a homogenized ordering (c DESC, b, a, d). This is roughly
equivalent to Simmen's “Cover Order” procedure. If we cannot make
such a cover, we simply make a new last-resort ordering (a,b,c,d).
We don't consider equivalences here; perhaps we should, at least
for at-end groupings.
*/
void LogicalOrderings::CreateOrderingsFromGroupings(THD *thd) {
OrderingElementsGuard tmp_guard(this, thd->mem_root);
Ordering::Elements &tmp = tmp_guard.Get();
int num_original_orderings = m_orderings.size();
for (int grouping_idx = 1; grouping_idx < num_original_orderings;
++grouping_idx) {
const Ordering &grouping = m_orderings[grouping_idx].ordering;
if (grouping.GetKind() != Ordering::Kind::kGroup ||
m_orderings[grouping_idx].type != OrderingWithInfo::INTERESTING) {
continue;
}
bool has_cover = false;
for (int ordering_idx = 1; ordering_idx < num_original_orderings;
++ordering_idx) {
const Ordering &ordering = m_orderings[ordering_idx].ordering;
if (ordering.GetKind() != Ordering::Kind::kOrder ||
m_orderings[ordering_idx].type != OrderingWithInfo::INTERESTING ||
ordering.size() > grouping.size()) {
continue;
}
bool can_cover =
all_of(ordering.GetElements().begin(), ordering.GetElements().end(),
[&grouping](const OrderElement &element) {
return Contains(grouping.GetElements(), element.item);
});
if (!can_cover) {
continue;
}
has_cover = true;
// On a full match, just note that we have a cover, don't make a new
// ordering. We assume both are free of duplicates.
if (ordering.size() == grouping.size()) {
continue;
}
for (size_t i = 0; i < ordering.size(); ++i) {
tmp[i] = ordering.GetElements()[i];
}
int len = ordering.size();
for (const OrderElement &element : grouping.GetElements()) {
if (!Contains(ordering.GetElements(), element.item)) {
tmp[len].item = element.item;
tmp[len].direction = ORDER_ASC; // Arbitrary.
++len;
}
}
assert(len == static_cast<int>(grouping.size()));
AddOrderingInternal(
thd, Ordering(tmp.prefix(len), Ordering::Kind::kOrder),
OrderingWithInfo::HOMOGENIZED, m_orderings[grouping_idx].used_at_end,
/*homogenize_tables=*/0);
}
// Make a fallback ordering if no cover was found.
if (!has_cover) {
for (size_t i = 0; i < grouping.size(); ++i) {
tmp[i].item = grouping.GetElements()[i].item;
tmp[i].direction = ORDER_ASC; // Arbitrary.
}
AddOrderingInternal(
thd, Ordering(tmp.prefix(grouping.size()), Ordering::Kind::kOrder),
OrderingWithInfo::HOMOGENIZED, m_orderings[grouping_idx].used_at_end,
/*homogenize_tables=*/0);
}