MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
item_subselect.cc
Go to the documentation of this file.
1 /* Copyright (c) 2002, 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 Foundation,
14  51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */
15 
27 #include "sql_priv.h"
28 /*
29  It is necessary to include set_var.h instead of item.h because there
30  are dependencies on include order for set_var.h and item.h. This
31  will be resolved later.
32 */
33 #include "sql_class.h" // set_var.h: THD
34 #include "set_var.h"
35 #include "sql_select.h"
36 #include "opt_trace.h"
37 #include "sql_parse.h" // check_stack_overrun
38 #include "sql_derived.h" // mysql_derived_create, ...
39 #include "debug_sync.h"
40 #include "sql_test.h"
41 #include "sql_join_buffer.h" // JOIN_CACHE
42 #include "sql_optimizer.h" // JOIN
43 #include "opt_explain_format.h"
44 
45 Item_subselect::Item_subselect():
46  Item_result_field(), value_assigned(0), traced_before(false),
47  substitution(NULL), in_cond_of_tab(INT_MIN), engine(NULL), old_engine(NULL),
48  used_tables_cache(0), have_to_be_excluded(0), const_item_cache(1),
49  engine_changed(false), changed(false)
50 {
51  with_subselect= 1;
52  reset();
53  /*
54  Item value is NULL if select_result_interceptor didn't change this value
55  (i.e. some rows will be found returned)
56  */
57  null_value= TRUE;
58 }
59 
60 
61 void Item_subselect::init(st_select_lex *select_lex,
62  select_result_interceptor *result)
63 {
64  /*
65  Please see Item_singlerow_subselect::invalidate_and_restore_select_lex(),
66  which depends on alterations to the parse tree implemented here.
67  */
68 
69  DBUG_ENTER("Item_subselect::init");
70  DBUG_PRINT("enter", ("select_lex: 0x%lx", (long) select_lex));
71  unit= select_lex->master_unit();
72 
73  if (unit->item)
74  {
75  /*
76  Item can be changed in JOIN::prepare while engine in JOIN::optimize
77  => we do not copy old_engine here
78  */
79  engine= unit->item->engine;
80  parsing_place= unit->item->parsing_place;
81  unit->item->engine= 0;
82  unit->item= this;
83  engine->change_result(this, result);
84  }
85  else
86  {
87  SELECT_LEX *outer_select= unit->outer_select();
88  /*
89  do not take into account expression inside aggregate functions because
90  they can access original table fields
91  */
92  parsing_place= (outer_select->in_sum_expr ?
93  NO_MATTER :
94  outer_select->parsing_place);
95  if (unit->is_union())
96  engine= new subselect_union_engine(unit, result, this);
97  else
98  engine= new subselect_single_select_engine(select_lex, result, this);
99  }
100  {
101  SELECT_LEX *upper= unit->outer_select();
102  if (upper->parsing_place == IN_HAVING)
103  upper->subquery_in_having= 1;
104  }
105  DBUG_VOID_RETURN;
106 }
107 
108 
109 void Item_subselect::cleanup()
110 {
111  DBUG_ENTER("Item_subselect::cleanup");
112  Item_result_field::cleanup();
113  if (old_engine)
114  {
115  if (engine)
116  {
117  engine->cleanup();
118  delete engine;
119  }
120  engine= old_engine;
121  old_engine= 0;
122  }
123  if (engine)
124  engine->cleanup();
125  reset();
126  value_assigned= 0;
127  traced_before= false;
128  in_cond_of_tab= INT_MIN;
129  DBUG_VOID_RETURN;
130 }
131 
132 
133 void Item_singlerow_subselect::cleanup()
134 {
135  DBUG_ENTER("Item_singlerow_subselect::cleanup");
136  value= 0; row= 0;
137  Item_subselect::cleanup();
138  DBUG_VOID_RETURN;
139 }
140 
141 
143 {
144  DBUG_ASSERT(exec_method == EXEC_EXISTS_OR_MAT ||
145  exec_method == EXEC_EXISTS);
146  /*
147  Change
148  SELECT expr1, expr2
149  to
150  SELECT 1,1
151  because EXISTS does not care about the selected expressions, only about
152  the existence of rows.
153 
154  If UNION, we have to modify the SELECT list of each SELECT in the
155  UNION, fortunately this function is indeed called for each SELECT_LEX.
156 
157  If this is a prepared statement, we must allow the next execution to use
158  materialization. So, we should back up the original SELECT list. If this
159  is a UNION, this means backing up the N original SELECT lists. To
160  avoid this constraint, we change the SELECT list only if this is not a
161  prepared statement.
162  */
163  if (unit->thd->stmt_arena->is_conventional()) // not prepared stmt
164  {
165  uint cnt= select_lex->item_list.elements;
166  select_lex->item_list.empty();
167  for(; cnt > 0; cnt--)
168  select_lex->item_list.push_back(new Item_int(NAME_STRING("Not_used"),
169  (longlong) 1,
170  MY_INT64_NUM_DECIMAL_DIGITS));
171  Opt_trace_context * const trace= &unit->thd->opt_trace;
172  OPT_TRACE_TRANSFORM(trace, oto0, oto1,
173  select_lex->select_number,
174  "IN (SELECT)", "EXISTS (CORRELATED SELECT)");
175  oto1.add("put_1_in_SELECT_list", true);
176  }
177  /*
178  Note that if the subquery is "SELECT1 UNION SELECT2" then this is not
179  working optimally (Bug#14215895).
180  */
181  unit->global_parameters->select_limit= new Item_int((int32) 1);
182  unit->set_limit(unit->global_parameters);
183 
184  select_lex->join->allow_outer_refs= true; // for JOIN::set_prefix_tables()
185  exec_method= EXEC_EXISTS;
186  return false;
187 }
188 
189 
190 
191 /*
192  Removes every predicate injected by IN->EXISTS.
193 
194  This function is different from others:
195  - it wants to remove all traces of IN->EXISTS (for
196  materialization)
197  - remove_subq_pushed_predicates() and remove_additional_cond() want to
198  remove only the conditions of IN->EXISTS which index lookup already
199  satisfies (they are just an optimization).
200 
201  Code reading suggests that remove_additional_cond() is equivalent to
202  "if in_subs->left_expr->cols()==1 then remove_in2exists_conds(where)"
203  but that would still not fix Bug#13915291 of remove_additional_cond().
204 
205  @param conds condition
206  @returns new condition
207 */
208 Item *Item_in_subselect::remove_in2exists_conds(Item* conds)
209 {
210  if (conds->created_by_in2exists())
211  return NULL;
212  if (conds->type() != Item::COND_ITEM)
213  return conds;
214  Item_cond *cnd= static_cast<Item_cond *>(conds);
215  /*
216  If IN->EXISTS has added something to 'conds', cnd must be AND list and we
217  must inspect each member.
218  */
219  if (cnd->functype() != Item_func::COND_AND_FUNC)
220  return conds;
221  List_iterator<Item> li(*(cnd->argument_list()));
222  Item *item;
223  while ((item= li++))
224  {
225  // remove() does not invalidate iterator.
226  if (item->created_by_in2exists())
227  li.remove();
228  }
229  switch (cnd->argument_list()->elements)
230  {
231  case 0:
232  return NULL;
233  case 1: // AND(x) is the same as x, return x
234  return cnd->argument_list()->head();
235  default: // otherwise return AND
236  return conds;
237  }
238 }
239 
240 
242 {
243  DBUG_ASSERT(exec_method == EXEC_EXISTS_OR_MAT);
244  DBUG_ASSERT(engine->engine_type() == subselect_engine::SINGLE_SELECT_ENGINE);
245  THD * const thd= unit->thd;
246  subselect_single_select_engine *old_engine_derived=
247  static_cast<subselect_single_select_engine*>(engine);
248 
249  DBUG_ASSERT(join == old_engine_derived->join);
250  // No UNION in materialized subquery so this holds:
251  DBUG_ASSERT(join->select_lex == unit->first_select());
252  DBUG_ASSERT(join->unit == unit);
253  DBUG_ASSERT(unit->global_parameters->select_limit == NULL);
254 
255  exec_method= EXEC_MATERIALIZATION;
256 
257  /*
258  We need to undo several changes which IN->EXISTS had done. But we first
259  back them up, so that the next execution of the statement is allowed to
260  choose IN->EXISTS.
261  */
262 
263  /*
264  Undo conditions injected by IN->EXISTS.
265  Condition guards, which those conditions maybe used, are not needed
266  anymore.
267  Subquery becomes 'not dependent' again, as before IN->EXISTS.
268  */
269  if (join->conds)
270  join->conds= remove_in2exists_conds(join->conds);
271  if (join->having)
272  join->having= remove_in2exists_conds(join->having);
273  DBUG_ASSERT(!originally_dependent());
274  join->select_lex->uncacheable&= ~UNCACHEABLE_DEPENDENT;
275  /*
276  IN->EXISTS uses master_unit(); however, as we cannot have a UNION here,
277  'unit' must be correct too.
278  */
279  DBUG_ASSERT(unit == join->select_lex->master_unit());
280  unit->uncacheable&= ~UNCACHEABLE_DEPENDENT;
281 
282  OPT_TRACE_TRANSFORM(&thd->opt_trace, oto0, oto1,
283  old_engine_derived->join->select_lex->select_number,
284  "IN (SELECT)", "materialization");
285  oto1.add("chosen", true);
286 
287  subselect_hash_sj_engine * const new_engine=
288  new subselect_hash_sj_engine(thd, this, old_engine_derived);
289  if (!new_engine)
290  return true;
291  if (new_engine->setup(unit->get_unit_column_types()))
292  {
293  /*
294  For some reason we cannot use materialization for this IN predicate.
295  Delete all materialization-related objects, and return error.
296  */
297  delete new_engine;
298  return true;
299  }
300  if (change_engine(new_engine))
301  return true;
302 
303  join->allow_outer_refs= false; // for JOIN::set_prefix_tables()
304  return false;
305 }
306 
307 
308 void Item_in_subselect::cleanup()
309 {
310  DBUG_ENTER("Item_in_subselect::cleanup");
311  if (left_expr_cache)
312  {
313  left_expr_cache->delete_elements();
314  delete left_expr_cache;
315  left_expr_cache= NULL;
316  }
317  left_expr_cache_filled= false;
318  need_expr_cache= TRUE;
319 
320  switch(exec_method)
321  {
323  unit->first_select()->uncacheable|= UNCACHEABLE_DEPENDENT;
324  unit->uncacheable|= UNCACHEABLE_DEPENDENT;
325  // fall through
326  case EXEC_EXISTS:
327  /*
328  Back to EXISTS_OR_MAT, so that next execution of this statement can
329  choose between the two.
330  */
331  unit->global_parameters->select_limit= NULL;
332  exec_method= EXEC_EXISTS_OR_MAT;
333  break;
334  default:
335  break;
336  }
337 
338  Item_subselect::cleanup();
339  DBUG_VOID_RETURN;
340 }
341 
342 Item_subselect::~Item_subselect()
343 {
344  delete engine;
345 }
346 
347 Item_subselect::trans_res
348 Item_subselect::select_transformer(JOIN *join)
349 {
350  DBUG_ENTER("Item_subselect::select_transformer");
351  DBUG_RETURN(RES_OK);
352 }
353 
354 
355 bool Item_subselect::fix_fields(THD *thd, Item **ref)
356 {
357  char const *save_where= thd->where;
358  uint8 uncacheable;
359  bool res;
360 
361  DBUG_ASSERT(fixed == 0);
362  /*
363  Pointers to THD must match. unit::thd may vary over the lifetime of the
364  item (for example triggers, and thus their Item-s, are in a cache shared
365  by all connections), but reinit_stmt_before_use() keeps it up-to-date,
366  which we check here. subselect_union_engine functions also do sanity
367  checks.
368  */
369  DBUG_ASSERT(thd == unit->thd);
370 #ifndef DBUG_OFF
371  // Engine accesses THD via its 'item' pointer, check it:
372  DBUG_ASSERT(engine->get_item() == this);
373 #endif
374 
375  engine->set_thd_for_result();
376 
377  if (check_stack_overrun(thd, STACK_MIN_SIZE, (uchar*)&res))
378  return TRUE;
379 
380  if (!(res= engine->prepare()))
381  {
382  // all transformation is done (used by prepared statements)
383  changed= 1;
384 
385  /*
386  Substitute the current item with an Item_in_optimizer that was
387  created by Item_in_subselect::select_in_like_transformer and
388  call fix_fields for the substituted item which in turn calls
389  engine->prepare for the subquery predicate.
390  */
391  if (substitution)
392  {
393  int ret= 0;
394 
395  // did we changed top item of WHERE condition
396  if (unit->outer_select()->where == (*ref))
397  unit->outer_select()->where= substitution; // correct WHERE for PS
398  else if (unit->outer_select()->having == (*ref))
399  unit->outer_select()->having= substitution; // correct HAVING for PS
400 
401  (*ref)= substitution;
402  substitution->item_name= item_name;
403  if (have_to_be_excluded)
404  engine->exclude();
405  substitution= 0;
406  thd->where= "checking transformed subquery";
407  if (!(*ref)->fixed)
408  ret= (*ref)->fix_fields(thd, ref);
409  thd->where= save_where;
410  return ret;
411  }
412  // Is it one field subselect?
413  if (engine->cols() > max_columns)
414  {
415  my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
416  return TRUE;
417  }
418  fix_length_and_dec();
419  }
420  else
421  goto err;
422 
423  if ((uncacheable= engine->uncacheable()))
424  {
425  const_item_cache= 0;
426  if (uncacheable & UNCACHEABLE_RAND)
427  used_tables_cache|= RAND_TABLE_BIT;
428  }
429  fixed= 1;
430 
431 err:
432  thd->where= save_where;
433  return res;
434 }
435 
436 
444  Item_processor processor,
445  bool walk_subquery,
446  uchar *argument)
447 {
448  TABLE_LIST *table;
449  List_iterator<TABLE_LIST> li(*tables);
450 
451  while ((table= li++))
452  {
453  if (table->join_cond() &&
454  table->join_cond()->walk(processor, walk_subquery, argument))
455  return true;
456 
457  if (table->nested_join != NULL &&
458  walk_join_condition(&table->nested_join->join_list, processor,
459  walk_subquery, argument))
460  return true;
461  }
462  return false;
463 }
464 
465 
469 bool Item_subselect::walk_body(Item_processor processor, bool walk_subquery,
470  uchar *argument)
471 {
472  if (walk_subquery)
473  {
474  for (SELECT_LEX *lex= unit->first_select(); lex; lex= lex->next_select())
475  {
476  List_iterator<Item> li(lex->item_list);
477  Item *item;
478  ORDER *order;
479 
480  while ((item=li++))
481  {
482  if (item->walk(processor, walk_subquery, argument))
483  return true;
484  }
485 
486  if (lex->join_list != NULL &&
487  walk_join_condition(lex->join_list, processor, walk_subquery, argument))
488  return true;
489 
490  if (lex->where && (lex->where)->walk(processor, walk_subquery, argument))
491  return true;
492 
493  for (order= lex->group_list.first ; order; order= order->next)
494  {
495  if ((*order->item)->walk(processor, walk_subquery, argument))
496  return true;
497  }
498 
499  if (lex->having && (lex->having)->walk(processor, walk_subquery,
500  argument))
501  return true;
502 
503  for (order= lex->order_list.first ; order; order= order->next)
504  {
505  if ((*order->item)->walk(processor, walk_subquery, argument))
506  return true;
507  }
508  }
509  }
510  return (this->*processor)(argument);
511 }
512 
513 bool Item_subselect::walk(Item_processor processor, bool walk_subquery,
514  uchar *argument)
515 {
516  return walk_body(processor, walk_subquery, argument);
517 }
518 
519 
538 {
540  *reinterpret_cast<Explain_subquery_marker **>(arg);
541 
542  if (m->type == CTX_WHERE)
543  {
544  /*
545  A subquery in the WHERE clause may be associated with a few JOIN_TABs
546  simultaneously.
547  */
548  if (unit->explain_marker == CTX_NONE)
549  unit->explain_marker= CTX_WHERE;
550  else
551  DBUG_ASSERT(unit->explain_marker == CTX_WHERE);
553  return false;
554  }
555 
556  if (m->type == CTX_HAVING && unit->explain_marker == CTX_WHERE)
557  {
558  /*
559  This subquery was in SELECT list of outer subquery transformed
560  with IN->EXISTS, so is referenced by WHERE and HAVING;
561  see Item_in_subselect::single_value_in_to_exists_transformer()
562  */
563  return false;
564  }
565 
566  if (unit->explain_marker == CTX_NONE)
567  goto overwrite;
568 
569  if (unit->explain_marker == m->type)
570  return false;
571 
572  /*
573  GROUP BY subqueries may be listed in different item trees simultaneously:
574  1) in GROUP BY items,
575  2) in ORDER BY items and/or
576  3) in SELECT list.
577  If such a subquery in the SELECT list, we mark the subquery as if it
578  belongs to SELECT list, otherwise we mark it as "GROUP BY" subquery.
579 
580  ORDER BY subqueries may be listed twice in SELECT list and ORDER BY list.
581  In this case we mark such a subquery as "SELECT list" subquery.
582  */
583  if (unit->explain_marker == CTX_GROUP_BY_SQ && m->type == CTX_ORDER_BY_SQ)
584  return false;
585  if (unit->explain_marker == CTX_ORDER_BY_SQ && m->type == CTX_GROUP_BY_SQ)
586  goto overwrite;
587 
588  if (unit->explain_marker == CTX_SELECT_LIST &&
589  (m->type == CTX_ORDER_BY_SQ || m->type == CTX_GROUP_BY_SQ))
590  return false;
591  if ((unit->explain_marker == CTX_ORDER_BY_SQ ||
592  unit->explain_marker == CTX_GROUP_BY_SQ) && m->type == CTX_SELECT_LIST)
593  goto overwrite;
594 
595  DBUG_ASSERT(!"Unexpected combination of item trees!");
596  return false;
597 
598 overwrite:
599  unit->explain_marker= m->type;
600  return false;
601 }
602 
603 
604 bool Item_subselect::exec()
605 {
606  DBUG_ENTER("Item_subselect::exec");
607  /*
608  Do not execute subselect in case of a fatal error
609  or if the query has been killed.
610  */
611  THD * const thd= unit->thd;
612  if (thd->is_error() || thd->killed)
613  DBUG_RETURN(true);
614 
615  DBUG_ASSERT(!thd->lex->context_analysis_only);
616  /*
617  Simulate a failure in sub-query execution. Used to test e.g.
618  out of memory or query being killed conditions.
619  */
620  DBUG_EXECUTE_IF("subselect_exec_fail", DBUG_RETURN(true););
621 
622  /*
623  Disable tracing of subquery execution if
624  1) this is not the first time the subselect is executed, and
625  2) REPEATED_SUBSELECT is disabled
626  */
627 #ifdef OPTIMIZER_TRACE
628  Opt_trace_context * const trace= &thd->opt_trace;
629  const bool disable_trace=
630  traced_before &&
631  !trace->feature_enabled(Opt_trace_context::REPEATED_SUBSELECT);
632  Opt_trace_disable_I_S disable_trace_wrapper(trace, disable_trace);
633  traced_before= true;
634 
635  Opt_trace_object trace_wrapper(trace);
636  Opt_trace_object trace_exec(trace, "subselect_execution");
637  trace_exec.add_select_number(unit->first_select()->select_number);
638  Opt_trace_array trace_steps(trace, "steps");
639 #endif
640 
641  bool res= engine->exec();
642 
643  if (engine_changed)
644  {
645  engine_changed= 0;
646  res= exec();
647  DBUG_RETURN(res);
648  }
649  DBUG_RETURN(res);
650 }
651 
652 
666 void Item_subselect::fix_after_pullout(st_select_lex *parent_select,
667  st_select_lex *removed_select)
668 
669 {
670  /* Clear usage information for this subquery predicate object */
671  used_tables_cache= 0;
672 
673  /*
674  Go through all query specification objects of the subquery and re-resolve
675  all relevant expressions belonging to them.
676  */
677  for (SELECT_LEX *sel= unit->first_select(); sel; sel= sel->next_select())
678  {
679  if (sel->where)
680  sel->where->fix_after_pullout(parent_select, removed_select);
681 
682  if (sel->having)
683  sel->having->fix_after_pullout(parent_select, removed_select);
684 
685  List_iterator<Item> li(sel->item_list);
686  Item *item;
687  while ((item=li++))
688  item->fix_after_pullout(parent_select, removed_select);
689 
690  /*
691  No need to call fix_after_pullout() for outer-join conditions, as these
692  cannot have outer references.
693  */
694 
695  /* Re-resolve ORDER BY and GROUP BY fields */
696 
697  for (ORDER *order= (ORDER*) sel->order_list.first;
698  order;
699  order= order->next)
700  (*order->item)->fix_after_pullout(parent_select, removed_select);
701 
702  for (ORDER *group= (ORDER*) sel->group_list.first;
703  group;
704  group= group->next)
705  (*group->item)->fix_after_pullout(parent_select, removed_select);
706  }
707 }
708 
709 bool Item_in_subselect::walk(Item_processor processor, bool walk_subquery,
710  uchar *argument)
711 {
712  if (left_expr->walk(processor, walk_subquery, argument))
713  return true;
714  /*
715  Cannot call "Item_subselect::walk(...)" because with gcc 4.1
716  Item_in_subselect::walk() was incorrectly called instead.
717  Using Item_subselect::walk_body() instead is a workaround.
718  */
719  return walk_body(processor, walk_subquery, argument);
720 }
721 
722 /*
723  Compute the IN predicate if the left operand's cache changed.
724 */
725 
726 bool Item_in_subselect::exec()
727 {
728  DBUG_ENTER("Item_in_subselect::exec");
729  DBUG_ASSERT(exec_method != EXEC_MATERIALIZATION ||
730  (exec_method == EXEC_MATERIALIZATION &&
731  engine->engine_type() == subselect_engine::HASH_SJ_ENGINE));
732  /*
733  Initialize the cache of the left predicate operand. This has to be done as
734  late as now, because Cached_item directly contains a resolved field (not
735  an item, and in some cases (when temp tables are created), these fields
736  end up pointing to the wrong field. One solution is to change Cached_item
737  to not resolve its field upon creation, but to resolve it dynamically
738  from a given Item_ref object.
739  Do not init the cache if a previous execution decided that it is not needed.
740  TODO: the cache should be applied conditionally based on:
741  - rules - e.g. only if the left operand is known to be ordered, and/or
742  - on a cost-based basis, that takes into account the cost of a cache
743  lookup, the cache hit rate, and the savings per cache hit.
744  */
745  if (need_expr_cache && !left_expr_cache &&
746  exec_method == EXEC_MATERIALIZATION &&
748  DBUG_RETURN(TRUE);
749 
750  if (left_expr_cache != NULL)
751  {
752  const int result= test_if_item_cache_changed(*left_expr_cache);
753  if (left_expr_cache_filled && // cache was previously filled
754  result < 0) // new value is identical to previous cached value
755  {
756  /*
757  We needn't do a full execution, can just reuse "value", "was_null",
758  "null_value" of the previous execution.
759  */
760  DBUG_RETURN(false);
761  }
763  }
764 
765  null_value= was_null= false;
766  const bool retval= Item_subselect::exec();
767  DBUG_RETURN(retval);
768 }
769 
770 
771 Item::Type Item_subselect::type() const
772 {
773  return SUBSELECT_ITEM;
774 }
775 
776 
777 void Item_subselect::fix_length_and_dec()
778 {
779  engine->fix_length_and_dec(0);
780 }
781 
782 
783 table_map Item_subselect::used_tables() const
784 {
785  return (table_map) (engine->uncacheable() ? used_tables_cache : 0L);
786 }
787 
788 
789 bool Item_subselect::const_item() const
790 {
791  if (unit->thd->lex->context_analysis_only)
792  return false;
793  /* Not constant until tables are locked. */
794  if (!unit->thd->lex->is_query_tables_locked())
795  return false;
796  return const_item_cache;
797 }
798 
799 Item *Item_subselect::get_tmp_table_item(THD *thd_arg)
800 {
801  if (!with_sum_func && !const_item())
802  return new Item_field(result_field);
803  return copy_or_same(thd_arg);
804 }
805 
806 void Item_subselect::update_used_tables()
807 {
808  if (!engine->uncacheable())
809  {
810  // did all used tables become static?
811  if (!(used_tables_cache & ~engine->upper_select_const_tables()))
812  const_item_cache= 1;
813  }
814 }
815 
816 
817 void Item_subselect::print(String *str, enum_query_type query_type)
818 {
819  if (engine)
820  {
821  str->append('(');
822  engine->print(str, query_type);
823  str->append(')');
824  }
825  else
826  str->append("(...)");
827 }
828 
829 
830 Item_singlerow_subselect::Item_singlerow_subselect(st_select_lex *select_lex)
831  :Item_subselect(), value(0), no_rows(false)
832 {
833  DBUG_ENTER("Item_singlerow_subselect::Item_singlerow_subselect");
834  init(select_lex, new select_singlerow_subselect(this));
835  maybe_null= 1;
836  max_columns= UINT_MAX;
837  DBUG_VOID_RETURN;
838 }
839 
840 st_select_lex *
842 {
843  DBUG_ENTER("Item_singlerow_subselect::invalidate_and_restore_select_lex");
844  st_select_lex *result= unit->first_select();
845 
846  DBUG_ASSERT(result);
847 
848  /*
849  This code restore the parse tree in it's state before the execution of
850  Item_singlerow_subselect::Item_singlerow_subselect(),
851  and in particular decouples this object from the SELECT_LEX,
852  so that the SELECT_LEX can be used with a different flavor
853  or Item_subselect instead, as part of query rewriting.
854  */
855  unit->item= NULL;
856 
857  DBUG_RETURN(result);
858 }
859 
860 Item_maxmin_subselect::Item_maxmin_subselect(THD *thd_param,
861  Item_subselect *parent,
862  st_select_lex *select_lex,
863  bool max_arg,
864  bool ignore_nulls)
865  :Item_singlerow_subselect(), was_values(false)
866 {
867  DBUG_ENTER("Item_maxmin_subselect::Item_maxmin_subselect");
868  max= max_arg;
869  init(select_lex, new select_max_min_finder_subselect(this, max_arg,
870  ignore_nulls));
871  max_columns= 1;
872  maybe_null= 1;
873  max_columns= 1;
874 
875  /*
876  Following information was collected during performing fix_fields()
877  of Items belonged to subquery, which will be not repeated
878  */
879  used_tables_cache= parent->get_used_tables_cache();
880  const_item_cache= parent->get_const_item_cache();
881 
882  DBUG_VOID_RETURN;
883 }
884 
885 void Item_maxmin_subselect::cleanup()
886 {
887  DBUG_ENTER("Item_maxmin_subselect::cleanup");
888  Item_singlerow_subselect::cleanup();
889 
890  was_values= false;
891  DBUG_VOID_RETURN;
892 }
893 
894 
895 void Item_maxmin_subselect::print(String *str, enum_query_type query_type)
896 {
897  str->append(max?"<max>":"<min>", 5);
898  Item_singlerow_subselect::print(str, query_type);
899 }
900 
901 
902 void Item_singlerow_subselect::reset()
903 {
904  null_value= TRUE;
905  if (value)
906  value->null_value= TRUE;
907 }
908 
909 
920 Item_subselect::trans_res
922 {
923  DBUG_ENTER("Item_singlerow_subselect::select_transformer");
924  if (changed)
925  DBUG_RETURN(RES_OK);
926 
927  SELECT_LEX *select_lex= join->select_lex;
928  THD * const thd= unit->thd;
929  Query_arena *arena= thd->stmt_arena;
930 
931  if (!select_lex->master_unit()->is_union() &&
932  !select_lex->table_list.elements &&
933  select_lex->item_list.elements == 1 &&
934  !select_lex->item_list.head()->with_sum_func &&
935  /*
936  We cant change name of Item_field or Item_ref, because it will
937  prevent it's correct resolving, but we should save name of
938  removed item => we do not make optimization if top item of
939  list is field or reference.
940  TODO: solve above problem
941  */
942  !(select_lex->item_list.head()->type() == FIELD_ITEM ||
943  select_lex->item_list.head()->type() == REF_ITEM) &&
944  !join->conds && !join->having &&
945  /*
946  switch off this optimization for prepare statement,
947  because we do not rollback this changes
948  TODO: make rollback for it, or special name resolving mode in 5.0.
949  */
950  !arena->is_stmt_prepare_or_first_sp_execute()
951  )
952  {
953 
954  have_to_be_excluded= 1;
955  if (thd->lex->describe)
956  {
957  char warn_buff[MYSQL_ERRMSG_SIZE];
958  sprintf(warn_buff, ER(ER_SELECT_REDUCED), select_lex->select_number);
959  push_warning(thd, Sql_condition::WARN_LEVEL_NOTE,
960  ER_SELECT_REDUCED, warn_buff);
961  }
962  substitution= select_lex->item_list.head();
963  /*
964  as far as we moved content to upper level, field which depend of
965  'upper' select is not really dependent => we remove this dependence
966  */
967  substitution->walk(&Item::remove_dependence_processor, 0,
968  (uchar *) select_lex->outer_select());
969  DBUG_RETURN(RES_REDUCE);
970  }
971  DBUG_RETURN(RES_OK);
972 }
973 
974 
975 void Item_singlerow_subselect::store(uint i, Item *item)
976 {
977  row[i]->store(item);
978  row[i]->cache_value();
979 }
980 
981 enum Item_result Item_singlerow_subselect::result_type() const
982 {
983  return engine->type();
984 }
985 
986 /*
987  Don't rely on the result type to calculate field type.
988  Ask the engine instead.
989 */
990 enum_field_types Item_singlerow_subselect::field_type() const
991 {
992  return engine->field_type();
993 }
994 
995 void Item_singlerow_subselect::fix_length_and_dec()
996 {
997  if ((max_columns= engine->cols()) == 1)
998  {
999  engine->fix_length_and_dec(row= &value);
1000  }
1001  else
1002  {
1003  if (!(row= (Item_cache**) sql_alloc(sizeof(Item_cache*)*max_columns)))
1004  return;
1005  engine->fix_length_and_dec(row);
1006  value= *row;
1007  }
1008  unsigned_flag= value->unsigned_flag;
1009  /*
1010  If there are not tables in subquery then ability to have NULL value
1011  depends on SELECT list (if single row subquery have tables then it
1012  always can be NULL if there are not records fetched).
1013  */
1014  if (engine->no_tables())
1015  maybe_null= engine->may_be_null();
1016 }
1017 
1018 void Item_singlerow_subselect::no_rows_in_result()
1019 {
1020  /*
1021  This is only possible if we have a dependent subquery in the SELECT list
1022  and an aggregated outer query based on zero rows, which is an illegal query
1023  according to the SQL standard. ONLY_FULL_GROUP_BY rejects such queries.
1024  */
1025  if (unit->uncacheable & UNCACHEABLE_DEPENDENT)
1026  no_rows= true;
1027 }
1028 
1029 uint Item_singlerow_subselect::cols()
1030 {
1031  return engine->cols();
1032 }
1033 
1034 bool Item_singlerow_subselect::check_cols(uint c)
1035 {
1036  if (c != engine->cols())
1037  {
1038  my_error(ER_OPERAND_COLUMNS, MYF(0), c);
1039  return 1;
1040  }
1041  return 0;
1042 }
1043 
1044 bool Item_singlerow_subselect::null_inside()
1045 {
1046  for (uint i= 0; i < max_columns ; i++)
1047  {
1048  if (row[i]->null_value)
1049  return 1;
1050  }
1051  return 0;
1052 }
1053 
1054 void Item_singlerow_subselect::bring_value()
1055 {
1056  if (!exec() && assigned())
1057  null_value= 0;
1058  else
1059  reset();
1060 }
1061 
1062 double Item_singlerow_subselect::val_real()
1063 {
1064  DBUG_ASSERT(fixed == 1);
1065  if (!no_rows && !exec() && !value->null_value)
1066  {
1067  null_value= FALSE;
1068  return value->val_real();
1069  }
1070  else
1071  {
1072  reset();
1073  return 0;
1074  }
1075 }
1076 
1077 longlong Item_singlerow_subselect::val_int()
1078 {
1079  DBUG_ASSERT(fixed == 1);
1080  if (!no_rows && !exec() && !value->null_value)
1081  {
1082  null_value= FALSE;
1083  return value->val_int();
1084  }
1085  else
1086  {
1087  reset();
1088  return 0;
1089  }
1090 }
1091 
1092 String *Item_singlerow_subselect::val_str(String *str)
1093 {
1094  if (!no_rows && !exec() && !value->null_value)
1095  {
1096  null_value= FALSE;
1097  return value->val_str(str);
1098  }
1099  else
1100  {
1101  reset();
1102  return 0;
1103  }
1104 }
1105 
1106 
1107 my_decimal *Item_singlerow_subselect::val_decimal(my_decimal *decimal_value)
1108 {
1109  if (!no_rows && !exec() && !value->null_value)
1110  {
1111  null_value= FALSE;
1112  return value->val_decimal(decimal_value);
1113  }
1114  else
1115  {
1116  reset();
1117  return 0;
1118  }
1119 }
1120 
1121 
1122 bool Item_singlerow_subselect::get_date(MYSQL_TIME *ltime, uint fuzzydate)
1123 {
1124  if (!no_rows && !exec() && !value->null_value)
1125  {
1126  null_value= false;
1127  return value->get_date(ltime, fuzzydate);
1128  }
1129  else
1130  {
1131  reset();
1132  return true;
1133  }
1134 }
1135 
1136 
1137 bool Item_singlerow_subselect::get_time(MYSQL_TIME *ltime)
1138 {
1139  if (!no_rows && !exec() && !value->null_value)
1140  {
1141  null_value= false;
1142  return value->get_time(ltime);
1143  }
1144  else
1145  {
1146  reset();
1147  return true;
1148  }
1149 }
1150 
1151 
1153 {
1154  if (!no_rows && !exec() && !value->null_value)
1155  {
1156  null_value= FALSE;
1157  return value->val_bool();
1158  }
1159  else
1160  {
1161  reset();
1162  return 0;
1163  }
1164 }
1165 
1166 
1167 Item_exists_subselect::Item_exists_subselect(st_select_lex *select_lex):
1168  Item_subselect(), value(FALSE), exec_method(EXEC_UNSPECIFIED),
1169  sj_convert_priority(0), embedding_join_nest(NULL)
1170 {
1171  DBUG_ENTER("Item_exists_subselect::Item_exists_subselect");
1172  init(select_lex, new select_exists_subselect(this));
1173  max_columns= UINT_MAX;
1174  null_value= FALSE; //can't be NULL
1175  maybe_null= 0; //can't be NULL
1176  DBUG_VOID_RETURN;
1177 }
1178 
1179 
1180 void Item_exists_subselect::print(String *str, enum_query_type query_type)
1181 {
1182  str->append(STRING_WITH_LEN("exists"));
1183  Item_subselect::print(str, query_type);
1184 }
1185 
1186 
1187 bool Item_in_subselect::test_limit(st_select_lex_unit *unit_arg)
1188 {
1189  if (unit_arg->fake_select_lex &&
1190  unit_arg->fake_select_lex->test_limit())
1191  return(1);
1192 
1193  SELECT_LEX *sl= unit_arg->first_select();
1194  for (; sl; sl= sl->next_select())
1195  {
1196  if (sl->test_limit())
1197  return(1);
1198  }
1199  return(0);
1200 }
1201 
1202 Item_in_subselect::Item_in_subselect(Item * left_exp,
1203  st_select_lex *select_lex):
1204  Item_exists_subselect(), left_expr(left_exp), left_expr_cache(NULL),
1205  left_expr_cache_filled(false), need_expr_cache(TRUE), expr(NULL),
1206  optimizer(NULL), was_null(FALSE), abort_on_null(FALSE),
1207  in2exists_info(NULL), pushed_cond_guards(NULL), upper_item(NULL)
1208 {
1209  DBUG_ENTER("Item_in_subselect::Item_in_subselect");
1210  init(select_lex, new select_exists_subselect(this));
1211  max_columns= UINT_MAX;
1212  maybe_null= 1;
1213  reset();
1214  //if test_limit will fail then error will be reported to client
1215  test_limit(select_lex->master_unit());
1216  DBUG_VOID_RETURN;
1217 }
1218 
1219 Item_allany_subselect::Item_allany_subselect(Item * left_exp,
1220  chooser_compare_func_creator fc,
1221  st_select_lex *select_lex,
1222  bool all_arg)
1223  :Item_in_subselect(), func_creator(fc), all(all_arg)
1224 {
1225  DBUG_ENTER("Item_allany_subselect::Item_allany_subselect");
1226  left_expr= left_exp;
1227  func= func_creator(all_arg);
1228  init(select_lex, new select_exists_subselect(this));
1229  max_columns= 1;
1230  abort_on_null= 0;
1231  reset();
1232  //if test_limit will fail then error will be reported to client
1233  test_limit(select_lex->master_unit());
1234  DBUG_VOID_RETURN;
1235 }
1236 
1237 
1238 void Item_exists_subselect::fix_length_and_dec()
1239 {
1240  decimals= 0;
1241  max_length= 1;
1242  max_columns= engine->cols();
1243  if (exec_method == EXEC_EXISTS)
1244  {
1245  /*
1246  We need only 1 row to determine existence.
1247  Note that if the subquery is "SELECT1 UNION SELECT2" then this is not
1248  working optimally (Bug#14215895).
1249  */
1250  unit->global_parameters->select_limit= new Item_int((int32) 1);
1251  }
1252 }
1253 
1254 double Item_exists_subselect::val_real()
1255 {
1256  DBUG_ASSERT(fixed == 1);
1257  if (exec())
1258  {
1259  reset();
1260  return 0;
1261  }
1262  return (double) value;
1263 }
1264 
1265 longlong Item_exists_subselect::val_int()
1266 {
1267  DBUG_ASSERT(fixed == 1);
1268  if (exec())
1269  {
1270  reset();
1271  return 0;
1272  }
1273  return value;
1274 }
1275 
1276 
1291 {
1292  DBUG_ASSERT(fixed == 1);
1293  if (exec())
1294  reset();
1295  str->set((ulonglong)value,&my_charset_bin);
1296  return str;
1297 }
1298 
1299 
1314 {
1315  DBUG_ASSERT(fixed == 1);
1316  if (exec())
1317  reset();
1318  int2my_decimal(E_DEC_FATAL_ERROR, value, 0, decimal_value);
1319  return decimal_value;
1320 }
1321 
1322 
1324 {
1325  DBUG_ASSERT(fixed == 1);
1326  if (exec())
1327  {
1328  reset();
1329  return 0;
1330  }
1331  return value != 0;
1332 }
1333 
1334 
1335 double Item_in_subselect::val_real()
1336 {
1337  /*
1338  As far as Item_in_subselect called only from Item_in_optimizer this
1339  method should not be used
1340  */
1341  DBUG_ASSERT(0);
1342  DBUG_ASSERT(fixed == 1);
1343  if (exec())
1344  {
1345  reset();
1346  return 0;
1347  }
1348  if (was_null && !value)
1349  null_value= TRUE;
1350  return (double) value;
1351 }
1352 
1353 
1354 longlong Item_in_subselect::val_int()
1355 {
1356  /*
1357  As far as Item_in_subselect called only from Item_in_optimizer this
1358  method should not be used
1359  */
1360  DBUG_ASSERT(0);
1361  DBUG_ASSERT(fixed == 1);
1362  if (exec())
1363  {
1364  reset();
1365  return 0;
1366  }
1367  if (was_null && !value)
1368  null_value= TRUE;
1369  return value;
1370 }
1371 
1372 
1374 {
1375  /*
1376  As far as Item_in_subselect called only from Item_in_optimizer this
1377  method should not be used
1378  */
1379  DBUG_ASSERT(0);
1380  DBUG_ASSERT(fixed == 1);
1381  if (exec())
1382  {
1383  reset();
1384  return 0;
1385  }
1386  if (was_null && !value)
1387  {
1388  null_value= TRUE;
1389  return 0;
1390  }
1391  str->set((ulonglong)value, &my_charset_bin);
1392  return str;
1393 }
1394 
1395 
1397 {
1398  DBUG_ASSERT(fixed == 1);
1399  if (exec())
1400  {
1401  reset();
1402  return 0;
1403  }
1404  if (was_null && !value)
1405  null_value= TRUE;
1406  return value;
1407 }
1408 
1410 {
1411  /*
1412  As far as Item_in_subselect called only from Item_in_optimizer this
1413  method should not be used
1414  */
1415  DBUG_ASSERT(0);
1416  DBUG_ASSERT(fixed == 1);
1417  if (exec())
1418  {
1419  reset();
1420  return 0;
1421  }
1422  if (was_null && !value)
1423  null_value= TRUE;
1424  int2my_decimal(E_DEC_FATAL_ERROR, value, 0, decimal_value);
1425  return decimal_value;
1426 }
1427 
1428 
1429 /*
1430  Rewrite a single-column IN/ALL/ANY subselect
1431 
1432  SYNOPSIS
1433  Item_in_subselect::single_value_transformer()
1434  join Join object of the subquery (i.e. 'child' join).
1435  func Subquery comparison creator
1436 
1437  DESCRIPTION
1438  Rewrite a single-column subquery using rule-based approach. The subquery
1439 
1440  oe $cmp$ (SELECT ie FROM ... WHERE subq_where ... HAVING subq_having)
1441 
1442  First, try to convert the subquery to scalar-result subquery in one of
1443  the forms:
1444 
1445  - oe $cmp$ (SELECT MAX(...) ) // handled by Item_singlerow_subselect
1446  - oe $cmp$ <max>(SELECT ...) // handled by Item_maxmin_subselect
1447 
1448  If that fails, the subquery will be handled with class Item_in_optimizer.
1449  There are two possibilites:
1450  - If the subquery execution method is materialization, then the subquery is
1451  not transformed any further.
1452  - Otherwise the IN predicates is transformed into EXISTS by injecting
1453  equi-join predicates and possibly other helper predicates. For details
1454  see method single_value_in_like_transformer().
1455 
1456  RETURN
1457  RES_OK Either subquery was transformed, or appopriate
1458  predicates where injected into it.
1459  RES_REDUCE The subquery was reduced to non-subquery
1460  RES_ERROR Error
1461 */
1462 
1463 Item_subselect::trans_res
1464 Item_in_subselect::single_value_transformer(JOIN *join,
1465  Comp_creator *func)
1466 {
1467  SELECT_LEX *select_lex= join->select_lex;
1468  bool subquery_maybe_null= false;
1469  DBUG_ENTER("Item_in_subselect::single_value_transformer");
1470 
1471  /*
1472  Check that the right part of the subselect contains no more than one
1473  column. E.g. in SELECT 1 IN (SELECT * ..) the right part is (SELECT * ...)
1474  */
1475  // psergey: duplicated_subselect_card_check
1476  if (select_lex->item_list.elements > 1)
1477  {
1478  my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
1479  DBUG_RETURN(RES_ERROR);
1480  }
1481 
1482  THD * const thd= unit->thd;
1483 
1484  /*
1485  Check the nullability of the subquery. The subquery should return
1486  only one column, so we check the nullability of the first item in
1487  SELECT_LEX::item_list. In case the subquery is a union, check the
1488  nullability of the first item of each SELECT_LEX belonging to the
1489  union.
1490  */
1491  for (SELECT_LEX* lex= select_lex->master_unit()->first_select();
1492  lex != NULL && lex->master_unit() == select_lex->master_unit();
1493  lex= lex->next_select())
1494  if (lex->item_list.head()->maybe_null)
1495  subquery_maybe_null= true;
1496 
1497  /*
1498  If this is an ALL/ANY single-value subquery predicate, try to rewrite
1499  it with a MIN/MAX subquery.
1500 
1501  E.g. SELECT * FROM t1 WHERE b > ANY (SELECT a FROM t2) can be rewritten
1502  with SELECT * FROM t1 WHERE b > (SELECT MIN(a) FROM t2).
1503 
1504  A predicate may be transformed to use a MIN/MAX subquery if it:
1505  1. has a greater than/less than comparison operator, and
1506  2. is not correlated with the outer query, and
1507  3. UNKNOWN results are treated as FALSE, or can never be generated, and
1508  */
1509  if (!func->eqne_op() && // 1
1510  !select_lex->master_unit()->uncacheable && // 2
1511  (abort_on_null || (upper_item && upper_item->top_level()) || // 3
1512  (!left_expr->maybe_null && !subquery_maybe_null)))
1513  {
1514  if (substitution)
1515  {
1516  // It is second (third, ...) SELECT of UNION => All is done
1517  DBUG_RETURN(RES_OK);
1518  }
1519 
1520  Item *subs;
1521  if (!select_lex->group_list.elements &&
1522  !select_lex->having &&
1523  !select_lex->with_sum_func &&
1524  !(select_lex->next_select()) &&
1525  select_lex->table_list.elements &&
1526  !(substype() == ALL_SUBS && subquery_maybe_null))
1527  {
1528  OPT_TRACE_TRANSFORM(&thd->opt_trace, oto0, oto1,
1529  select_lex->select_number,
1530  "> ALL/ANY (SELECT)", "SELECT(MIN)");
1531  oto1.add("chosen", true);
1532  Item_sum_hybrid *item;
1533  nesting_map save_allow_sum_func;
1534  if (func->l_op())
1535  {
1536  /*
1537  (ALL && (> || =>)) || (ANY && (< || =<))
1538  for ALL condition is inverted
1539  */
1540  item= new Item_sum_max(join->ref_ptrs[0]);
1541  }
1542  else
1543  {
1544  /*
1545  (ALL && (< || =<)) || (ANY && (> || =>))
1546  for ALL condition is inverted
1547  */
1548  item= new Item_sum_min(join->ref_ptrs[0]);
1549  }
1550  if (upper_item)
1551  upper_item->set_sum_test(item);
1552  join->ref_ptrs[0]= item;
1553  {
1554  List_iterator<Item> it(select_lex->item_list);
1555  it++;
1556  it.replace(item);
1557  }
1558 
1559  DBUG_EXECUTE("where",
1560  print_where(item, "rewrite with MIN/MAX", QT_ORDINARY););
1561  if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY)
1562  {
1563  /*
1564  If the argument is a field, we assume that fix_fields() has
1565  tagged the select_lex with non_agg_field_used.
1566  We reverse that decision after this rewrite with MIN/MAX.
1567  */
1568  if (item->get_arg(0)->type() == Item::FIELD_ITEM)
1569  DBUG_ASSERT(select_lex->non_agg_field_used());
1570  select_lex->set_non_agg_field_used(false);
1571  }
1572 
1573  save_allow_sum_func= thd->lex->allow_sum_func;
1574  thd->lex->allow_sum_func|=
1575  (nesting_map)1 << thd->lex->current_select->nest_level;
1576  /*
1577  Item_sum_(max|min) can't substitute other item => we can use 0 as
1578  reference, also Item_sum_(max|min) can't be fixed after creation, so
1579  we do not check item->fixed
1580  */
1581  if (item->fix_fields(thd, 0))
1582  DBUG_RETURN(RES_ERROR);
1583  thd->lex->allow_sum_func= save_allow_sum_func;
1584  /* we added aggregate function => we have to change statistic */
1585  count_field_types(select_lex, &join->tmp_table_param, join->all_fields,
1586  0);
1587 
1588  subs= new Item_singlerow_subselect(select_lex);
1589  }
1590  else
1591  {
1592  OPT_TRACE_TRANSFORM(&thd->opt_trace, oto0, oto1,
1593  select_lex->select_number,
1594  "> ALL/ANY (SELECT)", "MIN (SELECT)");
1595  oto1.add("chosen", true);
1596  Item_maxmin_subselect *item;
1597  subs= item= new Item_maxmin_subselect(thd, this, select_lex, func->l_op(),
1598  substype()==ANY_SUBS);
1599  if (upper_item)
1600  upper_item->set_sub_test(item);
1601  }
1602  if (upper_item)
1603  upper_item->set_subselect(this);
1604  /*
1605  fix fields is already called for left expression.
1606  Note that real_item() should be used instead of
1607  original left expression because left_expr can be
1608  runtime created Ref item which is deleted at the end
1609  of the statement. Thus one of 'substitution' arguments
1610  can be broken in case of PS.
1611  */
1612  substitution= func->create(left_expr->real_item(), subs);
1613  DBUG_RETURN(RES_OK);
1614  }
1615 
1616  if (!substitution)
1617  {
1618  /* We're invoked for the 1st (or the only) SELECT in the subquery UNION */
1619  SELECT_LEX_UNIT *master_unit= select_lex->master_unit();
1620  substitution= optimizer;
1621 
1622  SELECT_LEX *current= thd->lex->current_select;
1623 
1624  thd->lex->current_select= current->outer_select();
1625  //optimizer never use Item **ref => we can pass 0 as parameter
1626  if (!optimizer || optimizer->fix_left(thd, 0))
1627  {
1628  thd->lex->current_select= current;
1629  DBUG_RETURN(RES_ERROR);
1630  }
1631  thd->lex->current_select= current;
1632 
1633  /* We will refer to upper level cache array => we have to save it for SP */
1634  optimizer->keep_top_level_cache();
1635 
1636  /*
1637  As far as Item_ref_in_optimizer do not substitute itself on fix_fields
1638  we can use same item for all selects.
1639  */
1640  Item_ref *const left=
1641  new Item_direct_ref(&select_lex->context, (Item**)optimizer->get_cache(),
1642  (char *)"<no matter>", (char *)in_left_expr_name);
1643  if (left == NULL)
1644  DBUG_RETURN(RES_ERROR);
1645 
1646  // Make the left expression "outer" relative to the subquery
1647  if (!left_expr->const_item())
1648  left->depended_from= select_lex->outer_select();
1649 
1650  expr= left;
1651 
1652  DBUG_ASSERT(in2exists_info == NULL);
1653  in2exists_info= new In2exists_info;
1654  in2exists_info->originally_dependent=
1655  master_unit->uncacheable & UNCACHEABLE_DEPENDENT;
1656  master_unit->uncacheable|= UNCACHEABLE_DEPENDENT;
1657  }
1658 
1659  if (!abort_on_null && left_expr->maybe_null && !pushed_cond_guards)
1660  {
1661  if (!(pushed_cond_guards= (bool*)join->thd->alloc(sizeof(bool))))
1662  DBUG_RETURN(RES_ERROR);
1663  pushed_cond_guards[0]= TRUE;
1664  }
1665 
1666  /* Perform the IN=>EXISTS transformation. */
1667  const trans_res retval= single_value_in_to_exists_transformer(join, func);
1668  DBUG_RETURN(retval);
1669 }
1670 
1671 
1711 Item_subselect::trans_res
1713 {
1714  SELECT_LEX *select_lex= join->select_lex;
1715  THD * const thd= unit->thd;
1716  DBUG_ENTER("Item_in_subselect::single_value_in_to_exists_transformer");
1717 
1718  OPT_TRACE_TRANSFORM(&thd->opt_trace, oto0, oto1, select_lex->select_number,
1719  "IN (SELECT)", "EXISTS (CORRELATED SELECT)");
1720  oto1.add("chosen", true);
1721 
1722  select_lex->uncacheable|= UNCACHEABLE_DEPENDENT;
1723  in2exists_info->added_to_where= false;
1724 
1725  if (join->having || select_lex->with_sum_func ||
1726  select_lex->group_list.elements)
1727  {
1728  bool tmp;
1729  Item_bool_func *item= func->create(expr,
1730  new Item_ref_null_helper(&select_lex->context,
1731  this,
1732  &join->ref_ptrs[0],
1733  (char *)"<ref>",
1734  this->full_name()));
1735  item->set_created_by_in2exists();
1736  if (!abort_on_null && left_expr->maybe_null)
1737  {
1738  /*
1739  We can encounter "NULL IN (SELECT ...)". Wrap the added condition
1740  within a trig_cond.
1741  */
1742  item= new Item_func_trig_cond(item, get_cond_guard(0), NULL,
1744  OUTER_FIELD_IS_NOT_NULL);
1745  item->set_created_by_in2exists();
1746  }
1747 
1748  /*
1749  AND and comparison functions can't be changed during fix_fields()
1750  we can assign select_lex->having here, and pass 0 as last
1751  argument (reference) to fix_fields()
1752  */
1753  select_lex->having= join->having= and_items(join->having, item);
1754  if (join->having == item)
1755  item->item_name.set(in_having_cond);
1756  select_lex->having->top_level_item();
1757  select_lex->having_fix_field= 1;
1758  /*
1759  we do not check join->having->fixed, because Item_and (from and_items)
1760  or comparison function (from func->create) can't be fixed after creation
1761  */
1762  Opt_trace_array having_trace(&thd->opt_trace,
1763  "evaluating_constant_having_conditions");
1764  tmp= join->having->fix_fields(thd, 0);
1765  select_lex->having_fix_field= 0;
1766  if (tmp)
1767  DBUG_RETURN(RES_ERROR);
1768  }
1769  else
1770  {
1771  Item *orig_item= select_lex->item_list.head()->real_item();
1772 
1773  if (select_lex->table_list.elements)
1774  {
1775  bool tmp;
1776  Item_bool_func *item= func->create(expr, orig_item);
1777  /*
1778  We may soon add a 'OR inner IS NULL' to 'item', but that may later be
1779  removed if 'inner' is not nullable, so the in2exists mark must be on
1780  'item' too. Not only on the OR node.
1781  */
1782  item->set_created_by_in2exists();
1783  if (!abort_on_null && orig_item->maybe_null)
1784  {
1785  Item_bool_func *having= new Item_is_not_null_test(this, orig_item);
1786  having->set_created_by_in2exists();
1787  if (left_expr->maybe_null)
1788  {
1789  if (!(having= new Item_func_trig_cond(having,
1790  get_cond_guard(0), NULL,
1792  OUTER_FIELD_IS_NOT_NULL)))
1793  DBUG_RETURN(RES_ERROR);
1794  having->set_created_by_in2exists();
1795  }
1796  /*
1797  Item_is_not_null_test can't be changed during fix_fields()
1798  we can assign select_lex->having here, and pass 0 as last
1799  argument (reference) to fix_fields()
1800  */
1801  having->item_name.set(in_having_cond);
1802  select_lex->having= join->having= having;
1803  select_lex->having_fix_field= 1;
1804  /*
1805  we do not check join->having->fixed, because Item_and (from
1806  and_items) or comparison function (from func->create) can't be
1807  fixed after creation
1808  */
1809  Opt_trace_array having_trace(&thd->opt_trace,
1810  "evaluating_constant_having_conditions");
1811  tmp= join->having->fix_fields(thd, 0);
1812  select_lex->having_fix_field= 0;
1813  if (tmp)
1814  DBUG_RETURN(RES_ERROR);
1815  item= new Item_cond_or(item,
1816  new Item_func_isnull(orig_item));
1817  item->set_created_by_in2exists();
1818  }
1819  /*
1820  If we may encounter NULL IN (SELECT ...) and care whether subquery
1821  result is NULL or FALSE, wrap condition in a trig_cond.
1822  */
1823  if (!abort_on_null && left_expr->maybe_null)
1824  {
1825  if (!(item= new Item_func_trig_cond(item, get_cond_guard(0), NULL,
1827  OUTER_FIELD_IS_NOT_NULL)))
1828  DBUG_RETURN(RES_ERROR);
1829  item->set_created_by_in2exists();
1830  }
1831  /*
1832  The following is intentionally not done in row_value_transformer(),
1833  see comment of JOIN::remove_subq_pushed_predicates().
1834  */
1835  item->item_name.set(in_additional_cond);
1836 
1837  /*
1838  AND can't be changed during fix_fields()
1839  we can assign select_lex->having here, and pass 0 as last
1840  argument (reference) to fix_fields()
1841  */
1842  select_lex->where= join->conds= and_items(join->conds, item);
1843  select_lex->where->top_level_item();
1844  in2exists_info->added_to_where= true;
1845  /*
1846  we do not check join->conds->fixed, because Item_and can't be fixed
1847  after creation
1848  */
1849  Opt_trace_array where_trace(&thd->opt_trace,
1850  "evaluating_constant_where_conditions");
1851  if (join->conds->fix_fields(thd, 0))
1852  DBUG_RETURN(RES_ERROR);
1853  }
1854  else
1855  {
1856  bool tmp;
1857  if (select_lex->master_unit()->is_union())
1858  {
1859  /*
1860  comparison functions can't be changed during fix_fields()
1861  we can assign select_lex->having here, and pass 0 as last
1862  argument (reference) to fix_fields()
1863  */
1864  Item_bool_func *new_having=
1865  func->create(expr,
1866  new Item_ref_null_helper(&select_lex->context, this,
1867  &join->ref_ptrs[0],
1868  (char *)"<no matter>",
1869  (char *)"<result>"));
1870  new_having->set_created_by_in2exists();
1871  if (!abort_on_null && left_expr->maybe_null)
1872  {
1873  if (!(new_having= new Item_func_trig_cond(new_having,
1874  get_cond_guard(0),
1875  NULL,
1877  OUTER_FIELD_IS_NOT_NULL)))
1878  DBUG_RETURN(RES_ERROR);
1879  new_having->set_created_by_in2exists();
1880  }
1881  new_having->item_name.set(in_having_cond);
1882  select_lex->having= join->having= new_having;
1883  select_lex->having_fix_field= 1;
1884 
1885  /*
1886  we do not check join->having->fixed, because comparison function
1887  (from func->create) can't be fixed after creation
1888  */
1889  Opt_trace_array having_trace(&thd->opt_trace,
1890  "evaluating_constant_having_conditions");
1891  tmp= join->having->fix_fields(thd, 0);
1892  select_lex->having_fix_field= 0;
1893  if (tmp)
1894  DBUG_RETURN(RES_ERROR);
1895  }
1896  else
1897  {
1898  // it is single select without tables => possible optimization
1899  // remove the dependence mark since the item is moved to upper
1900  // select and is not outer anymore.
1901  orig_item->walk(&Item::remove_dependence_processor, 0,
1902  (uchar *) select_lex->outer_select());
1903  /*
1904  fix_field of substitution item will be done in time of
1905  substituting.
1906  Note that real_item() should be used instead of
1907  original left expression because left_expr can be
1908  runtime created Ref item which is deleted at the end
1909  of the statement. Thus one of 'substitution' arguments
1910  can be broken in case of PS.
1911  */
1912  substitution= func->create(left_expr->real_item(), orig_item);
1913  have_to_be_excluded= 1;
1914  if (thd->lex->describe)
1915  {
1916  char warn_buff[MYSQL_ERRMSG_SIZE];
1917  sprintf(warn_buff, ER(ER_SELECT_REDUCED), select_lex->select_number);
1918  push_warning(thd, Sql_condition::WARN_LEVEL_NOTE,
1919  ER_SELECT_REDUCED, warn_buff);
1920  }
1921  DBUG_RETURN(RES_REDUCE);
1922  }
1923  }
1924  }
1925  join->having_for_explain= join->having;
1926 
1927  DBUG_RETURN(RES_OK);
1928 }
1929 
1930 
1931 Item_subselect::trans_res
1932 Item_in_subselect::row_value_transformer(JOIN *join)
1933 {
1934  SELECT_LEX *select_lex= join->select_lex;
1935  uint cols_num= left_expr->cols();
1936 
1937  DBUG_ENTER("Item_in_subselect::row_value_transformer");
1938 
1939  // psergey: duplicated_subselect_card_check
1940  if (select_lex->item_list.elements != left_expr->cols())
1941  {
1942  my_error(ER_OPERAND_COLUMNS, MYF(0), left_expr->cols());
1943  DBUG_RETURN(RES_ERROR);
1944  }
1945 
1946  /*
1947  Wrap the current IN predicate in an Item_in_optimizer. The actual
1948  substitution in the Item tree takes place in Item_subselect::fix_fields.
1949  */
1950  if (!substitution)
1951  {
1952  //first call for this unit
1953  SELECT_LEX_UNIT *master_unit= select_lex->master_unit();
1954  substitution= optimizer;
1955 
1956  THD * const thd= unit->thd;
1957  SELECT_LEX *current= thd->lex->current_select;
1958  thd->lex->current_select= current->outer_select();
1959  //optimizer never use Item **ref => we can pass 0 as parameter
1960  if (!optimizer || optimizer->fix_left(thd, 0))
1961  {
1962  thd->lex->current_select= current;
1963  DBUG_RETURN(RES_ERROR);
1964  }
1965 
1966  // we will refer to upper level cache array => we have to save it in PS
1967  optimizer->keep_top_level_cache();
1968 
1969  thd->lex->current_select= current;
1970  DBUG_ASSERT(in2exists_info == NULL);
1971  in2exists_info= new In2exists_info;
1972  in2exists_info->originally_dependent=
1973  master_unit->uncacheable & UNCACHEABLE_DEPENDENT;
1974  master_unit->uncacheable|= UNCACHEABLE_DEPENDENT;
1975 
1976  if (!abort_on_null && left_expr->maybe_null && !pushed_cond_guards)
1977  {
1978  if (!(pushed_cond_guards= (bool*)join->thd->alloc(sizeof(bool) *
1979  left_expr->cols())))
1980  DBUG_RETURN(RES_ERROR);
1981  for (uint i= 0; i < cols_num; i++)
1982  pushed_cond_guards[i]= TRUE;
1983  }
1984  }
1985 
1986  /* Perform the IN=>EXISTS transformation. */
1987  DBUG_RETURN(row_value_in_to_exists_transformer(join));
1988 }
1989 
1990 
2009 Item_subselect::trans_res
2011 {
2012  SELECT_LEX *select_lex= join->select_lex;
2013  THD * const thd= unit->thd;
2014  Item *having_item= 0;
2015  uint cols_num= left_expr->cols();
2016  bool is_having_used= (join->having || select_lex->with_sum_func ||
2017  select_lex->group_list.first ||
2018  !select_lex->table_list.elements);
2019 
2020  DBUG_ENTER("Item_in_subselect::row_value_in_to_exists_transformer");
2021  OPT_TRACE_TRANSFORM(&thd->opt_trace, oto0, oto1, select_lex->select_number,
2022  "IN (SELECT)", "EXISTS (CORRELATED SELECT)");
2023  oto1.add("chosen", true);
2024 
2025  select_lex->uncacheable|= UNCACHEABLE_DEPENDENT;
2026  in2exists_info->added_to_where= false;
2027 
2028  if (is_having_used)
2029  {
2030  /*
2031  (l1, l2, l3) IN (SELECT v1, v2, v3 ... HAVING having) =>
2032  EXISTS (SELECT ... HAVING having and
2033  (l1 = v1 or is null v1) and
2034  (l2 = v2 or is null v2) and
2035  (l3 = v3 or is null v3) and
2036  is_not_null_test(v1) and
2037  is_not_null_test(v2) and
2038  is_not_null_test(v3))
2039  where is_not_null_test used to register nulls in case if we have
2040  not found matching to return correct NULL value
2041  TODO: say here explicitly if the order of AND parts matters or not.
2042  */
2043  Item *item_having_part2= 0;
2044  for (uint i= 0; i < cols_num; i++)
2045  {
2046  Item *item_i= join->ref_ptrs[i];
2047  Item **pitem_i= &join->ref_ptrs[i];
2048  DBUG_ASSERT((left_expr->fixed && item_i->fixed) ||
2049  (item_i->type() == REF_ITEM &&
2050  ((Item_ref*)(item_i))->ref_type() == Item_ref::OUTER_REF));
2051  if (item_i-> check_cols(left_expr->element_index(i)->cols()))
2052  DBUG_RETURN(RES_ERROR);
2053  Item_bool_func *item_eq=
2054  new Item_func_eq(new
2055  Item_ref(&select_lex->context,
2056  (*optimizer->get_cache())->
2057  addr(i),
2058  (char *)"<no matter>",
2059  (char *)in_left_expr_name),
2060  new
2061  Item_ref(&select_lex->context,
2062  pitem_i,
2063  (char *)"<no matter>",
2064  (char *)"<list ref>")
2065  );
2066  item_eq->set_created_by_in2exists();
2067  Item_bool_func *item_isnull=
2068  new Item_func_isnull(new
2069  Item_ref(&select_lex->context,
2070  pitem_i,
2071  (char *)"<no matter>",
2072  (char *)"<list ref>")
2073  );
2074  item_isnull->set_created_by_in2exists();
2075  Item_bool_func *col_item= new Item_cond_or(item_eq, item_isnull);
2076  col_item->set_created_by_in2exists();
2077  if (!abort_on_null && left_expr->element_index(i)->maybe_null)
2078  {
2079  if (!(col_item= new Item_func_trig_cond(col_item, get_cond_guard(i),
2080  NULL, Item_func_trig_cond::
2081  OUTER_FIELD_IS_NOT_NULL)))
2082  DBUG_RETURN(RES_ERROR);
2083  col_item->set_created_by_in2exists();
2084  }
2085  having_item= and_items(having_item, col_item);
2086 
2087  Item_bool_func *item_nnull_test=
2088  new Item_is_not_null_test(this,
2089  new Item_ref(&select_lex->context,
2090  pitem_i,
2091  (char *)"<no matter>",
2092  (char *)"<list ref>"));
2093  item_nnull_test->set_created_by_in2exists();
2094  if (!abort_on_null && left_expr->element_index(i)->maybe_null)
2095  {
2096  if (!(item_nnull_test=
2097  new Item_func_trig_cond(item_nnull_test, get_cond_guard(i),
2098  NULL, Item_func_trig_cond::
2099  OUTER_FIELD_IS_NOT_NULL)))
2100  DBUG_RETURN(RES_ERROR);
2101  item_nnull_test->set_created_by_in2exists();
2102  }
2103  item_having_part2= and_items(item_having_part2, item_nnull_test);
2104  item_having_part2->top_level_item();
2105  }
2106  having_item= and_items(having_item, item_having_part2);
2107  having_item->top_level_item();
2108  }
2109  else
2110  {
2111  /*
2112  (l1, l2, l3) IN (SELECT v1, v2, v3 ... WHERE where) =>
2113  EXISTS (SELECT ... WHERE where and
2114  (l1 = v1 or is null v1) and
2115  (l2 = v2 or is null v2) and
2116  (l3 = v3 or is null v3)
2117  HAVING is_not_null_test(v1) and
2118  is_not_null_test(v2) and
2119  is_not_null_test(v3))
2120  where is_not_null_test register NULLs values but reject rows
2121 
2122  in case when we do not need correct NULL, we have simplier construction:
2123  EXISTS (SELECT ... WHERE where and
2124  (l1 = v1) and
2125  (l2 = v2) and
2126  (l3 = v3)
2127  */
2128  Item *where_item= 0;
2129  for (uint i= 0; i < cols_num; i++)
2130  {
2131  Item *item_i= join->ref_ptrs[i];
2132  Item **pitem_i= &join->ref_ptrs[i];
2133  DBUG_ASSERT((left_expr->fixed && item_i->fixed) ||
2134  (item_i->type() == REF_ITEM &&
2135  ((Item_ref*)(item_i))->ref_type() == Item_ref::OUTER_REF));
2136  if (item_i->check_cols(left_expr->element_index(i)->cols()))
2137  DBUG_RETURN(RES_ERROR);
2138  Item_ref *const left=
2139  new Item_direct_ref(&select_lex->context,
2140  (*optimizer->get_cache())->addr(i),
2141  (char *)"<no matter>", (char *)in_left_expr_name);
2142  if (left == NULL)
2143  DBUG_RETURN(RES_ERROR);
2144 
2145  // Make the left expression "outer" relative to the subquery
2146  if (!left_expr->element_index(i)->const_item())
2147  left->depended_from= select_lex->outer_select();
2148 
2149  Item_bool_func *item=
2150  new Item_func_eq(left,
2151  new
2152  Item_direct_ref(&select_lex->context,
2153  pitem_i,
2154  (char *)"<no matter>",
2155  (char *)"<list ref>")
2156  );
2157  item->set_created_by_in2exists();
2158  if (!abort_on_null)
2159  {
2160  Item_bool_func *having_col_item=
2161  new Item_is_not_null_test(this,
2162  new
2163  Item_ref(&select_lex->context,
2164  pitem_i,
2165  (char *)"<no matter>",
2166  (char *)"<list ref>"));
2167 
2168  having_col_item->set_created_by_in2exists();
2169  Item_bool_func *item_isnull= new
2170  Item_func_isnull(new
2171  Item_direct_ref(&select_lex->context,
2172  pitem_i,
2173  (char *)"<no matter>",
2174  (char *)"<list ref>")
2175  );
2176  item_isnull->set_created_by_in2exists();
2177  item= new Item_cond_or(item, item_isnull);
2178  item->set_created_by_in2exists();
2179  /*
2180  TODO: why we create the above for cases where the right part
2181  cant be NULL?
2182  */
2183  if (left_expr->element_index(i)->maybe_null)
2184  {
2185  if (!(item= new Item_func_trig_cond(item, get_cond_guard(i), NULL,
2187  OUTER_FIELD_IS_NOT_NULL)))
2188  DBUG_RETURN(RES_ERROR);
2189  item->set_created_by_in2exists();
2190  if (!(having_col_item=
2191  new Item_func_trig_cond(having_col_item, get_cond_guard(i),
2192  NULL,
2194  OUTER_FIELD_IS_NOT_NULL)))
2195  DBUG_RETURN(RES_ERROR);
2196  having_col_item->set_created_by_in2exists();
2197  }
2198  having_item= and_items(having_item, having_col_item);
2199  }
2200 
2201  where_item= and_items(where_item, item);
2202  }
2203  /*
2204  AND can't be changed during fix_fields()
2205  we can assign select_lex->where here, and pass 0 as last
2206  argument (reference) to fix_fields()
2207  */
2208  select_lex->where= join->conds= and_items(join->conds, where_item);
2209  select_lex->where->top_level_item();
2210  in2exists_info->added_to_where= true;
2211  Opt_trace_array where_trace(&thd->opt_trace,
2212  "evaluating_constant_where_conditions");
2213  if (join->conds->fix_fields(thd, 0))
2214  DBUG_RETURN(RES_ERROR);
2215  }
2216  if (having_item)
2217  {
2218  bool res;
2219  select_lex->having= join->having= join->having_for_explain=
2220  and_items(join->having, having_item);
2221  if (having_item == select_lex->having)
2222  having_item->item_name.set(in_having_cond);
2223  select_lex->having->top_level_item();
2224  /*
2225  AND can't be changed during fix_fields()
2226  we can assign select_lex->having here, and pass 0 as last
2227  argument (reference) to fix_fields()
2228  */
2229  select_lex->having_fix_field= 1;
2230  Opt_trace_array having_trace(&thd->opt_trace,
2231  "evaluating_constant_having_conditions");
2232  res= join->having->fix_fields(thd, 0);
2233  select_lex->having_fix_field= 0;
2234  if (res)
2235  {
2236  DBUG_RETURN(RES_ERROR);
2237  }
2238  }
2239 
2240  DBUG_RETURN(RES_OK);
2241 }
2242 
2243 
2244 Item_subselect::trans_res
2245 Item_in_subselect::select_transformer(JOIN *join)
2246 {
2247  return select_in_like_transformer(join, &eq_creator);
2248 }
2249 
2250 
2272 Item_subselect::trans_res
2274 {
2275  THD * const thd= unit->thd;
2276  SELECT_LEX *current= thd->lex->current_select;
2277  const char *save_where= thd->where;
2278  Item_subselect::trans_res res= RES_ERROR;
2279  bool result;
2280 
2281  DBUG_ENTER("Item_in_subselect::select_in_like_transformer");
2282 
2283 #ifndef DBUG_OFF
2284  {
2285  /*
2286  IN/SOME/ALL/ANY subqueries don't support LIMIT clause. Without
2287  it, ORDER BY becomes meaningless and should already have been
2288  removed in resolve_subquery()
2289  */
2290  SELECT_LEX *sl= current->master_unit()->first_select();
2291  for (; sl; sl= sl->next_select())
2292  if (sl->join)
2293  DBUG_ASSERT(!sl->join->order || sl->join->order.src == ESC_GROUP_BY);
2294  }
2295 #endif
2296 
2297  if (changed)
2298  DBUG_RETURN(RES_OK);
2299 
2300  thd->where= "IN/ALL/ANY subquery";
2301 
2302  /*
2303  In some optimisation cases we will not need this Item_in_optimizer
2304  object, but we can't know it here, but here we need address correct
2305  reference on left expresion.
2306 
2307  //psergey: he means confluent cases like "... IN (SELECT 1)"
2308  */
2309  if (!optimizer)
2310  {
2311  Prepared_stmt_arena_holder ps_arena_holder(thd);
2312  optimizer= new Item_in_optimizer(left_expr, this);
2313 
2314  if (!optimizer)
2315  goto err;
2316  }
2317 
2318  thd->lex->current_select= current->outer_select();
2319  result= (!left_expr->fixed &&
2320  left_expr->fix_fields(thd, optimizer->arguments()));
2321  /* fix_fields can change reference to left_expr, we need reassign it */
2322  left_expr= optimizer->arguments()[0];
2323 
2324  thd->lex->current_select= current;
2325  if (result)
2326  goto err;
2327 
2328  /*
2329  If we didn't choose an execution method up to this point, we choose
2330  the IN=>EXISTS transformation, at least temporarily.
2331  */
2332  if (exec_method == EXEC_UNSPECIFIED)
2333  exec_method= EXEC_EXISTS_OR_MAT;
2334 
2335  /*
2336  Both transformers call fix_fields() only for Items created inside them,
2337  and all those items do not make permanent changes in the current item arena
2338  which allows us to call them with changed arena (if we do not know the
2339  nature of Item, we have to call fix_fields() for it only with the original
2340  arena to avoid memory leak).
2341  */
2342 
2343  {
2344  Prepared_stmt_arena_holder ps_arena_holder(thd);
2345 
2346  if (left_expr->cols() == 1)
2347  res= single_value_transformer(join, func);
2348  else
2349  {
2350  /* we do not support row operation for ALL/ANY/SOME */
2351  if (func != &eq_creator)
2352  {
2353  my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
2354  DBUG_RETURN(RES_ERROR);
2355  }
2356  res= row_value_transformer(join);
2357  }
2358  }
2359 
2360 err:
2361  thd->where= save_where;
2362  DBUG_RETURN(res);
2363 }
2364 
2365 
2366 void Item_in_subselect::print(String *str, enum_query_type query_type)
2367 {
2368  if (exec_method == EXEC_EXISTS_OR_MAT || exec_method == EXEC_EXISTS)
2369  str->append(STRING_WITH_LEN("<exists>"));
2370  else
2371  {
2372  left_expr->print(str, query_type);
2373  str->append(STRING_WITH_LEN(" in "));
2374  }
2375  Item_subselect::print(str, query_type);
2376 }
2377 
2378 
2379 bool Item_in_subselect::fix_fields(THD *thd_arg, Item **ref)
2380 {
2381  bool result = 0;
2382 
2383  if (exec_method == EXEC_SEMI_JOIN)
2384  return !( (*ref)= new Item_int(1));
2385 
2386  if ((thd_arg->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) &&
2387  left_expr && !left_expr->fixed)
2388  result = left_expr->fix_fields(thd_arg, &left_expr);
2389 
2390  return result || Item_subselect::fix_fields(thd_arg, ref);
2391 }
2392 
2393 
2394 void Item_in_subselect::fix_after_pullout(st_select_lex *parent_select,
2395  st_select_lex *removed_select)
2396 {
2397  Item_subselect::fix_after_pullout(parent_select, removed_select);
2398 
2399  left_expr->fix_after_pullout(parent_select, removed_select);
2400 
2401  used_tables_cache|= left_expr->used_tables();
2402 }
2403 
2404 
2417 {
2418  JOIN *outer_join;
2419  Next_select_func end_select;
2420  bool use_result_field= FALSE;
2421 
2422  outer_join= unit->outer_select()->join;
2423  /*
2424  An IN predicate might be evaluated in a query for which all tables have
2425  been optimzied away.
2426  */
2427  if (!outer_join || !outer_join->tables || !outer_join->tables_list)
2428  {
2429  need_expr_cache= FALSE;
2430  return FALSE;
2431  }
2432 
2433  /*
2434  If we use end_[send | write]_group to handle complete rows of the outer
2435  query, make the cache of the left IN operand use Item_field::result_field
2436  instead of Item_field::field. We need this because normally
2437  Cached_item_field uses Item::field to fetch field data, while
2438  copy_ref_key() that copies the left IN operand into a lookup key uses
2439  Item::result_field. In the case end_[send | write]_group result_field is
2440  one row behind field.
2441  */
2442  end_select= outer_join->join_tab[outer_join->primary_tables-1].next_select;
2443  if (end_select == end_send_group || end_select == end_write_group)
2444  use_result_field= TRUE;
2445 
2446  if (!(left_expr_cache= new List<Cached_item>))
2447  return TRUE;
2448 
2449  for (uint i= 0; i < left_expr->cols(); i++)
2450  {
2451  Cached_item *cur_item_cache= new_Cached_item(unit->thd,
2452  left_expr->element_index(i),
2453  use_result_field);
2454  if (!cur_item_cache || left_expr_cache->push_front(cur_item_cache))
2455  return TRUE;
2456  }
2457  return FALSE;
2458 }
2459 
2460 
2470 {
2471  in_cond_of_tab= *reinterpret_cast<int *>(join_tab_index);
2472  return false;
2473 }
2474 
2475 
2487 {
2488  st_select_lex *root=
2489  static_cast<st_select_lex*>(static_cast<void*>(arg));
2490  st_select_lex *sl= unit->outer_select();
2491 
2492  /*
2493  While traversing the item tree with Item::walk(), Item_refs may
2494  point to Item_subselects at different positions in the query. We
2495  should only exclude units that are descendants of the starting
2496  point for the walk.
2497 
2498  Traverse the tree towards the root. Afterwards, we have:
2499  1) sl == root: unit is a descendant of the starting point, or
2500  2) sl == NULL: unit is not a descendant of the starting point
2501  */
2502  while (sl != root && sl != NULL)
2503  sl= sl->outer_select();
2504  if (sl == root)
2505  unit->exclude_tree();
2506  return false;
2507 }
2508 
2509 
2510 Item_subselect::trans_res
2511 Item_allany_subselect::select_transformer(JOIN *join)
2512 {
2513  DBUG_ENTER("Item_allany_subselect::select_transformer");
2514  if (upper_item)
2515  upper_item->show= 1;
2516  trans_res retval= select_in_like_transformer(join, func);
2517  DBUG_RETURN(retval);
2518 }
2519 
2520 
2521 void Item_allany_subselect::print(String *str, enum_query_type query_type)
2522 {
2523  if (exec_method == EXEC_EXISTS_OR_MAT || exec_method == EXEC_EXISTS)
2524  str->append(STRING_WITH_LEN("<exists>"));
2525  else
2526  {
2527  left_expr->print(str, query_type);
2528  str->append(' ');
2529  str->append(func->symbol(all));
2530  str->append(all ? " all " : " any ", 5);
2531  }
2532  Item_subselect::print(str, query_type);
2533 }
2534 
2535 
2537 {
2538  /*
2539  select_result's constructor sets neither select_result::thd nor
2540  select_result::unit.
2541  */
2542  if (result)
2543  result->set_thd(item->unit->thd);
2544 }
2545 
2546 
2547 subselect_single_select_engine::
2548 subselect_single_select_engine(st_select_lex *select,
2549  select_result_interceptor *result_arg,
2550  Item_subselect *item_arg)
2551  :subselect_engine(item_arg, result_arg),
2552  prepared(0), executed(0), optimize_error(0), select_lex(select), join(0)
2553 {
2554  select_lex->master_unit()->item= item_arg;
2555 }
2556 
2557 
2559 {
2560  DBUG_ENTER("subselect_single_select_engine::cleanup");
2561  prepared= executed= optimize_error= false;
2562  join= 0;
2563  result->cleanup();
2564  DBUG_VOID_RETURN;
2565 }
2566 
2567 
2569 {
2570  DBUG_ENTER("subselect_union_engine::cleanup");
2571  result->cleanup();
2572  DBUG_VOID_RETURN;
2573 }
2574 
2575 
2576 bool subselect_union_engine::is_executed() const
2577 {
2578  return unit->executed;
2579 }
2580 
2581 
2582 subselect_union_engine::subselect_union_engine(st_select_lex_unit *u,
2583  select_result_interceptor *result_arg,
2584  Item_subselect *item_arg)
2585  :subselect_engine(item_arg, result_arg)
2586 {
2587  unit= u;
2588  unit->item= item_arg;
2589 }
2590 
2591 
2619 {
2620  if (prepared)
2621  return 0;
2622  THD * const thd= item->unit->thd;
2623  join= new JOIN(thd, select_lex->item_list,
2624  select_lex->options | SELECT_NO_UNLOCK, result);
2625  if (!join || !result)
2626  return 1; /* Fatal error is set already. */
2627  prepared= 1;
2628  SELECT_LEX *save_select= thd->lex->current_select;
2629  thd->lex->current_select= select_lex;
2630  if (join->prepare(select_lex->table_list.first,
2631  select_lex->with_wild,
2632  select_lex->where,
2633  select_lex->order_list.elements +
2634  select_lex->group_list.elements,
2635  select_lex->order_list.first,
2636  select_lex->group_list.first,
2637  select_lex->having,
2638  select_lex,
2639  select_lex->master_unit()))
2640  return 1;
2641  thd->lex->current_select= save_select;
2642  return 0;
2643 }
2644 
2645 
2646 bool subselect_union_engine::prepare()
2647 {
2648  THD * const thd= unit->thd;
2649  // We can access THD as above, or via 'item', verify equality:
2650  DBUG_ASSERT(thd == item->unit->thd);
2651  return unit->prepare(thd, result, SELECT_NO_UNLOCK);
2652 }
2653 
2654 
2655 bool subselect_indexsubquery_engine::prepare()
2656 {
2657  /* Should never be called. */
2658  DBUG_ASSERT(FALSE);
2659  return 1;
2660 }
2661 
2662 
2663 /*
2664  makes storage for the output values for the subquery and calcuates
2665  their data and column types and their nullability.
2666 */
2667 void subselect_engine::set_row(List<Item> &item_list, Item_cache **row)
2668 {
2669  Item *sel_item;
2670  List_iterator_fast<Item> li(item_list);
2671  res_type= STRING_RESULT;
2672  res_field_type= MYSQL_TYPE_VAR_STRING;
2673  for (uint i= 0; (sel_item= li++); i++)
2674  {
2675  item->max_length= sel_item->max_length;
2676  res_type= sel_item->result_type();
2677  res_field_type= sel_item->field_type();
2678  item->decimals= sel_item->decimals;
2679  item->unsigned_flag= sel_item->unsigned_flag;
2680  maybe_null= sel_item->maybe_null;
2681  if (!(row[i]= Item_cache::get_cache(sel_item)))
2682  return;
2683  row[i]->setup(sel_item);
2684  row[i]->store(sel_item);
2685  }
2686  if (item_list.elements > 1)
2687  res_type= ROW_RESULT;
2688 }
2689 
2690 void subselect_single_select_engine::fix_length_and_dec(Item_cache **row)
2691 {
2692  DBUG_ASSERT(row || select_lex->item_list.elements==1);
2693  set_row(select_lex->item_list, row);
2694  item->collation.set(row[0]->collation);
2695  if (cols() != 1)
2696  maybe_null= 0;
2697 }
2698 
2699 void subselect_union_engine::fix_length_and_dec(Item_cache **row)
2700 {
2701  DBUG_ASSERT(row || unit->first_select()->item_list.elements==1);
2702 
2703  if (unit->first_select()->item_list.elements == 1)
2704  {
2705  set_row(unit->types, row);
2706  item->collation.set(row[0]->collation);
2707  }
2708  else
2709  {
2710  bool maybe_null_saved= maybe_null;
2711  set_row(unit->types, row);
2712  maybe_null= maybe_null_saved;
2713  }
2714 }
2715 
2716 void subselect_indexsubquery_engine::fix_length_and_dec(Item_cache **row)
2717 {
2718  //this never should be called
2719  DBUG_ASSERT(0);
2720 }
2721 
2722 int read_first_record_seq(JOIN_TAB *tab);
2723 int rr_sequential(READ_RECORD *info);
2724 
2725 bool subselect_single_select_engine::exec()
2726 {
2727  DBUG_ENTER("subselect_single_select_engine::exec");
2728 
2729  if (optimize_error)
2730  DBUG_RETURN(true);
2731 
2732  int rc= 0;
2733  THD * const thd= item->unit->thd;
2734  char const *save_where= thd->where;
2735  SELECT_LEX *save_select= thd->lex->current_select;
2736  thd->lex->current_select= select_lex;
2737  if (!join->optimized)
2738  {
2739  SELECT_LEX_UNIT *unit= select_lex->master_unit();
2740 
2741  unit->set_limit(unit->global_parameters);
2742 
2743  DBUG_EXECUTE_IF("bug11747970_simulate_error",
2744  DBUG_SET("+d,bug11747970_raise_error"););
2745 
2746  if (join->optimize())
2747  {
2748  optimize_error= true;
2749  rc= join->error ? join->error : 1;
2750  goto exit;
2751  }
2752  if (item->engine_changed)
2753  {
2754  rc= 1;
2755  goto exit;
2756  }
2757  }
2758  if (select_lex->uncacheable &&
2759  select_lex->uncacheable != UNCACHEABLE_EXPLAIN
2760  && executed)
2761  {
2762  join->reset();
2763  item->reset();
2764  item->assigned((executed= 0));
2765  }
2766  if (!executed)
2767  {
2768  item->reset_value_registration();
2769  JOIN_TAB *changed_tabs[MAX_TABLES];
2770  JOIN_TAB **last_changed_tab= changed_tabs;
2771  if (item->have_guarded_conds())
2772  {
2773  /*
2774  For at least one of the pushed predicates the following is true:
2775  We should not apply optimizations based on the condition that was
2776  pushed down into the subquery. Those optimizations are ref[_or_null]
2777  acceses. Change them to be full table scans.
2778  */
2779  for (uint i= join->const_tables; i < join->primary_tables; i++)
2780  {
2781  JOIN_TAB *tab=join->join_tab+i;
2782  if (tab && tab->keyuse)
2783  {
2784  for (uint i= 0; i < tab->ref.key_parts; i++)
2785  {
2786  bool *cond_guard= tab->ref.cond_guards[i];
2787  if (cond_guard && !*cond_guard)
2788  {
2789  /*
2790  Can't use BKA if switching from ref to "full scan on
2791  NULL key"
2792 
2793  @see Item_in_optimizer::val_int()
2794  @see TABLE_REF::cond_guards
2795  @see push_index_cond()
2796  @see setup_join_buffering()
2797  */
2798  DBUG_ASSERT(tab->use_join_cache != JOIN_CACHE::ALG_BKA);
2799  DBUG_ASSERT(tab->use_join_cache != JOIN_CACHE::ALG_BKA_UNIQUE);
2800 
2801  /* Change the access method to full table scan */
2802  tab->save_read_first_record= tab->read_first_record;
2803  tab->save_read_record= tab->read_record.read_record;
2804  tab->read_record.read_record= rr_sequential;
2805  tab->read_first_record= read_first_record_seq;
2806  tab->read_record.record= tab->table->record[0];
2807  tab->read_record.thd= join->thd;
2808  tab->read_record.ref_length= tab->table->file->ref_length;
2809  tab->read_record.unlock_row= rr_unlock_row;
2810  *(last_changed_tab++)= tab;
2811  break;
2812  }
2813  }
2814  }
2815  }
2816  }
2817 
2818  join->exec();
2819 
2820  /* Enable the optimizations back */
2821  for (JOIN_TAB **ptab= changed_tabs; ptab != last_changed_tab; ptab++)
2822  {
2823  JOIN_TAB *tab= *ptab;
2824  tab->read_record.record= 0;
2825  tab->read_record.ref_length= 0;
2826  tab->read_first_record= tab->save_read_first_record;
2827  tab->read_record.read_record= tab->save_read_record;
2828  tab->save_read_first_record= NULL;
2829  }
2830  executed= true;
2831 
2832  rc= join->error || thd->is_fatal_error;
2833  }
2834 
2835 exit:
2836  thd->where= save_where;
2837  thd->lex->current_select= save_select;
2838  DBUG_RETURN(rc);
2839 }
2840 
2841 bool subselect_union_engine::exec()
2842 {
2843  THD * const thd= unit->thd;
2844  DBUG_ASSERT(thd == item->unit->thd);
2845  char const *save_where= thd->where;
2846  const bool res= (unit->optimize() || unit->exec());
2847  thd->where= save_where;
2848  return res;
2849 }
2850 
2851 
2862 {
2863  int error;
2864  TABLE *table= tab->table;
2865  DBUG_ENTER("subselect_indexsubquery_engine::scan_table");
2866 
2867  // We never need to do a table scan of the materialized table.
2868  DBUG_ASSERT(engine_type() != HASH_SJ_ENGINE);
2869 
2870  if ((table->file->inited &&
2871  (error= table->file->ha_index_end())) ||
2872  (error= table->file->ha_rnd_init(1)))
2873  {
2874  (void) report_handler_error(table, error);
2875  DBUG_RETURN(true);
2876  }
2877 
2878  table->file->extra_opt(HA_EXTRA_CACHE,
2879  current_thd->variables.read_buff_size);
2880  table->null_row= 0;
2881  for (;;)
2882  {
2883  error=table->file->ha_rnd_next(table->record[0]);
2884  if (error && error != HA_ERR_END_OF_FILE)
2885  {
2886  error= report_handler_error(table, error);
2887  break;
2888  }
2889  /* No more rows */
2890  if (table->status)
2891  break;
2892 
2893  if (!cond || cond->val_int())
2894  {
2895  static_cast<Item_in_subselect*>(item)->value= true;
2896  break;
2897  }
2898  }
2899 
2900  table->file->ha_rnd_end();
2901  DBUG_RETURN(error != 0);
2902 }
2903 
2904 
2953  bool *convert_error)
2954 {
2955  DBUG_ENTER("subselect_indexsubquery_engine::copy_ref_key");
2956 
2957  *require_scan= false;
2958  *convert_error= false;
2959  for (uint part_no= 0; part_no < tab->ref.key_parts; part_no++)
2960  {
2961  store_key *s_key= tab->ref.key_copy[part_no];
2962  if (s_key == NULL)
2963  continue; // key is const and does not need to be reevaluated
2964 
2965  const enum store_key::store_key_result store_res= s_key->copy();
2966  tab->ref.key_err= store_res;
2967 
2968  if (s_key->null_key)
2969  {
2970  /*
2971  If we have materialized the subquery:
2972  - this NULL ref item cannot be local to the subquery (any such
2973  conditions was handled during materialization)
2974  - neither can it be outer, because this case is
2975  separately managed in subselect_hash_sj_engine::exec().
2976  */
2977  DBUG_ASSERT(engine_type() != HASH_SJ_ENGINE);
2978 
2979  const bool *cond_guard= tab->ref.cond_guards[part_no];
2980 
2981  /*
2982  NULL value is from the outer_value_list if the key part has a
2983  cond guard that deactivates the condition. @see
2984  TABLE_REF::cond_guards
2985 
2986  */
2987  if (cond_guard && !*cond_guard)
2988  {
2989  DBUG_ASSERT(!(static_cast <Item_in_subselect*>(item)
2990  ->is_top_level_item()));
2991 
2992  *require_scan= true;
2993  DBUG_VOID_RETURN;
2994  }
2995  }
2996 
2997  /*
2998  Check if the error is equal to STORE_KEY_FATAL. This is not expressed
2999  using the store_key::store_key_result enum because ref.key_err is a
3000  boolean and we want to detect both TRUE and STORE_KEY_FATAL from the
3001  space of the union of the values of [TRUE, FALSE] and
3002  store_key::store_key_result.
3003  TODO: fix the variable an return types.
3004  */
3005  if (store_res == store_key::STORE_KEY_FATAL)
3006  {
3007  /*
3008  Error converting the left IN operand to the column type of the right
3009  IN operand.
3010  */
3011  tab->table->status= STATUS_NOT_FOUND;
3012  *convert_error= true;
3013  DBUG_VOID_RETURN;
3014  }
3015  }
3016  DBUG_VOID_RETURN;
3017 }
3018 
3019 
3020 /*
3021  Index-lookup subselect 'engine' - run the subquery
3022 
3023  SYNOPSIS
3024  subselect_indexsubquery_engine:exec()
3025  full_scan
3026 
3027  DESCRIPTION
3028  The engine is used to resolve subqueries in form
3029 
3030  oe IN (SELECT key FROM tbl WHERE subq_where)
3031 
3032  The value of the predicate is calculated as follows:
3033  1. If oe IS NULL, this is a special case, do a full table scan on
3034  table tbl and search for row that satisfies subq_where. If such
3035  row is found, return NULL, otherwise return FALSE.
3036  2. Make an index lookup via key=oe, search for a row that satisfies
3037  subq_where. If found, return TRUE.
3038  3. If check_null==TRUE, make another lookup via key=NULL, search for a
3039  row that satisfies subq_where. If found, return NULL, otherwise
3040  return FALSE.
3041  4. If unique==true, there can be only one row with key=oe and only one row
3042  with key=NULL, we use that fact to shorten the search process.
3043 
3044  TODO
3045  The step #1 can be optimized further when the index has several key
3046  parts. Consider a subquery:
3047 
3048  (oe1, oe2) IN (SELECT keypart1, keypart2 FROM tbl WHERE subq_where)
3049 
3050  and suppose we need to evaluate it for {oe1, oe2}=={const1, NULL}.
3051  Current code will do a full table scan and obtain correct result. There
3052  is a better option: instead of evaluating
3053 
3054  SELECT keypart1, keypart2 FROM tbl WHERE subq_where (1)
3055 
3056  and checking if it has produced any matching rows, evaluate
3057 
3058  SELECT keypart2 FROM tbl WHERE subq_where AND keypart1=const1 (2)
3059 
3060  If this query produces a row, the result is NULL (as we're evaluating
3061  "(const1, NULL) IN { (const1, X), ... }", which has a value of UNKNOWN,
3062  i.e. NULL). If the query produces no rows, the result is FALSE.
3063 
3064  We currently evaluate (1) by doing a full table scan. (2) can be
3065  evaluated by doing a "ref" scan on "keypart1=const1", which can be much
3066  cheaper. We can use index statistics to quickly check whether "ref" scan
3067  will be cheaper than full table scan.
3068 
3069  RETURN
3070  0
3071  1
3072 */
3073 
3074 bool subselect_indexsubquery_engine::exec()
3075 {
3076  DBUG_ENTER("subselect_indexsubquery_engine::exec");
3077  int error;
3078  bool null_finding= 0;
3079  TABLE *table= tab->table;
3080  // 'tl' is NULL if this is a tmp table created by subselect_hash_sj_engine.
3081  TABLE_LIST *tl= table->pos_in_table_list;
3082  Item_in_subselect *const item_in= static_cast<Item_in_subselect*>(item);
3083  item_in->value= false;
3084  table->status= 0;
3085 
3086  if (tl && tl->uses_materialization() && !tab->materialized)
3087  {
3088  bool err= mysql_handle_single_derived(table->in_use->lex, tl,
3089  mysql_derived_create) ||
3090  mysql_handle_single_derived(table->in_use->lex, tl,
3091  mysql_derived_materialize);
3092  if (!tab->table->in_use->lex->describe)
3093  mysql_handle_single_derived(table->in_use->lex, tl,
3094  mysql_derived_cleanup);
3095  if (err)
3096  DBUG_RETURN(1);
3097 
3098  tab->materialized= true;
3099  }
3100 
3101  if (check_null)
3102  {
3103  /* We need to check for NULL if there wasn't a matching value */
3104  *tab->ref.null_ref_key= 0; // Search first for not null
3105  item_in->was_null= false;
3106  }
3107 
3108  /* Copy the ref key and check for nulls... */
3109  bool require_scan, convert_error;
3110  copy_ref_key(&require_scan, &convert_error);
3111  if (convert_error)
3112  DBUG_RETURN(0);
3113 
3114  if (require_scan)
3115  {
3116  const bool scan_result= scan_table();
3117  DBUG_RETURN(scan_result);
3118  }
3119 
3120  if (!table->file->inited &&
3121  (error= table->file->ha_index_init(tab->ref.key, !unique /* sorted */)))
3122  {
3123  (void) report_handler_error(table, error);
3124  DBUG_RETURN(true);
3125  }
3126  error= table->file->ha_index_read_map(table->record[0],
3127  tab->ref.key_buff,
3128  make_prev_keypart_map(tab->ref.key_parts),
3129  HA_READ_KEY_EXACT);
3130  if (error &&
3131  error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3132  error= report_handler_error(table, error);
3133  else
3134  {
3135  for (;;)
3136  {
3137  error= 0;
3138  table->null_row= 0;
3139  if (!table->status)
3140  {
3141  if ((!cond || cond->val_int()) && (!having || having->val_int()))
3142  {
3143  item_in->value= true;
3144  if (null_finding)
3145  {
3146  /*
3147  This is dead code; subqueries with check_null==true are always
3148  transformed with IN-to-EXISTS and thus their artificial HAVING
3149  rejects NULL values...
3150  */
3151  DBUG_ASSERT(false);
3152  item_in->was_null= true;
3153  }
3154  break;
3155  }
3156  if (unique)
3157  break;
3158  error= table->file->ha_index_next_same(table->record[0],
3159  tab->ref.key_buff,
3160  tab->ref.key_length);
3161  if (error && error != HA_ERR_END_OF_FILE)
3162  {
3163  error= report_handler_error(table, error);
3164  break;
3165  }
3166  }
3167  else
3168  {
3169  if (!check_null || null_finding)
3170  break; /* We don't need to check nulls */
3171  /*
3172  Check if there exists a row with a null value in the index. We come
3173  here only if ref_or_null, and ref_or_null is always on a single
3174  column (first keypart of the index). So we have only one NULL bit to
3175  turn on:
3176  */
3177  *tab->ref.null_ref_key= 1;
3178  null_finding= 1;
3179  if ((error= (safe_index_read(tab) == 1)))
3180  break;
3181  }
3182  }
3183  }
3184  DBUG_RETURN(error != 0);
3185 }
3186 
3187 
3188 uint subselect_single_select_engine::cols() const
3189 {
3190  return select_lex->item_list.elements;
3191 }
3192 
3193 
3194 uint subselect_union_engine::cols() const
3195 {
3196  DBUG_ASSERT(unit->is_prepared()); // should be called after fix_fields()
3197  return unit->types.elements;
3198 }
3199 
3200 
3201 uint8 subselect_single_select_engine::uncacheable() const
3202 {
3203  return select_lex->uncacheable;
3204 }
3205 
3206 
3207 uint8 subselect_union_engine::uncacheable() const
3208 {
3209  return unit->uncacheable;
3210 }
3211 
3212 
3213 void subselect_single_select_engine::exclude()
3214 {
3215  select_lex->master_unit()->exclude_level();
3216 }
3217 
3218 void subselect_union_engine::exclude()
3219 {
3220  unit->exclude_level();
3221 }
3222 
3223 
3224 void subselect_indexsubquery_engine::exclude()
3225 {
3226  //this never should be called
3227  DBUG_ASSERT(0);
3228 }
3229 
3230 
3231 table_map subselect_engine::calc_const_tables(TABLE_LIST *table)
3232 {
3233  table_map map= 0;
3234  for (; table; table= table->next_leaf)
3235  {
3236  TABLE *tbl= table->table;
3237  if (tbl && tbl->const_table)
3238  map|= tbl->map;
3239  }
3240  return map;
3241 }
3242 
3243 
3244 table_map subselect_single_select_engine::upper_select_const_tables() const
3245 {
3246  return calc_const_tables(select_lex->outer_select()->leaf_tables);
3247 }
3248 
3249 
3250 table_map subselect_union_engine::upper_select_const_tables() const
3251 {
3252  return calc_const_tables(unit->outer_select()->leaf_tables);
3253 }
3254 
3255 
3256 void subselect_single_select_engine::print(String *str,
3257  enum_query_type query_type)
3258 {
3259  select_lex->print(item->unit->thd, str, query_type);
3260 }
3261 
3262 
3263 void subselect_union_engine::print(String *str, enum_query_type query_type)
3264 {
3265  unit->print(str, query_type);
3266 }
3267 
3268 
3269 /*
3270 TODO:
3271 The ::print method below should be changed as follows. Do it after
3272 all other tests pass.
3273 
3274 void subselect_indexsubquery_engine::print(String *str)
3275 {
3276  KEY *key_info= tab->table->key_info + tab->ref.key;
3277  str->append(STRING_WITH_LEN("<primary_index_lookup>("));
3278  for (uint i= 0; i < key_info->key_parts; i++)
3279  tab->ref.items[i]->print(str);
3280  str->append(STRING_WITH_LEN(" in "));
3281  str->append(tab->table->s->table_name.str, tab->table->s->table_name.length);
3282  str->append(STRING_WITH_LEN(" on "));
3283  str->append(key_info->name);
3284  if (cond)
3285  {
3286  str->append(STRING_WITH_LEN(" where "));
3287  cond->print(str);
3288  }
3289  str->append(')');
3290 }
3291 */
3292 
3293 void subselect_indexsubquery_engine::print(String *str,
3294  enum_query_type query_type)
3295 {
3296  if (unique)
3297  str->append(STRING_WITH_LEN("<primary_index_lookup>("));
3298  else
3299  str->append(STRING_WITH_LEN("<index_lookup>("));
3300  tab->ref.items[0]->print(str, query_type);
3301  str->append(STRING_WITH_LEN(" in "));
3302  if (tab->table->pos_in_table_list &&
3303  tab->table->pos_in_table_list->uses_materialization())
3304  {
3305  /*
3306  For materialized derived tables/views use table/view alias instead of
3307  temporary table name, as it changes on each run and not acceptable for
3308  EXPLAIN EXTENDED.
3309  */
3310  str->append(tab->table->alias, strlen(tab->table->alias));
3311  }
3312  else if (tab->table->s->table_category == TABLE_CATEGORY_TEMPORARY)
3313  {
3314  // Could be from subselect_hash_sj_engine.
3315  str->append(STRING_WITH_LEN("<temporary table>"));
3316  }
3317  else
3318  str->append(tab->table->s->table_name.str, tab->table->s->table_name.length);
3319  KEY *key_info= tab->table->key_info+ tab->ref.key;
3320  str->append(STRING_WITH_LEN(" on "));
3321  str->append(key_info->name);
3322  if (check_null)
3323  str->append(STRING_WITH_LEN(" checking NULL"));
3324  if (cond)
3325  {
3326  str->append(STRING_WITH_LEN(" where "));
3327  cond->print(str, query_type);
3328  }
3329  if (having)
3330  {
3331  str->append(STRING_WITH_LEN(" having "));
3332  having->print(str, query_type);
3333  }
3334  str->append(')');
3335 }
3336 
3350  select_result_interceptor *res)
3351 {
3352  item= si;
3353  result= res;
3354  return select_lex->join->change_result(result);
3355 }
3356 
3357 
3371  select_result_interceptor *res)
3372 {
3373  item= si;
3374  int rc= unit->change_result(res, result);
3375  result= res;
3376  return rc;
3377 }
3378 
3379 
3393  select_result_interceptor *res)
3394 {
3395  DBUG_ASSERT(0);
3396  return TRUE;
3397 }
3398 
3399 
3409 {
3410  return(select_lex->table_list.elements == 0);
3411 }
3412 
3413 
3414 /*
3415  Check statically whether the subquery can return NULL
3416 
3417  SINOPSYS
3418  subselect_single_select_engine::may_be_null()
3419 
3420  RETURN
3421  FALSE can guarantee that the subquery never return NULL
3422  TRUE otherwise
3423 */
3424 bool subselect_single_select_engine::may_be_null() const
3425 {
3426  return ((no_tables() && !join->conds && !join->having) ? maybe_null : 1);
3427 }
3428 
3429 
3439 {
3440  for (SELECT_LEX *sl= unit->first_select(); sl; sl= sl->next_select())
3441  {
3442  if (sl->table_list.elements)
3443  return FALSE;
3444  }
3445  return TRUE;
3446 }
3447 
3448 
3459 {
3460  /* returning value is correct, but this method should never be called */
3461  return 0;
3462 }
3463 
3464 
3465 /******************************************************************************
3466  WL#1110 - Implementation of class subselect_hash_sj_engine
3467 ******************************************************************************/
3468 
3469 
3493 {
3494  /* The result sink where we will materialize the subquery result. */
3495  select_union *tmp_result_sink;
3496  /* The table into which the subquery is materialized. */
3497  TABLE *tmp_table;
3498  KEY *tmp_key; /* The only index on the temporary table. */
3499  uint tmp_key_parts; /* Number of keyparts in tmp_key. */
3500  Item_in_subselect *item_in= (Item_in_subselect *) item;
3501 
3502  DBUG_ENTER("subselect_hash_sj_engine::setup");
3503 
3504  /* 1. Create/initialize materialization related objects. */
3505 
3506  /*
3507  Create and initialize a select result interceptor that stores the
3508  result stream in a temporary table. The temporary table itself is
3509  managed (created/filled/etc) internally by the interceptor.
3510  */
3511  if (!(tmp_result_sink= new select_union))
3512  DBUG_RETURN(TRUE);
3513  THD * const thd= item->unit->thd;
3514  if (tmp_result_sink->create_result_table(
3515  thd, tmp_columns, true,
3516  thd->variables.option_bits | TMP_TABLE_ALL_COLUMNS,
3517  "materialized-subquery", true, true))
3518  DBUG_RETURN(TRUE);
3519 
3520  tmp_table= tmp_result_sink->table;
3521  tmp_key= tmp_table->key_info;
3522  tmp_key_parts= tmp_key->user_defined_key_parts;
3523 
3524  /*
3525  If the subquery has blobs, or the total key lenght is bigger than some
3526  length, then the created index cannot be used for lookups and we
3527  can't use hash semi join. If this is the case, delete the temporary
3528  table since it will not be used, and tell the caller we failed to
3529  initialize the engine.
3530  */
3531  if (tmp_table->s->keys == 0)
3532  {
3533  DBUG_ASSERT(tmp_table->s->db_type() == myisam_hton);
3534  DBUG_ASSERT(
3535  tmp_table->s->uniques ||
3536  tmp_table->key_info->key_length >= tmp_table->file->max_key_length() ||
3537  tmp_table->key_info->user_defined_key_parts >
3538  tmp_table->file->max_key_parts());
3539  free_tmp_table(thd, tmp_table);
3540  delete result;
3541  result= NULL;
3542  DBUG_RETURN(TRUE);
3543  }
3544  result= tmp_result_sink;
3545 
3546  /*
3547  Make sure there is only one index on the temp table, and it doesn't have
3548  the extra key part created when s->uniques > 0.
3549  */
3550  DBUG_ASSERT(tmp_table->s->keys == 1 &&
3551  tmp_columns->elements == tmp_key_parts);
3552 
3553  /* 2. Create/initialize execution related objects. */
3554 
3555  /*
3556  Create and initialize the JOIN_TAB that represents an index lookup
3557  plan operator into the materialized subquery result. Notice that:
3558  - this JOIN_TAB has no corresponding JOIN (and doesn't need one), and
3559  - here we initialize only those members that are used by
3560  subselect_indexsubquery_engine, so these objects are incomplete.
3561  */
3562  JOIN_TAB * const tmp_tab= new (thd->mem_root) JOIN_TAB;
3563  if (tmp_tab == NULL)
3564  DBUG_RETURN(TRUE);
3565  tmp_tab->table= tmp_table;
3566  tmp_tab->ref.key= 0; /* The only temp table index. */
3567  tmp_tab->ref.key_length= tmp_key->key_length;
3568  if (!(tmp_tab->ref.key_buff=
3569  (uchar*) thd->calloc(ALIGN_SIZE(tmp_key->key_length) * 2)) ||
3570  !(tmp_tab->ref.key_copy=
3571  (store_key**) thd->alloc((sizeof(store_key*) * tmp_key_parts))) ||
3572  !(tmp_tab->ref.items=
3573  (Item**) thd->alloc(sizeof(Item*) * tmp_key_parts)))
3574  DBUG_RETURN(TRUE);
3575 
3576  uchar *cur_ref_buff= tmp_tab->ref.key_buff;
3577 
3578  /*
3579  Like semijoin-materialization-lookup (see create_subquery_equalities()),
3580  create an artificial condition to post-filter those rows matched by index
3581  lookups that cannot be distinguished by the index lookup procedure, e.g.
3582  because of truncation (if the outer column type's length is bigger than
3583  the inner column type's, index lookup will use a truncated outer
3584  value as search key, yielding false positives).
3585  Prepared statements execution requires that fix_fields is called
3586  for every execution. In order to call fix_fields we need to create a
3587  Name_resolution_context and a corresponding TABLE_LIST for the temporary
3588  table for the subquery, so that all column references to the materialized
3589  subquery table can be resolved correctly.
3590  */
3591  DBUG_ASSERT(cond == NULL);
3592  if (!(cond= new Item_cond_and))
3593  DBUG_RETURN(TRUE);
3594  /*
3595  Table reference for tmp_table that is used to resolve column references
3596  (Item_fields) to columns in tmp_table.
3597  */
3598  TABLE_LIST *tmp_table_ref;
3599  if (!(tmp_table_ref= (TABLE_LIST*) thd->calloc(sizeof(TABLE_LIST))))
3600  DBUG_RETURN(TRUE);
3601 
3602  tmp_table_ref->init_one_table("", 0, "materialized-subquery", 21,
3603  "materialized-subquery", TL_READ);
3604  tmp_table_ref->table= tmp_table;
3605 
3606  /* Name resolution context for all tmp_table columns created below. */
3608  context->init();
3609  context->first_name_resolution_table=
3610  context->last_name_resolution_table= tmp_table_ref;
3611 
3612  KEY_PART_INFO *key_parts= tmp_key->key_part;
3613  for (uint part_no= 0; part_no < tmp_key_parts; part_no++)
3614  {
3615  /* New equi-join condition for the current column. */
3616  Item_func_eq *eq_cond;
3617  /* Item for the corresponding field from the materialized temp table. */
3618  Item_field *right_col_item;
3619  const bool nullable= key_parts[part_no].field->real_maybe_null();
3620  tmp_tab->ref.items[part_no]= item_in->left_expr->element_index(part_no);
3621 
3622  if (!(right_col_item= new Item_field(thd, context,
3623  key_parts[part_no].field)) ||
3624  !(eq_cond= new Item_func_eq(tmp_tab->ref.items[part_no],
3625  right_col_item)) ||
3626  ((Item_cond_and*)cond)->add(eq_cond))
3627  {
3628  delete cond;
3629  cond= NULL;
3630  DBUG_RETURN(TRUE);
3631  }
3632 
3633  tmp_tab->ref.key_copy[part_no]=
3634  new store_key_item(thd, key_parts[part_no].field,
3635  /* TODO:
3636  the NULL byte is taken into account in
3637  key_parts[part_no].store_length, so instead of
3638  cur_ref_buff + test(maybe_null), we could
3639  use that information instead.
3640  */
3641  cur_ref_buff + (nullable ? 1 : 0),
3642  nullable ? cur_ref_buff : 0,
3643  key_parts[part_no].length,
3644  tmp_tab->ref.items[part_no]);
3645  if (nullable && // nullable column in tmp table,
3646  // and UNKNOWN should not be interpreted as FALSE
3647  !item_in->is_top_level_item())
3648  {
3649  // It must be the single column, or we wouldn't be here
3650  DBUG_ASSERT(tmp_key_parts == 1);
3651  // Be ready to search for NULL into inner column:
3652  tmp_tab->ref.null_ref_key= cur_ref_buff;
3653  mat_table_has_nulls= NEX_UNKNOWN;
3654  }
3655  else
3656  {
3657  tmp_tab->ref.null_ref_key= NULL;
3658  mat_table_has_nulls= NEX_IRRELEVANT_OR_FALSE;
3659  }
3660 
3661  cur_ref_buff+= key_parts[part_no].store_length;
3662  }
3663  tmp_tab->ref.key_err= 1;
3664  tmp_tab->ref.key_parts= tmp_key_parts;
3665 
3666  if (cond->fix_fields(thd, &cond))
3667  DBUG_RETURN(TRUE);
3668 
3669  // Set 'tab' only when function cannot fail, because of assert in destructor
3670  tab= tmp_tab;
3671 
3672  /*
3673  Create and optimize the JOIN that will be used to materialize
3674  the subquery if not yet created.
3675  */
3676  materialize_engine->prepare();
3677  /* Let our engine reuse this query plan for materialization. */
3678  materialize_engine->join->change_result(result);
3679 
3680  DBUG_RETURN(FALSE);
3681 }
3682 
3683 
3684 subselect_hash_sj_engine::~subselect_hash_sj_engine()
3685 {
3686  /* Assure that cleanup has been called for this engine. */
3687  DBUG_ASSERT(!tab);
3688 
3689  delete result;
3690 }
3691 
3692 
3701 {
3702  DBUG_ENTER("subselect_hash_sj_engine::cleanup");
3703  is_materialized= false;
3704  result->cleanup(); /* Resets the temp table as well. */
3705  THD * const thd= item->unit->thd;
3706  DEBUG_SYNC(thd, "before_index_end_in_subselect");
3707  if (tab->table->file->inited)
3708  tab->table->file->ha_index_end(); // Close the scan over the index
3709  free_tmp_table(thd, tab->table);
3710  tab= NULL;
3711  materialize_engine->cleanup();
3712  DBUG_VOID_RETURN;
3713 }
3714 
3715 
3728 {
3729  Item_in_subselect *item_in= (Item_in_subselect *) item;
3730  TABLE *const table= tab->table;
3731  DBUG_ENTER("subselect_hash_sj_engine::exec");
3732 
3733  /*
3734  Optimize and materialize the subquery during the first execution of
3735  the subquery predicate.
3736  */
3737  if (!is_materialized)
3738  {
3739  bool res;
3740  THD * const thd= item->unit->thd;
3741  SELECT_LEX *save_select= thd->lex->current_select;
3742  thd->lex->current_select= materialize_engine->select_lex;
3743  if ((res= materialize_engine->join->optimize()))
3744  goto err; /* purecov: inspected */
3745 
3746  materialize_engine->join->exec();
3747  if ((res= test(materialize_engine->join->error || thd->is_fatal_error)))
3748  goto err;
3749 
3750  /*
3751  TODO:
3752  - Unlock all subquery tables as we don't need them. To implement this
3753  we need to add new functionality to JOIN::join_free that can unlock
3754  all tables in a subquery (and all its subqueries).
3755  - The temp table used for grouping in the subquery can be freed
3756  immediately after materialization (yet it's done together with
3757  unlocking).
3758  */
3759  is_materialized= TRUE;
3760 
3761  // Calculate row count:
3762  table->file->info(HA_STATUS_VARIABLE);
3763 
3764  /* Set tmp_param only if its usable, i.e. tmp_param->copy_field != NULL. */
3765  tmp_param= &(item_in->unit->outer_select()->join->tmp_table_param);
3766  if (tmp_param && !tmp_param->copy_field)
3767  tmp_param= NULL;
3768 
3769 err:
3770  thd->lex->current_select= save_select;
3771  if (res)
3772  DBUG_RETURN(res);
3773  } // if (!is_materialized)
3774 
3775  if (table->file->stats.records == 0)
3776  {
3777  // The correct answer is FALSE.
3778  item_in->value= false;
3779  DBUG_RETURN(false);
3780  }
3781  /*
3782  Here we could be brutal and set item_in->null_value. But we prefer to be
3783  well-behaved and rather set the properties which
3784  Item_in_subselect::val_bool() and Item_in_optimizer::val_int() expect,
3785  and then those functions will set null_value based on those properties.
3786  */
3787  if (item_in->left_expr->element_index(0)->null_value)
3788  {
3789  /*
3790  The first outer expression oe1 is NULL. It is the single outer
3791  expression because if there would be more ((oe1,oe2,...)IN(...)) then
3792  either they would be non-nullable (so we wouldn't be here) or the
3793  predicate would be top-level (so we wouldn't be here,
3794  Item_in_optimizer::val_int() would have short-cut). The correct answer
3795  is UNKNOWN. Do as if searching with all triggered conditions disabled:
3796  this would surely find a row. The caller will translate this to UNKNOWN.
3797  */
3798  DBUG_ASSERT(item_in->left_expr->cols() == 1);
3799  item_in->value= true;
3800  DBUG_RETURN(false);
3801  }
3802 
3803  if (subselect_indexsubquery_engine::exec()) // Search with index
3804  DBUG_RETURN(true);
3805 
3806  if (!item_in->value && // no exact match
3807  mat_table_has_nulls != NEX_IRRELEVANT_OR_FALSE)
3808  {
3809  /*
3810  There is only one outer expression. It's not NULL. exec() above has set
3811  the answer to FALSE, but if there exists an inner NULL in the temporary
3812  table, then the correct answer is UNKNOWN, so let's find out.
3813  */
3814  if (mat_table_has_nulls == NEX_UNKNOWN) // We do not know yet
3815  {
3816  // Search for NULL inside tmp table, and remember the outcome.
3817  *tab->ref.null_ref_key= 1;
3818  if (!table->file->inited &&
3819  table->file->ha_index_init(tab->ref.key, false /* sorted */))
3820  DBUG_RETURN(true);
3821  if (safe_index_read(tab) == 1)
3822  DBUG_RETURN(true);
3823  *tab->ref.null_ref_key= 0; // prepare for next searches of non-NULL
3824  mat_table_has_nulls=
3825  (table->status == 0) ? NEX_TRUE : NEX_IRRELEVANT_OR_FALSE;
3826  }
3827  if (mat_table_has_nulls == NEX_TRUE)
3828  {
3829  /*
3830  There exists an inner NULL. The correct answer is UNKNOWN.
3831  Do as if searching with all triggered conditions enabled; that
3832  would not find any match, but Item_is_not_null_test would notice a
3833  NULL:
3834  */
3835  item_in->value= false;
3836  item_in->was_null= true;
3837  }
3838  }
3839  DBUG_RETURN(false);
3840 }
3841 
3842 
3847 void subselect_hash_sj_engine::print(String *str, enum_query_type query_type)
3848 {
3849  str->append(STRING_WITH_LEN(" <materialize> ("));
3850  materialize_engine->print(str, query_type);
3851  str->append(STRING_WITH_LEN(" ), "));
3852  if (tab)
3853  subselect_indexsubquery_engine::print(str, query_type);
3854  else
3855  str->append(STRING_WITH_LEN(
3856  "<the access method for lookups is not yet created>"
3857  ));
3858 }