Drizzled Public API Documentation

subselect.cc
Go to the documentation of this file.
00001 /* Copyright (C) 2000 MySQL AB
00002 
00003    This program is free software; you can redistribute it and/or modify
00004    it under the terms of the GNU General Public License as published by
00005    the Free Software Foundation; version 2 of the License.
00006 
00007    This program is distributed in the hope that it will be useful,
00008    but WITHOUT ANY WARRANTY; without even the implied warranty of
00009    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00010    GNU General Public License for more details.
00011 
00012    You should have received a copy of the GNU General Public License
00013    along with this program; if not, write to the Free Software
00014    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
00015 
00026 #include <config.h>
00027 
00028 #include <cstdio>
00029 #include <limits.h>
00030 
00031 #include <drizzled/session.h>
00032 #include <drizzled/sql_select.h>
00033 #include <drizzled/error.h>
00034 #include <drizzled/item/cache.h>
00035 #include <drizzled/item/subselect.h>
00036 #include <drizzled/item/cmpfunc.h>
00037 #include <drizzled/item/ref_null_helper.h>
00038 #include <drizzled/cached_item.h>
00039 #include <drizzled/check_stack_overrun.h>
00040 #include <drizzled/item/ref_null_helper.h>
00041 #include <drizzled/item/direct_ref.h>
00042 #include <drizzled/join.h>
00043 #include <drizzled/plugin/storage_engine.h>
00044 #include <drizzled/select_singlerow_subselect.h>
00045 #include <drizzled/select_max_min_finder_subselect.h>
00046 #include <drizzled/select_exists_subselect.h>
00047 #include <drizzled/select_union.h>
00048 #include <drizzled/sql_lex.h>
00049 #include <drizzled/system_variables.h>
00050 
00051 namespace drizzled {
00052 
00053 extern plugin::StorageEngine *myisam_engine;
00054 
00055 inline Item* and_items(Item* cond, Item *item)
00056 {
00057   return cond ? new Item_cond_and(cond, item) : item;
00058 }
00059 
00060 Item_subselect::Item_subselect() :
00061   Item_result_field(),
00062   value_assigned(false),
00063   session(NULL),
00064   substitution(NULL),
00065   unit(NULL),
00066   engine(NULL),
00067   old_engine(NULL),
00068   used_tables_cache(0),
00069   max_columns(0),
00070   parsing_place(NO_MATTER),
00071   have_to_be_excluded(false),
00072   const_item_cache(true),
00073   engine_changed(false),
00074   changed(false),
00075   is_correlated(false)
00076 {
00077   with_subselect= 1;
00078   reset();
00079   /*
00080     Item value is NULL if select_result_interceptor didn't change this value
00081     (i.e. some rows will be found returned)
00082   */
00083   null_value= 1;
00084 }
00085 
00086 
00087 void Item_subselect::init(Select_Lex *select_lex,
00088         select_result_interceptor *result)
00089 {
00090   /*
00091     Please see Item_singlerow_subselect::invalidate_and_restore_select_lex(),
00092     which depends on alterations to the parse tree implemented here.
00093   */
00094 
00095   unit= select_lex->master_unit();
00096 
00097   if (unit->item)
00098   {
00099     /*
00100       Item can be changed in JOIN::prepare while engine in Join::optimize
00101       => we do not copy old_engine here
00102     */
00103     engine= unit->item->engine;
00104     parsing_place= unit->item->parsing_place;
00105     unit->item->engine= 0;
00106     unit->item= this;
00107     engine->change_result(this, result);
00108   }
00109   else
00110   {
00111     Select_Lex *outer_select= unit->outer_select();
00112     /*
00113       do not take into account expression inside aggregate functions because
00114       they can access original table fields
00115     */
00116     parsing_place= (outer_select->in_sum_expr ?
00117                     NO_MATTER :
00118                     outer_select->parsing_place);
00119     if (unit->is_union())
00120       engine= new subselect_union_engine(unit, result, this);
00121     else
00122       engine= new subselect_single_select_engine(select_lex, result, this);
00123   }
00124   {
00125     Select_Lex *upper= unit->outer_select();
00126     if (upper->parsing_place == IN_HAVING)
00127       upper->subquery_in_having= 1;
00128   }
00129   return;
00130 }
00131 
00132 Select_Lex *
00133 Item_subselect::get_select_lex()
00134 {
00135   return unit->first_select();
00136 }
00137 
00138 void Item_subselect::cleanup()
00139 {
00140   Item_result_field::cleanup();
00141   if (old_engine)
00142   {
00143     if (engine)
00144       engine->cleanup();
00145     engine= old_engine;
00146     old_engine= 0;
00147   }
00148   if (engine)
00149     engine->cleanup();
00150   reset();
00151   value_assigned= 0;
00152 }
00153 
00154 void Item_singlerow_subselect::cleanup()
00155 {
00156   value= 0; row= 0;
00157   Item_subselect::cleanup();
00158 }
00159 
00160 
00161 void Item_in_subselect::cleanup()
00162 {
00163   if (left_expr_cache)
00164   {
00165     left_expr_cache->delete_elements();
00166     delete left_expr_cache;
00167     left_expr_cache= NULL;
00168   }
00169   first_execution= true;
00170   Item_subselect::cleanup();
00171 }
00172 
00173 Item_subselect::~Item_subselect()
00174 {
00175   delete engine;
00176 }
00177 
00178 Item_subselect::trans_res
00179 Item_subselect::select_transformer(Join *)
00180 {
00181   return RES_OK;
00182 }
00183 
00184 
00185 bool Item_subselect::fix_fields(Session *session_param, Item **ref)
00186 {
00187   char const *save_where= session_param->where();
00188   bool res;
00189 
00190   assert(fixed == 0);
00191   engine->set_session((session= session_param));
00192 
00193   if (check_stack_overrun(session, STACK_MIN_SIZE, (unsigned char*)&res))
00194     return true;
00195 
00196   res= engine->prepare();
00197 
00198   // all transformation is done (used by prepared statements)
00199   changed= 1;
00200 
00201   if (!res)
00202   {
00203     /*
00204       Substitute the current item with an Item_in_optimizer that was
00205       created by Item_in_subselect::select_in_like_transformer and
00206       call fix_fields for the substituted item which in turn calls
00207       engine->prepare for the subquery predicate.
00208     */
00209     if (substitution)
00210     {
00211       int ret= 0;
00212 
00213       // did we changed top item of WHERE condition
00214       if (unit->outer_select()->where == (*ref))
00215       {
00216         unit->outer_select()->where= substitution; // correct WHERE for PS
00217       }
00218       else if (unit->outer_select()->having == (*ref))
00219       {
00220         unit->outer_select()->having= substitution; // correct HAVING for PS
00221       }
00222 
00223       (*ref)= substitution;
00224       substitution->name= name;
00225       if (have_to_be_excluded)
00226       {
00227         engine->exclude();
00228       }
00229       substitution= 0;
00230       session->setWhere("checking transformed subquery");
00231       if (! (*ref)->fixed)
00232       {
00233         ret= (*ref)->fix_fields(session, ref);
00234       }
00235       session->setWhere(save_where);
00236 
00237       return ret;
00238     }
00239     // Is it one field subselect?
00240     if (engine->cols() > max_columns)
00241     {
00242       my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
00243       return true;
00244     }
00245     fix_length_and_dec();
00246   }
00247   else
00248     goto err;
00249 
00250   if (engine->uncacheable())
00251   {
00252     const_item_cache= false;
00253     if (engine->uncacheable(UNCACHEABLE_RAND))
00254     {
00255       used_tables_cache|= RAND_TABLE_BIT;
00256     }
00257   }
00258   fixed= 1;
00259 
00260 err:
00261   session->setWhere(save_where);
00262   return res;
00263 }
00264 
00265 
00266 bool Item_subselect::walk(Item_processor processor, bool walk_subquery,
00267                           unsigned char *argument)
00268 {
00269 
00270   if (walk_subquery)
00271   {
00272     for (Select_Lex *lex= unit->first_select(); lex; lex= lex->next_select())
00273     {
00274       List<Item>::iterator li(lex->item_list.begin());
00275       Item *item;
00276       Order *order;
00277 
00278       if (lex->where && (lex->where)->walk(processor, walk_subquery, argument))
00279         return 1;
00280       if (lex->having && (lex->having)->walk(processor, walk_subquery,
00281                                              argument))
00282         return 1;
00283 
00284       while ((item=li++))
00285       {
00286         if (item->walk(processor, walk_subquery, argument))
00287           return 1;
00288       }
00289       for (order= (Order*) lex->order_list.first ; order; order= order->next)
00290       {
00291         if ((*order->item)->walk(processor, walk_subquery, argument))
00292           return 1;
00293       }
00294       for (order= (Order*) lex->group_list.first ; order; order= order->next)
00295       {
00296         if ((*order->item)->walk(processor, walk_subquery, argument))
00297           return 1;
00298       }
00299     }
00300   }
00301   return (this->*processor)(argument);
00302 }
00303 
00304 
00305 bool Item_subselect::exec()
00306 {
00307   int res;
00308 
00309   if (session->is_error())
00310   /* Do not execute subselect in case of a fatal error */
00311     return 1;
00312 
00313   res= engine->exec();
00314 
00315   if (engine_changed)
00316   {
00317     engine_changed= 0;
00318     return exec();
00319   }
00320   return (res);
00321 }
00322 
00323 
00324 /*
00325   Compute the IN predicate if the left operand's cache changed.
00326 */
00327 
00328 bool Item_in_subselect::exec()
00329 {
00330   assert(exec_method != MATERIALIZATION ||
00331               (exec_method == MATERIALIZATION &&
00332                engine->engine_type() == subselect_engine::HASH_SJ_ENGINE));
00333   /*
00334     Initialize the cache of the left predicate operand. This has to be done as
00335     late as now, because Cached_item directly contains a resolved field (not
00336     an item, and in some cases (when temp tables are created), these fields
00337     end up pointing to the wrong field. One solution is to change Cached_item
00338     to not resolve its field upon creation, but to resolve it dynamically
00339     from a given Item_ref object.
00340     TODO: the cache should be applied conditionally based on:
00341     - rules - e.g. only if the left operand is known to be ordered, and/or
00342     - on a cost-based basis, that takes into account the cost of a cache
00343       lookup, the cache hit rate, and the savings per cache hit.
00344   */
00345   if (!left_expr_cache && exec_method == MATERIALIZATION)
00346     init_left_expr_cache();
00347 
00348   /* If the new left operand is already in the cache, reuse the old result. */
00349   if (left_expr_cache && test_if_item_cache_changed(*left_expr_cache) < 0)
00350   {
00351     /* Always compute IN for the first row as the cache is not valid for it. */
00352     if (!first_execution)
00353       return false;
00354     first_execution= false;
00355   }
00356 
00357   /*
00358     The exec() method below updates item::value, and item::null_value, thus if
00359     we don't call it, the next call to item::val_int() will return whatever
00360     result was computed by its previous call.
00361   */
00362   return(Item_subselect::exec());
00363 }
00364 
00365 
00366 Item::Type Item_subselect::type() const
00367 {
00368   return SUBSELECT_ITEM;
00369 }
00370 
00371 
00372 void Item_subselect::fix_length_and_dec()
00373 {
00374   engine->fix_length_and_dec(0);
00375 }
00376 
00377 
00378 table_map Item_subselect::used_tables() const
00379 {
00380   return (table_map) (engine->uncacheable() ? used_tables_cache : 0L);
00381 }
00382 
00383 
00384 bool Item_subselect::const_item() const
00385 {
00386   return const_item_cache;
00387 }
00388 
00389 Item *Item_subselect::get_tmp_table_item(Session *session_arg)
00390 {
00391   if (!with_sum_func && !const_item())
00392     return new Item_field(result_field);
00393   return copy_or_same(session_arg);
00394 }
00395 
00396 void Item_subselect::update_used_tables()
00397 {
00398   if (! engine->uncacheable())
00399   {
00400     // did all used tables become static?
00401     if (!(used_tables_cache & ~engine->upper_select_const_tables()))
00402       const_item_cache= true;
00403   }
00404 }
00405 
00406 
00407 void Item_subselect::print(String *str)
00408 {
00409   str->append('(');
00410   engine->print(str);
00411   str->append(')');
00412 }
00413 
00414 
00415 Item_singlerow_subselect::Item_singlerow_subselect(Select_Lex *select_lex)
00416   :Item_subselect(), value(0)
00417 {
00418   init(select_lex, new select_singlerow_subselect(this));
00419   maybe_null= 1;
00420   max_columns= UINT_MAX;
00421 }
00422 
00423 Select_Lex *
00424 Item_singlerow_subselect::invalidate_and_restore_select_lex()
00425 {
00426   Select_Lex *result= get_select_lex();
00427 
00428   assert(result);
00429 
00430   /*
00431     This code restore the parse tree in it's state before the execution of
00432     Item_singlerow_subselect::Item_singlerow_subselect(),
00433     and in particular decouples this object from the Select_Lex,
00434     so that the Select_Lex can be used with a different flavor
00435     or Item_subselect instead, as part of query rewriting.
00436   */
00437   unit->item= NULL;
00438 
00439   return(result);
00440 }
00441 
00442 Item_maxmin_subselect::Item_maxmin_subselect(Session *session_param,
00443                                              Item_subselect *parent,
00444                Select_Lex *select_lex,
00445                bool max_arg)
00446   :Item_singlerow_subselect(), was_values(true)
00447 {
00448   max= max_arg;
00449   init(select_lex, new select_max_min_finder_subselect(this, max_arg));
00450   max_columns= 1;
00451   maybe_null= 1;
00452   max_columns= 1;
00453 
00454   /*
00455     Following information was collected during performing fix_fields()
00456     of Items belonged to subquery, which will be not repeated
00457   */
00458   used_tables_cache= parent->get_used_tables_cache();
00459   const_item_cache= parent->get_const_item_cache();
00460 
00461   /*
00462     this subquery always creates during preparation, so we can assign
00463     session here
00464   */
00465   session= session_param;
00466 }
00467 
00468 void Item_maxmin_subselect::cleanup()
00469 {
00470   Item_singlerow_subselect::cleanup();
00471 
00472   /*
00473     By default it is true to avoid true reporting by
00474     Item_func_not_all/Item_func_nop_all if this item was never called.
00475 
00476     Engine exec() set it to false by reset_value_registration() call.
00477     select_max_min_finder_subselect::send_data() set it back to true if some
00478     value will be found.
00479   */
00480   was_values= true;
00481 }
00482 
00483 
00484 void Item_maxmin_subselect::print(String *str)
00485 {
00486   str->append(max?"<max>":"<min>", 5);
00487   Item_singlerow_subselect::print(str);
00488 }
00489 
00490 
00491 void Item_singlerow_subselect::reset()
00492 {
00493   null_value= 1;
00494   if (value)
00495     value->null_value= 1;
00496 }
00497 
00498 
00509 Item_subselect::trans_res
00510 Item_singlerow_subselect::select_transformer(Join *join)
00511 {
00512   if (changed)
00513     return(RES_OK);
00514 
00515   Select_Lex *select_lex= join->select_lex;
00516 
00517   if (!select_lex->master_unit()->is_union() &&
00518       !select_lex->table_list.elements &&
00519       select_lex->item_list.size() == 1 &&
00520       !select_lex->item_list.front().with_sum_func &&
00521       /*
00522   We cant change name of Item_field or Item_ref, because it will
00523   prevent it's correct resolving, but we should save name of
00524   removed item => we do not make optimization if top item of
00525   list is field or reference.
00526   TODO: solve above problem
00527       */
00528       !(select_lex->item_list.front().type() == FIELD_ITEM ||
00529   select_lex->item_list.front().type() == REF_ITEM) &&
00530       !join->conds && !join->having
00531       )
00532   {
00533 
00534     have_to_be_excluded= 1;
00535     if (session->lex().describe)
00536     {
00537       char warn_buff[DRIZZLE_ERRMSG_SIZE];
00538       snprintf(warn_buff, sizeof(warn_buff), ER(ER_SELECT_REDUCED), select_lex->select_number);
00539       push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
00540        ER_SELECT_REDUCED, warn_buff);
00541     }
00542     substitution= &select_lex->item_list.front();
00543     /*
00544       as far as we moved content to upper level, field which depend of
00545       'upper' select is not really dependent => we remove this dependence
00546     */
00547     substitution->walk(&Item::remove_dependence_processor, 0,
00548            (unsigned char *) select_lex->outer_select());
00549     return(RES_REDUCE);
00550   }
00551   return(RES_OK);
00552 }
00553 
00554 
00555 void Item_singlerow_subselect::store(uint32_t i, Item *item)
00556 {
00557   row[i]->store(item);
00558 }
00559 
00560 enum Item_result Item_singlerow_subselect::result_type() const
00561 {
00562   return engine->type();
00563 }
00564 
00565 /*
00566  Don't rely on the result type to calculate field type.
00567  Ask the engine instead.
00568 */
00569 enum_field_types Item_singlerow_subselect::field_type() const
00570 {
00571   return engine->field_type();
00572 }
00573 
00574 void Item_singlerow_subselect::fix_length_and_dec()
00575 {
00576   if ((max_columns= engine->cols()) == 1)
00577   {
00578     engine->fix_length_and_dec(row= &value);
00579   }
00580   else
00581   {
00582     if (!(row= (Item_cache**) memory::sql_alloc(sizeof(Item_cache*)*max_columns)))
00583       return;
00584     engine->fix_length_and_dec(row);
00585     value= *row;
00586   }
00587   unsigned_flag= value->unsigned_flag;
00588   /*
00589     If there are not tables in subquery then ability to have NULL value
00590     depends on SELECT list (if single row subquery have tables then it
00591     always can be NULL if there are not records fetched).
00592   */
00593   if (engine->no_tables())
00594     maybe_null= engine->may_be_null();
00595 }
00596 
00597 uint32_t Item_singlerow_subselect::cols()
00598 {
00599   return engine->cols();
00600 }
00601 
00602 bool Item_singlerow_subselect::check_cols(uint32_t c)
00603 {
00604   if (c != engine->cols())
00605   {
00606     my_error(ER_OPERAND_COLUMNS, MYF(0), c);
00607     return 1;
00608   }
00609   return 0;
00610 }
00611 
00612 bool Item_singlerow_subselect::null_inside()
00613 {
00614   for (uint32_t i= 0; i < max_columns ; i++)
00615   {
00616     if (row[i]->null_value)
00617       return 1;
00618   }
00619   return 0;
00620 }
00621 
00622 void Item_singlerow_subselect::bring_value()
00623 {
00624   exec();
00625 }
00626 
00627 double Item_singlerow_subselect::val_real()
00628 {
00629   assert(fixed == 1);
00630   if (!exec() && !value->null_value)
00631   {
00632     null_value= 0;
00633     return value->val_real();
00634   }
00635   else
00636   {
00637     reset();
00638     return 0;
00639   }
00640 }
00641 
00642 int64_t Item_singlerow_subselect::val_int()
00643 {
00644   assert(fixed == 1);
00645   if (!exec() && !value->null_value)
00646   {
00647     null_value= 0;
00648     return value->val_int();
00649   }
00650   else
00651   {
00652     reset();
00653     return 0;
00654   }
00655 }
00656 
00657 String *Item_singlerow_subselect::val_str(String *str)
00658 {
00659   if (!exec() && !value->null_value)
00660   {
00661     null_value= 0;
00662     return value->val_str(str);
00663   }
00664   else
00665   {
00666     reset();
00667     return 0;
00668   }
00669 }
00670 
00671 
00672 type::Decimal *Item_singlerow_subselect::val_decimal(type::Decimal *decimal_value)
00673 {
00674   if (!exec() && !value->null_value)
00675   {
00676     null_value= 0;
00677     return value->val_decimal(decimal_value);
00678   }
00679   else
00680   {
00681     reset();
00682     return 0;
00683   }
00684 }
00685 
00686 
00687 bool Item_singlerow_subselect::val_bool()
00688 {
00689   if (!exec() && !value->null_value)
00690   {
00691     null_value= 0;
00692     return value->val_bool();
00693   }
00694   else
00695   {
00696     reset();
00697     return 0;
00698   }
00699 }
00700 
00701 
00702 Item_exists_subselect::Item_exists_subselect(Select_Lex *select_lex):
00703   Item_subselect()
00704 {
00705   bool val_bool();
00706   init(select_lex, new select_exists_subselect(this));
00707   max_columns= UINT_MAX;
00708   null_value= 0; //can't be NULL
00709   maybe_null= 0; //can't be NULL
00710   value= 0;
00711   return;
00712 }
00713 
00714 
00715 void Item_exists_subselect::print(String *str)
00716 {
00717   str->append(STRING_WITH_LEN("exists"));
00718   Item_subselect::print(str);
00719 }
00720 
00721 
00722 bool Item_in_subselect::test_limit(Select_Lex_Unit *unit_arg)
00723 {
00724   if (unit_arg->fake_select_lex &&
00725       unit_arg->fake_select_lex->test_limit())
00726     return 1;
00727 
00728   Select_Lex *sl= unit_arg->first_select();
00729   for (; sl; sl= sl->next_select())
00730   {
00731     if (sl->test_limit())
00732       return 1;
00733   }
00734   return 0;
00735 }
00736 
00737 Item_in_subselect::Item_in_subselect(Item * left_exp,
00738                                      Select_Lex *select_lex) :
00739   Item_exists_subselect(),
00740   left_expr(left_exp),
00741   left_expr_cache(NULL),
00742   first_execution(true),
00743   optimizer(NULL),
00744   pushed_cond_guards(NULL),
00745   sj_convert_priority(0),
00746   expr_join_nest(NULL),
00747   exec_method(NOT_TRANSFORMED),
00748   upper_item(NULL)
00749 {
00750   init(select_lex, new select_exists_subselect(this));
00751   max_columns= UINT_MAX;
00752   maybe_null= 1;
00753   abort_on_null= 0;
00754   reset();
00755   //if test_limit will fail then error will be reported to client
00756   test_limit(select_lex->master_unit());
00757   return;
00758 }
00759 
00760 Item_allany_subselect::Item_allany_subselect(Item * left_exp,
00761                                              chooser_compare_func_creator fc,
00762                Select_Lex *select_lex,
00763                bool all_arg)
00764   :Item_in_subselect(), func_creator(fc), all(all_arg)
00765 {
00766   left_expr= left_exp;
00767   func= func_creator(all_arg);
00768   init(select_lex, new select_exists_subselect(this));
00769   max_columns= 1;
00770   abort_on_null= 0;
00771   reset();
00772   //if test_limit will fail then error will be reported to client
00773   test_limit(select_lex->master_unit());
00774   return;
00775 }
00776 
00777 
00778 void Item_exists_subselect::fix_length_and_dec()
00779 {
00780    decimals= 0;
00781    max_length= 1;
00782    max_columns= engine->cols();
00783   /* We need only 1 row to determine existence */
00784   unit->global_parameters->select_limit= new Item_int((int32_t) 1);
00785 }
00786 
00787 double Item_exists_subselect::val_real()
00788 {
00789   assert(fixed == 1);
00790   if (exec())
00791   {
00792     reset();
00793     return 0;
00794   }
00795   return (double) value;
00796 }
00797 
00798 int64_t Item_exists_subselect::val_int()
00799 {
00800   assert(fixed == 1);
00801   if (exec())
00802   {
00803     reset();
00804     return 0;
00805   }
00806   return value;
00807 }
00808 
00809 String *Item_exists_subselect::val_str(String *str)
00810 {
00811   assert(fixed == 1);
00812   if (exec())
00813   {
00814     reset();
00815     return 0;
00816   }
00817   str->set((uint64_t)value,&my_charset_bin);
00818   return str;
00819 }
00820 
00821 
00822 type::Decimal *Item_exists_subselect::val_decimal(type::Decimal *decimal_value)
00823 {
00824   assert(fixed == 1);
00825   if (exec())
00826   {
00827     reset();
00828     return 0;
00829   }
00830   int2_class_decimal(E_DEC_FATAL_ERROR, value, 0, decimal_value);
00831   return decimal_value;
00832 }
00833 
00834 
00835 bool Item_exists_subselect::val_bool()
00836 {
00837   assert(fixed == 1);
00838   if (exec())
00839   {
00840     reset();
00841     return 0;
00842   }
00843   return value != 0;
00844 }
00845 
00846 
00847 double Item_in_subselect::val_real()
00848 {
00849   /*
00850     As far as Item_in_subselect called only from Item_in_optimizer this
00851     method should not be used
00852   */
00853   assert(0);
00854   assert(fixed == 1);
00855   null_value= 0;
00856   if (exec())
00857   {
00858     reset();
00859     null_value= 1;
00860     return 0;
00861   }
00862   if (was_null && !value)
00863     null_value= 1;
00864   return (double) value;
00865 }
00866 
00867 
00868 int64_t Item_in_subselect::val_int()
00869 {
00870   /*
00871     As far as Item_in_subselect called only from Item_in_optimizer this
00872     method should not be used
00873   */
00874   assert(fixed == 1);
00875   null_value= 0;
00876   if (exec())
00877   {
00878     reset();
00879     null_value= 1;
00880     return 0;
00881   }
00882   if (was_null && !value)
00883     null_value= 1;
00884   return value;
00885 }
00886 
00887 
00888 String *Item_in_subselect::val_str(String *str)
00889 {
00890   /*
00891     As far as Item_in_subselect called only from Item_in_optimizer this
00892     method should not be used
00893   */
00894   assert(0);
00895   assert(fixed == 1);
00896   null_value= 0;
00897   if (exec())
00898   {
00899     reset();
00900     null_value= 1;
00901     return 0;
00902   }
00903   if (was_null && !value)
00904   {
00905     null_value= 1;
00906     return 0;
00907   }
00908   str->set((uint64_t)value, &my_charset_bin);
00909   return str;
00910 }
00911 
00912 
00913 bool Item_in_subselect::val_bool()
00914 {
00915   assert(fixed == 1);
00916   null_value= 0;
00917   if (exec())
00918   {
00919     reset();
00920     /*
00921       Must mark the IN predicate as NULL so as to make sure an enclosing NOT
00922       predicate will return false. See the comments in
00923       subselect_uniquesubquery_engine::copy_ref_key for further details.
00924     */
00925     null_value= 1;
00926     return 0;
00927   }
00928   if (was_null && !value)
00929     null_value= 1;
00930   return value;
00931 }
00932 
00933 type::Decimal *Item_in_subselect::val_decimal(type::Decimal *decimal_value)
00934 {
00935   /*
00936     As far as Item_in_subselect called only from Item_in_optimizer this
00937     method should not be used
00938   */
00939   assert(0);
00940   null_value= 0;
00941   assert(fixed == 1);
00942   if (exec())
00943   {
00944     reset();
00945     null_value= 1;
00946     return 0;
00947   }
00948   if (was_null && !value)
00949     null_value= 1;
00950   int2_class_decimal(E_DEC_FATAL_ERROR, value, 0, decimal_value);
00951   return decimal_value;
00952 }
00953 
00954 
00955 /*
00956   Rewrite a single-column IN/ALL/ANY subselect
00957 
00958   SYNOPSIS
00959     Item_in_subselect::single_value_transformer()
00960       join  Join object of the subquery (i.e. 'child' join).
00961       func  Subquery comparison creator
00962 
00963   DESCRIPTION
00964     Rewrite a single-column subquery using rule-based approach. The subquery
00965 
00966        oe $cmp$ (SELECT ie FROM ... WHERE subq_where ... HAVING subq_having)
00967 
00968     First, try to convert the subquery to scalar-result subquery in one of
00969     the forms:
00970 
00971        - oe $cmp$ (SELECT MAX(...) )  // handled by Item_singlerow_subselect
00972        - oe $cmp$ <max>(SELECT ...)   // handled by Item_maxmin_subselect
00973 
00974     If that fails, the subquery will be handled with class Item_in_optimizer.
00975     There are two possibilites:
00976     - If the subquery execution method is materialization, then the subquery is
00977       not transformed any further.
00978     - Otherwise the IN predicates is transformed into EXISTS by injecting
00979       equi-join predicates and possibly other helper predicates. For details
00980       see method single_value_in_like_transformer().
00981 
00982   RETURN
00983     RES_OK     Either subquery was transformed, or appopriate
00984                        predicates where injected into it.
00985     RES_REDUCE The subquery was reduced to non-subquery
00986     RES_ERROR  Error
00987 */
00988 
00989 Item_subselect::trans_res
00990 Item_in_subselect::single_value_transformer(Join *join,
00991               const Comp_creator *func)
00992 {
00993   Select_Lex *select_lex= join->select_lex;
00994 
00995   /*
00996     Check that the right part of the subselect contains no more than one
00997     column. E.g. in SELECT 1 IN (SELECT * ..) the right part is (SELECT * ...)
00998   */
00999   if (select_lex->item_list.size() > 1)
01000   {
01001     my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
01002     return(RES_ERROR);
01003   }
01004 
01005   /*
01006     If this is an ALL/ANY single-value subselect, try to rewrite it with
01007     a MIN/MAX subselect. We can do that if a possible NULL result of the
01008     subselect can be ignored.
01009     E.g. SELECT * FROM t1 WHERE b > ANY (SELECT a FROM t2) can be rewritten
01010     with SELECT * FROM t1 WHERE b > (SELECT MAX(a) FROM t2).
01011     We can't check that this optimization is safe if it's not a top-level
01012     item of the WHERE clause (e.g. because the WHERE clause can contain IS
01013     NULL/IS NOT NULL functions). If so, we rewrite ALL/ANY with NOT EXISTS
01014     later in this method.
01015   */
01016   if ((abort_on_null || (upper_item && upper_item->top_level())) &&
01017       select_lex->master_unit()->uncacheable.none() && !func->eqne_op())
01018   {
01019     if (substitution)
01020     {
01021       // It is second (third, ...) SELECT of UNION => All is done
01022       return(RES_OK);
01023     }
01024 
01025     Item *subs;
01026     if (!select_lex->group_list.elements &&
01027         !select_lex->having &&
01028   !select_lex->with_sum_func &&
01029   !(select_lex->next_select()) &&
01030         select_lex->table_list.elements)
01031     {
01032       Item_sum_hybrid *item;
01033       nesting_map save_allow_sum_func;
01034       if (func->l_op())
01035       {
01036   /*
01037     (ALL && (> || =>)) || (ANY && (< || =<))
01038     for ALL condition is inverted
01039   */
01040   item= new Item_sum_max(*select_lex->ref_pointer_array);
01041       }
01042       else
01043       {
01044   /*
01045     (ALL && (< || =<)) || (ANY && (> || =>))
01046     for ALL condition is inverted
01047   */
01048   item= new Item_sum_min(*select_lex->ref_pointer_array);
01049       }
01050       if (upper_item)
01051         upper_item->set_sum_test(item);
01052       *select_lex->ref_pointer_array= item;
01053       {
01054   List<Item>::iterator it(select_lex->item_list.begin());
01055   it++;
01056   it.replace(item);
01057       }
01058 
01059       save_allow_sum_func= session->lex().allow_sum_func;
01060       session->lex().allow_sum_func|= 1 << session->lex().current_select->nest_level;
01061       /*
01062   Item_sum_(max|min) can't substitute other item => we can use 0 as
01063         reference, also Item_sum_(max|min) can't be fixed after creation, so
01064         we do not check item->fixed
01065       */
01066       if (item->fix_fields(session, 0))
01067   return(RES_ERROR);
01068       session->lex().allow_sum_func= save_allow_sum_func;
01069       /* we added aggregate function => we have to change statistic */
01070       count_field_types(select_lex, &join->tmp_table_param, join->all_fields,
01071                         0);
01072 
01073       subs= new Item_singlerow_subselect(select_lex);
01074     }
01075     else
01076     {
01077       Item_maxmin_subselect *item;
01078       subs= item= new Item_maxmin_subselect(session, this, select_lex, func->l_op());
01079       if (upper_item)
01080         upper_item->set_sub_test(item);
01081     }
01082     /* fix fields is already called for  left expression */
01083     substitution= func->create(left_expr, subs);
01084     return(RES_OK);
01085   }
01086 
01087   if (!substitution)
01088   {
01089     /* We're invoked for the 1st (or the only) SELECT in the subquery UNION */
01090     Select_Lex_Unit *master_unit= select_lex->master_unit();
01091     substitution= optimizer;
01092 
01093     Select_Lex *current= session->lex().current_select, *up;
01094 
01095     session->lex().current_select= up= current->return_after_parsing();
01096     //optimizer never use Item **ref => we can pass 0 as parameter
01097     if (!optimizer || optimizer->fix_left(session, 0))
01098     {
01099       session->lex().current_select= current;
01100       return(RES_ERROR);
01101     }
01102     session->lex().current_select= current;
01103 
01104     /*
01105       As far as  Item_ref_in_optimizer do not substitute itself on fix_fields
01106       we can use same item for all selects.
01107     */
01108     expr= new Item_direct_ref(&select_lex->context, (Item**)optimizer->get_cache(), "<no matter>", in_left_expr_name);
01109 
01110     master_unit->uncacheable.set(UNCACHEABLE_DEPENDENT);
01111   }
01112 
01113   if (!abort_on_null && left_expr->maybe_null && !pushed_cond_guards)
01114   {
01115     pushed_cond_guards= new (join->session->mem) bool;
01116     pushed_cond_guards[0]= true;
01117   }
01118 
01119   /*
01120     If this IN predicate can be computed via materialization, do not
01121     perform the IN -> EXISTS transformation.
01122   */
01123   if (exec_method == MATERIALIZATION)
01124     return(RES_OK);
01125 
01126   /* Perform the IN=>EXISTS transformation. */
01127   return(single_value_in_to_exists_transformer(join, func));
01128 }
01129 
01130 
01167 Item_subselect::trans_res
01168 Item_in_subselect::single_value_in_to_exists_transformer(Join * join, const Comp_creator *func)
01169 {
01170   Select_Lex *select_lex= join->select_lex;
01171 
01172   select_lex->uncacheable.set(UNCACHEABLE_DEPENDENT);
01173   if (join->having || select_lex->with_sum_func ||
01174       select_lex->group_list.elements)
01175   {
01176     bool tmp;
01177     Item *item= func->create(expr, new Item_ref_null_helper(&select_lex->context, this, select_lex->ref_pointer_array, "<ref>", this->full_name()));
01178     if (!abort_on_null && left_expr->maybe_null)
01179     {
01180       /*
01181         We can encounter "NULL IN (SELECT ...)". Wrap the added condition
01182         within a trig_cond.
01183       */
01184       item= new Item_func_trig_cond(item, get_cond_guard(0));
01185     }
01186 
01187     /*
01188       AND and comparison functions can't be changed during fix_fields()
01189       we can assign select_lex->having here, and pass 0 as last
01190       argument (reference) to fix_fields()
01191     */
01192     select_lex->having= join->having= and_items(join->having, item);
01193     if (join->having == item)
01194       item->name= (char*)in_having_cond;
01195     select_lex->having->top_level_item();
01196     select_lex->having_fix_field= 1;
01197     /*
01198       we do not check join->having->fixed, because Item_and (from and_items)
01199       or comparison function (from func->create) can't be fixed after creation
01200     */
01201     tmp= join->having->fix_fields(session, 0);
01202     select_lex->having_fix_field= 0;
01203     if (tmp)
01204       return(RES_ERROR);
01205   }
01206   else
01207   {
01208     Item *item= &select_lex->item_list.front();
01209 
01210     if (select_lex->table_list.elements)
01211     {
01212       bool tmp;
01213       Item *having= item, *orig_item= item;
01214       select_lex->item_list.clear();
01215       select_lex->item_list.push_back(new Item_int("Not_used", 1, MY_INT64_NUM_DECIMAL_DIGITS));
01216       select_lex->ref_pointer_array[0]= &select_lex->item_list.front();
01217 
01218       item= func->create(expr, item);
01219       if (!abort_on_null && orig_item->maybe_null)
01220       {
01221   having= new Item_is_not_null_test(this, having);
01222         if (left_expr->maybe_null)
01223           having= new Item_func_trig_cond(having, get_cond_guard(0));
01224   /*
01225     Item_is_not_null_test can't be changed during fix_fields()
01226     we can assign select_lex->having here, and pass 0 as last
01227     argument (reference) to fix_fields()
01228   */
01229         having->name= (char*)in_having_cond;
01230   select_lex->having= join->having= having;
01231   select_lex->having_fix_field= 1;
01232         /*
01233           we do not check join->having->fixed, because Item_and (from
01234           and_items) or comparison function (from func->create) can't be
01235           fixed after creation
01236         */
01237   tmp= join->having->fix_fields(session, 0);
01238         select_lex->having_fix_field= 0;
01239         if (tmp)
01240     return(RES_ERROR);
01241   item= new Item_cond_or(item, new Item_func_isnull(orig_item));
01242       }
01243       /*
01244         If we may encounter NULL IN (SELECT ...) and care whether subquery
01245         result is NULL or false, wrap condition in a trig_cond.
01246       */
01247       if (!abort_on_null && left_expr->maybe_null)
01248         item= new Item_func_trig_cond(item, get_cond_guard(0));
01249       /*
01250         TODO: figure out why the following is done here in
01251         single_value_transformer but there is no corresponding action in
01252         row_value_transformer?
01253       */
01254       item->name= (char *)in_additional_cond;
01255 
01256       /*
01257   AND can't be changed during fix_fields()
01258   we can assign select_lex->having here, and pass 0 as last
01259   argument (reference) to fix_fields()
01260       */
01261       select_lex->where= join->conds= and_items(join->conds, item);
01262       select_lex->where->top_level_item();
01263       /*
01264         we do not check join->conds->fixed, because Item_and can't be fixed
01265         after creation
01266       */
01267       if (join->conds->fix_fields(session, 0))
01268   return(RES_ERROR);
01269     }
01270     else
01271     {
01272       bool tmp;
01273       if (select_lex->master_unit()->is_union())
01274       {
01275   /*
01276     comparison functions can't be changed during fix_fields()
01277     we can assign select_lex->having here, and pass 0 as last
01278     argument (reference) to fix_fields()
01279   */
01280         Item *new_having= func->create(expr, new Item_ref_null_helper(&select_lex->context, this, select_lex->ref_pointer_array, "<no matter>", "<result>"));
01281         if (!abort_on_null && left_expr->maybe_null)
01282           new_having= new Item_func_trig_cond(new_having, get_cond_guard(0));
01283         new_having->name= in_having_cond;
01284   select_lex->having= join->having= new_having;
01285   select_lex->having_fix_field= 1;
01286 
01287         /*
01288           we do not check join->having->fixed, because comparison function
01289           (from func->create) can't be fixed after creation
01290         */
01291   tmp= join->having->fix_fields(session, 0);
01292         select_lex->having_fix_field= 0;
01293         if (tmp)
01294     return(RES_ERROR);
01295       }
01296       else
01297       {
01298   // it is single select without tables => possible optimization
01299   item= func->create(left_expr, item);
01300   // fix_field of item will be done in time of substituting
01301   substitution= item;
01302   have_to_be_excluded= 1;
01303   if (session->lex().describe)
01304   {
01305     char warn_buff[DRIZZLE_ERRMSG_SIZE];
01306     snprintf(warn_buff, sizeof(warn_buff), ER(ER_SELECT_REDUCED), select_lex->select_number);
01307     push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
01308            ER_SELECT_REDUCED, warn_buff);
01309   }
01310   return(RES_REDUCE);
01311       }
01312     }
01313   }
01314 
01315   return(RES_OK);
01316 }
01317 
01318 
01319 Item_subselect::trans_res
01320 Item_in_subselect::row_value_transformer(Join *join)
01321 {
01322   Select_Lex *select_lex= join->select_lex;
01323   uint32_t cols_num= left_expr->cols();
01324 
01325   if (select_lex->item_list.size() != left_expr->cols())
01326   {
01327     my_error(ER_OPERAND_COLUMNS, MYF(0), left_expr->cols());
01328     return(RES_ERROR);
01329   }
01330 
01331   /*
01332     Wrap the current IN predicate in an Item_in_optimizer. The actual
01333     substitution in the Item tree takes place in Item_subselect::fix_fields.
01334   */
01335   if (!substitution)
01336   {
01337     //first call for this unit
01338     Select_Lex_Unit *master_unit= select_lex->master_unit();
01339     substitution= optimizer;
01340 
01341     Select_Lex *current= session->lex().current_select, *up;
01342     session->lex().current_select= up= current->return_after_parsing();
01343     //optimizer never use Item **ref => we can pass 0 as parameter
01344     if (!optimizer || optimizer->fix_left(session, 0))
01345     {
01346       session->lex().current_select= current;
01347       return(RES_ERROR);
01348     }
01349 
01350     // we will refer to upper level cache array => we have to save it in PS
01351     optimizer->keep_top_level_cache();
01352 
01353     session->lex().current_select= current;
01354     master_unit->uncacheable.set(UNCACHEABLE_DEPENDENT);
01355 
01356     if (!abort_on_null && left_expr->maybe_null && !pushed_cond_guards)
01357     {
01358       pushed_cond_guards= new (join->session->mem) bool[left_expr->cols()];
01359       for (uint32_t i= 0; i < cols_num; i++)
01360         pushed_cond_guards[i]= true;
01361     }
01362   }
01363 
01364   /*
01365     If this IN predicate can be computed via materialization, do not
01366     perform the IN -> EXISTS transformation.
01367   */
01368   if (exec_method == MATERIALIZATION)
01369     return(RES_OK);
01370 
01371   /* Perform the IN=>EXISTS transformation. */
01372   return(row_value_in_to_exists_transformer(join));
01373 }
01374 
01375 
01394 Item_subselect::trans_res
01395 Item_in_subselect::row_value_in_to_exists_transformer(Join * join)
01396 {
01397   Select_Lex *select_lex= join->select_lex;
01398   Item *having_item= 0;
01399   uint32_t cols_num= left_expr->cols();
01400   bool is_having_used= (join->having || select_lex->with_sum_func ||
01401                         select_lex->group_list.first ||
01402                         !select_lex->table_list.elements);
01403 
01404   select_lex->uncacheable.set(UNCACHEABLE_DEPENDENT);
01405   if (is_having_used)
01406   {
01407     /*
01408       (l1, l2, l3) IN (SELECT v1, v2, v3 ... HAVING having) =>
01409       EXISTS (SELECT ... HAVING having and
01410                                 (l1 = v1 or is null v1) and
01411                                 (l2 = v2 or is null v2) and
01412                                 (l3 = v3 or is null v3) and
01413                                 is_not_null_test(v1) and
01414                                 is_not_null_test(v2) and
01415                                 is_not_null_test(v3))
01416       where is_not_null_test used to register nulls in case if we have
01417       not found matching to return correct NULL value
01418       TODO: say here explicitly if the order of AND parts matters or not.
01419     */
01420     Item *item_having_part2= 0;
01421     for (uint32_t i= 0; i < cols_num; i++)
01422     {
01423       assert((left_expr->fixed && select_lex->ref_pointer_array[i]->fixed) ||
01424                   (select_lex->ref_pointer_array[i]->type() == REF_ITEM &&
01425                    ((Item_ref*)(select_lex->ref_pointer_array[i]))->ref_type() ==
01426                     Item_ref::OUTER_REF));
01427       if (select_lex->ref_pointer_array[i]->
01428           check_cols(left_expr->element_index(i)->cols()))
01429         return(RES_ERROR);
01430       Item *item_eq=
01431         new Item_func_eq(new
01432                          Item_ref(&select_lex->context,
01433                                   (*optimizer->get_cache())->
01434                                   addr(i),
01435                                   "<no matter>",
01436                                   in_left_expr_name),
01437                          new
01438                          Item_ref(&select_lex->context,
01439                                   select_lex->ref_pointer_array + i,
01440                                   "<no matter>",
01441                                   "<list ref>")
01442                         );
01443       Item *item_isnull=
01444         new Item_func_isnull(new
01445                              Item_ref(&select_lex->context,
01446                                       select_lex->ref_pointer_array+i,
01447                                       "<no matter>",
01448                                       "<list ref>")
01449                             );
01450       Item *col_item= new Item_cond_or(item_eq, item_isnull);
01451       if (!abort_on_null && left_expr->element_index(i)->maybe_null)
01452         col_item= new Item_func_trig_cond(col_item, get_cond_guard(i));
01453       having_item= and_items(having_item, col_item);
01454 
01455       Item *item_nnull_test=
01456          new Item_is_not_null_test(this,
01457                                    new Item_ref(&select_lex->context,
01458                                                 select_lex->
01459                                                 ref_pointer_array + i,
01460                                                 "<no matter>",
01461                                                 "<list ref>"));
01462       if (!abort_on_null && left_expr->element_index(i)->maybe_null)
01463       {
01464         item_nnull_test= new Item_func_trig_cond(item_nnull_test, get_cond_guard(i));
01465       }
01466       item_having_part2= and_items(item_having_part2, item_nnull_test);
01467       item_having_part2->top_level_item();
01468     }
01469     having_item= and_items(having_item, item_having_part2);
01470     having_item->top_level_item();
01471   }
01472   else
01473   {
01474     /*
01475       (l1, l2, l3) IN (SELECT v1, v2, v3 ... WHERE where) =>
01476       EXISTS (SELECT ... WHERE where and
01477                                (l1 = v1 or is null v1) and
01478                                (l2 = v2 or is null v2) and
01479                                (l3 = v3 or is null v3)
01480                          HAVING is_not_null_test(v1) and
01481                                 is_not_null_test(v2) and
01482                                 is_not_null_test(v3))
01483       where is_not_null_test register NULLs values but reject rows
01484 
01485       in case when we do not need correct NULL, we have simplier construction:
01486       EXISTS (SELECT ... WHERE where and
01487                                (l1 = v1) and
01488                                (l2 = v2) and
01489                                (l3 = v3)
01490     */
01491     Item *where_item= 0;
01492     for (uint32_t i= 0; i < cols_num; i++)
01493     {
01494       Item *item, *item_isnull;
01495       assert((left_expr->fixed && select_lex->ref_pointer_array[i]->fixed) ||
01496                   (select_lex->ref_pointer_array[i]->type() == REF_ITEM &&
01497                    ((Item_ref*)(select_lex->ref_pointer_array[i]))->ref_type() ==
01498                     Item_ref::OUTER_REF));
01499       if (select_lex->ref_pointer_array[i]->
01500           check_cols(left_expr->element_index(i)->cols()))
01501         return(RES_ERROR);
01502       item=
01503         new Item_func_eq(new
01504                          Item_direct_ref(&select_lex->context,
01505                                          (*optimizer->get_cache())->
01506                                          addr(i),
01507                                          "<no matter>",
01508                                          in_left_expr_name),
01509                          new
01510                          Item_direct_ref(&select_lex->context,
01511                                          select_lex->
01512                                          ref_pointer_array+i,
01513                                          "<no matter>",
01514                                          "<list ref>")
01515                         );
01516       if (!abort_on_null)
01517       {
01518         Item *having_col_item=
01519           new Item_is_not_null_test(this,
01520                                     new
01521                                     Item_ref(&select_lex->context,
01522                                              select_lex->ref_pointer_array + i,
01523                                              "<no matter>",
01524                                              "<list ref>"));
01525 
01526 
01527         item_isnull= new
01528           Item_func_isnull(new
01529                            Item_direct_ref(&select_lex->context,
01530                                            select_lex->
01531                                            ref_pointer_array+i,
01532                                            "<no matter>",
01533                                            "<list ref>")
01534                           );
01535         item= new Item_cond_or(item, item_isnull);
01536         /*
01537           TODO: why we create the above for cases where the right part
01538                 cant be NULL?
01539         */
01540         if (left_expr->element_index(i)->maybe_null)
01541         {
01542           item= new Item_func_trig_cond(item, get_cond_guard(i));
01543           having_col_item= new Item_func_trig_cond(having_col_item, get_cond_guard(i));
01544         }
01545         having_item= and_items(having_item, having_col_item);
01546       }
01547       where_item= and_items(where_item, item);
01548     }
01549     /*
01550       AND can't be changed during fix_fields()
01551       we can assign select_lex->where here, and pass 0 as last
01552       argument (reference) to fix_fields()
01553     */
01554     select_lex->where= join->conds= and_items(join->conds, where_item);
01555     select_lex->where->top_level_item();
01556     if (join->conds->fix_fields(session, 0))
01557       return(RES_ERROR);
01558   }
01559   if (having_item)
01560   {
01561     bool res;
01562     select_lex->having= join->having= and_items(join->having, having_item);
01563     if (having_item == select_lex->having)
01564       having_item->name= (char*)in_having_cond;
01565     select_lex->having->top_level_item();
01566     /*
01567       AND can't be changed during fix_fields()
01568       we can assign select_lex->having here, and pass 0 as last
01569       argument (reference) to fix_fields()
01570     */
01571     select_lex->having_fix_field= 1;
01572     res= join->having->fix_fields(session, 0);
01573     select_lex->having_fix_field= 0;
01574     if (res)
01575     {
01576       return(RES_ERROR);
01577     }
01578   }
01579 
01580   return(RES_OK);
01581 }
01582 
01583 
01584 Item_subselect::trans_res
01585 Item_in_subselect::select_transformer(Join *join)
01586 {
01587   return select_in_like_transformer(join, Eq_creator::instance());
01588 }
01589 
01590 
01612 Item_subselect::trans_res
01613 Item_in_subselect::select_in_like_transformer(Join *join, const Comp_creator *func)
01614 {
01615   Select_Lex *current= session->lex().current_select, *up;
01616   const char *save_where= session->where();
01617   Item_subselect::trans_res res= RES_ERROR;
01618   bool result;
01619 
01620   {
01621     /*
01622       IN/SOME/ALL/ANY subqueries aren't support LIMIT clause. Without it
01623       ORDER BY clause becomes meaningless thus we drop it here.
01624     */
01625     Select_Lex *sl= current->master_unit()->first_select();
01626     for (; sl; sl= sl->next_select())
01627     {
01628       if (sl->join)
01629         sl->join->order= 0;
01630     }
01631   }
01632 
01633   if (changed)
01634     return(RES_OK);
01635 
01636   session->setWhere("IN/ALL/ANY subquery");
01637 
01638   /*
01639     In some optimisation cases we will not need this Item_in_optimizer
01640     object, but we can't know it here, but here we need address correct
01641     reference on left expresion.
01642   */
01643   if (!optimizer)
01644   {
01645     result= (!(optimizer= new Item_in_optimizer(left_expr, this)));
01646     if (result)
01647       goto err;
01648   }
01649 
01650   session->lex().current_select= up= current->return_after_parsing();
01651   result= (!left_expr->fixed &&
01652            left_expr->fix_fields(session, optimizer->arguments()));
01653   /* fix_fields can change reference to left_expr, we need reassign it */
01654   left_expr= optimizer->arguments()[0];
01655 
01656   session->lex().current_select= current;
01657   if (result)
01658     goto err;
01659 
01660   /*
01661     If we didn't choose an execution method up to this point, we choose
01662     the IN=>EXISTS transformation.
01663   */
01664   if (exec_method == NOT_TRANSFORMED)
01665     exec_method= IN_TO_EXISTS;
01666 
01667   /*
01668     Both transformers call fix_fields() only for Items created inside them,
01669     and all those items do not make permanent changes in the current item arena
01670     which allows us to call them with changed arena (if we do not know the
01671     nature of Item, we have to call fix_fields() for it only with the original
01672     arena to avoid memory leak).
01673   */
01674   if (left_expr->cols() == 1)
01675     res= single_value_transformer(join, func);
01676   else
01677   {
01678     /* we do not support row operation for ALL/ANY/SOME */
01679     if (func != Eq_creator::instance())
01680     {
01681       my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
01682       return(RES_ERROR);
01683     }
01684     res= row_value_transformer(join);
01685   }
01686 err:
01687   session->setWhere(save_where);
01688   return res;
01689 }
01690 
01691 
01692 void Item_in_subselect::print(String *str)
01693 {
01694   if (exec_method == IN_TO_EXISTS)
01695     str->append(STRING_WITH_LEN("<exists>"));
01696   else
01697   {
01698     left_expr->print(str);
01699     str->append(STRING_WITH_LEN(" in "));
01700   }
01701   Item_subselect::print(str);
01702 }
01703 
01704 
01705 bool Item_in_subselect::fix_fields(Session *session_arg, Item **ref)
01706 {
01707   bool result = 0;
01708 
01709   if (exec_method == SEMI_JOIN)
01710     return !( (*ref)= new Item_int(1));
01711 
01712   return result || Item_subselect::fix_fields(session_arg, ref);
01713 }
01714 
01715 
01740 bool Item_in_subselect::setup_engine()
01741 {
01742   subselect_hash_sj_engine *new_engine= NULL;
01743   bool res= false;
01744 
01745   if (engine->engine_type() == subselect_engine::SINGLE_SELECT_ENGINE)
01746   {
01747     /* Create/initialize objects in permanent memory. */
01748     subselect_single_select_engine *old_engine_ptr;
01749 
01750     old_engine_ptr= static_cast<subselect_single_select_engine *>(engine);
01751     new_engine= new subselect_hash_sj_engine(session, this, old_engine_ptr);
01752     if (new_engine->init_permanent(unit->get_unit_column_types()))
01753     {
01754       Item_subselect::trans_res new_trans_res;
01755       /*
01756         If for some reason we cannot use materialization for this IN predicate,
01757         delete all materialization-related objects, and apply the IN=>EXISTS
01758         transformation.
01759       */
01760       delete new_engine;
01761       new_engine= NULL;
01762       exec_method= NOT_TRANSFORMED;
01763       if (left_expr->cols() == 1)
01764         new_trans_res= single_value_in_to_exists_transformer(old_engine_ptr->join, Eq_creator::instance());
01765       else
01766         new_trans_res= row_value_in_to_exists_transformer(old_engine_ptr->join);
01767       res= (new_trans_res != Item_subselect::RES_OK);
01768     }
01769     if (new_engine)
01770       engine= new_engine;
01771   }
01772   else
01773   {
01774     assert(engine->engine_type() == subselect_engine::HASH_SJ_ENGINE);
01775     new_engine= static_cast<subselect_hash_sj_engine *>(engine);
01776   }
01777 
01778   /* Initilizations done in runtime memory, repeated for each execution. */
01779   if (new_engine)
01780   {
01781     /*
01782       Reset the LIMIT 1 set in Item_exists_subselect::fix_length_and_dec.
01783       TODO:
01784       Currently we set the subquery LIMIT to infinity, and this is correct
01785       because we forbid at parse time LIMIT inside IN subqueries (see
01786       Item_in_subselect::test_limit). However, once we allow this, here
01787       we should set the correct limit if given in the query.
01788     */
01789     unit->global_parameters->select_limit= NULL;
01790     new_engine->init_runtime();
01791   }
01792 
01793   return res;
01794 }
01795 
01796 
01809 bool Item_in_subselect::init_left_expr_cache()
01810 {
01811   Join *outer_join= NULL;
01812 
01813   outer_join= unit->outer_select()->join;
01814   if (! outer_join || ! outer_join->tables || ! outer_join->join_tab)
01815     return true;
01816 
01817   left_expr_cache= new List<Cached_item>;
01818 
01819   for (uint32_t i= 0; i < left_expr->cols(); i++)
01820   {
01821     Cached_item *cur_item_cache= new_Cached_item(session, left_expr->element_index(i));
01822     if (!cur_item_cache)
01823       return true;
01824     left_expr_cache->push_front(cur_item_cache);
01825   }
01826   return false;
01827 }
01828 
01829 
01830 /*
01831   Callback to test if an IN predicate is expensive.
01832 
01833   @details
01834     IN predicates are considered expensive only if they will be executed via
01835     materialization. The return value affects the behavior of
01836     make_cond_for_table() in such a way that it is unchanged when we use
01837     the IN=>EXISTS transformation to compute IN.
01838 
01839   @retval true  if the predicate is expensive
01840   @retval false otherwise
01841 */
01842 
01843 bool Item_in_subselect::is_expensive_processor(unsigned char *)
01844 {
01845   return exec_method == MATERIALIZATION;
01846 }
01847 
01848 
01849 Item_subselect::trans_res
01850 Item_allany_subselect::select_transformer(Join *join)
01851 {
01852   exec_method= IN_TO_EXISTS;
01853   if (upper_item)
01854     upper_item->show= 1;
01855   return(select_in_like_transformer(join, func));
01856 }
01857 
01858 
01859 void Item_allany_subselect::print(String *str)
01860 {
01861   if (exec_method == IN_TO_EXISTS)
01862     str->append(STRING_WITH_LEN("<exists>"));
01863   else
01864   {
01865     left_expr->print(str);
01866     str->append(' ');
01867     str->append(func->symbol(all));
01868     str->append(all ? " all " : " any ", 5);
01869   }
01870   Item_subselect::print(str);
01871 }
01872 
01873 
01874 void subselect_engine::set_session(Session *session_arg)
01875 {
01876   session= session_arg;
01877   if (result)
01878     result->set_session(session_arg);
01879 }
01880 
01881 
01882 subselect_single_select_engine::
01883 subselect_single_select_engine(Select_Lex *select,
01884              select_result_interceptor *result_arg,
01885              Item_subselect *item_arg)
01886   :subselect_engine(item_arg, result_arg),
01887    prepared(0), executed(0), select_lex(select), join(0)
01888 {
01889   select_lex->master_unit()->item= item_arg;
01890 }
01891 
01892 
01893 void subselect_single_select_engine::cleanup()
01894 {
01895   prepared= executed= 0;
01896   join= 0;
01897   result->cleanup();
01898   return;
01899 }
01900 
01901 
01902 void subselect_union_engine::cleanup()
01903 {
01904   unit->reinit_exec_mechanism();
01905   result->cleanup();
01906   return;
01907 }
01908 
01909 
01910 bool subselect_union_engine::is_executed() const
01911 {
01912   return unit->executed;
01913 }
01914 
01915 
01916 /*
01917   Check if last execution of the subquery engine produced any rows
01918 
01919   SYNOPSIS
01920     subselect_union_engine::no_rows()
01921 
01922   DESCRIPTION
01923     Check if last execution of the subquery engine produced any rows. The
01924     return value is undefined if last execution ended in an error.
01925 
01926   RETURN
01927     true  - Last subselect execution has produced no rows
01928     false - Otherwise
01929 */
01930 
01931 bool subselect_union_engine::no_rows()
01932 {
01933   /* Check if we got any rows when reading UNION result from temp. table: */
01934   return test(!unit->fake_select_lex->join->send_records);
01935 }
01936 
01937 
01938 void subselect_uniquesubquery_engine::cleanup()
01939 {
01940   /* Tell handler we don't need the index anymore */
01941   if (tab->table->cursor->inited)
01942     tab->table->cursor->endIndexScan();
01943   return;
01944 }
01945 
01946 
01947 subselect_union_engine::subselect_union_engine(Select_Lex_Unit *u,
01948                  select_result_interceptor *result_arg,
01949                  Item_subselect *item_arg)
01950   :subselect_engine(item_arg, result_arg)
01951 {
01952   unit= u;
01953   unit->item= item_arg;
01954 }
01955 
01956 
01983 int subselect_single_select_engine::prepare()
01984 {
01985   if (prepared)
01986     return 0;
01987   join= new Join(session, select_lex->item_list, select_lex->options | SELECT_NO_UNLOCK, result);
01988   if (not result)
01989     return 1; /* Fatal error is set already. */
01990   prepared= 1;
01991   Select_Lex *save_select= session->lex().current_select;
01992   session->lex().current_select= select_lex;
01993   if (join->prepare(&select_lex->ref_pointer_array,
01994         (TableList*) select_lex->table_list.first,
01995         select_lex->with_wild,
01996         select_lex->where,
01997         select_lex->order_list.elements +
01998         select_lex->group_list.elements,
01999         (Order*) select_lex->order_list.first,
02000         (Order*) select_lex->group_list.first,
02001         select_lex->having,
02002         select_lex, select_lex->master_unit()))
02003     return 1;
02004   session->lex().current_select= save_select;
02005   return 0;
02006 }
02007 
02008 int subselect_union_engine::prepare()
02009 {
02010   return unit->prepare(session, result, (uint32_t)SELECT_NO_UNLOCK);
02011 }
02012 
02013 int subselect_uniquesubquery_engine::prepare()
02014 {
02015   /* Should never be called. */
02016   assert(false);
02017   return 1;
02018 }
02019 
02020 
02021 /*
02022   Check if last execution of the subquery engine produced any rows
02023 
02024   SYNOPSIS
02025     subselect_single_select_engine::no_rows()
02026 
02027   DESCRIPTION
02028     Check if last execution of the subquery engine produced any rows. The
02029     return value is undefined if last execution ended in an error.
02030 
02031   RETURN
02032     true  - Last subselect execution has produced no rows
02033     false - Otherwise
02034 */
02035 
02036 bool subselect_single_select_engine::no_rows()
02037 {
02038   return !item->assigned();
02039 }
02040 
02041 
02042 /*
02043  makes storage for the output values for the subquery and calcuates
02044  their data and column types and their nullability.
02045 */
02046 void subselect_engine::set_row(List<Item> &item_list, Item_cache **row)
02047 {
02048   Item *sel_item;
02049   List<Item>::iterator li(item_list.begin());
02050   res_type= STRING_RESULT;
02051   res_field_type= DRIZZLE_TYPE_VARCHAR;
02052   for (uint32_t i= 0; (sel_item= li++); i++)
02053   {
02054     item->max_length= sel_item->max_length;
02055     res_type= sel_item->result_type();
02056     res_field_type= sel_item->field_type();
02057     item->decimals= sel_item->decimals;
02058     item->unsigned_flag= sel_item->unsigned_flag;
02059     maybe_null= sel_item->maybe_null;
02060     if (!(row[i]= Item_cache::get_cache(sel_item)))
02061       return;
02062     row[i]->setup(sel_item);
02063   }
02064   if (item_list.size() > 1)
02065     res_type= ROW_RESULT;
02066 }
02067 
02068 void subselect_single_select_engine::fix_length_and_dec(Item_cache **row)
02069 {
02070   assert(row || select_lex->item_list.size() == 1);
02071   set_row(select_lex->item_list, row);
02072   item->collation.set(row[0]->collation);
02073   if (cols() != 1)
02074     maybe_null= 0;
02075 }
02076 
02077 void subselect_union_engine::fix_length_and_dec(Item_cache **row)
02078 {
02079   assert(row || unit->first_select()->item_list.size() == 1);
02080 
02081   if (unit->first_select()->item_list.size() == 1)
02082   {
02083     set_row(unit->types, row);
02084     item->collation.set(row[0]->collation);
02085   }
02086   else
02087   {
02088     bool maybe_null_saved= maybe_null;
02089     set_row(unit->types, row);
02090     maybe_null= maybe_null_saved;
02091   }
02092 }
02093 
02094 void subselect_uniquesubquery_engine::fix_length_and_dec(Item_cache **)
02095 {
02096   //this never should be called
02097   assert(0);
02098 }
02099 
02100 int subselect_single_select_engine::exec()
02101 {
02102   char const *save_where= session->where();
02103   Select_Lex *save_select= session->lex().current_select;
02104   session->lex().current_select= select_lex;
02105   if (!join->optimized)
02106   {
02107     Select_Lex_Unit *unit= select_lex->master_unit();
02108 
02109     unit->set_limit(unit->global_parameters);
02110     if (join->optimize())
02111     {
02112       session->setWhere(save_where);
02113       executed= 1;
02114       session->lex().current_select= save_select;
02115       return(join->error ? join->error : 1);
02116     }
02117     save_join_if_explain();
02118     if (item->engine_changed)
02119     {
02120       return 1;
02121     }
02122   }
02123   if (select_lex->uncacheable.any() &&
02124       ! select_lex->uncacheable.test(UNCACHEABLE_EXPLAIN) &&
02125       executed)
02126   {
02127     if (join->reinit())
02128     {
02129       session->setWhere(save_where);
02130       session->lex().current_select= save_select;
02131       return 1;
02132     }
02133     item->reset();
02134     item->assigned((executed= 0));
02135   }
02136   if (!executed)
02137   {
02138     item->reset_value_registration();
02139     JoinTable *changed_tabs[MAX_TABLES];
02140     JoinTable **last_changed_tab= changed_tabs;
02141     if (item->have_guarded_conds())
02142     {
02143       /*
02144         For at least one of the pushed predicates the following is true:
02145         We should not apply optimizations based on the condition that was
02146         pushed down into the subquery. Those optimizations are ref[_or_null]
02147         acceses. Change them to be full table scans.
02148       */
02149       for (uint32_t i=join->const_tables ; i < join->tables ; i++)
02150       {
02151         JoinTable *tab=join->join_tab+i;
02152         if (tab && tab->keyuse)
02153         {
02154           for (uint32_t key_part= 0;
02155                key_part < tab->ref.key_parts;
02156                key_part++)
02157           {
02158             bool *cond_guard= tab->ref.cond_guards[key_part];
02159             if (cond_guard && !*cond_guard)
02160             {
02161               /* Change the access method to full table scan */
02162               tab->save_read_first_record= tab->read_first_record;
02163               tab->save_read_record= tab->read_record.read_record;
02164               tab->read_first_record= init_read_record_seq;
02165               tab->read_record.record= tab->table->record[0];
02166               tab->read_record.session= join->session;
02167               tab->read_record.ref_length= tab->table->cursor->ref_length;
02168               *(last_changed_tab++)= tab;
02169               break;
02170             }
02171           }
02172         }
02173       }
02174     }
02175 
02176     join->exec();
02177 
02178     /* Enable the optimizations back */
02179     for (JoinTable **ptab= changed_tabs; ptab != last_changed_tab; ptab++)
02180     {
02181       JoinTable *tab= *ptab;
02182       tab->read_record.record= 0;
02183       tab->read_record.ref_length= 0;
02184       tab->read_first_record= tab->save_read_first_record;
02185       tab->read_record.read_record= tab->save_read_record;
02186     }
02187     executed= 1;
02188     session->setWhere(save_where);
02189     session->lex().current_select= save_select;
02190     return(join->error||session->is_fatal_error);
02191   }
02192   session->setWhere(save_where);
02193   session->lex().current_select= save_select;
02194   return 0;
02195 }
02196 
02197 void subselect_single_select_engine::save_join_if_explain()
02198 {
02199   /*
02200     Save this JOIN to join->tmp_join since the original layout will be
02201     replaced when JOIN::exec() calls make_simple_join() if:
02202      1) We are executing an EXPLAIN query
02203      2) An uncacheable flag has not been set for the select_lex. If
02204         set, JOIN::optimize() has already saved the JOIN
02205      3) Call does not come from select_describe()). If it does,
02206         JOIN::exec() will not call make_simple_join() and the JOIN we
02207         plan to save will not be replaced anyway.
02208      4) A temp table is needed. This is what triggers JOIN::exec() to
02209         make a replacement JOIN by calling make_simple_join(). 
02210      5) The Item_subselect is cacheable
02211   */
02212   if (session->lex().describe &&                          // 1
02213       select_lex->uncacheable.none() &&                  // 2
02214       !(join->select_options & SELECT_DESCRIBE) &&       // 3
02215       join->need_tmp &&                                  // 4
02216       item->const_item())                                // 5
02217   {
02218     /*
02219       Save this JOIN to join->tmp_join since the original layout will
02220       be replaced when JOIN::exec() calls make_simple_join() due to
02221       need_tmp==TRUE. The original layout is needed so we can describe
02222       the query. No need to do this if uncacheable != 0 since in this
02223       case the JOIN has already been saved during JOIN::optimize()
02224     */
02225     select_lex->uncacheable.set(UNCACHEABLE_EXPLAIN);
02226     select_lex->master_unit()->uncacheable.set(UNCACHEABLE_EXPLAIN);
02227     join->init_save_join_tab();
02228   }
02229 }
02230 
02231 
02232 int subselect_union_engine::exec()
02233 {
02234   char const *save_where= session->where();
02235   int res= unit->exec();
02236   session->setWhere(save_where);
02237 
02238   return res;
02239 }
02240 
02241 
02242 /*
02243   Search for at least one row satisfying select condition
02244 
02245   SYNOPSIS
02246     subselect_uniquesubquery_engine::scan_table()
02247 
02248   DESCRIPTION
02249     Scan the table using sequential access until we find at least one row
02250     satisfying select condition.
02251 
02252     The caller must set this->empty_result_set=false before calling this
02253     function. This function will set it to true if it finds a matching row.
02254 
02255   RETURN
02256     false - OK
02257     true  - Error
02258 */
02259 
02260 int subselect_uniquesubquery_engine::scan_table()
02261 {
02262   int error;
02263   Table *table= tab->table;
02264 
02265   if (table->cursor->inited)
02266     table->cursor->endIndexScan();
02267 
02268   if ((error= table->cursor->startTableScan(1)))
02269   {
02270     table->print_error(error, MYF(0));
02271     return 1;
02272   }
02273 
02274   assert(table->getSession());
02275   table->cursor->extra_opt(HA_EXTRA_CACHE,
02276                            table->getSession()->variables.read_buff_size);
02277   table->null_row= 0;
02278   for (;;)
02279   {
02280     error=table->cursor->rnd_next(table->record[0]);
02281     if (error && error != HA_ERR_END_OF_FILE)
02282     {
02283       error= table->report_error(error);
02284       break;
02285     }
02286     /* No more rows */
02287     if (table->status)
02288       break;
02289 
02290     if (!cond || cond->val_int())
02291     {
02292       empty_result_set= false;
02293       break;
02294     }
02295   }
02296 
02297   table->cursor->endTableScan();
02298   return(error != 0);
02299 }
02300 
02301 
02302 /*
02303   Copy ref key and check for null parts in it
02304 
02305   SYNOPSIS
02306     subselect_uniquesubquery_engine::copy_ref_key()
02307 
02308   DESCRIPTION
02309     Copy ref key and check for null parts in it.
02310     Depending on the nullability and conversion problems this function
02311     recognizes and processes the following states :
02312       1. Partial match on top level. This means IN has a value of false
02313          regardless of the data in the subquery table.
02314          Detected by finding a NULL in the left IN operand of a top level
02315          expression.
02316          We may actually skip reading the subquery, so return true to skip
02317          the table scan in subselect_uniquesubquery_engine::exec and make
02318          the value of the IN predicate a NULL (that is equal to false on
02319          top level).
02320       2. No exact match when IN is nested inside another predicate.
02321          Detected by finding a NULL in the left IN operand when IN is not
02322          a top level predicate.
02323          We cannot have an exact match. But we must proceed further with a
02324          table scan to find out if it's a partial match (and IN has a value
02325          of NULL) or no match (and IN has a value of false).
02326          So we return false to continue with the scan and see if there are
02327          any record that would constitute a partial match (as we cannot
02328          determine that from the index).
02329       3. Error converting the left IN operand to the column type of the
02330          right IN operand. This counts as no match (and IN has the value of
02331          false). We mark the subquery table cursor as having no more rows
02332          (to ensure that the processing that follows will not find a match)
02333          and return false, so IN is not treated as returning NULL.
02334 
02335 
02336   RETURN
02337     false - The value of the IN predicate is not known. Proceed to find the
02338             value of the IN predicate using the determined values of
02339             null_keypart and table->status.
02340     true  - IN predicate has a value of NULL. Stop the processing right there
02341             and return NULL to the outer predicates.
02342 */
02343 
02344 bool subselect_uniquesubquery_engine::copy_ref_key()
02345 {
02346   for (StoredKey **copy= tab->ref.key_copy ; *copy ; copy++)
02347   {
02348     StoredKey::store_key_result store_res= (*copy)->copy();
02349     tab->ref.key_err= store_res;
02350 
02351     /*
02352       When there is a NULL part in the key we don't need to make index
02353       lookup for such key thus we don't need to copy whole key.
02354       If we later should do a sequential scan return OK. Fail otherwise.
02355 
02356       See also the comment for the subselect_uniquesubquery_engine::exec()
02357       function.
02358     */
02359     null_keypart= (*copy)->null_key;
02360     if (null_keypart)
02361     {
02362       bool top_level= ((Item_in_subselect *) item)->is_top_level_item();
02363       if (top_level)
02364       {
02365         /* Partial match on top level */
02366         return 1;
02367       }
02368       else
02369       {
02370         /* No exact match when IN is nested inside another predicate */
02371         break;
02372       }
02373     }
02374 
02375     /*
02376       Check if the error is equal to STORE_KEY_FATAL. This is not expressed
02377       using the StoredKey::store_key_result enum because ref.key_err is a
02378       boolean and we want to detect both true and STORE_KEY_FATAL from the
02379       space of the union of the values of [true, false] and
02380       StoredKey::store_key_result.
02381       TODO: fix the variable an return types.
02382     */
02383     if (store_res == StoredKey::STORE_KEY_FATAL)
02384     {
02385       /*
02386        Error converting the left IN operand to the column type of the right
02387        IN operand.
02388       */
02389       tab->table->status= STATUS_NOT_FOUND;
02390       break;
02391     }
02392   }
02393   return 0;
02394 }
02395 
02396 
02397 /*
02398   Execute subselect
02399 
02400   SYNOPSIS
02401     subselect_uniquesubquery_engine::exec()
02402 
02403   DESCRIPTION
02404     Find rows corresponding to the ref key using index access.
02405     If some part of the lookup key is NULL, then we're evaluating
02406       NULL IN (SELECT ... )
02407     This is a special case, we don't need to search for NULL in the table,
02408     instead, the result value is
02409       - NULL  if select produces empty row set
02410       - false otherwise.
02411 
02412     In some cases (IN subselect is a top level item, i.e. abort_on_null==true)
02413     the caller doesn't distinguish between NULL and false result and we just
02414     return false.
02415     Otherwise we make a full table scan to see if there is at least one
02416     matching row.
02417 
02418     The result of this function (info about whether a row was found) is
02419     stored in this->empty_result_set.
02420   NOTE
02421 
02422   RETURN
02423     false - ok
02424     true  - an error occured while scanning
02425 */
02426 
02427 int subselect_uniquesubquery_engine::exec()
02428 {
02429   int error;
02430   Table *table= tab->table;
02431   empty_result_set= true;
02432   table->status= 0;
02433 
02434   /* TODO: change to use of 'full_scan' here? */
02435   if (copy_ref_key())
02436     return 1;
02437   if (table->status)
02438   {
02439     /*
02440       We know that there will be no rows even if we scan.
02441       Can be set in copy_ref_key.
02442     */
02443     ((Item_in_subselect *) item)->value= 0;
02444     return 0;
02445   }
02446 
02447   if (null_keypart)
02448     return(scan_table());
02449 
02450   if (!table->cursor->inited)
02451   {
02452     error= table->cursor->startIndexScan(tab->ref.key, 0);
02453 
02454     if (error != 0)
02455     {
02456       error= table->report_error(error);
02457       return (error != 0);
02458     }
02459   }
02460 
02461   error= table->cursor->index_read_map(table->record[0],
02462                                      tab->ref.key_buff,
02463                                      make_prev_keypart_map(tab->ref.key_parts),
02464                                      HA_READ_KEY_EXACT);
02465   if (error &&
02466       error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
02467     error= table->report_error(error);
02468   else
02469   {
02470     error= 0;
02471     table->null_row= 0;
02472     if (!table->status && (!cond || cond->val_int()))
02473     {
02474       ((Item_in_subselect *) item)->value= 1;
02475       empty_result_set= false;
02476     }
02477     else
02478       ((Item_in_subselect *) item)->value= 0;
02479   }
02480 
02481   return(error != 0);
02482 }
02483 
02484 
02485 /*
02486   Index-lookup subselect 'engine' - run the subquery
02487 
02488   SYNOPSIS
02489     subselect_indexsubquery_engine:exec()
02490       full_scan
02491 
02492   DESCRIPTION
02493     The engine is used to resolve subqueries in form
02494 
02495       oe IN (SELECT key FROM tbl WHERE subq_where)
02496 
02497     The value of the predicate is calculated as follows:
02498     1. If oe IS NULL, this is a special case, do a full table scan on
02499        table tbl and search for row that satisfies subq_where. If such
02500        row is found, return NULL, otherwise return false.
02501     2. Make an index lookup via key=oe, search for a row that satisfies
02502        subq_where. If found, return true.
02503     3. If check_null==true, make another lookup via key=NULL, search for a
02504        row that satisfies subq_where. If found, return NULL, otherwise
02505        return false.
02506 
02507   TODO
02508     The step #1 can be optimized further when the index has several key
02509     parts. Consider a subquery:
02510 
02511       (oe1, oe2) IN (SELECT keypart1, keypart2 FROM tbl WHERE subq_where)
02512 
02513     and suppose we need to evaluate it for {oe1, oe2}=={const1, NULL}.
02514     Current code will do a full table scan and obtain correct result. There
02515     is a better option: instead of evaluating
02516 
02517       SELECT keypart1, keypart2 FROM tbl WHERE subq_where            (1)
02518 
02519     and checking if it has produced any matching rows, evaluate
02520 
02521       SELECT keypart2 FROM tbl WHERE subq_where AND keypart1=const1  (2)
02522 
02523     If this query produces a row, the result is NULL (as we're evaluating
02524     "(const1, NULL) IN { (const1, X), ... }", which has a value of UNKNOWN,
02525     i.e. NULL).  If the query produces no rows, the result is false.
02526 
02527     We currently evaluate (1) by doing a full table scan. (2) can be
02528     evaluated by doing a "ref" scan on "keypart1=const1", which can be much
02529     cheaper. We can use index statistics to quickly check whether "ref" scan
02530     will be cheaper than full table scan.
02531 
02532   RETURN
02533     0
02534     1
02535 */
02536 
02537 int subselect_indexsubquery_engine::exec()
02538 {
02539   int error;
02540   bool null_finding= 0;
02541   Table *table= tab->table;
02542 
02543   ((Item_in_subselect *) item)->value= 0;
02544   empty_result_set= true;
02545   null_keypart= 0;
02546   table->status= 0;
02547 
02548   if (check_null)
02549   {
02550     /* We need to check for NULL if there wasn't a matching value */
02551     *tab->ref.null_ref_key= 0;      // Search first for not null
02552     ((Item_in_subselect *) item)->was_null= 0;
02553   }
02554 
02555   /* Copy the ref key and check for nulls... */
02556   if (copy_ref_key())
02557     return 1;
02558 
02559   if (table->status)
02560   {
02561     /*
02562       We know that there will be no rows even if we scan.
02563       Can be set in copy_ref_key.
02564     */
02565     ((Item_in_subselect *) item)->value= 0;
02566     return 0;
02567   }
02568 
02569   if (null_keypart)
02570     return(scan_table());
02571 
02572   if (!table->cursor->inited)
02573   {
02574     error= table->cursor->startIndexScan(tab->ref.key, 1);
02575 
02576     if (error != 0)
02577     {
02578       error= table->report_error(error);
02579       return(error != 0);
02580     }
02581   }
02582   error= table->cursor->index_read_map(table->record[0],
02583                                      tab->ref.key_buff,
02584                                      make_prev_keypart_map(tab->ref.key_parts),
02585                                      HA_READ_KEY_EXACT);
02586   if (error &&
02587       error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
02588     error= table->report_error(error);
02589   else
02590   {
02591     for (;;)
02592     {
02593       error= 0;
02594       table->null_row= 0;
02595       if (!table->status)
02596       {
02597         if ((!cond || cond->val_int()) && (!having || having->val_int()))
02598         {
02599           empty_result_set= false;
02600           if (null_finding)
02601             ((Item_in_subselect *) item)->was_null= 1;
02602           else
02603             ((Item_in_subselect *) item)->value= 1;
02604           break;
02605         }
02606         error= table->cursor->index_next_same(table->record[0],
02607                                             tab->ref.key_buff,
02608                                             tab->ref.key_length);
02609         if (error && error != HA_ERR_END_OF_FILE)
02610         {
02611           error= table->report_error(error);
02612           break;
02613         }
02614       }
02615       else
02616       {
02617         if (!check_null || null_finding)
02618           break;      /* We don't need to check nulls */
02619         *tab->ref.null_ref_key= 1;
02620         null_finding= 1;
02621         /* Check if there exists a row with a null value in the index */
02622         if ((error= (safe_index_read(tab) == 1)))
02623           break;
02624       }
02625     }
02626   }
02627   return(error != 0);
02628 }
02629 
02630 
02631 uint32_t subselect_single_select_engine::cols()
02632 {
02633   return select_lex->item_list.size();
02634 }
02635 
02636 
02637 uint32_t subselect_union_engine::cols()
02638 {
02639   return unit->types.size();
02640 }
02641 
02642 
02643 bool subselect_single_select_engine::uncacheable()
02644 {
02645   return select_lex->uncacheable.any();
02646 }
02647 
02648 
02649 bool subselect_single_select_engine::uncacheable(uint32_t bit_pos)
02650 {
02651   return select_lex->uncacheable.test(bit_pos);
02652 }
02653 
02654 
02655 bool subselect_union_engine::uncacheable()
02656 {
02657   return unit->uncacheable.any();
02658 }
02659 
02660 
02661 bool subselect_union_engine::uncacheable(uint32_t bit_pos)
02662 {
02663   return unit->uncacheable.test(bit_pos);
02664 }
02665 
02666 
02667 void subselect_single_select_engine::exclude()
02668 {
02669   select_lex->master_unit()->exclude_level();
02670 }
02671 
02672 void subselect_union_engine::exclude()
02673 {
02674   unit->exclude_level();
02675 }
02676 
02677 
02678 void subselect_uniquesubquery_engine::exclude()
02679 {
02680   //this never should be called
02681   assert(0);
02682 }
02683 
02684 
02685 table_map subselect_engine::calc_const_tables(TableList *table)
02686 {
02687   table_map map= 0;
02688   for (; table; table= table->next_leaf)
02689   {
02690     Table *tbl= table->table;
02691     if (tbl && tbl->const_table)
02692       map|= tbl->map;
02693   }
02694   return map;
02695 }
02696 
02697 
02698 table_map subselect_single_select_engine::upper_select_const_tables()
02699 {
02700   return calc_const_tables((TableList *) select_lex->outer_select()->
02701          leaf_tables);
02702 }
02703 
02704 
02705 table_map subselect_union_engine::upper_select_const_tables()
02706 {
02707   return calc_const_tables((TableList *) unit->outer_select()->leaf_tables);
02708 }
02709 
02710 
02711 void subselect_single_select_engine::print(String *str)
02712 {
02713   select_lex->print(session, str);
02714 }
02715 
02716 
02717 void subselect_union_engine::print(String *str)
02718 {
02719   unit->print(str);
02720 }
02721 
02722 
02723 void subselect_uniquesubquery_engine::print(String *str)
02724 {
02725   str->append(STRING_WITH_LEN("<primary_index_lookup>("));
02726   tab->ref.items[0]->print(str);
02727   str->append(STRING_WITH_LEN(" in "));
02728   if (tab->table->getShare()->isTemporaryCategory())
02729   {
02730     /*
02731       Temporary tables' names change across runs, so they can't be used for
02732       EXPLAIN EXTENDED.
02733     */
02734     str->append(STRING_WITH_LEN("<temporary table>"));
02735   }
02736   else
02737     str->append(tab->table->getShare()->getTableNameRef());
02738   str->append(STRING_WITH_LEN(" on "));
02739   str->append(tab->table->key_info[tab->ref.key].name);
02740   if (cond)
02741   {
02742     str->append(STRING_WITH_LEN(" where "));
02743     cond->print(str);
02744   }
02745   str->append(')');
02746 }
02747 
02748 /*
02749 TODO:
02750 The above ::print method should be changed as below. Do it after
02751 all other tests pass.
02752 
02753 void subselect_uniquesubquery_engine::print(String *str)
02754 {
02755   KEY *key_info= tab->table->key_info + tab->ref.key;
02756   str->append(STRING_WITH_LEN("<primary_index_lookup>("));
02757   for (uint32_t i= 0; i < key_info->key_parts; i++)
02758     tab->ref.items[i]->print(str);
02759   str->append(STRING_WITH_LEN(" in "));
02760   str->append(tab->table->getShare()->getTableName(), tab->table->getShare()->getTableNameSize());
02761   str->append(STRING_WITH_LEN(" on "));
02762   str->append(key_info->name);
02763   if (cond)
02764   {
02765     str->append(STRING_WITH_LEN(" where "));
02766     cond->print(str);
02767   }
02768   str->append(')');
02769 }
02770 */
02771 
02772 void subselect_indexsubquery_engine::print(String *str)
02773 {
02774   str->append(STRING_WITH_LEN("<index_lookup>("));
02775   tab->ref.items[0]->print(str);
02776   str->append(STRING_WITH_LEN(" in "));
02777   str->append(tab->table->getShare()->getTableNameRef());
02778   KeyInfo *key_info= tab->table->key_info+ tab->ref.key;
02779   str->append(STRING_WITH_LEN(" on "));
02780   str->append(key_info->name);
02781   if (check_null)
02782     str->append(STRING_WITH_LEN(" checking NULL"));
02783   if (cond)
02784   {
02785     str->append(STRING_WITH_LEN(" where "));
02786     cond->print(str);
02787   }
02788   if (having)
02789   {
02790     str->append(STRING_WITH_LEN(" having "));
02791     having->print(str);
02792   }
02793   str->append(')');
02794 }
02795 
02808 bool subselect_single_select_engine::change_result(Item_subselect *si,
02809                                                  select_result_interceptor *res)
02810 {
02811   item= si;
02812   result= res;
02813   return select_lex->join->change_result(result);
02814 }
02815 
02816 
02829 bool subselect_union_engine::change_result(Item_subselect *si,
02830                                            select_result_interceptor *res)
02831 {
02832   item= si;
02833   int rc= unit->change_result(res, result);
02834   result= res;
02835   return rc;
02836 }
02837 
02838 
02851 bool subselect_uniquesubquery_engine::change_result(Item_subselect *,
02852                                                     select_result_interceptor *)
02853 {
02854   assert(0);
02855   return true;
02856 }
02857 
02858 
02867 bool subselect_single_select_engine::no_tables()
02868 {
02869   return(select_lex->table_list.elements == 0);
02870 }
02871 
02872 
02873 /*
02874   Check statically whether the subquery can return NULL
02875 
02876   SINOPSYS
02877     subselect_single_select_engine::may_be_null()
02878 
02879   RETURN
02880     false  can guarantee that the subquery never return NULL
02881     true   otherwise
02882 */
02883 bool subselect_single_select_engine::may_be_null()
02884 {
02885   return ((no_tables() && !join->conds && !join->having) ? maybe_null : 1);
02886 }
02887 
02888 
02897 bool subselect_union_engine::no_tables()
02898 {
02899   for (Select_Lex *sl= unit->first_select(); sl; sl= sl->next_select())
02900   {
02901     if (sl->table_list.elements)
02902       return false;
02903   }
02904   return true;
02905 }
02906 
02907 
02917 bool subselect_uniquesubquery_engine::no_tables()
02918 {
02919   /* returning value is correct, but this method should never be called */
02920   return 0;
02921 }
02922 
02923 
02924 /******************************************************************************
02925   WL#1110 - Implementation of class subselect_hash_sj_engine
02926 ******************************************************************************/
02927 
02928 
02949 bool subselect_hash_sj_engine::init_permanent(List<Item> *tmp_columns)
02950 {
02951   /* The result sink where we will materialize the subquery result. */
02952   select_union  *tmp_result_sink;
02953   /* The table into which the subquery is materialized. */
02954   Table         *tmp_table;
02955   KeyInfo           *tmp_key; /* The only index on the temporary table. */
02956   uint32_t          tmp_key_parts; /* Number of keyparts in tmp_key. */
02957   Item_in_subselect *item_in= (Item_in_subselect *) item;
02958 
02959   /* 1. Create/initialize materialization related objects. */
02960 
02961   /*
02962     Create and initialize a select result interceptor that stores the
02963     result stream in a temporary table. The temporary table itself is
02964     managed (created/filled/etc) internally by the interceptor.
02965   */
02966   tmp_result_sink= new select_union;
02967 
02968   if (tmp_result_sink->create_result_table(session, tmp_columns, true, 
02969     session->options | TMP_TABLE_ALL_COLUMNS, "materialized subselect"))
02970     return true;
02971 
02972   tmp_table= tmp_result_sink->table;
02973   tmp_key= tmp_table->key_info;
02974   tmp_key_parts= tmp_key->key_parts;
02975 
02976   /*
02977      If the subquery has blobs, or the total key lenght is bigger than some
02978      length, then the created index cannot be used for lookups and we
02979      can't use hash semi join. If this is the case, delete the temporary
02980      table since it will not be used, and tell the caller we failed to
02981      initialize the engine.
02982   */
02983   if (tmp_table->getShare()->sizeKeys() == 0)
02984   {
02985     assert(tmp_table->getShare()->db_type() == myisam_engine);
02986     assert(
02987       tmp_table->getShare()->uniques ||
02988       tmp_table->key_info->key_length >= tmp_table->cursor->getEngine()->max_key_length() ||
02989       tmp_table->key_info->key_parts > tmp_table->cursor->getEngine()->max_key_parts());
02990     tmp_table= NULL;
02991     delete result;
02992     result= NULL;
02993     return true;
02994   }
02995   result= tmp_result_sink;
02996 
02997   /*
02998     Make sure there is only one index on the temp table, and it doesn't have
02999     the extra key part created when s->uniques > 0.
03000   */
03001   assert(tmp_table->getShare()->sizeKeys() == 1 && tmp_columns->size() == tmp_key_parts);
03002 
03003 
03004   /* 2. Create/initialize execution related objects. */
03005 
03006   /*
03007     Create and initialize the JoinTable that represents an index lookup
03008     plan operator into the materialized subquery result. Notice that:
03009     - this JoinTable has no corresponding JOIN (and doesn't need one), and
03010     - here we initialize only those members that are used by
03011       subselect_uniquesubquery_engine, so these objects are incomplete.
03012   */
03013   tab= new (session->mem) JoinTable;
03014   tab->table= tmp_table;
03015   tab->ref.key= 0; /* The only temp table index. */
03016   tab->ref.key_length= tmp_key->key_length;
03017   tab->ref.key_buff= (unsigned char*) session->mem.calloc(ALIGN_SIZE(tmp_key->key_length) * 2);
03018   tab->ref.key_copy= new (session->mem) StoredKey*[tmp_key_parts + 1];
03019   tab->ref.items= new (session->mem) Item*[tmp_key_parts];
03020 
03021   KeyPartInfo *cur_key_part= tmp_key->key_part;
03022   StoredKey **ref_key= tab->ref.key_copy;
03023   unsigned char *cur_ref_buff= tab->ref.key_buff;
03024 
03025   for (uint32_t i= 0; i < tmp_key_parts; i++, cur_key_part++, ref_key++)
03026   {
03027     tab->ref.items[i]= item_in->left_expr->element_index(i);
03028     int null_count= test(cur_key_part->field->real_maybe_null());
03029     *ref_key= new store_key_item(session, cur_key_part->field,
03030                                  /* TODO:
03031                                     the NULL byte is taken into account in
03032                                     cur_key_part->store_length, so instead of
03033                                     cur_ref_buff + test(maybe_null), we could
03034                                     use that information instead.
03035                                  */
03036                                  cur_ref_buff + null_count,
03037                                  null_count ? tab->ref.key_buff : 0,
03038                                  cur_key_part->length, tab->ref.items[i]);
03039     cur_ref_buff+= cur_key_part->store_length;
03040   }
03041   *ref_key= NULL; /* End marker. */
03042   tab->ref.key_err= 1;
03043   tab->ref.key_parts= tmp_key_parts;
03044 
03045   return false;
03046 }
03047 
03048 
03057 void subselect_hash_sj_engine::init_runtime()
03058 {
03059   /*
03060     Create and optimize the JOIN that will be used to materialize
03061     the subquery if not yet created.
03062   */
03063   materialize_engine->prepare();
03064   /* Let our engine reuse this query plan for materialization. */
03065   materialize_join= materialize_engine->join;
03066   materialize_join->change_result(result);
03067 }
03068 
03069 
03070 subselect_hash_sj_engine::~subselect_hash_sj_engine()
03071 {
03072   delete result;
03073   if (tab)
03074   {
03075     tab->table= NULL;
03076   }
03077 }
03078 
03079 
03087 void subselect_hash_sj_engine::cleanup()
03088 {
03089   is_materialized= false;
03090   result->cleanup(); /* Resets the temp table as well. */
03091   materialize_engine->cleanup();
03092   subselect_uniquesubquery_engine::cleanup();
03093 }
03094 
03095 
03107 int subselect_hash_sj_engine::exec()
03108 {
03109   Item_in_subselect *item_in= (Item_in_subselect *) item;
03110 
03111   /*
03112     Optimize and materialize the subquery during the first execution of
03113     the subquery predicate.
03114   */
03115   if (!is_materialized)
03116   {
03117     int res= 0;
03118     Select_Lex *save_select= session->lex().current_select;
03119     session->lex().current_select= materialize_engine->select_lex;
03120     if ((res= materialize_join->optimize()))
03121       goto err;
03122 
03123     materialize_engine->save_join_if_explain();
03124 
03125     materialize_join->exec();
03126     if ((res= test(materialize_join->error || session->is_fatal_error)))
03127       goto err;
03128 
03129     /*
03130       TODO:
03131       - Unlock all subquery tables as we don't need them. To implement this
03132         we need to add new functionality to Join::join_free that can unlock
03133         all tables in a subquery (and all its subqueries).
03134       - The temp table used for grouping in the subquery can be freed
03135         immediately after materialization (yet it's done together with
03136         unlocking).
03137      */
03138     is_materialized= true;
03139     /*
03140       If the subquery returned no rows, the temporary table is empty, so we know
03141       directly that the result of IN is false. We first update the table
03142       statistics, then we test if the temporary table for the query result is
03143       empty.
03144     */
03145     tab->table->cursor->info(HA_STATUS_VARIABLE);
03146     if (!tab->table->cursor->stats.records)
03147     {
03148       empty_result_set= true;
03149       item_in->value= false;
03150       /* TODO: check we need this: item_in->null_value= false; */
03151       return false;
03152     }
03153     /* Set tmp_param only if its usable, i.e. tmp_param->copy_field != NULL. */
03154     tmp_param= &(item_in->unit->outer_select()->join->tmp_table_param);
03155     if (tmp_param && !tmp_param->copy_field)
03156       tmp_param= NULL;
03157 
03158 err:
03159     session->lex().current_select= save_select;
03160     if (res)
03161       return res;
03162   }
03163 
03164   /*
03165     Lookup the left IN operand in the hash index of the materialized subquery.
03166   */
03167   return(subselect_uniquesubquery_engine::exec());
03168 }
03169 
03170 
03175 void subselect_hash_sj_engine::print(String *str)
03176 {
03177   str->append(STRING_WITH_LEN(" <materialize> ("));
03178   materialize_engine->print(str);
03179   str->append(STRING_WITH_LEN(" ), "));
03180   if (tab)
03181     subselect_uniquesubquery_engine::print(str);
03182   else
03183     str->append(STRING_WITH_LEN(
03184            "<the access method for lookups is not yet created>"
03185          ));
03186 }
03187 
03188 } /* namespace drizzled */