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