Debian Codegraph @

unittest/gunit/hypergraph_optimizer-t.cc

raw symbols SCIP
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 #include <assert.h>
25 #include <gmock/gmock.h>
26 #include <gtest/gtest.h>
27 #include <math.h>
28 #include <string.h>
29
30 #include <initializer_list>
31 #include <iterator>
32 #include <limits>
33 #include <memory>
34 #include <regex>
35 #include <string>
36 #include <string_view>
37 #include <unordered_map>
38 #include <vector>
39
40 #include "my_alloc.h"
41 #include "my_base.h"
42 #include "my_inttypes.h"
43 #include "my_sqlcommand.h"
44 #include "my_sys.h"
45 #include "mysqld_error.h"
46 #include "scope_guard.h"
47 #include "sql/field.h"
48 #include "sql/filesort.h"
49 #include "sql/handler.h"
50 #include "sql/item.h"
51 #include "sql/item_cmpfunc.h"
52 #include "sql/item_sum.h"
53 #include "sql/join_optimizer/access_path.h"
54 #include "sql/join_optimizer/bit_utils.h"
55 #include "sql/join_optimizer/common_subexpression_elimination.h"
56 #include "sql/join_optimizer/explain_access_path.h"
57 #include "sql/join_optimizer/hypergraph.h"
58 #include "sql/join_optimizer/join_optimizer.h"
59 #include "sql/join_optimizer/make_join_hypergraph.h"
60 #include "sql/join_optimizer/print_utils.h"
61 #include "sql/join_optimizer/relational_expression.h"
62 #include "sql/join_optimizer/subgraph_enumeration.h"
63 #include "sql/join_optimizer/walk_access_paths.h"
64 #include "sql/join_type.h"
65 #include "sql/mem_root_array.h"
66 #include "sql/sort_param.h"
67 #include "sql/sql_class.h"
68 #include "sql/sql_const.h"
69 #include "sql/sql_lex.h"
70 #include "sql/sql_list.h"
71 #include "sql/sql_opt_exec_shared.h"
72 #include "sql/sql_optimizer.h"
73 #include "sql/system_variables.h"
74 #include "sql/table.h"
75 #include "sql/thd_raii.h"
76 #include "sql/visible_fields.h"
77 #include "template_utils.h"
78 #include "temptable/mock_field_varstring.h"
79 #include "unittest/gunit/base_mock_field.h"
80 #include "unittest/gunit/benchmark.h"
81 #include "unittest/gunit/fake_table.h"
82 #include "unittest/gunit/handler-t.h"
83 #include "unittest/gunit/mock_field_datetime.h"
84 #include "unittest/gunit/mock_field_long.h"
85 #include "unittest/gunit/optimizer_test.h"
86 #include "unittest/gunit/parsertest.h"
87 #include "unittest/gunit/test_utils.h"
88
89 using hypergraph::NodeMap;
90 using my_testing::Server_initializer;
91 using std::string;
92 using std::string_view;
93 using std::to_string;
94 using std::unordered_map;
95 using std::vector;
96 using testing::_;
97 using testing::ElementsAre;
98 using testing::Pair;
99 using testing::Return;
100 using testing::StartsWith;
101 using testing::UnorderedElementsAre;
102 using namespace std::literals; // For operator""sv.
103
104 static AccessPath *FindBestQueryPlanAndFinalize(THD *thd,
105 Query_block *query_block,
106 string *trace) {
107 AccessPath *path = FindBestQueryPlan(thd, query_block, trace);
108 if (path != nullptr) {
109 query_block->join->set_root_access_path(path);
110 EXPECT_FALSE(FinalizePlanForQueryBlock(thd, query_block));
111 }
112 return path;
113 }
114
115 namespace {
116
117 /// An error checker which, upon destruction, verifies that a single error was
118 /// raised while the checker was alive, and that the error had the expected
119 /// error number. If an error is raised, the THD::is_error() flag will be set,
120 /// just as in the server. (The default error_handler_hook used by the unit
121 /// tests, does not set the error flag in the THD.) If expected_errno is 0, it
122 /// will instead check that no error was raised.
123 class ErrorChecker {
124 public:
125 ErrorChecker(const THD *thd, unsigned expected_errno)
126 : m_thd(thd),
127 m_errno(expected_errno),
128 m_saved_error_hook(error_handler_hook) {
129 // Use an error handler which sets the THD::is_error() flag.
130 error_handler_hook = my_message_sql;
131 EXPECT_FALSE(thd->is_error());
132 }
133
134 ~ErrorChecker() {
135 error_handler_hook = m_saved_error_hook;
136 if (m_errno != 0) {
137 EXPECT_TRUE(m_thd->is_error());
138 EXPECT_EQ(m_errno, m_thd->get_stmt_da()->mysql_errno());
139 EXPECT_EQ(1, m_thd->get_stmt_da()->current_statement_cond_count());
140 } else {
141 EXPECT_FALSE(m_thd->is_error());
142 }
143 }
144
145 private:
146 const THD *m_thd;
147 unsigned m_errno;
148 ErrorHandlerFunctionPointer m_saved_error_hook;
149 };
150
151 // Sort the nodes in the given graph by name, which makes the test
152 // a bit more robust against irrelevant changes. Note that we don't
153 // sort edges, since it's often useful to correlate the code with
154 // the Graphviz output in the optimizer trace, which isn't sorted.
155 void SortNodes(JoinHypergraph *graph) {
156 // Sort nodes (by alias). We sort a series of indexes first the same way
157 // so that we know which went where.
158 std::vector<int> node_order;
159 for (unsigned i = 0; i < graph->nodes.size(); ++i) {
160 node_order.push_back(i);
161 }
162 std::sort(node_order.begin(), node_order.end(), [graph](int a, int b) {
163 return strcmp(graph->nodes[a].table->alias, graph->nodes[b].table->alias) <
164 0;
165 });
166 std::sort(graph->nodes.begin(), graph->nodes.end(),
167 [](const JoinHypergraph::Node &a, const JoinHypergraph::Node &b) {
168 return strcmp(a.table->alias, b.table->alias) < 0;
169 });
170
171 // Remap hyperedges to the new node indexes. Note that we don't
172 // change the neighborhood, because nothing in these tests need it.
173 int node_map[MAX_TABLES];
174 for (unsigned i = 0; i < graph->nodes.size(); ++i) {
175 node_map[node_order[i]] = i;
176 }
177 for (hypergraph::Hyperedge &edge : graph->graph.edges) {
178 NodeMap new_left = 0, new_right = 0;
179 for (int node_idx : BitsSetIn(edge.left)) {
180 new_left |= NodeMap{1} << node_map[node_idx];
181 }
182 for (int node_idx : BitsSetIn(edge.right)) {
183 new_right |= NodeMap{1} << node_map[node_idx];
184 }
185 edge.left = new_left;
186 edge.right = new_right;
187 }
188
189 // Remap TES.
190 for (Predicate &pred : graph->predicates) {
191 NodeMap new_tes = 0;
192 for (int node_idx : BitsSetIn(pred.total_eligibility_set)) {
193 new_tes |= NodeMap{1} << node_map[node_idx];
194 }
195 pred.total_eligibility_set = new_tes;
196 }
197 }
198
199 } // namespace
200
201 using MakeHypergraphTest = OptimizerTestBase;
202
203 TEST_F(MakeHypergraphTest, SingleTable) {
204 Query_block *query_block =
205 ParseAndResolve("SELECT 1 FROM t1", /*nullable=*/true);
206
207 JoinHypergraph graph(m_thd->mem_root, query_block);
208 string trace;
209 bool always_false = false;
210 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
211 EXPECT_FALSE(always_false);
212
213 SCOPED_TRACE(trace); // Prints out the trace on failure.
214
215 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
216 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
217
218 ASSERT_EQ(1, graph.nodes.size());
219 EXPECT_EQ(0, graph.edges.size());
220 EXPECT_EQ(0, graph.predicates.size());
221
222 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
223 }
224
225 TEST_F(MakeHypergraphTest, InnerJoin) {
226 Query_block *query_block = ParseAndResolve(
227 "SELECT 1 FROM t1 JOIN t2 ON t1.x=t2.x JOIN t3 ON t2.y=t3.y",
228 /*nullable=*/true);
229
230 JoinHypergraph graph(m_thd->mem_root, query_block);
231 string trace;
232 bool always_false = false;
233 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
234 EXPECT_FALSE(always_false);
235
236 SCOPED_TRACE(trace); // Prints out the trace on failure.
237
238 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
239 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
240
241 SortNodes(&graph);
242
243 ASSERT_EQ(3, graph.nodes.size());
244 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
245 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
246 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
247
248 // Simple edges; order doesn't matter.
249 ASSERT_EQ(2, graph.edges.size());
250
251 // t1/t2. There is no index information, so the default 0.1 should be used.
252 EXPECT_EQ(0x01, graph.graph.edges[2].left);
253 EXPECT_EQ(0x02, graph.graph.edges[2].right);
254 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[1].expr->type);
255 EXPECT_FLOAT_EQ(0.1F, graph.edges[1].selectivity);
256
257 // t2/t3.
258 EXPECT_EQ(0x02, graph.graph.edges[0].left);
259 EXPECT_EQ(0x04, graph.graph.edges[0].right);
260 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[0].expr->type);
261 EXPECT_FLOAT_EQ(0.1F, graph.edges[0].selectivity);
262
263 EXPECT_EQ(0, graph.predicates.size());
264 }
265
266 TEST_F(MakeHypergraphTest, OuterJoin) {
267 Query_block *query_block = ParseAndResolve(
268 "SELECT 1 FROM t1 LEFT JOIN (t2 LEFT JOIN t3 ON t2.y=t3.y) ON t1.x=t2.x",
269 /*nullable=*/true);
270
271 JoinHypergraph graph(m_thd->mem_root, query_block);
272 string trace;
273 bool always_false = false;
274 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
275 EXPECT_FALSE(always_false);
276
277 SCOPED_TRACE(trace); // Prints out the trace on failure.
278
279 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
280 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
281
282 ASSERT_EQ(3, graph.nodes.size());
283 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
284 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
285 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
286
287 // Hyperedges. Order doesn't matter.
288 ASSERT_EQ(2, graph.edges.size());
289
290 // t2/t3.
291 EXPECT_EQ(0x02, graph.graph.edges[0].left);
292 EXPECT_EQ(0x04, graph.graph.edges[0].right);
293 EXPECT_EQ(RelationalExpression::LEFT_JOIN, graph.edges[0].expr->type);
294 EXPECT_FLOAT_EQ(0.1F, graph.edges[0].selectivity);
295
296 // t1/t2; since the predicate is null-rejecting on t2, we can rewrite.
297 EXPECT_EQ(0x01, graph.graph.edges[2].left);
298 EXPECT_EQ(0x02, graph.graph.edges[2].right);
299 EXPECT_EQ(RelationalExpression::LEFT_JOIN, graph.edges[1].expr->type);
300 EXPECT_FLOAT_EQ(0.1F, graph.edges[1].selectivity);
301
302 EXPECT_EQ(0, graph.predicates.size());
303 }
304
305 TEST_F(MakeHypergraphTest, OuterJoinNonNullRejecting) {
306 Query_block *query_block = ParseAndResolve(
307 "SELECT 1 FROM t1 LEFT JOIN (t2 LEFT JOIN t3 ON t2.y=t3.y OR t2.y "
308 "IS NULL) ON t1.x=t2.x",
309 /*nullable=*/true);
310
311 JoinHypergraph graph(m_thd->mem_root, query_block);
312 string trace;
313 bool always_false = false;
314 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
315 EXPECT_FALSE(always_false);
316
317 SCOPED_TRACE(trace); // Prints out the trace on failure.
318
319 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
320 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
321
322 ASSERT_EQ(3, graph.nodes.size());
323 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
324 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
325 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
326
327 // Hyperedges. Order doesn't matter.
328 ASSERT_EQ(2, graph.edges.size());
329
330 // t2/t3.
331 EXPECT_EQ(0x02, graph.graph.edges[0].left);
332 EXPECT_EQ(0x04, graph.graph.edges[0].right);
333 EXPECT_EQ(RelationalExpression::LEFT_JOIN, graph.edges[0].expr->type);
334 EXPECT_FLOAT_EQ(1.0F - (0.9F * 0.9F),
335 graph.edges[0].selectivity); // OR of two conditions.
336
337 // t1/{t2,t3}; the predicate is not null-rejecting (unlike the previous test),
338 // so we need the full hyperedge.
339 EXPECT_EQ(0x01, graph.graph.edges[2].left);
340 EXPECT_EQ(0x06, graph.graph.edges[2].right);
341 EXPECT_EQ(RelationalExpression::LEFT_JOIN, graph.edges[1].expr->type);
342 EXPECT_FLOAT_EQ(0.1F, graph.edges[1].selectivity);
343
344 EXPECT_EQ(0, graph.predicates.size());
345 }
346
347 TEST_F(MakeHypergraphTest, SemiJoin) {
348 Query_block *query_block = ParseAndResolve(
349 "SELECT 1 FROM t1 WHERE t1.x IN (SELECT t2.x FROM t2 JOIN t3 ON "
350 "t2.y=t3.y)",
351 /*nullable=*/true);
352
353 JoinHypergraph graph(m_thd->mem_root, query_block);
354 string trace;
355 bool always_false = false;
356 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
357 EXPECT_FALSE(always_false);
358
359 SCOPED_TRACE(trace); // Prints out the trace on failure.
360
361 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
362 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
363
364 ASSERT_EQ(3, graph.nodes.size());
365 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
366 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
367 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
368
369 // Hyperedges. Order doesn't matter.
370 ASSERT_EQ(2, graph.edges.size());
371
372 // t2/t3.
373 EXPECT_EQ(0x02, graph.graph.edges[0].left);
374 EXPECT_EQ(0x04, graph.graph.edges[0].right);
375 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[0].expr->type);
376 EXPECT_FLOAT_EQ(0.1F, graph.edges[0].selectivity);
377
378 // t1/{t2,t3}.
379 EXPECT_EQ(0x01, graph.graph.edges[2].left);
380 EXPECT_EQ(0x06, graph.graph.edges[2].right);
381 EXPECT_EQ(RelationalExpression::SEMIJOIN, graph.edges[1].expr->type);
382 EXPECT_FLOAT_EQ(0.1F, graph.edges[1].selectivity);
383
384 EXPECT_EQ(0, graph.predicates.size());
385 }
386
387 TEST_F(MakeHypergraphTest, AntiJoin) {
388 // NOTE: Fields must be non-nullable, or NOT IN can not be rewritten.
389 Query_block *query_block = ParseAndResolve(
390 "SELECT 1 FROM t1 WHERE t1.x NOT IN (SELECT t2.x FROM t2 JOIN t3 ON "
391 "t2.y=t3.y)",
392 /*nullable=*/false);
393
394 JoinHypergraph graph(m_thd->mem_root, query_block);
395 string trace;
396 bool always_false = false;
397 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
398 EXPECT_FALSE(always_false);
399
400 SCOPED_TRACE(trace); // Prints out the trace on failure.
401
402 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
403 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
404
405 ASSERT_EQ(3, graph.nodes.size());
406 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
407 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
408 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
409
410 // Hyperedges. Order doesn't matter.
411 ASSERT_EQ(2, graph.edges.size());
412
413 // t2/t3.
414 EXPECT_EQ(0x02, graph.graph.edges[0].left);
415 EXPECT_EQ(0x04, graph.graph.edges[0].right);
416 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[0].expr->type);
417 EXPECT_FLOAT_EQ(0.1F, graph.edges[0].selectivity);
418
419 // t1/{t2,t3}.
420 EXPECT_EQ(0x01, graph.graph.edges[2].left);
421 EXPECT_EQ(0x06, graph.graph.edges[2].right);
422 EXPECT_EQ(RelationalExpression::ANTIJOIN, graph.edges[1].expr->type);
423 EXPECT_FLOAT_EQ(0.1F, graph.edges[1].selectivity);
424
425 EXPECT_EQ(0, graph.predicates.size());
426 }
427
428 TEST_F(MakeHypergraphTest, Predicates) {
429 // The OR ... IS NULL part is to keep the LEFT JOIN from being simplified
430 // to an inner join.
431 Query_block *query_block = ParseAndResolve(
432 "SELECT 1 FROM t1 LEFT JOIN t2 ON t1.x=t2.x "
433 "WHERE t1.x=2 AND (t2.y=3 OR t2.y IS NULL)",
434 /*nullable=*/true);
435
436 JoinHypergraph graph(m_thd->mem_root, query_block);
437 string trace;
438 bool always_false = false;
439 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
440 EXPECT_FALSE(always_false);
441
442 SCOPED_TRACE(trace); // Prints out the trace on failure.
443
444 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
445 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
446
447 ASSERT_EQ(2, graph.nodes.size());
448 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
449 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
450
451 // t1/t2.
452 ASSERT_EQ(1, graph.edges.size());
453 EXPECT_EQ(0x01, graph.graph.edges[0].left);
454 EXPECT_EQ(0x02, graph.graph.edges[0].right);
455 EXPECT_EQ(RelationalExpression::LEFT_JOIN, graph.edges[0].expr->type);
456 EXPECT_FLOAT_EQ(0.1F, graph.edges[0].selectivity);
457
458 ASSERT_EQ(2, graph.predicates.size());
459 EXPECT_EQ("(t1.x = 2)", ItemToString(graph.predicates[0].condition));
460 EXPECT_EQ(0x01, graph.predicates[0].total_eligibility_set); // Only t1.
461 EXPECT_FLOAT_EQ(0.1F,
462 graph.predicates[0].selectivity); // No specific information.
463
464 EXPECT_EQ("((t2.y = 3) or (t2.y is null))",
465 ItemToString(graph.predicates[1].condition));
466 EXPECT_GT(graph.predicates[1].selectivity,
467 0.1); // More common due to the OR NULL.
468 EXPECT_EQ(0x03,
469 graph.predicates[1].total_eligibility_set); // Both t1 and t2!
470 }
471
472 TEST_F(MakeHypergraphTest, PushdownFromOuterJoinCondition) {
473 Query_block *query_block = ParseAndResolve(
474 "SELECT 1 FROM t1 LEFT JOIN (t2 JOIN t3) "
475 "ON t1.x=t2.x AND t2.y=t3.y AND t3.z > 3",
476 /*nullable=*/true);
477
478 JoinHypergraph graph(m_thd->mem_root, query_block);
479 string trace;
480 bool always_false = false;
481 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
482 EXPECT_FALSE(always_false);
483
484 SCOPED_TRACE(trace); // Prints out the trace on failure.
485
486 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
487 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
488
489 ASSERT_EQ(3, graph.nodes.size());
490 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
491 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
492 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
493
494 // t2/t3.
495 ASSERT_EQ(2, graph.edges.size());
496 EXPECT_EQ(0x02, graph.graph.edges[0].left);
497 EXPECT_EQ(0x04, graph.graph.edges[0].right);
498 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[0].expr->type);
499 EXPECT_EQ(0, graph.edges[0].expr->join_conditions.size());
500 ASSERT_EQ(1, graph.edges[0].expr->equijoin_conditions.size());
501 EXPECT_EQ("(t2.y = t3.y)",
502 ItemToString(graph.edges[0].expr->equijoin_conditions[0]));
503
504 // t1/(t2,t3).
505 EXPECT_EQ(0x01, graph.graph.edges[2].left);
506 EXPECT_EQ(0x06, graph.graph.edges[2].right);
507 EXPECT_EQ(RelationalExpression::LEFT_JOIN, graph.edges[1].expr->type);
508 ASSERT_EQ(0, graph.edges[1].expr->join_conditions.size());
509 ASSERT_EQ(1, graph.edges[1].expr->equijoin_conditions.size());
510 EXPECT_EQ("(t1.x = t2.x)",
511 ItemToString(graph.edges[1].expr->equijoin_conditions[0]));
512
513 // The z > 3 condition should be pushed all the way down to a predicate.
514 ASSERT_EQ(1, graph.predicates.size());
515 EXPECT_EQ("(t3.z > 3)", ItemToString(graph.predicates[0].condition));
516 EXPECT_EQ(0x04, graph.predicates[0].total_eligibility_set); // Only t3.
517 }
518
519 // See also the PredicatePushdown* tests below.
520 TEST_F(MakeHypergraphTest, AssociativeRewriteToImprovePushdown) {
521 // Note that the WHERE condition needs _both_ associativity and
522 // commutativity to become a proper join condition (t2 needs to be
523 // pulled out; doing t1 instead would create a degenerate join).
524 // The IS NULL is to keep the left join from being converted
525 // into an inner join.
526 Query_block *query_block = ParseAndResolve(
527 "SELECT 1 FROM (t1 JOIN t2 ON TRUE) LEFT JOIN t3 ON TRUE "
528 "WHERE t2.x=t3.x OR t3.x IS NULL",
529 /*nullable=*/true);
530
531 JoinHypergraph graph(m_thd->mem_root, query_block);
532 string trace;
533 bool always_false = false;
534 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
535 EXPECT_FALSE(always_false);
536
537 SCOPED_TRACE(trace); // Prints out the trace on failure.
538
539 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
540 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
541
542 ASSERT_EQ(3, graph.nodes.size());
543 EXPECT_STREQ("t2", graph.nodes[0].table->alias);
544 EXPECT_STREQ("t1", graph.nodes[1].table->alias);
545 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
546
547 // t1/t3.
548 ASSERT_EQ(2, graph.edges.size());
549 EXPECT_EQ(0x02, graph.graph.edges[0].left);
550 EXPECT_EQ(0x04, graph.graph.edges[0].right);
551 EXPECT_EQ(RelationalExpression::LEFT_JOIN, graph.edges[0].expr->type);
552 EXPECT_EQ(0, graph.edges[0].expr->join_conditions.size());
553 EXPECT_FLOAT_EQ(1.0F, graph.edges[0].selectivity);
554
555 // t2/{t1,t3}. This join should also carry the predicate.
556 EXPECT_EQ(0x01, graph.graph.edges[2].left);
557 EXPECT_EQ(0x06, graph.graph.edges[2].right);
558 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[1].expr->type);
559 EXPECT_EQ(1, graph.edges[1].expr->join_conditions.size());
560 EXPECT_FLOAT_EQ(1.0F, graph.edges[1].selectivity);
561
562 EXPECT_EQ(0, graph.predicates.size());
563 }
564
565 TEST_F(MakeHypergraphTest, Cycle) {
566 // If == is outer join and -- is inner join:
567 //
568 // t6 == t1 -- t2 -- t4 == t5
569 // | /
570 // | /
571 // t3
572 //
573 // Note that t6 is on the _left_ side of the inner join, so we should be able
574 // to push down conditions to it.
575
576 Query_block *query_block = ParseAndResolve(
577 "SELECT 1 FROM "
578 "((t1,t2,t3,t4) LEFT JOIN t5 ON t4.x=t5.x) LEFT JOIN t6 ON t1.x=t6.x "
579 "WHERE t1.x=t2.x AND t2.x=t3.x AND t1.x=t3.x AND t2.x=t4.x",
580 /*nullable=*/true);
581
582 JoinHypergraph graph(m_thd->mem_root, query_block);
583 string trace;
584 bool always_false = false;
585 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
586 EXPECT_FALSE(always_false);
587
588 SCOPED_TRACE(trace); // Prints out the trace on failure.
589
590 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
591 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
592
593 SortNodes(&graph);
594
595 ASSERT_EQ(6, graph.nodes.size());
596 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
597 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
598 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
599 EXPECT_STREQ("t4", graph.nodes[3].table->alias);
600 EXPECT_STREQ("t5", graph.nodes[4].table->alias);
601 EXPECT_STREQ("t6", graph.nodes[5].table->alias);
602
603 // t1/t2.
604 ASSERT_EQ(6, graph.edges.size());
605 EXPECT_EQ(0x01, graph.graph.edges[0].left);
606 EXPECT_EQ(0x02, graph.graph.edges[0].right);
607 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[0].expr->type);
608
609 // t2/t3.
610 EXPECT_EQ(0x04, graph.graph.edges[2].left);
611 EXPECT_EQ(0x02, graph.graph.edges[2].right);
612 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[1].expr->type);
613
614 // t4/t2.
615 EXPECT_EQ(0x08, graph.graph.edges[4].left);
616 EXPECT_EQ(0x02, graph.graph.edges[4].right);
617 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[2].expr->type);
618
619 // t4/t5.
620 EXPECT_EQ(0x08, graph.graph.edges[6].left);
621 EXPECT_EQ(0x10, graph.graph.edges[6].right);
622 EXPECT_EQ(RelationalExpression::LEFT_JOIN, graph.edges[3].expr->type);
623
624 // t1/t6.
625 EXPECT_EQ(0x01, graph.graph.edges[8].left);
626 EXPECT_EQ(0x20, graph.graph.edges[8].right);
627 EXPECT_EQ(RelationalExpression::LEFT_JOIN, graph.edges[4].expr->type);
628
629 // t3/t1; added last because it completes a cycle.
630 EXPECT_EQ(0x04, graph.graph.edges[10].left);
631 EXPECT_EQ(0x01, graph.graph.edges[10].right);
632 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[5].expr->type);
633
634 // The three predicates from the cycle should be added, but no others.
635 // The TES should be equivalent to the SES, ie., the outer joins should
636 // not influence this.
637 ASSERT_EQ(3, graph.predicates.size());
638
639 EXPECT_EQ("(t1.x = t2.x)", ItemToString(graph.predicates[0].condition));
640 EXPECT_EQ(0x03, graph.predicates[0].total_eligibility_set); // t1/t2.
641 EXPECT_TRUE(graph.predicates[0].was_join_condition);
642
643 EXPECT_EQ("(t2.x = t3.x)", ItemToString(graph.predicates[1].condition));
644 EXPECT_EQ(0x06, graph.predicates[1].total_eligibility_set); // t2/t3.
645 EXPECT_TRUE(graph.predicates[1].was_join_condition);
646
647 EXPECT_EQ("(t1.x = t3.x)", ItemToString(graph.predicates[2].condition));
648 EXPECT_EQ(0x05, graph.predicates[2].total_eligibility_set); // t1/t3.
649 EXPECT_TRUE(graph.predicates[2].was_join_condition);
650 }
651
652 TEST_F(MakeHypergraphTest, NoCycleBelowOuterJoin) {
653 // The OR ... IS NULL part is to keep the LEFT JOIN from being simplified
654 // to an inner join.
655 Query_block *query_block = ParseAndResolve(
656 "SELECT 1 FROM t1 LEFT JOIN (t2,t3,t4) ON t1.x=t2.x "
657 "WHERE (t2.x=t3.x OR t2.x IS NULL) "
658 "AND (t3.x=t4.x OR t3.x IS NULL) "
659 "AND (t4.x=t2.x OR t4.x IS NULL)",
660 /*nullable=*/true);
661
662 JoinHypergraph graph(m_thd->mem_root, query_block);
663 string trace;
664 bool always_false = false;
665 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
666 EXPECT_FALSE(always_false);
667
668 SCOPED_TRACE(trace); // Prints out the trace on failure.
669
670 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
671 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
672
673 ASSERT_EQ(4, graph.nodes.size());
674 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
675 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
676 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
677 EXPECT_STREQ("t4", graph.nodes[3].table->alias);
678
679 // t2/t3.
680 ASSERT_EQ(3, graph.edges.size());
681 EXPECT_EQ(0x02, graph.graph.edges[0].left);
682 EXPECT_EQ(0x04, graph.graph.edges[0].right);
683 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[0].expr->type);
684
685 // {t2,t3}/t4 (due to the Cartesian product).
686 EXPECT_EQ(0x06, graph.graph.edges[2].left);
687 EXPECT_EQ(0x08, graph.graph.edges[2].right);
688 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[1].expr->type);
689
690 // t1/{t2,t3,t4} (the outer join).
691 EXPECT_EQ(0x01, graph.graph.edges[4].left);
692 EXPECT_EQ(0x0e, graph.graph.edges[4].right);
693 EXPECT_EQ(RelationalExpression::LEFT_JOIN, graph.edges[2].expr->type);
694
695 // The three predicates are still there; no extra predicates due to cycles.
696 EXPECT_EQ(3, graph.predicates.size());
697 }
698
699 TEST_F(MakeHypergraphTest, CyclePushedFromOuterJoinCondition) {
700 Query_block *query_block = ParseAndResolve(
701 "SELECT 1 FROM "
702 "t1 LEFT JOIN (t2 JOIN (t3 JOIN t4 ON t3.x=t4.x) ON t2.x=t3.x) "
703 "ON t1.x=t2.x AND t2.x=t4.x",
704 /*nullable=*/true);
705
706 JoinHypergraph graph(m_thd->mem_root, query_block);
707 string trace;
708 bool always_false = false;
709 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
710 EXPECT_FALSE(always_false);
711
712 SCOPED_TRACE(trace); // Prints out the trace on failure.
713
714 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
715 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
716
717 SortNodes(&graph);
718
719 ASSERT_EQ(4, graph.nodes.size());
720 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
721 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
722 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
723 EXPECT_STREQ("t4", graph.nodes[3].table->alias);
724
725 // t3/t2.
726 ASSERT_EQ(4, graph.edges.size());
727 EXPECT_EQ(0x04, graph.graph.edges[2].left);
728 EXPECT_EQ(0x02, graph.graph.edges[2].right);
729 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[1].expr->type);
730
731 // t2/t4 (pushed from the ON condition).
732 EXPECT_EQ(0x02, graph.graph.edges[0].left);
733 EXPECT_EQ(0x08, graph.graph.edges[0].right);
734 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[0].expr->type);
735
736 // t1/{t2,t3,t4} (the outer join).
737 EXPECT_EQ(0x01, graph.graph.edges[4].left);
738 EXPECT_EQ(0x0e, graph.graph.edges[4].right);
739 EXPECT_EQ(RelationalExpression::LEFT_JOIN, graph.edges[2].expr->type);
740
741 // t3/t4; added last because it completes a cycle.
742 EXPECT_EQ(0x04, graph.graph.edges[6].left);
743 EXPECT_EQ(0x08, graph.graph.edges[6].right);
744 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[3].expr->type);
745
746 // The three predicates from the cycle should be added, but no others.
747 // The TES should be equivalent to the SES, ie., the outer joins should
748 // not influence this.
749 ASSERT_EQ(3, graph.predicates.size());
750
751 EXPECT_EQ("(t2.x = t3.x)", ItemToString(graph.predicates[1].condition));
752 EXPECT_EQ(0x06, graph.predicates[1].total_eligibility_set); // t2/t3.
753 EXPECT_TRUE(graph.predicates[1].was_join_condition);
754
755 EXPECT_EQ("(t2.x = t4.x)", ItemToString(graph.predicates[0].condition));
756 EXPECT_EQ(0x0a, graph.predicates[0].total_eligibility_set); // t2/t4.
757 EXPECT_TRUE(graph.predicates[0].was_join_condition);
758
759 EXPECT_EQ("(t3.x = t4.x)", ItemToString(graph.predicates[2].condition));
760 EXPECT_EQ(0x0c, graph.predicates[2].total_eligibility_set); // t3/t4.
761 EXPECT_TRUE(graph.predicates[2].was_join_condition);
762 }
763
764 TEST_F(MakeHypergraphTest, CycleWithNullSafeEqual) {
765 Query_block *query_block = ParseAndResolve(
766 "SELECT 1 FROM t1, t2, t3 WHERE "
767 "t1.x <=> t2.x AND t2.y <=> t3.y AND t1.z <=> t3.z",
768 /*nullable=*/true);
769
770 JoinHypergraph graph(m_thd->mem_root, query_block);
771 string trace;
772 bool always_false = false;
773 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
774 EXPECT_FALSE(always_false);
775
776 SCOPED_TRACE(trace); // Prints out the trace on failure.
777
778 // Expect a hypergraph of three nodes, and one simple edge connecting each
779 // pair of nodes.
780 EXPECT_EQ(3, graph.nodes.size());
781 EXPECT_EQ(3, graph.edges.size());
782
783 // All the edges should have equijoin conditions.
784 vector<string> predicates;
785 for (const JoinPredicate &predicate : graph.edges) {
786 const RelationalExpression *expr = predicate.expr;
787 EXPECT_TRUE(expr->join_conditions.empty());
788 ASSERT_EQ(1, expr->equijoin_conditions.size());
789 predicates.push_back(ItemToString(expr->equijoin_conditions[0]));
790 }
791 EXPECT_THAT(predicates,
792 UnorderedElementsAre("(t1.x <=> t2.x)", "(t2.y <=> t3.y)",
793 "(t1.z <=> t3.z)"));
794 }
795
796 TEST_F(MakeHypergraphTest, MultipleEqualitiesCauseCycle) {
797 Query_block *query_block =
798 ParseAndResolve("SELECT 1 FROM t1,t2,t3 WHERE t1.x=t2.x AND t2.x=t3.x",
799 /*nullable=*/true);
800
801 // Build multiple equalities from the WHERE condition.
802 COND_EQUAL *cond_equal = nullptr;
803 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
804 &query_block->m_table_nest,
805 &query_block->cond_value));
806
807 JoinHypergraph graph(m_thd->mem_root, query_block);
808 string trace;
809 bool always_false = false;
810 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
811 EXPECT_FALSE(always_false);
812
813 SCOPED_TRACE(trace); // Prints out the trace on failure.
814
815 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
816 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
817
818 ASSERT_EQ(3, graph.nodes.size());
819 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
820 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
821 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
822
823 // t1/t2.
824 ASSERT_EQ(3, graph.edges.size());
825 EXPECT_EQ(0x01, graph.graph.edges[0].left);
826 EXPECT_EQ(0x02, graph.graph.edges[0].right);
827
828 // t2/t3.
829 EXPECT_EQ(0x02, graph.graph.edges[2].left);
830 EXPECT_EQ(0x04, graph.graph.edges[2].right);
831
832 // t1/t3 (the cycle edge).
833 EXPECT_EQ(0x01, graph.graph.edges[4].left);
834 EXPECT_EQ(0x04, graph.graph.edges[4].right);
835 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[2].expr->type);
836 }
837
838 TEST_F(MakeHypergraphTest, CyclesGetConsistentSelectivities) {
839 // Same setup as MultipleEqualitiesCauseCycle, but with an index on t1.x.
840 // The information we get from t1=t2 should also be used for t2=t3,
841 // due to the multiple equality.
842 Query_block *query_block =
843 ParseAndResolve("SELECT 1 FROM t1,t2,t3 WHERE t1.x=t2.x AND t2.x=t3.x",
844 /*nullable=*/true);
845 Fake_TABLE *t1 = m_fake_tables["t1"];
846 t1->create_index(t1->field[0], nullptr, /*unique=*/false);
847 ulong rec_per_key_int[] = {2};
848 float rec_per_key[] = {2.0f};
849 t1->key_info[0].set_rec_per_key_array(rec_per_key_int, rec_per_key);
850 t1->file->stats.records = 100;
851
852 // Build multiple equalities from the WHERE condition.
853 COND_EQUAL *cond_equal = nullptr;
854 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
855 &query_block->m_table_nest,
856 &query_block->cond_value));
857
858 JoinHypergraph graph(m_thd->mem_root, query_block);
859 string trace;
860 bool always_false = false;
861 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
862 EXPECT_FALSE(always_false);
863
864 SCOPED_TRACE(trace); // Prints out the trace on failure.
865
866 ASSERT_EQ(3, graph.edges.size());
867 EXPECT_FLOAT_EQ(0.02F, graph.edges[0].selectivity);
868 EXPECT_FLOAT_EQ(0.02F, graph.edges[1].selectivity);
869 EXPECT_FLOAT_EQ(0.02F, graph.edges[2].selectivity);
870 }
871
872 TEST_F(MakeHypergraphTest, MultiEqualityPredicateAppliedOnce) {
873 Query_block *query_block = ParseAndResolve(
874 "SELECT 1 FROM t1, t2, t3, t4 "
875 "WHERE t1.x <> t4.y AND t4.z <> t3.y AND t2.z <> t3.x AND "
876 "t2.x = t4.x AND t1.y = t2.x",
877 /*nullable=*/true);
878
879 // Build multiple equalities from the WHERE condition.
880 COND_EQUAL *cond_equal = nullptr;
881 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
882 &query_block->m_table_nest,
883 &query_block->cond_value));
884
885 JoinHypergraph graph(m_thd->mem_root, query_block);
886 string trace;
887 bool always_false = false;
888 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
889 EXPECT_FALSE(always_false);
890
891 SCOPED_TRACE(trace); // Prints out the trace on failure.
892
893 ASSERT_EQ(4, graph.nodes.size());
894 EXPECT_STREQ("t3", graph.nodes[0].table->alias);
895 EXPECT_STREQ("t1", graph.nodes[1].table->alias);
896 EXPECT_STREQ("t2", graph.nodes[2].table->alias);
897 EXPECT_STREQ("t4", graph.nodes[3].table->alias);
898
899 ASSERT_EQ(4, graph.edges.size());
900
901 // t1/t2: t1.y = t2.x
902 EXPECT_EQ(TableBitmap(1), graph.graph.edges[0].left);
903 EXPECT_EQ(TableBitmap(2), graph.graph.edges[0].right);
904 EXPECT_FLOAT_EQ(COND_FILTER_EQUALITY, graph.edges[0].selectivity);
905
906 // t1/t4: (t1.y = t4.x) and (t1.x <> t4.y)
907 EXPECT_EQ(TableBitmap(1), graph.graph.edges[2].left);
908 EXPECT_EQ(TableBitmap(3), graph.graph.edges[2].right);
909 // Used to apply the equality predicate twice. Once as t1.y = t4.x and
910 // once as t4.x = t1.y. Verify that it's applied once now.
911 EXPECT_FLOAT_EQ(COND_FILTER_EQUALITY * (1.0f - COND_FILTER_EQUALITY),
912 graph.edges[1].selectivity);
913
914 // t3/t2t4: (t4.z <> t3.y) AND (t2.z <> t3.x)
915 EXPECT_EQ(TableBitmap(0), graph.graph.edges[4].left);
916 EXPECT_EQ(TableBitmap(2) | TableBitmap(3), graph.graph.edges[4].right);
917 EXPECT_FLOAT_EQ((1.0f - COND_FILTER_EQUALITY) * (1.0f - COND_FILTER_EQUALITY),
918 graph.edges[2].selectivity);
919
920 // t2/t4: t2.x = t4.x
921 EXPECT_EQ(TableBitmap(2), graph.graph.edges[6].left);
922 EXPECT_EQ(TableBitmap(3), graph.graph.edges[6].right);
923 EXPECT_FLOAT_EQ(COND_FILTER_EQUALITY, graph.edges[3].selectivity);
924 }
925
926 TEST_F(MakeHypergraphTest, MultiEqualityPredicateNoRedundantJoinCondition) {
927 Query_block *query_block = ParseAndResolve(
928 "SELECT 1 FROM t1, t2, (t3 LEFT JOIN t4 ON t3.x = t4.x), t5 "
929 "WHERE t2.x = t3.x AND t3.x = t5.x AND t3.x = t3.y AND t1.y <> t5.y",
930 /*nullable=*/true);
931
932 // Build multiple equalities from the WHERE condition.
933 COND_EQUAL *cond_equal = nullptr;
934 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
935 &query_block->m_table_nest,
936 &query_block->cond_value));
937
938 JoinHypergraph graph(m_thd->mem_root, query_block);
939 string trace;
940 bool always_false = false;
941 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
942 EXPECT_FALSE(always_false);
943
944 SCOPED_TRACE(trace); // Prints out the trace on failure.
945
946 ASSERT_EQ(5, graph.nodes.size());
947 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
948 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
949 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
950 EXPECT_STREQ("t4", graph.nodes[3].table->alias);
951 EXPECT_STREQ("t5", graph.nodes[4].table->alias);
952
953 EXPECT_EQ(6, graph.edges.size());
954
955 // Find the edge between t2 and t3.
956 int t2_t3_edge_idx = -1;
957 for (size_t i = 0; i < graph.graph.edges.size(); ++i) {
958 if (graph.graph.edges[i].left == TableBitmap(1) &&
959 graph.graph.edges[i].right == TableBitmap(2)) {
960 t2_t3_edge_idx = i / 2;
961 break;
962 }
963 }
964 ASSERT_NE(-1, t2_t3_edge_idx);
965
966 // Check the condition on the edge. It should be a single equality predicate;
967 // either t2.x = t3.x or t2.x = t3.y. It used to have both predicates, and
968 // therefore double-count the selectivity. (Having one of the predicates is
969 // enough, because t3.x = t3.y will always be applied as a table predicate and
970 // make the other join predicate redundant.)
971 const JoinPredicate &predicate = graph.edges[t2_t3_edge_idx];
972 EXPECT_TRUE(predicate.expr->join_conditions.empty());
973 EXPECT_EQ(1, predicate.expr->equijoin_conditions.size());
974 EXPECT_FLOAT_EQ(COND_FILTER_EQUALITY, predicate.selectivity);
975 }
976
977 TEST_F(MakeHypergraphTest, MultiEqualityPredicateNoRedundantJoinCondition2) {
978 Query_block *query_block = ParseAndResolve(
979 "SELECT 1 FROM t1 JOIN t2 ON t1.x = t2.x "
980 "JOIN t3 LEFT JOIN t4 ON t3.x = t4.x "
981 "JOIN t5 JOIN t6 ON t5.y = t6.x ON t5.x = t3.x ON t1.x = t6.x "
982 "WHERE (t3.y IS NULL OR t6.y <> t4.y) AND t3.y <> t5.z",
983 /*nullable=*/true);
984
985 // Build multiple equalities from the WHERE condition.
986 COND_EQUAL *cond_equal = nullptr;
987 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
988 &query_block->m_table_nest,
989 &query_block->cond_value));
990
991 JoinHypergraph graph(m_thd->mem_root, query_block);
992 string trace;
993 bool always_false = false;
994 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
995 EXPECT_FALSE(always_false);
996
997 SCOPED_TRACE(trace); // Prints out the trace on failure.
998
999 ASSERT_EQ(6, graph.nodes.size());
1000 SortNodes(&graph);
1001 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
1002 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
1003 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
1004 EXPECT_STREQ("t4", graph.nodes[3].table->alias);
1005 EXPECT_STREQ("t5", graph.nodes[4].table->alias);
1006 EXPECT_STREQ("t6", graph.nodes[5].table->alias);
1007
1008 EXPECT_EQ(11, graph.edges.size());
1009
1010 // Find the edge {t2,t3,t4}/{t6}
1011 int edge_idx = -1;
1012 for (size_t i = 0; i < graph.graph.edges.size(); ++i) {
1013 if (graph.graph.edges[i].left == TablesBetween(1, 4) &&
1014 graph.graph.edges[i].right == TableBitmap(5)) {
1015 edge_idx = i / 2;
1016 break;
1017 }
1018 }
1019 ASSERT_NE(-1, edge_idx);
1020
1021 // Check the condition on the edge. In addition to a non-equijoin condition
1022 // for the OR predicate, it should contain a single equijoin condition. It
1023 // happens to be t2.x=t6.x, but it could equally well have been t1.x=t6.x.
1024 // Because of multiple equalities, t1.x=t2.x will already have been applied on
1025 // the {t1,t2,t3,t4} subplan, and t1.x=t6.x is implied by t1.x=t2.x and
1026 // t2.x=t6.x. The main point of this test case is to verify that this edge
1027 // contains only one of those two equijoin conditions, and that its
1028 // selectivity is not double-counted.
1029 const JoinPredicate &predicate = graph.edges[edge_idx];
1030 ASSERT_EQ(1, predicate.expr->join_conditions.size());
1031 EXPECT_EQ("((t3.y is null) or (t6.y <> t4.y))",
1032 ItemToString(predicate.expr->join_conditions[0]));
1033 ASSERT_EQ(1, predicate.expr->equijoin_conditions.size());
1034 EXPECT_EQ("(t2.x = t6.x)",
1035 ItemToString(predicate.expr->equijoin_conditions[0]));
1036 EXPECT_FLOAT_EQ(
1037 COND_FILTER_ALLPASS // selectivity of non-equijoin condition
1038 * COND_FILTER_EQUALITY, // selectivity of a single equijoin condition
1039 predicate.selectivity);
1040 }
1041
1042 TEST_F(MakeHypergraphTest, ConflictRulesWithManyTables) {
1043 Query_block *query_block = ParseAndResolve(
1044 "SELECT 1 FROM t1 JOIN t2 JOIN t3 LEFT JOIN t4"
1045 " ON t4.y=t1.y WHERE t2.x = t1.x "
1046 "AND EXISTS (SELECT 1 FROM t5 WHERE t5.x=t1.x)",
1047 /*nullable=*/true);
1048
1049 // Build multiple equalities from the WHERE condition.
1050 COND_EQUAL *cond_equal = nullptr;
1051 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
1052 &query_block->m_table_nest,
1053 &query_block->cond_value));
1054
1055 JoinHypergraph graph(m_thd->mem_root, query_block);
1056 string trace;
1057 bool always_false = false;
1058 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
1059 EXPECT_FALSE(always_false);
1060
1061 SCOPED_TRACE(trace); // Prints out the trace on failure.
1062
1063 SortNodes(&graph);
1064 ASSERT_EQ(5, graph.nodes.size());
1065 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
1066 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
1067 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
1068 EXPECT_STREQ("t4", graph.nodes[3].table->alias);
1069 EXPECT_STREQ("t5", graph.nodes[4].table->alias);
1070
1071 for (const JoinPredicate &pred : graph.edges) {
1072 // We are not interested in the plan. However, while generating
1073 // conflict rules, earlier it would wrongly place the conflict
1074 // rule {t4}->{t3} for the edge t1->t5. This was because it
1075 // was using table_map instead of NodeMap to determine the rule.
1076 EXPECT_EQ(0, pred.expr->conflict_rules.size());
1077 }
1078 }
1079
1080 TEST_F(MakeHypergraphTest, HyperpredicatesDoNotBlockExtraCycleEdges) {
1081 Query_block *query_block = ParseAndResolve(
1082 "SELECT 1 "
1083 "FROM t1 JOIN t2 ON t1.x = t2.x JOIN t3 ON t1.y = t3.y "
1084 "WHERE t1.z = 0 OR t2.z = 0 OR t3.z = 0",
1085 /*nullable=*/true);
1086
1087 // Build (trivial!) multiple equalities from the ON conditions.
1088 COND_EQUAL *cond_equal = nullptr;
1089 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
1090 &query_block->m_table_nest,
1091 &query_block->cond_value));
1092
1093 JoinHypergraph graph(m_thd->mem_root, query_block);
1094 string trace;
1095 bool always_false = false;
1096 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
1097 EXPECT_FALSE(always_false);
1098
1099 SCOPED_TRACE(trace); // Prints out the trace on failure.
1100
1101 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
1102 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
1103
1104 ASSERT_EQ(3, graph.nodes.size());
1105 EXPECT_STREQ("t2", graph.nodes[0].table->alias);
1106 EXPECT_STREQ("t1", graph.nodes[1].table->alias);
1107 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
1108
1109 // t1/t3.
1110 ASSERT_EQ(3, graph.edges.size());
1111 EXPECT_EQ(0x02, graph.graph.edges[0].left);
1112 EXPECT_EQ(0x04, graph.graph.edges[0].right);
1113
1114 // {t1,t3}/t2. We don't really care how this hyperedge turns out,
1115 // but we _do_ care that its presence does not prevent a separate
1116 // t1-t2 edge from being added.
1117 EXPECT_EQ(0x01, graph.graph.edges[2].left);
1118 EXPECT_EQ(0x06, graph.graph.edges[2].right);
1119
1120 // t1/t2. This edge didn't use to be added. But that effectively blocked
1121 // the join order (t1 JOIN t2) JOIN t3, which could be advantageous if
1122 // (t1 JOIN t3) had much higher cardinality than (t1 JOIN t2). So now we
1123 // want it to be there.
1124 EXPECT_EQ(0x02, graph.graph.edges[4].left);
1125 EXPECT_EQ(0x01, graph.graph.edges[4].right);
1126 }
1127
1128 TEST_F(MakeHypergraphTest, Flattening) {
1129 // This query is impossible to push cleanly without flattening,
1130 // or adding broad hyperedges. We want to make sure we don't try to
1131 // “solve” it by pushing the t2.x = t3.x condition twice.
1132 // Due to flattening, we also don't get any Cartesian products.
1133 Query_block *query_block = ParseAndResolve(
1134 "SELECT 1 FROM t1 JOIN (t2 JOIN (t3 JOIN t4)) "
1135 "WHERE t1.y = t4.y AND t2.x = t3.x AND t3.x = t4.x",
1136 /*nullable=*/true);
1137
1138 // Build multiple equalities from the WHERE condition.
1139 COND_EQUAL *cond_equal = nullptr;
1140 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
1141 &query_block->m_table_nest,
1142 &query_block->cond_value));
1143 EXPECT_EQ("(multiple equal(t1.y, t4.y) and multiple equal(t2.x, t3.x, t4.x))",
1144 ItemToString(query_block->where_cond()));
1145
1146 JoinHypergraph graph(m_thd->mem_root, query_block);
1147 string trace;
1148 bool always_false = false;
1149 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
1150 EXPECT_FALSE(always_false);
1151
1152 SCOPED_TRACE(trace); // Prints out the trace on failure.
1153
1154 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
1155 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
1156
1157 SortNodes(&graph);
1158
1159 ASSERT_EQ(4, graph.nodes.size());
1160 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
1161 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
1162 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
1163 EXPECT_STREQ("t4", graph.nodes[3].table->alias);
1164
1165 ASSERT_EQ(4, graph.edges.size());
1166
1167 // t2/t3.
1168 EXPECT_EQ(0x02, graph.graph.edges[0].left);
1169 EXPECT_EQ(0x04, graph.graph.edges[0].right);
1170 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[0].expr->type);
1171 ASSERT_EQ(1, graph.edges[1].expr->equijoin_conditions.size());
1172 EXPECT_EQ("(t2.x = t3.x)",
1173 ItemToString(graph.edges[0].expr->equijoin_conditions[0]));
1174
1175 // t1/t4.
1176 EXPECT_EQ(0x01, graph.graph.edges[2].left);
1177 EXPECT_EQ(0x08, graph.graph.edges[2].right);
1178 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[1].expr->type);
1179 ASSERT_EQ(1, graph.edges[1].expr->equijoin_conditions.size());
1180 EXPECT_EQ("(t1.y = t4.y)",
1181 ItemToString(graph.edges[1].expr->equijoin_conditions[0]));
1182
1183 // t3/t4.
1184 EXPECT_EQ(0x04, graph.graph.edges[4].left);
1185 EXPECT_EQ(0x08, graph.graph.edges[4].right);
1186 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[2].expr->type);
1187 ASSERT_EQ(1, graph.edges[2].expr->equijoin_conditions.size());
1188 EXPECT_EQ("(t3.x = t4.x)",
1189 ItemToString(graph.edges[2].expr->equijoin_conditions[0]));
1190
1191 // t2/t4.
1192 EXPECT_EQ(0x02, graph.graph.edges[6].left);
1193 EXPECT_EQ(0x08, graph.graph.edges[6].right);
1194 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[3].expr->type);
1195 ASSERT_EQ(1, graph.edges[3].expr->equijoin_conditions.size());
1196 EXPECT_EQ("(t2.x = t4.x)",
1197 ItemToString(graph.edges[3].expr->equijoin_conditions[0]));
1198 }
1199
1200 TEST_F(MakeHypergraphTest, PredicatePromotionOnMultipleEquals) {
1201 Query_block *query_block = ParseAndResolve(
1202 "SELECT 1 FROM t1,t2,t3 WHERE t1.x=t2.x AND t2.x=t3.x AND t1.y=t3.y",
1203 /*nullable=*/true);
1204
1205 // Build multiple equalities from the WHERE condition.
1206 COND_EQUAL *cond_equal = nullptr;
1207 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
1208 &query_block->m_table_nest,
1209 &query_block->cond_value));
1210
1211 JoinHypergraph graph(m_thd->mem_root, query_block);
1212 string trace;
1213 bool always_false = false;
1214 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
1215 EXPECT_FALSE(always_false);
1216
1217 SCOPED_TRACE(trace); // Prints out the trace on failure.
1218
1219 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
1220 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
1221
1222 ASSERT_EQ(3, graph.nodes.size());
1223 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
1224 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
1225 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
1226
1227 // t1/t2.
1228 ASSERT_EQ(3, graph.edges.size());
1229 EXPECT_EQ(0x01, graph.graph.edges[0].left);
1230 EXPECT_EQ(0x02, graph.graph.edges[0].right);
1231 EXPECT_EQ(0, graph.edges[0].expr->join_conditions.size());
1232 ASSERT_EQ(1, graph.edges[0].expr->equijoin_conditions.size());
1233 EXPECT_EQ("(t1.x = t2.x)",
1234 ItemToString(graph.edges[0].expr->equijoin_conditions[0]));
1235
1236 // t2/t3.
1237 EXPECT_EQ(0x02, graph.graph.edges[2].left);
1238 EXPECT_EQ(0x04, graph.graph.edges[2].right);
1239 EXPECT_EQ(0, graph.edges[1].expr->join_conditions.size());
1240 ASSERT_EQ(1, graph.edges[1].expr->equijoin_conditions.size());
1241 EXPECT_EQ("(t2.x = t3.x)",
1242 ItemToString(graph.edges[1].expr->equijoin_conditions[0]));
1243
1244 // t1/t3 (the cycle edge). Has both the original condition and the
1245 // multi-equality condition.
1246 EXPECT_EQ(0x01, graph.graph.edges[4].left);
1247 EXPECT_EQ(0x04, graph.graph.edges[4].right);
1248 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[2].expr->type);
1249 EXPECT_EQ(0, graph.edges[2].expr->join_conditions.size());
1250 ASSERT_EQ(2, graph.edges[2].expr->equijoin_conditions.size());
1251 EXPECT_EQ("(t1.y = t3.y)",
1252 ItemToString(graph.edges[2].expr->equijoin_conditions[0]));
1253 EXPECT_EQ("(t1.x = t3.x)",
1254 ItemToString(graph.edges[2].expr->equijoin_conditions[1]));
1255
1256 // Verify that the ones coming from the multi-equality are marked with
1257 // the same index, so that they are properly deduplicated.
1258 ASSERT_EQ(4, graph.predicates.size());
1259
1260 EXPECT_EQ("(t1.x = t2.x)", ItemToString(graph.predicates[0].condition));
1261 EXPECT_TRUE(graph.predicates[0].was_join_condition);
1262 EXPECT_EQ(0, graph.predicates[0].source_multiple_equality_idx);
1263
1264 EXPECT_EQ("(t2.x = t3.x)", ItemToString(graph.predicates[1].condition));
1265 EXPECT_TRUE(graph.predicates[1].was_join_condition);
1266 EXPECT_EQ(0, graph.predicates[1].source_multiple_equality_idx);
1267
1268 EXPECT_EQ("(t1.y = t3.y)", ItemToString(graph.predicates[2].condition));
1269 EXPECT_TRUE(graph.predicates[2].was_join_condition);
1270 EXPECT_EQ(-1, graph.predicates[2].source_multiple_equality_idx);
1271
1272 EXPECT_EQ("(t1.x = t3.x)", ItemToString(graph.predicates[3].condition));
1273 EXPECT_TRUE(graph.predicates[3].was_join_condition);
1274 EXPECT_EQ(0, graph.predicates[3].source_multiple_equality_idx);
1275 }
1276
1277 // Verify that multiple equalities are properly resolved to a single equality,
1278 // and not left as a multiple one. Antijoins have a similar issue.
1279 // Inspired by issues in a larger query (DBT-3 Q21).
1280 TEST_F(MakeHypergraphTest, MultipleEqualityPushedFromJoinConditions) {
1281 Query_block *query_block = ParseAndResolve(
1282 "SELECT 1 FROM t1, t2 "
1283 "WHERE t1.x=t2.x AND t1.x IN (SELECT t3.x FROM t3) ",
1284 /*nullable=*/false);
1285
1286 // Build multiple equalities from the WHERE condition.
1287 COND_EQUAL *cond_equal = nullptr;
1288 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
1289 &query_block->m_table_nest,
1290 &query_block->cond_value));
1291
1292 JoinHypergraph graph(m_thd->mem_root, query_block);
1293 string trace;
1294 bool always_false = false;
1295 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
1296 EXPECT_FALSE(always_false);
1297
1298 SCOPED_TRACE(trace); // Prints out the trace on failure.
1299
1300 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
1301 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
1302
1303 ASSERT_EQ(3, graph.nodes.size());
1304 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
1305 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
1306 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
1307
1308 // t1/t2.
1309 ASSERT_EQ(2, graph.edges.size());
1310 EXPECT_EQ(0x01, graph.graph.edges[0].left);
1311 EXPECT_EQ(0x02, graph.graph.edges[0].right);
1312 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[0].expr->type);
1313 ASSERT_EQ(1, graph.edges[0].expr->equijoin_conditions.size());
1314 EXPECT_EQ("(t1.x = t2.x)",
1315 ItemToString(graph.edges[0].expr->equijoin_conditions[0]));
1316 EXPECT_EQ(0, graph.edges[0].expr->join_conditions.size());
1317
1318 // t2/t3 (semijoin). t1/t3 would also be fine. The really important part
1319 // is that we do not also have a t1/t2 or t1/t3 join conditions.
1320 EXPECT_EQ(0x02, graph.graph.edges[2].left);
1321 EXPECT_EQ(0x04, graph.graph.edges[2].right);
1322 EXPECT_EQ(RelationalExpression::SEMIJOIN, graph.edges[1].expr->type);
1323 ASSERT_EQ(1, graph.edges[1].expr->equijoin_conditions.size());
1324 EXPECT_EQ("(t2.x = t3.x)",
1325 ItemToString(graph.edges[1].expr->equijoin_conditions[0]));
1326 EXPECT_EQ(0, graph.edges[1].expr->join_conditions.size());
1327 }
1328
1329 TEST_F(MakeHypergraphTest, UnpushableMultipleEqualityCausesCycle) {
1330 Query_block *query_block = ParseAndResolve(
1331 "SELECT 1 FROM t1, t2, t3, t4 "
1332 // Two simple equalities that set up a join structure.
1333 "WHERE t1.y=t2.y AND t2.z=t3.z "
1334 // And then a multi-equality that is not cleanly pushable onto that
1335 // structure.
1336 "AND t1.x=t3.x AND t3.x=t4.x",
1337 /*nullable=*/false);
1338
1339 // Build multiple equalities from the WHERE condition.
1340 COND_EQUAL *cond_equal = nullptr;
1341 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
1342 &query_block->m_table_nest,
1343 &query_block->cond_value));
1344
1345 JoinHypergraph graph(m_thd->mem_root, query_block);
1346 string trace;
1347 bool always_false = false;
1348 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
1349 EXPECT_FALSE(always_false);
1350
1351 SCOPED_TRACE(trace); // Prints out the trace on failure.
1352
1353 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
1354 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
1355
1356 SortNodes(&graph);
1357
1358 ASSERT_EQ(4, graph.nodes.size());
1359 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
1360 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
1361 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
1362 EXPECT_STREQ("t4", graph.nodes[3].table->alias);
1363
1364 ASSERT_EQ(5, graph.edges.size());
1365
1366 // t1/t2.
1367 EXPECT_EQ(0x01, graph.graph.edges[0].left);
1368 EXPECT_EQ(0x02, graph.graph.edges[0].right);
1369 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[0].expr->type);
1370 ASSERT_EQ(1, graph.edges[0].expr->equijoin_conditions.size());
1371 EXPECT_EQ("(t1.y = t2.y)",
1372 ItemToString(graph.edges[0].expr->equijoin_conditions[0]));
1373 EXPECT_EQ(0, graph.edges[0].expr->join_conditions.size());
1374
1375 // t3/t2.
1376 EXPECT_EQ(0x04, graph.graph.edges[2].left);
1377 EXPECT_EQ(0x02, graph.graph.edges[2].right);
1378 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[1].expr->type);
1379 ASSERT_EQ(1, graph.edges[1].expr->equijoin_conditions.size());
1380 EXPECT_EQ("(t2.z = t3.z)",
1381 ItemToString(graph.edges[1].expr->equijoin_conditions[0]));
1382 EXPECT_EQ(0, graph.edges[1].expr->join_conditions.size());
1383
1384 // t4/t3 (the first of many cycle edges from the multiple equality).
1385 EXPECT_EQ(0x08, graph.graph.edges[4].left);
1386 EXPECT_EQ(0x04, graph.graph.edges[4].right);
1387 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[2].expr->type);
1388 ASSERT_EQ(1, graph.edges[2].expr->equijoin_conditions.size());
1389 EXPECT_EQ("(t4.x = t3.x)",
1390 ItemToString(graph.edges[2].expr->equijoin_conditions[0]));
1391 EXPECT_EQ(0, graph.edges[2].expr->join_conditions.size());
1392
1393 // t3/t1 (cycle edge).
1394 EXPECT_EQ(0x04, graph.graph.edges[6].left);
1395 EXPECT_EQ(0x01, graph.graph.edges[6].right);
1396 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[3].expr->type);
1397 ASSERT_EQ(1, graph.edges[3].expr->equijoin_conditions.size());
1398 EXPECT_EQ("(t1.x = t3.x)",
1399 ItemToString(graph.edges[3].expr->equijoin_conditions[0]));
1400 EXPECT_EQ(0, graph.edges[3].expr->join_conditions.size());
1401
1402 // t1/t4 (cycle edge within the cycle, comes from meshing).
1403 EXPECT_EQ(0x01, graph.graph.edges[8].left);
1404 EXPECT_EQ(0x08, graph.graph.edges[8].right);
1405 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[4].expr->type);
1406 ASSERT_EQ(1, graph.edges[4].expr->equijoin_conditions.size());
1407 EXPECT_EQ("(t1.x = t4.x)",
1408 ItemToString(graph.edges[4].expr->equijoin_conditions[0]));
1409 EXPECT_EQ(0, graph.edges[4].expr->join_conditions.size());
1410 }
1411
1412 TEST_F(MakeHypergraphTest, UnpushableMultipleEqualityWithSameTableTwice) {
1413 // The (t2.y, t3.x, t3.y, t4.x) multi-equality is unpushable
1414 // due to the t1.z = t4.w equality that's already set up;
1415 // we need to create a cycle from t2/t3/t4, while still not losing
1416 // the t3.x = t3.y condition.
1417 Query_block *query_block = ParseAndResolve(
1418 "SELECT 1 FROM t1, t1 AS t2, t1 AS t3, t1 AS t4 "
1419 "WHERE t1.z = t4.w "
1420 "AND t2.y = t3.x AND t3.x = t3.y AND t3.y = t4.x",
1421 /*nullable=*/false);
1422
1423 // Build multiple equalities from the WHERE condition.
1424 COND_EQUAL *cond_equal = nullptr;
1425 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
1426 &query_block->m_table_nest,
1427 &query_block->cond_value));
1428
1429 JoinHypergraph graph(m_thd->mem_root, query_block);
1430 string trace;
1431 bool always_false = false;
1432 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
1433 EXPECT_FALSE(always_false);
1434
1435 SCOPED_TRACE(trace); // Prints out the trace on failure.
1436
1437 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
1438 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
1439
1440 SortNodes(&graph);
1441
1442 ASSERT_EQ(4, graph.nodes.size());
1443 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
1444 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
1445 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
1446 EXPECT_STREQ("t4", graph.nodes[3].table->alias);
1447
1448 ASSERT_EQ(4, graph.edges.size());
1449
1450 // We only check that the given edges exist, and that we didn't lose
1451 // the t3.x = t3.y condition. All edges come from explicit
1452 // WHERE conditions.
1453
1454 // t2/t3. Note that we get both t2.y=t3.y and t2.y=t3.x;
1455 // they come from the same multi-equality and we've already
1456 // checked t3.x=t3.y, so one is redundant, but we can't
1457 // figure this out yet.
1458 EXPECT_EQ(0x02, graph.graph.edges[0].left);
1459 EXPECT_EQ(0x04, graph.graph.edges[0].right);
1460
1461 // t1/t4.
1462 EXPECT_EQ(0x01, graph.graph.edges[2].left);
1463 EXPECT_EQ(0x08, graph.graph.edges[2].right);
1464
1465 // t3/t4.
1466 EXPECT_EQ(0x04, graph.graph.edges[4].left);
1467 EXPECT_EQ(0x08, graph.graph.edges[4].right);
1468
1469 // t2/t4.
1470 EXPECT_EQ(0x02, graph.graph.edges[6].left);
1471 EXPECT_EQ(0x08, graph.graph.edges[6].right);
1472
1473 bool found_predicate = false;
1474 for (const Predicate &pred : graph.predicates) {
1475 if (ItemToString(pred.condition) == "(t3.x = t3.y)") {
1476 found_predicate = true;
1477 }
1478 }
1479 EXPECT_TRUE(found_predicate);
1480 }
1481
1482 TEST_F(MakeHypergraphTest, EqualityPropagationExpandsTopConjunction) {
1483 // The WHERE clause of the query is a subjunction in which the second leg is
1484 // found to be always false during equality propagation and removed.
1485 Query_block *query_block = ParseAndResolve(
1486 "SELECT 1 FROM t1, t2 WHERE "
1487 "(t1.x = t2.x AND t1.x < 10) OR (t1.y = t2.y AND t1.y < t2.y)",
1488 /*nullable=*/false);
1489
1490 // Build multiple equalities from the WHERE condition.
1491 COND_EQUAL *cond_equal = nullptr;
1492 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
1493 &query_block->m_table_nest,
1494 &query_block->cond_value));
1495
1496 JoinHypergraph graph(m_thd->mem_root, query_block);
1497 string trace;
1498 bool always_false = false;
1499 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
1500 EXPECT_FALSE(always_false);
1501
1502 SCOPED_TRACE(trace); // Prints out the trace on failure.
1503
1504 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
1505 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
1506
1507 SortNodes(&graph);
1508
1509 ASSERT_EQ(2, graph.nodes.size());
1510 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
1511 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
1512
1513 // Expect to find a simple equijoin condition and a table filter. The table
1514 // filter used to be part of the join condition, but it should not be.
1515 ASSERT_EQ(1, graph.edges.size());
1516 EXPECT_EQ("(t1.x = t2.x)",
1517 ItemsToString(graph.edges[0].expr->equijoin_conditions));
1518 EXPECT_EQ("(none)", ItemsToString(graph.edges[0].expr->join_conditions));
1519 ASSERT_EQ(1, graph.num_where_predicates);
1520 EXPECT_EQ("(t1.x < 10)", ItemToString(graph.predicates[0].condition));
1521 }
1522
1523 // Sets up a nonsensical query, but the point is that the multiple equality
1524 // on the antijoin can be resolved to either t1.x or t2.x, and it should choose
1525 // the same as is already there due to the inequality in order to not create
1526 // an overly broad hyperedge. This is similar to a situation in DBT-3 Q21.
1527 //
1528 // We test with the inequality referring to both tables in turn, to make sure
1529 // that we're not just getting lucky.
1530 using MakeHypergraphMultipleEqualParamTest = OptimizerTestWithParam<int>;
1531
1532 TEST_P(MakeHypergraphMultipleEqualParamTest,
1533 MultipleEqualityOnAntijoinGetsIdeallyResolved) {
1534 const int table_num = GetParam();
1535 string other_table = (table_num == 0) ? "t1" : "t2";
1536 string query_str =
1537 "SELECT 1 FROM t1, t2 WHERE t1.x=t2.x "
1538 "AND t1.x NOT IN (SELECT t3.x FROM t3 WHERE t3.y <> " +
1539 other_table + ".y + 1)";
1540 Query_block *query_block = ParseAndResolve(query_str.c_str(),
1541 /*nullable=*/false);
1542
1543 // Build multiple equalities from the WHERE condition.
1544 COND_EQUAL *cond_equal = nullptr;
1545 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
1546 &query_block->m_table_nest,
1547 &query_block->cond_value));
1548
1549 JoinHypergraph graph(m_thd->mem_root, query_block);
1550 string trace;
1551 bool always_false = false;
1552 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
1553 EXPECT_FALSE(always_false);
1554
1555 SCOPED_TRACE(trace); // Prints out the trace on failure.
1556
1557 EXPECT_EQ(graph.graph.nodes.size(), graph.nodes.size());
1558 EXPECT_EQ(graph.graph.edges.size(), 2 * graph.edges.size());
1559
1560 ASSERT_EQ(3, graph.nodes.size());
1561 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
1562 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
1563 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
1564
1565 // t1/t2. This one should not be too surprising.
1566 ASSERT_EQ(2, graph.edges.size());
1567 EXPECT_EQ(0x01, graph.graph.edges[0].left);
1568 EXPECT_EQ(0x02, graph.graph.edges[0].right);
1569 EXPECT_EQ(RelationalExpression::INNER_JOIN, graph.edges[0].expr->type);
1570 ASSERT_EQ(1, graph.edges[0].expr->equijoin_conditions.size());
1571 EXPECT_EQ("(t1.x = t2.x)",
1572 ItemToString(graph.edges[0].expr->equijoin_conditions[0]));
1573 EXPECT_EQ(0, graph.edges[0].expr->join_conditions.size());
1574
1575 // t1/t3 (antijoin) or t2/t3. The important part is that this should _not_
1576 // be a hyperedge.
1577 if (table_num == 0) {
1578 EXPECT_EQ(0x01, graph.graph.edges[2].left);
1579 } else {
1580 EXPECT_EQ(0x02, graph.graph.edges[2].left);
1581 }
1582 EXPECT_EQ(0x04, graph.graph.edges[2].right);
1583 EXPECT_EQ(RelationalExpression::ANTIJOIN, graph.edges[1].expr->type);
1584 ASSERT_EQ(1, graph.edges[1].expr->equijoin_conditions.size());
1585 ASSERT_EQ(1, graph.edges[1].expr->join_conditions.size());
1586 EXPECT_EQ("(" + other_table + ".x = t3.x)",
1587 ItemToString(graph.edges[1].expr->equijoin_conditions[0]));
1588 EXPECT_EQ("(t3.y <> (" + other_table + ".y + 1))",
1589 ItemToString(graph.edges[1].expr->join_conditions[0]));
1590 }
1591
1592 INSTANTIATE_TEST_SUITE_P(All, MakeHypergraphMultipleEqualParamTest,
1593 ::testing::Values(0, 1));
1594
1595 // An alias for better naming.
1596 // We don't verify costs; to do that, we'd probably need to mock out
1597 // the cost model.
1598 using HypergraphOptimizerTest = MakeHypergraphTest;
1599
1600 TEST_F(HypergraphOptimizerTest, SingleTable) {
1601 Query_block *query_block =
1602 ParseAndResolve("SELECT 1 FROM t1", /*nullable=*/true);
1603 m_fake_tables["t1"]->file->stats.records = 100;
1604
1605 string trace;
1606 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
1607 SCOPED_TRACE(trace); // Prints out the trace on failure.
1608
1609 ASSERT_EQ(AccessPath::TABLE_SCAN, root->type);
1610 EXPECT_EQ(m_fake_tables["t1"], root->table_scan().table);
1611 EXPECT_FLOAT_EQ(100.0F, root->num_output_rows());
1612 }
1613
1614 TEST_F(HypergraphOptimizerTest, NumberOfAccessPaths) {
1615 Query_block *query_block = ParseAndResolve(
1616 "SELECT 1 FROM t1 "
1617 "JOIN t2 ON t1.x=t2.x "
1618 "JOIN t3 ON t1.x=t3.x "
1619 "JOIN t4 ON t1.x=t4.x "
1620 "JOIN t5 ON t1.x=t5.x",
1621 /*nullable=*/true);
1622
1623 m_fake_tables["t1"]->file->stats.records = 101;
1624 m_fake_tables["t2"]->file->stats.records = 102;
1625 m_fake_tables["t3"]->file->stats.records = 103;
1626 m_fake_tables["t4"]->file->stats.records = 104;
1627 m_fake_tables["t5"]->file->stats.records = 105;
1628
1629 m_fake_tables["t1"]->file->stats.data_file_length = 100;
1630 m_fake_tables["t2"]->file->stats.data_file_length = 100;
1631 m_fake_tables["t3"]->file->stats.data_file_length = 100;
1632 m_fake_tables["t4"]->file->stats.data_file_length = 100;
1633 m_fake_tables["t5"]->file->stats.data_file_length = 100;
1634
1635 string trace;
1636 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
1637 SCOPED_TRACE(trace); // Prints out the trace on failure.
1638 EXPECT_TRUE(root != nullptr);
1639 std::smatch matches;
1640 std::regex_search(trace, matches,
1641 std::regex("keeping a total of ([0-9]+) access paths"));
1642 ASSERT_EQ(matches.size(), 2); // One match and one sub-match.
1643 int paths = std::stoi(matches[1]);
1644 EXPECT_LT(paths, 100);
1645 }
1646
1647 TEST_F(HypergraphOptimizerTest,
1648 PredicatePushdown) { // Also tests nested loop join.
1649 Query_block *query_block = ParseAndResolve(
1650 "SELECT 1 FROM t1 JOIN t2 ON t1.x=t2.x WHERE t2.y=3", /*nullable=*/true);
1651 m_fake_tables["t1"]->file->stats.records = 200;
1652 m_fake_tables["t2"]->file->stats.records = 3;
1653
1654 string trace;
1655 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
1656 SCOPED_TRACE(trace); // Prints out the trace on failure.
1657 // Prints out the query plan on failure.
1658 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
1659 /*is_root_of_join=*/true));
1660
1661 // The pushed-down filter makes the optimal plan be t2 on the left side,
1662 // with a nested loop.
1663 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
1664 EXPECT_EQ(JoinType::INNER, root->nested_loop_join().join_type);
1665 EXPECT_FLOAT_EQ(6.0F, root->num_output_rows()); // 60 rows, 10% selectivity.
1666
1667 // The condition should be posted directly on t2.
1668 AccessPath *outer = root->nested_loop_join().outer;
1669 ASSERT_EQ(AccessPath::FILTER, outer->type);
1670 EXPECT_EQ("(t2.y = 3)", ItemToString(outer->filter().condition));
1671 EXPECT_FLOAT_EQ(0.3F, outer->num_output_rows()); // 10% default selectivity.
1672
1673 AccessPath *outer_child = outer->filter().child;
1674 ASSERT_EQ(AccessPath::TABLE_SCAN, outer_child->type);
1675 EXPECT_EQ(m_fake_tables["t2"], outer_child->table_scan().table);
1676 EXPECT_FLOAT_EQ(3.0F, outer_child->num_output_rows());
1677
1678 // The inner part should have a join condition as a filter.
1679 AccessPath *inner = root->nested_loop_join().inner;
1680 ASSERT_EQ(AccessPath::FILTER, inner->type);
1681 EXPECT_EQ("(t1.x = t2.x)", ItemToString(inner->filter().condition));
1682 EXPECT_FLOAT_EQ(20.0F,
1683 inner->num_output_rows()); // 10% default selectivity.
1684
1685 AccessPath *inner_child = inner->filter().child;
1686 ASSERT_EQ(AccessPath::TABLE_SCAN, inner_child->type);
1687 EXPECT_EQ(m_fake_tables["t1"], inner_child->table_scan().table);
1688 }
1689
1690 TEST_F(HypergraphOptimizerTest, PredicatePushdownOuterJoin) {
1691 // The OR ... IS NULL part is to keep the LEFT JOIN from being simplified
1692 // to an inner join.
1693 Query_block *query_block = ParseAndResolve(
1694 "SELECT 1 FROM t1 LEFT JOIN t2 ON t1.x=t2.x "
1695 "WHERE t1.y=42 AND (t2.y=3 OR t2.y IS NULL)",
1696 /*nullable=*/true);
1697 m_fake_tables["t1"]->file->stats.records = 2000;
1698 m_fake_tables["t2"]->file->stats.records = 3;
1699
1700 string trace;
1701 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
1702 SCOPED_TRACE(trace); // Prints out the trace on failure.
1703
1704 // The t2 filter cannot be pushed down through the join, so it should be
1705 // on the root.
1706 ASSERT_EQ(AccessPath::FILTER, root->type);
1707 EXPECT_EQ("((t2.y = 3) or (t2.y is null))",
1708 ItemToString(root->filter().condition));
1709
1710 AccessPath *join = root->filter().child;
1711 ASSERT_EQ(AccessPath::HASH_JOIN, join->type);
1712 EXPECT_EQ(RelationalExpression::LEFT_JOIN,
1713 join->hash_join().join_predicate->expr->type);
1714 EXPECT_FLOAT_EQ(
1715 200.0F,
1716 join->num_output_rows()); // Selectivity overridden by outer join.
1717
1718 // The t1 condition should be pushed down to t1, since it's outer to the join.
1719 AccessPath *outer = join->hash_join().outer;
1720 ASSERT_EQ(AccessPath::FILTER, outer->type);
1721 EXPECT_EQ("(t1.y = 42)", ItemToString(outer->filter().condition));
1722
1723 AccessPath *t1 = outer->filter().child;
1724 ASSERT_EQ(AccessPath::TABLE_SCAN, t1->type);
1725 EXPECT_EQ(m_fake_tables["t1"], t1->table_scan().table);
1726
1727 AccessPath *inner = join->hash_join().inner;
1728 ASSERT_EQ(AccessPath::TABLE_SCAN, inner->type);
1729 EXPECT_EQ(m_fake_tables["t2"], inner->table_scan().table);
1730 EXPECT_FLOAT_EQ(3.0F, inner->num_output_rows());
1731 }
1732
1733 // NOTE: We don't test selectivity here, because it's not necessarily
1734 // correct.
1735 TEST_F(HypergraphOptimizerTest, PartialPredicatePushdown) {
1736 Query_block *query_block = ParseAndResolve(
1737 "SELECT 1 FROM t1, t2 "
1738 "WHERE (t1.x=1 AND t2.y=2) OR (t1.x=3 AND t2.y=4)",
1739 /*nullable=*/true);
1740 m_fake_tables["t1"]->file->stats.records = 200;
1741 m_fake_tables["t2"]->file->stats.records = 30;
1742
1743 string trace;
1744 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
1745 SCOPED_TRACE(trace); // Prints out the trace on failure.
1746 // Prints out the query plan on failure.
1747 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
1748 /*is_root_of_join=*/true));
1749
1750 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
1751 EXPECT_EQ(RelationalExpression::INNER_JOIN,
1752 root->hash_join().join_predicate->expr->type);
1753
1754 // The WHERE should have been pushed down to a join condition,
1755 // which should not be removed despite the partial pushdown.
1756 const Mem_root_array<Item *> &join_conditions =
1757 root->hash_join().join_predicate->expr->join_conditions;
1758 ASSERT_EQ(1, join_conditions.size());
1759 EXPECT_EQ("(((t1.x = 1) and (t2.y = 2)) or ((t1.x = 3) and (t2.y = 4)))",
1760 ItemToString(join_conditions[0]));
1761
1762 // t1 should have a partial condition.
1763 AccessPath *outer = root->hash_join().outer;
1764 ASSERT_EQ(AccessPath::FILTER, outer->type);
1765 EXPECT_EQ("((t1.x = 1) or (t1.x = 3))",
1766 ItemToString(outer->filter().condition));
1767
1768 AccessPath *outer_child = outer->filter().child;
1769 ASSERT_EQ(AccessPath::TABLE_SCAN, outer_child->type);
1770 EXPECT_EQ(m_fake_tables["t1"], outer_child->table_scan().table);
1771
1772 // t2 should have a different partial condition.
1773 AccessPath *inner = root->hash_join().inner;
1774 ASSERT_EQ(AccessPath::FILTER, inner->type);
1775 EXPECT_EQ("((t2.y = 2) or (t2.y = 4))",
1776 ItemToString(inner->filter().condition));
1777
1778 AccessPath *inner_child = inner->filter().child;
1779 ASSERT_EQ(AccessPath::TABLE_SCAN, inner_child->type);
1780 EXPECT_EQ(m_fake_tables["t2"], inner_child->table_scan().table);
1781 }
1782
1783 TEST_F(HypergraphOptimizerTest, PartialPredicatePushdownOuterJoin) {
1784 Query_block *query_block = ParseAndResolve(
1785 "SELECT 1 FROM t1 LEFT JOIN t2 ON "
1786 "(t1.x=1 AND t2.y=2) OR (t1.x=3 AND t2.y=4)",
1787 /*nullable=*/true);
1788 m_fake_tables["t1"]->file->stats.records = 200;
1789 m_fake_tables["t2"]->file->stats.records = 30;
1790
1791 string trace;
1792 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
1793 SCOPED_TRACE(trace); // Prints out the trace on failure.
1794 // Prints out the query plan on failure.
1795 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
1796 /*is_root_of_join=*/true));
1797
1798 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
1799 EXPECT_EQ(RelationalExpression::LEFT_JOIN,
1800 root->hash_join().join_predicate->expr->type);
1801
1802 // The join condition should still be there.
1803 const Mem_root_array<Item *> &join_conditions =
1804 root->hash_join().join_predicate->expr->join_conditions;
1805 ASSERT_EQ(1, join_conditions.size());
1806 EXPECT_EQ("(((t1.x = 1) and (t2.y = 2)) or ((t1.x = 3) and (t2.y = 4)))",
1807 ItemToString(join_conditions[0]));
1808
1809 // t1 should _not_ have a partial condition, as it would
1810 // cause NULL-complemented rows to be eaten.
1811 AccessPath *outer = root->hash_join().outer;
1812 ASSERT_EQ(AccessPath::TABLE_SCAN, outer->type);
1813 EXPECT_EQ(m_fake_tables["t1"], outer->table_scan().table);
1814
1815 // t2 should have a partial condition.
1816 AccessPath *inner = root->hash_join().inner;
1817 ASSERT_EQ(AccessPath::FILTER, inner->type);
1818 EXPECT_EQ("((t2.y = 2) or (t2.y = 4))",
1819 ItemToString(inner->filter().condition));
1820
1821 AccessPath *inner_child = inner->filter().child;
1822 ASSERT_EQ(AccessPath::TABLE_SCAN, inner_child->type);
1823 EXPECT_EQ(m_fake_tables["t2"], inner_child->table_scan().table);
1824 }
1825
1826 TEST_F(HypergraphOptimizerTest, PredicatePushdownToRef) {
1827 Query_block *query_block =
1828 ParseAndResolve("SELECT 1 FROM t1 WHERE t1.x=3", /*nullable=*/true);
1829 Fake_TABLE *t1 = m_fake_tables["t1"];
1830 t1->create_index(t1->field[0], t1->field[1], /*unique=*/true);
1831 m_fake_tables["t1"]->file->stats.records = 100;
1832 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
1833
1834 string trace;
1835 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
1836 SCOPED_TRACE(trace); // Prints out the trace on failure.
1837 // Prints out the query plan on failure.
1838 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
1839 /*is_root_of_join=*/true));
1840
1841 // The condition should be gone, and only ref access should be in its place.
1842 // There shouldn't be EQ_REF, since we only have a partial match.
1843 ASSERT_EQ(AccessPath::REF, root->type);
1844 EXPECT_EQ(0, root->ref().ref->key);
1845 EXPECT_EQ(5, root->ref().ref->key_length);
1846 EXPECT_EQ(1, root->ref().ref->key_parts);
1847 EXPECT_FLOAT_EQ(10.0, root->num_output_rows());
1848 }
1849
1850 TEST_F(HypergraphOptimizerTest, NotPredicatePushdownToRef) {
1851 Query_block *query_block =
1852 ParseAndResolve("SELECT 1 FROM t1 WHERE t1.y=3", /*nullable=*/true);
1853 Fake_TABLE *t1 = m_fake_tables["t1"];
1854 t1->create_index(t1->field[0], t1->field[1], /*unique=*/true);
1855
1856 string trace;
1857 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
1858 SCOPED_TRACE(trace); // Prints out the trace on failure.
1859 // Prints out the query plan on failure.
1860 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
1861 /*is_root_of_join=*/true));
1862
1863 // t1.y can't be pushed since t1.x wasn't.
1864 ASSERT_EQ(AccessPath::FILTER, root->type);
1865 EXPECT_EQ("(t1.y = 3)", ItemToString(root->filter().condition));
1866 }
1867
1868 TEST_F(HypergraphOptimizerTest, MultiPartPredicatePushdownToRef) {
1869 Query_block *query_block = ParseAndResolve(
1870 "SELECT 1 FROM t1 WHERE t1.y=3 AND t1.x=2", /*nullable=*/true);
1871 Fake_TABLE *t1 = m_fake_tables["t1"];
1872 t1->create_index(t1->field[0], t1->field[1], /*unique=*/true);
1873
1874 string trace;
1875 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
1876 SCOPED_TRACE(trace); // Prints out the trace on failure.
1877 // Prints out the query plan on failure.
1878 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
1879 /*is_root_of_join=*/true));
1880
1881 // Both should be pushed, and we should now use the unique index.
1882 ASSERT_EQ(AccessPath::EQ_REF, root->type);
1883 EXPECT_EQ(0, root->eq_ref().ref->key);
1884 EXPECT_EQ(10, root->eq_ref().ref->key_length);
1885 EXPECT_EQ(2, root->eq_ref().ref->key_parts);
1886 }
1887
1888 TEST_F(HypergraphOptimizerTest, JoinConditionToRef) {
1889 Query_block *query_block = ParseAndResolve(
1890 "SELECT 1 FROM t1 LEFT JOIN (t2 JOIN t3 ON t2.y=t3.y) ON t1.x=t3.x",
1891 /*nullable=*/true);
1892 Fake_TABLE *t2 = m_fake_tables["t2"];
1893 Fake_TABLE *t3 = m_fake_tables["t3"];
1894 t2->create_index(t2->field[1], /*column2=*/nullptr, /*unique=*/false);
1895 t3->create_index(t3->field[0], t3->field[1], /*unique=*/true);
1896
1897 // Hash join between t2/t3 is attractive, but hash join between t1 and t2/t3
1898 // should not be.
1899 m_fake_tables["t1"]->file->stats.records = 1000000;
1900 m_fake_tables["t2"]->file->stats.records = 100;
1901 m_fake_tables["t3"]->file->stats.records = 1000;
1902 m_fake_tables["t3"]->file->stats.data_file_length = 1e6;
1903
1904 string trace;
1905 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
1906 SCOPED_TRACE(trace); // Prints out the trace on failure.
1907 // Prints out the query plan on failure.
1908 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
1909 /*is_root_of_join=*/true));
1910
1911 // The optimal plan consists of only nested-loop joins.
1912 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
1913 EXPECT_EQ(JoinType::OUTER, root->nested_loop_join().join_type);
1914
1915 AccessPath *outer = root->nested_loop_join().outer;
1916 ASSERT_EQ(AccessPath::TABLE_SCAN, outer->type);
1917 EXPECT_EQ(m_fake_tables["t1"], outer->table_scan().table);
1918 EXPECT_FLOAT_EQ(1000000.0F, outer->num_output_rows());
1919
1920 // The inner part should also be nested-loop.
1921 AccessPath *inner = root->nested_loop_join().inner;
1922 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, inner->type);
1923 EXPECT_EQ(JoinType::INNER, inner->nested_loop_join().join_type);
1924
1925 // We should have t2 on the left, and t3 on the right
1926 // (or we couldn't use the entire unique index).
1927 AccessPath *t2_path = inner->nested_loop_join().outer;
1928 ASSERT_EQ(AccessPath::TABLE_SCAN, t2_path->type);
1929 EXPECT_EQ(m_fake_tables["t2"], t2_path->table_scan().table);
1930 EXPECT_FLOAT_EQ(100.0F, t2_path->num_output_rows());
1931
1932 // t3 should use the unique index, and thus be capped at one row.
1933 AccessPath *t3_path = inner->nested_loop_join().inner;
1934 ASSERT_EQ(AccessPath::EQ_REF, t3_path->type);
1935 EXPECT_EQ(m_fake_tables["t3"], t3_path->eq_ref().table);
1936 EXPECT_FLOAT_EQ(1.0F, t3_path->num_output_rows());
1937
1938 // t2/t3 is 100 * 1, obviously.
1939 EXPECT_FLOAT_EQ(100.0F, inner->num_output_rows());
1940
1941 // The root should have t1 multiplied by t2/t3;
1942 // since the join predicate is already applied (and subsumed),
1943 // we should have no further reduction from it.
1944 EXPECT_FLOAT_EQ(outer->num_output_rows() * inner->num_output_rows(),
1945 root->num_output_rows());
1946 }
1947
1948 TEST_F(HypergraphOptimizerTest, PreferWidestEqRefKey) {
1949 Query_block *query_block =
1950 ParseAndResolve("SELECT 1 FROM t1 WHERE t1.x = 1 AND t1.y = 2",
1951 /*nullable=*/true);
1952
1953 Fake_TABLE *t1 = m_fake_tables["t1"];
1954
1955 // Create three unique indexes.
1956 const int key_x =
1957 t1->create_index(t1->field[0], /*column2=*/nullptr, /*unique=*/true);
1958 const int key_xy =
1959 t1->create_index(t1->field[0], t1->field[1], /*unique=*/true);
1960 const int key_y =
1961 t1->create_index(t1->field[1], /*column2=*/nullptr, /*unique=*/true);
1962
1963 EXPECT_EQ(0, key_x);
1964 EXPECT_EQ(1, key_xy);
1965 EXPECT_EQ(2, key_y);
1966
1967 t1->file->stats.records = 10000;
1968 t1->file->stats.data_file_length = 1e6;
1969
1970 string trace;
1971 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
1972 SCOPED_TRACE(trace); // Prints out the trace on failure.
1973 // Prints out the query plan on failure.
1974 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
1975 /*is_root_of_join=*/true));
1976
1977 // Expect that we use the widest key. That is, we should pick an EQ_REF on the
1978 // (x, y) index with no filter, not an EQ_REF on the single-column indexes
1979 // with a filter on top.
1980 ASSERT_EQ(AccessPath::EQ_REF, root->type);
1981 EXPECT_EQ(key_xy, root->eq_ref().ref->key);
1982 }
1983
1984 // Verify that we can push ref access into a hash join's hash table.
1985 TEST_F(HypergraphOptimizerTest, RefIntoHashJoin) {
1986 Query_block *query_block = ParseAndResolve(
1987 "SELECT 1 FROM t1 LEFT JOIN (t2 JOIN t3 ON t2.y=t3.y) ON t1.x=t3.x",
1988 /*nullable=*/true);
1989 Fake_TABLE *t3 = m_fake_tables["t3"];
1990 t3->create_index(t3->field[0], /*column2=*/nullptr, /*unique=*/false);
1991 ulong rec_per_key_int[] = {1};
1992 float rec_per_key[] = {0.001f};
1993 t3->key_info[0].set_rec_per_key_array(rec_per_key_int, rec_per_key);
1994
1995 // Hash join between t2/t3 is attractive, but hash join between t1 and t2/t3
1996 // should not be.
1997 m_fake_tables["t1"]->file->stats.records = 10;
1998 m_fake_tables["t2"]->file->stats.records = 10000;
1999 m_fake_tables["t3"]->file->stats.records = 10000000;
2000 m_fake_tables["t3"]->file->stats.data_file_length = 1e6;
2001
2002 // Forbid changing the order of t2/t3, just to get the plan we want.
2003 // (In a more real situation, we could have e.g. an antijoin outside a left
2004 // join, but it's a bit tricky to set up in a test.)
2005 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
2006 hton->secondary_engine_flags =
2007 MakeSecondaryEngineFlags(SecondaryEngineFlag::SUPPORTS_HASH_JOIN,
2008 SecondaryEngineFlag::SUPPORTS_NESTED_LOOP_JOIN);
2009 hton->secondary_engine_modify_access_path_cost =
2010 [](THD *, const JoinHypergraph &, AccessPath *path) {
2011 if (path->type == AccessPath::NESTED_LOOP_JOIN) {
2012 AccessPath *outer = path->nested_loop_join().outer;
2013 if (outer->type == AccessPath::TABLE_SCAN &&
2014 strcmp(outer->table_scan().table->alias, "t3") == 0) {
2015 return true;
2016 }
2017 if (outer->type == AccessPath::REF &&
2018 strcmp(outer->ref().table->alias, "t3") == 0) {
2019 return true;
2020 }
2021 }
2022 return false;
2023 };
2024
2025 string trace;
2026 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
2027 SCOPED_TRACE(trace); // Prints out the trace on failure.
2028 // Prints out the query plan on failure.
2029 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2030 /*is_root_of_join=*/true));
2031
2032 // The t1-{t2,t3} join should be nested loop.
2033 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
2034 EXPECT_EQ(JoinType::OUTER, root->nested_loop_join().join_type);
2035
2036 AccessPath *outer = root->nested_loop_join().outer;
2037 ASSERT_EQ(AccessPath::TABLE_SCAN, outer->type);
2038 EXPECT_EQ(m_fake_tables["t1"], outer->table_scan().table);
2039
2040 // The inner part, however, should be a hash join.
2041 AccessPath *inner = root->nested_loop_join().inner;
2042 ASSERT_EQ(AccessPath::HASH_JOIN, inner->type);
2043 EXPECT_EQ(RelationalExpression::INNER_JOIN,
2044 inner->hash_join().join_predicate->expr->type);
2045
2046 // ...and t3 should be on the right, as a ref access against t1.
2047 AccessPath *t3_path = inner->hash_join().inner;
2048 ASSERT_EQ(AccessPath::REF, t3_path->type);
2049 EXPECT_EQ(m_fake_tables["t3"], t3_path->ref().table);
2050 EXPECT_EQ(0, t3_path->ref().ref->key);
2051 EXPECT_EQ("t1.x", ItemToString(t3_path->ref().ref->items[0]));
2052 }
2053
2054 // Verify that we can make sargable predicates out of multiple equalities.
2055 TEST_F(HypergraphOptimizerTest, MultiEqualitySargable) {
2056 Query_block *query_block = ParseAndResolve(
2057 "SELECT 1 FROM t1, t2, t3 WHERE t1.x = t2.x AND t2.x = t3.x",
2058 /*nullable=*/true);
2059 Fake_TABLE *t2 = m_fake_tables["t2"];
2060 Fake_TABLE *t3 = m_fake_tables["t3"];
2061 t2->create_index(t2->field[0], /*column2=*/nullptr, /*unique=*/true);
2062 t3->create_index(t3->field[0], /*column2=*/nullptr, /*unique=*/true);
2063
2064 // Build multiple equalities from the WHERE condition.
2065 COND_EQUAL *cond_equal = nullptr;
2066 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
2067 &query_block->m_table_nest,
2068 &query_block->cond_value));
2069
2070 // The logical plan should be t1/t2/t3, with index lookups on t2 and t3.
2071 m_fake_tables["t1"]->file->stats.records = 100;
2072 m_fake_tables["t2"]->file->stats.records = 10000;
2073 m_fake_tables["t3"]->file->stats.records = 1000000;
2074
2075 string trace;
2076 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
2077 SCOPED_TRACE(trace); // Prints out the trace on failure.
2078 // Prints out the query plan on failure.
2079 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2080 /*is_root_of_join=*/true));
2081
2082 // The optimal plan consists of only nested-loop joins (notably left-deep).
2083 // We don't verify costs.
2084 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
2085 EXPECT_EQ(JoinType::INNER, root->nested_loop_join().join_type);
2086
2087 // The inner part should also be nested-loop.
2088 AccessPath *outer = root->nested_loop_join().outer;
2089 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, outer->type);
2090 EXPECT_EQ(JoinType::INNER, outer->nested_loop_join().join_type);
2091
2092 // t1 is on the very left side.
2093 AccessPath *t1 = outer->nested_loop_join().outer;
2094 ASSERT_EQ(AccessPath::TABLE_SCAN, t1->type);
2095 EXPECT_EQ(m_fake_tables["t1"], t1->table_scan().table);
2096
2097 // We have two index lookups; t2 and t3. We don't care about the order.
2098 ASSERT_EQ(AccessPath::EQ_REF, outer->nested_loop_join().inner->type);
2099 ASSERT_EQ(AccessPath::EQ_REF, root->nested_loop_join().inner->type);
2100 }
2101
2102 TEST_F(HypergraphOptimizerTest, DoNotApplyBothSargableJoinAndFilterJoin) {
2103 Query_block *query_block = ParseAndResolve(
2104 "SELECT 1 FROM t1, t2, t3, t4 WHERE t1.x = t2.x AND t2.x = t3.x",
2105 /*nullable=*/true);
2106 Fake_TABLE *t1 = m_fake_tables["t1"];
2107 t1->create_index(t1->field[0], /*column2=*/nullptr, /*unique=*/false);
2108
2109 // Build multiple equalities from the WHERE condition.
2110 COND_EQUAL *cond_equal = nullptr;
2111 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
2112 &query_block->m_table_nest,
2113 &query_block->cond_value));
2114
2115 // The logical plan should be to hash-join t2/t3, then nestloop-join
2116 // against the index on t1. The t4 table somehow needs to be present
2117 // to trigger the issue; it doesn't really matter whether it's on the
2118 // left or right side (since it doesn't have a join condition),
2119 // but it happens to be put on the right.
2120 m_fake_tables["t1"]->file->stats.records = 100;
2121 m_fake_tables["t2"]->file->stats.records = 100000000;
2122 m_fake_tables["t3"]->file->stats.records = 1000000;
2123 m_fake_tables["t4"]->file->stats.records = 10000;
2124
2125 // Incentivize ref access on t1, just to get the plan we want.
2126 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
2127 hton->secondary_engine_flags =
2128 MakeSecondaryEngineFlags(SecondaryEngineFlag::SUPPORTS_HASH_JOIN,
2129 SecondaryEngineFlag::SUPPORTS_NESTED_LOOP_JOIN);
2130 hton->secondary_engine_modify_access_path_cost =
2131 [](THD *, const JoinHypergraph &, AccessPath *path) {
2132 if (path->type == AccessPath::REF &&
2133 strcmp(path->ref().table->alias, "t1") == 0) {
2134 path->cost *= 0.01;
2135 path->init_cost *= 0.01;
2136 path->cost_before_filter *= 0.01;
2137 }
2138 return false;
2139 };
2140
2141 string trace;
2142 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
2143 SCOPED_TRACE(trace); // Prints out the trace on failure.
2144 // Prints out the query plan on failure.
2145 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2146 /*is_root_of_join=*/true));
2147
2148 // t4 needs to come in on the top (since we've put it as a Cartesian product);
2149 // either left or right side. It happens to be on the right.
2150 // We don't verify costs.
2151 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
2152 EXPECT_EQ(JoinType::INNER, root->nested_loop_join().join_type);
2153
2154 AccessPath *inner = root->nested_loop_join().inner;
2155 ASSERT_EQ(AccessPath::TABLE_SCAN, inner->type);
2156 EXPECT_EQ(m_fake_tables["t4"], inner->table_scan().table);
2157
2158 // Now for the meat of the plan. There should be a nested loop,
2159 // with t2/t3 on the inside and t1 on the outside.
2160 AccessPath *outer = root->nested_loop_join().outer;
2161 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, outer->type);
2162
2163 // We don't check the t2/t3 part very thoroughly.
2164 EXPECT_EQ(AccessPath::HASH_JOIN, outer->nested_loop_join().outer->type);
2165
2166 // Now for the point of the test: We should have t1 on the inner side,
2167 // with t1=t2 pushed down into the index, and it should _not_ have a t1=t3
2168 // filter; even though it would seemingly be attractive to join t1=t3 against
2169 // the ref access, that would be double-counting the selectivity and thus
2170 // not permitted. (Well, it would be permitted, but we'd have to add code
2171 // not to apply the selectivity twice, and then it would just be extra cost
2172 // applying a redundant filter.)
2173 AccessPath *inner_inner = outer->nested_loop_join().inner;
2174 ASSERT_EQ(AccessPath::REF, inner_inner->type);
2175 EXPECT_STREQ("t1", inner_inner->ref().table->alias);
2176 EXPECT_EQ(0, inner_inner->ref().ref->key);
2177 EXPECT_EQ("t2.x", ItemToString(inner_inner->ref().ref->items[0]));
2178 }
2179
2180 // The selectivity of sargable join predicates could in some cases be
2181 // double-counted when the sargable join predicate was part of a cycle in the
2182 // join graph.
2183 TEST_F(HypergraphOptimizerTest, SargableJoinPredicateSelectivity) {
2184 // The inconsistent row estimates were only seen if the sargable predicate
2185 // t1.x=t2.x was not fully subsumed by a ref access on t1.x. Achieved by
2186 // giving t2.x a different type (UNSIGNED) than t1.x (SIGNED).
2187 Mock_field_long t2_x("x", /*is_nullable=*/false, /*is_unsigned=*/true);
2188 Mock_field_long t2_y("y", /*is_nullable=*/false, /*is_unsigned=*/false);
2189 Fake_TABLE *t2 = new (m_thd->mem_root) Fake_TABLE(&t2_x, &t2_y);
2190 m_fake_tables["t2"] = t2;
2191 t2->set_created();
2192
2193 Query_block *query_block = ParseAndResolve(
2194 "SELECT 1 FROM t1, t2, t3 "
2195 "WHERE t1.x = t2.x AND t1.y = t3.x AND t2.y = t3.y",
2196 /*nullable=*/false);
2197
2198 // Add an index on t1(x) to make t1.x=t2.x sargable.
2199 Fake_TABLE *t1 = m_fake_tables["t1"];
2200 const int t1_idx =
2201 t1->create_index(t1->field[0], /*column2=*/nullptr, /*unique=*/false);
2202 ulong rec_per_key_int[] = {1};
2203 float rec_per_key[] = {1.0f};
2204 t1->key_info[t1_idx].set_rec_per_key_array(rec_per_key_int, rec_per_key);
2205
2206 Fake_TABLE *t3 = m_fake_tables["t3"];
2207 t1->file->stats.records = 1000;
2208 t1->file->stats.data_file_length = 1e6;
2209 t2->file->stats.records = 100;
2210 t2->file->stats.data_file_length = 1e5;
2211 t3->file->stats.records = 10;
2212 t3->file->stats.data_file_length = 1e4;
2213
2214 string trace;
2215 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
2216 SCOPED_TRACE(trace); // Prints out the trace on failure.
2217 // Prints out the query plan on failure.
2218 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2219 /*is_root_of_join=*/true));
2220
2221 // We don't really care about which exact plan is chosen, but the inconsistent
2222 // row estimates were caused by REF access, so make sure our plan has one.
2223 AccessPath *ref_path = nullptr;
2224 WalkAccessPaths(root, query_block->join,
2225 WalkAccessPathPolicy::STOP_AT_MATERIALIZATION,
2226 [&ref_path](AccessPath *path, const JOIN *) {
2227 if (path->type == AccessPath::REF) {
2228 EXPECT_EQ(nullptr, ref_path);
2229 ref_path = path;
2230 }
2231 return false;
2232 });
2233 ASSERT_NE(nullptr, ref_path);
2234 EXPECT_STREQ("t1", ref_path->ref().table->alias);
2235 EXPECT_EQ(string("t2.x"), ItemToString(ref_path->ref().ref->items[0]));
2236
2237 // We do care about the estimated cardinality of the result. It used to be
2238 // much too low because the selectivity of the sargable predicate was applied
2239 // twice.
2240 EXPECT_FLOAT_EQ(
2241 /* Rows from t1: */ rec_per_key[0] *
2242 /* Rows from t2: */ t2->file->stats.records * COND_FILTER_EQUALITY *
2243 /* Rows from t3: */ t3->file->stats.records * COND_FILTER_EQUALITY,
2244 root->num_output_rows());
2245 }
2246
2247 TEST_F(HypergraphOptimizerTest, SargableJoinPredicateWithTypeMismatch) {
2248 // Give t1.x a different type than t2.x.
2249 Mock_field_varstring t1_x(/*share=*/nullptr, /*name=*/"x",
2250 /*char_len=*/100, /*is_nullable=*/true);
2251 Fake_TABLE *t1 = new (m_thd->mem_root) Fake_TABLE(&t1_x);
2252 m_fake_tables["t1"] = t1;
2253
2254 Query_block *query_block = ParseAndResolve(
2255 "SELECT 1 FROM t1, t2 WHERE t1.x = t2.x", /*nullable=*/true);
2256
2257 // Add an index on t2(x) to make the join predicate sargable.
2258 Fake_TABLE *t2 = m_fake_tables["t2"];
2259 t2->create_index(t2->field[0], /*column2=*/nullptr, /*unique=*/true);
2260
2261 // Set up sizes to make index access on t2 preferable.
2262 t1->file->stats.records = 100;
2263 t1->file->stats.data_file_length = 1e5;
2264 t2->file->stats.records = 100000;
2265 t2->file->stats.data_file_length = 1e7;
2266
2267 string trace;
2268 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
2269 SCOPED_TRACE(trace); // Prints out the trace on failure.
2270 // Prints out the query plan on failure.
2271 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2272 /*is_root_of_join=*/true));
2273
2274 // Expect NLJ(t1, EQ_REF(t2)). Because of the type mismatch between t1.x and
2275 // t2.x, a filter is needed on top of the EQ_REF to make sure no false matches
2276 // are returned.
2277 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
2278 ASSERT_EQ(AccessPath::FILTER, root->nested_loop_join().inner->type);
2279 EXPECT_EQ("(cast(t1.x as double) = cast(t2.x as double))",
2280 ItemToString(root->nested_loop_join().inner->filter().condition));
2281 ASSERT_EQ(AccessPath::EQ_REF,
2282 root->nested_loop_join().inner->filter().child->type);
2283 EXPECT_STREQ(
2284 "t2",
2285 root->nested_loop_join().inner->filter().child->eq_ref().table->alias);
2286 }
2287
2288 // Test that we can use index for join conditions on the form t1.field =
2289 // f(t2.field), not only for t1.field = t2.field.
2290 TEST_F(HypergraphOptimizerTest, SargableJoinPredicateWithFunction) {
2291 Query_block *query_block = ParseAndResolve(
2292 "SELECT 1 FROM t1, t2 WHERE t1.x = t2.x + 1", /*nullable=*/true);
2293
2294 Fake_TABLE *t1 = m_fake_tables["t1"];
2295 Fake_TABLE *t2 = m_fake_tables["t2"];
2296
2297 // Add an index on t1.x to make the join predicate sargable.
2298 t1->create_index(t1->field[0], /*column2=*/nullptr, /*unique=*/true);
2299
2300 // Set up sizes to make index access on t1 preferable.
2301 t1->file->stats.records = 100000;
2302 t1->file->stats.data_file_length = 1e7;
2303 t2->file->stats.records = 100;
2304 t2->file->stats.data_file_length = 1e5;
2305
2306 string trace;
2307 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
2308 SCOPED_TRACE(trace); // Prints out the trace on failure.
2309 // Prints out the query plan on failure.
2310 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2311 /*is_root_of_join=*/true));
2312
2313 // Expect NLJ(t2, EQ_REF(t1)). A (redundant?) filter is put on top of the
2314 // index lookup to protect against inexact conversion from t2.x+1 to INT (see
2315 // ref_lookup_subsumes_comparison()).
2316 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
2317 ASSERT_EQ(AccessPath::FILTER, root->nested_loop_join().inner->type);
2318 EXPECT_EQ("(t1.x = (t2.x + 1))",
2319 ItemToString(root->nested_loop_join().inner->filter().condition));
2320 ASSERT_EQ(AccessPath::EQ_REF,
2321 root->nested_loop_join().inner->filter().child->type);
2322 EXPECT_STREQ(
2323 "t1",
2324 root->nested_loop_join().inner->filter().child->eq_ref().table->alias);
2325 }
2326
2327 TEST_F(HypergraphOptimizerTest, SargableSubquery) {
2328 Query_block *query_block = ParseAndResolve(
2329 "SELECT 1 FROM t1 WHERE t1.x = (SELECT 1 FROM t2)", /*nullable=*/true);
2330
2331 // Plan the subquery first.
2332 {
2333 Query_block *subquery =
2334 query_block->first_inner_query_expression()->first_query_block();
2335 ResolveQueryBlock(m_thd, subquery, /*nullable=*/true, &m_fake_tables);
2336 string trace;
2337 AccessPath *subquery_path =
2338 FindBestQueryPlanAndFinalize(m_thd, subquery, &trace);
2339 SCOPED_TRACE(trace); // Prints out the trace on failure.
2340 // Prints out the query plan on failure.
2341 SCOPED_TRACE(PrintQueryPlan(0, subquery_path, subquery->join,
2342 /*is_root_of_join=*/true));
2343 EXPECT_EQ(AccessPath::TABLE_SCAN, subquery_path->type);
2344 }
2345
2346 // Add an index on t1.x to make the predicate sargable.
2347 Fake_TABLE *t1 = m_fake_tables["t1"];
2348 t1->create_index(t1->field[0], /*column2=*/nullptr, /*unique=*/true);
2349
2350 // Set up sizes to make index lookup preferable.
2351 t1->file->stats.records = 100000;
2352 t1->file->stats.data_file_length = 1e7;
2353
2354 string trace;
2355 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
2356 SCOPED_TRACE(trace); // Prints out the trace on failure.
2357 // Prints out the query plan on failure.
2358 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2359 /*is_root_of_join=*/true));
2360
2361 // Expect an index lookup with a (redundant?) filter on top.
2362 ASSERT_EQ(AccessPath::FILTER, root->type);
2363 EXPECT_EQ("(t1.x = (select #2))", ItemToString(root->filter().condition));
2364 ASSERT_EQ(AccessPath::EQ_REF, root->filter().child->type);
2365 EXPECT_EQ("(select #2)",
2366 ItemToString(root->filter().child->eq_ref().ref->items[0]));
2367 EXPECT_STREQ("t1", root->filter().child->eq_ref().table->alias);
2368 }
2369
2370 TEST_F(HypergraphOptimizerTest, SargableOuterReference) {
2371 Query_block *query_block = ParseAndResolve(
2372 "SELECT 1 FROM t1 WHERE (SELECT t2.y FROM t2 WHERE t2.x = t1.x)",
2373 /*nullable=*/true);
2374
2375 Query_block *subquery =
2376 query_block->first_inner_query_expression()->first_query_block();
2377 ResolveQueryBlock(m_thd, subquery, /*nullable=*/true, &m_fake_tables);
2378
2379 // Add an index on t2.x to make the predicate in the subquery sargable.
2380 Fake_TABLE *t2 = m_fake_tables["t2"];
2381 t2->create_index(t2->field[0], /*column2=*/nullptr, /*unique=*/true);
2382 t2->file->stats.records = 100000;
2383 t2->file->stats.data_file_length = 1e7;
2384
2385 string trace;
2386 AccessPath *subquery_path = FindBestQueryPlan(m_thd, subquery, &trace);
2387 SCOPED_TRACE(trace); // Prints out the trace on failure.
2388 // Prints out the query plan on failure.
2389 SCOPED_TRACE(PrintQueryPlan(0, subquery_path, subquery->join,
2390 /*is_root_of_join=*/true));
2391
2392 // Expect the subquery to become an index lookup using the outer reference as
2393 // a constant value.
2394 ASSERT_EQ(AccessPath::EQ_REF, subquery_path->type);
2395 EXPECT_STREQ("t2", subquery_path->eq_ref().table->alias);
2396 EXPECT_EQ("t1.x", ItemToString(subquery_path->eq_ref().ref->items[0]));
2397 EXPECT_TRUE(subquery_path->eq_ref().ref->items[0]->is_outer_reference());
2398 }
2399
2400 TEST_F(HypergraphOptimizerTest, SargableHyperpredicate) {
2401 Query_block *query_block = ParseAndResolve(
2402 "SELECT 1 FROM t1, t2, t3 WHERE t1.x = t2.x + t3.x AND t2.y = t3.y",
2403 /*nullable=*/true);
2404
2405 Fake_TABLE *t1 = m_fake_tables["t1"];
2406 Fake_TABLE *t2 = m_fake_tables["t2"];
2407 Fake_TABLE *t3 = m_fake_tables["t3"];
2408
2409 // Add an index on t1.x to make the join predicate sargable.
2410 t1->create_index(t1->field[0], /*column2=*/nullptr, /*unique=*/true);
2411
2412 // Set up sizes to make index access on t1 preferable.
2413 t1->file->stats.records = 100000;
2414 t1->file->stats.data_file_length = 1e7;
2415 t2->file->stats.records = 100;
2416 t2->file->stats.data_file_length = 1e5;
2417 t3->file->stats.records = 200;
2418 t3->file->stats.data_file_length = 2e5;
2419
2420 string trace;
2421 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
2422 SCOPED_TRACE(trace); // Prints out the trace on failure.
2423 // Prints out the query plan on failure.
2424 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2425 /*is_root_of_join=*/true));
2426
2427 // Expect the join predicate t1.x = t2.x + t3.x to be sargable and result in
2428 // an index lookup, giving this plan: NLJ(HJ(t3, t2), FILTER(EQ_REF(t1)))
2429 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
2430 EXPECT_EQ(AccessPath::HASH_JOIN, root->nested_loop_join().outer->type);
2431
2432 AccessPath *inner = root->nested_loop_join().inner;
2433 ASSERT_EQ(AccessPath::FILTER, inner->type);
2434 EXPECT_EQ("(t1.x = (t2.x + t3.x))", ItemToString(inner->filter().condition));
2435
2436 AccessPath *index_path = inner->filter().child;
2437 ASSERT_EQ(AccessPath::EQ_REF, index_path->type);
2438 EXPECT_STREQ("t1", index_path->eq_ref().table->alias);
2439 EXPECT_EQ("(t2.x + t3.x)", ItemToString(index_path->eq_ref().ref->items[0]));
2440 }
2441
2442 TEST_F(HypergraphOptimizerTest, AntiJoinGetsSameEstimateWithAndWithoutIndex) {
2443 double ref_output_rows = 0.0;
2444 for (bool has_index : {false, true}) {
2445 Query_block *query_block = ParseAndResolve(
2446 "SELECT 1 FROM t1 WHERE t1.x NOT IN ( SELECT t2.x FROM t2 )",
2447 /*nullable=*/false);
2448
2449 m_fake_tables["t1"]->file->stats.records = 10000;
2450
2451 Fake_TABLE *t2 = m_fake_tables["t2"];
2452 if (has_index) {
2453 t2->create_index(t2->field[0], /*column2=*/nullptr, /*unique=*/false);
2454 }
2455 t2->file->stats.records = 100;
2456
2457 string trace;
2458 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
2459 SCOPED_TRACE(trace); // Prints out the trace on failure.
2460
2461 if (!has_index) {
2462 ref_output_rows = root->num_output_rows();
2463 } else {
2464 EXPECT_FLOAT_EQ(ref_output_rows, root->num_output_rows());
2465 EXPECT_GE(root->num_output_rows(),
2466 500.0); // Due to the 10% fudge factor.
2467 }
2468
2469 query_block->cleanup(/*full=*/true);
2470 ClearFakeTables();
2471 }
2472 }
2473
2474 // Tests a query which has a predicate that must be delayed until after the
2475 // join, and this predicate contains a subquery that may be materialized. The
2476 // selectivity of the delayed predicate used to be double-counted in the plans
2477 // that used materialization.
2478 TEST_F(HypergraphOptimizerTest, DelayedMaterializablePredicate) {
2479 Query_block *query_block = ParseAndResolve(
2480 "SELECT 1 FROM t1 LEFT JOIN t2 ON t1.x = t2.x "
2481 "WHERE t2.y > ALL (SELECT 1)",
2482 /*nullable=*/false);
2483
2484 m_fake_tables["t1"]->file->stats.records = 1000;
2485 m_fake_tables["t2"]->file->stats.records = 100;
2486
2487 string trace;
2488 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
2489 SCOPED_TRACE(trace); // Prints out the trace on failure.
2490 ASSERT_NE(nullptr, root);
2491
2492 // Expect a FILTER node with the delayed predicate, and its row estimate
2493 // should be cardinality(t1) * cardinality(t2) * selectivity(t1.x=t2.x) *
2494 // selectivity(t2.y > ALL).
2495 EXPECT_FLOAT_EQ(
2496 1000 * 100 * COND_FILTER_EQUALITY * (1 - COND_FILTER_INEQUALITY),
2497 root->num_output_rows());
2498 ASSERT_EQ(AccessPath::FILTER, root->type);
2499 EXPECT_EQ("<not>((t2.y <= <max>(select #2)))",
2500 ItemToString(root->filter().condition));
2501 }
2502
2503 TEST_F(HypergraphOptimizerTest, DoNotExpandJoinFiltersMultipleTimes) {
2504 Query_block *query_block = ParseAndResolve(
2505 "SELECT 1 FROM "
2506 " t1 "
2507 " JOIN t2 ON t1.x = t2.x "
2508 " JOIN t3 ON t1.x = t3.x "
2509 " JOIN t4 ON t2.y = t4.x",
2510 /*nullable=*/true);
2511 m_fake_tables["t1"]->file->stats.records = 1;
2512 m_fake_tables["t2"]->file->stats.records = 1;
2513 m_fake_tables["t3"]->file->stats.records = 10;
2514 m_fake_tables["t4"]->file->stats.records = 10;
2515
2516 // To provoke the bug, we need a plan where there is only one hash join,
2517 // and that is with t4 on the outer side (at the very top).
2518 // It's not clear exactly why this is, but presumably, this constellation
2519 // causes us to keep (and thus expand) at least two root paths containing
2520 // the same nested loop, which is required to do expansion twice and thus
2521 // trigger the issue.
2522 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
2523 hton->secondary_engine_flags =
2524 MakeSecondaryEngineFlags(SecondaryEngineFlag::SUPPORTS_HASH_JOIN,
2525 SecondaryEngineFlag::SUPPORTS_NESTED_LOOP_JOIN);
2526 hton->secondary_engine_modify_access_path_cost =
2527 [](THD *, const JoinHypergraph &, AccessPath *path) {
2528 if (path->type == AccessPath::NESTED_LOOP_JOIN &&
2529 Overlaps(GetUsedTableMap(path->nested_loop_join().inner, false),
2530 0b1000)) {
2531 return true;
2532 }
2533 if (path->type == AccessPath::HASH_JOIN &&
2534 GetUsedTableMap(path->hash_join().outer, false) != 0b1000) {
2535 return true;
2536 }
2537 return false;
2538 };
2539
2540 AccessPath *root =
2541 FindBestQueryPlanAndFinalize(m_thd, query_block, /*trace=*/nullptr);
2542 // Prints out the query plan on failure.
2543 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2544 /*is_root_of_join=*/true));
2545
2546 // Check that we don't have a filter on top of a filter.
2547 WalkAccessPaths(root, /*join=*/nullptr, WalkAccessPathPolicy::ENTIRE_TREE,
2548 [&](const AccessPath *path, const JOIN *) {
2549 if (path->type == AccessPath::FILTER) {
2550 EXPECT_NE(AccessPath::FILTER, path->filter().child->type);
2551 }
2552 return false;
2553 });
2554 }
2555
2556 // Verifies that DisallowParameterizedJoinPath() is doing its job.
2557 TEST_F(HypergraphOptimizerTest, InnerNestloopShouldBeLeftDeep) {
2558 Query_block *query_block = ParseAndResolve(
2559 "SELECT 1 FROM t1, t2, t3, t4 WHERE t1.x=t2.x AND t2.y=t3.y AND "
2560 "t3.z=t4.z",
2561 /*nullable=*/true);
2562 Fake_TABLE *t1 = m_fake_tables["t1"];
2563 Fake_TABLE *t2 = m_fake_tables["t2"];
2564 Fake_TABLE *t3 = m_fake_tables["t3"];
2565 Fake_TABLE *t4 = m_fake_tables["t4"];
2566 t1->create_index(t1->field[0], /*column2=*/nullptr, /*unique=*/false);
2567 t2->create_index(t2->field[0], /*column2=*/nullptr, /*unique=*/false);
2568 t2->create_index(t2->field[1], /*column2=*/nullptr, /*unique=*/false);
2569 t3->create_index(t3->field[1], /*column2=*/nullptr, /*unique=*/false);
2570 t3->create_index(t3->field[2], /*column2=*/nullptr, /*unique=*/false);
2571 t4->create_index(t4->field[2], /*column2=*/nullptr, /*unique=*/false);
2572
2573 // We use the secondary engine hook to check that we never try a join between
2574 // ref accesses. They are not _wrong_, but they are redundant in this
2575 // situation, so we should prune them out.
2576 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
2577 hton->secondary_engine_flags =
2578 MakeSecondaryEngineFlags(SecondaryEngineFlag::SUPPORTS_NESTED_LOOP_JOIN);
2579 hton->secondary_engine_modify_access_path_cost =
2580 [](THD *, const JoinHypergraph &, AccessPath *path) {
2581 if (path->type == AccessPath::NESTED_LOOP_JOIN) {
2582 AccessPath *outer = path->nested_loop_join().outer;
2583 AccessPath *inner = path->nested_loop_join().inner;
2584 EXPECT_FALSE(outer->type == AccessPath::REF &&
2585 inner->type == AccessPath::REF);
2586 }
2587 return false;
2588 };
2589
2590 EXPECT_NE(nullptr, FindBestQueryPlanAndFinalize(m_thd, query_block,
2591 /*trace=*/nullptr));
2592
2593 // We don't verify the plan in itself.
2594 }
2595
2596 TEST_F(HypergraphOptimizerTest, CombineFilters) {
2597 Query_block *query_block = ParseAndResolve(
2598 "SELECT 1 FROM t1 WHERE t1.x = 1 HAVING RAND() > 0.5", /*nullable=*/true);
2599 ASSERT_NE(nullptr, query_block);
2600
2601 string trace;
2602 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
2603 SCOPED_TRACE(trace); // Prints out the trace on failure.
2604 ASSERT_NE(nullptr, root);
2605 // Prints out the query plan on failure.
2606 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2607 /*is_root_of_join=*/true));
2608
2609 // We should see a single filter which combines the WHERE clause and the
2610 // HAVING clause. Not two filters stacked on top of each other.
2611 ASSERT_EQ(AccessPath::FILTER, root->type);
2612 EXPECT_EQ(AccessPath::TABLE_SCAN, root->filter().child->type);
2613
2614 EXPECT_EQ("((t1.x = 1) and (rand() > 0.5))",
2615 ItemToString(root->filter().condition));
2616 }
2617
2618 TEST_F(HypergraphOptimizerTest, InsertCastsInSelectExpressions) {
2619 Mock_field_datetime t1_x;
2620 Mock_field_long t1_y(/*is_unsigned=*/false);
2621 t1_x.field_name = "x";
2622 t1_y.field_name = "y";
2623
2624 Fake_TABLE *t1 = new (m_thd->mem_root) Fake_TABLE(&t1_x, &t1_y);
2625 m_fake_tables["t1"] = t1;
2626 t1->set_created();
2627
2628 Query_block *query_block =
2629 ParseAndResolve("SELECT t1.x = t1.y FROM t1", /*nullable=*/true);
2630 FindBestQueryPlanAndFinalize(m_thd, query_block, /*trace=*/nullptr);
2631 ASSERT_EQ(1, query_block->join->fields->size());
2632 EXPECT_EQ("(cast(t1.x as double) = cast(t1.y as double))",
2633 ItemToString((*query_block->join->fields)[0]));
2634 }
2635
2636 // Test that we evaluate the most selective and least expensive WHERE predicates
2637 // before the less selective and more expensive ones.
2638 TEST_F(HypergraphOptimizerTest, OrderingOfWherePredicates) {
2639 Query_block *query_block = ParseAndResolve(
2640 "SELECT 1 FROM t1 WHERE "
2641 "t1.x <> 10 AND t1.y = 123 AND "
2642 "t1.z >= ALL (SELECT t2.x FROM t2) AND "
2643 "t1.x + t1.y = t1.z + t1.w AND "
2644 "t1.w = (SELECT MAX(t3.x) FROM t3) AND "
2645 "t1.x > t1.z",
2646 /*nullable=*/true);
2647 ASSERT_NE(nullptr, query_block);
2648
2649 // Resolve the subqueries too.
2650 for (Query_expression *expr = query_block->first_inner_query_expression();
2651 expr != nullptr; expr = expr->next_query_expression()) {
2652 Query_block *subquery = expr->first_query_block();
2653 ResolveQueryBlock(m_thd, subquery, /*nullable=*/true, &m_fake_tables);
2654 string trace;
2655 AccessPath *subquery_path =
2656 FindBestQueryPlanAndFinalize(m_thd, subquery, &trace);
2657 SCOPED_TRACE(trace); // Prints out the trace on failure.
2658 ASSERT_NE(nullptr, subquery_path);
2659 }
2660
2661 string trace;
2662 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
2663 SCOPED_TRACE(trace); // Prints out the trace on failure.
2664 ASSERT_NE(nullptr, root);
2665 // Prints out the query plan on failure.
2666 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2667 /*is_root_of_join=*/true));
2668
2669 ASSERT_EQ(AccessPath::FILTER, root->type);
2670 EXPECT_EQ(
2671 // First the simple predicates, sorted by selectivity.
2672 "((t1.y = 123) and (t1.x > t1.z) and (t1.x <> 10) and "
2673 "((t1.x + t1.y) = (t1.z + t1.w)) and "
2674 // Then the predicates which contain subqueries.
2675 "<not>((t1.z < <max>(select #2))) and (t1.w = (select #3)))",
2676 ItemToString(root->filter().condition));
2677 }
2678
2679 TEST_F(HypergraphOptimizerTest, OrderingOfJoinPredicates) {
2680 Query_block *query_block = ParseAndResolve(
2681 "SELECT 1 FROM t1, t2 WHERE "
2682 "t1.x > t2.x AND t1.y = t2.y AND "
2683 "t1.z + t2.z = (SELECT MAX(t3.x) FROM t3) AND "
2684 "t1.w < t2.w",
2685 /*nullable=*/true);
2686 ASSERT_NE(nullptr, query_block);
2687
2688 // Resolve the subquery too.
2689 {
2690 Query_block *subquery =
2691 query_block->first_inner_query_expression()->first_query_block();
2692 ResolveQueryBlock(m_thd, subquery, /*nullable=*/true, &m_fake_tables);
2693 string trace;
2694 AccessPath *subquery_path =
2695 FindBestQueryPlanAndFinalize(m_thd, subquery, &trace);
2696 SCOPED_TRACE(trace); // Prints out the trace on failure.
2697 ASSERT_NE(nullptr, subquery_path);
2698 }
2699
2700 // Use small tables so that a nested loop join is preferred.
2701 m_fake_tables["t1"]->file->stats.records = 1;
2702 m_fake_tables["t2"]->file->stats.records = 1;
2703
2704 string trace;
2705 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
2706 SCOPED_TRACE(trace); // Prints out the trace on failure.
2707 ASSERT_NE(nullptr, root);
2708 // Prints out the query plan on failure.
2709 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2710 /*is_root_of_join=*/true));
2711
2712 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
2713 ASSERT_EQ(AccessPath::FILTER, root->nested_loop_join().inner->type);
2714
2715 // Expect the equijoin conditions to be evaluated before the non-equijoin
2716 // conditions. Conditions with subqueries should be evaluated last.
2717 EXPECT_EQ(
2718 "((t1.y = t2.y) and (t1.x > t2.x) and (t1.w < t2.w) and "
2719 "((t1.z + t2.z) = (select #2)))",
2720 ItemToString(root->nested_loop_join().inner->filter().condition));
2721 }
2722
2723 static string PrintSargablePredicate(const SargablePredicate &sp,
2724 const JoinHypergraph &graph) {
2725 return StringPrintf(
2726 "%s.%s -> %s [%s]", sp.field->table->alias, sp.field->field_name,
2727 ItemToString(sp.other_side).c_str(),
2728 ItemToString(graph.predicates[sp.predicate_index].condition).c_str());
2729 }
2730
2731 // Verify that when we add a cycle in the graph due to a multiple equality,
2732 // that join predicate also becomes sargable.
2733 using HypergraphOptimizerCyclePredicatesSargableTest =
2734 OptimizerTestWithParam<const char *>;
2735
2736 TEST_P(HypergraphOptimizerCyclePredicatesSargableTest,
2737 CyclePredicatesSargable) {
2738 Query_block *query_block = ParseAndResolve(GetParam(),
2739 /*nullable=*/true);
2740 Fake_TABLE *t1 = m_fake_tables["t1"];
2741 Fake_TABLE *t2 = m_fake_tables["t2"];
2742 Fake_TABLE *t3 = m_fake_tables["t3"];
2743 t1->create_index(t1->field[0], /*column2=*/nullptr, /*unique=*/false);
2744 t2->create_index(t2->field[0], /*column2=*/nullptr, /*unique=*/false);
2745 t3->create_index(t3->field[0], /*column2=*/nullptr, /*unique=*/false);
2746
2747 // Build multiple equalities from the WHERE condition.
2748 COND_EQUAL *cond_equal = nullptr;
2749 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
2750 &query_block->m_table_nest,
2751 &query_block->cond_value));
2752
2753 string trace;
2754 SCOPED_TRACE(trace); // Prints out the trace on failure.
2755 JoinHypergraph graph(m_thd->mem_root, query_block);
2756 bool always_false = false;
2757 EXPECT_FALSE(MakeJoinHypergraph(m_thd, &trace, &graph, &always_false));
2758 EXPECT_FALSE(always_false);
2759 FindSargablePredicates(m_thd, &trace, &graph);
2760
2761 // Each node should have two sargable join predicates
2762 // (one to each of the other nodes). Verify that they are
2763 // correctly set up (the order does not matter, though).
2764 ASSERT_EQ(3, graph.nodes.size());
2765 EXPECT_STREQ("t1", graph.nodes[0].table->alias);
2766 EXPECT_STREQ("t2", graph.nodes[1].table->alias);
2767 EXPECT_STREQ("t3", graph.nodes[2].table->alias);
2768
2769 ASSERT_EQ(2, graph.nodes[0].sargable_predicates.size());
2770 EXPECT_EQ(
2771 "t1.x -> t2.x [(t1.x = t2.x)]",
2772 PrintSargablePredicate(graph.nodes[0].sargable_predicates[0], graph));
2773 EXPECT_EQ(
2774 "t1.x -> t3.x [(t1.x = t3.x)]",
2775 PrintSargablePredicate(graph.nodes[0].sargable_predicates[1], graph));
2776
2777 ASSERT_EQ(2, graph.nodes[1].sargable_predicates.size());
2778 EXPECT_EQ(
2779 "t2.x -> t3.x [(t2.x = t3.x)]",
2780 PrintSargablePredicate(graph.nodes[1].sargable_predicates[0], graph));
2781 EXPECT_EQ(
2782 "t2.x -> t1.x [(t1.x = t2.x)]",
2783 PrintSargablePredicate(graph.nodes[1].sargable_predicates[1], graph));
2784
2785 ASSERT_EQ(2, graph.nodes[2].sargable_predicates.size());
2786 EXPECT_EQ(
2787 "t3.x -> t2.x [(t2.x = t3.x)]",
2788 PrintSargablePredicate(graph.nodes[2].sargable_predicates[0], graph));
2789 EXPECT_EQ(
2790 "t3.x -> t1.x [(t1.x = t3.x)]",
2791 PrintSargablePredicate(graph.nodes[2].sargable_predicates[1], graph));
2792 }
2793
2794 INSTANTIATE_TEST_SUITE_P(
2795 TrueAndFalse, HypergraphOptimizerCyclePredicatesSargableTest,
2796 ::testing::Values(
2797 // With and without an explicit cycle.
2798 "SELECT 1 FROM t1,t2,t3 WHERE t1.x=t2.x AND t2.x=t3.x AND t1.x=t3.x",
2799 "SELECT 1 FROM t1,t2,t3 WHERE t1.x=t2.x AND t2.x=t3.x"));
2800
2801 TEST_F(HypergraphOptimizerTest, SimpleInnerJoin) {
2802 Query_block *query_block = ParseAndResolve(
2803 "SELECT 1 FROM t1 JOIN t2 ON t1.x=t2.x JOIN t3 ON t2.y=t3.y",
2804 /*nullable=*/true);
2805 m_fake_tables["t1"]->file->stats.records = 1000;
2806 m_fake_tables["t2"]->file->stats.records = 100;
2807 m_fake_tables["t3"]->file->stats.records = 1000000;
2808
2809 // Set up some large scan costs to discourage nested loop.
2810 m_fake_tables["t1"]->file->stats.data_file_length = 10e6;
2811 m_fake_tables["t2"]->file->stats.data_file_length = 1e6;
2812 m_fake_tables["t3"]->file->stats.data_file_length = 10000e6;
2813
2814 string trace;
2815 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
2816 SCOPED_TRACE(trace); // Prints out the trace on failure.
2817 // Prints out the query plan on failure.
2818 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2819 /*is_root_of_join=*/true));
2820
2821 // It's pretty obvious given the sizes of these tables that the optimal
2822 // order for hash join is t3 hj (t1 hj t2). We don't check the costs
2823 // beyond that.
2824 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
2825 EXPECT_EQ(RelationalExpression::INNER_JOIN,
2826 root->hash_join().join_predicate->expr->type);
2827
2828 AccessPath *outer = root->hash_join().outer;
2829 ASSERT_EQ(AccessPath::TABLE_SCAN, outer->type);
2830 EXPECT_EQ(m_fake_tables["t3"], outer->table_scan().table);
2831
2832 AccessPath *inner = root->hash_join().inner;
2833 ASSERT_EQ(AccessPath::HASH_JOIN, inner->type);
2834
2835 AccessPath *t1 = inner->hash_join().outer;
2836 ASSERT_EQ(AccessPath::TABLE_SCAN, t1->type);
2837 EXPECT_EQ(m_fake_tables["t1"], t1->table_scan().table);
2838
2839 AccessPath *t2 = inner->hash_join().inner;
2840 ASSERT_EQ(AccessPath::TABLE_SCAN, t2->type);
2841 EXPECT_EQ(m_fake_tables["t2"], t2->table_scan().table);
2842
2843 // We should have seen the other plans, too (in particular, joining
2844 // {t1} versus {t2,t3}; {t1,t3} versus {t2} is illegal since we don't
2845 // consider Cartesian products). The six subplans seen are:
2846 //
2847 // t1, t2, t3, t1-t2, t2-t3, t1-{t2,t3}, {t1,t2}-t3
2848 EXPECT_EQ(m_thd->m_current_query_partial_plans, 6);
2849 }
2850
2851 TEST_F(HypergraphOptimizerTest, StraightJoin) {
2852 Query_block *query_block =
2853 ParseAndResolve("SELECT 1 FROM t1 STRAIGHT_JOIN t2 ON t1.x=t2.x",
2854 /*nullable=*/true);
2855 m_fake_tables["t1"]->file->stats.records = 100;
2856 m_fake_tables["t2"]->file->stats.records = 10000;
2857
2858 // Set up some large scan costs to discourage nested loop.
2859 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
2860 m_fake_tables["t2"]->file->stats.data_file_length = 100e6;
2861
2862 string trace;
2863 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
2864 SCOPED_TRACE(trace); // Prints out the trace on failure.
2865 // Prints out the query plan on failure.
2866 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2867 /*is_root_of_join=*/true));
2868
2869 // The optimal order would be to reorder (t2, t1), but this should be
2870 // disallowed due to the use of STRAIGHT_JOIN.
2871
2872 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
2873 EXPECT_EQ(RelationalExpression::STRAIGHT_INNER_JOIN,
2874 root->hash_join().join_predicate->expr->type);
2875
2876 AccessPath *outer = root->hash_join().outer;
2877 ASSERT_EQ(AccessPath::TABLE_SCAN, outer->type);
2878 EXPECT_EQ(m_fake_tables["t1"], outer->table_scan().table);
2879
2880 AccessPath *inner = root->hash_join().inner;
2881 ASSERT_EQ(AccessPath::TABLE_SCAN, inner->type);
2882 EXPECT_EQ(m_fake_tables["t2"], inner->table_scan().table);
2883
2884 // We should see only the two table scans and then t1-t2, no other orders.
2885 EXPECT_EQ(m_thd->m_current_query_partial_plans, 3);
2886 }
2887
2888 TEST_F(HypergraphOptimizerTest, StraightJoinWithMoreTables) {
2889 Query_block *query_block = ParseAndResolve(
2890 "SELECT 1 FROM t1 STRAIGHT_JOIN t2 ON t1.x=t2.x "
2891 "STRAIGHT_JOIN t3 ON t1.y=t3.y STRAIGHT_JOIN "
2892 "t4 ON (t4.y = t2.y and t3.x <> t4.x)",
2893 /*nullable=*/true);
2894 // Make a call to optimize_cond() so that we have the equalities
2895 // placed at the end in the final where condition.
2896 COND_EQUAL *cond_equal = nullptr;
2897 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
2898 &query_block->m_table_nest,
2899 &query_block->cond_value));
2900
2901 m_fake_tables["t1"]->file->stats.records = 100;
2902 m_fake_tables["t2"]->file->stats.records = 1000;
2903 m_fake_tables["t3"]->file->stats.records = 100;
2904 m_fake_tables["t4"]->file->stats.records = 10;
2905
2906 // Set up some large scan costs to discourage nested loop.
2907 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
2908 m_fake_tables["t2"]->file->stats.data_file_length = 10e6;
2909 m_fake_tables["t3"]->file->stats.data_file_length = 100e6;
2910 m_fake_tables["t4"]->file->stats.data_file_length = 1000e6;
2911
2912 string trace;
2913 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
2914 SCOPED_TRACE(trace); // Prints out the trace on failure.
2915 // Prints out the query plan on failure.
2916 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2917 /*is_root_of_join=*/true));
2918
2919 // The expected order would be
2920 // ((t1 HJ t2 ON t1.x=t2.x) HJ t3 ON t1.y=t3.y) HJ t4 ON t4.y = t2.y and t3.x
2921 // <> t4.x )
2922 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
2923 EXPECT_EQ(RelationalExpression::STRAIGHT_INNER_JOIN,
2924 root->hash_join().join_predicate->expr->type);
2925 RelationalExpression *expr1 = root->hash_join().join_predicate->expr;
2926 EXPECT_EQ(1, expr1->join_conditions.size());
2927 ASSERT_EQ(1, expr1->equijoin_conditions.size());
2928 // Check that the join condition (t3.x <> t4.x) gets added
2929 // to the top join instead of the join between t3 and t4.
2930 EXPECT_EQ("(t3.x <> t4.x)", ItemToString(expr1->join_conditions[0]));
2931 EXPECT_EQ("(t4.y = t2.y)", ItemToString(expr1->equijoin_conditions[0]));
2932
2933 AccessPath *t4 = root->hash_join().inner;
2934 ASSERT_EQ(AccessPath::TABLE_SCAN, t4->type);
2935 EXPECT_EQ(m_fake_tables["t4"], t4->table_scan().table);
2936
2937 AccessPath *t1t2t3 = root->hash_join().outer;
2938 ASSERT_EQ(AccessPath::HASH_JOIN, t1t2t3->type);
2939 RelationalExpression *expr2 = t1t2t3->hash_join().join_predicate->expr;
2940 EXPECT_EQ(RelationalExpression::STRAIGHT_INNER_JOIN, expr2->type);
2941 ASSERT_EQ(1, expr2->equijoin_conditions.size());
2942 EXPECT_EQ("(t1.y = t3.y)", ItemToString(expr2->equijoin_conditions[0]));
2943
2944 AccessPath *t3 = t1t2t3->hash_join().inner;
2945 ASSERT_EQ(AccessPath::TABLE_SCAN, t3->type);
2946 EXPECT_EQ(m_fake_tables["t3"], t3->table_scan().table);
2947
2948 AccessPath *t1t2 = t1t2t3->hash_join().outer;
2949 ASSERT_EQ(AccessPath::HASH_JOIN, t1t2->type);
2950 RelationalExpression *expr3 = t1t2->hash_join().join_predicate->expr;
2951 EXPECT_EQ(RelationalExpression::STRAIGHT_INNER_JOIN, expr3->type);
2952 ASSERT_EQ(1, expr3->equijoin_conditions.size());
2953 EXPECT_EQ("(t1.x = t2.x)", ItemToString(expr3->equijoin_conditions[0]));
2954
2955 AccessPath *t2 = t1t2->hash_join().inner;
2956 ASSERT_EQ(AccessPath::TABLE_SCAN, t2->type);
2957 EXPECT_EQ(m_fake_tables["t2"], t2->table_scan().table);
2958
2959 AccessPath *t1 = t1t2->hash_join().outer;
2960 ASSERT_EQ(AccessPath::TABLE_SCAN, t1->type);
2961 EXPECT_EQ(m_fake_tables["t1"], t1->table_scan().table);
2962 }
2963
2964 TEST_F(HypergraphOptimizerTest, StraightJoinNotAssociative) {
2965 Query_block *query_block = ParseAndResolve(
2966 "SELECT 1 FROM t1 STRAIGHT_JOIN t2 STRAIGHT_JOIN t3 "
2967 "STRAIGHT_JOIN t4 WHERE t3.y=t4.y AND t1.x=t2.x",
2968 /*nullable=*/true);
2969
2970 // For secondary engine straight joins are not associative.
2971 m_initializer.thd()->set_secondary_engine_optimization(
2972 Secondary_engine_optimization::SECONDARY);
2973 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
2974 hton->secondary_engine_flags =
2975 MakeSecondaryEngineFlags(SecondaryEngineFlag::SUPPORTS_HASH_JOIN);
2976
2977 string trace;
2978 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
2979 SCOPED_TRACE(trace); // Prints out the trace on failure.
2980 // Prints out the query plan on failure.
2981 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
2982 /*is_root_of_join=*/true));
2983
2984 // The expected order would be
2985 // ((t1 HJ t2 ON t1.x = t2.x) HJ t3) HJ t4 ON t3.y = t4.y
2986 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
2987 EXPECT_EQ(RelationalExpression::STRAIGHT_INNER_JOIN,
2988 root->hash_join().join_predicate->expr->type);
2989 RelationalExpression *expr1 = root->hash_join().join_predicate->expr;
2990 ASSERT_EQ(1, expr1->equijoin_conditions.size());
2991 EXPECT_EQ("(t3.y = t4.y)", ItemToString(expr1->equijoin_conditions[0]));
2992
2993 AccessPath *t4 = root->hash_join().inner;
2994 ASSERT_EQ(AccessPath::TABLE_SCAN, t4->type);
2995 EXPECT_EQ(m_fake_tables["t4"], t4->table_scan().table);
2996
2997 AccessPath *t1t2t3 = root->hash_join().outer;
2998 ASSERT_EQ(AccessPath::HASH_JOIN, t1t2t3->type);
2999 RelationalExpression *expr2 = t1t2t3->hash_join().join_predicate->expr;
3000 EXPECT_EQ(RelationalExpression::STRAIGHT_INNER_JOIN, expr2->type);
3001
3002 AccessPath *t3 = t1t2t3->hash_join().inner;
3003 ASSERT_EQ(AccessPath::TABLE_SCAN, t3->type);
3004 EXPECT_EQ(m_fake_tables["t3"], t3->table_scan().table);
3005
3006 AccessPath *t1t2 = t1t2t3->hash_join().outer;
3007 ASSERT_EQ(AccessPath::HASH_JOIN, t1t2->type);
3008 RelationalExpression *expr3 = t1t2->hash_join().join_predicate->expr;
3009 EXPECT_EQ(RelationalExpression::STRAIGHT_INNER_JOIN, expr3->type);
3010 ASSERT_EQ(1, expr3->equijoin_conditions.size());
3011 EXPECT_EQ("(t1.x = t2.x)", ItemToString(expr3->equijoin_conditions[0]));
3012
3013 AccessPath *t2 = t1t2->hash_join().inner;
3014 ASSERT_EQ(AccessPath::TABLE_SCAN, t2->type);
3015 EXPECT_EQ(m_fake_tables["t2"], t2->table_scan().table);
3016
3017 AccessPath *t1 = t1t2->hash_join().outer;
3018 ASSERT_EQ(AccessPath::TABLE_SCAN, t1->type);
3019 EXPECT_EQ(m_fake_tables["t1"], t1->table_scan().table);
3020 }
3021
3022 TEST_F(HypergraphOptimizerTest, NullSafeEqualHashJoin) {
3023 Query_block *query_block =
3024 ParseAndResolve("SELECT 1 FROM t1, t2 WHERE t1.x <=> t2.x",
3025 /*nullable=*/true);
3026 m_fake_tables["t1"]->file->stats.records = 100;
3027 m_fake_tables["t2"]->file->stats.records = 10000;
3028
3029 // Set up some large scan costs to discourage nested loop.
3030 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
3031 m_fake_tables["t2"]->file->stats.data_file_length = 100e6;
3032
3033 string trace;
3034 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
3035 SCOPED_TRACE(trace); // Prints out the trace on failure.
3036 // Prints out the query plan on failure.
3037 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3038 /*is_root_of_join=*/true));
3039
3040 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
3041
3042 // The <=> predicate should be an equijoin condition.
3043 const RelationalExpression *expr = root->hash_join().join_predicate->expr;
3044 EXPECT_EQ(RelationalExpression::INNER_JOIN, expr->type);
3045 EXPECT_EQ(0, expr->join_conditions.size());
3046 ASSERT_EQ(1, expr->equijoin_conditions.size());
3047 EXPECT_EQ("(t1.x <=> t2.x)", ItemToString(expr->equijoin_conditions[0]));
3048 }
3049
3050 TEST_F(HypergraphOptimizerTest, Cycle) {
3051 Query_block *query_block = ParseAndResolve(
3052 "SELECT 1 FROM "
3053 "t1,t2,t3 WHERE t1.x=t2.x AND t2.x=t3.x AND t1.x=t3.x",
3054 /*nullable=*/true);
3055
3056 string trace;
3057 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
3058 SCOPED_TRACE(trace); // Prints out the trace on failure.
3059 // Prints out the query plan on failure.
3060 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3061 /*is_root_of_join=*/true));
3062
3063 // We should see t1, t2, t3, {t1,t2}, {t2,t3}, {t1,t3} and {t1,t2,t3}.
3064 EXPECT_EQ(m_thd->m_current_query_partial_plans, 7);
3065 }
3066
3067 TEST_F(HypergraphOptimizerTest, CycleFromMultipleEquality) {
3068 Query_block *query_block = ParseAndResolve(
3069 "SELECT 1 FROM "
3070 "t1,t2,t3 WHERE t1.x=t2.x AND t2.x=t3.x",
3071 /*nullable=*/true);
3072
3073 // Build multiple equalities from the WHERE condition.
3074 COND_EQUAL *cond_equal = nullptr;
3075 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
3076 &query_block->m_table_nest,
3077 &query_block->cond_value));
3078
3079 string trace;
3080 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
3081 SCOPED_TRACE(trace); // Prints out the trace on failure.
3082 // Prints out the query plan on failure.
3083 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3084 /*is_root_of_join=*/true));
3085
3086 // We should see t1, t2, t3, {t1,t2}, {t2,t3}, {t1,t3} and {t1,t2,t3}.
3087 EXPECT_EQ(m_thd->m_current_query_partial_plans, 7);
3088 }
3089
3090 TEST_F(HypergraphOptimizerTest, UniqueIndexCapsBothWays) {
3091 Query_block *query_block =
3092 ParseAndResolve("SELECT 1 FROM t1 LEFT JOIN t2 ON t1.x=t2.x",
3093 /*nullable=*/false);
3094 Fake_TABLE *t1 = m_fake_tables["t1"];
3095 Fake_TABLE *t2 = m_fake_tables["t2"];
3096 t1->file->stats.records = 1000;
3097 t2->file->stats.records = 1000;
3098 t1->create_index(t1->field[0], nullptr, /*unique=*/true);
3099
3100 string trace;
3101 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
3102 SCOPED_TRACE(trace); // Prints out the trace on failure.
3103 // Prints out the query plan on failure.
3104 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3105 /*is_root_of_join=*/true));
3106
3107 // The unique index on t1 isn't usable, but it should inform
3108 // the selectivity for the hash join nevertheless. (Without it,
3109 // we would see an estimate of 100k rows, since we don't have
3110 // selectivity information in our index and fall back to the
3111 // default selectivity of 0.1 for field = field.)
3112 EXPECT_EQ(AccessPath::HASH_JOIN, root->type);
3113 EXPECT_FLOAT_EQ(1000.0, root->num_output_rows());
3114 }
3115
3116 /*
3117 Sets up this join graph:
3118
3119 t1 --- t2
3120 | . |
3121 | . |
3122 | . |
3123 t3 --- t4
3124
3125 t1-t3-t4 are joined along the x fields, t1-t2-t4 are joined along the y
3126 fields. The t1-t4 edge is created only due to multiple equalities, but the
3127 optimal plan is to use that edge, so that we can use the index on t4 to
3128 resolve both x and y. The crux of the issue is that this edge must then
3129 subsume both t1=t4 conditions.
3130 */
3131 TEST_F(HypergraphOptimizerTest, SubsumedSargableInDoubleCycle) {
3132 Query_block *query_block = ParseAndResolve(
3133 "SELECT 1 FROM t1, t2, t3, t4 "
3134 "WHERE t1.x = t3.x AND t3.x = t4.x AND t1.y = t2.y AND t2.y = t4.y",
3135 /*nullable=*/true);
3136 Fake_TABLE *t1 = m_fake_tables["t1"];
3137 Fake_TABLE *t2 = m_fake_tables["t2"];
3138 Fake_TABLE *t3 = m_fake_tables["t3"];
3139 Fake_TABLE *t4 = m_fake_tables["t4"];
3140 t1->file->stats.records = 100;
3141 t2->file->stats.records = 100;
3142 t3->file->stats.records = 100;
3143 t4->file->stats.records = 100;
3144 t4->file->stats.data_file_length = 100e6;
3145 t3->create_index(t3->field[0], nullptr, /*unique=*/false);
3146 t4->create_index(t4->field[0], t4->field[1], /*unique=*/false);
3147
3148 // Build multiple equalities from the WHERE condition.
3149 COND_EQUAL *cond_equal = nullptr;
3150 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
3151 &query_block->m_table_nest,
3152 &query_block->cond_value));
3153
3154 string trace;
3155 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
3156 SCOPED_TRACE(trace); // Prints out the trace on failure.
3157 // Prints out the query plan on failure.
3158 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3159 /*is_root_of_join=*/true));
3160
3161 // The four tables combined together, with three 0.1 selectivities in the
3162 // x multi-equality and then one on y.
3163 EXPECT_FLOAT_EQ(10000.0, root->num_output_rows());
3164
3165 // We should have an index lookup into t4, covering both t1=t4 conditions.
3166 bool found_t4_index_lookup = false;
3167 WalkAccessPaths(
3168 root, /*join=*/nullptr, WalkAccessPathPolicy::ENTIRE_TREE,
3169 [&](const AccessPath *path, const JOIN *) {
3170 if (path->type == AccessPath::REF &&
3171 strcmp("t4", path->ref().table->alias) == 0) {
3172 found_t4_index_lookup = true;
3173 EXPECT_EQ(2, path->ref().ref->key_parts);
3174 EXPECT_EQ("t1.x", ItemToString(path->ref().ref->items[0]));
3175 EXPECT_EQ("t1.y", ItemToString(path->ref().ref->items[1]));
3176 }
3177 return false;
3178 });
3179 EXPECT_TRUE(found_t4_index_lookup);
3180
3181 // And thus, there should be no filter containing both t1 and t4.
3182 WalkAccessPaths(root, /*join=*/nullptr, WalkAccessPathPolicy::ENTIRE_TREE,
3183 [&](const AccessPath *path, const JOIN *) {
3184 if (path->type == AccessPath::FILTER) {
3185 const string str = ItemToString(path->filter().condition);
3186 EXPECT_TRUE(str.find("t1") == string::npos ||
3187 str.find("t4") == string::npos);
3188 }
3189 return false;
3190 });
3191 }
3192
3193 /*
3194 Sets up a semi-join with this join graph:
3195
3196 t1 t3
3197 | \__/ |
3198 | / \ |
3199 t2 t4
3200
3201 The join predicates for both t1-t2 and t3-t4 are sargable, and the preferred
3202 paths apply them as sargable. The semi-join predicate should not come from the
3203 same multiple equality as the sargable predicates, so it should not be made
3204 redundant by them.
3205 */
3206 TEST_F(HypergraphOptimizerTest, SemiJoinPredicateNotRedundant) {
3207 Query_block *query_block = ParseAndResolve(
3208 "SELECT 1 FROM t1, t2 WHERE t1.y = t2.x AND t1.x IN "
3209 "(SELECT t3.x FROM t3, t4 WHERE t2.y = t3.y AND t3.x = t4.y)",
3210 /*nullable=*/true);
3211
3212 // Create indexes on t1(y) and t4(y).
3213 Fake_TABLE *t1 = m_fake_tables["t1"];
3214 t1->create_index(t1->field[1], /*column2=*/nullptr, /*unique=*/false);
3215 Fake_TABLE *t4 = m_fake_tables["t4"];
3216 t4->create_index(t4->field[1], /*column2=*/nullptr, /*unique=*/false);
3217
3218 Fake_TABLE *t2 = m_fake_tables["t2"];
3219 Fake_TABLE *t3 = m_fake_tables["t3"];
3220
3221 // Adjust sizes so that NLJ(TS(t2), REF(t1)) and NLJ(TS(t3), REF(t4)) are
3222 // preferred join orders for the smaller joins.
3223 t1->file->stats.records = 1000;
3224 t2->file->stats.records = 1;
3225 t3->file->stats.records = 1;
3226 t4->file->stats.records = 1000;
3227
3228 string trace;
3229 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
3230 SCOPED_TRACE(trace); // Prints out the trace on failure.
3231 // Prints out the query plan on failure.
3232 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3233 /*is_root_of_join=*/true));
3234
3235 // Check that the expected plan is produced. Before bug#33619350 no plan was
3236 // produced at all.
3237 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
3238 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->hash_join().outer->type);
3239 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->hash_join().inner->type);
3240 EXPECT_EQ(AccessPath::TABLE_SCAN,
3241 root->hash_join().outer->nested_loop_join().outer->type);
3242 EXPECT_EQ(AccessPath::REF,
3243 root->hash_join().outer->nested_loop_join().inner->type);
3244 EXPECT_EQ(AccessPath::TABLE_SCAN,
3245 root->hash_join().inner->nested_loop_join().outer->type);
3246 EXPECT_EQ(AccessPath::REF,
3247 root->hash_join().inner->nested_loop_join().inner->type);
3248 }
3249
3250 /*
3251 Another case where the semi-join condition is not redundant. In this case, the
3252 join condition on the outer side of the semi-join, the join condition on the
3253 inner side of the semi-join and the semi-join condition are part of the same
3254 multiple equality. But even so, the semi-join condition is not redundant,
3255 because none of the other two join conditions references any tables on the
3256 opposite side of the semi-join.
3257 */
3258 TEST_F(HypergraphOptimizerTest, SemiJoinPredicateNotRedundant2) {
3259 Query_block *query_block = ParseAndResolve(
3260 "SELECT 1 FROM t1, t2, t3 WHERE t2.x = t3.x AND t2.x IN "
3261 "(SELECT t5.x FROM t4, t5 WHERE t4.x = t5.x AND t4.y <> t1.y)",
3262 /*nullable=*/false);
3263
3264 // Add an index on t2.x to make the join predicate t2.x = t3.x sargable.
3265 Fake_TABLE *t2 = m_fake_tables["t2"];
3266 t2->create_index(t2->field[0], /*column2=*/nullptr, /*unique=*/false);
3267
3268 // Add a unique index to make the join predicate t4.x = t5.x sargable.
3269 Fake_TABLE *t5 = m_fake_tables["t5"];
3270 t5->create_index(t5->field[0], /*column2=*/nullptr, /*unique=*/true);
3271
3272 // Set up table sizes so that nested loop joins with REF(t2) and EQ_REF(t5) as
3273 // the innermost tables are attractive.
3274 m_fake_tables["t1"]->file->stats.records = 1;
3275 m_fake_tables["t2"]->file->stats.records = 1000;
3276 m_fake_tables["t3"]->file->stats.records = 1;
3277 m_fake_tables["t4"]->file->stats.records = 1;
3278 m_fake_tables["t5"]->file->stats.records = 1000;
3279
3280 // Build a multiple equality from the WHERE condition:
3281 // t2.x = t3.x = t4.x = t5.x
3282 COND_EQUAL *cond_equal = nullptr;
3283 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
3284 &query_block->m_table_nest,
3285 &query_block->cond_value));
3286 EXPECT_EQ(1, cond_equal->current_level.size());
3287 const Item_equal *eq = cond_equal->current_level.head();
3288 EXPECT_EQ(nullptr, eq->const_arg());
3289 EXPECT_EQ(4, eq->get_fields().size());
3290
3291 string trace;
3292 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
3293 SCOPED_TRACE(trace); // Prints out the trace on failure.
3294 // Prints out the query plan on failure.
3295 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3296 /*is_root_of_join=*/true));
3297
3298 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
3299 EXPECT_EQ(JoinType::SEMI, root->nested_loop_join().join_type);
3300
3301 // The innermost table on the left side is a REF lookup subsuming the join
3302 // condition t2.x = t3.x.
3303 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->nested_loop_join().outer->type);
3304 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN,
3305 root->nested_loop_join().outer->nested_loop_join().inner->type);
3306 EXPECT_EQ(AccessPath::REF, root->nested_loop_join()
3307 .outer->nested_loop_join()
3308 .inner->nested_loop_join()
3309 .inner->type);
3310
3311 // The semi-join condition t2.x = t5.x is not redundant, so there should be a
3312 // filter for it in some form (it ends up as t3.x = t4.x due to multiple
3313 // equalities).
3314 ASSERT_EQ(AccessPath::FILTER, root->nested_loop_join().inner->type);
3315 EXPECT_EQ("((t3.x = t4.x) and (t4.y <> t1.y))",
3316 ItemToString(root->nested_loop_join().inner->filter().condition));
3317
3318 // The innermost table on the right side is an EQ_REF lookup subsuming the
3319 // join condition t4.x = t5.x.
3320 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN,
3321 root->nested_loop_join().inner->filter().child->type);
3322 EXPECT_EQ(AccessPath::EQ_REF, root->nested_loop_join()
3323 .inner->filter()
3324 .child->nested_loop_join()
3325 .inner->type);
3326 }
3327
3328 TEST_F(HypergraphOptimizerTest, SemijoinToInnerWithSargable) {
3329 Query_block *query_block = ParseAndResolve(
3330 "SELECT 1 FROM t1 WHERE t1.x IN (SELECT t2.x FROM t2) "
3331 "AND t1.x IN (SELECT t3.x FROM t3)",
3332 /*nullable=*/false);
3333
3334 Fake_TABLE *t1 = m_fake_tables["t1"];
3335 Fake_TABLE *t2 = m_fake_tables["t2"];
3336 Fake_TABLE *t3 = m_fake_tables["t3"];
3337
3338 t2->create_index(t2->field[0], /*column2=*/nullptr, /*unique=*/false);
3339
3340 t1->file->stats.records = 10;
3341 t2->file->stats.records = 100;
3342 t3->file->stats.records = 1000;
3343
3344 // Build a multiple equality from the WHERE condition:
3345 // t1.x = t2.x = t3.x
3346 COND_EQUAL *cond_equal = nullptr;
3347 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
3348 &query_block->m_table_nest,
3349 &query_block->cond_value));
3350 EXPECT_EQ(1, cond_equal->current_level.size());
3351 const Item_equal *eq = cond_equal->current_level.head();
3352 EXPECT_EQ(nullptr, eq->const_arg());
3353 EXPECT_EQ(3, eq->get_fields().size());
3354
3355 string trace;
3356 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
3357 SCOPED_TRACE(trace); // Prints out the trace on failure.
3358 // Prints out the query plan on failure.
3359 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3360 /*is_root_of_join=*/true));
3361
3362 // We don't really care that much about which plan is chosen here. The main
3363 // thing we want to check, is that FindBestQueryPlan() didn't hit an assertion
3364 // because of inconsistent row estimates. The row estimates *are*
3365 // inconsistent, though, until bug#33550360 is fixed. The returned plan is
3366 // ((t1 semi-HJ t2) semi-HJ t3).
3367 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
3368 ASSERT_EQ(AccessPath::HASH_JOIN, root->hash_join().outer->type);
3369 ASSERT_EQ(AccessPath::TABLE_SCAN,
3370 root->hash_join().outer->hash_join().outer->type);
3371 ASSERT_EQ(AccessPath::TABLE_SCAN,
3372 root->hash_join().outer->hash_join().inner->type);
3373 ASSERT_EQ(AccessPath::TABLE_SCAN, root->hash_join().inner->type);
3374 EXPECT_STREQ(
3375 "t1",
3376 root->hash_join().outer->hash_join().outer->table_scan().table->alias);
3377 EXPECT_STREQ(
3378 "t2",
3379 root->hash_join().outer->hash_join().inner->table_scan().table->alias);
3380 EXPECT_STREQ("t3", root->hash_join().inner->table_scan().table->alias);
3381 }
3382
3383 TEST_F(HypergraphOptimizerTest, SemijoinToInnerWithDegenerateJoinCondition) {
3384 Query_block *query_block =
3385 ParseAndResolve("SELECT 1 FROM t1 WHERE 1 IN (SELECT t2.x FROM t2)",
3386 /*nullable=*/false);
3387
3388 // Make the tables big so that building a hash table of one of them looks
3389 // expensive.
3390 m_fake_tables["t1"]->file->stats.records = 1000000;
3391 m_fake_tables["t1"]->file->stats.data_file_length = 1e8;
3392 m_fake_tables["t2"]->file->stats.records = 1000000;
3393 m_fake_tables["t2"]->file->stats.data_file_length = 1e8;
3394
3395 string trace;
3396 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
3397 SCOPED_TRACE(trace); // Prints out the trace on failure.
3398 // Prints out the query plan on failure.
3399 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3400 /*is_root_of_join=*/true));
3401
3402 // Expect a nested-loop inner join using a limit on t2 to be preferred to a
3403 // hash semijoin.
3404 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
3405
3406 const AccessPath *outer = root->nested_loop_join().outer;
3407 ASSERT_EQ(AccessPath::LIMIT_OFFSET, outer->type);
3408 EXPECT_EQ(0, outer->limit_offset().offset);
3409 EXPECT_EQ(1, outer->limit_offset().limit);
3410 ASSERT_EQ(AccessPath::FILTER, outer->limit_offset().child->type);
3411 ASSERT_EQ(AccessPath::TABLE_SCAN,
3412 outer->limit_offset().child->filter().child->type);
3413 EXPECT_STREQ(
3414 "t2",
3415 outer->limit_offset().child->filter().child->table_scan().table->alias);
3416
3417 const AccessPath *inner = root->nested_loop_join().inner;
3418 ASSERT_EQ(AccessPath::TABLE_SCAN, inner->type);
3419 EXPECT_STREQ("t1", inner->table_scan().table->alias);
3420 }
3421
3422 /*
3423 Test a query with two multiple equalities on overlapping, but not identical,
3424 sets of tables, and where there is a hyperpredicate that references all of the
3425 tables in one of the multiple equalities.
3426
3427 The presence of the hyperpredicate used to prevent addition of a cycle edge
3428 for the tables in the first multiple equality. If the tables in the
3429 hyperpredicate were joined together without following the hyperedge
3430 corresponding to the hyperpredicate, via an alternative edge provided by the
3431 second multiple equality, one application of the first multiple equality would
3432 be lost, and inconsistent row estimates were seen.
3433
3434 Now, the presence of a hyperpredicate no longer prevents addition of a cycle
3435 edge. Both because of the inconsistencies that were seen in this test case,
3436 and because it turned out to be bad also for performance, as it blocked some
3437 valid and potentially cheaper join orders.
3438 */
3439 TEST_F(HypergraphOptimizerTest, HyperpredicatesConsistentRowEstimates) {
3440 Query_block *query_block = ParseAndResolve(
3441 "SELECT 1 FROM t1, t2, t3, t4 WHERE "
3442 "t1.x = t2.x AND t2.x = t3.x AND "
3443 "t2.y = t3.y AND t3.y = t4.y AND "
3444 "t1.z + t2.z < t3.z",
3445 /*nullable=*/true);
3446
3447 const ha_rows t1_rows = m_fake_tables["t1"]->file->stats.records = 1000;
3448 const ha_rows t2_rows = m_fake_tables["t2"]->file->stats.records = 1000;
3449 const ha_rows t3_rows = m_fake_tables["t3"]->file->stats.records = 10;
3450 const ha_rows t4_rows = m_fake_tables["t4"]->file->stats.records = 10;
3451
3452 // Build two multiple equalities: t1.x = t2.x = t3.x and t2.y = t3.y = t4.y.
3453 COND_EQUAL *cond_equal = nullptr;
3454 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
3455 &query_block->m_table_nest,
3456 &query_block->cond_value));
3457 EXPECT_EQ(2, cond_equal->current_level.size());
3458
3459 string trace;
3460 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
3461 SCOPED_TRACE(trace); // Prints out the trace on failure.
3462 // Prints out the query plan on failure.
3463 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3464 /*is_root_of_join=*/true));
3465 ASSERT_NE(nullptr, root);
3466
3467 // We don't really care which plan is chosen. The main point is that
3468 // FindBestQueryPlan() above didn't fail with an assertion about inconsistent
3469 // row estimates, and that the row estimate here is as expected. (It used to
3470 // be too high because one of the multiple equalities was only applied once.
3471 // Both multiple equalities should be applied twice.)
3472 EXPECT_FLOAT_EQ(
3473 t1_rows * t2_rows * t3_rows * t4_rows * // Input rows.
3474 powf(COND_FILTER_EQUALITY, 4) * // Selectivity of equalities.
3475 COND_FILTER_ALLPASS, // Selectivity of hyperpredicate.
3476 root->num_output_rows());
3477 }
3478
3479 TEST_F(HypergraphOptimizerTest, SwitchesOrderToMakeSafeForRowid) {
3480 // Mark t1.y as a blob, to make sure we need rowids for our sort.
3481 Mock_field_long t1_x(/*is_unsigned=*/false);
3482 Base_mock_field_blob t1_y("y", /*length=*/1000000);
3483 t1_x.field_name = "x";
3484
3485 Fake_TABLE *t1 = new (m_thd->mem_root) Fake_TABLE(&t1_x, &t1_y);
3486 m_fake_tables["t1"] = t1;
3487
3488 t1->set_created();
3489 Query_block *query_block = ParseAndResolve(
3490 "SELECT t1.y FROM t1 JOIN t2 ON t1.x=t2.x ORDER BY t1.y, t2.y",
3491 /*nullable=*/true);
3492
3493 t1->create_index(t1->field[0], nullptr, /*unique=*/false);
3494 Fake_TABLE *t2 = m_fake_tables["t2"];
3495 t2->create_index(t2->field[0], nullptr, /*unique=*/false);
3496
3497 // The normal case for rowid-unsafe tables are LATERAL derived tables,
3498 // but since we don't support derived tables in the unit test,
3499 // we cheat and mark t2 as unsafe for row IDs manually instead,
3500 // and also disallow hash join.
3501 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
3502 hton->secondary_engine_flags =
3503 MakeSecondaryEngineFlags(SecondaryEngineFlag::SUPPORTS_NESTED_LOOP_JOIN);
3504 hton->secondary_engine_modify_access_path_cost =
3505 [](THD *, const JoinHypergraph &, AccessPath *path) {
3506 if (path->type == AccessPath::REF &&
3507 strcmp("t2", path->ref().table->alias) == 0) {
3508 path->safe_for_rowid = AccessPath::SAFE_IF_SCANNED_ONCE;
3509 }
3510 return false;
3511 };
3512
3513 m_fake_tables["t1"]->file->stats.records = 99;
3514 m_fake_tables["t2"]->file->stats.records = 100;
3515
3516 string trace;
3517 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
3518 SCOPED_TRACE(trace); // Prints out the trace on failure.
3519 // Prints out the query plan on failure.
3520 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3521 /*is_root_of_join=*/true));
3522
3523 // Normally, it would be better to have t1 on the outside
3524 // and t2 on the inside, since t2 is the larger one, but that would create
3525 // a materialization, so the better version is to flip.
3526 ASSERT_EQ(AccessPath::SORT, root->type);
3527 AccessPath *join = root->sort().child;
3528 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, join->type);
3529 AccessPath *outer = join->nested_loop_join().outer;
3530 AccessPath *inner = join->nested_loop_join().inner;
3531
3532 ASSERT_EQ(AccessPath::TABLE_SCAN, outer->type);
3533 EXPECT_STREQ("t2", outer->table_scan().table->alias);
3534
3535 ASSERT_EQ(AccessPath::REF, inner->type);
3536 EXPECT_STREQ("t1", inner->ref().table->alias);
3537 }
3538
3539 // Test that a hash join can combine predicates from multiple edges in a cyclic
3540 // hypergraph, and create a wider hash join key than what it gets from the
3541 // single edge. (Previously, the eligible join predicates from other edges in
3542 // the cycle were instead added as post-join filters.)
3543 TEST_F(HypergraphOptimizerTest, MultiPredicateHashJoin) {
3544 // Test both regular equality and NULL-safe equality. Either kind of equality
3545 // can be used in the hash join key.
3546 for (const char *eq_op : {"=", "<=>"}) {
3547 const string query = StringPrintf(
3548 "SELECT 1 FROM t1, t2, t3 "
3549 "WHERE t1.x %s t2.x AND t2.y %s t3.y AND t1.z %s t3.z",
3550 eq_op, eq_op, eq_op);
3551 SCOPED_TRACE(query);
3552 Query_block *query_block = ParseAndResolve(query.data(),
3553 /*nullable=*/true);
3554
3555 // Sizes that make (t1 HJ t2) HJ t3 the preferred join order.
3556 m_fake_tables["t1"]->file->stats.records = 90000;
3557 m_fake_tables["t1"]->file->stats.data_file_length = 9e7;
3558 m_fake_tables["t2"]->file->stats.records = 100;
3559 m_fake_tables["t2"]->file->stats.data_file_length = 1e3;
3560 m_fake_tables["t3"]->file->stats.records = 3000;
3561 m_fake_tables["t3"]->file->stats.data_file_length = 3e5;
3562
3563 string trace;
3564 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
3565 SCOPED_TRACE(trace); // Prints out the trace on failure.
3566 // Prints out the query plan on failure.
3567 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3568 /*is_root_of_join=*/true));
3569
3570 // The top-level path should be a HASH_JOIN with two equi-join predicates.
3571 // In earlier versions, the hash join had only one of the predicates, and
3572 // the other predicate was in a FILTER on top of it.
3573 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
3574 EXPECT_EQ(0,
3575 root->hash_join().join_predicate->expr->join_conditions.size());
3576 {
3577 vector<string> equijoin_conditions;
3578 for (Item_eq_base *item :
3579 root->hash_join().join_predicate->expr->equijoin_conditions) {
3580 equijoin_conditions.push_back(ItemToString(item));
3581 }
3582 EXPECT_THAT(equijoin_conditions,
3583 UnorderedElementsAre(StringPrintf("(t2.y %s t3.y)", eq_op),
3584 StringPrintf("(t1.z %s t3.z)", eq_op)));
3585 }
3586
3587 ASSERT_EQ(AccessPath::HASH_JOIN, root->hash_join().outer->type);
3588 ASSERT_EQ(AccessPath::TABLE_SCAN, root->hash_join().inner->type);
3589 EXPECT_STREQ("t3", root->hash_join().inner->table_scan().table->alias);
3590
3591 EXPECT_EQ(0, root->hash_join()
3592 .outer->hash_join()
3593 .join_predicate->expr->join_conditions.size());
3594 {
3595 const Mem_root_array<Item_eq_base *> &equijoin_conditions =
3596 root->hash_join()
3597 .outer->hash_join()
3598 .join_predicate->expr->equijoin_conditions;
3599 ASSERT_EQ(1, equijoin_conditions.size());
3600 EXPECT_EQ(StringPrintf("(t1.x %s t2.x)", eq_op),
3601 ItemToString(equijoin_conditions[0]));
3602 }
3603
3604 ClearFakeTables();
3605 }
3606 }
3607
3608 TEST_F(HypergraphOptimizerTest, HashJoinWithEquijoinHyperpredicate) {
3609 Query_block *query_block = ParseAndResolve(
3610 "SELECT 1 FROM t1, t2, t3 WHERE t1.x = t2.x + t3.x AND t2.y = t3.y",
3611 /*nullable=*/true);
3612
3613 // Sizes that make t1 HJ (t2 HJ t3) the preferred join order.
3614 m_fake_tables["t1"]->file->stats.records = 100000;
3615 m_fake_tables["t1"]->file->stats.data_file_length = 1000e6;
3616 m_fake_tables["t2"]->file->stats.records = 100;
3617 m_fake_tables["t2"]->file->stats.data_file_length = 100e6;
3618 m_fake_tables["t3"]->file->stats.records = 10;
3619 m_fake_tables["t3"]->file->stats.data_file_length = 10e6;
3620
3621 string trace;
3622 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
3623 SCOPED_TRACE(trace); // Prints out the trace on failure.
3624 // Prints out the query plan on failure.
3625 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3626 /*is_root_of_join=*/true));
3627
3628 // The topmost path should be a HASH_JOIN with an equijoin predicate.
3629 // Previously, the hyperpredicate would be an "extra" condition, not an
3630 // equijoin condition.
3631 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
3632 RelationalExpression *expr = root->hash_join().join_predicate->expr;
3633 EXPECT_EQ("(t1.x = (t2.x + t3.x))", ItemsToString(expr->equijoin_conditions));
3634 EXPECT_EQ("(none)", ItemsToString(expr->join_conditions));
3635
3636 AccessPath *outer = root->hash_join().outer;
3637 ASSERT_EQ(AccessPath::TABLE_SCAN, outer->type);
3638 EXPECT_STREQ("t1", outer->table_scan().table->alias);
3639
3640 AccessPath *inner = root->hash_join().inner;
3641 ASSERT_EQ(AccessPath::HASH_JOIN, inner->type);
3642 RelationalExpression *inner_expr = inner->hash_join().join_predicate->expr;
3643 EXPECT_EQ("(t2.y = t3.y)", ItemsToString(inner_expr->equijoin_conditions));
3644 EXPECT_EQ("(none)", ItemsToString(inner_expr->join_conditions));
3645
3646 ASSERT_EQ(AccessPath::TABLE_SCAN, inner->hash_join().outer->type);
3647 ASSERT_EQ(AccessPath::TABLE_SCAN, inner->hash_join().inner->type);
3648 EXPECT_STREQ("t2", inner->hash_join().outer->table_scan().table->alias);
3649 EXPECT_STREQ("t3", inner->hash_join().inner->table_scan().table->alias);
3650 }
3651
3652 TEST_F(HypergraphOptimizerTest, HashJoinWithNonEquijoinHyperpredicate) {
3653 Query_block *query_block = ParseAndResolve(
3654 "SELECT 1 FROM t1 LEFT JOIN t2 JOIN t3 ON t2.y=t3.y ON t1.x+t2.x=t3.x",
3655 /*nullable=*/true);
3656
3657 // Sizes that make t1 HJ (t2 HJ t3) the preferred join order.
3658 m_fake_tables["t1"]->file->stats.records = 100000;
3659 m_fake_tables["t1"]->file->stats.data_file_length = 1000e6;
3660 m_fake_tables["t2"]->file->stats.records = 100;
3661 m_fake_tables["t2"]->file->stats.data_file_length = 100e6;
3662 m_fake_tables["t3"]->file->stats.records = 10;
3663 m_fake_tables["t3"]->file->stats.data_file_length = 10e6;
3664
3665 string trace;
3666 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
3667 SCOPED_TRACE(trace); // Prints out the trace on failure.
3668 // Prints out the query plan on failure.
3669 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3670 /*is_root_of_join=*/true));
3671
3672 // The topmost path should be a HASH_JOIN with a non-equijoin hyperpredicate.
3673 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
3674 RelationalExpression *expr = root->hash_join().join_predicate->expr;
3675 EXPECT_EQ("(none)", ItemsToString(expr->equijoin_conditions));
3676 EXPECT_EQ("((t1.x + t2.x) = t3.x)", ItemsToString(expr->join_conditions));
3677
3678 AccessPath *outer = root->hash_join().outer;
3679 ASSERT_EQ(AccessPath::TABLE_SCAN, outer->type);
3680 EXPECT_STREQ("t1", outer->table_scan().table->alias);
3681
3682 AccessPath *inner = root->hash_join().inner;
3683 ASSERT_EQ(AccessPath::HASH_JOIN, inner->type);
3684 RelationalExpression *inner_expr = inner->hash_join().join_predicate->expr;
3685 EXPECT_EQ("(t2.y = t3.y)", ItemsToString(inner_expr->equijoin_conditions));
3686 EXPECT_EQ("(none)", ItemsToString(inner_expr->join_conditions));
3687
3688 ASSERT_EQ(AccessPath::TABLE_SCAN, inner->hash_join().outer->type);
3689 ASSERT_EQ(AccessPath::TABLE_SCAN, inner->hash_join().inner->type);
3690 EXPECT_STREQ("t2", inner->hash_join().outer->table_scan().table->alias);
3691 EXPECT_STREQ("t3", inner->hash_join().inner->table_scan().table->alias);
3692 }
3693
3694 TEST_F(HypergraphOptimizerTest, HashJoinWithSubqueryPredicate) {
3695 Query_block *query_block = ParseAndResolve(
3696 "SELECT 1 FROM t1 JOIN t2 JOIN t3 ON (t1.y = t2.y)"
3697 "WHERE t3.x = t2.x and (t3.x > ALL (SELECT 4 FROM t4) OR (t3.y = t2.y))",
3698 /*nullable=*/true);
3699
3700 // Resolve the subqueries too.
3701 for (Query_expression *expr = query_block->first_inner_query_expression();
3702 expr != nullptr; expr = expr->next_query_expression()) {
3703 Query_block *subquery = expr->first_query_block();
3704 ResolveQueryBlock(m_thd, subquery, /*nullable=*/true, &m_fake_tables);
3705 string trace;
3706 AccessPath *subquery_path =
3707 FindBestQueryPlanAndFinalize(m_thd, subquery, &trace);
3708 SCOPED_TRACE(trace); // Prints out the trace on failure.
3709 ASSERT_NE(nullptr, subquery_path);
3710 }
3711
3712 COND_EQUAL *cond_equal = nullptr;
3713 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
3714 &query_block->m_table_nest,
3715 &query_block->cond_value));
3716
3717 // Sizes that make t1 HJ (t2 HJ t3) the preferred join order.
3718 m_fake_tables["t1"]->file->stats.records = 100000;
3719 m_fake_tables["t1"]->file->stats.data_file_length = 1000e6;
3720 m_fake_tables["t2"]->file->stats.records = 100;
3721 m_fake_tables["t2"]->file->stats.data_file_length = 100e6;
3722 m_fake_tables["t3"]->file->stats.records = 10;
3723 m_fake_tables["t3"]->file->stats.data_file_length = 10e6;
3724
3725 string trace;
3726 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
3727 SCOPED_TRACE(trace); // Prints out the trace on failure.
3728
3729 // The top-level path should be a filter access path with a
3730 // subquery. The subquery should not be moved to the join
3731 // predicates of the HASH JOIN.
3732 ASSERT_EQ(AccessPath::FILTER, root->type);
3733 EXPECT_EQ(
3734 ItemToString(root->filter().condition),
3735 "(<not>((t3.x <= (select #2))) or ((t1.y = t2.y) and (t2.y = t3.y)))");
3736
3737 // Verify that we have (t1 HJ (t2 HJ t3 ON (t3.x = t2.x)) ON (t1.y= t2.y)))
3738 AccessPath *join = root->filter().child;
3739 ASSERT_EQ(AccessPath::HASH_JOIN, join->type);
3740 const Mem_root_array<Item_eq_base *> &equijoin_conditions_t1t2 =
3741 join->hash_join().join_predicate->expr->equijoin_conditions;
3742 EXPECT_EQ(1, equijoin_conditions_t1t2.size());
3743 EXPECT_EQ("(t1.y = t2.y)", ItemToString(equijoin_conditions_t1t2[0]));
3744
3745 AccessPath *t1 = join->hash_join().outer;
3746 ASSERT_EQ(AccessPath::TABLE_SCAN, t1->type);
3747 EXPECT_EQ(m_fake_tables["t1"], t1->table_scan().table);
3748
3749 AccessPath *inner = join->hash_join().inner;
3750 ASSERT_EQ(AccessPath::HASH_JOIN, inner->type);
3751
3752 const Mem_root_array<Item_eq_base *> &equijoin_conditions_t2t3 =
3753 inner->hash_join().join_predicate->expr->equijoin_conditions;
3754 EXPECT_EQ(1, equijoin_conditions_t2t3.size());
3755 EXPECT_EQ("(t3.x = t2.x)", ItemToString(equijoin_conditions_t2t3[0]));
3756
3757 AccessPath *t2 = inner->hash_join().outer;
3758 ASSERT_EQ(AccessPath::TABLE_SCAN, t2->type);
3759 EXPECT_STREQ("t2", t2->table_scan().table->alias);
3760 AccessPath *t3 = inner->hash_join().inner;
3761 ASSERT_EQ(AccessPath::TABLE_SCAN, t3->type);
3762 EXPECT_STREQ("t3", t3->table_scan().table->alias);
3763 }
3764
3765 namespace {
3766
3767 struct FullTextParam {
3768 const char *query;
3769 bool expect_filter;
3770 bool expect_index;
3771 };
3772
3773 std::ostream &operator<<(std::ostream &os, const FullTextParam &param) {
3774 return os << param.query;
3775 }
3776
3777 } // namespace
3778
3779 using HypergraphFullTextTest = OptimizerTestWithParam<FullTextParam>;
3780
3781 TEST_P(HypergraphFullTextTest, FullTextSearch) {
3782 SCOPED_TRACE(GetParam().query);
3783
3784 // CREATE TABLE t1(x VARCHAR(100)).
3785 Base_mock_field_varstring column1(/*length=*/100, /*share=*/nullptr);
3786 column1.field_name = "x";
3787 Fake_TABLE *t1 = new (m_thd->mem_root) Fake_TABLE(&column1);
3788 t1->file->stats.records = 10000;
3789 m_fake_tables["t1"] = t1;
3790 t1->set_created();
3791
3792 // CREATE FULLTEXT INDEX idx ON t1(x).
3793 down_cast<Mock_HANDLER *>(t1->file)->set_ha_table_flags(
3794 t1->file->ha_table_flags() | HA_CAN_FULLTEXT);
3795 t1->create_index(&column1, /*column2=*/nullptr, ulong{HA_FULLTEXT});
3796
3797 Query_block *query_block = ParseAndResolve(GetParam().query,
3798 /*nullable=*/false);
3799 ASSERT_NE(nullptr, query_block);
3800
3801 string trace;
3802 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
3803 SCOPED_TRACE(trace); // Prints out the trace on failure.
3804 // Prints out the query plan on failure.
3805 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3806 /*is_root_of_join=*/true));
3807 ASSERT_NE(nullptr, root);
3808
3809 AccessPath *path = root;
3810
3811 if (GetParam().expect_filter) {
3812 ASSERT_EQ(AccessPath::FILTER, path->type);
3813 path = path->filter().child;
3814 }
3815
3816 if (GetParam().expect_index) {
3817 ASSERT_EQ(AccessPath::FULL_TEXT_SEARCH, path->type);
3818 // Since there is no ORDER BY in the query, expect an unordered index scan.
3819 EXPECT_FALSE(query_block->is_ordered());
3820 EXPECT_FALSE(path->full_text_search().use_order);
3821 } else {
3822 EXPECT_EQ(AccessPath::TABLE_SCAN, path->type);
3823 }
3824 }
3825
3826 static constexpr FullTextParam full_text_queries[] = {
3827 // Expect a full-text index scan if the predicate returns true for positive
3828 // scores only. Expect the index scan to have a filter on top of it if the
3829 // predicate does not return true for all non-zero scores.
3830 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc' IN BOOLEAN MODE)",
3831 /*expect_filter=*/false,
3832 /*expect_index=*/true},
3833 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc')",
3834 /*expect_filter=*/false,
3835 /*expect_index=*/true},
3836 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc') > 0",
3837 /*expect_filter=*/false,
3838 /*expect_index=*/true},
3839 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc') > 0.5",
3840 /*expect_filter=*/true,
3841 /*expect_index=*/true},
3842 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc') >= 0.5",
3843 /*expect_filter=*/true,
3844 /*expect_index=*/true},
3845 {"SELECT t1.x FROM t1 WHERE 0.5 < MATCH(t1.x) AGAINST ('abc')",
3846 /*expect_filter=*/true,
3847 /*expect_index=*/true},
3848 {"SELECT t1.x FROM t1 WHERE 0.5 <= MATCH(t1.x) AGAINST ('abc')",
3849 /*expect_filter=*/true,
3850 /*expect_index=*/true},
3851
3852 // Expect a table scan if the predicate might return true for zero or
3853 // negative scores. A filter node is added on top for the predicate.
3854 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc') < 0.5",
3855 /*expect_filter=*/true,
3856 /*expect_index=*/false},
3857 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc') <= 0.5",
3858 /*expect_filter=*/true,
3859 /*expect_index=*/false},
3860 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc') >= 0",
3861 /*expect_filter=*/true,
3862 /*expect_index=*/false},
3863 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc') > -1",
3864 /*expect_filter=*/true,
3865 /*expect_index=*/false},
3866 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc') <> 0.5",
3867 /*expect_filter=*/true,
3868 /*expect_index=*/false},
3869 {"SELECT t1.x FROM t1 WHERE 0.5 > MATCH(t1.x) AGAINST ('abc')",
3870 /*expect_filter=*/true,
3871 /*expect_index=*/false},
3872 {"SELECT t1.x FROM t1 WHERE 0.5 >= MATCH(t1.x) AGAINST ('abc')",
3873 /*expect_filter=*/true,
3874 /*expect_index=*/false},
3875
3876 // Expect a table scan if the predicate checks for an exact score. (Not
3877 // because an index scan cannot be used, but because it's not a very useful
3878 // query, so we haven't optimized for it.)
3879 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc') = 0.5",
3880 /*expect_filter=*/true,
3881 /*expect_index=*/false},
3882
3883 // Expect a table scan if the predicate is a disjunction.
3884 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc' IN BOOLEAN MODE) "
3885 "OR MATCH(t1.x) AGAINST ('xyz' IN BOOLEAN MODE)",
3886 /*expect_filter=*/true,
3887 /*expect_index=*/false},
3888
3889 // Expect an index scan if the predicate is a conjunction. A filter node
3890 // will be added for the predicate that is not subsumed by the index.
3891 {"SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc' IN BOOLEAN MODE) "
3892 "AND MATCH(t1.x) AGAINST ('xyz' IN BOOLEAN MODE)",
3893 /*expect_filter=*/true,
3894 /*expect_index=*/true},
3895 };
3896 INSTANTIATE_TEST_SUITE_P(FullTextQueries, HypergraphFullTextTest,
3897 ::testing::ValuesIn(full_text_queries));
3898
3899 TEST_F(HypergraphOptimizerTest, FullTextSearchNoHashJoin) {
3900 // CREATE TABLE t1(x VARCHAR(100)).
3901 Base_mock_field_varstring column1(/*length=*/100, /*share=*/nullptr);
3902 column1.field_name = "x";
3903 Fake_TABLE *t1 = new (m_thd->mem_root) Fake_TABLE(&column1);
3904 m_fake_tables["t1"] = t1;
3905 t1->set_created();
3906
3907 // CREATE FULLTEXT INDEX idx ON t1(x).
3908 down_cast<Mock_HANDLER *>(t1->file)->set_ha_table_flags(
3909 t1->file->ha_table_flags() | HA_CAN_FULLTEXT);
3910 t1->create_index(&column1, /*column2=*/nullptr, ulong{HA_FULLTEXT});
3911
3912 Query_block *query_block = ParseAndResolve(
3913 "SELECT MATCH(t1.x) AGAINST ('abc') FROM t1, t2 WHERE t1.x = t2.x",
3914 /*nullable=*/false);
3915 ASSERT_NE(nullptr, query_block);
3916
3917 // Add some rows to make a hash join more tempting than a nested loop join.
3918 m_fake_tables["t1"]->file->stats.records = 1000;
3919 m_fake_tables["t2"]->file->stats.records = 1000;
3920
3921 string trace;
3922 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
3923 SCOPED_TRACE(trace); // Prints out the trace on failure.
3924 // Prints out the query plan on failure.
3925 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3926 /*is_root_of_join=*/true));
3927 ASSERT_NE(nullptr, root);
3928
3929 // FTS does not work well with hash join, so we force nested loop join for
3930 // this query.
3931 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
3932 }
3933
3934 TEST_F(HypergraphOptimizerTest, FullTextCanSkipRanking) {
3935 // CREATE TABLE t1(x VARCHAR(100)).
3936 Base_mock_field_varstring column1(/*length=*/100, /*share=*/nullptr);
3937 column1.field_name = "x";
3938 Fake_TABLE *t1 = new (m_thd->mem_root) Fake_TABLE(&column1);
3939 m_fake_tables["t1"] = t1;
3940 t1->set_created();
3941
3942 // CREATE FULLTEXT INDEX idx ON t1(x).
3943 down_cast<Mock_HANDLER *>(t1->file)->set_ha_table_flags(
3944 t1->file->ha_table_flags() | HA_CAN_FULLTEXT);
3945 t1->create_index(&column1, /*column2=*/nullptr, ulong{HA_FULLTEXT});
3946
3947 Query_block *query_block = ParseAndResolve(
3948 "SELECT MATCH(t1.x) AGAINST ('a') FROM t1 WHERE "
3949 "MATCH(t1.x) AGAINST ('a') AND "
3950 "MATCH(t1.x) AGAINST ('b') AND "
3951 "MATCH(t1.x) AGAINST ('c') AND MATCH(t1.x) AGAINST ('c') > 0.1",
3952 /*nullable=*/false);
3953 ASSERT_NE(nullptr, query_block);
3954
3955 string trace;
3956 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
3957 SCOPED_TRACE(trace); // Prints out the trace on failure.
3958 // Prints out the query plan on failure.
3959 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
3960 /*is_root_of_join=*/true));
3961 ASSERT_NE(nullptr, root);
3962
3963 const List<Item_func_match> *ftfuncs = query_block->ftfunc_list;
3964 ASSERT_EQ(5, ftfuncs->size());
3965
3966 // MATCH(t1.x) AGAINST ('a') needs ranking because it is used in the
3967 // SELECT list.
3968 EXPECT_EQ("(match t1.x against ('a'))", ItemToString((*ftfuncs)[0]));
3969 EXPECT_EQ(nullptr, (*ftfuncs)[0]->master);
3970 EXPECT_FALSE((*ftfuncs)[0]->can_skip_ranking());
3971 EXPECT_EQ((*ftfuncs)[0], (*ftfuncs)[1]->get_master());
3972
3973 // MATCH (t1.x) AGAINST ('b') does not need ranking, since it's only used
3974 // in a standalone predicate.
3975 EXPECT_EQ("(match t1.x against ('b'))", ItemToString((*ftfuncs)[2]));
3976 EXPECT_EQ(nullptr, (*ftfuncs)[2]->master);
3977 EXPECT_TRUE((*ftfuncs)[2]->can_skip_ranking());
3978
3979 // MATCH (t1.x) AGAINST ('c') needs ranking because one of the predicates
3980 // requires it to return > 0.1.
3981 EXPECT_EQ("(match t1.x against ('c'))", ItemToString((*ftfuncs)[3]));
3982 EXPECT_EQ(nullptr, (*ftfuncs)[3]->master);
3983 EXPECT_FALSE((*ftfuncs)[3]->can_skip_ranking());
3984 EXPECT_EQ((*ftfuncs)[3], (*ftfuncs)[4]->get_master());
3985 }
3986
3987 TEST_F(HypergraphOptimizerTest, FullTextAvoidDescSort) {
3988 // CREATE TABLE t1(x VARCHAR(100)).
3989 Base_mock_field_varstring column1(/*length=*/100, /*share=*/nullptr);
3990 column1.field_name = "x";
3991 Fake_TABLE *t1 = new (m_thd->mem_root) Fake_TABLE(&column1);
3992 t1->file->stats.records = 10000;
3993 m_fake_tables["t1"] = t1;
3994 t1->set_created();
3995
3996 // CREATE FULLTEXT INDEX idx ON t1(x).
3997 down_cast<Mock_HANDLER *>(t1->file)->set_ha_table_flags(
3998 t1->file->ha_table_flags() | HA_CAN_FULLTEXT);
3999 t1->create_index(&column1, /*column2=*/nullptr, ulong{HA_FULLTEXT});
4000
4001 Query_block *query_block = ParseAndResolve(
4002 "SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc') "
4003 "ORDER BY MATCH(t1.x) AGAINST ('abc') DESC",
4004 /*nullable=*/false);
4005 ASSERT_NE(nullptr, query_block);
4006
4007 string trace;
4008 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4009 SCOPED_TRACE(trace); // Prints out the trace on failure.
4010 // Prints out the query plan on failure.
4011 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4012 /*is_root_of_join=*/true));
4013 ASSERT_NE(nullptr, root);
4014
4015 // Expect no sort in the plan. An ordered index scan is used.
4016 ASSERT_EQ(AccessPath::FULL_TEXT_SEARCH, root->type);
4017 EXPECT_TRUE(root->full_text_search().use_order);
4018 }
4019
4020 TEST_F(HypergraphOptimizerTest, FullTextAscSort) {
4021 // CREATE TABLE t1(x VARCHAR(100)).
4022 Base_mock_field_varstring column1(/*length=*/100, /*share=*/nullptr);
4023 column1.field_name = "x";
4024 Fake_TABLE *t1 = new (m_thd->mem_root) Fake_TABLE(&column1);
4025 t1->file->stats.records = 10000;
4026 m_fake_tables["t1"] = t1;
4027 t1->set_created();
4028
4029 // CREATE FULLTEXT INDEX idx ON t1(x).
4030 down_cast<Mock_HANDLER *>(t1->file)->set_ha_table_flags(
4031 t1->file->ha_table_flags() | HA_CAN_FULLTEXT);
4032 t1->create_index(&column1, /*column2=*/nullptr, ulong{HA_FULLTEXT});
4033
4034 Query_block *query_block = ParseAndResolve(
4035 "SELECT t1.x FROM t1 WHERE MATCH(t1.x) AGAINST ('abc') "
4036 "ORDER BY MATCH(t1.x) AGAINST ('abc') ASC",
4037 /*nullable=*/false);
4038 ASSERT_NE(nullptr, query_block);
4039
4040 string trace;
4041 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4042 SCOPED_TRACE(trace); // Prints out the trace on failure.
4043 // Prints out the query plan on failure.
4044 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4045 /*is_root_of_join=*/true));
4046 ASSERT_NE(nullptr, root);
4047
4048 // The full-text index can only return results in descending order, so expect
4049 // a SORT node on top.
4050 EXPECT_EQ(AccessPath::SORT, root->type);
4051 }
4052
4053 TEST_F(HypergraphOptimizerTest, FullTextDescSortNoPredicate) {
4054 // CREATE TABLE t1(x VARCHAR(100)).
4055 Base_mock_field_varstring column1(/*length=*/100, /*share=*/nullptr);
4056 column1.field_name = "x";
4057 Fake_TABLE *t1 = new (m_thd->mem_root) Fake_TABLE(&column1);
4058 t1->file->stats.records = 10000;
4059 m_fake_tables["t1"] = t1;
4060 t1->set_created();
4061
4062 // CREATE FULLTEXT INDEX idx ON t1(x).
4063 down_cast<Mock_HANDLER *>(t1->file)->set_ha_table_flags(
4064 t1->file->ha_table_flags() | HA_CAN_FULLTEXT);
4065 t1->create_index(&column1, /*column2=*/nullptr, ulong{HA_FULLTEXT});
4066
4067 Query_block *query_block = ParseAndResolve(
4068 "SELECT t1.x FROM t1 ORDER BY MATCH(t1.x) AGAINST ('abc') DESC",
4069 /*nullable=*/false);
4070 ASSERT_NE(nullptr, query_block);
4071
4072 string trace;
4073 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4074 SCOPED_TRACE(trace); // Prints out the trace on failure.
4075 // Prints out the query plan on failure.
4076 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4077 /*is_root_of_join=*/true));
4078 ASSERT_NE(nullptr, root);
4079
4080 // A full-text index scan cannot be used for ordering when there is no
4081 // predicate, since the index scan doesn't return all rows (only those with a
4082 // positive score). Expect a SORT node on top.
4083 EXPECT_EQ(AccessPath::SORT, root->type);
4084 }
4085
4086 TEST_F(HypergraphOptimizerTest, DistinctIsDoneAsSort) {
4087 Query_block *query_block =
4088 ParseAndResolve("SELECT DISTINCT t1.y, t1.x FROM t1", /*nullable=*/true);
4089
4090 string trace;
4091 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4092 SCOPED_TRACE(trace); // Prints out the trace on failure.
4093 // Prints out the query plan on failure.
4094 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4095 /*is_root_of_join=*/true));
4096
4097 ASSERT_EQ(AccessPath::SORT, root->type);
4098 Filesort *sort = root->sort().filesort;
4099 ASSERT_EQ(2, sort->sort_order_length());
4100 EXPECT_EQ("t1.y", ItemToString(sort->sortorder[0].item));
4101 EXPECT_EQ("t1.x", ItemToString(sort->sortorder[1].item));
4102 EXPECT_TRUE(sort->m_remove_duplicates);
4103
4104 EXPECT_EQ(AccessPath::TABLE_SCAN, root->sort().child->type);
4105
4106 query_block->cleanup(/*full=*/true);
4107 }
4108
4109 TEST_F(HypergraphOptimizerTest, DistinctIsSubsumedByGroup) {
4110 Query_block *query_block = ParseAndResolve(
4111 "SELECT DISTINCT t1.y, t1.x, 3 FROM t1 GROUP BY t1.x, t1.y",
4112 /*nullable=*/true);
4113
4114 string trace;
4115 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4116 SCOPED_TRACE(trace); // Prints out the trace on failure.
4117 // Prints out the query plan on failure.
4118 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4119 /*is_root_of_join=*/true));
4120
4121 ASSERT_EQ(AccessPath::AGGREGATE, root->type);
4122 AccessPath *child = root->aggregate().child;
4123
4124 EXPECT_EQ(AccessPath::SORT, child->type);
4125 EXPECT_FALSE(child->sort().filesort->m_remove_duplicates);
4126 }
4127
4128 TEST_F(HypergraphOptimizerTest, DistinctWithOrderBy) {
4129 m_thd->variables.sql_mode &= ~MODE_ONLY_FULL_GROUP_BY;
4130 Query_block *query_block =
4131 ParseAndResolve("SELECT DISTINCT t1.y FROM t1 ORDER BY t1.x, t1.y",
4132 /*nullable=*/true);
4133 m_thd->variables.sql_mode |= MODE_ONLY_FULL_GROUP_BY;
4134
4135 string trace;
4136 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4137 SCOPED_TRACE(trace); // Prints out the trace on failure.
4138 // Prints out the query plan on failure.
4139 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4140 /*is_root_of_join=*/true));
4141
4142 ASSERT_EQ(AccessPath::SORT, root->type);
4143 Filesort *sort = root->sort().filesort;
4144 ASSERT_EQ(2, sort->sort_order_length());
4145 EXPECT_EQ("t1.x", ItemToString(sort->sortorder[0].item));
4146 EXPECT_EQ("t1.y", ItemToString(sort->sortorder[1].item));
4147 EXPECT_FALSE(sort->m_remove_duplicates);
4148
4149 // We can't coalesce the two sorts, due to the deduplication in this step.
4150 AccessPath *child = root->sort().child;
4151 ASSERT_EQ(AccessPath::SORT, child->type);
4152 Filesort *sort2 = child->sort().filesort;
4153 ASSERT_EQ(1, sort2->sort_order_length());
4154 EXPECT_EQ("t1.y", ItemToString(sort2->sortorder[0].item));
4155 EXPECT_TRUE(sort2->m_remove_duplicates);
4156
4157 EXPECT_EQ(AccessPath::TABLE_SCAN, child->sort().child->type);
4158
4159 query_block->cleanup(/*full=*/true);
4160 }
4161
4162 TEST_F(HypergraphOptimizerTest, DistinctSubsumesOrderBy) {
4163 Query_block *query_block =
4164 ParseAndResolve("SELECT DISTINCT t1.y, t1.x FROM t1 ORDER BY t1.x",
4165 /*nullable=*/true);
4166
4167 string trace;
4168 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4169 SCOPED_TRACE(trace); // Prints out the trace on failure.
4170 // Prints out the query plan on failure.
4171 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4172 /*is_root_of_join=*/true));
4173
4174 ASSERT_EQ(AccessPath::SORT, root->type);
4175 Filesort *sort = root->sort().filesort;
4176 ASSERT_EQ(2, sort->sort_order_length());
4177 EXPECT_EQ("t1.x", ItemToString(sort->sortorder[0].item));
4178 EXPECT_EQ("t1.y", ItemToString(sort->sortorder[1].item));
4179 EXPECT_TRUE(sort->m_remove_duplicates);
4180
4181 // No separate sort for ORDER BY.
4182 EXPECT_EQ(AccessPath::TABLE_SCAN, root->sort().child->type);
4183
4184 query_block->cleanup(/*full=*/true);
4185 }
4186
4187 TEST_F(HypergraphOptimizerTest, SortAheadSingleTable) {
4188 Query_block *query_block =
4189 ParseAndResolve("SELECT t1.x, t2.x FROM t1, t2 ORDER BY t2.x",
4190 /*nullable=*/true);
4191
4192 m_fake_tables["t1"]->file->stats.records = 100;
4193 m_fake_tables["t2"]->file->stats.records = 10000;
4194 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
4195 m_fake_tables["t2"]->file->stats.data_file_length = 100e6;
4196
4197 string trace;
4198 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4199 SCOPED_TRACE(trace); // Prints out the trace on failure.
4200 // Prints out the query plan on failure.
4201 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4202 /*is_root_of_join=*/true));
4203
4204 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
4205 EXPECT_EQ(JoinType::INNER, root->nested_loop_join().join_type);
4206
4207 // The sort should be on t2, which should be on the outer side.
4208 AccessPath *outer = root->nested_loop_join().outer;
4209 ASSERT_EQ(AccessPath::SORT, outer->type);
4210 Filesort *sort = outer->sort().filesort;
4211 ASSERT_EQ(1, sort->sort_order_length());
4212 EXPECT_EQ("t2.x", ItemToString(sort->sortorder[0].item));
4213 EXPECT_FALSE(sort->m_remove_duplicates);
4214
4215 AccessPath *outer_child = outer->sort().child;
4216 ASSERT_EQ(AccessPath::TABLE_SCAN, outer_child->type);
4217 EXPECT_STREQ("t2", outer_child->table_scan().table->alias);
4218
4219 // The inner side should just be t1, no sort.
4220 AccessPath *inner = root->nested_loop_join().inner;
4221 ASSERT_EQ(AccessPath::TABLE_SCAN, inner->type);
4222 EXPECT_STREQ("t1", inner->table_scan().table->alias);
4223
4224 query_block->cleanup(/*full=*/true);
4225 }
4226
4227 TEST_F(HypergraphOptimizerTest, CannotSortAheadBeforeBothTablesAreAvailable) {
4228 Query_block *query_block =
4229 ParseAndResolve("SELECT t1.x, t2.x FROM t1, t2 ORDER BY t1.x, t2.x",
4230 /*nullable=*/true);
4231
4232 m_fake_tables["t1"]->file->stats.records = 100;
4233 m_fake_tables["t2"]->file->stats.records = 10000;
4234 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
4235 m_fake_tables["t2"]->file->stats.data_file_length = 100e6;
4236
4237 string trace;
4238 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4239 SCOPED_TRACE(trace); // Prints out the trace on failure.
4240 // Prints out the query plan on failure.
4241 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4242 /*is_root_of_join=*/true));
4243
4244 // The sort should be at the root, because the sort cannot be pushed
4245 // to e.g. t2 (unlike in the previous test); t1.x isn't available yet.
4246 ASSERT_EQ(AccessPath::SORT, root->type);
4247
4248 // Check that there is no pushed sort in the tree.
4249 WalkAccessPaths(root->sort().child, /*join=*/nullptr,
4250 WalkAccessPathPolicy::ENTIRE_TREE,
4251 [&](const AccessPath *path, const JOIN *) {
4252 EXPECT_NE(AccessPath::SORT, path->type);
4253 return false;
4254 });
4255
4256 query_block->cleanup(/*full=*/true);
4257 }
4258
4259 TEST_F(HypergraphOptimizerTest, SortAheadTwoTables) {
4260 Query_block *query_block = ParseAndResolve(
4261 "SELECT t1.x, t2.x, t3.x FROM t1, t2, t3 ORDER BY t1.x, t2.x",
4262 /*nullable=*/true);
4263
4264 m_fake_tables["t1"]->file->stats.records = 100;
4265 m_fake_tables["t2"]->file->stats.records = 100;
4266 m_fake_tables["t3"]->file->stats.records = 10000;
4267 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
4268 m_fake_tables["t2"]->file->stats.data_file_length = 1e6;
4269 m_fake_tables["t3"]->file->stats.data_file_length = 100e6;
4270
4271 string trace;
4272 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4273 SCOPED_TRACE(trace); // Prints out the trace on failure.
4274 // Prints out the query plan on failure.
4275 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4276 /*is_root_of_join=*/true));
4277
4278 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
4279 EXPECT_EQ(JoinType::INNER, root->nested_loop_join().join_type);
4280
4281 // There should be a sort pushed down, with t1 and t2 below.
4282 AccessPath *outer = root->nested_loop_join().outer;
4283 ASSERT_EQ(AccessPath::SORT, outer->type);
4284 Filesort *sort = outer->sort().filesort;
4285 ASSERT_EQ(2, sort->sort_order_length());
4286 EXPECT_EQ("t1.x", ItemToString(sort->sortorder[0].item));
4287 EXPECT_EQ("t2.x", ItemToString(sort->sortorder[1].item));
4288 EXPECT_FALSE(sort->m_remove_duplicates);
4289
4290 // We don't check that t1 and t2 are actually below there
4291 // (and we don't care about the join type chosen, even though
4292 // it should usually be hash join), but we do check
4293 // that there are no more sorts.
4294 WalkAccessPaths(outer->sort().child, /*join=*/nullptr,
4295 WalkAccessPathPolicy::ENTIRE_TREE,
4296 [&](const AccessPath *path, const JOIN *) {
4297 EXPECT_NE(AccessPath::SORT, path->type);
4298 return false;
4299 });
4300
4301 // The inner side should just be t3, no sort.
4302 AccessPath *inner = root->nested_loop_join().inner;
4303 ASSERT_EQ(AccessPath::TABLE_SCAN, inner->type);
4304 EXPECT_STREQ("t3", inner->table_scan().table->alias);
4305
4306 query_block->cleanup(/*full=*/true);
4307 }
4308
4309 TEST_F(HypergraphOptimizerTest, NoSortAheadOnNondeterministicFunction) {
4310 Query_block *query_block =
4311 ParseAndResolve("SELECT t1.x, t2.x FROM t1, t2 ORDER BY t1.x + RAND()",
4312 /*nullable=*/true);
4313
4314 m_fake_tables["t1"]->file->stats.records = 100;
4315 m_fake_tables["t2"]->file->stats.records = 100;
4316 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
4317 m_fake_tables["t2"]->file->stats.data_file_length = 1e6;
4318
4319 string trace;
4320 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4321 SCOPED_TRACE(trace); // Prints out the trace on failure.
4322 // Prints out the query plan on failure.
4323 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4324 /*is_root_of_join=*/true));
4325
4326 // The sort should _not_ be pushed to t1, but kept at the top.
4327 // We don't care about the rest of the plan.
4328 ASSERT_EQ(AccessPath::SORT, root->type);
4329
4330 query_block->cleanup(/*full=*/true);
4331 }
4332
4333 TEST_F(HypergraphOptimizerTest, SortAheadDueToEquivalence) {
4334 Query_block *query_block = ParseAndResolve(
4335 "SELECT t1.x, t2.x FROM t1 JOIN t2 ON t1.x=t2.x ORDER BY t1.x, t2.x "
4336 "LIMIT 10",
4337 /*nullable=*/true);
4338
4339 m_fake_tables["t1"]->file->stats.records = 100;
4340 m_fake_tables["t2"]->file->stats.records = 10000;
4341 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
4342 m_fake_tables["t2"]->file->stats.data_file_length = 100e6;
4343
4344 string trace;
4345 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4346 SCOPED_TRACE(trace); // Prints out the trace on failure.
4347 // Prints out the query plan on failure.
4348 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4349 /*is_root_of_join=*/true));
4350
4351 ASSERT_EQ(AccessPath::LIMIT_OFFSET, root->type);
4352 EXPECT_EQ(10, root->limit_offset().limit);
4353
4354 // There should be no sort at the limit; join directly.
4355 AccessPath *join = root->limit_offset().child;
4356 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, join->type);
4357
4358 // The outer side should have a sort, on t1 only.
4359 AccessPath *outer = join->nested_loop_join().outer;
4360 ASSERT_EQ(AccessPath::SORT, outer->type);
4361 Filesort *sort = outer->sort().filesort;
4362 ASSERT_EQ(1, sort->sort_order_length());
4363 EXPECT_EQ("t1.x", ItemToString(sort->sortorder[0].item));
4364 EXPECT_FALSE(sort->m_remove_duplicates);
4365
4366 // And it should indeed be t1 that is sorted, since it's the
4367 // smallest one.
4368 AccessPath *t1 = outer->sort().child;
4369 ASSERT_EQ(AccessPath::TABLE_SCAN, t1->type);
4370 EXPECT_STREQ("t1", t1->table_scan().table->alias);
4371
4372 // The inner side should be t2, with the join condition as filter.
4373 AccessPath *inner = join->nested_loop_join().inner;
4374 ASSERT_EQ(AccessPath::FILTER, inner->type);
4375 EXPECT_EQ("(t1.x = t2.x)", ItemToString(inner->filter().condition));
4376
4377 AccessPath *t2 = inner->filter().child;
4378 ASSERT_EQ(AccessPath::TABLE_SCAN, t2->type);
4379 EXPECT_STREQ("t2", t2->table_scan().table->alias);
4380
4381 query_block->cleanup(/*full=*/true);
4382 }
4383
4384 TEST_F(HypergraphOptimizerTest, SortAheadDueToUniqueIndex) {
4385 Query_block *query_block = ParseAndResolve(
4386 "SELECT t1.x, t2.x FROM t1 JOIN t2 ON t1.x=t2.x "
4387 "ORDER BY t1.x, t2.x, t2.y LIMIT 10",
4388 /*nullable=*/true);
4389
4390 // Create a unique index on t2.x. This means that t2.y is now
4391 // redundant, and can (will) be reduced away when creating the homogenized
4392 // order.
4393 m_fake_tables["t2"]->create_index(m_fake_tables["t2"]->field[0],
4394 /*column2=*/nullptr, /*unique=*/true);
4395
4396 m_fake_tables["t1"]->file->stats.records = 200;
4397 m_fake_tables["t2"]->file->stats.records = 10000;
4398 m_fake_tables["t1"]->file->stats.data_file_length = 2e6;
4399 m_fake_tables["t2"]->file->stats.data_file_length = 100e6;
4400
4401 string trace;
4402 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4403 SCOPED_TRACE(trace); // Prints out the trace on failure.
4404 // Prints out the query plan on failure.
4405 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4406 /*is_root_of_join=*/true));
4407
4408 ASSERT_EQ(AccessPath::LIMIT_OFFSET, root->type);
4409 EXPECT_EQ(10, root->limit_offset().limit);
4410
4411 // There should be no sort at the limit; join directly.
4412 AccessPath *join = root->limit_offset().child;
4413 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, join->type);
4414
4415 // The outer side should have a sort, on t1 only.
4416 AccessPath *outer = join->nested_loop_join().outer;
4417 ASSERT_EQ(AccessPath::SORT, outer->type);
4418 Filesort *sort = outer->sort().filesort;
4419 ASSERT_EQ(1, sort->sort_order_length());
4420 EXPECT_EQ("t1.x", ItemToString(sort->sortorder[0].item));
4421 EXPECT_FALSE(sort->m_remove_duplicates);
4422
4423 // And it should indeed be t1 that is sorted, since it's the
4424 // smallest one.
4425 AccessPath *t1 = outer->sort().child;
4426 ASSERT_EQ(AccessPath::TABLE_SCAN, t1->type);
4427 EXPECT_STREQ("t1", t1->table_scan().table->alias);
4428
4429 // The inner side should be t2, with the join condition pushed down into an
4430 // EQ_REF.
4431 AccessPath *inner = join->nested_loop_join().inner;
4432 ASSERT_EQ(AccessPath::EQ_REF, inner->type);
4433 EXPECT_STREQ("t2", inner->eq_ref().table->alias);
4434
4435 query_block->cleanup(/*full=*/true);
4436 }
4437
4438 TEST_F(HypergraphOptimizerTest, NoSortAheadOnNonUniqueIndex) {
4439 Query_block *query_block = ParseAndResolve(
4440 "SELECT t1.x, t2.x FROM t1 JOIN t2 ON t1.x=t2.x "
4441 "ORDER BY t1.x, t2.x, t2.y LIMIT 10",
4442 /*nullable=*/true);
4443
4444 // With a non-unique index, there is no functional dependency,
4445 // and we should resort to sorting the largest table (t2).
4446 // The rest of the test is equal to SortAheadDueToUniqueIndex,
4447 // and we don't really verify it.
4448 m_fake_tables["t2"]->create_index(m_fake_tables["t2"]->field[0],
4449 /*column2=*/nullptr, /*unique=*/false);
4450
4451 m_fake_tables["t1"]->file->stats.records = 200;
4452 m_fake_tables["t2"]->file->stats.records = 10000;
4453 m_fake_tables["t1"]->file->stats.data_file_length = 2e6;
4454 m_fake_tables["t2"]->file->stats.data_file_length = 100e6;
4455
4456 string trace;
4457 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4458 SCOPED_TRACE(trace); // Prints out the trace on failure.
4459 // Prints out the query plan on failure.
4460 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4461 /*is_root_of_join=*/true));
4462
4463 ASSERT_EQ(AccessPath::LIMIT_OFFSET, root->type);
4464 EXPECT_EQ(10, root->limit_offset().limit);
4465
4466 AccessPath *join = root->limit_offset().child;
4467 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, join->type);
4468
4469 // The outer side should have a sort, on t2 only.
4470 AccessPath *outer = join->nested_loop_join().outer;
4471 ASSERT_EQ(AccessPath::SORT, outer->type);
4472 Filesort *sort = outer->sort().filesort;
4473 ASSERT_EQ(2, sort->sort_order_length());
4474 EXPECT_EQ("t2.x", ItemToString(sort->sortorder[0].item));
4475 EXPECT_EQ("t2.y", ItemToString(sort->sortorder[1].item));
4476 EXPECT_FALSE(sort->m_remove_duplicates);
4477
4478 query_block->cleanup(/*full=*/true);
4479 }
4480
4481 TEST_F(HypergraphOptimizerTest, ElideSortDueToBaseFilters) {
4482 Query_block *query_block = ParseAndResolve(
4483 "SELECT t1.x, t1.y FROM t1 WHERE t1.x=3 ORDER BY t1.x, t1.y",
4484 /*nullable=*/true);
4485
4486 m_fake_tables["t1"]->create_index(m_fake_tables["t1"]->field[0],
4487 /*column2=*/nullptr, /*unique=*/true);
4488 m_fake_tables["t1"]->file->stats.records = 100;
4489 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
4490
4491 string trace;
4492 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4493 SCOPED_TRACE(trace); // Prints out the trace on failure.
4494 // Prints out the query plan on failure.
4495 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4496 /*is_root_of_join=*/true));
4497
4498 // The sort should be elided entirely due to the unique index
4499 // and the constant lookup.
4500 ASSERT_EQ(AccessPath::EQ_REF, root->type);
4501
4502 query_block->cleanup(/*full=*/true);
4503 }
4504
4505 TEST_F(HypergraphOptimizerTest, ElideSortDueToDelayedFilters) {
4506 Query_block *query_block = ParseAndResolve(
4507 "SELECT t1.x, t1.y FROM t1 LEFT JOIN t2 ON t1.y=t2.y WHERE t2.x IS NULL "
4508 "ORDER BY t2.x, t2.y ",
4509 /*nullable=*/true);
4510
4511 m_fake_tables["t2"]->create_index(m_fake_tables["t2"]->field[0],
4512 /*column2=*/nullptr, /*unique=*/true);
4513 m_fake_tables["t1"]->file->stats.records = 100;
4514 m_fake_tables["t2"]->file->stats.records = 10000;
4515 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
4516 m_fake_tables["t2"]->file->stats.data_file_length = 100e6;
4517
4518 string trace;
4519 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4520 SCOPED_TRACE(trace); // Prints out the trace on failure.
4521 // Prints out the query plan on failure.
4522 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4523 /*is_root_of_join=*/true));
4524
4525 // We should have the IS NULL at the root, and no sort, due to the
4526 // functional dependency from t2.x to t2.y.
4527 ASSERT_EQ(AccessPath::FILTER, root->type);
4528 EXPECT_EQ("(t2.x is null)", ItemToString(root->filter().condition));
4529 WalkAccessPaths(root->filter().child, /*join=*/nullptr,
4530 WalkAccessPathPolicy::ENTIRE_TREE,
4531 [&](const AccessPath *path, const JOIN *) {
4532 EXPECT_NE(AccessPath::SORT, path->type);
4533 return false;
4534 });
4535
4536 query_block->cleanup(/*full=*/true);
4537 }
4538
4539 TEST_F(HypergraphOptimizerTest, ElideSortDueToIndex) {
4540 Query_block *query_block =
4541 ParseAndResolve("SELECT t1.x FROM t1 ORDER BY t1.x DESC",
4542 /*nullable=*/true);
4543
4544 m_fake_tables["t1"]->create_index(m_fake_tables["t1"]->field[0],
4545 /*column2=*/nullptr, /*unique=*/false);
4546 m_fake_tables["t1"]->file->stats.records = 100;
4547 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
4548
4549 // Mark the index as returning ordered results.
4550 ON_CALL(*down_cast<Mock_HANDLER *>(m_fake_tables["t1"]->file),
4551 index_flags(_, _, _))
4552 .WillByDefault(Return(HA_READ_ORDER | HA_READ_NEXT | HA_READ_PREV));
4553
4554 string trace;
4555 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4556 SCOPED_TRACE(trace); // Prints out the trace on failure.
4557 // Prints out the query plan on failure.
4558 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4559 /*is_root_of_join=*/true));
4560
4561 // The sort should be elided entirely due to index.
4562 ASSERT_EQ(AccessPath::INDEX_SCAN, root->type);
4563 EXPECT_STREQ("t1", root->index_scan().table->alias);
4564 EXPECT_EQ(0, root->index_scan().idx);
4565 EXPECT_TRUE(root->index_scan().use_order);
4566 EXPECT_TRUE(root->index_scan().reverse);
4567
4568 query_block->cleanup(/*full=*/true);
4569 }
4570
4571 TEST_F(HypergraphOptimizerTest, ElideConstSort) {
4572 Query_block *query_block =
4573 ParseAndResolve("SELECT t1.x FROM t1 ORDER BY 'a', 'b', CONCAT('c')",
4574 /*nullable=*/true);
4575
4576 string trace;
4577 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4578 SCOPED_TRACE(trace); // Prints out the trace on failure.
4579 // Prints out the query plan on failure.
4580 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4581 /*is_root_of_join=*/true));
4582
4583 // The sort should be elided entirely.
4584 ASSERT_EQ(AccessPath::TABLE_SCAN, root->type);
4585
4586 query_block->cleanup(/*full=*/true);
4587 }
4588
4589 TEST_F(HypergraphOptimizerTest, ElideRedundantPartsOfSortKey) {
4590 Query_block *query_block = ParseAndResolve(
4591 "SELECT 1 FROM t1, t2 WHERE t1.x = t2.x "
4592 "ORDER BY t1.x, t2.x, 'abc', t1.y, t2.y",
4593 /*nullable=*/true);
4594
4595 string trace;
4596 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4597 SCOPED_TRACE(trace); // Prints out the trace on failure.
4598 // Prints out the query plan on failure.
4599 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4600 /*is_root_of_join=*/true));
4601
4602 ASSERT_EQ(AccessPath::SORT, root->type);
4603
4604 // Expect redundant elements to be removed from the sort key. t2.x is
4605 // redundant because of t1.x and the functional dependency t1.x = t2.x. The
4606 // constant 'abc' does not contribute to the ordering because it has the same
4607 // value in all rows, and is also removed.
4608 vector<string> order_items;
4609 for (const ORDER *order = root->sort().order; order != nullptr;
4610 order = order->next) {
4611 order_items.push_back(ItemToString(*order->item));
4612 }
4613 EXPECT_THAT(order_items, ElementsAre("t1.x", "t1.y", "t2.y"));
4614
4615 // Expect the redundant elements to be removed from join->order as well.
4616 EXPECT_EQ(query_block->join->order.order, root->sort().order);
4617
4618 query_block->cleanup(/*full=*/true);
4619 }
4620
4621 TEST_F(HypergraphOptimizerTest, ElideRedundantSortAfterGrouping) {
4622 Query_block *query_block = ParseAndResolve(
4623 "SELECT 1 FROM t1 LEFT JOIN t2 ON t1.x = t2.x WHERE t2.x IS NULL "
4624 "GROUP BY t1.x ORDER BY t2.x",
4625 /*nullable=*/true);
4626
4627 string trace;
4628 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
4629 SCOPED_TRACE(trace); // Prints out the trace on failure.
4630 // Prints out the query plan on failure.
4631 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4632 /*is_root_of_join=*/true));
4633
4634 // Expect that there is no SORT on top of the AGGREGATE node, because the
4635 // ordering requested by the ORDER BY clause is ensured by the predicate.
4636 EXPECT_EQ(AccessPath::AGGREGATE, root->type);
4637
4638 // The ORDER BY clause should be optimized away altogether.
4639 EXPECT_EQ(nullptr, query_block->join->order.order);
4640 }
4641
4642 TEST_F(HypergraphOptimizerTest, ElideRedundantSortForDistinct) {
4643 Query_block *query_block = ParseAndResolve(
4644 "SELECT DISTINCT t2.x FROM t1 LEFT JOIN t2 ON t1.x = t2.x "
4645 "WHERE t2.x IS NULL",
4646 /*nullable=*/true);
4647
4648 string trace;
4649 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
4650 SCOPED_TRACE(trace); // Prints out the trace on failure.
4651 // Prints out the query plan on failure.
4652 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4653 /*is_root_of_join=*/true));
4654
4655 // Expect that there is no SORT for DISTINCT. Since the filter ensures that
4656 // all rows have the same value, duplicate elimination can be done by adding
4657 // LIMIT 1 on top of the filter.
4658 ASSERT_EQ(AccessPath::LIMIT_OFFSET, root->type);
4659 EXPECT_EQ(0, root->limit_offset().offset);
4660 EXPECT_EQ(1, root->limit_offset().limit);
4661 ASSERT_EQ(AccessPath::FILTER, root->limit_offset().child->type);
4662 EXPECT_EQ("(t2.x is null)",
4663 ItemToString(root->limit_offset().child->filter().condition));
4664 }
4665
4666 // This case is tricky; the order given by the index is (x, y), but the
4667 // interesting order is just (y). Normally, we only grow orders into interesting
4668 // orders, but here, we have to reduce them as well.
4669 TEST_F(HypergraphOptimizerTest, IndexTailGetsUsed) {
4670 Query_block *query_block =
4671 ParseAndResolve("SELECT t1.x, t1.y FROM t1 WHERE t1.x=42 ORDER BY t1.y",
4672 /*nullable=*/true);
4673
4674 m_fake_tables["t1"]->create_index(m_fake_tables["t1"]->field[0],
4675 m_fake_tables["t1"]->field[1],
4676 /*unique=*/false);
4677 m_fake_tables["t1"]->file->stats.records = 100;
4678 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
4679
4680 // Mark the index as returning ordered results.
4681 ON_CALL(*down_cast<Mock_HANDLER *>(m_fake_tables["t1"]->file),
4682 index_flags(_, _, _))
4683 .WillByDefault(Return(HA_READ_ORDER | HA_READ_NEXT | HA_READ_PREV));
4684
4685 string trace;
4686 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4687 SCOPED_TRACE(trace); // Prints out the trace on failure.
4688 // Prints out the query plan on failure.
4689 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4690 /*is_root_of_join=*/true));
4691
4692 // The sort should be elided entirely due to index.
4693 ASSERT_EQ(AccessPath::REF, root->type);
4694 EXPECT_STREQ("t1", root->ref().table->alias);
4695 EXPECT_EQ(0, root->ref().ref->key);
4696 EXPECT_EQ(true, root->ref().use_order);
4697 EXPECT_EQ(false, root->ref().reverse);
4698
4699 query_block->cleanup(/*full=*/true);
4700 }
4701
4702 TEST_F(HypergraphOptimizerTest, SortAheadByCoverToElideSortForGroup) {
4703 Query_block *query_block = ParseAndResolve(
4704 "SELECT t1.x FROM t1, t2 GROUP BY t1.x, t1.y ORDER BY t1.y DESC",
4705 /*nullable=*/true);
4706
4707 m_fake_tables["t1"]->file->stats.records = 100;
4708 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
4709 m_fake_tables["t2"]->file->stats.records = 100;
4710 m_fake_tables["t2"]->file->stats.data_file_length = 1e6;
4711
4712 string trace;
4713 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4714 SCOPED_TRACE(trace); // Prints out the trace on failure.
4715 // Prints out the query plan on failure.
4716 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4717 /*is_root_of_join=*/true));
4718
4719 // The root should be a group, and it should _not_ have a sort beneath it
4720 // (it should be elided due to sortahead).
4721 ASSERT_EQ(AccessPath::AGGREGATE, root->type);
4722 AccessPath *join = root->aggregate().child;
4723 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, join->type);
4724 AccessPath *outer = join->nested_loop_join().outer;
4725
4726 // The outer table should be sorted on (y↓, x); it is compatible with the
4727 // grouping (even though it was on {x, y}), and also compatible with the
4728 // ordering.
4729 ASSERT_EQ(AccessPath::SORT, outer->type);
4730 Filesort *filesort = outer->sort().filesort;
4731 ASSERT_EQ(2, filesort->sort_order_length());
4732 EXPECT_EQ("t1.y", ItemToString(filesort->sortorder[0].item));
4733 EXPECT_TRUE(filesort->sortorder[0].reverse);
4734 EXPECT_EQ("t1.x", ItemToString(filesort->sortorder[1].item));
4735 EXPECT_FALSE(filesort->sortorder[1].reverse);
4736
4737 // We don't test the inner side.
4738
4739 query_block->cleanup(/*full=*/true);
4740 }
4741
4742 TEST_F(HypergraphOptimizerTest, SatisfyGroupByWithIndex) {
4743 Query_block *query_block =
4744 ParseAndResolve("SELECT t1.x FROM t1 GROUP BY t1.x",
4745 /*nullable=*/true);
4746
4747 m_fake_tables["t1"]->create_index(m_fake_tables["t1"]->field[0],
4748 /*column2=*/nullptr, /*unique=*/false);
4749 m_fake_tables["t1"]->file->stats.records = 100;
4750 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
4751
4752 // Mark the index as returning ordered results.
4753 ON_CALL(*down_cast<Mock_HANDLER *>(m_fake_tables["t1"]->file),
4754 index_flags(_, _, _))
4755 .WillByDefault(Return(HA_READ_ORDER | HA_READ_NEXT | HA_READ_PREV));
4756
4757 string trace;
4758 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4759 SCOPED_TRACE(trace); // Prints out the trace on failure.
4760 // Prints out the query plan on failure.
4761 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4762 /*is_root_of_join=*/true));
4763
4764 // The root is a group node, of course.
4765 ASSERT_EQ(AccessPath::AGGREGATE, root->type);
4766 AccessPath *inner = root->aggregate().child;
4767
4768 // The grouping should be taking care of by the ordered index.
4769 EXPECT_EQ(AccessPath::INDEX_SCAN, inner->type);
4770
4771 query_block->cleanup(/*full=*/true);
4772 }
4773
4774 TEST_F(HypergraphOptimizerTest, SatisfyGroupingForDistinctWithIndex) {
4775 Query_block *query_block =
4776 ParseAndResolve("SELECT DISTINCT t1.y, t1.x FROM t1",
4777 /*nullable=*/true);
4778
4779 m_fake_tables["t1"]->create_index(m_fake_tables["t1"]->field[0],
4780 m_fake_tables["t1"]->field[1],
4781 /*unique=*/false);
4782 m_fake_tables["t1"]->file->stats.records = 100;
4783 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
4784
4785 // Mark the index as returning ordered results.
4786 ON_CALL(*down_cast<Mock_HANDLER *>(m_fake_tables["t1"]->file),
4787 index_flags(_, _, _))
4788 .WillByDefault(Return(HA_READ_ORDER | HA_READ_NEXT | HA_READ_PREV));
4789
4790 string trace;
4791 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4792 SCOPED_TRACE(trace); // Prints out the trace on failure.
4793 // Prints out the query plan on failure.
4794 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4795 /*is_root_of_join=*/true));
4796
4797 // The root should be a duplicate removal node; no sort.
4798 // Order of the group items doesn't matter.
4799 ASSERT_EQ(AccessPath::REMOVE_DUPLICATES, root->type);
4800 ASSERT_EQ(2, root->remove_duplicates().group_items_size);
4801 EXPECT_EQ("t1.y", ItemToString(root->remove_duplicates().group_items[0]));
4802 EXPECT_EQ("t1.x", ItemToString(root->remove_duplicates().group_items[1]));
4803
4804 // The grouping should be taking care of by the ordered index.
4805 AccessPath *inner = root->remove_duplicates().child;
4806 EXPECT_EQ(AccessPath::INDEX_SCAN, inner->type);
4807
4808 query_block->cleanup(/*full=*/true);
4809 }
4810
4811 TEST_F(HypergraphOptimizerTest, SemiJoinThroughLooseScan) {
4812 Query_block *query_block =
4813 ParseAndResolve("SELECT 1 FROM t1 WHERE t1.x IN (SELECT t2.x FROM t2)",
4814 /*nullable=*/true);
4815
4816 // Make t1 large and with a relevant index, and t2 small
4817 // and with none. The best plan then will be to remove
4818 // duplicates from t2 and then do lookups into t1.
4819 m_fake_tables["t1"]->create_index(m_fake_tables["t1"]->field[0],
4820 /*column2=*/nullptr,
4821 /*unique=*/true);
4822 m_fake_tables["t1"]->file->stats.records = 1000000;
4823 m_fake_tables["t1"]->file->stats.data_file_length = 10000e6;
4824 m_fake_tables["t2"]->file->stats.records = 100;
4825 m_fake_tables["t2"]->file->stats.data_file_length = 1e6;
4826
4827 string trace;
4828 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
4829 SCOPED_TRACE(trace); // Prints out the trace on failure.
4830 // Prints out the query plan on failure.
4831 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4832 /*is_root_of_join=*/true));
4833
4834 // The join should be changed to an _inner_ join, and the inner side
4835 // should be an EQ_REF on t1.
4836 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
4837 EXPECT_EQ(JoinType::INNER, root->nested_loop_join().join_type);
4838
4839 AccessPath *inner = root->nested_loop_join().inner;
4840 ASSERT_EQ(AccessPath::EQ_REF, inner->type);
4841 EXPECT_STREQ("t1", inner->eq_ref().table->alias);
4842
4843 // The outer side is slightly trickier. There should first be
4844 // a duplicate removal on the join key...
4845 AccessPath *outer = root->nested_loop_join().outer;
4846 ASSERT_EQ(AccessPath::REMOVE_DUPLICATES, outer->type);
4847 ASSERT_EQ(1, outer->remove_duplicates().group_items_size);
4848 EXPECT_EQ("t2.x", ItemToString(outer->remove_duplicates().group_items[0]));
4849
4850 // ...then a sort to get the grouping...
4851 AccessPath *sort = outer->remove_duplicates().child;
4852 ASSERT_EQ(AccessPath::SORT, sort->type);
4853 Filesort *filesort = sort->sort().filesort;
4854 ASSERT_EQ(1, filesort->sort_order_length());
4855 EXPECT_EQ("t2.x", ItemToString(filesort->sortorder[0].item));
4856
4857 // Note that ideally, we'd have true here instead of the duplicate removal,
4858 // but we can't track duplicates-removed status through AccessPaths yet.
4859 EXPECT_FALSE(filesort->m_remove_duplicates);
4860
4861 // ...and then finally a table scan.
4862 AccessPath *t2 = sort->sort().child;
4863 ASSERT_EQ(AccessPath::TABLE_SCAN, t2->type);
4864 EXPECT_STREQ("t2", t2->table_scan().table->alias);
4865
4866 query_block->cleanup(/*full=*/true);
4867 }
4868
4869 TEST_F(HypergraphOptimizerTest, ImpossibleJoinConditionGivesZeroRows) {
4870 Query_block *query_block = ParseAndResolve(
4871 "SELECT 1 FROM t1 LEFT JOIN (t2 JOIN t3 ON t2.x=t3.x AND 1=2) ON "
4872 "t1.x=t2.x",
4873 /*nullable=*/false);
4874
4875 // We don't need any statistics; the best plan is quite obvious.
4876 // But we'd like to confirm the estimated row count for the join.
4877 m_fake_tables["t1"]->file->stats.records = 10;
4878 m_fake_tables["t2"]->file->stats.records = 1000;
4879 m_fake_tables["t3"]->file->stats.records = 1000;
4880
4881 string trace;
4882 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
4883 SCOPED_TRACE(trace); // Prints out the trace on failure.
4884 // Prints out the query plan on failure.
4885 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4886 /*is_root_of_join=*/true));
4887
4888 // Since there are no rows on the right side, we should have a nested loop
4889 // with t1 on the left side.
4890 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->type);
4891 EXPECT_EQ(JoinType::OUTER, root->nested_loop_join().join_type);
4892 EXPECT_FLOAT_EQ(10.0F, root->num_output_rows());
4893
4894 AccessPath *outer = root->nested_loop_join().outer;
4895 ASSERT_EQ(AccessPath::TABLE_SCAN, outer->type);
4896 EXPECT_STREQ("t1", outer->table_scan().table->alias);
4897
4898 // On the right side, we should have pushed _up_ the 1=2 condition,
4899 // and seen that it kills all the rows on the right side.
4900 AccessPath *inner = root->nested_loop_join().inner;
4901 ASSERT_EQ(AccessPath::ZERO_ROWS, inner->type);
4902
4903 // Just verify that we indeed have a join under there.
4904 // (It is needed to get the zero row flags set on t2 and t3.)
4905 EXPECT_EQ(AccessPath::NESTED_LOOP_JOIN, inner->zero_rows().child->type);
4906
4907 query_block->cleanup(/*full=*/true);
4908 }
4909
4910 TEST_F(HypergraphOptimizerTest, ImpossibleWhereInJoinGivesZeroRows) {
4911 // Test a query with an impossible WHERE clause. Add aggregation and ordering
4912 // and various extra filters to see that the entire query is optimized away.
4913 // It used to optimize away only the access to the t2 table, and keep the
4914 // paths for joining, aggregation, sorting, etc on top of the ZERO_ROWS path.
4915 Query_block *query_block = ParseAndResolve(
4916 "SELECT MAX(t1.y) FROM t1 LEFT JOIN t2 ON t1.x = t2.x "
4917 "WHERE t2.y IS NULL AND t2.y IN (1, 2) AND RAND(0) < 0.5 "
4918 "GROUP BY t1.x HAVING MAX(t1.y) > 0 "
4919 "ORDER BY MAX(t1.y) LIMIT 20 OFFSET 10",
4920 /*nullable=*/false);
4921
4922 // Create an index on t2.y so that the range optimizer analyzes the WHERE
4923 // clause and detects that it always evaluates to FALSE.
4924 Fake_TABLE *t2 = m_fake_tables["t2"];
4925 t2->create_index(t2->field[1],
4926 /*column2=*/nullptr,
4927 /*unique=*/false);
4928
4929 string trace;
4930 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
4931 SCOPED_TRACE(trace); // Prints out the trace on failure.
4932 // Prints out the query plan on failure.
4933 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4934 /*is_root_of_join=*/true));
4935
4936 EXPECT_EQ(AccessPath::ZERO_ROWS, root->type);
4937 }
4938
4939 TEST_F(HypergraphOptimizerTest, ImpossibleRangeInJoinWithFilterAndAggregation) {
4940 // Test a query with an impossible range condition (t2.y IS NULL AND t2.y IN
4941 // (1, 2)) and a non-pushable condition that has to stay in a post-join filter
4942 // (RAND(0) < 0.5), and which is implicitly grouped so that it has to return
4943 // one row even if the join result is empty. Optimizing this query used to hit
4944 // an assert failure due to inconsistent cost estimates.
4945 Query_block *query_block = ParseAndResolve(
4946 "SELECT COUNT(*) FROM t1, t2 WHERE t1.x = t2.x AND "
4947 "t2.y IS NULL AND t2.y IN (1, 2) AND RAND(0) < 0.5",
4948 /*nullable=*/true);
4949
4950 // Create an index on t2.y so that the range optimizer analyzes the WHERE
4951 // clause and detects that it always evaluates to FALSE.
4952 Fake_TABLE *t2 = m_fake_tables["t2"];
4953 t2->create_index(t2->field[1],
4954 /*column2=*/nullptr,
4955 /*unique=*/false);
4956
4957 string trace;
4958 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
4959 SCOPED_TRACE(trace); // Prints out the trace on failure.
4960 // Prints out the query plan on failure.
4961 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4962 /*is_root_of_join=*/true));
4963
4964 EXPECT_EQ(AccessPath::ZERO_ROWS_AGGREGATED, root->type);
4965 }
4966
4967 TEST_F(HypergraphOptimizerTest, SimpleRangeScan) {
4968 Query_block *query_block = ParseAndResolve("SELECT 1 FROM t1 WHERE t1.x < 3",
4969 /*nullable=*/false);
4970
4971 Fake_TABLE *t1 = m_fake_tables["t1"];
4972 t1->file->stats.records = 1000;
4973 t1->create_index(t1->field[0], nullptr, /*unique=*/false);
4974
4975 // Mark the index as supporting range scans.
4976 ON_CALL(*down_cast<Mock_HANDLER *>(m_fake_tables["t1"]->file),
4977 index_flags(_, _, _))
4978 .WillByDefault(Return(HA_READ_RANGE | HA_READ_NEXT | HA_READ_PREV));
4979
4980 string trace;
4981 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
4982 SCOPED_TRACE(trace); // Prints out the trace on failure.
4983 // Prints out the query plan on failure.
4984 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
4985 /*is_root_of_join=*/true));
4986
4987 ASSERT_EQ(AccessPath::INDEX_RANGE_SCAN, root->type);
4988 EXPECT_EQ(0, root->index_range_scan().index);
4989 // HA_MRR_SUPPORT_SORTED and HA_MRR_USE_DEFAULT_IMPL are added by the handler,
4990 // not by the optimizer.
4991 EXPECT_EQ(
4992 HA_MRR_SUPPORT_SORTED | HA_MRR_USE_DEFAULT_IMPL | HA_MRR_NO_ASSOCIATION,
4993 root->index_range_scan().mrr_flags);
4994 ASSERT_EQ(1, root->index_range_scan().num_ranges);
4995 EXPECT_EQ(NO_MIN_RANGE | NEAR_MAX, root->index_range_scan().ranges[0]->flag);
4996 string_view max_key{
4997 pointer_cast<char *>(root->index_range_scan().ranges[0]->max_key),
4998 root->index_range_scan().ranges[0]->max_length};
4999 EXPECT_EQ("\x03\x00\x00\x00"sv, max_key);
5000 EXPECT_FALSE(root->index_range_scan().reverse);
5001
5002 query_block->cleanup(/*full=*/true);
5003 }
5004
5005 TEST_F(HypergraphOptimizerTest, ComplexMultipartRangeScan) {
5006 Query_block *query_block = ParseAndResolve(
5007 "SELECT 1 FROM t1 "
5008 "WHERE (t1.x < 3 OR t1.x = 5) AND SQRT(t1.x) > 3 AND t1.y >= 15",
5009 /*nullable=*/false);
5010
5011 Fake_TABLE *t1 = m_fake_tables["t1"];
5012 t1->file->stats.records = 1000;
5013 t1->create_index(t1->field[0], t1->field[1], /*unique=*/false);
5014
5015 // Mark the index as supporting range scans.
5016 ON_CALL(*down_cast<Mock_HANDLER *>(m_fake_tables["t1"]->file),
5017 index_flags(_, _, _))
5018 .WillByDefault(Return(HA_READ_RANGE | HA_READ_NEXT | HA_READ_PREV));
5019
5020 string trace;
5021 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5022 SCOPED_TRACE(trace); // Prints out the trace on failure.
5023 // Prints out the query plan on failure.
5024 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5025 /*is_root_of_join=*/true));
5026
5027 // sqrt(t1.x) > 3 isn't doable as a range scan (since we never do algebraic
5028 // rewrites). The other predicate on t1.x is subsumed, and should not be part
5029 // of the filter. (t1.x < 3 AND t1.y >= 15) is not representable as a range
5030 // scan (it gets truncated to just t1.x < 3 for the range), and thus,
5031 // t1.y >= 15 should also not be subsumed.
5032 ASSERT_EQ(AccessPath::FILTER, root->type);
5033 EXPECT_EQ("((t1.y >= 15) and (sqrt(t1.x) > 3))",
5034 ItemToString(root->filter().condition));
5035
5036 AccessPath *range_scan = root->filter().child;
5037 ASSERT_EQ(AccessPath::INDEX_RANGE_SCAN, range_scan->type);
5038 EXPECT_EQ(0, range_scan->index_range_scan().index);
5039 // HA_MRR_SUPPORT_SORTED and HA_MRR_USE_DEFAULT_IMPL are added by the handler,
5040 // not by the optimizer.
5041 EXPECT_EQ(
5042 HA_MRR_SUPPORT_SORTED | HA_MRR_USE_DEFAULT_IMPL | HA_MRR_NO_ASSOCIATION,
5043 range_scan->index_range_scan().mrr_flags);
5044 ASSERT_EQ(2, range_scan->index_range_scan().num_ranges);
5045
5046 // t1.x < 3 (same as previous test).
5047 EXPECT_EQ(NO_MIN_RANGE | NEAR_MAX,
5048 range_scan->index_range_scan().ranges[0]->flag);
5049 string_view max_key_0{
5050 pointer_cast<char *>(range_scan->index_range_scan().ranges[0]->max_key),
5051 range_scan->index_range_scan().ranges[0]->max_length};
5052 EXPECT_EQ("\x03\x00\x00\x00"sv, max_key_0);
5053
5054 // t1.x = 5 AND t1.y >= 15 (represented as (x,y) >= (5,15) and (x) <= (5));
5055 // even though we couldn't fit t1.y >= 15 into the last keypart, it should be
5056 // included here.
5057 EXPECT_EQ(0, range_scan->index_range_scan().ranges[1]->flag);
5058 string_view min_key_1{
5059 pointer_cast<char *>(range_scan->index_range_scan().ranges[1]->min_key),
5060 range_scan->index_range_scan().ranges[1]->min_length};
5061 string_view max_key_1{
5062 pointer_cast<char *>(range_scan->index_range_scan().ranges[1]->max_key),
5063 range_scan->index_range_scan().ranges[1]->max_length};
5064 EXPECT_EQ("\x05\x00\x00\x00\x0f\x00\x00\x00"sv, min_key_1);
5065 EXPECT_EQ("\x05\x00\x00\x00"sv, max_key_1);
5066
5067 // It would have been nice to verify here that the filter had a lower
5068 // output row count than the range scan, due to sqrt(x) > 3 not being
5069 // part of the range scan. However, the returned selectivity for such
5070 // estimates is always 1.0, so it's not really visible. Instead, we simply
5071 // check that both are reasonably sane.
5072 EXPECT_GT(range_scan->num_output_rows(), 0.0);
5073 EXPECT_GE(root->num_output_rows(), range_scan->num_output_rows());
5074
5075 query_block->cleanup(/*full=*/true);
5076 }
5077
5078 TEST_F(HypergraphOptimizerTest, RangeScanWithReverseOrdering) {
5079 Query_block *query_block =
5080 ParseAndResolve("SELECT 1 FROM t1 WHERE t1.x < 3 ORDER BY t1.x DESC",
5081 /*nullable=*/false);
5082
5083 Fake_TABLE *t1 = m_fake_tables["t1"];
5084 t1->file->stats.records = 1000;
5085 t1->create_index(t1->field[0], nullptr, /*unique=*/false);
5086
5087 // Mark the index as supporting range scans _and_ ordering.
5088 ON_CALL(*down_cast<Mock_HANDLER *>(m_fake_tables["t1"]->file),
5089 index_flags(_, _, _))
5090 .WillByDefault(
5091 Return(HA_READ_RANGE | HA_READ_ORDER | HA_READ_NEXT | HA_READ_PREV));
5092
5093 string trace;
5094 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5095 SCOPED_TRACE(trace); // Prints out the trace on failure.
5096 // Prints out the query plan on failure.
5097 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5098 /*is_root_of_join=*/true));
5099
5100 ASSERT_EQ(AccessPath::INDEX_RANGE_SCAN, root->type);
5101 EXPECT_EQ(0, root->index_range_scan().index);
5102 // We need sorted output, in reverse.
5103 // HA_MRR_SUPPORT_SORTED and HA_MRR_USE_DEFAULT_IMPL are added by the handler,
5104 // not by the optimizer.
5105 EXPECT_EQ(HA_MRR_SUPPORT_SORTED | HA_MRR_USE_DEFAULT_IMPL | HA_MRR_SORTED |
5106 HA_MRR_NO_ASSOCIATION,
5107 root->index_range_scan().mrr_flags);
5108 EXPECT_TRUE(root->index_range_scan().reverse);
5109
5110 query_block->cleanup(/*full=*/true);
5111 }
5112
5113 TEST_F(HypergraphOptimizerTest, ImpossibleRange) {
5114 Query_block *query_block =
5115 ParseAndResolve("SELECT 1 FROM t1 WHERE t1.x < 3 AND t1.x > 5",
5116 /*nullable=*/false);
5117
5118 // We need an index, or we would never analyze ranges on t1.x.
5119 Fake_TABLE *t1 = m_fake_tables["t1"];
5120 t1->create_index(t1->field[0], nullptr, /*unique=*/false);
5121 ON_CALL(*down_cast<Mock_HANDLER *>(t1->file), index_flags(_, _, _))
5122 .WillByDefault(Return(HA_READ_RANGE | HA_READ_NEXT | HA_READ_PREV));
5123
5124 string trace;
5125 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5126 SCOPED_TRACE(trace); // Prints out the trace on failure.
5127 // Prints out the query plan on failure.
5128 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5129 /*is_root_of_join=*/true));
5130
5131 EXPECT_EQ(AccessPath::ZERO_ROWS, root->type);
5132
5133 query_block->cleanup(/*full=*/true);
5134 }
5135
5136 TEST_F(HypergraphOptimizerTest, ImpossibleRangeWithOverflowBitset) {
5137 // We want to test a query that has an impossible range and enough predicates
5138 // that they don't fit in an inlined OverflowBitset in the zero-rows access
5139 // path. We need at least 64 predicates to make OverflowBitset overflow. Also
5140 // add a join to the query, since an assert failure was seen when proposing a
5141 // join path with a table with an always false range condition on one of the
5142 // sides when the number of predicates exceeded what could fit in an inlined
5143 // OverflowBitset.
5144 constexpr int number_of_predicates = 70;
5145 string query =
5146 "SELECT 1 FROM t1, t2 WHERE t1.x >= 2 AND t1.x <= 1 AND t1.y = t2.y";
5147 for (int i = 2; i < number_of_predicates; ++i) {
5148 query += " AND t1.z <> " + to_string(i);
5149 }
5150
5151 Query_block *query_block = ParseAndResolve(query.c_str(),
5152 /*nullable=*/false);
5153
5154 // Add an index on t1.x so that we try a range scan on the
5155 // impossible range (x >= 2 AND x <= 1).
5156 Fake_TABLE *t1 = m_fake_tables["t1"];
5157 t1->create_index(t1->field[0], nullptr, /*unique=*/false);
5158 ON_CALL(*down_cast<Mock_HANDLER *>(t1->file), index_flags(_, _, _))
5159 .WillByDefault(Return(HA_READ_RANGE | HA_READ_NEXT | HA_READ_PREV));
5160
5161 string trace;
5162 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5163 SCOPED_TRACE(trace); // Prints out the trace on failure.
5164 ASSERT_NE(nullptr, root);
5165 // Prints out the query plan on failure.
5166 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5167 /*is_root_of_join=*/true));
5168
5169 EXPECT_EQ(AccessPath::ZERO_ROWS, root->type);
5170 }
5171
5172 TEST_F(HypergraphOptimizerTest, IndexMerge) {
5173 Query_block *query_block =
5174 ParseAndResolve("SELECT 1 FROM t1 WHERE t1.x < 3 OR t1.y > 4",
5175 /*nullable=*/false);
5176
5177 Fake_TABLE *t1 = m_fake_tables["t1"];
5178 t1->file->stats.records = 1000;
5179 t1->create_index(t1->field[0], nullptr, /*unique=*/false);
5180 t1->create_index(t1->field[1], nullptr, /*unique=*/false);
5181
5182 // Mark the index as supporting range scans.
5183 ON_CALL(*down_cast<Mock_HANDLER *>(m_fake_tables["t1"]->file),
5184 index_flags(_, _, _))
5185 .WillByDefault(Return(HA_READ_RANGE | HA_READ_NEXT | HA_READ_PREV));
5186
5187 string trace;
5188 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5189 SCOPED_TRACE(trace); // Prints out the trace on failure.
5190 // Prints out the query plan on failure.
5191 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5192 /*is_root_of_join=*/true));
5193
5194 // No filter; it should be subsumed.
5195 ASSERT_EQ(AccessPath::INDEX_MERGE, root->type);
5196 ASSERT_EQ(2, root->index_merge().children->size());
5197
5198 // t1.x < 3; we don't bother checking the other range, since it's so tedious.
5199 AccessPath *child0 = (*root->index_merge().children)[0];
5200 ASSERT_EQ(AccessPath::INDEX_RANGE_SCAN, child0->type);
5201 ASSERT_EQ(1, child0->index_range_scan().num_ranges);
5202 EXPECT_EQ(NO_MIN_RANGE | NEAR_MAX,
5203 child0->index_range_scan().ranges[0]->flag);
5204 string_view max_key{
5205 pointer_cast<char *>(child0->index_range_scan().ranges[0]->max_key),
5206 child0->index_range_scan().ranges[0]->max_length};
5207 EXPECT_EQ("\x03\x00\x00\x00"sv, max_key);
5208
5209 AccessPath *child1 = (*root->index_merge().children)[1];
5210 EXPECT_EQ(AccessPath::INDEX_RANGE_SCAN, child1->type);
5211
5212 query_block->cleanup(/*full=*/true);
5213 }
5214
5215 TEST_F(HypergraphOptimizerTest, IndexMergeSubsumesOnlyOnePredicate) {
5216 Query_block *query_block = ParseAndResolve(
5217 "SELECT 1 FROM t1 WHERE (t1.x < 3 OR t1.y > 4) AND (t1.y > 0 OR t1.z > "
5218 "0)",
5219 /*nullable=*/false);
5220
5221 Fake_TABLE *t1 = m_fake_tables["t1"];
5222 t1->file->stats.records = 1000;
5223 t1->create_index(t1->field[0], nullptr, /*unique=*/false);
5224 t1->create_index(t1->field[1], nullptr, /*unique=*/false);
5225
5226 // Mark the index as supporting range scans.
5227 ON_CALL(*down_cast<Mock_HANDLER *>(m_fake_tables["t1"]->file),
5228 index_flags(_, _, _))
5229 .WillByDefault(Return(HA_READ_RANGE | HA_READ_NEXT | HA_READ_PREV));
5230
5231 string trace;
5232 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5233 SCOPED_TRACE(trace); // Prints out the trace on failure.
5234 // Prints out the query plan on failure.
5235 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5236 /*is_root_of_join=*/true));
5237
5238 // The second predicate should not be subsumed, so we have a filter.
5239 ASSERT_EQ(AccessPath::FILTER, root->type);
5240 EXPECT_EQ("((t1.y > 0) or (t1.z > 0))",
5241 ItemToString(root->filter().condition));
5242 EXPECT_EQ(AccessPath::INDEX_MERGE, root->filter().child->type);
5243
5244 query_block->cleanup(/*full=*/true);
5245 }
5246
5247 // Tests a case where we have the choice between an index range scan on a set of
5248 // predicates and an index merge scan on another set of predicates. When the
5249 // index range scan is chosen, the index merge predicates must be in a filter on
5250 // top of the range scan. Before bug#34173949, the filter was missing.
5251 TEST_F(HypergraphOptimizerTest, DontSubsumeIndexMergePredicateInRangeScan) {
5252 Query_block *query_block = ParseAndResolve(
5253 "SELECT t1.x, t1.y FROM t1 WHERE t1.x IN (71, 255) AND t1.y <> 115 AND "
5254 "(t1.y = 6 OR t1.x = 29)",
5255 /*nullable=*/false);
5256
5257 Fake_TABLE *t1 = m_fake_tables["t1"];
5258 t1->file->stats.records = 1000;
5259 t1->file->stats.data_file_length = 1e6;
5260
5261 // Create indexes on (x, y) and on (y).
5262 EXPECT_EQ(0, t1->create_index(t1->field[0], t1->field[1], /*unique=*/false));
5263 EXPECT_EQ(1, t1->create_index(t1->field[1], nullptr, /*unique=*/false));
5264
5265 // Mark the indexes as supporting range scans.
5266 Mock_HANDLER *handler = down_cast<Mock_HANDLER *>(t1->file);
5267 EXPECT_CALL(*handler, index_flags)
5268 .WillRepeatedly(Return(HA_READ_RANGE | HA_READ_NEXT | HA_READ_PREV));
5269
5270 // Report smaller ranges in the (x, y) index than in the (y) index, so that a
5271 // range scan on (x, y) is preferred to a range scan on (y). And also
5272 // preferred to an index merge or a table scan.
5273 EXPECT_CALL(*handler, records_in_range(0, _, _)).WillRepeatedly(Return(1));
5274 EXPECT_CALL(*handler, records_in_range(1, _, _)).WillRepeatedly(Return(10));
5275
5276 string trace;
5277 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5278 SCOPED_TRACE(trace); // Prints out the trace on failure.
5279 // Prints out the query plan on failure.
5280 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5281 /*is_root_of_join=*/true));
5282
5283 // The predicate that could have been used for an index merge should be in a
5284 // filter on top.
5285 ASSERT_EQ(AccessPath::FILTER, root->type);
5286 EXPECT_EQ("((t1.y = 6) or (t1.x = 29))",
5287 ItemToString(root->filter().condition));
5288
5289 // An index range scan has subsumed the rest of the predicates as:
5290 // (x = 71 AND y < 115) OR (x = 71 AND 115 < y) OR
5291 // (x = 255 AND y < 115) OR (x = 255 AND 115 < y)
5292 ASSERT_EQ(AccessPath::INDEX_RANGE_SCAN, root->filter().child->type);
5293 const auto range_scan = root->filter().child->index_range_scan();
5294 EXPECT_EQ(0, range_scan.index);
5295 EXPECT_EQ(4, range_scan.num_ranges);
5296 }
5297
5298 // Test that an index merge doesn't subsume a range predicate that it is AND-ed
5299 // with. This could happen if the AND was contained in an OR, and the OR
5300 // contained an always false condition that allowed the range optimizer to
5301 // eliminate the subjunction.
5302 TEST_F(HypergraphOptimizerTest, DontSubsumeRangePredicateInIndexMerge) {
5303 // Always false condition: t1.x BETWEEN 5 AND 0
5304 // Possible range scan: t1.x IS NULL
5305 // Possible index merge: t1.y = 2 OR t1.z = 3
5306 Query_block *query_block = ParseAndResolve(
5307 "SELECT 1 FROM t1 WHERE t1.x BETWEEN 5 AND 0 "
5308 "OR (t1.x IS NULL AND (t1.y = 2 OR t1.z = 3))",
5309 /*nullable=*/true);
5310
5311 Fake_TABLE *t1 = m_fake_tables["t1"];
5312 t1->file->stats.records = 1000;
5313 t1->file->stats.data_file_length = 1e6;
5314
5315 // Create indexes on x, y and z.
5316 for (int i = 0; i < 3; ++i) {
5317 EXPECT_EQ(i, t1->create_index(t1->field[i], nullptr));
5318 }
5319
5320 // Mark the indexes as supporting range scans.
5321 Mock_HANDLER *handler = down_cast<Mock_HANDLER *>(t1->file);
5322 EXPECT_CALL(*handler, index_flags)
5323 .WillRepeatedly(Return(HA_READ_RANGE | HA_READ_NEXT | HA_READ_PREV));
5324
5325 // Make the index on x less selective than the other indexes, so that an index
5326 // merge on y and z is preferred to an index range scan on x.
5327 EXPECT_CALL(*handler, records_in_range(0, _, _)).WillRepeatedly(Return(100));
5328 EXPECT_CALL(*handler, records_in_range(1, _, _)).WillRepeatedly(Return(10));
5329 EXPECT_CALL(*handler, records_in_range(2, _, _)).WillRepeatedly(Return(10));
5330
5331 string trace;
5332 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5333 SCOPED_TRACE(trace); // Prints out the trace on failure.
5334 // Prints out the query plan on failure.
5335 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5336 /*is_root_of_join=*/true));
5337
5338 ASSERT_EQ(AccessPath::FILTER, root->type);
5339 EXPECT_EQ(AccessPath::INDEX_MERGE, root->filter().child->type);
5340
5341 // There needs to be a filter because the index merge doesn't represent the
5342 // full WHERE clause. It is sufficient with a filter on (t1.x IS NULL), but
5343 // the hypergraph optimizer cannot currently operate on that granularity, so
5344 // we get the entire WHERE condition for now.
5345 EXPECT_EQ(
5346 "((t1.x between 5 and 0) or "
5347 "((t1.x is null) and ((t1.y = 2) or (t1.z = 3))))",
5348 ItemToString(root->filter().condition));
5349 }
5350
5351 TEST_F(HypergraphOptimizerTest, IndexMergePrefersNonCPKToOrderByPrimaryKey) {
5352 for (bool order_by : {false, true}) {
5353 SCOPED_TRACE(order_by ? "With ORDER BY" : "Without ORDER BY");
5354
5355 Query_block *query_block = ParseAndResolve(
5356 order_by ? "SELECT 1 FROM t1 WHERE t1.x < 3 OR t1.y > 4 ORDER BY t1.x"
5357 : "SELECT 1 FROM t1 WHERE t1.x < 3 OR t1.y > 4",
5358 /*nullable=*/false);
5359
5360 Fake_TABLE *t1 = m_fake_tables["t1"];
5361 t1->file->stats.records = 1000;
5362 t1->s->primary_key =
5363 t1->create_index(t1->field[0], nullptr, /*unique=*/false);
5364 t1->create_index(t1->field[1], nullptr, /*unique=*/false);
5365
5366 // Mark the index as supporting range scans, being ordered, and being
5367 // clustered.
5368 ON_CALL(*down_cast<Mock_HANDLER *>(m_fake_tables["t1"]->file),
5369 index_flags(_, _, _))
5370 .WillByDefault(Return(HA_READ_RANGE | HA_READ_ORDER | HA_READ_NEXT |
5371 HA_READ_PREV));
5372 ON_CALL(*down_cast<Mock_HANDLER *>(m_fake_tables["t1"]->file),
5373 primary_key_is_clustered())
5374 .WillByDefault(Return(true));
5375
5376 string trace;
5377 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5378 SCOPED_TRACE(trace); // Prints out the trace on failure.
5379 // Prints out the query plan on failure.
5380 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5381 /*is_root_of_join=*/true));
5382
5383 ASSERT_EQ(AccessPath::INDEX_MERGE, root->type);
5384 EXPECT_EQ(2, root->index_merge().children->size());
5385 if (order_by) {
5386 // We should choose a non-clustered primary key scan, since that gets the
5387 // ordering and thus elides the sort.
5388 EXPECT_FALSE(root->index_merge().allow_clustered_primary_key_scan);
5389 } else {
5390 // If there's no ordering, then using the CPK scan is cheaper.
5391 EXPECT_TRUE(root->index_merge().allow_clustered_primary_key_scan);
5392 }
5393
5394 query_block->cleanup(/*full=*/true);
5395 ClearFakeTables();
5396 }
5397 }
5398
5399 TEST_F(HypergraphOptimizerTest, IndexMergeInexactRangeWithOverflowBitset) {
5400 // CREATE TABLE t1(x VARCHAR(100), y INT, z INT, KEY(x), KEY(y)).
5401 Mock_field_varstring x(/*share=*/nullptr, /*name=*/"x",
5402 /*char_len=*/100, /*is_nullable=*/true);
5403 Mock_field_long y("y");
5404 Mock_field_long z("z");
5405 Fake_TABLE *t1 = new (m_thd->mem_root) Fake_TABLE(&x, &y, &z);
5406 t1->file->stats.records = 10000;
5407 t1->file->stats.data_file_length = 1e6;
5408 t1->create_index(&x, nullptr, /*unique=*/false);
5409 t1->create_index(&y, nullptr, /*unique=*/false);
5410 ON_CALL(*down_cast<Mock_HANDLER *>(t1->file), index_flags(_, _, _))
5411 .WillByDefault(Return(HA_READ_RANGE | HA_READ_NEXT | HA_READ_PREV));
5412 m_fake_tables["t1"] = t1;
5413
5414 // We want to test a query that does an inexact range scan (achieved by having
5415 // a LIKE predicate on one of the indexed columns) and has enough predicates
5416 // that they don't fit in an inlined OverflowBitset in the range scan access
5417 // path. We need at least 64 predicates to make OverflowBitset overflow.
5418 constexpr int number_of_predicates = 70;
5419 string predicates = "(((t1.x like 'abc%xyz') or (t1.y > 3))";
5420 for (int i = 1; i < number_of_predicates; ++i) {
5421 predicates += " and (t1.z <> " + to_string(i) + ')';
5422 }
5423 predicates += ')';
5424
5425 string query = "SELECT 1 FROM t1 WHERE " + predicates;
5426 Query_block *query_block = ParseAndResolve(query.c_str(),
5427 /*nullable=*/false);
5428
5429 string trace;
5430 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5431 SCOPED_TRACE(trace); // Prints out the trace on failure.
5432 ASSERT_NE(nullptr, root);
5433 // Prints out the query plan on failure.
5434 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5435 /*is_root_of_join=*/true));
5436
5437 ASSERT_EQ(AccessPath::FILTER, root->type);
5438 EXPECT_EQ(AccessPath::INDEX_MERGE, root->filter().child->type);
5439
5440 // Since an inexact range predicate is used, all predicates should be kept in
5441 // the filter node on top.
5442 EXPECT_EQ(predicates, ItemToString(root->filter().condition));
5443 }
5444
5445 TEST_F(HypergraphOptimizerTest, PropagateCondConstants) {
5446 Query_block *query_block =
5447 ParseAndResolve("SELECT t1.x FROM t1 WHERE t1.x = 10 and t1.x <> 11",
5448 /*nullable=*/true);
5449
5450 m_initializer.thd()->lex->set_using_hypergraph_optimizer(true);
5451 COND_EQUAL *cond_equal = nullptr;
5452 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
5453 nullptr, &query_block->cond_value));
5454 // Check that the second predicate in the where condition is removed
5455 // as it's always true.
5456 EXPECT_EQ("(t1.x = 10)", ItemToString(query_block->where_cond()));
5457 }
5458
5459 TEST_F(HypergraphOptimizerTest, PropagationInNonEqualities) {
5460 Query_block *query_block = ParseAndResolve(
5461 "SELECT t1.x FROM t1 JOIN t2 WHERE t1.x = t2.x AND t1.x <> t2.x + 10",
5462 /*nullable=*/true);
5463
5464 COND_EQUAL *cond_equal = nullptr;
5465 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
5466 &query_block->m_table_nest,
5467 &query_block->cond_value));
5468 m_fake_tables["t1"]->file->stats.records = 100;
5469 m_fake_tables["t2"]->file->stats.records = 10000;
5470
5471 // Set up some large scan costs to discourage nested loop.
5472 m_fake_tables["t1"]->file->stats.data_file_length = 1e6;
5473 m_fake_tables["t2"]->file->stats.data_file_length = 100e6;
5474
5475 string trace;
5476 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5477 SCOPED_TRACE(trace); // Prints out the trace on failure.
5478 // Prints out the query plan on failure.
5479 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5480 /*is_root_of_join=*/true));
5481
5482 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
5483 RelationalExpression *expr = root->hash_join().join_predicate->expr;
5484 ASSERT_EQ(1, expr->equijoin_conditions.size());
5485 EXPECT_EQ("(t1.x = t2.x)", ItemToString(expr->equijoin_conditions[0]));
5486
5487 AccessPath *t1 = root->hash_join().inner;
5488 ASSERT_EQ(AccessPath::FILTER, t1->type);
5489 EXPECT_EQ("(t1.x <> (t1.x + 10))", ItemToString(t1->filter().condition));
5490 EXPECT_EQ(m_fake_tables["t1"], t1->filter().child->table_scan().table);
5491
5492 AccessPath *t2 = root->hash_join().outer;
5493 ASSERT_EQ(AccessPath::TABLE_SCAN, t2->type);
5494 EXPECT_EQ(m_fake_tables["t2"], t2->table_scan().table);
5495 }
5496
5497 TEST_F(HypergraphOptimizerTest, PropagateEqualityToZeroRows) {
5498 Query_block *query_block =
5499 ParseAndResolve("SELECT 1 FROM t1, t2 WHERE t1.x = t2.x AND t1.x < t2.x",
5500 /*nullable=*/true);
5501
5502 COND_EQUAL *cond_equal = nullptr;
5503 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
5504 &query_block->m_table_nest,
5505 &query_block->cond_value));
5506
5507 string trace;
5508 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5509 SCOPED_TRACE(trace); // Prints out the trace on failure.
5510 // Prints out the query plan on failure.
5511 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5512 /*is_root_of_join=*/true));
5513
5514 EXPECT_EQ(AccessPath::ZERO_ROWS, root->type);
5515 }
5516
5517 TEST_F(HypergraphOptimizerTest, PropagateEqualityToZeroRowsAggregated) {
5518 Query_block *query_block = ParseAndResolve(
5519 "SELECT COUNT(*) FROM t1, t2 WHERE t1.x = t2.x AND t1.x < t2.x",
5520 /*nullable=*/true);
5521
5522 COND_EQUAL *cond_equal = nullptr;
5523 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
5524 &query_block->m_table_nest,
5525 &query_block->cond_value));
5526
5527 string trace;
5528 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5529 SCOPED_TRACE(trace); // Prints out the trace on failure.
5530 // Prints out the query plan on failure.
5531 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5532 /*is_root_of_join=*/true));
5533
5534 EXPECT_EQ(AccessPath::ZERO_ROWS_AGGREGATED, root->type);
5535 }
5536
5537 TEST_F(HypergraphOptimizerTest, RowCountImplicitlyGrouped) {
5538 Query_block *query_block =
5539 ParseAndResolve("SELECT SUM(t1.x) FROM t1", /*nullable=*/true);
5540
5541 m_fake_tables["t1"]->file->stats.records = 100000;
5542
5543 string trace;
5544 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5545 SCOPED_TRACE(trace); // Prints out the trace on failure.
5546 // Prints out the query plan on failure.
5547 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5548 /*is_root_of_join=*/true));
5549
5550 // Implicitly grouped queries always return a single row.
5551 EXPECT_EQ(AccessPath::AGGREGATE, root->type);
5552 EXPECT_FLOAT_EQ(1.0, root->num_output_rows());
5553 }
5554
5555 TEST_F(HypergraphOptimizerTest, SingleTableDeleteWithOrderByLimit) {
5556 Query_block *query_block =
5557 ParseAndResolve("DELETE FROM t1 WHERE t1.x > 0 ORDER BY t1.y LIMIT 2",
5558 /*nullable=*/false);
5559 ASSERT_NE(nullptr, query_block);
5560
5561 string trace;
5562 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5563 SCOPED_TRACE(trace); // Prints out the trace on failure.
5564 ASSERT_NE(nullptr, root);
5565 ASSERT_EQ(AccessPath::DELETE_ROWS, root->type);
5566 EXPECT_EQ(m_fake_tables["t1"]->pos_in_table_list->map(),
5567 root->delete_rows().immediate_tables);
5568 ASSERT_EQ(AccessPath::SORT, root->delete_rows().child->type);
5569 EXPECT_EQ(2, root->delete_rows().child->sort().limit);
5570 ASSERT_EQ(AccessPath::FILTER, root->delete_rows().child->sort().child->type);
5571 EXPECT_EQ(AccessPath::TABLE_SCAN,
5572 root->delete_rows().child->sort().child->filter().child->type);
5573
5574 query_block->cleanup(/*full=*/true);
5575 }
5576
5577 TEST_F(HypergraphOptimizerTest, SingleTableDeleteWithLimit) {
5578 Query_block *query_block =
5579 ParseAndResolve("DELETE FROM t1 WHERE t1.x > 0 LIMIT 2",
5580 /*nullable=*/false);
5581 ASSERT_NE(nullptr, query_block);
5582
5583 string trace;
5584 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5585 SCOPED_TRACE(trace); // Prints out the trace on failure.
5586 ASSERT_NE(nullptr, root);
5587 ASSERT_EQ(AccessPath::DELETE_ROWS, root->type);
5588 EXPECT_EQ(m_fake_tables["t1"]->pos_in_table_list->map(),
5589 root->delete_rows().immediate_tables);
5590 ASSERT_EQ(AccessPath::LIMIT_OFFSET, root->delete_rows().child->type);
5591 ASSERT_EQ(AccessPath::FILTER,
5592 root->delete_rows().child->limit_offset().child->type);
5593 EXPECT_EQ(
5594 AccessPath::TABLE_SCAN,
5595 root->delete_rows().child->limit_offset().child->filter().child->type);
5596
5597 query_block->cleanup(/*full=*/true);
5598 }
5599
5600 // Delete from a single table using the multi-table delete syntax.
5601 TEST_F(HypergraphOptimizerTest, DeleteSingleAsMultiTable) {
5602 Query_block *query_block = ParseAndResolve("DELETE t1 FROM t1 WHERE t1.x = 1",
5603 /*nullable=*/false);
5604 ASSERT_NE(nullptr, query_block);
5605
5606 string trace;
5607 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5608 SCOPED_TRACE(trace); // Prints out the trace on failure.
5609 ASSERT_NE(nullptr, root);
5610 ASSERT_EQ(AccessPath::DELETE_ROWS, root->type);
5611 EXPECT_EQ(m_fake_tables["t1"]->pos_in_table_list->map(),
5612 root->delete_rows().immediate_tables);
5613 ASSERT_EQ(AccessPath::FILTER, root->delete_rows().child->type);
5614 EXPECT_EQ(AccessPath::TABLE_SCAN,
5615 root->delete_rows().child->filter().child->type);
5616
5617 query_block->cleanup(/*full=*/true);
5618 }
5619
5620 TEST_F(HypergraphOptimizerTest, DeleteFromTwoTables) {
5621 Query_block *query_block =
5622 ParseAndResolve("DELETE t1, t2 FROM t1, t2 WHERE t1.x = t2.x",
5623 /*nullable=*/false);
5624 ASSERT_NE(nullptr, query_block);
5625
5626 m_fake_tables["t1"]->file->stats.records = 1000;
5627 m_fake_tables["t2"]->file->stats.records = 100;
5628
5629 string trace;
5630 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5631 SCOPED_TRACE(trace); // Prints out the trace on failure.
5632 ASSERT_NE(nullptr, root);
5633 ASSERT_EQ(AccessPath::DELETE_ROWS, root->type);
5634 ASSERT_EQ(AccessPath::HASH_JOIN, root->delete_rows().child->type);
5635
5636 // A hash join is chosen, since the tables are so big that a nested loop join
5637 // is more expensive, even though it does not have to buffer row IDs. The join
5638 // order (t1, t2) is preferred because t2 is smaller and hashes fewer rows.
5639 // None of the tables can be deleted from immediately when we use hash join.
5640 EXPECT_EQ(0, root->delete_rows().immediate_tables);
5641 ASSERT_EQ(AccessPath::TABLE_SCAN,
5642 root->delete_rows().child->hash_join().outer->type);
5643 EXPECT_EQ(m_fake_tables["t1"],
5644 root->delete_rows().child->hash_join().outer->table_scan().table);
5645
5646 query_block->cleanup(/*full=*/true);
5647 }
5648
5649 TEST_F(HypergraphOptimizerTest, DeletePreferImmediate) {
5650 // Delete from one table (t1), but read from one additional table (t2).
5651 Query_block *query_block =
5652 ParseAndResolve("DELETE t1 FROM t1, t2 WHERE t1.x = t2.x",
5653 /*nullable=*/false);
5654 ASSERT_NE(nullptr, query_block);
5655
5656 // Add indexes so that a nested loop join with an index lookup on the inner
5657 // side is preferred. Make t1 slightly larger, so that the join order (t2, t1)
5658 // is considered cheaper than (t1, t2) before the cost of buffered deletes is
5659 // taken into consideration.
5660 Fake_TABLE *t1 = m_fake_tables["t1"];
5661 t1->create_index(t1->field[0], nullptr, /*unique=*/true);
5662 t1->file->stats.records = 110000;
5663 t1->file->stats.data_file_length = 1.1e6;
5664 Fake_TABLE *t2 = m_fake_tables["t2"];
5665 t2->create_index(t2->field[0], nullptr, /*unique=*/true);
5666 t2->file->stats.records = 100000;
5667 t2->file->stats.data_file_length = 1.0e6;
5668
5669 string trace;
5670 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5671 SCOPED_TRACE(trace); // Prints out the trace on failure.
5672 ASSERT_NE(nullptr, root);
5673 // Prints out the query plan on failure.
5674 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5675 /*is_root_of_join=*/true));
5676 ASSERT_EQ(AccessPath::DELETE_ROWS, root->type);
5677 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->delete_rows().child->type);
5678 const auto &nested_loop_join = root->delete_rows().child->nested_loop_join();
5679
5680 // Even though joining (t2, t1) is cheaper, it should choose the order (t1,
5681 // t2) to allow immediate deletes from t1, which gives a lower total cost for
5682 // the delete operation.
5683 EXPECT_EQ(t1->pos_in_table_list->map(), root->delete_rows().immediate_tables);
5684 ASSERT_EQ(AccessPath::TABLE_SCAN, nested_loop_join.outer->type);
5685 EXPECT_STREQ("t1", nested_loop_join.outer->table_scan().table->alias);
5686 ASSERT_EQ(AccessPath::EQ_REF, nested_loop_join.inner->type);
5687 EXPECT_STREQ("t2", nested_loop_join.inner->eq_ref().table->alias);
5688
5689 query_block->cleanup(/*full=*/true);
5690 }
5691
5692 TEST_F(HypergraphOptimizerTest, ImmedateDeleteFromRangeScan) {
5693 Query_block *query_block =
5694 ParseAndResolve("DELETE t1 FROM t1 WHERE t1.x < 100",
5695 /*nullable=*/false);
5696 ASSERT_NE(nullptr, query_block);
5697
5698 Fake_TABLE *t1 = m_fake_tables["t1"];
5699 t1->create_index(t1->field[0], nullptr, /*unique=*/true);
5700 t1->file->stats.records = 100000;
5701
5702 // Mark the index as supporting range scans.
5703 ON_CALL(*down_cast<Mock_HANDLER *>(t1->file), index_flags(_, _, _))
5704 .WillByDefault(Return(HA_READ_RANGE | HA_READ_NEXT | HA_READ_PREV));
5705
5706 string trace;
5707 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5708 SCOPED_TRACE(trace); // Prints out the trace on failure.
5709 ASSERT_NE(nullptr, root);
5710 // Prints out the query plan on failure.
5711 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5712 /*is_root_of_join=*/true));
5713 ASSERT_EQ(AccessPath::DELETE_ROWS, root->type);
5714 EXPECT_EQ(t1->pos_in_table_list->map(), root->delete_rows().immediate_tables);
5715 EXPECT_EQ(AccessPath::INDEX_RANGE_SCAN, root->delete_rows().child->type);
5716
5717 query_block->cleanup(/*full=*/true);
5718 }
5719
5720 TEST_F(HypergraphOptimizerTest, ImmedateDeleteFromIndexMerge) {
5721 Query_block *query_block =
5722 ParseAndResolve("DELETE t1 FROM t1 WHERE t1.x > 0 OR t1.y > 0",
5723 /*nullable=*/false);
5724 ASSERT_NE(nullptr, query_block);
5725
5726 Fake_TABLE *t1 = m_fake_tables["t1"];
5727 t1->create_index(t1->field[0], nullptr, /*unique=*/true);
5728 t1->create_index(t1->field[1], nullptr, /*unique=*/true);
5729 t1->file->stats.records = 100000;
5730
5731 // Mark the indexes as supporting range scans.
5732 ON_CALL(*down_cast<Mock_HANDLER *>(t1->file), index_flags(_, _, _))
5733 .WillByDefault(Return(HA_READ_RANGE | HA_READ_NEXT | HA_READ_PREV));
5734
5735 string trace;
5736 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5737 SCOPED_TRACE(trace); // Prints out the trace on failure.
5738 ASSERT_NE(nullptr, root);
5739 // Prints out the query plan on failure.
5740 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5741 /*is_root_of_join=*/true));
5742 ASSERT_EQ(AccessPath::DELETE_ROWS, root->type);
5743 EXPECT_EQ(AccessPath::INDEX_MERGE, root->delete_rows().child->type);
5744 EXPECT_EQ(t1->pos_in_table_list->map(), root->delete_rows().immediate_tables);
5745
5746 query_block->cleanup(/*full=*/true);
5747 }
5748
5749 TEST_F(HypergraphOptimizerTest, UpdatePreferImmediate) {
5750 // Update one table (t1), but read from one additional table (t2).
5751 Query_block *query_block =
5752 ParseAndResolve("UPDATE t1, t2 SET t1.x = t1.x + 1 WHERE t1.x = t2.x",
5753 /*nullable=*/false);
5754 ASSERT_NE(nullptr, query_block);
5755
5756 // Add indexes so that a nested loop join with an index lookup on the inner
5757 // side is preferred. Make t1 slightly larger, so that the join order (t2, t1)
5758 // is considered cheaper than (t1, t2) before the cost of buffered updates is
5759 // taken into consideration.
5760 Fake_TABLE *t1 = m_fake_tables["t1"];
5761 t1->create_index(t1->field[0], nullptr, /*unique=*/true);
5762 t1->file->stats.records = 110000;
5763 t1->file->stats.data_file_length = 1.1e6;
5764 Fake_TABLE *t2 = m_fake_tables["t2"];
5765 t2->create_index(t2->field[0], nullptr, /*unique=*/true);
5766 t2->file->stats.records = 100000;
5767 t2->file->stats.data_file_length = 1.0e6;
5768
5769 string trace;
5770 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5771 SCOPED_TRACE(trace); // Prints out the trace on failure.
5772 ASSERT_NE(nullptr, root);
5773 // Prints out the query plan on failure.
5774 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5775 /*is_root_of_join=*/true));
5776 ASSERT_EQ(AccessPath::UPDATE_ROWS, root->type);
5777 ASSERT_EQ(AccessPath::NESTED_LOOP_JOIN, root->update_rows().child->type);
5778 const auto &nested_loop_join = root->update_rows().child->nested_loop_join();
5779
5780 // Even though joining (t2, t1) is cheaper, it should choose the order (t1,
5781 // t2) to allow immediate update of t1, which gives a lower total cost for
5782 // the update operation.
5783 EXPECT_EQ(t1->pos_in_table_list->map(), root->update_rows().immediate_tables);
5784 ASSERT_EQ(AccessPath::TABLE_SCAN, nested_loop_join.outer->type);
5785 EXPECT_STREQ("t1", nested_loop_join.outer->table_scan().table->alias);
5786 ASSERT_EQ(AccessPath::EQ_REF, nested_loop_join.inner->type);
5787 EXPECT_STREQ("t2", nested_loop_join.inner->eq_ref().table->alias);
5788 }
5789
5790 TEST_F(HypergraphOptimizerTest, UpdateHashJoin) {
5791 Query_block *query_block =
5792 ParseAndResolve("UPDATE t1, t2 SET t1.x = 1, t2.x = 2 WHERE t1.y = t2.y",
5793 /*nullable=*/false);
5794 ASSERT_NE(nullptr, query_block);
5795
5796 // Size the tables so that a hash join is preferable to a nested loop join.
5797 Fake_TABLE *t1 = m_fake_tables["t1"];
5798 t1->file->stats.records = 100000;
5799 t1->file->stats.data_file_length = 1e6;
5800 Fake_TABLE *t2 = m_fake_tables["t2"];
5801 t2->file->stats.records = 10000;
5802 t2->file->stats.data_file_length = 1e5;
5803
5804 string trace;
5805 AccessPath *root = FindBestQueryPlan(m_thd, query_block, &trace);
5806 SCOPED_TRACE(trace); // Prints out the trace on failure.
5807 ASSERT_NE(nullptr, root);
5808 // Prints out the query plan on failure.
5809 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5810 /*is_root_of_join=*/true));
5811
5812 ASSERT_EQ(AccessPath::UPDATE_ROWS, root->type);
5813 // Both tables are updated.
5814 EXPECT_EQ(t1->pos_in_table_list->map() | t2->pos_in_table_list->map(),
5815 root->update_rows().tables_to_update);
5816 // No immediate update with hash join.
5817 EXPECT_EQ(0, root->update_rows().immediate_tables);
5818
5819 // Expect a hash join with the smaller table (t2) on the inner side.
5820 ASSERT_EQ(AccessPath::HASH_JOIN, root->update_rows().child->type);
5821 const auto &hash_join = root->update_rows().child->hash_join();
5822 ASSERT_EQ(AccessPath::TABLE_SCAN, hash_join.outer->type);
5823 EXPECT_EQ(t1, hash_join.outer->table_scan().table);
5824 ASSERT_EQ(AccessPath::TABLE_SCAN, hash_join.inner->type);
5825 EXPECT_EQ(t2, hash_join.inner->table_scan().table);
5826 }
5827
5828 // An alias for better naming.
5829 using HypergraphSecondaryEngineTest = HypergraphOptimizerTest;
5830
5831 TEST_F(HypergraphSecondaryEngineTest, SingleTable) {
5832 Query_block *query_block =
5833 ParseAndResolve("SELECT t1.x FROM t1", /*nullable=*/true);
5834 m_fake_tables["t1"]->file->stats.records = 100;
5835
5836 // Install a hook that doubles the row count estimate of t1.
5837 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
5838 hton->secondary_engine_modify_access_path_cost =
5839 [](THD *, const JoinHypergraph &, AccessPath *path) {
5840 EXPECT_EQ(AccessPath::TABLE_SCAN, path->type);
5841 EXPECT_STREQ("t1", path->table_scan().table->alias);
5842 path->set_num_output_rows(200);
5843 return false;
5844 };
5845
5846 string trace;
5847 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5848 SCOPED_TRACE(trace); // Prints out the trace on failure.
5849 ASSERT_NE(nullptr, root);
5850
5851 ASSERT_EQ(AccessPath::TABLE_SCAN, root->type);
5852 EXPECT_EQ(m_fake_tables["t1"], root->table_scan().table);
5853 EXPECT_FLOAT_EQ(200.0F, root->num_output_rows());
5854 }
5855
5856 TEST_F(HypergraphSecondaryEngineTest, SimpleInnerJoin) {
5857 Query_block *query_block = ParseAndResolve(
5858 "SELECT 1 FROM t1 JOIN t2 ON t1.x=t2.x JOIN t3 ON t2.y=t3.y",
5859 /*nullable=*/true);
5860 m_fake_tables["t1"]->file->stats.records = 10000;
5861 m_fake_tables["t2"]->file->stats.records = 100;
5862 m_fake_tables["t3"]->file->stats.records = 1000000;
5863
5864 // Install a hook that changes the row count estimate for t3 to 1.
5865 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
5866 hton->secondary_engine_modify_access_path_cost =
5867 [](THD *, const JoinHypergraph &, AccessPath *path) {
5868 // Nested-loop joins have been disabled for the secondary engine.
5869 EXPECT_NE(AccessPath::NESTED_LOOP_JOIN, path->type);
5870 if (path->type == AccessPath::TABLE_SCAN &&
5871 string(path->table_scan().table->alias) == "t3") {
5872 path->set_num_output_rows(1);
5873 }
5874 return false;
5875 };
5876
5877 string trace;
5878 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5879 SCOPED_TRACE(trace); // Prints out the trace on failure.
5880 ASSERT_NE(nullptr, root);
5881
5882 // Expect the biggest table to be the outer one. The table statistics tell
5883 // that this is t3, but the secondary engine cost hook changes the estimate
5884 // for t3 so that t1 becomes the biggest one.
5885 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
5886 ASSERT_EQ(AccessPath::TABLE_SCAN, root->hash_join().outer->type);
5887 EXPECT_STREQ("t1", root->hash_join().outer->table_scan().table->alias);
5888 }
5889
5890 TEST_F(HypergraphSecondaryEngineTest, OrderedAggregation) {
5891 Query_block *query_block =
5892 ParseAndResolve("SELECT t1.x FROM t1 GROUP BY t1.x", /*nullable=*/true);
5893 m_fake_tables["t1"]->file->stats.records = 100;
5894
5895 EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
5896
5897 string trace;
5898 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5899 SCOPED_TRACE(trace); // Prints out the trace on failure.
5900 ASSERT_NE(nullptr, root);
5901
5902 ASSERT_EQ(AccessPath::AGGREGATE, root->type);
5903 ASSERT_EQ(AccessPath::SORT, root->aggregate().child->type);
5904 }
5905
5906 TEST_F(HypergraphSecondaryEngineTest, UnorderedAggregation) {
5907 Query_block *query_block =
5908 ParseAndResolve("SELECT t1.x FROM t1 GROUP BY t1.x", /*nullable=*/true);
5909 m_fake_tables["t1"]->file->stats.records = 100;
5910
5911 EnableSecondaryEngine(/*aggregation_is_unordered=*/true);
5912
5913 string trace;
5914 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5915 SCOPED_TRACE(trace); // Prints out the trace on failure.
5916 ASSERT_NE(nullptr, root);
5917
5918 ASSERT_EQ(AccessPath::AGGREGATE, root->type);
5919 ASSERT_EQ(AccessPath::TABLE_SCAN, root->aggregate().child->type);
5920 }
5921
5922 TEST_F(HypergraphSecondaryEngineTest,
5923 OrderedAggregationCoversDistinctWithOrder) {
5924 Query_block *query_block =
5925 ParseAndResolve("SELECT DISTINCT t1.x, t1.y FROM t1 ORDER BY t1.y",
5926 /*nullable=*/true);
5927 m_fake_tables["t1"]->file->stats.records = 100;
5928
5929 EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
5930
5931 string trace;
5932 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5933 SCOPED_TRACE(trace); // Prints out the trace on failure.
5934 // Prints out the query plan on failure.
5935 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5936 /*is_root_of_join=*/true));
5937 ASSERT_NE(nullptr, root);
5938
5939 ASSERT_EQ(AccessPath::SORT, root->type);
5940 Filesort *sort = root->sort().filesort;
5941 ASSERT_EQ(2, sort->sort_order_length());
5942 EXPECT_EQ("t1.y", ItemToString(sort->sortorder[0].item));
5943 EXPECT_EQ("t1.x", ItemToString(sort->sortorder[1].item));
5944 EXPECT_TRUE(sort->m_remove_duplicates);
5945
5946 ASSERT_EQ(AccessPath::TABLE_SCAN, root->sort().child->type);
5947
5948 query_block->cleanup(/*full=*/true);
5949 }
5950
5951 TEST_F(HypergraphSecondaryEngineTest, UnorderedAggregationDoesNotCover) {
5952 Query_block *query_block =
5953 ParseAndResolve("SELECT DISTINCT t1.x, t1.y FROM t1 ORDER BY t1.y",
5954 /*nullable=*/true);
5955 m_fake_tables["t1"]->file->stats.records = 100;
5956
5957 EnableSecondaryEngine(/*aggregation_is_unordered=*/true);
5958
5959 string trace;
5960 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
5961 SCOPED_TRACE(trace); // Prints out the trace on failure.
5962 // Prints out the query plan on failure.
5963 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
5964 /*is_root_of_join=*/true));
5965 ASSERT_NE(nullptr, root);
5966 ASSERT_NE(nullptr, root);
5967
5968 // The final sort is just a regular sort, no duplicate removal.
5969 ASSERT_EQ(AccessPath::SORT, root->type);
5970 Filesort *sort = root->sort().filesort;
5971 ASSERT_EQ(1, sort->sort_order_length());
5972 EXPECT_EQ("t1.y", ItemToString(sort->sortorder[0].item));
5973 EXPECT_FALSE(sort->m_remove_duplicates);
5974
5975 // Below that, there's a duplicate-removing sort for DISTINCT.
5976 // Order does not matter, but it happens to choose the cover here.
5977 AccessPath *distinct = root->sort().child;
5978 ASSERT_EQ(AccessPath::SORT, distinct->type);
5979 sort = distinct->sort().filesort;
5980 ASSERT_EQ(2, sort->sort_order_length());
5981 EXPECT_EQ("t1.y", ItemToString(sort->sortorder[0].item));
5982 EXPECT_EQ("t1.x", ItemToString(sort->sortorder[1].item));
5983 EXPECT_TRUE(sort->m_remove_duplicates);
5984
5985 ASSERT_EQ(AccessPath::TABLE_SCAN, distinct->sort().child->type);
5986
5987 query_block->cleanup(/*full=*/true);
5988 }
5989
5990 TEST_F(HypergraphSecondaryEngineTest, RejectAllPlans) {
5991 Query_block *query_block = ParseAndResolve(
5992 "SELECT 1 FROM t1 JOIN t2 ON t1.x=t2.x JOIN t3 ON t2.y=t3.y",
5993 /*nullable=*/true);
5994
5995 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
5996 hton->secondary_engine_modify_access_path_cost =
5997 [](THD *, const JoinHypergraph &, AccessPath *path) {
5998 // Nested-loop joins have been disabled for the secondary engine.
5999 EXPECT_NE(AccessPath::NESTED_LOOP_JOIN, path->type);
6000 // Reject all plans.
6001 return true;
6002 };
6003
6004 // No plans will be found, so expect an error.
6005 ErrorChecker error_checker{m_thd, ER_SECONDARY_ENGINE};
6006
6007 string trace;
6008 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
6009 SCOPED_TRACE(trace); // Prints out the trace on failure.
6010 EXPECT_EQ(nullptr, root);
6011 }
6012
6013 TEST_F(HypergraphSecondaryEngineTest, RejectAllCompletePlans) {
6014 Query_block *query_block = ParseAndResolve(
6015 "SELECT 1 FROM t1 JOIN t2 ON t1.x=t2.x JOIN t3 ON t2.y=t3.y",
6016 /*nullable=*/true);
6017
6018 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
6019 hton->secondary_engine_modify_access_path_cost =
6020 [](THD *, const JoinHypergraph &, AccessPath *path) {
6021 // Reject the path if all three tables are referenced.
6022 return GetUsedTableMap(path, /*include_pruned_tables=*/true) == 0b111;
6023 };
6024
6025 // No plans will be found, so expect an error.
6026 ErrorChecker error_checker{m_thd, ER_SECONDARY_ENGINE};
6027
6028 string trace;
6029 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
6030 SCOPED_TRACE(trace); // Prints out the trace on failure.
6031 EXPECT_EQ(nullptr, root);
6032 }
6033
6034 TEST_F(HypergraphSecondaryEngineTest, RejectJoinOrders) {
6035 Query_block *query_block = ParseAndResolve(
6036 "SELECT 1 FROM t1 JOIN t2 ON t1.x=t2.x JOIN t3 ON t2.y=t3.y",
6037 /*nullable=*/true);
6038
6039 // Install a hook that only accepts hash joins where the outer table is a
6040 // table scan and the inner table is a table scan or another hash join, and
6041 // which only accepts join orders where the tables are ordered alphabetically
6042 // by their names.
6043 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
6044 hton->secondary_engine_modify_access_path_cost =
6045 [](THD *, const JoinHypergraph &, AccessPath *path) {
6046 // Nested-loop joins have been disabled for the secondary engine.
6047 EXPECT_NE(AccessPath::NESTED_LOOP_JOIN, path->type);
6048 if (path->type == AccessPath::HASH_JOIN) {
6049 if (path->hash_join().outer->type != AccessPath::TABLE_SCAN) {
6050 return true;
6051 }
6052 string outer = path->hash_join().outer->table_scan().table->alias;
6053 string inner;
6054 if (path->hash_join().inner->type == AccessPath::TABLE_SCAN) {
6055 inner = path->hash_join().inner->table_scan().table->alias;
6056 } else {
6057 EXPECT_EQ(AccessPath::HASH_JOIN, path->hash_join().inner->type);
6058 EXPECT_EQ(AccessPath::TABLE_SCAN,
6059 path->hash_join().inner->hash_join().inner->type);
6060 inner = path->hash_join()
6061 .inner->hash_join()
6062 .inner->table_scan()
6063 .table->alias;
6064 }
6065 // Reject plans where the join order is not alphabetical.
6066 return outer > inner;
6067 }
6068 return false;
6069 };
6070
6071 string trace;
6072 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
6073 SCOPED_TRACE(trace); // Prints out the trace on failure.
6074 ASSERT_NE(nullptr, root);
6075
6076 /*
6077 Expect the plan to have the following structure, because of the cost hook:
6078
6079 HJ
6080 / \
6081 t1 HJ
6082 / \
6083 t2 t3
6084 */
6085
6086 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
6087 const auto &outer_hash = root->hash_join();
6088 ASSERT_EQ(AccessPath::TABLE_SCAN, outer_hash.outer->type);
6089 ASSERT_EQ(AccessPath::HASH_JOIN, outer_hash.inner->type);
6090 const auto &inner_hash = outer_hash.inner->hash_join();
6091 ASSERT_EQ(AccessPath::TABLE_SCAN, inner_hash.inner->type);
6092 ASSERT_EQ(AccessPath::TABLE_SCAN, inner_hash.outer->type);
6093
6094 EXPECT_STREQ("t1", outer_hash.outer->table_scan().table->alias);
6095 EXPECT_STREQ("t2", inner_hash.outer->table_scan().table->alias);
6096 EXPECT_STREQ("t3", inner_hash.inner->table_scan().table->alias);
6097 }
6098
6099 /*
6100 For secondary engines we allow semijoin transformation for subqueries
6101 present in a join condition. We test if the transformation should
6102 be rejected or accepted when proposing hash joins.
6103 */
6104 TEST_F(HypergraphSecondaryEngineTest, SemiJoinWithOuterJoinMultipleEqual) {
6105 Query_block *query_block = ::parse(&m_initializer,
6106 "SELECT 1 FROM t1 LEFT JOIN t2 ON "
6107 "t1.x=t2.x AND t1.x IN (SELECT x FROM t3)",
6108 0);
6109 // Set using_hypergraph_optimizer to true and enable secondary engine
6110 // optimization so that the subquery to semijoin transformation
6111 // happens as intended. If not, resolver would think its the old join
6112 // optimizer and does the transformation anyways which makes testing
6113 // this use case harder.
6114 m_initializer.thd()->lex->set_using_hypergraph_optimizer(true);
6115 m_initializer.thd()->set_secondary_engine_optimization(
6116 Secondary_engine_optimization::SECONDARY);
6117 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
6118 ResolveQueryBlock(m_initializer.thd(), query_block, true, &m_fake_tables);
6119 hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
6120
6121 hton->secondary_engine_modify_access_path_cost =
6122 [](THD *, const JoinHypergraph &, AccessPath *path) {
6123 // Nested-loop joins have been disabled for the secondary engine.
6124 EXPECT_NE(AccessPath::NESTED_LOOP_JOIN, path->type);
6125 // Without the semijoin transformation, a subquery will
6126 // be placed in the ON condition of the outer join.
6127 if (path->type == AccessPath::HASH_JOIN) {
6128 if (path->hash_join().join_predicate->expr->type ==
6129 RelationalExpression::LEFT_JOIN) {
6130 RelationalExpression *left_join =
6131 path->hash_join().join_predicate->expr;
6132 // We reject all the plans which have subqueries in join conditions.
6133 if (!left_join->join_conditions.empty() &&
6134 left_join->join_conditions[0]->has_subquery())
6135 return true;
6136 }
6137 }
6138 return false;
6139 };
6140
6141 // Build multiple equalities from the join condition.
6142 COND_EQUAL *cond_equal = nullptr;
6143 EXPECT_FALSE(optimize_cond(m_thd, query_block->where_cond_ref(), &cond_equal,
6144 &query_block->m_table_nest,
6145 &query_block->cond_value));
6146 string trace;
6147 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
6148 SCOPED_TRACE(trace); // Prints out the trace on failure.
6149 // Check if a plan was generated as the query could be executed using
6150 // hash joins.
6151 EXPECT_NE(nullptr, root);
6152 // Plan would be this:
6153 // t1 LEFT JOIN (t2 SEMIJOIN t3 ON t2.x = t3.x) ON t1.x=t2.x
6154 // Make sure that the fields from the inner table of the semijoin
6155 // are not used in the join condition of the outer join.
6156 ASSERT_EQ(AccessPath::HASH_JOIN, root->type);
6157 const RelationalExpression *left_join =
6158 root->hash_join().join_predicate->expr;
6159 EXPECT_EQ(RelationalExpression::LEFT_JOIN, left_join->type);
6160 ASSERT_EQ(1, left_join->equijoin_conditions.size());
6161 EXPECT_EQ("(t1.x = t2.x)", ItemToString(left_join->equijoin_conditions[0]));
6162
6163 ASSERT_EQ(AccessPath::HASH_JOIN, root->hash_join().inner->type);
6164 const RelationalExpression *semijoin =
6165 root->hash_join().inner->hash_join().join_predicate->expr;
6166 EXPECT_EQ(RelationalExpression::SEMIJOIN, semijoin->type);
6167 ASSERT_EQ(1, semijoin->equijoin_conditions.size());
6168 EXPECT_EQ("(t2.x = t3.x)", ItemToString(semijoin->equijoin_conditions[0]));
6169 }
6170
6171 TEST_F(HypergraphSecondaryEngineTest, SemiJoinWithOuterJoin) {
6172 Query_block *query_block = ::parse(&m_initializer,
6173 "SELECT 1 FROM t1 LEFT JOIN t2 ON "
6174 "t1.x=t2.x AND t1.y IN (SELECT x FROM t3)",
6175 0);
6176 // Set using_hypergraph_optimizer to true and enable secondary engine
6177 // optimization so that the subquery to semijoin transformation
6178 // happens as intended. If not, resolver would think its the old join
6179 // optimizer and does the transformation anyways which makes testing
6180 // this use case harder.
6181 m_initializer.thd()->lex->set_using_hypergraph_optimizer(true);
6182 m_initializer.thd()->set_secondary_engine_optimization(
6183 Secondary_engine_optimization::SECONDARY);
6184 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
6185 ResolveQueryBlock(m_initializer.thd(), query_block, true, &m_fake_tables);
6186 hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
6187
6188 // Without the semijoin transformation, a subquery will be placed in the
6189 // ON condition of the outer join.
6190 hton->secondary_engine_modify_access_path_cost =
6191 [](THD *, const JoinHypergraph &, AccessPath *path) {
6192 // Nested-loop joins have been disabled for the secondary engine.
6193 EXPECT_NE(AccessPath::NESTED_LOOP_JOIN, path->type);
6194 if (path->type == AccessPath::HASH_JOIN) {
6195 if (path->hash_join().join_predicate->expr->type ==
6196 RelationalExpression::LEFT_JOIN) {
6197 RelationalExpression *left_join =
6198 path->hash_join().join_predicate->expr;
6199 // We reject plans which have subqueries in join conditions.
6200 if (!left_join->join_conditions.empty() &&
6201 left_join->join_conditions[0]->has_subquery())
6202 return true;
6203 }
6204 }
6205 return false;
6206 };
6207
6208 // No plans will be found, so expect an error.
6209 ErrorChecker error_checker{m_thd, ER_SECONDARY_ENGINE};
6210
6211 string trace;
6212 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
6213 SCOPED_TRACE(trace); // Prints out the trace on failure.
6214 // Check if all plans were rejected as the query cannot be executed
6215 // using hash joins.
6216 EXPECT_EQ(nullptr, root);
6217 }
6218
6219 namespace {
6220 struct RejectionParam {
6221 // The query to test.
6222 string query;
6223 // Path type to reject in the secondary engine cost hook.
6224 AccessPath::Type rejected_type;
6225 // Whether or not to expect an error if the specified path type always gives
6226 // an error or is rejected.
6227 bool expect_error;
6228 };
6229
6230 std::ostream &operator<<(std::ostream &os, const RejectionParam &param) {
6231 return os << param.query << '/' << param.rejected_type << '/'
6232 << param.expect_error;
6233 }
6234 } // namespace
6235
6236 using HypergraphSecondaryEngineRejectionTest =
6237 OptimizerTestWithParam<RejectionParam>;
6238
6239 TEST_P(HypergraphSecondaryEngineRejectionTest, RejectPathType) {
6240 const RejectionParam &param = GetParam();
6241 Query_block *query_block = ParseAndResolve(param.query.data(),
6242 /*nullable=*/true);
6243
6244 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
6245 hton->secondary_engine_modify_access_path_cost =
6246 [](THD *thd, const JoinHypergraph &, AccessPath *path) {
6247 EXPECT_FALSE(thd->is_error());
6248 return path->type == GetParam().rejected_type;
6249 };
6250
6251 ErrorChecker error_checker(m_thd,
6252 param.expect_error ? ER_SECONDARY_ENGINE : 0);
6253
6254 string trace;
6255 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
6256 SCOPED_TRACE(trace); // Prints out the trace on failure.
6257 EXPECT_EQ(param.expect_error, root == nullptr);
6258
6259 query_block->cleanup(/*full=*/true);
6260 }
6261
6262 TEST_P(HypergraphSecondaryEngineRejectionTest, ErrorOnPathType) {
6263 const RejectionParam &param = GetParam();
6264 Query_block *query_block = ParseAndResolve(param.query.data(),
6265 /*nullable=*/true);
6266
6267 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
6268 hton->secondary_engine_modify_access_path_cost =
6269 [](THD *thd, const JoinHypergraph &, AccessPath *path) {
6270 EXPECT_FALSE(thd->is_error());
6271 if (path->type == GetParam().rejected_type) {
6272 my_error(ER_SECONDARY_ENGINE_PLUGIN, MYF(0), "");
6273 return true;
6274 } else {
6275 return false;
6276 }
6277 };
6278
6279 ErrorChecker error_checker(
6280 m_thd, param.expect_error ? ER_SECONDARY_ENGINE_PLUGIN : 0);
6281
6282 string trace;
6283 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
6284 SCOPED_TRACE(trace); // Prints out the trace on failure.
6285 EXPECT_EQ(param.expect_error, root == nullptr);
6286
6287 query_block->cleanup(/*full=*/true);
6288 }
6289
6290 INSTANTIATE_TEST_SUITE_P(
6291 ErrorCases, HypergraphSecondaryEngineRejectionTest,
6292 ::testing::ValuesIn(std::initializer_list<RejectionParam>({
6293 {"SELECT 1 FROM t1 JOIN t2 ON t1.x=t2.x", AccessPath::TABLE_SCAN, true},
6294 {"SELECT 1 FROM t1 JOIN t2 ON t1.x=t2.x", AccessPath::HASH_JOIN, true},
6295 {"SELECT 1 FROM t1 JOIN t2 ON t1.x=t2.x ORDER BY t1.x",
6296 AccessPath::SORT, true},
6297 {"SELECT DISTINCT t1.x FROM t1", AccessPath::SORT, true},
6298 {"SELECT t1.x FROM t1 GROUP BY t1.x HAVING COUNT(*) > 5",
6299 AccessPath::FILTER, true},
6300 {"SELECT t1.x FROM t1 GROUP BY t1.x HAVING COUNT(*) > 5 ORDER BY t1.x",
6301 AccessPath::FILTER, true},
6302 {"SELECT 1 FROM t1 GROUP BY t1.x ORDER BY SUM(t1.y)",
6303 AccessPath::STREAM, true},
6304 })));
6305
6306 INSTANTIATE_TEST_SUITE_P(
6307 SuccessCases, HypergraphSecondaryEngineRejectionTest,
6308 ::testing::ValuesIn(std::initializer_list<RejectionParam>(
6309 {{"SELECT 1 FROM t1 WHERE t1.x=1", AccessPath::HASH_JOIN, false},
6310 {"SELECT 1 FROM t1 WHERE t1.x=1", AccessPath::SORT, false},
6311 {"SELECT DISTINCT t1.y, t1.x, 3 FROM t1 GROUP BY t1.x, t1.y",
6312 AccessPath::SORT, false}})));
6313
6314 TEST_F(HypergraphSecondaryEngineTest, NoRewriteOnFinalization) {
6315 Query_block *query_block = ParseAndResolve(
6316 "SELECT SUM(t1.x) FROM t1 GROUP BY t1.y ORDER BY AVG(t1.x)",
6317 /*nullable=*/true);
6318
6319 handlerton *handlerton =
6320 EnableSecondaryEngine(/*aggregation_is_unordered=*/true);
6321 handlerton->secondary_engine_flags |=
6322 MakeSecondaryEngineFlags(SecondaryEngineFlag::USE_EXTERNAL_EXECUTOR);
6323
6324 string trace;
6325 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
6326 SCOPED_TRACE(trace); // Prints out the trace on failure.
6327 ASSERT_NE(nullptr, root);
6328 // Prints out the query plan on failure.
6329 const string query_plan = PrintQueryPlan(0, root, query_block->join,
6330 /*is_root_of_join=*/true);
6331 SCOPED_TRACE(query_plan);
6332 // Verify that finalization was performed.
6333 EXPECT_FALSE(query_block->join->needs_finalize);
6334
6335 // There should be no materialization or streaming in the plan.
6336 ASSERT_EQ(AccessPath::SORT, root->type);
6337 ASSERT_EQ(AccessPath::AGGREGATE, root->sort().child->type);
6338 EXPECT_EQ(AccessPath::TABLE_SCAN,
6339 root->sort().child->aggregate().child->type);
6340
6341 // The item in the select list should be a SUM. It would have been an
6342 // Item_field pointing into a temporary table if the USE_EXTERNAL_EXECUTOR
6343 // flag was not set.
6344 auto visible_fields = VisibleFields(*query_block->join->fields);
6345 ASSERT_EQ(1, std::distance(visible_fields.begin(), visible_fields.end()));
6346 Item *select_list_item = *visible_fields.begin();
6347 ASSERT_EQ(Item::SUM_FUNC_ITEM, select_list_item->type());
6348 EXPECT_EQ(Item_sum::SUM_FUNC,
6349 down_cast<Item_sum *>(select_list_item)->sum_func());
6350
6351 // The order item should be an AVG. It would have been an Item_field pointing
6352 // into a temporary table if the USE_EXTERNAL_EXECUTOR flag was not set.
6353 Item *order_item = *root->sort().order->item;
6354 ASSERT_EQ(Item::SUM_FUNC_ITEM, order_item->type());
6355 EXPECT_EQ(Item_sum::AVG_FUNC, down_cast<Item_sum *>(order_item)->sum_func());
6356
6357 // Make sure the sort key is shown by EXPLAIN.
6358 EXPECT_THAT(query_plan, StartsWith("-> Sort: avg(t1.x) "));
6359
6360 query_block->cleanup(/*full=*/true);
6361 }
6362
6363 TEST_F(HypergraphSecondaryEngineTest, ExplainWindowForExternalExecutor) {
6364 Query_block *query_block =
6365 ParseAndResolve("SELECT PERCENT_RANK() OVER () FROM t1",
6366 /*nullable=*/true);
6367
6368 // Disable creation of intermediate temporary tables.
6369 handlerton *handlerton =
6370 EnableSecondaryEngine(/*aggregation_is_unordered=*/true);
6371 handlerton->secondary_engine_flags |=
6372 MakeSecondaryEngineFlags(SecondaryEngineFlag::USE_EXTERNAL_EXECUTOR);
6373
6374 string trace;
6375 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
6376 SCOPED_TRACE(trace); // Prints out the trace on failure.
6377 ASSERT_NE(nullptr, root);
6378 ASSERT_EQ(AccessPath::WINDOW, root->type);
6379 EXPECT_EQ(AccessPath::TABLE_SCAN, root->window().child->type);
6380
6381 // Finalization should not create temporary tables for the window functions.
6382 EXPECT_FALSE(query_block->join->needs_finalize);
6383 EXPECT_EQ(nullptr, root->window().temp_table);
6384 EXPECT_EQ(nullptr, root->window().temp_table_param);
6385
6386 // EXPLAIN for WINDOW paths used to get information from the associated
6387 // temporary table, which is not available until finalization has run.
6388 // Finalization is skipped when USE_EXTERNAL_EXECUTOR is enabled, so this used
6389 // to crash.
6390 EXPECT_THAT(
6391 PrintQueryPlan(0, root, query_block->join,
6392 /*is_root_of_join=*/true),
6393 StartsWith("-> Window aggregate with buffering: percent_rank() OVER ()"));
6394
6395 query_block->cleanup(/*full=*/true);
6396 }
6397
6398 TEST_F(HypergraphSecondaryEngineTest, NoMaterializationForExternalExecutor) {
6399 Base_mock_field_blob t1_x{"x", Field::MAX_LONG_BLOB_WIDTH};
6400 Mock_field_long t1_y{"y"};
6401 m_fake_tables["t1"] = new (m_thd->mem_root) Fake_TABLE{&t1_x, &t1_y};
6402
6403 Query_block *query_block =
6404 ParseAndResolve("SELECT MAX(t1.x) FROM t1 GROUP BY t1.y ORDER BY t1.y",
6405 /*nullable=*/true);
6406
6407 // Disable creation of intermediate temporary tables.
6408 handlerton *handlerton =
6409 EnableSecondaryEngine(/*aggregation_is_unordered=*/true);
6410 handlerton->secondary_engine_flags |=
6411 MakeSecondaryEngineFlags(SecondaryEngineFlag::USE_EXTERNAL_EXECUTOR);
6412
6413 string trace;
6414 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
6415 SCOPED_TRACE(trace); // Prints out the trace on failure.
6416 ASSERT_NE(nullptr, root);
6417 // Prints out the query plan on failure.
6418 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
6419 /*is_root_of_join=*/true));
6420
6421 // There should be no materialization into a temporary table in the plan. If
6422 // USE_EXTERNAL_EXECUTOR had not been enabled, the plan would have contained a
6423 // materialization step between AGGREGATE and SORT because of the BLOB column.
6424 ASSERT_EQ(AccessPath::SORT, root->type);
6425 ASSERT_EQ(AccessPath::AGGREGATE, root->sort().child->type);
6426 ASSERT_EQ(AccessPath::TABLE_SCAN,
6427 root->sort().child->aggregate().child->type);
6428 EXPECT_STREQ(
6429 "t1", root->sort().child->aggregate().child->table_scan().table->alias);
6430
6431 query_block->cleanup(/*full=*/true);
6432 }
6433
6434 TEST_F(HypergraphSecondaryEngineTest, DontCallCostHookForEmptyJoins) {
6435 Query_block *query_block = ParseAndResolve(
6436 "SELECT 1 FROM t1, t2 WHERE t1.x=t2.x "
6437 "AND t1.y IS NULL AND t1.y IN (1,2,3)",
6438 /*nullable=*/true);
6439
6440 // Create an index on t1.y, so that the range optimizer detects the impossible
6441 // table filter.
6442 Fake_TABLE *t1 = m_fake_tables["t1"];
6443 t1->create_index(t1->field[1], nullptr, /*unique=*/true);
6444
6445 // The secondary engine cost hook is stateless, so let's create a thread local
6446 // variable for it to store the state in.
6447 thread_local vector<AccessPath> paths;
6448 paths.clear();
6449
6450 handlerton *hton = EnableSecondaryEngine(/*aggregation_is_unordered=*/false);
6451 hton->secondary_engine_modify_access_path_cost =
6452 [](THD *, const JoinHypergraph &, AccessPath *path) {
6453 paths.push_back(*path);
6454 return false;
6455 };
6456
6457 string trace;
6458 AccessPath *root = FindBestQueryPlanAndFinalize(m_thd, query_block, &trace);
6459 SCOPED_TRACE(trace); // Prints out the trace on failure.
6460 ASSERT_NE(nullptr, root);
6461 // Prints out the query plan on failure.
6462 SCOPED_TRACE(PrintQueryPlan(0, root, query_block->join,
6463 /*is_root_of_join=*/true));
6464
6465 // The join is known to be always empty.
6466 EXPECT_EQ(AccessPath::ZERO_ROWS, root->type);
6467
6468 // The secondary engine cost hook should see the TABLE_SCAN on t2, since
6469 // that's the first table found by the join enumeration algorithm. When the
6470 // join enumeration goes on to see t1, it detects that t1 has a condition
6471 // that's always false, and it immediately stops exploring more plans. The
6472 // hook therefore doesn't see any more plans.
6473 ASSERT_EQ(1, paths.size());
6474 ASSERT_EQ(AccessPath::TABLE_SCAN, paths[0].type);
6475 EXPECT_STREQ("t2", paths[0].table_scan().table->alias);
6476 }
6477
6478 /*
6479 A hypergraph receiver that doesn't actually cost any plans;
6480 it only counts the number of possible plans that would be
6481 considered.
6482 */
6483 struct CountingReceiver {
6484 CountingReceiver(const JoinHypergraph &graph, size_t num_relations)
6485 : m_graph(graph), m_num_subplans(new size_t[1llu << num_relations]) {
6486 std::fill(m_num_subplans.get(),
6487 m_num_subplans.get() + (1llu << num_relations), 0);
6488 }
6489
6490 bool HasSeen(NodeMap subgraph) { return m_num_subplans[subgraph] != 0; }
6491
6492 bool FoundSingleNode(int node_idx) {
6493 NodeMap map = TableBitmap(node_idx);
6494 ++m_num_subplans[map];
6495 return false;
6496 }
6497
6498 bool FoundSubgraphPair(NodeMap left, NodeMap right, int edge_idx) {
6499 const JoinPredicate *edge = &m_graph.edges[edge_idx];
6500 if (!PassesConflictRules(left | right, edge->expr)) {
6501 return false;
6502 }
6503 size_t n = m_num_subplans[left] * m_num_subplans[right];
6504 if (OperatorIsCommutative(*edge->expr)) {
6505 m_num_subplans[left | right] += 2 * n;
6506 } else {
6507 m_num_subplans[left | right] += n;
6508 }
6509 return false;
6510 }
6511
6512 size_t count(NodeMap map) const {
6513 #if defined(__GNUC__) && __GNUC__ >= 14
6514 // Silence -Warray-bounds warning in GCC 14.
6515 [[assume(map != std::numeric_limits<uint64_t>::max())]];
6516 #endif
6517 return m_num_subplans[map];
6518 }
6519
6520 const JoinHypergraph &m_graph;
6521 std::unique_ptr<size_t[]> m_num_subplans;
6522 };
6523
6524 RelationalExpression *CloneRelationalExpr(THD *thd,
6525 const RelationalExpression *expr) {
6526 RelationalExpression *new_expr =
6527 new (thd->mem_root) RelationalExpression(thd);
6528 new_expr->type = expr->type;
6529 new_expr->tables_in_subtree = expr->tables_in_subtree;
6530 if (new_expr->type == RelationalExpression::TABLE) {
6531 new_expr->table = expr->table;
6532 } else {
6533 new_expr->left = CloneRelationalExpr(thd, expr->left);
6534 new_expr->right = CloneRelationalExpr(thd, expr->right);
6535 }
6536 return new_expr;
6537 }
6538
6539 // Generate all possible complete binary trees of (exactly) the given size,
6540 // consisting only of inner joins, and with fake tables at the leaves.
6541 vector<RelationalExpression *> GenerateAllCompleteBinaryTrees(
6542 THD *thd, size_t num_relations, size_t start_idx,
6543 vector<unique_ptr_destroy_only<Fake_TABLE>> *tables) {
6544 assert(num_relations != 0);
6545
6546 vector<RelationalExpression *> ret;
6547 if (num_relations == 1) {
6548 Fake_TABLE *table = new (thd->mem_root)
6549 Fake_TABLE(/*column_count=*/1, /*cols_nullable=*/true);
6550 table->pos_in_table_list->set_tableno(start_idx);
6551 tables->emplace_back(table);
6552
6553 // For debugging only.
6554 char name[32];
6555 snprintf(name, sizeof(name), "t%zu", start_idx + 1);
6556 table->alias = sql_strdup(name);
6557 table->pos_in_table_list->alias = table->alias;
6558
6559 RelationalExpression *expr = new (thd->mem_root) RelationalExpression(thd);
6560 expr->type = RelationalExpression::TABLE;
6561 expr->table = table->pos_in_table_list;
6562 expr->tables_in_subtree = table->pos_in_table_list->map();
6563
6564 ret.push_back(expr);
6565 return ret;
6566 }
6567
6568 for (size_t num_left = 1; num_left <= num_relations - 1; ++num_left) {
6569 size_t num_right = num_relations - num_left;
6570 vector<RelationalExpression *> left =
6571 GenerateAllCompleteBinaryTrees(thd, num_left, start_idx, tables);
6572 vector<RelationalExpression *> right = GenerateAllCompleteBinaryTrees(
6573 thd, num_right, start_idx + num_left, tables);
6574
6575 // Generate all pairs of trees, cloning as we go.
6576 for (size_t i = 0; i < left.size(); ++i) {
6577 for (size_t j = 0; j < right.size(); ++j) {
6578 RelationalExpression *expr =
6579 new (thd->mem_root) RelationalExpression(thd);
6580 expr->type = RelationalExpression::INNER_JOIN;
6581 expr->left = CloneRelationalExpr(thd, left[i]);
6582 expr->right = CloneRelationalExpr(thd, right[j]);
6583 expr->tables_in_subtree =
6584 expr->left->tables_in_subtree | expr->right->tables_in_subtree;
6585 ret.push_back(expr);
6586 }
6587 }
6588 }
6589 return ret;
6590 }
6591
6592 // For each join operation (starting from idx), try all join types
6593 // and all possible simple, non-degenerate predicaes, calling func()
6594 // for each combination.
6595 template <class Func>
6596 void TryAllPredicates(
6597 const vector<RelationalExpression *> &join_ops,
6598 const vector<Item_field *> &fields,
6599 const vector<RelationalExpression::Type> &join_types,
6600 unordered_map<RelationalExpression *, table_map> *generated_nulls,
6601 size_t idx, const Func &func) {
6602 if (idx == join_ops.size()) {
6603 func();
6604 return;
6605 }
6606
6607 RelationalExpression *expr = join_ops[idx];
6608 for (RelationalExpression::Type join_type : join_types) {
6609 expr->type = join_type;
6610
6611 // Check which tables are visible after this join
6612 // (you can't have a predicate pointing into the right side
6613 // of an antijoin).
6614 const table_map left_map = expr->left->tables_in_subtree;
6615 const table_map right_map = expr->right->tables_in_subtree;
6616 if (join_type == RelationalExpression::ANTIJOIN ||
6617 join_type == RelationalExpression::SEMIJOIN) {
6618 expr->tables_in_subtree = left_map;
6619 } else {
6620 expr->tables_in_subtree = left_map | right_map;
6621 }
6622
6623 (*generated_nulls)[expr] =
6624 (*generated_nulls)[expr->left] | (*generated_nulls)[expr->right];
6625 if (join_type == RelationalExpression::LEFT_JOIN) {
6626 (*generated_nulls)[expr] |= right_map;
6627 } else if (join_type == RelationalExpression::FULL_OUTER_JOIN) {
6628 (*generated_nulls)[expr] |= left_map | right_map;
6629 }
6630
6631 // Find all pairs of tables under this operation, and construct an equijoin
6632 // predicate for them.
6633 for (Item_field *field1 : fields) {
6634 if (!IsSubset(field1->used_tables(), left_map)) {
6635 continue;
6636 }
6637 if ((join_type == RelationalExpression::INNER_JOIN ||
6638 join_type == RelationalExpression::SEMIJOIN) &&
6639 IsSubset(field1->used_tables(), (*generated_nulls)[expr->left])) {
6640 // Should have be simplified away. (See test comment.)
6641 continue;
6642 }
6643 for (Item_field *field2 : fields) {
6644 if (!IsSubset(field2->used_tables(), right_map)) {
6645 continue;
6646 }
6647 if ((join_type == RelationalExpression::INNER_JOIN ||
6648 join_type == RelationalExpression::SEMIJOIN ||
6649 join_type == RelationalExpression::LEFT_JOIN ||
6650 join_type == RelationalExpression::ANTIJOIN) &&
6651 IsSubset(field2->used_tables(), (*generated_nulls)[expr->right])) {
6652 // Should have be simplified away. (See test comment.)
6653 continue;
6654 }
6655
6656 Item_func_eq *pred = new Item_func_eq(field1, field2);
6657 pred->update_used_tables();
6658 pred->quick_fix_field();
6659 expr->equijoin_conditions[0] = pred;
6660 expr->conditions_used_tables =
6661 field1->used_tables() | field2->used_tables();
6662
6663 TryAllPredicates(join_ops, fields, join_types, generated_nulls, idx + 1,
6664 func);
6665 }
6666 }
6667 }
6668 }
6669
6670 std::pair<size_t, size_t> CountTreesAndPlans(
6671 THD *thd, int num_relations,
6672 const std::vector<RelationalExpression::Type> &join_types) {
6673 size_t num_trees = 0, num_plans = 0;
6674
6675 vector<unique_ptr_destroy_only<Fake_TABLE>> tables;
6676 vector<RelationalExpression *> roots = GenerateAllCompleteBinaryTrees(
6677 thd, num_relations, /*start_idx=*/0, &tables);
6678 for (RelationalExpression *expr : roots) {
6679 vector<RelationalExpression *> join_ops;
6680 vector<Item_field *> fields;
6681
6682 // Which tables can get NULL-complemented rows due to outer joins.
6683 // We use this to reject inner joins against them, on the basis
6684 // that they would be simplified away and thus don't count.
6685 unordered_map<RelationalExpression *, table_map> generated_nulls;
6686
6687 // Collect lists of all ops, and create tables where needed.
6688 ForEachOperator(
6689 expr, [&join_ops, &fields, &generated_nulls](RelationalExpression *op) {
6690 if (op->type == RelationalExpression::TABLE) {
6691 Item_field *field = new Item_field(op->table->table->field[0]);
6692 field->quick_fix_field();
6693 fields.push_back(field);
6694 op->tables_in_subtree = op->table->map();
6695 generated_nulls.emplace(op, 0);
6696 } else {
6697 join_ops.push_back(op);
6698 op->equijoin_conditions.clear();
6699 op->equijoin_conditions.push_back(nullptr);
6700 }
6701 });
6702
6703 TryAllPredicates(
6704 join_ops, fields, join_types, &generated_nulls, /*idx=*/0, [&] {
6705 JoinHypergraph graph(thd->mem_root, /*query_block=*/nullptr);
6706 for (RelationalExpression *op : join_ops) {
6707 op->conflict_rules.clear();
6708 }
6709 MakeJoinGraphFromRelationalExpression(thd, expr, /*trace=*/nullptr,
6710 &graph);
6711 CountingReceiver receiver(graph, num_relations);
6712 ASSERT_FALSE(EnumerateAllConnectedPartitions(graph.graph, &receiver));
6713 ++num_trees;
6714 num_plans += receiver.count(TablesBetween(0, num_relations));
6715 });
6716 }
6717
6718 return {num_trees, num_plans};
6719 }
6720
6721 /*
6722 Reproduces tables 4 and 5 from [Moe13]; builds all possible complete
6723 binary trees, fills them with all possible join operators from a given
6724 set, adds a simple (non-degenerate) equality predicate for each,
6725 and counts the number of plans. By getting numbers that match exactly,
6726 we can say with a fairly high degree of certainty that we've managed to
6727 get all the associativity etc. tables correct.
6728
6729 The paper makes a few unspoken assumptions that are worth noting:
6730
6731 1. After an antijoin or semijoin, the right side “disappears” and
6732 can not be used for further join predicates. This is consistent
6733 with the typical EXISTS / NOT EXISTS formulation in SQL.
6734 2. Outer joins are assumed simplified away wherever possible, so
6735 queries like (a JOIN (b LEFT JOIN c ON ...) a.x=c.x) are discarded
6736 as meaningless -- since the join predicate would discard any NULLs
6737 generated for c, the LEFT JOIN could just as well be an inner join.
6738 3. All predicates are assumed to be NULL-rejecting.
6739
6740 Together, these explain why we have e.g. 26 queries with n=3 and the
6741 small operator set, instead of 36 (which would be logical for two shapes
6742 of binary trees, three operators for the top node, three for the bottom node
6743 and two possible top join predicates) or even more (if including non-nullable
6744 outer join predicates).
6745
6746 We don't match the number of empty and nonempty rule sets given, but ours
6747 are correct and the paper's have a bug that prevents some simplification
6748 (Moerkotte, personal communication).
6749 */
6750 TEST(ConflictDetectorTest, CountPlansSmallOperatorSet) {
6751 Server_initializer initializer;
6752 initializer.SetUp();
6753 THD *thd = initializer.thd();
6754 current_thd = thd;
6755
6756 vector<RelationalExpression::Type> join_types{
6757 RelationalExpression::INNER_JOIN, RelationalExpression::LEFT_JOIN,
6758 RelationalExpression::ANTIJOIN};
6759 EXPECT_THAT(CountTreesAndPlans(thd, 3, join_types), Pair(26, 88));
6760 EXPECT_THAT(CountTreesAndPlans(thd, 4, join_types), Pair(344, 4059));
6761 EXPECT_THAT(CountTreesAndPlans(thd, 5, join_types), Pair(5834, 301898));
6762
6763 // This takes too long to run for a normal unit test run (~10s in optimized
6764 // mode).
6765 if (false) {
6766 EXPECT_THAT(CountTreesAndPlans(thd, 6, join_types), Pair(117604, 32175460));
6767 EXPECT_THAT(CountTreesAndPlans(thd, 7, join_types),
6768 Pair(2708892, 4598129499));
6769 }
6770 initializer.TearDown();
6771 }
6772
6773 TEST(ConflictDetectorTest, CountPlansLargeOperatorSet) {
6774 Server_initializer initializer;
6775 initializer.SetUp();
6776 THD *thd = initializer.thd();
6777 current_thd = thd;
6778
6779 vector<RelationalExpression::Type> join_types{
6780 RelationalExpression::INNER_JOIN, RelationalExpression::LEFT_JOIN,
6781 RelationalExpression::FULL_OUTER_JOIN, RelationalExpression::SEMIJOIN,
6782 RelationalExpression::ANTIJOIN};
6783 EXPECT_THAT(CountTreesAndPlans(thd, 3, join_types), Pair(62, 203));
6784 EXPECT_THAT(CountTreesAndPlans(thd, 4, join_types), Pair(1114, 11148));
6785
6786 // These take too long to run for a normal unit test run (~80s in optimized
6787 // mode).
6788 if (false) {
6789 EXPECT_THAT(CountTreesAndPlans(thd, 5, join_types), Pair(25056, 934229));
6790 EXPECT_THAT(CountTreesAndPlans(thd, 6, join_types),
6791 Pair(661811, 108294798));
6792 EXPECT_THAT(CountTreesAndPlans(thd, 7, join_types),
6793 Pair(19846278, 16448441514));
6794 }
6795 initializer.TearDown();
6796 }
6797
6798 class CSETest : public OptimizerTestBase {
6799 protected:
6800 string TestCSE(const string &expression);
6801 };
6802
6803 string CSETest::TestCSE(const string &expression) {
6804 // Abuse ParseAndResolve() to get the expression parsed.
6805 Query_block *query_block = ParseAndResolve(
6806 ("SELECT 1 FROM t1, t2, t3, t4, t5 WHERE " + expression).c_str(),
6807 /*nullable=*/true);
6808 return ItemToString(
6809 CommonSubexpressionElimination(query_block->join->where_cond));
6810 }
6811
6812 TEST_F(CSETest, NoopSimpleItem) {
6813 EXPECT_EQ(TestCSE("t1.x=t2.x"), "(t1.x = t2.x)");
6814 }
6815
6816 TEST_F(CSETest, NoopANDNoOR) {
6817 EXPECT_EQ(TestCSE("t1.x=t2.x AND t2.x = t3.x"),
6818 "((t1.x = t2.x) and (t2.x = t3.x))");
6819 }
6820
6821 TEST_F(CSETest, NoopORNoAND) {
6822 EXPECT_EQ(TestCSE("t1.x=t2.x OR t2.x = t3.x"),
6823 "((t1.x = t2.x) or (t2.x = t3.x))");
6824 }
6825
6826 TEST_F(CSETest, NoopNoCommon) {
6827 EXPECT_EQ(TestCSE("t1.x=t2.x OR (t2.x = t3.x AND t3.x > 4)"),
6828 "((t1.x = t2.x) or ((t2.x = t3.x) and (t3.x > 4)))");
6829 }
6830
6831 TEST_F(CSETest, BasicSplit) {
6832 EXPECT_EQ(TestCSE("(t1.x=t2.x AND t2.x > 3) OR (t1.x=t2.x AND t2.x < 0)"),
6833 "((t1.x = t2.x) and ((t2.x > 3) or (t2.x < 0)))");
6834 }
6835
6836 TEST_F(CSETest, SplitFromRecursedORGroups) {
6837 EXPECT_EQ(TestCSE("(t1.x=0 AND t2.x>1) OR ((t1.x=0 AND t2.y>1) OR (t1.x=0 "
6838 "AND t2.z>0))"),
6839 "((t1.x = 0) and ((t2.x > 1) or (t2.y > 1) or (t2.z > 0)))");
6840 }
6841
6842 TEST_F(CSETest, SplitFromRecursedANDGroups) {
6843 EXPECT_EQ(TestCSE("(t2.x>1 AND (t2.y>1 AND (t1.x=0))) OR "
6844 "(t3.x>1 AND (t3.y>1 AND (t1.x=0)))"),
6845 "((t1.x = 0) and "
6846 "(((t2.x > 1) and (t2.y > 1)) or ((t3.x > 1) and (t3.y > 1))))");
6847 }
6848
6849 // Split out t1.x > 1 and t2.y < 2, ie., more than one element,
6850 // and they are in different orders. There are multiple items left
6851 // in the rightmost OR group, too.
6852 TEST_F(CSETest, SplitOutMoreThanOneElement) {
6853 EXPECT_EQ(TestCSE("(t1.x > 1 AND t2.y < 2 AND t2.x > 3) OR ((t2.y < 2 AND "
6854 "t1.x > 1 AND t2.x < 1 AND t2.z >= 4))"),
6855 "((t1.x > 1) and (t2.y < 2) and "
6856 "((t2.x > 3) or ((t2.x < 1) and (t2.z >= 4))))");
6857 }
6858
6859 TEST_F(CSETest, ShortCircuit) {
6860 EXPECT_EQ(TestCSE("t1.x=t2.x OR (t1.x=t2.x AND t2.x < 0)"), "(t1.x = t2.x)");
6861 }
6862
6863 TEST_F(CSETest, ShortCircuitWithMultipleElements) {
6864 EXPECT_EQ(TestCSE("(t1.x=0 AND t1.y=1) OR (t1.x=0 AND t1.y=1)"),
6865 "((t1.x = 0) and (t1.y = 1))");
6866 }
6867
6868 TEST_F(CSETest, EmptyOr) {
6869 // remove_eq_conds() may leave degenerate OR conditions with no children if
6870 // all elements of the OR expression are false. Verify that we don't balk at
6871 // such items.
6872 EXPECT_EQ("false", ItemToString(CommonSubexpressionElimination(
6873 new (m_thd->mem_root) Item_cond_or)));
6874 }
6875
6876 namespace {
6877 // A fake handler implementation that can be used in microbenchmarks. The
6878 // Mock_HANDLER object in Fake_TABLE has a lot of instrumentation that disturbs
6879 // the timing, so we roll our own lightweight handler instead.
6880 class Fake_handler_for_benchmark final : public handler {
6881 public:
6882 explicit Fake_handler_for_benchmark(Fake_TABLE *table_arg)
6883 : handler(table_arg->file->ht, table_arg->s) {
6884 set_ha_table(table_arg);
6885 }
6886
6887 // Report that range scans are supported, so that the range optimizer has
6888 // something to work with.
6889 ulong index_flags(uint, uint, bool) const override {
6890 return HA_READ_RANGE | HA_READ_NEXT | HA_READ_PREV;
6891 }
6892
6893 // Report that primary keys are clustered, to match InnoDB's default.
6894 bool primary_key_is_clustered() const override { return true; }
6895
6896 // Just stub out the rest of the functions. Raise assert failures on those
6897 // that are only expected to be called during execution.
6898
6899 void position(const uchar *) override { assert(false); }
6900 int info(uint) override { return 0; }
6901 const char *table_type() const override { return "fake"; }
6902 THR_LOCK_DATA **store_lock(THD *, THR_LOCK_DATA **,
6903 enum thr_lock_type) override {
6904 assert(false);
6905 return nullptr;
6906 }
6907 int create(const char *, TABLE *, HA_CREATE_INFO *, dd::Table *) override {
6908 assert(false);
6909 return HA_ERR_WRONG_COMMAND;
6910 }
6911
6912 protected:
6913 int rnd_next(uchar *) override {
6914 assert(false);
6915 return HA_ERR_WRONG_COMMAND;
6916 }
6917 int rnd_pos(uchar *, uchar *) override {
6918 assert(false);
6919 return HA_ERR_WRONG_COMMAND;
6920 }
6921
6922 private:
6923 int open(const char *, int, uint, const dd::Table *) override {
6924 assert(false);
6925 return HA_ERR_WRONG_COMMAND;
6926 }
6927 int close() override {
6928 assert(false);
6929 return HA_ERR_WRONG_COMMAND;
6930 }
6931 int rnd_init(bool) override {
6932 assert(false);
6933 return HA_ERR_WRONG_COMMAND;
6934 }
6935 Table_flags table_flags() const override { return 0; }
6936 };
6937 } // namespace
6938
6939 // Measures the time spent in FindBestQueryPlan() and
6940 // FinalizePlanForQueryBlock() for a point-select query.
6941 static void BM_FindBestQueryPlanPointSelect(size_t num_iterations) {
6942 StopBenchmarkTiming();
6943
6944 Server_initializer initializer;
6945 initializer.SetUp();
6946 unordered_map<string, Fake_TABLE *> fake_tables;
6947
6948 THD *const thd = initializer.thd();
6949
6950 Query_block *const query_block =
6951 ParseAndResolve("SELECT t1.y FROM t1 WHERE t1.x = 123",
6952 /*nullable=*/false, initializer, &fake_tables);
6953
6954 // Make t1.x the primary key. Add secondary indexes on t1.y and t1.z, just to
6955 // give the optimizer some more information to look into.
6956 Fake_TABLE *t1 = fake_tables["t1"];
6957 Fake_handler_for_benchmark fake_handler(t1);
6958 t1->set_handler(&fake_handler);
6959 t1->s->primary_key = t1->create_index(t1->field[0], nullptr, /*unique=*/true);
6960 t1->create_index(t1->field[1], nullptr, /*unique=*/false);
6961 t1->create_index(t1->field[2], nullptr, /*unique=*/false);
6962 t1->file->stats.records = 100000;
6963 t1->file->stats.data_file_length = 1e8;
6964
6965 // Build multiple equalities from the WHERE clause.
6966 COND_EQUAL *cond_equal = nullptr;
6967 EXPECT_FALSE(optimize_cond(thd, query_block->where_cond_ref(), &cond_equal,
6968 &query_block->m_table_nest,
6969 &query_block->cond_value));
6970 EXPECT_EQ(1, cond_equal->current_level.size());
6971 EXPECT_TRUE(is_function_of_type(query_block->where_cond(),
6972 Item_func::MULT_EQUAL_FUNC));
6973 query_block->join->where_cond = query_block->where_cond();
6974
6975 const size_t mem_root_size_after_resolving = thd->mem_root->allocated_size();
6976
6977 {
6978 // Use a separate MEM_ROOT for the allocations done by the hypergraph
6979 // optimizer, so that this memory can be freed after each iteration without
6980 // interfering with the data structures allocated during resolving above.
6981 MEM_ROOT optimize_mem_root;
6982 Query_arena arena_backup;
6983 Query_arena arena{&optimize_mem_root, Query_arena::STMT_PREPARED};
6984 thd->swap_query_arena(arena, &arena_backup);
6985
6986 StartBenchmarkTiming();
6987
6988 for (size_t i = 0; i < num_iterations; ++i) {
6989 assert(query_block->join->where_cond == query_block->where_cond());
6990 AccessPath *path = FindBestQueryPlan(thd, query_block, /*trace=*/nullptr);
6991 assert(path != nullptr);
6992 assert(path->type == AccessPath::EQ_REF);
6993 query_block->join->set_root_access_path(path);
6994
6995 [[maybe_unused]] const bool error =
6996 FinalizePlanForQueryBlock(thd, query_block);
6997 assert(!error);
6998
6999 query_block->cleanup(/*full=*/false);
7000 query_block->join->set_root_access_path(nullptr);
7001 thd->rollback_item_tree_changes();
7002 cleanup_items(arena.item_list());
7003 arena.free_items();
7004 optimize_mem_root.ClearForReuse();
7005 }
7006
7007 StopBenchmarkTiming();
7008
7009 thd->swap_query_arena(arena_backup, &arena);
7010 }
7011
7012 // Check that all the allocations in FindBestQueryPlan() used
7013 // optimize_mem_root. We don't want the memory footprint to grow for each
7014 // iteration.
7015 EXPECT_EQ(mem_root_size_after_resolving, thd->mem_root->allocated_size());
7016
7017 query_block->cleanup(/*full=*/true);
7018 DestroyFakeTables(fake_tables);
7019 }
7020 BENCHMARK(BM_FindBestQueryPlanPointSelect)