-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathitem_subselect.cc
3800 lines (3309 loc) · 136 KB
/
item_subselect.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) 2002, 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 */
/**
@file
@brief
Implements the subselect Item, used when there is a subselect in a
SELECT list, WHERE, etc.
*/
#include "sql/item_subselect.h"
#include <climits>
#include <cstdio>
#include <cstring>
#include <initializer_list>
#include <memory>
#include <string>
#include <utility>
#include "decimal.h"
#include "lex_string.h"
#include "my_alloc.h"
#include "my_base.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_pointer_arithmetic.h"
#include "my_sys.h"
#include "mysql/strings/m_ctype.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "scope_guard.h"
#include "sql-common/my_decimal.h"
#include "sql/check_stack.h"
#include "sql/current_thd.h" // current_thd
#include "sql/debug_sync.h" // DEBUG_SYNC
#include "sql/derror.h" // ER_THD
#include "sql/field.h"
#include "sql/handler.h"
#include "sql/item_cmpfunc.h"
#include "sql/item_func.h"
#include "sql/item_sum.h" // Item_sum_max
#include "sql/iterators/basic_row_iterators.h" // ZeroRowsIterator
#include "sql/iterators/composite_iterators.h" // FilterIterator
#include "sql/iterators/ref_row_iterators.h"
#include "sql/iterators/row_iterator.h" // RowIterator
#include "sql/iterators/timing_iterator.h"
#include "sql/join_optimizer/access_path.h"
#include "sql/join_optimizer/cost_model.h"
#include "sql/join_optimizer/join_optimizer.h"
#include "sql/key.h"
#include "sql/mysqld.h" // in_left_expr_name
#include "sql/opt_explain_format.h"
#include "sql/opt_trace.h" // OPT_TRACE_TRANSFORM
#include "sql/opt_trace_context.h"
#include "sql/parse_tree_nodes.h" // PT_subquery
#include "sql/query_options.h"
#include "sql/query_result.h"
#include "sql/sql_class.h" // THD
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_executor.h"
#include "sql/sql_lex.h" // Query_block
#include "sql/sql_list.h"
#include "sql/sql_opt_exec_shared.h"
#include "sql/sql_optimizer.h" // JOIN
#include "sql/sql_select.h"
#include "sql/sql_test.h" // print_where
#include "sql/sql_tmp_table.h" // free_tmp_table
#include "sql/sql_union.h" // Query_result_union
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/temp_table_param.h"
#include "sql/thd_raii.h"
#include "sql/window.h"
#include "sql_string.h"
#include "string_with_len.h"
#include "template_utils.h"
class Json_wrapper;
static const enum_walk walk_options =
enum_walk::PREFIX | enum_walk::POSTFIX | enum_walk::SUBQUERY;
/// Query result class for scalar and row subqueries
class Query_result_scalar_subquery : public Query_result_subquery {
public:
explicit Query_result_scalar_subquery(Item_subselect *item_arg)
: Query_result_subquery(item_arg) {}
bool send_data(THD *thd, const mem_root_deque<Item *> &items) override;
};
/**
Check if a query block is guaranteed to return one row. We know that
this is the case if it has no tables and is not filtered with WHERE,
HAVING, QUALIFY or LIMIT/OFFSET clauses. Also, it should not use non-primitive
grouping (such as ROLLUP), as that may increase the number of rows.
@param qb the Query_block to check
@returns true if we are certain that the query block always returns
one row, false otherwise
*/
static bool guaranteed_one_row(const Query_block *qb) {
return !qb->has_tables() && qb->where_cond() == nullptr &&
qb->having_cond() == nullptr && qb->qualify_cond() == nullptr &&
qb->olap == UNSPECIFIED_OLAP_TYPE &&
qb->limit_offset_preserves_first_row();
}
/**
Check if a query block is part of an INTERSECT or EXCEPT set operation.
@param qb Query block to check
@returns true if query block is part of INTERSECT/EXCEPT, false otherwise.
*/
static bool wrapped_in_intersect_except(Query_term *qb) {
for (qb = qb->parent(); qb != nullptr; qb = qb->parent()) {
if (qb->term_type() == QT_EXCEPT || qb->term_type() == QT_INTERSECT)
return true;
}
return false;
}
void Item_subselect::bind(Query_expression *qe) {
m_query_expr = qe;
Query_block *outer = query_expr()->outer_query_block();
if (m_query_expr->item != nullptr) {
m_parsing_place = m_query_expr->item->m_parsing_place;
} else {
m_parsing_place = outer->parsing_place;
}
m_query_expr->item = this;
if (outer->parsing_place == CTX_HAVING) outer->subquery_in_having = true;
}
/**
Accumulate missing used_tables information from embedded query expression
into the subquery.
This function relies on a few other functions to accumulate information:
accumulate_expression(), accumulate_condition().
Currently, the only property that is accumulated is INNER_TABLE_BIT.
Information about local tables and outer references are accumulated in
mark_as_dependent() (@see item.cc).
RAND_TABLE_BIT is currently not accumulated (but uncacheable is used instead).
@todo - maybe_null is not set properly for all types of subqueries and
expressions. Use this sketch as a guideline for further handling:
- When constructing an Item_subselect, maybe_null is false and null_value
is true. This is obviously wrong.
- When constructing an Item_in_subselect (subclass of Item_subselect),
maybe_null is set true and null_value is set false.
We should probably keep both maybe_null and null_value as false in
the constructor. Then, set maybe_null during preparation, according to
type of subquery:
- Scalar subquery is nullable when query block may have an empty result (not
DUAL or implicitly grouped).
- Scalar subquery is nullable when one of the selected expressions
are nullable.
- Scalar subquery is nullable when WHERE clause or HAVING clause is non-empty
and not always true.
- EXISTS subquery is never nullable!
- IN subquery nullability ignores subquery cardinality.
- IN subquery is nullable when one of the selected expressions are nullable.
- UNIONed query blocks may cancel out nullability.
*/
void Item_subselect::accumulate_properties() {
for (Query_block *qb = m_query_expr->first_query_block(); qb != nullptr;
qb = qb->next_query_block())
accumulate_properties(qb);
for (auto qt : query_expr()->query_terms<QTC_POST_ORDER, VL_SKIP_LEAVES>()) {
/*
qt->query_block() may only contain components with special table
dependencies in the ORDER BY clause, so inspect these expressions only.
(The SELECT list may contain table references that are valid only in
a local scope - references to the UNION temporary table - and should
not be propagated to the subquery level.)
*/
for (ORDER *order = qt->query_block()->order_list.first; order != nullptr;
order = order->next)
accumulate_condition(*order->item);
}
// Save used tables information for the subquery only
m_used_tables_cache |= m_subquery_used_tables;
}
/**
Accumulate missing used_tables information for a query block.
@param select Reference to query block
*/
void Item_subselect::accumulate_properties(Query_block *select) {
for (Item *item : select->visible_fields()) {
accumulate_expression(item);
}
if (select->where_cond()) accumulate_condition(select->where_cond());
if (select->m_current_table_nest)
walk_join_list(*select->m_current_table_nest,
[this](Table_ref *tr) -> bool {
if (tr->join_cond()) accumulate_condition(tr->join_cond());
return false;
});
for (ORDER *group = select->group_list.first; group; group = group->next)
accumulate_condition(*group->item);
if (select->having_cond()) accumulate_condition(select->having_cond());
for (ORDER *order = select->order_list.first; order; order = order->next)
accumulate_expression(*order->item);
if (select->has_tables()) m_subquery_used_tables |= INNER_TABLE_BIT;
List_iterator<Window> wi(select->m_windows);
Window *w;
while ((w = wi++)) {
for (ORDER *wp = w->first_partition_by(); wp != nullptr; wp = wp->next)
accumulate_expression(*wp->item);
for (ORDER *wo = w->first_order_by(); wo != nullptr; wo = wo->next)
accumulate_expression(*wo->item);
}
}
/**
Accumulate used_tables information for an expression from a query block.
@param item Reference to expression.
*/
void Item_subselect::accumulate_expression(Item *item) {
if (item->used_tables() & ~OUTER_REF_TABLE_BIT)
m_subquery_used_tables |= INNER_TABLE_BIT;
set_nullable(is_nullable() || item->is_nullable());
}
/**
Accumulate used_tables information for a condition from a query block.
@param item Reference to condition.
*/
void Item_subselect::accumulate_condition(Item *item) {
if (item->used_tables() & ~OUTER_REF_TABLE_BIT)
m_subquery_used_tables |= INNER_TABLE_BIT;
}
void Item_subselect::create_iterators(THD *thd) {
if (indexsubquery_engine != nullptr) {
indexsubquery_engine->create_iterators(thd);
}
}
Item_subselect::enum_engine_type Item_subselect::engine_type() const {
if (indexsubquery_engine != nullptr) {
switch (indexsubquery_engine->engine_type()) {
case subselect_indexsubquery_engine::INDEXSUBQUERY_ENGINE:
return Item_subselect::INDEXSUBQUERY_ENGINE;
case subselect_indexsubquery_engine::HASH_SJ_ENGINE:
return Item_subselect::HASH_SJ_ENGINE;
default:
assert(false);
}
}
return Item_subselect::OTHER_ENGINE;
}
const TABLE *Item_subselect::get_table() const {
return down_cast<subselect_hash_sj_engine *>(indexsubquery_engine)
->get_table();
}
const Index_lookup &Item_subselect::index_lookup() const {
return down_cast<subselect_hash_sj_engine *>(indexsubquery_engine)
->index_lookup();
}
join_type Item_subselect::get_join_type() const {
return down_cast<subselect_hash_sj_engine *>(indexsubquery_engine)
->get_join_type();
}
void Item_subselect::cleanup() {
Item_result_field::cleanup();
if (m_query_result != nullptr) m_query_result->cleanup();
if (indexsubquery_engine != nullptr) {
indexsubquery_engine->cleanup();
::destroy_at(indexsubquery_engine);
indexsubquery_engine = nullptr;
}
reset();
m_value_assigned = false;
m_traced_before = false;
in_cond_of_tab = NO_PLAN_IDX;
}
bool Item_singlerow_subselect::fix_fields(THD *thd, Item **ref) {
assert(!fixed);
m_query_result = new (thd->mem_root) Query_result_scalar_subquery(this);
if (m_query_result == nullptr) return true;
if (Item_subselect::fix_fields(thd, ref)) return true;
Query_block *inner = query_expr()->first_query_block();
Query_block *outer = inner->outer_query_block();
Item *single_field = inner->single_visible_field();
if (single_field != nullptr &&
single_field->type() == Item::VALUES_COLUMN_ITEM && !is_maxmin()) {
/*
A subquery that is a VALUES clause can be used as a scalar subquery.
But VALUES clauses with a single row are transformed to their simple
components and will not be shown as VALUES_COLUMN_ITEM here.
*/
assert(inner->row_value_list->size() > 1);
/*
Since scalar subqueries can have at most one row, reject VALUES
clauses (with more than one row) immediately.
But note (see condition above) that this does not apply for the
internally generated max-min subquery type.
*/
my_error(ER_SUBQUERY_NO_1_ROW, MYF(0));
return true;
}
fixed = true;
if (thd->lex->is_view_context_analysis()) return false;
// A subquery containing a simple selected expression can be eliminated
if (!query_expr()->is_set_operation() && guaranteed_one_row(inner) &&
single_field != nullptr && !single_field->has_aggregation() &&
!single_field->has_wf() && !is_maxmin()) {
if (thd->lex->is_explain()) {
char warn_buff[MYSQL_ERRMSG_SIZE];
sprintf(warn_buff, ER_THD(thd, ER_SELECT_REDUCED), inner->select_number);
push_warning(thd, Sql_condition::SL_NOTE, ER_SELECT_REDUCED, warn_buff);
}
// Allow field to be used for name lookup in this query block
if (item_name.is_set()) {
single_field->item_name = item_name;
}
if (single_field->type() == SUBQUERY_ITEM) {
Item_subselect *subs = down_cast<Item_subselect *>(single_field);
subs->query_expr()->set_explain_marker_from(thd, query_expr());
}
// Unlink the subquery's query expression:
query_expr()->exclude_level();
// Merge subquery's name resolution contexts into parent's
outer->merge_contexts(inner);
// Fix query block contexts after merging the subquery
single_field->fix_after_pullout(outer, inner);
*ref = single_field;
}
return false;
}
void Item_singlerow_subselect::cleanup() {
DBUG_TRACE;
Item_subselect::cleanup();
}
/**
Decide whether to mark the injected left expression "outer" relative to
the subquery. It should be marked as outer in the following cases:
1) If the left expression is not constant.
2) If the left expression could be a constant NULL and we care about the
difference between UNKNOWN and FALSE. In this case, JOIN::optimize() for
the subquery must be prevented from evaluating any triggered condition, as
the triggers for such conditions have not yet been properly set by
Item_in_optimizer::val_int(). By marking the left expression as outer, a
triggered condition using it will not be considered constant, will not be
evaluated by JOIN::optimize(); it will only be evaluated by JOIN::exec()
which is called from Item_in_optimizer::val_int()
3) If the left expression comes from a subquery and is not a basic
constant. In this case, the value cannot be read until after the subquery
has been evaluated. By marking it as outer, we prevent it from being read
when JOIN::optimize() attempts to evaluate constant conditions.
@param[in] left_row The item that represents the left operand of the IN
operator
@param[in] col The column number of the expression in the left operand
to possibly mark as dependent of the outer select
@returns true if we should mark the injected left expression "outer"
relative to the subquery
*/
bool Item_in_subselect::mark_as_outer(Item *left_row, size_t col) {
const Item *left_col = left_row->element_index(col);
return !left_col->const_item() ||
(!abort_on_null && left_col->is_nullable()) ||
(left_row->type() == SUBQUERY_ITEM && !left_col->basic_const_item());
}
bool Item_in_subselect::finalize_exists_transform(THD *thd,
Query_block *query_block) {
assert(strategy == Subquery_strategy::CANDIDATE_FOR_IN2EXISTS_OR_MAT ||
strategy == Subquery_strategy::SUBQ_EXISTS);
/*
Note that if the subquery is "SELECT1 UNION SELECT2" then this is not
working optimally (Bug#14215895).
*/
if (!(query_expr()->global_parameters()->select_limit = new Item_int(1))) {
return true;
}
query_expr()->global_parameters()->m_internal_limit = true;
if (query_expr()->set_limit(thd, query_expr()->global_parameters()))
return true; /* purecov: inspected */
if (query_expr()->finalize(thd)) {
return true;
}
query_block->join->allow_outer_refs = true; // for JOIN::set_prefix_tables()
strategy = Subquery_strategy::SUBQ_EXISTS;
return false;
}
Item *remove_in2exists_conds(Item *conds) {
bool modified = false;
List<Item> new_conds;
if (WalkConjunction(conds, [&modified, &new_conds](Item *cond) {
if (cond->created_by_in2exists()) {
modified = true;
return false;
} else {
return new_conds.push_back(cond);
}
})) {
return nullptr;
}
return modified ? CreateConjunction(&new_conds) : conds;
}
bool Item_in_subselect::finalize_materialization_transform(THD *thd,
JOIN *join) {
assert(strategy == Subquery_strategy::CANDIDATE_FOR_IN2EXISTS_OR_MAT);
assert(query_expr()->is_simple());
assert(join == query_expr()->first_query_block()->join);
// No UNION in materialized subquery so this holds:
assert(join->query_block == query_expr()->first_query_block());
assert(join->query_expression() == query_expr());
assert(query_expr()->global_parameters()->select_limit == nullptr);
strategy = Subquery_strategy::SUBQ_MATERIALIZATION;
// We need to undo several changes which IN->EXISTS had done:
/*
The conditions added by in2exists depend on the concrete value from the
outer query block, so they need to be removed before we materialize.
*/
// This part is not relevant for the hypergraph optimizer.
if (join->where_cond)
join->where_cond = remove_in2exists_conds(join->where_cond);
if (join->having_cond)
join->having_cond = remove_in2exists_conds(join->having_cond);
// This part is only relevant for the hypergraph optimizer.
query_expr()->change_to_access_path_without_in2exists(thd);
assert(!m_in2exists_info->dependent_before);
if (query_expr()->finalize(thd)) {
return true;
}
join->query_block->uncacheable &= ~UNCACHEABLE_DEPENDENT;
query_expr()->uncacheable &= ~UNCACHEABLE_DEPENDENT;
OPT_TRACE_TRANSFORM(&thd->opt_trace, oto0, oto1,
query_expr()->first_query_block()->select_number,
"IN (SELECT)", "materialization");
oto1.add("chosen", true);
subselect_hash_sj_engine *const new_engine =
new (thd->mem_root) subselect_hash_sj_engine(this, query_expr());
if (!new_engine) return true;
if (new_engine->setup(thd, *query_expr()->get_unit_column_types())) {
/*
For some reason we cannot use materialization for this IN predicate.
Delete all materialization-related objects, and return error.
*/
new_engine->cleanup();
::destroy_at(new_engine);
return true;
}
indexsubquery_engine = new_engine;
join->allow_outer_refs = false; // for JOIN::set_prefix_tables()
return false;
}
void Item_in_subselect::cleanup() {
DBUG_TRACE;
if (m_left_expr_cache != nullptr) {
m_left_expr_cache->destroy_elements();
::destroy_at(m_left_expr_cache);
m_left_expr_cache = nullptr;
}
m_left_expr_cache_filled = false;
need_expr_cache = true;
switch (strategy) {
case Subquery_strategy::SUBQ_MATERIALIZATION:
if (m_in2exists_info->dependent_after) {
query_expr()->first_query_block()->uncacheable |= UNCACHEABLE_DEPENDENT;
query_expr()->uncacheable |= UNCACHEABLE_DEPENDENT;
}
[[fallthrough]];
case Subquery_strategy::SUBQ_EXISTS:
/*
Back to EXISTS_OR_MAT, so that next execution of this statement can
choose between the two.
*/
query_expr()->global_parameters()->select_limit = nullptr;
strategy = Subquery_strategy::CANDIDATE_FOR_IN2EXISTS_OR_MAT;
break;
default:
break;
}
Item_subselect::cleanup();
}
AccessPath *Item_in_subselect::root_access_path() const {
if (strategy == Subquery_strategy::SUBQ_MATERIALIZATION &&
indexsubquery_engine->engine_type() ==
subselect_indexsubquery_engine::HASH_SJ_ENGINE) {
return down_cast<subselect_hash_sj_engine *>(indexsubquery_engine)
->root_access_path();
} else {
// Only subselect_hash_sj_engine owns its own iterator;
// for subselect_indexsubquery_engine, the unit still has it, since it's a
// normally executed query block. Thus, we should never get called
// otherwise.
//
// However, in some situations where the hypergraph optimizer prints out
// the query to the log for debugging, it isn't fully optimized
// yet and might not yet have an iterator. Thus, return nullptr instead of
// assert-failing.
assert(current_thd->lex->using_hypergraph_optimizer());
return nullptr;
}
}
bool Item_subselect::fix_fields(THD *thd, Item **) {
char const *save_where = thd->where;
uint8 uncacheable;
bool res;
assert(!fixed);
assert(indexsubquery_engine == nullptr);
#ifndef NDEBUG
assert(contextualized);
#endif
if (check_stack_overrun(thd, STACK_MIN_SIZE, (uchar *)&res)) return true;
if (!query_expr()->is_prepared() &&
query_expr()->prepare(thd, m_query_result, nullptr, SELECT_NO_UNLOCK, 0))
return true;
// Accumulate properties referring to "inner tables"
accumulate_properties();
// Check that subquery does not contain more selected expression than allowed
if (query_expr()->num_visible_fields() > m_max_columns) {
my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
return true;
}
if (resolve_type(thd)) return true;
if ((uncacheable = query_expr()->uncacheable)) {
if (uncacheable & UNCACHEABLE_RAND) {
m_subquery_used_tables |= RAND_TABLE_BIT;
m_used_tables_cache |= RAND_TABLE_BIT;
}
}
/*
If this subquery references window functions, per the SQL standard they
are aggregated in the subquery's query block, and never outside of it, so:
*/
assert(!has_wf());
thd->where = save_where;
return false;
}
bool Item_subselect::walk(Item_processor processor, enum_walk walk,
uchar *arg) {
if ((walk & enum_walk::PREFIX) && (this->*processor)(arg)) return true;
if ((walk & enum_walk::SUBQUERY) && query_expr()->walk(processor, walk, arg))
return true;
return (walk & enum_walk::POSTFIX) && (this->*processor)(arg);
}
/**
Register subquery to the table where it is used within a condition.
@param arg qep_row to which the subquery belongs
@returns false
@note We always return "false" as far as we don't want to dive deeper because
we explain inner subqueries in their joins contexts.
*/
bool Item_subselect::explain_subquery_checker(uchar **arg) {
qep_row *qr = reinterpret_cast<qep_row *>(*arg);
qr->register_where_subquery(query_expr());
return false;
}
bool Item_subselect::exec(THD *thd) {
DBUG_TRACE;
/*
Do not execute subselect in case of a fatal error
or if the query has been killed.
*/
if (thd->is_error() || thd->killed) return true;
// No subqueries should be evaluated when analysing a view
assert(!thd->lex->is_view_context_analysis());
/*
Simulate a failure in sub-query execution. Used to test e.g.
out of memory or query being killed conditions.
*/
DBUG_EXECUTE_IF("subselect_exec_fail", return true;);
/*
Disable tracing of subquery execution if
1) this is not the first time the subselect is executed, and
2) REPEATED_SUBSELECT is disabled
*/
Opt_trace_context *const trace = &thd->opt_trace;
const bool disable_trace =
m_traced_before &&
!trace->feature_enabled(Opt_trace_context::REPEATED_SUBSELECT);
const Opt_trace_disable_I_S disable_trace_wrapper(trace, disable_trace);
m_traced_before = true;
const Opt_trace_object trace_wrapper(trace);
Opt_trace_object trace_exec(trace, "subselect_execution");
trace_exec.add_select_number(
query_expr()->first_query_block()->select_number);
const Opt_trace_array trace_steps(trace, "steps");
// subselect_hash_sj_engine creates its own iterators; it does not call
// exec().
const bool should_create_iterators =
!(indexsubquery_engine != nullptr &&
indexsubquery_engine->engine_type() ==
subselect_indexsubquery_engine::HASH_SJ_ENGINE);
// Normally, the query expression would be optimized here, but statements
// like DO and SET may still rely on lazy optimization. Also, we might not
// have iterators, so make sure to create them if they're missing.
if (!query_expr()->is_optimized()) {
if (query_expr()->optimize(thd, /*materialize_destination=*/nullptr,
/*finalize_access_paths=*/false))
return true;
// NOTE: We defer finalization and creating iterators to the statements
// below; asking optimize() to finalize a plan with two choices
// (materialization and exists) rightfully causes a failed assertion. We
// should probably have made a cost-based choice between the two here, but
// as it stands, we will always implicitly choose in2exists in these cases
// (DO/SET).
}
if (should_create_iterators && query_expr()->root_access_path() != nullptr) {
if (query_expr()->finalize(thd)) {
return true;
}
if (query_expr()->force_create_iterators(thd)) return true;
}
if (indexsubquery_engine != nullptr) {
return indexsubquery_engine->exec(thd);
} else {
char const *save_where = thd->where;
const bool res = query_expr()->execute(thd);
thd->where = save_where;
return res;
}
}
/// @see Query_expression::fix_after_pullout()
void Item_subselect::fix_after_pullout(Query_block *parent_query_block,
Query_block *removed_query_block)
{
/* Clear usage information for this subquery predicate object */
m_used_tables_cache = 0;
m_subquery_used_tables = 0;
query_expr()->fix_after_pullout(parent_query_block, removed_query_block);
// Accumulate properties like INNER_TABLE_BIT
accumulate_properties();
if (query_expr()->uncacheable & UNCACHEABLE_RAND) {
m_subquery_used_tables |= RAND_TABLE_BIT;
}
m_used_tables_cache = m_subquery_used_tables;
}
bool Item_in_subselect::walk(Item_processor processor, enum_walk walk,
uchar *arg) {
if (left_expr->walk(processor, walk, arg)) return true;
return Item_subselect::walk(processor, walk, arg);
}
Item *Item_in_subselect::transform(Item_transformer transformer, uchar *arg) {
left_expr = left_expr->transform(transformer, arg);
if (left_expr == nullptr) return nullptr;
return (this->*transformer)(arg);
}
Item *Item_in_subselect::compile(Item_analyzer analyzer, uchar **arg_p,
Item_transformer transformer, uchar *arg_t) {
if (!(this->*analyzer)(arg_p)) return this;
// Compile the left expression of the IN subquery
Item *item = left_expr->compile(analyzer, arg_p, transformer, arg_t);
if (item == nullptr) return nullptr; /* purecov: inspected */
if (item != left_expr) current_thd->change_item_tree(&left_expr, item);
return (this->*transformer)(arg_t);
}
/*
Compute the IN predicate if the left operand's cache changed.
*/
bool Item_in_subselect::exec(THD *thd) {
DBUG_TRACE;
assert(strategy != Subquery_strategy::SUBQ_MATERIALIZATION ||
indexsubquery_engine->engine_type() ==
subselect_indexsubquery_engine::HASH_SJ_ENGINE);
/*
Initialize the cache of the left predicate operand. This has to be done as
late as now, because Cached_item directly contains a resolved field (not
an item, and in some cases (when temp tables are created), these fields
end up pointing to the wrong field. One solution is to change Cached_item
to not resolve its field upon creation, but to resolve it dynamically
from a given Item_ref object.
Do not init the cache if a previous execution decided that it is not needed.
TODO: the cache should be applied conditionally based on:
- rules - e.g. only if the left operand is known to be ordered, and/or
- on a cost-based basis, that takes into account the cost of a cache
lookup, the cache hit rate, and the savings per cache hit.
*/
if (need_expr_cache && m_left_expr_cache == nullptr &&
strategy == Subquery_strategy::SUBQ_MATERIALIZATION &&
init_left_expr_cache(thd))
return true;
if (m_left_expr_cache != nullptr) {
const int result = update_item_cache_if_changed(*m_left_expr_cache);
if (m_left_expr_cache_filled && // cache was previously filled
result < 0) // new value is identical to previous cached value
{
/*
We needn't do a full execution, can just reuse "value", "was_null",
"null_value" of the previous execution.
*/
return false;
}
m_left_expr_cache_filled = true;
}
const bool uncacheable =
query_expr()->uncacheable || indexsubquery_engine != nullptr;
if (query_expr()->is_executed() && uncacheable) {
// Second or later execution (and it's actually going to be executed,
// not just the return the cached value from the first run), so clear out
// state from the previous run(s).
//
// Note that subselect_hash_sj_engine and subselect_indexsubquery_engine
// are both uncacheable (due to dependency on the left side), even if the
// underlying query expression is not marked as such.
null_value = false;
m_was_null = false;
}
return Item_subselect::exec(thd);
}
Item::Type Item_subselect::type() const { return SUBQUERY_ITEM; }
Item *Item_subselect::get_tmp_table_item(THD *thd_arg) {
DBUG_TRACE;
if (!has_aggregation() && !(const_for_execution() &&
evaluate_during_optimization(
this, thd_arg->lex->current_query_block()))) {
Item *result = new Item_field(result_field);
return result;
}
Item *result = copy_or_same(thd_arg);
return result;
}
void Item_subselect::update_used_tables() {
if (!query_expr()->uncacheable) {
// There is no expression with outer reference, randomness or side-effect,
// so the subquery's content depends only on its inner tables:
m_subquery_used_tables &= INNER_TABLE_BIT;
}
m_used_tables_cache = m_subquery_used_tables;
}
void Item_subselect::print(const THD *thd, String *str,
enum_query_type query_type) const {
str->append('(');
if (query_type & QT_SUBSELECT_AS_ONLY_SELECT_NUMBER) {
str->append("select #");
uint select_number = query_expr()->first_query_block()->select_number;
str->append_ulonglong(select_number);
} else if (indexsubquery_engine != nullptr) {
indexsubquery_engine->print(thd, str, query_type);
} else {
query_expr()->print(thd, str, query_type);
}
str->append(')');
}
bool Query_result_scalar_subquery::send_data(
THD *thd, const mem_root_deque<Item *> &items) {
DBUG_TRACE;
Item_singlerow_subselect *it = down_cast<Item_singlerow_subselect *>(item);
if (it->is_value_assigned()) {
my_error(ER_SUBQUERY_NO_1_ROW, MYF(0));
return true;
}
uint i = 0;
for (Item *val_item : VisibleFields(items)) {
it->store(i++, val_item);
}
if (thd->is_error()) return true;
it->set_value_assigned();
return false;
}
Item_singlerow_subselect::Item_singlerow_subselect(const POS &pos,
Query_block *query_block)
: Item_subselect(pos) {
bind(query_block->master_query_expression());
m_max_columns = UINT_MAX;
}
Item_singlerow_subselect::Item_singlerow_subselect(Query_block *query_block)
: Item_subselect() {
bind(query_block->master_query_expression());
m_max_columns = UINT_MAX;
}
Query_block *Item_singlerow_subselect::invalidate_and_restore_query_block() {
DBUG_TRACE;
Query_block *result = query_expr()->first_query_block();
assert(result);
/*
This code restore the parse tree in it's state before the execution of
Item_singlerow_subselect::Item_singlerow_subselect(),
and in particular decouples this object from the Query_block,
so that the Query_block can be used with a different flavor
or Item_subselect instead, as part of query rewriting.
*/
query_expr()->item = nullptr;
return result;
}
/* used in independent ALL/ANY optimisation */
class Query_result_max_min_subquery final : public Query_result_subquery {
Item_cache *cache;
bool (Query_result_max_min_subquery::*op)();
bool fmax;
/**
If ignoring NULLs, comparisons will skip NULL values. If not
ignoring NULLs, the first (if any) NULL value discovered will be
returned as the maximum/minimum value.
*/
bool ignore_nulls;
public:
Query_result_max_min_subquery(Item_subselect *item_arg, bool mx,
bool ignore_nulls)
: Query_result_subquery(item_arg),
cache(nullptr),
fmax(mx),
ignore_nulls(ignore_nulls) {}
void cleanup() override;
bool send_data(THD *thd, const mem_root_deque<Item *> &items) override;
private:
bool cmp_real();
bool cmp_int();
bool cmp_decimal();
bool cmp_str();
};
void Query_result_max_min_subquery::cleanup() {
DBUG_TRACE;
cache = nullptr;
}
bool Query_result_max_min_subquery::send_data(
THD *, const mem_root_deque<Item *> &items) {
DBUG_TRACE;
Item_maxmin_subselect *it = (Item_maxmin_subselect *)item;
Item *val_item = nullptr;
for (Item *item : VisibleFields(items)) {
val_item = item;
break;
}
assert(val_item != nullptr);
it->register_value();
if (it->is_value_assigned()) {
cache->store(val_item);
if ((this->*op)()) it->store(0, cache);
} else {
if (cache == nullptr) {
cache = Item_cache::get_cache(val_item);
switch (val_item->result_type()) {
case REAL_RESULT:
op = &Query_result_max_min_subquery::cmp_real;
break;
case INT_RESULT:
op = &Query_result_max_min_subquery::cmp_int;
break;
case STRING_RESULT:
op = &Query_result_max_min_subquery::cmp_str;
break;
case DECIMAL_RESULT:
op = &Query_result_max_min_subquery::cmp_decimal;
break;
case ROW_RESULT:
case INVALID_RESULT:
// This case should never be chosen
assert(0);
op = nullptr;
}