-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathitem_func.cc
10215 lines (8832 loc) · 320 KB
/
item_func.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
This file defines all numerical Items
*/
#include "sql/item_func.h"
#include <algorithm>
#include <atomic>
#include <bit>
#include <cfloat> // DBL_DIG
#include <cmath> // std::log2
#include <cstdio>
#include <cstring>
#include <ctime>
#include <initializer_list>
#include <iosfwd>
#include <limits> // std::numeric_limits
#include <memory>
#include <new>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include "integer_digits.h"
#include "m_string.h"
#include "map_helpers.h"
#include "mutex_lock.h" // MUTEX_LOCK
#include "my_bitmap.h"
#include "my_byteorder.h"
#include "my_dbug.h"
#include "my_double2ulonglong.h"
#include "my_hostname.h"
#include "my_psi_config.h"
#include "my_rnd.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "my_systime.h"
#include "my_thread.h"
#include "my_user.h" // parse_user
#include "mysql/components/services/bits/mysql_cond_bits.h"
#include "mysql/components/services/bits/mysql_mutex_bits.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/components/services/bits/psi_mutex_bits.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/components/services/log_shared.h"
#include "mysql/my_loglevel.h"
#include "mysql/mysql_lex_string.h"
#include "mysql/plugin_audit.h"
#include "mysql/psi/mysql_cond.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysql/service_mysql_password_policy.h"
#include "mysql/service_thd_wait.h"
#include "mysql/status_var.h"
#include "mysql/strings/dtoa.h"
#include "mysql/strings/int2str.h"
#include "mysql/strings/m_ctype.h"
#include "mysql/strings/my_strtoll10.h"
#include "prealloced_array.h"
#include "sql-common/json_dom.h" // Json_wrapper
#include "sql/auth/auth_acls.h"
#include "sql/auth/auth_common.h" // check_password_strength
#include "sql/auth/sql_security_ctx.h"
#include "sql/binlog.h" // mysql_bin_log
#include "sql/check_stack.h"
#include "sql/current_thd.h" // current_thd
#include "sql/dd/info_schema/table_stats.h" // dd::info_schema::Table_stati...
#include "sql/dd/info_schema/tablespace_stats.h" // dd::info_schema::Tablesp...
#include "sql/dd/object_id.h"
#include "sql/dd/properties.h" // dd::Properties
#include "sql/dd/types/abstract_table.h"
#include "sql/dd/types/column.h"
#include "sql/dd/types/index.h" // Index::enum_index_type
#include "sql/dd_sql_view.h" // push_view_warning_or_error
#include "sql/dd_table_share.h" // dd_get_old_field_type
#include "sql/debug_sync.h" // DEBUG_SYNC
#include "sql/derror.h" // ER_THD
#include "sql/error_handler.h" // Internal_error_handler
#include "sql/item.h" // Item_json
#include "sql/item_cmpfunc.h" // get_datetime_value
#include "sql/item_json_func.h" // get_json_wrapper
#include "sql/item_strfunc.h" // Item_func_concat_ws
#include "sql/item_subselect.h" // Item_subselect
#include "sql/key.h"
#include "sql/log_event.h" // server_version
#include "sql/mdl.h"
#include "sql/mysqld.h" // log_10 stage_user_sleep
#include "sql/parse_tree_helpers.h" // PT_item_list
#include "sql/parse_tree_node_base.h" // Parse_context
#include "sql/protocol.h"
#include "sql/psi_memory_key.h"
#include "sql/resourcegroups/resource_group.h"
#include "sql/resourcegroups/resource_group_basic_types.h"
#include "sql/resourcegroups/resource_group_mgr.h"
#include "sql/rpl_gtid.h"
#include "sql/rpl_mi.h" // Master_info
#include "sql/rpl_msr.h" // channel_map
#include "sql/rpl_rli.h" // Relay_log_info
#include "sql/sp.h" // sp_setup_routine
#include "sql/sp_head.h" // sp_name
#include "sql/sp_pcontext.h" // sp_variable
#include "sql/sql_array.h" // just to keep clang happy
#include "sql/sql_audit.h" // audit_global_variable
#include "sql/sql_base.h" // Internal_error_handler_holder
#include "sql/sql_bitmap.h"
#include "sql/sql_class.h" // THD
#include "sql/sql_cmd.h"
#include "sql/sql_derived.h" // Condition_pushdown
#include "sql/sql_error.h"
#include "sql/sql_exchange.h" // sql_exchange
#include "sql/sql_executor.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_load.h" // Sql_cmd_load_table
#include "sql/sql_optimizer.h" // JOIN
#include "sql/sql_parse.h" // check_stack_overrun
#include "sql/sql_show.h" // append_identifier_*
#include "sql/sql_time.h" // TIME_from_longlong_packed
#include "sql/strfunc.h" // find_type
#include "sql/system_variables.h"
#include "sql/thd_raii.h"
#include "sql/val_int_compare.h" // Integer_value
#include "sql_string.h"
#include "storage/perfschema/terminology_use_previous_enum.h"
#include "string_with_len.h"
#include "template_utils.h"
#include "template_utils.h" // pointer_cast
#include "thr_mutex.h"
#include "vector-common/vector_constants.h" // get_dimensions
using std::max;
using std::min;
static void free_user_var(user_var_entry *entry) { entry->destroy(); }
static int get_var_with_binlog(THD *thd, enum_sql_command sql_command,
const Name_string &name,
user_var_entry **out_entry);
bool check_reserved_words(const char *name) {
if (!my_strcasecmp(system_charset_info, name, "GLOBAL") ||
!my_strcasecmp(system_charset_info, name, "LOCAL") ||
!my_strcasecmp(system_charset_info, name, "SESSION"))
return true;
return false;
}
void report_conversion_error(const CHARSET_INFO *to_cs, const char *from,
size_t from_length, const CHARSET_INFO *from_cs) {
char printable_buff[32];
convert_to_printable(printable_buff, sizeof(printable_buff), from,
from_length, from_cs, 6);
const char *from_name = from_cs->csname;
const char *to_name = to_cs->csname;
my_error(ER_CANNOT_CONVERT_STRING, MYF(0), printable_buff, from_name,
to_name);
}
/**
Simplify the string arguments to a function, if possible.
Currently used to substitute const values with character strings
in the desired character set. Only used during resolving.
@param thd thread handler
@param c Desired character set and collation
@param args Pointer to argument array
@param nargs Number of arguments to process
@returns false if success, true if error
*/
bool simplify_string_args(THD *thd, const DTCollation &c, Item **args,
uint nargs) {
// Only used during resolving
assert(!thd->lex->is_exec_started());
if (thd->lex->is_view_context_analysis()) return false;
uint i;
Item **arg;
for (i = 0, arg = args; i < nargs; i++, arg++) {
size_t dummy_offset;
// Only convert const values.
if (!(*arg)->const_item()) continue;
if (!String::needs_conversion(1, (*arg)->collation.collation, c.collation,
&dummy_offset))
continue;
StringBuffer<STRING_BUFFER_USUAL_SIZE> original;
StringBuffer<STRING_BUFFER_USUAL_SIZE> converted;
String *ostr = (*arg)->val_str(&original);
if (ostr == nullptr) {
if (thd->is_error()) return true;
*arg = new (thd->mem_root) Item_null;
if (*arg == nullptr) return true;
continue;
}
uint conv_status;
converted.copy(ostr->ptr(), ostr->length(), ostr->charset(), c.collation,
&conv_status);
if (conv_status != 0) {
report_conversion_error(c.collation, ostr->ptr(), ostr->length(),
ostr->charset());
return true;
}
// If source is a binary string, the string may have to be validated:
if (c.collation != &my_charset_bin && ostr->charset() == &my_charset_bin &&
!converted.is_valid_string(c.collation)) {
report_conversion_error(c.collation, ostr->ptr(), ostr->length(),
ostr->charset());
return true;
}
char *ptr = thd->strmake(converted.ptr(), converted.length());
if (ptr == nullptr) return true;
Item *conv = new (thd->mem_root)
Item_string(ptr, converted.length(), converted.charset(), c.derivation);
if (conv == nullptr) return true;
*arg = conv;
assert(conv->fixed);
}
return false;
}
/**
Evaluate an argument string and return it in the desired character set.
Perform character set conversion if needed.
Perform character set validation (from a binary string) if needed.
@param to_cs The desired character set
@param arg Argument to evaluate as a string value
@param buffer String buffer where argument is evaluated, if necessary
@returns string pointer if success, NULL if error or NULL value
*/
String *eval_string_arg_noinline(const CHARSET_INFO *to_cs, Item *arg,
String *buffer) {
size_t offset;
const bool convert =
String::needs_conversion(0, arg->collation.collation, to_cs, &offset);
if (convert) {
StringBuffer<STRING_BUFFER_USUAL_SIZE> local_string(nullptr, 0, to_cs);
String *res = arg->val_str(&local_string);
// Return immediately if argument is a NULL value, or there was an error
if (res == nullptr) return nullptr;
/*
String must be converted from source character set. It has been built
in the "local_string" buffer and will be copied with conversion into the
caller provided buffer.
*/
uint errors = 0;
buffer->length(0);
buffer->copy(res->ptr(), res->length(), res->charset(), to_cs, &errors);
if (errors) {
report_conversion_error(to_cs, res->ptr(), res->length(), res->charset());
return nullptr;
}
return buffer;
}
String *res = arg->val_str(buffer);
// Return immediately if argument is a NULL value, or there was an error
if (res == nullptr) return nullptr;
// If source is a binary string, the string may have to be validated:
if (to_cs != &my_charset_bin && arg->collation.collation == &my_charset_bin &&
!res->is_valid_string(to_cs)) {
report_conversion_error(to_cs, res->ptr(), res->length(), res->charset());
return nullptr;
}
// Adjust target character set to the desired value
res->set_charset(to_cs);
return res;
}
/**
Evaluate a constant condition, represented by an Item tree
@param thd Thread handler
@param cond The constant condition to evaluate
@param[out] value Returned value, either true or false
@returns false if evaluation is successful, true otherwise
*/
bool eval_const_cond(THD *thd, Item *cond, bool *value) {
// Function may be used both during resolving and during optimization:
assert(cond->may_evaluate_const(thd));
*value = cond->val_bool();
return thd->is_error();
}
/**
Test if the sum of arguments overflows the ulonglong range.
*/
static inline bool test_if_sum_overflows_ull(ulonglong arg1, ulonglong arg2) {
return ULLONG_MAX - arg1 < arg2;
}
bool Item_func::set_arguments(mem_root_deque<Item *> *list, bool context_free) {
allowed_arg_cols = 1;
if (alloc_args(*THR_MALLOC, list->size())) return true;
std::copy(list->begin(), list->end(), args);
if (!context_free) {
for (const Item *arg : make_array(args, arg_count)) {
add_accum_properties(arg);
}
}
list->clear(); // Fields are used
return false;
}
Item_func::Item_func(const POS &pos, PT_item_list *opt_list)
: Item_result_field(pos), allowed_arg_cols(1) {
if (opt_list == nullptr) {
args = m_embedded_arguments;
arg_count = 0;
} else
set_arguments(&opt_list->value, true);
}
Item_func::Item_func(THD *thd, const Item_func *item)
: Item_result_field(thd, item),
null_on_null(item->null_on_null),
allowed_arg_cols(item->allowed_arg_cols),
used_tables_cache(item->used_tables_cache),
not_null_tables_cache(item->not_null_tables_cache) {
if (alloc_args(thd->mem_root, item->arg_count)) return;
std::copy_n(item->args, arg_count, args);
}
bool Item_func::do_itemize(Parse_context *pc, Item **res) {
if (skip_itemize(res)) return false;
if (Item_result_field::do_itemize(pc, res)) return true;
const bool no_named_params = !may_have_named_parameters();
for (size_t i = 0; i < arg_count; i++) {
if (args[i]->itemize(pc, &args[i])) return true;
add_accum_properties(args[i]);
if (no_named_params && !args[i]->item_name.is_autogenerated()) {
my_error(functype() == FUNC_SP ? ER_WRONG_PARAMETERS_TO_STORED_FCT
: ER_WRONG_PARAMETERS_TO_NATIVE_FCT,
MYF(0), func_name());
return true;
}
}
return false;
}
/*
Resolve references to table column for a function and its argument
SYNOPSIS:
fix_fields()
thd Thread object
DESCRIPTION
Call fix_fields() for all arguments to the function. The main intention
is to allow all Item_field() objects to setup pointers to the table fields.
Sets as a side effect the following class variables:
maybe_null Set if any argument may return NULL
used_tables_cache Set to union of the tables used by arguments
str_value.charset If this is a string function, set this to the
character set for the first argument.
If any argument is binary, this is set to binary
If for any item any of the defaults are wrong, then this can
be fixed in the resolve_type() function that is called after this one or
by writing a specialized fix_fields() for the item.
RETURN VALUES
false ok
true Got error. Stored with my_error().
*/
bool Item_func::fix_fields(THD *thd, Item **) {
assert(!fixed || basic_const_item());
Item **arg, **arg_end;
uchar buff[STACK_BUFF_ALLOC]; // Max argument in function
const Condition_context CCT(thd->lex->current_query_block());
used_tables_cache = get_initial_pseudo_tables();
not_null_tables_cache = 0;
/*
Use stack limit of STACK_MIN_SIZE * 2 since
on some platforms a recursive call to fix_fields
requires more than STACK_MIN_SIZE bytes (e.g. for
MIPS, it takes about 22kB to make one recursive
call to Item_func::fix_fields())
*/
if (check_stack_overrun(thd, STACK_MIN_SIZE * 2, buff))
return true; // Fatal error if flag is set!
if (arg_count) { // Print purify happy
for (arg = args, arg_end = args + arg_count; arg != arg_end; arg++) {
if (fix_func_arg(thd, arg)) return true;
}
}
if (resolve_type(thd) || thd->is_error()) // Some impls still not error-safe
return true;
fixed = true;
return false;
}
bool Item_func::fix_func_arg(THD *thd, Item **arg) {
if ((!(*arg)->fixed && (*arg)->fix_fields(thd, arg)))
return true; /* purecov: inspected */
Item *item = *arg;
if (allowed_arg_cols) {
if (item->check_cols(allowed_arg_cols)) return true;
} else {
/* we have to fetch allowed_arg_cols from first argument */
assert(arg == args); // it is first argument
allowed_arg_cols = item->cols();
assert(allowed_arg_cols); // Can't be 0 any more
}
set_nullable(is_nullable() || item->is_nullable());
used_tables_cache |= item->used_tables();
if (null_on_null) not_null_tables_cache |= item->not_null_tables();
add_accum_properties(item);
return false;
}
void Item_func::fix_after_pullout(Query_block *parent_query_block,
Query_block *removed_query_block) {
if (const_item()) {
/*
Pulling out a const item changes nothing to it. Moreover, some items may
have decided that they're const by some other logic than the generic
one below, and we must preserve that decision.
*/
return;
}
Item **arg, **arg_end;
used_tables_cache = get_initial_pseudo_tables();
not_null_tables_cache = 0;
if (arg_count) {
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();
if (null_on_null) not_null_tables_cache |= item->not_null_tables();
}
}
}
/**
Default implementation for all functions:
Propagate base_item's type into all arguments.
The functions that have context-aware parameter type detection must
implement Item::default_data_type() and Item::resolve_type_inner().
If an SQL function or operator F embeds another SQL function or
operator G: F::fix_fields() runs and calls G::fix_fields() which calls
G::resolve_type(); assuming that G is outer-context dependent and has only
dynamic parameters as arguments, G misses type information and thus does a
no-op resolve_type(); then F::fix_fields() continues and calls
F::resolve_type() which sees that G::data_type() == MYSQL_TYPE_INVALID;
F thus calls G::propagate_type() to send it the necessary type
information (i.e. provide the outer context); this then assigns the type
to dynamic parameters of G and finishes the job of G::resolve_type() by
calling G::resolve_type_inner().
*/
bool Item_func::propagate_type(THD *thd, const Type_properties &type) {
assert(data_type() == MYSQL_TYPE_INVALID);
for (uint i = 0; i < arg_count; i++) {
if (args[i]->data_type() == MYSQL_TYPE_INVALID)
if (args[i]->propagate_type(thd, type)) return true;
}
if (resolve_type_inner(thd)) return true;
assert(data_type() != MYSQL_TYPE_INVALID);
return false;
}
/**
For arguments of this Item_func ("args" array), in range
[start, start+step, start+2*step,...,end[ : if they're a PS
parameter with invalid (not known) type, give them default type "def".
@param thd thread handler
@param start range's start (included)
@param end range's end (excluded)
@param step range's step
@param def default type
@returns false if success, true if error
*/
bool Item_func::param_type_is_default(THD *thd, uint start, uint end, uint step,
enum_field_types def) {
for (uint i = start; i < end; i += step) {
if (i >= arg_count) break;
if (args[i]->propagate_type(thd, def)) return true;
}
return false;
}
/**
For arguments of this Item_func ("args" array), in range [start,end[ :
sends error if they're a dynamic parameter.
@param start range's start (included)
@param end range's end (excluded)
@returns true if error.
*/
bool Item_func::param_type_is_rejected(uint start, uint end) {
for (uint i = start; i < end; i++) {
if (i >= arg_count) break;
if (args[i]->data_type() == MYSQL_TYPE_INVALID) {
my_error(ER_INVALID_PARAMETER_USE, MYF(0), "?");
return true;
}
}
return false;
}
/**
For arguments of this Item_func ("args" array), all of them: find an
argument that is not a dynamic parameter; if found, all dynamic parameters
without a valid type get the type of this; if not found, they get type "def".
@param thd thread handler
@param arg_count number of arguments to check
@param args array of arguments, size 'arg_count'
@param def default type
@returns false if success, true if error
*/
inline bool param_type_uses_non_param_inner(THD *thd, uint arg_count,
Item **args, enum_field_types def) {
// Use first non-parameter type as base item
// @todo If there are multiple non-parameter items, we could use a
// consolidated type instead of the first one (consider CASE, COALESCE,
// BETWEEN).
const uint col_cnt = args[0]->cols();
if (col_cnt > 1) {
/*
Row or subquery object: set parameter type recursively for the ith
Item in each argument row.
*/
Item **arguments = new (*THR_MALLOC) Item *[arg_count];
for (uint i = 0; i < col_cnt; i++) {
for (uint j = 0; j < arg_count; j++) {
if (args[j]->cols() != col_cnt) // Column count not checked yet
return false;
if (args[j]->type() == Item::ROW_ITEM)
arguments[j] = down_cast<Item_row *>(args[j])->element_index(i);
else if (args[j]->type() == Item::SUBQUERY_ITEM)
arguments[j] = (*down_cast<Item_subselect *>(args[j])
->query_expr()
->get_unit_column_types())[i];
}
if (param_type_uses_non_param_inner(thd, arg_count, arguments, def))
return true;
}
// Resolving for row done, set data type to MYSQL_TYPE_NULL as final action.
for (uint j = 0; j < arg_count; j++)
args[j]->set_data_type(MYSQL_TYPE_NULL);
return false;
}
Item *base_item = nullptr;
for (uint i = 0; i < arg_count; i++) {
if (args[i]->data_type() != MYSQL_TYPE_INVALID) {
base_item = args[i];
break;
}
}
if (base_item == nullptr) {
if (args[0]->propagate_type(thd, def)) return true;
base_item = args[0];
}
for (uint i = 0; i < arg_count; i++) {
if (args[i]->data_type() != MYSQL_TYPE_INVALID) continue;
if (args[i]->propagate_type(thd, Type_properties(*base_item))) return true;
}
return false;
}
bool Item_func::param_type_uses_non_param(THD *thd, enum_field_types def) {
if (arg_count == 0) return false;
return param_type_uses_non_param_inner(thd, arg_count, args, def);
}
Item *Item_func::replace_func_call(uchar *arg) {
auto *info = pointer_cast<Item::Item_func_call_replacement *>(arg);
if (eq(info->m_target)) {
assert(info->m_curr_block == info->m_trans_block);
return info->m_item;
}
return this;
}
bool Item_func::walk(Item_processor processor, enum_walk walk,
uchar *argument) {
if ((walk & enum_walk::PREFIX) && (this->*processor)(argument)) return true;
Item **arg, **arg_end;
for (arg = args, arg_end = args + arg_count; arg != arg_end; arg++) {
if ((*arg)->walk(processor, walk, argument)) return true;
}
return (walk & enum_walk::POSTFIX) && (this->*processor)(argument);
}
void Item_func::traverse_cond(Cond_traverser traverser, void *argument,
traverse_order order) {
if (arg_count) {
Item **arg, **arg_end;
switch (order) {
case (PREFIX):
(*traverser)(this, argument);
for (arg = args, arg_end = args + arg_count; arg != arg_end; arg++) {
(*arg)->traverse_cond(traverser, argument, order);
}
break;
case (POSTFIX):
for (arg = args, arg_end = args + arg_count; arg != arg_end; arg++) {
(*arg)->traverse_cond(traverser, argument, order);
}
(*traverser)(this, argument);
}
} else
(*traverser)(this, argument);
}
/**
Transform an Item_func object with a transformer callback function.
The function recursively applies the transform method to each
argument of the Item_func node.
If the call of the method for an argument item returns a new item
the old item is substituted for a new one.
After this the transformer is applied to the root node
of the Item_func object.
*/
Item *Item_func::transform(Item_transformer transformer, uchar *argument) {
if (arg_count) {
Item **arg, **arg_end;
for (arg = args, arg_end = args + arg_count; arg != arg_end; arg++) {
*arg = (*arg)->transform(transformer, argument);
if (*arg == nullptr) return nullptr; /* purecov: inspected */
}
}
return (this->*transformer)(argument);
}
/**
Compile Item_func object with a processor and a transformer
callback functions.
First the function applies the analyzer to the root node of
the Item_func object. Then if the analyzer succeeeds (returns true)
the function recursively applies the compile method to each argument
of the Item_func node.
If the call of the method for an argument item returns a new item
the old item is substituted for a new one.
After this the transformer is applied to the root node
of the Item_func object.
*/
Item *Item_func::compile(Item_analyzer analyzer, uchar **arg_p,
Item_transformer transformer, uchar *arg_t) {
if (!(this->*analyzer)(arg_p)) return this;
if (arg_count) {
Item **arg, **arg_end;
for (arg = args, arg_end = args + arg_count; arg != arg_end; arg++) {
/*
The same parameter value of arg_p must be passed
to analyze any argument of the condition formula.
*/
uchar *arg_v = *arg_p;
Item *new_item = (*arg)->compile(analyzer, &arg_v, transformer, arg_t);
if (new_item == nullptr) return nullptr;
if (*arg != new_item) current_thd->change_item_tree(arg, new_item);
}
}
return (this->*transformer)(arg_t);
}
/**
See comments in Item_cmp_func::split_sum_func()
*/
bool Item_func::split_sum_func(THD *thd, Ref_item_array ref_item_array,
mem_root_deque<Item *> *fields) {
Item **arg, **arg_end;
for (arg = args, arg_end = args + arg_count; arg != arg_end; arg++) {
if ((*arg)->split_sum_func2(thd, ref_item_array, fields, arg, true)) {
return true;
}
}
return false;
}
void Item_func::update_used_tables() {
used_tables_cache = get_initial_pseudo_tables();
not_null_tables_cache = 0;
// Reset all flags except Grouping Set dependency
m_accum_properties &= 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();
if (null_on_null) not_null_tables_cache |= args[i]->not_null_tables();
add_accum_properties(args[i]);
}
}
void Item_func::print(const THD *thd, String *str,
enum_query_type query_type) const {
str->append(func_name());
str->append('(');
print_args(thd, str, 0, query_type);
str->append(')');
}
void Item_func::print_args(const THD *thd, String *str, uint from,
enum_query_type query_type) const {
for (uint i = from; i < arg_count; i++) {
if (i != from) str->append(',');
args[i]->print(thd, str, query_type);
}
}
void Item_func::print_op(const THD *thd, String *str,
enum_query_type query_type) const {
str->append('(');
for (uint i = 0; i < arg_count - 1; i++) {
args[i]->print(thd, str, query_type);
str->append(' ');
str->append(func_name());
str->append(' ');
}
args[arg_count - 1]->print(thd, str, query_type);
str->append(')');
}
bool Item_func::eq(const Item *item) const {
if (this == item) return true;
if (item->type() != type()) return false;
const Item_func::Functype func_type = functype();
const Item_func *func = down_cast<const Item_func *>(item);
/*
Note: most function names are in ASCII character set, however stored
functions and UDFs return names in system character set,
therefore the comparison is performed using this character set.
*/
return func_type == func->functype() && arg_count == func->arg_count &&
!my_strcasecmp(system_charset_info, func_name(), func->func_name()) &&
(arg_count == 0 || AllItemsAreEqual(args, func->args, arg_count)) &&
eq_specific(item);
}
Field *Item_func::tmp_table_field(TABLE *table) {
Field *field = nullptr;
switch (result_type()) {
case INT_RESULT:
if (this->data_type() == MYSQL_TYPE_YEAR)
field = new (*THR_MALLOC) Field_year(is_nullable(), item_name.ptr());
else if (max_length > MY_INT32_NUM_DECIMAL_DIGITS)
field = new (*THR_MALLOC) Field_longlong(
max_length, is_nullable(), item_name.ptr(), unsigned_flag);
else
field = new (*THR_MALLOC) Field_long(max_length, is_nullable(),
item_name.ptr(), unsigned_flag);
break;
case REAL_RESULT:
if (this->data_type() == MYSQL_TYPE_FLOAT) {
field = new (*THR_MALLOC)
Field_float(max_char_length(), is_nullable(), item_name.ptr(),
decimals, unsigned_flag);
} else {
field = new (*THR_MALLOC)
Field_double(max_char_length(), is_nullable(), item_name.ptr(),
decimals, unsigned_flag);
}
break;
case STRING_RESULT:
return make_string_field(table);
break;
case DECIMAL_RESULT:
field = Field_new_decimal::create_from_item(this);
break;
case ROW_RESULT:
default:
// This case should never be chosen
assert(0);
field = nullptr;
break;
}
if (field) field->init(table);
return field;
}
my_decimal *Item_func::val_decimal(my_decimal *decimal_value) {
assert(fixed);
longlong nr = val_int();
if (null_value) return nullptr; /* purecov: inspected */
if (current_thd->is_error()) return error_decimal(decimal_value);
int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
return decimal_value;
}
String *Item_real_func::val_str(String *str) {
assert(fixed);
double nr = val_real();
if (null_value) return nullptr; /* purecov: inspected */
if (current_thd->is_error()) return error_str();
str->set_real(nr, decimals, collation.collation);
return str;
}
my_decimal *Item_real_func::val_decimal(my_decimal *decimal_value) {
assert(fixed);
double nr = val_real();
if (null_value) return nullptr; /* purecov: inspected */
double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
return decimal_value;
}
void Item_func::fix_num_length_and_dec() {
uint fl_length = 0;
decimals = 0;
for (uint i = 0; i < arg_count; i++) {
decimals = max(decimals, args[i]->decimals);
fl_length = max(fl_length, args[i]->max_length);
}
max_length = float_length(decimals);
if (fl_length > max_length) {
decimals = DECIMAL_NOT_SPECIFIED;
max_length = float_length(DECIMAL_NOT_SPECIFIED);
}
}
void Item_func_numhybrid::fix_num_length_and_dec() {}
void Item_func::signal_divide_by_null() {
THD *thd = current_thd;
if (thd->variables.sql_mode & MODE_ERROR_FOR_DIVISION_BY_ZERO)
push_warning(thd, Sql_condition::SL_WARNING, ER_DIVISION_BY_ZERO,
ER_THD(thd, ER_DIVISION_BY_ZERO));
null_value = true;
}
void Item_func::signal_invalid_argument_for_log() {
THD *thd = current_thd;
push_warning(thd, Sql_condition::SL_WARNING,
ER_INVALID_ARGUMENT_FOR_LOGARITHM,
ER_THD(thd, ER_INVALID_ARGUMENT_FOR_LOGARITHM));
null_value = true;
}
Item *Item_func::get_tmp_table_item(THD *thd) {
DBUG_TRACE;
/*
For items with aggregate functions, return the copy
of the function.
For constant items, return the same object, as fields
are not created in temp tables for them.
For items with windowing functions, return the same
object (temp table fields are not created for windowing
functions if they are not evaluated at this stage).
*/
if (!has_aggregation() && !has_wf() &&
!(const_for_execution() &&
evaluate_during_optimization(this, thd->lex->current_query_block()))) {
Item *result = new Item_field(result_field);
return result;
}
Item *result = copy_or_same(thd);
return result;
}
const Item_field *Item_func::contributes_to_filter(
THD *thd, table_map read_tables, table_map filter_for_table,
const MY_BITMAP *fields_to_ignore) const {
// We are loth to change existing plans. Therefore we keep the existing
// behavior for the original optimizer, which is to return nullptr if
// any of PSEUDO_TABLE_BITS are set in used_tables().
const table_map remaining_tables = thd->lex->using_hypergraph_optimizer()
? (~read_tables & ~PSEUDO_TABLE_BITS)
: ~read_tables;
assert((read_tables & filter_for_table) == 0);
/*
Multiple equality (Item_multi_eq) should not call this function
because it would reject valid comparisons.
*/
assert(functype() != MULTI_EQ_FUNC);
/*
To contribute to filtering effect, the condition must refer to
exactly one unread table: the table filtering is currently
calculated for.
*/
if ((used_tables() & remaining_tables) != filter_for_table) return nullptr;
/*
Whether or not this Item_func has an operand that is a field in
'filter_for_table' that is not in 'fields_to_ignore'.
*/
Item_field *usable_field = nullptr;
/*
Whether or not this Item_func has an operand that can be used as
available value. arg_count==1 for Items with implicit values like
"field IS NULL".
*/
bool found_comparable = (arg_count == 1);
for (uint i = 0; i < arg_count; i++) {
const Item::Type arg_type = args[i]->real_item()->type();
if (arg_type == Item::SUBQUERY_ITEM) {
if (args[i]->const_for_execution()) {
// Constant subquery, i.e., not a dependent subquery.
found_comparable = true;
continue;
}
/*
This is either "fld OP <dependent_subquery>" or "fld BETWEEN X
and Y" where either X or Y is a dependent subquery. Filtering
effect should not be calculated for this item because the cost
of evaluating the dependent subquery is currently not
calculated and its accompanying filtering effect is too
uncertain. See WL#7384.
*/
return nullptr;
} // ... if subquery.
const table_map used_tabs = args[i]->used_tables();
if (arg_type == Item::FIELD_ITEM && (used_tabs == filter_for_table)) {
/*
The qualifying table of args[i] is filter_for_table. args[i]
may be a field or a reference to a field, e.g. through a
view.
*/
Item_field *fld = static_cast<Item_field *>(args[i]->real_item());
/*
Use args[i] as value if
1) this field shall be ignored, or
2) a usable field has already been found (meaning that
this is "filter_for_table.colX OP filter_for_table.colY").
*/
if (bitmap_is_set(fields_to_ignore, fld->field->field_index()) || // 1)
usable_field) // 2)
{
found_comparable = true;
continue;
}
/*
This field shall contribute to filtering effect if a
value is found for it
*/
usable_field = fld;