MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
sql_base.cc
1 /* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software
14  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15 
16 /* Basic functions needed by many modules */
17 
18 #include "sql_base.h" // setup_table_map
19 #include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */
20 #include "sql_priv.h"
21 #include "unireg.h"
22 #include "debug_sync.h"
23 #include "lock.h" // mysql_lock_remove,
24  // mysql_unlock_tables,
25  // mysql_lock_have_duplicate
26 #include "sql_show.h" // append_identifier
27 #include "strfunc.h" // find_type
28 #include "sql_view.h" // mysql_make_view, VIEW_ANY_ACL
29 #include "sql_parse.h" // check_table_access
30 #include "sql_insert.h" // kill_delayed_threads
31 #include "sql_acl.h" // *_ACL, check_grant_all_columns,
32  // check_column_grant_in_table_ref,
33  // get_column_grant
34 #include "sql_partition.h" // ALTER_PARTITION_PARAM_TYPE
35 #include "sql_derived.h" // mysql_derived_prepare,
36  // mysql_handle_derived,
37  // mysql_derived_filling
38 #include "sql_handler.h" // mysql_ha_flush
39 #include "sql_partition.h" // ALTER_PARTITION_PARAM_TYPE
40 #include "log_event.h" // Query_log_event
41 #include "sql_select.h"
42 #include "sp_head.h"
43 #include "sp.h"
44 #include "sp_cache.h"
45 #include "sql_trigger.h"
46 #include "transaction.h"
47 #include "sql_prepare.h"
48 #include <m_ctype.h>
49 #include <my_dir.h>
50 #include <hash.h>
51 #include "rpl_filter.h"
52 #include "sql_table.h" // build_table_filename
53 #include "datadict.h" // dd_frm_type()
54 #include "sql_hset.h" // Hash_set
55 #include "sql_tmp_table.h" // free_tmp_table
56 #ifdef __WIN__
57 #include <io.h>
58 #endif
59 #include "table_cache.h" // Table_cache_manager, Table_cache
60 
61 
62 bool
63 No_such_table_error_handler::handle_condition(THD *,
64  uint sql_errno,
65  const char*,
66  Sql_condition::enum_warning_level,
67  const char*,
68  Sql_condition ** cond_hdl)
69 {
70  *cond_hdl= NULL;
71  if (sql_errno == ER_NO_SUCH_TABLE)
72  {
73  m_handled_errors++;
74  return TRUE;
75  }
76 
77  m_unhandled_errors++;
78  return FALSE;
79 }
80 
81 
83 {
84  /*
85  If m_unhandled_errors != 0, something else, unanticipated, happened,
86  so the error is not trapped but returned to the caller.
87  Multiple ER_NO_SUCH_TABLE can be raised in case of views.
88  */
89  return ((m_handled_errors > 0) && (m_unhandled_errors == 0));
90 }
91 
92 
99 class Repair_mrg_table_error_handler : public Internal_error_handler
100 {
101 public:
103  : m_handled_errors(false), m_unhandled_errors(false)
104  {}
105 
106  bool handle_condition(THD *thd,
107  uint sql_errno,
108  const char* sqlstate,
109  Sql_condition::enum_warning_level level,
110  const char* msg,
111  Sql_condition ** cond_hdl);
112 
118  {
119  /*
120  Check for m_handled_errors is here for extra safety.
121  It can be useful in situation when call to open_table()
122  fails because some error which was suppressed by another
123  error handler (e.g. in case of MDL deadlock which we
124  decided to solve by back-off and retry).
125  */
126  return (m_handled_errors && (! m_unhandled_errors));
127  }
128 
129 private:
130  bool m_handled_errors;
131  bool m_unhandled_errors;
132 };
133 
134 
135 bool
136 Repair_mrg_table_error_handler::handle_condition(THD *,
137  uint sql_errno,
138  const char*,
139  Sql_condition::enum_warning_level level,
140  const char*,
141  Sql_condition ** cond_hdl)
142 {
143  *cond_hdl= NULL;
144  if (sql_errno == ER_NO_SUCH_TABLE || sql_errno == ER_WRONG_MRG_TABLE)
145  {
146  m_handled_errors= true;
147  return TRUE;
148  }
149 
150  m_unhandled_errors= true;
151  return FALSE;
152 }
153 
154 
194 
195 #ifdef HAVE_PSI_INTERFACE
196 static PSI_mutex_key key_LOCK_open;
197 static PSI_mutex_info all_tdc_mutexes[]= {
198  { &key_LOCK_open, "LOCK_open", PSI_FLAG_GLOBAL }
199 };
200 
206 static void init_tdc_psi_keys(void)
207 {
208  const char *category= "sql";
209  int count;
210 
211  count= array_elements(all_tdc_mutexes);
212  mysql_mutex_register(category, all_tdc_mutexes, count);
213 }
214 #endif /* HAVE_PSI_INTERFACE */
215 
216 static void modify_slave_open_temp_tables(THD *thd, int inc)
217 {
218  if (thd->system_thread == SYSTEM_THREAD_SLAVE_WORKER)
219  {
220  my_atomic_rwlock_wrlock(&slave_open_temp_tables_lock);
221  my_atomic_add32(&slave_open_temp_tables, inc);
222  my_atomic_rwlock_wrunlock(&slave_open_temp_tables_lock);
223  }
224  else
225  {
226  slave_open_temp_tables += inc;
227  }
228 }
229 
230 
231 HASH table_def_cache;
232 static TABLE_SHARE *oldest_unused_share, end_of_unused_share;
233 static bool table_def_inited= false;
234 static bool table_def_shutdown_in_progress= false;
235 
236 static bool check_and_update_table_version(THD *thd, TABLE_LIST *tables,
237  TABLE_SHARE *table_share);
238 static bool open_table_entry_fini(THD *thd, TABLE_SHARE *share, TABLE *entry);
239 static bool auto_repair_table(THD *thd, TABLE_LIST *table_list);
240 static bool
241 has_write_table_with_auto_increment(TABLE_LIST *tables);
242 static bool
243 has_write_table_with_auto_increment_and_select(TABLE_LIST *tables);
244 static bool has_write_table_auto_increment_not_first_in_pk(TABLE_LIST *tables);
245 
246 
271 static uint create_table_def_key(THD *thd, char *key,
272  const char *db_name, const char *table_name,
273  bool tmp_table)
274 {
275  /*
276  In theory caller should ensure that both db and table_name are
277  not longer than NAME_LEN bytes. In practice we play safe to avoid
278  buffer overruns.
279  */
280  DBUG_ASSERT(strlen(db_name) <= NAME_LEN && strlen(table_name) <= NAME_LEN);
281  uint key_length= static_cast<uint>(strmake(strmake(key, db_name, NAME_LEN) +
282  1, table_name, NAME_LEN) - key +
283  1);
284 
285  if (tmp_table)
286  {
287  int4store(key + key_length, thd->server_id);
288  int4store(key + key_length + 4, thd->variables.pseudo_thread_id);
289  key_length+= TMP_TABLE_KEY_EXTRA;
290  }
291  return key_length;
292 }
293 
294 
315 uint get_table_def_key(const TABLE_LIST *table_list, const char **key)
316 {
317  /*
318  This call relies on the fact that TABLE_LIST::mdl_request::key object
319  is properly initialized, so table definition cache can be produced
320  from key used by MDL subsystem.
321  */
322  DBUG_ASSERT(!strcmp(table_list->get_db_name(),
323  table_list->mdl_request.key.db_name()) &&
324  !strcmp(table_list->get_table_name(),
325  table_list->mdl_request.key.name()));
326 
327  *key= (const char*)table_list->mdl_request.key.ptr() + 1;
328  return table_list->mdl_request.key.length() - 1;
329 }
330 
331 
332 
333 /*****************************************************************************
334  Functions to handle table definition cach (TABLE_SHARE)
335 *****************************************************************************/
336 
337 extern "C" uchar *table_def_key(const uchar *record, size_t *length,
338  my_bool not_used __attribute__((unused)))
339 {
340  TABLE_SHARE *entry=(TABLE_SHARE*) record;
341  *length= entry->table_cache_key.length;
342  return (uchar*) entry->table_cache_key.str;
343 }
344 
345 
346 static void table_def_free_entry(TABLE_SHARE *share)
347 {
348  DBUG_ENTER("table_def_free_entry");
349  mysql_mutex_assert_owner(&LOCK_open);
350  if (share->prev)
351  {
352  /* remove from old_unused_share list */
353  *share->prev= share->next;
354  share->next->prev= share->prev;
355  }
356  free_table_share(share);
357  DBUG_VOID_RETURN;
358 }
359 
360 
361 bool table_def_init(void)
362 {
363 #ifdef HAVE_PSI_INTERFACE
364  init_tdc_psi_keys();
365 #endif
366  mysql_mutex_init(key_LOCK_open, &LOCK_open, MY_MUTEX_INIT_FAST);
367  oldest_unused_share= &end_of_unused_share;
368  end_of_unused_share.prev= &oldest_unused_share;
369 
370  if (table_cache_manager.init())
371  {
372  mysql_mutex_destroy(&LOCK_open);
373  return true;
374  }
375 
376  /*
377  It is safe to destroy zero-initialized HASH even if its
378  initialization has failed.
379  */
380  table_def_inited= true;
381 
382  return my_hash_init(&table_def_cache, &my_charset_bin, table_def_size,
383  0, 0, table_def_key,
384  (my_hash_free_key) table_def_free_entry, 0) != 0;
385 }
386 
387 
395 {
396  if (table_def_inited)
397  {
398  table_cache_manager.lock_all_and_tdc();
399  /*
400  Ensure that TABLE and TABLE_SHARE objects which are created for
401  tables that are open during process of plugins' shutdown are
402  immediately released. This keeps number of references to engine
403  plugins minimal and allows shutdown to proceed smoothly.
404  */
405  table_def_shutdown_in_progress= true;
406  table_cache_manager.unlock_all_and_tdc();
407  /* Free all cached but unused TABLEs and TABLE_SHAREs. */
408  close_cached_tables(NULL, NULL, FALSE, LONG_TIMEOUT);
409  }
410 }
411 
412 
413 void table_def_free(void)
414 {
415  DBUG_ENTER("table_def_free");
416  if (table_def_inited)
417  {
418  table_def_inited= false;
419  /* Free table definitions. */
420  my_hash_free(&table_def_cache);
421  table_cache_manager.destroy();
422  mysql_mutex_destroy(&LOCK_open);
423  }
424  DBUG_VOID_RETURN;
425 }
426 
427 
428 uint cached_table_definitions(void)
429 {
430  return table_def_cache.records;
431 }
432 
433 
434 /*
435  Get TABLE_SHARE for a table.
436 
437  get_table_share()
438  thd Thread handle
439  table_list Table that should be opened
440  key Table cache key
441  key_length Length of key
442  db_flags Flags to open_table_def():
443  OPEN_VIEW
444  error out: Error code from open_table_def()
445 
446  IMPLEMENTATION
447  Get a table definition from the table definition cache.
448  If it doesn't exist, create a new from the table definition file.
449 
450  NOTES
451  We must have wrlock on LOCK_open when we come here
452  (To be changed later)
453 
454  RETURN
455  0 Error
456  # Share for table
457 */
458 
459 TABLE_SHARE *get_table_share(THD *thd, TABLE_LIST *table_list,
460  const char *key, uint key_length,
461  uint db_flags, int *error,
462  my_hash_value_type hash_value)
463 {
464  TABLE_SHARE *share;
465  DBUG_ENTER("get_table_share");
466 
467  *error= 0;
468 
469  /*
470  To be able perform any operation on table we should own
471  some kind of metadata lock on it.
472  */
473  DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE,
474  table_list->db,
475  table_list->table_name,
476  MDL_SHARED));
477 
478  /* Read table definition from cache */
479  if ((share= (TABLE_SHARE*) my_hash_search_using_hash_value(&table_def_cache,
480  hash_value, (uchar*) key, key_length)))
481  goto found;
482 
483  if (!(share= alloc_table_share(table_list, key, key_length)))
484  {
485  DBUG_RETURN(0);
486  }
487 
488  /*
489  We assign a new table id under the protection of LOCK_open.
490  We do this instead of creating a new mutex
491  and using it for the sole purpose of serializing accesses to a
492  static variable, we assign the table id here. We assign it to the
493  share before inserting it into the table_def_cache to be really
494  sure that it cannot be read from the cache without having a table
495  id assigned.
496 
497  CAVEAT. This means that the table cannot be used for
498  binlogging/replication purposes, unless get_table_share() has been
499  called directly or indirectly.
500  */
501  assign_new_table_id(share);
502 
503  if (my_hash_insert(&table_def_cache, (uchar*) share))
504  {
505  free_table_share(share);
506  DBUG_RETURN(0); // return error
507  }
508  if (open_table_def(thd, share, db_flags))
509  {
510  *error= share->error;
511  (void) my_hash_delete(&table_def_cache, (uchar*) share);
512  DBUG_RETURN(0);
513  }
514  share->ref_count++; // Mark in use
515 
516 #ifdef HAVE_PSI_TABLE_INTERFACE
517  share->m_psi= PSI_TABLE_CALL(get_table_share)(false, share);
518 #else
519  share->m_psi= NULL;
520 #endif
521 
522  DBUG_PRINT("exit", ("share: 0x%lx ref_count: %u",
523  (ulong) share, share->ref_count));
524  DBUG_RETURN(share);
525 
526 found:
527  /*
528  We found an existing table definition. Return it if we didn't get
529  an error when reading the table definition from file.
530  */
531  if (share->error)
532  {
533  /* Table definition contained an error */
534  open_table_error(share, share->error, share->open_errno, share->errarg);
535  DBUG_RETURN(0);
536  }
537  if (share->is_view && !(db_flags & OPEN_VIEW))
538  {
539  open_table_error(share, 1, ENOENT, 0);
540  DBUG_RETURN(0);
541  }
542 
543  ++share->ref_count;
544 
545  if (share->ref_count == 1 && share->prev)
546  {
547  /*
548  Share was not used before and it was in the old_unused_share list
549  Unlink share from this list
550  */
551  DBUG_PRINT("info", ("Unlinking from not used list"));
552  *share->prev= share->next;
553  share->next->prev= share->prev;
554  share->next= 0;
555  share->prev= 0;
556  }
557 
558  /* Free cache if too big */
559  while (table_def_cache.records > table_def_size &&
560  oldest_unused_share->next)
561  my_hash_delete(&table_def_cache, (uchar*) oldest_unused_share);
562 
563  DBUG_PRINT("exit", ("share: 0x%lx ref_count: %u",
564  (ulong) share, share->ref_count));
565  DBUG_RETURN(share);
566 }
567 
568 
575 static TABLE_SHARE *
576 get_table_share_with_discover(THD *thd, TABLE_LIST *table_list,
577  const char *key, uint key_length,
578  uint db_flags, int *error,
579  my_hash_value_type hash_value)
580 
581 {
582  TABLE_SHARE *share;
583  bool exists;
584  DBUG_ENTER("get_table_share_with_create");
585 
586  share= get_table_share(thd, table_list, key, key_length, db_flags, error,
587  hash_value);
588  /*
589  If share is not NULL, we found an existing share.
590 
591  If share is NULL, and there is no error, we're inside
592  pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
593  with the intention to silently drop non-existing tables
594  from the pre-locking list. In this case we still need to try
595  auto-discover before returning a NULL share.
596 
597  Or, we're inside SHOW CREATE VIEW, which
598  also installs a silencer for ER_NO_SUCH_TABLE error.
599 
600  If share is NULL and the error is ER_NO_SUCH_TABLE, this is
601  the same as above, only that the error was not silenced by
602  pre-locking or SHOW CREATE VIEW.
603 
604  In both these cases it won't harm to try to discover the
605  table.
606 
607  Finally, if share is still NULL, it's a real error and we need
608  to abort.
609 
610  @todo Rework alternative ways to deal with ER_NO_SUCH TABLE.
611  */
612  if (share || (thd->is_error() &&
613  thd->get_stmt_da()->sql_errno() != ER_NO_SUCH_TABLE))
614  {
615  DBUG_RETURN(share);
616  }
617 
618  *error= 0;
619 
620  /* Table didn't exist. Check if some engine can provide it */
621  if (ha_check_if_table_exists(thd, table_list->db, table_list->table_name,
622  &exists))
623  {
624  thd->clear_error();
625  /* Conventionally, the storage engine API does not report errors. */
626  my_error(ER_OUT_OF_RESOURCES, MYF(0));
627  }
628  else if (! exists)
629  {
630  /*
631  No such table in any engine.
632  Hide "Table doesn't exist" errors if the table belongs to a view.
633  The check for thd->is_error() is necessary to not push an
634  unwanted error in case the error was already silenced.
635  @todo Rework the alternative ways to deal with ER_NO_SUCH TABLE.
636  */
637  if (thd->is_error())
638  {
639  if (table_list->parent_l)
640  {
641  thd->clear_error();
642  my_error(ER_WRONG_MRG_TABLE, MYF(0));
643  }
644  else if (table_list->belong_to_view)
645  {
646  TABLE_LIST *view= table_list->belong_to_view;
647  thd->clear_error();
648  my_error(ER_VIEW_INVALID, MYF(0),
649  view->view_db.str, view->view_name.str);
650  }
651  }
652  }
653  else
654  {
655  thd->clear_error();
656  *error= 7; /* Run auto-discover. */
657  }
658  DBUG_RETURN(NULL);
659 }
660 
661 
673 {
674  DBUG_ENTER("release_table_share");
675  DBUG_PRINT("enter",
676  ("share: 0x%lx table: %s.%s ref_count: %u version: %lu",
677  (ulong) share, share->db.str, share->table_name.str,
678  share->ref_count, share->version));
679 
680  mysql_mutex_assert_owner(&LOCK_open);
681 
682  DBUG_ASSERT(share->ref_count);
683  if (!--share->ref_count)
684  {
685  if (share->has_old_version() || table_def_shutdown_in_progress)
686  my_hash_delete(&table_def_cache, (uchar*) share);
687  else
688  {
689  /* Link share last in used_table_share list */
690  DBUG_PRINT("info",("moving share to unused list"));
691 
692  DBUG_ASSERT(share->next == 0);
693  share->prev= end_of_unused_share.prev;
694  *end_of_unused_share.prev= share;
695  end_of_unused_share.prev= &share->next;
696  share->next= &end_of_unused_share;
697 
698  if (table_def_cache.records > table_def_size)
699  {
700  /* Delete the least used share to preserve LRU order. */
701  my_hash_delete(&table_def_cache, (uchar*) oldest_unused_share);
702  }
703  }
704  }
705 
706  DBUG_VOID_RETURN;
707 }
708 
709 
710 /*
711  Check if table definition exits in cache
712 
713  SYNOPSIS
714  get_cached_table_share()
715  db Database name
716  table_name Table name
717 
718  RETURN
719  0 Not cached
720  # TABLE_SHARE for table
721 */
722 
723 TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name)
724 {
725  char key[MAX_DBKEY_LENGTH];
726  uint key_length;
727  mysql_mutex_assert_owner(&LOCK_open);
728 
729  key_length= create_table_def_key((THD*) 0, key, db, table_name, 0);
730  return (TABLE_SHARE*) my_hash_search(&table_def_cache,
731  (uchar*) key, key_length);
732 }
733 
734 
735 /*
736  Create a list for all open tables matching SQL expression
737 
738  SYNOPSIS
739  list_open_tables()
740  thd Thread THD
741  wild SQL like expression
742 
743  NOTES
744  One gets only a list of tables for which one has any kind of privilege.
745  db and table names are allocated in result struct, so one doesn't need
746  a lock on LOCK_open when traversing the return list.
747 
748  RETURN VALUES
749  NULL Error (Probably OOM)
750  # Pointer to list of names of open tables.
751 */
752 
753 OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild)
754 {
755  int result = 0;
756  OPEN_TABLE_LIST **start_list, *open_list;
757  TABLE_LIST table_list;
758  DBUG_ENTER("list_open_tables");
759 
760  memset(&table_list, 0, sizeof(table_list));
761  start_list= &open_list;
762  open_list=0;
763 
764  table_cache_manager.lock_all_and_tdc();
765 
766  for (uint idx=0 ; result == 0 && idx < table_def_cache.records; idx++)
767  {
768  TABLE_SHARE *share= (TABLE_SHARE *)my_hash_element(&table_def_cache, idx);
769 
770  if (db && my_strcasecmp(system_charset_info, db, share->db.str))
771  continue;
772  if (wild && wild_compare(share->table_name.str, wild, 0))
773  continue;
774 
775  /* Check if user has SELECT privilege for any column in the table */
776  table_list.db= share->db.str;
777  table_list.table_name= share->table_name.str;
778  table_list.grant.privilege=0;
779 
780  if (check_table_access(thd,SELECT_ACL,&table_list, TRUE, 1, TRUE))
781  continue;
782 
783  if (!(*start_list = (OPEN_TABLE_LIST *)
784  sql_alloc(sizeof(**start_list)+share->table_cache_key.length)))
785  {
786  open_list=0; // Out of memory
787  break;
788  }
789  strmov((*start_list)->table=
790  strmov(((*start_list)->db= (char*) ((*start_list)+1)),
791  share->db.str)+1,
792  share->table_name.str);
793  (*start_list)->in_use= 0;
794  Table_cache_iterator it(share);
795  while (it++)
796  ++(*start_list)->in_use;
797  (*start_list)->locked= 0; /* Obsolete. */
798  start_list= &(*start_list)->next;
799  *start_list=0;
800  }
801  table_cache_manager.unlock_all_and_tdc();
802  DBUG_RETURN(open_list);
803 }
804 
805 /*****************************************************************************
806  * Functions to free open table cache
807  ****************************************************************************/
808 
809 
810 void intern_close_table(TABLE *table)
811 { // Free all structures
812  DBUG_ENTER("intern_close_table");
813  DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx",
814  table->s ? table->s->db.str : "?",
815  table->s ? table->s->table_name.str : "?",
816  (long) table));
817 
818  free_io_cache(table);
819  delete table->triggers;
820  if (table->file) // Not true if placeholder
821  (void) closefrm(table, 1); // close file
822  my_free(table);
823  DBUG_VOID_RETURN;
824 }
825 
826 
827 /* Free resources allocated by filesort() and read_record() */
828 
829 void free_io_cache(TABLE *table)
830 {
831  DBUG_ENTER("free_io_cache");
832  if (table->sort.io_cache)
833  {
834  close_cached_file(table->sort.io_cache);
835  my_free(table->sort.io_cache);
836  table->sort.io_cache=0;
837  }
838  DBUG_VOID_RETURN;
839 }
840 
841 
851 static void kill_delayed_threads_for_table(TABLE_SHARE *share)
852 {
853  table_cache_manager.assert_owner_all();
854 
855  Table_cache_iterator it(share);
856  TABLE *tab;
857 
858  while ((tab= it++))
859  {
860  THD *in_use= tab->in_use;
861 
862  if ((in_use->system_thread & SYSTEM_THREAD_DELAYED_INSERT) &&
863  ! in_use->killed)
864  {
865  in_use->killed= THD::KILL_CONNECTION;
866  mysql_mutex_lock(&in_use->mysys_var->mutex);
867  if (in_use->mysys_var->current_cond)
868  {
869  mysql_mutex_lock(in_use->mysys_var->current_mutex);
870  mysql_cond_broadcast(in_use->mysys_var->current_cond);
871  mysql_mutex_unlock(in_use->mysys_var->current_mutex);
872  }
873  mysql_mutex_unlock(&in_use->mysys_var->mutex);
874  }
875  }
876 }
877 
878 
879 /*
880  Close all tables which aren't in use by any thread
881 
882  @param thd Thread context
883  @param tables List of tables to remove from the cache
884  @param wait_for_refresh Wait for a impending flush
885  @param timeout Timeout for waiting for flush to be completed.
886 
887  @note THD can be NULL, but then wait_for_refresh must be FALSE
888  and tables must be NULL.
889 
890  @note When called as part of FLUSH TABLES WITH READ LOCK this function
891  ignores metadata locks held by other threads. In order to avoid
892  situation when FLUSH TABLES WITH READ LOCK sneaks in at the moment
893  when some write-locked table is being reopened (by FLUSH TABLES or
894  ALTER TABLE) we have to rely on additional global shared metadata
895  lock taken by thread trying to obtain global read lock.
896 */
897 
898 bool close_cached_tables(THD *thd, TABLE_LIST *tables,
899  bool wait_for_refresh, ulong timeout)
900 {
901  bool result= FALSE;
902  bool found= TRUE;
903  struct timespec abstime;
904  DBUG_ENTER("close_cached_tables");
905  DBUG_ASSERT(thd || (!wait_for_refresh && !tables));
906 
907  table_cache_manager.lock_all_and_tdc();
908  if (!tables)
909  {
910  /*
911  Force close of all open tables.
912 
913  Note that code in TABLE_SHARE::wait_for_old_version() assumes that
914  incrementing of refresh_version and removal of unused tables and
915  shares from TDC happens atomically under protection of LOCK_open,
916  or putting it another way that TDC does not contain old shares
917  which don't have any tables used.
918  */
919  refresh_version++;
920  DBUG_PRINT("tcache", ("incremented global refresh_version to: %lu",
921  refresh_version));
922  kill_delayed_threads();
923  /*
924  Get rid of all unused TABLE and TABLE_SHARE instances. By doing
925  this we automatically close all tables which were marked as "old".
926  */
927  table_cache_manager.free_all_unused_tables();
928  /* Free table shares which were not freed implicitly by loop above. */
929  while (oldest_unused_share->next)
930  (void) my_hash_delete(&table_def_cache, (uchar*) oldest_unused_share);
931  }
932  else
933  {
934  bool found=0;
935  for (TABLE_LIST *table= tables; table; table= table->next_local)
936  {
937  TABLE_SHARE *share= get_cached_table_share(table->db, table->table_name);
938 
939  if (share)
940  {
941  kill_delayed_threads_for_table(share);
942  /* tdc_remove_table() also sets TABLE_SHARE::version to 0. */
943  tdc_remove_table(thd, TDC_RT_REMOVE_UNUSED, table->db,
944  table->table_name, TRUE);
945  found=1;
946  }
947  }
948  if (!found)
949  wait_for_refresh=0; // Nothing to wait for
950  }
951 
952  table_cache_manager.unlock_all_and_tdc();
953 
954  if (!wait_for_refresh)
955  DBUG_RETURN(result);
956 
957  set_timespec(abstime, timeout);
958 
959  if (thd->locked_tables_mode)
960  {
961  /*
962  If we are under LOCK TABLES, we need to reopen the tables without
963  opening a door for any concurrent threads to sneak in and get
964  lock on our tables. To achieve this we use exclusive metadata
965  locks.
966  */
967  TABLE_LIST *tables_to_reopen= (tables ? tables :
968  thd->locked_tables_list.locked_tables());
969 
970  /* Close open HANLER instances to avoid self-deadlock. */
971  mysql_ha_flush_tables(thd, tables_to_reopen);
972 
973  for (TABLE_LIST *table_list= tables_to_reopen; table_list;
974  table_list= table_list->next_global)
975  {
976  /* A check that the table was locked for write is done by the caller. */
977  TABLE *table= find_table_for_mdl_upgrade(thd, table_list->db,
978  table_list->table_name, TRUE);
979 
980  /* May return NULL if this table has already been closed via an alias. */
981  if (! table)
982  continue;
983 
984  if (wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN))
985  {
986  result= TRUE;
987  goto err_with_reopen;
988  }
989  close_all_tables_for_name(thd, table->s, false, NULL);
990  }
991  }
992 
993  /* Wait until all threads have closed all the tables we are flushing. */
994  DBUG_PRINT("info", ("Waiting for other threads to close their open tables"));
995 
996  while (found && ! thd->killed)
997  {
998  TABLE_SHARE *share;
999  found= FALSE;
1000  /*
1001  To a self-deadlock or deadlocks with other FLUSH threads
1002  waiting on our open HANDLERs, we have to flush them.
1003  */
1004  mysql_ha_flush(thd);
1005  DEBUG_SYNC(thd, "after_flush_unlock");
1006 
1007  mysql_mutex_lock(&LOCK_open);
1008 
1009  if (!tables)
1010  {
1011  for (uint idx=0 ; idx < table_def_cache.records ; idx++)
1012  {
1013  share= (TABLE_SHARE*) my_hash_element(&table_def_cache, idx);
1014  if (share->has_old_version())
1015  {
1016  found= TRUE;
1017  break;
1018  }
1019  }
1020  }
1021  else
1022  {
1023  for (TABLE_LIST *table= tables; table; table= table->next_local)
1024  {
1025  share= get_cached_table_share(table->db, table->table_name);
1026  if (share && share->has_old_version())
1027  {
1028  found= TRUE;
1029  break;
1030  }
1031  }
1032  }
1033 
1034  if (found)
1035  {
1036  /*
1037  The method below temporarily unlocks LOCK_open and frees
1038  share's memory.
1039  */
1040  if (share->wait_for_old_version(thd, &abstime,
1041  MDL_wait_for_subgraph::DEADLOCK_WEIGHT_DDL))
1042  {
1043  mysql_mutex_unlock(&LOCK_open);
1044  result= TRUE;
1045  goto err_with_reopen;
1046  }
1047  }
1048 
1049  mysql_mutex_unlock(&LOCK_open);
1050  }
1051 
1052 err_with_reopen:
1053  if (thd->locked_tables_mode)
1054  {
1055  /*
1056  No other thread has the locked tables open; reopen them and get the
1057  old locks. This should always succeed (unless some external process
1058  has removed the tables)
1059  */
1060  thd->locked_tables_list.reopen_tables(thd);
1061  /*
1062  Since downgrade_lock() won't do anything with shared
1063  metadata lock it is much simpler to go through all open tables rather
1064  than picking only those tables that were flushed.
1065  */
1066  for (TABLE *tab= thd->open_tables; tab; tab= tab->next)
1067  tab->mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE);
1068  }
1069  DBUG_RETURN(result);
1070 }
1071 
1072 
1078 bool close_cached_connection_tables(THD *thd, LEX_STRING *connection)
1079 {
1080  uint idx;
1081  TABLE_LIST tmp, *tables= NULL;
1082  bool result= FALSE;
1083  DBUG_ENTER("close_cached_connections");
1084  DBUG_ASSERT(thd);
1085 
1086  memset(&tmp, 0, sizeof(TABLE_LIST));
1087 
1088  mysql_mutex_lock(&LOCK_open);
1089 
1090  for (idx= 0; idx < table_def_cache.records; idx++)
1091  {
1092  TABLE_SHARE *share= (TABLE_SHARE *) my_hash_element(&table_def_cache, idx);
1093 
1094  /* Ignore if table is not open or does not have a connect_string */
1095  if (!share->connect_string.length || !share->ref_count)
1096  continue;
1097 
1098  /* Compare the connection string */
1099  if (connection &&
1100  (connection->length > share->connect_string.length ||
1101  (connection->length < share->connect_string.length &&
1102  (share->connect_string.str[connection->length] != '/' &&
1103  share->connect_string.str[connection->length] != '\\')) ||
1104  strncasecmp(connection->str, share->connect_string.str,
1105  connection->length)))
1106  continue;
1107 
1108  /* close_cached_tables() only uses these elements */
1109  tmp.db= share->db.str;
1110  tmp.table_name= share->table_name.str;
1111  tmp.next_local= tables;
1112 
1113  tables= (TABLE_LIST *) memdup_root(thd->mem_root, (char*)&tmp,
1114  sizeof(TABLE_LIST));
1115  }
1116  mysql_mutex_unlock(&LOCK_open);
1117 
1118  if (tables)
1119  result= close_cached_tables(thd, tables, FALSE, LONG_TIMEOUT);
1120 
1121  DBUG_RETURN(result);
1122 }
1123 
1124 
1135 static void mark_temp_tables_as_free_for_reuse(THD *thd)
1136 {
1137  for (TABLE *table= thd->temporary_tables ; table ; table= table->next)
1138  {
1139  if ((table->query_id == thd->query_id) && ! table->open_by_handler)
1140  mark_tmp_table_for_reuse(table);
1141  }
1142 }
1143 
1144 
1154 {
1155  DBUG_ASSERT(table->s->tmp_table);
1156 
1157  table->query_id= 0;
1158  table->file->ha_reset();
1159 
1160  /* Detach temporary MERGE children from temporary parent. */
1161  DBUG_ASSERT(table->file);
1162  table->file->extra(HA_EXTRA_DETACH_CHILDREN);
1163 
1164  /*
1165  Reset temporary table lock type to it's default value (TL_WRITE).
1166 
1167  Statements such as INSERT INTO .. SELECT FROM tmp, CREATE TABLE
1168  .. SELECT FROM tmp and UPDATE may under some circumstances modify
1169  the lock type of the tables participating in the statement. This
1170  isn't a problem for non-temporary tables since their lock type is
1171  reset at every open, but the same does not occur for temporary
1172  tables for historical reasons.
1173 
1174  Furthermore, the lock type of temporary tables is not really that
1175  important because they can only be used by one query at a time and
1176  not even twice in a query -- a temporary table is represented by
1177  only one TABLE object. Nonetheless, it's safer from a maintenance
1178  point of view to reset the lock type of this singleton TABLE object
1179  as to not cause problems when the table is reused.
1180 
1181  Even under LOCK TABLES mode its okay to reset the lock type as
1182  LOCK TABLES is allowed (but ignored) for a temporary table.
1183  */
1184  table->reginfo.lock_type= TL_WRITE;
1185 }
1186 
1187 
1188 /*
1189  Mark all tables in the list which were used by current substatement
1190  as free for reuse.
1191 
1192  SYNOPSIS
1193  mark_used_tables_as_free_for_reuse()
1194  thd - thread context
1195  table - head of the list of tables
1196 
1197  DESCRIPTION
1198  Marks all tables in the list which were used by current substatement
1199  (they are marked by its query_id) as free for reuse.
1200 
1201  NOTE
1202  The reason we reset query_id is that it's not enough to just test
1203  if table->query_id != thd->query_id to know if a table is in use.
1204 
1205  For example
1206  SELECT f1_that_uses_t1() FROM t1;
1207  In f1_that_uses_t1() we will see one instance of t1 where query_id is
1208  set to query_id of original query.
1209 */
1210 
1211 static void mark_used_tables_as_free_for_reuse(THD *thd, TABLE *table)
1212 {
1213  for (; table ; table= table->next)
1214  {
1215  DBUG_ASSERT(table->pos_in_locked_tables == NULL ||
1216  table->pos_in_locked_tables->table == table);
1217  if (table->query_id == thd->query_id)
1218  {
1219  table->query_id= 0;
1220  table->file->ha_reset();
1221  }
1222  }
1223 }
1224 
1225 
1234 static void close_open_tables(THD *thd)
1235 {
1236  mysql_mutex_assert_not_owner(&LOCK_open);
1237 
1238  DBUG_PRINT("info", ("thd->open_tables: 0x%lx", (long) thd->open_tables));
1239 
1240  while (thd->open_tables)
1241  close_thread_table(thd, &thd->open_tables);
1242 }
1243 
1244 
1266 void
1268  bool remove_from_locked_tables,
1269  TABLE *skip_table)
1270 {
1271  char key[MAX_DBKEY_LENGTH];
1272  uint key_length= share->table_cache_key.length;
1273  const char *db= key;
1274  const char *table_name= db + share->db.length + 1;
1275 
1276  memcpy(key, share->table_cache_key.str, key_length);
1277 
1278  mysql_mutex_assert_not_owner(&LOCK_open);
1279  for (TABLE **prev= &thd->open_tables; *prev; )
1280  {
1281  TABLE *table= *prev;
1282 
1283  if (table->s->table_cache_key.length == key_length &&
1284  !memcmp(table->s->table_cache_key.str, key, key_length) &&
1285  table != skip_table)
1286  {
1287  thd->locked_tables_list.unlink_from_list(thd,
1288  table->pos_in_locked_tables,
1289  remove_from_locked_tables);
1290  /*
1291  Does nothing if the table is not locked.
1292  This allows one to use this function after a table
1293  has been unlocked, e.g. in partition management.
1294  */
1295  mysql_lock_remove(thd, thd->lock, table);
1296 
1297  /* Inform handler that table will be dropped after close */
1298  if (table->db_stat && /* Not true for partitioned tables. */
1299  skip_table == NULL)
1300  table->file->extra(HA_EXTRA_PREPARE_FOR_DROP);
1301  close_thread_table(thd, prev);
1302  }
1303  else
1304  {
1305  /* Step to next entry in open_tables list. */
1306  prev= &table->next;
1307  }
1308  }
1309  if (skip_table == NULL)
1310  {
1311  /* Remove the table share from the cache. */
1312  tdc_remove_table(thd, TDC_RT_REMOVE_ALL, db, table_name,
1313  FALSE);
1314  }
1315 }
1316 
1317 
1318 /*
1319  Close all tables used by the current substatement, or all tables
1320  used by this thread if we are on the upper level.
1321 
1322  SYNOPSIS
1323  close_thread_tables()
1324  thd Thread handler
1325 
1326  IMPLEMENTATION
1327  Unlocks tables and frees derived tables.
1328  Put all normal tables used by thread in free list.
1329 
1330  It will only close/mark as free for reuse tables opened by this
1331  substatement, it will also check if we are closing tables after
1332  execution of complete query (i.e. we are on upper level) and will
1333  leave prelocked mode if needed.
1334 */
1335 
1336 void close_thread_tables(THD *thd)
1337 {
1338  TABLE *table;
1339  DBUG_ENTER("close_thread_tables");
1340 
1341 #ifdef EXTRA_DEBUG
1342  DBUG_PRINT("tcache", ("open tables:"));
1343  for (table= thd->open_tables; table; table= table->next)
1344  DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str,
1345  table->s->table_name.str, (long) table));
1346 #endif
1347 
1348 #if defined(ENABLED_DEBUG_SYNC)
1349  /* debug_sync may not be initialized for some slave threads */
1350  if (thd->debug_sync_control)
1351  DEBUG_SYNC(thd, "before_close_thread_tables");
1352 #endif
1353 
1354  DBUG_ASSERT(thd->transaction.stmt.is_empty() || thd->in_sub_stmt ||
1355  (thd->state_flags & Open_tables_state::BACKUPS_AVAIL));
1356 
1357  /* Detach MERGE children after every statement. Even under LOCK TABLES. */
1358  for (table= thd->open_tables; table; table= table->next)
1359  {
1360  /* Table might be in use by some outer statement. */
1361  DBUG_PRINT("tcache", ("table: '%s' query_id: %lu",
1362  table->s->table_name.str, (ulong) table->query_id));
1363  if (thd->locked_tables_mode <= LTM_LOCK_TABLES ||
1364  table->query_id == thd->query_id)
1365  {
1366  DBUG_ASSERT(table->file);
1367  table->file->extra(HA_EXTRA_DETACH_CHILDREN);
1368  }
1369  }
1370 
1371  /*
1372  We are assuming here that thd->derived_tables contains ONLY derived
1373  tables for this substatement. i.e. instead of approach which uses
1374  query_id matching for determining which of the derived tables belong
1375  to this substatement we rely on the ability of substatements to
1376  save/restore thd->derived_tables during their execution.
1377 
1378  TODO: Probably even better approach is to simply associate list of
1379  derived tables with (sub-)statement instead of thread and destroy
1380  them at the end of its execution.
1381  */
1382  if (thd->derived_tables)
1383  {
1384  TABLE *next;
1385  /*
1386  Close all derived tables generated in queries like
1387  SELECT * FROM (SELECT * FROM t1)
1388  */
1389  for (table= thd->derived_tables ; table ; table= next)
1390  {
1391  next= table->next;
1392  free_tmp_table(thd, table);
1393  }
1394  thd->derived_tables= 0;
1395  }
1396 
1397  /*
1398  Mark all temporary tables used by this statement as free for reuse.
1399  */
1400  mark_temp_tables_as_free_for_reuse(thd);
1401 
1402  if (thd->locked_tables_mode)
1403  {
1404 
1405  /* Ensure we are calling ha_reset() for all used tables */
1406  mark_used_tables_as_free_for_reuse(thd, thd->open_tables);
1407 
1408  /*
1409  Mark this statement as one that has "unlocked" its tables.
1410  For purposes of Query_tables_list::lock_tables_state we treat
1411  any statement which passed through close_thread_tables() as
1412  such.
1413  */
1414  thd->lex->lock_tables_state= Query_tables_list::LTS_NOT_LOCKED;
1415 
1416  /*
1417  We are under simple LOCK TABLES or we're inside a sub-statement
1418  of a prelocked statement, so should not do anything else.
1419 
1420  Note that even if we are in LTM_LOCK_TABLES mode and statement
1421  requires prelocking (e.g. when we are closing tables after
1422  failing ot "open" all tables required for statement execution)
1423  we will exit this function a few lines below.
1424  */
1425  if (! thd->lex->requires_prelocking())
1426  DBUG_VOID_RETURN;
1427 
1428  /*
1429  We are in the top-level statement of a prelocked statement,
1430  so we have to leave the prelocked mode now with doing implicit
1431  UNLOCK TABLES if needed.
1432  */
1433  if (thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES)
1434  thd->locked_tables_mode= LTM_LOCK_TABLES;
1435 
1436  if (thd->locked_tables_mode == LTM_LOCK_TABLES)
1437  DBUG_VOID_RETURN;
1438 
1439  thd->leave_locked_tables_mode();
1440 
1441  /* Fallthrough */
1442  }
1443 
1444  if (thd->lock)
1445  {
1446  /*
1447  For RBR we flush the pending event just before we unlock all the
1448  tables. This means that we are at the end of a topmost
1449  statement, so we ensure that the STMT_END_F flag is set on the
1450  pending event. For statements that are *inside* stored
1451  functions, the pending event will not be flushed: that will be
1452  handled either before writing a query log event (inside
1453  binlog_query()) or when preparing a pending event.
1454  */
1455  (void)thd->binlog_flush_pending_rows_event(TRUE);
1456  mysql_unlock_tables(thd, thd->lock);
1457  thd->lock=0;
1458  }
1459 
1460  thd->lex->lock_tables_state= Query_tables_list::LTS_NOT_LOCKED;
1461 
1462  /*
1463  Closing a MERGE child before the parent would be fatal if the
1464  other thread tries to abort the MERGE lock in between.
1465  */
1466  if (thd->open_tables)
1467  close_open_tables(thd);
1468 
1469  DBUG_VOID_RETURN;
1470 }
1471 
1472 
1473 /* move one table to free list */
1474 
1475 void close_thread_table(THD *thd, TABLE **table_ptr)
1476 {
1477  TABLE *table= *table_ptr;
1478  DBUG_ENTER("close_thread_table");
1479  DBUG_ASSERT(table->key_read == 0);
1480  DBUG_ASSERT(!table->file || table->file->inited == handler::NONE);
1481  mysql_mutex_assert_not_owner(&LOCK_open);
1482  /*
1483  The metadata lock must be released after giving back
1484  the table to the table cache.
1485  */
1486  DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE,
1487  table->s->db.str,
1488  table->s->table_name.str,
1489  MDL_SHARED));
1490  table->mdl_ticket= NULL;
1491 
1492  mysql_mutex_lock(&thd->LOCK_thd_data);
1493  *table_ptr=table->next;
1494  mysql_mutex_unlock(&thd->LOCK_thd_data);
1495 
1496  if (! table->needs_reopen())
1497  {
1498  /* Avoid having MERGE tables with attached children in unused_tables. */
1499  table->file->extra(HA_EXTRA_DETACH_CHILDREN);
1500  /* Free memory and reset for next loop. */
1501  free_field_buffers_larger_than(table, MAX_TDC_BLOB_SIZE);
1502  table->file->ha_reset();
1503  }
1504 
1505  /* Do this *before* entering the LOCK_open critical section. */
1506  if (table->file != NULL)
1507  table->file->unbind_psi();
1508 
1509  Table_cache *tc= table_cache_manager.get_cache(thd);
1510 
1511  tc->lock();
1512 
1513  if (table->s->has_old_version() || table->needs_reopen() ||
1514  table_def_shutdown_in_progress)
1515  {
1516  tc->remove_table(table);
1517  mysql_mutex_lock(&LOCK_open);
1518  intern_close_table(table);
1519  mysql_mutex_unlock(&LOCK_open);
1520  }
1521  else
1522  tc->release_table(thd, table);
1523 
1524  tc->unlock();
1525  DBUG_VOID_RETURN;
1526 }
1527 
1528 
1529 /* close_temporary_tables' internal, 4 is due to uint4korr definition */
1530 static inline uint tmpkeyval(THD *thd, TABLE *table)
1531 {
1532  return uint4korr(table->s->table_cache_key.str + table->s->table_cache_key.length - 4);
1533 }
1534 
1535 
1536 /*
1537  Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
1538  creates one DROP TEMPORARY TABLE binlog event for each pseudo-thread
1539 */
1540 
1541 bool close_temporary_tables(THD *thd)
1542 {
1543  DBUG_ENTER("close_temporary_tables");
1544  TABLE *table;
1545  TABLE *next= NULL;
1546  TABLE *prev_table;
1547  /* Assume thd->variables.option_bits has OPTION_QUOTE_SHOW_CREATE */
1548  bool was_quote_show= TRUE;
1549  bool error= 0;
1550 
1551  if (!thd->temporary_tables)
1552  DBUG_RETURN(FALSE);
1553 
1554  if (!mysql_bin_log.is_open())
1555  {
1556  TABLE *tmp_next;
1557  for (table= thd->temporary_tables; table; table= tmp_next)
1558  {
1559  tmp_next= table->next;
1560  close_temporary(table, 1, 1);
1561  }
1562  thd->temporary_tables= 0;
1563  DBUG_RETURN(FALSE);
1564  }
1565 
1566  /* Better add "if exists", in case a RESET MASTER has been done */
1567  const char stub[]= "DROP /*!40005 TEMPORARY */ TABLE IF EXISTS ";
1568  uint stub_len= sizeof(stub) - 1;
1569  char buf[256];
1570  String s_query= String(buf, sizeof(buf), system_charset_info);
1571  bool found_user_tables= FALSE;
1572 
1573  memcpy(buf, stub, stub_len);
1574 
1575  /*
1576  Insertion sort of temp tables by pseudo_thread_id to build ordered list
1577  of sublists of equal pseudo_thread_id
1578  */
1579 
1580  for (prev_table= thd->temporary_tables, table= prev_table->next;
1581  table;
1582  prev_table= table, table= table->next)
1583  {
1584  TABLE *prev_sorted /* same as for prev_table */, *sorted;
1585  if (is_user_table(table))
1586  {
1587  if (!found_user_tables)
1588  found_user_tables= true;
1589  for (prev_sorted= NULL, sorted= thd->temporary_tables; sorted != table;
1590  prev_sorted= sorted, sorted= sorted->next)
1591  {
1592  if (!is_user_table(sorted) ||
1593  tmpkeyval(thd, sorted) > tmpkeyval(thd, table))
1594  {
1595  /* move into the sorted part of the list from the unsorted */
1596  prev_table->next= table->next;
1597  table->next= sorted;
1598  if (prev_sorted)
1599  {
1600  prev_sorted->next= table;
1601  }
1602  else
1603  {
1604  thd->temporary_tables= table;
1605  }
1606  table= prev_table;
1607  break;
1608  }
1609  }
1610  }
1611  }
1612 
1613  /* We always quote db,table names though it is slight overkill */
1614  if (found_user_tables &&
1615  !(was_quote_show= test(thd->variables.option_bits & OPTION_QUOTE_SHOW_CREATE)))
1616  {
1617  thd->variables.option_bits |= OPTION_QUOTE_SHOW_CREATE;
1618  }
1619 
1620  /* scan sorted tmps to generate sequence of DROP */
1621  for (table= thd->temporary_tables; table; table= next)
1622  {
1623  if (is_user_table(table))
1624  {
1625  bool save_thread_specific_used= thd->thread_specific_used;
1626  my_thread_id save_pseudo_thread_id= thd->variables.pseudo_thread_id;
1627  /* Set pseudo_thread_id to be that of the processed table */
1628  thd->variables.pseudo_thread_id= tmpkeyval(thd, table);
1629  String db;
1630  db.append(table->s->db.str);
1631  /* Loop forward through all tables that belong to a common database
1632  within the sublist of common pseudo_thread_id to create single
1633  DROP query
1634  */
1635  for (s_query.length(stub_len);
1636  table && is_user_table(table) &&
1637  tmpkeyval(thd, table) == thd->variables.pseudo_thread_id &&
1638  table->s->db.length == db.length() &&
1639  strcmp(table->s->db.str, db.ptr()) == 0;
1640  table= next)
1641  {
1642  /*
1643  We are going to add ` around the table names and possible more
1644  due to special characters
1645  */
1646  append_identifier(thd, &s_query, table->s->table_name.str,
1647  strlen(table->s->table_name.str));
1648  s_query.append(',');
1649  next= table->next;
1650  close_temporary(table, 1, 1);
1651  }
1652  thd->clear_error();
1653  const CHARSET_INFO *cs_save= thd->variables.character_set_client;
1654  thd->variables.character_set_client= system_charset_info;
1655  thd->thread_specific_used= TRUE;
1656  Query_log_event qinfo(thd, s_query.ptr(),
1657  s_query.length() - 1 /* to remove trailing ',' */,
1658  FALSE, TRUE, FALSE, 0);
1659  qinfo.db= db.ptr();
1660  qinfo.db_len= db.length();
1661  thd->variables.character_set_client= cs_save;
1662 
1663  thd->get_stmt_da()->set_overwrite_status(true);
1664  if ((error= (mysql_bin_log.write_event(&qinfo) ||
1665  mysql_bin_log.commit(thd, true) ||
1666  error)))
1667  {
1668  /*
1669  If we're here following THD::cleanup, thence the connection
1670  has been closed already. So lets print a message to the
1671  error log instead of pushing yet another error into the
1672  Diagnostics_area.
1673 
1674  Also, we keep the error flag so that we propagate the error
1675  up in the stack. This way, if we're the SQL thread we notice
1676  that close_temporary_tables failed. (Actually, the SQL
1677  thread only calls close_temporary_tables while applying old
1678  Start_log_event_v3 events.)
1679  */
1680  sql_print_error("Failed to write the DROP statement for "
1681  "temporary tables to binary log");
1682  }
1683  thd->get_stmt_da()->set_overwrite_status(false);
1684 
1685  thd->variables.pseudo_thread_id= save_pseudo_thread_id;
1686  thd->thread_specific_used= save_thread_specific_used;
1687  }
1688  else
1689  {
1690  next= table->next;
1691  close_temporary(table, 1, 1);
1692  }
1693  }
1694  if (!was_quote_show)
1695  thd->variables.option_bits&= ~OPTION_QUOTE_SHOW_CREATE; /* restore option */
1696  thd->temporary_tables=0;
1697 
1698  DBUG_RETURN(error);
1699 }
1700 
1701 /*
1702  Find table in list.
1703 
1704  SYNOPSIS
1705  find_table_in_list()
1706  table Pointer to table list
1707  offset Offset to which list in table structure to use
1708  db_name Data base name
1709  table_name Table name
1710 
1711  NOTES:
1712  This is called by find_table_in_local_list() and
1713  find_table_in_global_list().
1714 
1715  RETURN VALUES
1716  NULL Table not found
1717  # Pointer to found table.
1718 */
1719 
1720 TABLE_LIST *find_table_in_list(TABLE_LIST *table,
1722  const char *db_name,
1723  const char *table_name)
1724 {
1725  for (; table; table= table->*link )
1726  {
1727  if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
1728  strcmp(table->db, db_name) == 0 &&
1729  strcmp(table->table_name, table_name) == 0)
1730  break;
1731  }
1732  return table;
1733 }
1734 
1735 
1769 static
1770 TABLE_LIST* find_dup_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list,
1771  bool check_alias)
1772 {
1773  TABLE_LIST *res;
1774  const char *d_name, *t_name, *t_alias;
1775  DBUG_ENTER("find_dup_table");
1776  DBUG_PRINT("enter", ("table alias: %s", table->alias));
1777 
1778  /*
1779  If this function called for query which update table (INSERT/UPDATE/...)
1780  then we have in table->table pointer to TABLE object which we are
1781  updating even if it is VIEW so we need TABLE_LIST of this TABLE object
1782  to get right names (even if lower_case_table_names used).
1783 
1784  If this function called for CREATE command that we have not opened table
1785  (table->table equal to 0) and right names is in current TABLE_LIST
1786  object.
1787  */
1788  if (table->table)
1789  {
1790  /* All MyISAMMRG children are plain MyISAM tables. */
1791  DBUG_ASSERT(table->table->file->ht->db_type != DB_TYPE_MRG_MYISAM);
1792 
1793  /* temporary table is always unique */
1794  if (table->table && table->table->s->tmp_table != NO_TMP_TABLE)
1795  DBUG_RETURN(0);
1796  table= table->find_underlying_table(table->table);
1797  /*
1798  as far as we have table->table we have to find real TABLE_LIST of
1799  it in underlying tables
1800  */
1801  DBUG_ASSERT(table);
1802  }
1803  d_name= table->db;
1804  t_name= table->table_name;
1805  t_alias= table->alias;
1806 
1807  DBUG_PRINT("info", ("real table: %s.%s", d_name, t_name));
1808  for (;;)
1809  {
1810  /*
1811  Table is unique if it is present only once in the global list
1812  of tables and once in the list of table locks.
1813  */
1814  if (! (res= find_table_in_global_list(table_list, d_name, t_name)))
1815  break;
1816 
1817  /* Skip if same underlying table. */
1818  if (res->table && (res->table == table->table))
1819  goto next;
1820 
1821  /* Skip if table alias does not match. */
1822  if (check_alias)
1823  {
1824  if (lower_case_table_names ?
1825  my_strcasecmp(files_charset_info, t_alias, res->alias) :
1826  strcmp(t_alias, res->alias))
1827  goto next;
1828  }
1829 
1830  /*
1831  Skip if marked to be excluded (could be a derived table) or if
1832  entry is a prelocking placeholder.
1833  */
1834  if (res->select_lex &&
1835  !res->select_lex->exclude_from_table_unique_test &&
1836  !res->prelocking_placeholder)
1837  break;
1838 
1839  /*
1840  If we found entry of this table or table of SELECT which already
1841  processed in derived table or top select of multi-update/multi-delete
1842  (exclude_from_table_unique_test) or prelocking placeholder.
1843  */
1844 next:
1845  table_list= res->next_global;
1846  DBUG_PRINT("info",
1847  ("found same copy of table or table which we should skip"));
1848  }
1849  DBUG_RETURN(res);
1850 }
1851 
1852 
1868 TABLE_LIST*
1869 unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list,
1870  bool check_alias)
1871 {
1872  TABLE_LIST *dup;
1873  if (table->table && table->table->file->ht->db_type == DB_TYPE_MRG_MYISAM)
1874  {
1875  TABLE_LIST *child;
1876  dup= NULL;
1877  /* Check duplicates of all merge children. */
1878  for (child= table->next_global; child && child->parent_l == table;
1879  child= child->next_global)
1880  {
1881  if ((dup= find_dup_table(thd, child, child->next_global, check_alias)))
1882  break;
1883  }
1884  }
1885  else
1886  dup= find_dup_table(thd, table, table_list, check_alias);
1887  return dup;
1888 }
1889 /*
1890  Issue correct error message in case we found 2 duplicate tables which
1891  prevent some update operation
1892 
1893  SYNOPSIS
1894  update_non_unique_table_error()
1895  update table which we try to update
1896  operation name of update operation
1897  duplicate duplicate table which we found
1898 
1899  NOTE:
1900  here we hide view underlying tables if we have them
1901 */
1902 
1903 void update_non_unique_table_error(TABLE_LIST *update,
1904  const char *operation,
1905  TABLE_LIST *duplicate)
1906 {
1907  update= update->top_table();
1908  duplicate= duplicate->top_table();
1909  if (!update->view || !duplicate->view ||
1910  update->view == duplicate->view ||
1911  update->view_name.length != duplicate->view_name.length ||
1912  update->view_db.length != duplicate->view_db.length ||
1913  my_strcasecmp(table_alias_charset,
1914  update->view_name.str, duplicate->view_name.str) != 0 ||
1915  my_strcasecmp(table_alias_charset,
1916  update->view_db.str, duplicate->view_db.str) != 0)
1917  {
1918  /*
1919  it is not the same view repeated (but it can be parts of the same copy
1920  of view), so we have to hide underlying tables.
1921  */
1922  if (update->view)
1923  {
1924  /* Issue the ER_NON_INSERTABLE_TABLE error for an INSERT */
1925  if (update->view == duplicate->view)
1926  my_error(!strncmp(operation, "INSERT", 6) ?
1927  ER_NON_INSERTABLE_TABLE : ER_NON_UPDATABLE_TABLE, MYF(0),
1928  update->alias, operation);
1929  else
1930  my_error(ER_VIEW_PREVENT_UPDATE, MYF(0),
1931  (duplicate->view ? duplicate->alias : update->alias),
1932  operation, update->alias);
1933  return;
1934  }
1935  if (duplicate->view)
1936  {
1937  my_error(ER_VIEW_PREVENT_UPDATE, MYF(0), duplicate->alias, operation,
1938  update->alias);
1939  return;
1940  }
1941  }
1942  my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias);
1943 }
1944 
1945 
1953 TABLE *find_temporary_table(THD *thd, const char *db, const char *table_name)
1954 {
1955  char key[MAX_DBKEY_LENGTH];
1956  uint key_length= create_table_def_key(thd, key, db, table_name, 1);
1957  return find_temporary_table(thd, key, key_length);
1958 }
1959 
1960 
1969 {
1970  const char *key;
1971  uint key_length;
1972  char key_suffix[TMP_TABLE_KEY_EXTRA];
1973  TABLE *table;
1974 
1975  key_length= get_table_def_key(tl, &key);
1976 
1977  int4store(key_suffix, thd->server_id);
1978  int4store(key_suffix + 4, thd->variables.pseudo_thread_id);
1979 
1980  for (table= thd->temporary_tables; table; table= table->next)
1981  {
1982  if ((table->s->table_cache_key.length == key_length +
1983  TMP_TABLE_KEY_EXTRA) &&
1984  !memcmp(table->s->table_cache_key.str, key, key_length) &&
1985  !memcmp(table->s->table_cache_key.str + key_length, key_suffix,
1986  TMP_TABLE_KEY_EXTRA))
1987  return table;
1988  }
1989  return NULL;
1990 }
1991 
1992 
2000  const char *table_key,
2001  uint table_key_length)
2002 {
2003  for (TABLE *table= thd->temporary_tables; table; table= table->next)
2004  {
2005  if (table->s->table_cache_key.length == table_key_length &&
2006  !memcmp(table->s->table_cache_key.str, table_key, table_key_length))
2007  {
2008  return table;
2009  }
2010  }
2011 
2012  return NULL;
2013 }
2014 
2015 
2050 int drop_temporary_table(THD *thd, TABLE_LIST *table_list, bool *is_trans)
2051 {
2052  DBUG_ENTER("drop_temporary_table");
2053  DBUG_PRINT("tmptable", ("closing table: '%s'.'%s'",
2054  table_list->db, table_list->table_name));
2055 
2056  if (!is_temporary_table(table_list))
2057  DBUG_RETURN(1);
2058 
2059  TABLE *table= table_list->table;
2060 
2061  /* Table might be in use by some outer statement. */
2062  if (table->query_id && table->query_id != thd->query_id)
2063  {
2064  my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
2065  DBUG_RETURN(-1);
2066  }
2067 
2068  *is_trans= table->file->has_transactions();
2069 
2070  /*
2071  If LOCK TABLES list is not empty and contains this table,
2072  unlock the table and remove the table from this list.
2073  */
2074  mysql_lock_remove(thd, thd->lock, table);
2075  close_temporary_table(thd, table, 1, 1);
2076  table_list->table= NULL;
2077  DBUG_RETURN(0);
2078 }
2079 
2080 /*
2081  unlink from thd->temporary tables and close temporary table
2082 */
2083 
2084 void close_temporary_table(THD *thd, TABLE *table,
2085  bool free_share, bool delete_table)
2086 {
2087  DBUG_ENTER("close_temporary_table");
2088  DBUG_PRINT("tmptable", ("closing table: '%s'.'%s' 0x%lx alias: '%s'",
2089  table->s->db.str, table->s->table_name.str,
2090  (long) table, table->alias));
2091 
2092  if (table->prev)
2093  {
2094  table->prev->next= table->next;
2095  if (table->prev->next)
2096  table->next->prev= table->prev;
2097  }
2098  else
2099  {
2100  /* removing the item from the list */
2101  DBUG_ASSERT(table == thd->temporary_tables);
2102  /*
2103  slave must reset its temporary list pointer to zero to exclude
2104  passing non-zero value to end_slave via rli->save_temporary_tables
2105  when no temp tables opened, see an invariant below.
2106  */
2107  thd->temporary_tables= table->next;
2108  if (thd->temporary_tables)
2109  table->next->prev= 0;
2110  }
2111  if (thd->slave_thread)
2112  {
2113  /* natural invariant of temporary_tables */
2114  DBUG_ASSERT(slave_open_temp_tables || !thd->temporary_tables);
2115  modify_slave_open_temp_tables(thd, -1);
2116  }
2117  close_temporary(table, free_share, delete_table);
2118  DBUG_VOID_RETURN;
2119 }
2120 
2121 
2122 /*
2123  Close and delete a temporary table
2124 
2125  NOTE
2126  This dosn't unlink table from thd->temporary
2127  If this is needed, use close_temporary_table()
2128 */
2129 
2130 void close_temporary(TABLE *table, bool free_share, bool delete_table)
2131 {
2132  handlerton *table_type= table->s->db_type();
2133  DBUG_ENTER("close_temporary");
2134  DBUG_PRINT("tmptable", ("closing table: '%s'.'%s'",
2135  table->s->db.str, table->s->table_name.str));
2136 
2137  free_io_cache(table);
2138  closefrm(table, 0);
2139  if (delete_table)
2140  rm_temporary_table(table_type, table->s->path.str);
2141  if (free_share)
2142  {
2143  free_table_share(table->s);
2144  my_free(table);
2145  }
2146  DBUG_VOID_RETURN;
2147 }
2148 
2149 
2150 /*
2151  Used by ALTER TABLE when the table is a temporary one. It changes something
2152  only if the ALTER contained a RENAME clause (otherwise, table_name is the old
2153  name).
2154  Prepares a table cache key, which is the concatenation of db, table_name and
2155  thd->slave_proxy_id, separated by '\0'.
2156 */
2157 
2158 bool rename_temporary_table(THD* thd, TABLE *table, const char *db,
2159  const char *table_name)
2160 {
2161  char *key;
2162  uint key_length;
2163  TABLE_SHARE *share= table->s;
2164  DBUG_ENTER("rename_temporary_table");
2165 
2166  if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
2167  DBUG_RETURN(1); /* purecov: inspected */
2168 
2169  key_length= create_table_def_key(thd, key, db, table_name, 1);
2170  share->set_table_cache_key(key, key_length);
2171  DBUG_RETURN(0);
2172 }
2173 
2174 
2192 bool wait_while_table_is_used(THD *thd, TABLE *table,
2193  enum ha_extra_function function)
2194 {
2195  DBUG_ENTER("wait_while_table_is_used");
2196  DBUG_PRINT("enter", ("table: '%s' share: 0x%lx db_stat: %u version: %lu",
2197  table->s->table_name.str, (ulong) table->s,
2198  table->db_stat, table->s->version));
2199 
2200  if (thd->mdl_context.upgrade_shared_lock(
2201  table->mdl_ticket, MDL_EXCLUSIVE,
2202  thd->variables.lock_wait_timeout))
2203  DBUG_RETURN(TRUE);
2204 
2205  tdc_remove_table(thd, TDC_RT_REMOVE_NOT_OWN,
2206  table->s->db.str, table->s->table_name.str,
2207  FALSE);
2208  /* extra() call must come only after all instances above are closed */
2209  (void) table->file->extra(function);
2210  DBUG_RETURN(FALSE);
2211 }
2212 
2213 
2233 void drop_open_table(THD *thd, TABLE *table, const char *db_name,
2234  const char *table_name)
2235 {
2236  DBUG_ENTER("drop_open_table");
2237  if (table->s->tmp_table)
2238  close_temporary_table(thd, table, 1, 1);
2239  else
2240  {
2241  DBUG_ASSERT(table == thd->open_tables);
2242 
2243  handlerton *table_type= table->s->db_type();
2244 
2245  table->file->extra(HA_EXTRA_PREPARE_FOR_DROP);
2246  close_thread_table(thd, &thd->open_tables);
2247  /* Remove the table share from the table cache. */
2248  tdc_remove_table(thd, TDC_RT_REMOVE_ALL, db_name, table_name,
2249  FALSE);
2250  /* Remove the table from the storage engine and rm the .frm. */
2251  quick_rm_table(thd, table_type, db_name, table_name, 0);
2252  }
2253  DBUG_VOID_RETURN;
2254 }
2255 
2256 
2276 bool check_if_table_exists(THD *thd, TABLE_LIST *table, bool *exists)
2277 {
2278  char path[FN_REFLEN + 1];
2279  TABLE_SHARE *share;
2280  DBUG_ENTER("check_if_table_exists");
2281 
2282  *exists= TRUE;
2283 
2284  DBUG_ASSERT(thd->mdl_context.
2285  is_lock_owner(MDL_key::TABLE, table->db,
2286  table->table_name, MDL_SHARED));
2287 
2288  mysql_mutex_lock(&LOCK_open);
2289  share= get_cached_table_share(table->db, table->table_name);
2290  mysql_mutex_unlock(&LOCK_open);
2291 
2292  if (share)
2293  goto end;
2294 
2295  build_table_filename(path, sizeof(path) - 1, table->db, table->table_name,
2296  reg_ext, 0);
2297 
2298  if (!access(path, F_OK))
2299  goto end;
2300 
2301  /* .FRM file doesn't exist. Check if some engine can provide it. */
2302  if (ha_check_if_table_exists(thd, table->db, table->table_name, exists))
2303  {
2304  my_printf_error(ER_OUT_OF_RESOURCES, "Failed to open '%-.64s', error while "
2305  "unpacking from engine", MYF(0), table->table_name);
2306  DBUG_RETURN(TRUE);
2307  }
2308 end:
2309  DBUG_RETURN(FALSE);
2310 }
2311 
2312 
2319 class MDL_deadlock_handler : public Internal_error_handler
2320 {
2321 public:
2323  : m_ot_ctx(ot_ctx_arg), m_is_active(FALSE)
2324  {}
2325 
2326  virtual ~MDL_deadlock_handler() {}
2327 
2328  virtual bool handle_condition(THD *thd,
2329  uint sql_errno,
2330  const char* sqlstate,
2331  Sql_condition::enum_warning_level level,
2332  const char* msg,
2333  Sql_condition ** cond_hdl);
2334 
2335 private:
2337  Open_table_context *m_ot_ctx;
2343  bool m_is_active;
2344 };
2345 
2346 
2347 bool MDL_deadlock_handler::handle_condition(THD *,
2348  uint sql_errno,
2349  const char*,
2350  Sql_condition::enum_warning_level,
2351  const char*,
2352  Sql_condition ** cond_hdl)
2353 {
2354  *cond_hdl= NULL;
2355  if (! m_is_active && sql_errno == ER_LOCK_DEADLOCK)
2356  {
2357  /* Disable the handler to avoid infinite recursion. */
2358  m_is_active= TRUE;
2359  (void) m_ot_ctx->request_backoff_action(
2360  Open_table_context::OT_BACKOFF_AND_RETRY,
2361  NULL);
2362  m_is_active= FALSE;
2363  /*
2364  If the above back-off request failed, a new instance of
2365  ER_LOCK_DEADLOCK error was emitted. Thus the current
2366  instance of error condition can be treated as handled.
2367  */
2368  return TRUE;
2369  }
2370  return FALSE;
2371 }
2372 
2373 
2401 static bool
2402 open_table_get_mdl_lock(THD *thd, Open_table_context *ot_ctx,
2403  MDL_request *mdl_request,
2404  uint flags,
2405  MDL_ticket **mdl_ticket)
2406 {
2407  MDL_request mdl_request_shared;
2408 
2409  if (flags & (MYSQL_OPEN_FORCE_SHARED_MDL |
2410  MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL))
2411  {
2412  /*
2413  MYSQL_OPEN_FORCE_SHARED_MDL flag means that we are executing
2414  PREPARE for a prepared statement and want to override
2415  the type-of-operation aware metadata lock which was set
2416  in the parser/during view opening with a simple shared
2417  metadata lock.
2418  This is necessary to allow concurrent execution of PREPARE
2419  and LOCK TABLES WRITE statement against the same table.
2420 
2421  MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL flag means that we open
2422  the table in order to get information about it for one of I_S
2423  queries and also want to override the type-of-operation aware
2424  shared metadata lock which was set earlier (e.g. during view
2425  opening) with a high-priority shared metadata lock.
2426  This is necessary to avoid unnecessary waiting and extra
2427  ER_WARN_I_S_SKIPPED_TABLE warnings when accessing I_S tables.
2428 
2429  These two flags are mutually exclusive.
2430  */
2431  DBUG_ASSERT(!(flags & MYSQL_OPEN_FORCE_SHARED_MDL) ||
2432  !(flags & MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL));
2433 
2434  mdl_request_shared.init(&mdl_request->key,
2435  (flags & MYSQL_OPEN_FORCE_SHARED_MDL) ?
2436  MDL_SHARED : MDL_SHARED_HIGH_PRIO,
2437  MDL_TRANSACTION);
2438  mdl_request= &mdl_request_shared;
2439  }
2440 
2441  if (flags & MYSQL_OPEN_FAIL_ON_MDL_CONFLICT)
2442  {
2443  /*
2444  When table is being open in order to get data for I_S table,
2445  we might have some tables not only open but also locked (e.g. when
2446  this happens under LOCK TABLES or in a stored function).
2447  As a result by waiting on a conflicting metadata lock to go away
2448  we may create a deadlock which won't entirely belong to the
2449  MDL subsystem and thus won't be detectable by this subsystem's
2450  deadlock detector.
2451  To avoid such situation we skip the trouble-making table if
2452  there is a conflicting lock.
2453  */
2454  if (thd->mdl_context.try_acquire_lock(mdl_request))
2455  return TRUE;
2456  if (mdl_request->ticket == NULL)
2457  {
2458  my_error(ER_WARN_I_S_SKIPPED_TABLE, MYF(0),
2459  mdl_request->key.db_name(), mdl_request->key.name());
2460  return TRUE;
2461  }
2462  }
2463  else
2464  {
2465  /*
2466  We are doing a normal table open. Let us try to acquire a metadata
2467  lock on the table. If there is a conflicting lock, acquire_lock()
2468  will wait for it to go away. Sometimes this waiting may lead to a
2469  deadlock, with the following results:
2470  1) If a deadlock is entirely within MDL subsystem, it is
2471  detected by the deadlock detector of this subsystem.
2472  ER_LOCK_DEADLOCK error is produced. Then, the error handler
2473  that is installed prior to the call to acquire_lock() attempts
2474  to request a back-off and retry. Upon success, ER_LOCK_DEADLOCK
2475  error is suppressed, otherwise propagated up the calling stack.
2476  2) Otherwise, a deadlock may occur when the wait-for graph
2477  includes edges not visible to the MDL deadlock detector.
2478  One such example is a wait on an InnoDB row lock, e.g. when:
2479  conn C1 gets SR MDL lock on t1 with SELECT * FROM t1
2480  conn C2 gets a row lock on t2 with SELECT * FROM t2 FOR UPDATE
2481  conn C3 gets in and waits on C1 with DROP TABLE t0, t1
2482  conn C2 continues and blocks on C3 with SELECT * FROM t0
2483  conn C1 deadlocks by waiting on C2 by issuing SELECT * FROM
2484  t2 LOCK IN SHARE MODE.
2485  Such circular waits are currently only resolved by timeouts,
2486  e.g. @@innodb_lock_wait_timeout or @@lock_wait_timeout.
2487  */
2488  MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);
2489 
2490  thd->push_internal_handler(&mdl_deadlock_handler);
2491  bool result= thd->mdl_context.acquire_lock(mdl_request,
2492  ot_ctx->get_timeout());
2493  thd->pop_internal_handler();
2494 
2495  if (result && !ot_ctx->can_recover_from_failed_open())
2496  return TRUE;
2497  }
2498  *mdl_ticket= mdl_request->ticket;
2499  return FALSE;
2500 }
2501 
2502 
2517 static bool
2518 tdc_wait_for_old_version(THD *thd, const char *db, const char *table_name,
2519  ulong wait_timeout, uint deadlock_weight)
2520 {
2521  TABLE_SHARE *share;
2522  bool res= FALSE;
2523 
2524  mysql_mutex_lock(&LOCK_open);
2525  if ((share= get_cached_table_share(db, table_name)) &&
2526  share->has_old_version())
2527  {
2528  struct timespec abstime;
2529  set_timespec(abstime, wait_timeout);
2530  res= share->wait_for_old_version(thd, &abstime, deadlock_weight);
2531  }
2532  mysql_mutex_unlock(&LOCK_open);
2533  return res;
2534 }
2535 
2536 
2570 bool open_table(THD *thd, TABLE_LIST *table_list, Open_table_context *ot_ctx)
2571 {
2572  reg1 TABLE *table;
2573  const char *key;
2574  uint key_length;
2575  char *alias= table_list->alias;
2576  uint flags= ot_ctx->get_flags();
2577  MDL_ticket *mdl_ticket;
2578  int error;
2579  TABLE_SHARE *share;
2580  my_hash_value_type hash_value;
2581 
2582  DBUG_ENTER("open_table");
2583 
2584  /*
2585  The table must not be opened already. The table can be pre-opened for
2586  some statements if it is a temporary table.
2587 
2588  open_temporary_table() must be used to open temporary tables.
2589  */
2590  DBUG_ASSERT(!table_list->table);
2591 
2592  /* an open table operation needs a lot of the stack space */
2593  if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (uchar *)&alias))
2594  DBUG_RETURN(TRUE);
2595 
2596  if (!(flags & MYSQL_OPEN_IGNORE_KILLED) && thd->killed)
2597  DBUG_RETURN(TRUE);
2598 
2599  /*
2600  Check if we're trying to take a write lock in a read only transaction.
2601 
2602  Note that we allow write locks on log tables as otherwise logging
2603  to general/slow log would be disabled in read only transactions.
2604  */
2605  if (table_list->mdl_request.type >= MDL_SHARED_WRITE &&
2606  thd->tx_read_only &&
2607  !(flags & (MYSQL_LOCK_LOG_TABLE | MYSQL_OPEN_HAS_MDL_LOCK)))
2608  {
2609  my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0));
2610  DBUG_RETURN(true);
2611  }
2612 
2613  key_length= get_table_def_key(table_list, &key);
2614 
2615  /*
2616  If we're in pre-locked or LOCK TABLES mode, let's try to find the
2617  requested table in the list of pre-opened and locked tables. If the
2618  table is not there, return an error - we can't open not pre-opened
2619  tables in pre-locked/LOCK TABLES mode.
2620  TODO: move this block into a separate function.
2621  */
2622  if (thd->locked_tables_mode &&
2623  ! (flags & MYSQL_OPEN_GET_NEW_TABLE))
2624  { // Using table locks
2625  TABLE *best_table= 0;
2626  int best_distance= INT_MIN;
2627  for (table=thd->open_tables; table ; table=table->next)
2628  {
2629  if (table->s->table_cache_key.length == key_length &&
2630  !memcmp(table->s->table_cache_key.str, key, key_length))
2631  {
2632  if (!my_strcasecmp(system_charset_info, table->alias, alias) &&
2633  table->query_id != thd->query_id && /* skip tables already used */
2634  (thd->locked_tables_mode == LTM_LOCK_TABLES ||
2635  table->query_id == 0))
2636  {
2637  int distance= ((int) table->reginfo.lock_type -
2638  (int) table_list->lock_type);
2639 
2640  /*
2641  Find a table that either has the exact lock type requested,
2642  or has the best suitable lock. In case there is no locked
2643  table that has an equal or higher lock than requested,
2644  we us the closest matching lock to be able to produce an error
2645  message about wrong lock mode on the table. The best_table
2646  is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.
2647 
2648  distance < 0 - No suitable lock found
2649  distance > 0 - we have lock mode higher then we require
2650  distance == 0 - we have lock mode exactly which we need
2651  */
2652  if ((best_distance < 0 && distance > best_distance) ||
2653  (distance >= 0 && distance < best_distance))
2654  {
2655  best_distance= distance;
2656  best_table= table;
2657  if (best_distance == 0)
2658  {
2659  /*
2660  We have found a perfect match and can finish iterating
2661  through open tables list. Check for table use conflict
2662  between calling statement and SP/trigger is done in
2663  lock_tables().
2664  */
2665  break;
2666  }
2667  }
2668  }
2669  }
2670  }
2671  if (best_table)
2672  {
2673  table= best_table;
2674  table->query_id= thd->query_id;
2675  DBUG_PRINT("info",("Using locked table"));
2676  goto reset;
2677  }
2678  /*
2679  Is this table a view and not a base table?
2680  (it is work around to allow to open view with locked tables,
2681  real fix will be made after definition cache will be made)
2682 
2683  Since opening of view which was not explicitly locked by LOCK
2684  TABLES breaks metadata locking protocol (potentially can lead
2685  to deadlocks) it should be disallowed.
2686  */
2687  if (thd->mdl_context.is_lock_owner(MDL_key::TABLE,
2688  table_list->db,
2689  table_list->table_name,
2690  MDL_SHARED))
2691  {
2692  char path[FN_REFLEN + 1];
2693  enum legacy_db_type not_used;
2694  build_table_filename(path, sizeof(path) - 1,
2695  table_list->db, table_list->table_name, reg_ext, 0);
2696  /*
2697  Note that we can't be 100% sure that it is a view since it's
2698  possible that we either simply have not found unused TABLE
2699  instance in THD::open_tables list or were unable to open table
2700  during prelocking process (in this case in theory we still
2701  should hold shared metadata lock on it).
2702  */
2703  if (dd_frm_type(thd, path, &not_used) == FRMTYPE_VIEW)
2704  {
2705  if (!tdc_open_view(thd, table_list, alias, key, key_length,
2706  CHECK_METADATA_VERSION))
2707  {
2708  DBUG_ASSERT(table_list->view != 0);
2709  DBUG_RETURN(FALSE); // VIEW
2710  }
2711  }
2712  }
2713  /*
2714  No table in the locked tables list. In case of explicit LOCK TABLES
2715  this can happen if a user did not include the table into the list.
2716  In case of pre-locked mode locked tables list is generated automatically,
2717  so we may only end up here if the table did not exist when
2718  locked tables list was created.
2719  */
2720  if (thd->locked_tables_mode == LTM_PRELOCKED)
2721  my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->alias);
2722  else
2723  my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
2724  DBUG_RETURN(TRUE);
2725  }
2726 
2727  /* Non pre-locked/LOCK TABLES mode. This is the normal use case. */
2728 
2729  if (! (flags & MYSQL_OPEN_HAS_MDL_LOCK))
2730  {
2731  /*
2732  We are not under LOCK TABLES and going to acquire write-lock/
2733  modify the base table. We need to acquire protection against
2734  global read lock until end of this statement in order to have
2735  this statement blocked by active FLUSH TABLES WITH READ LOCK.
2736 
2737  We don't block acquire this protection under LOCK TABLES as
2738  such protection already acquired at LOCK TABLES time and
2739  not released until UNLOCK TABLES.
2740 
2741  We don't block statements which modify only temporary tables
2742  as these tables are not preserved by backup by any form of
2743  backup which uses FLUSH TABLES WITH READ LOCK.
2744 
2745  TODO: The fact that we sometimes acquire protection against
2746  GRL only when we encounter table to be write-locked
2747  slightly increases probability of deadlock.
2748  This problem will be solved once Alik pushes his
2749  temporary table refactoring patch and we can start
2750  pre-acquiring metadata locks at the beggining of
2751  open_tables() call.
2752  */
2753  if (table_list->mdl_request.type >= MDL_SHARED_WRITE &&
2754  ! (flags & (MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK |
2755  MYSQL_OPEN_FORCE_SHARED_MDL |
2756  MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL |
2757  MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK)) &&
2758  ! ot_ctx->has_protection_against_grl())
2759  {
2760  MDL_request protection_request;
2761  MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);
2762 
2763  if (thd->global_read_lock.can_acquire_protection())
2764  DBUG_RETURN(TRUE);
2765 
2766  protection_request.init(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE,
2767  MDL_STATEMENT);
2768 
2769  /*
2770  Install error handler which if possible will convert deadlock error
2771  into request to back-off and restart process of opening tables.
2772  */
2773  thd->push_internal_handler(&mdl_deadlock_handler);
2774  bool result= thd->mdl_context.acquire_lock(&protection_request,
2775  ot_ctx->get_timeout());
2776  thd->pop_internal_handler();
2777 
2778  if (result)
2779  DBUG_RETURN(TRUE);
2780 
2782  }
2783 
2784  if (open_table_get_mdl_lock(thd, ot_ctx, &table_list->mdl_request,
2785  flags, &mdl_ticket) ||
2786  mdl_ticket == NULL)
2787  {
2788  DEBUG_SYNC(thd, "before_open_table_wait_refresh");
2789  DBUG_RETURN(TRUE);
2790  }
2791  DEBUG_SYNC(thd, "after_open_table_mdl_shared");
2792  }
2793  else
2794  {
2795  /*
2796  Grab reference to the MDL lock ticket that was acquired
2797  by the caller.
2798  */
2799  mdl_ticket= table_list->mdl_request.ticket;
2800  }
2801 
2802  hash_value= my_calc_hash(&table_def_cache, (uchar*) key, key_length);
2803 
2804 
2805  if (table_list->open_strategy == TABLE_LIST::OPEN_IF_EXISTS ||
2806  table_list->open_strategy == TABLE_LIST::OPEN_FOR_CREATE)
2807  {
2808  bool exists;
2809 
2810  if (check_if_table_exists(thd, table_list, &exists))
2811  DBUG_RETURN(TRUE);
2812 
2813  if (!exists)
2814  {
2815  if (table_list->open_strategy == TABLE_LIST::OPEN_FOR_CREATE &&
2816  ! (flags & (MYSQL_OPEN_FORCE_SHARED_MDL |
2817  MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL)))
2818  {
2819  MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);
2820 
2821  thd->push_internal_handler(&mdl_deadlock_handler);
2822 
2823  DEBUG_SYNC(thd, "before_upgrading_lock_from_S_to_X_for_create_table");
2824  bool wait_result= thd->mdl_context.upgrade_shared_lock(
2825  table_list->mdl_request.ticket,
2826  MDL_EXCLUSIVE,
2827  thd->variables.lock_wait_timeout);
2828 
2829  thd->pop_internal_handler();
2830  DEBUG_SYNC(thd, "after_upgrading_lock_from_S_to_X_for_create_table");
2831 
2832  /* Deadlock or timeout occurred while upgrading the lock. */
2833  if (wait_result)
2834  DBUG_RETURN(TRUE);
2835  }
2836 
2837  DBUG_RETURN(FALSE);
2838  }
2839 
2840  /* Table exists. Let us try to open it. */
2841  }
2842  else if (table_list->open_strategy == TABLE_LIST::OPEN_STUB)
2843  DBUG_RETURN(FALSE);
2844 
2845 retry_share:
2846  {
2847  Table_cache *tc= table_cache_manager.get_cache(thd);
2848 
2849  tc->lock();
2850 
2851  /*
2852  Try to get unused TABLE object or at least pointer to
2853  TABLE_SHARE from the table cache.
2854  */
2855  table= tc->get_table(thd, hash_value, key, key_length, &share);
2856 
2857  if (table)
2858  {
2859  /* We have found an unused TABLE object. */
2860 
2861  if (!(flags & MYSQL_OPEN_IGNORE_FLUSH))
2862  {
2863  /*
2864  TABLE_SHARE::version can only be initialised while holding the
2865  LOCK_open and in this case no one has a reference to the share
2866  object, if a reference exists to the share object it is necessary
2867  to lock both LOCK_open AND all table caches in order to update
2868  TABLE_SHARE::version. The same locks are required to increment
2869  refresh_version global variable.
2870 
2871  As result it is safe to compare TABLE_SHARE::version and
2872  refresh_version values while having only lock on the table
2873  cache for this thread.
2874 
2875  Table cache should not contain any unused TABLE objects with
2876  old versions.
2877  */
2878  DBUG_ASSERT(!share->has_old_version());
2879 
2880  /*
2881  Still some of already opened might become outdated (e.g. due to
2882  concurrent table flush). So we need to compare version of opened
2883  tables with version of TABLE object we just have got.
2884  */
2885  if (thd->open_tables &&
2886  thd->open_tables->s->version != share->version)
2887  {
2888  tc->release_table(thd, table);
2889  tc->unlock();
2890  (void)ot_ctx->request_backoff_action(
2891  Open_table_context::OT_REOPEN_TABLES,
2892  NULL);
2893  DBUG_RETURN(TRUE);
2894  }
2895  }
2896  tc->unlock();
2897 
2898  /* Call rebind_psi outside of the critical section. */
2899  DBUG_ASSERT(table->file != NULL);
2900  table->file->rebind_psi();
2901 
2902  thd->status_var.table_open_cache_hits++;
2903  goto table_found;
2904  }
2905  else if (share)
2906  {
2907  /*
2908  We weren't able to get an unused TABLE object. Still we have
2909  found TABLE_SHARE for it. So let us try to create new TABLE
2910  for it. We start by incrementing share's reference count and
2911  checking its version.
2912  */
2913  mysql_mutex_lock(&LOCK_open);
2914  tc->unlock();
2915  share->ref_count++;
2916  goto share_found;
2917  }
2918  else
2919  {
2920  /*
2921  We have not found neither TABLE nor TABLE_SHARE object in
2922  table cache (this means that there are no TABLE objects for
2923  it in it).
2924  Let us try to get TABLE_SHARE from table definition cache or
2925  from disk and then to create TABLE object for it.
2926  */
2927  tc->unlock();
2928  }
2929  }
2930 
2931  mysql_mutex_lock(&LOCK_open);
2932 
2933  if (!(share= get_table_share_with_discover(thd, table_list, key,
2934  key_length, OPEN_VIEW,
2935  &error,
2936  hash_value)))
2937  {
2938  mysql_mutex_unlock(&LOCK_open);
2939  /*
2940  If thd->is_error() is not set, we either need discover
2941  (error == 7), or the error was silenced by the prelocking
2942  handler (error == 0), in which case we should skip this
2943  table.
2944  */
2945  if (error == 7 && !thd->is_error())
2946  {
2947  (void) ot_ctx->request_backoff_action(Open_table_context::OT_DISCOVER,
2948  table_list);
2949  }
2950  DBUG_RETURN(TRUE);
2951  }
2952 
2953  /*
2954  Check if this TABLE_SHARE-object corresponds to a view. Note, that there is
2955  no need to call TABLE_SHARE::has_old_version() as we do for regular tables,
2956  because view shares are always up to date.
2957  */
2958  if (share->is_view)
2959  {
2960  /*
2961  If parent_l of the table_list is non null then a merge table
2962  has this view as child table, which is not supported.
2963  */
2964  if (table_list->parent_l)
2965  {
2966  my_error(ER_WRONG_MRG_TABLE, MYF(0));
2967  goto err_unlock;
2968  }
2969 
2970  /*
2971  This table is a view. Validate its metadata version: in particular,
2972  that it was a view when the statement was prepared.
2973  */
2974  if (check_and_update_table_version(thd, table_list, share))
2975  goto err_unlock;
2976  if (table_list->i_s_requested_object & OPEN_TABLE_ONLY)
2977  {
2978  my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db,
2979  table_list->table_name);
2980  goto err_unlock;
2981  }
2982 
2983  /* Open view */
2984  if (mysql_make_view(thd, share, table_list, false))
2985  goto err_unlock;
2986 
2987  /* TODO: Don't free this */
2988  release_table_share(share);
2989 
2990  DBUG_ASSERT(table_list->view);
2991 
2992  mysql_mutex_unlock(&LOCK_open);
2993  DBUG_RETURN(FALSE);
2994  }
2995 
2996  /*
2997  Note that situation when we are trying to open a table for what
2998  was a view during previous execution of PS will be handled in by
2999  the caller. Here we should simply open our table even if
3000  TABLE_LIST::view is true.
3001  */
3002 
3003  if (table_list->i_s_requested_object & OPEN_VIEW_ONLY)
3004  {
3005  my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db,
3006  table_list->table_name);
3007  goto err_unlock;
3008  }
3009 
3010 share_found:
3011  if (!(flags & MYSQL_OPEN_IGNORE_FLUSH))
3012  {
3013  if (share->has_old_version())
3014  {
3015  /*
3016  We already have an MDL lock. But we have encountered an old
3017  version of table in the table definition cache which is possible
3018  when someone changes the table version directly in the cache
3019  without acquiring a metadata lock (e.g. this can happen during
3020  "rolling" FLUSH TABLE(S)).
3021  Release our reference to share, wait until old version of
3022  share goes away and then try to get new version of table share.
3023  */
3024  release_table_share(share);
3025  mysql_mutex_unlock(&LOCK_open);
3026 
3027  MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);
3028  bool wait_result;
3029 
3030  thd->push_internal_handler(&mdl_deadlock_handler);
3031  wait_result= tdc_wait_for_old_version(thd, table_list->db,
3032  table_list->table_name,
3033  ot_ctx->get_timeout(),
3034  mdl_ticket->get_deadlock_weight());
3035  thd->pop_internal_handler();
3036 
3037  if (wait_result)
3038  DBUG_RETURN(TRUE);
3039 
3040  goto retry_share;
3041  }
3042 
3043  if (thd->open_tables && thd->open_tables->s->version != share->version)
3044  {
3045  /*
3046  If the version changes while we're opening the tables,
3047  we have to back off, close all the tables opened-so-far,
3048  and try to reopen them. Note: refresh_version is currently
3049  changed only during FLUSH TABLES.
3050  */
3051  release_table_share(share);
3052  mysql_mutex_unlock(&LOCK_open);
3053  (void)ot_ctx->request_backoff_action(Open_table_context::OT_REOPEN_TABLES,
3054  NULL);
3055  DBUG_RETURN(TRUE);
3056  }
3057  }
3058 
3059  mysql_mutex_unlock(&LOCK_open);
3060 
3061  /* make a new table */
3062  if (!(table= (TABLE*) my_malloc(sizeof(*table), MYF(MY_WME))))
3063  goto err_lock;
3064 
3065  error= open_table_from_share(thd, share, alias,
3066  (uint) (HA_OPEN_KEYFILE |
3067  HA_OPEN_RNDFILE |
3068  HA_GET_INDEX |
3069  HA_TRY_READ_ONLY),
3070  (READ_KEYINFO | COMPUTE_TYPES |
3071  EXTRA_RECORD),
3072  thd->open_options, table, FALSE);
3073 
3074  if (error)
3075  {
3076  my_free(table);
3077 
3078  if (error == 7)
3079  (void) ot_ctx->request_backoff_action(Open_table_context::OT_DISCOVER,
3080  table_list);
3081  else if (share->crashed)
3082  (void) ot_ctx->request_backoff_action(Open_table_context::OT_REPAIR,
3083  table_list);
3084  goto err_lock;
3085  }
3086  if (open_table_entry_fini(thd, share, table))
3087  {
3088  closefrm(table, 0);
3089  my_free(table);
3090  goto err_lock;
3091  }
3092  {
3093  /* Add new TABLE object to table cache for this connection. */
3094  Table_cache *tc= table_cache_manager.get_cache(thd);
3095 
3096  tc->lock();
3097 
3098  if (tc->add_used_table(thd, table))
3099  {
3100  tc->unlock();
3101  goto err_lock;
3102  }
3103  tc->unlock();
3104  }
3105  thd->status_var.table_open_cache_misses++;
3106 
3107 table_found:
3108  table->mdl_ticket= mdl_ticket;
3109 
3110  table->next= thd->open_tables; /* Link into simple list */
3111  thd->set_open_tables(table);
3112 
3113  table->reginfo.lock_type=TL_READ; /* Assume read */
3114 
3115  reset:
3116  table->set_created();
3117  /*
3118  Check that there is no reference to a condition from an earlier query
3119  (cf. Bug#58553).
3120  */
3121  DBUG_ASSERT(table->file->pushed_cond == NULL);
3122  table_list->updatable= 1; // It is not derived table nor non-updatable VIEW
3123  table_list->table= table;
3124 
3125 #ifdef WITH_PARTITION_STORAGE_ENGINE
3126  if (table->part_info)
3127  {
3128  /* Set all [named] partitions as used. */
3129  if (table->part_info->set_partition_bitmaps(table_list))
3130  DBUG_RETURN(true);
3131  }
3132  else if (table_list->partition_names)
3133  {
3134  /* Don't allow PARTITION () clause on a nonpartitioned table */
3135  my_error(ER_PARTITION_CLAUSE_ON_NONPARTITIONED, MYF(0));
3136  DBUG_RETURN(true);
3137  }
3138 #endif
3139 
3140  table->init(thd, table_list);
3141 
3142  DBUG_RETURN(FALSE);
3143 
3144 err_lock:
3145  mysql_mutex_lock(&LOCK_open);
3146 err_unlock:
3147  release_table_share(share);
3148  mysql_mutex_unlock(&LOCK_open);
3149 
3150  DBUG_RETURN(TRUE);
3151 }
3152 
3153 
3164 TABLE *find_locked_table(TABLE *list, const char *db, const char *table_name)
3165 {
3166  char key[MAX_DBKEY_LENGTH];
3167  uint key_length= create_table_def_key((THD*)NULL, key, db, table_name,
3168  false);
3169 
3170  for (TABLE *table= list; table ; table=table->next)
3171  {
3172  if (table->s->table_cache_key.length == key_length &&
3173  !memcmp(table->s->table_cache_key.str, key, key_length))
3174  return table;
3175  }
3176  return(0);
3177 }
3178 
3179 
3201 TABLE *find_table_for_mdl_upgrade(THD *thd, const char *db,
3202  const char *table_name, bool no_error)
3203 {
3204  TABLE *tab= find_locked_table(thd->open_tables, db, table_name);
3205 
3206  if (!tab)
3207  {
3208  if (!no_error)
3209  my_error(ER_TABLE_NOT_LOCKED, MYF(0), table_name);
3210  return NULL;
3211  }
3212 
3213  /*
3214  It is not safe to upgrade the metadata lock without a global IX lock.
3215  This can happen with FLUSH TABLES <list> WITH READ LOCK as we in these
3216  cases don't take a global IX lock in order to be compatible with
3217  global read lock.
3218  */
3219  if (!thd->mdl_context.is_lock_owner(MDL_key::GLOBAL, "", "",
3220  MDL_INTENTION_EXCLUSIVE))
3221  {
3222  if (!no_error)
3223  my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), table_name);
3224  return NULL;
3225  }
3226 
3227  while (tab->mdl_ticket != NULL &&
3228  !tab->mdl_ticket->is_upgradable_or_exclusive() &&
3229  (tab= find_locked_table(tab->next, db, table_name)))
3230  continue;
3231 
3232  if (!tab && !no_error)
3233  my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), table_name);
3234 
3235  return tab;
3236 }
3237 
3238 
3239 /***********************************************************************
3240  class Locked_tables_list implementation. Declared in sql_class.h
3241 ************************************************************************/
3242 
3255 bool
3256 Locked_tables_list::init_locked_tables(THD *thd)
3257 {
3258  DBUG_ASSERT(thd->locked_tables_mode == LTM_NONE);
3259  DBUG_ASSERT(m_locked_tables == NULL);
3260  DBUG_ASSERT(m_reopen_array == NULL);
3261  DBUG_ASSERT(m_locked_tables_count == 0);
3262 
3263  for (TABLE *table= thd->open_tables; table;
3264  table= table->next, m_locked_tables_count++)
3265  {
3266  TABLE_LIST *src_table_list= table->pos_in_table_list;
3267  char *db, *table_name, *alias;
3268  size_t db_len= src_table_list->db_length;
3269  size_t table_name_len= src_table_list->table_name_length;
3270  size_t alias_len= strlen(src_table_list->alias);
3271  TABLE_LIST *dst_table_list;
3272 
3273  if (! multi_alloc_root(&m_locked_tables_root,
3274  &dst_table_list, sizeof(*dst_table_list),
3275  &db, db_len + 1,
3276  &table_name, table_name_len + 1,
3277  &alias, alias_len + 1,
3278  NullS))
3279  {
3280  unlock_locked_tables(0);
3281  return TRUE;
3282  }
3283 
3284  memcpy(db, src_table_list->db, db_len + 1);
3285  memcpy(table_name, src_table_list->table_name, table_name_len + 1);
3286  memcpy(alias, src_table_list->alias, alias_len + 1);
3294  dst_table_list->init_one_table(db, db_len, table_name, table_name_len,
3295  alias,
3296  src_table_list->table->reginfo.lock_type);
3297  dst_table_list->table= table;
3298  dst_table_list->mdl_request.ticket= src_table_list->mdl_request.ticket;
3299 
3300  /* Link last into the list of tables */
3301  *(dst_table_list->prev_global= m_locked_tables_last)= dst_table_list;
3302  m_locked_tables_last= &dst_table_list->next_global;
3303  table->pos_in_locked_tables= dst_table_list;
3304  }
3305  if (m_locked_tables_count)
3306  {
3312  m_reopen_array= (TABLE**)alloc_root(&m_locked_tables_root,
3313  sizeof(TABLE*) *
3314  (m_locked_tables_count+1));
3315  if (m_reopen_array == NULL)
3316  {
3317  unlock_locked_tables(0);
3318  return TRUE;
3319  }
3320  }
3321  thd->enter_locked_tables_mode(LTM_LOCK_TABLES);
3322 
3323  return FALSE;
3324 }
3325 
3326 
3335 void
3336 Locked_tables_list::unlock_locked_tables(THD *thd)
3337 
3338 {
3339  if (thd)
3340  {
3341  DBUG_ASSERT(!thd->in_sub_stmt &&
3342  !(thd->state_flags & Open_tables_state::BACKUPS_AVAIL));
3343  /*
3344  Sic: we must be careful to not close open tables if
3345  we're not in LOCK TABLES mode: unlock_locked_tables() is
3346  sometimes called implicitly, expecting no effect on
3347  open tables, e.g. from begin_trans().
3348  */
3349  if (thd->locked_tables_mode != LTM_LOCK_TABLES)
3350  return;
3351 
3352  for (TABLE_LIST *table_list= m_locked_tables;
3353  table_list; table_list= table_list->next_global)
3354  {
3355  /*
3356  Clear the position in the list, the TABLE object will be
3357  returned to the table cache.
3358  */
3359  table_list->table->pos_in_locked_tables= NULL;
3360  }
3361  thd->leave_locked_tables_mode();
3362 
3363  DBUG_ASSERT(thd->transaction.stmt.is_empty());
3364  close_thread_tables(thd);
3365  /*
3366  We rely on the caller to implicitly commit the
3367  transaction and release transactional locks.
3368  */
3369  }
3370  /*
3371  After closing tables we can free memory used for storing lock
3372  request for metadata locks and TABLE_LIST elements.
3373  */
3374  free_root(&m_locked_tables_root, MYF(0));
3375  m_locked_tables= NULL;
3376  m_locked_tables_last= &m_locked_tables;
3377  m_reopen_array= NULL;
3378  m_locked_tables_count= 0;
3379 }
3380 
3381 
3403 void Locked_tables_list::unlink_from_list(THD *thd,
3404  TABLE_LIST *table_list,
3405  bool remove_from_locked_tables)
3406 {
3407  /*
3408  If mode is not LTM_LOCK_TABLES, we needn't do anything. Moreover,
3409  outside this mode pos_in_locked_tables value is not trustworthy.
3410  */
3411  if (thd->locked_tables_mode != LTM_LOCK_TABLES)
3412  return;
3413 
3414  /*
3415  table_list must be set and point to pos_in_locked_tables of some
3416  table.
3417  */
3418  DBUG_ASSERT(table_list->table->pos_in_locked_tables == table_list);
3419 
3420  /* Clear the pointer, the table will be returned to the table cache. */
3421  table_list->table->pos_in_locked_tables= NULL;
3422 
3423  /* Mark the table as closed in the locked tables list. */
3424  table_list->table= NULL;
3425 
3426  /*
3427  If the table is being dropped or renamed, remove it from
3428  the locked tables list (implicitly drop the LOCK TABLES lock
3429  on it).
3430  */
3431  if (remove_from_locked_tables)
3432  {
3433  *table_list->prev_global= table_list->next_global;
3434  if (table_list->next_global == NULL)
3435  m_locked_tables_last= table_list->prev_global;
3436  else
3437  table_list->next_global->prev_global= table_list->prev_global;
3438  }
3439 }
3440 
3450 void Locked_tables_list::
3451 unlink_all_closed_tables(THD *thd, MYSQL_LOCK *lock, size_t reopen_count)
3452 {
3453  /* If we managed to take a lock, unlock tables and free the lock. */
3454  if (lock)
3455  mysql_unlock_tables(thd, lock);
3456  /*
3457  If a failure happened in reopen_tables(), we may have succeeded
3458  reopening some tables, but not all.
3459  This works when the connection was killed in mysql_lock_tables().
3460  */
3461  if (reopen_count)
3462  {
3463  while (reopen_count--)
3464  {
3465  /*
3466  When closing the table, we must remove it
3467  from thd->open_tables list.
3468  We rely on the fact that open_table() that was used
3469  in reopen_tables() always links the opened table
3470  to the beginning of the open_tables list.
3471  */
3472  DBUG_ASSERT(thd->open_tables == m_reopen_array[reopen_count]);
3473 
3474  thd->open_tables->pos_in_locked_tables->table= NULL;
3475 
3476  close_thread_table(thd, &thd->open_tables);
3477  }
3478  }
3479  /* Exclude all closed tables from the LOCK TABLES list. */
3480  for (TABLE_LIST *table_list= m_locked_tables; table_list; table_list=
3481  table_list->next_global)
3482  {
3483  if (table_list->table == NULL)
3484  {
3485  /* Unlink from list. */
3486  *table_list->prev_global= table_list->next_global;
3487  if (table_list->next_global == NULL)
3488  m_locked_tables_last= table_list->prev_global;
3489  else
3490  table_list->next_global->prev_global= table_list->prev_global;
3491  }
3492  }
3493 }
3494 
3495 
3508 bool
3509 Locked_tables_list::reopen_tables(THD *thd)
3510 {
3511  Open_table_context ot_ctx(thd, MYSQL_OPEN_REOPEN);
3512  size_t reopen_count= 0;
3513  MYSQL_LOCK *lock;
3514  MYSQL_LOCK *merged_lock;
3515 
3516  for (TABLE_LIST *table_list= m_locked_tables;
3517  table_list; table_list= table_list->next_global)
3518  {
3519  if (table_list->table) /* The table was not closed */
3520  continue;
3521 
3522  /* Links into thd->open_tables upon success */
3523  if (open_table(thd, table_list, &ot_ctx))
3524  {
3525  unlink_all_closed_tables(thd, 0, reopen_count);
3526  return TRUE;
3527  }
3528  table_list->table->pos_in_locked_tables= table_list;
3529  /* See also the comment on lock type in init_locked_tables(). */
3530  table_list->table->reginfo.lock_type= table_list->lock_type;
3531 
3532  DBUG_ASSERT(reopen_count < m_locked_tables_count);
3533  m_reopen_array[reopen_count++]= table_list->table;
3534  }
3535  if (reopen_count)
3536  {
3537  thd->in_lock_tables= 1;
3538  /*
3539  We re-lock all tables with mysql_lock_tables() at once rather
3540  than locking one table at a time because of the case
3541  reported in Bug#45035: when the same table is present
3542  in the list many times, thr_lock.c fails to grant READ lock
3543  on a table that is already locked by WRITE lock, even if
3544  WRITE lock is taken by the same thread. If READ and WRITE
3545  lock are passed to thr_lock.c in the same list, everything
3546  works fine. Patching legacy code of thr_lock.c is risking to
3547  break something else.
3548  */
3549  lock= mysql_lock_tables(thd, m_reopen_array, reopen_count,
3550  MYSQL_OPEN_REOPEN);
3551  thd->in_lock_tables= 0;
3552  if (lock == NULL || (merged_lock=
3553  mysql_lock_merge(thd->lock, lock)) == NULL)
3554  {
3555  unlink_all_closed_tables(thd, lock, reopen_count);
3556  if (! thd->killed)
3557  my_error(ER_LOCK_DEADLOCK, MYF(0));
3558  return TRUE;
3559  }
3560  thd->lock= merged_lock;
3561  }
3562  return FALSE;
3563 }
3564 
3565 
3566 /*
3567  Function to assign a new table map id to a table share.
3568 
3569  PARAMETERS
3570 
3571  share - Pointer to table share structure
3572 
3573  DESCRIPTION
3574 
3575  We are intentionally not checking that share->mutex is locked
3576  since this function should only be called when opening a table
3577  share and before it is entered into the table_def_cache (meaning
3578  that it cannot be fetched by another thread, even accidentally).
3579 
3580  PRE-CONDITION(S)
3581 
3582  share is non-NULL
3583  The LOCK_open mutex is locked.
3584 
3585  POST-CONDITION(S)
3586 
3587  share->table_map_id is given a value that with a high certainty is
3588  not used by any other table (the only case where a table id can be
3589  reused is on wrap-around, which means more than 2^48 table
3590  share opens have been executed while one table was open all the
3591  time).
3592 
3593 */
3594 static Table_id last_table_id;
3595 
3596 void assign_new_table_id(TABLE_SHARE *share)
3597 {
3598 
3599  DBUG_ENTER("assign_new_table_id");
3600 
3601  /* Preconditions */
3602  DBUG_ASSERT(share != NULL);
3603  mysql_mutex_assert_owner(&LOCK_open);
3604 
3605  DBUG_EXECUTE_IF("dbug_table_map_id_500", last_table_id= 500;);
3606  DBUG_EXECUTE_IF("dbug_table_map_id_4B_UINT_MAX+501",
3607  last_table_id= 501ULL + UINT_MAX;);
3608  DBUG_EXECUTE_IF("dbug_table_map_id_6B_UINT_MAX",
3609  last_table_id= (~0ULL >> 16););
3610 
3611  share->table_map_id= last_table_id++;
3612  DBUG_PRINT("info", ("table_id=%llu", share->table_map_id.id()));
3613 
3614  DBUG_VOID_RETURN;
3615 }
3616 
3617 #ifndef DBUG_OFF
3618 /* Cause a spurious statement reprepare for debug purposes. */
3619 static bool inject_reprepare(THD *thd)
3620 {
3621  Reprepare_observer *reprepare_observer= thd->get_reprepare_observer();
3622 
3623  if (reprepare_observer && !thd->stmt_arena->is_reprepared)
3624  {
3625  (void)reprepare_observer->report_error(thd);
3626  return true;
3627  }
3628 
3629  return false;
3630 }
3631 #endif
3632 
3665 static bool
3666 check_and_update_table_version(THD *thd,
3667  TABLE_LIST *tables, TABLE_SHARE *table_share)
3668 {
3669  if (! tables->is_table_ref_id_equal(table_share))
3670  {
3671  Reprepare_observer *reprepare_observer= thd->get_reprepare_observer();
3672 
3673  if (reprepare_observer &&
3674  reprepare_observer->report_error(thd))
3675  {
3676  /*
3677  Version of the table share is different from the
3678  previous execution of the prepared statement, and it is
3679  unacceptable for this SQLCOM. Error has been reported.
3680  */
3681  DBUG_ASSERT(thd->is_error());
3682  return TRUE;
3683  }
3684  /* Always maintain the latest version and type */
3685  tables->set_table_ref_id(table_share);
3686  }
3687 
3688  DBUG_EXECUTE_IF("reprepare_each_statement", return inject_reprepare(thd););
3689  return FALSE;
3690 }
3691 
3692 
3719 static bool
3720 check_and_update_routine_version(THD *thd, Sroutine_hash_entry *rt,
3721  sp_head *sp)
3722 {
3723  ulong spc_version= sp_cache_version();
3724  /* sp is NULL if there is no such routine. */
3725  ulong version= sp ? sp->sp_cache_version() : spc_version;
3726  /*
3727  If the version in the parse tree is stale,
3728  or the version in the cache is stale and sp is not used,
3729  we need to reprepare.
3730  Sic: version != spc_version <--> sp is not NULL.
3731  */
3732  if (rt->m_sp_cache_version != version ||
3733  (version != spc_version && !sp->is_invoked()))
3734  {
3735  Reprepare_observer *reprepare_observer= thd->get_reprepare_observer();
3736 
3737  if (reprepare_observer &&
3738  reprepare_observer->report_error(thd))
3739  {
3740  /*
3741  Version of the sp cache is different from the
3742  previous execution of the prepared statement, and it is
3743  unacceptable for this SQLCOM. Error has been reported.
3744  */
3745  DBUG_ASSERT(thd->is_error());
3746  return TRUE;
3747  }
3748  /* Always maintain the latest cache version. */
3749  rt->m_sp_cache_version= version;
3750  }
3751  return FALSE;
3752 }
3753 
3754 
3771 bool tdc_open_view(THD *thd, TABLE_LIST *table_list, const char *alias,
3772  const char *cache_key, uint cache_key_length, uint flags)
3773 {
3774  int error;
3775  my_hash_value_type hash_value;
3776  TABLE_SHARE *share;
3777 
3778  hash_value= my_calc_hash(&table_def_cache, (uchar*) cache_key,
3779  cache_key_length);
3780  mysql_mutex_lock(&LOCK_open);
3781 
3782  if (!(share= get_table_share(thd, table_list, cache_key,
3783  cache_key_length,
3784  OPEN_VIEW, &error,
3785  hash_value)))
3786  goto err;
3787 
3788  if ((flags & CHECK_METADATA_VERSION))
3789  {
3790  /*
3791  Check TABLE_SHARE-version of view only if we have been instructed to do
3792  so. We do not need to check the version if we're executing CREATE VIEW or
3793  ALTER VIEW statements.
3794 
3795  In the future, this functionality should be moved out from
3796  tdc_open_view(), and tdc_open_view() should became a part of a clean
3797  table-definition-cache interface.
3798  */
3799  if (check_and_update_table_version(thd, table_list, share))
3800  {
3801  release_table_share(share);
3802  goto err;
3803  }
3804  }
3805 
3806  if (share->is_view &&
3807  !mysql_make_view(thd, share, table_list, (flags & OPEN_VIEW_NO_PARSE)))
3808  {
3809  release_table_share(share);
3810  mysql_mutex_unlock(&LOCK_open);
3811  return FALSE;
3812  }
3813 
3814  my_error(ER_WRONG_OBJECT, MYF(0), share->db.str, share->table_name.str, "VIEW");
3815  release_table_share(share);
3816 err:
3817  mysql_mutex_unlock(&LOCK_open);
3818  return TRUE;
3819 }
3820 
3821 
3827 static bool open_table_entry_fini(THD *thd, TABLE_SHARE *share, TABLE *entry)
3828 {
3829  if (Table_triggers_list::check_n_load(thd, share->db.str,
3830  share->table_name.str, entry, 0))
3831  return TRUE;
3832 
3833  /*
3834  If we are here, there was no fatal error (but error may be still
3835  unitialized).
3836  */
3837  if (unlikely(entry->file->implicit_emptied))
3838  {
3839  entry->file->implicit_emptied= 0;
3840  if (mysql_bin_log.is_open())
3841  {
3842  bool error= false;
3843  String temp_buf;
3844  error= temp_buf.append("DELETE FROM ");
3845  append_identifier(thd, &temp_buf, share->db.str, strlen(share->db.str));
3846  error= temp_buf.append(".");
3847  append_identifier(thd, &temp_buf, share->table_name.str,
3848  strlen(share->table_name.str));
3849  int errcode= query_error_code(thd, TRUE);
3850  if (thd->binlog_query(THD::STMT_QUERY_TYPE,
3851  temp_buf.c_ptr_safe(), temp_buf.length(),
3852  FALSE, TRUE, FALSE, errcode))
3853  return TRUE;
3854  if (error)
3855  {
3856  /*
3857  As replication is maybe going to be corrupted, we need to warn the
3858  DBA on top of warning the client (which will automatically be done
3859  because of MYF(MY_WME) in my_malloc() above).
3860  */
3861  sql_print_error("When opening HEAP table, could not allocate memory "
3862  "to write 'DELETE FROM `%s`.`%s`' to the binary log",
3863  share->db.str, share->table_name.str);
3864  delete entry->triggers;
3865  return TRUE;
3866  }
3867  }
3868  }
3869  return FALSE;
3870 }
3871 
3872 
3877 static bool auto_repair_table(THD *thd, TABLE_LIST *table_list)
3878 {
3879  const char *cache_key;
3880  uint cache_key_length;
3881  TABLE_SHARE *share;
3882  TABLE *entry;
3883  int not_used;
3884  bool result= TRUE;
3885  my_hash_value_type hash_value;
3886 
3887  cache_key_length= get_table_def_key(table_list, &cache_key);
3888 
3889  thd->clear_error();
3890 
3891  hash_value= my_calc_hash(&table_def_cache, (uchar*) cache_key,
3892  cache_key_length);
3893  mysql_mutex_lock(&LOCK_open);
3894 
3895  if (!(share= get_table_share(thd, table_list, cache_key,
3896  cache_key_length,
3897  OPEN_VIEW, &not_used,
3898  hash_value)))
3899  goto end_unlock;
3900 
3901  if (share->is_view)
3902  {
3903  release_table_share(share);
3904  goto end_unlock;
3905  }
3906 
3907  if (!(entry= (TABLE*)my_malloc(sizeof(TABLE), MYF(MY_WME))))
3908  {
3909  release_table_share(share);
3910  goto end_unlock;
3911  }
3912  mysql_mutex_unlock(&LOCK_open);
3913 
3914  if (open_table_from_share(thd, share, table_list->alias,
3915  (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
3916  HA_GET_INDEX |
3917  HA_TRY_READ_ONLY),
3918  READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD,
3919  ha_open_options | HA_OPEN_FOR_REPAIR,
3920  entry, FALSE) || ! entry->file ||
3921  (entry->file->is_crashed() && entry->file->ha_check_and_repair(thd)))
3922  {
3923  /* Give right error message */
3924  thd->clear_error();
3925  my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str);
3926  sql_print_error("Couldn't repair table: %s.%s", share->db.str,
3927  share->table_name.str);
3928  if (entry->file)
3929  closefrm(entry, 0);
3930  }
3931  else
3932  {
3933  thd->clear_error(); // Clear error message
3934  closefrm(entry, 0);
3935  result= FALSE;
3936  }
3937  my_free(entry);
3938 
3939  table_cache_manager.lock_all_and_tdc();
3940  release_table_share(share);
3941  /* Remove the repaired share from the table cache. */
3942  tdc_remove_table(thd, TDC_RT_REMOVE_ALL,
3943  table_list->db, table_list->table_name,
3944  TRUE);
3945  table_cache_manager.unlock_all_and_tdc();
3946  return result;
3947 end_unlock:
3948  mysql_mutex_unlock(&LOCK_open);
3949  return result;
3950 }
3951 
3952 
3956  :m_thd(thd),
3957  m_failed_table(NULL),
3958  m_start_of_statement_svp(thd->mdl_context.mdl_savepoint()),
3959  m_timeout(flags & MYSQL_LOCK_IGNORE_TIMEOUT ?
3960  LONG_TIMEOUT : thd->variables.lock_wait_timeout),
3961  m_flags(flags),
3962  m_action(OT_NO_ACTION),
3963  m_has_locks(thd->mdl_context.has_locks()),
3964  m_has_protection_against_grl(FALSE)
3965 {}
3966 
3967 
3976 bool
3978 request_backoff_action(enum_open_table_action action_arg,
3979  TABLE_LIST *table)
3980 {
3981  /*
3982  A back off action may be one of three kinds:
3983 
3984  * We met a broken table that needs repair, or a table that
3985  is not present on this MySQL server and needs re-discovery.
3986  To perform the action, we need an exclusive metadata lock on
3987  the table. Acquiring an X lock while holding other shared
3988  locks is very deadlock-prone. If this is a multi- statement
3989  transaction that holds metadata locks for completed
3990  statements, we don't do it, and report an error instead.
3991  The action type in this case is OT_DISCOVER or OT_REPAIR.
3992  * Our attempt to acquire an MDL lock lead to a deadlock,
3993  detected by the MDL deadlock detector. The current
3994  session was chosen a victim. If this is a multi-statement
3995  transaction that holds metadata locks taken by completed
3996  statements, restarting locking for the current statement
3997  may lead to a livelock. Releasing locks of completed
3998  statements can not be done as will lead to violation
3999  of ACID. Thus, again, if m_has_locks is set,
4000  we report an error. Otherwise, when there are no metadata
4001  locks other than which belong to this statement, we can
4002  try to recover from error by releasing all locks and
4003  restarting the pre-locking.
4004  Similarly, a deadlock error can occur when the
4005  pre-locking process met a TABLE_SHARE that is being
4006  flushed, and unsuccessfully waited for the flush to
4007  complete. A deadlock in this case can happen, e.g.,
4008  when our session is holding a metadata lock that
4009  is being waited on by a session which is using
4010  the table which is being flushed. The only way
4011  to recover from this error is, again, to close all
4012  open tables, release all locks, and retry pre-locking.
4013  Action type name is OT_REOPEN_TABLES. Re-trying
4014  while holding some locks may lead to a livelock,
4015  and thus we don't do it.
4016  * Finally, this session has open TABLEs from different
4017  "generations" of the table cache. This can happen, e.g.,
4018  when, after this session has successfully opened one
4019  table used for a statement, FLUSH TABLES interfered and
4020  expelled another table used in it. FLUSH TABLES then
4021  blocks and waits on the table already opened by this
4022  statement.
4023  We detect this situation by ensuring that table cache
4024  version of all tables used in a statement is the same.
4025  If it isn't, all tables needs to be reopened.
4026  Note, that we can always perform a reopen in this case,
4027  even if we already have metadata locks, since we don't
4028  keep tables open between statements and a livelock
4029  is not possible.
4030  */
4031  if (action_arg != OT_REOPEN_TABLES && m_has_locks)
4032  {
4033  my_error(ER_LOCK_DEADLOCK, MYF(0));
4034  mark_transaction_to_rollback(m_thd, true);
4035  return TRUE;
4036  }
4037  /*
4038  If auto-repair or discovery are requested, a pointer to table
4039  list element must be provided.
4040  */
4041  if (table)
4042  {
4043  DBUG_ASSERT(action_arg == OT_DISCOVER || action_arg == OT_REPAIR);
4044  m_failed_table= (TABLE_LIST*) m_thd->alloc(sizeof(TABLE_LIST));
4045  if (m_failed_table == NULL)
4046  return TRUE;
4047  m_failed_table->init_one_table(table->db, table->db_length,
4048  table->table_name,
4049  table->table_name_length,
4050  table->alias, TL_WRITE);
4051  m_failed_table->mdl_request.set_type(MDL_EXCLUSIVE);
4052  }
4053  m_action= action_arg;
4054  return FALSE;
4055 }
4056 
4057 
4068 bool
4071 {
4072  bool result= FALSE;
4073  /* Execute the action. */
4074  switch (m_action)
4075  {
4076  case OT_BACKOFF_AND_RETRY:
4077  break;
4078  case OT_REOPEN_TABLES:
4079  break;
4080  case OT_DISCOVER:
4081  {
4082  if ((result= lock_table_names(m_thd, m_failed_table, NULL,
4083  get_timeout(), 0)))
4084  break;
4085 
4086  tdc_remove_table(m_thd, TDC_RT_REMOVE_ALL, m_failed_table->db,
4087  m_failed_table->table_name, FALSE);
4088  ha_create_table_from_engine(m_thd, m_failed_table->db,
4089  m_failed_table->table_name);
4090 
4091  m_thd->get_stmt_da()->clear_warning_info(m_thd->query_id);
4092  m_thd->clear_error(); // Clear error message
4093  m_thd->mdl_context.release_transactional_locks();
4094  break;
4095  }
4096  case OT_REPAIR:
4097  {
4098  if ((result= lock_table_names(m_thd, m_failed_table, NULL,
4099  get_timeout(), 0)))
4100  break;
4101 
4102  tdc_remove_table(m_thd, TDC_RT_REMOVE_ALL, m_failed_table->db,
4103  m_failed_table->table_name, FALSE);
4104 
4105  result= auto_repair_table(m_thd, m_failed_table);
4106  m_thd->mdl_context.release_transactional_locks();
4107  break;
4108  }
4109  default:
4110  DBUG_ASSERT(0);
4111  }
4112  /*
4113  Reset the pointers to conflicting MDL request and the
4114  TABLE_LIST element, set when we need auto-discovery or repair,
4115  for safety.
4116  */
4117  m_failed_table= NULL;
4118  /*
4119  Reset flag indicating that we have already acquired protection
4120  against GRL. It is no longer valid as the corresponding lock was
4121  released by close_tables_for_reopen().
4122  */
4123  m_has_protection_against_grl= FALSE;
4124  /* Prepare for possible another back-off. */
4125  m_action= OT_NO_ACTION;
4126  return result;
4127 }
4128 
4129 
4130 /*
4131  Return a appropriate read lock type given a table object.
4132 
4133  @param thd Thread context
4134  @param prelocking_ctx Prelocking context.
4135  @param table_list Table list element for table to be locked.
4136  @param routine_modifies_data
4137  Some routine that is invoked by statement
4138  modifies data.
4139 
4140  @remark Due to a statement-based replication limitation, statements such as
4141  INSERT INTO .. SELECT FROM .. and CREATE TABLE .. SELECT FROM need
4142  to grab a TL_READ_NO_INSERT lock on the source table in order to
4143  prevent the replication of a concurrent statement that modifies the
4144  source table. If such a statement gets applied on the slave before
4145  the INSERT .. SELECT statement finishes, data on the master could
4146  differ from data on the slave and end-up with a discrepancy between
4147  the binary log and table state.
4148  This also applies to SELECT/SET/DO statements which use stored
4149  functions. Calls to such functions are going to be logged as a
4150  whole and thus should be serialized against concurrent changes
4151  to tables used by those functions. This is avoided when functions
4152  do not modify data but only read it, since in this case nothing is
4153  written to the binary log. Argument routine_modifies_data
4154  denotes the same. So effectively, if the statement is not a
4155  update query and routine_modifies_data is false, then
4156  prelocking_placeholder does not take importance.
4157 
4158  Furthermore, this does not apply to I_S and log tables as it's
4159  always unsafe to replicate such tables under statement-based
4160  replication as the table on the slave might contain other data
4161  (ie: general_log is enabled on the slave). The statement will
4162  be marked as unsafe for SBR in decide_logging_format().
4163  @remark Note that even in prelocked mode it is important to correctly
4164  determine lock type value. In this mode lock type is passed to
4165  handler::start_stmt() method and can be used by storage engine,
4166  for example, to determine what kind of row locks it should acquire
4167  when reading data from the table.
4168 */
4169 
4170 thr_lock_type read_lock_type_for_table(THD *thd,
4171  Query_tables_list *prelocking_ctx,
4172  TABLE_LIST *table_list,
4173  bool routine_modifies_data)
4174 {
4175  /*
4176  In cases when this function is called for a sub-statement executed in
4177  prelocked mode we can't rely on OPTION_BIN_LOG flag in THD::options
4178  bitmap to determine that binary logging is turned on as this bit can
4179  be cleared before executing sub-statement. So instead we have to look
4180  at THD::variables::sql_log_bin member.
4181  */
4182  bool log_on= mysql_bin_log.is_open() && thd->variables.sql_log_bin;
4183  ulong binlog_format= thd->variables.binlog_format;
4184  if ((log_on == FALSE) || (binlog_format == BINLOG_FORMAT_ROW) ||
4185  (table_list->table->s->table_category == TABLE_CATEGORY_LOG) ||
4186  (table_list->table->s->table_category == TABLE_CATEGORY_RPL_INFO) ||
4187  (table_list->table->s->table_category == TABLE_CATEGORY_PERFORMANCE) ||
4188  !(is_update_query(prelocking_ctx->sql_command) ||
4189  (routine_modifies_data && table_list->prelocking_placeholder) ||
4190  (thd->locked_tables_mode > LTM_LOCK_TABLES)))
4191  return TL_READ;
4192  else
4193  return TL_READ_NO_INSERT;
4194 }
4195 
4196 
4197 /*
4198  Handle element of prelocking set other than table. E.g. cache routine
4199  and, if prelocking strategy prescribes so, extend the prelocking set
4200  with tables and routines used by it.
4201 
4202  @param[in] thd Thread context.
4203  @param[in] prelocking_ctx Prelocking context.
4204  @param[in] rt Element of prelocking set to be processed.
4205  @param[in] prelocking_strategy Strategy which specifies how the
4206  prelocking set should be extended when
4207  one of its elements is processed.
4208  @param[in] has_prelocking_list Indicates that prelocking set/list for
4209  this statement has already been built.
4210  @param[in] ot_ctx Context of open_table used to recover from
4211  locking failures.
4212  @param[out] need_prelocking Set to TRUE if it was detected that this
4213  statement will require prelocked mode for
4214  its execution, not touched otherwise.
4215  @param[out] routine_modifies_data Set to TRUE if it was detected that this
4216  routine does modify table data.
4217 
4218  @retval FALSE Success.
4219  @retval TRUE Failure (Conflicting metadata lock, OOM, other errors).
4220 */
4221 
4222 static bool
4223 open_and_process_routine(THD *thd, Query_tables_list *prelocking_ctx,
4224  Sroutine_hash_entry *rt,
4225  Prelocking_strategy *prelocking_strategy,
4226  bool has_prelocking_list,
4227  Open_table_context *ot_ctx,
4228  bool *need_prelocking, bool *routine_modifies_data)
4229 {
4230  MDL_key::enum_mdl_namespace mdl_type= rt->mdl_request.key.mdl_namespace();
4231  *routine_modifies_data= false;
4232  DBUG_ENTER("open_and_process_routine");
4233 
4234  switch (mdl_type)
4235  {
4236  case MDL_key::FUNCTION:
4237  case MDL_key::PROCEDURE:
4238  {
4239  sp_head *sp;
4240  /*
4241  Try to get MDL lock on the routine.
4242  Note that we do not take locks on top-level CALLs as this can
4243  lead to a deadlock. Not locking top-level CALLs does not break
4244  the binlog as only the statements in the called procedure show
4245  up there, not the CALL itself.
4246  */
4247  if (rt != (Sroutine_hash_entry*)prelocking_ctx->sroutines_list.first ||
4248  mdl_type != MDL_key::PROCEDURE)
4249  {
4250  /*
4251  Since we acquire only shared lock on routines we don't
4252  need to care about global intention exclusive locks.
4253  */
4254  DBUG_ASSERT(rt->mdl_request.type == MDL_SHARED);
4255 
4256  /*
4257  Waiting for a conflicting metadata lock to go away may
4258  lead to a deadlock, detected by MDL subsystem.
4259  If possible, we try to resolve such deadlocks by releasing all
4260  metadata locks and restarting the pre-locking process.
4261  To prevent the error from polluting the diagnostics area
4262  in case of successful resolution, install a special error
4263  handler for ER_LOCK_DEADLOCK error.
4264  */
4265  MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);
4266 
4267  thd->push_internal_handler(&mdl_deadlock_handler);
4268  bool result= thd->mdl_context.acquire_lock(&rt->mdl_request,
4269  ot_ctx->get_timeout());
4270  thd->pop_internal_handler();
4271 
4272  if (result)
4273  DBUG_RETURN(TRUE);
4274 
4275  DEBUG_SYNC(thd, "after_shared_lock_pname");
4276 
4277  /* Ensures the routine is up-to-date and cached, if exists. */
4278  if (sp_cache_routine(thd, rt, has_prelocking_list, &sp))
4279  DBUG_RETURN(TRUE);
4280 
4281  /* Remember the version of the routine in the parse tree. */
4282  if (check_and_update_routine_version(thd, rt, sp))
4283  DBUG_RETURN(TRUE);
4284 
4285  /* 'sp' is NULL when there is no such routine. */
4286  if (sp)
4287  {
4288  *routine_modifies_data= sp->modifies_data();
4289 
4290  if (!has_prelocking_list)
4291  prelocking_strategy->handle_routine(thd, prelocking_ctx, rt, sp,
4292  need_prelocking);
4293  }
4294  }
4295  else
4296  {
4297  /*
4298  If it's a top level call, just make sure we have a recent
4299  version of the routine, if it exists.
4300  Validating routine version is unnecessary, since CALL
4301  does not affect the prepared statement prelocked list.
4302  */
4303  if (sp_cache_routine(thd, rt, FALSE, &sp))
4304  DBUG_RETURN(TRUE);
4305  }
4306  }
4307  break;
4308  case MDL_key::TRIGGER:
4339  break;
4340  default:
4341  /* Impossible type value. */
4342  DBUG_ASSERT(0);
4343  }
4344  DBUG_RETURN(FALSE);
4345 }
4346 
4347 
4372 static bool
4373 open_and_process_table(THD *thd, LEX *lex, TABLE_LIST *tables,
4374  uint *counter, uint flags,
4375  Prelocking_strategy *prelocking_strategy,
4376  bool has_prelocking_list,
4377  Open_table_context *ot_ctx)
4378 {
4379  bool error= FALSE;
4380  bool safe_to_ignore_table= FALSE;
4381  DBUG_ENTER("open_and_process_table");
4382  DEBUG_SYNC(thd, "open_and_process_table");
4383 
4384  /*
4385  Ignore placeholders for derived tables. After derived tables
4386  processing, link to created temporary table will be put here.
4387  If this is derived table for view then we still want to process
4388  routines used by this view.
4389  */
4390  if (tables->derived)
4391  {
4392  if (!tables->view)
4393  goto end;
4394  /*
4395  We restore view's name and database wiped out by derived tables
4396  processing and fall back to standard open process in order to
4397  obtain proper metadata locks and do other necessary steps like
4398  stored routine processing.
4399  */
4400  tables->db= tables->view_db.str;
4401  tables->db_length= tables->view_db.length;
4402  tables->table_name= tables->view_name.str;
4403  tables->table_name_length= tables->view_name.length;
4404  }
4405  /*
4406  If this TABLE_LIST object is a placeholder for an information_schema
4407  table, create a temporary table to represent the information_schema
4408  table in the query. Do not fill it yet - will be filled during
4409  execution.
4410  */
4411  if (tables->schema_table)
4412  {
4413  /*
4414  If this information_schema table is merged into a mergeable
4415  view, ignore it for now -- it will be filled when its respective
4416  TABLE_LIST is processed. This code works only during re-execution.
4417  */
4418  if (tables->view)
4419  {
4420  MDL_ticket *mdl_ticket;
4421  /*
4422  We still need to take a MDL lock on the merged view to protect
4423  it from concurrent changes.
4424  */
4425  if (!open_table_get_mdl_lock(thd, ot_ctx, &tables->mdl_request,
4426  flags, &mdl_ticket) &&
4427  mdl_ticket != NULL)
4428  goto process_view_routines;
4429  /* Fall-through to return error. */
4430  }
4431  else if (!mysql_schema_table(thd, lex, tables) &&
4432  !check_and_update_table_version(thd, tables, tables->table->s))
4433  {
4434  goto end;
4435  }
4436  error= TRUE;
4437  goto end;
4438  }
4439  DBUG_PRINT("tcache", ("opening table: '%s'.'%s' item: %p",
4440  tables->db, tables->table_name, tables)); //psergey: invalid read of size 1 here
4441  (*counter)++;
4442 
4443  /* Not a placeholder: must be a base/temporary table or a view. Let us open it. */
4444 
4445  if (tables->table)
4446  {
4447  /*
4448  If this TABLE_LIST object has an associated open TABLE object
4449  (TABLE_LIST::table is not NULL), that TABLE object must be a pre-opened
4450  temporary table.
4451  */
4452  DBUG_ASSERT(is_temporary_table(tables));
4453  }
4454  else if (tables->open_type == OT_TEMPORARY_ONLY)
4455  {
4456  /*
4457  OT_TEMPORARY_ONLY means that we are in CREATE TEMPORARY TABLE statement.
4458  Also such table list element can't correspond to prelocking placeholder
4459  or to underlying table of merge table.
4460  So existing temporary table should have been preopened by this moment
4461  and we can simply continue without trying to open temporary or base
4462  table.
4463  */
4464  DBUG_ASSERT(tables->open_strategy);
4465  DBUG_ASSERT(!tables->prelocking_placeholder);
4466  DBUG_ASSERT(!tables->parent_l);
4467  }
4468  else if (tables->prelocking_placeholder)
4469  {
4470  /*
4471  For the tables added by the pre-locking code, attempt to open
4472  the table but fail silently if the table does not exist.
4473  The real failure will occur when/if a statement attempts to use
4474  that table.
4475  */
4476  No_such_table_error_handler no_such_table_handler;
4477  thd->push_internal_handler(&no_such_table_handler);
4478 
4479  /*
4480  We're opening a table from the prelocking list.
4481 
4482  Since this table list element might have been added after pre-opening
4483  of temporary tables we have to try to open temporary table for it.
4484 
4485  We can't simply skip this table list element and postpone opening of
4486  temporary tabletill the execution of substatement for several reasons:
4487  - Temporary table can be a MERGE table with base underlying tables,
4488  so its underlying tables has to be properly open and locked at
4489  prelocking stage.
4490  - Temporary table can be a MERGE table and we might be in PREPARE
4491  phase for a prepared statement. In this case it is important to call
4492  HA_ATTACH_CHILDREN for all merge children.
4493  This is necessary because merge children remember "TABLE_SHARE ref type"
4494  and "TABLE_SHARE def version" in the HA_ATTACH_CHILDREN operation.
4495  If HA_ATTACH_CHILDREN is not called, these attributes are not set.
4496  Then, during the first EXECUTE, those attributes need to be updated.
4497  That would cause statement re-preparing (because changing those
4498  attributes during EXECUTE is caught by THD::m_reprepare_observers).
4499  The problem is that since those attributes are not set in merge
4500  children, another round of PREPARE will not help.
4501  */
4502  error= open_temporary_table(thd, tables);
4503 
4504  if (!error && !tables->table)
4505  error= open_table(thd, tables, ot_ctx);
4506 
4507  thd->pop_internal_handler();
4508  safe_to_ignore_table= no_such_table_handler.safely_trapped_errors();
4509  }
4510  else if (tables->parent_l && (thd->open_options & HA_OPEN_FOR_REPAIR))
4511  {
4512  /*
4513  Also fail silently for underlying tables of a MERGE table if this
4514  table is opened for CHECK/REPAIR TABLE statement. This is needed
4515  to provide complete list of problematic underlying tables in
4516  CHECK/REPAIR TABLE output.
4517  */
4518  Repair_mrg_table_error_handler repair_mrg_table_handler;
4519  thd->push_internal_handler(&repair_mrg_table_handler);
4520 
4521  error= open_temporary_table(thd, tables);
4522  if (!error && !tables->table)
4523  error= open_table(thd, tables, ot_ctx);
4524 
4525  thd->pop_internal_handler();
4526  safe_to_ignore_table= repair_mrg_table_handler.safely_trapped_errors();
4527  }
4528  else
4529  {
4530  if (tables->parent_l)
4531  {
4532  /*
4533  Even if we are opening table not from the prelocking list we
4534  still might need to look for a temporary table if this table
4535  list element corresponds to underlying table of a merge table.
4536  */
4537  error= open_temporary_table(thd, tables);
4538  }
4539 
4540  if (!error && !tables->table)
4541  error= open_table(thd, tables, ot_ctx);
4542  }
4543 
4544  if (error)
4545  {
4546  if (! ot_ctx->can_recover_from_failed_open() && safe_to_ignore_table)
4547  {
4548  DBUG_PRINT("info", ("open_table: ignoring table '%s'.'%s'",
4549  tables->db, tables->alias));
4550  error= FALSE;
4551  }
4552  goto end;
4553  }
4554 
4555  /*
4556  We can't rely on simple check for TABLE_LIST::view to determine
4557  that this is a view since during re-execution we might reopen
4558  ordinary table in place of view and thus have TABLE_LIST::view
4559  set from repvious execution and TABLE_LIST::table set from
4560  current.
4561  */
4562  if (!tables->table && tables->view)
4563  {
4564  /* VIEW placeholder */
4565  (*counter)--;
4566 
4567  /*
4568  tables->next_global list consists of two parts:
4569  1) Query tables and underlying tables of views.
4570  2) Tables used by all stored routines that this statement invokes on
4571  execution.
4572  We need to know where the bound between these two parts is. If we've
4573  just opened a view, which was the last table in part #1, and it
4574  has added its base tables after itself, adjust the boundary pointer
4575  accordingly.
4576  */
4577  if (lex->query_tables_own_last == &(tables->next_global) &&
4578  tables->view->query_tables)
4579  lex->query_tables_own_last= tables->view->query_tables_last;
4580  /*
4581  Let us free memory used by 'sroutines' hash here since we never
4582  call destructor for this LEX.
4583  */
4584  my_hash_free(&tables->view->sroutines);
4585  goto process_view_routines;
4586  }
4587 
4588  /*
4589  Special types of open can succeed but still don't set
4590  TABLE_LIST::table to anything.
4591  */
4592  if (tables->open_strategy && !tables->table)
4593  goto end;
4594 
4595  /*
4596  If we are not already in prelocked mode and extended table list is not
4597  yet built we might have to build the prelocking set for this statement.
4598 
4599  Since currently no prelocking strategy prescribes doing anything for
4600  tables which are only read, we do below checks only if table is going
4601  to be changed.
4602  */
4603  if (thd->locked_tables_mode <= LTM_LOCK_TABLES &&
4604  ! has_prelocking_list &&
4605  tables->lock_type >= TL_WRITE_ALLOW_WRITE)
4606  {
4607  bool need_prelocking= FALSE;
4608  TABLE_LIST **save_query_tables_last= lex->query_tables_last;
4609  /*
4610  Extend statement's table list and the prelocking set with
4611  tables and routines according to the current prelocking
4612  strategy.
4613 
4614  For example, for DML statements we need to add tables and routines
4615  used by triggers which are going to be invoked for this element of
4616  table list and also add tables required for handling of foreign keys.
4617  */
4618  error= prelocking_strategy->handle_table(thd, lex, tables,
4619  &need_prelocking);
4620 
4621  if (need_prelocking && ! lex->requires_prelocking())
4622  lex->mark_as_requiring_prelocking(save_query_tables_last);
4623 
4624  if (error)
4625  goto end;
4626  }
4627 
4628  /* Copy grant information from TABLE_LIST instance to TABLE one. */
4629  tables->table->grant= tables->grant;
4630 
4631  /* Check and update metadata version of a base table. */
4632  error= check_and_update_table_version(thd, tables, tables->table->s);
4633 
4634  if (error)
4635  goto end;
4636  /*
4637  After opening a MERGE table add the children to the query list of
4638  tables, so that they are opened too.
4639  Note that placeholders don't have the handler open.
4640  */
4641  /* MERGE tables need to access parent and child TABLE_LISTs. */
4642  DBUG_ASSERT(tables->table->pos_in_table_list == tables);
4643  /* Non-MERGE tables ignore this call. */
4644  if (tables->table->file->extra(HA_EXTRA_ADD_CHILDREN_LIST))
4645  {
4646  error= TRUE;
4647  goto end;
4648  }
4649 
4650 process_view_routines:
4651  /*
4652  Again we may need cache all routines used by this view and add
4653  tables used by them to table list.
4654  */
4655  if (tables->view &&
4656  thd->locked_tables_mode <= LTM_LOCK_TABLES &&
4657  ! has_prelocking_list)
4658  {
4659  bool need_prelocking= FALSE;
4660  TABLE_LIST **save_query_tables_last= lex->query_tables_last;
4661 
4662  error= prelocking_strategy->handle_view(thd, lex, tables,
4663  &need_prelocking);
4664 
4665  if (need_prelocking && ! lex->requires_prelocking())
4666  lex->mark_as_requiring_prelocking(save_query_tables_last);
4667 
4668  if (error)
4669  goto end;
4670  }
4671 
4672 end:
4673  DBUG_RETURN(error);
4674 }
4675 
4676 extern "C" uchar *schema_set_get_key(const uchar *record, size_t *length,
4677  my_bool not_used __attribute__((unused)))
4678 {
4679  TABLE_LIST *table=(TABLE_LIST*) record;
4680  *length= table->db_length;
4681  return (uchar*) table->db;
4682 }
4683 
4704 bool
4706  TABLE_LIST *tables_start, TABLE_LIST *tables_end,
4707  ulong lock_wait_timeout, uint flags)
4708 {
4709  MDL_request_list mdl_requests;
4710  TABLE_LIST *table;
4711  MDL_request global_request;
4713 
4714  DBUG_ASSERT(!thd->locked_tables_mode);
4715 
4716  for (table= tables_start; table && table != tables_end;
4717  table= table->next_global)
4718  {
4719  if ((table->mdl_request.type < MDL_SHARED_UPGRADABLE &&
4720  table->open_strategy != TABLE_LIST::OPEN_FOR_CREATE) ||
4721  table->open_type == OT_TEMPORARY_ONLY ||
4722  (table->open_type == OT_TEMPORARY_OR_BASE && is_temporary_table(table)))
4723  {
4724  continue;
4725  }
4726 
4727  /* Write lock on normal tables is not allowed in a read only transaction. */
4728  if (thd->tx_read_only)
4729  {
4730  my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0));
4731  return true;
4732  }
4733 
4734  if (! (flags & MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK) && schema_set.insert(table))
4735  return TRUE;
4736 
4737  mdl_requests.push_front(&table->mdl_request);
4738  }
4739 
4740  if (! (flags & MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK) &&
4741  ! mdl_requests.is_empty())
4742  {
4743  /*
4744  Scoped locks: Take intention exclusive locks on all involved
4745  schemas.
4746  */
4748  while ((table= it++))
4749  {
4750  MDL_request *schema_request= new (thd->mem_root) MDL_request;
4751  if (schema_request == NULL)
4752  return TRUE;
4753  schema_request->init(MDL_key::SCHEMA, table->db, "",
4754  MDL_INTENTION_EXCLUSIVE,
4755  MDL_TRANSACTION);
4756  mdl_requests.push_front(schema_request);
4757  }
4758 
4759  /*
4760  Protect this statement against concurrent global read lock
4761  by acquiring global intention exclusive lock with statement
4762  duration.
4763  */
4764  if (thd->global_read_lock.can_acquire_protection())
4765  return TRUE;
4766  global_request.init(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE,
4767  MDL_STATEMENT);
4768  mdl_requests.push_front(&global_request);
4769  }
4770 
4771  if (thd->mdl_context.acquire_locks(&mdl_requests, lock_wait_timeout))
4772  return TRUE;
4773 
4774  return FALSE;
4775 }
4776 
4777 
4794 static bool
4795 open_tables_check_upgradable_mdl(THD *thd, TABLE_LIST *tables_start,
4796  TABLE_LIST *tables_end, uint flags)
4797 {
4798  TABLE_LIST *table;
4799 
4800  DBUG_ASSERT(thd->locked_tables_mode);
4801 
4802  for (table= tables_start; table && table != tables_end;
4803  table= table->next_global)
4804  {
4805  if (table->mdl_request.type < MDL_SHARED_UPGRADABLE ||
4806  table->open_type == OT_TEMPORARY_ONLY ||
4807  (table->open_type == OT_TEMPORARY_OR_BASE && is_temporary_table(table)))
4808  {
4809  continue;
4810  }
4811 
4812  /*
4813  We don't need to do anything about the found TABLE instance as it
4814  will be handled later in open_tables(), we only need to check that
4815  an upgradable lock is already acquired. When we enter LOCK TABLES
4816  mode, SNRW locks are acquired before all other locks. So if under
4817  LOCK TABLES we find that there is TABLE instance with upgradeable
4818  lock, all other instances of TABLE for the same table will have the
4819  same ticket.
4820 
4821  Note that this works OK even for CREATE TABLE statements which
4822  request X type of metadata lock. This is because under LOCK TABLES
4823  such statements don't create the table but only check if it exists
4824  or, in most complex case, only insert into it.
4825  Thus SNRW lock should be enough.
4826 
4827  Note that find_table_for_mdl_upgrade() will report an error if
4828  no suitable ticket is found.
4829  */
4830  if (!find_table_for_mdl_upgrade(thd, table->db, table->table_name, false))
4831  return TRUE;
4832  }
4833 
4834  return FALSE;
4835 }
4836 
4837 
4867 bool open_tables(THD *thd, TABLE_LIST **start, uint *counter, uint flags,
4868  Prelocking_strategy *prelocking_strategy)
4869 {
4870  /*
4871  We use pointers to "next_global" member in the last processed TABLE_LIST
4872  element and to the "next" member in the last processed Sroutine_hash_entry
4873  element as iterators over, correspondingly, the table list and stored routines
4874  list which stay valid and allow to continue iteration when new elements are
4875  added to the tail of the lists.
4876  */
4877  TABLE_LIST **table_to_open;
4878  Sroutine_hash_entry **sroutine_to_open;
4879  TABLE_LIST *tables;
4880  Open_table_context ot_ctx(thd, flags);
4881  bool error= FALSE;
4882  bool some_routine_modifies_data= FALSE;
4883  bool has_prelocking_list;
4884  DBUG_ENTER("open_tables");
4885 
4886  /* Accessing data in XA_IDLE or XA_PREPARED is not allowed. */
4887  enum xa_states xa_state= thd->transaction.xid_state.xa_state;
4888  if (*start && (xa_state == XA_IDLE || xa_state == XA_PREPARED))
4889  {
4890  my_error(ER_XAER_RMFAIL, MYF(0), xa_state_names[xa_state]);
4891  DBUG_RETURN(true);
4892  }
4893 
4894  thd->current_tablenr= 0;
4895 restart:
4896  /*
4897  Close HANDLER tables which are marked for flush or against which there
4898  are pending exclusive metadata locks. This is needed both in order to
4899  avoid deadlocks and to have a point during statement execution at
4900  which such HANDLERs are closed even if they don't create problems for
4901  the current session (i.e. to avoid having a DDL blocked by HANDLERs
4902  opened for a long time).
4903  */
4904  if (thd->handler_tables_hash.records)
4905  mysql_ha_flush(thd);
4906 
4907  has_prelocking_list= thd->lex->requires_prelocking();
4908  table_to_open= start;
4909  sroutine_to_open= (Sroutine_hash_entry**) &thd->lex->sroutines_list.first;
4910  *counter= 0;
4911  THD_STAGE_INFO(thd, stage_opening_tables);
4912 
4913  /*
4914  If we are executing LOCK TABLES statement or a DDL statement
4915  (in non-LOCK TABLES mode) we might have to acquire upgradable
4916  semi-exclusive metadata locks (SNW or SNRW) on some of the
4917  tables to be opened.
4918  When executing CREATE TABLE .. If NOT EXISTS .. SELECT, the
4919  table may not yet exist, in which case we acquire an exclusive
4920  lock.
4921  We acquire all such locks at once here as doing this in one
4922  by one fashion may lead to deadlocks or starvation. Later when
4923  we will be opening corresponding table pre-acquired metadata
4924  lock will be reused (thanks to the fact that in recursive case
4925  metadata locks are acquired without waiting).
4926  */
4927  if (! (flags & (MYSQL_OPEN_HAS_MDL_LOCK |
4928  MYSQL_OPEN_FORCE_SHARED_MDL |
4929  MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL)))
4930  {
4931  if (thd->locked_tables_mode)
4932  {
4933  /*
4934  Under LOCK TABLES, we can't acquire new locks, so we instead
4935  need to check if appropriate locks were pre-acquired.
4936  */
4937  if (open_tables_check_upgradable_mdl(thd, *start,
4938  thd->lex->first_not_own_table(),
4939  flags))
4940  {
4941  error= TRUE;
4942  goto err;
4943  }
4944  }
4945  else
4946  {
4947  TABLE_LIST *table;
4948  if (lock_table_names(thd, *start, thd->lex->first_not_own_table(),
4949  ot_ctx.get_timeout(), flags))
4950  {
4951  error= TRUE;
4952  goto err;
4953  }
4954  for (table= *start; table && table != thd->lex->first_not_own_table();
4955  table= table->next_global)
4956  {
4957  if (table->mdl_request.type >= MDL_SHARED_UPGRADABLE ||
4958  table->open_strategy == TABLE_LIST::OPEN_FOR_CREATE)
4959  table->mdl_request.ticket= NULL;
4960  }
4961  }
4962  }
4963 
4964  /*
4965  Perform steps of prelocking algorithm until there are unprocessed
4966  elements in prelocking list/set.
4967  */
4968  while (*table_to_open ||
4969  (thd->locked_tables_mode <= LTM_LOCK_TABLES &&
4970  *sroutine_to_open))
4971  {
4972  /*
4973  For every table in the list of tables to open, try to find or open
4974  a table.
4975  */
4976  for (tables= *table_to_open; tables;
4977  table_to_open= &tables->next_global, tables= tables->next_global)
4978  {
4979  error= open_and_process_table(thd, thd->lex, tables, counter,
4980  flags, prelocking_strategy,
4981  has_prelocking_list, &ot_ctx);
4982 
4983  if (error)
4984  {
4985  if (ot_ctx.can_recover_from_failed_open())
4986  {
4987  /*
4988  We have met exclusive metadata lock or old version of table.
4989  Now we have to close all tables and release metadata locks.
4990  We also have to throw away set of prelocked tables (and thus
4991  close tables from this set that were open by now) since it
4992  is possible that one of tables which determined its content
4993  was changed.
4994 
4995  Instead of implementing complex/non-robust logic mentioned
4996  above we simply close and then reopen all tables.
4997 
4998  We have to save pointer to table list element for table which we
4999  have failed to open since closing tables can trigger removal of
5000  elements from the table list (if MERGE tables are involved),
5001  */
5002  close_tables_for_reopen(thd, start, ot_ctx.start_of_statement_svp());
5003 
5004  /*
5005  Here we rely on the fact that 'tables' still points to the valid
5006  TABLE_LIST element. Altough currently this assumption is valid
5007  it may change in future.
5008  */
5009  if (ot_ctx.recover_from_failed_open())
5010  goto err;
5011 
5012  /* Re-open temporary tables after close_tables_for_reopen(). */
5013  if (open_temporary_tables(thd, *start))
5014  goto err;
5015 
5016  error= FALSE;
5017  goto restart;
5018  }
5019  goto err;
5020  }
5021 
5022  DEBUG_SYNC(thd, "open_tables_after_open_and_process_table");
5023  }
5024 
5025  /*
5026  If we are not already in prelocked mode and extended table list is
5027  not yet built for our statement we need to cache routines it uses
5028  and build the prelocking list for it.
5029  If we are not in prelocked mode but have built the extended table
5030  list, we still need to call open_and_process_routine() to take
5031  MDL locks on the routines.
5032  */
5033  if (thd->locked_tables_mode <= LTM_LOCK_TABLES)
5034  {
5035  bool routine_modifies_data;
5036  /*
5037  Process elements of the prelocking set which are present there
5038  since parsing stage or were added to it by invocations of
5039  Prelocking_strategy methods in the above loop over tables.
5040 
5041  For example, if element is a routine, cache it and then,
5042  if prelocking strategy prescribes so, add tables it uses to the
5043  table list and routines it might invoke to the prelocking set.
5044  */
5045  for (Sroutine_hash_entry *rt= *sroutine_to_open; rt;
5046  sroutine_to_open= &rt->next, rt= rt->next)
5047  {
5048  bool need_prelocking= false;
5049  TABLE_LIST **save_query_tables_last= thd->lex->query_tables_last;
5050 
5051  error= open_and_process_routine(thd, thd->lex, rt, prelocking_strategy,
5052  has_prelocking_list, &ot_ctx,
5053  &need_prelocking,
5054  &routine_modifies_data);
5055 
5056 
5057  if (need_prelocking && ! thd->lex->requires_prelocking())
5058  thd->lex->mark_as_requiring_prelocking(save_query_tables_last);
5059 
5060  if (need_prelocking && ! *start)
5061  *start= thd->lex->query_tables;
5062 
5063  if (error)
5064  {
5065  if (ot_ctx.can_recover_from_failed_open())
5066  {
5067  close_tables_for_reopen(thd, start,
5068  ot_ctx.start_of_statement_svp());
5069  if (ot_ctx.recover_from_failed_open())
5070  goto err;
5071 
5072  /* Re-open temporary tables after close_tables_for_reopen(). */
5073  if (open_temporary_tables(thd, *start))
5074  goto err;
5075 
5076  error= FALSE;
5077  goto restart;
5078  }
5079  /*
5080  Serious error during reading stored routines from mysql.proc table.
5081  Something is wrong with the table or its contents, and an error has
5082  been emitted; we must abort.
5083  */
5084  goto err;
5085  }
5086 
5087  // Remember if any of SF modifies data.
5088  some_routine_modifies_data|= routine_modifies_data;
5089  }
5090  }
5091  }
5092 
5093  /*
5094  After successful open of all tables, including MERGE parents and
5095  children, attach the children to their parents. At end of statement,
5096  the children are detached. Attaching and detaching are always done,
5097  even under LOCK TABLES.
5098 
5099  We also convert all TL_WRITE_DEFAULT and TL_READ_DEFAULT locks to
5100  appropriate "real" lock types to be used for locking and to be passed
5101  to storage engine.
5102  */
5103  for (tables= *start; tables; tables= tables->next_global)
5104  {
5105  TABLE *tbl= tables->table;
5106 
5107  /*
5108  NOTE: temporary merge tables should be processed here too, because
5109  a temporary merge table can be based on non-temporary tables.
5110  */
5111 
5112  /* Schema tables may not have a TABLE object here. */
5113  if (tbl && tbl->file->ht->db_type == DB_TYPE_MRG_MYISAM)
5114  {
5115  /* MERGE tables need to access parent and child TABLE_LISTs. */
5116  DBUG_ASSERT(tbl->pos_in_table_list == tables);
5117  if (tbl->file->extra(HA_EXTRA_ATTACH_CHILDREN))
5118  {
5119  error= TRUE;
5120  goto err;
5121  }
5122  }
5123 
5124  /* Set appropriate TABLE::lock_type. */
5125  if (tbl && tables->lock_type != TL_UNLOCK &&
5126  !thd->locked_tables_mode)
5127  {
5128  if (tables->lock_type == TL_WRITE_DEFAULT)
5129  tbl->reginfo.lock_type= thd->update_lock_default;
5130  else if (tables->lock_type == TL_READ_DEFAULT)
5131  tbl->reginfo.lock_type=
5132  read_lock_type_for_table(thd, thd->lex, tables,
5133  some_routine_modifies_data);
5134  else
5135  tbl->reginfo.lock_type= tables->lock_type;
5136  }
5137 
5138  }
5139 
5140 err:
5141  if (error && *table_to_open)
5142  {
5143  (*table_to_open)->table= NULL;
5144  }
5145  DBUG_PRINT("open_tables", ("returning: %d", (int) error));
5146  DBUG_RETURN(error);
5147 }
5148 
5149 
5175 handle_routine(THD *thd, Query_tables_list *prelocking_ctx,
5176  Sroutine_hash_entry *rt, sp_head *sp, bool *need_prelocking)
5177 {
5178  /*
5179  We assume that for any "CALL proc(...)" statement sroutines_list will
5180  have 'proc' as first element (it may have several, consider e.g.
5181  "proc(sp_func(...)))". This property is currently guaranted by the
5182  parser.
5183  */
5184 
5185  if (rt != (Sroutine_hash_entry*)prelocking_ctx->sroutines_list.first ||
5186  rt->mdl_request.key.mdl_namespace() != MDL_key::PROCEDURE)
5187  {
5188  *need_prelocking= TRUE;
5189  sp_update_stmt_used_routines(thd, prelocking_ctx, &sp->m_sroutines,
5190  rt->belong_to_view);
5191  (void)sp->add_used_tables_to_table_list(thd,
5192  &prelocking_ctx->query_tables_last,
5193  rt->belong_to_view);
5194  }
5195  sp->propagate_attributes(prelocking_ctx);
5196  return FALSE;
5197 }
5198 
5199 
5223 handle_table(THD *thd, Query_tables_list *prelocking_ctx,
5224  TABLE_LIST *table_list, bool *need_prelocking)
5225 {
5226  /* We rely on a caller to check that table is going to be changed. */
5227  DBUG_ASSERT(table_list->lock_type >= TL_WRITE_ALLOW_WRITE);
5228 
5229  if (table_list->trg_event_map)
5230  {
5231  if (table_list->table->triggers)
5232  {
5233  *need_prelocking= TRUE;
5234 
5235  if (table_list->table->triggers->
5236  add_tables_and_routines_for_triggers(thd, prelocking_ctx, table_list))
5237  return TRUE;
5238  }
5239  }
5240 
5241  return FALSE;
5242 }
5243 
5244 
5261 handle_view(THD *thd, Query_tables_list *prelocking_ctx,
5262  TABLE_LIST *table_list, bool *need_prelocking)
5263 {
5264  if (table_list->view->uses_stored_routines())
5265  {
5266  *need_prelocking= TRUE;
5267 
5268  sp_update_stmt_used_routines(thd, prelocking_ctx,
5269  &table_list->view->sroutines_list,
5270  table_list->top_table());
5271  }
5272  return FALSE;
5273 }
5274 
5275 
5291 bool Lock_tables_prelocking_strategy::
5292 handle_table(THD *thd, Query_tables_list *prelocking_ctx,
5293  TABLE_LIST *table_list, bool *need_prelocking)
5294 {
5295  if (DML_prelocking_strategy::handle_table(thd, prelocking_ctx, table_list,
5296  need_prelocking))
5297  return TRUE;
5298 
5299  /* We rely on a caller to check that table is going to be changed. */
5300  DBUG_ASSERT(table_list->lock_type >= TL_WRITE_ALLOW_WRITE);
5301 
5302  return FALSE;
5303 }
5304 
5305 
5316 handle_routine(THD *thd, Query_tables_list *prelocking_ctx,
5317  Sroutine_hash_entry *rt, sp_head *sp, bool *need_prelocking)
5318 {
5319  return FALSE;
5320 }
5321 
5322 
5342 handle_table(THD *thd, Query_tables_list *prelocking_ctx,
5343  TABLE_LIST *table_list, bool *need_prelocking)
5344 {
5345  return FALSE;
5346 }
5347 
5348 
5357 handle_view(THD *thd, Query_tables_list *prelocking_ctx,
5358  TABLE_LIST *table_list, bool *need_prelocking)
5359 {
5360  return FALSE;
5361 }
5362 
5363 
5375 static bool check_lock_and_start_stmt(THD *thd,
5376  Query_tables_list *prelocking_ctx,
5377  TABLE_LIST *table_list)
5378 {
5379  int error;
5380  thr_lock_type lock_type;
5381  DBUG_ENTER("check_lock_and_start_stmt");
5382 
5383  /*
5384  TL_WRITE_DEFAULT and TL_READ_DEFAULT are supposed to be parser only
5385  types of locks so they should be converted to appropriate other types
5386  to be passed to storage engine. The exact lock type passed to the
5387  engine is important as, for example, InnoDB uses it to determine
5388  what kind of row locks should be acquired when executing statement
5389  in prelocked mode or under LOCK TABLES with @@innodb_table_locks = 0.
5390 
5391  Last argument routine_modifies_data for read_lock_type_for_table()
5392  is ignored, as prelocking placeholder will never be set here.
5393  */
5394  if (table_list->lock_type == TL_WRITE_DEFAULT)
5395  lock_type= thd->update_lock_default;
5396  else if (table_list->lock_type == TL_READ_DEFAULT)
5397  lock_type= read_lock_type_for_table(thd, prelocking_ctx, table_list, true);
5398  else
5399  lock_type= table_list->lock_type;
5400 
5401  if ((int) lock_type > (int) TL_WRITE_ALLOW_WRITE &&
5402  (int) table_list->table->reginfo.lock_type <= (int) TL_WRITE_ALLOW_WRITE)
5403  {
5404  my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), table_list->alias);
5405  DBUG_RETURN(1);
5406  }
5407  if ((error= table_list->table->file->start_stmt(thd, lock_type)))
5408  {
5409  table_list->table->file->print_error(error, MYF(0));
5410  DBUG_RETURN(1);
5411  }
5412  DBUG_RETURN(0);
5413 }
5414 
5415 
5451  thr_lock_type lock_type, uint flags,
5452  Prelocking_strategy *prelocking_strategy)
5453 {
5454  TABLE_LIST *save_next_global;
5455  DBUG_ENTER("open_n_lock_single_table");
5456 
5457  /* Remember old 'next' pointer. */
5458  save_next_global= table_l->next_global;
5459  /* Break list. */
5460  table_l->next_global= NULL;
5461 
5462  /* Set requested lock type. */
5463  table_l->lock_type= lock_type;
5464  /* Allow to open real tables only. */
5465  table_l->required_type= FRMTYPE_TABLE;
5466 
5467  /* Open the table. */
5468  if (open_and_lock_tables(thd, table_l, FALSE, flags,
5469  prelocking_strategy))
5470  table_l->table= NULL; /* Just to be sure. */
5471 
5472  /* Restore list. */
5473  table_l->next_global= save_next_global;
5474 
5475  DBUG_RETURN(table_l->table);
5476 }
5477 
5478 
5479 /*
5480  Open and lock one table
5481 
5482  SYNOPSIS
5483  open_ltable()
5484  thd Thread handler
5485  table_list Table to open is first table in this list
5486  lock_type Lock to use for open
5487  lock_flags Flags passed to mysql_lock_table
5488 
5489  NOTE
5490  This function doesn't do anything like SP/SF/views/triggers analysis done
5491  in open_table()/lock_tables(). It is intended for opening of only one
5492  concrete table. And used only in special contexts.
5493 
5494  RETURN VALUES
5495  table Opened table
5496  0 Error
5497 
5498  If ok, the following are also set:
5499  table_list->lock_type lock_type
5500  table_list->table table
5501 */
5502 
5503 TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type lock_type,
5504  uint lock_flags)
5505 {
5506  TABLE *table;
5507  Open_table_context ot_ctx(thd, lock_flags);
5508  bool error;
5509  DBUG_ENTER("open_ltable");
5510 
5511  /* should not be used in a prelocked_mode context, see NOTE above */
5512  DBUG_ASSERT(thd->locked_tables_mode < LTM_PRELOCKED);
5513 
5514  THD_STAGE_INFO(thd, stage_opening_tables);
5515  thd->current_tablenr= 0;
5516  /* open_ltable can be used only for BASIC TABLEs */
5517  table_list->required_type= FRMTYPE_TABLE;
5518 
5519  /* This function can't properly handle requests for such metadata locks. */
5520  DBUG_ASSERT(table_list->mdl_request.type < MDL_SHARED_UPGRADABLE);
5521 
5522  while ((error= open_table(thd, table_list, &ot_ctx)) &&
5523  ot_ctx.can_recover_from_failed_open())
5524  {
5525  /*
5526  Even though we have failed to open table we still need to
5527  call release_transactional_locks() to release metadata locks which
5528  might have been acquired successfully.
5529  */
5530  thd->mdl_context.rollback_to_savepoint(ot_ctx.start_of_statement_svp());
5531  table_list->mdl_request.ticket= 0;
5532  if (ot_ctx.recover_from_failed_open())
5533  break;
5534  }
5535 
5536  if (!error)
5537  {
5538  /*
5539  We can't have a view or some special "open_strategy" in this function
5540  so there should be a TABLE instance.
5541  */
5542  DBUG_ASSERT(table_list->table);
5543  table= table_list->table;
5544  if (table->file->ht->db_type == DB_TYPE_MRG_MYISAM)
5545  {
5546  /* A MERGE table must not come here. */
5547  /* purecov: begin tested */
5548  my_error(ER_WRONG_OBJECT, MYF(0), table->s->db.str,
5549  table->s->table_name.str, "BASE TABLE");
5550  table= 0;
5551  goto end;
5552  /* purecov: end */
5553  }
5554 
5555  table_list->lock_type= lock_type;
5556  table->grant= table_list->grant;
5557  if (thd->locked_tables_mode)
5558  {
5559  if (check_lock_and_start_stmt(thd, thd->lex, table_list))
5560  table= 0;
5561  }
5562  else
5563  {
5564  DBUG_ASSERT(thd->lock == 0); // You must lock everything at once
5565  if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
5566  if (! (thd->lock= mysql_lock_tables(thd, &table_list->table, 1,
5567  lock_flags)))
5568  {
5569  table= 0;
5570  }
5571  }
5572  }
5573  else
5574  table= 0;
5575 
5576 end:
5577  if (table == NULL)
5578  {
5579  if (!thd->in_sub_stmt)
5580  trans_rollback_stmt(thd);
5581  close_thread_tables(thd);
5582  }
5583  DBUG_RETURN(table);
5584 }
5585 
5586 
5607 bool open_and_lock_tables(THD *thd, TABLE_LIST *tables,
5608  bool derived, uint flags,
5609  Prelocking_strategy *prelocking_strategy)
5610 {
5611  uint counter;
5612  MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
5613  DBUG_ENTER("open_and_lock_tables");
5614  DBUG_PRINT("enter", ("derived handling: %d", derived));
5615 
5616  if (open_tables(thd, &tables, &counter, flags, prelocking_strategy))
5617  goto err;
5618 
5619  DBUG_EXECUTE_IF("sleep_open_and_lock_after_open", {
5620  const char *old_proc_info= thd->proc_info;
5621  thd->proc_info= "DBUG sleep";
5622  my_sleep(6000000);
5623  thd->proc_info= old_proc_info;});
5624 
5625  if (lock_tables(thd, tables, counter, flags))
5626  goto err;
5627 
5628  if (derived &&
5629  (mysql_handle_derived(thd->lex, &mysql_derived_prepare)))
5630  goto err;
5631 
5632  DBUG_RETURN(FALSE);
5633 err:
5634  if (! thd->in_sub_stmt)
5635  trans_rollback_stmt(thd); /* Necessary if derived handling failed. */
5636  close_thread_tables(thd);
5637  /* Don't keep locks for a failed statement. */
5638  thd->mdl_context.rollback_to_savepoint(mdl_savepoint);
5639  DBUG_RETURN(TRUE);
5640 }
5641 
5642 
5663 bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags)
5664 {
5665  DML_prelocking_strategy prelocking_strategy;
5666  MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
5667  DBUG_ENTER("open_normal_and_derived_tables");
5668  if (open_tables(thd, &tables, &thd->lex->table_count, flags,
5669  &prelocking_strategy) ||
5670  mysql_handle_derived(thd->lex, &mysql_derived_prepare))
5671  goto end;
5672 
5673  DBUG_RETURN(0);
5674 end:
5675  /*
5676  No need to commit/rollback the statement transaction: it's
5677  either not started or we're filling in an INFORMATION_SCHEMA
5678  table on the fly, and thus mustn't manipulate with the
5679  transaction of the enclosing statement.
5680  */
5681  DBUG_ASSERT(thd->transaction.stmt.is_empty() ||
5682  (thd->state_flags & Open_tables_state::BACKUPS_AVAIL) ||
5683  thd->in_sub_stmt);
5684  close_thread_tables(thd);
5685  /* Don't keep locks for a failed statement. */
5686  thd->mdl_context.rollback_to_savepoint(mdl_savepoint);
5687 
5688  DBUG_RETURN(TRUE); /* purecov: inspected */
5689 }
5690 
5691 
5692 /*
5693  Mark all real tables in the list as free for reuse.
5694 
5695  SYNOPSIS
5696  mark_real_tables_as_free_for_reuse()
5697  thd - thread context
5698  table - head of the list of tables
5699 
5700  DESCRIPTION
5701  Marks all real tables in the list (i.e. not views, derived
5702  or schema tables) as free for reuse.
5703 */
5704 
5705 static void mark_real_tables_as_free_for_reuse(TABLE_LIST *table_list)
5706 {
5707  TABLE_LIST *table;
5708  for (table= table_list; table; table= table->next_global)
5709  if (!table->placeholder())
5710  {
5711  table->table->query_id= 0;
5712  }
5713  for (table= table_list; table; table= table->next_global)
5714  if (!table->placeholder())
5715  {
5716  /*
5717  Detach children of MyISAMMRG tables used in
5718  sub-statements, they will be reattached at open.
5719  This has to be done in a separate loop to make sure
5720  that children have had their query_id cleared.
5721  */
5722  table->table->file->extra(HA_EXTRA_DETACH_CHILDREN);
5723  }
5724 }
5725 
5726 
5747 bool lock_tables(THD *thd, TABLE_LIST *tables, uint count,
5748  uint flags)
5749 {
5750  TABLE_LIST *table;
5751 
5752  DBUG_ENTER("lock_tables");
5753  /*
5754  We can't meet statement requiring prelocking if we already
5755  in prelocked mode.
5756  */
5757  DBUG_ASSERT(thd->locked_tables_mode <= LTM_LOCK_TABLES ||
5758  !thd->lex->requires_prelocking());
5759 
5760  /*
5761  lock_tables() should not be called if this statement has
5762  already locked its tables.
5763  */
5764  DBUG_ASSERT(thd->lex->lock_tables_state == Query_tables_list::LTS_NOT_LOCKED);
5765 
5766  if (!tables && !thd->lex->requires_prelocking())
5767  {
5768  /*
5769  Even though we are not really locking any tables mark this
5770  statement as one that has locked its tables, so we won't
5771  call this function second time for the same execution of
5772  the same statement.
5773  */
5774  thd->lex->lock_tables_state= Query_tables_list::LTS_LOCKED;
5775  DBUG_RETURN(thd->decide_logging_format(tables));
5776  }
5777 
5778  /*
5779  Check for thd->locked_tables_mode to avoid a redundant
5780  and harmful attempt to lock the already locked tables again.
5781  Checking for thd->lock is not enough in some situations. For example,
5782  if a stored function contains
5783  "drop table t3; create temporary t3 ..; insert into t3 ...;"
5784  thd->lock may be 0 after drop tables, whereas locked_tables_mode
5785  is still on. In this situation an attempt to lock temporary
5786  table t3 will lead to a memory leak.
5787  */
5788  if (! thd->locked_tables_mode)
5789  {
5790  DBUG_ASSERT(thd->lock == 0); // You must lock everything at once
5791  TABLE **start,**ptr;
5792 
5793  if (!(ptr=start=(TABLE**) thd->alloc(sizeof(TABLE*)*count)))
5794  DBUG_RETURN(TRUE);
5795  for (table= tables; table; table= table->next_global)
5796  {
5797  if (!table->placeholder())
5798  *(ptr++)= table->table;
5799  }
5800 
5801  /*
5802  DML statements that modify a table with an auto_increment column based on
5803  rows selected from a table are unsafe as the order in which the rows are
5804  fetched fron the select tables cannot be determined and may differ on
5805  master and slave.
5806  */
5807  if (thd->variables.binlog_format != BINLOG_FORMAT_ROW && tables &&
5808  has_write_table_with_auto_increment_and_select(tables))
5809  thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_WRITE_AUTOINC_SELECT);
5810  /* Todo: merge all has_write_table_auto_inc with decide_logging_format */
5811  if (thd->variables.binlog_format != BINLOG_FORMAT_ROW && tables)
5812  {
5813  if (has_write_table_auto_increment_not_first_in_pk(tables))
5814  thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_AUTOINC_NOT_FIRST);
5815  }
5816 
5817  /*
5818  INSERT...ON DUPLICATE KEY UPDATE on a table with more than one unique keys
5819  can be unsafe.
5820  */
5821  uint unique_keys= 0;
5822  for (TABLE_LIST *query_table= tables; query_table && unique_keys <= 1;
5823  query_table= query_table->next_global)
5824  if(query_table->table)
5825  {
5826  uint keys= query_table->table->s->keys, i= 0;
5827  unique_keys= 0;
5828  for (KEY* keyinfo= query_table->table->s->key_info;
5829  i < keys && unique_keys <= 1; i++, keyinfo++)
5830  {
5831  if (keyinfo->flags & HA_NOSAME)
5832  unique_keys++;
5833  }
5834  if (!query_table->placeholder() &&
5835  query_table->lock_type >= TL_WRITE_ALLOW_WRITE &&
5836  unique_keys > 1 && thd->lex->sql_command == SQLCOM_INSERT &&
5837  /* Duplicate key update is not supported by INSERT DELAYED */
5838  thd->get_command() != COM_DELAYED_INSERT &&
5839  thd->lex->duplicates == DUP_UPDATE)
5840  thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_INSERT_TWO_KEYS);
5841  }
5842 
5843 
5844  /* We have to emulate LOCK TABLES if we are statement needs prelocking. */
5845  if (thd->lex->requires_prelocking())
5846  {
5847 
5848  /*
5849  A query that modifies autoinc column in sub-statement can make the
5850  master and slave inconsistent.
5851  We can solve these problems in mixed mode by switching to binlogging
5852  if at least one updated table is used by sub-statement
5853  */
5854  if (thd->variables.binlog_format != BINLOG_FORMAT_ROW && tables &&
5855  has_write_table_with_auto_increment(thd->lex->first_not_own_table()))
5856  thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_AUTOINC_COLUMNS);
5857  }
5858 
5859  DEBUG_SYNC(thd, "before_lock_tables_takes_lock");
5860 
5861  if (! (thd->lock= mysql_lock_tables(thd, start, (uint) (ptr - start),
5862  flags)))
5863  DBUG_RETURN(TRUE);
5864 
5865  DEBUG_SYNC(thd, "after_lock_tables_takes_lock");
5866 
5867  if (thd->lex->requires_prelocking() &&
5868  thd->lex->sql_command != SQLCOM_LOCK_TABLES)
5869  {
5870  TABLE_LIST *first_not_own= thd->lex->first_not_own_table();
5871  /*
5872  We just have done implicit LOCK TABLES, and now we have
5873  to emulate first open_and_lock_tables() after it.
5874 
5875  When open_and_lock_tables() is called for a single table out of
5876  a table list, the 'next_global' chain is temporarily broken. We
5877  may not find 'first_not_own' before the end of the "list".
5878  Look for example at those places where open_n_lock_single_table()
5879  is called. That function implements the temporary breaking of
5880  a table list for opening a single table.
5881  */
5882  for (table= tables;
5883  table && table != first_not_own;
5884  table= table->next_global)
5885  {
5886  if (!table->placeholder())
5887  {
5888  table->table->query_id= thd->query_id;
5889  if (check_lock_and_start_stmt(thd, thd->lex, table))
5890  {
5891  mysql_unlock_tables(thd, thd->lock);
5892  thd->lock= 0;
5893  DBUG_RETURN(TRUE);
5894  }
5895  }
5896  }
5897  /*
5898  Let us mark all tables which don't belong to the statement itself,
5899  and was marked as occupied during open_tables() as free for reuse.
5900  */
5901  mark_real_tables_as_free_for_reuse(first_not_own);
5902  DBUG_PRINT("info",("locked_tables_mode= LTM_PRELOCKED"));
5903  thd->enter_locked_tables_mode(LTM_PRELOCKED);
5904  }
5905  }
5906  else
5907  {
5908  TABLE_LIST *first_not_own= thd->lex->first_not_own_table();
5909  /*
5910  When open_and_lock_tables() is called for a single table out of
5911  a table list, the 'next_global' chain is temporarily broken. We
5912  may not find 'first_not_own' before the end of the "list".
5913  Look for example at those places where open_n_lock_single_table()
5914  is called. That function implements the temporary breaking of
5915  a table list for opening a single table.
5916  */
5917  for (table= tables;
5918  table && table != first_not_own;
5919  table= table->next_global)
5920  {
5921  if (table->placeholder())
5922  continue;
5923 
5924  /*
5925  In a stored function or trigger we should ensure that we won't change
5926  a table that is already used by the calling statement.
5927  */
5928  if (thd->locked_tables_mode >= LTM_PRELOCKED &&
5929  table->lock_type >= TL_WRITE_ALLOW_WRITE)
5930  {
5931  for (TABLE* opentab= thd->open_tables; opentab; opentab= opentab->next)
5932  {
5933  if (table->table->s == opentab->s && opentab->query_id &&
5934  table->table->query_id != opentab->query_id)
5935  {
5936  my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),
5937  table->table->s->table_name.str);
5938  DBUG_RETURN(TRUE);
5939  }
5940  }
5941  }
5942 
5943  if (check_lock_and_start_stmt(thd, thd->lex, table))
5944  {
5945  DBUG_RETURN(TRUE);
5946  }
5947  }
5948  /*
5949  If we are under explicit LOCK TABLES and our statement requires
5950  prelocking, we should mark all "additional" tables as free for use
5951  and enter prelocked mode.
5952  */
5953  if (thd->lex->requires_prelocking())
5954  {
5955  mark_real_tables_as_free_for_reuse(first_not_own);
5956  DBUG_PRINT("info",
5957  ("thd->locked_tables_mode= LTM_PRELOCKED_UNDER_LOCK_TABLES"));
5958  thd->locked_tables_mode= LTM_PRELOCKED_UNDER_LOCK_TABLES;
5959  }
5960  }
5961 
5962  /*
5963  Mark the statement as having tables locked. For purposes
5964  of Query_tables_list::lock_tables_state we treat any
5965  statement which passes through lock_tables() as such.
5966  */
5967  thd->lex->lock_tables_state= Query_tables_list::LTS_LOCKED;
5968 
5969  DBUG_RETURN(thd->decide_logging_format(tables));
5970 }
5971 
5972 
5989 void close_tables_for_reopen(THD *thd, TABLE_LIST **tables,
5990  const MDL_savepoint &start_of_statement_svp)
5991 {
5992  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
5993  TABLE_LIST *tmp;
5994 
5995  /*
5996  If table list consists only from tables from prelocking set, table list
5997  for new attempt should be empty, so we have to update list's root pointer.
5998  */
5999  if (first_not_own_table == *tables)
6000  *tables= 0;
6001  thd->lex->chop_off_not_own_tables();
6002  /* Reset MDL tickets for procedures/functions */
6003  for (Sroutine_hash_entry *rt=
6004  (Sroutine_hash_entry*)thd->lex->sroutines_list.first;
6005  rt; rt= rt->next)
6006  rt->mdl_request.ticket= NULL;
6007  sp_remove_not_own_routines(thd->lex);
6008  for (tmp= *tables; tmp; tmp= tmp->next_global)
6009  {
6010  tmp->table= 0;
6011  tmp->mdl_request.ticket= NULL;
6012  /* We have to cleanup translation tables of views. */
6013  tmp->cleanup_items();
6014  }
6015  /*
6016  No need to commit/rollback the statement transaction: it's
6017  either not started or we're filling in an INFORMATION_SCHEMA
6018  table on the fly, and thus mustn't manipulate with the
6019  transaction of the enclosing statement.
6020  */
6021  DBUG_ASSERT(thd->transaction.stmt.is_empty() ||
6022  (thd->state_flags & Open_tables_state::BACKUPS_AVAIL));
6023  close_thread_tables(thd);
6024  thd->mdl_context.rollback_to_savepoint(start_of_statement_svp);
6025 }
6026 
6027 
6052 TABLE *open_table_uncached(THD *thd, const char *path, const char *db,
6053  const char *table_name,
6054  bool add_to_temporary_tables_list,
6055  bool open_in_engine)
6056 {
6057  TABLE *tmp_table;
6058  TABLE_SHARE *share;
6059  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
6060  uint key_length;
6061  DBUG_ENTER("open_table_uncached");
6062  DBUG_PRINT("enter",
6063  ("table: '%s'.'%s' path: '%s' server_id: %u "
6064  "pseudo_thread_id: %lu",
6065  db, table_name, path,
6066  (uint) thd->server_id, (ulong) thd->variables.pseudo_thread_id));
6067 
6068  /* Create the cache_key for temporary tables */
6069  key_length= create_table_def_key(thd, cache_key, db, table_name, 1);
6070 
6071  if (!(tmp_table= (TABLE*) my_malloc(sizeof(*tmp_table) + sizeof(*share) +
6072  strlen(path)+1 + key_length,
6073  MYF(MY_WME))))
6074  DBUG_RETURN(0); /* purecov: inspected */
6075 
6076 #ifndef DBUG_OFF
6077  mysql_mutex_lock(&LOCK_open);
6078  DBUG_ASSERT(!my_hash_search(&table_def_cache, (uchar*) cache_key,
6079  key_length));
6080  mysql_mutex_unlock(&LOCK_open);
6081 #endif
6082 
6083  share= (TABLE_SHARE*) (tmp_table+1);
6084  tmp_path= (char*) (share+1);
6085  saved_cache_key= strmov(tmp_path, path)+1;
6086  memcpy(saved_cache_key, cache_key, key_length);
6087 
6088  init_tmp_table_share(thd, share, saved_cache_key, key_length,
6089  strend(saved_cache_key)+1, tmp_path);
6090 
6091  if (open_table_def(thd, share, 0))
6092  {
6093  /* No need to lock share->mutex as this is not needed for tmp tables */
6094  free_table_share(share);
6095  my_free(tmp_table);
6096  DBUG_RETURN(0);
6097  }
6098 
6099 #ifdef HAVE_PSI_TABLE_INTERFACE
6100  share->m_psi= PSI_TABLE_CALL(get_table_share)(true, share);
6101 #else
6102  share->m_psi= NULL;
6103 #endif
6104 
6105  if (open_table_from_share(thd, share, table_name,
6106  open_in_engine ?
6107  (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
6108  HA_GET_INDEX) : 0,
6109  READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD,
6110  ha_open_options,
6111  tmp_table,
6112  /*
6113  Set "is_create_table" if the table does not
6114  exist in SE
6115  */
6116  open_in_engine ? false : true))
6117  {
6118  /* No need to lock share->mutex as this is not needed for tmp tables */
6119  free_table_share(share);
6120  my_free(tmp_table);
6121  DBUG_RETURN(0);
6122  }
6123 
6124  tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked
6125  share->tmp_table= (tmp_table->file->has_transactions() ?
6126  TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
6127 
6128  if (add_to_temporary_tables_list)
6129  {
6130  /* growing temp list at the head */
6131  tmp_table->next= thd->temporary_tables;
6132  if (tmp_table->next)
6133  tmp_table->next->prev= tmp_table;
6134  thd->temporary_tables= tmp_table;
6135  thd->temporary_tables->prev= 0;
6136  if (thd->slave_thread)
6137  modify_slave_open_temp_tables(thd, 1);
6138  }
6139  tmp_table->pos_in_table_list= 0;
6140 
6141  tmp_table->set_created();
6142 
6143  DBUG_PRINT("tmptable", ("opened table: '%s'.'%s' 0x%lx", tmp_table->s->db.str,
6144  tmp_table->s->table_name.str, (long) tmp_table));
6145  DBUG_RETURN(tmp_table);
6146 }
6147 
6148 
6160 bool rm_temporary_table(handlerton *base, const char *path)
6161 {
6162  bool error=0;
6163  handler *file;
6164  char frm_path[FN_REFLEN + 1];
6165  DBUG_ENTER("rm_temporary_table");
6166 
6167  strxnmov(frm_path, sizeof(frm_path) - 1, path, reg_ext, NullS);
6168  if (mysql_file_delete(key_file_frm, frm_path, MYF(0)))
6169  error=1; /* purecov: inspected */
6170  file= get_new_handler((TABLE_SHARE*) 0, current_thd->mem_root, base);
6171  if (file && file->ha_delete_table(path))
6172  {
6173  error=1;
6174  sql_print_warning("Could not remove temporary table: '%s', error: %d",
6175  path, my_errno);
6176  }
6177  delete file;
6178  DBUG_RETURN(error);
6179 }
6180 
6181 
6182 /*****************************************************************************
6183 * The following find_field_in_XXX procedures implement the core of the
6184 * name resolution functionality. The entry point to resolve a column name in a
6185 * list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
6186 * for each table reference. In turn, depending on the type of table reference,
6187 * 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
6188 * below specific for the type of table reference.
6189 ******************************************************************************/
6190 
6191 /* Special Field pointers as return values of find_field_in_XXX functions. */
6192 Field *not_found_field= (Field*) 0x1;
6193 Field *view_ref_found= (Field*) 0x2;
6194 
6195 #define WRONG_GRANT (Field*) -1
6196 
6197 static void update_field_dependencies(THD *thd, Field *field, TABLE *table)
6198 {
6199  DBUG_ENTER("update_field_dependencies");
6200  if (thd->mark_used_columns != MARK_COLUMNS_NONE)
6201  {
6202  MY_BITMAP *bitmap;
6203 
6204  /*
6205  We always want to register the used keys, as the column bitmap may have
6206  been set for all fields (for example for view).
6207  */
6208 
6209  table->covering_keys.intersect(field->part_of_key);
6210  table->merge_keys.merge(field->part_of_key);
6211 
6212  if (thd->mark_used_columns == MARK_COLUMNS_READ)
6213  bitmap= table->read_set;
6214  else
6215  bitmap= table->write_set;
6216 
6217  /*
6218  The test-and-set mechanism in the bitmap is not reliable during
6219  multi-UPDATE statements under MARK_COLUMNS_READ mode
6220  (thd->mark_used_columns == MARK_COLUMNS_READ), as this bitmap contains
6221  only those columns that are used in the SET clause. I.e they are being
6222  set here. See multi_update::prepare()
6223  */
6224  if (bitmap_fast_test_and_set(bitmap, field->field_index))
6225  {
6226  if (thd->mark_used_columns == MARK_COLUMNS_WRITE)
6227  {
6228  DBUG_PRINT("warning", ("Found duplicated field"));
6229  thd->dup_field= field;
6230  }
6231  else
6232  {
6233  DBUG_PRINT("note", ("Field found before"));
6234  }
6235  DBUG_VOID_RETURN;
6236  }
6237  if (table->get_fields_in_item_tree)
6238  field->flags|= GET_FIXED_FIELDS_FLAG;
6239  table->used_fields++;
6240  }
6241  else if (table->get_fields_in_item_tree)
6242  field->flags|= GET_FIXED_FIELDS_FLAG;
6243  DBUG_VOID_RETURN;
6244 }
6245 
6246 
6273 {
6274  DBUG_ENTER("open_temporary_table");
6275  DBUG_PRINT("enter", ("table: '%s'.'%s'", tl->db, tl->table_name));
6276 
6277  /*
6278  Code in open_table() assumes that TABLE_LIST::table can
6279  be non-zero only for pre-opened temporary tables.
6280  */
6281  DBUG_ASSERT(tl->table == NULL);
6282 
6283  /*
6284  This function should not be called for cases when derived or I_S
6285  tables can be met since table list elements for such tables can
6286  have invalid db or table name.
6287  Instead open_temporary_tables() should be used.
6288  */
6289  DBUG_ASSERT(!tl->derived && !tl->schema_table);
6290 
6291  if (tl->open_type == OT_BASE_ONLY)
6292  {
6293  DBUG_PRINT("info", ("skip_temporary is set"));
6294  DBUG_RETURN(FALSE);
6295  }
6296 
6297  TABLE *table= find_temporary_table(thd, tl);
6298 
6299  if (!table)
6300  {
6301  if (tl->open_type == OT_TEMPORARY_ONLY &&
6302  tl->open_strategy == TABLE_LIST::OPEN_NORMAL)
6303  {
6304  my_error(ER_NO_SUCH_TABLE, MYF(0), tl->db, tl->table_name);
6305  DBUG_RETURN(TRUE);
6306  }
6307  DBUG_RETURN(FALSE);
6308  }
6309 
6310 #ifdef WITH_PARTITION_STORAGE_ENGINE
6311  if (tl->partition_names)
6312  {
6313  /* Partitioned temporary tables is not supported. */
6314  DBUG_ASSERT(!table->part_info);
6315  my_error(ER_PARTITION_CLAUSE_ON_NONPARTITIONED, MYF(0));
6316  DBUG_RETURN(true);
6317  }
6318 #endif
6319 
6320  if (table->query_id)
6321  {
6322  /*
6323  We're trying to use the same temporary table twice in a query.
6324  Right now we don't support this because a temporary table is always
6325  represented by only one TABLE object in THD, and it can not be
6326  cloned. Emit an error for an unsupported behaviour.
6327  */
6328 
6329  DBUG_PRINT("error",
6330  ("query_id: %lu server_id: %u pseudo_thread_id: %lu",
6331  (ulong) table->query_id, (uint) thd->server_id,
6332  (ulong) thd->variables.pseudo_thread_id));
6333  my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
6334  DBUG_RETURN(TRUE);
6335  }
6336 
6337  table->query_id= thd->query_id;
6338  thd->thread_specific_used= TRUE;
6339 
6340  tl->updatable= 1; // It is not derived table nor non-updatable VIEW.
6341  tl->table= table;
6342 
6343  table->init(thd, tl);
6344 
6345  DBUG_PRINT("info", ("Using temporary table"));
6346  DBUG_RETURN(FALSE);
6347 }
6348 
6349 
6363 bool open_temporary_tables(THD *thd, TABLE_LIST *tl_list)
6364 {
6365  TABLE_LIST *first_not_own= thd->lex->first_not_own_table();
6366  DBUG_ENTER("open_temporary_tables");
6367 
6368  for (TABLE_LIST *tl= tl_list; tl && tl != first_not_own; tl= tl->next_global)
6369  {
6370  if (tl->derived || tl->schema_table)
6371  {
6372  /*
6373  Derived and I_S tables will be handled by a later call to open_tables().
6374  */
6375  continue;
6376  }
6377 
6378  if (open_temporary_table(thd, tl))
6379  DBUG_RETURN(TRUE);
6380  }
6381 
6382  DBUG_RETURN(FALSE);
6383 }
6384 
6385 
6386 /*
6387  Find a field by name in a view that uses merge algorithm.
6388 
6389  SYNOPSIS
6390  find_field_in_view()
6391  thd thread handler
6392  table_list view to search for 'name'
6393  name name of field
6394  length length of name
6395  item_name name of item if it will be created (VIEW)
6396  ref expression substituted in VIEW should be passed
6397  using this reference (return view_ref_found)
6398  register_tree_change TRUE if ref is not stack variable and we
6399  need register changes in item tree
6400 
6401  RETURN
6402  0 field is not found
6403  view_ref_found found value in VIEW (real result is in *ref)
6404  # pointer to field - only for schema table fields
6405 */
6406 
6407 static Field *
6408 find_field_in_view(THD *thd, TABLE_LIST *table_list,
6409  const char *name, uint length,
6410  const char *item_name, Item **ref,
6411  bool register_tree_change)
6412 {
6413  DBUG_ENTER("find_field_in_view");
6414  DBUG_PRINT("enter",
6415  ("view: '%s', field name: '%s', item name: '%s', ref 0x%lx",
6416  table_list->alias, name, item_name, (ulong) ref));
6417  Field_iterator_view field_it;
6418  field_it.set(table_list);
6419 
6420  DBUG_ASSERT(table_list->schema_table_reformed ||
6421  (ref != 0 && table_list->view != 0));
6422  for (; !field_it.end_of_fields(); field_it.next())
6423  {
6424  if (!my_strcasecmp(system_charset_info, field_it.name(), name))
6425  {
6426  Item *item;
6427 
6428  {
6429  /*
6430  Use own arena for Prepared Statements or data will be freed after
6431  PREPARE.
6432  */
6433  Prepared_stmt_arena_holder ps_arena_holder(
6434  thd,
6435  register_tree_change &&
6436  thd->stmt_arena->is_stmt_prepare_or_first_stmt_execute());
6437 
6438  /*
6439  create_item() may, or may not create a new Item, depending on
6440  the column reference. See create_view_field() for details.
6441  */
6442  item= field_it.create_item(thd);
6443 
6444  if (!item)
6445  DBUG_RETURN(0);
6446  }
6447 
6448  /*
6449  *ref != NULL means that *ref contains the item that we need to
6450  replace. If the item was aliased by the user, set the alias to
6451  the replacing item.
6452  We need to set alias on both ref itself and on ref real item.
6453  */
6454  if (*ref && !(*ref)->item_name.is_autogenerated())
6455  {
6456  item->item_name= (*ref)->item_name;
6457  item->real_item()->item_name= (*ref)->item_name;
6458  }
6459  if (register_tree_change)
6460  thd->change_item_tree(ref, item);
6461  else
6462  *ref= item;
6463  DBUG_RETURN((Field*) view_ref_found);
6464  }
6465  }
6466  DBUG_RETURN(0);
6467 }
6468 
6469 
6470 /*
6471  Find field by name in a NATURAL/USING join table reference.
6472 
6473  SYNOPSIS
6474  find_field_in_natural_join()
6475  thd [in] thread handler
6476  table_ref [in] table reference to search
6477  name [in] name of field
6478  length [in] length of name
6479  ref [in/out] if 'name' is resolved to a view field, ref is
6480  set to point to the found view field
6481  register_tree_change [in] TRUE if ref is not stack variable and we
6482  need register changes in item tree
6483  actual_table [out] the original table reference where the field
6484  belongs - differs from 'table_list' only for
6485  NATURAL/USING joins
6486 
6487  DESCRIPTION
6488  Search for a field among the result fields of a NATURAL/USING join.
6489  Notice that this procedure is called only for non-qualified field
6490  names. In the case of qualified fields, we search directly the base
6491  tables of a natural join.
6492 
6493  RETURN
6494  NULL if the field was not found
6495  WRONG_GRANT if no access rights to the found field
6496  # Pointer to the found Field
6497 */
6498 
6499 static Field *
6500 find_field_in_natural_join(THD *thd, TABLE_LIST *table_ref, const char *name,
6501  uint length, Item **ref, bool register_tree_change,
6502  TABLE_LIST **actual_table)
6503 {
6505  field_it(*(table_ref->join_columns));
6506  Natural_join_column *nj_col, *curr_nj_col;
6507  Field *found_field;
6508  DBUG_ENTER("find_field_in_natural_join");
6509  DBUG_PRINT("enter", ("field name: '%s', ref 0x%lx",
6510  name, (ulong) ref));
6511  DBUG_ASSERT(table_ref->is_natural_join && table_ref->join_columns);
6512  DBUG_ASSERT(*actual_table == NULL);
6513 
6514  LINT_INIT(found_field);
6515 
6516  for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col;
6517  curr_nj_col= field_it++)
6518  {
6519  if (!my_strcasecmp(system_charset_info, curr_nj_col->name(), name))
6520  {
6521  if (nj_col)
6522  {
6523  my_error(ER_NON_UNIQ_ERROR, MYF(0), name, thd->where);
6524  DBUG_RETURN(NULL);
6525  }
6526  nj_col= curr_nj_col;
6527  }
6528  }
6529  if (!nj_col)
6530  DBUG_RETURN(NULL);
6531 
6532  if (nj_col->view_field)
6533  {
6534  Item *item;
6535 
6536  {
6537  Prepared_stmt_arena_holder ps_arena_holder(thd, register_tree_change);
6538 
6539  /*
6540  create_item() may, or may not create a new Item, depending on the
6541  column reference. See create_view_field() for details.
6542  */
6543  item= nj_col->create_item(thd);
6544 
6545  if (!item)
6546  DBUG_RETURN(NULL);
6547  }
6548 
6549  /*
6550  *ref != NULL means that *ref contains the item that we need to
6551  replace. If the item was aliased by the user, set the alias to
6552  the replacing item.
6553  We need to set alias on both ref itself and on ref real item.
6554  */
6555  if (*ref && !(*ref)->item_name.is_autogenerated())
6556  {
6557  item->item_name= (*ref)->item_name;
6558  item->real_item()->item_name= (*ref)->item_name;
6559  }
6560 
6561  DBUG_ASSERT(nj_col->table_field == NULL);
6562  if (nj_col->table_ref->schema_table_reformed)
6563  {
6564  /*
6565  Translation table items are always Item_fields and fixed
6566  already('mysql_schema_table' function). So we can return
6567  ->field. It is used only for 'show & where' commands.
6568  */
6569  DBUG_RETURN(((Item_field*) (nj_col->view_field->item))->field);
6570  }
6571  if (register_tree_change)
6572  thd->change_item_tree(ref, item);
6573  else
6574  *ref= item;
6575  found_field= (Field*) view_ref_found;
6576  }
6577  else
6578  {
6579  /* This is a base table. */
6580  DBUG_ASSERT(nj_col->view_field == NULL);
6581  /*
6582  This fix_fields is not necessary (initially this item is fixed by
6583  the Item_field constructor; after reopen_tables the Item_func_eq
6584  calls fix_fields on that item), it's just a check during table
6585  reopening for columns that was dropped by the concurrent connection.
6586  */
6587  if (!nj_col->table_field->fixed &&
6588  nj_col->table_field->fix_fields(thd, (Item **)&nj_col->table_field))
6589  {
6590  DBUG_PRINT("info", ("column '%s' was dropped by the concurrent connection",
6591  nj_col->table_field->item_name.ptr()));
6592  DBUG_RETURN(NULL);
6593  }
6594  DBUG_ASSERT(nj_col->table_ref->table == nj_col->table_field->field->table);
6595  found_field= nj_col->table_field->field;
6596  update_field_dependencies(thd, found_field, nj_col->table_ref->table);
6597  }
6598 
6599  *actual_table= nj_col->table_ref;
6600 
6601  DBUG_RETURN(found_field);
6602 }
6603 
6604 
6605 /*
6606  Find field by name in a base table or a view with temp table algorithm.
6607 
6608  The caller is expected to check column-level privileges.
6609 
6610  SYNOPSIS
6611  find_field_in_table()
6612  thd thread handler
6613  table table where to search for the field
6614  name name of field
6615  length length of name
6616  allow_rowid do allow finding of "_rowid" field?
6617  cached_field_index_ptr cached position in field list (used to speedup
6618  lookup for fields in prepared tables)
6619 
6620  RETURN
6621  0 field is not found
6622  # pointer to field
6623 */
6624 
6625 Field *
6626 find_field_in_table(THD *thd, TABLE *table, const char *name, uint length,
6627  bool allow_rowid, uint *cached_field_index_ptr)
6628 {
6629  Field **field_ptr, *field;
6630  uint cached_field_index= *cached_field_index_ptr;
6631  DBUG_ENTER("find_field_in_table");
6632  DBUG_PRINT("enter", ("table: '%s', field name: '%s'", table->alias, name));
6633 
6634  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
6635  if (cached_field_index < table->s->fields &&
6636  !my_strcasecmp(system_charset_info,
6637  table->field[cached_field_index]->field_name, name))
6638  field_ptr= table->field + cached_field_index;
6639  else if (table->s->name_hash.records)
6640  {
6641  field_ptr= (Field**) my_hash_search(&table->s->name_hash, (uchar*) name,
6642  length);
6643  if (field_ptr)
6644  {
6645  /*
6646  field_ptr points to field in TABLE_SHARE. Convert it to the matching
6647  field in table
6648  */
6649  field_ptr= (table->field + (field_ptr - table->s->field));
6650  }
6651  }
6652  else
6653  {
6654  if (!(field_ptr= table->field))
6655  DBUG_RETURN((Field *)0);
6656  for (; *field_ptr; ++field_ptr)
6657  if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
6658  break;
6659  }
6660 
6661  if (field_ptr && *field_ptr)
6662  {
6663  *cached_field_index_ptr= field_ptr - table->field;
6664  field= *field_ptr;
6665  }
6666  else
6667  {
6668  if (!allow_rowid ||
6669  my_strcasecmp(system_charset_info, name, "_rowid") ||
6670  table->s->rowid_field_offset == 0)
6671  DBUG_RETURN((Field*) 0);
6672  field= table->field[table->s->rowid_field_offset-1];
6673  }
6674 
6675  update_field_dependencies(thd, field, table);
6676 
6677  DBUG_RETURN(field);
6678 }
6679 
6680 
6681 /*
6682  Find field in a table reference.
6683 
6684  SYNOPSIS
6685  find_field_in_table_ref()
6686  thd [in] thread handler
6687  table_list [in] table reference to search
6688  name [in] name of field
6689  length [in] field length of name
6690  item_name [in] name of item if it will be created (VIEW)
6691  db_name [in] optional database name that qualifies the
6692  table_name [in] optional table name that qualifies the field
6693  ref [in/out] if 'name' is resolved to a view field, ref
6694  is set to point to the found view field
6695  check_privileges [in] check privileges
6696  allow_rowid [in] do allow finding of "_rowid" field?
6697  cached_field_index_ptr [in] cached position in field list (used to
6698  speedup lookup for fields in prepared tables)
6699  register_tree_change [in] TRUE if ref is not stack variable and we
6700  need register changes in item tree
6701  actual_table [out] the original table reference where the field
6702  belongs - differs from 'table_list' only for
6703  NATURAL_USING joins.
6704 
6705  DESCRIPTION
6706  Find a field in a table reference depending on the type of table
6707  reference. There are three types of table references with respect
6708  to the representation of their result columns:
6709  - an array of Field_translator objects for MERGE views and some
6710  information_schema tables,
6711  - an array of Field objects (and possibly a name hash) for stored
6712  tables,
6713  - a list of Natural_join_column objects for NATURAL/USING joins.
6714  This procedure detects the type of the table reference 'table_list'
6715  and calls the corresponding search routine.
6716 
6717  The routine checks column-level privieleges for the found field.
6718 
6719  RETURN
6720  0 field is not found
6721  view_ref_found found value in VIEW (real result is in *ref)
6722  # pointer to field
6723 */
6724 
6725 Field *
6726 find_field_in_table_ref(THD *thd, TABLE_LIST *table_list,
6727  const char *name, uint length,
6728  const char *item_name, const char *db_name,
6729  const char *table_name, Item **ref,
6730  bool check_privileges, bool allow_rowid,
6731  uint *cached_field_index_ptr,
6732  bool register_tree_change, TABLE_LIST **actual_table)
6733 {
6734  Field *fld;
6735  DBUG_ENTER("find_field_in_table_ref");
6736  DBUG_ASSERT(table_list->alias);
6737  DBUG_ASSERT(name);
6738  DBUG_ASSERT(item_name);
6739  DBUG_PRINT("enter",
6740  ("table: '%s' field name: '%s' item name: '%s' ref 0x%lx",
6741  table_list->alias, name, item_name, (ulong) ref));
6742 
6743  /*
6744  Check that the table and database that qualify the current field name
6745  are the same as the table reference we are going to search for the field.
6746 
6747  Exclude from the test below nested joins because the columns in a
6748  nested join generally originate from different tables. Nested joins
6749  also have no table name, except when a nested join is a merge view
6750  or an information schema table.
6751 
6752  We include explicitly table references with a 'field_translation' table,
6753  because if there are views over natural joins we don't want to search
6754  inside the view, but we want to search directly in the view columns
6755  which are represented as a 'field_translation'.
6756 
6757  TODO: Ensure that table_name, db_name and tables->db always points to
6758  something !
6759  */
6760  if (/* Exclude nested joins. */
6761  (!table_list->nested_join ||
6762  /* Include merge views and information schema tables. */
6763  table_list->field_translation) &&
6764  /*
6765  Test if the field qualifiers match the table reference we plan
6766  to search.
6767  */
6768  table_name && table_name[0] &&
6769  (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
6770  (db_name && db_name[0] && table_list->db && table_list->db[0] &&
6771  (table_list->schema_table ?
6772  my_strcasecmp(system_charset_info, db_name, table_list->db) :
6773  strcmp(db_name, table_list->db)))))
6774  DBUG_RETURN(0);
6775 
6776  *actual_table= NULL;
6777 
6778  if (table_list->field_translation)
6779  {
6780  /* 'table_list' is a view or an information schema table. */
6781  if ((fld= find_field_in_view(thd, table_list, name, length, item_name, ref,
6782  register_tree_change)))
6783  *actual_table= table_list;
6784  }
6785  else if (!table_list->nested_join)
6786  {
6787  /* 'table_list' is a stored table. */
6788  DBUG_ASSERT(table_list->table);
6789  if ((fld= find_field_in_table(thd, table_list->table, name, length,
6790  allow_rowid,
6791  cached_field_index_ptr)))
6792  *actual_table= table_list;
6793  }
6794  else
6795  {
6796  /*
6797  'table_list' is a NATURAL/USING join, or an operand of such join that
6798  is a nested join itself.
6799 
6800  If the field name we search for is qualified, then search for the field
6801  in the table references used by NATURAL/USING the join.
6802  */
6803  if (table_name && table_name[0])
6804  {
6805  List_iterator<TABLE_LIST> it(table_list->nested_join->join_list);
6806  TABLE_LIST *table;
6807  while ((table= it++))
6808  {
6809  if ((fld= find_field_in_table_ref(thd, table, name, length, item_name,
6810  db_name, table_name, ref,
6811  check_privileges, allow_rowid,
6812  cached_field_index_ptr,
6813  register_tree_change, actual_table)))
6814  DBUG_RETURN(fld);
6815  }
6816  DBUG_RETURN(0);
6817  }
6818  /*
6819  Non-qualified field, search directly in the result columns of the
6820  natural join. The condition of the outer IF is true for the top-most
6821  natural join, thus if the field is not qualified, we will search
6822  directly the top-most NATURAL/USING join.
6823  */
6824  fld= find_field_in_natural_join(thd, table_list, name, length, ref,
6825  register_tree_change, actual_table);
6826  }
6827 
6828  if (fld)
6829  {
6830 #ifndef NO_EMBEDDED_ACCESS_CHECKS
6831  /* Check if there are sufficient access rights to the found field. */
6832  if (check_privileges &&
6833  check_column_grant_in_table_ref(thd, *actual_table, name, length))
6834  fld= WRONG_GRANT;
6835  else
6836 #endif
6837  if (thd->mark_used_columns != MARK_COLUMNS_NONE)
6838  {
6839  /*
6840  Get rw_set correct for this field so that the handler
6841  knows that this field is involved in the query and gets
6842  retrieved/updated
6843  */
6844  Field *field_to_set= NULL;
6845  if (fld == view_ref_found)
6846  {
6847  Item *it= (*ref)->real_item();
6848  if (it->type() == Item::FIELD_ITEM)
6849  field_to_set= ((Item_field*)it)->field;
6850  else
6851  {
6852  if (thd->mark_used_columns == MARK_COLUMNS_READ)
6853  it->walk(&Item::register_field_in_read_map, 1, (uchar *) 0);
6854  }
6855  }
6856  else
6857  field_to_set= fld;
6858  if (field_to_set)
6859  {
6860  TABLE *table= field_to_set->table;
6861  if (thd->mark_used_columns == MARK_COLUMNS_READ)
6862  bitmap_set_bit(table->read_set, field_to_set->field_index);
6863  else
6864  bitmap_set_bit(table->write_set, field_to_set->field_index);
6865  }
6866  }
6867  }
6868  DBUG_RETURN(fld);
6869 }
6870 
6871 
6872 /*
6873  Find field in table, no side effects, only purpose is to check for field
6874  in table object and get reference to the field if found.
6875 
6876  SYNOPSIS
6877  find_field_in_table_sef()
6878 
6879  table table where to find
6880  name Name of field searched for
6881 
6882  RETURN
6883  0 field is not found
6884  # pointer to field
6885 */
6886 
6887 Field *find_field_in_table_sef(TABLE *table, const char *name)
6888 {
6889  Field **field_ptr;
6890  if (table->s->name_hash.records)
6891  {
6892  field_ptr= (Field**)my_hash_search(&table->s->name_hash,(uchar*) name,
6893  strlen(name));
6894  if (field_ptr)
6895  {
6896  /*
6897  field_ptr points to field in TABLE_SHARE. Convert it to the matching
6898  field in table
6899  */
6900  field_ptr= (table->field + (field_ptr - table->s->field));
6901  }
6902  }
6903  else
6904  {
6905  if (!(field_ptr= table->field))
6906  return (Field *)0;
6907  for (; *field_ptr; ++field_ptr)
6908  if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
6909  break;
6910  }
6911  if (field_ptr)
6912  return *field_ptr;
6913  else
6914  return (Field *)0;
6915 }
6916 
6917 
6918 /*
6919  Find field in table list.
6920 
6921  SYNOPSIS
6922  find_field_in_tables()
6923  thd pointer to current thread structure
6924  item field item that should be found
6925  first_table list of tables to be searched for item
6926  last_table end of the list of tables to search for item. If NULL
6927  then search to the end of the list 'first_table'.
6928  ref if 'item' is resolved to a view field, ref is set to
6929  point to the found view field
6930  report_error Degree of error reporting:
6931  - IGNORE_ERRORS then do not report any error
6932  - IGNORE_EXCEPT_NON_UNIQUE report only non-unique
6933  fields, suppress all other errors
6934  - REPORT_EXCEPT_NON_UNIQUE report all other errors
6935  except when non-unique fields were found
6936  - REPORT_ALL_ERRORS
6937  check_privileges need to check privileges
6938  register_tree_change TRUE if ref is not a stack variable and we
6939  to need register changes in item tree
6940 
6941  RETURN VALUES
6942  0 If error: the found field is not unique, or there are
6943  no sufficient access priviliges for the found field,
6944  or the field is qualified with non-existing table.
6945  not_found_field The function was called with report_error ==
6946  (IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
6947  field was not found.
6948  view_ref_found View field is found, item passed through ref parameter
6949  found field If a item was resolved to some field
6950 */
6951 
6952 Field *
6953 find_field_in_tables(THD *thd, Item_ident *item,
6954  TABLE_LIST *first_table, TABLE_LIST *last_table,
6955  Item **ref, find_item_error_report_type report_error,
6956  bool check_privileges, bool register_tree_change)
6957 {
6958  Field *found=0;
6959  const char *db= item->db_name;
6960  const char *table_name= item->table_name;
6961  const char *name= item->field_name;
6962  uint length=(uint) strlen(name);
6963  char name_buff[NAME_LEN+1];
6964  TABLE_LIST *cur_table= first_table;
6965  TABLE_LIST *actual_table;
6966  bool allow_rowid;
6967 
6968  if (!table_name || !table_name[0])
6969  {
6970  table_name= 0; // For easier test
6971  db= 0;
6972  }
6973 
6974  allow_rowid= table_name || (cur_table && !cur_table->next_local);
6975 
6976  if (item->cached_table)
6977  {
6978  /*
6979  This shortcut is used by prepared statements. We assume that
6980  TABLE_LIST *first_table is not changed during query execution (which
6981  is true for all queries except RENAME but luckily RENAME doesn't
6982  use fields...) so we can rely on reusing pointer to its member.
6983  With this optimization we also miss case when addition of one more
6984  field makes some prepared query ambiguous and so erroneous, but we
6985  accept this trade off.
6986  */
6987  TABLE_LIST *table_ref= item->cached_table;
6988  /*
6989  The condition (table_ref->view == NULL) ensures that we will call
6990  find_field_in_table even in the case of information schema tables
6991  when table_ref->field_translation != NULL.
6992  */
6993  if (table_ref->table && !table_ref->view)
6994  {
6995  found= find_field_in_table(thd, table_ref->table, name, length,
6996  TRUE, &(item->cached_field_index));
6997 #ifndef NO_EMBEDDED_ACCESS_CHECKS
6998  /* Check if there are sufficient access rights to the found field. */
6999  if (found && check_privileges &&
7000  check_column_grant_in_table_ref(thd, table_ref, name, length))
7001  found= WRONG_GRANT;
7002 #endif
7003  }
7004  else
7005  found= find_field_in_table_ref(thd, table_ref, name, length,
7006  item->item_name.ptr(),
7007  NULL, NULL, ref, check_privileges,
7008  TRUE, &(item->cached_field_index),
7009  register_tree_change,
7010  &actual_table);
7011  if (found)
7012  {
7013  if (found == WRONG_GRANT)
7014  return (Field*) 0;
7015 
7016  /*
7017  Only views fields should be marked as dependent, not an underlying
7018  fields.
7019  */
7020  if (!table_ref->belong_to_view)
7021  {
7022  SELECT_LEX *current_sel= thd->lex->current_select;
7023  SELECT_LEX *last_select= table_ref->select_lex;
7024  /*
7025  If the field was an outer referencee, mark all selects using this
7026  sub query as dependent on the outer query
7027  */
7028  if (current_sel != last_select)
7029  mark_select_range_as_dependent(thd, last_select, current_sel,
7030  found, *ref, item);
7031  }
7032  return found;
7033  }
7034  }
7035 
7036  if (db && lower_case_table_names)
7037  {
7038  /*
7039  convert database to lower case for comparison.
7040  We can't do this in Item_field as this would change the
7041  'name' of the item which may be used in the select list
7042  */
7043  strmake(name_buff, db, sizeof(name_buff)-1);
7044  my_casedn_str(files_charset_info, name_buff);
7045  db= name_buff;
7046  }
7047 
7048  if (last_table)
7049  last_table= last_table->next_name_resolution_table;
7050 
7051  for (; cur_table != last_table ;
7052  cur_table= cur_table->next_name_resolution_table)
7053  {
7054  Field *cur_field= find_field_in_table_ref(thd, cur_table, name, length,
7055  item->item_name.ptr(), db, table_name, ref,
7056  (thd->lex->sql_command ==
7057  SQLCOM_SHOW_FIELDS)
7058  ? false : check_privileges,
7059  allow_rowid,
7060  &(item->cached_field_index),
7061  register_tree_change,
7062  &actual_table);
7063  if (cur_field)
7064  {
7065  if (cur_field == WRONG_GRANT)
7066  {
7067  if (thd->lex->sql_command != SQLCOM_SHOW_FIELDS)
7068  return (Field*) 0;
7069 
7070  thd->clear_error();
7071  cur_field= find_field_in_table_ref(thd, cur_table, name, length,
7072  item->item_name.ptr(), db, table_name, ref,
7073  false,
7074  allow_rowid,
7075  &(item->cached_field_index),
7076  register_tree_change,
7077  &actual_table);
7078  if (cur_field)
7079  {
7080  Field *nf=new Field_null(NULL,0,Field::NONE,
7081  cur_field->field_name,
7082  &my_charset_bin);
7083  nf->init(cur_table->table);
7084  cur_field= nf;
7085  }
7086  }
7087 
7088  /*
7089  Store the original table of the field, which may be different from
7090  cur_table in the case of NATURAL/USING join.
7091  */
7092  item->cached_table= (!actual_table->cacheable_table || found) ?
7093  0 : actual_table;
7094 
7095  DBUG_ASSERT(thd->where);
7096  /*
7097  If we found a fully qualified field we return it directly as it can't
7098  have duplicates.
7099  */
7100  if (db)
7101  return cur_field;
7102 
7103  if (found)
7104  {
7105  if (report_error == REPORT_ALL_ERRORS ||
7106  report_error == IGNORE_EXCEPT_NON_UNIQUE)
7107  my_error(ER_NON_UNIQ_ERROR, MYF(0),
7108  table_name ? item->full_name() : name, thd->where);
7109  return (Field*) 0;
7110  }
7111  found= cur_field;
7112  }
7113  }
7114 
7115  if (found)
7116  return found;
7117 
7118  /*
7119  If the field was qualified and there were no tables to search, issue
7120  an error that an unknown table was given. The situation is detected
7121  as follows: if there were no tables we wouldn't go through the loop
7122  and cur_table wouldn't be updated by the loop increment part, so it
7123  will be equal to the first table.
7124  */
7125  if (table_name && (cur_table == first_table) &&
7126  (report_error == REPORT_ALL_ERRORS ||
7127  report_error == REPORT_EXCEPT_NON_UNIQUE))
7128  {
7129  char buff[NAME_LEN*2 + 2];
7130  if (db && db[0])
7131  {
7132  strxnmov(buff,sizeof(buff)-1,db,".",table_name,NullS);
7133  table_name=buff;
7134  }
7135  my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, thd->where);
7136  }
7137  else
7138  {
7139  if (report_error == REPORT_ALL_ERRORS ||
7140  report_error == REPORT_EXCEPT_NON_UNIQUE)
7141  my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), thd->where);
7142  else
7143  found= not_found_field;
7144  }
7145  return found;
7146 }
7147 
7148 
7149 /*
7150  Find Item in list of items (find_field_in_tables analog)
7151 
7152  TODO
7153  is it better return only counter?
7154 
7155  SYNOPSIS
7156  find_item_in_list()
7157  find Item to find
7158  items List of items
7159  counter To return number of found item
7160  report_error
7161  REPORT_ALL_ERRORS report errors, return 0 if error
7162  REPORT_EXCEPT_NOT_FOUND Do not report 'not found' error and
7163  return not_found_item, report other errors,
7164  return 0
7165  IGNORE_ERRORS Do not report errors, return 0 if error
7166  resolution Set to the resolution type if the item is found
7167  (it says whether the item is resolved
7168  against an alias name,
7169  or as a field name without alias,
7170  or as a field hidden by alias,
7171  or ignoring alias)
7172 
7173  RETURN VALUES
7174  0 Item is not found or item is not unique,
7175  error message is reported
7176  not_found_item Function was called with
7177  report_error == REPORT_EXCEPT_NOT_FOUND and
7178  item was not found. No error message was reported
7179  found field
7180 */
7181 
7182 /* Special Item pointer to serve as a return value from find_item_in_list(). */
7183 Item **not_found_item= (Item**) 0x1;
7184 
7185 
7186 Item **
7187 find_item_in_list(Item *find, List<Item> &items, uint *counter,
7188  find_item_error_report_type report_error,
7189  enum_resolution_type *resolution)
7190 {
7191  List_iterator<Item> li(items);
7192  Item **found=0, **found_unaliased= 0, *item;
7193  const char *db_name=0;
7194  const char *field_name=0;
7195  const char *table_name=0;
7196  bool found_unaliased_non_uniq= 0;
7197  /*
7198  true if the item that we search for is a valid name reference
7199  (and not an item that happens to have a name).
7200  */
7201  bool is_ref_by_name= 0;
7202  uint unaliased_counter= 0;
7203 
7204  *resolution= NOT_RESOLVED;
7205 
7206  is_ref_by_name= (find->type() == Item::FIELD_ITEM ||
7207  find->type() == Item::REF_ITEM);
7208  if (is_ref_by_name)
7209  {
7210  field_name= ((Item_ident*) find)->field_name;
7211  table_name= ((Item_ident*) find)->table_name;
7212  db_name= ((Item_ident*) find)->db_name;
7213  }
7214 
7215  for (uint i= 0; (item=li++); i++)
7216  {
7217  if (field_name && item->real_item()->type() == Item::FIELD_ITEM)
7218  {
7219  Item_ident *item_field= (Item_ident*) item;
7220 
7221  /*
7222  In case of group_concat() with ORDER BY condition in the QUERY
7223  item_field can be field of temporary table without item name
7224  (if this field created from expression argument of group_concat()),
7225  => we have to check presence of name before compare
7226  */
7227  if (!item_field->item_name.is_set())
7228  continue;
7229 
7230  if (table_name)
7231  {
7232  /*
7233  If table name is specified we should find field 'field_name' in
7234  table 'table_name'. According to SQL-standard we should ignore
7235  aliases in this case.
7236 
7237  Since we should NOT prefer fields from the select list over
7238  other fields from the tables participating in this select in
7239  case of ambiguity we have to do extra check outside this function.
7240 
7241  We use strcmp for table names and database names as these may be
7242  case sensitive. In cases where they are not case sensitive, they
7243  are always in lower case.
7244 
7245  item_field->field_name and item_field->table_name can be 0x0 if
7246  item is not fix_field()'ed yet.
7247  */
7248  if (item_field->field_name && item_field->table_name &&
7249  !my_strcasecmp(system_charset_info, item_field->field_name,
7250  field_name) &&
7251  !my_strcasecmp(table_alias_charset, item_field->table_name,
7252  table_name) &&
7253  (!db_name || (item_field->db_name &&
7254  !strcmp(item_field->db_name, db_name))))
7255  {
7256  if (found_unaliased)
7257  {
7258  if ((*found_unaliased)->eq(item, 0))
7259  continue;
7260  /*
7261  Two matching fields in select list.
7262  We already can bail out because we are searching through
7263  unaliased names only and will have duplicate error anyway.
7264  */
7265  if (report_error != IGNORE_ERRORS)
7266  my_error(ER_NON_UNIQ_ERROR, MYF(0),
7267  find->full_name(), current_thd->where);
7268  return (Item**) 0;
7269  }
7270  found_unaliased= li.ref();
7271  unaliased_counter= i;
7272  *resolution= RESOLVED_IGNORING_ALIAS;
7273  if (db_name)
7274  break; // Perfect match
7275  }
7276  }
7277  else
7278  {
7279  int fname_cmp= my_strcasecmp(system_charset_info,
7280  item_field->field_name,
7281  field_name);
7282  if (item_field->item_name.eq_safe(field_name))
7283  {
7284  /*
7285  If table name was not given we should scan through aliases
7286  and non-aliased fields first. We are also checking unaliased
7287  name of the field in then next else-if, to be able to find
7288  instantly field (hidden by alias) if no suitable alias or
7289  non-aliased field was found.
7290  */
7291  if (found)
7292  {
7293  if ((*found)->eq(item, 0))
7294  continue; // Same field twice
7295  if (report_error != IGNORE_ERRORS)
7296  my_error(ER_NON_UNIQ_ERROR, MYF(0),
7297  find->full_name(), current_thd->where);
7298  return (Item**) 0;
7299  }
7300  found= li.ref();
7301  *counter= i;
7302  *resolution= fname_cmp ? RESOLVED_AGAINST_ALIAS:
7303  RESOLVED_WITH_NO_ALIAS;
7304  }
7305  else if (!fname_cmp)
7306  {
7307  /*
7308  We will use non-aliased field or react on such ambiguities only if
7309  we won't be able to find aliased field.
7310  Again if we have ambiguity with field outside of select list
7311  we should prefer fields from select list.
7312  */
7313  if (found_unaliased)
7314  {
7315  if ((*found_unaliased)->eq(item, 0))
7316  continue; // Same field twice
7317  found_unaliased_non_uniq= 1;
7318  }
7319  found_unaliased= li.ref();
7320  unaliased_counter= i;
7321  }
7322  }
7323  }
7324  else if (!table_name)
7325  {
7326  if (is_ref_by_name && item->item_name.eq_safe(find->item_name))
7327  {
7328  found= li.ref();
7329  *counter= i;
7330  *resolution= RESOLVED_AGAINST_ALIAS;
7331  break;
7332  }
7333  else if (find->eq(item,0))
7334  {
7335  found= li.ref();
7336  *counter= i;
7337  *resolution= RESOLVED_IGNORING_ALIAS;
7338  break;
7339  }
7340  }
7341  else if (table_name && item->type() == Item::REF_ITEM &&
7342  ((Item_ref *)item)->ref_type() == Item_ref::VIEW_REF)
7343  {
7344  /*
7345  TODO:Here we process prefixed view references only. What we should
7346  really do is process all types of Item_refs. But this will currently
7347  lead to a clash with the way references to outer SELECTs (from the
7348  HAVING clause) are handled in e.g. :
7349  SELECT 1 FROM t1 AS t1_o GROUP BY a
7350  HAVING (SELECT t1_o.a FROM t1 AS t1_i GROUP BY t1_i.a LIMIT 1).
7351  Processing all Item_refs here will cause t1_o.a to resolve to itself.
7352  We still need to process the special case of Item_direct_view_ref
7353  because in the context of views they have the same meaning as
7354  Item_field for tables.
7355  */
7356  Item_ident *item_ref= (Item_ident *) item;
7357  if (item_ref->item_name.eq_safe(field_name) &&
7358  item_ref->table_name &&
7359  !my_strcasecmp(table_alias_charset, item_ref->table_name,
7360  table_name) &&
7361  (!db_name || (item_ref->db_name &&
7362  !strcmp (item_ref->db_name, db_name))))
7363  {
7364  found= li.ref();
7365  *counter= i;
7366  *resolution= RESOLVED_IGNORING_ALIAS;
7367  break;
7368  }
7369  }
7370  }
7371  if (!found)
7372  {
7373  if (found_unaliased_non_uniq)
7374  {
7375  if (report_error != IGNORE_ERRORS)
7376  my_error(ER_NON_UNIQ_ERROR, MYF(0),
7377  find->full_name(), current_thd->where);
7378  return (Item **) 0;
7379  }
7380  if (found_unaliased)
7381  {
7382  found= found_unaliased;
7383  *counter= unaliased_counter;
7384  *resolution= RESOLVED_BEHIND_ALIAS;
7385  }
7386  }
7387  if (found)
7388  return found;
7389  if (report_error != REPORT_EXCEPT_NOT_FOUND)
7390  {
7391  if (report_error == REPORT_ALL_ERRORS)
7392  my_error(ER_BAD_FIELD_ERROR, MYF(0),
7393  find->full_name(), current_thd->where);
7394  return (Item **) 0;
7395  }
7396  else
7397  return (Item **) not_found_item;
7398 }
7399 
7400 
7401 /*
7402  Test if a string is a member of a list of strings.
7403 
7404  SYNOPSIS
7405  test_if_string_in_list()
7406  find the string to look for
7407  str_list a list of strings to be searched
7408 
7409  DESCRIPTION
7410  Sequentially search a list of strings for a string, and test whether
7411  the list contains the same string.
7412 
7413  RETURN
7414  TRUE if find is in str_list
7415  FALSE otherwise
7416 */
7417 
7418 static bool
7419 test_if_string_in_list(const char *find, List<String> *str_list)
7420 {
7421  List_iterator<String> str_list_it(*str_list);
7422  String *curr_str;
7423  size_t find_length= strlen(find);
7424  while ((curr_str= str_list_it++))
7425  {
7426  if (find_length != curr_str->length())
7427  continue;
7428  if (!my_strcasecmp(system_charset_info, find, curr_str->ptr()))
7429  return TRUE;
7430  }
7431  return FALSE;
7432 }
7433 
7434 
7435 /*
7436  Create a new name resolution context for an item so that it is
7437  being resolved in a specific table reference.
7438 
7439  SYNOPSIS
7440  set_new_item_local_context()
7441  thd pointer to current thread
7442  item item for which new context is created and set
7443  table_ref table ref where an item showld be resolved
7444 
7445  DESCRIPTION
7446  Create a new name resolution context for an item, so that the item
7447  is resolved only the supplied 'table_ref'.
7448 
7449  RETURN
7450  FALSE if all OK
7451  TRUE otherwise
7452 */
7453 
7454 static bool
7455 set_new_item_local_context(THD *thd, Item_ident *item, TABLE_LIST *table_ref)
7456 {
7457  Name_resolution_context *context;
7458  if (!(context= new (thd->mem_root) Name_resolution_context))
7459  return TRUE;
7460  context->init();
7461  context->first_name_resolution_table=
7462  context->last_name_resolution_table= table_ref;
7463  item->context= context;
7464  return FALSE;
7465 }
7466 
7467 
7468 /*
7469  Find and mark the common columns of two table references.
7470 
7471  SYNOPSIS
7472  mark_common_columns()
7473  thd [in] current thread
7474  table_ref_1 [in] the first (left) join operand
7475  table_ref_2 [in] the second (right) join operand
7476  using_fields [in] if the join is JOIN...USING - the join columns,
7477  if NATURAL join, then NULL
7478  found_using_fields [out] number of fields from the USING clause that were
7479  found among the common fields
7480 
7481  DESCRIPTION
7482  The procedure finds the common columns of two relations (either
7483  tables or intermediate join results), and adds an equi-join condition
7484  to the ON clause of 'table_ref_2' for each pair of matching columns.
7485  If some of table_ref_XXX represents a base table or view, then we
7486  create new 'Natural_join_column' instances for each column
7487  reference and store them in the 'join_columns' of the table
7488  reference.
7489 
7490  IMPLEMENTATION
7491  The procedure assumes that store_natural_using_join_columns() was
7492  called for the previous level of NATURAL/USING joins.
7493 
7494  RETURN
7495  TRUE error when some common column is non-unique, or out of memory
7496  FALSE OK
7497 */
7498 
7499 static bool
7500 mark_common_columns(THD *thd, TABLE_LIST *table_ref_1, TABLE_LIST *table_ref_2,
7501  List<String> *using_fields, uint *found_using_fields)
7502 {
7503  Field_iterator_table_ref it_1, it_2;
7504  Natural_join_column *nj_col_1, *nj_col_2;
7505  bool first_outer_loop= TRUE;
7506  /*
7507  Leaf table references to which new natural join columns are added
7508  if the leaves are != NULL.
7509  */
7510  TABLE_LIST *leaf_1= (table_ref_1->nested_join &&
7511  !table_ref_1->is_natural_join) ?
7512  NULL : table_ref_1;
7513  TABLE_LIST *leaf_2= (table_ref_2->nested_join &&
7514  !table_ref_2->is_natural_join) ?
7515  NULL : table_ref_2;
7516 
7517  DBUG_ENTER("mark_common_columns");
7518  DBUG_PRINT("info", ("operand_1: %s operand_2: %s",
7519  table_ref_1->alias, table_ref_2->alias));
7520 
7521  Prepared_stmt_arena_holder ps_arena_holder(thd);
7522 
7523  *found_using_fields= 0;
7524 
7525  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
7526  {
7527  bool found= FALSE;
7528  const char *field_name_1;
7529  /* true if field_name_1 is a member of using_fields */
7530  bool is_using_column_1;
7531  if (!(nj_col_1= it_1.get_or_create_column_ref(thd, leaf_1)))
7532  DBUG_RETURN(true);
7533  field_name_1= nj_col_1->name();
7534  is_using_column_1= using_fields &&
7535  test_if_string_in_list(field_name_1, using_fields);
7536  DBUG_PRINT ("info", ("field_name_1=%s.%s",
7537  nj_col_1->table_name() ? nj_col_1->table_name() : "",
7538  field_name_1));
7539 
7540  /*
7541  Find a field with the same name in table_ref_2.
7542 
7543  Note that for the second loop, it_2.set() will iterate over
7544  table_ref_2->join_columns and not generate any new elements or
7545  lists.
7546  */
7547  nj_col_2= NULL;
7548  for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next())
7549  {
7550  Natural_join_column *cur_nj_col_2;
7551  const char *cur_field_name_2;
7552  if (!(cur_nj_col_2= it_2.get_or_create_column_ref(thd, leaf_2)))
7553  DBUG_RETURN(true);
7554  cur_field_name_2= cur_nj_col_2->name();
7555  DBUG_PRINT ("info", ("cur_field_name_2=%s.%s",
7556  cur_nj_col_2->table_name() ?
7557  cur_nj_col_2->table_name() : "",
7558  cur_field_name_2));
7559 
7560  /*
7561  Compare the two columns and check for duplicate common fields.
7562  A common field is duplicate either if it was already found in
7563  table_ref_2 (then found == TRUE), or if a field in table_ref_2
7564  was already matched by some previous field in table_ref_1
7565  (then cur_nj_col_2->is_common == TRUE).
7566  Note that it is too early to check the columns outside of the
7567  USING list for ambiguity because they are not actually "referenced"
7568  here. These columns must be checked only on unqualified reference
7569  by name (e.g. in SELECT list).
7570  */
7571  if (!my_strcasecmp(system_charset_info, field_name_1, cur_field_name_2))
7572  {
7573  DBUG_PRINT ("info", ("match c1.is_common=%d", nj_col_1->is_common));
7574  if (cur_nj_col_2->is_common ||
7575  (found && (!using_fields || is_using_column_1)))
7576  {
7577  my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, thd->where);
7578  DBUG_RETURN(true);
7579  }
7580  nj_col_2= cur_nj_col_2;
7581  found= TRUE;
7582  }
7583  }
7584  if (first_outer_loop && leaf_2)
7585  {
7586  /*
7587  Make sure that the next inner loop "knows" that all columns
7588  are materialized already.
7589  */
7590  leaf_2->is_join_columns_complete= TRUE;
7591  first_outer_loop= FALSE;
7592  }
7593  if (!found)
7594  continue; // No matching field
7595 
7596  /*
7597  field_1 and field_2 have the same names. Check if they are in the USING
7598  clause (if present), mark them as common fields, and add a new
7599  equi-join condition to the ON clause.
7600  */
7601  if (nj_col_2 && (!using_fields ||is_using_column_1))
7602  {
7603  Item *item_1= nj_col_1->create_item(thd);
7604  Item *item_2= nj_col_2->create_item(thd);
7605  Field *field_1= nj_col_1->field();
7606  Field *field_2= nj_col_2->field();
7607  Item_ident *item_ident_1, *item_ident_2;
7608  Item_func_eq *eq_cond;
7609 
7610  if (!item_1 || !item_2)
7611  DBUG_RETURN(true); // Out of memory.
7612 
7613  /*
7614  The following assert checks that the two created items are of
7615  type Item_ident.
7616  */
7617  DBUG_ASSERT(!thd->lex->current_select->no_wrap_view_item);
7618  /*
7619  In the case of no_wrap_view_item == 0, the created items must be
7620  of sub-classes of Item_ident.
7621  */
7622  DBUG_ASSERT(item_1->type() == Item::FIELD_ITEM ||
7623  item_1->type() == Item::REF_ITEM);
7624  DBUG_ASSERT(item_2->type() == Item::FIELD_ITEM ||
7625  item_2->type() == Item::REF_ITEM);
7626 
7627  /*
7628  We need to cast item_1,2 to Item_ident, because we need to hook name
7629  resolution contexts specific to each item.
7630  */
7631  item_ident_1= (Item_ident*) item_1;
7632  item_ident_2= (Item_ident*) item_2;
7633  /*
7634  Create and hook special name resolution contexts to each item in the
7635  new join condition . We need this to both speed-up subsequent name
7636  resolution of these items, and to enable proper name resolution of
7637  the items during the execute phase of PS.
7638  */
7639  if (set_new_item_local_context(thd, item_ident_1, nj_col_1->table_ref) ||
7640  set_new_item_local_context(thd, item_ident_2, nj_col_2->table_ref))
7641  DBUG_RETURN(true);
7642 
7643  if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
7644  DBUG_RETURN(true); // Out of memory.
7645 
7646  /*
7647  Add the new equi-join condition to the ON clause. Notice that
7648  fix_fields() is applied to all ON conditions in setup_conds()
7649  so we don't do it here.
7650  */
7651  add_join_on((table_ref_1->outer_join & JOIN_TYPE_RIGHT ?
7652  table_ref_1 : table_ref_2),
7653  eq_cond);
7654 
7655  nj_col_1->is_common= nj_col_2->is_common= TRUE;
7656  DBUG_PRINT ("info", ("%s.%s and %s.%s are common",
7657  nj_col_1->table_name() ?
7658  nj_col_1->table_name() : "",
7659  nj_col_1->name(),
7660  nj_col_2->table_name() ?
7661  nj_col_2->table_name() : "",
7662  nj_col_2->name()));
7663 
7664  if (field_1)
7665  {
7666  TABLE *table_1= nj_col_1->table_ref->table;
7667  /* Mark field_1 used for table cache. */
7668  bitmap_set_bit(table_1->read_set, field_1->field_index);
7669  table_1->covering_keys.intersect(field_1->part_of_key);
7670  table_1->merge_keys.merge(field_1->part_of_key);
7671  }
7672  if (field_2)
7673  {
7674  TABLE *table_2= nj_col_2->table_ref->table;
7675  /* Mark field_2 used for table cache. */
7676  bitmap_set_bit(table_2->read_set, field_2->field_index);
7677  table_2->covering_keys.intersect(field_2->part_of_key);
7678  table_2->merge_keys.merge(field_2->part_of_key);
7679  }
7680 
7681  if (using_fields != NULL)
7682  ++(*found_using_fields);
7683  }
7684  }
7685  if (leaf_1)
7686  leaf_1->is_join_columns_complete= TRUE;
7687 
7688  /*
7689  Everything is OK.
7690  Notice that at this point there may be some column names in the USING
7691  clause that are not among the common columns. This is an SQL error and
7692  we check for this error in store_natural_using_join_columns() when
7693  (found_using_fields < length(join_using_fields)).
7694  */
7695  DBUG_RETURN(false);
7696 }
7697 
7698 
7699 
7700 /*
7701  Materialize and store the row type of NATURAL/USING join.
7702 
7703  SYNOPSIS
7704  store_natural_using_join_columns()
7705  thd current thread
7706  natural_using_join the table reference of the NATURAL/USING join
7707  table_ref_1 the first (left) operand (of a NATURAL/USING join).
7708  table_ref_2 the second (right) operand (of a NATURAL/USING join).
7709  using_fields if the join is JOIN...USING - the join columns,
7710  if NATURAL join, then NULL
7711  found_using_fields number of fields from the USING clause that were
7712  found among the common fields
7713 
7714  DESCRIPTION
7715  Iterate over the columns of both join operands and sort and store
7716  all columns into the 'join_columns' list of natural_using_join
7717  where the list is formed by three parts:
7718  part1: The coalesced columns of table_ref_1 and table_ref_2,
7719  sorted according to the column order of the first table.
7720  part2: The other columns of the first table, in the order in
7721  which they were defined in CREATE TABLE.
7722  part3: The other columns of the second table, in the order in
7723  which they were defined in CREATE TABLE.
7724  Time complexity - O(N1+N2), where Ni = length(table_ref_i).
7725 
7726  IMPLEMENTATION
7727  The procedure assumes that mark_common_columns() has been called
7728  for the join that is being processed.
7729 
7730  RETURN
7731  TRUE error: Some common column is ambiguous
7732  FALSE OK
7733 */
7734 
7735 static bool
7736 store_natural_using_join_columns(THD *thd, TABLE_LIST *natural_using_join,
7737  TABLE_LIST *table_ref_1,
7738  TABLE_LIST *table_ref_2,
7739  List<String> *using_fields,
7740  uint found_using_fields)
7741 {
7742  Field_iterator_table_ref it_1, it_2;
7743  Natural_join_column *nj_col_1, *nj_col_2;
7744  List<Natural_join_column> *non_join_columns;
7745  DBUG_ENTER("store_natural_using_join_columns");
7746 
7747  DBUG_ASSERT(!natural_using_join->join_columns);
7748 
7749  Prepared_stmt_arena_holder ps_arena_holder(thd);
7750 
7751  if (!(non_join_columns= new List<Natural_join_column>) ||
7752  !(natural_using_join->join_columns= new List<Natural_join_column>))
7753  DBUG_RETURN(true);
7754 
7755  /* Append the columns of the first join operand. */
7756  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
7757  {
7758  nj_col_1= it_1.get_natural_column_ref();
7759  if (nj_col_1->is_common)
7760  {
7761  natural_using_join->join_columns->push_back(nj_col_1);
7762  /* Reset the common columns for the next call to mark_common_columns. */
7763  nj_col_1->is_common= FALSE;
7764  }
7765  else
7766  non_join_columns->push_back(nj_col_1);
7767  }
7768 
7769  /*
7770  Check that all columns in the USING clause are among the common
7771  columns. If this is not the case, report the first one that was
7772  not found in an error.
7773  */
7774  if (using_fields && found_using_fields < using_fields->elements)
7775  {
7776  String *using_field_name;
7777  List_iterator_fast<String> using_fields_it(*using_fields);
7778  while ((using_field_name= using_fields_it++))
7779  {
7780  const char *using_field_name_ptr= using_field_name->c_ptr();
7782  it(*(natural_using_join->join_columns));
7783  Natural_join_column *common_field;
7784 
7785  for (;;)
7786  {
7787  /* If reached the end of fields, and none was found, report error. */
7788  if (!(common_field= it++))
7789  {
7790  my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
7791  current_thd->where);
7792  DBUG_RETURN(true);
7793  }
7794  if (!my_strcasecmp(system_charset_info,
7795  common_field->name(), using_field_name_ptr))
7796  break; // Found match
7797  }
7798  }
7799  }
7800 
7801  /* Append the non-equi-join columns of the second join operand. */
7802  for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next())
7803  {
7804  nj_col_2= it_2.get_natural_column_ref();
7805  if (!nj_col_2->is_common)
7806  non_join_columns->push_back(nj_col_2);
7807  else
7808  {
7809  /* Reset the common columns for the next call to mark_common_columns. */
7810  nj_col_2->is_common= FALSE;
7811  }
7812  }
7813 
7814  if (non_join_columns->elements > 0)
7815  natural_using_join->join_columns->concat(non_join_columns);
7816  natural_using_join->is_join_columns_complete= TRUE;
7817 
7818  DBUG_RETURN(false);
7819 }
7820 
7821 
7822 /*
7823  Precompute and store the row types of the top-most NATURAL/USING joins.
7824 
7825  SYNOPSIS
7826  store_top_level_join_columns()
7827  thd current thread
7828  table_ref nested join or table in a FROM clause
7829  left_neighbor neighbor table reference to the left of table_ref at the
7830  same level in the join tree
7831  right_neighbor neighbor table reference to the right of table_ref at the
7832  same level in the join tree
7833 
7834  DESCRIPTION
7835  The procedure performs a post-order traversal of a nested join tree
7836  and materializes the row types of NATURAL/USING joins in a
7837  bottom-up manner until it reaches the TABLE_LIST elements that
7838  represent the top-most NATURAL/USING joins. The procedure should be
7839  applied to each element of SELECT_LEX::top_join_list (i.e. to each
7840  top-level element of the FROM clause).
7841 
7842  IMPLEMENTATION
7843  Notice that the table references in the list nested_join->join_list
7844  are in reverse order, thus when we iterate over it, we are moving
7845  from the right to the left in the FROM clause.
7846 
7847  RETURN
7848  TRUE Error
7849  FALSE OK
7850 */
7851 
7852 static bool
7853 store_top_level_join_columns(THD *thd, TABLE_LIST *table_ref,
7854  TABLE_LIST *left_neighbor,
7855  TABLE_LIST *right_neighbor)
7856 {
7857  DBUG_ENTER("store_top_level_join_columns");
7858 
7859  Prepared_stmt_arena_holder ps_arena_holder(thd);
7860 
7861  /* Call the procedure recursively for each nested table reference. */
7862  if (table_ref->nested_join)
7863  {
7864  List_iterator_fast<TABLE_LIST> nested_it(table_ref->nested_join->join_list);
7865  TABLE_LIST *same_level_left_neighbor= nested_it++;
7866  TABLE_LIST *same_level_right_neighbor= NULL;
7867  /* Left/right-most neighbors, possibly at higher levels in the join tree. */
7868  TABLE_LIST *real_left_neighbor, *real_right_neighbor;
7869 
7870  while (same_level_left_neighbor)
7871  {
7872  TABLE_LIST *cur_table_ref= same_level_left_neighbor;
7873  same_level_left_neighbor= nested_it++;
7874  /*
7875  The order of RIGHT JOIN operands is reversed in 'join list' to
7876  transform it into a LEFT JOIN. However, in this procedure we need
7877  the join operands in their lexical order, so below we reverse the
7878  join operands. Notice that this happens only in the first loop,
7879  and not in the second one, as in the second loop
7880  same_level_left_neighbor == NULL.
7881  This is the correct behavior, because the second loop sets
7882  cur_table_ref reference correctly after the join operands are
7883  swapped in the first loop.
7884  */
7885  if (same_level_left_neighbor &&
7886  cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
7887  {
7888  /* This can happen only for JOIN ... ON. */
7889  DBUG_ASSERT(table_ref->nested_join->join_list.elements == 2);
7890  swap_variables(TABLE_LIST*, same_level_left_neighbor, cur_table_ref);
7891  }
7892 
7893  /*
7894  Pick the parent's left and right neighbors if there are no immediate
7895  neighbors at the same level.
7896  */
7897  real_left_neighbor= (same_level_left_neighbor) ?
7898  same_level_left_neighbor : left_neighbor;
7899  real_right_neighbor= (same_level_right_neighbor) ?
7900  same_level_right_neighbor : right_neighbor;
7901 
7902  if (cur_table_ref->nested_join &&
7903  store_top_level_join_columns(thd, cur_table_ref,
7904  real_left_neighbor, real_right_neighbor))
7905  DBUG_RETURN(true);
7906  same_level_right_neighbor= cur_table_ref;
7907  }
7908  }
7909 
7910  /*
7911  If this is a NATURAL/USING join, materialize its result columns and
7912  convert to a JOIN ... ON.
7913  */
7914  if (table_ref->is_natural_join)
7915  {
7916  DBUG_ASSERT(table_ref->nested_join &&
7917  table_ref->nested_join->join_list.elements == 2);
7918  List_iterator_fast<TABLE_LIST> operand_it(table_ref->nested_join->join_list);
7919  /*
7920  Notice that the order of join operands depends on whether table_ref
7921  represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
7922  in inverted order.
7923  */
7924  TABLE_LIST *table_ref_2= operand_it++; /* Second NATURAL join operand.*/
7925  TABLE_LIST *table_ref_1= operand_it++; /* First NATURAL join operand. */
7926  List<String> *using_fields= table_ref->join_using_fields;
7927  uint found_using_fields;
7928 
7929  /*
7930  The two join operands were interchanged in the parser, change the order
7931  back for 'mark_common_columns'.
7932  */
7933  if (table_ref_2->outer_join & JOIN_TYPE_RIGHT)
7934  swap_variables(TABLE_LIST*, table_ref_1, table_ref_2);
7935  if (mark_common_columns(thd, table_ref_1, table_ref_2,
7936  using_fields, &found_using_fields))
7937  DBUG_RETURN(true);
7938 
7939  /*
7940  Swap the join operands back, so that we pick the columns of the second
7941  one as the coalesced columns. In this way the coalesced columns are the
7942  same as of an equivalent LEFT JOIN.
7943  */
7944  if (table_ref_1->outer_join & JOIN_TYPE_RIGHT)
7945  swap_variables(TABLE_LIST*, table_ref_1, table_ref_2);
7946  if (store_natural_using_join_columns(thd, table_ref, table_ref_1,
7947  table_ref_2, using_fields,
7948  found_using_fields))
7949  DBUG_RETURN(true);
7950 
7951  /*
7952  Change NATURAL JOIN to JOIN ... ON. We do this for both operands
7953  because either one of them or the other is the one with the
7954  natural join flag because RIGHT joins are transformed into LEFT,
7955  and the two tables may be reordered.
7956  */
7957  table_ref_1->natural_join= table_ref_2->natural_join= NULL;
7958 
7959  /* Add a TRUE condition to outer joins that have no common columns. */
7960  if (table_ref_2->outer_join &&
7961  !table_ref_1->join_cond() && !table_ref_2->join_cond())
7962  table_ref_2->set_join_cond(new Item_int((longlong) 1,1)); // Always true.
7963 
7964  /* Change this table reference to become a leaf for name resolution. */
7965  if (left_neighbor)
7966  {
7967  TABLE_LIST *last_leaf_on_the_left;
7968  last_leaf_on_the_left= left_neighbor->last_leaf_for_name_resolution();
7969  last_leaf_on_the_left->next_name_resolution_table= table_ref;
7970  }
7971  if (right_neighbor)
7972  {
7973  TABLE_LIST *first_leaf_on_the_right;
7974  first_leaf_on_the_right= right_neighbor->first_leaf_for_name_resolution();
7975  table_ref->next_name_resolution_table= first_leaf_on_the_right;
7976  }
7977  else
7978  table_ref->next_name_resolution_table= NULL;
7979  }
7980 
7981  DBUG_RETURN(false);
7982 }
7983 
7984 
7985 /*
7986  Compute and store the row types of the top-most NATURAL/USING joins
7987  in a FROM clause.
7988 
7989  SYNOPSIS
7990  setup_natural_join_row_types()
7991  thd current thread
7992  from_clause list of top-level table references in a FROM clause
7993 
7994  DESCRIPTION
7995  Apply the procedure 'store_top_level_join_columns' to each of the
7996  top-level table referencs of the FROM clause. Adjust the list of tables
7997  for name resolution - context->first_name_resolution_table to the
7998  top-most, lef-most NATURAL/USING join.
7999 
8000  IMPLEMENTATION
8001  Notice that the table references in 'from_clause' are in reverse
8002  order, thus when we iterate over it, we are moving from the right
8003  to the left in the FROM clause.
8004 
8005  RETURN
8006  TRUE Error
8007  FALSE OK
8008 */
8009 static bool setup_natural_join_row_types(THD *thd,
8010  List<TABLE_LIST> *from_clause,
8011  Name_resolution_context *context)
8012 {
8013  DBUG_ENTER("setup_natural_join_row_types");
8014  thd->where= "from clause";
8015  if (from_clause->elements == 0)
8016  DBUG_RETURN(false); /* We come here in the case of UNIONs. */
8017 
8018  List_iterator_fast<TABLE_LIST> table_ref_it(*from_clause);
8019  TABLE_LIST *table_ref; /* Current table reference. */
8020  /* Table reference to the left of the current. */
8021  TABLE_LIST *left_neighbor;
8022  /* Table reference to the right of the current. */
8023  TABLE_LIST *right_neighbor= NULL;
8024 
8025  /* Note that tables in the list are in reversed order */
8026  for (left_neighbor= table_ref_it++; left_neighbor ; )
8027  {
8028  table_ref= left_neighbor;
8029  left_neighbor= table_ref_it++;
8030  /*
8031  Do not redo work if already done:
8032  1) for stored procedures,
8033  2) for multitable update after lock failure and table reopening.
8034  */
8035  if (context->select_lex->first_natural_join_processing)
8036  {
8037  if (store_top_level_join_columns(thd, table_ref,
8038  left_neighbor, right_neighbor))
8039  DBUG_RETURN(true);
8040  if (left_neighbor)
8041  {
8042  TABLE_LIST *first_leaf_on_the_right;
8043  first_leaf_on_the_right= table_ref->first_leaf_for_name_resolution();
8044  left_neighbor->next_name_resolution_table= first_leaf_on_the_right;
8045  }
8046  }
8047  right_neighbor= table_ref;
8048  }
8049 
8050  /*
8051  Store the top-most, left-most NATURAL/USING join, so that we start
8052  the search from that one instead of context->table_list. At this point
8053  right_neighbor points to the left-most top-level table reference in the
8054  FROM clause.
8055  */
8056  DBUG_ASSERT(right_neighbor);
8057  context->first_name_resolution_table=
8058  right_neighbor->first_leaf_for_name_resolution();
8059  context->select_lex->first_natural_join_processing= false;
8060 
8061  DBUG_RETURN (false);
8062 }
8063 
8064 
8065 /****************************************************************************
8066 ** Expand all '*' in given fields
8067 ****************************************************************************/
8068 
8069 int setup_wild(THD *thd, TABLE_LIST *tables, List<Item> &fields,
8070  List<Item> *sum_func_list,
8071  uint wild_num)
8072 {
8073  if (!wild_num)
8074  return(0);
8075 
8076  Item *item;
8077  List_iterator<Item> it(fields);
8078  DBUG_ENTER("setup_wild");
8079 
8080  /*
8081  Don't use arena if we are not in prepared statements or stored procedures
8082  For PS/SP we have to use arena to remember the changes
8083  */
8084  Prepared_stmt_arena_holder ps_arena_holder(thd);
8085 
8086  // When we enter, we're "nowhere":
8087  DBUG_ASSERT(thd->lex->current_select->cur_pos_in_all_fields ==
8088  SELECT_LEX::ALL_FIELDS_UNDEF_POS);
8089  // Now we're in the SELECT list:
8090  thd->lex->current_select->cur_pos_in_all_fields= 0;
8091  while (wild_num && (item= it++))
8092  {
8093  if (item->type() == Item::FIELD_ITEM &&
8094  ((Item_field*) item)->field_name &&
8095  ((Item_field*) item)->field_name[0] == '*' &&
8096  !((Item_field*) item)->field)
8097  {
8098  uint elem= fields.elements;
8099  bool any_privileges= ((Item_field *) item)->any_privileges;
8100  Item_subselect *subsel= thd->lex->current_select->master_unit()->item;
8101  if (subsel &&
8102  subsel->substype() == Item_subselect::EXISTS_SUBS)
8103  {
8104  /*
8105  It is EXISTS(SELECT * ...) and we can replace * by any constant.
8106 
8107  Item_int do not need fix_fields() because it is basic constant.
8108  */
8109  it.replace(new Item_int(NAME_STRING("Not_used"), (longlong) 1,
8110  MY_INT64_NUM_DECIMAL_DIGITS));
8111  }
8112  else if (insert_fields(thd, ((Item_field*) item)->context,
8113  ((Item_field*) item)->db_name,
8114  ((Item_field*) item)->table_name, &it,
8115  any_privileges))
8116  {
8117  DBUG_RETURN(-1);
8118  }
8119  if (sum_func_list)
8120  {
8121  /*
8122  sum_func_list is a list that has the fields list as a tail.
8123  Because of this we have to update the element count also for this
8124  list after expanding the '*' entry.
8125  */
8126  sum_func_list->elements+= fields.elements - elem;
8127  }
8128  wild_num--;
8129  }
8130  else
8131  thd->lex->current_select->cur_pos_in_all_fields++;
8132  }
8133  // We're nowhere again:
8134  thd->lex->current_select->cur_pos_in_all_fields=
8135  SELECT_LEX::ALL_FIELDS_UNDEF_POS;
8136 
8137  if (ps_arena_holder.is_activated())
8138  {
8139  /* make * substituting permanent */
8140  SELECT_LEX *select_lex= thd->lex->current_select;
8141  select_lex->with_wild= 0;
8142  /*
8143  The assignment below is translated to memcpy() call (at least on some
8144  platforms). memcpy() expects that source and destination areas do not
8145  overlap. That problem was detected by valgrind.
8146  */
8147  if (&select_lex->item_list != &fields)
8148  select_lex->item_list= fields;
8149  }
8150  DBUG_RETURN(0);
8151 }
8152 
8153 /****************************************************************************
8154 ** Check that all given fields exists and fill struct with current data
8155 ****************************************************************************/
8156 
8157 bool setup_fields(THD *thd, Ref_ptr_array ref_pointer_array,
8158  List<Item> &fields, enum_mark_columns mark_used_columns,
8159  List<Item> *sum_func_list, bool allow_sum_func)
8160 {
8161  reg2 Item *item;
8162  enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
8163  nesting_map save_allow_sum_func= thd->lex->allow_sum_func;
8164  List_iterator<Item> it(fields);
8165  bool save_is_item_list_lookup;
8166  DBUG_ENTER("setup_fields");
8167 
8168  thd->mark_used_columns= mark_used_columns;
8169  DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
8170  if (allow_sum_func)
8171  thd->lex->allow_sum_func|=
8172  (nesting_map)1 << thd->lex->current_select->nest_level;
8173  thd->where= THD::DEFAULT_WHERE;
8174  save_is_item_list_lookup= thd->lex->current_select->is_item_list_lookup;
8175  thd->lex->current_select->is_item_list_lookup= 0;
8176 
8177  /*
8178  To prevent fail on forward lookup we fill it with zerows,
8179  then if we got pointer on zero after find_item_in_list we will know
8180  that it is forward lookup.
8181 
8182  There is other way to solve problem: fill array with pointers to list,
8183  but it will be slower.
8184 
8185  TODO: remove it when (if) we made one list for allfields and
8186  ref_pointer_array
8187  */
8188  if (!ref_pointer_array.is_null())
8189  {
8190  DBUG_ASSERT(ref_pointer_array.size() >= fields.elements);
8191  memset(ref_pointer_array.array(), 0, sizeof(Item *) * fields.elements);
8192  }
8193 
8194  /*
8195  We call set_entry() there (before fix_fields() of the whole list of field
8196  items) because:
8197  1) the list of field items has same order as in the query, and the
8198  Item_func_get_user_var item may go before the Item_func_set_user_var:
8199  SELECT @a, @a := 10 FROM t;
8200  2) The entry->update_query_id value controls constantness of
8201  Item_func_get_user_var items, so in presence of Item_func_set_user_var
8202  items we have to refresh their entries before fixing of
8203  Item_func_get_user_var items.
8204  */
8205  List_iterator<Item_func_set_user_var> li(thd->lex->set_var_list);
8207  while ((var= li++))
8208  var->set_entry(thd, FALSE);
8209 
8210  Ref_ptr_array ref= ref_pointer_array;
8211  DBUG_ASSERT(thd->lex->current_select->cur_pos_in_all_fields ==
8212  SELECT_LEX::ALL_FIELDS_UNDEF_POS);
8213  thd->lex->current_select->cur_pos_in_all_fields= 0;
8214  while ((item= it++))
8215  {
8216  if ((!item->fixed && item->fix_fields(thd, it.ref())) ||
8217  (item= *(it.ref()))->check_cols(1))
8218  {
8219  thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
8220  thd->lex->allow_sum_func= save_allow_sum_func;
8221  thd->mark_used_columns= save_mark_used_columns;
8222  DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
8223  DBUG_RETURN(TRUE); /* purecov: inspected */
8224  }
8225  if (!ref.is_null())
8226  {
8227  ref[0]= item;
8228  ref.pop_front();
8229  }
8230  if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM &&
8231  sum_func_list)
8232  item->split_sum_func(thd, ref_pointer_array, *sum_func_list);
8233  thd->lex->current_select->select_list_tables|= item->used_tables();
8234  thd->lex->used_tables|= item->used_tables();
8235  thd->lex->current_select->cur_pos_in_all_fields++;
8236  }
8237  thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
8238  thd->lex->current_select->cur_pos_in_all_fields=
8239  SELECT_LEX::ALL_FIELDS_UNDEF_POS;
8240 
8241  thd->lex->allow_sum_func= save_allow_sum_func;
8242  thd->mark_used_columns= save_mark_used_columns;
8243  DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
8244  DBUG_RETURN(test(thd->is_error()));
8245 }
8246 
8247 
8248 /*
8249  make list of leaves of join table tree
8250 
8251  SYNOPSIS
8252  make_leaves_list()
8253  list pointer to pointer on list first element
8254  tables table list
8255 
8256  RETURN pointer on pointer to next_leaf of last element
8257 */
8258 
8259 TABLE_LIST **make_leaves_list(TABLE_LIST **list, TABLE_LIST *tables)
8260 {
8261  for (TABLE_LIST *table= tables; table; table= table->next_local)
8262  {
8263  if (table->merge_underlying_list)
8264  {
8265  DBUG_ASSERT(table->view &&
8266  table->effective_algorithm == VIEW_ALGORITHM_MERGE);
8267  list= make_leaves_list(list, table->merge_underlying_list);
8268  }
8269  else
8270  {
8271  *list= table;
8272  list= &table->next_leaf;
8273  }
8274  }
8275  return list;
8276 }
8277 
8278 /*
8279  prepare tables
8280 
8281  SYNOPSIS
8282  setup_tables()
8283  thd Thread handler
8284  context name resolution contest to setup table list there
8285  from_clause Top-level list of table references in the FROM clause
8286  tables Table list (select_lex->table_list)
8287  leaves List of join table leaves list (select_lex->leaf_tables)
8288  refresh It is onle refresh for subquery
8289  select_insert It is SELECT ... INSERT command
8290 
8291  NOTE
8292  Check also that the 'used keys' and 'ignored keys' exists and set up the
8293  table structure accordingly.
8294  Create a list of leaf tables. For queries with NATURAL/USING JOINs,
8295  compute the row types of the top most natural/using join table references
8296  and link these into a list of table references for name resolution.
8297 
8298  This has to be called for all tables that are used by items, as otherwise
8299  table->map is not set and all Item_field will be regarded as const items.
8300 
8301  RETURN
8302  FALSE ok; In this case *map will includes the chosen index
8303  TRUE error
8304 */
8305 
8306 bool setup_tables(THD *thd, Name_resolution_context *context,
8307  List<TABLE_LIST> *from_clause, TABLE_LIST *tables,
8308  TABLE_LIST **leaves, bool select_insert)
8309 {
8310  uint tablenr= 0;
8311  DBUG_ENTER("setup_tables");
8312 
8313  DBUG_ASSERT ((select_insert && !tables->next_name_resolution_table) || !tables ||
8314  (context->table_list && context->first_name_resolution_table));
8315  /*
8316  this is used for INSERT ... SELECT.
8317  For select we setup tables except first (and its underlying tables)
8318  */
8319  TABLE_LIST *first_select_table= (select_insert ?
8320  tables->next_local:
8321  0);
8322  if (!(*leaves))
8323  make_leaves_list(leaves, tables);
8324 
8325  TABLE_LIST *table_list;
8326  for (table_list= *leaves;
8327  table_list;
8328  table_list= table_list->next_leaf, tablenr++)
8329  {
8330  TABLE *table= table_list->table;
8331  table->pos_in_table_list= table_list;
8332  if (first_select_table &&
8333  table_list->top_table() == first_select_table)
8334  {
8335  /* new counting for SELECT of INSERT ... SELECT command */
8336  first_select_table= 0;
8337  tablenr= 0;
8338  }
8339  setup_table_map(table, table_list, tablenr);
8340  if (table_list->process_index_hints(table))
8341  DBUG_RETURN(1);
8342  }
8343  if (tablenr > MAX_TABLES)
8344  {
8345  my_error(ER_TOO_MANY_TABLES,MYF(0), static_cast<int>(MAX_TABLES));
8346  DBUG_RETURN(1);
8347  }
8348  for (table_list= tables;
8349  table_list;
8350  table_list= table_list->next_local)
8351  {
8352  if (table_list->merge_underlying_list)
8353  {
8354  DBUG_ASSERT(table_list->view &&
8355  table_list->effective_algorithm == VIEW_ALGORITHM_MERGE);
8356 
8357  Prepared_stmt_arena_holder ps_arena_holder(thd);
8358  if (table_list->setup_underlying(thd))
8359  DBUG_RETURN(1);
8360  }
8361  }
8362 
8363  /* Precompute and store the row types of NATURAL/USING joins. */
8364  if (setup_natural_join_row_types(thd, from_clause, context))
8365  DBUG_RETURN(1);
8366 
8367  DBUG_RETURN(0);
8368 }
8369 
8370 
8399  Name_resolution_context *context,
8400  List<TABLE_LIST> *from_clause,
8401  TABLE_LIST *tables,
8402  TABLE_LIST **leaves,
8403  bool select_insert,
8404  ulong want_access_first,
8405  ulong want_access)
8406 {
8407  TABLE_LIST *leaves_tmp= NULL;
8408  bool first_table= true;
8409 
8410  if (setup_tables(thd, context, from_clause, tables,
8411  &leaves_tmp, select_insert))
8412  return TRUE;
8413 
8414  if (leaves)
8415  *leaves= leaves_tmp;
8416 
8417  for (; leaves_tmp; leaves_tmp= leaves_tmp->next_leaf)
8418  {
8419  if (leaves_tmp->belong_to_view &&
8420  check_single_table_access(thd, first_table ? want_access_first :
8421  want_access, leaves_tmp, FALSE))
8422  {
8423  tables->hide_view_error(thd);
8424  return TRUE;
8425  }
8426  first_table= 0;
8427  }
8428  return FALSE;
8429 }
8430 
8431 
8432 /*
8433  Drops in all fields instead of current '*' field
8434 
8435  SYNOPSIS
8436  insert_fields()
8437  thd Thread handler
8438  context Context for name resolution
8439  db_name Database name in case of 'database_name.table_name.*'
8440  table_name Table name in case of 'table_name.*'
8441  it Pointer to '*'
8442  any_privileges 0 If we should ensure that we have SELECT privileges
8443  for all columns
8444  1 If any privilege is ok
8445  RETURN
8446  0 ok 'it' is updated to point at last inserted
8447  1 error. Error message is generated but not sent to client
8448 */
8449 
8450 bool
8451 insert_fields(THD *thd, Name_resolution_context *context, const char *db_name,
8452  const char *table_name, List_iterator<Item> *it,
8453  bool any_privileges)
8454 {
8455  Field_iterator_table_ref field_iterator;
8456  bool found;
8457  char name_buff[NAME_LEN+1];
8458  DBUG_ENTER("insert_fields");
8459  DBUG_PRINT("arena", ("stmt arena: 0x%lx", (ulong)thd->stmt_arena));
8460 
8461  if (db_name && lower_case_table_names)
8462  {
8463  /*
8464  convert database to lower case for comparison
8465  We can't do this in Item_field as this would change the
8466  'name' of the item which may be used in the select list
8467  */
8468  strmake(name_buff, db_name, sizeof(name_buff)-1);
8469  my_casedn_str(files_charset_info, name_buff);
8470  db_name= name_buff;
8471  }
8472 
8473  found= FALSE;
8474 
8475  /*
8476  If table names are qualified, then loop over all tables used in the query,
8477  else treat natural joins as leaves and do not iterate over their underlying
8478  tables.
8479  */
8480  for (TABLE_LIST *tables= (table_name ? context->table_list :
8481  context->first_name_resolution_table);
8482  tables;
8483  tables= (table_name ? tables->next_local :
8484  tables->next_name_resolution_table)
8485  )
8486  {
8487  Field *field;
8488  TABLE *table= tables->table;
8489 
8490  DBUG_ASSERT(tables->is_leaf_for_name_resolution());
8491 
8492  if ((table_name && my_strcasecmp(table_alias_charset, table_name,
8493  tables->alias)) ||
8494  (db_name && strcmp(tables->db,db_name)))
8495  continue;
8496 
8497 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8498  /*
8499  Ensure that we have access rights to all fields to be inserted. Under
8500  some circumstances, this check may be skipped.
8501 
8502  - If any_privileges is true, skip the check.
8503 
8504  - If the SELECT privilege has been found as fulfilled already for both
8505  the TABLE and TABLE_LIST objects (and both of these exist, of
8506  course), the check is skipped.
8507 
8508  - If the SELECT privilege has been found fulfilled for the TABLE object
8509  and the TABLE_LIST represents a derived table other than a view (see
8510  below), the check is skipped.
8511 
8512  - If the TABLE_LIST object represents a view, we may skip checking if
8513  the SELECT privilege has been found fulfilled for it, regardless of
8514  the TABLE object.
8515 
8516  - If there is no TABLE object, the test is skipped if either
8517  * the TABLE_LIST does not represent a view, or
8518  * the SELECT privilege has been found fulfilled.
8519 
8520  A TABLE_LIST that is not a view may be a subquery, an
8521  information_schema table, or a nested table reference. See the comment
8522  for TABLE_LIST.
8523  */
8524  if (!((table && !tables->view && (table->grant.privilege & SELECT_ACL)) ||
8525  (tables->view && (tables->grant.privilege & SELECT_ACL))) &&
8526  !any_privileges)
8527  {
8528  field_iterator.set(tables);
8529  if (check_grant_all_columns(thd, SELECT_ACL, &field_iterator))
8530  DBUG_RETURN(TRUE);
8531  }
8532 #endif
8533 
8534  /*
8535  Update the tables used in the query based on the referenced fields. For
8536  views and natural joins this update is performed inside the loop below.
8537  */
8538  if (table)
8539  {
8540  thd->lex->used_tables|= table->map;
8541  thd->lex->current_select->select_list_tables|= table->map;
8542  }
8543 
8544  /*
8545  Initialize a generic field iterator for the current table reference.
8546  Notice that it is guaranteed that this iterator will iterate over the
8547  fields of a single table reference, because 'tables' is a leaf (for
8548  name resolution purposes).
8549  */
8550  field_iterator.set(tables);
8551 
8552  for (; !field_iterator.end_of_fields(); field_iterator.next())
8553  {
8554  Item *item;
8555 
8556  if (!(item= field_iterator.create_item(thd)))
8557  DBUG_RETURN(TRUE);
8558  DBUG_ASSERT(item->fixed);
8559  /* cache the table for the Item_fields inserted by expanding stars */
8560  if (item->type() == Item::FIELD_ITEM && tables->cacheable_table)
8561  ((Item_field *)item)->cached_table= tables;
8562 
8563  if (!found)
8564  {
8565  found= TRUE;
8566  it->replace(item); /* Replace '*' with the first found item. */
8567  }
8568  else
8569  it->after(item); /* Add 'item' to the SELECT list. */
8570 
8571 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8572  /*
8573  Set privilege information for the fields of newly created views.
8574  We have that (any_priviliges == TRUE) if and only if we are creating
8575  a view. In the time of view creation we can't use the MERGE algorithm,
8576  therefore if 'tables' is itself a view, it is represented by a
8577  temporary table. Thus in this case we can be sure that 'item' is an
8578  Item_field.
8579  */
8580  if (any_privileges)
8581  {
8582  DBUG_ASSERT((tables->field_translation == NULL && table) ||
8583  tables->is_natural_join);
8584  DBUG_ASSERT(item->type() == Item::FIELD_ITEM);
8585  Item_field *fld= (Item_field*) item;
8586  const char *field_table_name= field_iterator.get_table_name();
8587 
8588  if (!tables->schema_table &&
8589  !(fld->have_privileges=
8590  (get_column_grant(thd, field_iterator.grant(),
8591  field_iterator.get_db_name(),
8592  field_table_name, fld->field_name) &
8593  VIEW_ANY_ACL)))
8594  {
8595  my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0), "ANY",
8596  thd->security_ctx->priv_user,
8597  thd->security_ctx->host_or_ip,
8598  field_table_name);
8599  DBUG_RETURN(TRUE);
8600  }
8601  }
8602 #endif
8603 
8604  if ((field= field_iterator.field()))
8605  {
8606  /* Mark fields as used to allow storage engine to optimze access */
8607  bitmap_set_bit(field->table->read_set, field->field_index);
8608  if (table)
8609  {
8610  table->covering_keys.intersect(field->part_of_key);
8611  table->merge_keys.merge(field->part_of_key);
8612  }
8613  if (tables->is_natural_join)
8614  {
8615  TABLE *field_table;
8616  /*
8617  In this case we are sure that the column ref will not be created
8618  because it was already created and stored with the natural join.
8619  */
8620  Natural_join_column *nj_col;
8621  if (!(nj_col= field_iterator.get_natural_column_ref()))
8622  DBUG_RETURN(TRUE);
8623  DBUG_ASSERT(nj_col->table_field);
8624  field_table= nj_col->table_ref->table;
8625  if (field_table)
8626  {
8627  thd->lex->used_tables|= field_table->map;
8628  thd->lex->current_select->select_list_tables|=
8629  field_table->map;
8630  field_table->covering_keys.intersect(field->part_of_key);
8631  field_table->merge_keys.merge(field->part_of_key);
8632  field_table->used_fields++;
8633  }
8634  }
8635  }
8636  else
8637  {
8638  thd->lex->used_tables|= item->used_tables();
8639  thd->lex->current_select->select_list_tables|=
8640  item->used_tables();
8641  }
8642  thd->lex->current_select->cur_pos_in_all_fields++;
8643  }
8644  /*
8645  In case of stored tables, all fields are considered as used,
8646  while in the case of views, the fields considered as used are the
8647  ones marked in setup_tables during fix_fields of view columns.
8648  For NATURAL joins, used_tables is updated in the IF above.
8649  */
8650  if (table)
8651  table->used_fields= table->s->fields;
8652  }
8653  if (found)
8654  DBUG_RETURN(FALSE);
8655 
8656  /*
8657  TODO: in the case when we skipped all columns because there was a
8658  qualified '*', and all columns were coalesced, we have to give a more
8659  meaningful message than ER_BAD_TABLE_ERROR.
8660  */
8661  if (!table_name || !*table_name)
8662  my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
8663  else
8664  {
8665  String tbl_name;
8666  if (db_name)
8667  {
8668  tbl_name.append(String(db_name,system_charset_info));
8669  tbl_name.append('.');
8670  }
8671  tbl_name.append(String(table_name,system_charset_info));
8672 
8673  my_error(ER_BAD_TABLE_ERROR, MYF(0), tbl_name.c_ptr_safe());
8674  }
8675 
8676  DBUG_RETURN(TRUE);
8677 }
8678 
8679 
8680 /*
8681  Fix all conditions and outer join expressions.
8682 
8683  SYNOPSIS
8684  setup_conds()
8685  thd thread handler
8686  tables list of tables for name resolving (select_lex->table_list)
8687  leaves list of leaves of join table tree (select_lex->leaf_tables)
8688  conds WHERE clause
8689 
8690  DESCRIPTION
8691  TODO
8692 
8693  RETURN
8694  TRUE if some error occured (e.g. out of memory)
8695  FALSE if all is OK
8696 */
8697 
8698 int setup_conds(THD *thd, TABLE_LIST *tables, TABLE_LIST *leaves,
8699  Item **conds)
8700 {
8701  SELECT_LEX *select_lex= thd->lex->current_select;
8702  TABLE_LIST *table= NULL; // For HP compilers
8703  /*
8704  it_is_update set to TRUE when tables of primary SELECT_LEX (SELECT_LEX
8705  which belong to LEX, i.e. most up SELECT) will be updated by
8706  INSERT/UPDATE/LOAD
8707  NOTE: using this condition helps to prevent call of prepare_check_option()
8708  from subquery of VIEW, because tables of subquery belongs to VIEW
8709  (see condition before prepare_check_option() call)
8710  */
8711  bool it_is_update= (select_lex == &thd->lex->select_lex) &&
8712  thd->lex->which_check_option_applicable();
8713  bool save_is_item_list_lookup= select_lex->is_item_list_lookup;
8714  select_lex->is_item_list_lookup= 0;
8715  DBUG_ENTER("setup_conds");
8716 
8717  thd->mark_used_columns= MARK_COLUMNS_READ;
8718  DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
8719  select_lex->cond_count= 0;
8720  select_lex->between_count= 0;
8721  select_lex->max_equal_elems= 0;
8722 
8723  for (table= tables; table; table= table->next_local)
8724  {
8725  select_lex->resolve_place= st_select_lex::RESOLVE_CONDITION;
8726  /*
8727  Walk up tree of join nests and try to find outer join nest.
8728  This is needed because simplify_joins() has not yet been called,
8729  and hence inner join nests have not yet been removed.
8730  */
8731  for (TABLE_LIST *embedding= table;
8732  embedding;
8733  embedding= embedding->embedding)
8734  {
8735  if (embedding->outer_join)
8736  {
8737  /*
8738  The join condition belongs to an outer join next.
8739  Record this fact and the outer join nest for possible transformation
8740  of subqueries into semi-joins.
8741  */
8742  select_lex->resolve_place= st_select_lex::RESOLVE_JOIN_NEST;
8743  select_lex->resolve_nest= embedding;
8744  break;
8745  }
8746  }
8747  if (table->prepare_where(thd, conds, FALSE))
8748  goto err_no_arena;
8749  select_lex->resolve_place= st_select_lex::RESOLVE_NONE;
8750  select_lex->resolve_nest= NULL;
8751  }
8752 
8753  if (*conds)
8754  {
8755  select_lex->resolve_place= st_select_lex::RESOLVE_CONDITION;
8756  thd->where="where clause";
8757  if ((!(*conds)->fixed && (*conds)->fix_fields(thd, conds)) ||
8758  (*conds)->check_cols(1))
8759  goto err_no_arena;
8760  select_lex->where= *conds;
8761  select_lex->resolve_place= st_select_lex::RESOLVE_NONE;
8762  }
8763 
8764  /*
8765  Apply fix_fields() to all ON clauses at all levels of nesting,
8766  including the ones inside view definitions.
8767  */
8768  for (table= leaves; table; table= table->next_leaf)
8769  {
8770  TABLE_LIST *embedded; /* The table at the current level of nesting. */
8771  TABLE_LIST *embedding= table; /* The parent nested table reference. */
8772  do
8773  {
8774  embedded= embedding;
8775  if (embedded->join_cond())
8776  {
8777  /* Make a join an a expression */
8778  select_lex->resolve_place= st_select_lex::RESOLVE_JOIN_NEST;
8779  select_lex->resolve_nest= embedded;
8780  thd->where="on clause";
8781  if ((!embedded->join_cond()->fixed &&
8782  embedded->join_cond()->fix_fields(thd, embedded->join_cond_ref())) ||
8783  embedded->join_cond()->check_cols(1))
8784  goto err_no_arena;
8785  select_lex->cond_count++;
8786  select_lex->resolve_place= st_select_lex::RESOLVE_NONE;
8787  select_lex->resolve_nest= NULL;
8788  }
8789  embedding= embedded->embedding;
8790  }
8791  while (embedding &&
8792  embedding->nested_join->join_list.head() == embedded);
8793 
8794  /* process CHECK OPTION */
8795  if (it_is_update)
8796  {
8797  TABLE_LIST *view= table->top_table();
8798  if (view->effective_with_check)
8799  {
8800  if (view->prepare_check_option(thd))
8801  goto err_no_arena;
8802  thd->change_item_tree(&table->check_option, view->check_option);
8803  }
8804  }
8805  }
8806 
8807  thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
8808  DBUG_RETURN(test(thd->is_error()));
8809 
8810 err_no_arena:
8811  select_lex->is_item_list_lookup= save_is_item_list_lookup;
8812  DBUG_RETURN(1);
8813 }
8814 
8815 
8816 /******************************************************************************
8817 ** Fill a record with data (for INSERT or UPDATE)
8818 ** Returns : 1 if some field has wrong type
8819 ******************************************************************************/
8820 
8821 
8822 /*
8823  Fill fields with given items.
8824 
8825  @param thd thread handler
8826  @param fields Item_fields list to be filled
8827  @param values values to fill with
8828  @param ignore_errors TRUE if we should ignore errors
8829  @param bitmap Bitmap over fields to fill
8830 
8831  @note fill_record() may set table->auto_increment_field_not_null and a
8832  caller should make sure that it is reset after their last call to this
8833  function.
8834 
8835  @return Operation status
8836  @retval false OK
8837  @retval true Error occured
8838 */
8839 
8840 bool
8841 fill_record(THD * thd, List<Item> &fields, List<Item> &values,
8842  bool ignore_errors, MY_BITMAP *bitmap)
8843 {
8844  List_iterator_fast<Item> f(fields),v(values);
8845  Item *value, *fld;
8846  Item_field *field;
8847  TABLE *table= 0;
8848  DBUG_ENTER("fill_record");
8849  DBUG_ASSERT(fields.elements == values.elements);
8850  /*
8851  Reset the table->auto_increment_field_not_null as it is valid for
8852  only one row.
8853  */
8854  if (fields.elements)
8855  {
8856  /*
8857  On INSERT or UPDATE fields are checked to be from the same table,
8858  thus we safely can take table from the first field.
8859  */
8860  fld= (Item_field*)f++;
8861  if (!(field= fld->field_for_view_update()))
8862  {
8863  my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->item_name.ptr());
8864  goto err;
8865  }
8866  table= field->field->table;
8867  table->auto_increment_field_not_null= FALSE;
8868  f.rewind();
8869  }
8870  while ((fld= f++))
8871  {
8872  if (!(field= fld->field_for_view_update()))
8873  {
8874  my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->item_name.ptr());
8875  goto err;
8876  }
8877  value=v++;
8878  Field *rfield= field->field;
8879  /* If bitmap over wanted fields are set, skip non marked fields. */
8880  if (bitmap && !bitmap_is_set(bitmap, rfield->field_index))
8881  continue;
8882  table= rfield->table;
8883  if (rfield == table->next_number_field)
8884  table->auto_increment_field_not_null= TRUE;
8885  if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
8886  {
8887  my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
8888  goto err;
8889  }
8890  }
8891  DBUG_RETURN(thd->is_error());
8892 err:
8893  if (table)
8894  table->auto_increment_field_not_null= FALSE;
8895  DBUG_RETURN(TRUE);
8896 }
8897 
8898 
8899 /*
8900  Fill fields in list with values from the list of items and invoke
8901  before triggers.
8902 
8903  SYNOPSIS
8904  fill_record_n_invoke_before_triggers()
8905  thd thread context
8906  fields Item_fields list to be filled
8907  values values to fill with
8908  ignore_errors TRUE if we should ignore errors
8909  triggers object holding list of triggers to be invoked
8910  event event type for triggers to be invoked
8911 
8912  NOTE
8913  This function assumes that fields which values will be set and triggers
8914  to be invoked belong to the same table, and that TABLE::record[0] and
8915  record[1] buffers correspond to new and old versions of row respectively.
8916 
8917  RETURN
8918  FALSE OK
8919  TRUE error occured
8920 */
8921 
8922 bool
8923 fill_record_n_invoke_before_triggers(THD *thd, List<Item> &fields,
8924  List<Item> &values, bool ignore_errors,
8925  Table_triggers_list *triggers,
8926  enum trg_event_type event)
8927 {
8928  return (fill_record(thd, fields, values, ignore_errors, NULL) ||
8929  (triggers && triggers->process_triggers(thd, event,
8930  TRG_ACTION_BEFORE, TRUE)));
8931 }
8932 
8933 
8952 bool
8953 fill_record(THD *thd, Field **ptr, List<Item> &values, bool ignore_errors,
8954  MY_BITMAP *bitmap)
8955 {
8956  List_iterator_fast<Item> v(values);
8957  Item *value;
8958  TABLE *table= 0;
8959  DBUG_ENTER("fill_record");
8960 
8961  Field *field;
8962  /*
8963  Reset the table->auto_increment_field_not_null as it is valid for
8964  only one row.
8965  */
8966  if (*ptr)
8967  {
8968  /*
8969  On INSERT or UPDATE fields are checked to be from the same table,
8970  thus we safely can take table from the first field.
8971  */
8972  table= (*ptr)->table;
8973  table->auto_increment_field_not_null= FALSE;
8974  }
8975  while ((field = *ptr++) && ! thd->is_error())
8976  {
8977  value=v++;
8978  table= field->table;
8979  /* If bitmap over wanted fields are set, skip non marked fields. */
8980  if (bitmap && !bitmap_is_set(bitmap, field->field_index))
8981  continue;
8982  if (field == table->next_number_field)
8983  table->auto_increment_field_not_null= TRUE;
8984  if (value->save_in_field(field, 0) == TYPE_ERR_NULL_CONSTRAINT_VIOLATION)
8985  goto err;
8986  }
8987  DBUG_ASSERT(thd->is_error() || !v++); // No extra value!
8988  DBUG_RETURN(thd->is_error());
8989 
8990 err:
8991  if (table)
8992  table->auto_increment_field_not_null= FALSE;
8993  DBUG_RETURN(TRUE);
8994 }
8995 
8996 
8997 /*
8998  Fill fields in array with values from the list of items and invoke
8999  before triggers.
9000 
9001  SYNOPSIS
9002  fill_record_n_invoke_before_triggers()
9003  thd thread context
9004  ptr NULL-ended array of fields to be filled
9005  values values to fill with
9006  ignore_errors TRUE if we should ignore errors
9007  triggers object holding list of triggers to be invoked
9008  event event type for triggers to be invoked
9009 
9010  NOTE
9011  This function assumes that fields which values will be set and triggers
9012  to be invoked belong to the same table, and that TABLE::record[0] and
9013  record[1] buffers correspond to new and old versions of row respectively.
9014 
9015  RETURN
9016  FALSE OK
9017  TRUE error occured
9018 */
9019 
9020 bool
9021 fill_record_n_invoke_before_triggers(THD *thd, Field **ptr,
9022  List<Item> &values, bool ignore_errors,
9023  Table_triggers_list *triggers,
9024  enum trg_event_type event)
9025 {
9026  return (fill_record(thd, ptr, values, ignore_errors, NULL) ||
9027  (triggers && triggers->process_triggers(thd, event,
9028  TRG_ACTION_BEFORE, TRUE)));
9029 }
9030 
9031 
9032 my_bool mysql_rm_tmp_tables(void)
9033 {
9034  uint i, idx;
9035  char filePath[FN_REFLEN], *tmpdir, filePathCopy[FN_REFLEN];
9036  MY_DIR *dirp;
9037  FILEINFO *file;
9038  TABLE_SHARE share;
9039  THD *thd;
9040  DBUG_ENTER("mysql_rm_tmp_tables");
9041 
9042  if (!(thd= new THD))
9043  DBUG_RETURN(1);
9044  thd->thread_stack= (char*) &thd;
9045  thd->store_globals();
9046 
9047  for (i=0; i<=mysql_tmpdir_list.max; i++)
9048  {
9049  tmpdir=mysql_tmpdir_list.list[i];
9050  /* See if the directory exists */
9051  if (!(dirp = my_dir(tmpdir,MYF(MY_WME | MY_DONT_SORT))))
9052  continue;
9053 
9054  /* Remove all SQLxxx tables from directory */
9055 
9056  for (idx=0 ; idx < (uint) dirp->number_off_files ; idx++)
9057  {
9058  file=dirp->dir_entry+idx;
9059 
9060  /* skiping . and .. */
9061  if (file->name[0] == '.' && (!file->name[1] ||
9062  (file->name[1] == '.' && !file->name[2])))
9063  continue;
9064 
9065  if (!memcmp(file->name, tmp_file_prefix,
9066  tmp_file_prefix_length))
9067  {
9068  char *ext= fn_ext(file->name);
9069  uint ext_len= strlen(ext);
9070  uint filePath_len= my_snprintf(filePath, sizeof(filePath),
9071  "%s%c%s", tmpdir, FN_LIBCHAR,
9072  file->name);
9073  if (!memcmp(reg_ext, ext, ext_len))
9074  {
9075  handler *handler_file= 0;
9076  /* We should cut file extention before deleting of table */
9077  memcpy(filePathCopy, filePath, filePath_len - ext_len);
9078  filePathCopy[filePath_len - ext_len]= 0;
9079  init_tmp_table_share(thd, &share, "", 0, "", filePathCopy);
9080  if (!open_table_def(thd, &share, 0) &&
9081  ((handler_file= get_new_handler(&share, thd->mem_root,
9082  share.db_type()))))
9083  {
9084  handler_file->ha_delete_table(filePathCopy);
9085  delete handler_file;
9086  }
9087  free_table_share(&share);
9088  }
9089  /*
9090  File can be already deleted by tmp_table.file->delete_table().
9091  So we hide error messages which happnes during deleting of these
9092  files(MYF(0)).
9093  */
9094  (void) mysql_file_delete(key_file_misc, filePath, MYF(0));
9095  }
9096  }
9097  my_dirend(dirp);
9098  }
9099  delete thd;
9100  my_pthread_setspecific_ptr(THR_THD, 0);
9101  DBUG_RETURN(0);
9102 }
9103 
9104 
9105 
9106 /*****************************************************************************
9107  unireg support functions
9108 *****************************************************************************/
9109 
9110 /*
9111  free all unused tables
9112 
9113  NOTE
9114  This is called by 'handle_manager' when one wants to periodicly flush
9115  all not used tables.
9116 */
9117 
9118 void tdc_flush_unused_tables()
9119 {
9120  table_cache_manager.lock_all_and_tdc();
9121  table_cache_manager.free_all_unused_tables();
9122  table_cache_manager.unlock_all_and_tdc();
9123 }
9124 
9125 
9165 void tdc_remove_table(THD *thd, enum_tdc_remove_table_type remove_type,
9166  const char *db, const char *table_name,
9167  bool has_lock)
9168 {
9169  char key[MAX_DBKEY_LENGTH];
9170  uint key_length;
9171  TABLE_SHARE *share;
9172 
9173  if (! has_lock)
9174  table_cache_manager.lock_all_and_tdc();
9175  else
9176  table_cache_manager.assert_owner_all_and_tdc();
9177 
9178  DBUG_ASSERT(remove_type == TDC_RT_REMOVE_UNUSED ||
9179  thd->mdl_context.is_lock_owner(MDL_key::TABLE, db, table_name,
9180  MDL_EXCLUSIVE));
9181 
9182  key_length= create_table_def_key(thd, key, db, table_name, false);
9183 
9184  if ((share= (TABLE_SHARE*) my_hash_search(&table_def_cache,(uchar*) key,
9185  key_length)))
9186  {
9187  if (share->ref_count)
9188  {
9189  /*
9190  Set share's version to zero in order to ensure that it gets
9191  automatically deleted once it is no longer referenced.
9192 
9193  Note that code in TABLE_SHARE::wait_for_old_version() assumes
9194  that marking share as old and removal of its unused tables
9195  and of the share itself from TDC happens atomically under
9196  protection of LOCK_open, or, putting it another way, that
9197  TDC does not contain old shares which don't have any tables
9198  used.
9199  */
9200  if (remove_type != TDC_RT_REMOVE_NOT_OWN_KEEP_SHARE)
9201  share->version= 0;
9202  table_cache_manager.free_table(thd, remove_type, share);
9203  }
9204  else
9205  {
9206  DBUG_ASSERT(remove_type != TDC_RT_REMOVE_NOT_OWN_KEEP_SHARE);
9207  (void) my_hash_delete(&table_def_cache, (uchar*) share);
9208  }
9209  }
9210 
9211  if (! has_lock)
9212  table_cache_manager.unlock_all_and_tdc();
9213 }
9214 
9215 
9216 int setup_ftfuncs(SELECT_LEX *select_lex)
9217 {
9218  List_iterator<Item_func_match> li(*(select_lex->ftfunc_list)),
9219  lj(*(select_lex->ftfunc_list));
9220  Item_func_match *ftf, *ftf2;
9221 
9222  while ((ftf=li++))
9223  {
9224  if (ftf->fix_index())
9225  return 1;
9226  lj.rewind();
9227  while ((ftf2=lj++) != ftf)
9228  {
9229  if (ftf->eq(ftf2,1) && !ftf2->master)
9230  ftf2->master=ftf;
9231  }
9232  }
9233 
9234  return 0;
9235 }
9236 
9237 
9238 int init_ftfuncs(THD *thd, SELECT_LEX *select_lex, bool no_order)
9239 {
9240  if (select_lex->ftfunc_list->elements)
9241  {
9242  List_iterator<Item_func_match> li(*(select_lex->ftfunc_list));
9243  Item_func_match *ifm;
9244  DBUG_PRINT("info",("Performing FULLTEXT search"));
9245  THD_STAGE_INFO(thd, stage_fulltext_initialization);
9246 
9247  while ((ifm=li++))
9248  ifm->init_search(no_order);
9249  }
9250  return 0;
9251 }
9252 
9253 
9254 bool is_equal(const LEX_STRING *a, const LEX_STRING *b)
9255 {
9256  return a->length == b->length && !strncmp(a->str, b->str, a->length);
9257 }
9258 
9259 
9260 /*
9261  Tells if two (or more) tables have auto_increment columns and we want to
9262  lock those tables with a write lock.
9263 
9264  SYNOPSIS
9265  has_two_write_locked_tables_with_auto_increment
9266  tables Table list
9267 
9268  NOTES:
9269  Call this function only when you have established the list of all tables
9270  which you'll want to update (including stored functions, triggers, views
9271  inside your statement).
9272 */
9273 
9274 static bool
9275 has_write_table_with_auto_increment(TABLE_LIST *tables)
9276 {
9277  for (TABLE_LIST *table= tables; table; table= table->next_global)
9278  {
9279  /* we must do preliminary checks as table->table may be NULL */
9280  if (!table->placeholder() &&
9281  table->table->found_next_number_field &&
9282  (table->lock_type >= TL_WRITE_ALLOW_WRITE))
9283  return 1;
9284  }
9285 
9286  return 0;
9287 }
9288 
9289 /*
9290  checks if we have select tables in the table list and write tables
9291  with auto-increment column.
9292 
9293  SYNOPSIS
9294  has_two_write_locked_tables_with_auto_increment_and_select
9295  tables Table list
9296 
9297  RETURN VALUES
9298 
9299  -true if the table list has atleast one table with auto-increment column
9300 
9301 
9302  and atleast one table to select from.
9303  -false otherwise
9304 */
9305 
9306 static bool
9307 has_write_table_with_auto_increment_and_select(TABLE_LIST *tables)
9308 {
9309  bool has_select= false;
9310  bool has_auto_increment_tables = has_write_table_with_auto_increment(tables);
9311  for(TABLE_LIST *table= tables; table; table= table->next_global)
9312  {
9313  if (!table->placeholder() &&
9314  (table->lock_type <= TL_READ_NO_INSERT))
9315  {
9316  has_select= true;
9317  break;
9318  }
9319  }
9320  return(has_select && has_auto_increment_tables);
9321 }
9322 
9323 /*
9324  Tells if there is a table whose auto_increment column is a part
9325  of a compound primary key while is not the first column in
9326  the table definition.
9327 
9328  @param tables Table list
9329 
9330  @return true if the table exists, fais if does not.
9331 */
9332 
9333 static bool
9334 has_write_table_auto_increment_not_first_in_pk(TABLE_LIST *tables)
9335 {
9336  for (TABLE_LIST *table= tables; table; table= table->next_global)
9337  {
9338  /* we must do preliminary checks as table->table may be NULL */
9339  if (!table->placeholder() &&
9340  table->table->found_next_number_field &&
9341  (table->lock_type >= TL_WRITE_ALLOW_WRITE)
9342  && table->table->s->next_number_keypart != 0)
9343  return 1;
9344  }
9345 
9346  return 0;
9347 }
9348 
9349 
9350 
9351 /*
9352  Open and lock system tables for read.
9353 
9354  SYNOPSIS
9355  open_system_tables_for_read()
9356  thd Thread context.
9357  table_list List of tables to open.
9358  backup Pointer to Open_tables_state instance where
9359  information about currently open tables will be
9360  saved, and from which will be restored when we will
9361  end work with system tables.
9362 
9363  NOTES
9364  Thanks to restrictions which we put on opening and locking of
9365  system tables for writing, we can open and lock them for reading
9366  even when we already have some other tables open and locked. One
9367  must call close_system_tables() to close systems tables opened
9368  with this call.
9369 
9370  RETURN
9371  FALSE Success
9372  TRUE Error
9373 */
9374 
9375 bool
9376 open_system_tables_for_read(THD *thd, TABLE_LIST *table_list,
9377  Open_tables_backup *backup)
9378 {
9379  Query_tables_list query_tables_list_backup;
9380  LEX *lex= thd->lex;
9381 
9382  DBUG_ENTER("open_system_tables_for_read");
9383 
9384  /*
9385  Besides using new Open_tables_state for opening system tables,
9386  we also have to backup and reset/and then restore part of LEX
9387  which is accessed by open_tables() in order to determine if
9388  prelocking is needed and what tables should be added for it.
9389  */
9390  lex->reset_n_backup_query_tables_list(&query_tables_list_backup);
9391  thd->reset_n_backup_open_tables_state(backup);
9392 
9393  if (open_and_lock_tables(thd, table_list, FALSE,
9394  MYSQL_OPEN_IGNORE_FLUSH |
9395  MYSQL_LOCK_IGNORE_TIMEOUT))
9396  {
9397  lex->restore_backup_query_tables_list(&query_tables_list_backup);
9398  thd->restore_backup_open_tables_state(backup);
9399  DBUG_RETURN(TRUE);
9400  }
9401 
9402  for (TABLE_LIST *tables= table_list; tables; tables= tables->next_global)
9403  {
9404  DBUG_ASSERT(tables->table->s->table_category == TABLE_CATEGORY_SYSTEM);
9405  tables->table->use_all_columns();
9406  }
9407  lex->restore_backup_query_tables_list(&query_tables_list_backup);
9408 
9409  DBUG_RETURN(FALSE);
9410 }
9411 
9412 
9413 /*
9414  Close system tables, opened with open_system_tables_for_read().
9415 
9416  SYNOPSIS
9417  close_system_tables()
9418  thd Thread context
9419  backup Pointer to Open_tables_backup instance which holds
9420  information about tables which were open before we
9421  decided to access system tables.
9422 */
9423 
9424 void
9425 close_system_tables(THD *thd, Open_tables_backup *backup)
9426 {
9427  Query_tables_list query_tables_list_backup;
9428 
9429  /*
9430  In order not affect execution of current statement we have to
9431  backup/reset/restore Query_tables_list part of LEX, which is
9432  accessed and updated in the process of closing tables.
9433  */
9434  thd->lex->reset_n_backup_query_tables_list(&query_tables_list_backup);
9435  close_thread_tables(thd);
9436  thd->lex->restore_backup_query_tables_list(&query_tables_list_backup);
9437  thd->restore_backup_open_tables_state(backup);
9438 }
9439 
9440 
9464 void
9466 {
9467  /* No need to commit/rollback statement transaction, it's not started. */
9468  DBUG_ASSERT(thd->transaction.stmt.is_empty());
9469  close_thread_tables(thd);
9470  thd->mdl_context.release_transactional_locks();
9471 }
9472 
9473 /*
9474  Open and lock one system table for update.
9475 
9476  SYNOPSIS
9477  open_system_table_for_update()
9478  thd Thread context.
9479  one_table Table to open.
9480 
9481  NOTES
9482  Table opened with this call should closed using close_thread_tables().
9483 
9484  RETURN
9485  0 Error
9486  # Pointer to TABLE object of system table
9487 */
9488 
9489 TABLE *
9490 open_system_table_for_update(THD *thd, TABLE_LIST *one_table)
9491 {
9492  DBUG_ENTER("open_system_table_for_update");
9493 
9494  TABLE *table= open_ltable(thd, one_table, one_table->lock_type,
9495  MYSQL_LOCK_IGNORE_TIMEOUT);
9496  if (table)
9497  {
9498  DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_SYSTEM);
9499  table->use_all_columns();
9500  }
9501 
9502  DBUG_RETURN(table);
9503 }
9504 
9516 TABLE *
9517 open_log_table(THD *thd, TABLE_LIST *one_table, Open_tables_backup *backup)
9518 {
9519  uint flags= ( MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK |
9520  MYSQL_LOCK_IGNORE_GLOBAL_READ_ONLY |
9521  MYSQL_OPEN_IGNORE_FLUSH |
9522  MYSQL_LOCK_IGNORE_TIMEOUT |
9523  MYSQL_LOCK_LOG_TABLE);
9524  TABLE *table;
9525  /* Save value that is changed in mysql_lock_tables() */
9526  ulonglong save_utime_after_lock= thd->utime_after_lock;
9527  DBUG_ENTER("open_log_table");
9528 
9529  thd->reset_n_backup_open_tables_state(backup);
9530 
9531  if ((table= open_ltable(thd, one_table, one_table->lock_type, flags)))
9532  {
9533  DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_LOG);
9534  /* Make sure all columns get assigned to a default value */
9535  table->use_all_columns();
9536  DBUG_ASSERT(table->no_replicate);
9537  }
9538  else
9539  thd->restore_backup_open_tables_state(backup);
9540 
9541  thd->utime_after_lock= save_utime_after_lock;
9542  DBUG_RETURN(table);
9543 }
9544 
9552 void close_log_table(THD *thd, Open_tables_backup *backup)
9553 {
9554  close_system_tables(thd, backup);
9555 }
9556