MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
item_cmpfunc.cc
Go to the documentation of this file.
1 /* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software
14  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15 
16 
24 #include "sql_priv.h"
25 #include <m_ctype.h>
26 #include "sql_select.h"
27 #include "sql_optimizer.h" // JOIN_TAB
28 #include "sql_parse.h" // check_stack_overrun
29 #include "sql_time.h" // make_truncated_value_warning
30 
31 #include <algorithm>
32 using std::min;
33 using std::max;
34 
35 static bool convert_constant_item(THD *, Item_field *, Item **);
36 static longlong
37 get_year_value(THD *thd, Item ***item_arg, Item **cache_arg,
38  Item *warn_item, bool *is_null);
39 
40 static Item_result item_store_type(Item_result a, Item *item,
41  my_bool unsigned_flag)
42 {
43  Item_result b= item->result_type();
44 
45  if (a == STRING_RESULT || b == STRING_RESULT)
46  return STRING_RESULT;
47  else if (a == REAL_RESULT || b == REAL_RESULT)
48  return REAL_RESULT;
49  else if (a == DECIMAL_RESULT || b == DECIMAL_RESULT ||
50  unsigned_flag != item->unsigned_flag)
51  return DECIMAL_RESULT;
52  else
53  return INT_RESULT;
54 }
55 
56 static void agg_result_type(Item_result *type, Item **items, uint nitems)
57 {
58  Item **item, **item_end;
59  my_bool unsigned_flag= 0;
60 
61  *type= STRING_RESULT;
62  /* Skip beginning NULL items */
63  for (item= items, item_end= item + nitems; item < item_end; item++)
64  {
65  if ((*item)->type() != Item::NULL_ITEM)
66  {
67  *type= (*item)->result_type();
68  unsigned_flag= (*item)->unsigned_flag;
69  item++;
70  break;
71  }
72  }
73  /* Combine result types. Note: NULL items don't affect the result */
74  for (; item < item_end; item++)
75  {
76  if ((*item)->type() != Item::NULL_ITEM)
77  *type= item_store_type(*type, *item, unsigned_flag);
78  }
79 }
80 
81 
82 /*
83  Compare row signature of two expressions
84 
85  SYNOPSIS:
86  cmp_row_type()
87  item1 the first expression
88  item2 the second expression
89 
90  DESCRIPTION
91  The function checks that two expressions have compatible row signatures
92  i.e. that the number of columns they return are the same and that if they
93  are both row expressions then each component from the first expression has
94  a row signature compatible with the signature of the corresponding component
95  of the second expression.
96 
97  RETURN VALUES
98  1 type incompatibility has been detected
99  0 otherwise
100 */
101 
102 static int cmp_row_type(Item* item1, Item* item2)
103 {
104  uint n= item1->cols();
105  if (item2->check_cols(n))
106  return 1;
107  for (uint i=0; i<n; i++)
108  {
109  if (item2->element_index(i)->check_cols(item1->element_index(i)->cols()) ||
110  (item1->element_index(i)->result_type() == ROW_RESULT &&
111  cmp_row_type(item1->element_index(i), item2->element_index(i))))
112  return 1;
113  }
114  return 0;
115 }
116 
117 
141 static int agg_cmp_type(Item_result *type, Item **items, uint nitems)
142 {
143  uint i;
144  type[0]= items[0]->result_type();
145  for (i= 1 ; i < nitems ; i++)
146  {
147  type[0]= item_cmp_type(type[0], items[i]->result_type());
148  /*
149  When aggregating types of two row expressions we have to check
150  that they have the same cardinality and that each component
151  of the first row expression has a compatible row signature with
152  the signature of the corresponding component of the second row
153  expression.
154  */
155  if (type[0] == ROW_RESULT && cmp_row_type(items[0], items[i]))
156  return 1; // error found: invalid usage of rows
157  }
158  return 0;
159 }
160 
161 
180 enum_field_types agg_field_type(Item **items, uint nitems)
181 {
182  uint i;
183  if (!nitems || items[0]->result_type() == ROW_RESULT )
184  return (enum_field_types)-1;
185  enum_field_types res= items[0]->field_type();
186  for (i= 1 ; i < nitems ; i++)
187  res= Field::field_type_merge(res, items[i]->field_type());
188  return real_type_to_type(res);
189 }
190 
191 /*
192  Collects different types for comparison of first item with each other items
193 
194  SYNOPSIS
195  collect_cmp_types()
196  items Array of items to collect types from
197  nitems Number of items in the array
198  skip_nulls Don't collect types of NULL items if TRUE
199 
200  DESCRIPTION
201  This function collects different result types for comparison of the first
202  item in the list with each of the remaining items in the 'items' array.
203 
204  RETURN
205  0 - if row type incompatibility has been detected (see cmp_row_type)
206  Bitmap of collected types - otherwise
207 */
208 
209 static uint collect_cmp_types(Item **items, uint nitems, bool skip_nulls= FALSE)
210 {
211  uint i;
212  uint found_types;
213  Item_result left_result= items[0]->result_type();
214  DBUG_ASSERT(nitems > 1);
215  found_types= 0;
216  for (i= 1; i < nitems ; i++)
217  {
218  if (skip_nulls && items[i]->type() == Item::NULL_ITEM)
219  continue; // Skip NULL constant items
220  if ((left_result == ROW_RESULT ||
221  items[i]->result_type() == ROW_RESULT) &&
222  cmp_row_type(items[0], items[i]))
223  return 0;
224  found_types|= 1U << (uint)item_cmp_type(left_result,
225  items[i]->result_type());
226  }
227  /*
228  Even if all right-hand items are NULLs and we are skipping them all, we need
229  at least one type bit in the found_type bitmask.
230  */
231  if (skip_nulls && !found_types)
232  found_types= 1U << (uint)left_result;
233  return found_types;
234 }
235 
236 static void my_coll_agg_error(DTCollation &c1, DTCollation &c2,
237  const char *fname)
238 {
239  my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0),
240  c1.collation->name,c1.derivation_name(),
241  c2.collation->name,c2.derivation_name(),
242  fname);
243 }
244 
245 
246 Item_bool_func2* Eq_creator::create(Item *a, Item *b) const
247 {
248  return new Item_func_eq(a, b);
249 }
250 
251 
252 Item_bool_func2* Ne_creator::create(Item *a, Item *b) const
253 {
254  return new Item_func_ne(a, b);
255 }
256 
257 
258 Item_bool_func2* Gt_creator::create(Item *a, Item *b) const
259 {
260  return new Item_func_gt(a, b);
261 }
262 
263 
264 Item_bool_func2* Lt_creator::create(Item *a, Item *b) const
265 {
266  return new Item_func_lt(a, b);
267 }
268 
269 
270 Item_bool_func2* Ge_creator::create(Item *a, Item *b) const
271 {
272  return new Item_func_ge(a, b);
273 }
274 
275 
276 Item_bool_func2* Le_creator::create(Item *a, Item *b) const
277 {
278  return new Item_func_le(a, b);
279 }
280 
281 /*
282  Test functions
283  Most of these returns 0LL if false and 1LL if true and
284  NULL if some arg is NULL.
285 */
286 
287 longlong Item_func_not::val_int()
288 {
289  DBUG_ASSERT(fixed == 1);
290  bool value= args[0]->val_bool();
291  null_value=args[0]->null_value;
292  return ((!null_value && value == 0) ? 1 : 0);
293 }
294 
295 /*
296  We put any NOT expression into parenthesis to avoid
297  possible problems with internal view representations where
298  any '!' is converted to NOT. It may cause a problem if
299  '!' is used in an expression together with other operators
300  whose precedence is lower than the precedence of '!' yet
301  higher than the precedence of NOT.
302 */
303 
304 void Item_func_not::print(String *str, enum_query_type query_type)
305 {
306  str->append('(');
307  Item_func::print(str, query_type);
308  str->append(')');
309 }
310 
317 {
318  DBUG_ASSERT(fixed == 1);
319  bool value= args[0]->val_bool();
320 
321  /*
322  return TRUE if there was records in underlying select in max/min
323  optimization (ALL subquery)
324  */
325  if (empty_underlying_subquery())
326  return 1;
327 
328  null_value= args[0]->null_value;
329  return ((!null_value && value == 0) ? 1 : 0);
330 }
331 
332 
333 bool Item_func_not_all::empty_underlying_subquery()
334 {
335  DBUG_ASSERT(subselect || !(test_sum_item || test_sub_item));
336  /*
337  When outer argument is NULL the subquery has not yet been evaluated, we
338  need to evaluate it to get to know whether it returns any rows to return
339  the correct result. 'ANY' subqueries are an exception because the
340  result would be false or null which for a top level item always mean false.
341  The subselect->unit->item->... chain should be used instead of
342  subselect->... to workaround subquery transformation which could make
343  subselect->engine unusable.
344  */
345  if (subselect &&
346  subselect->substype() != Item_subselect::ANY_SUBS &&
347  !subselect->unit->item->is_evaluated())
348  subselect->unit->item->exec();
349  return ((test_sum_item && !test_sum_item->any_value()) ||
350  (test_sub_item && !test_sub_item->any_value()));
351 }
352 
353 void Item_func_not_all::print(String *str, enum_query_type query_type)
354 {
355  if (show)
356  Item_func::print(str, query_type);
357  else
358  args[0]->print(str, query_type);
359 }
360 
361 
372 {
373  DBUG_ASSERT(fixed == 1);
374  longlong value= args[0]->val_int();
375 
376  /*
377  return FALSE if there was records in underlying select in max/min
378  optimization (SAME/ANY subquery)
379  */
380  if (empty_underlying_subquery())
381  return 0;
382 
383  null_value= args[0]->null_value;
384  return (null_value || value == 0) ? 0 : 1;
385 }
386 
387 
415 static bool convert_constant_item(THD *thd, Item_field *field_item,
416  Item **item)
417 {
418  Field *field= field_item->field;
419  int result= 0;
420 
421  if ((*item)->const_item())
422  {
423  TABLE *table= field->table;
424  sql_mode_t orig_sql_mode= thd->variables.sql_mode;
425  enum_check_fields orig_count_cuted_fields= thd->count_cuted_fields;
426  my_bitmap_map *old_maps[2];
427  ulonglong UNINIT_VAR(orig_field_val); /* original field value if valid */
428 
429  LINT_INIT(old_maps[0]);
430  LINT_INIT(old_maps[1]);
431 
432  if (table)
433  dbug_tmp_use_all_columns(table, old_maps,
434  table->read_set, table->write_set);
435  /* For comparison purposes allow invalid dates like 2000-01-32 */
436  thd->variables.sql_mode= (orig_sql_mode & ~MODE_NO_ZERO_DATE) |
437  MODE_INVALID_DATES;
438  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
439 
440  /*
441  Store the value of the field/constant if it references an outer field
442  because the call to save_in_field below overrides that value.
443  Don't save field value if no data has been read yet.
444  Outer constant values are always saved.
445  */
446  bool save_field_value= (field_item->depended_from &&
447  (field_item->const_item() ||
448  !(field->table->status &
449  (STATUS_GARBAGE | STATUS_NOT_FOUND))));
450  if (save_field_value)
451  orig_field_val= field->val_int();
452  int rc;
453  if (!(*item)->is_null() &&
454  (((rc= (*item)->save_in_field(field, 1)) == TYPE_OK) ||
455  rc == TYPE_NOTE_TIME_TRUNCATED)) // TS-TODO
456  {
457  int field_cmp= 0;
458  /*
459  If item is a decimal value, we must reject it if it was truncated.
460  TODO: consider doing the same for MYSQL_TYPE_YEAR,.
461  However: we have tests which assume that things '1999' and
462  '1991-01-01 01:01:01' can be converted to year.
463  Testing for MYSQL_TYPE_YEAR here, would treat such literals
464  as 'incorrect DOUBLE value'.
465  See Bug#13580652 YEAR COLUMN CAN BE EQUAL TO 1999.1
466  */
467  if (field->type() == MYSQL_TYPE_LONGLONG)
468  {
469  field_cmp= stored_field_cmp_to_item(thd, field, *item);
470  DBUG_PRINT("info", ("convert_constant_item %d", field_cmp));
471  }
472 
473  if (0 == field_cmp)
474  {
475  Item *tmp= field->type() == MYSQL_TYPE_TIME ?
476 #define OLD_CMP
477 #ifdef OLD_CMP
478  new Item_time_with_ref(field->decimals(),
479  field->val_time_temporal(), *item) :
480 #else
481  new Item_time_with_ref(max((*item)->time_precision(),
482  field->decimals()),
483  (*item)->val_time_temporal(),
484  *item) :
485 #endif
486  field->is_temporal_with_date() ?
487 #ifdef OLD_CMP
488  new Item_datetime_with_ref(field->type(),
489  field->decimals(),
490  field->val_date_temporal(),
491  *item) :
492 #else
493  new Item_datetime_with_ref(field->type(),
494  max((*item)->datetime_precision(),
495  field->decimals()),
496  (*item)->val_date_temporal(),
497  *item) :
498 #endif
499  new Item_int_with_ref(field->val_int(), *item,
500  test(field->flags & UNSIGNED_FLAG));
501  if (tmp)
502  thd->change_item_tree(item, tmp);
503  result= 1; // Item was replaced
504  }
505  }
506  /* Restore the original field value. */
507  if (save_field_value)
508  {
509  result= field->store(orig_field_val, TRUE);
510  /* orig_field_val must be a valid value that can be restored back. */
511  DBUG_ASSERT(!result);
512  }
513  thd->variables.sql_mode= orig_sql_mode;
514  thd->count_cuted_fields= orig_count_cuted_fields;
515  if (table)
516  dbug_tmp_restore_column_maps(table->read_set, table->write_set, old_maps);
517  }
518  return result;
519 }
520 
521 
522 bool Item_bool_func2::convert_constant_arg(THD *thd, Item *field, Item **item)
523 {
524  if (field->real_item()->type() != FIELD_ITEM)
525  return false;
526 
527  Item_field *field_item= (Item_field*) (field->real_item());
528  if (field_item->field->can_be_compared_as_longlong() &&
529  !(field_item->is_temporal_with_date() &&
530  (*item)->result_type() == STRING_RESULT))
531  {
532  if (convert_constant_item(thd, field_item, item))
533  {
534  cmp.set_cmp_func(this, tmp_arg, tmp_arg + 1, INT_RESULT);
535  field->cmp_context= (*item)->cmp_context= INT_RESULT;
536  return true;
537  }
538  }
539  return false;
540 }
541 
542 
543 void Item_bool_func2::fix_length_and_dec()
544 {
545  max_length= 1; // Function returns 0 or 1
546  THD *thd;
547 
548  /*
549  As some compare functions are generated after sql_yacc,
550  we have to check for out of memory conditions here
551  */
552  if (!args[0] || !args[1])
553  return;
554 
555  DBUG_ENTER("Item_bool_func2::fix_length_and_dec");
556 
557  /*
558  See agg_item_charsets() in item.cc for comments
559  on character set and collation aggregation.
560  */
561  if (args[0]->result_type() == STRING_RESULT &&
562  args[1]->result_type() == STRING_RESULT &&
563  agg_arg_charsets_for_comparison(cmp.cmp_collation, args, 2))
564  DBUG_VOID_RETURN;
565 
566  args[0]->cmp_context= args[1]->cmp_context=
567  item_cmp_type(args[0]->result_type(), args[1]->result_type());
568  // Make a special case of compare with fields to get nicer DATE comparisons
569 
570  if (functype() == LIKE_FUNC) // Disable conversion in case of LIKE function.
571  {
572  set_cmp_func();
573  DBUG_VOID_RETURN;
574  }
575 
576  thd= current_thd;
577  if (!thd->lex->is_ps_or_view_context_analysis())
578  {
579  if (convert_constant_arg(thd, args[0], &args[1]) ||
580  convert_constant_arg(thd, args[1], &args[0]))
581  DBUG_VOID_RETURN;
582  }
583  set_cmp_func();
584  DBUG_VOID_RETURN;
585 }
586 
587 
588 int Arg_comparator::set_compare_func(Item_result_field *item, Item_result type)
589 {
590  owner= item;
591  func= comparator_matrix[type]
592  [is_owner_equal_func()];
593 
594  switch (type) {
595  case ROW_RESULT:
596  {
597  uint n= (*a)->cols();
598  if (n != (*b)->cols())
599  {
600  my_error(ER_OPERAND_COLUMNS, MYF(0), n);
601  comparators= 0;
602  return 1;
603  }
604  if (!(comparators= new Arg_comparator[n]))
605  return 1;
606  for (uint i=0; i < n; i++)
607  {
608  if ((*a)->element_index(i)->cols() != (*b)->element_index(i)->cols())
609  {
610  my_error(ER_OPERAND_COLUMNS, MYF(0), (*a)->element_index(i)->cols());
611  return 1;
612  }
613  if (comparators[i].set_cmp_func(owner, (*a)->addr(i), (*b)->addr(i),
614  set_null))
615  return 1;
616  }
617  break;
618  }
619  case STRING_RESULT:
620  {
621  /*
622  We must set cmp_charset here as we may be called from for an automatic
623  generated item, like in natural join
624  */
625  if (cmp_collation.set((*a)->collation, (*b)->collation) ||
626  cmp_collation.derivation == DERIVATION_NONE)
627  {
628  my_coll_agg_error((*a)->collation, (*b)->collation,
629  owner->func_name());
630  return 1;
631  }
632  if (cmp_collation.collation == &my_charset_bin)
633  {
634  /*
635  We are using BLOB/BINARY/VARBINARY, change to compare byte by byte,
636  without removing end space
637  */
638  if (func == &Arg_comparator::compare_string)
640  else if (func == &Arg_comparator::compare_e_string)
641  func= &Arg_comparator::compare_e_binary_string;
642 
643  /*
644  As this is binary compassion, mark all fields that they can't be
645  transformed. Otherwise we would get into trouble with comparisons
646  like:
647  WHERE col= 'j' AND col LIKE BINARY 'j'
648  which would be transformed to:
649  WHERE col= 'j'
650  */
651  (*a)->walk(&Item::set_no_const_sub, FALSE, (uchar*) 0);
652  (*b)->walk(&Item::set_no_const_sub, FALSE, (uchar*) 0);
653  }
654  break;
655  }
656  case INT_RESULT:
657  {
658  if ((*a)->is_temporal() && (*b)->is_temporal())
659  {
660  func= is_owner_equal_func() ?
663  }
664  else if (func == &Arg_comparator::compare_int_signed)
665  {
666  if ((*a)->unsigned_flag)
667  func= (((*b)->unsigned_flag)?
670  else if ((*b)->unsigned_flag)
672  }
673  else if (func== &Arg_comparator::compare_e_int)
674  {
675  if ((*a)->unsigned_flag ^ (*b)->unsigned_flag)
677  }
678  break;
679  }
680  case DECIMAL_RESULT:
681  break;
682  case REAL_RESULT:
683  {
684  if ((*a)->decimals < NOT_FIXED_DEC && (*b)->decimals < NOT_FIXED_DEC)
685  {
686  precision= 5 / log_10[max((*a)->decimals, (*b)->decimals) + 1];
687  if (func == &Arg_comparator::compare_real)
688  func= &Arg_comparator::compare_real_fixed;
689  else if (func == &Arg_comparator::compare_e_real)
690  func= &Arg_comparator::compare_e_real_fixed;
691  }
692  break;
693  }
694  default:
695  DBUG_ASSERT(0);
696  }
697  return 0;
698 }
699 
721 bool get_mysql_time_from_str(THD *thd, String *str, timestamp_type warn_type,
722  const char *warn_name, MYSQL_TIME *l_time)
723 {
724  bool value;
725  MYSQL_TIME_STATUS status;
726 
727  if (!str_to_datetime(str, l_time,
728  (TIME_FUZZY_DATE | MODE_INVALID_DATES |
729  (thd->variables.sql_mode &
730  (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE))), &status) &&
731  (l_time->time_type == MYSQL_TIMESTAMP_DATETIME ||
732  l_time->time_type == MYSQL_TIMESTAMP_DATE))
733  /*
734  Do not return yet, we may still want to throw a "trailing garbage"
735  warning.
736  */
737  value= FALSE;
738  else
739  {
740  value= TRUE;
741  status.warnings= MYSQL_TIME_WARN_TRUNCATED; /* force warning */
742  }
743 
744  if (status.warnings > 0)
745  make_truncated_value_warning(thd, Sql_condition::WARN_LEVEL_WARN,
746  ErrConvString(str), warn_type, warn_name);
747 
748  return value;
749 }
750 
751 
771 static ulonglong get_date_from_str(THD *thd, String *str,
772  timestamp_type warn_type,
773  const char *warn_name, bool *error_arg)
774 {
775  MYSQL_TIME l_time;
776  *error_arg= get_mysql_time_from_str(thd, str, warn_type, warn_name, &l_time);
777 
778  if (*error_arg)
779  return 0;
780  return TIME_to_longlong_datetime_packed(&l_time);
781 }
782 
783 
795 bool Arg_comparator::get_date_from_const(Item *date_arg,
796  Item *str_arg,
797  ulonglong *const_value)
798 {
799  THD *thd= current_thd;
800  /*
801  Do not cache GET_USER_VAR() function as its const_item() may return TRUE
802  for the current thread but it still may change during the execution.
803  Don't use cache while in the context analysis mode only (i.e. for
804  EXPLAIN/CREATE VIEW and similar queries). Cache is useless in such
805  cases and can cause problems. For example evaluating subqueries can
806  confuse storage engines since in context analysis mode tables
807  aren't locked.
808  */
809  if (!thd->lex->is_ps_or_view_context_analysis() &&
810  str_arg->const_item() &&
811  (str_arg->type() != Item::FUNC_ITEM ||
812  ((Item_func*) str_arg)->functype() != Item_func::GUSERVAR_FUNC))
813  {
814  ulonglong value;
815  if (str_arg->field_type() == MYSQL_TYPE_TIME)
816  {
817  // Convert from TIME to DATETIME
818  value= str_arg->val_date_temporal();
819  if (str_arg->null_value)
820  return true;
821  }
822  else
823  {
824  // Convert from string to DATETIME
825  DBUG_ASSERT(str_arg->result_type() == STRING_RESULT);
826  bool error;
827  String tmp, *str_val= 0;
828  timestamp_type t_type= (date_arg->field_type() == MYSQL_TYPE_DATE ?
829  MYSQL_TIMESTAMP_DATE : MYSQL_TIMESTAMP_DATETIME);
830  str_val= str_arg->val_str(&tmp);
831  if (str_arg->null_value)
832  return true;
833  value= get_date_from_str(thd, str_val, t_type,
834  date_arg->item_name.ptr(), &error);
835  if (error)
836  return true;
837  }
838  if (const_value)
839  *const_value= value;
840  }
841  return false;
842 }
843 
844 
845 /*
846  Check whether compare_datetime() can be used to compare items.
847 
848  SYNOPSIS
849  Arg_comparator::can_compare_as_dates()
850  a, b [in] items to be compared
851  const_value [out] converted value of the string constant, if any
852 
853  DESCRIPTION
854  Check several cases when the DATE/DATETIME comparator should be used.
855  The following cases are checked:
856  1. Both a and b is a DATE/DATETIME field/function returning string or
857  int result.
858  2. Only a or b is a DATE/DATETIME field/function returning string or
859  int result and the other item (b or a) is an item with string result.
860  If the second item is a constant one then it's checked to be
861  convertible to the DATE/DATETIME type. If the constant can't be
862  converted to a DATE/DATETIME then the compare_datetime() comparator
863  isn't used and the warning about wrong DATE/DATETIME value is issued.
864  In all other cases (date-[int|real|decimal]/[int|real|decimal]-date)
865  the comparison is handled by other comparators.
866  If the datetime comparator can be used and one the operands of the
867  comparison is a string constant that was successfully converted to a
868  DATE/DATETIME type then the result of the conversion is returned in the
869  const_value if it is provided. If there is no constant or
870  compare_datetime() isn't applicable then the *const_value remains
871  unchanged.
872 
873  @return true if can compare as dates, false otherwise.
874 */
875 
876 bool
877 Arg_comparator::can_compare_as_dates(Item *a, Item *b, ulonglong *const_value)
878 {
879  if (a->type() == Item::ROW_ITEM || b->type() == Item::ROW_ITEM)
880  return false;
881 
882  if (a->is_temporal_with_date())
883  {
884  if (b->is_temporal_with_date()) // date[time] + date
885  {
886  return true;
887  }
888  else if (b->result_type() == STRING_RESULT) // date[time] + string
889  {
890  return !get_date_from_const(a, b, const_value);
891  }
892  else
893  return false; // date[time] + number
894  }
895  else if (b->is_temporal_with_date() &&
896  a->result_type() == STRING_RESULT) // string + date[time]
897  {
898  return !get_date_from_const(b, a, const_value);
899  }
900  else
901  return false; // No date[time] items found
902 }
903 
904 
905 /*
906  Retrieves correct TIME value from the given item.
907 
908  SYNOPSIS
909  get_time_value()
910  thd thread handle
911  item_arg [in/out] item to retrieve TIME value from
912  cache_arg [in/out] pointer to place to store the cache item to
913  warn_item [in] unused
914  is_null [out] TRUE <=> the item_arg is null
915 
916  DESCRIPTION
917  Retrieves the correct TIME value from given item for comparison by the
918  compare_datetime() function.
919  If item's result can be compared as longlong then its int value is used
920  and a value returned by get_time function is used otherwise.
921  If an item is a constant one then its value is cached and it isn't
922  get parsed again. An Item_cache_int object is used for for cached values.
923  It seamlessly substitutes the original item. The cache item is marked as
924  non-constant to prevent re-caching it again.
925 
926  RETURN
927  obtained value
928 */
929 
930 longlong
931 get_time_value(THD *thd, Item ***item_arg, Item **cache_arg,
932  Item *warn_item, bool *is_null)
933 {
934  longlong value;
935  Item *item= **item_arg;
936 
937  /*
938  Note, it's wrong to assume that we always get
939  a TIME expression or NULL here:
940 
941  DBUG_ASSERT(item->field_type() == MYSQL_TYPE_TIME ||
942  item->field_type() == MYSQL_TYPE_NULL);
943 
944  because when this condition is optimized:
945 
946  WHERE time_column=DATE(NULL) AND time_column=TIME(NULL);
947 
948  rhe first AND part is eliminated and DATE(NULL) is substituted
949  to the second AND part like this:
950 
951  WHERE DATE(NULL) = TIME(NULL) // as TIME
952 
953  whose Arg_comparator has already get_time_value set for both arguments.
954  Therefore, get_time_value is executed for DATE(NULL).
955  This condition is further evaluated as impossible condition.
956 
957  TS-TODO: perhaps such cases should be evaluated without
958  calling get_time_value at all.
959 
960  See a similar comment in Arg_comparator::compare_time_packed.
961  */
962  value= item->val_time_temporal();
963  *is_null= item->null_value;
964 
965  /*
966  Do not cache GET_USER_VAR() function as its const_item() may return TRUE
967  for the current thread but it still may change during the execution.
968  */
969  if (item->const_item() && cache_arg &&
970  item->type() != Item::CACHE_ITEM &&
971  (item->type() != Item::FUNC_ITEM ||
972  ((Item_func*)item)->functype() != Item_func::GUSERVAR_FUNC))
973  {
974  Item_cache_datetime *cache= new Item_cache_datetime(item->field_type());
975  /* Mark the cache as non-const to prevent re-caching. */
976  cache->set_used_tables(1);
977  cache->store(item, value);
978  *cache_arg= cache;
979  *item_arg= cache_arg;
980  }
981  return value;
982 }
983 
984 
985 int Arg_comparator::set_cmp_func(Item_result_field *owner_arg,
986  Item **a1, Item **a2,
987  Item_result type)
988 {
989  ulonglong const_value= (ulonglong)-1;
990  thd= current_thd;
991  owner= owner_arg;
992  set_null= set_null && owner_arg;
993  a= a1;
994  b= a2;
995 
996  if (can_compare_as_dates(*a, *b, &const_value))
997  {
998  a_type= (*a)->field_type();
999  b_type= (*b)->field_type();
1000  a_cache= 0;
1001  b_cache= 0;
1002 
1003  if (const_value != (ulonglong)-1)
1004  {
1005  /*
1006  cache_converted_constant can't be used here because it can't
1007  correctly convert a DATETIME value from string to int representation.
1008  */
1009  Item_cache_datetime *cache= new Item_cache_datetime(MYSQL_TYPE_DATETIME);
1010  /* Mark the cache as non-const to prevent re-caching. */
1011  cache->set_used_tables(1);
1012  if (!(*a)->is_temporal_with_date())
1013  {
1014  cache->store((*a), const_value);
1015  a_cache= cache;
1016  a= (Item **)&a_cache;
1017  }
1018  else
1019  {
1020  cache->store((*b), const_value);
1021  b_cache= cache;
1022  b= (Item **)&b_cache;
1023  }
1024  }
1025  is_nulls_eq= is_owner_equal_func();
1026  func= &Arg_comparator::compare_datetime;
1027  get_value_a_func= &get_datetime_value;
1028  get_value_b_func= &get_datetime_value;
1029  cmp_collation.set(&my_charset_numeric);
1030  set_cmp_context_for_datetime();
1031  return 0;
1032  }
1033  else if (type == STRING_RESULT && (*a)->field_type() == MYSQL_TYPE_TIME &&
1034  (*b)->field_type() == MYSQL_TYPE_TIME)
1035  {
1036  /* Compare TIME values as integers. */
1037  a_cache= 0;
1038  b_cache= 0;
1039  is_nulls_eq= is_owner_equal_func();
1040  func= &Arg_comparator::compare_datetime;
1041  get_value_a_func= &get_time_value;
1042  get_value_b_func= &get_time_value;
1043  set_cmp_context_for_datetime();
1044  return 0;
1045  }
1046  else if (type == STRING_RESULT &&
1047  (*a)->result_type() == STRING_RESULT &&
1048  (*b)->result_type() == STRING_RESULT)
1049  {
1050  DTCollation coll;
1051  coll.set((*a)->collation.collation);
1052  if (agg_item_set_converter(coll, owner->func_name(),
1053  b, 1, MY_COLL_CMP_CONV, 1))
1054  return 1;
1055  }
1056  else if (try_year_cmp_func(type))
1057  return 0;
1058 
1059  a= cache_converted_constant(thd, a, &a_cache, type);
1060  b= cache_converted_constant(thd, b, &b_cache, type);
1061  return set_compare_func(owner_arg, type);
1062 }
1063 
1064 
1065 /*
1066  Helper function to call from Arg_comparator::set_cmp_func()
1067 */
1068 
1069 bool Arg_comparator::try_year_cmp_func(Item_result type)
1070 {
1071  if (type == ROW_RESULT)
1072  return FALSE;
1073 
1074  bool a_is_year= (*a)->field_type() == MYSQL_TYPE_YEAR;
1075  bool b_is_year= (*b)->field_type() == MYSQL_TYPE_YEAR;
1076 
1077  if (!a_is_year && !b_is_year)
1078  return FALSE;
1079 
1080  if (a_is_year && b_is_year)
1081  {
1082  get_value_a_func= &get_year_value;
1083  get_value_b_func= &get_year_value;
1084  }
1085  else if (a_is_year && (*b)->is_temporal_with_date())
1086  {
1087  get_value_a_func= &get_year_value;
1088  get_value_b_func= &get_datetime_value;
1089  }
1090  else if (b_is_year && (*a)->is_temporal_with_date())
1091  {
1092  get_value_b_func= &get_year_value;
1093  get_value_a_func= &get_datetime_value;
1094  }
1095  else
1096  return FALSE;
1097 
1098  is_nulls_eq= is_owner_equal_func();
1099  func= &Arg_comparator::compare_datetime;
1100  set_cmp_context_for_datetime();
1101 
1102  return TRUE;
1103 }
1104 
1123  Item **cache_item,
1124  Item_result type)
1125 {
1126  /* Don't need cache if doing context analysis only. */
1127  if (!thd->lex->is_ps_or_view_context_analysis() &&
1128  (*value)->const_item() && type != (*value)->result_type())
1129  {
1130  Item_cache *cache= Item_cache::get_cache(*value, type);
1131  cache->setup(*value);
1132  *cache_item= cache;
1133  return cache_item;
1134  }
1135  return value;
1136 }
1137 
1138 
1139 void Arg_comparator::set_datetime_cmp_func(Item_result_field *owner_arg,
1140  Item **a1, Item **b1)
1141 {
1142  thd= current_thd;
1143  owner= owner_arg;
1144  a= a1;
1145  b= b1;
1146  a_type= (*a)->field_type();
1147  b_type= (*b)->field_type();
1148  a_cache= 0;
1149  b_cache= 0;
1150  is_nulls_eq= FALSE;
1151  func= &Arg_comparator::compare_datetime;
1152  get_value_a_func= &get_datetime_value;
1153  get_value_b_func= &get_datetime_value;
1154  set_cmp_context_for_datetime();
1155 }
1156 
1157 
1158 /*
1159  Retrieves correct DATETIME value from given item.
1160 
1161  SYNOPSIS
1162  get_datetime_value()
1163  thd thread handle
1164  item_arg [in/out] item to retrieve DATETIME value from
1165  cache_arg [in/out] pointer to place to store the caching item to
1166  warn_item [in] item for issuing the conversion warning
1167  is_null [out] TRUE <=> the item_arg is null
1168 
1169  DESCRIPTION
1170  Retrieves the correct DATETIME value from given item for comparison by the
1171  compare_datetime() function.
1172  If item's result can be compared as longlong then its int value is used
1173  and its string value is used otherwise. Strings are always parsed and
1174  converted to int values by the get_date_from_str() function.
1175  This allows us to compare correctly string dates with missed insignificant
1176  zeros. If an item is a constant one then its value is cached and it isn't
1177  get parsed again. An Item_cache_int object is used for caching values. It
1178  seamlessly substitutes the original item. The cache item is marked as
1179  non-constant to prevent re-caching it again. In order to compare
1180  correctly DATE and DATETIME items the result of the former are treated as
1181  a DATETIME with zero time (00:00:00).
1182 
1183  RETURN
1184  obtained value
1185 */
1186 
1187 
1188 longlong
1189 get_datetime_value(THD *thd, Item ***item_arg, Item **cache_arg,
1190  Item *warn_item, bool *is_null)
1191 {
1192  longlong value= 0;
1193  String buf, *str= 0;
1194  Item *item= **item_arg;
1195 
1196  if (item->is_temporal())
1197  {
1198  value= item->val_date_temporal();
1199  *is_null= item->null_value;
1200  }
1201  else
1202  {
1203  str= item->val_str(&buf);
1204  *is_null= item->null_value;
1205  }
1206  if (*is_null)
1207  return ~(ulonglong) 0;
1208  /*
1209  Convert strings to the integer DATE/DATETIME representation.
1210  Even if both dates provided in strings we can't compare them directly as
1211  strings as there is no warranty that they are correct and do not miss
1212  some insignificant zeros.
1213  */
1214  if (str)
1215  {
1216  bool error;
1217  enum_field_types f_type= warn_item->field_type();
1218  timestamp_type t_type= f_type ==
1219  MYSQL_TYPE_DATE ? MYSQL_TIMESTAMP_DATE : MYSQL_TIMESTAMP_DATETIME;
1220  value= (longlong) get_date_from_str(thd, str, t_type, warn_item->item_name.ptr(), &error);
1221  /*
1222  If str did not contain a valid date according to the current
1223  SQL_MODE, get_date_from_str() has already thrown a warning,
1224  and we don't want to throw NULL on invalid date (see 5.2.6
1225  "SQL modes" in the manual), so we're done here.
1226  */
1227  }
1228  /*
1229  Do not cache GET_USER_VAR() function as its const_item() may return TRUE
1230  for the current thread but it still may change during the execution.
1231  */
1232  if (item->const_item() && cache_arg &&
1233  item->type() != Item::CACHE_ITEM &&
1234  (item->type() != Item::FUNC_ITEM ||
1235  ((Item_func*)item)->functype() != Item_func::GUSERVAR_FUNC))
1236  {
1237  Item_cache_datetime *cache= new Item_cache_datetime(MYSQL_TYPE_DATETIME);
1238  /* Mark the cache as non-const to prevent re-caching. */
1239  cache->set_used_tables(1);
1240  cache->store(item, value);
1241  *cache_arg= cache;
1242  *item_arg= cache_arg;
1243  }
1244  return value;
1245 }
1246 
1247 
1248 /*
1249  Retrieves YEAR value of 19XX-00-00 00:00:00 form from given item.
1250 
1251  SYNOPSIS
1252  get_year_value()
1253  thd thread handle
1254  item_arg [in/out] item to retrieve YEAR value from
1255  cache_arg [in/out] pointer to place to store the caching item to
1256  warn_item [in] item for issuing the conversion warning
1257  is_null [out] TRUE <=> the item_arg is null
1258 
1259  DESCRIPTION
1260  Retrieves the YEAR value of 19XX form from given item for comparison by the
1261  compare_datetime() function.
1262  Converts year to DATETIME of form YYYY-00-00 00:00:00 for the compatibility
1263  with the get_datetime_value function result.
1264 
1265  RETURN
1266  obtained value
1267 */
1268 
1269 static longlong
1270 get_year_value(THD *thd, Item ***item_arg, Item **cache_arg,
1271  Item *warn_item, bool *is_null)
1272 {
1273  longlong value= 0;
1274  Item *item= **item_arg;
1275 
1276  value= item->val_int();
1277  *is_null= item->null_value;
1278  if (*is_null)
1279  return ~(ulonglong) 0;
1280 
1281  /*
1282  Coerce value to the 19XX form in order to correctly compare
1283  YEAR(2) & YEAR(4) types.
1284  Here we are converting all item values but YEAR(4) fields since
1285  1) YEAR(4) already has a regular YYYY form and
1286  2) we don't want to convert zero/bad YEAR(4) values to the
1287  value of 2000.
1288  */
1289  Item *real_item= item->real_item();
1290  Field *field= NULL;
1291  if (real_item->type() == Item::FIELD_ITEM)
1292  field= ((Item_field *)real_item)->field;
1293  else if (real_item->type() == Item::CACHE_ITEM)
1294  field= ((Item_cache *)real_item)->field();
1295  if (!(field && field->type() == MYSQL_TYPE_YEAR && field->field_length == 4))
1296  {
1297  if (value < 70)
1298  value+= 100;
1299  if (value <= 1900)
1300  value+= 1900;
1301  }
1302  /* Convert year to DATETIME packed format */
1303  return year_to_longlong_datetime_packed(value);
1304 }
1305 
1306 
1307 /*
1308  Compare items values as dates.
1309 
1310  SYNOPSIS
1311  Arg_comparator::compare_datetime()
1312 
1313  DESCRIPTION
1314  Compare items values as DATE/DATETIME for both EQUAL_FUNC and from other
1315  comparison functions. The correct DATETIME values are obtained
1316  with help of the get_datetime_value() function.
1317 
1318  RETURN
1319  If is_nulls_eq is TRUE:
1320  1 if items are equal or both are null
1321  0 otherwise
1322  If is_nulls_eq is FALSE:
1323  -1 a < b or at least one item is null
1324  0 a == b
1325  1 a > b
1326  See the table:
1327  is_nulls_eq | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 |
1328  a_is_null | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 |
1329  b_is_null | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 0 |
1330  result | 1 | 0 | 0 |0/1|-1 |-1 |-1 |-1/0/1|
1331 */
1332 
1333 int Arg_comparator::compare_datetime()
1334 {
1335  bool a_is_null, b_is_null;
1336  longlong a_value, b_value;
1337 
1338  /* Get DATE/DATETIME/TIME value of the 'a' item. */
1339  a_value= (*get_value_a_func)(thd, &a, &a_cache, *b, &a_is_null);
1340  if (!is_nulls_eq && a_is_null)
1341  {
1342  if (set_null)
1343  owner->null_value= 1;
1344  return -1;
1345  }
1346 
1347  /* Get DATE/DATETIME/TIME value of the 'b' item. */
1348  b_value= (*get_value_b_func)(thd, &b, &b_cache, *a, &b_is_null);
1349  if (a_is_null || b_is_null)
1350  {
1351  if (set_null)
1352  owner->null_value= is_nulls_eq ? 0 : 1;
1353  return is_nulls_eq ? (a_is_null == b_is_null) : -1;
1354  }
1355 
1356  /* Here we have two not-NULL values. */
1357  if (set_null)
1358  owner->null_value= 0;
1359 
1360  /* Compare values. */
1361  if (is_nulls_eq)
1362  return (a_value == b_value);
1363  return a_value < b_value ? -1 : (a_value > b_value ? 1 : 0);
1364 }
1365 
1366 
1367 int Arg_comparator::compare_string()
1368 {
1369  String *res1,*res2;
1370  if ((res1= (*a)->val_str(&value1)))
1371  {
1372  if ((res2= (*b)->val_str(&value2)))
1373  {
1374  if (set_null)
1375  owner->null_value= 0;
1376  return sortcmp(res1,res2,cmp_collation.collation);
1377  }
1378  }
1379  if (set_null)
1380  owner->null_value= 1;
1381  return -1;
1382 }
1383 
1384 
1397 {
1398  String *res1,*res2;
1399  if ((res1= (*a)->val_str(&value1)))
1400  {
1401  if ((res2= (*b)->val_str(&value2)))
1402  {
1403  if (set_null)
1404  owner->null_value= 0;
1405  uint res1_length= res1->length();
1406  uint res2_length= res2->length();
1407  int cmp= memcmp(res1->ptr(), res2->ptr(), min(res1_length,res2_length));
1408  return cmp ? cmp : (int) (res1_length - res2_length);
1409  }
1410  }
1411  if (set_null)
1412  owner->null_value= 1;
1413  return -1;
1414 }
1415 
1416 
1423 {
1424  String *res1,*res2;
1425  res1= (*a)->val_str(&value1);
1426  res2= (*b)->val_str(&value2);
1427  if (!res1 || !res2)
1428  return test(res1 == res2);
1429  return test(sortcmp(res1, res2, cmp_collation.collation) == 0);
1430 }
1431 
1432 
1433 int Arg_comparator::compare_e_binary_string()
1434 {
1435  String *res1,*res2;
1436  res1= (*a)->val_str(&value1);
1437  res2= (*b)->val_str(&value2);
1438  if (!res1 || !res2)
1439  return test(res1 == res2);
1440  return test(stringcmp(res1, res2) == 0);
1441 }
1442 
1443 
1444 int Arg_comparator::compare_real()
1445 {
1446  /*
1447  Fix yet another manifestation of Bug#2338. 'Volatile' will instruct
1448  gcc to flush double values out of 80-bit Intel FPU registers before
1449  performing the comparison.
1450  */
1451  volatile double val1, val2;
1452  val1= (*a)->val_real();
1453  if (!(*a)->null_value)
1454  {
1455  val2= (*b)->val_real();
1456  if (!(*b)->null_value)
1457  {
1458  if (set_null)
1459  owner->null_value= 0;
1460  if (val1 < val2) return -1;
1461  if (val1 == val2) return 0;
1462  return 1;
1463  }
1464  }
1465  if (set_null)
1466  owner->null_value= 1;
1467  return -1;
1468 }
1469 
1470 int Arg_comparator::compare_decimal()
1471 {
1472  my_decimal decimal1;
1473  my_decimal *val1= (*a)->val_decimal(&decimal1);
1474  if (!(*a)->null_value)
1475  {
1476  my_decimal decimal2;
1477  my_decimal *val2= (*b)->val_decimal(&decimal2);
1478  if (!(*b)->null_value)
1479  {
1480  if (set_null)
1481  owner->null_value= 0;
1482  return my_decimal_cmp(val1, val2);
1483  }
1484  }
1485  if (set_null)
1486  owner->null_value= 1;
1487  return -1;
1488 }
1489 
1490 int Arg_comparator::compare_e_real()
1491 {
1492  double val1= (*a)->val_real();
1493  double val2= (*b)->val_real();
1494  if ((*a)->null_value || (*b)->null_value)
1495  return test((*a)->null_value && (*b)->null_value);
1496  return test(val1 == val2);
1497 }
1498 
1499 int Arg_comparator::compare_e_decimal()
1500 {
1501  my_decimal decimal1, decimal2;
1502  my_decimal *val1= (*a)->val_decimal(&decimal1);
1503  my_decimal *val2= (*b)->val_decimal(&decimal2);
1504  if ((*a)->null_value || (*b)->null_value)
1505  return test((*a)->null_value && (*b)->null_value);
1506  return test(my_decimal_cmp(val1, val2) == 0);
1507 }
1508 
1509 
1510 int Arg_comparator::compare_real_fixed()
1511 {
1512  /*
1513  Fix yet another manifestation of Bug#2338. 'Volatile' will instruct
1514  gcc to flush double values out of 80-bit Intel FPU registers before
1515  performing the comparison.
1516  */
1517  volatile double val1, val2;
1518  val1= (*a)->val_real();
1519  if (!(*a)->null_value)
1520  {
1521  val2= (*b)->val_real();
1522  if (!(*b)->null_value)
1523  {
1524  if (set_null)
1525  owner->null_value= 0;
1526  if (val1 == val2 || fabs(val1 - val2) < precision)
1527  return 0;
1528  if (val1 < val2)
1529  return -1;
1530  return 1;
1531  }
1532  }
1533  if (set_null)
1534  owner->null_value= 1;
1535  return -1;
1536 }
1537 
1538 
1539 int Arg_comparator::compare_e_real_fixed()
1540 {
1541  double val1= (*a)->val_real();
1542  double val2= (*b)->val_real();
1543  if ((*a)->null_value || (*b)->null_value)
1544  return test((*a)->null_value && (*b)->null_value);
1545  return test(val1 == val2 || fabs(val1 - val2) < precision);
1546 }
1547 
1548 
1549 int Arg_comparator::compare_int_signed()
1550 {
1551  longlong val1= (*a)->val_int();
1552  if (!(*a)->null_value)
1553  {
1554  longlong val2= (*b)->val_int();
1555  if (!(*b)->null_value)
1556  {
1557  if (set_null)
1558  owner->null_value= 0;
1559  if (val1 < val2) return -1;
1560  if (val1 == val2) return 0;
1561  return 1;
1562  }
1563  }
1564  if (set_null)
1565  owner->null_value= 1;
1566  return -1;
1567 }
1568 
1569 
1574 {
1575  /*
1576  Note, we cannot do this:
1577  DBUG_ASSERT((*a)->field_type() == MYSQL_TYPE_TIME);
1578  DBUG_ASSERT((*b)->field_type() == MYSQL_TYPE_TIME);
1579 
1580  SELECT col_time_key FROM t1
1581  WHERE
1582  col_time_key != UTC_DATE()
1583  AND
1584  col_time_key = MAKEDATE(43, -2852);
1585 
1586  is rewritten to:
1587 
1588  SELECT col_time_key FROM t1
1589  WHERE
1590  MAKEDATE(43, -2852) != UTC_DATE()
1591  AND
1592  col_time_key = MAKEDATE(43, -2852);
1593  */
1594  longlong val1= (*a)->val_time_temporal();
1595  if (!(*a)->null_value)
1596  {
1597  longlong val2= (*b)->val_time_temporal();
1598  if (!(*b)->null_value)
1599  {
1600  if (set_null)
1601  owner->null_value= 0;
1602  return val1 < val2 ? -1 : val1 > val2 ? 1 : 0;
1603  }
1604  }
1605  if (set_null)
1606  owner->null_value= 1;
1607  return -1;
1608 }
1609 
1610 
1615 {
1616  longlong val1= (*a)->val_time_temporal();
1617  longlong val2= (*b)->val_time_temporal();
1618  if ((*a)->null_value || (*b)->null_value)
1619  return test((*a)->null_value && (*b)->null_value);
1620  return test(val1 == val2);
1621 }
1622 
1623 
1624 
1630 {
1631  ulonglong val1= (*a)->val_int();
1632  if (!(*a)->null_value)
1633  {
1634  ulonglong val2= (*b)->val_int();
1635  if (!(*b)->null_value)
1636  {
1637  if (set_null)
1638  owner->null_value= 0;
1639  if (val1 < val2) return -1;
1640  if (val1 == val2) return 0;
1641  return 1;
1642  }
1643  }
1644  if (set_null)
1645  owner->null_value= 1;
1646  return -1;
1647 }
1648 
1649 
1655 {
1656  longlong sval1= (*a)->val_int();
1657  if (!(*a)->null_value)
1658  {
1659  ulonglong uval2= (ulonglong)(*b)->val_int();
1660  if (!(*b)->null_value)
1661  {
1662  if (set_null)
1663  owner->null_value= 0;
1664  if (sval1 < 0 || (ulonglong)sval1 < uval2)
1665  return -1;
1666  if ((ulonglong)sval1 == uval2)
1667  return 0;
1668  return 1;
1669  }
1670  }
1671  if (set_null)
1672  owner->null_value= 1;
1673  return -1;
1674 }
1675 
1676 
1682 {
1683  ulonglong uval1= (ulonglong)(*a)->val_int();
1684  if (!(*a)->null_value)
1685  {
1686  longlong sval2= (*b)->val_int();
1687  if (!(*b)->null_value)
1688  {
1689  if (set_null)
1690  owner->null_value= 0;
1691  if (sval2 < 0)
1692  return 1;
1693  if (uval1 < (ulonglong)sval2)
1694  return -1;
1695  if (uval1 == (ulonglong)sval2)
1696  return 0;
1697  return 1;
1698  }
1699  }
1700  if (set_null)
1701  owner->null_value= 1;
1702  return -1;
1703 }
1704 
1705 
1706 int Arg_comparator::compare_e_int()
1707 {
1708  longlong val1= (*a)->val_int();
1709  longlong val2= (*b)->val_int();
1710  if ((*a)->null_value || (*b)->null_value)
1711  return test((*a)->null_value && (*b)->null_value);
1712  return test(val1 == val2);
1713 }
1714 
1719 {
1720  longlong val1= (*a)->val_int();
1721  longlong val2= (*b)->val_int();
1722  if ((*a)->null_value || (*b)->null_value)
1723  return test((*a)->null_value && (*b)->null_value);
1724  return (val1 >= 0) && test(val1 == val2);
1725 }
1726 
1727 int Arg_comparator::compare_row()
1728 {
1729  int res= 0;
1730  bool was_null= 0;
1731  (*a)->bring_value();
1732  (*b)->bring_value();
1733 
1734  if ((*a)->null_value || (*b)->null_value)
1735  {
1736  owner->null_value= 1;
1737  return -1;
1738  }
1739 
1740  uint n= (*a)->cols();
1741  for (uint i= 0; i<n; i++)
1742  {
1743  res= comparators[i].compare();
1744  /* Aggregate functions don't need special null handling. */
1745  if (owner->null_value && owner->type() == Item::FUNC_ITEM)
1746  {
1747  // NULL was compared
1748  switch (((Item_func*)owner)->functype()) {
1749  case Item_func::NE_FUNC:
1750  break; // NE never aborts on NULL even if abort_on_null is set
1751  case Item_func::LT_FUNC:
1752  case Item_func::LE_FUNC:
1753  case Item_func::GT_FUNC:
1754  case Item_func::GE_FUNC:
1755  return -1; // <, <=, > and >= always fail on NULL
1756  default: // EQ_FUNC
1757  if (((Item_bool_func2*)owner)->abort_on_null)
1758  return -1; // We do not need correct NULL returning
1759  }
1760  was_null= 1;
1761  owner->null_value= 0;
1762  res= 0; // continue comparison (maybe we will meet explicit difference)
1763  }
1764  else if (res)
1765  return res;
1766  }
1767  if (was_null)
1768  {
1769  /*
1770  There was NULL(s) in comparison in some parts, but there was no
1771  explicit difference in other parts, so we have to return NULL.
1772  */
1773  owner->null_value= 1;
1774  return -1;
1775  }
1776  return 0;
1777 }
1778 
1779 
1780 int Arg_comparator::compare_e_row()
1781 {
1782  (*a)->bring_value();
1783  (*b)->bring_value();
1784  uint n= (*a)->cols();
1785  for (uint i= 0; i<n; i++)
1786  {
1787  if (!comparators[i].compare())
1788  return 0;
1789  }
1790  return 1;
1791 }
1792 
1793 
1794 void Item_func_truth::fix_length_and_dec()
1795 {
1796  maybe_null= 0;
1797  null_value= 0;
1798  decimals= 0;
1799  max_length= 1;
1800 }
1801 
1802 
1803 void Item_func_truth::print(String *str, enum_query_type query_type)
1804 {
1805  str->append('(');
1806  args[0]->print(str, query_type);
1807  str->append(STRING_WITH_LEN(" is "));
1808  if (! affirmative)
1809  str->append(STRING_WITH_LEN("not "));
1810  if (value)
1811  str->append(STRING_WITH_LEN("true"));
1812  else
1813  str->append(STRING_WITH_LEN("false"));
1814  str->append(')');
1815 }
1816 
1817 
1819 {
1820  bool val= args[0]->val_bool();
1821  if (args[0]->null_value)
1822  {
1823  /*
1824  NULL val IS {TRUE, FALSE} --> FALSE
1825  NULL val IS NOT {TRUE, FALSE} --> TRUE
1826  */
1827  return (! affirmative);
1828  }
1829 
1830  if (affirmative)
1831  {
1832  /* {TRUE, FALSE} val IS {TRUE, FALSE} value */
1833  return (val == value);
1834  }
1835 
1836  /* {TRUE, FALSE} val IS NOT {TRUE, FALSE} value */
1837  return (val != value);
1838 }
1839 
1840 
1841 longlong Item_func_truth::val_int()
1842 {
1843  return (val_bool() ? 1 : 0);
1844 }
1845 
1846 
1847 bool Item_in_optimizer::fix_left(THD *thd, Item **ref)
1848 {
1849  /*
1850  Refresh this pointer as left_expr may have been substituted
1851  during resolving.
1852  */
1853  args[0]= ((Item_in_subselect *)args[1])->left_expr;
1854 
1855  if ((!args[0]->fixed && args[0]->fix_fields(thd, args)) ||
1856  (!cache && !(cache= Item_cache::get_cache(args[0]))))
1857  return 1;
1858 
1859  cache->setup(args[0]);
1860  used_tables_cache= args[0]->used_tables();
1861  if (cache->cols() == 1)
1862  {
1863  cache->set_used_tables(used_tables_cache);
1864  }
1865  else
1866  {
1867  uint n= cache->cols();
1868  for (uint i= 0; i < n; i++)
1869  {
1870  ((Item_cache *)cache->element_index(i))->
1871  set_used_tables(args[0]->element_index(i)->used_tables());
1872  }
1873  }
1874  not_null_tables_cache= args[0]->not_null_tables();
1875  with_sum_func= args[0]->with_sum_func;
1876  if ((const_item_cache= args[0]->const_item()))
1877  cache->store(args[0]);
1878  return 0;
1879 }
1880 
1881 
1882 bool Item_in_optimizer::fix_fields(THD *thd, Item **ref)
1883 {
1884  DBUG_ASSERT(fixed == 0);
1885  if (fix_left(thd, ref))
1886  return TRUE;
1887  if (args[0]->maybe_null)
1888  maybe_null=1;
1889 
1890  if (!args[1]->fixed && args[1]->fix_fields(thd, args+1))
1891  return TRUE;
1892  Item_in_subselect * sub= (Item_in_subselect *)args[1];
1893  if (args[0]->cols() != sub->engine->cols())
1894  {
1895  my_error(ER_OPERAND_COLUMNS, MYF(0), args[0]->cols());
1896  return TRUE;
1897  }
1898  if (args[1]->maybe_null)
1899  maybe_null=1;
1900  with_sum_func= with_sum_func || args[1]->with_sum_func;
1901  used_tables_cache|= args[1]->used_tables();
1902  not_null_tables_cache|= args[1]->not_null_tables();
1903 
1904  if (!sub->is_top_level_item())
1905  {
1906  /*
1907  This is a NOT IN subquery predicate (or equivalent). Null values passed
1908  from outer tables and used in the left-hand expression of the predicate
1909  must be considered in the evaluation, hence filter out these tables
1910  from the set of null-rejecting tables.
1911  */
1912  not_null_tables_cache&= ~args[0]->not_null_tables();
1913  }
1914  const_item_cache&= args[1]->const_item();
1915  fixed= 1;
1916  return FALSE;
1917 }
1918 
1919 
1920 void Item_in_optimizer::fix_after_pullout(st_select_lex *parent_select,
1921  st_select_lex *removed_select)
1922 {
1925  const_item_cache= 1;
1926 
1927  /*
1928  No need to call fix_after_pullout() on args[0] (ie left expression),
1929  as Item_in_subselect::fix_after_pullout() will do this.
1930  So, just forward the call to the Item_in_subselect object.
1931  */
1932 
1933  args[1]->fix_after_pullout(parent_select, removed_select);
1934 
1935  used_tables_cache|= args[1]->used_tables();
1936  not_null_tables_cache|= args[1]->not_null_tables();
1937  const_item_cache&= args[1]->const_item();
1938 }
1939 
1940 
2016 {
2017  bool tmp;
2018  DBUG_ASSERT(fixed == 1);
2019  cache->store(args[0]);
2020  cache->cache_value();
2021 
2022  if (cache->null_value)
2023  {
2024  Item_in_subselect * const item_subs=
2025  static_cast<Item_in_subselect *>(args[1]);
2026  /*
2027  We're evaluating
2028  "<outer_value_list> [NOT] IN (SELECT <inner_value_list>...)"
2029  where one or more of the outer values is NULL.
2030  */
2031  if (item_subs->is_top_level_item())
2032  {
2033  /*
2034  We're evaluating a top level item, e.g.
2035  "<outer_value_list> IN (SELECT <inner_value_list>...)",
2036  and in this case a NULL value in the outer_value_list means
2037  that the result shall be NULL/FALSE (makes no difference for
2038  top level items). The cached value is NULL, so just return
2039  NULL.
2040  */
2041  null_value= 1;
2042  }
2043  else
2044  {
2045  /*
2046  We're evaluating an item where a NULL value in either the
2047  outer or inner value list does not automatically mean that we
2048  can return NULL/FALSE. An example of such a query is
2049  "<outer_value_list> NOT IN (SELECT <inner_value_list>...)"
2050  The result when there is at least one NULL value is: NULL if the
2051  SELECT evaluated over the non-NULL values produces at least
2052  one row, FALSE otherwise
2053  */
2054  bool all_left_cols_null= true;
2055  const uint ncols= cache->cols();
2056 
2057  /*
2058  Turn off the predicates that are based on column compares for
2059  which the left part is currently NULL
2060  */
2061  for (uint i= 0; i < ncols; i++)
2062  {
2063  if (cache->element_index(i)->null_value)
2064  item_subs->set_cond_guard_var(i, FALSE);
2065  else
2066  all_left_cols_null= false;
2067  }
2068 
2069  if (all_left_cols_null && result_for_null_param != UNKNOWN &&
2070  !item_subs->originally_dependent())
2071  {
2072  /*
2073  This subquery was originally not correlated. The IN->EXISTS
2074  transformation may have made it correlated, but only to the left
2075  expression. All values in the left expression are NULL, and we have
2076  already evaluated the subquery for all NULL values: return the same
2077  result we did last time without evaluating the subquery.
2078  */
2079  null_value= result_for_null_param;
2080  }
2081  else
2082  {
2083  /* The subquery has to be evaluated */
2084  (void) item_subs->val_bool_result();
2085  if (!item_subs->value)
2086  null_value= item_subs->null_value;
2087  else
2088  null_value= TRUE;
2089  if (all_left_cols_null)
2090  result_for_null_param= null_value;
2091  }
2092 
2093  /* Turn all predicates back on */
2094  for (uint i= 0; i < ncols; i++)
2095  item_subs->set_cond_guard_var(i, TRUE);
2096  }
2097  return 0;
2098  }
2099  tmp= args[1]->val_bool_result();
2100  null_value= args[1]->null_value;
2101  return tmp;
2102 }
2103 
2104 
2105 void Item_in_optimizer::keep_top_level_cache()
2106 {
2107  cache->keep_array();
2108  save_cache= 1;
2109 }
2110 
2111 
2112 void Item_in_optimizer::cleanup()
2113 {
2114  DBUG_ENTER("Item_in_optimizer::cleanup");
2115  Item_bool_func::cleanup();
2116  if (!save_cache)
2117  cache= 0;
2118  DBUG_VOID_RETURN;
2119 }
2120 
2121 
2122 bool Item_in_optimizer::is_null()
2123 {
2124  val_int();
2125  return null_value;
2126 }
2127 
2128 
2151 Item *Item_in_optimizer::transform(Item_transformer transformer, uchar *argument)
2152 {
2153  Item *new_item;
2154 
2155  DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
2156  DBUG_ASSERT(arg_count == 2);
2157 
2158  /* Transform the left IN operand. */
2159  new_item= args[0]->transform(transformer, argument);
2160  if (!new_item)
2161  return 0;
2162  /*
2163  THD::change_item_tree() should be called only if the tree was
2164  really transformed, i.e. when a new item has been created.
2165  Otherwise we'll be allocating a lot of unnecessary memory for
2166  change records at each execution.
2167  */
2168  if (args[0] != new_item)
2169  current_thd->change_item_tree(args, new_item);
2170 
2171  /*
2172  Transform the right IN operand which should be an Item_in_subselect or a
2173  subclass of it. The left operand of the IN must be the same as the left
2174  operand of this Item_in_optimizer, so in this case there is no further
2175  transformation, we only make both operands the same.
2176  TODO: is it the way it should be?
2177  */
2178  DBUG_ASSERT((args[1])->type() == Item::SUBSELECT_ITEM &&
2179  (((Item_subselect*)(args[1]))->substype() ==
2180  Item_subselect::IN_SUBS ||
2181  ((Item_subselect*)(args[1]))->substype() ==
2182  Item_subselect::ALL_SUBS ||
2183  ((Item_subselect*)(args[1]))->substype() ==
2184  Item_subselect::ANY_SUBS));
2185 
2186  Item_in_subselect *in_arg= (Item_in_subselect*)args[1];
2187 
2188  if (in_arg->left_expr != args[0])
2189  current_thd->change_item_tree(&in_arg->left_expr, args[0]);
2190 
2191  return (this->*transformer)(argument);
2192 }
2193 
2194 
2195 longlong Item_func_eq::val_int()
2196 {
2197  DBUG_ASSERT(fixed == 1);
2198  int value= cmp.compare();
2199  return value == 0 ? 1 : 0;
2200 }
2201 
2202 
2206 {
2208  maybe_null=null_value=0;
2209 }
2210 
2211 longlong Item_func_equal::val_int()
2212 {
2213  DBUG_ASSERT(fixed == 1);
2214  return cmp.compare();
2215 }
2216 
2217 longlong Item_func_ne::val_int()
2218 {
2219  DBUG_ASSERT(fixed == 1);
2220  int value= cmp.compare();
2221  return value != 0 && !null_value ? 1 : 0;
2222 }
2223 
2224 
2225 longlong Item_func_ge::val_int()
2226 {
2227  DBUG_ASSERT(fixed == 1);
2228  int value= cmp.compare();
2229  return value >= 0 ? 1 : 0;
2230 }
2231 
2232 
2233 longlong Item_func_gt::val_int()
2234 {
2235  DBUG_ASSERT(fixed == 1);
2236  int value= cmp.compare();
2237  return value > 0 ? 1 : 0;
2238 }
2239 
2240 longlong Item_func_le::val_int()
2241 {
2242  DBUG_ASSERT(fixed == 1);
2243  int value= cmp.compare();
2244  return value <= 0 && !null_value ? 1 : 0;
2245 }
2246 
2247 
2248 longlong Item_func_lt::val_int()
2249 {
2250  DBUG_ASSERT(fixed == 1);
2251  int value= cmp.compare();
2252  return value < 0 && !null_value ? 1 : 0;
2253 }
2254 
2255 
2256 longlong Item_func_strcmp::val_int()
2257 {
2258  DBUG_ASSERT(fixed == 1);
2259  String *a=args[0]->val_str(&cmp.value1);
2260  String *b=args[1]->val_str(&cmp.value2);
2261  if (!a || !b)
2262  {
2263  null_value=1;
2264  return 0;
2265  }
2266  int value= sortcmp(a,b,cmp.cmp_collation.collation);
2267  null_value=0;
2268  return !value ? 0 : (value < 0 ? (longlong) -1 : (longlong) 1);
2269 }
2270 
2271 
2272 bool Item_func_opt_neg::eq(const Item *item, bool binary_cmp) const
2273 {
2274  /* Assume we don't have rtti */
2275  if (this == item)
2276  return 1;
2277  if (item->type() != FUNC_ITEM)
2278  return 0;
2279  Item_func *item_func=(Item_func*) item;
2280  if (arg_count != item_func->arg_count ||
2281  functype() != item_func->functype())
2282  return 0;
2283  if (negated != ((Item_func_opt_neg *) item_func)->negated)
2284  return 0;
2285  for (uint i=0; i < arg_count ; i++)
2286  if (!args[i]->eq(item_func->arguments()[i], binary_cmp))
2287  return 0;
2288  return 1;
2289 }
2290 
2291 
2292 void Item_func_interval::fix_length_and_dec()
2293 {
2294  uint rows= row->cols();
2295 
2296  use_decimal_comparison= ((row->element_index(0)->result_type() ==
2297  DECIMAL_RESULT) ||
2298  (row->element_index(0)->result_type() ==
2299  INT_RESULT));
2300  if (rows > 8)
2301  {
2302  bool not_null_consts= TRUE;
2303 
2304  for (uint i= 1; not_null_consts && i < rows; i++)
2305  {
2306  Item *el= row->element_index(i);
2307  not_null_consts&= el->const_item() & !el->is_null();
2308  }
2309 
2310  if (not_null_consts &&
2311  (intervals=
2312  (interval_range*) sql_alloc(sizeof(interval_range) * (rows - 1))))
2313  {
2314  if (use_decimal_comparison)
2315  {
2316  for (uint i= 1; i < rows; i++)
2317  {
2318  Item *el= row->element_index(i);
2319  interval_range *range= intervals + (i-1);
2320  if ((el->result_type() == DECIMAL_RESULT) ||
2321  (el->result_type() == INT_RESULT))
2322  {
2323  range->type= DECIMAL_RESULT;
2324  range->dec.init();
2325  my_decimal *dec= el->val_decimal(&range->dec);
2326  if (dec != &range->dec)
2327  {
2328  range->dec= *dec;
2329  }
2330  }
2331  else
2332  {
2333  range->type= REAL_RESULT;
2334  range->dbl= el->val_real();
2335  }
2336  }
2337  }
2338  else
2339  {
2340  for (uint i= 1; i < rows; i++)
2341  {
2342  intervals[i-1].dbl= row->element_index(i)->val_real();
2343  }
2344  }
2345  }
2346  }
2347  maybe_null= 0;
2348  max_length= 2;
2349  used_tables_cache|= row->used_tables();
2350  not_null_tables_cache= row->not_null_tables();
2351  with_sum_func= with_sum_func || row->with_sum_func;
2352  const_item_cache&= row->const_item();
2353 }
2354 
2355 
2371 {
2372  DBUG_ASSERT(fixed == 1);
2373  double value;
2374  my_decimal dec_buf, *dec= NULL;
2375  uint i;
2376 
2377  if (use_decimal_comparison)
2378  {
2379  dec= row->element_index(0)->val_decimal(&dec_buf);
2380  if (row->element_index(0)->null_value)
2381  return -1;
2382  my_decimal2double(E_DEC_FATAL_ERROR, dec, &value);
2383  }
2384  else
2385  {
2386  value= row->element_index(0)->val_real();
2387  if (row->element_index(0)->null_value)
2388  return -1;
2389  }
2390 
2391  if (intervals)
2392  { // Use binary search to find interval
2393  uint start,end;
2394  start= 0;
2395  end= row->cols()-2;
2396  while (start != end)
2397  {
2398  uint mid= (start + end + 1) / 2;
2399  interval_range *range= intervals + mid;
2400  my_bool cmp_result;
2401  /*
2402  The values in the range intervall may have different types,
2403  Only do a decimal comparision of the first argument is a decimal
2404  and we are comparing against a decimal
2405  */
2406  if (dec && range->type == DECIMAL_RESULT)
2407  cmp_result= my_decimal_cmp(&range->dec, dec) <= 0;
2408  else
2409  cmp_result= (range->dbl <= value);
2410  if (cmp_result)
2411  start= mid;
2412  else
2413  end= mid - 1;
2414  }
2415  interval_range *range= intervals+start;
2416  return ((dec && range->type == DECIMAL_RESULT) ?
2417  my_decimal_cmp(dec, &range->dec) < 0 :
2418  value < range->dbl) ? 0 : start + 1;
2419  }
2420 
2421  for (i=1 ; i < row->cols() ; i++)
2422  {
2423  Item *el= row->element_index(i);
2424  if (use_decimal_comparison &&
2425  ((el->result_type() == DECIMAL_RESULT) ||
2426  (el->result_type() == INT_RESULT)))
2427  {
2428  my_decimal e_dec_buf, *e_dec= el->val_decimal(&e_dec_buf);
2429  /* Skip NULL ranges. */
2430  if (el->null_value)
2431  continue;
2432  if (my_decimal_cmp(e_dec, dec) > 0)
2433  return i - 1;
2434  }
2435  else
2436  {
2437  double val= el->val_real();
2438  /* Skip NULL ranges. */
2439  if (el->null_value)
2440  continue;
2441  if (val > value)
2442  return i - 1;
2443  }
2444  }
2445  return i-1;
2446 }
2447 
2448 
2478 {
2479  if (Item_func_opt_neg::fix_fields(thd, ref))
2480  return 1;
2481 
2482  thd->lex->current_select->between_count++;
2483 
2484  /* not_null_tables_cache == union(T1(e),T1(e1),T1(e2)) */
2485  if (pred_level && !negated)
2486  return 0;
2487 
2488  /* not_null_tables_cache == union(T1(e), intersection(T1(e1),T1(e2))) */
2489  not_null_tables_cache= (args[0]->not_null_tables() |
2490  (args[1]->not_null_tables() &
2491  args[2]->not_null_tables()));
2492 
2493  return 0;
2494 }
2495 
2496 
2497 void Item_func_between::fix_length_and_dec()
2498 {
2499  max_length= 1;
2500  int i;
2501  int datetime_items_found= 0;
2502  int time_items_found= 0;
2503  compare_as_dates_with_strings= false;
2504  compare_as_temporal_times= compare_as_temporal_dates= false;
2505  THD *thd= current_thd;
2506 
2507  /*
2508  As some compare functions are generated after sql_yacc,
2509  we have to check for out of memory conditions here
2510  */
2511  if (!args[0] || !args[1] || !args[2])
2512  return;
2513  if ( agg_cmp_type(&cmp_type, args, 3))
2514  return;
2515  if (cmp_type == STRING_RESULT &&
2516  agg_arg_charsets_for_comparison(cmp_collation, args, 3))
2517  return;
2518 
2519  /*
2520  Detect the comparison of DATE/DATETIME items.
2521  At least one of items should be a DATE/DATETIME item and other items
2522  should return the STRING result.
2523  */
2524  if (cmp_type == STRING_RESULT)
2525  {
2526  for (i= 0; i < 3; i++)
2527  {
2528  if (args[i]->is_temporal_with_date())
2529  datetime_items_found++;
2530  else
2531  if (args[i]->field_type() == MYSQL_TYPE_TIME)
2532  time_items_found++;
2533  }
2534  }
2535 
2536  if (datetime_items_found + time_items_found == 3)
2537  {
2538  if (time_items_found == 3)
2539  {
2540  // All items are TIME
2541  cmp_type= INT_RESULT;
2542  compare_as_temporal_times= true;
2543  }
2544  else
2545  {
2546  /*
2547  There is at least one DATE or DATETIME item,
2548  all other items are DATE, DATETIME or TIME.
2549  */
2550  cmp_type= INT_RESULT;
2551  compare_as_temporal_dates= true;
2552  }
2553  }
2554  else if (datetime_items_found > 0)
2555  {
2556  /*
2557  There is at least one DATE or DATETIME item.
2558  All other items are DATE, DATETIME or strings.
2559  */
2560  compare_as_dates_with_strings= true;
2561  ge_cmp.set_datetime_cmp_func(this, args, args + 1);
2562  le_cmp.set_datetime_cmp_func(this, args, args + 2);
2563  }
2564  else if (args[0]->real_item()->type() == FIELD_ITEM &&
2565  thd->lex->sql_command != SQLCOM_CREATE_VIEW &&
2566  thd->lex->sql_command != SQLCOM_SHOW_CREATE)
2567  {
2568  Item_field *field_item= (Item_field*) (args[0]->real_item());
2569  if (field_item->field->can_be_compared_as_longlong())
2570  {
2571  /*
2572  The following can't be recoded with || as convert_constant_item
2573  changes the argument
2574  */
2575  const bool cvt_arg1= convert_constant_item(thd, field_item, &args[1]);
2576  const bool cvt_arg2= convert_constant_item(thd, field_item, &args[2]);
2577  if (args[0]->is_temporal())
2578  { // special handling of date/time etc.
2579  if (cvt_arg1 || cvt_arg2)
2580  cmp_type=INT_RESULT;
2581  }
2582  else
2583  {
2584  if (cvt_arg1 && cvt_arg2)
2585  cmp_type=INT_RESULT;
2586  }
2587 
2588  if (args[0]->is_temporal() &&
2589  args[1]->is_temporal() &&
2590  args[2]->is_temporal())
2591  {
2592  /*
2593  An expression:
2594  time_or_datetime_field
2595  BETWEEN const_number_or_time_or_datetime_expr1
2596  AND const_number_or_time_or_datetime_expr2
2597  was rewritten to:
2598  time_field
2599  BETWEEN Item_time_with_ref1
2600  AND Item_time_with_ref2
2601  or
2602  datetime_field
2603  BETWEEN Item_datetime_with_ref1
2604  AND Item_datetime_with_ref2
2605  */
2606  if (field_item->field_type() == MYSQL_TYPE_TIME)
2607  compare_as_temporal_times= true;
2608  else if (field_item->is_temporal_with_date())
2609  compare_as_temporal_dates= true;
2610  }
2611  }
2612  }
2613 }
2614 
2615 
2616 longlong Item_func_between::val_int()
2617 { // ANSI BETWEEN
2618  DBUG_ASSERT(fixed == 1);
2619  if (compare_as_dates_with_strings)
2620  {
2621  int ge_res, le_res;
2622 
2623  ge_res= ge_cmp.compare();
2624  if ((null_value= args[0]->null_value))
2625  return 0;
2626  le_res= le_cmp.compare();
2627 
2628  if (!args[1]->null_value && !args[2]->null_value)
2629  return (longlong) ((ge_res >= 0 && le_res <=0) != negated);
2630  else if (args[1]->null_value)
2631  {
2632  null_value= le_res > 0; // not null if false range.
2633  }
2634  else
2635  {
2636  null_value= ge_res < 0;
2637  }
2638  }
2639  else if (cmp_type == STRING_RESULT)
2640  {
2641  String *value,*a,*b;
2642  value=args[0]->val_str(&value0);
2643  if ((null_value=args[0]->null_value))
2644  return 0;
2645  a=args[1]->val_str(&value1);
2646  b=args[2]->val_str(&value2);
2647  if (!args[1]->null_value && !args[2]->null_value)
2648  return (longlong) ((sortcmp(value,a,cmp_collation.collation) >= 0 &&
2649  sortcmp(value,b,cmp_collation.collation) <= 0) !=
2650  negated);
2651  if (args[1]->null_value && args[2]->null_value)
2652  null_value=1;
2653  else if (args[1]->null_value)
2654  {
2655  // Set to not null if false range.
2656  null_value= sortcmp(value,b,cmp_collation.collation) <= 0;
2657  }
2658  else
2659  {
2660  // Set to not null if false range.
2661  null_value= sortcmp(value,a,cmp_collation.collation) >= 0;
2662  }
2663  }
2664  else if (cmp_type == INT_RESULT)
2665  {
2666  longlong a, b, value;
2667  value= compare_as_temporal_times ? args[0]->val_time_temporal() :
2668  compare_as_temporal_dates ? args[0]->val_date_temporal() :
2669  args[0]->val_int();
2670  if ((null_value=args[0]->null_value))
2671  return 0; /* purecov: inspected */
2672  if (compare_as_temporal_times)
2673  {
2674  a= args[1]->val_time_temporal();
2675  b= args[2]->val_time_temporal();
2676  }
2677  else if (compare_as_temporal_dates)
2678  {
2679  a= args[1]->val_date_temporal();
2680  b= args[2]->val_date_temporal();
2681  }
2682  else
2683  {
2684  a= args[1]->val_int();
2685  b= args[2]->val_int();
2686  }
2687  if (!args[1]->null_value && !args[2]->null_value)
2688  return (longlong) ((value >= a && value <= b) != negated);
2689  if (args[1]->null_value && args[2]->null_value)
2690  null_value=1;
2691  else if (args[1]->null_value)
2692  {
2693  null_value= value <= b; // not null if false range.
2694  }
2695  else
2696  {
2697  null_value= value >= a;
2698  }
2699  }
2700  else if (cmp_type == DECIMAL_RESULT)
2701  {
2702  my_decimal dec_buf, *dec= args[0]->val_decimal(&dec_buf),
2703  a_buf, *a_dec, b_buf, *b_dec;
2704  if ((null_value=args[0]->null_value))
2705  return 0; /* purecov: inspected */
2706  a_dec= args[1]->val_decimal(&a_buf);
2707  b_dec= args[2]->val_decimal(&b_buf);
2708  if (!args[1]->null_value && !args[2]->null_value)
2709  return (longlong) ((my_decimal_cmp(dec, a_dec) >= 0 &&
2710  my_decimal_cmp(dec, b_dec) <= 0) != negated);
2711  if (args[1]->null_value && args[2]->null_value)
2712  null_value=1;
2713  else if (args[1]->null_value)
2714  null_value= (my_decimal_cmp(dec, b_dec) <= 0);
2715  else
2716  null_value= (my_decimal_cmp(dec, a_dec) >= 0);
2717  }
2718  else
2719  {
2720  double value= args[0]->val_real(),a,b;
2721  if ((null_value=args[0]->null_value))
2722  return 0; /* purecov: inspected */
2723  a= args[1]->val_real();
2724  b= args[2]->val_real();
2725  if (!args[1]->null_value && !args[2]->null_value)
2726  return (longlong) ((value >= a && value <= b) != negated);
2727  if (args[1]->null_value && args[2]->null_value)
2728  null_value=1;
2729  else if (args[1]->null_value)
2730  {
2731  null_value= value <= b; // not null if false range.
2732  }
2733  else
2734  {
2735  null_value= value >= a;
2736  }
2737  }
2738  return (longlong) (!null_value && negated);
2739 }
2740 
2741 
2742 void Item_func_between::print(String *str, enum_query_type query_type)
2743 {
2744  str->append('(');
2745  args[0]->print(str, query_type);
2746  if (negated)
2747  str->append(STRING_WITH_LEN(" not"));
2748  str->append(STRING_WITH_LEN(" between "));
2749  args[1]->print(str, query_type);
2750  str->append(STRING_WITH_LEN(" and "));
2751  args[2]->print(str, query_type);
2752  str->append(')');
2753 }
2754 
2755 void
2756 Item_func_ifnull::fix_length_and_dec()
2757 {
2758  uint32 char_length;
2759  agg_result_type(&hybrid_type, args, 2);
2760  cached_field_type= agg_field_type(args, 2);
2761  maybe_null=args[1]->maybe_null;
2762  decimals= max(args[0]->decimals, args[1]->decimals);
2763  unsigned_flag= args[0]->unsigned_flag && args[1]->unsigned_flag;
2764 
2765  if (hybrid_type == DECIMAL_RESULT || hybrid_type == INT_RESULT)
2766  {
2767  int len0= args[0]->max_char_length() - args[0]->decimals
2768  - (args[0]->unsigned_flag ? 0 : 1);
2769 
2770  int len1= args[1]->max_char_length() - args[1]->decimals
2771  - (args[1]->unsigned_flag ? 0 : 1);
2772 
2773  char_length= max(len0, len1) + decimals + (unsigned_flag ? 0 : 1);
2774  }
2775  else
2776  char_length= max(args[0]->max_char_length(), args[1]->max_char_length());
2777 
2778  switch (hybrid_type) {
2779  case STRING_RESULT:
2780  if (count_string_result_length(cached_field_type, args, arg_count))
2781  return;
2782  break;
2783  case DECIMAL_RESULT:
2784  case REAL_RESULT:
2785  break;
2786  case INT_RESULT:
2787  decimals= 0;
2788  break;
2789  case ROW_RESULT:
2790  default:
2791  DBUG_ASSERT(0);
2792  }
2793  fix_char_length(char_length);
2794 }
2795 
2796 
2797 uint Item_func_ifnull::decimal_precision() const
2798 {
2799  int arg0_int_part= args[0]->decimal_int_part();
2800  int arg1_int_part= args[1]->decimal_int_part();
2801  int max_int_part= max(arg0_int_part, arg1_int_part);
2802  int precision= max_int_part + decimals;
2803  return min<uint>(precision, DECIMAL_MAX_PRECISION);
2804 }
2805 
2806 
2807 Field *Item_func_ifnull::tmp_table_field(TABLE *table)
2808 {
2809  return tmp_table_field_from_field_type(table, 0);
2810 }
2811 
2812 double
2814 {
2815  DBUG_ASSERT(fixed == 1);
2816  double value= args[0]->val_real();
2817  if (!args[0]->null_value)
2818  {
2819  null_value=0;
2820  return value;
2821  }
2822  value= args[1]->val_real();
2823  if ((null_value=args[1]->null_value))
2824  return 0.0;
2825  return value;
2826 }
2827 
2828 longlong
2830 {
2831  DBUG_ASSERT(fixed == 1);
2832  longlong value=args[0]->val_int();
2833  if (!args[0]->null_value)
2834  {
2835  null_value=0;
2836  return value;
2837  }
2838  value=args[1]->val_int();
2839  if ((null_value=args[1]->null_value))
2840  return 0;
2841  return value;
2842 }
2843 
2844 
2846 {
2847  DBUG_ASSERT(fixed == 1);
2848  my_decimal *value= args[0]->val_decimal(decimal_value);
2849  if (!args[0]->null_value)
2850  {
2851  null_value= 0;
2852  return value;
2853  }
2854  value= args[1]->val_decimal(decimal_value);
2855  if ((null_value= args[1]->null_value))
2856  return 0;
2857  return value;
2858 }
2859 
2860 
2861 bool Item_func_ifnull::date_op(MYSQL_TIME *ltime, uint fuzzydate)
2862 {
2863  DBUG_ASSERT(fixed == 1);
2864  if (!args[0]->get_date(ltime, fuzzydate))
2865  return (null_value= false);
2866  return (null_value= args[1]->get_date(ltime, fuzzydate));
2867 }
2868 
2869 
2870 bool Item_func_ifnull::time_op(MYSQL_TIME *ltime)
2871 {
2872  DBUG_ASSERT(fixed == 1);
2873  if (!args[0]->get_time(ltime))
2874  return (null_value= false);
2875  return (null_value= args[1]->get_time(ltime));
2876 }
2877 
2878 
2879 String *
2881 {
2882  DBUG_ASSERT(fixed == 1);
2883  String *res =args[0]->val_str(str);
2884  if (!args[0]->null_value)
2885  {
2886  null_value=0;
2887  res->set_charset(collation.collation);
2888  return res;
2889  }
2890  res=args[1]->val_str(str);
2891  if ((null_value=args[1]->null_value))
2892  return 0;
2893  res->set_charset(collation.collation);
2894  return res;
2895 }
2896 
2897 
2924 bool
2926 {
2927  DBUG_ASSERT(fixed == 0);
2928  args[0]->top_level_item();
2929 
2930  if (Item_func::fix_fields(thd, ref))
2931  return 1;
2932 
2933  not_null_tables_cache= (args[1]->not_null_tables() &
2934  args[2]->not_null_tables());
2935 
2936  return 0;
2937 }
2938 
2939 
2940 void Item_func_if::cache_type_info(Item *source)
2941 {
2942  collation.set(source->collation);
2943  cached_field_type= source->field_type();
2944  cached_result_type= source->result_type();
2945  decimals= source->decimals;
2946  max_length= source->max_length;
2947  maybe_null= source->maybe_null;
2948  unsigned_flag= source->unsigned_flag;
2949 }
2950 
2951 
2952 void
2953 Item_func_if::fix_length_and_dec()
2954 {
2955  // Let IF(cond, expr, NULL) and IF(cond, NULL, expr) inherit type from expr.
2956  if (args[1]->type() == NULL_ITEM)
2957  {
2958  cache_type_info(args[2]);
2959  maybe_null= true;
2960  // If both arguments are NULL, make resulting type BINARY(0).
2961  if (args[2]->type() == NULL_ITEM)
2962  cached_field_type= MYSQL_TYPE_STRING;
2963  return;
2964  }
2965  if (args[2]->type() == NULL_ITEM)
2966  {
2967  cache_type_info(args[1]);
2968  maybe_null= true;
2969  return;
2970  }
2971 
2972  agg_result_type(&cached_result_type, args + 1, 2);
2973  cached_field_type= agg_field_type(args + 1, 2);
2974  maybe_null= args[1]->maybe_null || args[2]->maybe_null;
2975  decimals= max(args[1]->decimals, args[2]->decimals);
2976  unsigned_flag=args[1]->unsigned_flag && args[2]->unsigned_flag;
2977 
2978  if (cached_result_type == STRING_RESULT)
2979  {
2980  if (count_string_result_length(cached_field_type, args + 1, 2))
2981  return;
2982  }
2983  else
2984  {
2985  collation.set_numeric(); // Number
2986  }
2987 
2988  uint32 char_length;
2989  if ((cached_result_type == DECIMAL_RESULT )
2990  || (cached_result_type == INT_RESULT))
2991  {
2992  int len1= args[1]->max_length - args[1]->decimals
2993  - (args[1]->unsigned_flag ? 0 : 1);
2994 
2995  int len2= args[2]->max_length - args[2]->decimals
2996  - (args[2]->unsigned_flag ? 0 : 1);
2997 
2998  char_length= max(len1, len2) + decimals + (unsigned_flag ? 0 : 1);
2999  }
3000  else
3001  char_length= max(args[1]->max_char_length(), args[2]->max_char_length());
3002  fix_char_length(char_length);
3003 }
3004 
3005 
3006 uint Item_func_if::decimal_precision() const
3007 {
3008  int arg1_prec= args[1]->decimal_int_part();
3009  int arg2_prec= args[2]->decimal_int_part();
3010  int precision=max(arg1_prec,arg2_prec) + decimals;
3011  return min<uint>(precision, DECIMAL_MAX_PRECISION);
3012 }
3013 
3014 
3015 double
3016 Item_func_if::val_real()
3017 {
3018  DBUG_ASSERT(fixed == 1);
3019  Item *arg= args[0]->val_bool() ? args[1] : args[2];
3020  double value= arg->val_real();
3021  null_value=arg->null_value;
3022  return value;
3023 }
3024 
3025 longlong
3026 Item_func_if::val_int()
3027 {
3028  DBUG_ASSERT(fixed == 1);
3029  Item *arg= args[0]->val_bool() ? args[1] : args[2];
3030  longlong value=arg->val_int();
3031  null_value=arg->null_value;
3032  return value;
3033 }
3034 
3035 String *
3036 Item_func_if::val_str(String *str)
3037 {
3038  DBUG_ASSERT(fixed == 1);
3039 
3040  switch (field_type())
3041  {
3042  case MYSQL_TYPE_DATETIME:
3043  case MYSQL_TYPE_TIMESTAMP:
3044  return val_string_from_datetime(str);
3045  case MYSQL_TYPE_DATE:
3046  return val_string_from_date(str);
3047  case MYSQL_TYPE_TIME:
3048  return val_string_from_time(str);
3049  default:
3050  {
3051  Item *item= args[0]->val_bool() ? args[1] : args[2];
3052  String *res;
3053  if ((res= item->val_str(str)))
3054  {
3055  res->set_charset(collation.collation);
3056  null_value= 0;
3057  return res;
3058  }
3059  }
3060  }
3061  null_value= true;
3062  return (String *) 0;
3063 }
3064 
3065 
3066 my_decimal *
3067 Item_func_if::val_decimal(my_decimal *decimal_value)
3068 {
3069  DBUG_ASSERT(fixed == 1);
3070  Item *arg= args[0]->val_bool() ? args[1] : args[2];
3071  my_decimal *value= arg->val_decimal(decimal_value);
3072  null_value= arg->null_value;
3073  return value;
3074 }
3075 
3076 
3077 bool Item_func_if::get_date(MYSQL_TIME *ltime, uint fuzzydate)
3078 {
3079  DBUG_ASSERT(fixed == 1);
3080  Item *arg= args[0]->val_bool() ? args[1] : args[2];
3081  return (null_value= arg->get_date(ltime, fuzzydate));
3082 }
3083 
3084 
3085 bool Item_func_if::get_time(MYSQL_TIME *ltime)
3086 {
3087  DBUG_ASSERT(fixed == 1);
3088  Item *arg= args[0]->val_bool() ? args[1] : args[2];
3089  return (null_value= arg->get_time(ltime));
3090 }
3091 
3092 
3093 void
3094 Item_func_nullif::fix_length_and_dec()
3095 {
3096  Item_bool_func2::fix_length_and_dec();
3097  maybe_null=1;
3098  if (args[0]) // Only false if EOM
3099  {
3100  max_length=args[0]->max_length;
3101  decimals=args[0]->decimals;
3102  unsigned_flag= args[0]->unsigned_flag;
3103  cached_result_type= args[0]->result_type();
3104  if (cached_result_type == STRING_RESULT &&
3105  agg_arg_charsets_for_comparison(collation, args, arg_count))
3106  return;
3107  }
3108 }
3109 
3110 
3121 double
3123 {
3124  DBUG_ASSERT(fixed == 1);
3125  double value;
3126  if (!cmp.compare())
3127  {
3128  null_value=1;
3129  return 0.0;
3130  }
3131  value= args[0]->val_real();
3132  null_value=args[0]->null_value;
3133  return value;
3134 }
3135 
3136 longlong
3137 Item_func_nullif::val_int()
3138 {
3139  DBUG_ASSERT(fixed == 1);
3140  longlong value;
3141  if (!cmp.compare())
3142  {
3143  null_value=1;
3144  return 0;
3145  }
3146  value=args[0]->val_int();
3147  null_value=args[0]->null_value;
3148  return value;
3149 }
3150 
3151 String *
3152 Item_func_nullif::val_str(String *str)
3153 {
3154  DBUG_ASSERT(fixed == 1);
3155  String *res;
3156  if (!cmp.compare())
3157  {
3158  null_value=1;
3159  return 0;
3160  }
3161  res=args[0]->val_str(str);
3162  null_value=args[0]->null_value;
3163  return res;
3164 }
3165 
3166 
3167 my_decimal *
3168 Item_func_nullif::val_decimal(my_decimal * decimal_value)
3169 {
3170  DBUG_ASSERT(fixed == 1);
3171  my_decimal *res;
3172  if (!cmp.compare())
3173  {
3174  null_value=1;
3175  return 0;
3176  }
3177  res= args[0]->val_decimal(decimal_value);
3178  null_value= args[0]->null_value;
3179  return res;
3180 }
3181 
3182 
3183 bool
3184 Item_func_nullif::is_null()
3185 {
3186  return (null_value= (!cmp.compare() ? 1 : args[0]->null_value));
3187 }
3188 
3189 
3212 {
3213  uint value_added_map= 0;
3214 
3215  if (first_expr_num == -1)
3216  {
3217  for (uint i=0 ; i < ncases ; i+=2)
3218  {
3219  // No expression between CASE and the first WHEN
3220  if (args[i]->val_bool())
3221  return args[i+1];
3222  continue;
3223  }
3224  }
3225  else
3226  {
3227  /* Compare every WHEN argument with it and return the first match */
3228  for (uint i=0 ; i < ncases ; i+=2)
3229  {
3230  if (args[i]->real_item()->type() == NULL_ITEM)
3231  continue;
3232  cmp_type= item_cmp_type(left_result_type, args[i]->result_type());
3233  DBUG_ASSERT(cmp_type != ROW_RESULT);
3234  DBUG_ASSERT(cmp_items[(uint)cmp_type]);
3235  if (!(value_added_map & (1U << (uint)cmp_type)))
3236  {
3237  cmp_items[(uint)cmp_type]->store_value(args[first_expr_num]);
3238  if ((null_value=args[first_expr_num]->null_value))
3239  return else_expr_num != -1 ? args[else_expr_num] : 0;
3240  value_added_map|= 1U << (uint)cmp_type;
3241  }
3242  if (!cmp_items[(uint)cmp_type]->cmp(args[i]) && !args[i]->null_value)
3243  return args[i + 1];
3244  }
3245  }
3246  // No, WHEN clauses all missed, return ELSE expression
3247  return else_expr_num != -1 ? args[else_expr_num] : 0;
3248 }
3249 
3250 
3251 String *Item_func_case::val_str(String *str)
3252 {
3253  DBUG_ASSERT(fixed == 1);
3254  switch (field_type()) {
3255  case MYSQL_TYPE_DATETIME:
3256  case MYSQL_TYPE_TIMESTAMP:
3257  return val_string_from_datetime(str);
3258  case MYSQL_TYPE_DATE:
3259  return val_string_from_date(str);
3260  case MYSQL_TYPE_TIME:
3261  return val_string_from_time(str);
3262  default:
3263  {
3264  Item *item= find_item(str);
3265  if (item)
3266  {
3267  String *res;
3268  if ((res= item->val_str(str)))
3269  {
3270  res->set_charset(collation.collation);
3271  null_value= 0;
3272  return res;
3273  }
3274  }
3275  }
3276  }
3277  null_value= true;
3278  return (String *) 0;
3279 }
3280 
3281 
3282 longlong Item_func_case::val_int()
3283 {
3284  DBUG_ASSERT(fixed == 1);
3285  char buff[MAX_FIELD_WIDTH];
3286  String dummy_str(buff,sizeof(buff),default_charset());
3287  Item *item=find_item(&dummy_str);
3288  longlong res;
3289 
3290  if (!item)
3291  {
3292  null_value=1;
3293  return 0;
3294  }
3295  res=item->val_int();
3296  null_value=item->null_value;
3297  return res;
3298 }
3299 
3300 double Item_func_case::val_real()
3301 {
3302  DBUG_ASSERT(fixed == 1);
3303  char buff[MAX_FIELD_WIDTH];
3304  String dummy_str(buff,sizeof(buff),default_charset());
3305  Item *item=find_item(&dummy_str);
3306  double res;
3307 
3308  if (!item)
3309  {
3310  null_value=1;
3311  return 0;
3312  }
3313  res= item->val_real();
3314  null_value=item->null_value;
3315  return res;
3316 }
3317 
3318 
3319 my_decimal *Item_func_case::val_decimal(my_decimal *decimal_value)
3320 {
3321  DBUG_ASSERT(fixed == 1);
3322  char buff[MAX_FIELD_WIDTH];
3323  String dummy_str(buff, sizeof(buff), default_charset());
3324  Item *item= find_item(&dummy_str);
3325  my_decimal *res;
3326 
3327  if (!item)
3328  {
3329  null_value=1;
3330  return 0;
3331  }
3332 
3333  res= item->val_decimal(decimal_value);
3334  null_value= item->null_value;
3335  return res;
3336 }
3337 
3338 
3339 bool Item_func_case::get_date(MYSQL_TIME *ltime, uint fuzzydate)
3340 {
3341  DBUG_ASSERT(fixed == 1);
3342  char buff[MAX_FIELD_WIDTH];
3343  String dummy_str(buff, sizeof(buff), default_charset());
3344  Item *item= find_item(&dummy_str);
3345  if (!item)
3346  return (null_value= true);
3347  return (null_value= item->get_date(ltime, fuzzydate));
3348 }
3349 
3350 
3351 bool Item_func_case::get_time(MYSQL_TIME *ltime)
3352 {
3353  DBUG_ASSERT(fixed == 1);
3354  char buff[MAX_FIELD_WIDTH];
3355  String dummy_str(buff, sizeof(buff), default_charset());
3356  Item *item= find_item(&dummy_str);
3357  if (!item)
3358  return (null_value= true);
3359  return (null_value= item->get_time(ltime));
3360 }
3361 
3362 
3363 bool Item_func_case::fix_fields(THD *thd, Item **ref)
3364 {
3365  /*
3366  buff should match stack usage from
3367  Item_func_case::val_int() -> Item_func_case::find_item()
3368  */
3369  uchar buff[MAX_FIELD_WIDTH*2+sizeof(String)*2+sizeof(String*)*2+sizeof(double)*2+sizeof(longlong)*2];
3370  bool res= Item_func::fix_fields(thd, ref);
3371  /*
3372  Call check_stack_overrun after fix_fields to be sure that stack variable
3373  is not optimized away
3374  */
3375  if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
3376  return TRUE; // Fatal error flag is set!
3377  return res;
3378 }
3379 
3380 
3381 void Item_func_case::agg_num_lengths(Item *arg)
3382 {
3383  uint len= my_decimal_length_to_precision(arg->max_length, arg->decimals,
3384  arg->unsigned_flag) - arg->decimals;
3385  set_if_bigger(max_length, len);
3386  set_if_bigger(decimals, arg->decimals);
3387  unsigned_flag= unsigned_flag && arg->unsigned_flag;
3388 }
3389 
3390 
3402 static void change_item_tree_if_needed(THD *thd,
3403  Item **place,
3404  Item *new_value)
3405 {
3406  if (*place == new_value)
3407  return;
3408 
3409  thd->change_item_tree(place, new_value);
3410 }
3411 
3412 
3413 void Item_func_case::fix_length_and_dec()
3414 {
3415  Item **agg;
3416  uint nagg;
3417  uint found_types= 0;
3418  THD *thd= current_thd;
3419 
3420  if (!(agg= (Item**) sql_alloc(sizeof(Item*)*(ncases+1))))
3421  return;
3422 
3423  /*
3424  fix_fields() does not handle ELSE expression automatically,
3425  as it's not in the args[] list. Check its maybe_null value.
3426  */
3427  if (else_expr_num == -1 || args[else_expr_num]->maybe_null)
3428  maybe_null=1;
3429 
3430  /*
3431  Aggregate all THEN and ELSE expression types
3432  and collations when string result
3433  */
3434 
3435  for (nagg= 0; nagg < ncases / 2; nagg++)
3436  agg[nagg]= args[nagg * 2 + 1];
3437 
3438  if (else_expr_num != -1)
3439  agg[nagg++]= args[else_expr_num];
3440 
3441  cached_field_type= agg_field_type(agg, nagg);
3442  agg_result_type(&cached_result_type, agg, nagg);
3443  if (cached_result_type == STRING_RESULT)
3444  {
3445  /* Note: String result type is the same for CASE and COALESCE. */
3446  if (count_string_result_length(cached_field_type, agg, nagg))
3447  return;
3448  /*
3449  Copy all THEN and ELSE items back to args[] array.
3450  Some of the items might have been changed to Item_func_conv_charset.
3451  */
3452  for (nagg= 0 ; nagg < ncases / 2 ; nagg++)
3453  change_item_tree_if_needed(thd, &args[nagg * 2 + 1], agg[nagg]);
3454 
3455  if (else_expr_num != -1)
3456  change_item_tree_if_needed(thd, &args[else_expr_num], agg[nagg++]);
3457  }
3458  else
3459  {
3460  /*
3461  TODO: Perhaps CASE and COALESCE should eventually
3462  share fix_length_and_dec() code for numeric result types.
3463  COALESCE is a CASE abbreviation according to the standard,
3464  so there is little sense to have separate fix_length_and_dec()
3465  implementations for numeric result types and thus potentually
3466  different behaviour.
3467  */
3468  collation.set_numeric();
3469  max_length= 0;
3470  decimals= 0;
3471  unsigned_flag= TRUE;
3472  for (uint i= 0; i < nagg; i++)
3473  agg_num_lengths(agg[i]);
3474  max_length= my_decimal_precision_to_length_no_truncation(max_length +
3475  decimals, decimals,
3476  unsigned_flag);
3477  }
3478 
3479 
3480  /*
3481  Aggregate first expression and all WHEN expression types
3482  and collations when string comparison
3483  */
3484  if (first_expr_num != -1)
3485  {
3486  uint i;
3487  agg[0]= args[first_expr_num];
3488  left_result_type= agg[0]->result_type();
3489 
3490  /*
3491  As the first expression and WHEN expressions
3492  are intermixed in args[] array THEN and ELSE items,
3493  extract the first expression and all WHEN expressions into
3494  a temporary array, to process them easier.
3495  */
3496  for (nagg= 0; nagg < ncases/2 ; nagg++)
3497  agg[nagg+1]= args[nagg*2];
3498  nagg++;
3499  if (!(found_types= collect_cmp_types(agg, nagg)))
3500  return;
3501  if (found_types & (1U << STRING_RESULT))
3502  {
3503  /*
3504  If we'll do string comparison, we also need to aggregate
3505  character set and collation for first/WHEN items and
3506  install converters for some of them to cmp_collation when necessary.
3507  This is done because cmp_item compatators cannot compare
3508  strings in two different character sets.
3509  Some examples when we install converters:
3510 
3511  1. Converter installed for the first expression:
3512 
3513  CASE latin1_item WHEN utf16_item THEN ... END
3514 
3515  is replaced to:
3516 
3517  CASE CONVERT(latin1_item USING utf16) WHEN utf16_item THEN ... END
3518 
3519  2. Converter installed for the left WHEN item:
3520 
3521  CASE utf16_item WHEN latin1_item THEN ... END
3522 
3523  is replaced to:
3524 
3525  CASE utf16_item WHEN CONVERT(latin1_item USING utf16) THEN ... END
3526  */
3527  if (agg_arg_charsets_for_comparison(cmp_collation, agg, nagg))
3528  return;
3529  /*
3530  Now copy first expression and all WHEN expressions back to args[]
3531  arrray, because some of the items might have been changed to converters
3532  (e.g. Item_func_conv_charset, or Item_string for constants).
3533  */
3534  change_item_tree_if_needed(thd, &args[first_expr_num], agg[0]);
3535 
3536  for (nagg= 0; nagg < ncases / 2; nagg++)
3537  change_item_tree_if_needed(thd, &args[nagg * 2], agg[nagg + 1]);
3538  }
3539  for (i= 0; i <= (uint)DECIMAL_RESULT; i++)
3540  {
3541  if (found_types & (1U << i) && !cmp_items[i])
3542  {
3543  DBUG_ASSERT((Item_result)i != ROW_RESULT);
3544  if (!(cmp_items[i]=
3545  cmp_item::get_comparator((Item_result)i,
3546  cmp_collation.collation)))
3547  return;
3548  }
3549  }
3550  /*
3551  Set cmp_context of all WHEN arguments. This prevents
3552  Item_field::equal_fields_propagator() from transforming a
3553  zerofill argument into a string constant. Such a change would
3554  require rebuilding cmp_items.
3555  */
3556  for (i= 0; i < ncases; i+= 2)
3557  args[i]->cmp_context= item_cmp_type(left_result_type,
3558  args[i]->result_type());
3559  }
3560 
3561 }
3562 
3563 
3564 uint Item_func_case::decimal_precision() const
3565 {
3566  int max_int_part=0;
3567  for (uint i=0 ; i < ncases ; i+=2)
3568  set_if_bigger(max_int_part, args[i+1]->decimal_int_part());
3569 
3570  if (else_expr_num != -1)
3571  set_if_bigger(max_int_part, args[else_expr_num]->decimal_int_part());
3572  return min<uint>(max_int_part + decimals, DECIMAL_MAX_PRECISION);
3573 }
3574 
3575 
3581 void Item_func_case::print(String *str, enum_query_type query_type)
3582 {
3583  str->append(STRING_WITH_LEN("(case "));
3584  if (first_expr_num != -1)
3585  {
3586  args[first_expr_num]->print(str, query_type);
3587  str->append(' ');
3588  }
3589  for (uint i=0 ; i < ncases ; i+=2)
3590  {
3591  str->append(STRING_WITH_LEN("when "));
3592  args[i]->print(str, query_type);
3593  str->append(STRING_WITH_LEN(" then "));
3594  args[i+1]->print(str, query_type);
3595  str->append(' ');
3596  }
3597  if (else_expr_num != -1)
3598  {
3599  str->append(STRING_WITH_LEN("else "));
3600  args[else_expr_num]->print(str, query_type);
3601  str->append(' ');
3602  }
3603  str->append(STRING_WITH_LEN("end)"));
3604 }
3605 
3606 
3607 void Item_func_case::cleanup()
3608 {
3609  uint i;
3610  DBUG_ENTER("Item_func_case::cleanup");
3611  Item_func::cleanup();
3612  for (i= 0; i <= (uint)DECIMAL_RESULT; i++)
3613  {
3614  delete cmp_items[i];
3615  cmp_items[i]= 0;
3616  }
3617  DBUG_VOID_RETURN;
3618 }
3619 
3620 
3626 {
3627  DBUG_ASSERT(fixed == 1);
3628  null_value=0;
3629  for (uint i=0 ; i < arg_count ; i++)
3630  {
3631  String *res;
3632  if ((res=args[i]->val_str(str)))
3633  return res;
3634  }
3635  null_value=1;
3636  return 0;
3637 }
3638 
3640 {
3641  DBUG_ASSERT(fixed == 1);
3642  null_value=0;
3643  for (uint i=0 ; i < arg_count ; i++)
3644  {
3645  longlong res=args[i]->val_int();
3646  if (!args[i]->null_value)
3647  return res;
3648  }
3649  null_value=1;
3650  return 0;
3651 }
3652 
3654 {
3655  DBUG_ASSERT(fixed == 1);
3656  null_value=0;
3657  for (uint i=0 ; i < arg_count ; i++)
3658  {
3659  double res= args[i]->val_real();
3660  if (!args[i]->null_value)
3661  return res;
3662  }
3663  null_value=1;
3664  return 0;
3665 }
3666 
3667 
3669 {
3670  DBUG_ASSERT(fixed == 1);
3671  null_value= 0;
3672  for (uint i= 0; i < arg_count; i++)
3673  {
3674  my_decimal *res= args[i]->val_decimal(decimal_value);
3675  if (!args[i]->null_value)
3676  return res;
3677  }
3678  null_value=1;
3679  return 0;
3680 }
3681 
3682 
3683 
3684 bool Item_func_coalesce::date_op(MYSQL_TIME *ltime, uint fuzzydate)
3685 {
3686  DBUG_ASSERT(fixed == 1);
3687  for (uint i= 0; i < arg_count; i++)
3688  {
3689  if (!args[i]->get_date(ltime, fuzzydate))
3690  return (null_value= false);
3691  }
3692  return (null_value= true);
3693 }
3694 
3695 
3696 bool Item_func_coalesce::time_op(MYSQL_TIME *ltime)
3697 {
3698  DBUG_ASSERT(fixed == 1);
3699  for (uint i= 0; i < arg_count; i++)
3700  {
3701  if (!args[i]->get_time(ltime))
3702  return (null_value= false);
3703  }
3704  return (null_value= true);
3705 }
3706 
3707 
3708 void Item_func_coalesce::fix_length_and_dec()
3709 {
3710  cached_field_type= agg_field_type(args, arg_count);
3711  agg_result_type(&hybrid_type, args, arg_count);
3712  switch (hybrid_type) {
3713  case STRING_RESULT:
3714  if (count_string_result_length(cached_field_type, args, arg_count))
3715  return;
3716  break;
3717  case DECIMAL_RESULT:
3719  break;
3720  case REAL_RESULT:
3722  break;
3723  case INT_RESULT:
3724  count_only_length(args, arg_count);
3725  decimals= 0;
3726  break;
3727  case ROW_RESULT:
3728  default:
3729  DBUG_ASSERT(0);
3730  }
3731 }
3732 
3733 /****************************************************************************
3734  Classes and function for the IN operator
3735 ****************************************************************************/
3736 
3737 /*
3738  Determine which of the signed longlong arguments is bigger
3739 
3740  SYNOPSIS
3741  cmp_longs()
3742  a_val left argument
3743  b_val right argument
3744 
3745  DESCRIPTION
3746  This function will compare two signed longlong arguments
3747  and will return -1, 0, or 1 if left argument is smaller than,
3748  equal to or greater than the right argument.
3749 
3750  RETURN VALUE
3751  -1 left argument is smaller than the right argument.
3752  0 left argument is equal to the right argument.
3753  1 left argument is greater than the right argument.
3754 */
3755 static inline int cmp_longs (longlong a_val, longlong b_val)
3756 {
3757  return a_val < b_val ? -1 : a_val == b_val ? 0 : 1;
3758 }
3759 
3760 
3761 /*
3762  Determine which of the unsigned longlong arguments is bigger
3763 
3764  SYNOPSIS
3765  cmp_ulongs()
3766  a_val left argument
3767  b_val right argument
3768 
3769  DESCRIPTION
3770  This function will compare two unsigned longlong arguments
3771  and will return -1, 0, or 1 if left argument is smaller than,
3772  equal to or greater than the right argument.
3773 
3774  RETURN VALUE
3775  -1 left argument is smaller than the right argument.
3776  0 left argument is equal to the right argument.
3777  1 left argument is greater than the right argument.
3778 */
3779 static inline int cmp_ulongs (ulonglong a_val, ulonglong b_val)
3780 {
3781  return a_val < b_val ? -1 : a_val == b_val ? 0 : 1;
3782 }
3783 
3784 
3785 /*
3786  Compare two integers in IN value list format (packed_longlong)
3787 
3788  SYNOPSIS
3789  cmp_longlong()
3790  cmp_arg an argument passed to the calling function (my_qsort2)
3791  a left argument
3792  b right argument
3793 
3794  DESCRIPTION
3795  This function will compare two integer arguments in the IN value list
3796  format and will return -1, 0, or 1 if left argument is smaller than,
3797  equal to or greater than the right argument.
3798  It's used in sorting the IN values list and finding an element in it.
3799  Depending on the signedness of the arguments cmp_longlong() will
3800  compare them as either signed (using cmp_longs()) or unsigned (using
3801  cmp_ulongs()).
3802 
3803  RETURN VALUE
3804  -1 left argument is smaller than the right argument.
3805  0 left argument is equal to the right argument.
3806  1 left argument is greater than the right argument.
3807 */
3808 int cmp_longlong(void *cmp_arg,
3811 {
3812  if (a->unsigned_flag != b->unsigned_flag)
3813  {
3814  /*
3815  One of the args is unsigned and is too big to fit into the
3816  positive signed range. Report no match.
3817  */
3818  if ((a->unsigned_flag && ((ulonglong) a->val) > (ulonglong) LONGLONG_MAX) ||
3819  (b->unsigned_flag && ((ulonglong) b->val) > (ulonglong) LONGLONG_MAX))
3820  return a->unsigned_flag ? 1 : -1;
3821  /*
3822  Although the signedness differs both args can fit into the signed
3823  positive range. Make them signed and compare as usual.
3824  */
3825  return cmp_longs (a->val, b->val);
3826  }
3827  if (a->unsigned_flag)
3828  return cmp_ulongs ((ulonglong) a->val, (ulonglong) b->val);
3829  else
3830  return cmp_longs (a->val, b->val);
3831 }
3832 
3833 static int cmp_double(void *cmp_arg, double *a,double *b)
3834 {
3835  return *a < *b ? -1 : *a == *b ? 0 : 1;
3836 }
3837 
3838 static int cmp_row(void *cmp_arg, cmp_item_row *a, cmp_item_row *b)
3839 {
3840  return a->compare(b);
3841 }
3842 
3843 
3844 static int cmp_decimal(void *cmp_arg, my_decimal *a, my_decimal *b)
3845 {
3846  /*
3847  We need call of fixing buffer pointer, because fast sort just copy
3848  decimal buffers in memory and pointers left pointing on old buffer place
3849  */
3850  a->fix_buffer_pointer();
3851  b->fix_buffer_pointer();
3852  return my_decimal_cmp(a, b);
3853 }
3854 
3855 
3856 int in_vector::find(Item *item)
3857 {
3858  uchar *result=get_value(item);
3859  if (!result || !used_count)
3860  return 0; // Null value
3861 
3862  uint start,end;
3863  start=0; end=used_count-1;
3864  while (start != end)
3865  {
3866  uint mid=(start+end+1)/2;
3867  int res;
3868  if ((res=(*compare)(collation, base+mid*size, result)) == 0)
3869  return 1;
3870  if (res < 0)
3871  start=mid;
3872  else
3873  end=mid-1;
3874  }
3875  return (int) ((*compare)(collation, base+start*size, result) == 0);
3876 }
3877 
3878 in_string::in_string(uint elements,qsort2_cmp cmp_func,
3879  const CHARSET_INFO *cs)
3880  :in_vector(elements, sizeof(String), cmp_func, cs),
3881  tmp(buff, sizeof(buff), &my_charset_bin)
3882 {}
3883 
3884 in_string::~in_string()
3885 {
3886  if (base)
3887  {
3888  // base was allocated with help of sql_alloc => following is OK
3889  for (uint i=0 ; i < count ; i++)
3890  ((String*) base)[i].free();
3891  }
3892 }
3893 
3894 void in_string::set(uint pos,Item *item)
3895 {
3896  String *str=((String*) base)+pos;
3897  String *res=item->val_str(str);
3898  if (res && res != str)
3899  {
3900  if (res->uses_buffer_owned_by(str))
3901  res->copy();
3902  if (item->type() == Item::FUNC_ITEM)
3903  str->copy(*res);
3904  else
3905  *str= *res;
3906  }
3907  if (!str->charset())
3908  {
3909  const CHARSET_INFO *cs;
3910  if (!(cs= item->collation.collation))
3911  cs= &my_charset_bin; // Should never happen for STR items
3912  str->set_charset(cs);
3913  }
3914 }
3915 
3916 
3917 uchar *in_string::get_value(Item *item)
3918 {
3919  return (uchar*) item->val_str(&tmp);
3920 }
3921 
3922 in_row::in_row(uint elements, Item * item)
3923 {
3924  base= (char*) new cmp_item_row[count= elements];
3925  size= sizeof(cmp_item_row);
3926  compare= (qsort2_cmp) cmp_row;
3927  /*
3928  We need to reset these as otherwise we will call sort() with
3929  uninitialized (even if not used) elements
3930  */
3931  used_count= elements;
3932  collation= 0;
3933 }
3934 
3935 in_row::~in_row()
3936 {
3937  if (base)
3938  delete [] (cmp_item_row*) base;
3939 }
3940 
3941 uchar *in_row::get_value(Item *item)
3942 {
3943  tmp.store_value(item);
3944  if (item->is_null())
3945  return 0;
3946  return (uchar *)&tmp;
3947 }
3948 
3949 void in_row::set(uint pos, Item *item)
3950 {
3951  DBUG_ENTER("in_row::set");
3952  DBUG_PRINT("enter", ("pos: %u item: 0x%lx", pos, (ulong) item));
3953  ((cmp_item_row*) base)[pos].store_value_by_template(&tmp, item);
3954  DBUG_VOID_RETURN;
3955 }
3956 
3957 in_longlong::in_longlong(uint elements)
3958  :in_vector(elements,sizeof(packed_longlong),(qsort2_cmp) cmp_longlong, 0)
3959 {}
3960 
3961 void in_longlong::set(uint pos,Item *item)
3962 {
3963  struct packed_longlong *buff= &((packed_longlong*) base)[pos];
3964 
3965  buff->val= item->val_int();
3966  buff->unsigned_flag= item->unsigned_flag;
3967 }
3968 
3969 uchar *in_longlong::get_value(Item *item)
3970 {
3971  tmp.val= item->val_int();
3972  if (item->null_value)
3973  return 0;
3974  tmp.unsigned_flag= item->unsigned_flag;
3975  return (uchar*) &tmp;
3976 }
3977 
3978 
3979 void in_time_as_longlong::set(uint pos,Item *item)
3980 {
3981  struct packed_longlong *buff= &((packed_longlong*) base)[pos];
3982  buff->val= item->val_time_temporal();
3983  buff->unsigned_flag= item->unsigned_flag;
3984 }
3985 
3986 
3987 uchar *in_time_as_longlong::get_value(Item *item)
3988 {
3989  tmp.val= item->val_time_temporal();
3990  if (item->null_value)
3991  return 0;
3992  tmp.unsigned_flag= item->unsigned_flag;
3993  return (uchar*) &tmp;
3994 }
3995 
3996 
3997 void in_datetime_as_longlong::set(uint pos,Item *item)
3998 {
3999  struct packed_longlong *buff= &((packed_longlong*) base)[pos];
4000  buff->val= item->val_date_temporal();
4001  buff->unsigned_flag= item->unsigned_flag;
4002 }
4003 
4004 
4005 uchar *in_datetime_as_longlong::get_value(Item *item)
4006 {
4007  tmp.val= item->val_date_temporal();
4008  if (item->null_value)
4009  return 0;
4010  tmp.unsigned_flag= item->unsigned_flag;
4011  return (uchar*) &tmp;
4012 }
4013 
4014 
4015 void in_datetime::set(uint pos,Item *item)
4016 {
4017  Item **tmp_item= &item;
4018  bool is_null;
4019  struct packed_longlong *buff= &((packed_longlong*) base)[pos];
4020 
4021  buff->val= get_datetime_value(thd, &tmp_item, 0, warn_item, &is_null);
4022  buff->unsigned_flag= 1L;
4023 }
4024 
4025 
4026 uchar *in_datetime::get_value(Item *item)
4027 {
4028  bool is_null;
4029  Item **tmp_item= lval_cache ? &lval_cache : &item;
4030  tmp.val= get_datetime_value(thd, &tmp_item, &lval_cache, warn_item, &is_null);
4031  if (item->null_value)
4032  return 0;
4033  tmp.unsigned_flag= 1L;
4034  return (uchar*) &tmp;
4035 }
4036 
4037 
4038 in_double::in_double(uint elements)
4039  :in_vector(elements,sizeof(double),(qsort2_cmp) cmp_double, 0)
4040 {}
4041 
4042 void in_double::set(uint pos,Item *item)
4043 {
4044  ((double*) base)[pos]= item->val_real();
4045 }
4046 
4047 uchar *in_double::get_value(Item *item)
4048 {
4049  tmp= item->val_real();
4050  if (item->null_value)
4051  return 0; /* purecov: inspected */
4052  return (uchar*) &tmp;
4053 }
4054 
4055 
4056 in_decimal::in_decimal(uint elements)
4057  :in_vector(elements, sizeof(my_decimal),(qsort2_cmp) cmp_decimal, 0)
4058 {}
4059 
4060 
4061 void in_decimal::set(uint pos, Item *item)
4062 {
4063  /* as far as 'item' is constant, we can store reference on my_decimal */
4064  my_decimal *dec= ((my_decimal *)base) + pos;
4065  dec->len= DECIMAL_BUFF_LENGTH;
4066  dec->fix_buffer_pointer();
4067  my_decimal *res= item->val_decimal(dec);
4068  /* if item->val_decimal() is evaluated to NULL then res == 0 */
4069  if (!item->null_value && res != dec)
4070  my_decimal2decimal(res, dec);
4071 }
4072 
4073 
4074 uchar *in_decimal::get_value(Item *item)
4075 {
4076  my_decimal *result= item->val_decimal(&val);
4077  if (item->null_value)
4078  return 0;
4079  return (uchar *)result;
4080 }
4081 
4082 
4083 cmp_item* cmp_item::get_comparator(Item_result type,
4084  const CHARSET_INFO *cs)
4085 {
4086  switch (type) {
4087  case STRING_RESULT:
4088  return new cmp_item_sort_string(cs);
4089  case INT_RESULT:
4090  return new cmp_item_int;
4091  case REAL_RESULT:
4092  return new cmp_item_real;
4093  case ROW_RESULT:
4094  return new cmp_item_row;
4095  case DECIMAL_RESULT:
4096  return new cmp_item_decimal;
4097  default:
4098  DBUG_ASSERT(0);
4099  break;
4100  }
4101  return 0; // to satisfy compiler :)
4102 }
4103 
4104 
4105 cmp_item* cmp_item_sort_string::make_same()
4106 {
4107  return new cmp_item_sort_string_in_static(cmp_charset);
4108 }
4109 
4110 cmp_item* cmp_item_int::make_same()
4111 {
4112  return new cmp_item_int();
4113 }
4114 
4115 cmp_item* cmp_item_real::make_same()
4116 {
4117  return new cmp_item_real();
4118 }
4119 
4120 cmp_item* cmp_item_row::make_same()
4121 {
4122  return new cmp_item_row();
4123 }
4124 
4125 
4126 cmp_item_row::~cmp_item_row()
4127 {
4128  DBUG_ENTER("~cmp_item_row");
4129  DBUG_PRINT("enter",("this: 0x%lx", (long) this));
4130  if (comparators)
4131  {
4132  for (uint i= 0; i < n; i++)
4133  {
4134  if (comparators[i])
4135  delete comparators[i];
4136  }
4137  }
4138  DBUG_VOID_RETURN;
4139 }
4140 
4141 
4142 void cmp_item_row::alloc_comparators()
4143 {
4144  if (!comparators)
4145  comparators= (cmp_item **) current_thd->calloc(sizeof(cmp_item *)*n);
4146 }
4147 
4148 
4149 void cmp_item_row::store_value(Item *item)
4150 {
4151  DBUG_ENTER("cmp_item_row::store_value");
4152  n= item->cols();
4153  alloc_comparators();
4154  if (comparators)
4155  {
4156  item->bring_value();
4157  item->null_value= 0;
4158  for (uint i=0; i < n; i++)
4159  {
4160  if (!comparators[i])
4161  if (!(comparators[i]=
4162  cmp_item::get_comparator(item->element_index(i)->result_type(),
4163  item->element_index(i)->collation.collation)))
4164  break; // new failed
4165  comparators[i]->store_value(item->element_index(i));
4166  item->null_value|= item->element_index(i)->null_value;
4167  }
4168  }
4169  DBUG_VOID_RETURN;
4170 }
4171 
4172 
4173 void cmp_item_row::store_value_by_template(cmp_item *t, Item *item)
4174 {
4175  cmp_item_row *tmpl= (cmp_item_row*) t;
4176  if (tmpl->n != item->cols())
4177  {
4178  my_error(ER_OPERAND_COLUMNS, MYF(0), tmpl->n);
4179  return;
4180  }
4181  n= tmpl->n;
4182  if ((comparators= (cmp_item **) sql_alloc(sizeof(cmp_item *)*n)))
4183  {
4184  item->bring_value();
4185  item->null_value= 0;
4186  for (uint i=0; i < n; i++)
4187  {
4188  if (!(comparators[i]= tmpl->comparators[i]->make_same()))
4189  break; // new failed
4190  comparators[i]->store_value_by_template(tmpl->comparators[i],
4191  item->element_index(i));
4192  item->null_value|= item->element_index(i)->null_value;
4193  }
4194  }
4195 }
4196 
4197 
4198 int cmp_item_row::cmp(Item *arg)
4199 {
4200  arg->null_value= 0;
4201  if (arg->cols() != n)
4202  {
4203  my_error(ER_OPERAND_COLUMNS, MYF(0), n);
4204  return 1;
4205  }
4206  bool was_null= 0;
4207  arg->bring_value();
4208  for (uint i=0; i < n; i++)
4209  {
4210  if (comparators[i]->cmp(arg->element_index(i)))
4211  {
4212  if (!arg->element_index(i)->null_value)
4213  return 1;
4214  was_null= 1;
4215  }
4216  }
4217  return (arg->null_value= was_null);
4218 }
4219 
4220 
4222 {
4223  cmp_item_row *l_cmp= (cmp_item_row *) c;
4224  for (uint i=0; i < n; i++)
4225  {
4226  int res;
4227  if ((res= comparators[i]->compare(l_cmp->comparators[i])))
4228  return res;
4229  }
4230  return 0;
4231 }
4232 
4233 
4234 void cmp_item_decimal::store_value(Item *item)
4235 {
4236  my_decimal *val= item->val_decimal(&value);
4237  /* val may be zero if item is nnull */
4238  if (val && val != &value)
4239  my_decimal2decimal(val, &value);
4240 }
4241 
4242 
4243 int cmp_item_decimal::cmp(Item *arg)
4244 {
4245  my_decimal tmp_buf, *tmp= arg->val_decimal(&tmp_buf);
4246  if (arg->null_value)
4247  return 1;
4248  return my_decimal_cmp(&value, tmp);
4249 }
4250 
4251 
4253 {
4254  cmp_item_decimal *l_cmp= (cmp_item_decimal*) arg;
4255  return my_decimal_cmp(&value, &l_cmp->value);
4256 }
4257 
4258 
4259 cmp_item* cmp_item_decimal::make_same()
4260 {
4261  return new cmp_item_decimal();
4262 }
4263 
4264 
4265 void cmp_item_datetime::store_value(Item *item)
4266 {
4267  bool is_null;
4268  Item **tmp_item= lval_cache ? &lval_cache : &item;
4269  value= get_datetime_value(thd, &tmp_item, &lval_cache, warn_item, &is_null);
4270 }
4271 
4272 
4273 int cmp_item_datetime::cmp(Item *arg)
4274 {
4275  bool is_null;
4276  Item **tmp_item= &arg;
4277  return value !=
4278  get_datetime_value(thd, &tmp_item, 0, warn_item, &is_null);
4279 }
4280 
4281 
4283 {
4284  cmp_item_datetime *l_cmp= (cmp_item_datetime *)ci;
4285  return (value < l_cmp->value) ? -1 : ((value == l_cmp->value) ? 0 : 1);
4286 }
4287 
4288 
4289 cmp_item *cmp_item_datetime::make_same()
4290 {
4291  return new cmp_item_datetime(warn_item);
4292 }
4293 
4294 
4295 bool Item_func_in::nulls_in_row()
4296 {
4297  Item **arg,**arg_end;
4298  for (arg= args+1, arg_end= args+arg_count; arg != arg_end ; arg++)
4299  {
4300  if ((*arg)->null_inside())
4301  return 1;
4302  }
4303  return 0;
4304 }
4305 
4306 
4335 bool
4337 {
4338  Item **arg, **arg_end;
4339 
4340  if (Item_func_opt_neg::fix_fields(thd, ref))
4341  return 1;
4342 
4343  /* not_null_tables_cache == union(T1(e),union(T1(ei))) */
4344  if (pred_level && negated)
4345  return 0;
4346 
4347  /* not_null_tables_cache = union(T1(e),intersection(T1(ei))) */
4348  not_null_tables_cache= ~(table_map) 0;
4349  for (arg= args + 1, arg_end= args + arg_count; arg != arg_end; arg++)
4350  not_null_tables_cache&= (*arg)->not_null_tables();
4351  not_null_tables_cache|= (*args)->not_null_tables();
4352  return 0;
4353 }
4354 
4355 
4356 static int srtcmp_in(CHARSET_INFO *cs, const String *x,const String *y)
4357 {
4358  return cs->coll->strnncollsp(cs,
4359  (uchar *) x->ptr(),x->length(),
4360  (uchar *) y->ptr(),y->length(), 0);
4361 }
4362 
4363 
4364 void Item_func_in::fix_length_and_dec()
4365 {
4366  Item **arg, **arg_end;
4367  bool const_itm= 1;
4368  THD *thd= current_thd;
4369  bool datetime_found= FALSE;
4370  /* TRUE <=> arguments values will be compared as DATETIMEs. */
4371  bool compare_as_datetime= FALSE;
4372  Item *date_arg= 0;
4373  uint found_types= 0;
4374  uint type_cnt= 0, i;
4375  Item_result cmp_type= STRING_RESULT;
4376  left_result_type= args[0]->result_type();
4377  if (!(found_types= collect_cmp_types(args, arg_count, true)))
4378  return;
4379 
4380  for (arg= args + 1, arg_end= args + arg_count; arg != arg_end ; arg++)
4381  {
4382  if (!arg[0]->const_item())
4383  {
4384  const_itm= 0;
4385  break;
4386  }
4387  }
4388  for (i= 0; i <= (uint)DECIMAL_RESULT; i++)
4389  {
4390  if (found_types & (1U << i))
4391  {
4392  (type_cnt)++;
4393  cmp_type= (Item_result) i;
4394  }
4395  }
4396 
4397  if (type_cnt == 1)
4398  {
4399  if (cmp_type == STRING_RESULT &&
4400  agg_arg_charsets_for_comparison(cmp_collation, args, arg_count))
4401  return;
4402  arg_types_compatible= TRUE;
4403  }
4404  if (type_cnt == 1)
4405  {
4406  /*
4407  When comparing rows create the row comparator object beforehand to ease
4408  the DATETIME comparison detection procedure.
4409  */
4410  if (cmp_type == ROW_RESULT)
4411  {
4412  cmp_item_row *cmp= 0;
4413  if (const_itm && !nulls_in_row())
4414  {
4415  array= new in_row(arg_count-1, 0);
4416  cmp= &((in_row*)array)->tmp;
4417  }
4418  else
4419  {
4420  if (!(cmp= new cmp_item_row))
4421  return;
4422  cmp_items[ROW_RESULT]= cmp;
4423  }
4424  cmp->n= args[0]->cols();
4425  cmp->alloc_comparators();
4426  }
4427  /* All DATE/DATETIME fields/functions has the STRING result type. */
4428  if (cmp_type == STRING_RESULT || cmp_type == ROW_RESULT)
4429  {
4430  uint col, cols= args[0]->cols();
4431 
4432  for (col= 0; col < cols; col++)
4433  {
4434  bool skip_column= FALSE;
4435  /*
4436  Check that all items to be compared has the STRING result type and at
4437  least one of them is a DATE/DATETIME item.
4438  */
4439  for (arg= args, arg_end= args + arg_count; arg != arg_end ; arg++)
4440  {
4441  Item *itm= ((cmp_type == STRING_RESULT) ? arg[0] :
4442  arg[0]->element_index(col));
4443  if (itm->result_type() != STRING_RESULT)
4444  {
4445  skip_column= TRUE;
4446  break;
4447  }
4448  else if (itm->is_temporal_with_date())
4449  {
4450  datetime_found= TRUE;
4451  /*
4452  Internally all DATE/DATETIME values are converted to the DATETIME
4453  type. So try to find a DATETIME item to issue correct warnings.
4454  */
4455  if (!date_arg)
4456  date_arg= itm;
4457  else if (itm->field_type() == MYSQL_TYPE_DATETIME)
4458  {
4459  date_arg= itm;
4460  /* All arguments are already checked to have the STRING result. */
4461  if (cmp_type == STRING_RESULT)
4462  break;
4463  }
4464  }
4465  }
4466  if (skip_column)
4467  continue;
4468  if (datetime_found)
4469  {
4470  if (cmp_type == ROW_RESULT)
4471  {
4472  cmp_item **cmp= 0;
4473  if (array)
4474  cmp= ((in_row*)array)->tmp.comparators + col;
4475  else
4476  cmp= ((cmp_item_row*)cmp_items[ROW_RESULT])->comparators + col;
4477  *cmp= new cmp_item_datetime(date_arg);
4478  /* Reset variables for the next column. */
4479  date_arg= 0;
4480  datetime_found= FALSE;
4481  }
4482  else
4483  compare_as_datetime= TRUE;
4484  }
4485  }
4486  }
4487  }
4488  /*
4489  Row item with NULLs inside can return NULL or FALSE =>
4490  they can't be processed as static
4491  */
4492  if (type_cnt == 1 && const_itm && !nulls_in_row())
4493  {
4494  if (compare_as_datetime)
4495  array= new in_datetime(date_arg, arg_count - 1);
4496  else
4497  {
4498  /*
4499  IN must compare INT columns and constants as int values (the same
4500  way as equality does).
4501  So we must check here if the column on the left and all the constant
4502  values on the right can be compared as integers and adjust the
4503  comparison type accordingly.
4504  */
4505  bool datetime_as_longlong= false;
4506  if (args[0]->real_item()->type() == FIELD_ITEM &&
4507  thd->lex->sql_command != SQLCOM_CREATE_VIEW &&
4508  thd->lex->sql_command != SQLCOM_SHOW_CREATE &&
4509  cmp_type != INT_RESULT)
4510  {
4511  Item_field *field_item= (Item_field*) (args[0]->real_item());
4512  if (field_item->field->can_be_compared_as_longlong())
4513  {
4514  bool all_converted= true;
4515  for (arg=args + 1, arg_end= args + arg_count; arg != arg_end ; arg++)
4516  {
4517  if (!convert_constant_item (thd, field_item, &arg[0]))
4518  all_converted= false;
4519  }
4520  if (all_converted)
4521  {
4522  cmp_type= INT_RESULT;
4523  datetime_as_longlong= field_item->is_temporal();
4524  }
4525  }
4526  }
4527  switch (cmp_type) {
4528  case STRING_RESULT:
4529  array=new in_string(arg_count-1,(qsort2_cmp) srtcmp_in,
4530  cmp_collation.collation);
4531  break;
4532  case INT_RESULT:
4533  array= datetime_as_longlong ?
4534  args[0]->field_type() == MYSQL_TYPE_TIME ?
4535  (in_vector*) new in_time_as_longlong(arg_count - 1) :
4536  (in_vector*) new in_datetime_as_longlong(arg_count - 1) :
4537  (in_vector*) new in_longlong(arg_count - 1);
4538  break;
4539  case REAL_RESULT:
4540  array= new in_double(arg_count-1);
4541  break;
4542  case ROW_RESULT:
4543  /*
4544  The row comparator was created at the beginning but only DATETIME
4545  items comparators were initialized. Call store_value() to setup
4546  others.
4547  */
4548  ((in_row*)array)->tmp.store_value(args[0]);
4549  break;
4550  case DECIMAL_RESULT:
4551  array= new in_decimal(arg_count - 1);
4552  break;
4553  default:
4554  DBUG_ASSERT(0);
4555  return;
4556  }
4557  }
4558  if (array && !(thd->is_fatal_error)) // If not EOM
4559  {
4560  uint j=0;
4561  for (uint i=1 ; i < arg_count ; i++)
4562  {
4563  array->set(j,args[i]);
4564  if (!args[i]->null_value) // Skip NULL values
4565  j++;
4566  else
4567  have_null= 1;
4568  }
4569  if ((array->used_count= j))
4570  array->sort();
4571  }
4572  }
4573  else
4574  {
4575  if (compare_as_datetime)
4576  cmp_items[STRING_RESULT]= new cmp_item_datetime(date_arg);
4577  else
4578  {
4579  for (i= 0; i <= (uint) DECIMAL_RESULT; i++)
4580  {
4581  if (found_types & (1U << i) && !cmp_items[i])
4582  {
4583  if ((Item_result)i == STRING_RESULT &&
4584  agg_arg_charsets_for_comparison(cmp_collation, args, arg_count))
4585  return;
4586  if (!cmp_items[i] && !(cmp_items[i]=
4587  cmp_item::get_comparator((Item_result)i,
4588  cmp_collation.collation)))
4589  return;
4590  }
4591  }
4592  }
4593  }
4594  /*
4595  Set cmp_context of all arguments. This prevents
4596  Item_field::equal_fields_propagator() from transforming a zerofill integer
4597  argument into a string constant. Such a change would require rebuilding
4598  cmp_itmes.
4599  */
4600  for (arg= args + 1, arg_end= args + arg_count; arg != arg_end ; arg++)
4601  {
4602  arg[0]->cmp_context= item_cmp_type(left_result_type, arg[0]->result_type());
4603  }
4604  max_length= 1;
4605 }
4606 
4607 
4608 void Item_func_in::print(String *str, enum_query_type query_type)
4609 {
4610  str->append('(');
4611  args[0]->print(str, query_type);
4612  if (negated)
4613  str->append(STRING_WITH_LEN(" not"));
4614  str->append(STRING_WITH_LEN(" in ("));
4615  print_args(str, 1, query_type);
4616  str->append(STRING_WITH_LEN("))"));
4617 }
4618 
4619 
4620 /*
4621  Evaluate the function and return its value.
4622 
4623  SYNOPSIS
4624  val_int()
4625 
4626  DESCRIPTION
4627  Evaluate the function and return its value.
4628 
4629  IMPLEMENTATION
4630  If the array object is defined then the value of the function is
4631  calculated by means of this array.
4632  Otherwise several cmp_item objects are used in order to do correct
4633  comparison of left expression and an expression from the values list.
4634  One cmp_item object correspond to one used comparison type. Left
4635  expression can be evaluated up to number of different used comparison
4636  types. A bit mapped variable value_added_map is used to check whether
4637  the left expression already was evaluated for a particular result type.
4638  Result types are mapped to it according to their integer values i.e.
4639  STRING_RESULT is mapped to bit 0, REAL_RESULT to bit 1, so on.
4640 
4641  RETURN
4642  Value of the function
4643 */
4644 
4645 longlong Item_func_in::val_int()
4646 {
4647  cmp_item *in_item;
4648  DBUG_ASSERT(fixed == 1);
4649  uint value_added_map= 0;
4650  if (array)
4651  {
4652  int tmp=array->find(args[0]);
4653  null_value=args[0]->null_value || (!tmp && have_null);
4654  return (longlong) (!null_value && tmp != negated);
4655  }
4656 
4657  if ((null_value= args[0]->real_item()->type() == NULL_ITEM))
4658  return 0;
4659 
4660  have_null= 0;
4661  for (uint i= 1 ; i < arg_count ; i++)
4662  {
4663  if (args[i]->real_item()->type() == NULL_ITEM)
4664  {
4665  have_null= TRUE;
4666  continue;
4667  }
4668  Item_result cmp_type= item_cmp_type(left_result_type, args[i]->result_type());
4669  in_item= cmp_items[(uint)cmp_type];
4670  DBUG_ASSERT(in_item);
4671  if (!(value_added_map & (1U << (uint)cmp_type)))
4672  {
4673  in_item->store_value(args[0]);
4674  if ((null_value= args[0]->null_value))
4675  return 0;
4676  value_added_map|= 1U << (uint)cmp_type;
4677  }
4678  if (!in_item->cmp(args[i]) && !args[i]->null_value)
4679  return (longlong) (!negated);
4680  have_null|= args[i]->null_value;
4681  }
4682 
4683  null_value= have_null;
4684  return (longlong) (!null_value && negated);
4685 }
4686 
4687 
4688 longlong Item_func_bit_or::val_int()
4689 {
4690  DBUG_ASSERT(fixed == 1);
4691  ulonglong arg1= (ulonglong) args[0]->val_int();
4692  if (args[0]->null_value)
4693  {
4694  null_value=1; /* purecov: inspected */
4695  return 0; /* purecov: inspected */
4696  }
4697  ulonglong arg2= (ulonglong) args[1]->val_int();
4698  if (args[1]->null_value)
4699  {
4700  null_value=1;
4701  return 0;
4702  }
4703  null_value=0;
4704  return (longlong) (arg1 | arg2);
4705 }
4706 
4707 
4708 longlong Item_func_bit_and::val_int()
4709 {
4710  DBUG_ASSERT(fixed == 1);
4711  ulonglong arg1= (ulonglong) args[0]->val_int();
4712  if (args[0]->null_value)
4713  {
4714  null_value=1; /* purecov: inspected */
4715  return 0; /* purecov: inspected */
4716  }
4717  ulonglong arg2= (ulonglong) args[1]->val_int();
4718  if (args[1]->null_value)
4719  {
4720  null_value=1; /* purecov: inspected */
4721  return 0; /* purecov: inspected */
4722  }
4723  null_value=0;
4724  return (longlong) (arg1 & arg2);
4725 }
4726 
4727 Item_cond::Item_cond(THD *thd, Item_cond *item)
4728  :Item_bool_func(thd, item),
4729  abort_on_null(item->abort_on_null)
4730 {
4731  /*
4732  item->list will be copied by copy_andor_arguments() call
4733  */
4734 }
4735 
4736 
4737 void Item_cond::copy_andor_arguments(THD *thd, Item_cond *item, bool real_items)
4738 {
4739  List_iterator_fast<Item> li(item->list);
4740  while (Item *it= li++)
4741  list.push_back((real_items ? it->real_item() : it)->
4742  copy_andor_structure(thd, real_items));
4743 }
4744 
4745 
4746 bool
4747 Item_cond::fix_fields(THD *thd, Item **ref)
4748 {
4749  DBUG_ASSERT(fixed == 0);
4750  List_iterator<Item> li(list);
4751  Item *item;
4752  Switch_resolve_place SRP(&thd->lex->current_select->resolve_place,
4753  st_select_lex::RESOLVE_NONE,
4754  functype() != COND_AND_FUNC);
4755  uchar buff[sizeof(char*)]; // Max local vars in function
4756  used_tables_cache= 0;
4757  const_item_cache= true;
4758 
4759  if (functype() == COND_AND_FUNC && abort_on_null)
4761  else
4762  not_null_tables_cache= ~(table_map) 0;
4763 
4764  if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
4765  return TRUE; // Fatal error flag is set!
4766  /*
4767  The following optimization reduces the depth of an AND-OR tree.
4768  E.g. a WHERE clause like
4769  F1 AND (F2 AND (F2 AND F4))
4770  is parsed into a tree with the same nested structure as defined
4771  by braces. This optimization will transform such tree into
4772  AND (F1, F2, F3, F4).
4773  Trees of OR items are flattened as well:
4774  ((F1 OR F2) OR (F3 OR F4)) => OR (F1, F2, F3, F4)
4775  Items for removed AND/OR levels will dangle until the death of the
4776  entire statement.
4777  The optimization is currently prepared statements and stored procedures
4778  friendly as it doesn't allocate any memory and its effects are durable
4779  (i.e. do not depend on PS/SP arguments).
4780  */
4781  while ((item=li++))
4782  {
4783  while (item->type() == Item::COND_ITEM &&
4784  ((Item_cond*) item)->functype() == functype() &&
4785  !((Item_cond*) item)->list.is_empty())
4786  { // Identical function
4787  li.replace(((Item_cond*) item)->list);
4788  ((Item_cond*) item)->list.empty();
4789  item= *li.ref(); // new current item
4790  }
4791  if (abort_on_null)
4792  item->top_level_item();
4793 
4794  // item can be substituted in fix_fields
4795  if ((!item->fixed &&
4796  item->fix_fields(thd, li.ref())) ||
4797  (item= *li.ref())->check_cols(1))
4798  return TRUE; /* purecov: inspected */
4799  used_tables_cache|= item->used_tables();
4800  const_item_cache&= item->const_item();
4801 
4802  if (functype() == COND_AND_FUNC && abort_on_null)
4803  not_null_tables_cache|= item->not_null_tables();
4804  else
4805  not_null_tables_cache&= item->not_null_tables();
4806  with_sum_func|= item->with_sum_func;
4807  with_subselect|= item->has_subquery();
4808  with_stored_program|= item->has_stored_program();
4809  if (item->maybe_null)
4810  maybe_null= true;
4811  }
4812  thd->lex->current_select->cond_count+= list.elements;
4813  fix_length_and_dec();
4814  fixed= true;
4815  return false;
4816 }
4817 
4818 
4819 void Item_cond::fix_after_pullout(st_select_lex *parent_select,
4820  st_select_lex *removed_select)
4821 {
4822  List_iterator<Item> li(list);
4823  Item *item;
4824 
4825  used_tables_cache= get_initial_pseudo_tables();
4826  const_item_cache= true;
4827 
4828  if (functype() == COND_AND_FUNC && abort_on_null)
4830  else
4831  not_null_tables_cache= ~(table_map) 0;
4832 
4833  while ((item=li++))
4834  {
4835  item->fix_after_pullout(parent_select, removed_select);
4836  used_tables_cache|= item->used_tables();
4837  const_item_cache&= item->const_item();
4838  if (functype() == COND_AND_FUNC && abort_on_null)
4839  not_null_tables_cache|= item->not_null_tables();
4840  else
4841  not_null_tables_cache&= item->not_null_tables();
4842  }
4843 }
4844 
4845 
4846 bool Item_cond::walk(Item_processor processor, bool walk_subquery, uchar *arg)
4847 {
4848  List_iterator_fast<Item> li(list);
4849  Item *item;
4850  while ((item= li++))
4851  if (item->walk(processor, walk_subquery, arg))
4852  return 1;
4853  return Item_func::walk(processor, walk_subquery, arg);
4854 }
4855 
4856 
4875 Item *Item_cond::transform(Item_transformer transformer, uchar *arg)
4876 {
4877  DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
4878 
4879  List_iterator<Item> li(list);
4880  Item *item;
4881  while ((item= li++))
4882  {
4883  Item *new_item= item->transform(transformer, arg);
4884  if (!new_item)
4885  return 0;
4886 
4887  /*
4888  THD::change_item_tree() should be called only if the tree was
4889  really transformed, i.e. when a new item has been created.
4890  Otherwise we'll be allocating a lot of unnecessary memory for
4891  change records at each execution.
4892  */
4893  if (new_item != item)
4894  current_thd->change_item_tree(li.ref(), new_item);
4895  }
4896  return Item_func::transform(transformer, arg);
4897 }
4898 
4899 
4925 Item *Item_cond::compile(Item_analyzer analyzer, uchar **arg_p,
4926  Item_transformer transformer, uchar *arg_t)
4927 {
4928  if (!(this->*analyzer)(arg_p))
4929  return this;
4930 
4931  List_iterator<Item> li(list);
4932  Item *item;
4933  while ((item= li++))
4934  {
4935  /*
4936  The same parameter value of arg_p must be passed
4937  to analyze any argument of the condition formula.
4938  */
4939  uchar *arg_v= *arg_p;
4940  Item *new_item= item->compile(analyzer, &arg_v, transformer, arg_t);
4941  if (new_item == NULL)
4942  return NULL;
4943  if (new_item != item)
4944  current_thd->change_item_tree(li.ref(), new_item);
4945  }
4946  return Item_func::transform(transformer, arg_t);
4947 }
4948 
4949 void Item_cond::traverse_cond(Cond_traverser traverser,
4950  void *arg, traverse_order order)
4951 {
4952  List_iterator<Item> li(list);
4953  Item *item;
4954 
4955  switch(order) {
4956  case(PREFIX):
4957  (*traverser)(this, arg);
4958  while ((item= li++))
4959  {
4960  item->traverse_cond(traverser, arg, order);
4961  }
4962  (*traverser)(NULL, arg);
4963  break;
4964  case(POSTFIX):
4965  while ((item= li++))
4966  {
4967  item->traverse_cond(traverser, arg, order);
4968  }
4969  (*traverser)(this, arg);
4970  }
4971 }
4972 
4990 void Item_cond::split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array,
4991  List<Item> &fields)
4992 {
4993  List_iterator<Item> li(list);
4994  Item *item;
4995  while ((item= li++))
4996  item->split_sum_func2(thd, ref_pointer_array, fields, li.ref(), TRUE);
4997 }
4998 
4999 
5000 void Item_cond::update_used_tables()
5001 {
5002  List_iterator_fast<Item> li(list);
5003  Item *item;
5004 
5005  used_tables_cache=0;
5006  const_item_cache=1;
5007  with_subselect= false;
5008  with_stored_program= false;
5009  while ((item=li++))
5010  {
5011  item->update_used_tables();
5012  used_tables_cache|= item->used_tables();
5013  const_item_cache&= item->const_item();
5014  with_subselect|= item->has_subquery();
5015  with_stored_program|= item->has_stored_program();
5016  }
5017 }
5018 
5019 
5020 void Item_cond::print(String *str, enum_query_type query_type)
5021 {
5022  str->append('(');
5023  List_iterator_fast<Item> li(list);
5024  Item *item;
5025  if ((item=li++))
5026  item->print(str, query_type);
5027  while ((item=li++))
5028  {
5029  str->append(' ');
5030  str->append(func_name());
5031  str->append(' ');
5032  item->print(str, query_type);
5033  }
5034  str->append(')');
5035 }
5036 
5037 
5038 void Item_cond::neg_arguments(THD *thd)
5039 {
5040  List_iterator<Item> li(list);
5041  Item *item;
5042  while ((item= li++)) /* Apply not transformation to the arguments */
5043  {
5044  Item *new_item= item->neg_transformer(thd);
5045  if (!new_item)
5046  {
5047  if (!(new_item= new Item_func_not(item)))
5048  return; // Fatal OEM error
5049  }
5050  (void) li.replace(new_item);
5051  }
5052 }
5053 
5054 
5076 {
5077  DBUG_ASSERT(fixed == 1);
5078  List_iterator_fast<Item> li(list);
5079  Item *item;
5080  null_value= 0;
5081  while ((item=li++))
5082  {
5083  if (!item->val_bool())
5084  {
5085  if (abort_on_null || !(null_value= item->null_value))
5086  return 0; // return FALSE
5087  }
5088  }
5089  return null_value ? 0 : 1;
5090 }
5091 
5092 
5093 longlong Item_cond_or::val_int()
5094 {
5095  DBUG_ASSERT(fixed == 1);
5096  List_iterator_fast<Item> li(list);
5097  Item *item;
5098  null_value=0;
5099  while ((item=li++))
5100  {
5101  if (item->val_bool())
5102  {
5103  null_value=0;
5104  return 1;
5105  }
5106  if (item->null_value)
5107  null_value=1;
5108  }
5109  return 0;
5110 }
5111 
5132 Item *and_expressions(Item *a, Item *b, Item **org_item)
5133 {
5134  if (!a)
5135  return (*org_item= (Item*) b);
5136  if (a == *org_item)
5137  {
5138  Item_cond *res;
5139  if ((res= new Item_cond_and(a, (Item*) b)))
5140  {
5141  res->set_used_tables(a->used_tables() | b->used_tables());
5142  res->set_not_null_tables(a->not_null_tables() | b->not_null_tables());
5143  }
5144  return res;
5145  }
5146  if (((Item_cond_and*) a)->add((Item*) b))
5147  return 0;
5148  ((Item_cond_and*) a)->set_used_tables(a->used_tables() | b->used_tables());
5149  ((Item_cond_and*) a)->set_not_null_tables(a->not_null_tables() |
5150  b->not_null_tables());
5151  return a;
5152 }
5153 
5154 
5155 longlong Item_func_isnull::val_int()
5156 {
5157  DBUG_ASSERT(fixed == 1);
5158  /*
5159  Handle optimization if the argument can't be null
5160  This has to be here because of the test in update_used_tables().
5161  */
5162  if (const_item_cache)
5163  return cached_value;
5164  return args[0]->is_null() ? 1: 0;
5165 }
5166 
5167 longlong Item_is_not_null_test::val_int()
5168 {
5169  DBUG_ASSERT(fixed == 1);
5170  DBUG_ENTER("Item_is_not_null_test::val_int");
5171  if (!used_tables_cache && !with_subselect && !with_stored_program)
5172  {
5173  /*
5174  TODO: Currently this branch never executes, since used_tables_cache
5175  is never equal to 0 -- it always contains RAND_TABLE_BIT,
5176  see get_initial_pseudo_tables().
5177  */
5178  owner->was_null|= (!cached_value);
5179  DBUG_PRINT("info", ("cached: %ld", (long) cached_value));
5180  DBUG_RETURN(cached_value);
5181  }
5182  if (args[0]->is_null())
5183  {
5184  DBUG_PRINT("info", ("null"));
5185  owner->was_null|= 1;
5186  DBUG_RETURN(0);
5187  }
5188  else
5189  DBUG_RETURN(1);
5190 }
5191 
5196 {
5197  const table_map initial_pseudo_tables= get_initial_pseudo_tables();
5198  used_tables_cache= initial_pseudo_tables;
5199  if (!args[0]->maybe_null)
5200  {
5201  cached_value= 1;
5202  return;
5203  }
5204  args[0]->update_used_tables();
5205  with_subselect= args[0]->has_subquery();
5206  with_stored_program= args[0]->has_stored_program();
5207  used_tables_cache|= args[0]->used_tables();
5208  if (used_tables_cache == initial_pseudo_tables && !with_subselect &&
5209  !with_stored_program)
5210  /* Remember if the value is always NULL or never NULL */
5211  cached_value= !args[0]->is_null();
5212 }
5213 
5214 
5215 longlong Item_func_isnotnull::val_int()
5216 {
5217  DBUG_ASSERT(fixed == 1);
5218  return args[0]->is_null() ? 0 : 1;
5219 }
5220 
5221 
5222 void Item_func_isnotnull::print(String *str, enum_query_type query_type)
5223 {
5224  str->append('(');
5225  args[0]->print(str, query_type);
5226  str->append(STRING_WITH_LEN(" is not null)"));
5227 }
5228 
5229 
5230 longlong Item_func_like::val_int()
5231 {
5232  DBUG_ASSERT(fixed == 1);
5233  String* res = args[0]->val_str(&cmp.value1);
5234  if (args[0]->null_value)
5235  {
5236  null_value=1;
5237  return 0;
5238  }
5239  String* res2 = args[1]->val_str(&cmp.value2);
5240  if (args[1]->null_value)
5241  {
5242  null_value=1;
5243  return 0;
5244  }
5245  null_value=0;
5246  if (canDoTurboBM)
5247  return turboBM_matches(res->ptr(), res->length()) ? 1 : 0;
5248  return my_wildcmp(cmp.cmp_collation.collation,
5249  res->ptr(),res->ptr()+res->length(),
5250  res2->ptr(),res2->ptr()+res2->length(),
5251  escape,wild_one,wild_many) ? 0 : 1;
5252 }
5253 
5254 
5259 Item_func::optimize_type Item_func_like::select_optimize() const
5260 {
5261  if (!args[1]->const_item())
5262  return OPTIMIZE_NONE;
5263 
5264  String* res2= args[1]->val_str((String *)&cmp.value2);
5265  if (!res2)
5266  return OPTIMIZE_NONE;
5267 
5268  if (!res2->length()) // Can optimize empty wildcard: column LIKE ''
5269  return OPTIMIZE_OP;
5270 
5271  DBUG_ASSERT(res2->ptr());
5272  char first= res2->ptr()[0];
5273  return (first == wild_many || first == wild_one) ?
5274  OPTIMIZE_NONE : OPTIMIZE_OP;
5275 }
5276 
5277 
5278 bool Item_func_like::fix_fields(THD *thd, Item **ref)
5279 {
5280  DBUG_ASSERT(fixed == 0);
5281  if (Item_bool_func2::fix_fields(thd, ref) ||
5282  escape_item->fix_fields(thd, &escape_item))
5283  return TRUE;
5284 
5285  if (!escape_item->const_during_execution())
5286  {
5287  my_error(ER_WRONG_ARGUMENTS,MYF(0),"ESCAPE");
5288  return TRUE;
5289  }
5290 
5291  if (escape_item->const_item())
5292  {
5293  /* If we are on execution stage */
5294  String *escape_str= escape_item->val_str(&cmp.value1);
5295  if (escape_str)
5296  {
5297  const char *escape_str_ptr= escape_str->ptr();
5298  if (escape_used_in_parsing && (
5299  (((thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
5300  escape_str->numchars() != 1) ||
5301  escape_str->numchars() > 1)))
5302  {
5303  my_error(ER_WRONG_ARGUMENTS,MYF(0),"ESCAPE");
5304  return TRUE;
5305  }
5306 
5307  if (use_mb(cmp.cmp_collation.collation))
5308  {
5309  const CHARSET_INFO *cs= escape_str->charset();
5310  my_wc_t wc;
5311  int rc= cs->cset->mb_wc(cs, &wc,
5312  (const uchar*) escape_str_ptr,
5313  (const uchar*) escape_str_ptr +
5314  escape_str->length());
5315  escape= (int) (rc > 0 ? wc : '\\');
5316  }
5317  else
5318  {
5319  /*
5320  In the case of 8bit character set, we pass native
5321  code instead of Unicode code as "escape" argument.
5322  Convert to "cs" if charset of escape differs.
5323  */
5324  const CHARSET_INFO *cs= cmp.cmp_collation.collation;
5325  uint32 unused;
5326  if (escape_str->needs_conversion(escape_str->length(),
5327  escape_str->charset(), cs, &unused))
5328  {
5329  char ch;
5330  uint errors;
5331  uint32 cnvlen= copy_and_convert(&ch, 1, cs, escape_str_ptr,
5332  escape_str->length(),
5333  escape_str->charset(), &errors);
5334  escape= cnvlen ? ch : '\\';
5335  }
5336  else
5337  escape= escape_str_ptr ? *escape_str_ptr : '\\';
5338  }
5339  }
5340  else
5341  escape= '\\';
5342 
5343  /*
5344  We could also do boyer-more for non-const items, but as we would have to
5345  recompute the tables for each row it's not worth it.
5346  */
5347  if (args[1]->const_item() && !use_strnxfrm(collation.collation) &&
5348  !(specialflag & SPECIAL_NO_NEW_FUNC))
5349  {
5350  String* res2 = args[1]->val_str(&cmp.value2);
5351  if (!res2)
5352  return FALSE; // Null argument
5353 
5354  const size_t len = res2->length();
5355  const char* first = res2->ptr();
5356  const char* last = first + len - 1;
5357  /*
5358  len must be > 2 ('%pattern%')
5359  heuristic: only do TurboBM for pattern_len > 2
5360  */
5361 
5362  if (len > MIN_TURBOBM_PATTERN_LEN + 2 &&
5363  *first == wild_many &&
5364  *last == wild_many)
5365  {
5366  const char* tmp = first + 1;
5367  for (; *tmp != wild_many && *tmp != wild_one && *tmp != escape; tmp++) ;
5368  canDoTurboBM = (tmp == last) && !use_mb(args[0]->collation.collation);
5369  }
5370  if (canDoTurboBM)
5371  {
5372  pattern_len = (int) len - 2;
5373  pattern = thd->strmake(first + 1, pattern_len);
5374  DBUG_PRINT("info", ("Initializing pattern: '%s'", first));
5375  int *suff = (int*) thd->alloc((int) (sizeof(int)*
5376  ((pattern_len + 1)*2+
5377  alphabet_size)));
5378  bmGs = suff + pattern_len + 1;
5379  bmBc = bmGs + pattern_len + 1;
5380  turboBM_compute_good_suffix_shifts(suff);
5381  turboBM_compute_bad_character_shifts();
5382  DBUG_PRINT("info",("done"));
5383  }
5384  }
5385  }
5386  return FALSE;
5387 }
5388 
5389 void Item_func_like::cleanup()
5390 {
5391  canDoTurboBM= FALSE;
5392  Item_bool_func2::cleanup();
5393 }
5394 
5408 int Item_func_regex::regcomp(bool send_error)
5409 {
5410  char buff[MAX_FIELD_WIDTH];
5411  String tmp(buff,sizeof(buff),&my_charset_bin);
5412  String *res= args[1]->val_str(&tmp);
5413  int error;
5414 
5415  if (args[1]->null_value)
5416  return -1;
5417 
5418  if (regex_compiled)
5419  {
5420  if (!stringcmp(res, &prev_regexp))
5421  return 0;
5422  prev_regexp.copy(*res);
5423  my_regfree(&preg);
5424  regex_compiled= 0;
5425  }
5426 
5427  if (cmp_collation.collation != regex_lib_charset)
5428  {
5429  /* Convert UCS2 strings to UTF8 */
5430  uint dummy_errors;
5431  if (conv.copy(res->ptr(), res->length(), res->charset(),
5432  regex_lib_charset, &dummy_errors))
5433  return 1;
5434  res= &conv;
5435  }
5436 
5437  if ((error= my_regcomp(&preg, res->c_ptr_safe(),
5438  regex_lib_flags, regex_lib_charset)))
5439  {
5440  if (send_error)
5441  {
5442  (void) my_regerror(error, &preg, buff, sizeof(buff));
5443  my_error(ER_REGEXP_ERROR, MYF(0), buff);
5444  }
5445  return 1;
5446  }
5447  regex_compiled= 1;
5448  return 0;
5449 }
5450 
5451 
5452 bool
5453 Item_func_regex::fix_fields(THD *thd, Item **ref)
5454 {
5455  DBUG_ASSERT(fixed == 0);
5456  if ((!args[0]->fixed &&
5457  args[0]->fix_fields(thd, args)) || args[0]->check_cols(1) ||
5458  (!args[1]->fixed &&
5459  args[1]->fix_fields(thd, args + 1)) || args[1]->check_cols(1))
5460  return TRUE; /* purecov: inspected */
5461  with_sum_func=args[0]->with_sum_func || args[1]->with_sum_func;
5462  with_subselect= args[0]->has_subquery() || args[1]->has_subquery();
5463  with_stored_program= args[0]->has_stored_program() ||
5464  args[1]->has_stored_program();
5465  max_length= 1;
5466  decimals= 0;
5467 
5468  if (agg_arg_charsets_for_comparison(cmp_collation, args, 2))
5469  return TRUE;
5470 
5471  regex_lib_flags= (cmp_collation.collation->state &
5472  (MY_CS_BINSORT | MY_CS_CSSORT)) ?
5473  MY_REG_EXTENDED | MY_REG_NOSUB :
5474  MY_REG_EXTENDED | MY_REG_NOSUB | MY_REG_ICASE;
5475  /*
5476  If the case of UCS2 and other non-ASCII character sets,
5477  we will convert patterns and strings to UTF8.
5478  */
5479  regex_lib_charset= (cmp_collation.collation->mbminlen > 1) ?
5480  &my_charset_utf8_general_ci :
5481  cmp_collation.collation;
5482 
5483  used_tables_cache=args[0]->used_tables() | args[1]->used_tables();
5484  not_null_tables_cache= (args[0]->not_null_tables() |
5485  args[1]->not_null_tables());
5486  const_item_cache=args[0]->const_item() && args[1]->const_item();
5487  if (!regex_compiled && args[1]->const_item())
5488  {
5489  int comp_res= regcomp(TRUE);
5490  if (comp_res == -1)
5491  { // Will always return NULL
5492  maybe_null=1;
5493  fixed= 1;
5494  return FALSE;
5495  }
5496  else if (comp_res)
5497  return TRUE;
5498  regex_is_const= 1;
5499  maybe_null= args[0]->maybe_null;
5500  }
5501  else
5502  maybe_null=1;
5503  fixed= 1;
5504  return FALSE;
5505 }
5506 
5507 
5508 longlong Item_func_regex::val_int()
5509 {
5510  DBUG_ASSERT(fixed == 1);
5511  char buff[MAX_FIELD_WIDTH];
5512  String tmp(buff,sizeof(buff),&my_charset_bin);
5513  String *res= args[0]->val_str(&tmp);
5514 
5515  if ((null_value= (args[0]->null_value ||
5516  (!regex_is_const && regcomp(FALSE)))))
5517  return 0;
5518 
5519  if (cmp_collation.collation != regex_lib_charset)
5520  {
5521  /* Convert UCS2 strings to UTF8 */
5522  uint dummy_errors;
5523  if (conv.copy(res->ptr(), res->length(), res->charset(),
5524  regex_lib_charset, &dummy_errors))
5525  {
5526  null_value= 1;
5527  return 0;
5528  }
5529  res= &conv;
5530  }
5531  return my_regexec(&preg,res->c_ptr_safe(),0,(my_regmatch_t*) 0,0) ? 0 : 1;
5532 }
5533 
5534 
5535 void Item_func_regex::cleanup()
5536 {
5537  DBUG_ENTER("Item_func_regex::cleanup");
5538  Item_bool_func::cleanup();
5539  if (regex_compiled)
5540  {
5541  my_regfree(&preg);
5542  regex_compiled=0;
5543  prev_regexp.length(0);
5544  }
5545  DBUG_VOID_RETURN;
5546 }
5547 
5548 
5549 #ifdef LIKE_CMP_TOUPPER
5550 #define likeconv(cs,A) (uchar) (cs)->toupper(A)
5551 #else
5552 #define likeconv(cs,A) (uchar) (cs)->sort_order[(uchar) (A)]
5553 #endif
5554 
5555 
5560 void Item_func_like::turboBM_compute_suffixes(int *suff)
5561 {
5562  const int plm1 = pattern_len - 1;
5563  int f = 0;
5564  int g = plm1;
5565  int *const splm1 = suff + plm1;
5566  const CHARSET_INFO *cs= cmp.cmp_collation.collation;
5567 
5568  *splm1 = pattern_len;
5569 
5570  if (!cs->sort_order)
5571  {
5572  int i;
5573  for (i = pattern_len - 2; i >= 0; i--)
5574  {
5575  int tmp = *(splm1 + i - f);
5576  if (g < i && tmp < i - g)
5577  suff[i] = tmp;
5578  else
5579  {
5580  if (i < g)
5581  g = i; // g = min(i, g)
5582  f = i;
5583  while (g >= 0 && pattern[g] == pattern[g + plm1 - f])
5584  g--;
5585  suff[i] = f - g;
5586  }
5587  }
5588  }
5589  else
5590  {
5591  int i;
5592  for (i = pattern_len - 2; 0 <= i; --i)
5593  {
5594  int tmp = *(splm1 + i - f);
5595  if (g < i && tmp < i - g)
5596  suff[i] = tmp;
5597  else
5598  {
5599  if (i < g)
5600  g = i; // g = min(i, g)
5601  f = i;
5602  while (g >= 0 &&
5603  likeconv(cs, pattern[g]) == likeconv(cs, pattern[g + plm1 - f]))
5604  g--;
5605  suff[i] = f - g;
5606  }
5607  }
5608  }
5609 }
5610 
5611 
5616 void Item_func_like::turboBM_compute_good_suffix_shifts(int *suff)
5617 {
5618  turboBM_compute_suffixes(suff);
5619 
5620  int *end = bmGs + pattern_len;
5621  int *k;
5622  for (k = bmGs; k < end; k++)
5623  *k = pattern_len;
5624 
5625  int tmp;
5626  int i;
5627  int j = 0;
5628  const int plm1 = pattern_len - 1;
5629  for (i = plm1; i > -1; i--)
5630  {
5631  if (suff[i] == i + 1)
5632  {
5633  for (tmp = plm1 - i; j < tmp; j++)
5634  {
5635  int *tmp2 = bmGs + j;
5636  if (*tmp2 == pattern_len)
5637  *tmp2 = tmp;
5638  }
5639  }
5640  }
5641 
5642  int *tmp2;
5643  for (tmp = plm1 - i; j < tmp; j++)
5644  {
5645  tmp2 = bmGs + j;
5646  if (*tmp2 == pattern_len)
5647  *tmp2 = tmp;
5648  }
5649 
5650  tmp2 = bmGs + plm1;
5651  for (i = 0; i <= pattern_len - 2; i++)
5652  *(tmp2 - suff[i]) = plm1 - i;
5653 }
5654 
5655 
5660 void Item_func_like::turboBM_compute_bad_character_shifts()
5661 {
5662  int *i;
5663  int *end = bmBc + alphabet_size;
5664  int j;
5665  const int plm1 = pattern_len - 1;
5666  const CHARSET_INFO *cs= cmp.cmp_collation.collation;
5667 
5668  for (i = bmBc; i < end; i++)
5669  *i = pattern_len;
5670 
5671  if (!cs->sort_order)
5672  {
5673  for (j = 0; j < plm1; j++)
5674  bmBc[(uint) (uchar) pattern[j]] = plm1 - j;
5675  }
5676  else
5677  {
5678  for (j = 0; j < plm1; j++)
5679  bmBc[(uint) likeconv(cs,pattern[j])] = plm1 - j;
5680  }
5681 }
5682 
5683 
5691 bool Item_func_like::turboBM_matches(const char* text, int text_len) const
5692 {
5693  int bcShift;
5694  int turboShift;
5695  int shift = pattern_len;
5696  int j = 0;
5697  int u = 0;
5698  const CHARSET_INFO *cs= cmp.cmp_collation.collation;
5699 
5700  const int plm1= pattern_len - 1;
5701  const int tlmpl= text_len - pattern_len;
5702 
5703  /* Searching */
5704  if (!cs->sort_order)
5705  {
5706  while (j <= tlmpl)
5707  {
5708  int i= plm1;
5709  while (i >= 0 && pattern[i] == text[i + j])
5710  {
5711  i--;
5712  if (i == plm1 - shift)
5713  i-= u;
5714  }
5715  if (i < 0)
5716  return 1;
5717 
5718  const int v = plm1 - i;
5719  turboShift = u - v;
5720  bcShift = bmBc[(uint) (uchar) text[i + j]] - plm1 + i;
5721  shift = max(turboShift, bcShift);
5722  shift = max(shift, bmGs[i]);
5723  if (shift == bmGs[i])
5724  u = min(pattern_len - shift, v);
5725  else
5726  {
5727  if (turboShift < bcShift)
5728  shift = max(shift, u + 1);
5729  u = 0;
5730  }
5731  j+= shift;
5732  }
5733  return 0;
5734  }
5735  else
5736  {
5737  while (j <= tlmpl)
5738  {
5739  int i = plm1;
5740  while (i >= 0 && likeconv(cs,pattern[i]) == likeconv(cs,text[i + j]))
5741  {
5742  i--;
5743  if (i == plm1 - shift)
5744  i-= u;
5745  }
5746  if (i < 0)
5747  return 1;
5748 
5749  const int v = plm1 - i;
5750  turboShift = u - v;
5751  bcShift = bmBc[(uint) likeconv(cs, text[i + j])] - plm1 + i;
5752  shift = max(turboShift, bcShift);
5753  shift = max(shift, bmGs[i]);
5754  if (shift == bmGs[i])
5755  u = min(pattern_len - shift, v);
5756  else
5757  {
5758  if (turboShift < bcShift)
5759  shift = max(shift, u + 1);
5760  u = 0;
5761  }
5762  j+= shift;
5763  }
5764  return 0;
5765  }
5766 }
5767 
5768 
5786 {
5787  DBUG_ASSERT(fixed == 1);
5788  int result= 0;
5789  null_value= false;
5790  for (uint i= 0; i < arg_count; i++)
5791  {
5792  result^= (args[i]->val_int() != 0);
5793  if (args[i]->null_value)
5794  {
5795  null_value= true;
5796  return 0;
5797  }
5798  }
5799  return result;
5800 }
5801 
5828 Item *Item_func_not::neg_transformer(THD *thd) /* NOT(x) -> x */
5829 {
5830  return args[0];
5831 }
5832 
5833 
5834 Item *Item_bool_rowready_func2::neg_transformer(THD *thd)
5835 {
5836  Item *item= negated_item();
5837  return item;
5838 }
5839 
5850 {
5851  Item *neg_operand;
5852  Item_func_xor *new_item;
5853  if ((neg_operand= args[0]->neg_transformer(thd)))
5854  // args[0] has neg_tranformer
5855  new_item= new(thd->mem_root) Item_func_xor(neg_operand, args[1]);
5856  else if ((neg_operand= args[1]->neg_transformer(thd)))
5857  // args[1] has neg_tranformer
5858  new_item= new(thd->mem_root) Item_func_xor(args[0], neg_operand);
5859  else
5860  {
5861  neg_operand= new(thd->mem_root) Item_func_not(args[0]);
5862  new_item= new(thd->mem_root) Item_func_xor(neg_operand, args[1]);
5863  }
5864  return new_item;
5865 }
5866 
5867 
5872 {
5873  Item *item= new Item_func_isnotnull(args[0]);
5874  return item;
5875 }
5876 
5877 
5882 {
5883  Item *item= new Item_func_isnull(args[0]);
5884  return item;
5885 }
5886 
5887 
5888 Item *Item_cond_and::neg_transformer(THD *thd) /* NOT(a AND b AND ...) -> */
5889  /* NOT a OR NOT b OR ... */
5890 {
5891  neg_arguments(thd);
5892  Item *item= new Item_cond_or(list);
5893  return item;
5894 }
5895 
5896 
5897 Item *Item_cond_or::neg_transformer(THD *thd) /* NOT(a OR b OR ...) -> */
5898  /* NOT a AND NOT b AND ... */
5899 {
5900  neg_arguments(thd);
5901  Item *item= new Item_cond_and(list);
5902  return item;
5903 }
5904 
5905 
5907 {
5908  /* "NOT (e $cmp$ ANY (SELECT ...)) -> e $rev_cmp$" ALL (SELECT ...) */
5909  Item_func_not_all *new_item= new Item_func_not_all(args[0]);
5910  Item_allany_subselect *allany= (Item_allany_subselect*)args[0];
5911  allany->func= allany->func_creator(FALSE);
5912  allany->all= !allany->all;
5913  allany->upper_item= new_item;
5914  return new_item;
5915 }
5916 
5918 {
5919  /* "NOT (e $cmp$ ALL (SELECT ...)) -> e $rev_cmp$" ANY (SELECT ...) */
5920  Item_func_nop_all *new_item= new Item_func_nop_all(args[0]);
5921  Item_allany_subselect *allany= (Item_allany_subselect*)args[0];
5922  allany->all= !allany->all;
5923  allany->func= allany->func_creator(TRUE);
5924  allany->upper_item= new_item;
5925  return new_item;
5926 }
5927 
5928 Item *Item_func_eq::negated_item() /* a = b -> a != b */
5929 {
5930  return new Item_func_ne(args[0], args[1]);
5931 }
5932 
5933 
5934 Item *Item_func_ne::negated_item() /* a != b -> a = b */
5935 {
5936  return new Item_func_eq(args[0], args[1]);
5937 }
5938 
5939 
5940 Item *Item_func_lt::negated_item() /* a < b -> a >= b */
5941 {
5942  return new Item_func_ge(args[0], args[1]);
5943 }
5944 
5945 
5946 Item *Item_func_ge::negated_item() /* a >= b -> a < b */
5947 {
5948  return new Item_func_lt(args[0], args[1]);
5949 }
5950 
5951 
5952 Item *Item_func_gt::negated_item() /* a > b -> a <= b */
5953 {
5954  return new Item_func_le(args[0], args[1]);
5955 }
5956 
5957 
5958 Item *Item_func_le::negated_item() /* a <= b -> a > b */
5959 {
5960  return new Item_func_gt(args[0], args[1]);
5961 }
5962 
5967 {
5968  DBUG_ASSERT(0);
5969  return 0;
5970 }
5971 
5972 Item_equal::Item_equal(Item_field *f1, Item_field *f2)
5973  : Item_bool_func(), const_item(0), eval_item(0), cond_false(0),
5974  compare_as_dates(FALSE)
5975 {
5976  const_item_cache= 0;
5977  fields.push_back(f1);
5978  fields.push_back(f2);
5979 }
5980 
5981 Item_equal::Item_equal(Item *c, Item_field *f)
5982  : Item_bool_func(), eval_item(0), cond_false(0)
5983 {
5984  const_item_cache= 0;
5985  fields.push_back(f);
5986  const_item= c;
5987  compare_as_dates= f->is_temporal_with_date();
5988 }
5989 
5990 
5991 Item_equal::Item_equal(Item_equal *item_equal)
5992  : Item_bool_func(), eval_item(0), cond_false(0)
5993 {
5994  const_item_cache= 0;
5995  List_iterator_fast<Item_field> li(item_equal->fields);
5996  Item_field *item;
5997  while ((item= li++))
5998  {
5999  fields.push_back(item);
6000  }
6001  const_item= item_equal->const_item;
6002  compare_as_dates= item_equal->compare_as_dates;
6003  cond_false= item_equal->cond_false;
6004 }
6005 
6006 
6007 void Item_equal::compare_const(Item *c)
6008 {
6009  if (compare_as_dates)
6010  {
6011  cmp.set_datetime_cmp_func(this, &c, &const_item);
6012  cond_false= cmp.compare();
6013  }
6014  else
6015  {
6016  Item_func_eq *func= new Item_func_eq(c, const_item);
6017  if(func->set_cmp_func())
6018  return;
6019  func->quick_fix_field();
6020  cond_false= !func->val_int();
6021  }
6022  if (cond_false)
6023  const_item_cache= 1;
6024 }
6025 
6026 
6027 void Item_equal::add(Item *c, Item_field *f)
6028 {
6029  if (cond_false)
6030  return;
6031  if (!const_item)
6032  {
6033  DBUG_ASSERT(f);
6034  const_item= c;
6035  compare_as_dates= f->is_temporal_with_date();
6036  return;
6037  }
6038  compare_const(c);
6039 }
6040 
6041 
6042 void Item_equal::add(Item *c)
6043 {
6044  if (cond_false)
6045  return;
6046  if (!const_item)
6047  {
6048  const_item= c;
6049  return;
6050  }
6051  compare_const(c);
6052 }
6053 
6054 void Item_equal::add(Item_field *f)
6055 {
6056  fields.push_back(f);
6057 }
6058 
6059 uint Item_equal::members()
6060 {
6061  return fields.elements;
6062 }
6063 
6064 
6079 {
6080  List_iterator_fast<Item_field> it(fields);
6081  Item_field *item;
6082  while ((item= it++))
6083  {
6084  if (field->eq(item->field))
6085  return 1;
6086  }
6087  return 0;
6088 }
6089 
6090 
6103 {
6104  fields.concat(&item->fields);
6105  Item *c= item->const_item;
6106  if (c)
6107  {
6108  /*
6109  The flag cond_false will be set to 1 after this, if
6110  the multiple equality already contains a constant and its
6111  value is not equal to the value of c.
6112  */
6113  add(c);
6114  }
6115  cond_false|= item->cond_false;
6116 }
6117 
6118 
6136 void Item_equal::sort(Item_field_cmpfunc compare, void *arg)
6137 {
6138  fields.sort((Node_cmp_func)compare, arg);
6139 }
6140 
6141 
6153 {
6154  List_iterator<Item_field> it(fields);
6155  Item *item;
6156  while ((item= it++))
6157  {
6158  if (item->const_item() &&
6159  /*
6160  Don't propagate constant status of outer-joined column.
6161  Such a constant status here is a result of:
6162  a) empty outer-joined table: in this case such a column has a
6163  value of NULL; but at the same time other arguments of
6164  Item_equal don't have to be NULLs and the value of the whole
6165  multiple equivalence expression doesn't have to be NULL or FALSE
6166  because of the outer join nature;
6167  or
6168  b) outer-joined table contains only 1 row: the result of
6169  this column is equal to a row field value *or* NULL.
6170  Both values are inacceptable as Item_equal constants.
6171  */
6172  !item->is_outer_field())
6173  {
6174  it.remove();
6175  add(item);
6176  }
6177  }
6178 }
6179 
6180 bool Item_equal::fix_fields(THD *thd, Item **ref)
6181 {
6182  List_iterator_fast<Item_field> li(fields);
6183  Item *item;
6184  not_null_tables_cache= used_tables_cache= 0;
6185  const_item_cache= 0;
6186  while ((item= li++))
6187  {
6188  table_map tmp_table_map;
6189  used_tables_cache|= item->used_tables();
6190  tmp_table_map= item->not_null_tables();
6191  not_null_tables_cache|= tmp_table_map;
6192  if (item->maybe_null)
6193  maybe_null=1;
6194  }
6195  fix_length_and_dec();
6196  fixed= 1;
6197  return 0;
6198 }
6199 
6200 void Item_equal::update_used_tables()
6201 {
6202  List_iterator_fast<Item_field> li(fields);
6203  Item *item;
6204  not_null_tables_cache= used_tables_cache= 0;
6205  if ((const_item_cache= cond_false))
6206  return;
6207  with_subselect= false;
6208  with_stored_program= false;
6209  while ((item=li++))
6210  {
6211  item->update_used_tables();
6212  used_tables_cache|= item->used_tables();
6213  /* see commentary at Item_equal::update_const() */
6214  const_item_cache&= item->const_item() && !item->is_outer_field();
6215  with_subselect|= item->has_subquery();
6216  with_stored_program|= item->has_stored_program();
6217  }
6218 }
6219 
6220 longlong Item_equal::val_int()
6221 {
6222  Item_field *item_field;
6223  if (cond_false)
6224  return 0;
6225  List_iterator_fast<Item_field> it(fields);
6226  Item *item= const_item ? const_item : it++;
6227  eval_item->store_value(item);
6228  if ((null_value= item->null_value))
6229  return 0;
6230  while ((item_field= it++))
6231  {
6232  /* Skip fields of non-const tables. They haven't been read yet */
6233  if (item_field->field->table->const_table)
6234  {
6235  if (eval_item->cmp(item_field) || (null_value= item_field->null_value))
6236  return 0;
6237  }
6238  }
6239  return 1;
6240 }
6241 
6242 void Item_equal::fix_length_and_dec()
6243 {
6244  Item *item= get_first();
6245  eval_item= cmp_item::get_comparator(item->result_type(),
6246  item->collation.collation);
6247 }
6248 
6249 bool Item_equal::walk(Item_processor processor, bool walk_subquery, uchar *arg)
6250 {
6251  List_iterator_fast<Item_field> it(fields);
6252  Item *item;
6253  while ((item= it++))
6254  {
6255  if (item->walk(processor, walk_subquery, arg))
6256  return 1;
6257  }
6258  return Item_func::walk(processor, walk_subquery, arg);
6259 }
6260 
6261 Item *Item_equal::transform(Item_transformer transformer, uchar *arg)
6262 {
6263  DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
6264 
6265  List_iterator<Item_field> it(fields);
6266  Item *item;
6267  while ((item= it++))
6268  {
6269  Item *new_item= item->transform(transformer, arg);
6270  if (!new_item)
6271  return 0;
6272 
6273  /*
6274  THD::change_item_tree() should be called only if the tree was
6275  really transformed, i.e. when a new item has been created.
6276  Otherwise we'll be allocating a lot of unnecessary memory for
6277  change records at each execution.
6278  */
6279  if (new_item != item)
6280  current_thd->change_item_tree((Item **) it.ref(), new_item);
6281  }
6282  return Item_func::transform(transformer, arg);
6283 }
6284 
6285 void Item_equal::print(String *str, enum_query_type query_type)
6286 {
6287  str->append(func_name());
6288  str->append('(');
6289  List_iterator_fast<Item_field> it(fields);
6290  Item *item;
6291  if (const_item)
6292  const_item->print(str, query_type);
6293  else
6294  {
6295  item= it++;
6296  item->print(str, query_type);
6297  }
6298  while ((item= it++))
6299  {
6300  str->append(',');
6301  str->append(' ');
6302  item->print(str, query_type);
6303  }
6304  str->append(')');
6305 }
6306 
6307 
6308 void Item_func_trig_cond::print(String *str, enum_query_type query_type)
6309 {
6310  /*
6311  Print:
6312  <if>(<property><(optional list of source tables)>, condition, TRUE)
6313  which means: if a certain property (<property>) is true, then return
6314  the value of <condition>, else return TRUE. If source tables are
6315  present, they are the owner of the property.
6316  */
6317  str->append(func_name());
6318  str->append("(");
6319  switch(trig_type)
6320  {
6321  case IS_NOT_NULL_COMPL:
6322  str->append("is_not_null_compl");
6323  break;
6324  case FOUND_MATCH:
6325  str->append("found_match");
6326  break;
6328  str->append("outer_field_is_not_null");
6329  break;
6330  default:
6331  DBUG_ASSERT(0);
6332  }
6333  if (trig_tab != NULL)
6334  {
6335  str->append("(");
6336  str->append(trig_tab->table->alias);
6337  if (trig_tab->last_inner != trig_tab)
6338  {
6339  /* case of t1 LEFT JOIN (t2,t3,...): print range of inner tables */
6340  str->append("..");
6341  str->append(trig_tab->last_inner->table->alias);
6342  }
6343  str->append(")");
6344  }
6345  str->append(", ");
6346  args[0]->print(str, query_type);
6347  str->append(", true)");
6348 }
6349 
6350 
6373 {
6374  DBUG_ASSERT(field != NULL);
6375 
6376  const JOIN_TAB *field_tab= field->field->table->reginfo.join_tab;
6377 
6378  /*
6379  field_tab is NULL if this function was not called from
6380  JOIN::optimize() but from e.g. mysql_delete() or mysql_update().
6381  In these cases there is only one table and no semijoin
6382  */
6383  if (field_tab &&
6384  sj_is_materialize_strategy(field_tab->get_sj_strategy()))
6385  {
6386  /*
6387  It's a field from a materialized semijoin. We can substitute it only
6388  with a field from the same semijoin.
6389 
6390  Example: suppose we have a join_tab order:
6391 
6392  ot1 ot2 <subquery> ot3 SJM(it1 it2 it3)
6393 
6394  <subquery> is the temporary table that is materialized from the join
6395  of it1, it2 and it3.
6396 
6397  and equality ot2.col = <subquery>.col = it1.col = it2.col
6398 
6399  If we're looking for best substitute for 'it2.col', we must pick it1.col
6400  and not ot2.col. it2.col is evaluated while performing materialization,
6401  when the outer tables are not available in the execution.
6402 
6403  Note that subquery materialization does not have the same problem:
6404  even though IN->EXISTS has injected equalities involving outer query's
6405  expressions, it has wrapped those expressions in variants of Item_ref,
6406  never Item_field, so they can be part of an Item_equal only if they are
6407  constant (in which case there is no problem with choosing them below);
6408  @see check_simple_equality().
6409  */
6410  List_iterator<Item_field> it(fields);
6411  Item_field *item;
6412  const JOIN_TAB *first= field_tab->first_sj_inner_tab;
6413  const JOIN_TAB *last= field_tab->last_sj_inner_tab;
6414 
6415  while ((item= it++))
6416  {
6417  if (item->field->table->reginfo.join_tab >= first &&
6418  item->field->table->reginfo.join_tab <= last)
6419  {
6420  return item;
6421  }
6422  }
6423  }
6424  else
6425  {
6426  /*
6427  The field is not in a materialized semijoin nest. We can return
6428  the first field in the multiple equality.
6429 
6430  Example: suppose we have a join_tab order with MaterializeLookup:
6431 
6432  ot1 ot2 <subquery> SJM(it1 it2)
6433 
6434  Here we should always pick the first field in the multiple equality,
6435  as this will be present before all other dependent fields.
6436 
6437  Example: suppose we have a join_tab order with MaterializeScan:
6438 
6439  <subquery> ot1 ot2 SJM(it1 it2)
6440 
6441  and equality <subquery>.col = ot2.col = ot1.col = it2.col.
6442 
6443  When looking for best substitute for ot2.col, we should pick
6444  <subquery>.col, because column values from the inner materialized tables
6445  are copied to the temporary table <subquery>, and when we run the scan,
6446  field values are read into this table's field buffers.
6447  */
6448  return fields.head();
6449  }
6450  DBUG_ASSERT(FALSE); // Should never get here.
6451  return NULL;
6452 }
6453 
6467 {
6468  TABLE_LIST *sj_nest= reinterpret_cast<TABLE_LIST *>(arg);
6469  List_iterator<Item_field> it(fields);
6470  List<Item_field> added_fields;
6471  Item_field *item;
6472  // Iterate over the fields in the multiple equality
6473  while ((item= it++))
6474  {
6475  // Skip fields that do not come from materialized subqueries
6476  const JOIN_TAB *tab= item->field->table->reginfo.join_tab;
6477  if (!tab || !sj_is_materialize_strategy(tab->get_sj_strategy()))
6478  continue;
6479 
6480  // Iterate over the fields selected from the subquery
6481  List_iterator<Item> mit(sj_nest->nested_join->sj_inner_exprs);
6482  Item *existing;
6483  uint fieldno= 0;
6484  while ((existing= mit++))
6485  {
6486  if (existing->real_item()->eq(item, false))
6487  added_fields.push_back(sj_nest->nested_join->sjm.mat_fields[fieldno]);
6488  fieldno++;
6489  }
6490  }
6491  fields.concat(&added_fields);
6492 
6493  return this;
6494 }
6495 
6508 {
6509  TABLE_LIST *sj_nest= reinterpret_cast<TABLE_LIST *>(arg);
6510 
6511  // Iterate over the fields selected from the subquery
6512  List_iterator<Item> mit(sj_nest->nested_join->sj_inner_exprs);
6513  Item *existing;
6514  uint fieldno= 0;
6515  while ((existing= mit++))
6516  {
6517  if (existing->real_item()->eq(args[1], false) &&
6518  (args[0]->used_tables() & ~sj_nest->sj_inner_tables))
6519  current_thd->change_item_tree(args+1,
6520  sj_nest->nested_join->sjm.mat_fields[fieldno]);
6521  fieldno++;
6522  }
6523  return this;
6524 }