MySQL 9.7.0
Source Code Documentation
make_join_hypergraph.h
Go to the documentation of this file.
1/* Copyright (c) 2020, 2026, 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_MAKE_JOIN_HYPERGRAPH
25#define SQL_JOIN_OPTIMIZER_MAKE_JOIN_HYPERGRAPH 1
26
27#include <assert.h>
28
29#include <algorithm>
30#include <array>
31#include <cstddef>
32#include <optional>
33#include <span>
34#include <string>
35#include <unordered_map>
36#include <utility>
37
38#include "map_helpers.h"
39#include "my_table_map.h"
40#include "sql/item.h"
46#include "sql/mem_root_array.h"
47#include "sql/sql_const.h"
48
49class Field;
50class JOIN;
51class Query_block;
52class THD;
53struct MEM_ROOT;
56struct TABLE;
57
58/**
59 A sargable (from “Search ARGument”) predicate is one that we can attempt
60 to push down into an index (what we'd call “ref access” or “index range
61 scan”/“quick”). This structure denotes one such instance, precomputed from
62 all the predicates in the given hypergraph.
63 */
65 // Index into the “predicates” array in the graph.
67
68 // The predicate is assumed to be <field> = <other_side>.
69 // Later, we could push down other kinds of relations, such as
70 // greater-than.
73
74 /// True if it is safe to evaluate "other_side" during optimization. It must
75 /// be constant during execution. Also, it should not contain subqueries or
76 /// stored procedures, which we do not want to execute during optimization.
78};
79
80/// Information about a join condition that can potentially be pushed down as a
81/// sargable predicate for a Node.
83 /// The condition that may be pushed as a sargable predicate.
85 /// The relational expression from which this condition is pushable.
87};
88
89/**
90 A struct containing a join hypergraph of a single query block, encapsulating
91 the constraints given by the relational expressions (e.g. inner joins are
92 more freely reorderable than outer joins).
93
94 Since the Hypergraph class does not carry any payloads for nodes and edges,
95 and we need to associate e.g. TABLE pointers with each node, we store our
96 extra data in “nodes” and “edges”, indexed the same way the hypergraph is
97 indexed.
98 */
101 : graph(mem_root),
107
109
110 /// Flags set when AccessPaths are proposed to secondary engines for costing.
111 /// The intention of these flags is to avoid traversing the AccessPath tree to
112 /// check for certain criteria.
113 /// TODO (tikoldit) Move to JOIN or Secondary_engine_execution_context, so
114 /// that JoinHypergraph can be immutable during planning
116
117 // Maps table->tableno() to an index in “nodes”, also suitable for
118 // a bit index in a NodeMap. This is normally the identity mapping,
119 // except for when scalar-to-derived conversion is active.
120 std::array<int, MAX_TABLES> table_num_to_node_num;
121
122 class Node final {
123 public:
125 : m_table{table},
129 assert(mem_root != nullptr);
130 assert(table != nullptr);
131 }
132
133 TABLE *table() const { return m_table; }
134
135 void AddSargable(const SargablePredicate &predicate) {
136 assert(predicate.predicate_index >= 0);
137 assert(predicate.field != nullptr);
138 assert(predicate.other_side != nullptr);
139 m_sargable_predicates.push_back(predicate);
140 }
141
144 }
145
146 /**
147 Add a join condition that is potentially pushable as a sargable predicate
148 for this node.
149
150 @param cond The condition to be considered for pushdown.
151 @param from The relational expression from which this condition
152 originates.
153 */
154 void AddPushable(Item *cond, const RelationalExpression *from) {
155 // Don't add duplicate conditions, as this causes their selectivity to
156 // be applied multiple times, giving poor row estimates (cf.
157 // bug#36135001).
158 if (std::ranges::none_of(m_pushable_conditions,
159 [&](const PushableJoinCondition &other) {
160 return ItemsAreEqual(cond, other.cond);
161 })) {
162 m_pushable_conditions.push_back({.cond = cond, .from = from});
163 }
164 }
165
168 }
169
172 }
173
175 m_lateral_dependencies = dependencies;
176 }
177
178 int64_t read_set_width() const { return m_read_set_width; }
179
180 /* Estimated rows cardinality after table filters. */
181 std::optional<double> cardinality;
182
183 private:
185 // List of all sargable predicates (see SargablePredicate) where
186 // the field is part of this table. When we see the node for
187 // the first time, we will evaluate all of these and consider
188 // creating access paths that exploit these predicates.
190
191 // Join conditions that are potentially pushable to this node
192 // as sargable predicates (if they are sargable, they will be
193 // added to sargable_predicates below, together with sargable
194 // non-join conditions). This is a verbatim copy of
195 // the m_pushable_conditions member in RelationalExpression,
196 // which is computed as a side effect during join pushdown.
197 // (We could in principle have gone and collected all join conditions
198 // ourselves when determining sargable conditions, but there would be
199 // a fair amount of duplicated code in determining pushability,
200 // which is why regular join pushdown does the computation.)
202
203 // The lateral dependencies of this table. That is, the set of tables that
204 // must be available on the outer side of a nested loop join in which this
205 // table is on the inner side. This map may be set for LATERAL derived
206 // tables and derived tables with outer references, and for table functions.
208
209 // The estimated size (in bytes) of a row. This is used when making cost
210 // estimates for hash joins. It is cached here to avoid computing it
211 // repeatedly.
213 };
215
216 // Note that graph.edges contain each edge twice (see Hypergraph
217 // for more information), so edges[i] corresponds to graph.edges[i*2].
219
220 // The first <num_filter_predicates> are filter predicates. These are the
221 // predicates that may be added as filters on nodes in the join tree by
222 // setting the corresponding bit in AccessPath::filter_predicates, which at
223 // the end of join optimization gets expanded to proper FILTER access paths by
224 // ExpandFilterAccessPaths(). They include:
225 //
226 // - Actual WHERE predicates that could not be pushed down into one of the
227 // join conditions.
228 //
229 // - Predicates that could be pushed all the way down and become a table
230 // filter. These could be WHERE predicates, but they could also be
231 // predicates that are possible to push all the way down, but not possible
232 // to pull all the way up. Take for example "SELECT 1 FROM t1 LEFT JOIN t2
233 // ON t1.a=t2.a AND t2.b=1". The t2.b=1 predicate can be pushed down as a
234 // table filter, but it cannot be used as a WHERE predicate, as it would
235 // incorrectly filter out the NULL-complemented rows. Still, such table
236 // filters are also counted in "num_filter_predicates".
237 //
238 // - Predicates that are join conditions in some inner join that is involved
239 // in a cycle in the join hypergraph. These are applied as filters in the
240 // join tree if the tables are joined via another edge in the cycle. Such
241 // predicates are also not necessarily possible to pull up to the WHERE
242 // clause. If they for example came from an inner join on the inner side of
243 // some outer join, they cannot be applied as WHERE predicates. Even so,
244 // they are still counted in "num_filter_predicates".
245 //
246 // The rest are sargable join predicates. The latter are in the array
247 // solely so they can be part of the regular "applied_filters" bitmap
248 // if they are pushed down into an index, so that we know that we
249 // don't need to apply them as join conditions later.
250 //
251 // Layout of predicates[]:
252 //
253 // [ Cycle join preds | WHERE preds | Table filter preds | Sargable join
254 // preds ]
255 // <--------------- num_filter_predicates ---------------->
256 //
257 // [0, num_filter_predicates): "filter predicates"
258 // (see description above)
259 // [num_filter_predicates, predicates.size()):
260 // Sargable join predicates (tracked for index pushdown only).
261 //
262 // If a sargable join predicate comes from a join that is part of a cycle in
263 // the hypergraph, it could be present in both partitions of the array.
265
266 // How many of the predicates in "predicates" are filter predicates. The rest
267 // of them are sargable join predicates.
269
270 /// Returns an immutable view of the filter predicates portion of the
271 /// predicates array.
272 std::span<const Predicate> filter_predicates() const {
273 return {predicates.data(), num_filter_predicates};
274 }
275
276 /// Returns a mutable view of the filter predicates portion of the predicates
277 /// array.
278 std::span<Predicate> filter_predicates() {
279 return {predicates.data(), num_filter_predicates};
280 }
281
282 // A bitmap over predicates that are, or contain, at least one
283 // materializable subquery.
285
286 /// Returns a pointer to the query block that is being planned.
287 const Query_block *query_block() const { return m_query_block; }
288
289 /// Returns a pointer to the JOIN object of the query block being planned.
290 const JOIN *join() const;
291
292 /// Whether, at any point, we could rewrite (t1 LEFT JOIN t2) LEFT JOIN t3
293 /// to t1 LEFT JOIN (t2 LEFT JOIN t3) or vice versa. We record this purely to
294 /// note that we have a known bug/inconsistency in row count estimation
295 /// in this case. Bug #33550360 has a test case, but to sum up:
296 /// Assume t1 and t3 has 25 rows, but t2 has zero rows, and selectivities
297 /// are 0.1. As long as we clamp the row count in FindOutputRowsForJoin(),
298 /// and do not modify these selectivities somehow, the former would give
299 /// 62.5 rows, and the second would give 25 rows. This should be fixed
300 /// eventually, but for now, at least we register it, so that we do not
301 /// assert-fail on inconsistent row counts if this (known) issue could be
302 /// the root cause.
304
305 // True if estimates for one or more Nodes in the graph have been provided
306 // by the secondary engine (i.e. at least one Node has the field `cardinality`
307 // set).
309
310 /// The set of nodes that are on the inner side of some outer join.
312
313 /// The set of nodes that are on the inner side of some semijoin.
315
316 /// The set of nodes that are on the inner side of some antijoin.
318
319 /// The set of nodes that are represented by table_function. This will be set
320 /// only when optimizing for secondary engine.
322
323 int FindSargableJoinPredicate(const Item *predicate) const {
324 const auto iter = m_sargable_join_predicates.find(predicate);
325 return iter == m_sargable_join_predicates.cend() ? -1 : iter->second;
326 }
327
328 void AddSargableJoinPredicate(const Item *predicate, int position) {
329 m_sargable_join_predicates.emplace(predicate, position);
330 }
331
333 bool (*)(const SecondaryEngineNrowsParameters &params);
334
335 /// Returns true if the secondary engine nrows hook is available.
337 return m_secondary_engine_nrows_hook != nullptr;
338 }
339
340 /// Calls the secondary engine nrows hook.
341 /// Requires has_secondary_engine_nrows_hook() == true; asserts otherwise.
343 const SecondaryEngineNrowsParameters &params) const {
344 assert(m_secondary_engine_nrows_hook != nullptr);
345 return m_secondary_engine_nrows_hook(params);
346 }
347
348 /// Sets the secondary engine nrows hook (nullptr means unavailable).
350 secondary_engine_nrows_hook_t secondary_engine_nrows_hook) {
351 m_secondary_engine_nrows_hook = secondary_engine_nrows_hook;
352 }
353
354 private:
356
357 // For each sargable join condition, maps into its index in “predicates”.
358 // We need the predicate index when applying the join to figure out whether
359 // we have already applied the predicate or not; see
360 // {applied,subsumed}_sargable_join_predicates in AccessPath.
362
363 /// A pointer to the query block being planned.
365};
366
367/**
368 Make a join hypergraph from the query block given by “graph->query_block”,
369 converting from MySQL's join list structures to the ones expected
370 by the hypergraph join optimizer. This includes pushdown of WHERE
371 predicates, and detection of conditions suitable for hash join.
372 However, it does not include simplification of outer to inner joins;
373 that is presumed to have happened earlier.
374
375 The result is suitable for running DPhyp (subgraph_enumeration.h)
376 to find optimal join planning.
377 */
378bool MakeJoinHypergraph(THD *thd, JoinHypergraph *graph,
379 bool *where_is_always_false);
380
381// Exposed for testing only.
383 JoinHypergraph *graph);
384
387 const std::array<int, MAX_TABLES> &table_num_to_node_num);
388
389std::string PrintDottyHypergraph(const JoinHypergraph &graph);
390
391/// Estimates the size of the hash join keys generated from the equi-join
392/// predicates in "expr".
394
396
397#endif // SQL_JOIN_OPTIMIZER_MAKE_JOIN_HYPERGRAPH
Definition: field.h:573
Base class that is used to represent any kind of expression in a relational query.
Definition: item.h:929
Definition: sql_optimizer.h:133
Definition: make_join_hypergraph.h:122
void AddSargable(const SargablePredicate &predicate)
Definition: make_join_hypergraph.h:135
const Mem_root_array< SargablePredicate > & sargable_predicates() const
Definition: make_join_hypergraph.h:142
TABLE * m_table
Definition: make_join_hypergraph.h:184
Mem_root_array< SargablePredicate > m_sargable_predicates
Definition: make_join_hypergraph.h:189
int64_t m_read_set_width
Definition: make_join_hypergraph.h:212
hypergraph::NodeMap lateral_dependencies() const
Definition: make_join_hypergraph.h:170
hypergraph::NodeMap m_lateral_dependencies
Definition: make_join_hypergraph.h:207
Node(MEM_ROOT *mem_root, TABLE *table, int64_t read_set_width)
Definition: make_join_hypergraph.h:124
Mem_root_array< PushableJoinCondition > m_pushable_conditions
Definition: make_join_hypergraph.h:201
int64_t read_set_width() const
Definition: make_join_hypergraph.h:178
const Mem_root_array< PushableJoinCondition > & pushable_conditions() const
Definition: make_join_hypergraph.h:166
TABLE * table() const
Definition: make_join_hypergraph.h:133
std::optional< double > cardinality
Definition: make_join_hypergraph.h:181
void AddPushable(Item *cond, const RelationalExpression *from)
Add a join condition that is potentially pushable as a sargable predicate for this node.
Definition: make_join_hypergraph.h:154
void set_lateral_dependencies(hypergraph::NodeMap dependencies)
Definition: make_join_hypergraph.h:174
A typesafe replacement for DYNAMIC_ARRAY.
Definition: mem_root_array.h:432
Definition: overflow_bitset.h:81
This class represents a query block, aka a query specification, which is a query consisting of a SELE...
Definition: sql_lex.h:1179
For each client connection we create a separate thread with THD serving as a thread/connection descri...
Definition: sql_lexer_thd.h:36
std::unordered_map, but allocated on a MEM_ROOT.
Definition: map_helpers.h:291
static MEM_ROOT mem_root
Definition: client_plugin.cc:114
Definition of an undirected (join) hypergraph.
bool ItemsAreEqual(const Item *a, const Item *b)
Returns true iff the two items are equal, as in a->eq(b), after unwrapping refs and Item_cache object...
Definition: item.cc:11869
bool MakeJoinHypergraph(THD *thd, JoinHypergraph *graph, bool *where_is_always_false)
Make a join hypergraph from the query block given by “graph->query_block”, converting from MySQL's jo...
Definition: make_join_hypergraph.cc:3826
hypergraph::NodeMap GetNodeMapFromTableMap(table_map table_map, const std::array< int, MAX_TABLES > &table_num_to_node_num)
std::string PrintDottyHypergraph(const JoinHypergraph &graph)
For the given hypergraph, make a textual representation in the form of a dotty graph.
Definition: make_join_hypergraph.cc:2636
void MakeJoinGraphFromRelationalExpression(THD *thd, RelationalExpression *expr, JoinHypergraph *graph)
Convert a join rooted at “expr” into a join hypergraph that encapsulates the constraints given by the...
Definition: make_join_hypergraph.cc:3339
table_map GetVisibleTables(const RelationalExpression *expr)
Definition: make_join_hypergraph.cc:4113
size_t EstimateHashJoinKeyWidth(const RelationalExpression *expr)
Estimates the size of the hash join keys generated from the equi-join predicates in "expr".
Definition: make_join_hypergraph.cc:2735
uint64_t table_map
Definition: my_table_map.h:30
uint64_t NodeMap
Since our graphs can never have more than 61 tables, node sets and edge lists are implemented using 6...
Definition: node_map.h:40
OverflowBitset is a fixed-size (once allocated) bitmap that is optimized for the common case of few e...
For updating an AccessPath's costs by a secondary engine, i.e.
uint64_t SecondaryEngineCostingFlags
Definition: secondary_engine_costing_flags.h:39
File containing constants that can be used throughout the server.
A struct containing a join hypergraph of a single query block, encapsulating the constraints given by...
Definition: make_join_hypergraph.h:99
void set_secondary_engine_nrows_hook(secondary_engine_nrows_hook_t secondary_engine_nrows_hook)
Sets the secondary engine nrows hook (nullptr means unavailable).
Definition: make_join_hypergraph.h:349
secondary_engine_nrows_hook_t m_secondary_engine_nrows_hook
Definition: make_join_hypergraph.h:355
hypergraph::NodeMap nodes_inner_to_outer_join
The set of nodes that are on the inner side of some outer join.
Definition: make_join_hypergraph.h:311
hypergraph::NodeMap nodes_for_table_function
The set of nodes that are represented by table_function.
Definition: make_join_hypergraph.h:321
Mem_root_array< Node > nodes
Definition: make_join_hypergraph.h:214
std::span< Predicate > filter_predicates()
Returns a mutable view of the filter predicates portion of the predicates array.
Definition: make_join_hypergraph.h:278
hypergraph::NodeMap nodes_inner_to_antijoin
The set of nodes that are on the inner side of some antijoin.
Definition: make_join_hypergraph.h:317
bool has_reordered_left_joins
Whether, at any point, we could rewrite (t1 LEFT JOIN t2) LEFT JOIN t3 to t1 LEFT JOIN (t2 LEFT JOIN ...
Definition: make_join_hypergraph.h:303
void AddSargableJoinPredicate(const Item *predicate, int position)
Definition: make_join_hypergraph.h:328
hypergraph::Hypergraph graph
Definition: make_join_hypergraph.h:108
hypergraph::NodeMap nodes_inner_to_semijoin
The set of nodes that are on the inner side of some semijoin.
Definition: make_join_hypergraph.h:314
const Query_block * query_block() const
Returns a pointer to the query block that is being planned.
Definition: make_join_hypergraph.h:287
JoinHypergraph(MEM_ROOT *mem_root, const Query_block *query_block)
Definition: make_join_hypergraph.h:100
const JOIN * join() const
Returns a pointer to the JOIN object of the query block being planned.
Definition: make_join_hypergraph.cc:3824
unsigned num_filter_predicates
Definition: make_join_hypergraph.h:268
const Query_block * m_query_block
A pointer to the query block being planned.
Definition: make_join_hypergraph.h:364
Mem_root_array< Predicate > predicates
Definition: make_join_hypergraph.h:264
int FindSargableJoinPredicate(const Item *predicate) const
Definition: make_join_hypergraph.h:323
OverflowBitset materializable_predicates
Definition: make_join_hypergraph.h:284
SecondaryEngineCostingFlags secondary_engine_costing_flags
Flags set when AccessPaths are proposed to secondary engines for costing.
Definition: make_join_hypergraph.h:115
bool has_secondary_engine_nrows_hook() const
Returns true if the secondary engine nrows hook is available.
Definition: make_join_hypergraph.h:336
bool(*)(const SecondaryEngineNrowsParameters &params) secondary_engine_nrows_hook_t
Definition: make_join_hypergraph.h:333
mem_root_unordered_map< const Item *, int > m_sargable_join_predicates
Definition: make_join_hypergraph.h:361
std::array< int, MAX_TABLES > table_num_to_node_num
Definition: make_join_hypergraph.h:120
bool call_secondary_engine_nrows_hook(const SecondaryEngineNrowsParameters &params) const
Calls the secondary engine nrows hook.
Definition: make_join_hypergraph.h:342
std::span< const Predicate > filter_predicates() const
Returns an immutable view of the filter predicates portion of the predicates array.
Definition: make_join_hypergraph.h:272
bool has_estimates_from_secondary_engine
Definition: make_join_hypergraph.h:308
Mem_root_array< JoinPredicate > edges
Definition: make_join_hypergraph.h:218
The MEM_ROOT is a simple arena, where allocations are carved out of larger blocks.
Definition: my_alloc.h:83
Information about a join condition that can potentially be pushed down as a sargable predicate for a ...
Definition: make_join_hypergraph.h:82
const RelationalExpression * from
The relational expression from which this condition is pushable.
Definition: make_join_hypergraph.h:86
Item * cond
The condition that may be pushed as a sargable predicate.
Definition: make_join_hypergraph.h:84
Represents an expression tree in the relational algebra of joins.
Definition: relational_expression.h:155
A sargable (from “Search ARGument”) predicate is one that we can attempt to push down into an index (...
Definition: make_join_hypergraph.h:64
int predicate_index
Definition: make_join_hypergraph.h:66
Field * field
Definition: make_join_hypergraph.h:71
Item * other_side
Definition: make_join_hypergraph.h:72
bool can_evaluate
True if it is safe to evaluate "other_side" during optimization.
Definition: make_join_hypergraph.h:77
Type for signature generation and for retrieving nrows estimate from secondary engine for current Acc...
Definition: handler.h:2485
Definition: table.h:1456
Definition: hypergraph.h:92