-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathitem_sum.cc
6786 lines (5841 loc) · 208 KB
/
item_sum.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) 2000, 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
Sum functions (COUNT, MIN...)
*/
#include "sql/item_sum.h"
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstring>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility> // std::forward
#include "decimal.h"
#include "field_types.h"
#include "my_alloc.h"
#include "my_base.h"
#include "my_byteorder.h"
#include "my_compare.h"
#include "my_dbug.h"
#include "my_double2ulonglong.h"
#include "my_sys.h"
#include "mysql/strings/dtoa.h"
#include "mysql/strings/m_ctype.h"
#include "mysql/strings/my_strtoll10.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "scope_guard.h"
#include "sql-common/json_dom.h"
#include "sql/aggregate_check.h" // Distinct_check
#include "sql/create_field.h"
#include "sql/current_thd.h" // current_thd
#include "sql/dd/cache/dictionary_client.h"
#include "sql/derror.h" // ER_THD
#include "sql/field.h"
#include "sql/gis/gc_utils.h"
#include "sql/gis/geometries.h"
#include "sql/gis/geometry_extraction.h"
#include "sql/gis/relops.h"
#include "sql/handler.h"
#include "sql/item_cmpfunc.h"
#include "sql/item_func.h"
#include "sql/item_json_func.h"
#include "sql/item_subselect.h"
#include "sql/key_spec.h"
#include "sql/mysqld.h"
#include "sql/parse_tree_helpers.h" // PT_item_list
#include "sql/parse_tree_node_base.h" // Parse_context
#include "sql/parse_tree_nodes.h" // PT_order_list
#include "sql/parser_yystype.h"
#include "sql/sql_array.h"
#include "sql/sql_class.h" // THD
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_exception_handler.h" // handle_std_exception
#include "sql/sql_executor.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_optimizer.h"
#include "sql/sql_resolver.h" // setup_order
#include "sql/sql_select.h"
#include "sql/sql_time.h"
#include "sql/sql_tmp_table.h" // create_tmp_table
#include "sql/srs_fetcher.h" // Srs_fetcher
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/temp_table_param.h" // Temp_table_param
#include "sql/uniques.h" // Unique
#include "sql/window.h"
#include "string_with_len.h"
using std::max;
using std::min;
bool Item_sum::do_itemize(Parse_context *pc, Item **res) {
if (skip_itemize(res)) return false;
if (Item_result_field::do_itemize(pc, res)) return true;
if (m_window) {
pc->select->in_window_expr++;
if (m_window->contextualize(pc)) return true; /* purecov: inspected */
if (!m_window->is_reference()) {
pc->select->m_windows.push_back(m_window);
m_window->set_def_pos(pc->select->m_windows.elements);
}
m_is_window_function = true;
pc->select->n_sum_items++;
set_wf();
} else {
mark_as_sum_func(pc->select);
pc->select->in_sum_expr++;
}
for (uint i = 0; i < arg_count; i++) {
if (args[i]->itemize(pc, &args[i])) return true;
}
(m_window == nullptr) ? pc->select->in_sum_expr--
: pc->select->in_window_expr--;
return false;
}
/**
Calculate the affordable RAM limit for structures like TREE or Unique
used in Item_sum_*
*/
ulonglong Item_sum::ram_limitation(THD *thd) {
ulonglong limitation =
min(thd->variables.tmp_table_size, thd->variables.max_heap_table_size);
DBUG_EXECUTE_IF("simulate_low_itemsum_ram_limitation", limitation = 32;);
return limitation;
}
/**
Prepare an aggregate function for checking of context.
The function initializes the members of the Item_sum object.
It also checks the general validity of the set function:
If none of the currently active query blocks allow evaluation of
set functions, an error is reported.
@note
This function must be called for all set functions when expressions are
resolved. It must be invoked in prefix order, ie at the descent of this
traversal. @see corresponding Item_sum::check_sum_func(), which should
be called on ascent.
@param thd reference to the thread context info
@returns false if success, true if error
*/
bool Item_sum::init_sum_func_check(THD *thd) {
LEX *const lex = thd->lex;
base_query_block = lex->current_query_block();
if (m_is_window_function) {
if (lex->deny_window_function(base_query_block)) {
my_error(ER_WINDOW_INVALID_WINDOW_FUNC_USE, MYF(0), func_name());
return true;
}
in_sum_func = nullptr;
} else {
if (!lex->allow_sum_func) {
my_error(ER_INVALID_GROUP_FUNC_USE, MYF(0));
return true;
}
// Set a reference to the containing set function if there is one
in_sum_func = lex->in_sum_func;
/*
Set this object as the current containing set function, used when
checking arguments of this set function.
*/
lex->in_sum_func = this;
}
save_deny_window_func = lex->m_deny_window_func;
lex->m_deny_window_func |= (nesting_map)1 << base_query_block->nest_level;
// @todo: When resolving once, move following code to constructor
aggr_query_block = nullptr; // Aggregation query block is undetermined yet
referenced_by[0] = nullptr;
/*
Leave referenced_by[1] unchanged as in execution of PS, in-to-exists is not
re-done, so referenced_by[1] isn't set again. So keep it as it was in
preparation.
*/
if (base_query_block->first_execution) referenced_by[1] = nullptr;
max_aggr_level = -1;
max_sum_func_level = -1;
used_tables_cache = 0;
return false;
}
/**
Validate the semantic requirements of a set function.
Check whether the context of the set function allows it to be aggregated
and, when it is an argument of another set function, directly or indirectly,
the function makes sure that these two set functions are aggregated in
different query blocks.
If the context conditions are not met, an error is reported.
If the set function is aggregated in some outer query block, it is
added to the chain of items inner_sum_func_list attached to the
aggregating query block.
A number of designated members of the object are used to check the
conditions. They are specified in the comment before the Item_sum
class declaration.
Additionally a bitmap variable called allow_sum_func is employed.
It is included into the LEX structure.
The bitmap contains 1 at n-th position if the query block at level "n"
allows a set function reference (i.e the current resolver context for
the query block is either in the SELECT list or in the HAVING or
ORDER BY clause).
Consider the query:
@code
SELECT SUM(t1.b) FROM t1 GROUP BY t1.a
HAVING t1.a IN (SELECT t2.c FROM t2 WHERE AVG(t1.b) > 20) AND
t1.a > (SELECT MIN(t2.d) FROM t2);
@endcode
when the set functions are resolved, allow_sum_func will contain:
- for SUM(t1.b) - 1 at position 0 (SUM is in SELECT list)
- for AVG(t1.b) - 1 at position 0 (subquery is in HAVING clause)
0 at position 1 (AVG is in WHERE clause)
- for MIN(t2.d) - 1 at position 0 (subquery is in HAVING clause)
1 at position 1 (MIN is in SELECT list)
@note
This function must be called for all set functions when expressions are
resolved. It must be invoked in postfix order, ie at the ascent of this
traversal.
@param thd reference to the thread context info
@param ref location of the pointer to this item in the containing expression
@returns false if success, true if error
*/
bool Item_sum::check_sum_func(THD *thd, Item **ref) {
DBUG_TRACE;
if (m_is_window_function) {
update_used_tables();
thd->lex->m_deny_window_func = save_deny_window_func;
return false;
}
const nesting_map allow_sum_func = thd->lex->allow_sum_func;
const nesting_map nest_level_map = (nesting_map)1
<< base_query_block->nest_level;
assert(thd->lex->current_query_block() == base_query_block);
assert(aggr_query_block == nullptr);
/*
max_aggr_level is the level of the innermost qualifying query block of
the column references of this set function. If the set function contains
no column references, max_aggr_level is -1.
max_aggr_level cannot be greater than nest level of the current query block.
*/
assert(max_aggr_level <= base_query_block->nest_level);
if (base_query_block->nest_level == max_aggr_level) {
/*
The function must be aggregated in the current query block,
and it must be referred within a clause where it is valid
(ie. HAVING clause, ORDER BY clause or SELECT list)
*/
if ((allow_sum_func & nest_level_map) != 0)
aggr_query_block = base_query_block;
} else if (max_aggr_level >= 0 || !(allow_sum_func & nest_level_map)) {
/*
Look for an outer query block where the set function should be
aggregated. If it finds such a query block, then aggr_query_block is set
to this query block
*/
for (Query_block *sl = base_query_block->outer_query_block();
sl && sl->nest_level >= max_aggr_level; sl = sl->outer_query_block()) {
if (allow_sum_func & ((nesting_map)1 << sl->nest_level))
aggr_query_block = sl;
}
} else // max_aggr_level < 0
{
/*
Set function without column reference is aggregated in innermost query,
without any validation.
*/
aggr_query_block = base_query_block;
}
if (aggr_query_block == nullptr && (allow_sum_func & nest_level_map) != 0 &&
!(thd->variables.sql_mode & MODE_ANSI))
aggr_query_block = base_query_block;
/*
At this place a query block where the set function is to be aggregated
has been found and is assigned to aggr_query_block, or aggr_query_block is
NULL to indicate an invalid set function.
Additionally, check whether possible nested set functions are acceptable
here: their aggregation level must be greater than this set function's
aggregation level.
*/
if (aggr_query_block == nullptr ||
aggr_query_block->nest_level <= max_sum_func_level) {
my_error(ER_INVALID_GROUP_FUNC_USE, MYF(0));
return true;
}
for (uint i = 0; i < arg_count; i++) {
if (args[i]->has_aggregation() &&
WalkItem(args[i], enum_walk::SUBQUERY_POSTFIX, [this](Item *subitem) {
if (subitem->type() != Item::SUM_FUNC_ITEM) return false;
Item_sum *si = down_cast<Item_sum *>(subitem);
return si->aggr_query_block == this->aggr_query_block;
})) {
my_error(ER_INVALID_GROUP_FUNC_USE, MYF(0));
return true;
}
}
if (aggr_query_block != base_query_block) {
referenced_by[0] = ref;
/*
Add the set function to the list inner_sum_func_list for the
aggregating query block.
@note
Now we 'register' only set functions that are aggregated in outer
query blocks. Actually it makes sense to link all set functions for
a query block in one chain. It would simplify the process of 'splitting'
for set functions.
*/
if (!aggr_query_block->inner_sum_func_list)
next_sum = this;
else {
next_sum = aggr_query_block->inner_sum_func_list->next_sum;
aggr_query_block->inner_sum_func_list->next_sum = this;
}
aggr_query_block->inner_sum_func_list = this;
aggr_query_block->with_sum_func = true;
/*
Mark subqueries as containing set function all the way up to the
set function's aggregation query block.
Note that we must not mark the Item of calculation context itself
because with_sum_func on the aggregation query block is already set above.
has_aggregation() being set for an Item means that this Item refers
(somewhere in it, e.g. one of its arguments if it's a function) directly
or indirectly to a set function that is calculated in a
context "outside" of the Item (e.g. in the current or outer query block).
with_sum_func being set for a query block means that this query block
has set functions directly referenced (i.e. not through a subquery).
If, going up, we meet a derived table, we do nothing special for it:
it doesn't need this information.
*/
for (Query_block *sl = base_query_block; sl && sl != aggr_query_block;
sl = sl->outer_query_block()) {
if (sl->master_query_expression()->item)
sl->master_query_expression()->item->set_aggregation();
}
base_query_block->mark_as_dependent(aggr_query_block, true);
}
if (in_sum_func) {
/*
If the set function is nested adjust the value of
max_sum_func_level for the containing set function.
We take into account only set functions that are to be aggregated on
the same level or outer compared to the nest level of the containing
set function.
But we must always pass up the max_sum_func_level because it is
the maximum nest level of all directly and indirectly contained
set functions. We must do that even for set functions that are
aggregated inside of their containing set function's nest level
because the containing function may contain another containing
function that is to be aggregated outside or on the same level
as its parent's nest level.
*/
if (in_sum_func->base_query_block->nest_level >=
aggr_query_block->nest_level)
in_sum_func->max_sum_func_level = max(in_sum_func->max_sum_func_level,
int8(aggr_query_block->nest_level));
in_sum_func->max_sum_func_level =
max(in_sum_func->max_sum_func_level, max_sum_func_level);
}
aggr_query_block->set_agg_func_used(true);
if (sum_func() == JSON_AGG_FUNC)
aggr_query_block->set_json_agg_func_used(true);
update_used_tables();
thd->lex->in_sum_func = in_sum_func;
thd->lex->m_deny_window_func = save_deny_window_func;
return false;
}
bool Item_sum::check_wf_semantics1(THD *, Query_block *,
Window_evaluation_requirements *r) {
const PT_frame *frame = m_window->frame();
/*
If we have ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, we can just
accumulate as we see rows, never need to invert old rows or to look at
future rows, so don't need a frame buffer.
*/
r->needs_buffer = !(frame->m_query_expression == WFU_ROWS &&
frame->m_from->m_border_type == WBT_UNBOUNDED_PRECEDING &&
frame->m_to->m_border_type == WBT_CURRENT_ROW);
if (with_distinct) {
my_error(ER_NOT_SUPPORTED_YET, MYF(0), "<window function>(DISTINCT ..)");
return true;
}
return false;
}
Item_sum::Item_sum(const POS &pos, PT_item_list *opt_list, PT_window *w)
: Item_func(pos, opt_list), m_window(w) {}
/**
Constructor used in processing select with temporary tebles.
*/
Item_sum::Item_sum(THD *thd, const Item_sum *item)
: Item_func(thd, item),
m_window(item->m_window),
base_query_block(item->base_query_block),
aggr_query_block(item->aggr_query_block),
allow_group_via_temp_table(item->allow_group_via_temp_table),
forced_const(item->forced_const),
m_null_resolved(item->m_null_resolved),
m_null_executed(item->m_null_executed) {
assert(arg_count == item->arg_count);
with_distinct = item->with_distinct;
if (item->aggr) {
Item_sum::set_aggregator(item->aggr->Aggrtype());
}
assert(!m_is_window_function); // WF items are never copied
}
void Item_sum::mark_as_sum_func() {
mark_as_sum_func(current_thd->lex->current_query_block());
}
void Item_sum::mark_as_sum_func(Query_block *cur_query_block) {
cur_query_block->n_sum_items++;
cur_query_block->with_sum_func = true;
set_aggregation();
}
void Item_sum::print(const THD *thd, String *str,
enum_query_type query_type) const {
str->append(func_name());
str->append('(');
if (has_with_distinct()) str->append("distinct ");
for (uint i = 0; i < arg_count; i++) {
if (i) str->append(',');
args[i]->print(thd, str, query_type);
}
str->append(')');
if (m_window) {
str->append(" OVER ");
m_window->print(thd, str, query_type, false);
}
}
bool Item_sum::resolve_type(THD *thd) {
if (param_type_is_default(thd, 0, -1)) return true;
set_nullable(true);
null_value = true;
const Sumfunctype t = sum_func();
// None except these 4 types are allowed for geometry arguments.
if (!(t == COUNT_FUNC || t == COUNT_DISTINCT_FUNC || t == SUM_BIT_FUNC ||
t == GEOMETRY_AGGREGATE_FUNC)) {
if (reject_geometry_args()) return true;
}
if (t != COUNT_FUNC && t != COUNT_DISTINCT_FUNC) {
if (reject_vector_args()) return true;
}
return false;
}
/**
Remove the item from the list of inner aggregation functions in the
Query_block it was moved to by Item_sum::check_sum_func().
This is done to undo some of the effects of Item_sum::check_sum_func() so
that the item may be removed from the query.
@note This doesn't completely undo Item_sum::check_sum_func(), as
aggregation information is left untouched. This means that if this
item is removed, aggr_query_block and all subquery items between
aggr_query_block and this item may be left with has_aggregation() set to true,
even if there are no aggregation functions. To our knowledge, this has no
impact on the query result.
@see Item_sum::check_sum_func()
@see remove_redundant_subquery_clauses()
If this is a window function, remove the reference from the window.
This is needed when constant predicates are being removed.
@see Item_cond::fix_fields()
@see Item_cond::remove_const_cond()
*/
bool Item_sum::clean_up_after_removal(uchar *arg) {
Cleanup_after_removal_context *const ctx =
pointer_cast<Cleanup_after_removal_context *>(arg);
if (ctx->is_stopped(this)) return false;
if (reference_count() > 1) {
(void)decrement_ref_count();
ctx->stop_at(this);
return false;
}
// Remove item on upward traversal, not downward:
if (marker == MARKER_NONE) {
marker = MARKER_TRAVERSAL;
return false;
}
assert(marker == MARKER_TRAVERSAL);
marker = MARKER_NONE;
/*
Don't do anything if
1) this is an unresolved item (This may happen if an
expression occurs twice in the same query. In that case, the
whole item tree for the second occurrence is replaced by the
item tree for the first occurrence, without calling fix_fields()
on the second tree. Therefore there's nothing to clean up.), or
If it is a grouped aggregate,
2) there is no inner_sum_func_list, or
3) the item is not an element in the inner_sum_func_list.
*/
if (!fixed || // 1
(m_window == nullptr &&
(aggr_query_block == nullptr ||
aggr_query_block->inner_sum_func_list == nullptr // 2
|| next_sum == nullptr))) // 3
return false;
if (m_window) {
// Cleanup the reference for this window function from m_functions
List_iterator<Item_sum> li(m_window->functions());
Item *item = nullptr;
while ((item = li++)) {
if (item == this) {
li.remove();
break;
}
}
} else {
if (next_sum == this)
aggr_query_block->inner_sum_func_list = nullptr;
else {
Item_sum *prev;
for (prev = this; prev->next_sum != this; prev = prev->next_sum)
;
prev->next_sum = next_sum;
next_sum = nullptr;
if (aggr_query_block->inner_sum_func_list == this)
aggr_query_block->inner_sum_func_list = prev;
}
// Replace the removed item with a NULL value. Perform a replace rather
// than a removal so that the size of the array stays the same. A hidden
// NULL value will not affect processing of the query block.
for (size_t i = 0; i < aggr_query_block->fields.size(); i++) {
if (aggr_query_block->fields[i] == this) {
Item_null *null_item = new Item_null();
null_item->hidden = true;
aggr_query_block->fields[i] = null_item;
break;
}
}
}
return false;
}
/**
@todo Remove this function when rollup wrappers are removed.
Item_func::eq() works for all Item_sum functions.
*/
bool Item_sum::eq(const Item *item) const {
if (this == item) return true;
if (item->type() != type()) return false;
const Item_sum *item_sum = down_cast<const Item_sum *>(item);
const enum Sumfunctype my_sum_func = sum_func();
if (item_sum->sum_func() != my_sum_func || item_sum->m_window != m_window)
return false;
if (is_rollup_sum_wrapper() || item_sum->is_rollup_sum_wrapper()) {
// we want to compare underlying Item_sums
const Item_sum *this_real_sum = unwrap_sum();
const Item_sum *item_real_sum = item_sum->unwrap_sum();
return this_real_sum->eq(item_real_sum);
}
if (arg_count != item_sum->arg_count ||
my_strcasecmp(system_charset_info, func_name(), item_sum->func_name()) ||
!eq_specific(item))
return false;
if (arg_count == 0) return true;
return AllItemsAreEqual(args, item_sum->args, arg_count);
}
bool Item_sum::eq_specific(const Item *item) const {
const Item_sum *item_sum = down_cast<const Item_sum *>(item);
if (item->m_is_window_function != m_is_window_function ||
item_sum->sum_func() != sum_func() || item_sum->m_window != m_window)
return false;
return true;
}
bool Item_sum::aggregate_check_distinct(uchar *arg) {
assert(fixed);
Distinct_check *dc = reinterpret_cast<Distinct_check *>(arg);
if (dc->is_stopped(this)) return false;
/*
In the Standard, ORDER BY cannot contain an aggregate function;
we are less strict, we allow it.
However, if the aggregate in ORDER BY is not in the SELECT list, it
might not be functionally dependent on all selected expressions, and thus
might produce random order in combination with DISTINCT; then we reject
it.
One case where the aggregate is surely functionally dependent on the
selected expressions, is if all GROUP BY expressions are in the SELECT
list. But in that case DISTINCT is redundant and we have removed it in
Query_block::prepare().
*/
if (aggr_query_block == dc->select) return true;
return false;
}
bool Item_sum::aggregate_check_group(uchar *arg) {
assert(fixed);
Group_check *gc = reinterpret_cast<Group_check *>(arg);
if (gc->is_stopped(this)) return false;
if (aggr_query_block != gc->select) {
/*
If aggr_query_block is inner to gc's query_block, this aggregate function
might reference some columns of gc, so we need to analyze its arguments.
If it is outer, analyzing its arguments should not cause a problem, we
will meet outer references which we will ignore.
*/
return false;
}
if (gc->is_fd_on_source(this)) {
gc->stop_at(this);
return false;
}
return true;
}
bool Item_sum::has_aggregate_ref_in_group_by(uchar *) {
/*
We reject references to aggregates in the GROUP BY clause of the
query block where the aggregation happens.
*/
return aggr_query_block != nullptr && aggr_query_block->group_fix_field;
}
Field *Item_sum::create_tmp_field(bool, TABLE *table) {
DBUG_TRACE;
Field *field;
switch (result_type()) {
case REAL_RESULT:
field = new (*THR_MALLOC) Field_double(
max_length, is_nullable(), item_name.ptr(), decimals, false, true);
break;
case INT_RESULT:
field = new (*THR_MALLOC) Field_longlong(max_length, is_nullable(),
item_name.ptr(), unsigned_flag);
break;
case STRING_RESULT:
return make_string_field(table);
case DECIMAL_RESULT:
field = Field_new_decimal::create_from_item(this);
break;
case ROW_RESULT:
default:
// This case should never be chosen
assert(0);
return nullptr;
}
if (field) field->init(table);
return field;
}
bool Item_sum::collect_grouped_aggregates(uchar *arg) {
auto *info = pointer_cast<Collect_grouped_aggregate_info *>(arg);
if (m_is_window_function || info->m_break_off) return false;
if (info->m_query_block == aggr_query_block && is_outer_reference()) {
// This aggregate function aggregates in the transformed query block, but is
// located inside a subquery. Currently, transform cannot get to this since
// it doesn't descend into subqueries. This means we cannot substitute a
// field for this aggregates, so break off. TODO.
info->m_break_off = true;
return false;
}
if (info->m_query_block != aggr_query_block) {
// Aggregated either inside a subquery of the transformed query block or
// outside of it. In either case, ignore it.
info->m_outside = true;
return false;
}
for (auto e : info->list) { // eliminate duplicates
if (e == this) {
return false;
}
}
info->list.emplace_back(this);
return false;
}
Item *Item_sum::replace_aggregate(uchar *arg) {
auto *info = pointer_cast<Item::Aggregate_replacement *>(arg);
if (info->m_target == this)
return info->m_replacement;
else
return this;
}
bool Item_sum::collect_scalar_subqueries(uchar *arg) {
if (!m_is_window_function) {
auto *info = pointer_cast<Collect_scalar_subquery_info *>(arg);
/// Don't walk below grouped aggregate functions
if (info->is_stopped(this)) return false;
info->stop_at(this);
}
return false;
}
bool Item_sum::collect_item_field_or_view_ref_processor(uchar *arg) {
if (!m_is_window_function) {
auto *info = pointer_cast<Collect_item_fields_or_view_refs *>(arg);
/// Don't walk below grouped aggregate functions
if (info->is_stopped(this)) return false;
info->stop_at(this);
}
return false;
}
void Item_sum::update_used_tables() {
/*
When evaluated as a constant value during optimization, there is no reason
to update used tables information, as used_tables() will always report
this item as const.
*/
if (forced_const) return;
used_tables_cache = 0;
// Re-accumulate all properties except three
m_accum_properties &=
(PROP_AGGREGATION | PROP_WINDOW_FUNCTION | PROP_HAS_GROUPING_SET_DEP);
for (uint i = 0; i < arg_count; i++) {
args[i]->update_used_tables();
used_tables_cache |= args[i]->used_tables();
add_accum_properties(args[i]);
}
add_used_tables_for_aggr_func();
}
void Item_sum::fix_after_pullout(Query_block *parent_query_block,
Query_block *removed_query_block) {
// Cannot aggregate into a context that is merged up.
assert(aggr_query_block != removed_query_block);
// We may merge up a query block, if it is not the aggregating query context
if (base_query_block == removed_query_block)
base_query_block = parent_query_block;
// Perform pullout of arguments to aggregate function
used_tables_cache = 0;
Item **arg, **arg_end;
for (arg = args, arg_end = args + arg_count; arg != arg_end; arg++) {
Item *const item = *arg;
item->fix_after_pullout(parent_query_block, removed_query_block);
used_tables_cache |= item->used_tables();
}
// Complete used_tables information by looking at aggregate function
add_used_tables_for_aggr_func();
if (!m_is_window_function) {
for (Query_block *child = base_query_block; child != aggr_query_block;
child = child->outer_query_block()) {
// The subquery on this level is outer-correlated due to the outer
// aggregation. Cf. similar code in Item_ident::fix_after_pullout.
child->master_query_expression()->accumulate_used_tables(
OUTER_REF_TABLE_BIT);
}
}
}
/**
Add used_tables information for aggregate function, based on its aggregated
query block.
If the function is aggregated into its local context, it can
be calculated only after evaluating the full join, thus it
depends on all tables of this join. Otherwise, it depends on
outer tables, even if its arguments args[] do not explicitly
reference an outer table, like COUNT (*) or COUNT(123).
Window functions are always evaluated in the local scope
and depend on all tables involved in the join since they cannot
be evaluated until after the join is completed.
*/
void Item_sum::add_used_tables_for_aggr_func() {
used_tables_cache |=
aggr_query_block == base_query_block || m_is_window_function
? base_query_block->all_tables_map()
: OUTER_REF_TABLE_BIT;
/*
Aggregate functions are not allowed to be const, so if there are no tables
to depend them on, ensure they are executed anyway:
*/
if (const_for_execution()) used_tables_cache |= RAND_TABLE_BIT;
}
Item *Item_sum::set_arg(THD *thd, uint i, Item *new_val) {
thd->change_item_tree(args + i, new_val);
return new_val;
}
int Item_sum::set_aggregator(Aggregator::Aggregator_type aggregator) {
/*
Dependent subselects may be executed multiple times, making
set_aggregator to be called multiple times. The aggregator type
will be the same, but it needs to be reset so that it is
reevaluated with the new dependent data.
This function may also be called multiple times during query optimization.
In this case, the type may change, so we delete the old aggregator,
and create a new one.
*/
if (aggr && aggregator == aggr->Aggrtype()) {
aggr->clear();
return false;
}
if (aggr != nullptr) {
::destroy_at(aggr);
aggr = nullptr;
}
switch (aggregator) {
case Aggregator::DISTINCT_AGGREGATOR:
aggr = new (*THR_MALLOC) Aggregator_distinct(this);
break;
case Aggregator::SIMPLE_AGGREGATOR:
aggr = new (*THR_MALLOC) Aggregator_simple(this);
break;
};
return aggr ? false : true;
}
void Item_sum::cleanup() {
if (aggr != nullptr) {
::destroy_at(aggr);
aggr = nullptr;
}
Item_result_field::cleanup();
// forced_const may have been set during optimization, reset it:
forced_const = false;
m_null_executed = false;
}
bool Item_sum::fix_fields(THD *thd, Item **ref [[maybe_unused]]) {
assert(!fixed);
if (m_window != nullptr) {
if (m_window_resolved) return false;
if (Window::resolve_reference(thd, this, &m_window)) return true;
m_window_resolved = true;
}
return false;
}
bool Item_sum::split_sum_func(THD *thd, Ref_item_array ref_item_array,
mem_root_deque<Item *> *fields) {
if (!m_is_window_function) return false;
for (auto &it : Bounds_checked_array<Item *>(args, arg_count)) {
if (it->split_sum_func2(thd, ref_item_array, fields, &it, true)) {
return true;
}
}
return false;
}
bool Item_sum::reset_wf_state(uchar *arg) {
if (!m_is_window_function) return false;
DBUG_TRACE;
bool *do_framing = (bool *)arg;
if (*do_framing) {
if (framing()) clear();
} else {
if (!framing()) clear();
}
return false;
}
bool Item_sum::wf_common_init() {
if (m_window->do_copy_null()) {
assert(m_window->needs_buffering());
null_value = is_nullable();
return true;
}
if (m_window->at_partition_border() && !m_window->needs_buffering()) {
clear();
}
return false;
}
/**
Compare keys consisting of single field that cannot be compared as binary.
Used by the Unique class to compare keys. Will do correct comparisons
for all field types.
@param arg Pointer to the relevant Field class instance
@param a left key image
@param b right key image
@return comparison result
@retval < 0 if key1 < key2
@retval = 0 if key1 = key2
@retval > 0 if key1 > key2
*/
static int simple_generic_key_cmp(const void *arg, const void *a,
const void *b) {
const Field *f = pointer_cast<const Field *>(arg);
const uchar *key1 = pointer_cast<const uchar *>(a);
const uchar *key2 = pointer_cast<const uchar *>(b);
return f->cmp(key1, key2);
}
/**
Correctly compare composite keys.
Used by the Unique class to compare keys. Will do correct comparisons
for composite keys with various field types.
@param arg Pointer to the relevant Aggregator_distinct instance
@param a left key image
@param b right key image
@return comparison result
@retval <0 if key1 < key2
@retval =0 if key1 = key2
@retval >0 if key1 > key2
*/
int Aggregator_distinct::composite_key_cmp(const void *arg, const void *a,
const void *b) {
const Aggregator_distinct *aggr =
static_cast<const Aggregator_distinct *>(arg);