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