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