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