-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
item_subselect.cc
6154 lines (5280 loc) · 175 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, 2016, Oracle and/or its affiliates.
Copyright (c) 2010, 2016, MariaDB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
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 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-1335 USA */
/**
@file
@brief
subselect Item
@todo
- add function from mysql_select that use JOIN* as parameter to JOIN
methods (sql_select.h/sql_select.cc)
*/
#ifdef USE_PRAGMA_IMPLEMENTATION
#pragma implementation // gcc: Class implementation
#endif
#include "sql_priv.h"
/*
It is necessary to include set_var.h instead of item.h because there
are dependencies on include order for set_var.h and item.h. This
will be resolved later.
*/
#include "sql_class.h" // set_var.h: THD
#include "set_var.h"
#include "sql_select.h"
#include "sql_parse.h" // check_stack_overrun
#include "sql_test.h"
double get_post_group_estimate(JOIN* join, double join_op_rows);
Item_subselect::Item_subselect():
Item_result_field(), value_assigned(0), own_engine(0), thd(0), old_engine(0),
used_tables_cache(0), have_to_be_excluded(0), const_item_cache(1),
inside_first_fix_fields(0), done_first_fix_fields(FALSE),
expr_cache(0), forced_const(FALSE), substitution(0), engine(0), eliminated(FALSE),
changed(0), is_correlated(FALSE)
{
DBUG_ENTER("Item_subselect::Item_subselect");
DBUG_PRINT("enter", ("this: 0x%lx", (ulong) this));
#ifndef DBUG_OFF
exec_counter= 0;
#endif
with_subselect= 1;
reset();
/*
Item value is NULL if select_result_interceptor didn't change this value
(i.e. some rows will be found returned)
*/
null_value= TRUE;
DBUG_VOID_RETURN;
}
void Item_subselect::init(st_select_lex *select_lex,
select_result_interceptor *result)
{
/*
Please see Item_singlerow_subselect::invalidate_and_restore_select_lex(),
which depends on alterations to the parse tree implemented here.
*/
DBUG_ENTER("Item_subselect::init");
DBUG_PRINT("enter", ("select_lex: 0x%lx this: 0x%lx",
(ulong) select_lex, (ulong) this));
unit= select_lex->master_unit();
if (unit->item)
{
/*
Item can be changed in JOIN::prepare while engine in JOIN::optimize
=> we do not copy old_engine here
*/
engine= unit->item->engine;
own_engine= FALSE;
parsing_place= unit->item->parsing_place;
unit->thd->change_item_tree((Item**)&unit->item, this);
engine->change_result(this, result, TRUE);
}
else
{
SELECT_LEX *outer_select= unit->outer_select();
/*
do not take into account expression inside aggregate functions because
they can access original table fields
*/
parsing_place= (outer_select->in_sum_expr ?
NO_MATTER :
outer_select->parsing_place);
if (unit->is_union())
engine= new subselect_union_engine(unit, result, this);
else
engine= new subselect_single_select_engine(select_lex, result, this);
}
{
SELECT_LEX *upper= unit->outer_select();
if (upper->parsing_place == IN_HAVING)
upper->subquery_in_having= 1;
/* The subquery is an expression cache candidate */
upper->expr_cache_may_be_used[upper->parsing_place]= TRUE;
}
DBUG_PRINT("info", ("engine: 0x%lx", (ulong)engine));
DBUG_VOID_RETURN;
}
st_select_lex *
Item_subselect::get_select_lex()
{
return unit->first_select();
}
void Item_subselect::cleanup()
{
DBUG_ENTER("Item_subselect::cleanup");
Item_result_field::cleanup();
if (old_engine)
{
if (engine)
engine->cleanup();
engine= old_engine;
old_engine= 0;
}
if (engine)
engine->cleanup();
reset();
value_assigned= 0;
expr_cache= 0;
forced_const= FALSE;
DBUG_PRINT("info", ("exec_counter: %d", exec_counter));
#ifndef DBUG_OFF
exec_counter= 0;
#endif
DBUG_VOID_RETURN;
}
void Item_singlerow_subselect::cleanup()
{
DBUG_ENTER("Item_singlerow_subselect::cleanup");
value= 0; row= 0;
Item_subselect::cleanup();
DBUG_VOID_RETURN;
}
void Item_in_subselect::cleanup()
{
DBUG_ENTER("Item_in_subselect::cleanup");
if (left_expr_cache)
{
left_expr_cache->delete_elements();
delete left_expr_cache;
left_expr_cache= NULL;
}
/*
TODO: This breaks the commented assert in add_strategy().
in_strategy&= ~SUBS_STRATEGY_CHOSEN;
*/
first_execution= TRUE;
pushed_cond_guards= NULL;
Item_subselect::cleanup();
DBUG_VOID_RETURN;
}
void Item_allany_subselect::cleanup()
{
/*
The MAX/MIN transformation through injection is reverted through the
change_item_tree() mechanism. Revert the select_lex object of the
query to its initial state.
*/
for (SELECT_LEX *sl= unit->first_select();
sl; sl= sl->next_select())
if (test_set_strategy(SUBS_MAXMIN_INJECTED))
sl->with_sum_func= false;
Item_in_subselect::cleanup();
}
Item_subselect::~Item_subselect()
{
DBUG_ENTER("Item_subselect::~Item_subselect");
DBUG_PRINT("enter", ("this: 0x%lx", (ulong) this));
if (own_engine)
delete engine;
else
engine->cleanup();
engine= NULL;
DBUG_VOID_RETURN;
}
bool
Item_subselect::select_transformer(JOIN *join)
{
DBUG_ENTER("Item_subselect::select_transformer");
DBUG_ASSERT(thd == join->thd);
DBUG_RETURN(false);
}
bool Item_subselect::fix_fields(THD *thd_param, Item **ref)
{
char const *save_where= thd_param->where;
uint8 uncacheable;
bool res;
thd= thd_param;
DBUG_ASSERT(unit->thd == thd);
status_var_increment(thd_param->status_var.feature_subquery);
DBUG_ASSERT(fixed == 0);
engine->set_thd((thd= thd_param));
if (!done_first_fix_fields)
{
done_first_fix_fields= TRUE;
inside_first_fix_fields= TRUE;
upper_refs.empty();
/*
psergey-todo: remove _first_fix_fields calls, we need changes on every
execution
*/
}
eliminated= FALSE;
parent_select= thd_param->lex->current_select;
if (check_stack_overrun(thd, STACK_MIN_SIZE, (uchar*)&res))
return TRUE;
if (!(res= engine->prepare(thd)))
{
// all transformation is done (used by prepared statements)
changed= 1;
inside_first_fix_fields= FALSE;
/*
Substitute the current item with an Item_in_optimizer that was
created by Item_in_subselect::select_in_like_transformer and
call fix_fields for the substituted item which in turn calls
engine->prepare for the subquery predicate.
*/
if (substitution)
{
/*
If the top item of the WHERE/HAVING condition changed,
set correct WHERE/HAVING for PS.
*/
if (unit->outer_select()->where == (*ref))
unit->outer_select()->where= substitution;
else if (unit->outer_select()->having == (*ref))
unit->outer_select()->having= substitution;
(*ref)= substitution;
substitution->name= name;
substitution->name_length= name_length;
if (have_to_be_excluded)
engine->exclude();
substitution= 0;
thd->where= "checking transformed subquery";
if (!(*ref)->fixed)
res= (*ref)->fix_fields(thd, ref);
goto end;
}
// Is it one field subselect?
if (engine->cols() > max_columns)
{
my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
goto end;
}
fix_length_and_dec();
}
else
goto end;
if ((uncacheable= engine->uncacheable() & ~UNCACHEABLE_EXPLAIN))
{
const_item_cache= 0;
if (uncacheable & UNCACHEABLE_RAND)
used_tables_cache|= RAND_TABLE_BIT;
}
fixed= 1;
end:
done_first_fix_fields= FALSE;
inside_first_fix_fields= FALSE;
thd->where= save_where;
return res;
}
bool Item_subselect::enumerate_field_refs_processor(uchar *arg)
{
List_iterator<Ref_to_outside> it(upper_refs);
Ref_to_outside *upper;
while ((upper= it++))
{
if (upper->item &&
upper->item->walk(&Item::enumerate_field_refs_processor, FALSE, arg))
return TRUE;
}
return FALSE;
}
bool Item_subselect::mark_as_eliminated_processor(uchar *arg)
{
eliminated= TRUE;
return FALSE;
}
/**
Remove a subselect item from its unit so that the unit no longer
represents a subquery.
@param arg unused parameter
@return
FALSE to force the evaluation of the processor for the subsequent items.
*/
bool Item_subselect::eliminate_subselect_processor(uchar *arg)
{
unit->item= NULL;
unit->exclude_from_tree();
eliminated= TRUE;
return FALSE;
}
/**
Adjust the master select of the subquery to be the fake_select which
represents the whole UNION right above the subquery, instead of the
last query of the UNION.
@param arg pointer to the fake select
@return
FALSE to force the evaluation of the processor for the subsequent items.
*/
bool Item_subselect::set_fake_select_as_master_processor(uchar *arg)
{
SELECT_LEX *fake_select= (SELECT_LEX*) arg;
/*
Move the st_select_lex_unit of a subquery from a global ORDER BY clause to
become a direct child of the fake_select of a UNION. In this way the
ORDER BY that is applied to the temporary table that contains the result of
the whole UNION, and all columns in the subquery are resolved against this
table. The transformation is applied only for immediate child subqueries of
a UNION query.
*/
if (unit->outer_select()->master_unit()->fake_select_lex == fake_select)
{
/*
Set the master of the subquery to be the fake select (i.e. the whole
UNION), instead of the last query in the UNION.
*/
fake_select->add_slave(unit);
DBUG_ASSERT(unit->outer_select() == fake_select);
/* Adjust the name resolution context hierarchy accordingly. */
for (SELECT_LEX *sl= unit->first_select(); sl; sl= sl->next_select())
sl->context.outer_context= &(fake_select->context);
/*
Undo Item_subselect::eliminate_subselect_processor because at that phase
we don't know yet that the ORDER clause will be moved to the fake select.
*/
unit->item= this;
eliminated= FALSE;
}
return FALSE;
}
bool Item_subselect::mark_as_dependent(THD *thd, st_select_lex *select,
Item *item)
{
if (inside_first_fix_fields)
{
is_correlated= TRUE;
Ref_to_outside *upper;
if (!(upper= new (thd->stmt_arena->mem_root) Ref_to_outside()))
return TRUE;
upper->select= select;
upper->item= item;
if (upper_refs.push_back(upper, thd->stmt_arena->mem_root))
return TRUE;
}
return FALSE;
}
/*
Adjust attributes after our parent select has been merged into grandparent
DESCRIPTION
Subquery is a composite object which may be correlated, that is, it may
have
1. references to tables of the parent select (i.e. one that has the clause
with the subquery predicate)
2. references to tables of the grandparent select
3. references to tables of further ancestors.
Before the pullout, this item indicates:
- #1 with table bits in used_tables()
- #2 and #3 with OUTER_REF_TABLE_BIT.
After parent has been merged with grandparent:
- references to parent and grandparent tables should be indicated with
table bits.
- references to greatgrandparent and further ancestors - with
OUTER_REF_TABLE_BIT.
*/
void Item_subselect::fix_after_pullout(st_select_lex *new_parent, Item **ref)
{
recalc_used_tables(new_parent, TRUE);
parent_select= new_parent;
}
class Field_fixer: public Field_enumerator
{
public:
table_map used_tables; /* Collect used_tables here */
st_select_lex *new_parent; /* Select we're in */
virtual void visit_field(Item_field *item)
{
//for (TABLE_LIST *tbl= new_parent->leaf_tables; tbl; tbl= tbl->next_local)
//{
// if (tbl->table == field->table)
// {
used_tables|= item->field->table->map;
// return;
// }
//}
//used_tables |= OUTER_REF_TABLE_BIT;
}
};
/*
Recalculate used_tables_cache
*/
void Item_subselect::recalc_used_tables(st_select_lex *new_parent,
bool after_pullout)
{
List_iterator<Ref_to_outside> it(upper_refs);
Ref_to_outside *upper;
DBUG_ENTER("recalc_used_tables");
used_tables_cache= 0;
while ((upper= it++))
{
bool found= FALSE;
/*
Check if
1. the upper reference refers to the new immediate parent select, or
2. one of the further ancestors.
We rely on the fact that the tree of selects is modified by some kind of
'flattening', i.e. a process where child selects are merged into their
parents.
The merged selects are removed from the select tree but keep pointers to
their parents.
*/
for (st_select_lex *sel= upper->select; sel; sel= sel->outer_select())
{
/*
If we've reached the new parent select by walking upwards from
reference's original select, this means that the reference is now
referring to the direct parent:
*/
if (sel == new_parent)
{
found= TRUE;
/*
upper->item may be NULL when we've referred to a grouping function,
in which case we don't care about what it's table_map really is,
because item->with_sum_func==1 will ensure correct placement of the
item.
*/
if (upper->item)
{
// Now, iterate over fields and collect used_tables() attribute:
Field_fixer fixer;
fixer.used_tables= 0;
fixer.new_parent= new_parent;
upper->item->walk(&Item::enumerate_field_refs_processor, FALSE,
(uchar*)&fixer);
used_tables_cache |= fixer.used_tables;
upper->item->walk(&Item::update_table_bitmaps_processor, FALSE, NULL);
/*
if (after_pullout)
upper->item->fix_after_pullout(new_parent, &(upper->item));
upper->item->update_used_tables();
*/
}
}
}
if (!found)
used_tables_cache|= OUTER_REF_TABLE_BIT;
}
/*
Don't update const_tables_cache yet as we don't yet know which of the
parent's tables are constant. Parent will call update_used_tables() after
he has done const table detection, and that will be our chance to update
const_tables_cache.
*/
DBUG_PRINT("exit", ("used_tables_cache: %llx", used_tables_cache));
DBUG_VOID_RETURN;
}
/**
Determine if a subquery is expensive to execute during query optimization.
@details The cost of execution of a subquery is estimated based on an
estimate of the number of rows the subquery will access during execution.
This measure is used instead of JOIN::read_time, because it is considered
to be much more reliable than the cost estimate.
@return true if the subquery is expensive
@return false otherwise
*/
bool Item_subselect::is_expensive()
{
double examined_rows= 0;
for (SELECT_LEX *sl= unit->first_select(); sl; sl= sl->next_select())
{
JOIN *cur_join= sl->join;
if (!cur_join)
continue;
/*
Subqueries whose result is known after optimization are not expensive.
Such subqueries have all tables optimized away, thus have no join plan.
*/
if (cur_join->optimized &&
(cur_join->zero_result_cause || !cur_join->tables_list))
return false;
/*
If a subquery is not optimized we cannot estimate its cost. A subquery is
considered optimized if it has a join plan.
*/
if (!(cur_join->optimized && cur_join->join_tab))
return true;
if (sl->first_inner_unit())
{
/*
Subqueries that contain subqueries are considered expensive.
@todo: accumulate the cost of subqueries.
*/
return true;
}
examined_rows+= cur_join->get_examined_rows();
}
// here we are sure that subquery is optimized so thd is set
return (examined_rows > thd->variables.expensive_subquery_limit);
}
bool Item_subselect::walk(Item_processor processor, bool walk_subquery,
uchar *argument)
{
if (!(unit->uncacheable & ~UNCACHEABLE_DEPENDENT) && engine->is_executed() &&
!unit->describe)
{
/*
The subquery has already been executed (for real, it wasn't EXPLAIN's
fake execution) so it should not matter what it has inside.
The actual reason for not walking inside is that parts of the subquery
(e.g. JTBM join nests and their IN-equality conditions may have been
invalidated by irreversible cleanups (those happen after an uncorrelated
subquery has been executed).
*/
return (this->*processor)(argument);
}
if (walk_subquery)
{
for (SELECT_LEX *lex= unit->first_select(); lex; lex= lex->next_select())
{
List_iterator<Item> li(lex->item_list);
Item *item;
ORDER *order;
if (lex->where && (lex->where)->walk(processor, walk_subquery, argument))
return 1;
if (lex->having && (lex->having)->walk(processor, walk_subquery,
argument))
return 1;
/* TODO: why does this walk WHERE/HAVING but not ON expressions of outer joins? */
while ((item=li++))
{
if (item->walk(processor, walk_subquery, argument))
return 1;
}
for (order= lex->order_list.first ; order; order= order->next)
{
if ((*order->item)->walk(processor, walk_subquery, argument))
return 1;
}
for (order= lex->group_list.first ; order; order= order->next)
{
if ((*order->item)->walk(processor, walk_subquery, argument))
return 1;
}
}
}
return (this->*processor)(argument);
}
bool Item_subselect::exec()
{
subselect_engine *org_engine= engine;
DBUG_ENTER("Item_subselect::exec");
DBUG_ASSERT(fixed);
/*
Do not execute subselect in case of a fatal error
or if the query has been killed.
*/
if (thd->is_error() || thd->killed)
DBUG_RETURN(true);
DBUG_ASSERT(!thd->lex->context_analysis_only);
/*
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", DBUG_RETURN(true););
bool res= engine->exec();
#ifndef DBUG_OFF
++exec_counter;
#endif
if (engine != org_engine)
{
/*
If the subquery engine changed during execution due to lazy subquery
optimization, or because the original engine found a more efficient other
engine, re-execute the subquery with the new engine.
*/
DBUG_RETURN(exec());
}
DBUG_RETURN(res);
}
void Item_subselect::get_cache_parameters(List<Item> ¶meters)
{
Collect_deps_prm prm= {¶meters,
unit->first_select()->nest_level_base,
unit->first_select()->nest_level};
walk(&Item::collect_outer_ref_processor, TRUE, (uchar*)&prm);
}
int Item_in_subselect::optimize(double *out_rows, double *cost)
{
int res;
DBUG_ENTER("Item_in_subselect::optimize");
DBUG_ASSERT(fixed);
SELECT_LEX *save_select= thd->lex->current_select;
JOIN *join= unit->first_select()->join;
thd->lex->current_select= join->select_lex;
if ((res= join->optimize()))
DBUG_RETURN(res);
/* Calculate #rows and cost of join execution */
join->get_partial_cost_and_fanout(join->table_count - join->const_tables,
table_map(-1),
cost, out_rows);
/*
Adjust join output cardinality. There can be these cases:
- Have no GROUP BY and no aggregate funcs: we won't get into this
function because such join will be processed as a merged semi-join
(TODO: does it really mean we don't need to handle such cases here at
all? put ASSERT)
- Have no GROUP BY but have aggregate funcs: output is 1 record.
- Have GROUP BY and have (or not) aggregate funcs: need to adjust output
cardinality.
*/
thd->lex->current_select= save_select;
if (!join->group_list && !join->group_optimized_away &&
join->tmp_table_param.sum_func_count)
{
DBUG_PRINT("info",("Materialized join will have only 1 row (it has "
"aggregates but no GROUP BY"));
*out_rows= 1;
}
/* Now with grouping */
if (join->group_list)
{
DBUG_PRINT("info",("Materialized join has grouping, trying to estimate it"));
double output_rows= get_post_group_estimate(join, *out_rows);
DBUG_PRINT("info",("Got value of %g", output_rows));
*out_rows= output_rows;
}
DBUG_RETURN(res);
}
/**
Check if an expression cache is needed for this subquery
@param thd Thread handle
@details
The function checks whether a cache is needed for a subquery and whether
the result of the subquery can be put in cache.
@retval TRUE cache is needed
@retval FALSE otherwise
*/
bool Item_subselect::expr_cache_is_needed(THD *thd)
{
return ((engine->uncacheable() & UNCACHEABLE_DEPENDENT) &&
engine->cols() == 1 &&
optimizer_flag(thd, OPTIMIZER_SWITCH_SUBQUERY_CACHE) &&
!(engine->uncacheable() & (UNCACHEABLE_RAND |
UNCACHEABLE_SIDEEFFECT)));
}
/**
Check if the left IN argument contains NULL values.
@retval TRUE there are NULLs
@retval FALSE otherwise
*/
inline bool Item_in_subselect::left_expr_has_null()
{
return (*(optimizer->get_cache()))->null_value;
}
/**
Check if an expression cache is needed for this subquery
@param thd Thread handle
@details
The function checks whether a cache is needed for a subquery and whether
the result of the subquery can be put in cache.
@note
This method allows many columns in the subquery because it is supported by
Item_in optimizer and result of the IN subquery will be scalar in this
case.
@retval TRUE cache is needed
@retval FALSE otherwise
*/
bool Item_in_subselect::expr_cache_is_needed(THD *thd)
{
return (optimizer_flag(thd, OPTIMIZER_SWITCH_SUBQUERY_CACHE) &&
!(engine->uncacheable() & (UNCACHEABLE_RAND |
UNCACHEABLE_SIDEEFFECT)));
}
/*
Compute the IN predicate if the left operand's cache changed.
*/
bool Item_in_subselect::exec()
{
DBUG_ENTER("Item_in_subselect::exec");
DBUG_ASSERT(fixed);
/*
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.
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 (!left_expr_cache && (test_strategy(SUBS_MATERIALIZATION)))
init_left_expr_cache();
/*
If the new left operand is already in the cache, reuse the old result.
Use the cached result only if this is not the first execution of IN
because the cache is not valid for the first execution.
*/
if (!first_execution && left_expr_cache &&
test_if_item_cache_changed(*left_expr_cache) < 0)
DBUG_RETURN(FALSE);
/*
The exec() method below updates item::value, and item::null_value, thus if
we don't call it, the next call to item::val_int() will return whatever
result was computed by its previous call.
*/
DBUG_RETURN(Item_subselect::exec());
}
Item::Type Item_subselect::type() const
{
return SUBSELECT_ITEM;
}
void Item_subselect::fix_length_and_dec()
{
engine->fix_length_and_dec(0);
}
table_map Item_subselect::used_tables() const
{
return (table_map) ((engine->uncacheable() & ~UNCACHEABLE_EXPLAIN)?
used_tables_cache : 0L);
}
bool Item_subselect::const_item() const
{
DBUG_ASSERT(thd);
return (thd->lex->context_analysis_only ?
FALSE :
forced_const || const_item_cache);
}
Item *Item_subselect::get_tmp_table_item(THD *thd_arg)
{
if (!with_sum_func && !const_item())
return new Item_field(result_field);
return copy_or_same(thd_arg);
}
void Item_subselect::update_used_tables()
{
if (!forced_const)
{
recalc_used_tables(parent_select, FALSE);
if (!(engine->uncacheable() & ~UNCACHEABLE_EXPLAIN))
{
// did all used tables become static?
if (!(used_tables_cache & ~engine->upper_select_const_tables()))
const_item_cache= 1;
}
}
}
void Item_subselect::print(String *str, enum_query_type query_type)
{
if (engine)
{
str->append('(');
engine->print(str, query_type);
str->append(')');
}
else
str->append("(...)");
}
Item_singlerow_subselect::Item_singlerow_subselect(st_select_lex *select_lex)
:Item_subselect(), value(0)
{
DBUG_ENTER("Item_singlerow_subselect::Item_singlerow_subselect");
init(select_lex, new select_singlerow_subselect(this));
maybe_null= 1;
max_columns= UINT_MAX;
DBUG_VOID_RETURN;
}
st_select_lex *
Item_singlerow_subselect::invalidate_and_restore_select_lex()
{
DBUG_ENTER("Item_singlerow_subselect::invalidate_and_restore_select_lex");
st_select_lex *result= get_select_lex();
DBUG_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 SELECT_LEX,
so that the SELECT_LEX can be used with a different flavor
or Item_subselect instead, as part of query rewriting.
*/
unit->item= NULL;
DBUG_RETURN(result);
}
Item_maxmin_subselect::Item_maxmin_subselect(THD *thd_param,
Item_subselect *parent,
st_select_lex *select_lex,
bool max_arg)
:Item_singlerow_subselect(), was_values(TRUE)
{
DBUG_ENTER("Item_maxmin_subselect::Item_maxmin_subselect");
max= max_arg;
init(select_lex,
new select_max_min_finder_subselect(this, max_arg,
parent->substype() ==
Item_subselect::ALL_SUBS));
max_columns= 1;
maybe_null= 1;
max_columns= 1;
/*
Following information was collected during performing fix_fields()
of Items belonged to subquery, which will be not repeated
*/
used_tables_cache= parent->get_used_tables_cache();
const_item_cache= parent->const_item();
/*
this subquery always creates during preparation, so we can assign
thd here
*/
thd= thd_param;
DBUG_VOID_RETURN;
}
void Item_maxmin_subselect::cleanup()
{
DBUG_ENTER("Item_maxmin_subselect::cleanup");
Item_singlerow_subselect::cleanup();
/*
By default it is TRUE to avoid TRUE reporting by
Item_func_not_all/Item_func_nop_all if this item was never called.
Engine exec() set it to FALSE by reset_value_registration() call.
select_max_min_finder_subselect::send_data() set it back to TRUE if some
value will be found.
*/
was_values= TRUE;
DBUG_VOID_RETURN;
}
void Item_maxmin_subselect::print(String *str, enum_query_type query_type)
{
str->append(max?"<max>":"<min>", 5);
Item_singlerow_subselect::print(str, query_type);
}
void Item_maxmin_subselect::no_rows_in_result()
{
/*
Subquery predicates outside of the SELECT list must be evaluated in order
to possibly filter the special result row generated for implicit grouping
if the subquery is in the HAVING clause.
If the predicate is constant, we need its actual value in the only result
row for queries with implicit grouping.
*/