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