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