-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathsql_union.cc
1491 lines (1292 loc) · 51.4 KB
/
sql_union.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2001, 2024, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/*
Process query expressions that are composed of
1. UNION of query blocks, and/or
2. have ORDER BY / LIMIT clauses in more than one level.
An example of 2) is:
(SELECT * FROM t1 ORDER BY a LIMIT 10) ORDER BY b LIMIT 5
*/
#include "sql/sql_union.h"
#include <sys/types.h>
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "mem_root_deque.h"
#include "my_alloc.h"
#include "my_base.h"
#include "my_dbug.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "mysql/udf_registration_types.h"
#include "mysqld_error.h"
#include "prealloced_array.h" // Prealloced_array
#include "scope_guard.h"
#include "sql/auth/auth_acls.h"
#include "sql/current_thd.h"
#include "sql/debug_sync.h" // DEBUG_SYNC
#include "sql/field.h"
#include "sql/handler.h"
#include "sql/item.h"
#include "sql/item_subselect.h"
#include "sql/iterators/row_iterator.h"
#include "sql/join_optimizer/access_path.h"
#include "sql/join_optimizer/bit_utils.h"
#include "sql/join_optimizer/explain_access_path.h"
#include "sql/join_optimizer/join_optimizer.h"
#include "sql/join_optimizer/materialize_path_parameters.h"
#include "sql/mem_root_array.h"
#include "sql/mysqld.h"
#include "sql/opt_explain.h"
#include "sql/opt_explain_format.h"
#include "sql/opt_trace.h"
#include "sql/parse_tree_node_base.h"
#include "sql/parse_tree_nodes.h" // PT_with_clause
#include "sql/parser_yystype.h"
#include "sql/pfs_batch_mode.h"
#include "sql/protocol.h"
#include "sql/query_options.h"
#include "sql/query_term.h"
#include "sql/sql_base.h" // fill_record
#include "sql/sql_class.h"
#include "sql/sql_cmd.h"
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_executor.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_optimizer.h" // JOIN
#include "sql/sql_select.h"
#include "sql/sql_tmp_table.h" // tmp tables
#include "sql/table_function.h" // Table_function
#include "sql/thd_raii.h"
#include "sql/visible_fields.h"
#include "sql/window.h" // Window
#include "template_utils.h"
using std::vector;
class Item_rollup_group_item;
class Item_rollup_sum_switcher;
class Opt_trace_context;
bool Query_result_union::prepare(THD *, const mem_root_deque<Item *> &,
Query_expression *u) {
unit = u;
return false;
}
bool Query_result_union::send_data(THD *thd,
const mem_root_deque<Item *> &values) {
if (fill_record(thd, table, table->visible_field_ptr(), values, nullptr,
nullptr, false))
return true; /* purecov: inspected */
if (table->is_union_or_table() && !check_unique_fields(table)) return false;
const int error = table->file->ha_write_row(table->record[0]);
if (!error) {
return false;
}
// create_ondisk_from_heap will generate error if needed
if (!table->file->is_ignorable_error(error)) {
bool is_duplicate;
if (create_ondisk_from_heap(thd, table, error, /*insert_last_record=*/true,
/*ignore_last_dup=*/true, &is_duplicate))
return true; /* purecov: inspected */
// Table's engine changed, index is not initialized anymore
if (table->hash_field) table->file->ha_index_init(0, false);
}
return false;
}
bool Query_result_union::send_eof(THD *) { return false; }
bool Query_result_union::flush() { return false; }
/**
Create a temporary table to store the result of a query expression
(used, among others, when materializing a UNION DISTINCT).
@param thd_arg thread handle
@param column_types a list of items used to define columns of the
temporary table
@param is_union_distinct if set, the temporary table will eliminate
duplicates on insert
@param options create options
@param table_alias name of the temporary table
@param create_table If false, a table handler will not be created when
creating the result table.
@param op If we are creating a result table for a set
operation, op should contain the relevant set
operation's query term. In other cases, op should
be nullptr.
@details
Create a temporary table that is used to store the result of a UNION,
derived table, or a materialized cursor.
@returns false if table created, true if error
*/
bool Query_result_union::create_result_table(
THD *thd_arg, const mem_root_deque<Item *> &column_types,
bool is_union_distinct, ulonglong options, const char *table_alias,
bool create_table, Query_term_set_op *op) {
mem_root_deque<Item *> visible_fields(thd_arg->mem_root);
for (Item *item : VisibleFields(column_types)) {
visible_fields.push_back(item);
}
assert(table == nullptr);
tmp_table_param = Temp_table_param();
count_field_types(thd_arg->lex->current_query_block(), &tmp_table_param,
visible_fields, false, true);
tmp_table_param.skip_create_table = !create_table;
if (unit != nullptr && op == nullptr) {
if (unit->is_recursive()) {
/*
If the UNIQUE key specified for UNION DISTINCT were a primary key in
InnoDB, rows would be returned by the scan in an order depending on
their columns' values, not in insertion order.
*/
tmp_table_param.can_use_pk_for_unique = false;
}
if (!unit->is_simple() && unit->can_materialize_directly_into_result()) {
op = unit->set_operation();
}
}
if (op == nullptr) {
;
} else if (op->term_type() == QT_INTERSECT || op->term_type() == QT_EXCEPT) {
tmp_table_param.m_operation = op->term_type() == QT_INTERSECT
? Temp_table_param::TTP_INTERSECT
: Temp_table_param::TTP_EXCEPT;
// No duplicate rows will exist after the last operation
tmp_table_param.m_last_operation_is_distinct = op->last_distinct() > 0;
assert((op->first_distinct() < std::numeric_limits<int64_t>::max() ||
!tmp_table_param.m_last_operation_is_distinct) &&
(op->first_distinct() <= op->last_distinct() ||
op->first_distinct() == std::numeric_limits<int64_t>::max()));
tmp_table_param.force_hash_field_for_unique = true;
} else if (op->has_mixed_distinct_operators()) {
// If we have mixed UNION DISTINCT / UNION ALL, we can't use an unique
// index to deduplicate, as we need to be able to turn off deduplication
// checking when we get to the UNION ALL part. The handler supports
// turning off indexes (and the pre-iterator executor used this to
// implement mixed DISTINCT/ALL), but not selectively, and we might very
// well need the other indexes when querying against the table.
// (Also, it would be nice to be able to remove this functionality
// altogether from the handler.) Thus, we do it manually instead.
tmp_table_param.force_hash_field_for_unique = true;
}
const bool use_setop_hashing =
op != nullptr &&
(op->term_type() == QT_EXCEPT || op->term_type() == QT_INTERSECT) &&
thd_arg->optimizer_switch_flag(OPTIMIZER_SWITCH_HASH_SET_OPERATIONS);
if (!(table = create_tmp_table(thd_arg, &tmp_table_param, visible_fields,
nullptr, is_union_distinct, true, options,
HA_POS_ERROR, table_alias)))
return true;
if (create_table) {
table->file->ha_extra(HA_EXTRA_IGNORE_DUP_KEY);
if (table->hash_field != nullptr && !use_setop_hashing)
table->file->ha_index_init(0, false);
}
return false;
}
/**
Reset and empty the temporary table that stores the materialized query result.
@note The cleanup performed here is exactly the same as for the two temp
tables of JOIN - exec_tmp_table_[1 | 2].
*/
bool Query_result_union::reset() {
return table ? table->empty_result_table() : false;
}
void Query_result_union::set_limit(ha_rows limit_rows) {
table->m_limit_rows = limit_rows;
}
/**
This class is effectively dead. It was used for non-DISTINCT UNIONs
in the pre-iterator executor. Now it exists only as a shell for certain
setup tasks, and should be removed.
*/
class Query_result_union_direct final : public Query_result_union {
private:
/// Result object that receives all rows
Query_result *result;
/// Wrapped result is optimized
bool optimized;
/// Wrapped result has started execution
bool execution_started;
public:
Query_result_union_direct(Query_result *result, Query_block *last_query_block)
: Query_result_union(),
result(result),
optimized(false),
execution_started(false) {
unit = last_query_block->master_query_expression();
}
bool change_query_result(THD *thd, Query_result *new_result) override;
uint field_count(const mem_root_deque<Item *> &) const override {
// Only called for top-level Query_results, usually Query_result_send
assert(false); /* purecov: inspected */
return 0; /* purecov: inspected */
}
bool postponed_prepare(THD *thd,
const mem_root_deque<Item *> &types) override;
bool send_result_set_metadata(THD *, const mem_root_deque<Item *> &,
uint) override {
// Should never be called.
my_abort();
}
bool send_data(THD *, const mem_root_deque<Item *> &) override {
// Should never be called.
my_abort();
}
bool start_execution(THD *thd) override {
if (execution_started) return false;
execution_started = true;
return result->start_execution(thd);
}
bool send_eof(THD *) override {
// Should never be called.
my_abort();
}
bool flush() override { return false; }
bool check_supports_cursor() const override {
// Only called for top-level Query_results, usually Query_result_send
assert(false); /* purecov: inspected */
return false; /* purecov: inspected */
}
void abort_result_set(THD *thd) override {
result->abort_result_set(thd); /* purecov: inspected */
}
void cleanup() override {}
};
/**
Replace the current query result with new_result and prepare it.
@param thd Thread handle
@param new_result New query result
@returns false if success, true if error
*/
bool Query_result_union_direct::change_query_result(THD *thd,
Query_result *new_result) {
result = new_result;
return result->prepare(thd, *unit->get_unit_column_types(), unit);
}
bool Query_result_union_direct::postponed_prepare(
THD *thd, const mem_root_deque<Item *> &types) {
if (result == nullptr) return false;
return result->prepare(thd, types, unit);
}
bool Query_expression::can_materialize_directly_into_result() const {
// There's no point in doing this if we're not already trying to materialize.
if (!is_set_operation()) {
return false;
}
// We can't materialize directly into the result if we have sorting.
// Otherwise, we're fine.
return global_parameters()->order_list.elements == 0;
}
/**
Prepares all query blocks of a query expression.
If a recursive query expression, this also creates the materialized temporary
table.
@param thd Thread handler
@param sel_result Result object where the unit's output should go.
@param insert_field_list Pointer to field list if INSERT op, NULL otherwise.
@param added_options These options will be added to the query blocks.
@param removed_options Options that cannot be used for this query
@returns false if success, true if error
*/
bool Query_expression::prepare(THD *thd, Query_result *sel_result,
mem_root_deque<Item *> *insert_field_list,
ulonglong added_options,
ulonglong removed_options) {
DBUG_TRACE;
assert(!is_prepared());
Change_current_query_block save_query_block(thd);
set_query_result(sel_result);
thd->lex->set_current_query_block(first_query_block());
if (is_simple()) {
// Only one query block. No extra result needed:
query_term()->query_block()->set_query_result(sel_result);
} else {
set_operation()->set_is_materialized(
query_term()->term_type() != QT_UNION ||
set_operation()->last_distinct() > 0 ||
global_parameters()->order_list.elements > 0 ||
((thd->lex->sql_command == SQLCOM_INSERT_SELECT ||
thd->lex->sql_command == SQLCOM_REPLACE_SELECT) &&
thd->lex->unit == this));
/*
There exists a query block that consolidates the result, so
no need to buffer bottom level query block's result.
*/
added_options &= ~OPTION_BUFFER_RESULT;
}
first_query_block()->context.resolve_in_select_list = true;
ulonglong create_options =
first_query_block()->active_options() | TMP_TABLE_ALL_COLUMNS;
if (query_term()->prepare_query_term(thd, this, &save_query_block,
insert_field_list,
/*common_result*/ nullptr, added_options,
removed_options, create_options))
return true;
if (is_recursive()) {
// This had to wait until all query blocks are prepared:
if (check_materialized_derived_query_blocks(thd))
return true; /* purecov: inspected */
}
// Query blocks are prepared, update the state
set_prepared();
return false;
}
/// Finalizes the initialization of all the full-text functions used in the
/// given query expression, and recursively in every query expression inner to
/// the given one. We do this fairly late, since we need to know whether or not
/// the full-text function is to be used for a full-text index scan, and whether
/// or not that scan is sorted. When the iterators have been created, we know
/// that the final decision has been made, so we do it right after the iterators
/// have been created.
static bool finalize_full_text_functions(THD *thd,
Query_expression *query_expression) {
assert(thd->lex->using_hypergraph_optimizer());
for (Query_expression *qe = query_expression; qe != nullptr;
qe = qe->next_query_expression()) {
for (Query_block *qb = qe->first_query_block(); qb != nullptr;
qb = qb->next_query_block()) {
if (qb->has_ft_funcs()) {
if (init_ftfuncs(thd, qb)) {
return true;
}
}
if (finalize_full_text_functions(thd,
qb->first_inner_query_expression())) {
return true;
}
}
}
return false;
}
/**
Determine if we should set or add the contribution of the given query block to
the total row count estimate for the query expression.
If we have INTERSECT or EXCEPT, only set row estimate for left side since
the total number of rows in the result set can only decrease as a result
of the set operation.
@param qb query block
@return true if the estimate should be added
*/
static bool contributes_to_rowcount_estimate(Query_block *qb) {
if (qb->parent() == nullptr) return true;
// When parent isn't nullptr, we know this is a leaf block.
Query_term *query_term = qb;
// See if this query block is contained in a right side of an INTERSECT
// or EXCEPT operation anywhere in tree. If so, we can ignore its count.
Query_term_set_op *parent = query_term->parent();
while (parent != nullptr) {
if (parent->in_right_side_in_except_or_intersect(query_term)) return false;
// Even if we are on the left side of an INTERSECT, EXCEPT, the set
// operation itself could still be in a non-contributing side higher up, so
// continue checking.
query_term = parent;
parent = parent->parent();
}
return true;
}
static bool use_iterator(TABLE *materialize_destination,
Query_term *query_term) {
if (materialize_destination == nullptr) return false;
switch (query_term->term_type()) {
case QT_INTERSECT:
case QT_EXCEPT:
// In corner cases for transform of scalar subquery, it can happen
// that the destination table isn't ready for INTERSECT or EXCEPT, so
// force double materialization.
// FIXME: find out if we can remove this exception.
return materialize_destination->is_union_or_table();
default:;
}
return false;
}
bool Query_expression::optimize(THD *thd, TABLE *materialize_destination,
bool finalize_access_paths) {
DBUG_TRACE;
assert(is_prepared() && !is_optimized());
Change_current_query_block save_query_block(thd);
ha_rows estimated_rowcount = 0;
double estimated_cost = 0.0;
if (query_result() != nullptr) query_result()->estimated_rowcount = 0;
for (Query_block *query_block = first_query_block(); query_block != nullptr;
query_block = query_block->next_query_block()) {
thd->lex->set_current_query_block(query_block);
// LIMIT is required for optimization
if (set_limit(thd, query_block)) return true; /* purecov: inspected */
if (query_block->optimize(thd, finalize_access_paths)) return true;
/*
Accumulate estimated number of rows.
1. Implicitly grouped query has one row (with HAVING it has zero or one
rows).
2. If GROUP BY clause is optimized away because it was a constant then
query produces at most one row.
*/
if (contributes_to_rowcount_estimate(query_block))
estimated_rowcount += (query_block->is_implicitly_grouped() ||
query_block->join->group_optimized_away)
? 1
: query_block->join->best_rowcount;
estimated_cost += query_block->join->best_read;
// Table_ref::fetch_number_of_rows() expects to get the number of rows
// from all earlier query blocks from the query result, so we need to update
// it as we go. In particular, this is used when optimizing a recursive
// SELECT in a CTE, so that it knows how many rows the non-recursive query
// blocks will produce.
//
// TODO(sgunders): Communicate this in a different way when the query result
// goes away.
if (query_result() != nullptr) {
query_result()->estimated_rowcount = estimated_rowcount;
query_result()->estimated_cost = estimated_cost;
}
}
if (!is_simple() && query_term()->open_result_tables(thd, 0)) return true;
if ((uncacheable & UNCACHEABLE_DEPENDENT) && estimated_rowcount <= 1) {
/*
This depends on outer references, so optimization cannot assume that all
executions will always produce the same row. So, increase the counter to
prevent that this table is replaced with a constant.
Not testing all bits of "uncacheable", as if derived table sets user
vars (UNCACHEABLE_SIDEEFFECT) the logic above doesn't apply.
*/
estimated_rowcount = PLACEHOLDER_TABLE_ROW_ESTIMATE;
}
if (!is_simple()) {
if (query_term()->optimize_query_term(thd, this)) return true;
if (set_limit(thd, query_term()->query_block())) return true;
if (!is_union()) query_result()->set_limit(select_limit_cnt);
}
query_result()->estimated_rowcount = estimated_rowcount;
query_result()->estimated_cost = estimated_cost;
// If the caller has asked for materialization directly into a table of its
// own, and we can do so, do an unfinished materialization (see the comment
// on this function for more details).
if (thd->lex->m_sql_cmd != nullptr &&
thd->lex->m_sql_cmd->using_secondary_storage_engine()) {
// Not supported when using secondary storage engine.
create_access_paths(thd);
} else if (estimated_rowcount <= 1 ||
use_iterator(materialize_destination, query_term())) {
// Don't do it for const tables, as for those, optimize_derived() wants to
// run the query during optimization, and thus needs an iterator.
//
// Do note that JOIN::extract_func_dependent_tables() can want to read from
// the derived table during the optimization phase even if it has
// estimated_rowcount larger than one (e.g., because it understands it can
// get only one row due to a unique index), but will detect that the table
// has not been created, and treat the the lookup as non-const.
create_access_paths(thd);
} else if (materialize_destination != nullptr &&
can_materialize_directly_into_result()) {
assert(!is_simple());
const bool calc_found_rows =
(first_query_block()->active_options() & OPTION_FOUND_ROWS);
m_operands = set_operation()->setup_materialize_set_op(
thd, materialize_destination,
/*union_distinct_only=*/false, calc_found_rows);
} else {
// Recursive CTEs expect to see the rows in the result table immediately
// after writing them.
assert(!is_recursive());
create_access_paths(thd);
}
set_optimized(); // All query blocks optimized, update the state
if (item != nullptr) {
// If we're part of an IN subquery, the containing engine may want to
// add its own iterators on top, e.g. to materialize us.
//
// TODO(sgunders): See if we can do away with the engine concept
// altogether, now that there's much less execution logic in them.
assert(!unfinished_materialization());
item->create_iterators(thd);
if (m_root_access_path == nullptr) {
return false;
}
}
// When done with the outermost query expression, and if max_join_size is in
// effect, estimate the total number of row accesses in the query, and error
// out if it exceeds max_join_size.
if (outer_query_block() == nullptr &&
!Overlaps(thd->variables.option_bits, OPTION_BIG_SELECTS) &&
!thd->lex->is_explain() &&
EstimateRowAccesses(m_root_access_path, /*num_evaluations=*/1.0,
std::numeric_limits<double>::infinity()) >
static_cast<double>(thd->variables.max_join_size)) {
my_error(ER_TOO_BIG_SELECT, MYF(0));
return true;
}
return false;
}
bool Query_expression::finalize(THD *thd) {
for (Query_block *query_block = first_query_block(); query_block != nullptr;
query_block = query_block->next_query_block()) {
if (query_block->join != nullptr && query_block->join->needs_finalize) {
if (FinalizePlanForQueryBlock(thd, query_block)) {
return true;
}
}
}
return false;
}
bool Query_expression::force_create_iterators(THD *thd) {
assert(IteratorsAreNeeded(thd, m_root_access_path));
if (m_root_iterator == nullptr) {
return create_iterators(thd);
}
return false;
}
bool Query_expression::create_iterators(THD *thd) {
assert(m_root_iterator == nullptr);
if (!IteratorsAreNeeded(thd, m_root_access_path)) {
return false;
}
JOIN *const top_join = query_term()->query_block()->join;
m_root_iterator =
CreateIteratorFromAccessPath(thd, m_root_access_path, top_join,
/*eligible_for_batch_mode=*/true);
if (m_root_iterator == nullptr) return true;
if (thd->lex->using_hypergraph_optimizer()) {
if (finalize_full_text_functions(thd, this)) {
return true;
}
}
return false;
}
#ifndef NDEBUG
void Query_expression::DebugPrintQueryPlan(THD *thd,
const char *keyword) const {
DBUG_PRINT(keyword, ("\n%s", thd->query().str));
if (m_query_term != nullptr) {
std::ostringstream buf;
m_query_term->debugPrint(0, buf);
DBUG_PRINT(keyword, ("\n%s", buf.str().c_str()));
}
JOIN *const join = query_term()->query_block()->join;
const bool is_root_of_join = join != nullptr;
DBUG_PRINT(
keyword,
("Query plan:\n%s\n",
PrintQueryPlan(0, m_root_access_path, join, is_root_of_join).c_str()));
}
#endif
/**
Make materialization parameters for a query block given its input path
and destination table,
@param child_path the input access path
@param dst_table the table to materialize into
@returns materialization parameter
*/
MaterializePathParameters::Operand Query_block::setup_materialize_query_block(
AccessPath *child_path, TABLE *dst_table) const {
ConvertItemsToCopy(*join->fields, dst_table->visible_field_ptr(),
&join->tmp_table_param);
MaterializePathParameters::Operand operand;
operand.subquery_path = child_path;
operand.select_number = select_number;
operand.join = join;
operand.disable_deduplication_by_hash_field = false;
operand.copy_items = true;
operand.temp_table_param = &join->tmp_table_param;
operand.is_recursive_reference = recursive_reference != nullptr;
return operand;
}
/**
Sets up each(*) query block in this query expression for materialization
into the given table by making a materialization parameter for each block
(*) modulo union_distinct_only.
@param thd session context
@param dst_table the table to materialize into
@param union_distinct_only
if true, materialize only UNION DISTINCT query blocks
(any UNION ALL blocks are presumed handled higher up, by AppendIterator)
@param calc_found_rows
if true, calculate rows found
@returns array of materialization parameters
*/
Mem_root_array<MaterializePathParameters::Operand>
Query_term_set_op::setup_materialize_set_op(THD *thd, TABLE *dst_table,
bool union_distinct_only,
bool calc_found_rows) {
Mem_root_array<MaterializePathParameters::Operand> operands(thd->mem_root);
int64 idx = -1;
for (Query_term *term : m_children) {
++idx;
bool activate_deduplication =
idx <= m_last_distinct ||
term_type() != QT_UNION; /* always for INTERSECT and EXCEPT */
JOIN *join = term->query_block()->join;
AccessPath *child_path = join->root_access_path();
assert(join->is_optimized() && child_path != nullptr);
if (term->term_type() != QT_QUERY_BLOCK)
child_path =
term->make_set_op_access_path(thd, nullptr, nullptr, calc_found_rows);
MaterializePathParameters::Operand param =
term->query_block()->setup_materialize_query_block(child_path,
dst_table);
param.m_first_distinct = m_first_distinct;
param.m_operand_idx = idx;
param.m_total_operands = m_children.size();
param.disable_deduplication_by_hash_field =
(has_mixed_distinct_operators() && !activate_deduplication);
operands.push_back(param);
if (idx == m_last_distinct && idx > 0 && union_distinct_only)
// The rest will be done by appending.
break;
}
return operands;
}
void Query_expression::create_access_paths(THD *thd) {
if (is_simple()) {
JOIN *join = first_query_block()->join;
assert(join && join->is_optimized());
m_root_access_path = join->root_access_path();
return;
}
// Decide whether we can stream rows, ie., never actually put them into the
// temporary table. If we can, we materialize the UNION DISTINCT blocks first,
// and then stream the remaining UNION ALL blocks (if any) by means of
// AppendIterator.
//
// If we cannot stream (ie., everything has to go into the temporary table),
// our strategy for mixed UNION ALL/DISTINCT becomes a bit different;
// see MaterializeIterator for details.
bool streaming_allowed = true;
if (global_parameters()->order_list.size() != 0 ||
(!is_simple() && set_operation()->is_materialized())) {
// If we're sorting, we currently put it in a real table no matter what.
// This is a legacy decision, because we used to not know whether filesort
// would want to refer to rows in the table after the sort (sort by row ID).
// We could probably be more intelligent here now.
streaming_allowed = false;
} else if ((thd->lex->sql_command == SQLCOM_INSERT_SELECT ||
thd->lex->sql_command == SQLCOM_REPLACE_SELECT) &&
thd->lex->unit == this) {
// If we're doing an INSERT or REPLACE, and we're not outputting to
// a temporary table already (ie., we are the topmost unit), then we
// don't want to insert any records before we're done scanning. Otherwise,
// we would risk incorrect results and/or infinite loops, as we'd be seeing
// our own records as they get inserted.
//
// @todo Figure out if we can check for OPTION_BUFFER_RESULT instead;
// see bug #23022426.
streaming_allowed = false;
}
ha_rows offset = global_parameters()->get_offset(thd);
ha_rows limit = global_parameters()->get_limit(thd);
if (limit + offset >= limit)
limit += offset;
else
limit = HA_POS_ERROR; /* purecov: inspected */
const bool calc_found_rows =
(first_query_block()->active_options() & OPTION_FOUND_ROWS);
Mem_root_array<AppendPathParameters> *union_all_sub_paths =
new (thd->mem_root) Mem_root_array<AppendPathParameters>(thd->mem_root);
// If streaming is allowed, we can do all the parts that are UNION ALL by
// streaming; the rest have to go to the table.
//
// Handle the query blocks that we need to materialize. This may be
// UNION DISTINCT query blocks only, or all blocks.
if (!streaming_allowed || !is_simple()) {
AppendPathParameters param;
param.path = m_query_term->make_set_op_access_path(
thd, /*parent*/ nullptr,
streaming_allowed ? union_all_sub_paths : nullptr, calc_found_rows);
param.join = nullptr;
if (!streaming_allowed) union_all_sub_paths->push_back(param);
// else filled in by make_set_op_access_path
}
assert(!union_all_sub_paths->empty());
if (union_all_sub_paths->size() == 1) {
m_root_access_path = (*union_all_sub_paths)[0].path;
} else {
// Just append all the UNION ALL sub-blocks.
assert(streaming_allowed);
m_root_access_path = NewAppendAccessPath(thd, union_all_sub_paths);
}
// NOTE: If there's a fake_query_block, its JOIN's iterator already handles
// LIMIT/OFFSET, so we don't do it again here.
if (streaming_allowed && (limit != HA_POS_ERROR || offset != 0) &&
(is_simple() || set_operation()->last_distinct() == 0)) {
m_root_access_path = NewLimitOffsetAccessPath(
thd, m_root_access_path, limit, offset, calc_found_rows,
/*reject_multiple_rows=*/false, &send_records);
}
}
bool Query_expression::explain_query_term(THD *explain_thd,
const THD *query_thd,
Query_term *qt) {
Explain_format *fmt = explain_thd->lex->explain_format;
switch (qt->term_type()) {
case QT_QUERY_BLOCK:
if (fmt->begin_context(CTX_QUERY_SPEC)) return true;
if (explain_query_specification(explain_thd, query_thd, qt, CTX_JOIN))
return true;
if (fmt->end_context(CTX_QUERY_SPEC)) return true;
break;
case QT_UNION: {
if (fmt->begin_context(CTX_UNION)) return true;
Query_term_set_op *const qts = down_cast<Query_term_set_op *>(qt);
for (size_t idx = 0; idx < qts->child_count(); ++idx) {
if (explain_query_term(explain_thd, query_thd, qts->child(idx)))
return true;
}
if (down_cast<Query_term_union *>(qt)->is_materialized() &&
explain_query_specification(explain_thd, query_thd, qt,
CTX_UNION_RESULT))
return true;
if (fmt->end_context(CTX_UNION)) return true;
} break;
case QT_INTERSECT: {
if (fmt->begin_context(CTX_INTERSECT)) return true;
Query_term_set_op *const qts = down_cast<Query_term_set_op *>(qt);
for (size_t idx = 0; idx < qts->child_count(); ++idx) {
if (explain_query_term(explain_thd, query_thd, qts->child(idx)))
return true;
}
if (explain_query_specification(explain_thd, query_thd, qt,
CTX_INTERSECT_RESULT))
return true;
if (fmt->end_context(CTX_INTERSECT)) return true;
} break;
case QT_EXCEPT: {
if (fmt->begin_context(CTX_EXCEPT)) return true;
Query_term_set_op *const qts = down_cast<Query_term_set_op *>(qt);
for (size_t idx = 0; idx < qts->child_count(); ++idx) {
if (explain_query_term(explain_thd, query_thd, qts->child(idx)))
return true;
}
if (explain_query_specification(explain_thd, query_thd, qt,
CTX_EXCEPT_RESULT))
return true;
if (fmt->end_context(CTX_EXCEPT)) return true;
} break;
case QT_UNARY: {
if (fmt->begin_context(CTX_UNARY)) return true;
Query_term_set_op *const qts = down_cast<Query_term_set_op *>(qt);
if (explain_query_term(explain_thd, query_thd, qts->child(0)))
return true;
if (explain_query_specification(explain_thd, query_thd, qt,
CTX_UNARY_RESULT))
return true;
if (fmt->end_context(CTX_UNARY)) return true;
} break;
}
return false;
}
/**
Explain query starting from this unit.
@param explain_thd thread handle for the connection doing explain
@param query_thd thread handle for the connection being explained
@return false if success, true if error
*/
bool Query_expression::explain(THD *explain_thd, const THD *query_thd) {
DBUG_TRACE;
#ifndef NDEBUG
Query_block *lex_select_save = query_thd->lex->current_query_block();
#endif
const bool other = (query_thd != explain_thd);
assert(other || is_optimized() || outer_query_block()->is_empty_query() ||
// @todo why is this necessary?
outer_query_block()->join == nullptr ||
outer_query_block()->join->zero_result_cause);
if (explain_query_term(explain_thd, query_thd, query_term())) return true;
if (!other)
assert(current_thd->lex->current_query_block() == lex_select_save);
return false;
}
bool Common_table_expr::clear_all_references() {
bool reset_tables = false;
for (Table_ref *tl : references) {
if (tl->table &&
tl->derived_query_expression()->uncacheable & UNCACHEABLE_DEPENDENT) {
reset_tables = true;
if (tl->derived_query_expression()->query_result()->reset()) return true;
}
/*
This loop has found all non-recursive clones; one writer and N
readers.
*/
}
if (!reset_tables) return false;
for (Table_ref *tl : tmp_tables) {
if (tl->is_derived()) continue; // handled above
if (tl->table->empty_result_table()) return true;
// This loop has found all recursive clones (only readers).
}
/*
Above, emptying all clones is necessary, to rewind every handler (cursor)
to the table's start. Setting materialized=false on all is also important
or the writer would skip materialization, see loop at start of
Table_ref::materialize_derived()). There is one "recursive table"
which we don't find here: it's the UNION DISTINCT tmp table. It's reset in
unit::execute() of the unit which is the body of the CTE.
*/
return false;
}
/**
Empties all correlated query blocks defined within the query expression;
that is, correlated CTEs defined in the expression's WITH clause, and
correlated derived tables.
*/
bool Query_expression::clear_correlated_query_blocks() {
for (Query_block *sl = first_query_block(); sl; sl = sl->next_query_block()) {
sl->join->clear_corr_derived_tmp_tables();
sl->join->clear_sj_tmp_tables();
sl->join->clear_hash_tables();
}
if (!m_with_clause) return false;
for (auto el : m_with_clause->m_list->elements()) {
Common_table_expr &cte = el->m_postparse;
if (cte.clear_all_references()) return true;
}
return false;
}
bool Query_expression::ClearForExecution() {
if (is_executed()) {
if (clear_correlated_query_blocks()) return true;
// TODO(sgunders): Most of JOIN::reset() should be done in iterators.
for (auto qt : query_terms<QTC_POST_ORDER>()) {
if (qt->term_type() == QT_QUERY_BLOCK ||
down_cast<Query_term_set_op *>(qt)->is_materialized()) {
Query_block *sl = qt->query_block();
if (sl->join->is_executed()) {
sl->join->reset();
}
}
}
}
for (Query_block *query_block = first_query_block(); query_block;