MySQL 8.3.0
Source Code Documentation
item.h
Go to the documentation of this file.
1#ifndef ITEM_INCLUDED
2#define ITEM_INCLUDED
3
4/* Copyright (c) 2000, 2023, Oracle and/or its affiliates.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License, version 2.0,
8 as published by the Free Software Foundation.
9
10 This program is also distributed with certain software (including
11 but not limited to OpenSSL) that is licensed under separate terms,
12 as designated in a particular file or component or in included license
13 documentation. The authors of MySQL hereby grant you an additional
14 permission to link the program and your derivative works with the
15 separately licensed software that they have included with MySQL.
16
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License, version 2.0, for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
25
26#include <sys/types.h>
27
28#include <cfloat>
29#include <climits>
30#include <cmath>
31#include <cstdio>
32#include <cstring>
33#include <memory>
34#include <new>
35#include <optional>
36#include <string>
37#include <type_traits>
38#include <vector>
39
40#include "decimal.h"
41#include "field_types.h" // enum_field_types
42#include "lex_string.h"
43#include "memory_debugging.h"
44#include "my_alloc.h"
45#include "my_bitmap.h"
46#include "my_compiler.h"
47#include "my_dbug.h"
48#include "my_double2ulonglong.h"
49#include "my_inttypes.h"
50#include "my_sys.h"
51#include "my_table_map.h"
52#include "my_time.h"
53#include "mysql/strings/dtoa.h"
57#include "mysql_com.h"
58#include "mysql_time.h"
59#include "mysqld_error.h"
60#include "nulls.h"
61#include "sql-common/my_decimal.h" // my_decimal
62#include "sql/enum_query_type.h"
63#include "sql/field.h" // Derivation
64#include "sql/mem_root_array.h"
65#include "sql/parse_location.h" // POS
66#include "sql/parse_tree_node_base.h" // Parse_tree_node
67#include "sql/sql_array.h" // Bounds_checked_array
68#include "sql/sql_const.h"
69#include "sql/sql_list.h"
70#include "sql/table.h"
71#include "sql/table_trigger_field_support.h" // Table_trigger_field_support
72#include "sql/thr_malloc.h"
73#include "sql/trigger_def.h" // enum_trigger_variable_type
74#include "sql_string.h"
75#include "string_with_len.h"
76#include "template_utils.h"
77
78class Item;
79class Item_field;
80class Item_func;
82class Item_sum;
83class Json_wrapper;
84class Protocol;
85class Query_block;
87class THD;
88class user_var_entry;
89struct TYPELIB;
90
92
93void item_init(void); /* Init item functions */
94
95/**
96 Default condition filtering (selectivity) values used by
97 get_filtering_effect() and friends when better estimates
98 (statistics) are not available for a predicate.
99*/
100/**
101 For predicates that are always satisfied. Must be 1.0 or the filter
102 calculation logic will break down.
103*/
104constexpr float COND_FILTER_ALLPASS{1.0f};
105/// Filtering effect for equalities: col1 = col2
106constexpr float COND_FILTER_EQUALITY{0.1f};
107/// Filtering effect for inequalities: col1 > col2
108constexpr float COND_FILTER_INEQUALITY{0.3333f};
109/// Filtering effect for between: col1 BETWEEN a AND b
110constexpr float COND_FILTER_BETWEEN{0.1111f};
111/**
112 Value is out-of-date, will need recalculation.
113 This is used by post-greedy-search logic which changes the access method and
114 thus makes obsolete the filtering value calculated by best_access_path(). For
115 example, test_if_skip_sort_order().
116*/
117constexpr float COND_FILTER_STALE{-1.0f};
118/**
119 A special subcase of the above:
120 - if this is table/index/range scan, and
121 - rows_fetched is how many rows we will examine, and
122 - rows_fetched is less than the number of rows in the table (as determined
123 by test_if_cheaper_ordering() and test_if_skip_sort_order()).
124 Unlike the ordinary case where rows_fetched:
125 - is set by calculate_scan_cost(), and
126 - is how many rows pass the constant condition (so, less than we will
127 examine), and
128 - the actual rows_fetched to show in EXPLAIN is the number of rows in the
129 table (== rows which we will examine), and
130 - the constant condition's effect has to be moved to filter_effect for
131 EXPLAIN.
132*/
133constexpr float COND_FILTER_STALE_NO_CONST{-2.0f};
134
135static inline uint32 char_to_byte_length_safe(uint32 char_length_arg,
136 uint32 mbmaxlen_arg) {
137 const ulonglong tmp = ((ulonglong)char_length_arg) * mbmaxlen_arg;
138 return (tmp > UINT_MAX32) ? (uint32)UINT_MAX32 : (uint32)tmp;
139}
140
142 Item_result result_type,
143 uint8 decimals) {
144 if (is_temporal_type(real_type_to_type(data_type)))
145 return decimals ? DECIMAL_RESULT : INT_RESULT;
146 if (result_type == STRING_RESULT) return REAL_RESULT;
147 return result_type;
148}
149
150/*
151 "Declared Type Collation"
152 A combination of collation and its derivation.
153
154 Flags for collation aggregation modes:
155 MY_COLL_ALLOW_SUPERSET_CONV - allow conversion to a superset
156 MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value
157 (i.e. constant).
158 MY_COLL_ALLOW_CONV - allow any kind of conversion
159 (combination of the above two)
160 MY_COLL_ALLOW_NUMERIC_CONV - if all items were numbers, convert to
161 @@character_set_connection
162 MY_COLL_DISALLOW_NONE - don't allow return DERIVATION_NONE
163 (e.g. when aggregating for comparison)
164 MY_COLL_CMP_CONV - combination of MY_COLL_ALLOW_CONV
165 and MY_COLL_DISALLOW_NONE
166*/
167
168#define MY_COLL_ALLOW_SUPERSET_CONV 1
169#define MY_COLL_ALLOW_COERCIBLE_CONV 2
170#define MY_COLL_DISALLOW_NONE 4
171#define MY_COLL_ALLOW_NUMERIC_CONV 8
172
173#define MY_COLL_ALLOW_CONV \
174 (MY_COLL_ALLOW_SUPERSET_CONV | MY_COLL_ALLOW_COERCIBLE_CONV)
175#define MY_COLL_CMP_CONV (MY_COLL_ALLOW_CONV | MY_COLL_DISALLOW_NONE)
176
178 public:
182
186 }
191 }
192 DTCollation(const CHARSET_INFO *collation_arg, Derivation derivation_arg) {
193 collation = collation_arg;
194 derivation = derivation_arg;
195 set_repertoire_from_charset(collation_arg);
196 }
197 void set(const DTCollation &dt) {
198 collation = dt.collation;
201 }
202 void set(const CHARSET_INFO *collation_arg, Derivation derivation_arg) {
203 collation = collation_arg;
204 derivation = derivation_arg;
205 set_repertoire_from_charset(collation_arg);
206 }
207 void set(const CHARSET_INFO *collation_arg, Derivation derivation_arg,
208 uint repertoire_arg) {
209 collation = collation_arg;
210 derivation = derivation_arg;
211 repertoire = repertoire_arg;
212 }
213 void set_numeric() {
217 }
218 void set(const CHARSET_INFO *collation_arg) {
219 collation = collation_arg;
220 set_repertoire_from_charset(collation_arg);
221 }
222 void set(Derivation derivation_arg) { derivation = derivation_arg; }
223 void set_repertoire(uint repertoire_arg) { repertoire = repertoire_arg; }
224 bool aggregate(DTCollation &dt, uint flags = 0);
225 bool set(DTCollation &dt1, DTCollation &dt2, uint flags = 0) {
226 set(dt1);
227 return aggregate(dt2, flags);
228 }
229 const char *derivation_name() const {
230 switch (derivation) {
232 return "NUMERIC";
234 return "IGNORABLE";
236 return "COERCIBLE";
238 return "IMPLICIT";
240 return "SYSCONST";
242 return "EXPLICIT";
243 case DERIVATION_NONE:
244 return "NONE";
245 default:
246 return "UNKNOWN";
247 }
248 }
249};
250
251/**
252 Class used as argument to Item::walk() together with mark_field_in_map()
253*/
255 public:
258
259 /**
260 If == NULL, update map of any table.
261 If <> NULL, update map of only this table.
262 */
263 TABLE *const table;
264 /// How to mark the map.
266};
267
268/**
269 Class used as argument to Item::walk() together with used_tables_for_level()
270*/
272 public:
274
275 Query_block *const select; ///< Level for which data is accumulated
276 table_map used_tables; ///< Accumulated used tables data
277};
278
279/*************************************************************************/
280
281/**
282 Storage for name strings.
283 Enpowers Simple_cstring with allocation routines from the sql_strmake family.
284
285 This class must stay as small as possible as we often
286 pass it into functions using call-by-value evaluation.
287
288 Don't add new members or virtual methods into this class!
289*/
291 private:
292 void set_or_copy(const char *str, size_t length, bool is_null_terminated) {
293 if (is_null_terminated)
294 set(str, length);
295 else
296 copy(str, length);
297 }
298
299 public:
301 /*
302 Please do NOT add constructor Name_string(const char *str) !
303 It will involve hidden strlen() call, which can affect
304 performance negatively. Use Name_string(str, len) instead.
305 */
306 Name_string(const char *str, size_t length) : Simple_cstring(str, length) {}
309 Name_string(const char *str, size_t length, bool is_null_terminated)
310 : Simple_cstring() {
311 set_or_copy(str, length, is_null_terminated);
312 }
313 Name_string(const LEX_STRING str, bool is_null_terminated)
314 : Simple_cstring() {
315 set_or_copy(str.str, str.length, is_null_terminated);
316 }
317 /**
318 Allocate space using sql_strmake() or sql_strmake_with_convert().
319 */
320 void copy(const char *str, size_t length, const CHARSET_INFO *cs);
321 /**
322 Variants for copy(), for various argument combinations.
323 */
324 void copy(const char *str, size_t length) {
326 }
327 void copy(const char *str) {
328 copy(str, (str ? strlen(str) : 0), system_charset_info);
329 }
330 void copy(const LEX_STRING lex) { copy(lex.str, lex.length); }
331 void copy(const LEX_STRING *lex) { copy(lex->str, lex->length); }
332 void copy(const Name_string str) { copy(str.ptr(), str.length()); }
333 /**
334 Compare name to another name in C string, case insensitively.
335 */
336 bool eq(const char *str) const {
337 assert(str && ptr());
338 return my_strcasecmp(system_charset_info, ptr(), str) == 0;
339 }
340 bool eq_safe(const char *str) const { return is_set() && str && eq(str); }
341 /**
342 Compare name to another name in Name_string, case insensitively.
343 */
344 bool eq(const Name_string name) const { return eq(name.ptr()); }
345 bool eq_safe(const Name_string name) const {
346 return is_set() && name.is_set() && eq(name);
347 }
348};
349
350#define NAME_STRING(x) Name_string(STRING_WITH_LEN(x))
351
352extern const Name_string null_name_string;
353
354/**
355 Storage for Item names.
356 Adds "autogenerated" flag and warning functionality to Name_string.
357*/
359 private:
360 bool m_is_autogenerated; /* indicates if name of this Item
361 was autogenerated or set by user */
362 public:
366 /**
367 Set m_is_autogenerated flag to the given value.
368 */
371 }
372 /**
373 Return the auto-generated flag.
374 */
375 bool is_autogenerated() const { return m_is_autogenerated; }
376 using Name_string::copy;
377 /**
378 Copy name together with autogenerated flag.
379 Produce a warning if name was cut.
380 */
381 void copy(const char *str_arg, size_t length_arg, const CHARSET_INFO *cs_arg,
382 bool is_autogenerated_arg);
383};
384
385/*
386 Instances of Name_resolution_context store the information necessary for
387 name resolution of Items and other context analysis of a query made in
388 fix_fields().
389
390 This structure is a part of Query_block, a pointer to this structure is
391 assigned when an item is created (which happens mostly during parsing
392 (sql_yacc.yy)), but the structure itself will be initialized after parsing
393 is complete
394
395 TODO: move subquery of INSERT ... SELECT and CREATE ... SELECT to
396 separate Query_block which allow to remove tricks of changing this
397 structure before and after INSERT/CREATE and its SELECT to make correct
398 field name resolution.
399*/
401 /*
402 The name resolution context to search in when an Item cannot be
403 resolved in this context (the context of an outer select)
404 */
406 /// Link to next name res context with the same query block as the base
408
409 /*
410 List of tables used to resolve the items of this context. Usually these
411 are tables from the FROM clause of SELECT statement. The exceptions are
412 INSERT ... SELECT and CREATE ... SELECT statements, where SELECT
413 subquery is not moved to a separate Query_block. For these types of
414 statements we have to change this member dynamically to ensure correct
415 name resolution of different parts of the statement.
416 */
418 /*
419 In most cases the two table references below replace 'table_list' above
420 for the purpose of name resolution. The first and last name resolution
421 table references allow us to search only in a sub-tree of the nested
422 join tree in a FROM clause. This is needed for NATURAL JOIN, JOIN ... USING
423 and JOIN ... ON.
424 */
426 /*
427 Last table to search in the list of leaf table references that begins
428 with first_name_resolution_table.
429 */
431
432 /*
433 Query_block item belong to, in case of merged VIEW it can differ from
434 Query_block where item was created, so we can't use table_list/field_list
435 from there
436 */
438
439 /*
440 Processor of errors caused during Item name resolving, now used only to
441 hide underlying tables in errors about views (i.e. it substitute some
442 errors for views)
443 */
446
447 /**
448 When true, items are resolved in this context against
449 Query_block::item_list, SELECT_lex::group_list and
450 this->table_list. If false, items are resolved only against
451 this->table_list.
452
453 @see Query_block::item_list, Query_block::group_list
454 */
456
457 /*
458 Security context of this name resolution context. It's used for views
459 and is non-zero only if the view is defined with SQL SECURITY DEFINER.
460 */
462
470 DBUG_PRINT("outer_field", ("creating ctx %p", this));
471 }
472
473 void init() {
475 view_error_handler = false;
478 }
479
483 }
484};
485
486/**
487 Struct used to pass around arguments to/from
488 check_function_as_value_generator
489*/
492 int default_error_code, Value_generator_source val_gen_src)
493 : err_code(default_error_code), source(val_gen_src) {}
494 /// the order of the column in table
495 int col_index{-1};
496 /// the error code found during check(if any)
498 /*
499 If it is a generated column, default expression or check constraint
500 expression value generator.
501 */
503 /// the name of the function which is not allowed
504 const char *banned_function_name{nullptr};
505
506 /// Return the correct error code, based on whether or not if we are checking
507 /// for disallowed functions in generated column expressions, in default
508 /// value expressions or in check constraint expression.
510 return ((source == VGS_GENERATED_COLUMN)
511 ? ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED
513 ? ER_DEFAULT_VAL_GENERATED_FUNCTION_IS_NOT_ALLOWED
514 : ER_CHECK_CONSTRAINT_FUNCTION_IS_NOT_ALLOWED);
515 }
516};
517/*
518 Store and restore the current state of a name resolution context.
519*/
520
522 private:
528
529 public:
530 /* Save the state of a name resolution context. */
531 void save_state(Name_resolution_context *context, Table_ref *table_list) {
532 save_table_list = context->table_list;
535 save_next_local = table_list->next_local;
537 }
538
539 /* Restore a name resolution context from saved state. */
540 void restore_state(Name_resolution_context *context, Table_ref *table_list) {
541 table_list->next_local = save_next_local;
543 context->table_list = save_table_list;
546 }
547
548 void update_next_local(Table_ref *table_list) {
549 save_next_local = table_list;
550 }
551
554 }
555};
556
557/*
558 This enum is used to report information about monotonicity of function
559 represented by Item* tree.
560 Monotonicity is defined only for Item* trees that represent table
561 partitioning expressions (i.e. have no subqueries/user vars/dynamic parameters
562 etc etc). An Item* tree is assumed to have the same monotonicity properties
563 as its corresponding function F:
564
565 [signed] longlong F(field1, field2, ...) {
566 put values of field_i into table record buffer;
567 return item->val_int();
568 }
569
570 NOTE
571 At the moment function monotonicity is not well defined (and so may be
572 incorrect) for Item trees with parameters/return types that are different
573 from INT_RESULT, may be NULL, or are unsigned.
574 It will be possible to address this issue once the related partitioning bugs
575 (BUG#16002, BUG#15447, BUG#13436) are fixed.
576
577 The NOT_NULL enums are used in TO_DAYS, since TO_DAYS('2001-00-00') returns
578 NULL which puts those rows into the NULL partition, but
579 '2000-12-31' < '2001-00-00' < '2001-01-01'. So special handling is needed
580 for this (see Bug#20577).
581*/
582
583typedef enum monotonicity_info {
584 NON_MONOTONIC, /* none of the below holds */
585 MONOTONIC_INCREASING, /* F() is unary and (x < y) => (F(x) <= F(y)) */
586 MONOTONIC_INCREASING_NOT_NULL, /* But only for valid/real x and y */
587 MONOTONIC_STRICT_INCREASING, /* F() is unary and (x < y) => (F(x) < F(y)) */
588 MONOTONIC_STRICT_INCREASING_NOT_NULL /* But only for valid/real x and y */
590
591/**
592 A type for SQL-like 3-valued Booleans: true/false/unknown.
593*/
594class Bool3 {
595 public:
596 /// @returns an instance set to "FALSE"
597 static const Bool3 false3() { return Bool3(v_FALSE); }
598 /// @returns an instance set to "UNKNOWN"
599 static const Bool3 unknown3() { return Bool3(v_UNKNOWN); }
600 /// @returns an instance set to "TRUE"
601 static const Bool3 true3() { return Bool3(v_TRUE); }
602
603 bool is_true() const { return m_val == v_TRUE; }
604 bool is_unknown() const { return m_val == v_UNKNOWN; }
605 bool is_false() const { return m_val == v_FALSE; }
606
607 private:
609 /// This is private; instead, use false3()/etc.
610 Bool3(value v) : m_val(v) {}
611
613 /*
614 No operator to convert Bool3 to bool (or int) - intentionally: how
615 would you map unknown3 to true/false?
616 It is because we want to block such conversions that Bool3 is a class
617 instead of a plain enum.
618 */
619};
620
621/**
622 Type properties, used to collect type information for later assignment
623 to an Item object. The object stores attributes signedness, max length
624 and collation. However, precision and scale (for decimal numbers) and
625 fractional second precision (for time and datetime) are not stored,
626 since any type derived from this object will have default values for these
627 attributes.
628*/
630 public:
631 /// Constructor for any signed numeric type or date type
632 /// Defaults are provided for attributes like signedness and max length
634 : m_type(type_arg),
635 m_unsigned_flag(false),
636 m_max_length(0),
638 assert(type_arg != MYSQL_TYPE_VARCHAR && type_arg != MYSQL_TYPE_JSON);
639 }
640 /// Constructor for any numeric type, with explicit signedness
641 Type_properties(enum_field_types type_arg, bool unsigned_arg)
642 : m_type(type_arg),
643 m_unsigned_flag(unsigned_arg),
644 m_max_length(0),
646 assert(is_numeric_type(type_arg) || type_arg == MYSQL_TYPE_BIT ||
647 type_arg == MYSQL_TYPE_YEAR);
648 }
649 /// Constructor for character type, with explicit character set.
650 /// Default length/max length is provided.
652 : m_type(type_arg),
653 m_unsigned_flag(false),
654 m_max_length(0),
656 /// Constructor for Item
657 Type_properties(Item &item);
659 const bool m_unsigned_flag;
662};
663
664/*************************************************************************/
665
666class sp_rcontext;
667
669 public:
671 virtual ~Settable_routine_parameter() = default;
672 /**
673 Set required privileges for accessing the parameter.
674
675 @param privilege The required privileges for this field, with the
676 following alternatives:
677 MODE_IN - SELECT_ACL
678 MODE_OUT - UPDATE_ACL
679 MODE_INOUT - SELECT_ACL | UPDATE_ACL
680 */
681 virtual void set_required_privilege(ulong privilege [[maybe_unused]]) {}
682
683 /*
684 Set parameter value.
685
686 SYNOPSIS
687 set_value()
688 thd thread handle
689 ctx context to which parameter belongs (if it is local
690 variable).
691 it item which represents new value
692
693 RETURN
694 false if parameter value has been set,
695 true if error has occurred.
696 */
697 virtual bool set_value(THD *thd, sp_rcontext *ctx, Item **it) = 0;
698
699 virtual void set_out_param_info(Send_field *info [[maybe_unused]]) {}
700
701 virtual const Send_field *get_out_param_info() const { return nullptr; }
702};
703
704/*
705 Analyzer function
706 SYNOPSIS
707 argp in/out IN: Analysis parameter
708 OUT: Parameter to be passed to the transformer
709
710 RETURN
711 true Invoke the transformer
712 false Don't do it
713
714*/
715typedef bool (Item::*Item_analyzer)(uchar **argp);
716
717/**
718 Type for transformers used by Item::transform and Item::compile
719 @param arg Argument used by the transformer. Really a typeless pointer
720 in spite of the uchar type (historical reasons). The
721 transformer needs to cast this to the desired pointer type
722 @returns The transformed item
723*/
724typedef Item *(Item::*Item_transformer)(uchar *arg);
725typedef void (*Cond_traverser)(const Item *item, void *arg);
726
727/**
728 Utility mixin class to be able to walk() only parts of item trees.
729
730 Used with PREFIX+POSTFIX walk: in the prefix call of the Item
731 processor, we process the item X, may decide that its children should not
732 be processed (just like if they didn't exist): processor calls stop_at(X)
733 for that. Then walk() goes to a child Y; the processor tests is_stopped(Y)
734 which returns true, so processor sees that it must not do any processing
735 and returns immediately. Finally, the postfix call to the processor on X
736 tests is_stopped(X) which returns "true" and understands that the
737 not-to-be-processed children have been skipped so calls restart(). Thus,
738 any sibling of X, any part of the Item tree not under X, can then be
739 processed.
740*/
742 protected:
747
748 /// Stops walking children of this item
749 void stop_at(const Item *i) {
750 assert(stopped_at_item == nullptr);
751 stopped_at_item = i;
752 }
753
754 /**
755 @returns if we are stopped. If item 'i' is where we stopped, restarts the
756 walk for next items.
757 */
758 bool is_stopped(const Item *i) {
759 if (stopped_at_item != nullptr) {
760 /*
761 Walking was disabled for a tree part rooted a one ancestor of 'i' or
762 rooted at 'i'.
763 */
764 if (stopped_at_item == i) {
765 /*
766 Walking was disabled for the tree part rooted at 'i'; we have now just
767 returned back to this root (POSTFIX call), left the tree part:
768 enable the walk again, for other tree parts.
769 */
770 stopped_at_item = nullptr;
771 }
772 // No further processing to do for this item:
773 return true;
774 }
775 return false;
776 }
777
778 private:
779 const Item *stopped_at_item{nullptr};
780};
781
782/// Increment *num if it is less than its maximal value.
783template <typename T>
784void SafeIncrement(T *num) {
785 if (*num < std::numeric_limits<T>::max()) {
786 *num += 1;
787 }
788}
789
790/**
791 This class represents the cost of evaluating an Item. @see SortPredicates
792 to see how this is used.
793*/
794class CostOfItem final {
795 public:
796 /// Set '*this' to represent the cost of 'item'.
797 void Compute(const Item &item) {
798 if (!m_computed) {
799 ComputeInternal(item);
800 }
801 }
802
804 assert(!m_computed);
805 m_is_expensive = true;
806 }
807
808 /// Add the cost of accessing a Field_str.
810 assert(!m_computed);
812 }
813
814 /// Add the cost of accessing any other Field.
816 assert(!m_computed);
818 }
819
820 bool IsExpensive() const {
821 assert(m_computed);
822 return m_is_expensive;
823 }
824
825 /**
826 Get the cost of field access when evaluating the Item associated with this
827 object. The cost unit is arbitrary, but the relative cost of different
828 items reflect the fact that operating on Field_str is more expensive than
829 other Field subclasses.
830 */
831 double FieldCost() const {
832 assert(m_computed);
834 }
835
836 private:
837 /// The cost of accessing a Field_str, relative to other Field types.
838 /// (The value was determined using benchmarks.)
839 static constexpr double kStrFieldCost = 1.8;
840
841 /// The cost of accessing a Field other than Field_str. 1.0 by definition.
842 static constexpr double kOtherFieldCost = 1.0;
843
844 /// True if 'ComputeInternal()' has been called.
845 bool m_computed{false};
846
847 /// True if the associated Item calls user defined functions or stored
848 /// procedures.
849 bool m_is_expensive{false};
850
851 /// The number of Field_str objects accessed by the associated Item.
853
854 /// The number of other Field objects accessed by the associated Item.
856
857 /// Compute the cost of 'root' and its descendants.
858 void ComputeInternal(const Item &root);
859};
860
861/**
862 This class represents a subquery contained in some subclass of
863 Item_subselect, @see FindContainedSubqueries().
864*/
866 /// The strategy for executing the subquery.
867 enum class Strategy : char {
868 /**
869 An independent subquery that is materialized, e.g.:
870 "SELECT * FROM tab WHERE field IN <independent subquery>".
871 where 'independent subquery' does not depend on any fields in 'tab'.
872 (This corresponds to the Item_in_subselect class.)
873 */
875
876 /**
877 A subquery that is reevaluated for each row, e.g.:
878 "SELECT * FROM tab WHERE field IN <dependent subquery>" or
879 "SELECT * FROM tab WHERE field = <dependent subquery>".
880 where 'dependent subquery' depends on at least one field in 'tab'.
881 Alternatively, the subquery may be independent of 'tab', but contain
882 a non-deterministic function such as 'rand()'. Such subqueries are also
883 required to be reevaluated for each row.
884 */
886
887 /**
888 An independent single-row subquery that is evaluated once, e.g.:
889 "SELECT * FROM tab WHERE field = <independent single-row subquery>".
890 (This corresponds to the Item_singlerow_subselect class.)
891 */
893 };
894
895 /// The root path of the subquery.
897
898 /// The strategy for executing the subquery.
900
901 /// The width (in bytes) of the subquery's rows. For variable-sized values we
902 /// use Item.max_length (but cap it at kMaxItemLengthEstimate).
903 /// @see kMaxItemLengthEstimate and
904 /// @see Item_in_subselect::get_contained_subquery().
906};
907
908/**
909 Base class that is used to represent any kind of expression in a
910 relational query. The class provides subclasses for simple components, like
911 literal (constant) values, column references and variable references,
912 as well as more complex expressions like comparison predicates,
913 arithmetic and string functions, row objects, function references and
914 subqueries.
915
916 The lifetime of an Item class object is often the same as a relational
917 statement, which may be used for several executions, but in some cases
918 it may also be generated for an optimized statement and thus be valid
919 only for one execution.
920
921 For Item objects with longer lifespan than one execution, we must take
922 special precautions when referencing objects with shorter lifespan.
923 For example, TABLE and Field objects against most tables are valid only for
924 one execution. For such objects, Item classes should rather reference
925 Table_ref and Item_field objects instead of TABLE and Field, because
926 these classes support dynamic rebinding of objects before each execution.
927 See Item::bind_fields() which binds new objects per execution and
928 Item::cleanup() that deletes references to such objects.
929
930 These mechanisms can also be used to handle other objects with shorter
931 lifespan, such as function references and variable references.
932*/
933class Item : public Parse_tree_node {
935
936 friend class udf_handler;
937
938 protected:
939 /**
940 Sets the result value of the function an empty string, using the current
941 character set. No memory is allocated.
942 @retval A pointer to the str_value member.
943 */
946 return &str_value;
947 }
948
949 public:
950 Item(const Item &) = delete;
951 void operator=(Item &) = delete;
952 static void *operator new(size_t size) noexcept {
953 return (*THR_MALLOC)->Alloc(size);
954 }
955 static void *operator new(size_t size, MEM_ROOT *mem_root,
956 const std::nothrow_t &arg
957 [[maybe_unused]] = std::nothrow) noexcept {
958 return mem_root->Alloc(size);
959 }
960
961 static void operator delete(void *ptr [[maybe_unused]],
962 size_t size [[maybe_unused]]) {
963 TRASH(ptr, size);
964 }
965 static void operator delete(void *, MEM_ROOT *,
966 const std::nothrow_t &) noexcept {}
967
968 enum Type {
999 };
1000
1002
1004
1005 /// How to cache constant JSON data
1007 /// Don't cache
1009 /// Source data is a JSON string, parse and cache result
1011 /// Source data is SQL scalar, convert and cache result
1014
1015 enum Bool_test ///< Modifier for result transformation
1026 };
1027
1028 // Return the default data type for a given result type
1030 switch (result) {
1031 case INT_RESULT:
1032 return MYSQL_TYPE_LONGLONG;
1033 case DECIMAL_RESULT:
1034 return MYSQL_TYPE_NEWDECIMAL;
1035 case REAL_RESULT:
1036 return MYSQL_TYPE_DOUBLE;
1037 case STRING_RESULT:
1038 return MYSQL_TYPE_VARCHAR;
1039 case INVALID_RESULT:
1040 return MYSQL_TYPE_INVALID;
1041 case ROW_RESULT:
1042 default:
1043 assert(false);
1044 }
1045 return MYSQL_TYPE_INVALID;
1046 }
1047
1048 // Return the default result type for a given data type
1050 switch (type) {
1051 case MYSQL_TYPE_TINY:
1052 case MYSQL_TYPE_SHORT:
1053 case MYSQL_TYPE_INT24:
1054 case MYSQL_TYPE_LONG:
1056 case MYSQL_TYPE_BOOL:
1057 case MYSQL_TYPE_BIT:
1058 case MYSQL_TYPE_YEAR:
1059 return INT_RESULT;
1061 case MYSQL_TYPE_DECIMAL:
1062 return DECIMAL_RESULT;
1063 case MYSQL_TYPE_FLOAT:
1064 case MYSQL_TYPE_DOUBLE:
1065 return REAL_RESULT;
1066 case MYSQL_TYPE_VARCHAR:
1068 case MYSQL_TYPE_STRING:
1072 case MYSQL_TYPE_BLOB:
1074 case MYSQL_TYPE_JSON:
1075 case MYSQL_TYPE_ENUM:
1076 case MYSQL_TYPE_SET:
1077 return STRING_RESULT;
1079 case MYSQL_TYPE_DATE:
1080 case MYSQL_TYPE_TIME:
1082 case MYSQL_TYPE_NEWDATE:
1085 case MYSQL_TYPE_TIME2:
1086 return STRING_RESULT;
1087 case MYSQL_TYPE_INVALID:
1088 return INVALID_RESULT;
1089 case MYSQL_TYPE_NULL:
1090 return STRING_RESULT;
1092 break;
1093 }
1094 assert(false);
1095 return INVALID_RESULT;
1096 }
1097
1098 /**
1099 Provide data type for a user or system variable, based on the type of
1100 the item that is assigned to the variable.
1101
1102 @note MYSQL_TYPE_VARCHAR is returned for all string types, but must be
1103 further adjusted based on maximum string length by the caller.
1104
1105 @param src_type Source type that variable's type is derived from
1106 */
1108 switch (src_type) {
1109 case MYSQL_TYPE_BOOL:
1110 case MYSQL_TYPE_TINY:
1111 case MYSQL_TYPE_SHORT:
1112 case MYSQL_TYPE_INT24:
1113 case MYSQL_TYPE_LONG:
1115 case MYSQL_TYPE_BIT:
1116 return MYSQL_TYPE_LONGLONG;
1117 case MYSQL_TYPE_DECIMAL:
1119 return MYSQL_TYPE_NEWDECIMAL;
1120 case MYSQL_TYPE_FLOAT:
1121 case MYSQL_TYPE_DOUBLE:
1122 return MYSQL_TYPE_DOUBLE;
1123 case MYSQL_TYPE_VARCHAR:
1125 case MYSQL_TYPE_STRING:
1126 return MYSQL_TYPE_VARCHAR;
1127 case MYSQL_TYPE_YEAR:
1128 return MYSQL_TYPE_LONGLONG;
1130 case MYSQL_TYPE_DATE:
1131 case MYSQL_TYPE_TIME:
1133 case MYSQL_TYPE_NEWDATE:
1136 case MYSQL_TYPE_TIME2:
1137 case MYSQL_TYPE_JSON:
1138 case MYSQL_TYPE_ENUM:
1139 case MYSQL_TYPE_SET:
1141 case MYSQL_TYPE_NULL:
1143 case MYSQL_TYPE_BLOB:
1146 return MYSQL_TYPE_VARCHAR;
1147 case MYSQL_TYPE_INVALID:
1149 return MYSQL_TYPE_INVALID;
1150 }
1151 assert(false);
1152 return MYSQL_TYPE_NULL;
1153 }
1154
1155 /// Item constructor for general use.
1156 Item();
1157
1158 /**
1159 Constructor used by Item_field, Item_ref & aggregate functions.
1160 Used for duplicating lists in processing queries with temporary tables.
1161
1162 Also used for Item_cond_and/Item_cond_or for creating top AND/OR structure
1163 of WHERE clause to protect it of optimisation changes in prepared statements
1164 */
1165 Item(THD *thd, const Item *item);
1166
1167 /**
1168 Parse-time context-independent constructor.
1169
1170 This constructor and caller constructors of child classes must not
1171 access/change thd->lex (including thd->lex->current_query_block(),
1172 thd->m_parser_state etc structures).
1173
1174 If we need to finalize the construction of the object, then we move
1175 all context-sensitive code to the itemize() virtual function.
1176
1177 The POS parameter marks this constructor and other context-independent
1178 constructors of child classes for easy recognition/separation from other
1179 (context-dependent) constructors.
1180 */
1181 explicit Item(const POS &);
1182
1183#ifdef EXTRA_DEBUG
1184 ~Item() override { item_name.set(0); }
1185#else
1186 ~Item() override = default;
1187#endif
1188
1189 private:
1190 /*
1191 Hide the contextualize*() functions: call/override the itemize()
1192 in Item class tree instead.
1193 */
1195 assert(0);
1196 return true;
1197 }
1198
1199 protected:
1200 /**
1201 Helper function to skip itemize() for grammar-allocated items
1202
1203 @param [out] res pointer to "this"
1204
1205 @retval true can skip itemize()
1206 @retval false can't skip: the item is allocated directly by the parser
1207 */
1208 bool skip_itemize(Item **res) {
1209 *res = this;
1210 return !is_parser_item;
1211 }
1212
1213 /*
1214 Checks if the function should return binary result based on the items
1215 provided as parameter.
1216 Function should only be used by Item_bit_func*
1217
1218 @param a item to check
1219 @param b item to check, may be nullptr
1220
1221 @returns true if binary result.
1222 */
1223 static bool bit_func_returns_binary(const Item *a, const Item *b);
1224
1225 /**
1226 The core function that does the actual itemization. itemize() is just a
1227 wrapper over this.
1228 */
1229 virtual bool do_itemize(Parse_context *pc, Item **res);
1230
1231 public:
1232 /**
1233 The same as contextualize() but with additional parameter
1234
1235 This function finalize the construction of Item objects (see the Item(POS)
1236 constructor): we can access/change parser contexts from the itemize()
1237 function.
1238
1239 Derived classes should not override this. If needed, they should
1240 override do_itemize().
1241
1242 @param pc current parse context
1243 @param [out] res pointer to "this" or to a newly allocated
1244 replacement object to use in the Item tree instead
1245
1246 @retval false success
1247 @retval true syntax/OOM/etc error
1248 */
1249 // Visual Studio with MSVC_CPPCHECK=ON gives warning C26435:
1250 // Function <fun> should specify exactly one of
1251 // 'virtual', 'override', or 'final'
1254 virtual bool itemize(Parse_context *pc, Item **res) final {
1255 // For condition#2 below ... If position is empty, this item was not
1256 // created in the parser; so don't show it in the parse tree.
1257 if (pc->m_show_parse_tree == nullptr || this->m_pos.is_empty())
1258 return do_itemize(pc, res);
1259
1260 Show_parse_tree *tree = pc->m_show_parse_tree.get();
1261
1262 if (begin_parse_tree(tree)) return true;
1263
1264 if (do_itemize(pc, res)) return true;
1265
1266 if (end_parse_tree(tree)) return true;
1267
1268 return false;
1269 }
1271
1272 void rename(char *new_name);
1273 void init_make_field(Send_field *tmp_field, enum enum_field_types type);
1274 /**
1275 Called for every Item after use (preparation and execution).
1276 Release all allocated resources, such as dynamic memory.
1277 Prepare for new execution by clearing cached values.
1278 Do not remove values allocated during preparation, destructor handles this.
1279 */
1280 virtual void cleanup() { marker = MARKER_NONE; }
1281 /**
1282 Called when an item has been removed, can be used to notify external
1283 objects about the removal, e.g subquery predicates that are part of
1284 the sj_candidates container.
1285 */
1286 virtual void notify_removal() {}
1287 virtual void make_field(Send_field *field);
1288 virtual Field *make_string_field(TABLE *table) const;
1289 virtual bool fix_fields(THD *, Item **);
1290 /**
1291 Fix after tables have been moved from one query_block level to the parent
1292 level, e.g by semijoin conversion.
1293 Basically re-calculate all attributes dependent on the tables.
1294
1295 @param parent_query_block query_block that tables are moved to.
1296 @param removed_query_block query_block that tables are moved away from,
1297 child of parent_query_block.
1298 */
1299 virtual void fix_after_pullout(Query_block *parent_query_block
1300 [[maybe_unused]],
1301 Query_block *removed_query_block
1302 [[maybe_unused]]) {}
1303 /*
1304 should be used in case where we are sure that we do not need
1305 complete fix_fields() procedure.
1306 */
1307 inline void quick_fix_field() { fixed = true; }
1308 virtual void set_can_use_prefix_key() {}
1309
1310 /**
1311 Propagate data type specifications into parameters and user variables.
1312 If item has descendants, propagate type recursively into these.
1313
1314 @param thd thread handler
1315 @param type Data type properties that are propagated
1316
1317 @returns false if success, true if error
1318 */
1319 virtual bool propagate_type(THD *thd [[maybe_unused]],
1320 const Type_properties &type [[maybe_unused]]) {
1321 return false;
1322 }
1323
1324 /**
1325 Wrapper for easier calling of propagate_type(const Type_properties &).
1326 @param thd thread handler
1327 @param def type to make Type_properties object
1328 @param pin if true: also mark the type as pinned
1329 @param inherit if true: also mark the type as inherited
1330
1331 @returns false if success, true if error
1332 */
1334 bool pin = false, bool inherit = false) {
1335 /*
1336 Propagate supplied type if types have not yet been assigned to expression,
1337 or type is pinned, in which case the supplied type overrides the
1338 actual type of parameters. Note we do not support "pinning" of
1339 expressions containing parameters, only standalone parameters,
1340 but this is a very minor problem.
1341 */
1342 if (data_type() != MYSQL_TYPE_INVALID && !(pin && type() == PARAM_ITEM))
1343 return false;
1344 if (propagate_type(thd,
1345 (def == MYSQL_TYPE_VARCHAR)
1347 : (def == MYSQL_TYPE_JSON)
1349 : Type_properties(def)))
1350 return true;
1351 if (pin) pin_data_type();
1352 if (inherit) set_data_type_inherited();
1353
1354 return false;
1355 }
1356
1357 /**
1358 For Items with data type JSON, mark that a string argument is treated
1359 as a scalar JSON value. Only relevant for the Item_param class.
1360 */
1361 virtual void mark_json_as_scalar() {}
1362
1363 /**
1364 If this item represents a IN/ALL/ANY/comparison_operator
1365 subquery, return that (along with data on how it will be executed).
1366 (These subqueries correspond to
1367 @see Item_in_subselect and @see Item_singlerow_subselect .) Also,
1368 @see FindContainedSubqueries() for context.
1369 @param outer_query_block the Query_block to which 'this' belongs.
1370 @returns The subquery that 'this' represents, if there is one.
1371 */
1372 virtual std::optional<ContainedSubquery> get_contained_subquery(
1373 const Query_block *outer_query_block [[maybe_unused]]) {
1374 return std::nullopt;
1375 }
1376
1377 protected:
1378 /**
1379 Helper function which does all of the work for
1380 save_in_field(Field*, bool), except some error checking common to
1381 all subclasses, which is performed by save_in_field() itself.
1382
1383 Subclasses that need to specialize the behaviour of
1384 save_in_field(), should override this function instead of
1385 save_in_field().
1386
1387 @param[in,out] field the field to save the item into
1388 @param no_conversions whether or not to allow conversions of the value
1389
1390 @return the status from saving into the field
1391 @retval TYPE_OK item saved without any errors or warnings
1392 @retval != TYPE_OK there were errors or warnings when saving the item
1393 */
1395 bool no_conversions);
1396
1397 public:
1398 /**
1399 Save the item into a field but do not emit any warnings.
1400
1401 @param field field to save the item into
1402 @param no_conversions whether or not to allow conversions of the value
1403
1404 @return the status from saving into the field
1405 @retval TYPE_OK item saved without any issues
1406 @retval != TYPE_OK there were issues saving the item
1407 */
1409 bool no_conversions);
1410 /**
1411 Save a temporal value in packed longlong format into a Field.
1412 Used in optimizer.
1413
1414 Subclasses that need to specialize this function, should override
1415 save_in_field_inner().
1416
1417 @param[in,out] field the field to save the item into
1418 @param no_conversions whether or not to allow conversions of the value
1419
1420 @return the status from saving into the field
1421 @retval TYPE_OK item saved without any errors or warnings
1422 @retval != TYPE_OK there were errors or warnings when saving the item
1423 */
1424 type_conversion_status save_in_field(Field *field, bool no_conversions);
1425
1426 /**
1427 A slightly faster value of save_in_field() that returns no error value
1428 (you will need to check thd->is_error() yourself), and does not support
1429 saving into hidden fields for functional indexes. Used by copy_funcs(),
1430 to avoid the functional call overhead and RAII setup of save_in_field().
1431 */
1432 void save_in_field_no_error_check(Field *field, bool no_conversions) {
1433 assert(!field->is_field_for_functional_index());
1434 save_in_field_inner(field, no_conversions);
1435 }
1436
1437 virtual void save_org_in_field(Field *field) { save_in_field(field, true); }
1438
1439 virtual bool send(Protocol *protocol, String *str);
1440 bool evaluate(THD *thd, String *str);
1441 virtual bool eq(const Item *, bool binary_cmp) const;
1442 virtual Item_result result_type() const { return REAL_RESULT; }
1443 /**
1444 Result type when an item appear in a numeric context.
1445 See Field::numeric_context_result_type() for more comments.
1446 */
1449 }
1450 /**
1451 Similar to result_type() but makes DATE, DATETIME, TIMESTAMP
1452 pretend to be numbers rather than strings.
1453 */
1456 : result_type();
1457 }
1458
1459 /**
1460 Set data type for item as inherited.
1461 Non-empty implementation only for dynamic parameters.
1462 */
1463 virtual void set_data_type_inherited() {}
1464
1465 /**
1466 Pin the data type for the item.
1467 Non-empty implementation only for dynamic parameters.
1468 */
1469 virtual void pin_data_type() {}
1470
1471 /// Retrieve the derived data type of the Item.
1473 return static_cast<enum_field_types>(m_data_type);
1474 }
1475
1476 /**
1477 Retrieve actual data type for an item. Equal to data_type() for
1478 all items, except parameters.
1479 */
1480 virtual enum_field_types actual_data_type() const { return data_type(); }
1481
1482 /**
1483 Get the default data (output) type for the specific item.
1484 Important for some SQL functions that may deliver multiple result types,
1485 and is used to determine data type for function's parameters that cannot
1486 be type-resolved by looking at the context.
1487 An example of such function is '+', which may return INT, DECIMAL,
1488 DOUBLE, depending on arguments.
1489 On the contrary, many other functions have a fixed output type, usually
1490 set with set_data_type_XXX(), which overrides the value of
1491 default_data_type(). For example, COS always returns DOUBLE,
1492 */
1494 // If data type has been set, the information returned here is irrelevant:
1495 assert(data_type() == MYSQL_TYPE_INVALID);
1496 return MYSQL_TYPE_VARCHAR;
1497 }
1498 /**
1499 Set the data type of the current Item. It is however recommended to
1500 use one of the type-specific setters if possible.
1501
1502 @param data_type The data type of this Item.
1503 */
1505 m_data_type = static_cast<uint8>(data_type);
1506 }
1507
1508 inline void set_data_type_null() {
1511 max_length = 0;
1512 set_nullable(true);
1513 }
1514
1515 inline void set_data_type_bool() {
1518 max_length = 1;
1519 }
1520
1521 /**
1522 Set the data type of the Item to be a specific integer type
1523
1524 @param type Integer type
1525 @param unsigned_prop Whether the integer is signed or not
1526 @param max_width Maximum width of field in number of digits
1527 */
1528 inline void set_data_type_int(enum_field_types type, bool unsigned_prop,
1529 uint32 max_width) {
1530 assert(type == MYSQL_TYPE_TINY || type == MYSQL_TYPE_SHORT ||
1535 unsigned_flag = unsigned_prop;
1536 fix_char_length(max_width);
1537 }
1538
1539 /**
1540 Set the data type of the Item to be longlong.
1541 Maximum display width is set to be the maximum of a 64-bit integer,
1542 but it may be adjusted later. The unsigned property is not affected.
1543 */
1547 fix_char_length(21);
1548 }
1549
1550 /**
1551 Set the data type of the Item to be decimal.
1552 The unsigned property must have been set before calling this function.
1553
1554 @param precision Number of digits of precision
1555 @param scale Number of digits after decimal point.
1556 */
1557 inline void set_data_type_decimal(uint8 precision, uint8 scale) {
1560 decimals = scale;
1562 precision, scale, unsigned_flag));
1563 }
1564
1565 /// Set the data type of the Item to be double precision floating point.
1566 inline void set_data_type_double() {
1571 }
1572
1573 /// Set the data type of the Item to be single precision floating point.
1574 inline void set_data_type_float() {
1579 }
1580
1581 /**
1582 Set the Item to be variable length string. Actual type is determined from
1583 maximum string size. Collation must have been set before calling function.
1584
1585 @param max_l Maximum number of characters in string
1586 */
1587 inline void set_data_type_string(uint32 max_l) {
1594 else
1596 }
1597
1598 /**
1599 Set the Item to be variable length string. Like function above, but with
1600 larger string length precision.
1601
1602 @param max_char_length_arg Maximum number of characters in string
1603 */
1604 inline void set_data_type_string(ulonglong max_char_length_arg) {
1605 ulonglong max_result_length =
1606 max_char_length_arg * collation.collation->mbmaxlen;
1607 if (max_result_length > MAX_BLOB_WIDTH) {
1608 max_result_length = MAX_BLOB_WIDTH;
1609 m_nullable = true;
1610 }
1612 uint32(max_result_length / collation.collation->mbmaxlen));
1613 }
1614
1615 /**
1616 Set the Item to be variable length string. Like function above, but will
1617 also set character set and collation.
1618
1619 @param max_l Maximum number of characters in string
1620 @param cs Pointer to character set and collation struct
1621 */
1622 inline void set_data_type_string(uint32 max_l, const CHARSET_INFO *cs) {
1624 set_data_type_string(max_l);
1625 }
1626
1627 /**
1628 Set the Item to be variable length string. Like function above, but will
1629 also set full collation information.
1630
1631 @param max_l Maximum number of characters in string
1632 @param coll Ref to collation data, including derivation and repertoire
1633 */
1634 inline void set_data_type_string(uint32 max_l, const DTCollation &coll) {
1635 collation.set(coll);
1636 set_data_type_string(max_l);
1637 }
1638
1639 /**
1640 Set the Item to be fixed length string. Collation must have been set
1641 before calling function.
1642
1643 @param max_l Number of characters in string
1644 */
1645 inline void set_data_type_char(uint32 max_l) {
1646 assert(max_l <= MAX_CHAR_WIDTH);
1650 }
1651
1652 /**
1653 Set the Item to be fixed length string. Like function above, but will
1654 also set character set and collation.
1655
1656 @param max_l Maximum number of characters in string
1657 @param cs Pointer to character set and collation struct
1658 */
1659 inline void set_data_type_char(uint32 max_l, const CHARSET_INFO *cs) {
1661 set_data_type_char(max_l);
1662 }
1663
1664 /**
1665 Set the Item to be of BLOB type.
1666
1667 @param type Actual blob data type
1668 @param max_l Maximum number of characters in data type
1669 */
1674 ulonglong max_width = max_l * collation.collation->mbmaxlen;
1675 if (max_width > Field::MAX_LONG_BLOB_WIDTH) {
1676 max_width = Field::MAX_LONG_BLOB_WIDTH;
1677 }
1678 max_length = max_width;
1680 }
1681
1682 /// Set all type properties for Item of DATE type.
1683 inline void set_data_type_date() {
1686 decimals = 0;
1688 }
1689
1690 /**
1691 Set all type properties for Item of TIME type.
1692
1693 @param fsp Fractional seconds precision
1694 */
1695 inline void set_data_type_time(uint8 fsp) {
1698 decimals = fsp;
1699 max_length = MAX_TIME_WIDTH + fsp + (fsp > 0 ? 1 : 0);
1700 }
1701
1702 /**
1703 Set all properties for Item of DATETIME type.
1704
1705 @param fsp Fractional seconds precision
1706 */
1710 decimals = fsp;
1711 max_length = MAX_DATETIME_WIDTH + fsp + (fsp > 0 ? 1 : 0);
1712 }
1713
1714 /**
1715 Set all properties for Item of TIMESTAMP type.
1716
1717 @param fsp Fractional seconds precision
1718 */
1722 decimals = fsp;
1723 max_length = MAX_DATETIME_WIDTH + fsp + (fsp > 0 ? 1 : 0);
1724 }
1725
1726 /**
1727 Set the data type of the Item to be GEOMETRY.
1728 */
1734 }
1735 /**
1736 Set the data type of the Item to be JSON.
1737 */
1743 }
1744
1745 /**
1746 Set the data type of the Item to be YEAR.
1747 */
1751 fix_char_length(4); // YYYY
1752 unsigned_flag = true;
1753 }
1754
1755 /**
1756 Set the data type of the Item to be bit.
1757
1758 @param max_bits Maximum number of bits to store in this field.
1759 */
1760 void set_data_type_bit(uint32 max_bits) {
1763 max_length = max_bits;
1764 unsigned_flag = true;
1765 }
1766
1767 /**
1768 Set data type properties of the item from the properties of another item.
1769
1770 @param item Item to set data type properties from.
1771 */
1772 inline void set_data_type_from_item(const Item *item) {
1773 set_data_type(item->data_type());
1774 collation = item->collation;
1775 max_length = item->max_length;
1776 decimals = item->decimals;
1778 }
1779
1780 /**
1781 Determine correct string field type, based on string length
1782
1783 @param max_bytes Maximum string size, in number of bytes
1784 */
1786 if (max_bytes > Field::MAX_MEDIUM_BLOB_WIDTH)
1787 return MYSQL_TYPE_LONG_BLOB;
1788 else if (max_bytes > Field::MAX_VARCHAR_WIDTH)
1790 else
1791 return MYSQL_TYPE_VARCHAR;
1792 }
1793
1794 /// Get the typelib information for an item of type set or enum
1795 virtual TYPELIB *get_typelib() const { return nullptr; }
1796
1797 virtual Item_result cast_to_int_type() const { return result_type(); }
1798 virtual enum Type type() const = 0;
1799
1800 bool aggregate_type(const char *name, Item **items, uint count);
1801
1802 /*
1803 Return information about function monotonicity. See comment for
1804 enum_monotonicity_info for details. This function can only be called
1805 after fix_fields() call.
1806 */
1808 return NON_MONOTONIC;
1809 }
1810
1811 /*
1812 Convert "func_arg $CMP$ const" half-interval into "FUNC(func_arg) $CMP2$
1813 const2"
1814
1815 SYNOPSIS
1816 val_int_endpoint()
1817 left_endp false <=> The interval is "x < const" or "x <= const"
1818 true <=> The interval is "x > const" or "x >= const"
1819
1820 incl_endp IN false <=> the comparison is '<' or '>'
1821 true <=> the comparison is '<=' or '>='
1822 OUT The same but for the "F(x) $CMP$ F(const)" comparison
1823
1824 DESCRIPTION
1825 This function is defined only for unary monotonic functions. The caller
1826 supplies the source half-interval
1827
1828 x $CMP$ const
1829
1830 The value of const is supplied implicitly as the value of this item's
1831 argument, the form of $CMP$ comparison is specified through the
1832 function's arguments. The call returns the result interval
1833
1834 F(x) $CMP2$ F(const)
1835
1836 passing back F(const) as the return value, and the form of $CMP2$
1837 through the out parameter. NULL values are assumed to be comparable and
1838 be less than any non-NULL values.
1839
1840 RETURN
1841 The output range bound, which equal to the value of val_int()
1842 - If the value of the function is NULL then the bound is the
1843 smallest possible value of LLONG_MIN
1844 */
1845 virtual longlong val_int_endpoint(bool left_endp [[maybe_unused]],
1846 bool *incl_endp [[maybe_unused]]) {
1847 assert(0);
1848 return 0;
1849 }
1850
1851 /* valXXX methods must return NULL or 0 or 0.0 if null_value is set. */
1852 /*
1853 Return double precision floating point representation of item.
1854
1855 SYNOPSIS
1856 val_real()
1857
1858 RETURN
1859 In case of NULL value return 0.0 and set null_value flag to true.
1860 If value is not null null_value flag will be reset to false.
1861 */
1862 virtual double val_real() = 0;
1863 /*
1864 Return integer representation of item.
1865
1866 SYNOPSIS
1867 val_int()
1868
1869 RETURN
1870 In case of NULL value return 0 and set null_value flag to true.
1871 If value is not null null_value flag will be reset to false.
1872 */
1873 virtual longlong val_int() = 0;
1874 /**
1875 Return date value of item in packed longlong format.
1876 */
1877 virtual longlong val_date_temporal();
1878 /**
1879 Return time value of item in packed longlong format.
1880 */
1881 virtual longlong val_time_temporal();
1882
1883 /**
1884 Return date or time value of item in packed longlong format,
1885 depending on item field type.
1886 */
1888 if (data_type() == MYSQL_TYPE_TIME) return val_time_temporal();
1889 assert(is_temporal_with_date());
1890 return val_date_temporal();
1891 }
1892
1893 /**
1894 Produces a key suitable for filesort. Most of the time, val_int() would
1895 suffice, but for temporal values, the packed value (as sent to the handler)
1896 is called for. It is also necessary that the value is in UTC. This function
1897 supplies just that.
1898
1899 @return A sort key value.
1900 */
1904 return val_int();
1905 }
1906
1907 /**
1908 Get date or time value in packed longlong format.
1909 Before conversion from MYSQL_TIME to packed format,
1910 the MYSQL_TIME value is rounded to "dec" fractional digits.
1911 */
1913
1914 /*
1915 This is just a shortcut to avoid the cast. You should still use
1916 unsigned_flag to check the sign of the item.
1917 */
1918 inline ulonglong val_uint() { return (ulonglong)val_int(); }
1919 /*
1920 Return string representation of this item object.
1921
1922 SYNOPSIS
1923 val_str()
1924 str an allocated buffer this or any nested Item object can use to
1925 store return value of this method.
1926
1927 NOTE
1928 Buffer passed via argument should only be used if the item itself
1929 doesn't have an own String buffer. In case when the item maintains
1930 it's own string buffer, it's preferable to return it instead to
1931 minimize number of mallocs/memcpys.
1932 The caller of this method can modify returned string, but only in case
1933 when it was allocated on heap, (is_alloced() is true). This allows
1934 the caller to efficiently use a buffer allocated by a child without
1935 having to allocate a buffer of it's own. The buffer, given to
1936 val_str() as argument, belongs to the caller and is later used by the
1937 caller at it's own choosing.
1938 A few implications from the above:
1939 - unless you return a string object which only points to your buffer
1940 but doesn't manages it you should be ready that it will be
1941 modified.
1942 - even for not allocated strings (is_alloced() == false) the caller
1943 can change charset (see Item_func_{typecast/binary}. XXX: is this
1944 a bug?
1945 - still you should try to minimize data copying and return internal
1946 object whenever possible.
1947
1948 RETURN
1949 In case of NULL value or error, return error_str() as this function will
1950 check if the return value may be null, and it will either set null_value
1951 to true and return nullptr or to false and it will return empty string.
1952 If value is not null set null_value flag to false before returning it.
1953 */
1954 virtual String *val_str(String *str) = 0;
1955
1956 /*
1957 Returns string representation of this item in ASCII format.
1958
1959 SYNOPSIS
1960 val_str_ascii()
1961 str - similar to val_str();
1962
1963 NOTE
1964 This method is introduced for performance optimization purposes.
1965
1966 1. val_str() result of some Items in string context
1967 depends on @@character_set_results.
1968 @@character_set_results can be set to a "real multibyte" character
1969 set like UCS2, UTF16, UTF32. (We'll use only UTF32 in the examples
1970 below for convenience.)
1971
1972 So the default string result of such functions
1973 in these circumstances is real multi-byte character set, like UTF32.
1974
1975 For example, all numbers in string context
1976 return result in @@character_set_results:
1977
1978 SELECT CONCAT(20010101); -> UTF32
1979
1980 We do sprintf() first (to get ASCII representation)
1981 and then convert to UTF32;
1982
1983 So these kind "data sources" can use ASCII representation
1984 internally, but return multi-byte data only because
1985 @@character_set_results wants so.
1986 Therefore, conversion from ASCII to UTF32 is applied internally.
1987
1988
1989 2. Some other functions need in fact ASCII input.
1990
1991 For example,
1992 inet_aton(), GeometryFromText(), Convert_TZ(), GET_FORMAT().
1993
1994 Similar, fields of certain type, like DATE, TIME,
1995 when you insert string data into them, expect in fact ASCII input.
1996 If they get non-ASCII input, for example UTF32, they
1997 convert input from UTF32 to ASCII, and then use ASCII
1998 representation to do further processing.
1999
2000
2001 3. Now imagine we pass result of a data source of the first type
2002 to a data destination of the second type.
2003
2004 What happens:
2005 a. data source converts data from ASCII to UTF32, because
2006 @@character_set_results wants so and passes the result to
2007 data destination.
2008 b. data destination gets UTF32 string.
2009 c. data destination converts UTF32 string to ASCII,
2010 because it needs ASCII representation to be able to handle data
2011 correctly.
2012
2013 As a result we get two steps of unnecessary conversion:
2014 From ASCII to UTF32, then from UTF32 to ASCII.
2015
2016 A better way to handle these situations is to pass ASCII
2017 representation directly from the source to the destination.
2018
2019 This is why val_str_ascii() introduced.
2020
2021 RETURN
2022 Similar to val_str()
2023 */
2024 virtual String *val_str_ascii(String *str);
2025
2026 /*
2027 Return decimal representation of item with fixed point.
2028
2029 SYNOPSIS
2030 val_decimal()
2031 decimal_buffer buffer which can be used by Item for returning value
2032 (but can be not)
2033
2034 NOTE
2035 Returned value should not be changed if it is not the same which was
2036 passed via argument.
2037
2038 RETURN
2039 Return pointer on my_decimal (it can be other then passed via argument)
2040 if value is not NULL (null_value flag will be reset to false).
2041 In case of NULL value it return 0 pointer and set null_value flag
2042 to true.
2043 */
2044 virtual my_decimal *val_decimal(my_decimal *decimal_buffer) = 0;
2045 /*
2046 Return boolean value of item.
2047
2048 RETURN
2049 false value is false or NULL
2050 true value is true (not equal to 0)
2051 */
2052 virtual bool val_bool();
2053
2054 /**
2055 Get a JSON value from an Item.
2056
2057 All subclasses that can return a JSON value, should override this
2058 function. The function in the base class is not expected to be
2059 called. If it is called, it most likely means that some subclass
2060 is missing an override of val_json().
2061
2062 @param[in,out] result The resulting Json_wrapper.
2063
2064 @return false if successful, true on failure
2065 */
2066 /* purecov: begin deadcode */
2067 virtual bool val_json(Json_wrapper *result [[maybe_unused]]) {
2068 assert(false);
2069 my_error(ER_NOT_SUPPORTED_YET, MYF(0), "item type for JSON");
2070 return error_json();
2071 }
2072 /* purecov: end */
2073
2074 /**
2075 Calculate the filter contribution that is relevant for table
2076 'filter_for_table' for this item.
2077
2078 @param thd Thread handler
2079 @param filter_for_table The table we are calculating filter effect for
2080 @param read_tables Tables earlier in the join sequence.
2081 Predicates for table 'filter_for_table' that
2082 rely on values from these tables can be part of
2083 the filter effect.
2084 @param fields_to_ignore Fields in 'filter_for_table' that should not
2085 be part of the filter calculation. The filtering
2086 effect of these fields is already part of the
2087 calculation somehow (e.g. because there is a
2088 predicate "col = <const>", and the optimizer
2089 has decided to do ref access on 'col').
2090 @param rows_in_table The number of rows in table 'filter_for_table'
2091
2092 @return the filtering effect (between 0 and 1) this
2093 Item contributes with.
2094 */
2095 virtual float get_filtering_effect(THD *thd [[maybe_unused]],
2096 table_map filter_for_table
2097 [[maybe_unused]],
2098 table_map read_tables [[maybe_unused]],
2099 const MY_BITMAP *fields_to_ignore
2100 [[maybe_unused]],
2101 double rows_in_table [[maybe_unused]]) {
2102 // Filtering effect cannot be calculated for a table already read.
2103 assert((read_tables & filter_for_table) == 0);
2104 return COND_FILTER_ALLPASS;
2105 }
2106
2107 /**
2108 Get the value to return from val_json() in case of errors.
2109
2110 @see Item::error_bool
2111
2112 @return The value val_json() should return, which is true.
2113 */
2114 bool error_json() {
2116 return true;
2117 }
2118
2119 /**
2120 Convert a non-temporal type to date
2121 */
2123
2124 /**
2125 Convert a non-temporal type to time
2126 */
2128
2129 protected:
2130 /* Helper functions, see item_sum.cc */
2147 double val_real_from_decimal();
2148 double val_real_from_string();
2149
2150 /**
2151 Get the value to return from val_bool() in case of errors.
2152
2153 This function is called from val_bool() when an error has occurred
2154 and we need to return something to abort evaluation of the
2155 item. The expected pattern in val_bool() is
2156
2157 if (@<error condition@>)
2158 {
2159 my_error(...)
2160 return error_bool();
2161 }
2162
2163 @return The value val_bool() should return.
2164 */
2165 bool error_bool() {
2167 return false;
2168 }
2169
2170 /**
2171 Get the value to return from val_int() in case of errors.
2172
2173 @see Item::error_bool
2174
2175 @return The value val_int() should return.
2176 */
2179 return 0;
2180 }
2181
2182 /**
2183 Get the value to return from val_real() in case of errors.
2184
2185 @see Item::error_bool
2186
2187 @return The value val_real() should return.
2188 */
2189 double error_real() {
2191 return 0.0;
2192 }
2193
2194 /**
2195 Get the value to return from get_date() in case of errors.
2196
2197 @see Item::error_bool
2198
2199 @return The true: the function failed.
2200 */
2201 bool error_date() {
2203 return true;
2204 }
2205
2206 /**
2207 Get the value to return from get_time() in case of errors.
2208
2209 @see Item::error_bool
2210
2211 @return The true: the function failed.
2212 */
2213 bool error_time() {
2215 return true;
2216 }
2217
2218 public:
2219 /**
2220 Get the value to return from val_decimal() in case of errors.
2221
2222 @see Item::error_decimal
2223
2224 @return The value val_decimal() should return.
2225 */
2228 if (null_value) return nullptr;
2229 my_decimal_set_zero(decimal_value);
2230 return decimal_value;
2231 }
2232
2233 /**
2234 Get the value to return from val_str() in case of errors.
2235
2236 @see Item::error_bool
2237
2238 @return The value val_str() should return.
2239 */
2243 }
2244
2245 protected:
2246 /**
2247 Gets the value to return from val_str() when returning a NULL value.
2248 @return The value val_str() should return.
2249 */
2251 assert(m_nullable);
2252 null_value = true;
2253 return nullptr;
2254 }
2255
2256 /**
2257 Convert val_str() to date in MYSQL_TIME
2258 */
2260 /**
2261 Convert val_real() to date in MYSQL_TIME
2262 */
2264 /**
2265 Convert val_decimal() to date in MYSQL_TIME
2266 */
2268 /**
2269 Convert val_int() to date in MYSQL_TIME
2270 */
2272 /**
2273 Convert get_time() from time to date in MYSQL_TIME
2274 */
2275 bool get_date_from_time(MYSQL_TIME *ltime);
2276
2277 /**
2278 Convert a numeric type to date
2279 */
2280 bool get_date_from_numeric(MYSQL_TIME *ltime, my_time_flags_t fuzzydate);
2281
2282 /**
2283 Convert val_str() to time in MYSQL_TIME
2284 */
2285 bool get_time_from_string(MYSQL_TIME *ltime);
2286 /**
2287 Convert val_real() to time in MYSQL_TIME
2288 */
2289 bool get_time_from_real(MYSQL_TIME *ltime);
2290 /**
2291 Convert val_decimal() to time in MYSQL_TIME
2292 */
2293 bool get_time_from_decimal(MYSQL_TIME *ltime);
2294 /**
2295 Convert val_int() to time in MYSQL_TIME
2296 */
2297 bool get_time_from_int(MYSQL_TIME *ltime);
2298 /**
2299 Convert date to time
2300 */
2301 bool get_time_from_date(MYSQL_TIME *ltime);
2302 /**
2303 Convert datetime to time
2304 */
2306
2307 /**
2308 Convert a numeric type to time
2309 */
2310 bool get_time_from_numeric(MYSQL_TIME *ltime);
2311
2313
2315
2316 public:
2320
2321 /**
2322 If this Item is being materialized into a temporary table, returns the
2323 field that is being materialized into. (Typically, this is the
2324 “result_field” members for items that have one.)
2325 */
2327 DBUG_TRACE;
2328 return nullptr;
2329 }
2330 /* This is also used to create fields in CREATE ... SELECT: */
2331 virtual Field *tmp_table_field(TABLE *) { return nullptr; }
2332 virtual const char *full_name() const {
2333 return item_name.is_set() ? item_name.ptr() : "???";
2334 }
2335
2336 /* bit map of tables used by item */
2337 virtual table_map used_tables() const { return (table_map)0L; }
2338
2339 /**
2340 Return table map of tables that can't be NULL tables (tables that are
2341 used in a context where if they would contain a NULL row generated
2342 by a LEFT or RIGHT join, the item would not be true).
2343 This expression is used on WHERE item to determinate if a LEFT JOIN can be
2344 converted to a normal join.
2345 Generally this function should return used_tables() if the function
2346 would return null if any of the arguments are null
2347 As this is only used in the beginning of optimization, the value don't
2348 have to be updated in update_used_tables()
2349 */
2350 virtual table_map not_null_tables() const { return used_tables(); }
2351
2352 /**
2353 Returns true if this is a simple constant item like an integer, not
2354 a constant expression. Used in the optimizer to propagate basic constants.
2355 It is assumed that val_xxx() does not modify the item's state for
2356 such items. It is also assumed that val_str() can be called with nullptr
2357 as argument as val_str() will return an internally cached const string.
2358 */
2359 virtual bool basic_const_item() const { return false; }
2360 /**
2361 @returns true when a const item may be evaluated during resolving.
2362 Only const items that are basic const items are evaluated when
2363 resolving CREATE VIEW statements. For other statements, all
2364 const items may be evaluated during resolving.
2365 */
2366 bool may_eval_const_item(const THD *thd) const;
2367 /**
2368 @return cloned item if it is constant
2369 @retval nullptr if this is not const
2370 */
2371 virtual Item *clone_item() const { return nullptr; }
2372 virtual cond_result eq_cmp_result() const { return COND_OK; }
2373 inline uint float_length(uint decimals_par) const {
2374 return decimals != DECIMAL_NOT_SPECIFIED ? (DBL_DIG + 2 + decimals_par)
2375 : DBL_DIG + 8;
2376 }
2377 virtual uint decimal_precision() const;
2378 inline int decimal_int_part() const {
2380 }
2381 /**
2382 TIME precision of the item: 0..6
2383 */
2384 virtual uint time_precision();
2385 /**
2386 DATETIME precision of the item: 0..6
2387 */
2388 virtual uint datetime_precision();
2389 /**
2390 Returns true if item is constant, regardless of query evaluation state.
2391 An expression is constant if it:
2392 - refers no tables.
2393 - refers no subqueries that refers any tables.
2394 - refers no non-deterministic functions.
2395 - refers no statement parameters.
2396 - contains no group expression under rollup
2397 */
2398 bool const_item() const { return (used_tables() == 0); }
2399 /**
2400 Returns true if item is constant during one query execution.
2401 If const_for_execution() is true but const_item() is false, value is
2402 not available before tables have been locked and parameters have been
2403 assigned values. This applies to
2404 - statement parameters
2405 - non-dependent subqueries
2406 - deterministic stored functions that contain SQL code.
2407 For items where the default implementation of used_tables() and
2408 const_item() are effective, const_item() will always return true.
2409 */
2410 bool const_for_execution() const {
2411 return !(used_tables() & ~INNER_TABLE_BIT);
2412 }
2413
2414 /**
2415 Return true if this is a const item that may be evaluated in
2416 the current phase of statement processing.
2417 - No evaluation is performed when analyzing a view, otherwise:
2418 - Items that have the const_item() property can always be evaluated.
2419 - Items that have the const_for_execution() property can be evaluated when
2420 tables are locked (ie during optimization or execution).
2421
2422 This function should be used in the following circumstances:
2423 - during preparation to check whether an item can be permanently transformed
2424 - to check that an item is constant in functions that may be used in both
2425 the preparation and optimization phases.
2426
2427 This function should not be used by code that is called during optimization
2428 and/or execution only. Use const_for_execution() in this case.
2429 */
2430 bool may_evaluate_const(const THD *thd) const;
2431
2432 /**
2433 @returns true if this item is non-deterministic, which means that a
2434 has a component that must be evaluated once per row in
2435 execution of a JOIN query.
2436 */
2438
2439 /**
2440 @returns true if this item is an outer reference, usually this means that
2441 it references a column that contained in a table located in
2442 the FROM clause of an outer query block.
2443 */
2444 bool is_outer_reference() const {
2446 }
2447
2448 /**
2449 This method is used for to:
2450 - to generate a view definition query (SELECT-statement);
2451 - to generate a SQL-query for EXPLAIN EXTENDED;
2452 - to generate a SQL-query to be shown in INFORMATION_SCHEMA;
2453 - to generate a SQL-query that looks like a prepared statement for
2454 query_rewrite
2455 - debug.
2456
2457 For more information about view definition query, INFORMATION_SCHEMA
2458 query and why they should be generated from the Item-tree, @see
2459 mysql_register_view().
2460 */
2461 virtual void print(const THD *, String *str, enum_query_type) const {
2462 str->append(full_name());
2463 }
2464
2465 void print_item_w_name(const THD *thd, String *,
2466 enum_query_type query_type) const;
2467 /**
2468 Prints the item when it's part of ORDER BY and GROUP BY.
2469 @param thd Thread handle
2470 @param str String to print to
2471 @param query_type How to format the item
2472 @param used_alias The alias with which this item was referenced, or
2473 nullptr if it was not referenced with an alias.
2474 */
2475 void print_for_order(const THD *thd, String *str, enum_query_type query_type,
2476 const char *used_alias) const;
2477
2478 /**
2479 Updates used tables, not null tables information and accumulates
2480 properties up the item tree, cf. used_tables_cache, not_null_tables_cache
2481 and m_accum_properties.
2482
2483 TODO(sgunders): Consider just removing these caches; it causes a lot of bugs
2484 (cache invalidation is known to be a complex problem), and the performance
2485 benefits are dubious.
2486 */
2487 virtual void update_used_tables() {}
2488
2490 return false;
2491 }
2492 /* Called for items that really have to be split */
2493 bool split_sum_func2(THD *thd, Ref_item_array ref_item_array,
2494 mem_root_deque<Item *> *fields, Item **ref,
2495 bool skip_registered);
2496 virtual bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) = 0;
2497 virtual bool get_time(MYSQL_TIME *ltime) = 0;
2498 /**
2499 Get timestamp in "struct timeval" format.
2500 @retval false on success
2501 @retval true on error
2502 */
2503 virtual bool get_timeval(my_timeval *tm, int *warnings);
2504 /**
2505 The method allows to determine nullness of a complex expression
2506 without fully evaluating it, instead of calling val*() then
2507 checking null_value. Used in Item_func_isnull/Item_func_isnotnull
2508 and Item_sum_count/Item_sum_count_distinct.
2509 Any item which can be NULL must implement this method.
2510
2511 @retval false if the expression is not NULL.
2512 @retval true if the expression is NULL, or evaluation caused an error.
2513 The null_value member is set according to the return value.
2514 */
2515 virtual bool is_null() { return false; }
2516
2517 /**
2518 Make sure the null_value member has a correct value.
2519 null_value is set true also when evaluation causes error.
2520
2521 @returns false if success, true if error
2522 */
2523 bool update_null_value();
2524
2525 /**
2526 Apply the IS TRUE truth property, meaning that an UNKNOWN result and a
2527 FALSE result are treated the same.
2528
2529 This property is applied e.g to all conditions in WHERE, HAVING and ON
2530 clauses, and is recursively applied to operands of AND, OR
2531 operators. Some items (currently AND and subquery predicates) may enable
2532 special optimizations when they have this property.
2533 */
2534 virtual void apply_is_true() {}
2535 /*
2536 set field of temporary table for Item which can be switched on temporary
2537 table during query processing (grouping and so on). @see
2538 Item_result_field.
2539 */
2540 virtual void set_result_field(Field *) {}
2541 virtual bool is_result_field() const { return false; }
2542 virtual Field *get_result_field() const { return nullptr; }
2543 virtual bool is_bool_func() const { return false; }
2544 /*
2545 Set value of aggregate function in case of no rows for grouping were found.
2546 Also used for subqueries with outer references in SELECT list.
2547 */
2548 virtual void no_rows_in_result() {}
2549 virtual Item *copy_or_same(THD *) { return this; }
2550 virtual Item *copy_andor_structure(THD *) { return this; }
2551 /**
2552 @returns the "real item" underlying the owner object. Used to strip away
2553 Item_ref objects.
2554 @note remember to implement both real_item() functions in sub classes!
2555 */
2556 virtual Item *real_item() { return this; }
2557 virtual const Item *real_item() const { return this; }
2558 /**
2559 If an Item is materialized in a temporary table, a different Item may have
2560 to be used in the part of the query that runs after the materialization.
2561 For instance, if the Item was an Item_field, the new Item_field needs to
2562 point into the temporary table instead of the original one, but if, on the
2563 other hand, the Item was a literal constant, it can be reused as-is.
2564 This function encapsulates these policies for the different kinds of Items.
2565 See also get_tmp_table_field().
2566
2567 TODO: Document how aggregate functions (Item_sum) are handled.
2568 */
2569 virtual Item *get_tmp_table_item(THD *thd) { return copy_or_same(thd); }
2570
2571 static const CHARSET_INFO *default_charset();
2572 virtual const CHARSET_INFO *compare_collation() const { return nullptr; }
2573
2574 /*
2575 For backward compatibility, to make numeric
2576 data types return "binary" charset in client-side metadata.
2577 */
2580 : &my_charset_bin;
2581 }
2582
2583 /**
2584 Traverses a tree of Items in prefix and/or postfix order.
2585 Optionally walks into subqueries.
2586
2587 @param processor processor function to be invoked per item
2588 returns true to abort traversal, false to continue
2589 @param walk controls how to traverse the item tree
2590 enum_walk::PREFIX: call processor before invoking
2591 children enum_walk::POSTFIX: call processor after invoking children
2592 enum_walk::SUBQUERY go down into subqueries
2593 walk values are bit-coded and may be combined.
2594 Omitting both enum_walk::PREFIX and enum_walk::POSTFIX
2595 is undefined behaviour.
2596 @param arg Optional pointer to a walk-specific object
2597
2598 @retval false walk succeeded
2599 @retval true walk aborted
2600 by agreement, an error may have been reported
2601 */
2602
2603 virtual bool walk(Item_processor processor, enum_walk walk [[maybe_unused]],
2604 uchar *arg) {
2605 return (this->*processor)(arg);
2606 }
2607
2608 /** @see WalkItem, CompileItem, TransformItem */
2609 template <class T>
2611 return (*reinterpret_cast<std::remove_reference_t<T> *>(arg))(this);
2612 }
2613
2614 /** See CompileItem */
2615 template <class T>
2617 return (*reinterpret_cast<std::remove_reference_t<T> *>(*arg))(this);
2618 }
2619
2620 /**
2621 Perform a generic transformation of the Item tree, by adding zero or
2622 more additional Item objects to it.
2623
2624 @param transformer Transformer function
2625 @param[in,out] arg Pointer to struct used by transformer function
2626
2627 @returns Returned item tree after transformation, NULL if error
2628
2629 Transformation is performed as follows:
2630
2631 @code
2632 transform()
2633 {
2634 transform children if any;
2635 return this->*some_transformer(...);
2636 }
2637 @endcode
2638
2639 Note that unlike Item::compile(), transform() does not support an analyzer
2640 function, ie. all children are unconditionally invoked.
2641
2642 Item::transform() should handle all transformations during preparation.
2643 Notice that all transformations are permanent; they are not rolled back.
2644
2645 Use Item::compile() to perform transformations during optimization.
2646 */
2647 virtual Item *transform(Item_transformer transformer, uchar *arg);
2648
2649 /**
2650 Perform a generic "compilation" of the Item tree, ie transform the Item tree
2651 by adding zero or more Item objects to it.
2652
2653 @param analyzer Analyzer function, see details section
2654 @param[in,out] arg_p Pointer to struct used by analyzer function
2655 @param transformer Transformer function, see details section
2656 @param[in,out] arg_t Pointer to struct used by transformer function
2657
2658 @returns Returned item tree after transformation, NULL if error
2659
2660 The process of this transformation is assumed to be as follows:
2661
2662 @code
2663 compile()
2664 {
2665 if (this->*some_analyzer(...))
2666 {
2667 compile children if any;
2668 return this->*some_transformer(...);
2669 }
2670 else
2671 return this;
2672 }
2673 @endcode
2674
2675 i.e. analysis is performed top-down while transformation is done
2676 bottom-up. If no transformation is applied, the item is returned unchanged.
2677 A transformation error is indicated by returning a NULL pointer. Notice
2678 that the analyzer function should never cause an error.
2679
2680 The function is supposed to be used during the optimization stage of
2681 query execution. All new allocations are recorded using
2682 THD::change_item_tree() so that they can be rolled back after execution.
2683
2684 @todo Pass THD to compile() function, thus no need to use current_thd.
2685 */
2686 virtual Item *compile(Item_analyzer analyzer, uchar **arg_p,
2687 Item_transformer transformer, uchar *arg_t) {
2688 if ((this->*analyzer)(arg_p)) return ((this->*transformer)(arg_t));
2689 return this;
2690 }
2691
2692 virtual void traverse_cond(Cond_traverser traverser, void *arg,
2694 (*traverser)(this, arg);
2695 }
2696
2697 /*
2698 This is used to get the most recent version of any function in
2699 an item tree. The version is the version where a MySQL function
2700 was introduced in. So any function which is added should use
2701 this function and set the int_arg to maximum of the input data
2702 and their own version info.
2703 */
2704 virtual bool intro_version(uchar *) { return false; }
2705
2706 /// cleanup() item if it is resolved ('fixed').
2708 if (fixed) cleanup();
2709 return false;
2710 }
2711
2712 virtual bool collect_item_field_processor(uchar *) { return false; }
2713 virtual bool collect_item_field_or_ref_processor(uchar *) { return false; }
2714
2716 public:
2719 : m_items(fields_or_refs) {}
2722 const Collect_item_fields_or_refs &) = delete;
2723
2724 friend class Item_sum;
2725 friend class Item_field;
2726 friend class Item_ref;
2727 };
2728
2730 public:
2733 /// Used to compute \c Item_field's \c m_protected_by_any_value. Pushed and
2734 /// popped when walking arguments of \c Item_func_any_value.a
2737 Query_block *transformed_block)
2738 : m_item_fields_or_view_refs(fields_or_vr),
2739 m_transformed_block(transformed_block) {}
2741 delete;
2743 const Collect_item_fields_or_view_refs &) = delete;
2744
2745 friend class Item_sum;
2746 friend class Item_field;
2748 friend class Item_view_ref;
2749 };
2750
2751 /**
2752 Collects fields and view references that have the qualifying table
2753 in the specified query block.
2754 */
2756 return false;
2757 }
2758
2759 /**
2760 Item::walk function. Set bit in table->tmp_set for all fields in
2761 table 'arg' that are referred to by the Item.
2762 */
2763 virtual bool add_field_to_set_processor(uchar *) { return false; }
2764
2765 /// A processor to handle the select lex visitor framework.
2766 virtual bool visitor_processor(uchar *arg);
2767
2768 /**
2769 Item::walk function. Set bit in table->cond_set for all fields of
2770 all tables that are referred to by the Item.
2771 */
2772 virtual bool add_field_to_cond_set_processor(uchar *) { return false; }
2773
2774 /**
2775 Visitor interface for removing all column expressions (Item_field) in
2776 this expression tree from a bitmap. @see walk()
2777
2778 @param arg A MY_BITMAP* cast to unsigned char*, where the bits represent
2779 Field::field_index values.
2780 */
2781 virtual bool remove_column_from_bitmap(uchar *arg [[maybe_unused]]) {
2782 return false;
2783 }
2784 virtual bool find_item_in_field_list_processor(uchar *) { return false; }
2785 virtual bool change_context_processor(uchar *) { return false; }
2786 virtual bool find_item_processor(uchar *arg) { return this == (void *)arg; }
2788 return !basic_const_item();
2789 }
2790 /// Is this an Item_field which references the given Field argument?
2791 virtual bool find_field_processor(uchar *) { return false; }
2792 /// Wrap incompatible arguments in CAST nodes to the expected data types
2793 virtual bool cast_incompatible_args(uchar *) { return false; }
2794 /**
2795 Mark underlying field in read or write map of a table.
2796
2797 @param arg Mark_field object
2798 */
2799 virtual bool mark_field_in_map(uchar *arg [[maybe_unused]]) { return false; }
2800
2801 protected:
2802 /**
2803 Helper function for mark_field_in_map(uchar *arg).
2804
2805 @param mark_field Mark_field object
2806 @param field Field to be marked for read/write
2807 */
2808 static inline bool mark_field_in_map(Mark_field *mark_field, Field *field) {
2809 TABLE *table = mark_field->table;
2810 if (table != nullptr && table != field->table) return false;
2811
2812 table = field->table;
2813 table->mark_column_used(field, mark_field->mark);
2814
2815 return false;
2816 }
2817
2818 public:
2819 /**
2820 Reset execution state for such window function types
2821 as determined by arg
2822
2823 @param arg pointing to a bool which, if true, says to reset state
2824 for framing window function, else for non-framing
2825 */
2826 virtual bool reset_wf_state(uchar *arg [[maybe_unused]]) { return false; }
2827
2828 /**
2829 Return used table information for the specified query block (level).
2830 For a field that is resolved from this query block, return the table number.
2831 For a field that is resolved from a query block outer to the specified one,
2832 return OUTER_REF_TABLE_BIT
2833
2834 @param[in,out] arg pointer to an instance of class Used_tables, which is
2835 constructed with the query block as argument.
2836 The used tables information is accumulated in the field
2837 used_tables in this class.
2838
2839 @note This function is used to update used tables information after
2840 merging a query block (a subquery) with its parent.
2841 */
2842 virtual bool used_tables_for_level(uchar *arg [[maybe_unused]]) {
2843 return false;
2844 }
2845 /**
2846 Check privileges.
2847
2848 @param thd thread handle
2849 */
2850 virtual bool check_column_privileges(uchar *thd [[maybe_unused]]) {
2851 return false;
2852 }
2853 virtual bool inform_item_in_cond_of_tab(uchar *) { return false; }
2854 /**
2855 Bind objects from the current execution context to field objects in
2856 item trees. Typically used to bind Field objects from TABLEs to
2857 Item_field objects.
2858 */
2859 virtual void bind_fields() {}
2860
2861 /**
2862 Context object for (functions that override)
2863 Item::clean_up_after_removal().
2864 */
2866 public:
2868 assert(root != nullptr);
2869 }
2870
2872
2873 private:
2874 /**
2875 Pointer to Cleanup_after_removal_context containing from which
2876 select the walk started, i.e., the Query_block that contained the clause
2877 that was removed.
2878 */
2880
2881 friend class Item;
2882 friend class Item_sum;
2883 friend class Item_subselect;
2884 friend class Item_ref;
2885 };
2886 /**
2887 Clean up after removing the item from the item tree.
2888
2889 param arg pointer to a Cleanup_after_removal_context object
2890 @todo: If class ORDER is refactored so that all indirect
2891 grouping/ordering expressions are represented with Item_ref
2892 objects, all implementations of cleanup_after_removal() except
2893 the one for Item_ref can be removed.
2894 */
2895 virtual bool clean_up_after_removal(uchar *arg);
2896
2897 /// @see Distinct_check::check_query()
2898 virtual bool aggregate_check_distinct(uchar *) { return false; }
2899 /// @see Group_check::check_query()
2900 virtual bool aggregate_check_group(uchar *) { return false; }
2901 /// @see Group_check::analyze_conjunct()
2902 virtual bool is_strong_side_column_not_in_fd(uchar *) { return false; }
2903 /// @see Group_check::is_in_fd_of_underlying()
2904 virtual bool is_column_not_in_fd(uchar *) { return false; }
2905 virtual Bool3 local_column(const Query_block *) const {
2906 return Bool3::false3();
2907 }
2908
2909 /**
2910 Minion class under Collect_scalar_subquery_info. Information about one
2911 scalar subquery being considered for transformation
2912 */
2913 struct Css_info {
2914 /// set of locations
2916 /// the scalar subquery
2919 /// Where did we find item above? Used when m_location == L_JOIN_COND,
2920 /// nullptr for other locations.
2922 /// If true, we can forego cardinality checking of the derived table
2924 /// If true, add a COALESCE around replaced subquery: used for implicitly
2925 /// grouped COUNT() in subquery select list when subquery is correlated
2926 bool m_add_coalesce{false};
2927 };
2928
2929 /**
2930 Context struct used by walk method collect_scalar_subqueries to
2931 accumulate information about scalar subqueries found.
2932
2933 In: m_location of expression walked, m_join_condition_context
2934 Out: m_list
2935 */
2937 enum Location { L_SELECT = 1, L_WHERE = 2, L_HAVING = 4, L_JOIN_COND = 8 };
2938 /// accumulated all scalar subqueries found
2939 std::vector<Css_info> m_list;
2940 /// we are currently looking at this kind of clause, cf. enum Location
2945 friend class Item_sum;
2947 };
2948
2949 virtual bool collect_scalar_subqueries(uchar *) { return false; }
2950 virtual bool collect_grouped_aggregates(uchar *) { return false; }
2951 virtual bool collect_subqueries(uchar *) { return false; }
2952 virtual bool update_depended_from(uchar *) { return false; }
2953 /**
2954 Check if an aggregate is referenced from within the GROUP BY
2955 clause of the query block in which it is aggregated. Such
2956 references will be rejected.
2957 @see Item_ref::fix_fields()
2958 @retval true if this is an aggregate which is referenced from
2959 the GROUP BY clause of the aggregating query block
2960 @retval false otherwise
2961 */
2962 virtual bool has_aggregate_ref_in_group_by(uchar *) { return false; }
2963
2964 bool visit_all_analyzer(uchar **) { return true; }
2965 virtual bool cache_const_expr_analyzer(uchar **cache_item);
2967
2968 virtual bool equality_substitution_analyzer(uchar **) { return false; }
2969
2970 virtual Item *equality_substitution_transformer(uchar *) { return this; }
2971
2972 /**
2973 Check if a partition function is allowed.
2974
2975 @return whether a partition function is not accepted
2976
2977 @details
2978 check_partition_func_processor is used to check if a partition function
2979 uses an allowed function. An allowed function will always ensure that
2980 X=Y guarantees that also part_function(X)=part_function(Y) where X is
2981 a set of partition fields and so is Y. The problems comes mainly from
2982 character sets where two equal strings can be quite unequal. E.g. the
2983 german character for double s is equal to 2 s.
2984
2985 The default is that an item is not allowed
2986 in a partition function. Allowed functions
2987 can never depend on server version, they cannot depend on anything
2988 related to the environment. They can also only depend on a set of
2989 fields in the table itself. They cannot depend on other tables and
2990 cannot contain any queries and cannot contain udf's or similar.
2991 If a new Item class is defined and it inherits from a class that is
2992 allowed in a partition function then it is very important to consider
2993 whether this should be inherited to the new class. If not the function
2994 below should be defined in the new Item class.
2995
2996 The general behaviour is that most integer functions are allowed.
2997 If the partition function contains any multi-byte collations then
2998 the function check_part_func_fields will report an error on the
2999 partition function independent of what functions are used. So the
3000 only character sets allowed are single character collation and
3001 even for those only a limited set of functions are allowed. The
3002 problem with multi-byte collations is that almost every string
3003 function has the ability to change things such that two strings
3004 that are equal will not be equal after manipulated by a string
3005 function. E.g. two strings one contains a double s, there is a
3006 special german character that is equal to two s. Now assume a
3007 string function removes one character at this place, then in
3008 one the double s will be removed and in the other there will
3009 still be one s remaining and the strings are no longer equal
3010 and thus the partition function will not sort equal strings into
3011 the same partitions.
3012
3013 So the check if a partition function is valid is two steps. First
3014 check that the field types are valid, next check that the partition
3015 function is valid. The current set of partition functions valid
3016 assumes that there are no multi-byte collations amongst the partition
3017 fields.
3018 */
3019 virtual bool check_partition_func_processor(uchar *) { return true; }
3020 virtual bool subst_argument_checker(uchar **arg) {
3021 if (*arg) *arg = nullptr;
3022 return true;
3023 }
3024 virtual bool explain_subquery_checker(uchar **) { return true; }
3025 virtual Item *explain_subquery_propagator(uchar *) { return this; }
3026
3027 virtual Item *equal_fields_propagator(uchar *) { return this; }
3028 // Mark the item to not be part of substitution.
3029 virtual bool disable_constant_propagation(uchar *) { return false; }
3030
3032 // Stack of pointers to enclosing functions
3034 };
3035 virtual Item *replace_equal_field(uchar *) { return this; }
3036 virtual bool replace_equal_field_checker(uchar **) { return true; }
3037 /*
3038 Check if an expression value has allowed arguments, like DATE/DATETIME
3039 for date functions. Also used by partitioning code to reject
3040 timezone-dependent expressions in a (sub)partitioning function.
3041 */
3042 virtual bool check_valid_arguments_processor(uchar *) { return false; }
3043
3044 /**
3045 Check if this item is allowed for a virtual column or inside a
3046 default expression. Should be overridden in child classes.
3047
3048 @param[in,out] args Due to the limitation of Item::walk()
3049 it is declared as a pointer to uchar, underneath there's a actually a
3050 structure of type Check_function_as_value_generator_parameters.
3051 It is used mainly in Item_field.
3052
3053 @returns true if function is not accepted
3054 */
3055 virtual bool check_function_as_value_generator(uchar *args);
3056
3057 /**
3058 Check if a generated expression depends on DEFAULT function with
3059 specific column name as argument.
3060
3061 @param[in] args Name of column used as DEFAULT function argument.
3062
3063 @returns false if the function is not DEFAULT(args), otherwise true.
3064 */
3066 [[maybe_unused]]) {
3067 return false;
3068 }
3069 /**
3070 Check if all the columns present in this expression are from the
3071 derived table. Used in determining if a condition can be pushed
3072 down to derived table.
3073 */
3074 virtual bool is_valid_for_pushdown(uchar *arg [[maybe_unused]]) {
3075 // A generic item cannot be pushed down unless it's a constant
3076 // which does not have a subquery.
3077 return !const_item() || has_subquery();
3078 }
3079
3080 /**
3081 Check if all the columns present in this expression are present
3082 in PARTITION clause of window functions of the derived table.
3083 Used in checking if a condition can be pushed down to derived table.
3084 */
3085 virtual bool check_column_in_window_functions(uchar *arg [[maybe_unused]]) {
3086 return false;
3087 }
3088 /**
3089 Check if all the columns present in this expression are present
3090 in GROUP BY clause of the derived table. Used in checking if
3091 a condition can be pushed down to derived table.
3092 */
3093 virtual bool check_column_in_group_by(uchar *arg [[maybe_unused]]) {
3094 return false;
3095 }
3096 /**
3097 Assuming this expression is part of a condition that would be pushed to the
3098 WHERE clause of a materialized derived table, replace, in this expression,
3099 each derived table's column with a clone of the expression lying under it
3100 in the derived table's definition. We replace with a clone, because the
3101 condition can be pushed further down in case of nested derived tables.
3102 */
3103 virtual Item *replace_with_derived_expr(uchar *arg [[maybe_unused]]) {
3104 return this;
3105 }
3106 /**
3107 Assuming this expression is part of a condition that would be pushed to the
3108 HAVING clause of a materialized derived table, replace, in this expression,
3109 each derived table's column with a reference to the expression lying under
3110 it in the derived table's definition. Unlike replace_with_derived_expr, a
3111 clone is not used because HAVING condition will not be pushed further
3112 down in case of nested derived tables.
3113 */
3114 virtual Item *replace_with_derived_expr_ref(uchar *arg [[maybe_unused]]) {
3115 return this;
3116 }
3117 /**
3118 Assuming this expression is part of a condition that would be pushed to a
3119 materialized derived table, replace, in this expression, each view reference
3120 with a clone of the expression in merged derived table's definition.
3121 We replace with a clone, because the referenced item in a view reference
3122 is shared by all the view references to that expression.
3123 */
3124 virtual Item *replace_view_refs_with_clone(uchar *arg [[maybe_unused]]) {
3125 return this;
3126 }
3127 /*
3128 For SP local variable returns pointer to Item representing its
3129 current value and pointer to current Item otherwise.
3130 */
3131 virtual Item *this_item() { return this; }
3132 virtual const Item *this_item() const { return this; }
3133
3134 /*
3135 For SP local variable returns address of pointer to Item representing its
3136 current value and pointer passed via parameter otherwise.
3137 */
3138 virtual Item **this_item_addr(THD *, Item **addr_arg) { return addr_arg; }
3139
3140 // Row emulation
3141 virtual uint cols() const { return 1; }
3142 virtual Item *element_index(uint) { return this; }
3143 virtual Item **addr(uint) { return nullptr; }
3144 virtual bool check_cols(uint c);
3145 // It is not row => null inside is impossible
3146 virtual bool null_inside() { return false; }
3147 // used in row subselects to get value of elements
3148 virtual void bring_value() {}
3149
3150 Field *tmp_table_field_from_field_type(TABLE *table, bool fixed_length) const;
3151 virtual Item_field *field_for_view_update() { return nullptr; }
3152 /**
3153 Informs an item that it is wrapped in a truth test, in case it wants to
3154 transforms itself to implement this test by itself.
3155 @param thd Thread handle
3156 @param test Truth test
3157 */
3158 virtual Item *truth_transformer(THD *thd [[maybe_unused]],
3159 Bool_test test [[maybe_unused]]) {
3160 return nullptr;
3161 }
3162 virtual Item *update_value_transformer(uchar *) { return this; }
3163
3165 Query_block *m_trans_block; ///< Transformed query block
3166 Query_block *m_curr_block; ///< Transformed query block or a contained
3167 ///< subquery. Pushed when diving into
3168 ///< subqueries.
3169 Item_replacement(Query_block *transformed_block, Query_block *current_block)
3170 : m_trans_block(transformed_block), m_curr_block(current_block) {}
3171 };
3173 Field *m_target; ///< The field to be replaced
3174 Item_field *m_item; ///< The replacement field
3175 enum class Mode {
3176 CONFLATE, // include both Item_field and Item_default_value
3177 FIELD, // ignore Item_default_value
3178 DEFAULT_VALUE // ignore Item_field
3179 };
3182 Mode default_value = Mode::CONFLATE)
3183 : Item_replacement(select, select),
3184 m_target(target),
3185 m_item(item),
3186 m_default_value(default_value) {}
3187 };
3188
3190 Item *m_target; ///< The item identifying the view_ref to be replaced
3191 Field *m_field; ///< The replacement field
3192 ///< subquery. Pushed when diving into
3193 ///< subqueries.
3195 : Item_replacement(select, select), m_target(target), m_field(field) {}
3196 };
3197
3202 : m_target(target), m_replacement(replacement) {}
3203 };
3204
3205 /**
3206 When walking the item tree seeing an Item_singlerow_subselect matching
3207 a target, replace it with a substitute field used when transforming
3208 scalar subqueries into derived tables. Cf.
3209 Query_block::transform_scalar_subqueries_to_join_with_derived.
3210 */
3211 virtual Item *replace_scalar_subquery(uchar *) { return this; }
3212
3213 /**
3214 Transform processor used by Query_block::transform_grouped_to_derived
3215 to replace fields which used to be at the transformed query block
3216 with corresponding fields in the new derived table containing the grouping
3217 operation of the original transformed query block.
3218 */
3219 virtual Item *replace_item_field(uchar *) { return this; }
3220 virtual Item *replace_item_view_ref(uchar *) { return this; }
3221 virtual Item *replace_aggregate(uchar *) { return this; }
3222 virtual Item *replace_outer_ref(uchar *) { return this; }
3223
3228 : m_target(target), m_owner(owner) {}
3229 };
3230
3231 /**
3232 A walker processor overridden by Item_aggregate_ref, q.v.
3233 */
3234 virtual bool update_aggr_refs(uchar *) { return false; }
3235
3236 virtual Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs);
3237 /**
3238 Delete this item.
3239 Note that item must have been cleanup up by calling Item::cleanup().
3240 */
3241 void delete_self() { delete this; }
3242
3243 /** @return whether the item is local to a stored procedure */
3244 virtual bool is_splocal() const { return false; }
3245
3246 /*
3247 Return Settable_routine_parameter interface of the Item. Return 0
3248 if this Item is not Settable_routine_parameter.
3249 */
3251 return nullptr;
3252 }
3253 inline bool is_temporal_with_date() const {
3255 }
3258 }
3259 inline bool is_temporal_with_time() const {
3261 }
3262 inline bool is_temporal() const {
3264 }
3265 /**
3266 Check whether this and the given item has compatible comparison context.
3267 Used by the equality propagation. See Item_field::equal_fields_propagator.
3268
3269 @return
3270 true if the context is the same or if fields could be
3271 compared as DATETIME values by the Arg_comparator.
3272 false otherwise.
3273 */
3274 inline bool has_compatible_context(Item *item) const {
3275 // If no explicit context has been set, assume the same type as the item
3276 const Item_result this_context =
3278 const Item_result other_context = item->cmp_context == INVALID_RESULT
3279 ? item->result_type()
3280 : item->cmp_context;
3281
3282 // Check if both items have the same context
3283 if (this_context == other_context) {
3284 return true;
3285 }
3286 /* DATETIME comparison context. */
3288 return item->is_temporal_with_date() || other_context == STRING_RESULT;
3289 if (item->is_temporal_with_date())
3290 return is_temporal_with_date() || this_context == STRING_RESULT;
3291 return false;
3292 }
3294 return Field::GEOM_GEOMETRY;
3295 }
3296 String *check_well_formed_result(String *str, bool send_error, bool truncate);
3297 bool eq_by_collation(Item *item, bool binary_cmp, const CHARSET_INFO *cs);
3298
3300 m_cost.Compute(*this);
3301 return m_cost;
3302 }
3303
3304 /**
3305 @return maximum number of characters that this Item can store
3306 If Item is of string or blob type, return max string length in bytes
3307 divided by bytes per character, otherwise return max_length.
3308 @todo - check if collation for other types should have mbmaxlen = 1
3309 */
3311 /*
3312 Length of e.g. 5.5e5 in an expression such as GREATEST(5.5e5, '5') is 5
3313 (length of that string) although length of the actual value is 6.
3314 Return MAX_DOUBLE_STR_LENGTH to prevent truncation of data without having
3315 to evaluate the value of the item.
3316 */
3317 const uint32 max_len =
3319 if (result_type() == STRING_RESULT)
3320 return max_len / collation.collation->mbmaxlen;
3321 return max_len;
3322 }
3323
3325 if (cs == &my_charset_bin && result_type() == STRING_RESULT) {
3326 return max_length;
3327 }
3328 return max_char_length();
3329 }
3330
3331 inline void fix_char_length(uint32 max_char_length_arg) {
3332 max_length = char_to_byte_length_safe(max_char_length_arg,
3334 }
3335
3336 /*
3337 Return true if the item points to a column of an outer-joined table.
3338 */
3339 virtual bool is_outer_field() const {
3340 assert(fixed);
3341 return false;
3342 }
3343
3344 /**
3345 Check if an item either is a blob field, or will be represented as a BLOB
3346 field if a field is created based on this item.
3347
3348 @retval true If a field based on this item will be a BLOB field,
3349 @retval false Otherwise.
3350 */
3351 bool is_blob_field() const;
3352
3353 /// @returns number of references to an item.
3354 uint reference_count() const { return m_ref_count; }
3355
3356 /// Increment reference count
3358 assert(!m_abandoned);
3359 ++m_ref_count;
3360 }
3361
3362 /// Decrement reference count
3364 assert(m_ref_count > 0);
3365 if (--m_ref_count == 0) m_abandoned = true;
3366 return m_ref_count;
3367 }
3368
3369 protected:
3370 /// Set accumulated properties for an Item
3371 void set_accum_properties(const Item *item) {
3373 }
3374
3375 /// Add more accumulated properties to an Item
3376 void add_accum_properties(const Item *item) {
3378 }
3379
3380 /// Set the "has subquery" property
3382
3383 /// Set the "has stored program" property
3385
3386 public:
3387 /// @return true if this item or any of its descendants contains a subquery.
3389
3390 /// @return true if this item or any of its descendants refers a stored func.
3391 bool has_stored_program() const {
3393 }
3394
3395 /// @return true if this item or any of its descendants is an aggregated func.
3397
3398 /// Set the "has aggregation" property
3400
3401 /// Reset the "has aggregation" property
3402 void reset_aggregation() { m_accum_properties &= ~PROP_AGGREGATION; }
3403
3404 /// @return true if this item or any of its descendants is a window func.
3406
3407 /// Set the "has window function" property
3409
3410 /**
3411 @return true if this item or any of its descendants within the same query
3412 has a reference to a GROUP BY modifier (such as ROLLUP)
3413 */
3416 }
3417
3418 /**
3419 Set the property: this item (tree) contains a reference to a GROUP BY
3420 modifier (such as ROLLUP)
3421 */
3424 }
3425
3426 /**
3427 @return true if this item or any of underlying items is a GROUPING function
3428 */
3429 bool has_grouping_func() const {
3431 }
3432
3433 /// Set the property: this item is a call to GROUPING
3435
3436 /// Whether this Item was created by the IN->EXISTS subquery transformation
3437 virtual bool created_by_in2exists() const { return false; }
3438
3440 if (has_subquery())
3442 }
3443
3444 /**
3445 Analyzer function for GC substitution. @see substitute_gc()
3446 */
3447 virtual bool gc_subst_analyzer(uchar **) { return false; }
3448 /**
3449 Transformer function for GC substitution. @see substitute_gc()
3450 */
3451 virtual Item *gc_subst_transformer(uchar *) { return this; }
3452
3453 /**
3454 A processor that replaces any Fields with a Create_field_wrapper. This
3455 will allow us to resolve functions during CREATE TABLE, where we only have
3456 Create_field available and not Field. Used for functional index
3457 implementation.
3458 */
3459 virtual bool replace_field_processor(uchar *) { return false; }
3460 /**
3461 Check if this item is of a type that is eligible for GC
3462 substitution. All items that belong to subclasses of Item_func are
3463 eligible for substitution. @see substitute_gc()
3464 Item_fields can also be eligible if they are given as an argument to
3465 a function that takes an array (the field can be substituted with a
3466 generated column that backs a multi-valued index on that field).
3467
3468 @param array true if the item is an argument to a function that takes an
3469 array, or false otherwise
3470 @return true if the expression is eligible for substitution, false otherwise
3471 */
3472 bool can_be_substituted_for_gc(bool array = false) const;
3473
3475 uint nitems);
3476 void aggregate_decimal_properties(Item **items, uint nitems);
3477 uint32 aggregate_char_width(Item **items, uint nitems);
3479 uint nitems);
3481 Item **items, uint nitems);
3482 void aggregate_bit_properties(Item **items, uint nitems);
3483
3484 /**
3485 This function applies only to Item_field objects referred to by an Item_ref
3486 object that has been marked as a const_item.
3487
3488 @param arg Keep track of whether an Item_ref refers to an Item_field.
3489 */
3490 virtual bool repoint_const_outer_ref(uchar *arg [[maybe_unused]]) {
3491 return false;
3492 }
3493 virtual bool strip_db_table_name_processor(uchar *) { return false; }
3494
3495 /**
3496 Compute the cost of evaluating this Item.
3497 @param root_cost The cost object to which the cost should be added.
3498 */
3499 virtual void compute_cost(CostOfItem *root_cost [[maybe_unused]]) const {}
3500
3501 bool is_abandoned() const { return m_abandoned; }
3502
3503 private:
3504 virtual bool subq_opt_away_processor(uchar *) { return false; }
3505
3506 public: // Start of data fields
3507 /**
3508 Intrusive list pointer for free list. If not null, points to the next
3509 Item on some Query_arena's free list. For instance, stored procedures
3510 have their own Query_arena's.
3511
3512 @see Query_arena::free_list
3513 */
3515
3516 protected:
3517 /// str_values's main purpose is to cache the value in save_in_field
3519
3520 public:
3521 /**
3522 Character set and collation properties assigned for this Item.
3523 Used if Item represents a character string expression.
3524 */
3526 Item_name_string item_name; ///< Name from query
3527 Item_name_string orig_name; ///< Original item name (if it was renamed)
3528 /**
3529 Maximum length of result of evaluating this item, in number of bytes.
3530 - For character or blob data types, max char length multiplied by max
3531 character size (collation.mbmaxlen).
3532 - For decimal type, it is the precision in digits plus sign (unless
3533 unsigned) plus decimal point (unless it has zero decimals).
3534 - For other numeric types, the default or specific display length.
3535 - For date/time types, the display length (10 for DATE, 10 + optional FSP
3536 for TIME, 19 + optional fsp for datetime/timestamp).
3537 - For bit, the number of bits.
3538 - For enum, the string length of the widest enum element.
3539 - For set, the sum of the string length of each set element plus separators.
3540 - For geometry, the maximum size of a BLOB (it's underlying storage type).
3541 - For json, the maximum size of a BLOB (it's underlying storage type).
3542 */
3543 uint32 max_length; ///< Maximum length, in bytes
3544 enum item_marker ///< Values for member 'marker'
3546 /// When contextualization or itemization adds an implicit comparison '0<>'
3547 /// (see make_condition()), to record that this Item_func_ne was created for
3548 /// this purpose; this value is tested during resolution.
3550 /// When doing constant propagation (e.g. change_cond_ref_to_const(), to
3551 /// remember that we have already processed the item.
3553 /// When creating an internal temporary table: says how to store BIT fields.
3555 /// When analyzing functional dependencies for only_full_group_by (says
3556 /// whether a nullable column can be treated at not nullable).
3558 /// When we change DISTINCT to GROUP BY: used for book-keeping of
3559 /// fields.
3561 /// When pushing conditions down to derived table: it says a condition
3562 /// contains only derived table's columns.
3564 /// Used during traversal to avoid deleting an item twice.
3566 /// When pushing index conditions: it says whether a condition uses only
3567 /// indexed columns.
3569 /**
3570 This member has several successive meanings, depending on the phase we're
3571 in (@see item_marker).
3572 The important property is that a phase must have a value (or few values)
3573 which is reserved for this phase. If it wants to set "marked", it assigns
3574 the value; it it wants to test if it is marked, it tests marker !=
3575 value. If the value has been assigned and the phase wants to cancel it can
3576 set marker to MARKER_NONE, which is a magic number which no phase
3577 reserves.
3578 A phase can expect 'marker' to be MARKER_NONE at the start of execution of
3579 a normal statement, at the start of preparation of a PS, and at the start
3580 of execution of a PS.
3581 A phase should not expect marker's value to survive after the phase's
3582 end - as a following phase may change it.
3583 */
3585 Item_result cmp_context; ///< Comparison context
3586 private:
3587 /**
3588 Number of references to this item. It is used for two purposes:
3589 1. When eliminating redundant expressions, the reference count is used
3590 to tell how many Item_ref objects that point to an item. When a
3591 sub-tree of items is eliminated, it is traversed and any item that
3592 is referenced from an Item_ref has its reference count decremented.
3593 Only when the reference count reaches zero is the item actually deleted.
3594 2. Keeping track of unused expressions selected from merged derived tables.
3595 An item that is added to the select list of a query block has its
3596 reference count set to 1. Any references from outer query blocks are
3597 through Item_ref objects, thus they will cause the reference count
3598 to be incremented. At end of resolving, the reference counts of all
3599 items in select list of merged derived tables are decremented, thus
3600 if the reference count becomes zero, the expression is known to
3601 be unused and can be removed.
3602 */
3604 bool m_abandoned{false}; ///< true if item has been fully de-referenced
3605 const bool is_parser_item; ///< true if allocated directly by parser
3606 uint8 m_data_type; ///< Data type assigned to Item
3607
3608 /**
3609 The cost of evaluating this item. This is only needed for predicates,
3610 therefore we use lazy evaluation.
3611 */
3613
3614 public:
3615 bool fixed; ///< True if item has been resolved
3616 /**
3617 Number of decimals in result when evaluating this item
3618 - For integer type, always zero.
3619 - For decimal type, number of decimals.
3620 - For float type, it may be DECIMAL_NOT_SPECIFIED
3621 - For time, datetime and timestamp, number of decimals in fractional second
3622 - For string types, may be decimals of cast source or DECIMAL_NOT_SPECIFIED
3623 */
3625
3626 bool is_nullable() const { return m_nullable; }
3627 void set_nullable(bool nullable) { m_nullable = nullable; }
3628
3629 private:
3630 /**
3631 True if this item may hold the NULL value(if null_value may be set to true).
3632
3633 For items that represent rows, it is true if one of the columns
3634 may be null.
3635
3636 For items that represent scalar or row subqueries, it is true if
3637 one of the returned columns could be null, or if the subquery
3638 could return zero rows.
3639
3640 It is worth noting that this information is correct only until
3641 equality propagation has been run by the optimization phase.
3642 Indeed, consider:
3643 select * from t1, t2,t3 where t1.pk=t2.a and t1.pk+1...
3644 the '+' is not nullable as t1.pk is not nullable;
3645 but if the optimizer chooses plan is t2-t3-t1, then, due to equality
3646 propagation it will replace t1.pk in '+' with t2.a (as t2 is before t1
3647 in plan), making the '+' capable of returning NULL when t2.a is NULL.
3648 */
3650
3651 public:
3652 bool null_value; ///< True if item is null
3654 bool m_is_window_function; ///< True if item represents window func
3655 /**
3656 If the item is in a SELECT list (Query_block::fields) and hidden is true,
3657 the item wasn't actually in the list as given by the user (it was added
3658 by the optimizer, to e.g. make sure it was part of a given
3659 materialization), and should not be returned in the actual result.
3660
3661 If the item is not in a SELECT list, the value is irrelevant.
3662 */
3663 bool hidden{false};
3664 /**
3665 True if item is a top most element in the expression being
3666 evaluated for a check constraint.
3667 */
3669
3670 protected:
3671 /**
3672 Set of properties that are calculated by accumulation from underlying items.
3673 Computed by constructors and fix_fields() and updated by
3674 update_used_tables(). The properties are accumulated up to the root of the
3675 current item tree, except they are not accumulated across subqueries and
3676 functions.
3677 */
3678 static constexpr uint8 PROP_SUBQUERY = 0x01;
3679 static constexpr uint8 PROP_STORED_PROGRAM = 0x02;
3680 static constexpr uint8 PROP_AGGREGATION = 0x04;
3681 static constexpr uint8 PROP_WINDOW_FUNCTION = 0x08;
3682 /**
3683 Set if the item or one or more of the underlying items contains a
3684 GROUP BY modifier (such as ROLLUP).
3685 */
3686 static constexpr uint8 PROP_HAS_GROUPING_SET_DEP = 0x10;
3687 /**
3688 Set if the item or one or more of the underlying items is a GROUPING
3689 function.
3690 */
3691 static constexpr uint8 PROP_GROUPING_FUNC = 0x20;
3692
3694
3695 public:
3696 /**
3697 Check if this expression can be used for partial update of a given
3698 JSON column.
3699
3700 For example, the expression `JSON_REPLACE(col, '$.foo', 'bar')`
3701 can be used to partially update the column `col`.
3702
3703 @param field the JSON column that is being updated
3704 @return true if this expression can be used for partial update,
3705 false otherwise
3706 */
3707 virtual bool supports_partial_update(const Field_json *field
3708 [[maybe_unused]]) const {
3709 return false;
3710 }
3711
3712 /**
3713 Whether the item returns array of its data type
3714 */
3715 virtual bool returns_array() const { return false; }
3716
3717 /**
3718 A helper function to ensure proper usage of CAST(.. AS .. ARRAY)
3719 */
3720 virtual void allow_array_cast() {}
3721};
3722
3723/**
3724 Descriptor of what and how to cache for
3725 Item::cache_const_expr_transformer/analyzer.
3726
3727*/
3728
3730 /// Path from the expression's top to the current item in item tree
3731 /// used to track parent of current item for caching JSON data
3733 /// Item to cache. Used as a binary flag, but kept as Item* for assertion
3734 Item *cache_item{nullptr};
3735 /// How to cache JSON data. @see Item::enum_const_item_cache
3737};
3738
3739/**
3740 A helper class to give in a functor to Item::walk(). Use as e.g.:
3741
3742 bool result = WalkItem(root_item, enum_walk::POSTFIX, [](Item *item) { ... });
3743
3744 TODO: Make Item::walk() just take in a functor in the first place, instead of
3745 a pointer-to-member and an opaque argument.
3746 */
3747template <class T>
3748inline bool WalkItem(Item *item, enum_walk walk, T &&functor) {
3749 return item->walk(&Item::walk_helper_thunk<T>, walk,
3750 reinterpret_cast<uchar *>(&functor));
3751}
3752
3753/**
3754 Overload for const 'item' and functor taking 'const Item*' argument.
3755*/
3756template <class T>
3757inline bool WalkItem(const Item *item, enum_walk walk, T &&functor) {
3758 auto to_const = [&](const Item *descendant) { return functor(descendant); };
3759 return WalkItem(const_cast<Item *>(item), walk, to_const);
3760}
3761
3762/**
3763 Same as WalkItem, but for Item::compile(). Use as e.g.:
3764
3765 Item *item = CompileItem(root_item,
3766 [](Item *item) { return true; }, // Analyzer.
3767 [](Item *item) { return item; }); // Transformer.
3768 */
3769template <class T, class U>
3770inline Item *CompileItem(Item *item, T &&analyzer, U &&transformer) {
3771 uchar *analyzer_ptr = reinterpret_cast<uchar *>(&analyzer);
3772 return item->compile(&Item::analyze_helper_thunk<T>, &analyzer_ptr,
3773 &Item::walk_helper_thunk<U>,
3774 reinterpret_cast<uchar *>(&transformer));
3775}
3776
3777/**
3778 Same as WalkItem, but for Item::transform(). Use as e.g.:
3779
3780 Item *item = TransformItem(root_item, [](Item *item) { return item; });
3781 */
3782template <class T>
3783Item *TransformItem(Item *item, T &&transformer) {
3784 return item->transform(&Item::walk_helper_thunk<T>,
3785 pointer_cast<uchar *>(&transformer));
3786}
3787
3788class sp_head;
3789
3792
3793 public:
3795 explicit Item_basic_constant(const POS &pos) : Item(pos), used_table_map(0) {}
3796
3797 /// @todo add implementation of basic_const_item
3798 /// and remove from subclasses as appropriate.
3799
3801 table_map used_tables() const override { return used_table_map; }
3802 bool check_function_as_value_generator(uchar *) override { return false; }
3803 /* to prevent drop fixed flag (no need parent cleanup call) */
3804 void cleanup() override {
3805 // @todo We should ensure we never change "basic constant" nodes.
3806 // We should then be able to add this assert:
3807 // assert(marker == MARKER_NONE);
3808 // and remove the call to Item::cleanup()
3809 Item::cleanup();
3810 }
3811 bool basic_const_item() const override { return true; }
3813};
3814
3815/*****************************************************************************
3816 The class is a base class for representation of stored routine variables in
3817 the Item-hierarchy. There are the following kinds of SP-vars:
3818 - local variables (Item_splocal);
3819 - CASE expression (Item_case_expr);
3820*****************************************************************************/
3821
3822class Item_sp_variable : public Item {
3823 public:
3825
3826 public:
3827#ifndef NDEBUG
3828 /*
3829 Routine to which this Item_splocal belongs. Used for checking if correct
3830 runtime context is used for variable handling.
3831 */
3832 sp_head *m_sp{nullptr};
3833#endif
3834
3835 public:
3836 Item_sp_variable(const Name_string sp_var_name);
3837
3838 table_map used_tables() const override { return INNER_TABLE_BIT; }
3839 bool fix_fields(THD *thd, Item **) override;
3840
3841 double val_real() override;
3842 longlong val_int() override;
3843 String *val_str(String *sp) override;
3844 my_decimal *val_decimal(my_decimal *decimal_value) override;
3845 bool val_json(Json_wrapper *result) override;
3846 bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
3847 bool get_time(MYSQL_TIME *ltime) override;
3848 bool is_null() override;
3849
3850 public:
3851 inline void make_field(Send_field *field) override;
3852 bool send(Protocol *protocol, String *str) override {
3853 // Need to override send() in case this_item() is an Item_field with a
3854 // ZEROFILL attribute.
3855 return this_item()->send(protocol, str);
3856 }
3857 bool is_valid_for_pushdown(uchar *arg [[maybe_unused]]) override {
3858 // It is ok to push down a condition like "column > SP_variable"
3859 return false;
3860 }
3861
3862 protected:
3864 Field *field, bool no_conversions) override;
3865};
3866
3867/*****************************************************************************
3868 Item_sp_variable inline implementation.
3869*****************************************************************************/
3870
3872 Item *it = this_item();
3874 it->make_field(field);
3875}
3876
3878 Field *field, bool no_conversions) {
3879 return this_item()->save_in_field(field, no_conversions);
3880}
3881
3882/*****************************************************************************
3883 A reference to local SP variable (incl. reference to SP parameter), used in
3884 runtime.
3885*****************************************************************************/
3886
3887class Item_splocal final : public Item_sp_variable,
3890
3893
3894 public:
3895 /*
3896 If this variable is a parameter in LIMIT clause.
3897 Used only during NAME_CONST substitution, to not append
3898 NAME_CONST to the resulting query and thus not break
3899 the slave.
3900 */
3902 /*
3903 Position of this reference to SP variable in the statement (the
3904 statement itself is in sp_instr_stmt::m_query).
3905 This is valid only for references to SP variables in statements,
3906 excluding DECLARE CURSOR statement. It is used to replace references to SP
3907 variables with NAME_CONST calls when putting statements into the binary
3908 log.
3909 Value of 0 means that this object doesn't corresponding to reference to
3910 SP variable in query text.
3911 */
3913 /*
3914 Byte length of SP variable name in the statement (see pos_in_query).
3915 The value of this field may differ from the name_length value because
3916 name_length contains byte length of UTF8-encoded item name, but
3917 the query string (see sp_instr_stmt::m_query) is currently stored with
3918 a charset from the SET NAMES statement.
3919 */
3921
3922 Item_splocal(const Name_string sp_var_name, uint sp_var_idx,
3923 enum_field_types sp_var_type, uint pos_in_q = 0,
3924 uint len_in_q = 0);
3925
3926 bool is_splocal() const override { return true; }
3927
3928 Item *this_item() override;
3929 const Item *this_item() const override;
3930 Item **this_item_addr(THD *thd, Item **) override;
3931
3932 void print(const THD *thd, String *str,
3933 enum_query_type query_type) const override;
3934
3935 public:
3936 inline uint get_var_idx() const { return m_var_idx; }
3937
3938 inline enum Type type() const override { return m_type; }
3939 inline Item_result result_type() const override { return m_result_type; }
3940 bool val_json(Json_wrapper *result) override;
3941
3942 private:
3943 bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override;
3944
3945 public:
3947 return this;
3948 }
3949};
3950
3951/*****************************************************************************
3952 A reference to case expression in SP, used in runtime.
3953*****************************************************************************/
3954
3955class Item_case_expr final : public Item_sp_variable {
3956 public:
3957 Item_case_expr(uint case_expr_id);
3958
3959 public:
3960 Item *this_item() override;
3961 const Item *this_item() const override;
3962 Item **this_item_addr(THD *thd, Item **) override;
3963
3964 Type type() const override { return this_item()->type(); }
3965 Item_result result_type() const override {
3966 return this_item()->result_type();
3967 }
3968 /*
3969 NOTE: print() is intended to be used from views and for debug.
3970 Item_case_expr can not occur in views, so here it is only for debug
3971 purposes.
3972 */
3973 void print(const THD *thd, String *str,
3974 enum_query_type query_type) const override;
3975
3976 private:
3978};
3979
3980/*
3981 NAME_CONST(given_name, const_value).
3982 This 'function' has all properties of the supplied const_value (which is
3983 assumed to be a literal constant), and the name given_name.
3984
3985 This is used to replace references to SP variables when we write PROCEDURE
3986 statements into the binary log.
3987
3988 TODO
3989 Together with Item_splocal and Item::this_item() we can actually extract
3990 common a base of this class and Item_splocal. Maybe it is possible to
3991 extract a common base with class Item_ref, too.
3992*/
3993
3994class Item_name_const final : public Item {
3995 typedef Item super;
3996
4000
4001 public:
4002 Item_name_const(const POS &pos, Item *name_arg, Item *val);
4003
4004 bool do_itemize(Parse_context *pc, Item **res) override;
4005 bool fix_fields(THD *, Item **) override;
4006
4007 enum Type type() const override;
4008 double val_real() override;
4009 longlong val_int() override;
4010 String *val_str(String *sp) override;
4011 my_decimal *val_decimal(my_decimal *) override;
4012 bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
4013 bool get_time(MYSQL_TIME *ltime) override;
4014 bool is_null() override;
4015 void print(const THD *thd, String *str,
4016 enum_query_type query_type) const override;
4017
4018 Item_result result_type() const override { return value_item->result_type(); }
4019
4021 // Item_name_const always wraps a literal, so there is no need to cache it.
4022 return false;
4023 }
4024
4025 protected:
4027 bool no_conversions) override {
4028 return value_item->save_in_field(field, no_conversions);
4029 }
4030};
4031
4033 Item **items, uint nitems, uint flags);
4034bool agg_item_set_converter(DTCollation &coll, const char *fname, Item **args,
4035 uint nargs, uint flags, int item_sep,
4036 bool only_consts);
4037bool agg_item_charsets(DTCollation &c, const char *name, Item **items,
4038 uint nitems, uint flags, int item_sep, bool only_consts);
4040 const char *name, Item **items,
4041 uint nitems, int item_sep = 1) {
4042 const uint flags = MY_COLL_ALLOW_SUPERSET_CONV |
4044 return agg_item_charsets(c, name, items, nitems, flags, item_sep, false);
4045}
4047 Item **items, uint nitems,
4048 int item_sep = 1) {
4049 const uint flags = MY_COLL_ALLOW_SUPERSET_CONV |
4051 return agg_item_charsets(c, name, items, nitems, flags, item_sep, true);
4052}
4053
4056
4057 public:
4059 explicit Item_num(const POS &pos) : super(pos) { collation.set_numeric(); }
4060
4061 virtual Item_num *neg() = 0;
4062 Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4063 bool check_partition_func_processor(uchar *) override { return false; }
4064};
4065
4066#define NO_FIELD_INDEX ((uint16)(-1))
4067
4068class Item_ident : public Item {
4069 typedef Item super;
4070
4071 protected:
4072 /**
4073 The fields m_orig_db_name, m_orig_table_name and m_orig_field_name are
4074 maintained so that we can provide information about the origin of a
4075 column that may have been renamed within the query, e.g. as required by
4076 connectors.
4077
4078 Names the original schema of the table that is the source of the field.
4079 If field is from
4080 - a non-aliased base table, the same as db_name.
4081 - an aliased base table, the name of the schema of the base table.
4082 - an expression (including aggregation), a NULL pointer.
4083 - a derived table, the name of the schema of the underlying base table.
4084 - a view, the name of the schema of the underlying base table.
4085 - a temporary table (in optimization stage), the name of the schema of
4086 the source base table.
4087 */
4088 const char *m_orig_db_name;
4089 /**
4090 Names the original table that is the source of the field. If field is from
4091 - a non-aliased base table, the same as table_name.
4092 - an aliased base table, the name of the base table.
4093 - an expression (including aggregation), a NULL pointer.
4094 - a derived table, the name of the underlying base table.
4095 - a view, the name of the underlying base table.
4096 - a temporary table (in optimization stage), the name of the source base tbl
4097 */
4099 /**
4100 Names the field in the source base table. If field is from
4101 - an expression, a NULL pointer.
4102 - a view or base table and is not aliased, the same as field_name.
4103 - a view or base table and is aliased, the column name of the view or
4104 base table.
4105 - a derived table, the column name of the underlying base table.
4106 - a temporary table (in optimization stage), the name of the source column.
4107 */
4109 bool m_alias_of_expr; ///< if this Item's name is alias of SELECT expression
4110
4111 public:
4112 /**
4113 For regularly resolved column references, 'context' points to a name
4114 resolution context object belonging to the query block which simply
4115 contains the reference. To further clarify, in
4116 SELECT (SELECT t.a) FROM t;
4117 t.a is an Item_ident whose 'context' belongs to the subquery
4118 (context->query_block == that of the subquery).
4119 For column references that are part of a generated column expression,
4120 'context' points to a temporary name resolution context object during
4121 resolving, but is set to nullptr after resolving is done. Note that
4122 Item_ident::local_column() depends on that.
4123 */
4125 /**
4126 Schema name of the base table or view the column is part of.
4127 If an expression, a NULL pointer.
4128 If from a derived table, a NULL pointer.
4129 */
4130 const char *db_name;
4131 /**
4132 If column is from a non-aliased base table or view, name of base table or
4133 view.
4134 If column is from an aliased base table or view, the alias name.
4135 If column is from a derived table, the name of the derived table.
4136 If column is from an expression, a NULL pointer.
4137 */
4138 const char *table_name;
4139 /**
4140 If column is aliased, the column alias name.
4141 If column is from a non-aliased base table or view, the name of the
4142 column in that base table or view.
4143 If column is from an expression, a string generated from that expression.
4144
4145 Notice that a column can be aliased in two ways:
4146 1. With an explicit column alias, or @<as clause@>, or
4147 2. With only a column name specified, which differs from the table's
4148 column name due to case insensitivity.
4149 In both cases field_name will differ from m_orig_field_name.
4150 field_name is normally identical to Item::item_name.
4151 */
4152 const char *field_name;
4153
4154 /*
4155 Cached pointer to table which contains this field, used for the same reason
4156 by prep. stmt. too in case then we have not-fully qualified field.
4157 0 - means no cached value.
4158 @todo Notice that this is usually the same as Item_field::table_ref.
4159 cached_table should be replaced by table_ref ASAP.
4160 */
4163
4164 Item_ident(Name_resolution_context *context_arg, const char *db_name_arg,
4165 const char *table_name_arg, const char *field_name_arg)
4166 : m_orig_db_name(db_name_arg),
4167 m_orig_table_name(table_name_arg),
4168 m_orig_field_name(field_name_arg),
4169 m_alias_of_expr(false),
4170 context(context_arg),
4171 db_name(db_name_arg),
4172 table_name(table_name_arg),
4173 field_name(field_name_arg),
4176 item_name.set(field_name_arg);
4177 }
4178
4179 Item_ident(const POS &pos, const char *db_name_arg,
4180 const char *table_name_arg, const char *field_name_arg)
4181 : super(pos),
4182 m_orig_db_name(db_name_arg),
4183 m_orig_table_name(table_name_arg),
4184 m_orig_field_name(field_name_arg),
4185 m_alias_of_expr(false),
4186 db_name(db_name_arg),
4187 table_name(table_name_arg),
4188 field_name(field_name_arg),
4191 item_name.set(field_name_arg);
4192 }
4193
4194 /// Constructor used by Item_field & Item_*_ref (see Item comment)
4195
4197 : Item(thd, item),
4202 context(item->context),
4203 db_name(item->db_name),
4204 table_name(item->table_name),
4205 field_name(item->field_name),
4208
4209 bool do_itemize(Parse_context *pc, Item **res) override;
4210
4211 const char *full_name() const override;
4212 void set_orignal_db_name(const char *name_arg) { m_orig_db_name = name_arg; }
4213 void set_original_table_name(const char *name_arg) {
4214 m_orig_table_name = name_arg;
4215 }
4216 void set_original_field_name(const char *name_arg) {
4217 m_orig_field_name = name_arg;
4218 }
4219 const char *original_db_name() const { return m_orig_db_name; }
4220 const char *original_table_name() const { return m_orig_table_name; }
4221 const char *original_field_name() const { return m_orig_field_name; }
4222 void fix_after_pullout(Query_block *parent_query_block,
4223 Query_block *removed_query_block) override;
4224 bool aggregate_check_distinct(uchar *arg) override;
4225 bool aggregate_check_group(uchar *arg) override;
4226 Bool3 local_column(const Query_block *sl) const override;
4227
4228 void print(const THD *thd, String *str,
4229 enum_query_type query_type) const override {
4230 print(thd, str, query_type, db_name, table_name);
4231 }
4232
4233 protected:
4234 /**
4235 Function to print column name for a table
4236
4237 To print a column for a permanent table (picks up database and table from
4238 Item_ident object):
4239
4240 item->print(str, qt)
4241
4242 To print a column for a temporary table:
4243
4244 item->print(str, qt, specific_db, specific_table)
4245
4246 Items of temporary table fields have empty/NULL values of table_name and
4247 db_name. To print column names in a 3D form (`database`.`table`.`column`),
4248 this function prints db_name_arg and table_name_arg parameters instead of
4249 this->db_name and this->table_name respectively.
4250
4251 @param thd Thread handle.
4252 @param [out] str Output string buffer.
4253 @param query_type Bitmap to control printing details.
4254 @param db_name_arg String to output as a column database name.
4255 @param table_name_arg String to output as a column table name.
4256 */
4257 void print(const THD *thd, String *str, enum_query_type query_type,
4258 const char *db_name_arg, const char *table_name_arg) const;
4259
4260 public:
4261 ///< Argument object to change_context_processor
4265 };
4266 bool change_context_processor(uchar *arg) override {
4267 context = reinterpret_cast<Change_context *>(arg)->m_context;
4268 return false;
4269 }
4270
4271 /// @returns true if this Item's name is alias of SELECT expression
4272 bool is_alias_of_expr() const { return m_alias_of_expr; }
4273 /// Marks that this Item's name is alias of SELECT expression
4275
4276 bool walk(Item_processor processor, enum_walk walk, uchar *arg) override {
4277 /*
4278 Item_ident processors like aggregate_check*() use
4279 enum_walk::PREFIX|enum_walk::POSTFIX and depend on the processor being
4280 called twice then.
4281 */
4282 return ((walk & enum_walk::PREFIX) && (this->*processor)(arg)) ||
4283 ((walk & enum_walk::POSTFIX) && (this->*processor)(arg));
4284 }
4285
4286 /**
4287 Argument structure for walk processor Item::update_depended_from
4288 */
4290 Query_block *old_depended_from; // the transformed query block
4291 Query_block *new_depended_from; // the new derived table for grouping
4292 };
4293
4294 bool update_depended_from(uchar *) override;
4295
4296 /**
4297 @returns true if a part of this Item's full name (name or table name) is
4298 an alias.
4299 */
4300 virtual bool alias_name_used() const { return m_alias_of_expr; }
4302 const char *db_name, const char *table_name,
4304 bool any_privileges);
4305 bool is_strong_side_column_not_in_fd(uchar *arg) override;
4306 bool is_column_not_in_fd(uchar *arg) override;
4307};
4308
4309class Item_ident_for_show final : public Item {
4310 public:
4312 const char *db_name;
4313 const char *table_name;
4314
4315 Item_ident_for_show(Field *par_field, const char *db_arg,
4316 const char *table_name_arg)
4317 : field(par_field), db_name(db_arg), table_name(table_name_arg) {}
4318
4319 enum Type type() const override { return FIELD_ITEM; }
4320 bool fix_fields(THD *thd, Item **ref) override;
4321 double val_real() override { return field->val_real(); }
4322 longlong val_int() override { return field->val_int(); }
4323 String *val_str(String *str) override { return field->val_str(str); }
4325 return field->val_decimal(dec);
4326 }
4327 bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4328 return field->get_date(ltime, fuzzydate);
4329 }
4330 bool get_time(MYSQL_TIME *ltime) override { return field->get_time(ltime); }
4331 void make_field(Send_field *tmp_field) override;
4333 return field->charset_for_protocol();
4334 }
4335};
4336
4337class COND_EQUAL;
4338class Item_equal;
4339
4340class Item_field : public Item_ident {
4342
4343 protected:
4344 void set_field(Field *field);
4345 void fix_after_pullout(Query_block *parent_query_block,
4346 Query_block *removed_query_block) override {
4347 super::fix_after_pullout(parent_query_block, removed_query_block);
4348
4349 // Update nullability information, as the table may have taken over
4350 // null_row status from the derived table it was part of.
4352 field->table->is_nullable());
4353 }
4355 bool no_conversions) override;
4356
4357 public:
4358 /**
4359 Table containing this resolved field. This is required e.g for calculation
4360 of table map. Notice that for the following types of "tables",
4361 no Table_ref object is assigned and hence table_ref is NULL:
4362 - Temporary tables assigned by join optimizer for sorting and aggregation.
4363 - Stored procedure dummy tables.
4364 For fields referencing such tables, table number is always 0, and other
4365 uses of table_ref is not needed.
4366 */
4368 /// Source field
4370
4371 private:
4372 /// Result field
4374
4375 // save_in_field() and save_org_in_field() are often called repeatedly
4376 // with the same destination field (although the destination for the
4377 // two are distinct, thus two distinct caches). We detect this case by
4378 // storing the last destination, and whether it was of a compatible type
4379 // that we can memcpy into (see fields_are_memcpyable()). This saves time
4380 // doing the same type checking over and over again.
4381 //
4382 // The _memcpyable fields are uint32_t(-1) if the fields are not memcpyable,
4383 // and pack_length() (ie., the amount of bytes to copy) if they are.
4384 // See field_conv_with_cache(), where this logic is encapsulated.
4389
4390 /**
4391 If this field is derived from another field, e.g. it is reading a column
4392 from a temporary table which is populated from a base table, this member
4393 points to the field used to populate the temporary table column.
4394 */
4396
4397 /**
4398 State used for transforming scalar subqueries to JOINs with derived tables,
4399 cf. \c transform_grouped_to_derived. Has accessor.
4400 */
4402
4403 public:
4404 /**
4405 Used during optimization to perform multiple equality analysis,
4406 this analysis should be performed during preparation instead, so that
4407 Item_field can be const after preparation.
4408 */
4410 /**
4411 Index for this field in table->field array. Holds NO_FIELD_INDEX
4412 if index value is not known.
4413 */
4415
4416 void set_item_equal(Item_equal *item_equal_arg) {
4417 if (item_equal == nullptr && item_equal_arg != nullptr) {
4418 item_equal = item_equal_arg;
4419 }
4420 }
4421
4423 if (item_equal != nullptr) {
4425 }
4426 }
4427
4428 // A list of fields that are considered "equal" to this field. E.g., a query
4429 // on the form "a JOIN b ON a.i = b.i JOIN c ON b.i = c.i" would consider
4430 // a.i, b.i and c.i equal due to equality propagation. This is the same as
4431 // "item_equal" above, except that "item_equal" will only contain fields from
4432 // the same join nest. This is used by hash join and BKA when they need to
4433 // undo multi-equality propagation done by the optimizer. (The optimizer may
4434 // generate join conditions that references unreachable fields for said
4435 // iterators.) The split is done because NDB expects the list to only
4436 // contain fields from the same join nest.
4438 /// If true, the optimizer's constant propagation will not replace this item
4439 /// with an equal constant.
4441 /*
4442 if any_privileges set to true then here real effective privileges will
4443 be stored
4444 */
4446 /* field need any privileges (for VIEW creation) */
4448 /*
4449 if this field is used in a context where covering prefix keys
4450 are supported.
4451 */
4453 Item_field(Name_resolution_context *context_arg, const char *db_arg,
4454 const char *table_name_arg, const char *field_name_arg);
4455 Item_field(const POS &pos, const char *db_arg, const char *table_name_arg,
4456 const char *field_name_arg);
4457 Item_field(THD *thd, Item_field *item);
4458 Item_field(THD *thd, Name_resolution_context *context_arg, Table_ref *tr,
4459 Field *field);
4461
4462 bool do_itemize(Parse_context *pc, Item **res) override;
4463
4464 enum Type type() const override { return FIELD_ITEM; }
4465 bool eq(const Item *item, bool binary_cmp) const override;
4466 double val_real() override;
4467 longlong val_int() override;
4468 longlong val_time_temporal() override;
4469 longlong val_date_temporal() override;
4472 my_decimal *val_decimal(my_decimal *) override;
4473 String *val_str(String *) override;
4474 bool val_json(Json_wrapper *result) override;
4475 bool send(Protocol *protocol, String *str_arg) override;
4476 void reset_field(Field *f);
4477 bool fix_fields(THD *, Item **) override;
4478 void make_field(Send_field *tmp_field) override;
4479 void save_org_in_field(Field *field) override;
4480 table_map used_tables() const override;
4481 Item_result result_type() const override { return field->result_type(); }
4484 }
4485 TYPELIB *get_typelib() const override;
4487 return field->cast_to_int_type();
4488 }
4491 }
4492 longlong val_int_endpoint(bool left_endp, bool *incl_endp) override;
4493 void set_result_field(Field *field_arg) override { result_field = field_arg; }
4495 Field *tmp_table_field(TABLE *) override { return result_field; }
4498 item->base_item_field() != nullptr ? item->base_item_field() : item;
4499 }
4501 return m_base_item_field ? m_base_item_field : this;
4502 }
4503 bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
4504 bool get_time(MYSQL_TIME *ltime) override;
4505 bool get_timeval(my_timeval *tm, int *warnings) override;
4506 bool is_null() override {
4507 // NOTE: May return true even if maybe_null is not set!
4508 // This can happen if the underlying TABLE did not have a NULL row
4509 // at set_field() time (ie., table->is_null_row() was false),
4510 // but does now.
4511 return field->is_null();
4512 }
4513 Item *get_tmp_table_item(THD *thd) override;
4514 bool collect_item_field_processor(uchar *arg) override;
4515 bool collect_item_field_or_ref_processor(uchar *arg) override;
4517 bool add_field_to_set_processor(uchar *arg) override;
4518 bool add_field_to_cond_set_processor(uchar *) override;
4519 bool remove_column_from_bitmap(uchar *arg) override;
4520 bool find_item_in_field_list_processor(uchar *arg) override;
4521 bool find_field_processor(uchar *arg) override {
4522 return pointer_cast<Field *>(arg) == field;
4523 }
4524 bool check_function_as_value_generator(uchar *args) override;
4525 bool mark_field_in_map(uchar *arg) override {
4526 auto mark_field = pointer_cast<Mark_field *>(arg);
4527 bool rc = Item::mark_field_in_map(mark_field, field);
4529 rc |= Item::mark_field_in_map(mark_field, result_field);
4530 return rc;
4531 }
4532 bool used_tables_for_level(uchar *arg) override;
4533 bool check_column_privileges(uchar *arg) override;
4534 bool check_partition_func_processor(uchar *) override { return false; }
4535 void bind_fields() override;
4536 bool is_valid_for_pushdown(uchar *arg) override;
4537 bool check_column_in_window_functions(uchar *arg) override;
4538 bool check_column_in_group_by(uchar *arg) override;
4539 Item *replace_with_derived_expr(uchar *arg) override;
4541 void cleanup() override;
4542 void reset_field();
4543 Item_equal *find_item_equal(COND_EQUAL *cond_equal) const;
4544 bool subst_argument_checker(uchar **arg) override;
4545 Item *equal_fields_propagator(uchar *arg) override;
4546 Item *replace_item_field(uchar *) override;
4549 return false;
4550 }
4551 Item *replace_equal_field(uchar *) override;
4553 Item_field *field_for_view_update() override { return this; }
4554 Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4555 int fix_outer_field(THD *thd, Field **field, Item **reference);
4556 Item *update_value_transformer(uchar *select_arg) override;
4557 void print(const THD *thd, String *str,
4558 enum_query_type query_type) const override;
4559 bool is_outer_field() const override {
4560 assert(fixed);
4562 }
4564 assert(data_type() == MYSQL_TYPE_GEOMETRY);
4565 return field->get_geometry_type();
4566 }
4567 const CHARSET_INFO *charset_for_protocol(void) override {
4568 return field->charset_for_protocol();
4569 }
4570
4571#ifndef NDEBUG
4572 void dbug_print() const {
4573 fprintf(DBUG_F