Drizzled Public API Documentation

sql_base.cc

00001 /* Copyright (C) 2000-2006 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 
00016 
00017 /* Basic functions needed by many modules */
00018 #include <config.h>
00019 #include <assert.h>
00020 
00021 #include <signal.h>
00022 
00023 #if TIME_WITH_SYS_TIME
00024 # include <sys/time.h>
00025 # include <time.h>
00026 #else
00027 # if HAVE_SYS_TIME_H
00028 #  include <sys/time.h>
00029 # else
00030 #  include <time.h>
00031 # endif
00032 #endif
00033 #include <drizzled/internal/my_pthread.h>
00034 #include <drizzled/internal/thread_var.h>
00035 
00036 #include <drizzled/sql_select.h>
00037 #include <drizzled/error.h>
00038 #include <drizzled/gettext.h>
00039 #include <drizzled/nested_join.h>
00040 #include <drizzled/sql_base.h>
00041 #include <drizzled/show.h>
00042 #include <drizzled/item/cmpfunc.h>
00043 #include <drizzled/replication_services.h>
00044 #include <drizzled/check_stack_overrun.h>
00045 #include <drizzled/lock.h>
00046 #include <drizzled/plugin/listen.h>
00047 #include <drizzled/cached_directory.h>
00048 #include <drizzled/field/epoch.h>
00049 #include <drizzled/field/null.h>
00050 #include <drizzled/sql_table.h>
00051 #include <drizzled/global_charset_info.h>
00052 #include <drizzled/pthread_globals.h>
00053 #include <drizzled/internal/iocache.h>
00054 #include <drizzled/drizzled.h>
00055 #include <drizzled/plugin/authorization.h>
00056 #include <drizzled/table/temporary.h>
00057 #include <drizzled/table/placeholder.h>
00058 #include <drizzled/table/unused.h>
00059 #include <drizzled/plugin/storage_engine.h>
00060 #include <drizzled/session.h>
00061 #include <drizzled/item/subselect.h>
00062 #include <drizzled/sql_lex.h>
00063 
00064 #include <drizzled/refresh_version.h>
00065 
00066 using namespace std;
00067 
00068 namespace drizzled
00069 {
00070 
00071 extern bool volatile shutdown_in_progress;
00072 
00073 bool table_cache_init(void)
00074 {
00075   return false;
00076 }
00077 
00078 uint32_t cached_open_tables(void)
00079 {
00080   return table::getCache().size();
00081 }
00082 
00083 void table_cache_free(void)
00084 {
00085   refresh_version++;        // Force close of open tables
00086 
00087   table::getUnused().clear();
00088   table::getCache().clear();
00089 }
00090 
00091 /*
00092   Close cursor handle, but leave the table in the table cache
00093 
00094   SYNOPSIS
00095   close_handle_and_leave_table_as_lock()
00096   table   Table Cursor
00097 
00098   NOTES
00099   By leaving the table in the table cache, it disallows any other thread
00100   to open the table
00101 
00102   session->getKilled() will be set if we run out of memory
00103 
00104   If closing a MERGE child, the calling function has to take care for
00105   closing the parent too, if necessary.
00106 */
00107 
00108 
00109 void close_handle_and_leave_table_as_lock(Table *table)
00110 {
00111   assert(table->db_stat);
00112   assert(table->getShare()->getType() == message::Table::STANDARD);
00113 
00114   /*
00115     Make a local copy of the table share and free the current one.
00116     This has to be done to ensure that the table share is removed from
00117     the table defintion cache as soon as the last instance is removed
00118   */
00119   identifier::Table identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
00120   const identifier::Table::Key &key(identifier.getKey());
00121   TableShare *share= new TableShare(identifier.getType(),
00122                                     identifier,
00123                                     const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
00124 
00125   table->cursor->close();
00126   table->db_stat= 0;                            // Mark cursor closed
00127   table::instance::release(table->getMutableShare());
00128   table->setShare(share);
00129 }
00130 
00131 
00132 /*****************************************************************************
00133  *   Functions to free open table cache
00134  ****************************************************************************/
00135 
00136 
00137 void Table::intern_close_table()
00138 {           // Free all structures
00139   free_io_cache();
00140   if (cursor)                              // Not true if name lock
00141   {
00142     delete_table(true);     // close cursor
00143   }
00144 }
00145 
00146 /* Free resources allocated by filesort() and read_record() */
00147 
00148 void Table::free_io_cache()
00149 {
00150   if (sort.io_cache)
00151   {
00152     sort.io_cache->close_cached_file();
00153     safe_delete(sort.io_cache);
00154   }
00155 }
00156 
00157 
00158 /*
00159   Close all tables which aren't in use by any thread
00160 
00161   @param session Thread context (may be NULL)
00162   @param tables List of tables to remove from the cache
00163   @param have_lock If table::Cache::singleton().mutex() is locked
00164   @param wait_for_refresh Wait for a impending flush
00165   @param wait_for_placeholders Wait for tables being reopened so that the GRL
00166   won't proceed while write-locked tables are being reopened by other
00167   threads.
00168 
00169   @remark Session can be NULL, but then wait_for_refresh must be false
00170   and tables must be NULL.
00171 */
00172 
00173 bool Session::close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders)
00174 {
00175   bool result= false;
00176   Session *session= this;
00177 
00178   {
00179     boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* Optionally lock for remove tables from open_cahe if not in use */
00180 
00181     if (tables == NULL)
00182     {
00183       refresh_version++;        // Force close of open tables
00184 
00185       table::getUnused().clear();
00186 
00187       if (wait_for_refresh)
00188       {
00189         /*
00190           Other threads could wait in a loop in open_and_lock_tables(),
00191           trying to lock one or more of our tables.
00192 
00193           If they wait for the locks in thr_multi_lock(), their lock
00194           request is aborted. They loop in open_and_lock_tables() and
00195           enter open_table(). Here they notice the table is refreshed and
00196           wait for COND_refresh. Then they loop again in
00197           openTablesLock() and this time open_table() succeeds. At
00198           this moment, if we (the FLUSH TABLES thread) are scheduled and
00199           on another FLUSH TABLES enter close_cached_tables(), they could
00200           awake while we sleep below, waiting for others threads (us) to
00201           close their open tables. If this happens, the other threads
00202           would find the tables unlocked. They would get the locks, one
00203           after the other, and could do their destructive work. This is an
00204           issue if we have LOCK TABLES in effect.
00205 
00206           The problem is that the other threads passed all checks in
00207           open_table() before we refresh the table.
00208 
00209           The fix for this problem is to set some_tables_deleted for all
00210           threads with open tables. These threads can still get their
00211           locks, but will immediately release them again after checking
00212           this variable. They will then loop in openTablesLock()
00213           again. There they will wait until we update all tables version
00214           below.
00215 
00216           Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
00217           in the other branch.
00218 
00219           In other words (reviewer suggestion): You need this setting of
00220           some_tables_deleted for the case when table was opened and all
00221           related checks were passed before incrementing refresh_version
00222           (which you already have) but attempt to lock the table happened
00223           after the call to Session::close_old_data_files() i.e. after removal of
00224           current thread locks.
00225         */
00226         for (table::CacheMap::const_iterator iter= table::getCache().begin();
00227              iter != table::getCache().end();
00228              iter++)
00229         {
00230           Table *table= iter->second;
00231           if (table->in_use)
00232             table->in_use->some_tables_deleted= false;
00233         }
00234       }
00235     }
00236     else
00237     {
00238       bool found= false;
00239       for (TableList *table= tables; table; table= table->next_local)
00240       {
00241         identifier::Table identifier(table->getSchemaName(), table->getTableName());
00242         if (table::Cache::singleton().removeTable(session, identifier,
00243                                     RTFC_OWNED_BY_Session_FLAG))
00244         {
00245           found= true;
00246         }
00247       }
00248       if (!found)
00249         wait_for_refresh= false;      // Nothing to wait for
00250     }
00251 
00252     if (wait_for_refresh)
00253     {
00254       /*
00255         If there is any table that has a lower refresh_version, wait until
00256         this is closed (or this thread is killed) before returning
00257       */
00258       session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
00259       session->mysys_var->current_cond= &COND_refresh;
00260       session->set_proc_info("Flushing tables");
00261 
00262       session->close_old_data_files();
00263 
00264       bool found= true;
00265       /* Wait until all threads has closed all the tables we had locked */
00266       while (found && ! session->getKilled())
00267       {
00268         found= false;
00269         for (table::CacheMap::const_iterator iter= table::getCache().begin();
00270              iter != table::getCache().end();
00271              iter++)
00272         {
00273           Table *table= iter->second;
00274           /* Avoid a self-deadlock. */
00275           if (table->in_use == session)
00276             continue;
00277           /*
00278             Note that we wait here only for tables which are actually open, and
00279             not for placeholders with Table::open_placeholder set. Waiting for
00280             latter will cause deadlock in the following scenario, for example:
00281 
00282             conn1-> lock table t1 write;
00283             conn2-> lock table t2 write;
00284             conn1-> flush tables;
00285             conn2-> flush tables;
00286 
00287             It also does not make sense to wait for those of placeholders that
00288             are employed by CREATE TABLE as in this case table simply does not
00289             exist yet.
00290           */
00291           if (table->needs_reopen_or_name_lock() && (table->db_stat ||
00292                                                      (table->open_placeholder && wait_for_placeholders)))
00293           {
00294             found= true;
00295             COND_refresh.wait(scopedLock);
00296             break;
00297           }
00298         }
00299       }
00300       /*
00301         No other thread has the locked tables open; reopen them and get the
00302         old locks. This should always succeed (unless some external process
00303         has removed the tables)
00304       */
00305       result= session->reopen_tables();
00306 
00307       /* Set version for table */
00308       for (Table *table= session->open_tables; table ; table= table->getNext())
00309       {
00310         /*
00311           Preserve the version (0) of write locked tables so that a impending
00312           global read lock won't sneak in.
00313         */
00314         if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
00315           table->getMutableShare()->refreshVersion();
00316       }
00317     }
00318   }
00319 
00320   if (wait_for_refresh)
00321   {
00322     boost_unique_lock_t scopedLock(session->mysys_var->mutex);
00323     session->mysys_var->current_mutex= 0;
00324     session->mysys_var->current_cond= 0;
00325     session->set_proc_info(0);
00326   }
00327 
00328   return result;
00329 }
00330 
00331 
00336 bool Session::free_cached_table(boost::mutex::scoped_lock &scopedLock)
00337 {
00338   bool found_old_table= false;
00339 
00340   (void)scopedLock;
00341 
00342   table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
00343 
00344   safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
00345   assert(table->key_read == 0);
00346   assert(!table->cursor || table->cursor->inited == Cursor::NONE);
00347 
00348   open_tables= table->getNext();
00349 
00350   if (table->needs_reopen_or_name_lock() ||
00351       version != refresh_version || !table->db_stat)
00352   {
00353     table::remove_table(table);
00354     found_old_table= true;
00355   }
00356   else
00357   {
00358     /*
00359       Open placeholders have Table::db_stat set to 0, so they should be
00360       handled by the first alternative.
00361     */
00362     assert(not table->open_placeholder);
00363 
00364     /* Free memory and reset for next loop */
00365     table->cursor->ha_reset();
00366     table->in_use= NULL;
00367 
00368     table::getUnused().link(table);
00369   }
00370 
00371   return found_old_table;
00372 }
00373 
00374 
00383 void Session::close_open_tables()
00384 {
00385   bool found_old_table= false;
00386 
00387   safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
00388 
00389   boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
00390 
00391   while (open_tables)
00392   {
00393     found_old_table|= free_cached_table(scoped_lock);
00394   }
00395   some_tables_deleted= false;
00396 
00397   if (found_old_table)
00398   {
00399     /* Tell threads waiting for refresh that something has happened */
00400     locking::broadcast_refresh();
00401   }
00402 }
00403 
00404 /*
00405   Find table in list.
00406 
00407   SYNOPSIS
00408   find_table_in_list()
00409   table   Pointer to table list
00410   offset    Offset to which list in table structure to use
00411   db_name   Data base name
00412   table_name    Table name
00413 
00414 NOTES:
00415 This is called by find_table_in_global_list().
00416 
00417 RETURN VALUES
00418 NULL  Table not found
00419 #   Pointer to found table.
00420 */
00421 
00422 TableList *find_table_in_list(TableList *table,
00423                               TableList *TableList::*link,
00424                               const char *db_name,
00425                               const char *table_name)
00426 {
00427   for (; table; table= table->*link )
00428   {
00429     if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) and
00430         my_strcasecmp(system_charset_info, table->getSchemaName(), db_name) == 0 and
00431         my_strcasecmp(system_charset_info, table->getTableName(), table_name) == 0)
00432     {
00433       break;
00434     }
00435   }
00436   return table;
00437 }
00438 
00439 
00440 /*
00441   Test that table is unique (It's only exists once in the table list)
00442 
00443   SYNOPSIS
00444   unique_table()
00445   session                   thread handle
00446   table                 table which should be checked
00447   table_list            list of tables
00448   check_alias           whether to check tables' aliases
00449 
00450 NOTE: to exclude derived tables from check we use following mechanism:
00451 a) during derived table processing set Session::derived_tables_processing
00452 b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
00453 Session::derived_tables_processing set. (we can't use JOIN::execute
00454 because for PS we perform only JOIN::prepare, but we can't set this
00455 flag in JOIN::prepare if we are not sure that we are in derived table
00456 processing loop, because multi-update call fix_fields() for some its
00457 items (which mean JOIN::prepare for subqueries) before unique_table
00458 call to detect which tables should be locked for write).
00459 c) unique_table skip all tables which belong to SELECT with
00460 SELECT::exclude_from_table_unique_test set.
00461 Also SELECT::exclude_from_table_unique_test used to exclude from check
00462 tables of main SELECT of multi-delete and multi-update
00463 
00464 We also skip tables with TableList::prelocking_placeholder set,
00465 because we want to allow SELECTs from them, and their modification
00466 will rise the error anyway.
00467 
00468 TODO: when we will have table/view change detection we can do this check
00469 only once for PS/SP
00470 
00471 RETURN
00472 found duplicate
00473 0 if table is unique
00474 */
00475 
00476 TableList* unique_table(TableList *table, TableList *table_list,
00477                         bool check_alias)
00478 {
00479   TableList *res;
00480   const char *d_name, *t_name, *t_alias;
00481 
00482   /*
00483     If this function called for query which update table (INSERT/UPDATE/...)
00484     then we have in table->table pointer to Table object which we are
00485     updating even if it is VIEW so we need TableList of this Table object
00486     to get right names (even if lower_case_table_names used).
00487 
00488     If this function called for CREATE command that we have not opened table
00489     (table->table equal to 0) and right names is in current TableList
00490     object.
00491   */
00492   if (table->table)
00493   {
00494     /* temporary table is always unique */
00495     if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
00496       return 0;
00497     table= table->find_underlying_table(table->table);
00498     /*
00499       as far as we have table->table we have to find real TableList of
00500       it in underlying tables
00501     */
00502     assert(table);
00503   }
00504   d_name= table->getSchemaName();
00505   t_name= table->getTableName();
00506   t_alias= table->alias;
00507 
00508   for (;;)
00509   {
00510     if ((! (res= find_table_in_global_list(table_list, d_name, t_name))) ||
00511         ((!res->table || res->table != table->table) &&
00512          (!check_alias || !(my_strcasecmp(files_charset_info, t_alias, res->alias))) &&
00513          res->select_lex && !res->select_lex->exclude_from_table_unique_test))
00514       break;
00515     /*
00516       If we found entry of this table or table of SELECT which already
00517       processed in derived table or top select of multi-update/multi-delete
00518       (exclude_from_table_unique_test) or prelocking placeholder.
00519     */
00520     table_list= res->next_global;
00521   }
00522   return(res);
00523 }
00524 
00525 
00526 void Open_tables_state::doGetTableNames(const identifier::Schema &schema_identifier,
00527                                         std::set<std::string>& set_of_names)
00528 {
00529   for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
00530   {
00531     if (schema_identifier.compare(table->getShare()->getSchemaName()))
00532     {
00533       set_of_names.insert(table->getShare()->getTableName());
00534     }
00535   }
00536 }
00537 
00538 void Open_tables_state::doGetTableNames(CachedDirectory &,
00539                                         const identifier::Schema &schema_identifier,
00540                                         std::set<std::string> &set_of_names)
00541 {
00542   doGetTableNames(schema_identifier, set_of_names);
00543 }
00544 
00545 void Open_tables_state::doGetTableIdentifiers(const identifier::Schema &schema_identifier,
00546                                               identifier::Table::vector &set_of_identifiers)
00547 {
00548   for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
00549   {
00550     if (schema_identifier.compare(table->getShare()->getSchemaName()))
00551     {
00552       set_of_identifiers.push_back(identifier::Table(table->getShare()->getSchemaName(),
00553                                                    table->getShare()->getTableName(),
00554                                                    table->getShare()->getPath()));
00555     }
00556   }
00557 }
00558 
00559 void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
00560                                               const identifier::Schema &schema_identifier,
00561                                               identifier::Table::vector &set_of_identifiers)
00562 {
00563   doGetTableIdentifiers(schema_identifier, set_of_identifiers);
00564 }
00565 
00566 bool Open_tables_state::doDoesTableExist(const identifier::Table &identifier)
00567 {
00568   for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
00569   {
00570     if (table->getShare()->getType() == message::Table::TEMPORARY)
00571     {
00572       if (identifier.getKey() == table->getShare()->getCacheKey())
00573       {
00574         return true;
00575       }
00576     }
00577   }
00578 
00579   return false;
00580 }
00581 
00582 int Open_tables_state::doGetTableDefinition(const identifier::Table &identifier,
00583                                             message::Table &table_proto)
00584 {
00585   for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
00586   {
00587     if (table->getShare()->getType() == message::Table::TEMPORARY)
00588     {
00589       if (identifier.getKey() == table->getShare()->getCacheKey())
00590       {
00591         table_proto.CopyFrom(*(table->getShare()->getTableMessage()));
00592 
00593         return EEXIST;
00594       }
00595     }
00596   }
00597 
00598   return ENOENT;
00599 }
00600 
00601 Table *Open_tables_state::find_temporary_table(const identifier::Table &identifier)
00602 {
00603   for (Table *table= temporary_tables ; table ; table= table->getNext())
00604   {
00605     if (identifier.getKey() == table->getShare()->getCacheKey())
00606       return table;
00607   }
00608 
00609   return NULL;                               // Not a temporary table
00610 }
00611 
00612 
00639 int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
00640 {
00641   Table *table;
00642 
00643   if (not (table= find_temporary_table(identifier)))
00644     return 1;
00645 
00646   /* Table might be in use by some outer statement. */
00647   if (table->query_id && table->query_id != getQueryId())
00648   {
00649     my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
00650     return -1;
00651   }
00652 
00653   close_temporary_table(table);
00654 
00655   return 0;
00656 }
00657 
00658 
00669 void Session::unlink_open_table(Table *find)
00670 {
00671   const identifier::Table::Key find_key(find->getShare()->getCacheKey());
00672   Table **prev;
00673   safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
00674 
00675   /*
00676     Note that we need to hold table::Cache::singleton().mutex() while changing the
00677     open_tables list. Another thread may work on it.
00678     (See: table::Cache::singleton().removeTable(), wait_completed_table())
00679     Closing a MERGE child before the parent would be fatal if the
00680     other thread tries to abort the MERGE lock in between.
00681   */
00682   for (prev= &open_tables; *prev; )
00683   {
00684     Table *list= *prev;
00685 
00686     if (list->getShare()->getCacheKey() == find_key)
00687     {
00688       /* Remove table from open_tables list. */
00689       *prev= list->getNext();
00690 
00691       /* Close table. */
00692       table::remove_table(static_cast<table::Concurrent *>(list));
00693     }
00694     else
00695     {
00696       /* Step to next entry in open_tables list. */
00697       prev= list->getNextPtr();
00698     }
00699   }
00700 
00701   // Notify any 'refresh' threads
00702   locking::broadcast_refresh();
00703 }
00704 
00705 
00725 void Session::drop_open_table(Table *table, const identifier::Table &identifier)
00726 {
00727   if (table->getShare()->getType())
00728   {
00729     close_temporary_table(table);
00730   }
00731   else
00732   {
00733     boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
00734     /*
00735       unlink_open_table() also tells threads waiting for refresh or close
00736       that something has happened.
00737     */
00738     unlink_open_table(table);
00739     (void)plugin::StorageEngine::dropTable(*this, identifier);
00740   }
00741 }
00742 
00743 
00744 /*
00745   Wait for condition but allow the user to send a kill to mysqld
00746 
00747   SYNOPSIS
00748   wait_for_condition()
00749   session Thread Cursor
00750   mutex mutex that is currently hold that is associated with condition
00751   Will be unlocked on return
00752   cond  Condition to wait for
00753 */
00754 
00755 void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
00756 {
00757   /* Wait until the current table is up to date */
00758   const char *saved_proc_info;
00759   mysys_var->current_mutex= &mutex;
00760   mysys_var->current_cond= &cond;
00761   saved_proc_info= get_proc_info();
00762   set_proc_info("Waiting for table");
00763   {
00764     /*
00765       We must unlock mutex first to avoid deadlock becasue conditions are
00766       sent to this thread by doing locks in the following order:
00767       lock(mysys_var->mutex)
00768       lock(mysys_var->current_mutex)
00769 
00770       One by effect of this that one can only use wait_for_condition with
00771       condition variables that are guranteed to not disapper (freed) even if this
00772       mutex is unlocked
00773     */
00774     boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
00775     if (not getKilled())
00776     {
00777       cond.wait(scopedLock);
00778     }
00779   }
00780   boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
00781   mysys_var->current_mutex= 0;
00782   mysys_var->current_cond= 0;
00783   set_proc_info(saved_proc_info);
00784 }
00785 
00786 
00800 table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
00801 {
00802   safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
00803 
00804   /*
00805     Create a table entry with the right key and with an old refresh version
00806   */
00807   identifier::Table identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
00808   table::Placeholder *table= new table::Placeholder(this, identifier);
00809 
00810   if (not table::Cache::singleton().insert(table))
00811   {
00812     safe_delete(table);
00813 
00814     return NULL;
00815   }
00816 
00817   return table;
00818 }
00819 
00820 
00842 bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
00843 {
00844   const identifier::Table::Key &key(identifier.getKey());
00845 
00846   boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table)  */
00847 
00848   if (find_ptr(table::getCache(), key))
00849   {
00850     *table= 0;
00851     return false;
00852   }
00853 
00854   if (not (*table= table_cache_insert_placeholder(identifier)))
00855   {
00856     return true;
00857   }
00858   (*table)->open_placeholder= true;
00859   (*table)->setNext(open_tables);
00860   open_tables= *table;
00861 
00862   return false;
00863 }
00864 
00865 /*
00866   Open a table.
00867 
00868   SYNOPSIS
00869   open_table()
00870   session                 Thread context.
00871   table_list          Open first table in list.
00872   refresh      INOUT  Pointer to memory that will be set to 1 if
00873   we need to close all tables and reopen them.
00874   If this is a NULL pointer, then the table is not
00875   put in the thread-open-list.
00876   flags               Bitmap of flags to modify how open works:
00877   DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
00878   someone has done a flush or namelock on it.
00879   No version number checking is done.
00880   DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
00881   table not the base table or view.
00882 
00883   IMPLEMENTATION
00884   Uses a cache of open tables to find a table not in use.
00885 
00886   If table list element for the table to be opened has "create" flag
00887   set and table does not exist, this function will automatically insert
00888   a placeholder for exclusive name lock into the open tables cache and
00889   will return the Table instance that corresponds to this placeholder.
00890 
00891   RETURN
00892   NULL  Open failed.  If refresh is set then one should close
00893   all other tables and retry the open.
00894 #     Success. Pointer to Table object for open table.
00895 */
00896 
00897 
00898 Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
00899 {
00900   Table *table;
00901   const char *alias= table_list->alias;
00902 
00903   /* Parsing of partitioning information from .frm needs session->lex set up. */
00904   assert(lex().is_lex_started);
00905 
00906   /* find a unused table in the open table cache */
00907   if (refresh)
00908     *refresh= false;
00909 
00910   /* an open table operation needs a lot of the stack space */
00911   if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
00912     return NULL;
00913 
00914   if (getKilled())
00915     return NULL;
00916 
00917   identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
00918   const identifier::Table::Key &key(identifier.getKey());
00919   table::CacheRange ppp;
00920 
00921   /*
00922     Unless requested otherwise, try to resolve this table in the list
00923     of temporary tables of this thread. In MySQL temporary tables
00924     are always thread-local and "shadow" possible base tables with the
00925     same name. This block implements the behaviour.
00926     TODO -> move this block into a separate function.
00927   */
00928   bool reset= false;
00929   for (table= getTemporaryTables(); table ; table=table->getNext())
00930   {
00931     if (table->getShare()->getCacheKey() == key)
00932     {
00933       /*
00934         We're trying to use the same temporary table twice in a query.
00935         Right now we don't support this because a temporary table
00936         is always represented by only one Table object in Session, and
00937         it can not be cloned. Emit an error for an unsupported behaviour.
00938       */
00939       if (table->query_id)
00940       {
00941         my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
00942         return NULL;
00943       }
00944       table->query_id= getQueryId();
00945       reset= true;
00946       break;
00947     }
00948   }
00949 
00950   if (not reset)
00951   {
00952     if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
00953     {
00954       my_error(ER_TABLE_UNKNOWN, identifier);
00955       return NULL;
00956     }
00957 
00958     /*
00959       If it's the first table from a list of tables used in a query,
00960       remember refresh_version (the version of open_cache state).
00961       If the version changes while we're opening the remaining tables,
00962       we will have to back off, close all the tables opened-so-far,
00963       and try to reopen them.
00964 
00965       Note-> refresh_version is currently changed only during FLUSH TABLES.
00966     */
00967     if (!open_tables)
00968     {
00969       version= refresh_version;
00970     }
00971     else if ((version != refresh_version) &&
00972              ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
00973     {
00974       /* Someone did a refresh while thread was opening tables */
00975       if (refresh)
00976         *refresh= true;
00977 
00978       return NULL;
00979     }
00980 
00981     /*
00982       Before we test the global cache, we test our local session cache.
00983     */
00984     if (cached_table)
00985     {
00986       assert(false); /* Not implemented yet */
00987     }
00988 
00989     /*
00990       Non pre-locked/LOCK TABLES mode, and the table is not temporary:
00991       this is the normal use case.
00992       Now we should:
00993       - try to find the table in the table cache.
00994       - if one of the discovered Table instances is name-locked
00995       (table->getShare()->version == 0) back off -- we have to wait
00996       until no one holds a name lock on the table.
00997       - if there is no such Table in the name cache, read the table definition
00998       and insert it into the cache.
00999       We perform all of the above under table::Cache::singleton().mutex() which currently protects
01000       the open cache (also known as table cache) and table definitions stored
01001       on disk.
01002     */
01003 
01004     {
01005       boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
01006 
01007       /*
01008         Actually try to find the table in the open_cache.
01009         The cache may contain several "Table" instances for the same
01010         physical table. The instances that are currently "in use" by
01011         some thread have their "in_use" member != NULL.
01012         There is no good reason for having more than one entry in the
01013         hash for the same physical table, except that we use this as
01014         an implicit "pending locks queue" - see
01015         wait_for_locked_table_names for details.
01016       */
01017       ppp= table::getCache().equal_range(key);
01018 
01019       table= NULL;
01020       for (table::CacheMap::const_iterator iter= ppp.first;
01021            iter != ppp.second; ++iter, table= NULL)
01022       {
01023         table= iter->second;
01024 
01025         if (not table->in_use)
01026           break;
01027         /*
01028           Here we flush tables marked for flush.
01029           Normally, table->getShare()->version contains the value of
01030           refresh_version from the moment when this table was
01031           (re-)opened and added to the cache.
01032           If since then we did (or just started) FLUSH TABLES
01033           statement, refresh_version has been increased.
01034           For "name-locked" Table instances, table->getShare()->version is set
01035           to 0 (see lock_table_name for details).
01036           In case there is a pending FLUSH TABLES or a name lock, we
01037           need to back off and re-start opening tables.
01038           If we do not back off now, we may dead lock in case of lock
01039           order mismatch with some other thread:
01040           c1-> name lock t1; -- sort of exclusive lock
01041           c2-> open t2;      -- sort of shared lock
01042           c1-> name lock t2; -- blocks
01043           c2-> open t1; -- blocks
01044         */
01045         if (table->needs_reopen_or_name_lock())
01046         {
01047           if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
01048           {
01049             /* Force close at once after usage */
01050             version= table->getShare()->getVersion();
01051             continue;
01052           }
01053 
01054           /* Avoid self-deadlocks by detecting self-dependencies. */
01055           if (table->open_placeholder && table->in_use == this)
01056           {
01057             my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
01058             return NULL;
01059           }
01060 
01061           /*
01062             Back off, part 1: mark the table as "unused" for the
01063             purpose of name-locking by setting table->db_stat to 0. Do
01064             that only for the tables in this thread that have an old
01065             table->getShare()->version (this is an optimization (?)).
01066             table->db_stat == 0 signals wait_for_locked_table_names
01067             that the tables in question are not used any more. See
01068             table_is_used call for details.
01069           */
01070           close_old_data_files(false, false);
01071 
01072           /*
01073             Back-off part 2: try to avoid "busy waiting" on the table:
01074             if the table is in use by some other thread, we suspend
01075             and wait till the operation is complete: when any
01076             operation that juggles with table->getShare()->version completes,
01077             it broadcasts COND_refresh condition variable.
01078             If 'old' table we met is in use by current thread we return
01079             without waiting since in this situation it's this thread
01080             which is responsible for broadcasting on COND_refresh
01081             (and this was done already in Session::close_old_data_files()).
01082             Good example of such situation is when we have statement
01083             that needs two instances of table and FLUSH TABLES comes
01084             after we open first instance but before we open second
01085             instance.
01086           */
01087           if (table->in_use != this)
01088           {
01089             /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
01090             wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
01091             scopedLock.release();
01092           }
01093           else
01094           {
01095             scopedLock.unlock();
01096           }
01097 
01098           /*
01099             There is a refresh in progress for this table.
01100             Signal the caller that it has to try again.
01101           */
01102           if (refresh)
01103             *refresh= true;
01104 
01105           return NULL;
01106         }
01107       }
01108 
01109       if (table)
01110       {
01111         table::getUnused().unlink(static_cast<table::Concurrent *>(table));
01112         table->in_use= this;
01113       }
01114       else
01115       {
01116         /* Insert a new Table instance into the open cache */
01117         int error;
01118         /* Free cache if too big */
01119         table::getUnused().cull();
01120 
01121         if (table_list->isCreate())
01122         {
01123           identifier::Table  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
01124 
01125           if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
01126           {
01127             /*
01128               Table to be created, so we need to create placeholder in table-cache.
01129             */
01130             if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
01131             {
01132               return NULL;
01133             }
01134             /*
01135               Link placeholder to the open tables list so it will be automatically
01136               removed once tables are closed. Also mark it so it won't be ignored
01137               by other trying to take name-lock.
01138             */
01139             table->open_placeholder= true;
01140             table->setNext(open_tables);
01141             open_tables= table;
01142 
01143             return table ;
01144           }
01145           /* Table exists. Let us try to open it. */
01146         }
01147 
01148         /* make a new table */
01149         {
01150           table::Concurrent *new_table= new table::Concurrent;
01151           table= new_table;
01152           if (new_table == NULL)
01153           {
01154             return NULL;
01155           }
01156 
01157           error= new_table->open_unireg_entry(this, alias, identifier);
01158           if (error != 0)
01159           {
01160             delete new_table;
01161             return NULL;
01162           }
01163           (void)table::Cache::singleton().insert(new_table);
01164         }
01165       }
01166     }
01167 
01168     if (refresh)
01169     {
01170       table->setNext(open_tables); /* Link into simple list */
01171       open_tables= table;
01172     }
01173     table->reginfo.lock_type= TL_READ; /* Assume read */
01174 
01175   }
01176   assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
01177 
01178   /* Fix alias if table name changes */
01179   if (strcmp(table->getAlias(), alias))
01180   {
01181     table->setAlias(alias);
01182   }
01183 
01184   /* These variables are also set in reopen_table() */
01185   table->tablenr= current_tablenr++;
01186   table->used_fields= 0;
01187   table->const_table= 0;
01188   table->null_row= false;
01189   table->maybe_null= false;
01190   table->force_index= false;
01191   table->status=STATUS_NO_RECORD;
01192   table->insert_values.clear();
01193   /* Catch wrong handling of the auto_increment_field_not_null. */
01194   assert(!table->auto_increment_field_not_null);
01195   table->auto_increment_field_not_null= false;
01196   if (table->timestamp_field)
01197   {
01198     table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
01199   }
01200   table->pos_in_table_list= table_list;
01201   table->clear_column_bitmaps();
01202   assert(table->key_read == 0);
01203 
01204   return table;
01205 }
01206 
01207 
01225 void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
01226 {
01227   safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
01228 
01229   if (lock)
01230   {
01231     /*
01232       If we are not under LOCK TABLES we should have only one table
01233       open and locked so it makes sense to remove the lock at once.
01234     */
01235     unlockTables(lock);
01236     lock= 0;
01237   }
01238 
01239   /*
01240     Note that open table list may contain a name-lock placeholder
01241     for target table name if we process ALTER Table ... RENAME.
01242     So loop below makes sense even if we are not under LOCK TABLES.
01243   */
01244   for (Table *table= open_tables; table ; table=table->getNext())
01245   {
01246     if (table->getShare()->getCacheKey() == identifier.getKey())
01247     {
01248       table->open_placeholder= true;
01249       close_handle_and_leave_table_as_lock(table);
01250     }
01251   }
01252 }
01253 
01254 
01275 bool Session::reopen_tables()
01276 {
01277   Table *table,*next,**prev;
01278   Table **tables= 0;      // For locks
01279   Table **tables_ptr= 0;      // For locks
01280   bool error= false;
01281   const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
01282     DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
01283     DRIZZLE_LOCK_IGNORE_FLUSH;
01284 
01285   if (open_tables == NULL)
01286     return false;
01287 
01288   safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
01289   {
01290     /*
01291       The ptr is checked later
01292       Do not handle locks of MERGE children.
01293     */
01294     uint32_t opens= 0;
01295 
01296     for (table= open_tables; table ; table=table->getNext())
01297     {
01298       opens++;
01299     }
01300     tables= new Table *[opens];
01301   }
01302 
01303   tables_ptr =tables;
01304 
01305   prev= &open_tables;
01306   for (table= open_tables; table ; table=next)
01307   {
01308     next= table->getNext();
01309 
01310     my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
01311     table::remove_table(static_cast<table::Concurrent *>(table));
01312     error= 1;
01313   }
01314   *prev=0;
01315 
01316   if (tables != tables_ptr)     // Should we get back old locks
01317   {
01318     DrizzleLock *local_lock;
01319     /*
01320       We should always get these locks. Anyway, we must not go into
01321       wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
01322       already locked.
01323     */
01324     some_tables_deleted= false;
01325 
01326     if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
01327     {
01328       /* unused */
01329     }
01330     else
01331     {
01332       /*
01333         This case should only happen if there is a bug in the reopen logic.
01334         Need to issue error message to have a reply for the application.
01335         Not exactly what happened though, but close enough.
01336       */
01337       my_error(ER_LOCK_DEADLOCK, MYF(0));
01338       error=1;
01339     }
01340   }
01341 
01342   delete [] tables;
01343 
01344   locking::broadcast_refresh();
01345 
01346   return error;
01347 }
01348 
01349 
01364 void Session::close_old_data_files(bool morph_locks, bool send_refresh)
01365 {
01366   bool found= send_refresh;
01367 
01368   Table *table= open_tables;
01369 
01370   for (; table ; table=table->getNext())
01371   {
01372     /*
01373       Reopen marked for flush.
01374     */
01375     if (table->needs_reopen_or_name_lock())
01376     {
01377       found= true;
01378       if (table->db_stat)
01379       {
01380         if (morph_locks)
01381         {
01382           Table *ulcktbl= table;
01383           if (ulcktbl->lock_count)
01384           {
01385             /*
01386               Wake up threads waiting for table-level lock on this table
01387               so they won't sneak in when we will temporarily remove our
01388               lock on it. This will also give them a chance to close their
01389               instances of this table.
01390             */
01391             abortLock(ulcktbl);
01392             removeLock(ulcktbl);
01393             ulcktbl->lock_count= 0;
01394           }
01395           if ((ulcktbl != table) && ulcktbl->db_stat)
01396           {
01397             /*
01398               Close the parent too. Note that parent can come later in
01399               the list of tables. It will then be noticed as closed and
01400               as a placeholder. When this happens, do not clear the
01401               placeholder flag. See the branch below ("***").
01402             */
01403             ulcktbl->open_placeholder= true;
01404             close_handle_and_leave_table_as_lock(ulcktbl);
01405           }
01406           /*
01407             We want to protect the table from concurrent DDL operations
01408             (like RENAME Table) until we will re-open and re-lock it.
01409           */
01410           table->open_placeholder= true;
01411         }
01412         close_handle_and_leave_table_as_lock(table);
01413       }
01414       else if (table->open_placeholder && !morph_locks)
01415       {
01416         /*
01417           We come here only in close-for-back-off scenario. So we have to
01418           "close" create placeholder here to avoid deadlocks (for example,
01419           in case of concurrent execution of CREATE TABLE t1 SELECT * FROM t2
01420           and RENAME Table t2 TO t1). In close-for-re-open scenario we will
01421           probably want to let it stay.
01422 
01423           Note "***": We must not enter this branch if the placeholder
01424           flag has been set because of a former close through a child.
01425           See above the comment that refers to this note.
01426         */
01427         table->open_placeholder= false;
01428       }
01429     }
01430   }
01431   if (found)
01432     locking::broadcast_refresh();
01433 }
01434 
01435 
01436 /*
01437   drop tables from locked list
01438 
01439   SYNOPSIS
01440   drop_locked_tables()
01441   session     Thread thandler
01442   db      Database
01443   table_name    Table name
01444 
01445   INFORMATION
01446   This is only called on drop tables
01447 
01448   The Table object for the dropped table is unlocked but still kept around
01449   as a name lock, which means that the table will be available for other
01450   thread as soon as we call unlock_table_names().
01451   If there is multiple copies of the table locked, all copies except
01452   the first, which acts as a name lock, is removed.
01453 
01454   RETURN
01455 #    If table existed, return table
01456 0  Table was not locked
01457 */
01458 
01459 
01460 Table *drop_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
01461 {
01462   Table *table,*next,**prev, *found= 0;
01463   prev= &session->open_tables;
01464 
01465   /*
01466     Note that we need to hold table::Cache::singleton().mutex() while changing the
01467     open_tables list. Another thread may work on it.
01468     (See: table::Cache::singleton().removeTable(), wait_completed_table())
01469     Closing a MERGE child before the parent would be fatal if the
01470     other thread tries to abort the MERGE lock in between.
01471   */
01472   for (table= session->open_tables; table ; table=next)
01473   {
01474     next=table->getNext();
01475     if (table->getShare()->getCacheKey() == identifier.getKey())
01476     {
01477       session->removeLock(table);
01478 
01479       if (!found)
01480       {
01481         found= table;
01482         /* Close engine table, but keep object around as a name lock */
01483         if (table->db_stat)
01484         {
01485           table->db_stat= 0;
01486           table->cursor->close();
01487         }
01488       }
01489       else
01490       {
01491         /* We already have a name lock, remove copy */
01492         table::remove_table(static_cast<table::Concurrent *>(table));
01493       }
01494     }
01495     else
01496     {
01497       *prev=table;
01498       prev= table->getNextPtr();
01499     }
01500   }
01501   *prev=0;
01502 
01503   if (found)
01504     locking::broadcast_refresh();
01505 
01506   return found;
01507 }
01508 
01509 
01510 /*
01511   If we have the table open, which only happens when a LOCK Table has been
01512   done on the table, change the lock type to a lock that will abort all
01513   other threads trying to get the lock.
01514 */
01515 
01516 void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
01517 {
01518   Table *table;
01519   for (table= session->open_tables; table ; table= table->getNext())
01520   {
01521     if (table->getShare()->getCacheKey() == identifier.getKey())
01522     {
01523       /* If MERGE child, forward lock handling to parent. */
01524       session->abortLock(table);
01525       assert(0);
01526       break;
01527     }
01528   }
01529 }
01530 
01531 
01532 /*
01533   Open all tables in list
01534 
01535   SYNOPSIS
01536   open_tables()
01537   session - thread Cursor
01538   start - list of tables in/out
01539   counter - number of opened tables will be return using this parameter
01540   flags   - bitmap of flags to modify how the tables will be open:
01541   DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
01542   done a flush or namelock on it.
01543 
01544   NOTE
01545   Unless we are already in prelocked mode, this function will also precache
01546   all SP/SFs explicitly or implicitly (via views and triggers) used by the
01547   query and add tables needed for their execution to table list. If resulting
01548   tables list will be non empty it will mark query as requiring precaching.
01549   Prelocked mode will be enabled for such query during lock_tables() call.
01550 
01551   If query for which we are opening tables is already marked as requiring
01552   prelocking it won't do such precaching and will simply reuse table list
01553   which is already built.
01554 
01555   RETURN
01556   0  - OK
01557   -1 - error
01558 */
01559 
01560 int Session::open_tables_from_list(TableList **start, uint32_t *counter, uint32_t flags)
01561 {
01562   TableList *tables= NULL;
01563   bool refresh;
01564   int result= 0;
01565   /* Also used for indicating that prelocking is need */
01566   bool safe_to_ignore_table;
01567 
01568   current_tablenr= 0;
01569 restart:
01570   *counter= 0;
01571   set_proc_info("Opening tables");
01572 
01573   /*
01574     For every table in the list of tables to open, try to find or open
01575     a table.
01576   */
01577   for (tables= *start; tables ;tables= tables->next_global)
01578   {
01579     safe_to_ignore_table= false;
01580 
01581     /*
01582       Ignore placeholders for derived tables. After derived tables
01583       processing, link to created temporary table will be put here.
01584       If this is derived table for view then we still want to process
01585       routines used by this view.
01586     */
01587     if (tables->derived)
01588     {
01589       continue;
01590     }
01591     (*counter)++;
01592 
01593     /*
01594      * Is the user authorized to see this table? Do this before we check
01595      * to see if it exists so that an unauthorized user cannot phish for
01596      * table/schema information via error messages
01597      */
01598     identifier::Table the_table(tables->getSchemaName(), tables->getTableName());
01599     if (not plugin::Authorization::isAuthorized(*user(), the_table))
01600     {
01601       result= -1;                               // Fatal error
01602       break;
01603     }
01604 
01605 
01606     /*
01607       Not a placeholder: must be a base table or a view, and the table is
01608       not opened yet. Try to open the table.
01609     */
01610     if (tables->table == NULL)
01611       tables->table= openTable(tables, &refresh, flags);
01612 
01613     if (tables->table == NULL)
01614     {
01615       if (refresh)        // Refresh in progress
01616       {
01617         /*
01618           We have met name-locked or old version of table. Now we have
01619           to close all tables which are not up to date. We also have to
01620           throw away set of prelocked tables (and thus close tables from
01621           this set that were open by now) since it possible that one of
01622           tables which determined its content was changed.
01623 
01624           Instead of implementing complex/non-robust logic mentioned
01625           above we simply close and then reopen all tables.
01626 
01627           In order to prepare for recalculation of set of prelocked tables
01628           we pretend that we have finished calculation which we were doing
01629           currently.
01630         */
01631         close_tables_for_reopen(start);
01632         goto restart;
01633       }
01634 
01635       if (safe_to_ignore_table)
01636         continue;
01637 
01638       result= -1;       // Fatal error
01639       break;
01640     }
01641     if (tables->lock_type != TL_UNLOCK)
01642     {
01643       if (tables->lock_type == TL_WRITE_DEFAULT)
01644         tables->table->reginfo.lock_type= update_lock_default;
01645       else if (tables->table->getShare()->getType() == message::Table::STANDARD)
01646         tables->table->reginfo.lock_type= tables->lock_type;
01647     }
01648   }
01649 
01650   set_proc_info(0);
01651 
01652   if (result && tables)
01653   {
01654     /*
01655       Some functions determine success as (tables->table != NULL).
01656       tables->table is in session->open_tables.
01657     */
01658     tables->table= NULL;
01659   }
01660 
01661   return(result);
01662 }
01663 
01664 
01665 /*
01666   Open and lock one table
01667 
01668   SYNOPSIS
01669   openTableLock()
01670   session     Thread Cursor
01671   table_list    Table to open is first table in this list
01672   lock_type   Lock to use for open
01673   lock_flags          Flags passed to mysql_lock_table
01674 
01675   NOTE
01676   This function don't do anything like SP/SF/views/triggers analysis done
01677   in open_tables(). It is intended for opening of only one concrete table.
01678   And used only in special contexts.
01679 
01680   RETURN VALUES
01681   table   Opened table
01682   0     Error
01683 
01684   If ok, the following are also set:
01685   table_list->lock_type   lock_type
01686   table_list->table   table
01687 */
01688 
01689 Table *Session::openTableLock(TableList *table_list, thr_lock_type lock_type)
01690 {
01691   Table *table;
01692   bool refresh;
01693 
01694   set_proc_info("Opening table");
01695   current_tablenr= 0;
01696   while (!(table= openTable(table_list, &refresh)) && refresh) ;
01697 
01698   if (table)
01699   {
01700     table_list->lock_type= lock_type;
01701     table_list->table=     table;
01702 
01703     assert(lock == 0);  // You must lock everything at once
01704     if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
01705     {
01706       if (not (lock= lockTables(&table_list->table, 1, 0)))
01707         table= NULL;
01708     }
01709   }
01710 
01711   set_proc_info(0);
01712 
01713   return table;
01714 }
01715 
01716 /*
01717   Lock all tables in list
01718 
01719   SYNOPSIS
01720   lock_tables()
01721   session     Thread Cursor
01722   tables    Tables to lock
01723   count   Number of opened tables
01724   need_reopen         Out parameter which if true indicates that some
01725   tables were dropped or altered during this call
01726   and therefore invoker should reopen tables and
01727   try to lock them once again (in this case
01728   lock_tables() will also return error).
01729 
01730   NOTES
01731   You can't call lock_tables twice, as this would break the dead-lock-free
01732   handling thr_lock gives us.  You most always get all needed locks at
01733   once.
01734 
01735   If query for which we are calling this function marked as requring
01736   prelocking, this function will do implicit LOCK TABLES and change
01737   session::prelocked_mode accordingly.
01738 
01739   RETURN VALUES
01740   0 ok
01741   -1  Error
01742 */
01743 
01744 int Session::lock_tables(TableList *tables, uint32_t count, bool *need_reopen)
01745 {
01746   TableList *table;
01747   Session *session= this;
01748 
01749   /*
01750     We can't meet statement requiring prelocking if we already
01751     in prelocked mode.
01752   */
01753   *need_reopen= false;
01754 
01755   if (tables == NULL)
01756     return 0;
01757 
01758   assert(session->lock == 0); // You must lock everything at once
01759   Table **start,**ptr;
01760   uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
01761 
01762   if (!(ptr=start=(Table**) session->getMemRoot()->allocate(sizeof(Table*)*count)))
01763     return -1;
01764 
01765   for (table= tables; table; table= table->next_global)
01766   {
01767     if (!table->placeholder())
01768       *(ptr++)= table->table;
01769   }
01770 
01771   if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
01772   {
01773     return -1;
01774   }
01775 
01776   return 0;
01777 }
01778 
01779 
01780 /*
01781   Open a single table without table caching and don't set it in open_list
01782 
01783   SYNPOSIS
01784   open_temporary_table()
01785   session     Thread object
01786   path    Path (without .frm)
01787   db      database
01788   table_name    Table name
01789   link_in_list  1 if table should be linked into session->temporary_tables
01790 
01791 NOTES:
01792 Used by alter_table to open a temporary table and when creating
01793 a temporary table with CREATE TEMPORARY ...
01794 
01795 RETURN
01796 0  Error
01797 #  Table object
01798 */
01799 
01800 Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
01801                                                bool link_in_list)
01802 {
01803   assert(identifier.isTmp());
01804 
01805 
01806   table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
01807                                                         identifier,
01808                                                         const_cast<char *>(const_cast<identifier::Table&>(identifier).getPath().c_str()),
01809                                                         static_cast<uint32_t>(identifier.getPath().length()));
01810   if (not new_tmp_table)
01811     return NULL;
01812 
01813   /*
01814     First open the share, and then open the table from the share we just opened.
01815   */
01816   if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
01817       new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
01818                                                               (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
01819                                                                           HA_GET_INDEX),
01820                                                               ha_open_options,
01821                                                               *new_tmp_table))
01822   {
01823     /* No need to lock share->mutex as this is not needed for tmp tables */
01824     delete new_tmp_table->getMutableShare();
01825     delete new_tmp_table;
01826 
01827     return 0;
01828   }
01829 
01830   new_tmp_table->reginfo.lock_type= TL_WRITE;  // Simulate locked
01831 
01832   if (link_in_list)
01833   {
01834     /* growing temp list at the head */
01835     new_tmp_table->setNext(this->temporary_tables);
01836     if (new_tmp_table->getNext())
01837     {
01838       new_tmp_table->getNext()->setPrev(new_tmp_table);
01839     }
01840     this->temporary_tables= new_tmp_table;
01841     this->temporary_tables->setPrev(0);
01842   }
01843   new_tmp_table->pos_in_table_list= 0;
01844 
01845   return new_tmp_table;
01846 }
01847 
01848 
01849 /*****************************************************************************
01850  * The following find_field_in_XXX procedures implement the core of the
01851  * name resolution functionality. The entry point to resolve a column name in a
01852  * list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
01853  * for each table reference. In turn, depending on the type of table reference,
01854  * 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
01855  * below specific for the type of table reference.
01856  ******************************************************************************/
01857 
01858 /* Special Field pointers as return values of find_field_in_XXX functions. */
01859 Field *not_found_field= (Field*) 0x1;
01860 Field *view_ref_found= (Field*) 0x2;
01861 
01862 static void update_field_dependencies(Session *session, Field *field, Table *table)
01863 {
01864   if (session->mark_used_columns != MARK_COLUMNS_NONE)
01865   {
01866     boost::dynamic_bitset<> *current_bitmap= NULL;
01867 
01868     /*
01869       We always want to register the used keys, as the column bitmap may have
01870       been set for all fields (for example for view).
01871     */
01872 
01873     table->covering_keys&= field->part_of_key;
01874     table->merge_keys|= field->part_of_key;
01875 
01876     if (session->mark_used_columns == MARK_COLUMNS_READ)
01877     {
01878       current_bitmap= table->read_set;
01879     }
01880     else
01881     {
01882       current_bitmap= table->write_set;
01883     }
01884 
01885     //if (current_bitmap->testAndSet(field->position()))
01886     if (current_bitmap->test(field->position()))
01887     {
01888       if (session->mark_used_columns == MARK_COLUMNS_WRITE)
01889         session->dup_field= field;
01890       return;
01891     }
01892     table->used_fields++;
01893   }
01894 }
01895 
01896 
01897 /*
01898   Find field by name in a NATURAL/USING join table reference.
01899 
01900   SYNOPSIS
01901   find_field_in_natural_join()
01902   session      [in]  thread Cursor
01903   table_ref            [in]  table reference to search
01904   name     [in]  name of field
01905   length     [in]  length of name
01906   ref                  [in/out] if 'name' is resolved to a view field, ref is
01907   set to point to the found view field
01908   register_tree_change [in]  true if ref is not stack variable and we
01909   need register changes in item tree
01910   actual_table         [out] the original table reference where the field
01911   belongs - differs from 'table_list' only for
01912   NATURAL/USING joins
01913 
01914   DESCRIPTION
01915   Search for a field among the result fields of a NATURAL/USING join.
01916   Notice that this procedure is called only for non-qualified field
01917   names. In the case of qualified fields, we search directly the base
01918   tables of a natural join.
01919 
01920   RETURN
01921   NULL        if the field was not found
01922   PTR         Pointer to the found Field
01923 */
01924 
01925 static Field *
01926 find_field_in_natural_join(Session *session, TableList *table_ref,
01927                            const char *name, uint32_t , Item **,
01928                            bool, TableList **actual_table)
01929 {
01930   List<Natural_join_column>::iterator
01931     field_it(table_ref->join_columns->begin());
01932   Natural_join_column *nj_col, *curr_nj_col;
01933   Field *found_field;
01934 
01935   assert(table_ref->is_natural_join && table_ref->join_columns);
01936   assert(*actual_table == NULL);
01937 
01938   for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col;
01939        curr_nj_col= field_it++)
01940   {
01941     if (!my_strcasecmp(system_charset_info, curr_nj_col->name(), name))
01942     {
01943       if (nj_col)
01944       {
01945         my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where());
01946         return NULL;
01947       }
01948       nj_col= curr_nj_col;
01949     }
01950   }
01951   if (!nj_col)
01952     return NULL;
01953   {
01954     /* This is a base table. */
01955     assert(nj_col->table_ref->table == nj_col->table_field->getTable());
01956     found_field= nj_col->table_field;
01957     update_field_dependencies(session, found_field, nj_col->table_ref->table);
01958   }
01959 
01960   *actual_table= nj_col->table_ref;
01961 
01962   return(found_field);
01963 }
01964 
01965 
01966 /*
01967   Find field by name in a base table or a view with temp table algorithm.
01968 
01969   SYNOPSIS
01970   find_field_in_table()
01971   session       thread Cursor
01972   table     table where to search for the field
01973   name      name of field
01974   length      length of name
01975   allow_rowid     do allow finding of "_rowid" field?
01976   cached_field_index_ptr  cached position in field list (used to speedup
01977   lookup for fields in prepared tables)
01978 
01979   RETURN
01980   0 field is not found
01981 # pointer to field
01982 */
01983 
01984 Field *
01985 find_field_in_table(Session *session, Table *table, const char *name, uint32_t length,
01986                     bool allow_rowid, uint32_t *cached_field_index_ptr)
01987 {
01988   Field **field_ptr, *field;
01989   uint32_t cached_field_index= *cached_field_index_ptr;
01990 
01991   /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
01992   if (cached_field_index < table->getShare()->sizeFields() &&
01993       !my_strcasecmp(system_charset_info,
01994                      table->getField(cached_field_index)->field_name, name))
01995   {
01996     field_ptr= table->getFields() + cached_field_index;
01997   }
01998   else if (table->getShare()->getNamedFieldSize())
01999   {
02000     field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
02001     if (field_ptr)
02002     {
02003       /*
02004         field_ptr points to field in TableShare. Convert it to the matching
02005         field in table
02006       */
02007       field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
02008     }
02009   }
02010   else
02011   {
02012     if (!(field_ptr= table->getFields()))
02013       return((Field *)0);
02014     for (; *field_ptr; ++field_ptr)
02015       if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
02016         break;
02017   }
02018 
02019   if (field_ptr && *field_ptr)
02020   {
02021     *cached_field_index_ptr= field_ptr - table->getFields();
02022     field= *field_ptr;
02023   }
02024   else
02025   {
02026     if (!allow_rowid ||
02027         my_strcasecmp(system_charset_info, name, "_rowid") ||
02028         table->getShare()->rowid_field_offset == 0)
02029       return((Field*) 0);
02030     field= table->getField(table->getShare()->rowid_field_offset-1);
02031   }
02032 
02033   update_field_dependencies(session, field, table);
02034 
02035   return field;
02036 }
02037 
02038 
02039 /*
02040   Find field in a table reference.
02041 
02042   SYNOPSIS
02043   find_field_in_table_ref()
02044   session        [in]  thread Cursor
02045   table_list       [in]  table reference to search
02046   name       [in]  name of field
02047   length       [in]  field length of name
02048   item_name              [in]  name of item if it will be created (VIEW)
02049   db_name                [in]  optional database name that qualifies the
02050   table_name             [in]  optional table name that qualifies the field
02051   ref          [in/out] if 'name' is resolved to a view field, ref
02052   is set to point to the found view field
02053   allow_rowid      [in]  do allow finding of "_rowid" field?
02054   cached_field_index_ptr [in]  cached position in field list (used to
02055   speedup lookup for fields in prepared tables)
02056   register_tree_change   [in]  true if ref is not stack variable and we
02057   need register changes in item tree
02058   actual_table           [out] the original table reference where the field
02059   belongs - differs from 'table_list' only for
02060   NATURAL_USING joins.
02061 
02062   DESCRIPTION
02063   Find a field in a table reference depending on the type of table
02064   reference. There are three types of table references with respect
02065   to the representation of their result columns:
02066   - an array of Field_translator objects for MERGE views and some
02067   information_schema tables,
02068   - an array of Field objects (and possibly a name hash) for stored
02069   tables,
02070   - a list of Natural_join_column objects for NATURAL/USING joins.
02071   This procedure detects the type of the table reference 'table_list'
02072   and calls the corresponding search routine.
02073 
02074   RETURN
02075   0     field is not found
02076   view_ref_found  found value in VIEW (real result is in *ref)
02077 #     pointer to field
02078 */
02079 
02080 Field *
02081 find_field_in_table_ref(Session *session, TableList *table_list,
02082                         const char *name, uint32_t length,
02083                         const char *item_name, const char *db_name,
02084                         const char *table_name, Item **ref,
02085                         bool allow_rowid,
02086                         uint32_t *cached_field_index_ptr,
02087                         bool register_tree_change, TableList **actual_table)
02088 {
02089   Field *fld= NULL;
02090 
02091   assert(table_list->alias);
02092   assert(name);
02093   assert(item_name);
02094 
02095   /*
02096     Check that the table and database that qualify the current field name
02097     are the same as the table reference we are going to search for the field.
02098 
02099     Exclude from the test below nested joins because the columns in a
02100     nested join generally originate from different tables. Nested joins
02101     also have no table name, except when a nested join is a merge view
02102     or an information schema table.
02103 
02104     We include explicitly table references with a 'field_translation' table,
02105     because if there are views over natural joins we don't want to search
02106     inside the view, but we want to search directly in the view columns
02107     which are represented as a 'field_translation'.
02108 
02109     TODO-> Ensure that table_name, db_name and tables->db always points to something !
02110   */
02111   if (/* Exclude nested joins. */
02112       (!table_list->getNestedJoin()) &&
02113       /* Include merge views and information schema tables. */
02114       /*
02115         Test if the field qualifiers match the table reference we plan
02116         to search.
02117       */
02118       table_name && table_name[0] &&
02119       (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
02120        (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
02121         strcmp(db_name, table_list->getSchemaName()))))
02122     return 0;
02123 
02124   *actual_table= NULL;
02125 
02126   if (!table_list->getNestedJoin())
02127   {
02128     /* 'table_list' is a stored table. */
02129     assert(table_list->table);
02130     if ((fld= find_field_in_table(session, table_list->table, name, length,
02131                                   allow_rowid,
02132                                   cached_field_index_ptr)))
02133       *actual_table= table_list;
02134   }
02135   else
02136   {
02137     /*
02138       'table_list' is a NATURAL/USING join, or an operand of such join that
02139       is a nested join itself.
02140 
02141       If the field name we search for is qualified, then search for the field
02142       in the table references used by NATURAL/USING the join.
02143     */
02144     if (table_name && table_name[0])
02145     {
02146       List<TableList>::iterator it(table_list->getNestedJoin()->join_list.begin());
02147       TableList *table;
02148       while ((table= it++))
02149       {
02150         if ((fld= find_field_in_table_ref(session, table, name, length, item_name,
02151                                           db_name, table_name, ref,
02152                                           allow_rowid,
02153                                           cached_field_index_ptr,
02154                                           register_tree_change, actual_table)))
02155           return fld;
02156       }
02157       return NULL;
02158     }
02159     /*
02160       Non-qualified field, search directly in the result columns of the
02161       natural join. The condition of the outer IF is true for the top-most
02162       natural join, thus if the field is not qualified, we will search
02163       directly the top-most NATURAL/USING join.
02164     */
02165     fld= find_field_in_natural_join(session, table_list, name, length, ref,
02166                                     register_tree_change, actual_table);
02167   }
02168 
02169   if (fld)
02170   {
02171     if (session->mark_used_columns != MARK_COLUMNS_NONE)
02172     {
02173       /*
02174         Get rw_set correct for this field so that the Cursor
02175         knows that this field is involved in the query and gets
02176         retrieved/updated
02177       */
02178       Field *field_to_set= NULL;
02179       if (fld == view_ref_found)
02180       {
02181         Item *it= (*ref)->real_item();
02182         if (it->type() == Item::FIELD_ITEM)
02183           field_to_set= ((Item_field*)it)->field;
02184         else
02185         {
02186           if (session->mark_used_columns == MARK_COLUMNS_READ)
02187             it->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
02188         }
02189       }
02190       else
02191         field_to_set= fld;
02192       if (field_to_set)
02193       {
02194         Table *table= field_to_set->getTable();
02195         if (session->mark_used_columns == MARK_COLUMNS_READ)
02196           table->setReadSet(field_to_set->position());
02197         else
02198           table->setWriteSet(field_to_set->position());
02199       }
02200     }
02201   }
02202   return(fld);
02203 }
02204 
02205 
02206 /*
02207   Find field in table list.
02208 
02209   SYNOPSIS
02210   find_field_in_tables()
02211   session       pointer to current thread structure
02212   item      field item that should be found
02213   first_table           list of tables to be searched for item
02214   last_table            end of the list of tables to search for item. If NULL
02215   then search to the end of the list 'first_table'.
02216   ref       if 'item' is resolved to a view field, ref is set to
02217   point to the found view field
02218   report_error    Degree of error reporting:
02219   - IGNORE_ERRORS then do not report any error
02220   - IGNORE_EXCEPT_NON_UNIQUE report only non-unique
02221   fields, suppress all other errors
02222   - REPORT_EXCEPT_NON_UNIQUE report all other errors
02223   except when non-unique fields were found
02224   - REPORT_ALL_ERRORS
02225   register_tree_change  true if ref is not a stack variable and we
02226   to need register changes in item tree
02227 
02228   RETURN VALUES
02229   0     If error: the found field is not unique, or there are
02230   no sufficient access priviliges for the found field,
02231   or the field is qualified with non-existing table.
02232   not_found_field The function was called with report_error ==
02233   (IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
02234   field was not found.
02235   view_ref_found  View field is found, item passed through ref parameter
02236   found field         If a item was resolved to some field
02237 */
02238 
02239 Field *
02240 find_field_in_tables(Session *session, Item_ident *item,
02241                      TableList *first_table, TableList *last_table,
02242                      Item **ref, find_item_error_report_type report_error,
02243                      bool register_tree_change)
02244 {
02245   Field *found=0;
02246   const char *db= item->db_name;
02247   const char *table_name= item->table_name;
02248   const char *name= item->field_name;
02249   uint32_t length=(uint32_t) strlen(name);
02250   char name_buff[NAME_LEN+1];
02251   TableList *cur_table= first_table;
02252   TableList *actual_table;
02253   bool allow_rowid;
02254 
02255   if (!table_name || !table_name[0])
02256   {
02257     table_name= 0;                              // For easier test
02258     db= 0;
02259   }
02260 
02261   allow_rowid= table_name || (cur_table && !cur_table->next_local);
02262 
02263   if (item->cached_table)
02264   {
02265     /*
02266       This shortcut is used by prepared statements. We assume that
02267       TableList *first_table is not changed during query execution (which
02268       is true for all queries except RENAME but luckily RENAME doesn't
02269       use fields...) so we can rely on reusing pointer to its member.
02270       With this optimization we also miss case when addition of one more
02271       field makes some prepared query ambiguous and so erroneous, but we
02272       accept this trade off.
02273     */
02274     TableList *table_ref= item->cached_table;
02275     /*
02276       The condition (table_ref->view == NULL) ensures that we will call
02277       find_field_in_table even in the case of information schema tables
02278       when table_ref->field_translation != NULL.
02279     */
02280     if (table_ref->table)
02281       found= find_field_in_table(session, table_ref->table, name, length,
02282                                  true, &(item->cached_field_index));
02283     else
02284       found= find_field_in_table_ref(session, table_ref, name, length, item->name,
02285                                      NULL, NULL, ref,
02286                                      true, &(item->cached_field_index),
02287                                      register_tree_change,
02288                                      &actual_table);
02289     if (found)
02290     {
02291       /*
02292         Only views fields should be marked as dependent, not an underlying
02293         fields.
02294       */
02295       {
02296         Select_Lex *current_sel= session->lex().current_select;
02297         Select_Lex *last_select= table_ref->select_lex;
02298         /*
02299           If the field was an outer referencee, mark all selects using this
02300           sub query as dependent on the outer query
02301         */
02302         if (current_sel != last_select)
02303           mark_select_range_as_dependent(session, last_select, current_sel,
02304                                          found, *ref, item);
02305       }
02306       return found;
02307     }
02308   }
02309 
02310   if (db)
02311   {
02312     /*
02313       convert database to lower case for comparison.
02314       We can't do this in Item_field as this would change the
02315       'name' of the item which may be used in the select list
02316     */
02317     strncpy(name_buff, db, sizeof(name_buff)-1);
02318     my_casedn_str(files_charset_info, name_buff);
02319     db= name_buff;
02320   }
02321 
02322   if (last_table)
02323     last_table= last_table->next_name_resolution_table;
02324 
02325   for (; cur_table != last_table ;
02326        cur_table= cur_table->next_name_resolution_table)
02327   {
02328     Field *cur_field= find_field_in_table_ref(session, cur_table, name, length,
02329                                               item->name, db, table_name, ref,
02330                                               allow_rowid,
02331                                               &(item->cached_field_index),
02332                                               register_tree_change,
02333                                               &actual_table);
02334     if (cur_field)
02335     {
02336       /*
02337         Store the original table of the field, which may be different from
02338         cur_table in the case of NATURAL/USING join.
02339       */
02340       item->cached_table= found ?  0 : actual_table;
02341 
02342       assert(session->where());
02343       /*
02344         If we found a fully qualified field we return it directly as it can't
02345         have duplicates.
02346       */
02347       if (db)
02348         return cur_field;
02349 
02350       if (found)
02351       {
02352         if (report_error == REPORT_ALL_ERRORS ||
02353             report_error == IGNORE_EXCEPT_NON_UNIQUE)
02354           my_error(ER_NON_UNIQ_ERROR, MYF(0),
02355                    table_name ? item->full_name() : name, session->where());
02356         return (Field*) 0;
02357       }
02358       found= cur_field;
02359     }
02360   }
02361 
02362   if (found)
02363     return found;
02364 
02365   /*
02366     If the field was qualified and there were no tables to search, issue
02367     an error that an unknown table was given. The situation is detected
02368     as follows: if there were no tables we wouldn't go through the loop
02369     and cur_table wouldn't be updated by the loop increment part, so it
02370     will be equal to the first table.
02371   */
02372   if (table_name && (cur_table == first_table) &&
02373       (report_error == REPORT_ALL_ERRORS ||
02374        report_error == REPORT_EXCEPT_NON_UNIQUE))
02375   {
02376     char buff[NAME_LEN*2+1];
02377     if (db && db[0])
02378     {
02379       /* We're in an error condition, two extra strlen's aren't going
02380        * to kill us */
02381       assert(strlen(db) <= NAME_LEN);
02382       assert(strlen(table_name) <= NAME_LEN);
02383       strcpy(buff, db);
02384       strcat(buff,".");
02385       strcat(buff, table_name);
02386       table_name=buff;
02387     }
02388     my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where());
02389   }
02390   else
02391   {
02392     if (report_error == REPORT_ALL_ERRORS ||
02393         report_error == REPORT_EXCEPT_NON_UNIQUE)
02394       my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where());
02395     else
02396       found= not_found_field;
02397   }
02398   return found;
02399 }
02400 
02401 
02402 /*
02403   Find Item in list of items (find_field_in_tables analog)
02404 
02405   TODO
02406   is it better return only counter?
02407 
02408   SYNOPSIS
02409   find_item_in_list()
02410   find      Item to find
02411   items     List of items
02412   counter     To return number of found item
02413   report_error
02414   REPORT_ALL_ERRORS   report errors, return 0 if error
02415   REPORT_EXCEPT_NOT_FOUND Do not report 'not found' error and
02416   return not_found_item, report other errors,
02417   return 0
02418   IGNORE_ERRORS   Do not report errors, return 0 if error
02419   resolution                  Set to the resolution type if the item is found
02420   (it says whether the item is resolved
02421   against an alias name,
02422   or as a field name without alias,
02423   or as a field hidden by alias,
02424   or ignoring alias)
02425 
02426   RETURN VALUES
02427   0     Item is not found or item is not unique,
02428   error message is reported
02429   not_found_item  Function was called with
02430   report_error == REPORT_EXCEPT_NOT_FOUND and
02431   item was not found. No error message was reported
02432   found field
02433 */
02434 
02435 /* Special Item pointer to serve as a return value from find_item_in_list(). */
02436 Item **not_found_item= (Item**) 0x1;
02437 
02438 
02439 Item **
02440 find_item_in_list(Session *session,
02441                   Item *find, List<Item> &items, uint32_t *counter,
02442                   find_item_error_report_type report_error,
02443                   enum_resolution_type *resolution)
02444 {
02445   List<Item>::iterator li(items.begin());
02446   Item **found=0, **found_unaliased= 0, *item;
02447   const char *db_name=0;
02448   const char *field_name=0;
02449   const char *table_name=0;
02450   bool found_unaliased_non_uniq= 0;
02451   /*
02452     true if the item that we search for is a valid name reference
02453     (and not an item that happens to have a name).
02454   */
02455   bool is_ref_by_name= 0;
02456   uint32_t unaliased_counter= 0;
02457 
02458   *resolution= NOT_RESOLVED;
02459 
02460   is_ref_by_name= (find->type() == Item::FIELD_ITEM  ||
02461                    find->type() == Item::REF_ITEM);
02462   if (is_ref_by_name)
02463   {
02464     field_name= ((Item_ident*) find)->field_name;
02465     table_name= ((Item_ident*) find)->table_name;
02466     db_name=    ((Item_ident*) find)->db_name;
02467   }
02468 
02469   for (uint32_t i= 0; (item=li++); i++)
02470   {
02471     if (field_name && item->real_item()->type() == Item::FIELD_ITEM)
02472     {
02473       Item_ident *item_field= (Item_ident*) item;
02474 
02475       /*
02476         In case of group_concat() with ORDER BY condition in the QUERY
02477         item_field can be field of temporary table without item name
02478         (if this field created from expression argument of group_concat()),
02479         => we have to check presence of name before compare
02480       */
02481       if (!item_field->name)
02482         continue;
02483 
02484       if (table_name)
02485       {
02486         /*
02487           If table name is specified we should find field 'field_name' in
02488           table 'table_name'. According to SQL-standard we should ignore
02489           aliases in this case.
02490 
02491           Since we should NOT prefer fields from the select list over
02492           other fields from the tables participating in this select in
02493           case of ambiguity we have to do extra check outside this function.
02494 
02495           We use strcmp for table names and database names as these may be
02496           case sensitive. In cases where they are not case sensitive, they
02497           are always in lower case.
02498 
02499           item_field->field_name and item_field->table_name can be 0x0 if
02500           item is not fix_field()'ed yet.
02501         */
02502         if (item_field->field_name && item_field->table_name &&
02503             !my_strcasecmp(system_charset_info, item_field->field_name,
02504                            field_name) &&
02505             !my_strcasecmp(table_alias_charset, item_field->table_name,
02506                            table_name) &&
02507             (!db_name || (item_field->db_name &&
02508                           !strcmp(item_field->db_name, db_name))))
02509         {
02510           if (found_unaliased)
02511           {
02512             if ((*found_unaliased)->eq(item, 0))
02513               continue;
02514             /*
02515               Two matching fields in select list.
02516               We already can bail out because we are searching through
02517               unaliased names only and will have duplicate error anyway.
02518             */
02519             if (report_error != IGNORE_ERRORS)
02520               my_error(ER_NON_UNIQ_ERROR, MYF(0),
02521                        find->full_name(), session->where());
02522             return (Item**) 0;
02523           }
02524           found_unaliased= li.ref();
02525           unaliased_counter= i;
02526           *resolution= RESOLVED_IGNORING_ALIAS;
02527           if (db_name)
02528             break;                              // Perfect match
02529         }
02530       }
02531       else
02532       {
02533         int fname_cmp= my_strcasecmp(system_charset_info,
02534                                      item_field->field_name,
02535                                      field_name);
02536         if (!my_strcasecmp(system_charset_info,
02537                            item_field->name,field_name))
02538         {
02539           /*
02540             If table name was not given we should scan through aliases
02541             and non-aliased fields first. We are also checking unaliased
02542             name of the field in then next  else-if, to be able to find
02543             instantly field (hidden by alias) if no suitable alias or
02544             non-aliased field was found.
02545           */
02546           if (found)
02547           {
02548             if ((*found)->eq(item, 0))
02549               continue;                           // Same field twice
02550             if (report_error != IGNORE_ERRORS)
02551               my_error(ER_NON_UNIQ_ERROR, MYF(0),
02552                        find->full_name(), session->where());
02553             return (Item**) 0;
02554           }
02555           found= li.ref();
02556           *counter= i;
02557           *resolution= fname_cmp ? RESOLVED_AGAINST_ALIAS:
02558             RESOLVED_WITH_NO_ALIAS;
02559         }
02560         else if (!fname_cmp)
02561         {
02562           /*
02563             We will use non-aliased field or react on such ambiguities only if
02564             we won't be able to find aliased field.
02565             Again if we have ambiguity with field outside of select list
02566             we should prefer fields from select list.
02567           */
02568           if (found_unaliased)
02569           {
02570             if ((*found_unaliased)->eq(item, 0))
02571               continue;                           // Same field twice
02572             found_unaliased_non_uniq= 1;
02573           }
02574           found_unaliased= li.ref();
02575           unaliased_counter= i;
02576         }
02577       }
02578     }
02579     else if (!table_name)
02580     {
02581       if (is_ref_by_name && find->name && item->name &&
02582           !my_strcasecmp(system_charset_info,item->name,find->name))
02583       {
02584         found= li.ref();
02585         *counter= i;
02586         *resolution= RESOLVED_AGAINST_ALIAS;
02587         break;
02588       }
02589       else if (find->eq(item,0))
02590       {
02591         found= li.ref();
02592         *counter= i;
02593         *resolution= RESOLVED_IGNORING_ALIAS;
02594         break;
02595       }
02596     }
02597   }
02598   if (!found)
02599   {
02600     if (found_unaliased_non_uniq)
02601     {
02602       if (report_error != IGNORE_ERRORS)
02603         my_error(ER_NON_UNIQ_ERROR, MYF(0),
02604                  find->full_name(), session->where());
02605       return (Item **) 0;
02606     }
02607     if (found_unaliased)
02608     {
02609       found= found_unaliased;
02610       *counter= unaliased_counter;
02611       *resolution= RESOLVED_BEHIND_ALIAS;
02612     }
02613   }
02614   if (found)
02615     return found;
02616   if (report_error != REPORT_EXCEPT_NOT_FOUND)
02617   {
02618     if (report_error == REPORT_ALL_ERRORS)
02619       my_error(ER_BAD_FIELD_ERROR, MYF(0),
02620                find->full_name(), session->where());
02621     return (Item **) 0;
02622   }
02623   else
02624     return (Item **) not_found_item;
02625 }
02626 
02627 
02628 /*
02629   Test if a string is a member of a list of strings.
02630 
02631   SYNOPSIS
02632   test_if_string_in_list()
02633   find      the string to look for
02634   str_list  a list of strings to be searched
02635 
02636   DESCRIPTION
02637   Sequentially search a list of strings for a string, and test whether
02638   the list contains the same string.
02639 
02640   RETURN
02641   true  if find is in str_list
02642   false otherwise
02643 */
02644 
02645 static bool
02646 test_if_string_in_list(const char *find, List<String> *str_list)
02647 {
02648   List<String>::iterator str_list_it(str_list->begin());
02649   String *curr_str;
02650   size_t find_length= strlen(find);
02651   while ((curr_str= str_list_it++))
02652   {
02653     if (find_length != curr_str->length())
02654       continue;
02655     if (!my_strcasecmp(system_charset_info, find, curr_str->ptr()))
02656       return true;
02657   }
02658   return false;
02659 }
02660 
02661 
02662 /*
02663   Create a new name resolution context for an item so that it is
02664   being resolved in a specific table reference.
02665 
02666   SYNOPSIS
02667   set_new_item_local_context()
02668   session        pointer to current thread
02669   item       item for which new context is created and set
02670   table_ref  table ref where an item showld be resolved
02671 
02672   DESCRIPTION
02673   Create a new name resolution context for an item, so that the item
02674   is resolved only the supplied 'table_ref'.
02675 
02676   RETURN
02677   false  if all OK
02678   true   otherwise
02679 */
02680 
02681 static bool
02682 set_new_item_local_context(Session *session, Item_ident *item, TableList *table_ref)
02683 {
02684   Name_resolution_context *context;
02685   if (!(context= new (session->mem_root) Name_resolution_context))
02686     return true;
02687   context->init();
02688   context->first_name_resolution_table=
02689     context->last_name_resolution_table= table_ref;
02690   item->context= context;
02691   return false;
02692 }
02693 
02694 
02695 /*
02696   Find and mark the common columns of two table references.
02697 
02698   SYNOPSIS
02699   mark_common_columns()
02700   session                [in] current thread
02701   table_ref_1        [in] the first (left) join operand
02702   table_ref_2        [in] the second (right) join operand
02703   using_fields       [in] if the join is JOIN...USING - the join columns,
02704   if NATURAL join, then NULL
02705   found_using_fields [out] number of fields from the USING clause that were
02706   found among the common fields
02707 
02708   DESCRIPTION
02709   The procedure finds the common columns of two relations (either
02710   tables or intermediate join results), and adds an equi-join condition
02711   to the ON clause of 'table_ref_2' for each pair of matching columns.
02712   If some of table_ref_XXX represents a base table or view, then we
02713   create new 'Natural_join_column' instances for each column
02714   reference and store them in the 'join_columns' of the table
02715   reference.
02716 
02717   IMPLEMENTATION
02718   The procedure assumes that store_natural_using_join_columns() was
02719   called for the previous level of NATURAL/USING joins.
02720 
02721   RETURN
02722   true   error when some common column is non-unique, or out of memory
02723   false  OK
02724 */
02725 
02726 static bool
02727 mark_common_columns(Session *session, TableList *table_ref_1, TableList *table_ref_2,
02728                     List<String> *using_fields, uint32_t *found_using_fields)
02729 {
02730   Field_iterator_table_ref it_1, it_2;
02731   Natural_join_column *nj_col_1, *nj_col_2;
02732   bool result= true;
02733   bool first_outer_loop= true;
02734   /*
02735     Leaf table references to which new natural join columns are added
02736     if the leaves are != NULL.
02737   */
02738   TableList *leaf_1= (table_ref_1->getNestedJoin() &&
02739                       ! table_ref_1->is_natural_join) ?
02740     NULL : table_ref_1;
02741   TableList *leaf_2= (table_ref_2->getNestedJoin() &&
02742                       ! table_ref_2->is_natural_join) ?
02743     NULL : table_ref_2;
02744 
02745   *found_using_fields= 0;
02746 
02747   for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
02748   {
02749     bool found= false;
02750     const char *field_name_1;
02751     /* true if field_name_1 is a member of using_fields */
02752     bool is_using_column_1;
02753     if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
02754       return(result);
02755     field_name_1= nj_col_1->name();
02756     is_using_column_1= using_fields &&
02757       test_if_string_in_list(field_name_1, using_fields);
02758 
02759     /*
02760       Find a field with the same name in table_ref_2.
02761 
02762       Note that for the second loop, it_2.set() will iterate over
02763       table_ref_2->join_columns and not generate any new elements or
02764       lists.
02765     */
02766     nj_col_2= NULL;
02767     for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next())
02768     {
02769       Natural_join_column *cur_nj_col_2;
02770       const char *cur_field_name_2;
02771       if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
02772         return(result);
02773       cur_field_name_2= cur_nj_col_2->name();
02774 
02775       /*
02776         Compare the two columns and check for duplicate common fields.
02777         A common field is duplicate either if it was already found in
02778         table_ref_2 (then found == true), or if a field in table_ref_2
02779         was already matched by some previous field in table_ref_1
02780         (then cur_nj_col_2->is_common == true).
02781         Note that it is too early to check the columns outside of the
02782         USING list for ambiguity because they are not actually "referenced"
02783         here. These columns must be checked only on unqualified reference
02784         by name (e.g. in SELECT list).
02785       */
02786       if (!my_strcasecmp(system_charset_info, field_name_1, cur_field_name_2))
02787       {
02788         if (cur_nj_col_2->is_common ||
02789             (found && (!using_fields || is_using_column_1)))
02790         {
02791           my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where());
02792           return(result);
02793         }
02794         nj_col_2= cur_nj_col_2;
02795         found= true;
02796       }
02797     }
02798     if (first_outer_loop && leaf_2)
02799     {
02800       /*
02801         Make sure that the next inner loop "knows" that all columns
02802         are materialized already.
02803       */
02804       leaf_2->is_join_columns_complete= true;
02805       first_outer_loop= false;
02806     }
02807     if (!found)
02808       continue;                                 // No matching field
02809 
02810     /*
02811       field_1 and field_2 have the same names. Check if they are in the USING
02812       clause (if present), mark them as common fields, and add a new
02813       equi-join condition to the ON clause.
02814     */
02815     if (nj_col_2 && (!using_fields ||is_using_column_1))
02816     {
02817       Item *item_1=   nj_col_1->create_item(session);
02818       Item *item_2=   nj_col_2->create_item(session);
02819       Field *field_1= nj_col_1->field();
02820       Field *field_2= nj_col_2->field();
02821       Item_ident *item_ident_1, *item_ident_2;
02822       Item_func_eq *eq_cond;
02823 
02824       if (!item_1 || !item_2)
02825         return(result); // out of memory
02826 
02827       /*
02828         In the case of no_wrap_view_item == 0, the created items must be
02829         of sub-classes of Item_ident.
02830       */
02831       assert(item_1->type() == Item::FIELD_ITEM ||
02832              item_1->type() == Item::REF_ITEM);
02833       assert(item_2->type() == Item::FIELD_ITEM ||
02834              item_2->type() == Item::REF_ITEM);
02835 
02836       /*
02837         We need to cast item_1,2 to Item_ident, because we need to hook name
02838         resolution contexts specific to each item.
02839       */
02840       item_ident_1= (Item_ident*) item_1;
02841       item_ident_2= (Item_ident*) item_2;
02842       /*
02843         Create and hook special name resolution contexts to each item in the
02844         new join condition . We need this to both speed-up subsequent name
02845         resolution of these items, and to enable proper name resolution of
02846         the items during the execute phase of PS.
02847       */
02848       if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
02849           set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
02850         return(result);
02851 
02852       if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
02853         return(result);                               /* Out of memory. */
02854 
02855       /*
02856         Add the new equi-join condition to the ON clause. Notice that
02857         fix_fields() is applied to all ON conditions in setup_conds()
02858         so we don't do it here.
02859       */
02860       add_join_on((table_ref_1->outer_join & JOIN_TYPE_RIGHT ?
02861                    table_ref_1 : table_ref_2),
02862                   eq_cond);
02863 
02864       nj_col_1->is_common= nj_col_2->is_common= true;
02865 
02866       if (field_1)
02867       {
02868         Table *table_1= nj_col_1->table_ref->table;
02869         /* Mark field_1 used for table cache. */
02870         table_1->setReadSet(field_1->position());
02871         table_1->covering_keys&= field_1->part_of_key;
02872         table_1->merge_keys|= field_1->part_of_key;
02873       }
02874       if (field_2)
02875       {
02876         Table *table_2= nj_col_2->table_ref->table;
02877         /* Mark field_2 used for table cache. */
02878         table_2->setReadSet(field_2->position());
02879         table_2->covering_keys&= field_2->part_of_key;
02880         table_2->merge_keys|= field_2->part_of_key;
02881       }
02882 
02883       if (using_fields != NULL)
02884         ++(*found_using_fields);
02885     }
02886   }
02887   if (leaf_1)
02888     leaf_1->is_join_columns_complete= true;
02889 
02890   /*
02891     Everything is OK.
02892     Notice that at this point there may be some column names in the USING
02893     clause that are not among the common columns. This is an SQL error and
02894     we check for this error in store_natural_using_join_columns() when
02895     (found_using_fields < length(join_using_fields)).
02896   */
02897   result= false;
02898 
02899   return(result);
02900 }
02901 
02902 
02903 
02904 /*
02905   Materialize and store the row type of NATURAL/USING join.
02906 
02907   SYNOPSIS
02908   store_natural_using_join_columns()
02909   session                current thread
02910   natural_using_join the table reference of the NATURAL/USING join
02911   table_ref_1        the first (left) operand (of a NATURAL/USING join).
02912   table_ref_2        the second (right) operand (of a NATURAL/USING join).
02913   using_fields       if the join is JOIN...USING - the join columns,
02914   if NATURAL join, then NULL
02915   found_using_fields number of fields from the USING clause that were
02916   found among the common fields
02917 
02918   DESCRIPTION
02919   Iterate over the columns of both join operands and sort and store
02920   all columns into the 'join_columns' list of natural_using_join
02921   where the list is formed by three parts:
02922 part1: The coalesced columns of table_ref_1 and table_ref_2,
02923 sorted according to the column order of the first table.
02924 part2: The other columns of the first table, in the order in
02925 which they were defined in CREATE TABLE.
02926 part3: The other columns of the second table, in the order in
02927 which they were defined in CREATE TABLE.
02928 Time complexity - O(N1+N2), where Ni = length(table_ref_i).
02929 
02930 IMPLEMENTATION
02931 The procedure assumes that mark_common_columns() has been called
02932 for the join that is being processed.
02933 
02934 RETURN
02935 true    error: Some common column is ambiguous
02936 false   OK
02937 */
02938 
02939 static bool
02940 store_natural_using_join_columns(Session *session,
02941                                  TableList *natural_using_join,
02942                                  TableList *table_ref_1,
02943                                  TableList *table_ref_2,
02944                                  List<String> *using_fields,
02945                                  uint32_t found_using_fields)
02946 {
02947   Field_iterator_table_ref it_1, it_2;
02948   Natural_join_column *nj_col_1, *nj_col_2;
02949   bool result= true;
02950   List<Natural_join_column> *non_join_columns;
02951 
02952   assert(!natural_using_join->join_columns);
02953 
02954   if (!(non_join_columns= new List<Natural_join_column>) ||
02955       !(natural_using_join->join_columns= new List<Natural_join_column>))
02956   {
02957     return(result);
02958   }
02959 
02960   /* Append the columns of the first join operand. */
02961   for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
02962   {
02963     nj_col_1= it_1.get_natural_column_ref();
02964     if (nj_col_1->is_common)
02965     {
02966       natural_using_join->join_columns->push_back(nj_col_1);
02967       /* Reset the common columns for the next call to mark_common_columns. */
02968       nj_col_1->is_common= false;
02969     }
02970     else
02971       non_join_columns->push_back(nj_col_1);
02972   }
02973 
02974   /*
02975     Check that all columns in the USING clause are among the common
02976     columns. If this is not the case, report the first one that was
02977     not found in an error.
02978   */
02979   if (using_fields && found_using_fields < using_fields->size())
02980   {
02981     String *using_field_name;
02982     List<String>::iterator using_fields_it(using_fields->begin());
02983     while ((using_field_name= using_fields_it++))
02984     {
02985       const char *using_field_name_ptr= using_field_name->c_ptr();
02986       List<Natural_join_column>::iterator
02987         it(natural_using_join->join_columns->begin());
02988       Natural_join_column *common_field;
02989 
02990       for (;;)
02991       {
02992         /* If reached the end of fields, and none was found, report error. */
02993         if (!(common_field= it++))
02994         {
02995           my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
02996                    session->where());
02997           return(result);
02998         }
02999         if (!my_strcasecmp(system_charset_info,
03000                            common_field->name(), using_field_name_ptr))
03001           break;                                // Found match
03002       }
03003     }
03004   }
03005 
03006   /* Append the non-equi-join columns of the second join operand. */
03007   for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next())
03008   {
03009     nj_col_2= it_2.get_natural_column_ref();
03010     if (!nj_col_2->is_common)
03011       non_join_columns->push_back(nj_col_2);
03012     else
03013     {
03014       /* Reset the common columns for the next call to mark_common_columns. */
03015       nj_col_2->is_common= false;
03016     }
03017   }
03018 
03019   if (non_join_columns->size() > 0)
03020     natural_using_join->join_columns->concat(non_join_columns);
03021   natural_using_join->is_join_columns_complete= true;
03022 
03023   result= false;
03024 
03025   return(result);
03026 }
03027 
03028 
03029 /*
03030   Precompute and store the row types of the top-most NATURAL/USING joins.
03031 
03032   SYNOPSIS
03033   store_top_level_join_columns()
03034   session            current thread
03035   table_ref      nested join or table in a FROM clause
03036   left_neighbor  neighbor table reference to the left of table_ref at the
03037   same level in the join tree
03038   right_neighbor neighbor table reference to the right of table_ref at the
03039   same level in the join tree
03040 
03041   DESCRIPTION
03042   The procedure performs a post-order traversal of a nested join tree
03043   and materializes the row types of NATURAL/USING joins in a
03044   bottom-up manner until it reaches the TableList elements that
03045   represent the top-most NATURAL/USING joins. The procedure should be
03046   applied to each element of Select_Lex::top_join_list (i.e. to each
03047   top-level element of the FROM clause).
03048 
03049   IMPLEMENTATION
03050   Notice that the table references in the list nested_join->join_list
03051   are in reverse order, thus when we iterate over it, we are moving
03052   from the right to the left in the FROM clause.
03053 
03054   RETURN
03055   true   Error
03056   false  OK
03057 */
03058 
03059 static bool
03060 store_top_level_join_columns(Session *session, TableList *table_ref,
03061                              TableList *left_neighbor,
03062                              TableList *right_neighbor)
03063 {
03064   bool result= true;
03065 
03066   /* Call the procedure recursively for each nested table reference. */
03067   if (table_ref->getNestedJoin())
03068   {
03069     List<TableList>::iterator nested_it(table_ref->getNestedJoin()->join_list.begin());
03070     TableList *same_level_left_neighbor= nested_it++;
03071     TableList *same_level_right_neighbor= NULL;
03072     /* Left/right-most neighbors, possibly at higher levels in the join tree. */
03073     TableList *real_left_neighbor, *real_right_neighbor;
03074 
03075     while (same_level_left_neighbor)
03076     {
03077       TableList *cur_table_ref= same_level_left_neighbor;
03078       same_level_left_neighbor= nested_it++;
03079       /*
03080         The order of RIGHT JOIN operands is reversed in 'join list' to
03081         transform it into a LEFT JOIN. However, in this procedure we need
03082         the join operands in their lexical order, so below we reverse the
03083         join operands. Notice that this happens only in the first loop,
03084         and not in the second one, as in the second loop
03085         same_level_left_neighbor == NULL.
03086         This is the correct behavior, because the second loop sets
03087         cur_table_ref reference correctly after the join operands are
03088         swapped in the first loop.
03089       */
03090       if (same_level_left_neighbor &&
03091           cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
03092       {
03093         /* This can happen only for JOIN ... ON. */
03094         assert(table_ref->getNestedJoin()->join_list.size() == 2);
03095         std::swap(same_level_left_neighbor, cur_table_ref);
03096       }
03097 
03098       /*
03099         Pick the parent's left and right neighbors if there are no immediate
03100         neighbors at the same level.
03101       */
03102       real_left_neighbor=  (same_level_left_neighbor) ?
03103         same_level_left_neighbor : left_neighbor;
03104       real_right_neighbor= (same_level_right_neighbor) ?
03105         same_level_right_neighbor : right_neighbor;
03106 
03107       if (cur_table_ref->getNestedJoin() &&
03108           store_top_level_join_columns(session, cur_table_ref,
03109                                        real_left_neighbor, real_right_neighbor))
03110         return(result);
03111       same_level_right_neighbor= cur_table_ref;
03112     }
03113   }
03114 
03115   /*
03116     If this is a NATURAL/USING join, materialize its result columns and
03117     convert to a JOIN ... ON.
03118   */
03119   if (table_ref->is_natural_join)
03120   {
03121     assert(table_ref->getNestedJoin() &&
03122            table_ref->getNestedJoin()->join_list.size() == 2);
03123     List<TableList>::iterator operand_it(table_ref->getNestedJoin()->join_list.begin());
03124     /*
03125       Notice that the order of join operands depends on whether table_ref
03126       represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
03127       in inverted order.
03128     */
03129     TableList *table_ref_2= operand_it++; /* Second NATURAL join operand.*/
03130     TableList *table_ref_1= operand_it++; /* First NATURAL join operand. */
03131     List<String> *using_fields= table_ref->join_using_fields;
03132     uint32_t found_using_fields;
03133 
03134     /*
03135       The two join operands were interchanged in the parser, change the order
03136       back for 'mark_common_columns'.
03137     */
03138     if (table_ref_2->outer_join & JOIN_TYPE_RIGHT)
03139       std::swap(table_ref_1, table_ref_2);
03140     if (mark_common_columns(session, table_ref_1, table_ref_2,
03141                             using_fields, &found_using_fields))
03142       return(result);
03143 
03144     /*
03145       Swap the join operands back, so that we pick the columns of the second
03146       one as the coalesced columns. In this way the coalesced columns are the
03147       same as of an equivalent LEFT JOIN.
03148     */
03149     if (table_ref_1->outer_join & JOIN_TYPE_RIGHT)
03150       std::swap(table_ref_1, table_ref_2);
03151     if (store_natural_using_join_columns(session, table_ref, table_ref_1,
03152                                          table_ref_2, using_fields,
03153                                          found_using_fields))
03154       return(result);
03155 
03156     /*
03157       Change NATURAL JOIN to JOIN ... ON. We do this for both operands
03158       because either one of them or the other is the one with the
03159       natural join flag because RIGHT joins are transformed into LEFT,
03160       and the two tables may be reordered.
03161     */
03162     table_ref_1->natural_join= table_ref_2->natural_join= NULL;
03163 
03164     /* Add a true condition to outer joins that have no common columns. */
03165     if (table_ref_2->outer_join &&
03166         !table_ref_1->on_expr && !table_ref_2->on_expr)
03167       table_ref_2->on_expr= new Item_int((int64_t) 1,1);   /* Always true. */
03168 
03169     /* Change this table reference to become a leaf for name resolution. */
03170     if (left_neighbor)
03171     {
03172       TableList *last_leaf_on_the_left;
03173       last_leaf_on_the_left= left_neighbor->last_leaf_for_name_resolution();
03174       last_leaf_on_the_left->next_name_resolution_table= table_ref;
03175     }
03176     if (right_neighbor)
03177     {
03178       TableList *first_leaf_on_the_right;
03179       first_leaf_on_the_right= right_neighbor->first_leaf_for_name_resolution();
03180       table_ref->next_name_resolution_table= first_leaf_on_the_right;
03181     }
03182     else
03183       table_ref->next_name_resolution_table= NULL;
03184   }
03185   result= false; /* All is OK. */
03186 
03187   return(result);
03188 }
03189 
03190 
03191 /*
03192   Compute and store the row types of the top-most NATURAL/USING joins
03193   in a FROM clause.
03194 
03195   SYNOPSIS
03196   setup_natural_join_row_types()
03197   session          current thread
03198   from_clause  list of top-level table references in a FROM clause
03199 
03200   DESCRIPTION
03201   Apply the procedure 'store_top_level_join_columns' to each of the
03202   top-level table referencs of the FROM clause. Adjust the list of tables
03203   for name resolution - context->first_name_resolution_table to the
03204   top-most, lef-most NATURAL/USING join.
03205 
03206   IMPLEMENTATION
03207   Notice that the table references in 'from_clause' are in reverse
03208   order, thus when we iterate over it, we are moving from the right
03209   to the left in the FROM clause.
03210 
03211   RETURN
03212   true   Error
03213   false  OK
03214 */
03215 static bool setup_natural_join_row_types(Session *session,
03216                                          List<TableList> *from_clause,
03217                                          Name_resolution_context *context)
03218 {
03219   session->setWhere("from clause");
03220   if (from_clause->size() == 0)
03221     return false; /* We come here in the case of UNIONs. */
03222 
03223   List<TableList>::iterator table_ref_it(from_clause->begin());
03224   TableList *table_ref; /* Current table reference. */
03225   /* Table reference to the left of the current. */
03226   TableList *left_neighbor;
03227   /* Table reference to the right of the current. */
03228   TableList *right_neighbor= NULL;
03229 
03230   /* Note that tables in the list are in reversed order */
03231   for (left_neighbor= table_ref_it++; left_neighbor ; )
03232   {
03233     table_ref= left_neighbor;
03234     left_neighbor= table_ref_it++;
03235     if (store_top_level_join_columns(session, table_ref,
03236                                      left_neighbor, right_neighbor))
03237       return true;
03238     if (left_neighbor)
03239     {
03240       TableList *first_leaf_on_the_right;
03241       first_leaf_on_the_right= table_ref->first_leaf_for_name_resolution();
03242       left_neighbor->next_name_resolution_table= first_leaf_on_the_right;
03243     }
03244     right_neighbor= table_ref;
03245   }
03246 
03247   /*
03248     Store the top-most, left-most NATURAL/USING join, so that we start
03249     the search from that one instead of context->table_list. At this point
03250     right_neighbor points to the left-most top-level table reference in the
03251     FROM clause.
03252   */
03253   assert(right_neighbor);
03254   context->first_name_resolution_table=
03255     right_neighbor->first_leaf_for_name_resolution();
03256 
03257   return false;
03258 }
03259 
03260 
03261 /****************************************************************************
03262  ** Expand all '*' in given fields
03263  ****************************************************************************/
03264 
03265 int setup_wild(Session *session, List<Item> &fields,
03266                List<Item> *sum_func_list,
03267                uint32_t wild_num)
03268 {
03269   if (!wild_num)
03270     return 0;
03271 
03272   Item *item;
03273   List<Item>::iterator it(fields.begin());
03274 
03275   session->lex().current_select->cur_pos_in_select_list= 0;
03276   while (wild_num && (item= it++))
03277   {
03278     if (item->type() == Item::FIELD_ITEM &&
03279         ((Item_field*) item)->field_name &&
03280         ((Item_field*) item)->field_name[0] == '*' &&
03281         !((Item_field*) item)->field)
03282     {
03283       uint32_t elem= fields.size();
03284       bool any_privileges= ((Item_field *) item)->any_privileges;
03285       Item_subselect *subsel= session->lex().current_select->master_unit()->item;
03286       if (subsel &&
03287           subsel->substype() == Item_subselect::EXISTS_SUBS)
03288       {
03289         /*
03290           It is EXISTS(SELECT * ...) and we can replace * by any constant.
03291 
03292           Item_int do not need fix_fields() because it is basic constant.
03293         */
03294         it.replace(new Item_int("Not_used", (int64_t) 1,
03295                                 MY_INT64_NUM_DECIMAL_DIGITS));
03296       }
03297       else if (insert_fields(session, ((Item_field*) item)->context,
03298                              ((Item_field*) item)->db_name,
03299                              ((Item_field*) item)->table_name, &it,
03300                              any_privileges))
03301       {
03302         return -1;
03303       }
03304       if (sum_func_list)
03305       {
03306         /*
03307           sum_func_list is a list that has the fields list as a tail.
03308           Because of this we have to update the element count also for this
03309           list after expanding the '*' entry.
03310         */
03311         sum_func_list->set_size(sum_func_list->size() + fields.size() - elem);
03312       }
03313       wild_num--;
03314     }
03315     else
03316       session->lex().current_select->cur_pos_in_select_list++;
03317   }
03318   session->lex().current_select->cur_pos_in_select_list= UNDEF_POS;
03319 
03320   return 0;
03321 }
03322 
03323 /****************************************************************************
03324  ** Check that all given fields exists and fill struct with current data
03325  ****************************************************************************/
03326 
03327 bool setup_fields(Session *session, Item **ref_pointer_array,
03328                   List<Item> &fields, enum_mark_columns mark_used_columns,
03329                   List<Item> *sum_func_list, bool allow_sum_func)
03330 {
03331   register Item *item;
03332   enum_mark_columns save_mark_used_columns= session->mark_used_columns;
03333   nesting_map save_allow_sum_func= session->lex().allow_sum_func;
03334   List<Item>::iterator it(fields.begin());
03335   bool save_is_item_list_lookup;
03336 
03337   session->mark_used_columns= mark_used_columns;
03338   if (allow_sum_func)
03339     session->lex().allow_sum_func|= 1 << session->lex().current_select->nest_level;
03340   session->setWhere(Session::DEFAULT_WHERE);
03341   save_is_item_list_lookup= session->lex().current_select->is_item_list_lookup;
03342   session->lex().current_select->is_item_list_lookup= 0;
03343 
03344   /*
03345     To prevent fail on forward lookup we fill it with zerows,
03346     then if we got pointer on zero after find_item_in_list we will know
03347     that it is forward lookup.
03348 
03349     There is other way to solve problem: fill array with pointers to list,
03350     but it will be slower.
03351 
03352     TODO-> remove it when (if) we made one list for allfields and ref_pointer_array
03353   */
03354   if (ref_pointer_array)
03355   {
03356     memset(ref_pointer_array, 0, sizeof(Item *) * fields.size());
03357   }
03358 
03359   Item **ref= ref_pointer_array;
03360   session->lex().current_select->cur_pos_in_select_list= 0;
03361   while ((item= it++))
03362   {
03363     if ((!item->fixed && item->fix_fields(session, it.ref())) || (item= *(it.ref()))->check_cols(1))
03364     {
03365       session->lex().current_select->is_item_list_lookup= save_is_item_list_lookup;
03366       session->lex().allow_sum_func= save_allow_sum_func;
03367       session->mark_used_columns= save_mark_used_columns;
03368       return true;
03369     }
03370     if (ref)
03371       *(ref++)= item;
03372     if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM &&
03373         sum_func_list)
03374       item->split_sum_func(session, ref_pointer_array, *sum_func_list);
03375     session->used_tables|= item->used_tables();
03376     session->lex().current_select->cur_pos_in_select_list++;
03377   }
03378   session->lex().current_select->is_item_list_lookup= save_is_item_list_lookup;
03379   session->lex().current_select->cur_pos_in_select_list= UNDEF_POS;
03380 
03381   session->lex().allow_sum_func= save_allow_sum_func;
03382   session->mark_used_columns= save_mark_used_columns;
03383   return(test(session->is_error()));
03384 }
03385 
03386 
03387 /*
03388   make list of leaves of join table tree
03389 
03390   SYNOPSIS
03391   make_leaves_list()
03392   list    pointer to pointer on list first element
03393   tables  table list
03394 
03395   RETURN pointer on pointer to next_leaf of last element
03396 */
03397 
03398 static TableList **make_leaves_list(TableList **list, TableList *tables)
03399 {
03400   for (TableList *table= tables; table; table= table->next_local)
03401   {
03402     {
03403       *list= table;
03404       list= &table->next_leaf;
03405     }
03406   }
03407   return list;
03408 }
03409 
03410 /*
03411   prepare tables
03412 
03413   SYNOPSIS
03414   setup_tables()
03415   session     Thread Cursor
03416   context       name resolution contest to setup table list there
03417   from_clause   Top-level list of table references in the FROM clause
03418   tables    Table list (select_lex->table_list)
03419   leaves        List of join table leaves list (select_lex->leaf_tables)
03420   refresh       It is onle refresh for subquery
03421   select_insert It is SELECT ... INSERT command
03422 
03423   NOTE
03424   Check also that the 'used keys' and 'ignored keys' exists and set up the
03425   table structure accordingly.
03426   Create a list of leaf tables. For queries with NATURAL/USING JOINs,
03427   compute the row types of the top most natural/using join table references
03428   and link these into a list of table references for name resolution.
03429 
03430   This has to be called for all tables that are used by items, as otherwise
03431   table->map is not set and all Item_field will be regarded as const items.
03432 
03433   RETURN
03434   false ok;  In this case *map will includes the chosen index
03435   true  error
03436 */
03437 
03438 bool setup_tables(Session *session, Name_resolution_context *context,
03439                   List<TableList> *from_clause, TableList *tables,
03440                   TableList **leaves, bool select_insert)
03441 {
03442   uint32_t tablenr= 0;
03443 
03444   assert ((select_insert && !tables->next_name_resolution_table) || !tables ||
03445           (context->table_list && context->first_name_resolution_table));
03446   /*
03447     this is used for INSERT ... SELECT.
03448     For select we setup tables except first (and its underlying tables)
03449   */
03450   TableList *first_select_table= (select_insert ?  tables->next_local: NULL);
03451 
03452   if (!(*leaves))
03453     make_leaves_list(leaves, tables);
03454 
03455   TableList *table_list;
03456   for (table_list= *leaves;
03457        table_list;
03458        table_list= table_list->next_leaf, tablenr++)
03459   {
03460     Table *table= table_list->table;
03461     table->pos_in_table_list= table_list;
03462     if (first_select_table &&
03463         table_list->top_table() == first_select_table)
03464     {
03465       /* new counting for SELECT of INSERT ... SELECT command */
03466       first_select_table= 0;
03467       tablenr= 0;
03468     }
03469     table->setup_table_map(table_list, tablenr);
03470     if (table_list->process_index_hints(table))
03471       return 1;
03472   }
03473   if (tablenr > MAX_TABLES)
03474   {
03475     my_error(ER_TOO_MANY_TABLES,MYF(0),MAX_TABLES);
03476     return 1;
03477   }
03478 
03479   /* Precompute and store the row types of NATURAL/USING joins. */
03480   if (setup_natural_join_row_types(session, from_clause, context))
03481     return 1;
03482 
03483   return 0;
03484 }
03485 
03486 
03487 /*
03488   prepare tables and check access for the view tables
03489 
03490   SYNOPSIS
03491   setup_tables_and_check_view_access()
03492   session     Thread Cursor
03493   context       name resolution contest to setup table list there
03494   from_clause   Top-level list of table references in the FROM clause
03495   tables    Table list (select_lex->table_list)
03496   conds   Condition of current SELECT (can be changed by VIEW)
03497   leaves        List of join table leaves list (select_lex->leaf_tables)
03498   refresh       It is onle refresh for subquery
03499   select_insert It is SELECT ... INSERT command
03500   want_access   what access is needed
03501 
03502   NOTE
03503   a wrapper for check_tables that will also check the resulting
03504   table leaves list for access to all the tables that belong to a view
03505 
03506   RETURN
03507   false ok;  In this case *map will include the chosen index
03508   true  error
03509 */
03510 bool setup_tables_and_check_access(Session *session,
03511                                    Name_resolution_context *context,
03512                                    List<TableList> *from_clause,
03513                                    TableList *tables,
03514                                    TableList **leaves,
03515                                    bool select_insert)
03516 {
03517   TableList *leaves_tmp= NULL;
03518 
03519   if (setup_tables(session, context, from_clause, tables,
03520                    &leaves_tmp, select_insert))
03521     return true;
03522 
03523   if (leaves)
03524     *leaves= leaves_tmp;
03525 
03526   return false;
03527 }
03528 
03529 
03530 /*
03531   Drops in all fields instead of current '*' field
03532 
03533   SYNOPSIS
03534   insert_fields()
03535   session     Thread Cursor
03536   context             Context for name resolution
03537   db_name   Database name in case of 'database_name.table_name.*'
03538   table_name    Table name in case of 'table_name.*'
03539   it      Pointer to '*'
03540   any_privileges  0 If we should ensure that we have SELECT privileges
03541   for all columns
03542   1 If any privilege is ok
03543   RETURN
03544   0 ok     'it' is updated to point at last inserted
03545   1 error.  Error message is generated but not sent to client
03546 */
03547 
03548 bool
03549 insert_fields(Session *session, Name_resolution_context *context, const char *db_name,
03550               const char *table_name, List<Item>::iterator *it,
03551               bool )
03552 {
03553   Field_iterator_table_ref field_iterator;
03554   bool found;
03555   char name_buff[NAME_LEN+1];
03556 
03557   if (db_name)
03558   {
03559     /*
03560       convert database to lower case for comparison
03561       We can't do this in Item_field as this would change the
03562       'name' of the item which may be used in the select list
03563     */
03564     strncpy(name_buff, db_name, sizeof(name_buff)-1);
03565     my_casedn_str(files_charset_info, name_buff);
03566     db_name= name_buff;
03567   }
03568 
03569   found= false;
03570 
03571   /*
03572     If table names are qualified, then loop over all tables used in the query,
03573     else treat natural joins as leaves and do not iterate over their underlying
03574     tables.
03575   */
03576   for (TableList *tables= (table_name ? context->table_list :
03577                            context->first_name_resolution_table);
03578        tables;
03579        tables= (table_name ? tables->next_local :
03580                 tables->next_name_resolution_table)
03581       )
03582   {
03583     Field *field;
03584     Table *table= tables->table;
03585 
03586     assert(tables->is_leaf_for_name_resolution());
03587 
03588     if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
03589         (db_name && my_strcasecmp(system_charset_info, tables->getSchemaName(),db_name)))
03590       continue;
03591 
03592     /*
03593       Update the tables used in the query based on the referenced fields. For
03594       views and natural joins this update is performed inside the loop below.
03595     */
03596     if (table)
03597       session->used_tables|= table->map;
03598 
03599     /*
03600       Initialize a generic field iterator for the current table reference.
03601       Notice that it is guaranteed that this iterator will iterate over the
03602       fields of a single table reference, because 'tables' is a leaf (for
03603       name resolution purposes).
03604     */
03605     field_iterator.set(tables);
03606 
03607     for (; !field_iterator.end_of_fields(); field_iterator.next())
03608     {
03609       Item *item;
03610 
03611       if (!(item= field_iterator.create_item(session)))
03612         return true;
03613 
03614       if (!found)
03615       {
03616         found= true;
03617         it->replace(item); /* Replace '*' with the first found item. */
03618       }
03619       else
03620         it->after(item);   /* Add 'item' to the SELECT list. */
03621 
03622       if ((field= field_iterator.field()))
03623       {
03624         /* Mark fields as used to allow storage engine to optimze access */
03625         field->getTable()->setReadSet(field->position());
03626         if (table)
03627         {
03628           table->covering_keys&= field->part_of_key;
03629           table->merge_keys|= field->part_of_key;
03630         }
03631         if (tables->is_natural_join)
03632         {
03633           Table *field_table;
03634           /*
03635             In this case we are sure that the column ref will not be created
03636             because it was already created and stored with the natural join.
03637           */
03638           Natural_join_column *nj_col;
03639           if (!(nj_col= field_iterator.get_natural_column_ref()))
03640             return true;
03641           assert(nj_col->table_field);
03642           field_table= nj_col->table_ref->table;
03643           if (field_table)
03644           {
03645             session->used_tables|= field_table->map;
03646             field_table->covering_keys&= field->part_of_key;
03647             field_table->merge_keys|= field->part_of_key;
03648             field_table->used_fields++;
03649           }
03650         }
03651       }
03652       else
03653       {
03654         session->used_tables|= item->used_tables();
03655       }
03656 
03657       session->lex().current_select->cur_pos_in_select_list++;
03658     }
03659     /*
03660       In case of stored tables, all fields are considered as used,
03661       while in the case of views, the fields considered as used are the
03662       ones marked in setup_tables during fix_fields of view columns.
03663       For NATURAL joins, used_tables is updated in the IF above.
03664     */
03665     if (table)
03666       table->used_fields= table->getShare()->sizeFields();
03667   }
03668   if (found)
03669     return false;
03670 
03671   /*
03672     @TODO in the case when we skipped all columns because there was a
03673     qualified '*', and all columns were coalesced, we have to give a more
03674     meaningful message than ER_BAD_TABLE_ERROR.
03675   */
03676   if (not table_name)
03677   {
03678     my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
03679   }
03680   else
03681   {
03682     my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
03683   }
03684 
03685   return true;
03686 }
03687 
03688 
03689 /*
03690   Fix all conditions and outer join expressions.
03691 
03692   SYNOPSIS
03693   setup_conds()
03694   session     thread Cursor
03695   tables  list of tables for name resolving (select_lex->table_list)
03696   leaves  list of leaves of join table tree (select_lex->leaf_tables)
03697   conds   WHERE clause
03698 
03699   DESCRIPTION
03700   TODO
03701 
03702   RETURN
03703   true  if some error occured (e.g. out of memory)
03704   false if all is OK
03705 */
03706 
03707 int Session::setup_conds(TableList *leaves, COND **conds)
03708 {
03709   Session *session= this;
03710   Select_Lex *select_lex= session->lex().current_select;
03711   TableList *table= NULL; // For HP compilers
03712   void *save_session_marker= session->session_marker;
03713   /*
03714     it_is_update set to true when tables of primary Select_Lex (Select_Lex
03715     which belong to LEX, i.e. most up SELECT) will be updated by
03716     INSERT/UPDATE/LOAD
03717     NOTE-> using this condition helps to prevent call of prepare_check_option()
03718     from subquery of VIEW, because tables of subquery belongs to VIEW
03719     (see condition before prepare_check_option() call)
03720   */
03721   bool save_is_item_list_lookup= select_lex->is_item_list_lookup;
03722   select_lex->is_item_list_lookup= 0;
03723 
03724   session->mark_used_columns= MARK_COLUMNS_READ;
03725   select_lex->cond_count= 0;
03726   select_lex->between_count= 0;
03727   select_lex->max_equal_elems= 0;
03728 
03729   session->session_marker= (void*)1;
03730   if (*conds)
03731   {
03732     session->setWhere("where clause");
03733     if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
03734         (*conds)->check_cols(1))
03735       goto err_no_arena;
03736   }
03737   session->session_marker= save_session_marker;
03738 
03739   /*
03740     Apply fix_fields() to all ON clauses at all levels of nesting,
03741     including the ones inside view definitions.
03742   */
03743   for (table= leaves; table; table= table->next_leaf)
03744   {
03745     TableList *embedded; /* The table at the current level of nesting. */
03746     TableList *embedding= table; /* The parent nested table reference. */
03747     do
03748     {
03749       embedded= embedding;
03750       if (embedded->on_expr)
03751       {
03752         /* Make a join an a expression */
03753         session->session_marker= (void*)embedded;
03754         session->setWhere("on clause");
03755         if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
03756             embedded->on_expr->check_cols(1))
03757           goto err_no_arena;
03758         select_lex->cond_count++;
03759       }
03760       embedding= embedded->getEmbedding();
03761     }
03762     while (embedding &&
03763            &embedding->getNestedJoin()->join_list.front() == embedded);
03764 
03765   }
03766   session->session_marker= save_session_marker;
03767 
03768   session->lex().current_select->is_item_list_lookup= save_is_item_list_lookup;
03769   return(test(session->is_error()));
03770 
03771 err_no_arena:
03772   select_lex->is_item_list_lookup= save_is_item_list_lookup;
03773 
03774   return 1;
03775 }
03776 
03777 
03778 /******************************************************************************
03779  ** Fill a record with data (for INSERT or UPDATE)
03780  ** Returns : 1 if some field has wrong type
03781  ******************************************************************************/
03782 
03783 
03784 /*
03785   Fill fields with given items.
03786 
03787   SYNOPSIS
03788   fill_record()
03789   fields        Item_fields list to be filled
03790   values        values to fill with
03791   ignore_errors true if we should ignore errors
03792 
03793   NOTE
03794   fill_record() may set table->auto_increment_field_not_null and a
03795   caller should make sure that it is reset after their last call to this
03796   function.
03797 
03798   RETURN
03799   false   OK
03800   true    error occured
03801 */
03802 
03803 bool
03804 fill_record(Session *session, List<Item> &fields, List<Item> &values, bool ignore_errors)
03805 {
03806   List<Item>::iterator f(fields.begin());
03807   List<Item>::iterator v(values.begin());
03808   Item *value;
03809   Item_field *field;
03810   Table *table;
03811 
03812   /*
03813     Reset the table->auto_increment_field_not_null as it is valid for
03814     only one row.
03815   */
03816   if (fields.size())
03817   {
03818     /*
03819       On INSERT or UPDATE fields are checked to be from the same table,
03820       thus we safely can take table from the first field.
03821     */
03822     field= static_cast<Item_field *>(f++);
03823     table= field->field->getTable();
03824     table->auto_increment_field_not_null= false;
03825     f= fields.begin();
03826   }
03827 
03828   while ((field= static_cast<Item_field *>(f++)))
03829   {
03830     value= v++;
03831 
03832     Field *rfield= field->field;
03833     table= rfield->getTable();
03834 
03835     if (rfield == table->next_number_field)
03836       table->auto_increment_field_not_null= true;
03837     if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
03838     {
03839       my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
03840       if (table)
03841         table->auto_increment_field_not_null= false;
03842 
03843       return true;
03844     }
03845   }
03846 
03847   return session->is_error();
03848 }
03849 
03850 
03851 /*
03852   Fill field buffer with values from Field list
03853 
03854   SYNOPSIS
03855   fill_record()
03856   ptr           pointer on pointer to record
03857   values        list of fields
03858   ignore_errors true if we should ignore errors
03859 
03860   NOTE
03861   fill_record() may set table->auto_increment_field_not_null and a
03862   caller should make sure that it is reset after their last call to this
03863   function.
03864 
03865   RETURN
03866   false   OK
03867   true    error occured
03868 */
03869 
03870 bool fill_record(Session *session, Field **ptr, List<Item> &values, bool)
03871 {
03872   List<Item>::iterator v(values.begin());
03873   Item *value;
03874   Table *table= 0;
03875   Field *field;
03876 
03877   /*
03878     Reset the table->auto_increment_field_not_null as it is valid for
03879     only one row.
03880   */
03881   if (*ptr)
03882   {
03883     /*
03884       On INSERT or UPDATE fields are checked to be from the same table,
03885       thus we safely can take table from the first field.
03886     */
03887     table= (*ptr)->getTable();
03888     table->auto_increment_field_not_null= false;
03889   }
03890 
03891   while ((field = *ptr++) && ! session->is_error())
03892   {
03893     value=v++;
03894     table= field->getTable();
03895 
03896     if (field == table->next_number_field)
03897       table->auto_increment_field_not_null= true;
03898 
03899     if (value->save_in_field(field, 0) < 0)
03900     {
03901       if (table)
03902         table->auto_increment_field_not_null= false;
03903 
03904       return true;
03905     }
03906   }
03907 
03908   return(session->is_error());
03909 }
03910 
03911 
03912 bool drizzle_rm_tmp_tables()
03913 {
03914 
03915   assert(drizzle_tmpdir.size());
03916   Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
03917 
03918   if (not session)
03919     return true;
03920   session->thread_stack= (char*) session.get();
03921   session->storeGlobals();
03922 
03923   plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
03924 
03925   return false;
03926 }
03927 
03928 
03929 
03930 /*****************************************************************************
03931   unireg support functions
03932  *****************************************************************************/
03933 
03934 
03935 
03936 
03941 void kill_drizzle(void)
03942 {
03943   pthread_kill(signal_thread, SIGTERM);
03944   shutdown_in_progress= 1;      // Safety if kill didn't work
03945 }
03946 
03947 } /* namespace drizzled */