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