MySQL 8.4.2
Source Code Documentation
interesting_orders.h
Go to the documentation of this file.
1/* Copyright (c) 2021, 2024, Oracle and/or its affiliates.
2
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License, version 2.0,
5 as published by the Free Software Foundation.
6
7 This program is designed to work with certain software (including
8 but not limited to OpenSSL) that is licensed under separate terms,
9 as designated in a particular file or component or in included license
10 documentation. The authors of MySQL hereby grant you an additional
11 permission to link the program and your derivative works with the
12 separately licensed software that they have either included with
13 the program or referenced in the documentation.
14
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License, version 2.0, for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
23
24#ifndef SQL_JOIN_OPTIMIZER_INTERESTING_ORDERS_H
25#define SQL_JOIN_OPTIMIZER_INTERESTING_ORDERS_H
26
27/**
28 @file
29
30 Tracks which tuple streams follow which orders, and in particular whether
31 they follow interesting orders.
32
33 An interesting order (and/or grouping) is one that we might need to sort by
34 at some point during query execution (e.g. to satisfy an ORDER BY predicate);
35 if the rows already are produced in that order, for instance because we
36 scanned along the right index, we can skip the sort and get a lower cost.
37
38 We generally follow these papers:
39
40 [Neu04] Neumann and Moerkotte: “An efficient framework for order
41 optimization”
42 [Neu04b] Neumann and Moerkotte: “A Combined Framework for
43 Grouping and Order Optimization”
44
45 [Neu04b] is an updated version of [Neu04] that also deals with interesting
46 groupings but omits some details to make more space, so both are needed.
47 A combined and updated version of the same material is available in
48 Moerkotte's “Query compilers” PDF.
49
50 Some further details, like order homogenization, come from
51
52 [Sim96] Simmen et al: “Fundamental Techniques for Order Optimization”
53
54 All three papers deal with the issue of _logical_ orderings, where any
55 tuple stream may follow more than one order simultaneously, as inferred
56 through functional dependencies (FDs). For instance, if we have an ordering
57 (ab) but also an active FD {a} → c (c is uniquely determined by a,
58 for instance because a is a primary key in the same table as c), this means
59 we also implicitly follow the orders (acb) and (abc). In addition,
60 we trivially follow the orders (a), (ac) and (ab). However, note that we
61 do _not_ necessarily follow the order (cab).
62
63 Similarly, equivalences, such as WHERE conditions and joins, give rise
64 to a stronger form of FDs. If we have an ordering (ab) and the FD b = c,
65 we can be said to follow (ac), (acb) or (abc). The former would not be
66 inferable from {b} → c and {c} → b alone. Equivalences with constants
67 are perhaps even stronger, e.g. WHERE x=3 would give rise to {} → x,
68 which could extend (a) to (xa), (ax) or (x).
69
70 Neumann et al solve this by modelling which ordering we're following as a
71 state in a non-deterministic finite state machine (NFSM). By repeatedly
72 applying FDs (which become edges in the NFSM), we can build up all possible
73 orderings from a base (which can be either the empty ordering, ordering from
74 scanning along an index, or one produced by an explicit sort) and then
75 checking whether we are in a state matching the ordering we are interested
76 in. (There can be quite a bit of states, so we need a fair amount of pruning
77 to keep the count manageable, or else performance will suffer.) Of course,
78 since NFSMs are nondeterministic, a base ordering and a set of FDs can
79 necessarily put us in a number of states, so we need to convert the NFSM
80 to a DFSM (using the standard powerset construction for NFAs; see
81 ConvertNFSMToDFSM()). This means that the ordering state for an access path
82 is only a single integer, the DFSM state number. When we activate more FDs,
83 for instance because we apply joins, we will move throughout the DFSM into
84 more attractive states. By checking simple precomputed lookup tables,
85 we can quickly find whether a given DFSM state follows a given ordering.
86
87 The other kind of edges we follow are from the artificial starting state;
88 they represent setting a specific ordering (e.g. because we sort by that
89 ordering). This is set up in the NFSM and preserved in the DFSM.
90
91 The actual collection of FDs and interesting orders happen outside this
92 class, in the caller.
93
94 A weakness in the approach is that transitive FDs are not always followed
95 correctly. E.g., if we have an ordering (a), and FDs {a} → b and {b} → c,
96 we will create (ab) and (abc), but _not_ (ac). This is not a problem for
97 equivalences, though, and most of the FDs we collect are equivalences.
98 We do have some heuristics to produce a new FD {a} → c where it is relevant,
99 but they are not always effective.
100
101 Neumann and Moerkotte distinguish between “tested-for” (O_T) and
102 “producing” (O_P) orderings, where all orders are interesting but only
103 some can be produced by explicit operators, such as sorts. Our implementation
104 is exactly opposite; we allow every ordering to be produced (by means of
105 sort-ahead), but there are orders that can be produced (e.g. when scanning
106 an index) that are not interesting in themselves. Such orders can be
107 pruned away early if we can show they do not produce anything interesting.
108
109
110 The operations related to interesting orders, in particular the concept
111 of functional dependencies, are related to the ones we are doing when
112 checking ONLY_FULL_GROUP_BY legality in sql/aggregate_check.h. However,
113 there are some key differences as well:
114
115 - Orderings are lexical, while groupings are just a bag of attributes.
116 This increases the state space for orderings significantly; groupings
117 can add elements at will and just grow the set freely, while orderings
118 need more care. In particular, this means that groupings only need
119 FDs on the form S → x (where S is a set), while orderings also benefit
120 from those of the type x = y, which replace an element instead of
121 adding a new one.
122
123 - ONLY_FULL_GROUP_BY is for correctness of rejecting or accepting the
124 query, while interesting orders is just an optimization, so not
125 recognizing rare cases is more acceptable.
126
127 - ONLY_FULL_GROUP_BY testing only cares about the set of FDs that hold
128 at one specific point (GROUP BY testing, naturally), while interesting
129 orders must be tracked throughout the entire operator tree. In particular,
130 if using interesting orders for merge join, the status at nearly every
131 join is relevant. Also, performance matters much more.
132
133 Together, these mean that the code ends up being fairly different,
134 and some cases are recognized by ONLY_FULL_GROUP_BY but not by interesting
135 orders. (The actual FD collection happens in BuildInterestingOrders in
136 join_optimizer.cc; see the comment there for FD differences.)
137
138 A note about nomenclature: Like Neumann et al, we use the term “ordering”
139 (and “grouping”) instead of “order”, with the special exception of the
140 already-established term “interesting order”.
141 */
142
143#include "my_table_map.h"
145#include "sql/key_spec.h"
146#include "sql/mem_root_array.h"
147#include "sql/sql_array.h"
148
149#include <bitset>
150#include <sstream>
151#include <string>
152
153class LogicalOrderings;
154class Window;
155
156/**
157 Represents a (potentially interesting) ordering, rollup or (non-rollup)
158 grouping.
159*/
160class Ordering final {
161 friend bool operator==(const Ordering &a, const Ordering &b);
162
163 public:
164 /// This type hold the individual elements of the ordering.
166
167 /// The kind of ordering that an Ordering instance may represent.
168 enum class Kind : char {
169 /// An ordering with no elements. Such an ordering is not useful in itself,
170 /// but may appear as an intermediate result.
171 kEmpty,
172
173 /// Specific sequence of m_elements, and specific direction of each element.
174 /// Needed for e.g. ORDER BY.
175 kOrder,
176
177 /// Specific sequence of m_elements, but each element may be ordered in any
178 /// direction. Needed for ROLLUP:
179 kRollup,
180
181 /// Elements may appear in any sequence and may be ordered in any direction.
182 /// Needed for GROUP BY (with out ROLLUP), DISCTINCT, semi-join etc.
183 kGroup
184 };
185
186 Ordering() : m_kind{Kind::kEmpty} {}
187
188 Ordering(Elements elements, Kind kind) : m_elements{elements}, m_kind{kind} {
189 assert(Valid());
190 }
191
192 /// Copy constructor. Only defined explicitly to check Valid().
193 Ordering(const Ordering &other)
194 : m_elements{other.m_elements}, m_kind{other.m_kind} {
195 assert(Valid());
196 }
197
198 /// Assignment operator. Only defined explicitly to check Valid().
199 Ordering &operator=(const Ordering &other) {
200 assert(Valid());
201 m_kind = other.m_kind;
202 m_elements = other.m_elements;
203 return *this;
204 }
205
206 /// Make a copy of *this. Allocate new memory for m_elements from mem_root.
208 assert(Valid());
210 }
211
212 Kind GetKind() const {
213 assert(Valid());
214 return m_kind;
215 }
216
217 const Elements &GetElements() const {
218 assert(Valid());
219 return m_elements;
220 }
221
223 assert(Valid());
224 return m_elements;
225 }
226
227 size_t size() const { return m_elements.size(); }
228
229 /**
230 Remove duplicate entries, in-place.
231 */
232 void Deduplicate();
233
234 private:
235 /// The ordering terms.
237
238 /// The kind of this ordering.
240
241 /// @returns true iff *this passes a consistency check.
242 bool Valid() const;
243};
244
245/// Check if 'a' and 'b' has the same kind and contains the same elements.
246inline bool operator==(const Ordering &a, const Ordering &b) {
247 assert(a.Valid());
248 assert(b.Valid());
249 return a.m_kind == b.m_kind &&
252}
253
254inline bool operator!=(const Ordering &a, const Ordering &b) {
255 return !(a == b);
256}
257
259 enum {
260 // A special “empty” kind of edge in the FSM that signifies
261 // adding no functional dependency, ie., a state we can reach
262 // with no further effort. This can happen in two ways:
263 //
264 // 1. An ordering can drop its last element, ie.,
265 // if a tuple stream is ordered on (a,b,c), it is also
266 // ordered on (a,b).
267 // 2. An ordering can be converted to a grouping, i.e,
268 // if a tuple stream is ordered on (a,b,c), it is also
269 // grouped on {a,b,c}.
270 //
271 // head must be empty, tail must be 0. Often called ϵ.
272 // Must be the first in the edge list.
274
275 // A standard functional dependency {a} → b; if a tuple stream
276 // is ordered on all elements of a and this FD is applied,
277 // it is also ordered on (a,b). A typical example is if {a}
278 // is an unique key in a table, and b is a column of the
279 // same table. head can be empty.
281
282 // An equivalence a = b; implies a → b and b → a, but is
283 // stronger (e.g. if ordered on (a,c), there is also an
284 // ordering on (b,c), which wouldn't be true just from
285 // applying FDs individually). head must be a single element.
288
291
292 // Whether this functional dependency can always be applied, ie.,
293 // there is never a point during query processing where it does not hold.
294 //
295 // Examples of not-always-active FDs include join conditions;
296 // e.g. for t1.x = t2.x, it is not true before the join has actually
297 // happened (and t1.x won't be the same order as t2.x before that,
298 // and thus cannot be used in e.g. a merge join).
299 //
300 // However, FDs that stem from unique indexes are always true; e.g. if
301 // t1.x is a primary key, {t1.x} → t1.y will always be true, and we can
302 // always reduce t1.y from an order if t1.x is present earlier.
303 // Similarly, WHERE conditions that are applied on the base table
304 // (ie., it is not delayed due to outer joins) will always be true,
305 // if t1.x = 3, we can safely assume {} → t1.x holds even before
306 // joining in t1, so a sort on (t1.x, t2.y) can be satisfied just by
307 // sorting t2 on y.
308 //
309 // Always-active FDs are baked into the DFSM, so that we need to follow
310 // fewer arcs during query processing. They can also be used for reducing
311 // the final order (to get more efficient sorting), but we don't do it yet.
312 bool always_active = false;
313};
314
317
318 public:
319 explicit LogicalOrderings(THD *thd);
320
321 // Maps the Item to an opaque integer handle. Deduplicates items as we go,
322 // inserting new ones if needed.
324
325 Item *item(ItemHandle item) const { return m_items[item].item; }
326 int num_items() const { return m_items.size(); }
327
328 // These are only available before Build() has been called.
329
330 // Mark an interesting ordering (or grouping) as interesting,
331 // returning an index that can be given to SetOrder() later.
332 // Will deduplicate against previous entries; if not deduplicated
333 // away, a copy will be taken.
334 //
335 // Uninteresting orderings are those that can be produced by some
336 // operator (for instance, index scan) but are not interesting to
337 // test for. Orderings may be merged, pruned (if uninteresting)
338 // and moved around after Build(); see RemapOrderingIndex().
339 //
340 // If used_at_end is true, the ordering is assumed to be used only
341 // after all joins have happened, so all FDs are assumed to be
342 // active. This enables reducing the ordering more (which can in
343 // some cases help with better sortahead or the likes), but is not
344 // correct if the ordering wants to be used earlier on, e.g.
345 // in merge join or for semijoin duplicate removal. If it is false,
346 // then it is also only attempted homogenized onto the given set
347 // of tables (otherwise, it is ignored, and homogenization is over
348 // all tables).
349 //
350 // The empty ordering/grouping is always index 0.
351 int AddOrdering(THD *thd, Ordering order, bool interesting, bool used_at_end,
352 table_map homogenize_tables) {
353 return AddOrderingInternal(thd, order,
356 used_at_end, homogenize_tables);
357 }
358
359 // NOTE: Will include the empty ordering.
360 int num_orderings() const { return m_orderings.size(); }
361
362 const Ordering &ordering(int ordering_idx) const {
363 return m_orderings[ordering_idx].ordering;
364 }
365
366 bool ordering_is_relevant_for_sortahead(int ordering_idx) const {
367 return !m_orderings[ordering_idx].ordering.GetElements().empty() &&
368 m_orderings[ordering_idx].type != OrderingWithInfo::UNINTERESTING;
369 }
370
371 // Add a functional dependency that may be applied at some point
372 // during the query planning. Same guarantees as AddOrdering().
373 // The special “decay” FD is always index 0.
375
376 // NOTE: Will include the decay (epsilon) FD.
377 int num_fds() const { return m_fds.size(); }
378
379 // Set the list of GROUP BY expressions, if any. This is used as the
380 // head of the functional dependencies for all aggregate functions
381 // (which by definition are functionally dependent on the GROUP BY
382 // expressions, unless ROLLUP is active -- see below), and must be
383 // valid (ie., not freed or modified) until Build() has run.
384 //
385 // If none is set, and there are aggregates present in orderings,
386 // implicit aggregation is assumed (ie., all aggregate functions
387 // are constant).
389 m_aggregate_head = head;
390 }
391
392 // Set whether ROLLUP is active; if so, we can no longer assume that
393 // aggregate functions are functionally dependent on (nullable)
394 // GROUP BY expressions, as two NULLs may be for different reasons.
395 void SetRollup(bool rollup) { m_rollup = rollup; }
396
397 // Builds the actual FSMs; all information about orderings and FDs is locked,
398 // optimized and then the state machine is built. After this, you can no
399 // longer add new orderings or FDs, ie., you are moving into the actual
400 // planning phase.
401 //
402 // Build() may prune away orderings and FDs, and it may also add homogenized
403 // orderings, ie., orderings derived from given interesting orders but
404 // modified so that they only require a single table (but will become an
405 // actual interesting order later, after the FDs have been applied). These are
406 // usually at the end, but may also be deduplicated against uninteresting
407 // orders, which will then be marked as interesting.
408 void Build(THD *thd);
409
410 // These are only available after Build() has been called.
411 // They are stateless and used in the actual planning phase.
412
413 // Converts an index returned by AddOrdering() to one that can be given
414 // to SetOrder() or DoesFollowOrder(). They don't convert themselves
415 // since it's completely legitimate to iterate over all orderings using
416 // num_orderings() and orderings(), and those indexes should _not_ be
417 // remapped.
418 //
419 // If an ordering has been pruned away, will return zero (the empty ordering),
420 // which is a valid input to SetOrder().
421 int RemapOrderingIndex(int ordering_idx) const {
422 assert(m_built);
423 return m_optimized_ordering_mapping[ordering_idx];
424 }
425
426 using StateIndex = int;
427
428 StateIndex SetOrder(int ordering_idx) const {
429 assert(m_built);
430 return m_orderings[ordering_idx].state_idx;
431 }
432
433 // Get a bitmap representing the given functional dependency. The bitmap
434 // can be all-zero if the given FD is optimized away, or outside the range
435 // of the representable bits. The bitmaps may be ORed together, but are
436 // otherwise to be treated as opaque to the client.
439 int new_fd_idx = m_optimized_fd_mapping[fd_idx];
440 if (new_fd_idx >= 1 && new_fd_idx <= kMaxSupportedFDs) {
441 fd_set.set(new_fd_idx - 1);
442 }
443 return fd_set;
444 }
445
446 // For a given state, see what other (better) state we can move to given a
447 // set of active functional dependencies, e.g. if we are in state ((),a) and
448 // the FD a=b becomes active, we can set its bit (see GetFDSet()) in the FD
449 // mask and use that to move to the state ((),a,b,ab,ba). Note that “fds”
450 // should contain the entire set of active FDs, not just newly-applied ones.
451 // This is because “old” FDs can suddenly become relevant when new logical
452 // orderings are possible, and the DFSM is not always able to bake this in.
454
455 bool DoesFollowOrder(StateIndex state_idx, int ordering_idx) const {
456 assert(m_built);
457 if (ordering_idx == 0) {
458 return true;
459 }
460 if (ordering_idx >= kMaxSupportedOrderings) {
461 return false;
462 }
463 return m_dfsm_states[state_idx].follows_interesting_order.test(
464 ordering_idx);
465 }
466
467 // Whether "a" follows any interesting orders than "b" does not, or could
468 // do so in the future. If !MoreOrderedThan(a, b) && !MoreOrderedThan(b, a)
469 // the states are equal (they follow the same interesting orders, and could
470 // lead to the same interesting orders given the same FDs -- see below).
471 // It is possible to have MoreOrderedThan(a, b) && MoreOrderedThan(b, a), e.g.
472 // if they simply follow disjunct orders.
473 //
474 // This is used in the planner, when pruning access paths -- an AP A can be
475 // kept even if it has higher cost than AP B, if it follows orders that B does
476 // not. Why is it enough to check interesting orders -- must we also not check
477 // uninteresting orders, since they could lead to new interesting orders
478 // later? This is because in the planner, two states will only ever be
479 // compared if the same functional dependencies have been applied to both
480 // sides:
481 //
482 // The set of logical orders, and thus the state, is uniquely determined
483 // by the initial ordering and applied FDs. Thus, if A has _uninteresting_
484 // orders that B does not, the initial ordering must have differed -- but the
485 // initial states only contain (and thus differ in) interesting orders.
486 // Thus, the additional uninteresting orders must have been caused by
487 // additional interesting orders (that do not go away), so testing the
488 // interesting ones really suffices in planner context.
489 //
490 // Note that this also means that in planner context, !MoreOrderedThan(a, b)
491 // && !MoreOrderedThan(b, a) implies that a == b.
493 StateIndex a_idx, StateIndex b_idx,
494 std::bitset<kMaxSupportedOrderings> ignored_orderings) const {
495 assert(m_built);
496 std::bitset<kMaxSupportedOrderings> a =
497 m_dfsm_states[a_idx].follows_interesting_order & ~ignored_orderings;
498 std::bitset<kMaxSupportedOrderings> b =
499 m_dfsm_states[b_idx].follows_interesting_order & ~ignored_orderings;
500 std::bitset<kMaxSupportedOrderings> future_a =
501 m_dfsm_states[a_idx].can_reach_interesting_order & ~ignored_orderings;
502 std::bitset<kMaxSupportedOrderings> future_b =
503 m_dfsm_states[b_idx].can_reach_interesting_order & ~ignored_orderings;
504 return (a & b) != a || (future_a & future_b) != future_a;
505 }
506
507 // See comment in .cc file.
509 Ordering::Elements tmp) const;
510
511 private:
512 struct NFSMState;
513 class OrderWithElementInserted;
514
515 bool m_built = false;
516
517 struct ItemInfo {
518 // Used to translate Item * to ItemHandle and back.
520
521 // Points to the head of this item's equivalence class. (If the item
522 // is not equivalent to anything, points to itself.) The equivalence class
523 // is defined by EQUIVALENCE FDs, transitively, and the head is the one with
524 // the lowest index. So if we have FDs a = b and b = c, all three {a,b,c}
525 // will point to a here. This is useful for pruning and homogenization;
526 // if two elements have the same equivalence class (ie., the same canonical
527 // item), they could become equivalent after applying FDs. See also
528 // m_can_be_added_by_fd, which deals with non-EQUIVALENCE FDs.
529 //
530 // Set by BuildEquivalenceClasses().
532
533 // Whether the given item (after canonicalization by means of
534 // m_canonical_item[]) shows up as the tail of any functional dependency.
535 //
536 // Set by FindElementsThatCanBeAddedByFDs();
537 bool can_be_added_by_fd = false;
538
539 // Whether the given item ever shows up in orderings as ASC or DESC,
540 // respectively. Used to see whether adding the item in that direction
541 // is worthwhile or not. Note that this is propagated through equivalences,
542 // so if a = b and any ordering contains b DESC and a is the head of that
543 // equivalence class, then a is also marked as used_desc = true.
544 bool used_asc = false;
545 bool used_desc = false;
546 bool used_in_grouping = false;
547 };
548 // All items we have seen in use (in orderings or FDs), deduplicated
549 // and indexed by ItemHandle.
551
552 // Head for all FDs generated for aggregate functions.
553 // See SetHeadForAggregates().
555
556 // Whether rollup is active; if so, we need to take care not to create
557 // FDs for aggregates in some cases. See SetHeadForAggregates() and
558 // SetRollup().
559 bool m_rollup = false;
560
561 struct NFSMEdge {
562 // Which FD is required to follow this edge. Index into m_fd, with one
563 // exception; from the initial state (0), we have constructor edges for
564 // setting a specific order without following an FD. Such edges have
565 // required_fd_idx = INT_MIN + order_idx, ie., they are negative.
567
568 // Destination state (index into m_states).
570
572 const LogicalOrderings *orderings) const {
573 return &orderings->m_fds[required_fd_idx];
574 }
575 const NFSMState *state(const LogicalOrderings *orderings) const {
576 return &orderings->m_states[state_idx];
577 }
578 };
579
580 friend bool operator==(const NFSMEdge &a, const NFSMEdge &b);
581 friend bool operator!=(const NFSMEdge &a, const NFSMEdge &b);
582
583 struct NFSMState {
587 int satisfied_ordering_idx; // Only for type == INTERESTING.
588
589 // Indexed by ordering.
590 std::bitset<kMaxSupportedOrderings> can_reach_interesting_order{0};
591
592 // Used during traversal, to keep track of which states we have
593 // already seen (for fast deduplication). We use the standard trick
594 // of using a generational counter instead of a bool, so that we don't
595 // have to clear it every time; we can just increase the generation
596 // and treat everything with lower/different “seen” as unseen.
597 int seen = 0;
598 };
599 struct DFSMState {
600 Mem_root_array<int> outgoing_edges; // Index into dfsm_edges.
601 Mem_root_array<int> nfsm_states; // Index into states.
602
603 // Structures derived from the above, but in forms for faster access.
604
605 // Indexed by FD.
607
608 // Indexed by ordering.
609 std::bitset<kMaxSupportedOrderings> follows_interesting_order{0};
610
611 // Interesting orders that this state can eventually reach,
612 // given that all FDs are applied (a superset of follows_interesting_order).
613 // We track this instead of the producing orders (e.g. which homogenized
614 // order are we following), because it allows for more access paths to
615 // compare equal. See also OrderingWithInfo::Type::HOMOGENIZED.
616 std::bitset<kMaxSupportedOrderings> can_reach_interesting_order{0};
617
618 // Whether applying the given functional dependency will take us to a
619 // different state from this one. Used to quickly intersect with the
620 // available FDs to find out what we can apply.
622 };
623
624 struct DFSMEdge {
627
629 const LogicalOrderings *orderings) const {
630 return &orderings->m_fds[required_fd_idx];
631 }
632 const DFSMState *state(const LogicalOrderings *orderings) const {
633 return &orderings->m_dfsm_states[state_idx];
634 }
635 };
636
639
640 // Status of the ordering. Note that types with higher indexes dominate
641 // lower, ie., two orderings can be collapsed into the one with the higher
642 // type index if they are otherwise equal.
643 enum Type {
644 // An ordering that is interesting in its own right,
645 // e.g. because it is given to ORDER BY.
647
648 // An ordering that is derived from an interesting order, but refers to
649 // one table only (or conceptually, a subset of tables -- but we don't
650 // support that in this implementation). Guaranteed to reach some
651 // interesting order at some point, but we don't track it as interesting
652 // in the FSM states. This means that these orderings don't get state bits
653 // in follows_interesting_order for themselves, but they will always have
654 // one or more interesting orders in can_reach_interesting_order.
655 // This helps us collapse access paths more efficiently; if we have
656 // an interesting order t3.x and create homogenized orderings t1.x
657 // and t2.x (due to some equality with t3.x), an access path following one
658 // isn't better than an access path following the other. They will lead
659 // to the same given the same FDs anyway (see MoreOrderedThan()), and
660 // thus are equally good.
662
663 // An ordering that is just added because it is easy to produce;
664 // e.g. because it is produced by scanning along an index. Such orderings
665 // can be shortened or pruned away entirely (in
666 // PruneUninterestingOrders())
667 // unless we find that they may lead to an interesting order.
668 UNINTERESTING = 0
670
672
673 // Only used if used_at_end = false (see AddOrdering()).
675
676 // Which initial state to use for this ordering (in SetOrder()).
678 };
679
681
682 // The longest ordering in m_orderings.
684
686
687 // NFSM. 0 is the initial state, all others are found by following edges.
689
690 // DFSM. 0 is the initial state, all others are found by following edges.
693
694 // After PruneUninterestingOrders has run, maps from the old indexes to the
695 // new indexes.
697
698 // After PruneFDs() has run, maps from the old indexes to the new indexes.
700
701 /// We may potentially use a lot of Ordering::Elements objects, with short and
702 /// non-overlapping life times. Therefore we have a pool
703 /// to allow reuse and avoid allocating from MEM_ROOT each time.
705
706 // The canonical order for two items in a grouping
707 // (after BuildEquivalenceClasses() has run; enforced by
708 // RecanonicalizeGroupings()). The reason why we sort by
709 // canonical_item first is so that switching out one element
710 // with an equivalent one (ie., applying an EQUIVALENCE
711 // functional dependency) does not change the order of the
712 // elements in the grouing, which could give false negatives
713 // in CouldBecomeInterestingOrdering().
715 if (m_items[a].canonical_item != m_items[b].canonical_item)
716 return m_items[a].canonical_item < m_items[b].canonical_item;
717 return a < b;
718 }
719
720 inline bool ItemBeforeInGroup(const OrderElement &a,
721 const OrderElement &b) const {
722 return ItemHandleBeforeInGroup(a.item, b.item);
723 }
724
725 // Helper for AddOrdering().
727 bool used_at_end, table_map homogenize_tables);
728
729 // See comment in .cc file.
730 void PruneUninterestingOrders(THD *thd);
731
732 // See comment in .cc file.
733 void PruneFDs(THD *thd);
734
735 // See comment in .cc file.
737 bool all_fds) const;
738
739 // Populates ItemInfo::canonical_item.
741
742 // See comment in .cc file.
744
745 // See comment in .cc file.
746 void AddFDsFromComputedItems(THD *thd);
747
748 // See comment in .cc file.
749 void AddFDsFromAggregateItems(THD *thd);
750
751 // See comment in .cc file.
753 THD *thd, ItemHandle argument_item, Window *window);
754
755 // See comment in .cc file.
756 void AddFDsFromConstItems(THD *thd);
757
758 // Populates ItemInfo::can_be_added_by_fd.
760
761 void PreReduceOrderings(THD *thd);
766 THD *thd, const Ordering &reduced_ordering, bool used_at_end,
767 int table_idx,
768 Bounds_checked_array<std::pair<ItemHandle, ItemHandle>>
769 reverse_canonical);
770
771 /// Sort the elements so that a will appear before b if
772 /// ItemBeforeInGroup(a,b)==true.
773 void SortElements(Ordering::Elements elements) const;
774
775 // See comment in .cc file.
777
778 void BuildNFSM(THD *thd);
779 void AddRollupFromOrder(THD *thd, int state_idx, const Ordering &ordering);
780 void AddGroupingFromOrder(THD *thd, int state_idx, const Ordering &ordering);
781 void AddGroupingFromRollup(THD *thd, int state_idx, const Ordering &ordering);
782 void TryAddingOrderWithElementInserted(THD *thd, int state_idx, int fd_idx,
783 Ordering old_ordering,
784 size_t start_point,
785 ItemHandle item_to_add,
786 enum_order direction);
787 void PruneNFSM(THD *thd);
788 bool AlwaysActiveFD(int fd_idx);
789 void FinalizeDFSMState(THD *thd, int state_idx);
791 int *generation, int extra_allowed_fd_idx);
792 void ConvertNFSMToDFSM(THD *thd);
793
794 // Populates state_idx for every ordering in m_ordering.
796
797 // If a state with the given ordering already exists (artificial or not),
798 // returns its index. Otherwise, adds an artificial state with the given
799 // order and returns its index.
800 int AddArtificialState(THD *thd, const Ordering &ordering);
801
802 // Add an edge from state_idx to an state with the given ordering; if there is
803 // no such state, adds an artificial state with it (taking a copy, so does not
804 // need to take ownership).
805 void AddEdge(THD *thd, int state_idx, int required_fd_idx,
806 const Ordering &ordering);
807
808 // Returns true if the given (non-DECAY) functional dependency applies to the
809 // given ordering, and the index of the element from which the FD is active
810 // (ie., the last element that was part of the head). One can start inserting
811 // the tail element at any point _after_ this index; if it is an EQUIVALENCE
812 // FD, one can instead choose to replace the element at start_point entirely.
814 const Ordering &ordering,
815 int *start_point) const;
816
817 /**
818 Fetch an Ordering::Elements object with size()==m_longest_ordering.
819 Get it from m_elements_pool if that is non-empty, otherwise allocate
820 from mem_root.
821 */
823 if (m_elements_pool.empty()) {
825 } else {
827 m_elements_pool.pop_back();
829 }
830 }
831
832 /**
833 Return an Ordering::Elements object with size()==m_longest_ordering
834 to m_elements_pool.
835 */
837 // Overwrite the array with garbage, so that we have a better chance
838 // of detecting it if we by mistake access it afterwards.
839 TRASH(elements.data(), m_longest_ordering * sizeof(elements.data()[0]));
840 m_elements_pool.push_back(elements.data());
841 }
842 // Used for optimizer trace.
843
844 std::string PrintOrdering(const Ordering &ordering) const;
846 bool html) const;
847 void PrintFunctionalDependencies(std::ostream *trace);
848 void PrintInterestingOrders(std::ostream *trace);
849 void PrintNFSMDottyGraph(std::ostream *trace) const;
850 void PrintDFSMDottyGraph(std::ostream *trace) const;
851};
852
855 return a.required_fd_idx == b.required_fd_idx && a.state_idx == b.state_idx;
856}
857
860 return !(a == b);
861}
862
863#endif // SQL_JOIN_OPTIMIZER_INTERESTING_ORDERS_H
Element_type * data()
Definition: sql_array.h:116
static Bounds_checked_array Alloc(MEM_ROOT *mem_root, size_t size)
Definition: sql_array.h:70
const_iterator cbegin() const
Returns a pointer to the first element in the array.
Definition: sql_array.h:144
size_t size() const
Definition: sql_array.h:154
Bounds_checked_array Clone(MEM_ROOT *mem_root) const
Make a copy of '*this'. Allocate memory for m_array on 'mem_root'.
Definition: sql_array.h:75
const_iterator cend() const
Returns a pointer to the past-the-end element in the array.
Definition: sql_array.h:146
Base class that is used to represent any kind of expression in a relational query.
Definition: item.h:936
Definition: interesting_orders.h:315
void SetHeadForAggregates(Bounds_checked_array< ItemHandle > head)
Definition: interesting_orders.h:388
void AddRollupFromOrder(THD *thd, int state_idx, const Ordering &ordering)
Definition: interesting_orders.cc:1705
void AddEdge(THD *thd, int state_idx, int required_fd_idx, const Ordering &ordering)
Definition: interesting_orders.cc:1301
bool ItemHandleBeforeInGroup(ItemHandle a, ItemHandle b) const
Definition: interesting_orders.h:714
void CreateOrderingsFromGroupings(THD *thd)
We don't currently have any operators that only group and do not sort (e.g.
Definition: interesting_orders.cc:934
void AddFDsFromComputedItems(THD *thd)
Try to add new FDs from items that are not base items; e.g., if we have an item (a + 1),...
Definition: interesting_orders.cc:624
Mem_root_array< OrderingWithInfo > m_orderings
Definition: interesting_orders.h:680
bool ImpliedByEarlierElements(ItemHandle item, Ordering::Elements prefix, bool all_fds) const
Checks whether the given item is redundant given previous elements in the ordering; ie....
Definition: interesting_orders.cc:827
Bounds_checked_array< int > m_optimized_fd_mapping
Definition: interesting_orders.h:699
StateIndex SetOrder(int ordering_idx) const
Definition: interesting_orders.h:428
int num_orderings() const
Definition: interesting_orders.h:360
bool DoesFollowOrder(StateIndex state_idx, int ordering_idx) const
Definition: interesting_orders.h:455
bool m_rollup
Definition: interesting_orders.h:559
int m_longest_ordering
Definition: interesting_orders.h:683
Mem_root_array< DFSMState > m_dfsm_states
Definition: interesting_orders.h:691
bool m_built
Definition: interesting_orders.h:515
void AddHomogenizedOrderingIfPossible(THD *thd, const Ordering &reduced_ordering, bool used_at_end, int table_idx, Bounds_checked_array< std::pair< ItemHandle, ItemHandle > > reverse_canonical)
Helper function for CreateHomogenizedOrderings().
Definition: interesting_orders.cc:1112
friend bool operator==(const NFSMEdge &a, const NFSMEdge &b)
Definition: interesting_orders.h:853
std::string PrintOrdering(const Ordering &ordering) const
Definition: interesting_orders.cc:2126
Ordering ReduceOrdering(Ordering ordering, bool all_fds, Ordering::Elements tmp) const
Remove redundant elements using the functional dependencies that we have, to give a more canonical fo...
Definition: interesting_orders.cc:1095
void PrintFunctionalDependencies(std::ostream *trace)
Definition: interesting_orders.cc:2179
int RemapOrderingIndex(int ordering_idx) const
Definition: interesting_orders.h:421
void FinalizeDFSMState(THD *thd, int state_idx)
Definition: interesting_orders.cc:1901
void AddGroupingFromRollup(THD *thd, int state_idx, const Ordering &ordering)
Definition: interesting_orders.cc:1685
void PrintDFSMDottyGraph(std::ostream *trace) const
Definition: interesting_orders.cc:2277
friend bool operator!=(const NFSMEdge &a, const NFSMEdge &b)
Definition: interesting_orders.h:858
Mem_root_array< OrderElement * > m_elements_pool
We may potentially use a lot of Ordering::Elements objects, with short and non-overlapping life times...
Definition: interesting_orders.h:704
int num_items() const
Definition: interesting_orders.h:326
bool ordering_is_relevant_for_sortahead(int ordering_idx) const
Definition: interesting_orders.h:366
void PreReduceOrderings(THD *thd)
Do safe reduction on all orderings (some of them may get merged by PruneUninterestingOrders() later),...
Definition: interesting_orders.cc:894
void SetRollup(bool rollup)
Definition: interesting_orders.h:395
void CreateHomogenizedOrderings(THD *thd)
For each interesting ordering, see if we can homogenize it onto each table.
Definition: interesting_orders.cc:1022
Mem_root_array< NFSMState > m_states
Definition: interesting_orders.h:688
void SortElements(Ordering::Elements elements) const
Sort the elements so that a will appear before b if ItemBeforeInGroup(a,b)==true.
Definition: interesting_orders.cc:1178
int AddOrderingInternal(THD *thd, Ordering order, OrderingWithInfo::Type type, bool used_at_end, table_map homogenize_tables)
Definition: interesting_orders.cc:214
void AddFDsFromConstItems(THD *thd)
Try to add FDs from items that are constant by themselves, e.g.
Definition: interesting_orders.cc:738
int AddFunctionalDependency(THD *thd, FunctionalDependency fd)
Definition: interesting_orders.cc:269
bool FunctionalDependencyApplies(const FunctionalDependency &fd, const Ordering &ordering, int *start_point) const
Definition: interesting_orders.cc:1319
Mem_root_array< DFSMEdge > m_dfsm_edges
Definition: interesting_orders.h:692
void ReturnElements(Ordering::Elements elements)
Return an Ordering::Elements object with size()==m_longest_ordering to m_elements_pool.
Definition: interesting_orders.h:836
bool MoreOrderedThan(StateIndex a_idx, StateIndex b_idx, std::bitset< kMaxSupportedOrderings > ignored_orderings) const
Definition: interesting_orders.h:492
bool AlwaysActiveFD(int fd_idx)
Definition: interesting_orders.cc:1896
void BuildNFSM(THD *thd)
Definition: interesting_orders.cc:1478
void PrintInterestingOrders(std::ostream *trace)
Definition: interesting_orders.cc:2196
void BuildEquivalenceClasses()
Definition: interesting_orders.cc:521
int AddArtificialState(THD *thd, const Ordering &ordering)
Definition: interesting_orders.cc:1285
int StateIndex
Definition: interesting_orders.h:426
void PruneNFSM(THD *thd)
Try to prune away irrelevant nodes from the NFSM; it is worth spending some time on this,...
Definition: interesting_orders.cc:1765
Item * item(ItemHandle item) const
Definition: interesting_orders.h:325
void PrintNFSMDottyGraph(std::ostream *trace) const
Definition: interesting_orders.cc:2243
const Ordering & ordering(int ordering_idx) const
Definition: interesting_orders.h:362
void FindElementsThatCanBeAddedByFDs()
Definition: interesting_orders.cc:799
StateIndex ApplyFDs(StateIndex state_idx, FunctionalDependencySet fds) const
Definition: interesting_orders.cc:362
Bounds_checked_array< int > m_optimized_ordering_mapping
Definition: interesting_orders.h:696
int AddOrdering(THD *thd, Ordering order, bool interesting, bool used_at_end, table_map homogenize_tables)
Definition: interesting_orders.h:351
Ordering::Elements RetrieveElements(MEM_ROOT *mem_root)
Fetch an Ordering::Elements object with size()==m_longest_ordering.
Definition: interesting_orders.h:822
void ExpandThroughAlwaysActiveFDs(Mem_root_array< int > *nfsm_states, int *generation, int extra_allowed_fd_idx)
Definition: interesting_orders.cc:1918
void PruneFDs(THD *thd)
Definition: interesting_orders.cc:452
void PruneUninterestingOrders(THD *thd)
Try to get rid of uninteresting orders, possibly by discarding irrelevant suffixes and merging them w...
Definition: interesting_orders.cc:394
void AddFDsFromAggregateItems(THD *thd)
Definition: interesting_orders.cc:761
Bounds_checked_array< ItemHandle > CollectHeadForStaticWindowFunction(THD *thd, ItemHandle argument_item, Window *window)
Definition: interesting_orders.cc:583
Mem_root_array< ItemInfo > m_items
Definition: interesting_orders.h:550
ItemHandle GetHandle(Item *item)
Definition: interesting_orders.cc:1189
void FindInitialStatesForOrdering()
Definition: interesting_orders.cc:2114
void AddGroupingFromOrder(THD *thd, int state_idx, const Ordering &ordering)
Definition: interesting_orders.cc:1662
LogicalOrderings(THD *thd)
Definition: interesting_orders.cc:192
Mem_root_array< FunctionalDependency > m_fds
Definition: interesting_orders.h:685
void ConvertNFSMToDFSM(THD *thd)
From the NFSM, convert an equivalent DFSM.
Definition: interesting_orders.cc:1962
Bounds_checked_array< ItemHandle > m_aggregate_head
Definition: interesting_orders.h:554
void TryAddingOrderWithElementInserted(THD *thd, int state_idx, int fd_idx, Ordering old_ordering, size_t start_point, ItemHandle item_to_add, enum_order direction)
FunctionalDependencySet GetFDSet(int fd_idx) const
Definition: interesting_orders.h:437
void RecanonicalizeGroupings()
Definition: interesting_orders.cc:571
void Build(THD *thd)
Definition: interesting_orders.cc:300
std::string PrintFunctionalDependency(const FunctionalDependency &fd, bool html) const
Definition: interesting_orders.cc:2146
void CreateOrderingsFromRollups(THD *thd)
bool ItemBeforeInGroup(const OrderElement &a, const OrderElement &b) const
Definition: interesting_orders.h:720
bool CouldBecomeInterestingOrdering(const Ordering &ordering) const
For a given ordering, check whether it ever has the hope of becoming an interesting ordering.
Definition: interesting_orders.cc:1227
int num_fds() const
Definition: interesting_orders.h:377
A typesafe replacement for DYNAMIC_ARRAY.
Definition: mem_root_array.h:426
A scope-guard class for allocating an Ordering::Elements instance which is automatically returned to ...
Definition: interesting_orders.cc:68
Represents a (potentially interesting) ordering, rollup or (non-rollup) grouping.
Definition: interesting_orders.h:160
Elements & GetElements()
Definition: interesting_orders.h:222
size_t size() const
Definition: interesting_orders.h:227
Kind
The kind of ordering that an Ordering instance may represent.
Definition: interesting_orders.h:168
@ kOrder
Specific sequence of m_elements, and specific direction of each element.
@ kGroup
Elements may appear in any sequence and may be ordered in any direction.
@ kRollup
Specific sequence of m_elements, but each element may be ordered in any direction.
@ kEmpty
An ordering with no elements.
Ordering & operator=(const Ordering &other)
Assignment operator. Only defined explicitly to check Valid().
Definition: interesting_orders.h:199
Kind GetKind() const
Definition: interesting_orders.h:212
Ordering()
Definition: interesting_orders.h:186
Ordering(Elements elements, Kind kind)
Definition: interesting_orders.h:188
void Deduplicate()
Remove duplicate entries, in-place.
Definition: interesting_orders.cc:156
Bounds_checked_array< OrderElement > Elements
This type hold the individual elements of the ordering.
Definition: interesting_orders.h:165
Kind m_kind
The kind of this ordering.
Definition: interesting_orders.h:239
Ordering Clone(MEM_ROOT *mem_root) const
Make a copy of *this. Allocate new memory for m_elements from mem_root.
Definition: interesting_orders.h:207
Elements m_elements
The ordering terms.
Definition: interesting_orders.h:236
friend bool operator==(const Ordering &a, const Ordering &b)
Check if 'a' and 'b' has the same kind and contains the same elements.
Definition: interesting_orders.h:246
Ordering(const Ordering &other)
Copy constructor. Only defined explicitly to check Valid().
Definition: interesting_orders.h:193
bool Valid() const
Definition: interesting_orders.cc:167
const Elements & GetElements() const
Definition: interesting_orders.h:217
For each client connection we create a separate thread with THD serving as a thread/connection descri...
Definition: sql_lexer_thd.h:36
Represents the (explicit) window of a SQL 2003 section 7.11 <window clause>, or the implicit (inlined...
Definition: window.h:110
static MEM_ROOT mem_root
Definition: client_plugin.cc:114
static bool equal(const Item *i1, const Item *i2, const Field *f2)
Definition: sql_select.cc:3860
bool operator!=(const Ordering &a, const Ordering &b)
Definition: interesting_orders.h:254
bool operator==(const Ordering &a, const Ordering &b)
Check if 'a' and 'b' has the same kind and contains the same elements.
Definition: interesting_orders.h:246
std::bitset< kMaxSupportedFDs > FunctionalDependencySet
Definition: interesting_orders_defs.h:63
static constexpr int kMaxSupportedFDs
Definition: interesting_orders_defs.h:62
static constexpr int kMaxSupportedOrderings
Definition: interesting_orders_defs.h:65
int ItemHandle
Definition: interesting_orders_defs.h:39
enum_order
Definition: key_spec.h:65
void TRASH(void *ptr, size_t length)
Put bad content in memory to be sure it will segfault if dereferenced.
Definition: memory_debugging.h:71
uint64_t table_map
Definition: my_table_map.h:30
mutable_buffer buffer(void *p, size_t n) noexcept
Definition: buffer.h:418
required string type
Definition: replication_group_member_actions.proto:34
Definition: interesting_orders.h:258
ItemHandle tail
Definition: interesting_orders.h:290
enum FunctionalDependency::@109 type
bool always_active
Definition: interesting_orders.h:312
Bounds_checked_array< ItemHandle > head
Definition: interesting_orders.h:289
@ FD
Definition: interesting_orders.h:280
@ DECAY
Definition: interesting_orders.h:273
@ EQUIVALENCE
Definition: interesting_orders.h:286
Definition: interesting_orders.h:624
int state_idx
Definition: interesting_orders.h:626
int required_fd_idx
Definition: interesting_orders.h:625
const DFSMState * state(const LogicalOrderings *orderings) const
Definition: interesting_orders.h:632
const FunctionalDependency * required_fd(const LogicalOrderings *orderings) const
Definition: interesting_orders.h:628
Definition: interesting_orders.h:599
FunctionalDependencySet can_use_fd
Definition: interesting_orders.h:621
Mem_root_array< int > nfsm_states
Definition: interesting_orders.h:601
std::bitset< kMaxSupportedOrderings > follows_interesting_order
Definition: interesting_orders.h:609
Mem_root_array< int > outgoing_edges
Definition: interesting_orders.h:600
std::bitset< kMaxSupportedOrderings > can_reach_interesting_order
Definition: interesting_orders.h:616
Bounds_checked_array< int > next_state
Definition: interesting_orders.h:606
Definition: interesting_orders.h:517
bool used_desc
Definition: interesting_orders.h:545
bool used_in_grouping
Definition: interesting_orders.h:546
ItemHandle canonical_item
Definition: interesting_orders.h:531
bool can_be_added_by_fd
Definition: interesting_orders.h:537
bool used_asc
Definition: interesting_orders.h:544
Item * item
Definition: interesting_orders.h:519
Definition: interesting_orders.h:561
const NFSMState * state(const LogicalOrderings *orderings) const
Definition: interesting_orders.h:575
int required_fd_idx
Definition: interesting_orders.h:566
const FunctionalDependency * required_fd(const LogicalOrderings *orderings) const
Definition: interesting_orders.h:571
int state_idx
Definition: interesting_orders.h:569
Definition: interesting_orders.h:583
enum LogicalOrderings::NFSMState::@110 type
Mem_root_array< NFSMEdge > outgoing_edges
Definition: interesting_orders.h:585
std::bitset< kMaxSupportedOrderings > can_reach_interesting_order
Definition: interesting_orders.h:590
int satisfied_ordering_idx
Definition: interesting_orders.h:587
int seen
Definition: interesting_orders.h:597
Ordering satisfied_ordering
Definition: interesting_orders.h:586
@ ARTIFICIAL
Definition: interesting_orders.h:584
@ DELETED
Definition: interesting_orders.h:584
@ INTERESTING
Definition: interesting_orders.h:584
Definition: interesting_orders.h:637
StateIndex state_idx
Definition: interesting_orders.h:677
Ordering ordering
Definition: interesting_orders.h:638
bool used_at_end
Definition: interesting_orders.h:671
Type
Definition: interesting_orders.h:643
@ UNINTERESTING
Definition: interesting_orders.h:668
@ INTERESTING
Definition: interesting_orders.h:646
@ HOMOGENIZED
Definition: interesting_orders.h:661
enum LogicalOrderings::OrderingWithInfo::Type type
table_map homogenize_tables
Definition: interesting_orders.h:674
The MEM_ROOT is a simple arena, where allocations are carved out of larger blocks.
Definition: my_alloc.h:83
Definition: interesting_orders_defs.h:44
ItemHandle item
Definition: interesting_orders_defs.h:45