MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
sql_parse.cc
1 /* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software
14  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15 
16 #define MYSQL_LEX 1
17 #include "my_global.h"
18 #include "sql_priv.h"
19 #include "unireg.h" // REQUIRED: for other includes
20 #include "sql_parse.h" // sql_kill, *_precheck, *_prepare
21 #include "lock.h" // try_transactional_lock,
22  // check_transactional_lock,
23  // set_handler_table_locks,
24  // lock_global_read_lock,
25  // make_global_read_lock_block_commit
26 #include "sql_base.h" // find_temporary_table
27 #include "sql_cache.h" // QUERY_CACHE_FLAGS_SIZE, query_cache_*
28 #include "sql_show.h" // mysqld_list_*, mysqld_show_*,
29  // calc_sum_of_all_status
30 #include "mysqld.h"
31 #include "sql_locale.h" // my_locale_en_US
32 #include "log.h" // flush_error_log
33 #include "sql_view.h" // mysql_create_view, mysql_drop_view
34 #include "sql_delete.h" // mysql_delete
35 #include "sql_insert.h" // mysql_insert
36 #include "sql_update.h" // mysql_update, mysql_multi_update
37 #include "sql_partition.h" // struct partition_info
38 #include "sql_db.h" // mysql_change_db, mysql_create_db,
39  // mysql_rm_db, mysql_upgrade_db,
40  // mysql_alter_db,
41  // check_db_dir_existence,
42  // my_dbopt_cleanup
43 #include "sql_table.h" // mysql_create_like_table,
44  // mysql_create_table,
45  // mysql_alter_table,
46  // mysql_backup_table,
47  // mysql_restore_table
48 #include "sql_reload.h" // reload_acl_and_cache
49 #include "sql_admin.h" // mysql_assign_to_keycache
50 #include "sql_connect.h" // check_user,
51  // decrease_user_connections,
52  // thd_init_client_charset, check_mqh,
53  // reset_mqh
54 #include "sql_rename.h" // mysql_rename_table
55 #include "sql_tablespace.h" // mysql_alter_tablespace
56 #include "hostname.h" // hostname_cache_refresh
57 #include "sql_acl.h" // *_ACL, check_grant, is_acl_user,
58  // has_any_table_level_privileges,
59  // mysql_drop_user, mysql_rename_user,
60  // check_grant_routine,
61  // mysql_routine_grant,
62  // mysql_show_grants,
63  // sp_grant_privileges, ...
64 #include "sql_test.h" // mysql_print_status
65 #include "sql_select.h" // handle_select, mysql_select,
66 #include "sql_load.h" // mysql_load
67 #include "sql_servers.h" // create_servers, alter_servers,
68  // drop_servers, servers_reload
69 #include "sql_handler.h" // mysql_ha_open, mysql_ha_close,
70  // mysql_ha_read
71 #include "sql_binlog.h" // mysql_client_binlog_statement
72 #include "sql_do.h" // mysql_do
73 #include "sql_help.h" // mysqld_help
74 #include "rpl_constants.h" // Incident, INCIDENT_LOST_EVENTS
75 #include "log_event.h"
76 #include "rpl_slave.h"
77 #include "rpl_master.h"
78 #include "rpl_filter.h"
79 #include <m_ctype.h>
80 #include <myisam.h>
81 #include <my_dir.h>
82 #include "rpl_handler.h"
83 
84 #include "sp_head.h"
85 #include "sp.h"
86 #include "sp_cache.h"
87 #include "events.h"
88 #include "sql_trigger.h"
89 #include "transaction.h"
90 #include "sql_audit.h"
91 #include "sql_prepare.h"
92 #include "debug_sync.h"
93 #include "probes_mysql.h"
94 #include "set_var.h"
95 #include "opt_trace.h"
97 #include "sql_bootstrap.h"
98 #include "opt_explain.h"
99 #include "sql_rewrite.h"
100 #include "global_threads.h"
101 #include "sql_analyse.h"
102 #include "table_cache.h" // table_cache_manager
103 
104 #include <algorithm>
105 using std::max;
106 using std::min;
107 
108 #define FLAGSTR(V,F) ((V)&(F)?#F" ":"")
109 
115 /* Used in error handling only */
116 #define SP_TYPE_STRING(LP) \
117  ((LP)->sphead->m_type == SP_TYPE_FUNCTION ? "FUNCTION" : "PROCEDURE")
118 #define SP_COM_STRING(LP) \
119  ((LP)->sql_command == SQLCOM_CREATE_SPFUNCTION || \
120  (LP)->sql_command == SQLCOM_ALTER_FUNCTION || \
121  (LP)->sql_command == SQLCOM_SHOW_CREATE_FUNC || \
122  (LP)->sql_command == SQLCOM_DROP_FUNCTION ? \
123  "FUNCTION" : "PROCEDURE")
124 
125 static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables);
126 static bool check_show_access(THD *thd, TABLE_LIST *table);
127 static void sql_kill(THD *thd, ulong id, bool only_kill_query);
128 static bool lock_tables_precheck(THD *thd, TABLE_LIST *tables);
129 
130 const char *any_db="*any*"; // Special symbol for check_access
131 
132 const LEX_STRING command_name[]={
133  { C_STRING_WITH_LEN("Sleep") },
134  { C_STRING_WITH_LEN("Quit") },
135  { C_STRING_WITH_LEN("Init DB") },
136  { C_STRING_WITH_LEN("Query") },
137  { C_STRING_WITH_LEN("Field List") },
138  { C_STRING_WITH_LEN("Create DB") },
139  { C_STRING_WITH_LEN("Drop DB") },
140  { C_STRING_WITH_LEN("Refresh") },
141  { C_STRING_WITH_LEN("Shutdown") },
142  { C_STRING_WITH_LEN("Statistics") },
143  { C_STRING_WITH_LEN("Processlist") },
144  { C_STRING_WITH_LEN("Connect") },
145  { C_STRING_WITH_LEN("Kill") },
146  { C_STRING_WITH_LEN("Debug") },
147  { C_STRING_WITH_LEN("Ping") },
148  { C_STRING_WITH_LEN("Time") },
149  { C_STRING_WITH_LEN("Delayed insert") },
150  { C_STRING_WITH_LEN("Change user") },
151  { C_STRING_WITH_LEN("Binlog Dump") },
152  { C_STRING_WITH_LEN("Table Dump") },
153  { C_STRING_WITH_LEN("Connect Out") },
154  { C_STRING_WITH_LEN("Register Slave") },
155  { C_STRING_WITH_LEN("Prepare") },
156  { C_STRING_WITH_LEN("Execute") },
157  { C_STRING_WITH_LEN("Long Data") },
158  { C_STRING_WITH_LEN("Close stmt") },
159  { C_STRING_WITH_LEN("Reset stmt") },
160  { C_STRING_WITH_LEN("Set option") },
161  { C_STRING_WITH_LEN("Fetch") },
162  { C_STRING_WITH_LEN("Daemon") },
163  { C_STRING_WITH_LEN("Binlog Dump GTID") },
164  { C_STRING_WITH_LEN("Error") } // Last command number
165 };
166 
167 const char *xa_state_names[]={
168  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED", "ROLLBACK ONLY"
169 };
170 
171 
172 Slow_log_throttle log_throttle_qni(&opt_log_throttle_queries_not_using_indexes,
173  &LOCK_log_throttle_qni,
174  Log_throttle::LOG_THROTTLE_WINDOW_SIZE,
175  slow_log_print,
176  "throttle: %10lu 'index "
177  "not used' warning(s) suppressed.");
178 
179 
180 #ifdef HAVE_REPLICATION
181 
184 inline bool all_tables_not_ok(THD *thd, TABLE_LIST *tables)
185 {
186  return rpl_filter->is_on() && tables && !thd->sp_runtime_ctx &&
187  !rpl_filter->tables_ok(thd->db, tables);
188 }
189 
206 inline bool db_stmt_db_ok(THD *thd, char* db)
207 {
208  DBUG_ENTER("db_stmt_db_ok");
209 
210  if (!thd->slave_thread)
211  DBUG_RETURN(TRUE);
212 
213  /*
214  No filters exist in ignore/do_db ? Then, just check
215  wild_do_table filtering. Otherwise, check the do_db
216  rules.
217  */
218  bool db_ok= (rpl_filter->get_do_db()->is_empty() &&
219  rpl_filter->get_ignore_db()->is_empty()) ?
220  rpl_filter->db_ok_with_wild_table(db) :
221  rpl_filter->db_ok(db);
222 
223  DBUG_RETURN(db_ok);
224 }
225 #endif
226 
227 
228 static bool some_non_temp_table_to_be_updated(THD *thd, TABLE_LIST *tables)
229 {
230  for (TABLE_LIST *table= tables; table; table= table->next_global)
231  {
232  DBUG_ASSERT(table->db && table->table_name);
233  if (table->updating && !find_temporary_table(thd, table))
234  return 1;
235  }
236  return 0;
237 }
238 
239 
240 /*
241  Implicitly commit a active transaction if statement requires so.
242 
243  @param thd Thread handle.
244  @param mask Bitmask used for the SQL command match.
245 
246 */
247 bool stmt_causes_implicit_commit(const THD *thd, uint mask)
248 {
249  const LEX *lex= thd->lex;
250  bool skip= FALSE;
251  DBUG_ENTER("stmt_causes_implicit_commit");
252 
253  if (!(sql_command_flags[lex->sql_command] & mask))
254  DBUG_RETURN(FALSE);
255 
256  switch (lex->sql_command) {
257  case SQLCOM_DROP_TABLE:
258  skip= lex->drop_temporary;
259  break;
260  case SQLCOM_ALTER_TABLE:
261  case SQLCOM_CREATE_TABLE:
262  /* If CREATE TABLE of non-temporary table, do implicit commit */
263  skip= (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE);
264  break;
265  case SQLCOM_SET_OPTION:
266  skip= lex->autocommit ? FALSE : TRUE;
267  break;
268  default:
269  break;
270  }
271 
272  DBUG_RETURN(!skip);
273 }
274 
275 
289 uint sql_command_flags[SQLCOM_END+1];
290 uint server_command_flags[COM_END+1];
291 
292 void init_update_queries(void)
293 {
294  /* Initialize the server command flags array. */
295  memset(server_command_flags, 0, sizeof(server_command_flags));
296 
297  server_command_flags[COM_STATISTICS]= CF_SKIP_QUESTIONS;
298  server_command_flags[COM_PING]= CF_SKIP_QUESTIONS;
299  server_command_flags[COM_STMT_PREPARE]= CF_SKIP_QUESTIONS;
300  server_command_flags[COM_STMT_CLOSE]= CF_SKIP_QUESTIONS;
301  server_command_flags[COM_STMT_RESET]= CF_SKIP_QUESTIONS;
302 
303  /* Initialize the sql command flags array. */
304  memset(sql_command_flags, 0, sizeof(sql_command_flags));
305 
306  /*
307  In general, DDL statements do not generate row events and do not go
308  through a cache before being written to the binary log. However, the
309  CREATE TABLE...SELECT is an exception because it may generate row
310  events. For that reason, the SQLCOM_CREATE_TABLE which represents
311  a CREATE TABLE, including the CREATE TABLE...SELECT, has the
312  CF_CAN_GENERATE_ROW_EVENTS flag. The distinction between a regular
313  CREATE TABLE and the CREATE TABLE...SELECT is made in other parts of
314  the code, in particular in the Query_log_event's constructor.
315  */
316  sql_command_flags[SQLCOM_CREATE_TABLE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
317  CF_AUTO_COMMIT_TRANS |
318  CF_CAN_GENERATE_ROW_EVENTS;
319  sql_command_flags[SQLCOM_CREATE_INDEX]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
320  sql_command_flags[SQLCOM_ALTER_TABLE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
321  CF_AUTO_COMMIT_TRANS;
322  sql_command_flags[SQLCOM_TRUNCATE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
323  CF_AUTO_COMMIT_TRANS;
324  sql_command_flags[SQLCOM_DROP_TABLE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
325  sql_command_flags[SQLCOM_LOAD]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
326  CF_CAN_GENERATE_ROW_EVENTS;
327  sql_command_flags[SQLCOM_CREATE_DB]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
328  sql_command_flags[SQLCOM_DROP_DB]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
329  sql_command_flags[SQLCOM_ALTER_DB_UPGRADE]= CF_AUTO_COMMIT_TRANS;
330  sql_command_flags[SQLCOM_ALTER_DB]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
331  sql_command_flags[SQLCOM_RENAME_TABLE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
332  sql_command_flags[SQLCOM_DROP_INDEX]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
333  sql_command_flags[SQLCOM_CREATE_VIEW]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
334  CF_AUTO_COMMIT_TRANS;
335  sql_command_flags[SQLCOM_DROP_VIEW]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
336  sql_command_flags[SQLCOM_CREATE_TRIGGER]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
337  sql_command_flags[SQLCOM_DROP_TRIGGER]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
338  sql_command_flags[SQLCOM_CREATE_EVENT]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
339  sql_command_flags[SQLCOM_ALTER_EVENT]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
340  sql_command_flags[SQLCOM_DROP_EVENT]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
341 
342  sql_command_flags[SQLCOM_UPDATE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
343  CF_CAN_GENERATE_ROW_EVENTS |
344  CF_OPTIMIZER_TRACE |
345  CF_CAN_BE_EXPLAINED;
346  sql_command_flags[SQLCOM_UPDATE_MULTI]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
347  CF_CAN_GENERATE_ROW_EVENTS |
348  CF_OPTIMIZER_TRACE |
349  CF_CAN_BE_EXPLAINED;
350  // This is INSERT VALUES(...), can be VALUES(stored_func()) so we trace it
351  sql_command_flags[SQLCOM_INSERT]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
352  CF_CAN_GENERATE_ROW_EVENTS |
353  CF_OPTIMIZER_TRACE |
354  CF_CAN_BE_EXPLAINED;
355  sql_command_flags[SQLCOM_INSERT_SELECT]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
356  CF_CAN_GENERATE_ROW_EVENTS |
357  CF_OPTIMIZER_TRACE |
358  CF_CAN_BE_EXPLAINED;
359  sql_command_flags[SQLCOM_DELETE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
360  CF_CAN_GENERATE_ROW_EVENTS |
361  CF_OPTIMIZER_TRACE |
362  CF_CAN_BE_EXPLAINED;
363  sql_command_flags[SQLCOM_DELETE_MULTI]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
364  CF_CAN_GENERATE_ROW_EVENTS |
365  CF_OPTIMIZER_TRACE |
366  CF_CAN_BE_EXPLAINED;
367  sql_command_flags[SQLCOM_REPLACE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
368  CF_CAN_GENERATE_ROW_EVENTS |
369  CF_OPTIMIZER_TRACE |
370  CF_CAN_BE_EXPLAINED;
371  sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
372  CF_CAN_GENERATE_ROW_EVENTS |
373  CF_OPTIMIZER_TRACE |
374  CF_CAN_BE_EXPLAINED;
375  sql_command_flags[SQLCOM_SELECT]= CF_REEXECUTION_FRAGILE |
376  CF_CAN_GENERATE_ROW_EVENTS |
377  CF_OPTIMIZER_TRACE |
378  CF_CAN_BE_EXPLAINED;
379  // (1) so that subquery is traced when doing "SET @var = (subquery)"
380  /*
381  @todo SQLCOM_SET_OPTION should have CF_CAN_GENERATE_ROW_EVENTS
382  set, because it may invoke a stored function that generates row
383  events. /Sven
384  */
385  sql_command_flags[SQLCOM_SET_OPTION]= CF_REEXECUTION_FRAGILE |
386  CF_AUTO_COMMIT_TRANS |
387  CF_CAN_GENERATE_ROW_EVENTS |
388  CF_OPTIMIZER_TRACE; // (1)
389  // (1) so that subquery is traced when doing "DO @var := (subquery)"
390  sql_command_flags[SQLCOM_DO]= CF_REEXECUTION_FRAGILE |
391  CF_CAN_GENERATE_ROW_EVENTS |
392  CF_OPTIMIZER_TRACE; // (1)
393 
394  sql_command_flags[SQLCOM_SHOW_STATUS_PROC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
395  sql_command_flags[SQLCOM_SHOW_STATUS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
396  sql_command_flags[SQLCOM_SHOW_DATABASES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
397  sql_command_flags[SQLCOM_SHOW_TRIGGERS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
398  sql_command_flags[SQLCOM_SHOW_EVENTS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
399  sql_command_flags[SQLCOM_SHOW_OPEN_TABLES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
400  sql_command_flags[SQLCOM_SHOW_PLUGINS]= CF_STATUS_COMMAND;
401  sql_command_flags[SQLCOM_SHOW_FIELDS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
402  sql_command_flags[SQLCOM_SHOW_KEYS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
403  sql_command_flags[SQLCOM_SHOW_VARIABLES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
404  sql_command_flags[SQLCOM_SHOW_CHARSETS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
405  sql_command_flags[SQLCOM_SHOW_COLLATIONS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
406  sql_command_flags[SQLCOM_SHOW_BINLOGS]= CF_STATUS_COMMAND;
407  sql_command_flags[SQLCOM_SHOW_SLAVE_HOSTS]= CF_STATUS_COMMAND;
408  sql_command_flags[SQLCOM_SHOW_BINLOG_EVENTS]= CF_STATUS_COMMAND;
409  sql_command_flags[SQLCOM_SHOW_STORAGE_ENGINES]= CF_STATUS_COMMAND;
410  sql_command_flags[SQLCOM_SHOW_PRIVILEGES]= CF_STATUS_COMMAND;
411  sql_command_flags[SQLCOM_SHOW_WARNS]= CF_STATUS_COMMAND | CF_DIAGNOSTIC_STMT;
412  sql_command_flags[SQLCOM_SHOW_ERRORS]= CF_STATUS_COMMAND | CF_DIAGNOSTIC_STMT;
413  sql_command_flags[SQLCOM_SHOW_ENGINE_STATUS]= CF_STATUS_COMMAND;
414  sql_command_flags[SQLCOM_SHOW_ENGINE_MUTEX]= CF_STATUS_COMMAND;
415  sql_command_flags[SQLCOM_SHOW_ENGINE_LOGS]= CF_STATUS_COMMAND;
416  sql_command_flags[SQLCOM_SHOW_PROCESSLIST]= CF_STATUS_COMMAND;
417  sql_command_flags[SQLCOM_SHOW_GRANTS]= CF_STATUS_COMMAND;
418  sql_command_flags[SQLCOM_SHOW_CREATE_DB]= CF_STATUS_COMMAND;
419  sql_command_flags[SQLCOM_SHOW_CREATE]= CF_STATUS_COMMAND;
420  sql_command_flags[SQLCOM_SHOW_MASTER_STAT]= CF_STATUS_COMMAND;
421  sql_command_flags[SQLCOM_SHOW_SLAVE_STAT]= CF_STATUS_COMMAND;
422  sql_command_flags[SQLCOM_SHOW_CREATE_PROC]= CF_STATUS_COMMAND;
423  sql_command_flags[SQLCOM_SHOW_CREATE_FUNC]= CF_STATUS_COMMAND;
424  sql_command_flags[SQLCOM_SHOW_CREATE_TRIGGER]= CF_STATUS_COMMAND;
425  sql_command_flags[SQLCOM_SHOW_STATUS_FUNC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
426  sql_command_flags[SQLCOM_SHOW_PROC_CODE]= CF_STATUS_COMMAND;
427  sql_command_flags[SQLCOM_SHOW_FUNC_CODE]= CF_STATUS_COMMAND;
428  sql_command_flags[SQLCOM_SHOW_CREATE_EVENT]= CF_STATUS_COMMAND;
429  sql_command_flags[SQLCOM_SHOW_PROFILES]= CF_STATUS_COMMAND;
430  sql_command_flags[SQLCOM_SHOW_PROFILE]= CF_STATUS_COMMAND;
431  sql_command_flags[SQLCOM_BINLOG_BASE64_EVENT]= CF_STATUS_COMMAND |
432  CF_CAN_GENERATE_ROW_EVENTS;
433 
434  sql_command_flags[SQLCOM_SHOW_TABLES]= (CF_STATUS_COMMAND |
435  CF_SHOW_TABLE_COMMAND |
436  CF_REEXECUTION_FRAGILE);
437  sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND |
438  CF_SHOW_TABLE_COMMAND |
439  CF_REEXECUTION_FRAGILE);
440 
441  sql_command_flags[SQLCOM_CREATE_USER]= CF_CHANGES_DATA;
442  sql_command_flags[SQLCOM_RENAME_USER]= CF_CHANGES_DATA;
443  sql_command_flags[SQLCOM_DROP_USER]= CF_CHANGES_DATA;
444  sql_command_flags[SQLCOM_ALTER_USER]= CF_CHANGES_DATA;
445  sql_command_flags[SQLCOM_GRANT]= CF_CHANGES_DATA;
446  sql_command_flags[SQLCOM_REVOKE]= CF_CHANGES_DATA;
447  sql_command_flags[SQLCOM_REVOKE_ALL]= CF_CHANGES_DATA;
448  sql_command_flags[SQLCOM_OPTIMIZE]= CF_CHANGES_DATA;
449  sql_command_flags[SQLCOM_CREATE_FUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
450  sql_command_flags[SQLCOM_CREATE_PROCEDURE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
451  sql_command_flags[SQLCOM_CREATE_SPFUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
452  sql_command_flags[SQLCOM_DROP_PROCEDURE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
453  sql_command_flags[SQLCOM_DROP_FUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
454  sql_command_flags[SQLCOM_ALTER_PROCEDURE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
455  sql_command_flags[SQLCOM_ALTER_FUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
456  sql_command_flags[SQLCOM_INSTALL_PLUGIN]= CF_CHANGES_DATA;
457  sql_command_flags[SQLCOM_UNINSTALL_PLUGIN]= CF_CHANGES_DATA;
458 
459  /* Does not change the contents of the diagnostics area. */
460  sql_command_flags[SQLCOM_GET_DIAGNOSTICS]= CF_DIAGNOSTIC_STMT;
461 
462  /*
463  (1): without it, in "CALL some_proc((subq))", subquery would not be
464  traced.
465  */
466  sql_command_flags[SQLCOM_CALL]= CF_REEXECUTION_FRAGILE |
467  CF_CAN_GENERATE_ROW_EVENTS |
468  CF_OPTIMIZER_TRACE; // (1)
469  sql_command_flags[SQLCOM_EXECUTE]= CF_CAN_GENERATE_ROW_EVENTS;
470 
471  /*
472  The following admin table operations are allowed
473  on log tables.
474  */
475  sql_command_flags[SQLCOM_REPAIR]= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS;
476  sql_command_flags[SQLCOM_OPTIMIZE]|= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS;
477  sql_command_flags[SQLCOM_ANALYZE]= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS;
478  sql_command_flags[SQLCOM_CHECK]= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS;
479 
480  sql_command_flags[SQLCOM_CREATE_USER]|= CF_AUTO_COMMIT_TRANS;
481  sql_command_flags[SQLCOM_DROP_USER]|= CF_AUTO_COMMIT_TRANS;
482  sql_command_flags[SQLCOM_RENAME_USER]|= CF_AUTO_COMMIT_TRANS;
483  sql_command_flags[SQLCOM_ALTER_USER]|= CF_AUTO_COMMIT_TRANS;
484  sql_command_flags[SQLCOM_REVOKE]|= CF_AUTO_COMMIT_TRANS;
485  sql_command_flags[SQLCOM_REVOKE_ALL]|= CF_AUTO_COMMIT_TRANS;
486  sql_command_flags[SQLCOM_GRANT]|= CF_AUTO_COMMIT_TRANS;
487 
488  sql_command_flags[SQLCOM_ASSIGN_TO_KEYCACHE]= CF_AUTO_COMMIT_TRANS;
489  sql_command_flags[SQLCOM_PRELOAD_KEYS]= CF_AUTO_COMMIT_TRANS;
490 
491  sql_command_flags[SQLCOM_FLUSH]= CF_AUTO_COMMIT_TRANS;
492  sql_command_flags[SQLCOM_RESET]= CF_AUTO_COMMIT_TRANS;
493  sql_command_flags[SQLCOM_CREATE_SERVER]= CF_AUTO_COMMIT_TRANS;
494  sql_command_flags[SQLCOM_ALTER_SERVER]= CF_AUTO_COMMIT_TRANS;
495  sql_command_flags[SQLCOM_DROP_SERVER]= CF_AUTO_COMMIT_TRANS;
496  sql_command_flags[SQLCOM_CHANGE_MASTER]= CF_AUTO_COMMIT_TRANS;
497  sql_command_flags[SQLCOM_SLAVE_START]= CF_AUTO_COMMIT_TRANS;
498  sql_command_flags[SQLCOM_SLAVE_STOP]= CF_AUTO_COMMIT_TRANS;
499 
500  /*
501  The following statements can deal with temporary tables,
502  so temporary tables should be pre-opened for those statements to
503  simplify privilege checking.
504 
505  There are other statements that deal with temporary tables and open
506  them, but which are not listed here. The thing is that the order of
507  pre-opening temporary tables for those statements is somewhat custom.
508  */
509  sql_command_flags[SQLCOM_CREATE_TABLE]|= CF_PREOPEN_TMP_TABLES;
510  sql_command_flags[SQLCOM_DROP_TABLE]|= CF_PREOPEN_TMP_TABLES;
511  sql_command_flags[SQLCOM_CREATE_INDEX]|= CF_PREOPEN_TMP_TABLES;
512  sql_command_flags[SQLCOM_ALTER_TABLE]|= CF_PREOPEN_TMP_TABLES;
513  sql_command_flags[SQLCOM_TRUNCATE]|= CF_PREOPEN_TMP_TABLES;
514  sql_command_flags[SQLCOM_LOAD]|= CF_PREOPEN_TMP_TABLES;
515  sql_command_flags[SQLCOM_DROP_INDEX]|= CF_PREOPEN_TMP_TABLES;
516  sql_command_flags[SQLCOM_UPDATE]|= CF_PREOPEN_TMP_TABLES;
517  sql_command_flags[SQLCOM_UPDATE_MULTI]|= CF_PREOPEN_TMP_TABLES;
518  sql_command_flags[SQLCOM_INSERT_SELECT]|= CF_PREOPEN_TMP_TABLES;
519  sql_command_flags[SQLCOM_DELETE]|= CF_PREOPEN_TMP_TABLES;
520  sql_command_flags[SQLCOM_DELETE_MULTI]|= CF_PREOPEN_TMP_TABLES;
521  sql_command_flags[SQLCOM_REPLACE_SELECT]|= CF_PREOPEN_TMP_TABLES;
522  sql_command_flags[SQLCOM_SELECT]|= CF_PREOPEN_TMP_TABLES;
523  sql_command_flags[SQLCOM_SET_OPTION]|= CF_PREOPEN_TMP_TABLES;
524  sql_command_flags[SQLCOM_DO]|= CF_PREOPEN_TMP_TABLES;
525  sql_command_flags[SQLCOM_CALL]|= CF_PREOPEN_TMP_TABLES;
526  sql_command_flags[SQLCOM_CHECKSUM]|= CF_PREOPEN_TMP_TABLES;
527  sql_command_flags[SQLCOM_ANALYZE]|= CF_PREOPEN_TMP_TABLES;
528  sql_command_flags[SQLCOM_CHECK]|= CF_PREOPEN_TMP_TABLES;
529  sql_command_flags[SQLCOM_OPTIMIZE]|= CF_PREOPEN_TMP_TABLES;
530  sql_command_flags[SQLCOM_REPAIR]|= CF_PREOPEN_TMP_TABLES;
531  sql_command_flags[SQLCOM_PRELOAD_KEYS]|= CF_PREOPEN_TMP_TABLES;
532  sql_command_flags[SQLCOM_ASSIGN_TO_KEYCACHE]|= CF_PREOPEN_TMP_TABLES;
533 
534  /*
535  DDL statements that should start with closing opened handlers.
536 
537  We use this flag only for statements for which open HANDLERs
538  have to be closed before emporary tables are pre-opened.
539  */
540  sql_command_flags[SQLCOM_CREATE_TABLE]|= CF_HA_CLOSE;
541  sql_command_flags[SQLCOM_DROP_TABLE]|= CF_HA_CLOSE;
542  sql_command_flags[SQLCOM_ALTER_TABLE]|= CF_HA_CLOSE;
543  sql_command_flags[SQLCOM_TRUNCATE]|= CF_HA_CLOSE;
544  sql_command_flags[SQLCOM_REPAIR]|= CF_HA_CLOSE;
545  sql_command_flags[SQLCOM_OPTIMIZE]|= CF_HA_CLOSE;
546  sql_command_flags[SQLCOM_ANALYZE]|= CF_HA_CLOSE;
547  sql_command_flags[SQLCOM_CHECK]|= CF_HA_CLOSE;
548  sql_command_flags[SQLCOM_CREATE_INDEX]|= CF_HA_CLOSE;
549  sql_command_flags[SQLCOM_DROP_INDEX]|= CF_HA_CLOSE;
550  sql_command_flags[SQLCOM_PRELOAD_KEYS]|= CF_HA_CLOSE;
551  sql_command_flags[SQLCOM_ASSIGN_TO_KEYCACHE]|= CF_HA_CLOSE;
552 
553  /*
554  Mark statements that always are disallowed in read-only
555  transactions. Note that according to the SQL standard,
556  even temporary table DDL should be disallowed.
557  */
558  sql_command_flags[SQLCOM_CREATE_TABLE]|= CF_DISALLOW_IN_RO_TRANS;
559  sql_command_flags[SQLCOM_ALTER_TABLE]|= CF_DISALLOW_IN_RO_TRANS;
560  sql_command_flags[SQLCOM_DROP_TABLE]|= CF_DISALLOW_IN_RO_TRANS;
561  sql_command_flags[SQLCOM_RENAME_TABLE]|= CF_DISALLOW_IN_RO_TRANS;
562  sql_command_flags[SQLCOM_CREATE_INDEX]|= CF_DISALLOW_IN_RO_TRANS;
563  sql_command_flags[SQLCOM_DROP_INDEX]|= CF_DISALLOW_IN_RO_TRANS;
564  sql_command_flags[SQLCOM_CREATE_DB]|= CF_DISALLOW_IN_RO_TRANS;
565  sql_command_flags[SQLCOM_DROP_DB]|= CF_DISALLOW_IN_RO_TRANS;
566  sql_command_flags[SQLCOM_ALTER_DB_UPGRADE]|= CF_DISALLOW_IN_RO_TRANS;
567  sql_command_flags[SQLCOM_ALTER_DB]|= CF_DISALLOW_IN_RO_TRANS;
568  sql_command_flags[SQLCOM_CREATE_VIEW]|= CF_DISALLOW_IN_RO_TRANS;
569  sql_command_flags[SQLCOM_DROP_VIEW]|= CF_DISALLOW_IN_RO_TRANS;
570  sql_command_flags[SQLCOM_CREATE_TRIGGER]|= CF_DISALLOW_IN_RO_TRANS;
571  sql_command_flags[SQLCOM_DROP_TRIGGER]|= CF_DISALLOW_IN_RO_TRANS;
572  sql_command_flags[SQLCOM_CREATE_EVENT]|= CF_DISALLOW_IN_RO_TRANS;
573  sql_command_flags[SQLCOM_ALTER_EVENT]|= CF_DISALLOW_IN_RO_TRANS;
574  sql_command_flags[SQLCOM_DROP_EVENT]|= CF_DISALLOW_IN_RO_TRANS;
575  sql_command_flags[SQLCOM_CREATE_USER]|= CF_DISALLOW_IN_RO_TRANS;
576  sql_command_flags[SQLCOM_RENAME_USER]|= CF_DISALLOW_IN_RO_TRANS;
577  sql_command_flags[SQLCOM_ALTER_USER]|= CF_DISALLOW_IN_RO_TRANS;
578  sql_command_flags[SQLCOM_DROP_USER]|= CF_DISALLOW_IN_RO_TRANS;
579  sql_command_flags[SQLCOM_CREATE_SERVER]|= CF_DISALLOW_IN_RO_TRANS;
580  sql_command_flags[SQLCOM_ALTER_SERVER]|= CF_DISALLOW_IN_RO_TRANS;
581  sql_command_flags[SQLCOM_DROP_SERVER]|= CF_DISALLOW_IN_RO_TRANS;
582  sql_command_flags[SQLCOM_CREATE_FUNCTION]|= CF_DISALLOW_IN_RO_TRANS;
583  sql_command_flags[SQLCOM_CREATE_PROCEDURE]|= CF_DISALLOW_IN_RO_TRANS;
584  sql_command_flags[SQLCOM_CREATE_SPFUNCTION]|=CF_DISALLOW_IN_RO_TRANS;
585  sql_command_flags[SQLCOM_DROP_PROCEDURE]|= CF_DISALLOW_IN_RO_TRANS;
586  sql_command_flags[SQLCOM_DROP_FUNCTION]|= CF_DISALLOW_IN_RO_TRANS;
587  sql_command_flags[SQLCOM_ALTER_PROCEDURE]|= CF_DISALLOW_IN_RO_TRANS;
588  sql_command_flags[SQLCOM_ALTER_FUNCTION]|= CF_DISALLOW_IN_RO_TRANS;
589  sql_command_flags[SQLCOM_TRUNCATE]|= CF_DISALLOW_IN_RO_TRANS;
590  sql_command_flags[SQLCOM_ALTER_TABLESPACE]|= CF_DISALLOW_IN_RO_TRANS;
591  sql_command_flags[SQLCOM_REPAIR]|= CF_DISALLOW_IN_RO_TRANS;
592  sql_command_flags[SQLCOM_OPTIMIZE]|= CF_DISALLOW_IN_RO_TRANS;
593  sql_command_flags[SQLCOM_GRANT]|= CF_DISALLOW_IN_RO_TRANS;
594  sql_command_flags[SQLCOM_REVOKE]|= CF_DISALLOW_IN_RO_TRANS;
595  sql_command_flags[SQLCOM_REVOKE_ALL]|= CF_DISALLOW_IN_RO_TRANS;
596  sql_command_flags[SQLCOM_INSTALL_PLUGIN]|= CF_DISALLOW_IN_RO_TRANS;
597  sql_command_flags[SQLCOM_UNINSTALL_PLUGIN]|= CF_DISALLOW_IN_RO_TRANS;
598 }
599 
600 bool sqlcom_can_generate_row_events(const THD *thd)
601 {
602  return (sql_command_flags[thd->lex->sql_command] &
603  CF_CAN_GENERATE_ROW_EVENTS);
604 }
605 
606 bool is_update_query(enum enum_sql_command command)
607 {
608  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
609  return (sql_command_flags[command] & CF_CHANGES_DATA) != 0;
610 }
611 
612 
613 bool is_explainable_query(enum enum_sql_command command)
614 {
615  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
616  return (sql_command_flags[command] & CF_CAN_BE_EXPLAINED) != 0;
617 }
618 
624 bool is_log_table_write_query(enum enum_sql_command command)
625 {
626  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
627  return (sql_command_flags[command] & CF_WRITE_LOGS_COMMAND) != 0;
628 }
629 
630 void execute_init_command(THD *thd, LEX_STRING *init_command,
631  mysql_rwlock_t *var_lock)
632 {
633  Vio* save_vio;
634  ulong save_client_capabilities;
635 
636  mysql_rwlock_rdlock(var_lock);
637  if (!init_command->length)
638  {
639  mysql_rwlock_unlock(var_lock);
640  return;
641  }
642 
643  /*
644  copy the value under a lock, and release the lock.
645  init_command has to be executed without a lock held,
646  as it may try to change itself
647  */
648  size_t len= init_command->length;
649  char *buf= thd->strmake(init_command->str, len);
650  mysql_rwlock_unlock(var_lock);
651 
652 #if defined(ENABLED_PROFILING)
653  thd->profiling.start_new_query();
654  thd->profiling.set_query_source(buf, len);
655 #endif
656 
657  THD_STAGE_INFO(thd, stage_execution_of_init_command);
658  save_client_capabilities= thd->client_capabilities;
659  thd->client_capabilities|= CLIENT_MULTI_QUERIES;
660  /*
661  We don't need return result of execution to client side.
662  To forbid this we should set thd->net.vio to 0.
663  */
664  save_vio= thd->net.vio;
665  thd->net.vio= 0;
666  dispatch_command(COM_QUERY, thd, buf, len);
667  thd->client_capabilities= save_client_capabilities;
668  thd->net.vio= save_vio;
669 
670 #if defined(ENABLED_PROFILING)
671  thd->profiling.finish_current_query();
672 #endif
673 }
674 
675 static char *fgets_fn(char *buffer, size_t size, fgets_input_t input, int *error)
676 {
677  MYSQL_FILE *in= static_cast<MYSQL_FILE*> (input);
678  char *line= mysql_file_fgets(buffer, size, in);
679  if (error)
680  *error= (line == NULL) ? ferror(in->m_file) : 0;
681  return line;
682 }
683 
684 static void handle_bootstrap_impl(THD *thd)
685 {
686  MYSQL_FILE *file= bootstrap_file;
687  char buffer[MAX_BOOTSTRAP_QUERY_SIZE];
688  char *query;
689  int length;
690  int rc;
691  int error= 0;
692 
693  DBUG_ENTER("handle_bootstrap");
694 
695 #ifndef EMBEDDED_LIBRARY
696  pthread_detach_this_thread();
697  thd->thread_stack= (char*) &thd;
698 #endif /* EMBEDDED_LIBRARY */
699 
700  thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME));
701  thd->security_ctx->priv_user[0]= thd->security_ctx->priv_host[0]=0;
702  /*
703  Make the "client" handle multiple results. This is necessary
704  to enable stored procedures with SELECTs and Dynamic SQL
705  in init-file.
706  */
707  thd->client_capabilities|= CLIENT_MULTI_RESULTS;
708 
709  thd->init_for_queries();
710 
711  buffer[0]= '\0';
712 
713  for ( ; ; )
714  {
715  rc= read_bootstrap_query(buffer, &length, file, fgets_fn, &error);
716 
717  if (rc == READ_BOOTSTRAP_EOF)
718  break;
719  /*
720  Check for bootstrap file errors. SQL syntax errors will be
721  caught below.
722  */
723  if (rc != READ_BOOTSTRAP_SUCCESS)
724  {
725  /*
726  mysql_parse() may have set a successful error status for the previous
727  query. We must clear the error status to report the bootstrap error.
728  */
729  thd->get_stmt_da()->reset_diagnostics_area();
730 
731  /* Get the nearest query text for reference. */
732  char *err_ptr= buffer + (length <= MAX_BOOTSTRAP_ERROR_LEN ?
733  0 : (length - MAX_BOOTSTRAP_ERROR_LEN));
734  switch (rc)
735  {
736  case READ_BOOTSTRAP_ERROR:
737  my_printf_error(ER_UNKNOWN_ERROR, "Bootstrap file error, return code (%d). "
738  "Nearest query: '%s'", MYF(0), error, err_ptr);
739  break;
740 
741  case READ_BOOTSTRAP_QUERY_SIZE:
742  my_printf_error(ER_UNKNOWN_ERROR, "Boostrap file error. Query size "
743  "exceeded %d bytes near '%s'.", MYF(0),
744  MAX_BOOTSTRAP_LINE_SIZE, err_ptr);
745  break;
746 
747  default:
748  DBUG_ASSERT(false);
749  break;
750  }
751 
752  thd->protocol->end_statement();
753  bootstrap_error= 1;
754  break;
755  }
756 
757  query= (char *) thd->memdup_w_gap(buffer, length + 1,
758  thd->db_length + 1 +
759  QUERY_CACHE_FLAGS_SIZE);
760  size_t db_len= 0;
761  memcpy(query + length + 1, (char *) &db_len, sizeof(size_t));
762  thd->set_query_and_id(query, length, thd->charset(), next_query_id());
763  DBUG_PRINT("query",("%-.4096s",thd->query()));
764 #if defined(ENABLED_PROFILING)
765  thd->profiling.start_new_query();
766  thd->profiling.set_query_source(thd->query(), length);
767 #endif
768 
769  /*
770  We don't need to obtain LOCK_thread_count here because in bootstrap
771  mode we have only one thread.
772  */
773  thd->set_time();
774  Parser_state parser_state;
775  if (parser_state.init(thd, thd->query(), length))
776  {
777  thd->protocol->end_statement();
778  bootstrap_error= 1;
779  break;
780  }
781 
782  mysql_parse(thd, thd->query(), length, &parser_state);
783 
784  bootstrap_error= thd->is_error();
785  thd->protocol->end_statement();
786 
787 #if defined(ENABLED_PROFILING)
788  thd->profiling.finish_current_query();
789 #endif
790 
791  if (bootstrap_error)
792  break;
793 
794  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
795  free_root(&thd->transaction.mem_root,MYF(MY_KEEP_PREALLOC));
796  }
797 
798  DBUG_VOID_RETURN;
799 }
800 
801 
808 pthread_handler_t handle_bootstrap(void *arg)
809 {
810  THD *thd=(THD*) arg;
811 
812  mysql_thread_set_psi_id(thd->thread_id);
813 
814  do_handle_bootstrap(thd);
815  return 0;
816 }
817 
818 void do_handle_bootstrap(THD *thd)
819 {
820  bool thd_added= false;
821  /* The following must be called before DBUG_ENTER */
822  thd->thread_stack= (char*) &thd;
823  if (my_thread_init() || thd->store_globals())
824  {
825 #ifndef EMBEDDED_LIBRARY
826  close_connection(thd, ER_OUT_OF_RESOURCES);
827 #endif
828  thd->fatal_error();
829  goto end;
830  }
831 
832  mysql_mutex_lock(&LOCK_thread_count);
833  thd_added= true;
834  add_global_thread(thd);
835  mysql_mutex_unlock(&LOCK_thread_count);
836 
837  handle_bootstrap_impl(thd);
838 
839 end:
840  net_end(&thd->net);
841  thd->release_resources();
842 
843  if (thd_added)
844  {
845  mysql_mutex_lock(&LOCK_thread_count);
846  remove_global_thread(thd);
847  mysql_mutex_unlock(&LOCK_thread_count);
848  }
849  /*
850  For safety we delete the thd before signalling that bootstrap is done,
851  since the server will be taken down immediately.
852  */
853  delete thd;
854 
855  mysql_mutex_lock(&LOCK_thread_count);
856  in_bootstrap= FALSE;
857  mysql_cond_broadcast(&COND_thread_count);
858  mysql_mutex_unlock(&LOCK_thread_count);
859 
860 #ifndef EMBEDDED_LIBRARY
861  my_thread_end();
862  pthread_exit(0);
863 #endif
864 
865  return;
866 }
867 
868 
869 /* This works because items are allocated with sql_alloc() */
870 
871 void free_items(Item *item)
872 {
873  Item *next;
874  DBUG_ENTER("free_items");
875  for (; item ; item=next)
876  {
877  next=item->next;
878  item->delete_self();
879  }
880  DBUG_VOID_RETURN;
881 }
882 
887 void cleanup_items(Item *item)
888 {
889  DBUG_ENTER("cleanup_items");
890  for (; item ; item=item->next)
891  item->cleanup();
892  DBUG_VOID_RETURN;
893 }
894 
895 #ifndef EMBEDDED_LIBRARY
896 
909 bool do_command(THD *thd)
910 {
911  bool return_value;
912  char *packet= 0;
913  ulong packet_length;
914  NET *net= &thd->net;
915  enum enum_server_command command;
916 
917  DBUG_ENTER("do_command");
918 
919  /*
920  indicator of uninitialized lex => normal flow of errors handling
921  (see my_message_sql)
922  */
923  thd->lex->current_select= 0;
924 
925  /*
926  This thread will do a blocking read from the client which
927  will be interrupted when the next command is received from
928  the client, the connection is closed or "net_wait_timeout"
929  number of seconds has passed.
930  */
931  my_net_set_read_timeout(net, thd->variables.net_wait_timeout);
932 
933  /*
934  XXX: this code is here only to clear possible errors of init_connect.
935  Consider moving to init_connect() instead.
936  */
937  thd->clear_error(); // Clear error message
938  thd->get_stmt_da()->reset_diagnostics_area();
939 
940  net_new_transaction(net);
941 
942  /*
943  Synchronization point for testing of KILL_CONNECTION.
944  This sync point can wait here, to simulate slow code execution
945  between the last test of thd->killed and blocking in read().
946 
947  The goal of this test is to verify that a connection does not
948  hang, if it is killed at this point of execution.
949  (Bug#37780 - main.kill fails randomly)
950 
951  Note that the sync point wait itself will be terminated by a
952  kill. In this case it consumes a condition broadcast, but does
953  not change anything else. The consumed broadcast should not
954  matter here, because the read/recv() below doesn't use it.
955  */
956  DEBUG_SYNC(thd, "before_do_command_net_read");
957 
958  /*
959  Because of networking layer callbacks in place,
960  this call will maintain the following instrumentation:
961  - IDLE events
962  - SOCKET events
963  - STATEMENT events
964  - STAGE events
965  when reading a new network packet.
966  In particular, a new instrumented statement is started.
967  See init_net_server_extension()
968  */
969  thd->m_server_idle= true;
970  packet_length= my_net_read(net);
971  thd->m_server_idle= false;
972 
973  if (packet_length == packet_error)
974  {
975  DBUG_PRINT("info",("Got error %d reading command from socket %s",
976  net->error,
977  vio_description(net->vio)));
978 
979  /* Instrument this broken statement as "statement/com/error" */
980  thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
981  com_statement_info[COM_END].m_key);
982 
983  /* Check if we can continue without closing the connection */
984 
985  /* The error must be set. */
986  DBUG_ASSERT(thd->is_error());
987  thd->protocol->end_statement();
988 
989  /* Mark the statement completed. */
990  MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
991  thd->m_statement_psi= NULL;
992 
993  if (net->error != 3)
994  {
995  return_value= TRUE; // We have to close it.
996  goto out;
997  }
998 
999  net->error= 0;
1000  return_value= FALSE;
1001  goto out;
1002  }
1003 
1004  packet= (char*) net->read_pos;
1005  /*
1006  'packet_length' contains length of data, as it was stored in packet
1007  header. In case of malformed header, my_net_read returns zero.
1008  If packet_length is not zero, my_net_read ensures that the returned
1009  number of bytes was actually read from network.
1010  There is also an extra safety measure in my_net_read:
1011  it sets packet[packet_length]= 0, but only for non-zero packets.
1012  */
1013  if (packet_length == 0) /* safety */
1014  {
1015  /* Initialize with COM_SLEEP packet */
1016  packet[0]= (uchar) COM_SLEEP;
1017  packet_length= 1;
1018  }
1019  /* Do not rely on my_net_read, extra safety against programming errors. */
1020  packet[packet_length]= '\0'; /* safety */
1021 
1022  command= (enum enum_server_command) (uchar) packet[0];
1023 
1024  if (command >= COM_END)
1025  command= COM_END; // Wrong command
1026 
1027  DBUG_PRINT("info",("Command on %s = %d (%s)",
1028  vio_description(net->vio), command,
1029  command_name[command].str));
1030 
1031  /* Restore read timeout value */
1032  my_net_set_read_timeout(net, thd->variables.net_read_timeout);
1033 
1034  DBUG_ASSERT(packet_length);
1035 
1036  return_value= dispatch_command(command, thd, packet+1, (uint) (packet_length-1));
1037 
1038 out:
1039  /* The statement instrumentation must be closed in all cases. */
1040  DBUG_ASSERT(thd->m_statement_psi == NULL);
1041  DBUG_RETURN(return_value);
1042 }
1043 #endif /* EMBEDDED_LIBRARY */
1044 
1059 static my_bool deny_updates_if_read_only_option(THD *thd,
1060  TABLE_LIST *all_tables)
1061 {
1062  DBUG_ENTER("deny_updates_if_read_only_option");
1063 
1064  if (!opt_readonly)
1065  DBUG_RETURN(FALSE);
1066 
1067  LEX *lex= thd->lex;
1068 
1069  const my_bool user_is_super=
1070  ((ulong)(thd->security_ctx->master_access & SUPER_ACL) ==
1071  (ulong)SUPER_ACL);
1072 
1073  if (user_is_super)
1074  DBUG_RETURN(FALSE);
1075 
1076  if (!(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA))
1077  DBUG_RETURN(FALSE);
1078 
1079  /* Multi update is an exception and is dealt with later. */
1080  if (lex->sql_command == SQLCOM_UPDATE_MULTI)
1081  DBUG_RETURN(FALSE);
1082 
1083  const my_bool create_temp_tables=
1084  (lex->sql_command == SQLCOM_CREATE_TABLE) &&
1085  (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE);
1086 
1087  const my_bool drop_temp_tables=
1088  (lex->sql_command == SQLCOM_DROP_TABLE) &&
1089  lex->drop_temporary;
1090 
1091  const my_bool update_real_tables=
1092  some_non_temp_table_to_be_updated(thd, all_tables) &&
1093  !(create_temp_tables || drop_temp_tables);
1094 
1095 
1096  const my_bool create_or_drop_databases=
1097  (lex->sql_command == SQLCOM_CREATE_DB) ||
1098  (lex->sql_command == SQLCOM_DROP_DB);
1099 
1100  if (update_real_tables || create_or_drop_databases)
1101  {
1102  /*
1103  An attempt was made to modify one or more non-temporary tables.
1104  */
1105  DBUG_RETURN(TRUE);
1106  }
1107 
1108 
1109  /* Assuming that only temporary tables are modified. */
1110  DBUG_RETURN(FALSE);
1111 }
1112 
1134 bool dispatch_command(enum enum_server_command command, THD *thd,
1135  char* packet, uint packet_length)
1136 {
1137  NET *net= &thd->net;
1138  bool error= 0;
1139  DBUG_ENTER("dispatch_command");
1140  DBUG_PRINT("info",("packet: '%*.s'; command: %d", packet_length, packet, command));
1141 
1142  /* SHOW PROFILE instrumentation, begin */
1143 #if defined(ENABLED_PROFILING)
1144  thd->profiling.start_new_query();
1145 #endif
1146 
1147  /* DTRACE instrumentation, begin */
1148  MYSQL_COMMAND_START(thd->thread_id, command,
1149  &thd->security_ctx->priv_user[0],
1150  (char *) thd->security_ctx->host_or_ip);
1151 
1152  /* Performance Schema Interface instrumentation, begin */
1153  thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
1154  com_statement_info[command].m_key);
1155 
1156  thd->set_command(command);
1157  /*
1158  Commands which always take a long time are logged into
1159  the slow log only if opt_log_slow_admin_statements is set.
1160  */
1161  thd->enable_slow_log= TRUE;
1162  thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
1163  thd->set_time();
1164  if (!thd->is_valid_time())
1165  {
1166  /*
1167  If the time has got past 2038 we need to shut this server down
1168  We do this by making sure every command is a shutdown and we
1169  have enough privileges to shut the server down
1170 
1171  TODO: remove this when we have full 64 bit my_time_t support
1172  */
1173  thd->security_ctx->master_access|= SHUTDOWN_ACL;
1174  command= COM_SHUTDOWN;
1175  }
1176  thd->set_query_id(next_query_id());
1177  inc_thread_running();
1178 
1179  if (!(server_command_flags[command] & CF_SKIP_QUESTIONS))
1180  statistic_increment(thd->status_var.questions, &LOCK_status);
1181 
1186  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
1187 
1198  if (unlikely(thd->security_ctx->password_expired &&
1199  command != COM_QUERY &&
1200  command != COM_STMT_CLOSE &&
1201  command != COM_STMT_SEND_LONG_DATA &&
1202  command != COM_PING &&
1203  command != COM_QUIT))
1204  {
1205  my_error(ER_MUST_CHANGE_PASSWORD, MYF(0));
1206  goto done;
1207  }
1208 
1209  switch (command) {
1210  case COM_INIT_DB:
1211  {
1212  LEX_STRING tmp;
1213  status_var_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB]);
1214  thd->convert_string(&tmp, system_charset_info,
1215  packet, packet_length, thd->charset());
1216  if (!mysql_change_db(thd, &tmp, FALSE))
1217  {
1218  general_log_write(thd, command, thd->db, thd->db_length);
1219  my_ok(thd);
1220  }
1221  break;
1222  }
1223 #ifdef HAVE_REPLICATION
1224  case COM_REGISTER_SLAVE:
1225  {
1226  if (!register_slave(thd, (uchar*)packet, packet_length))
1227  my_ok(thd);
1228  break;
1229  }
1230 #endif
1231  case COM_CHANGE_USER:
1232  {
1233  int auth_rc;
1234  status_var_increment(thd->status_var.com_other);
1235 
1236  thd->change_user();
1237  thd->clear_error(); // if errors from rollback
1238 
1239  /* acl_authenticate() takes the data from net->read_pos */
1240  net->read_pos= (uchar*)packet;
1241 
1242  USER_CONN *save_user_connect=
1243  const_cast<USER_CONN*>(thd->get_user_connect());
1244  char *save_db= thd->db;
1245  uint save_db_length= thd->db_length;
1246  Security_context save_security_ctx= *thd->security_ctx;
1247 
1248  auth_rc= acl_authenticate(thd, packet_length);
1249  MYSQL_AUDIT_NOTIFY_CONNECTION_CHANGE_USER(thd);
1250  if (auth_rc)
1251  {
1252  my_free(thd->security_ctx->user);
1253  *thd->security_ctx= save_security_ctx;
1254  thd->set_user_connect(save_user_connect);
1255  thd->reset_db(save_db, save_db_length);
1256 
1257  my_error(ER_ACCESS_DENIED_CHANGE_USER_ERROR, MYF(0),
1258  thd->security_ctx->user,
1259  thd->security_ctx->host_or_ip,
1260  (thd->password ? ER(ER_YES) : ER(ER_NO)));
1261  thd->killed= THD::KILL_CONNECTION;
1262  error=true;
1263  }
1264  else
1265  {
1266 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1267  /* we've authenticated new user */
1268  if (save_user_connect)
1269  decrease_user_connections(save_user_connect);
1270 #endif /* NO_EMBEDDED_ACCESS_CHECKS */
1271  mysql_mutex_lock(&thd->LOCK_thd_data);
1272  my_free(save_db);
1273  mysql_mutex_unlock(&thd->LOCK_thd_data);
1274  my_free(save_security_ctx.user);
1275 
1276  }
1277  break;
1278  }
1279  case COM_STMT_EXECUTE:
1280  {
1281  mysqld_stmt_execute(thd, packet, packet_length);
1282  break;
1283  }
1284  case COM_STMT_FETCH:
1285  {
1286  mysqld_stmt_fetch(thd, packet, packet_length);
1287  break;
1288  }
1289  case COM_STMT_SEND_LONG_DATA:
1290  {
1291  mysql_stmt_get_longdata(thd, packet, packet_length);
1292  break;
1293  }
1294  case COM_STMT_PREPARE:
1295  {
1296  mysqld_stmt_prepare(thd, packet, packet_length);
1297  break;
1298  }
1299  case COM_STMT_CLOSE:
1300  {
1301  mysqld_stmt_close(thd, packet, packet_length);
1302  break;
1303  }
1304  case COM_STMT_RESET:
1305  {
1306  mysqld_stmt_reset(thd, packet, packet_length);
1307  break;
1308  }
1309  case COM_QUERY:
1310  {
1311  if (alloc_query(thd, packet, packet_length))
1312  break; // fatal error is set
1313  MYSQL_QUERY_START(thd->query(), thd->thread_id,
1314  (char *) (thd->db ? thd->db : ""),
1315  &thd->security_ctx->priv_user[0],
1316  (char *) thd->security_ctx->host_or_ip);
1317  char *packet_end= thd->query() + thd->query_length();
1318 
1319  if (opt_log_raw)
1320  general_log_write(thd, command, thd->query(), thd->query_length());
1321 
1322  DBUG_PRINT("query",("%-.4096s",thd->query()));
1323 
1324 #if defined(ENABLED_PROFILING)
1325  thd->profiling.set_query_source(thd->query(), thd->query_length());
1326 #endif
1327 
1328  MYSQL_SET_STATEMENT_TEXT(thd->m_statement_psi, thd->query(), thd->query_length());
1329 
1330  Parser_state parser_state;
1331  if (parser_state.init(thd, thd->query(), thd->query_length()))
1332  break;
1333 
1334  mysql_parse(thd, thd->query(), thd->query_length(), &parser_state);
1335 
1336  while (!thd->killed && (parser_state.m_lip.found_semicolon != NULL) &&
1337  ! thd->is_error())
1338  {
1339  /*
1340  Multiple queries exits, execute them individually
1341  */
1342  char *beginning_of_next_stmt= (char*) parser_state.m_lip.found_semicolon;
1343 
1344  /* Finalize server status flags after executing a statement. */
1345  thd->update_server_status();
1346  thd->protocol->end_statement();
1347  query_cache_end_of_result(thd);
1348 
1349  mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_STATUS,
1350  thd->get_stmt_da()->is_error() ?
1351  thd->get_stmt_da()->sql_errno() : 0,
1352  command_name[command].str);
1353 
1354  ulong length= (ulong)(packet_end - beginning_of_next_stmt);
1355 
1356  log_slow_statement(thd);
1357 
1358  /* Remove garbage at start of query */
1359  while (length > 0 && my_isspace(thd->charset(), *beginning_of_next_stmt))
1360  {
1361  beginning_of_next_stmt++;
1362  length--;
1363  }
1364 
1365 /* PSI end */
1366  MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
1367  thd->m_statement_psi= NULL;
1368 
1369 /* DTRACE end */
1370  if (MYSQL_QUERY_DONE_ENABLED())
1371  {
1372  MYSQL_QUERY_DONE(thd->is_error());
1373  }
1374 
1375 /* SHOW PROFILE end */
1376 #if defined(ENABLED_PROFILING)
1377  thd->profiling.finish_current_query();
1378 #endif
1379 
1380 /* SHOW PROFILE begin */
1381 #if defined(ENABLED_PROFILING)
1382  thd->profiling.start_new_query("continuing");
1383  thd->profiling.set_query_source(beginning_of_next_stmt, length);
1384 #endif
1385 
1386 /* DTRACE begin */
1387  MYSQL_QUERY_START(beginning_of_next_stmt, thd->thread_id,
1388  (char *) (thd->db ? thd->db : ""),
1389  &thd->security_ctx->priv_user[0],
1390  (char *) thd->security_ctx->host_or_ip);
1391 
1392 /* PSI begin */
1393  thd->m_statement_psi= MYSQL_START_STATEMENT(&thd->m_statement_state,
1394  com_statement_info[command].m_key,
1395  thd->db, thd->db_length,
1396  thd->charset());
1397  THD_STAGE_INFO(thd, stage_init);
1398  MYSQL_SET_STATEMENT_TEXT(thd->m_statement_psi, beginning_of_next_stmt, length);
1399 
1400  thd->set_query_and_id(beginning_of_next_stmt, length,
1401  thd->charset(), next_query_id());
1402  /*
1403  Count each statement from the client.
1404  */
1405  statistic_increment(thd->status_var.questions, &LOCK_status);
1406  thd->set_time(); /* Reset the query start time. */
1407  parser_state.reset(beginning_of_next_stmt, length);
1408  /* TODO: set thd->lex->sql_command to SQLCOM_END here */
1409  mysql_parse(thd, beginning_of_next_stmt, length, &parser_state);
1410  }
1411 
1412  DBUG_PRINT("info",("query ready"));
1413  break;
1414  }
1415  case COM_FIELD_LIST: // This isn't actually needed
1416 #ifdef DONT_ALLOW_SHOW_COMMANDS
1417  my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
1418  MYF(0)); /* purecov: inspected */
1419  break;
1420 #else
1421  {
1422  char *fields, *packet_end= packet + packet_length, *arg_end;
1423  /* Locked closure of all tables */
1424  TABLE_LIST table_list;
1426  LEX_STRING db;
1427  /*
1428  SHOW statements should not add the used tables to the list of tables
1429  used in a transaction.
1430  */
1431  MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
1432 
1433  status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
1434  if (thd->copy_db_to(&db.str, &db.length))
1435  break;
1436  /*
1437  We have name + wildcard in packet, separated by endzero
1438  */
1439  arg_end= strend(packet);
1440  uint arg_length= arg_end - packet;
1441 
1442  /* Check given table name length. */
1443  if (arg_length >= packet_length || arg_length > NAME_LEN)
1444  {
1445  my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1446  break;
1447  }
1448  thd->convert_string(&table_name, system_charset_info,
1449  packet, arg_length, thd->charset());
1450  enum_ident_name_check ident_check_status=
1451  check_table_name(table_name.str, table_name.length, FALSE);
1452  if (ident_check_status == IDENT_NAME_WRONG)
1453  {
1454  /* this is OK due to convert_string() null-terminating the string */
1455  my_error(ER_WRONG_TABLE_NAME, MYF(0), table_name.str);
1456  break;
1457  }
1458  else if (ident_check_status == IDENT_NAME_TOO_LONG)
1459  {
1460  my_error(ER_TOO_LONG_IDENT, MYF(0), table_name.str);
1461  break;
1462  }
1463  packet= arg_end + 1;
1465  lex_start(thd);
1466  /* Must be before we init the table list. */
1467  if (lower_case_table_names)
1468  table_name.length= my_casedn_str(files_charset_info, table_name.str);
1469  table_list.init_one_table(db.str, db.length, table_name.str,
1470  table_name.length, table_name.str, TL_READ);
1471  /*
1472  Init TABLE_LIST members necessary when the undelrying
1473  table is view.
1474  */
1475  table_list.select_lex= &(thd->lex->select_lex);
1476  thd->lex->
1477  select_lex.table_list.link_in_list(&table_list,
1478  &table_list.next_local);
1479  thd->lex->add_to_query_tables(&table_list);
1480 
1481  if (is_infoschema_db(table_list.db, table_list.db_length))
1482  {
1483  ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, table_list.alias);
1484  if (schema_table)
1485  table_list.schema_table= schema_table;
1486  }
1487 
1488  uint query_length= (uint) (packet_end - packet); // Don't count end \0
1489  if (!(fields= (char *) thd->memdup(packet, query_length + 1)))
1490  break;
1491  thd->set_query(fields, query_length);
1492  general_log_print(thd, command, "%s %s", table_list.table_name, fields);
1493 
1494  if (open_temporary_tables(thd, &table_list))
1495  break;
1496 
1497  if (check_table_access(thd, SELECT_ACL, &table_list,
1498  TRUE, UINT_MAX, FALSE))
1499  break;
1500  /*
1501  Turn on an optimization relevant if the underlying table
1502  is a view: do not fill derived tables.
1503  */
1504  thd->lex->sql_command= SQLCOM_SHOW_FIELDS;
1505 
1506  // See comment in opt_trace_disable_if_no_security_context_access()
1507  Opt_trace_start ots(thd, &table_list, thd->lex->sql_command, NULL,
1508  NULL, 0, NULL, NULL);
1509 
1510  mysqld_list_fields(thd,&table_list,fields);
1511 
1512  thd->lex->unit.cleanup();
1513  /* No need to rollback statement transaction, it's not started. */
1514  DBUG_ASSERT(thd->transaction.stmt.is_empty());
1515  close_thread_tables(thd);
1516  thd->mdl_context.rollback_to_savepoint(mdl_savepoint);
1517 
1518  if (thd->transaction_rollback_request)
1519  {
1520  /*
1521  Transaction rollback was requested since MDL deadlock was
1522  discovered while trying to open tables. Rollback transaction
1523  in all storage engines including binary log and release all
1524  locks.
1525  */
1526  trans_rollback_implicit(thd);
1527  thd->mdl_context.release_transactional_locks();
1528  }
1529 
1530  thd->cleanup_after_query();
1531  break;
1532  }
1533 #endif
1534  case COM_QUIT:
1535  /* We don't calculate statistics for this command */
1536  general_log_print(thd, command, NullS);
1537  net->error=0; // Don't give 'abort' message
1538  thd->get_stmt_da()->disable_status(); // Don't send anything back
1539  error=TRUE; // End server
1540  break;
1541 #ifndef EMBEDDED_LIBRARY
1542  case COM_BINLOG_DUMP_GTID:
1543  error= com_binlog_dump_gtid(thd, packet, packet_length);
1544  break;
1545  case COM_BINLOG_DUMP:
1546  error= com_binlog_dump(thd, packet, packet_length);
1547  break;
1548 #endif
1549  case COM_REFRESH:
1550  {
1551  int not_used;
1552 
1553  if (packet_length < 1)
1554  {
1555  my_error(ER_MALFORMED_PACKET, MYF(0));
1556  break;
1557  }
1558 
1559  /*
1560  Initialize thd->lex since it's used in many base functions, such as
1561  open_tables(). Otherwise, it remains unitialized and may cause crash
1562  during execution of COM_REFRESH.
1563  */
1564  lex_start(thd);
1565 
1566  status_var_increment(thd->status_var.com_stat[SQLCOM_FLUSH]);
1567  ulong options= (ulong) (uchar) packet[0];
1568  if (trans_commit_implicit(thd))
1569  break;
1570  thd->mdl_context.release_transactional_locks();
1571  if (check_global_access(thd,RELOAD_ACL))
1572  break;
1573  general_log_print(thd, command, NullS);
1574 #ifndef DBUG_OFF
1575  bool debug_simulate= FALSE;
1576  DBUG_EXECUTE_IF("simulate_detached_thread_refresh", debug_simulate= TRUE;);
1577  if (debug_simulate)
1578  {
1579  /*
1580  Simulate a reload without a attached thread session.
1581  Provides a environment similar to that of when the
1582  server receives a SIGHUP signal and reloads caches
1583  and flushes tables.
1584  */
1585  bool res;
1586  my_pthread_setspecific_ptr(THR_THD, NULL);
1587  res= reload_acl_and_cache(NULL, options | REFRESH_FAST,
1588  NULL, &not_used);
1589  my_pthread_setspecific_ptr(THR_THD, thd);
1590  if (res)
1591  break;
1592  }
1593  else
1594 #endif
1595  if (reload_acl_and_cache(thd, options, (TABLE_LIST*) 0, &not_used))
1596  break;
1597  if (trans_commit_implicit(thd))
1598  break;
1599  close_thread_tables(thd);
1600  thd->mdl_context.release_transactional_locks();
1601  my_ok(thd);
1602  break;
1603  }
1604 #ifndef EMBEDDED_LIBRARY
1605  case COM_SHUTDOWN:
1606  {
1607  if (packet_length < 1)
1608  {
1609  my_error(ER_MALFORMED_PACKET, MYF(0));
1610  break;
1611  }
1612  status_var_increment(thd->status_var.com_other);
1613  if (check_global_access(thd,SHUTDOWN_ACL))
1614  break; /* purecov: inspected */
1615  /*
1616  If the client is < 4.1.3, it is going to send us no argument; then
1617  packet_length is 0, packet[0] is the end 0 of the packet. Note that
1618  SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in
1619  packet[0].
1620  */
1621  enum mysql_enum_shutdown_level level;
1622  if (!thd->is_valid_time())
1623  level= SHUTDOWN_DEFAULT;
1624  else
1625  level= (enum mysql_enum_shutdown_level) (uchar) packet[0];
1626  if (level == SHUTDOWN_DEFAULT)
1627  level= SHUTDOWN_WAIT_ALL_BUFFERS; // soon default will be configurable
1628  else if (level != SHUTDOWN_WAIT_ALL_BUFFERS)
1629  {
1630  my_error(ER_NOT_SUPPORTED_YET, MYF(0), "this shutdown level");
1631  break;
1632  }
1633  DBUG_PRINT("quit",("Got shutdown command for level %u", level));
1634  general_log_print(thd, command, NullS);
1635  my_eof(thd);
1636  kill_mysql();
1637  error=TRUE;
1638  break;
1639  }
1640 #endif
1641  case COM_STATISTICS:
1642  {
1643  STATUS_VAR current_global_status_var;
1644  ulong uptime;
1645  uint length __attribute__((unused));
1646  ulonglong queries_per_second1000;
1647  char buff[250];
1648  uint buff_len= sizeof(buff);
1649 
1650  general_log_print(thd, command, NullS);
1651  status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]);
1652  calc_sum_of_all_status(&current_global_status_var);
1653  if (!(uptime= (ulong) (thd->start_time.tv_sec - server_start_time)))
1654  queries_per_second1000= 0;
1655  else
1656  queries_per_second1000= thd->query_id * LL(1000) / uptime;
1657 
1658  length= my_snprintf(buff, buff_len - 1,
1659  "Uptime: %lu Threads: %d Questions: %lu "
1660  "Slow queries: %llu Opens: %llu Flush tables: %lu "
1661  "Open tables: %u Queries per second avg: %u.%03u",
1662  uptime,
1663  (int) get_thread_count(), (ulong) thd->query_id,
1664  current_global_status_var.long_query_count,
1665  current_global_status_var.opened_tables,
1666  refresh_version,
1667  table_cache_manager.cached_tables(),
1668  (uint) (queries_per_second1000 / 1000),
1669  (uint) (queries_per_second1000 % 1000));
1670 #ifdef EMBEDDED_LIBRARY
1671  /* Store the buffer in permanent memory */
1672  my_ok(thd, 0, 0, buff);
1673 #else
1674  (void) my_net_write(net, (uchar*) buff, length);
1675  (void) net_flush(net);
1676  thd->get_stmt_da()->disable_status();
1677 #endif
1678  break;
1679  }
1680  case COM_PING:
1681  status_var_increment(thd->status_var.com_other);
1682  my_ok(thd); // Tell client we are alive
1683  break;
1684  case COM_PROCESS_INFO:
1685  status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]);
1686  if (!thd->security_ctx->priv_user[0] &&
1687  check_global_access(thd, PROCESS_ACL))
1688  break;
1689  general_log_print(thd, command, NullS);
1690  mysqld_list_processes(thd,
1691  thd->security_ctx->master_access & PROCESS_ACL ?
1692  NullS : thd->security_ctx->priv_user, 0);
1693  break;
1694  case COM_PROCESS_KILL:
1695  {
1696  if (thread_id & (~0xfffffffful))
1697  my_error(ER_DATA_OUT_OF_RANGE, MYF(0), "thread_id", "mysql_kill()");
1698  else if (packet_length < 4)
1699  my_error(ER_MALFORMED_PACKET, MYF(0));
1700  else
1701  {
1702  status_var_increment(thd->status_var.com_stat[SQLCOM_KILL]);
1703  ulong id=(ulong) uint4korr(packet);
1704  sql_kill(thd,id,false);
1705  }
1706  break;
1707  }
1708  case COM_SET_OPTION:
1709  {
1710 
1711  if (packet_length < 2)
1712  {
1713  my_error(ER_MALFORMED_PACKET, MYF(0));
1714  break;
1715  }
1716  status_var_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION]);
1717  uint opt_command= uint2korr(packet);
1718 
1719  switch (opt_command) {
1720  case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON:
1721  thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
1722  my_eof(thd);
1723  break;
1724  case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF:
1725  thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
1726  my_eof(thd);
1727  break;
1728  default:
1729  my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1730  break;
1731  }
1732  break;
1733  }
1734  case COM_DEBUG:
1735  status_var_increment(thd->status_var.com_other);
1736  if (check_global_access(thd, SUPER_ACL))
1737  break; /* purecov: inspected */
1738  mysql_print_status();
1739  general_log_print(thd, command, NullS);
1740  my_eof(thd);
1741  break;
1742  case COM_SLEEP:
1743  case COM_CONNECT: // Impossible here
1744  case COM_TIME: // Impossible from client
1745  case COM_DELAYED_INSERT:
1746  case COM_END:
1747  default:
1748  my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1749  break;
1750  }
1751 
1752 done:
1753  DBUG_ASSERT(thd->derived_tables == NULL &&
1754  (thd->open_tables == NULL ||
1755  (thd->locked_tables_mode == LTM_LOCK_TABLES)));
1756 
1757  /* Finalize server status flags after executing a command. */
1758  thd->update_server_status();
1759  if (thd->killed)
1760  thd->send_kill_message();
1761  thd->protocol->end_statement();
1762  query_cache_end_of_result(thd);
1763 
1764  if (!thd->is_error() && !thd->killed_errno())
1765  mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_RESULT, 0, 0);
1766 
1767  mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_STATUS,
1768  thd->get_stmt_da()->is_error() ?
1769  thd->get_stmt_da()->sql_errno() : 0,
1770  command_name[command].str);
1771 
1772  log_slow_statement(thd);
1773 
1774  THD_STAGE_INFO(thd, stage_cleaning_up);
1775 
1776  thd->reset_query();
1777  thd->set_command(COM_SLEEP);
1778 
1779  /* Performance Schema Interface instrumentation, end */
1780  MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
1781  thd->m_statement_psi= NULL;
1782 
1783  dec_thread_running();
1784  thd->packet.shrink(thd->variables.net_buffer_length); // Reclaim some memory
1785  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
1786 
1787  /* DTRACE instrumentation, end */
1788  if (MYSQL_QUERY_DONE_ENABLED() || MYSQL_COMMAND_DONE_ENABLED())
1789  {
1790  int res __attribute__((unused));
1791  res= (int) thd->is_error();
1792  if (command == COM_QUERY)
1793  {
1794  MYSQL_QUERY_DONE(res);
1795  }
1796  MYSQL_COMMAND_DONE(res);
1797  }
1798 
1799  /* SHOW PROFILE instrumentation, end */
1800 #if defined(ENABLED_PROFILING)
1801  thd->profiling.finish_current_query();
1802 #endif
1803 
1804  DBUG_RETURN(error);
1805 }
1806 
1807 
1821 bool log_slow_applicable(THD *thd)
1822 {
1823  DBUG_ENTER("log_slow_applicable");
1824 
1825  /*
1826  The following should never be true with our current code base,
1827  but better to keep this here so we don't accidently try to log a
1828  statement in a trigger or stored function
1829  */
1830  if (unlikely(thd->in_sub_stmt))
1831  DBUG_RETURN(false); // Don't set time for sub stmt
1832 
1833  /*
1834  Do not log administrative statements unless the appropriate option is
1835  set.
1836  */
1837  if (thd->enable_slow_log)
1838  {
1839  bool warn_no_index= ((thd->server_status &
1840  (SERVER_QUERY_NO_INDEX_USED |
1841  SERVER_QUERY_NO_GOOD_INDEX_USED)) &&
1842  opt_log_queries_not_using_indexes &&
1843  !(sql_command_flags[thd->lex->sql_command] &
1844  CF_STATUS_COMMAND));
1845  bool log_this_query= ((thd->server_status & SERVER_QUERY_WAS_SLOW) ||
1846  warn_no_index) &&
1847  (thd->get_examined_row_count() >=
1848  thd->variables.min_examined_row_limit);
1849  bool suppress_logging= log_throttle_qni.log(thd, warn_no_index);
1850 
1851  if (!suppress_logging && log_this_query)
1852  DBUG_RETURN(true);
1853  }
1854  DBUG_RETURN(false);
1855 }
1856 
1857 
1865 void log_slow_do(THD *thd)
1866 {
1867  DBUG_ENTER("log_slow_do");
1868 
1869  THD_STAGE_INFO(thd, stage_logging_slow_query);
1870  thd->status_var.long_query_count++;
1871 
1872  if (thd->rewritten_query.length())
1873  slow_log_print(thd,
1874  thd->rewritten_query.c_ptr_safe(),
1875  thd->rewritten_query.length());
1876  else
1877  slow_log_print(thd, thd->query(), thd->query_length());
1878 
1879  DBUG_VOID_RETURN;
1880 }
1881 
1882 
1896 void log_slow_statement(THD *thd)
1897 {
1898  DBUG_ENTER("log_slow_statement");
1899 
1900  if (log_slow_applicable(thd))
1901  log_slow_do(thd);
1902 
1903  DBUG_VOID_RETURN;
1904 }
1905 
1906 
1933 int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident,
1934  enum enum_schema_tables schema_table_idx)
1935 {
1936  SELECT_LEX *schema_select_lex= NULL;
1937  DBUG_ENTER("prepare_schema_table");
1938 
1939  switch (schema_table_idx) {
1940  case SCH_SCHEMATA:
1941 #if defined(DONT_ALLOW_SHOW_COMMANDS)
1942  my_message(ER_NOT_ALLOWED_COMMAND,
1943  ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1944  DBUG_RETURN(1);
1945 #else
1946  break;
1947 #endif
1948 
1949  case SCH_TABLE_NAMES:
1950  case SCH_TABLES:
1951  case SCH_VIEWS:
1952  case SCH_TRIGGERS:
1953  case SCH_EVENTS:
1954 #ifdef DONT_ALLOW_SHOW_COMMANDS
1955  my_message(ER_NOT_ALLOWED_COMMAND,
1956  ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1957  DBUG_RETURN(1);
1958 #else
1959  {
1960  LEX_STRING db;
1961  size_t dummy;
1962  if (lex->select_lex.db == NULL &&
1963  lex->copy_db_to(&lex->select_lex.db, &dummy))
1964  {
1965  DBUG_RETURN(1);
1966  }
1967  schema_select_lex= new SELECT_LEX();
1968  db.str= schema_select_lex->db= lex->select_lex.db;
1969  schema_select_lex->table_list.first= NULL;
1970  db.length= strlen(db.str);
1971 
1972  if (check_and_convert_db_name(&db, FALSE) != IDENT_NAME_OK)
1973  DBUG_RETURN(1);
1974  break;
1975  }
1976 #endif
1977  case SCH_COLUMNS:
1978  case SCH_STATISTICS:
1979  {
1980 #ifdef DONT_ALLOW_SHOW_COMMANDS
1981  my_message(ER_NOT_ALLOWED_COMMAND,
1982  ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1983  DBUG_RETURN(1);
1984 #else
1985  DBUG_ASSERT(table_ident);
1986  TABLE_LIST **query_tables_last= lex->query_tables_last;
1987  schema_select_lex= new SELECT_LEX();
1988  /* 'parent_lex' is used in init_query() so it must be before it. */
1989  schema_select_lex->parent_lex= lex;
1990  schema_select_lex->init_query();
1991  if (!schema_select_lex->add_table_to_list(thd, table_ident, 0, 0, TL_READ,
1992  MDL_SHARED_READ))
1993  DBUG_RETURN(1);
1994  lex->query_tables_last= query_tables_last;
1995  break;
1996  }
1997 #endif
1998  case SCH_PROFILES:
1999  /*
2000  Mark this current profiling record to be discarded. We don't
2001  wish to have SHOW commands show up in profiling.
2002  */
2003 #if defined(ENABLED_PROFILING)
2004  thd->profiling.discard_current_query();
2005 #endif
2006  break;
2007  case SCH_OPTIMIZER_TRACE:
2008  case SCH_OPEN_TABLES:
2009  case SCH_VARIABLES:
2010  case SCH_STATUS:
2011  case SCH_PROCEDURES:
2012  case SCH_CHARSETS:
2013  case SCH_ENGINES:
2014  case SCH_COLLATIONS:
2015  case SCH_COLLATION_CHARACTER_SET_APPLICABILITY:
2016  case SCH_USER_PRIVILEGES:
2017  case SCH_SCHEMA_PRIVILEGES:
2018  case SCH_TABLE_PRIVILEGES:
2019  case SCH_COLUMN_PRIVILEGES:
2020  case SCH_TABLE_CONSTRAINTS:
2021  case SCH_KEY_COLUMN_USAGE:
2022  default:
2023  break;
2024  }
2025 
2026  SELECT_LEX *select_lex= lex->current_select;
2027  if (make_schema_select(thd, select_lex, schema_table_idx))
2028  {
2029  DBUG_RETURN(1);
2030  }
2031  TABLE_LIST *table_list= select_lex->table_list.first;
2032  table_list->schema_select_lex= schema_select_lex;
2033  table_list->schema_table_reformed= 1;
2034  DBUG_RETURN(0);
2035 }
2036 
2037 
2052 bool alloc_query(THD *thd, const char *packet, uint packet_length)
2053 {
2054  char *query;
2055  /* Remove garbage at start and end of query */
2056  while (packet_length > 0 && my_isspace(thd->charset(), packet[0]))
2057  {
2058  packet++;
2059  packet_length--;
2060  }
2061  const char *pos= packet + packet_length; // Point at end null
2062  while (packet_length > 0 &&
2063  (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1])))
2064  {
2065  pos--;
2066  packet_length--;
2067  }
2068  /* We must allocate some extra memory for query cache
2069 
2070  The query buffer layout is:
2071  buffer :==
2072  <statement> The input statement(s)
2073  '\0' Terminating null char (1 byte)
2074  <length> Length of following current database name (size_t)
2075  <db_name> Name of current database
2076  <flags> Flags struct
2077  */
2078  if (! (query= (char*) thd->memdup_w_gap(packet,
2079  packet_length,
2080  1 + sizeof(size_t) + thd->db_length +
2081  QUERY_CACHE_FLAGS_SIZE)))
2082  return TRUE;
2083  query[packet_length]= '\0';
2084  /*
2085  Space to hold the name of the current database is allocated. We
2086  also store this length, in case current database is changed during
2087  execution. We might need to reallocate the 'query' buffer
2088  */
2089  char *len_pos = (query + packet_length + 1);
2090  memcpy(len_pos, (char *) &thd->db_length, sizeof(size_t));
2091 
2092  thd->set_query(query, packet_length);
2093  thd->rewritten_query.free(); // free here lest PS break
2094 
2095  /* Reclaim some memory */
2096  thd->packet.shrink(thd->variables.net_buffer_length);
2097  thd->convert_buffer.shrink(thd->variables.net_buffer_length);
2098 
2099  return FALSE;
2100 }
2101 
2102 static void reset_one_shot_variables(THD *thd)
2103 {
2104  thd->variables.character_set_client=
2105  global_system_variables.character_set_client;
2106  thd->variables.collation_connection=
2107  global_system_variables.collation_connection;
2108  thd->variables.collation_database=
2109  global_system_variables.collation_database;
2110  thd->variables.collation_server=
2111  global_system_variables.collation_server;
2112  thd->update_charset();
2113  thd->variables.time_zone=
2114  global_system_variables.time_zone;
2115  thd->variables.lc_time_names= &my_locale_en_US;
2116  thd->one_shot_set= 0;
2117 }
2118 
2119 
2120 static
2121 bool sp_process_definer(THD *thd)
2122 {
2123  DBUG_ENTER("sp_process_definer");
2124 
2125  LEX *lex= thd->lex;
2126 
2127  /*
2128  If the definer is not specified, this means that CREATE-statement missed
2129  DEFINER-clause. DEFINER-clause can be missed in two cases:
2130 
2131  - The user submitted a statement w/o the clause. This is a normal
2132  case, we should assign CURRENT_USER as definer.
2133 
2134  - Our slave received an updated from the master, that does not
2135  replicate definer for stored rountines. We should also assign
2136  CURRENT_USER as definer here, but also we should mark this routine
2137  as NON-SUID. This is essential for the sake of backward
2138  compatibility.
2139 
2140  The problem is the slave thread is running under "special" user (@),
2141  that actually does not exist. In the older versions we do not fail
2142  execution of a stored routine if its definer does not exist and
2143  continue the execution under the authorization of the invoker
2144  (BUG#13198). And now if we try to switch to slave-current-user (@),
2145  we will fail.
2146 
2147  Actually, this leads to the inconsistent state of master and
2148  slave (different definers, different SUID behaviour), but it seems,
2149  this is the best we can do.
2150  */
2151 
2152  if (!lex->definer)
2153  {
2154  Prepared_stmt_arena_holder ps_arena_holder(thd);
2155 
2156  lex->definer= create_default_definer(thd);
2157 
2158  /* Error has been already reported. */
2159  if (lex->definer == NULL)
2160  DBUG_RETURN(TRUE);
2161 
2162  if (thd->slave_thread && lex->sphead)
2163  lex->sphead->m_chistics->suid= SP_IS_NOT_SUID;
2164  }
2165  else
2166  {
2167  /*
2168  If the specified definer differs from the current user, we
2169  should check that the current user has SUPER privilege (in order
2170  to create a stored routine under another user one must have
2171  SUPER privilege).
2172  */
2173  if ((strcmp(lex->definer->user.str, thd->security_ctx->priv_user) ||
2174  my_strcasecmp(system_charset_info, lex->definer->host.str,
2175  thd->security_ctx->priv_host)) &&
2176  check_global_access(thd, SUPER_ACL))
2177  {
2178  my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "SUPER");
2179  DBUG_RETURN(TRUE);
2180  }
2181  }
2182 
2183  /* Check that the specified definer exists. Emit a warning if not. */
2184 
2185 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2186  if (!is_acl_user(lex->definer->host.str, lex->definer->user.str))
2187  {
2188  push_warning_printf(thd,
2189  Sql_condition::WARN_LEVEL_NOTE,
2190  ER_NO_SUCH_USER,
2191  ER(ER_NO_SUCH_USER),
2192  lex->definer->user.str,
2193  lex->definer->host.str);
2194  }
2195 #endif /* NO_EMBEDDED_ACCESS_CHECKS */
2196 
2197  DBUG_RETURN(FALSE);
2198 }
2199 
2200 
2211 static bool lock_tables_open_and_lock_tables(THD *thd, TABLE_LIST *tables)
2212 {
2213  Lock_tables_prelocking_strategy lock_tables_prelocking_strategy;
2214  uint counter;
2215  TABLE_LIST *table;
2216 
2217  thd->in_lock_tables= 1;
2218 
2219  if (open_tables(thd, &tables, &counter, 0, &lock_tables_prelocking_strategy))
2220  goto err;
2221 
2222  /*
2223  We allow to change temporary tables even if they were locked for read
2224  by LOCK TABLES. To avoid a discrepancy between lock acquired at LOCK
2225  TABLES time and by the statement which is later executed under LOCK TABLES
2226  we ensure that for temporary tables we always request a write lock (such
2227  discrepancy can cause problems for the storage engine).
2228  We don't set TABLE_LIST::lock_type in this case as this might result in
2229  extra warnings from THD::decide_logging_format() even though binary logging
2230  is totally irrelevant for LOCK TABLES.
2231  */
2232  for (table= tables; table; table= table->next_global)
2233  if (!table->placeholder() && table->table->s->tmp_table)
2234  table->table->reginfo.lock_type= TL_WRITE;
2235 
2236  if (lock_tables(thd, tables, counter, 0) ||
2237  thd->locked_tables_list.init_locked_tables(thd))
2238  goto err;
2239 
2240  thd->in_lock_tables= 0;
2241 
2242  return FALSE;
2243 
2244 err:
2245  thd->in_lock_tables= 0;
2246 
2247  trans_rollback_stmt(thd);
2248  /*
2249  Need to end the current transaction, so the storage engine (InnoDB)
2250  can free its locks if LOCK TABLES locked some tables before finding
2251  that it can't lock a table in its list
2252  */
2253  trans_rollback(thd);
2254  /* Close tables and release metadata locks. */
2255  close_thread_tables(thd);
2256  DBUG_ASSERT(!thd->locked_tables_mode);
2257  thd->mdl_context.release_transactional_locks();
2258  return TRUE;
2259 }
2260 
2261 
2280 int
2282 {
2283  int res= FALSE;
2284  int up_result= 0;
2285  LEX *lex= thd->lex;
2286  /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
2287  SELECT_LEX *select_lex= &lex->select_lex;
2288  /* first table of first SELECT_LEX */
2289  TABLE_LIST *first_table= select_lex->table_list.first;
2290  /* list of all tables in query */
2291  TABLE_LIST *all_tables;
2292  /* most outer SELECT_LEX_UNIT of query */
2293  SELECT_LEX_UNIT *unit= &lex->unit;
2294 #ifdef HAVE_REPLICATION
2295  /* have table map for update for multi-update statement (BUG#37051) */
2296  bool have_table_map_for_update= FALSE;
2297 #endif
2298  DBUG_ENTER("mysql_execute_command");
2299  DBUG_ASSERT(!lex->describe || is_explainable_query(lex->sql_command));
2300 
2301  if (unlikely(lex->is_broken()))
2302  {
2303  // Force a Reprepare, to get a fresh LEX
2304  Reprepare_observer *reprepare_observer= thd->get_reprepare_observer();
2305  if (reprepare_observer &&
2306  reprepare_observer->report_error(thd))
2307  {
2308  DBUG_ASSERT(thd->is_error());
2309  DBUG_RETURN(1);
2310  }
2311  }
2312 
2313 #ifdef WITH_PARTITION_STORAGE_ENGINE
2314  thd->work_part_info= 0;
2315 #endif
2316 
2317  DBUG_ASSERT(thd->transaction.stmt.is_empty() || thd->in_sub_stmt);
2318  /*
2319  Each statement or replication event which might produce deadlock
2320  should handle transaction rollback on its own. So by the start of
2321  the next statement transaction rollback request should be fulfilled
2322  already.
2323  */
2324  DBUG_ASSERT(! thd->transaction_rollback_request || thd->in_sub_stmt);
2325  /*
2326  In many cases first table of main SELECT_LEX have special meaning =>
2327  check that it is first table in global list and relink it first in
2328  queries_tables list if it is necessary (we need such relinking only
2329  for queries with subqueries in select list, in this case tables of
2330  subqueries will go to global list first)
2331 
2332  all_tables will differ from first_table only if most upper SELECT_LEX
2333  do not contain tables.
2334 
2335  Because of above in place where should be at least one table in most
2336  outer SELECT_LEX we have following check:
2337  DBUG_ASSERT(first_table == all_tables);
2338  DBUG_ASSERT(first_table == all_tables && first_table != 0);
2339  */
2340  lex->first_lists_tables_same();
2341  /* should be assigned after making first tables same */
2342  all_tables= lex->query_tables;
2343  /* set context for commands which do not use setup_tables */
2344  select_lex->
2345  context.resolve_in_table_list_only(select_lex->
2346  table_list.first);
2347 
2348  /*
2349  Reset warning count for each query that uses tables
2350  A better approach would be to reset this for any commands
2351  that is not a SHOW command or a select that only access local
2352  variables, but for now this is probably good enough.
2353  */
2354  if ((sql_command_flags[lex->sql_command] & CF_DIAGNOSTIC_STMT) != 0)
2355  thd->get_stmt_da()->set_warning_info_read_only(TRUE);
2356  else
2357  {
2358  thd->get_stmt_da()->set_warning_info_read_only(FALSE);
2359  if (all_tables)
2360  thd->get_stmt_da()->opt_clear_warning_info(thd->query_id);
2361  }
2362 
2363 #ifdef HAVE_REPLICATION
2364  if (unlikely(thd->slave_thread))
2365  {
2366  if (lex->sql_command == SQLCOM_DROP_TRIGGER)
2367  {
2368  /*
2369  When dropping a trigger, we need to load its table name
2370  before checking slave filter rules.
2371  */
2372  add_table_for_trigger(thd, thd->lex->spname, 1, &all_tables);
2373 
2374  if (!all_tables)
2375  {
2376  /*
2377  If table name cannot be loaded,
2378  it means the trigger does not exists possibly because
2379  CREATE TRIGGER was previously skipped for this trigger
2380  according to slave filtering rules.
2381  Returning success without producing any errors in this case.
2382  */
2383  DBUG_RETURN(0);
2384  }
2385 
2386  // force searching in slave.cc:tables_ok()
2387  all_tables->updating= 1;
2388  }
2389 
2390  /*
2391  For fix of BUG#37051, the master stores the table map for update
2392  in the Query_log_event, and the value is assigned to
2393  thd->variables.table_map_for_update before executing the update
2394  query.
2395 
2396  If thd->variables.table_map_for_update is set, then we are
2397  replicating from a new master, we can use this value to apply
2398  filter rules without opening all the tables. However If
2399  thd->variables.table_map_for_update is not set, then we are
2400  replicating from an old master, so we just skip this and
2401  continue with the old method. And of course, the bug would still
2402  exist for old masters.
2403  */
2404  if (lex->sql_command == SQLCOM_UPDATE_MULTI &&
2405  thd->table_map_for_update)
2406  {
2407  have_table_map_for_update= TRUE;
2408  table_map table_map_for_update= thd->table_map_for_update;
2409  uint nr= 0;
2410  TABLE_LIST *table;
2411  for (table=all_tables; table; table=table->next_global, nr++)
2412  {
2413  if (table_map_for_update & ((table_map)1 << nr))
2414  table->updating= TRUE;
2415  else
2416  table->updating= FALSE;
2417  }
2418 
2419  if (all_tables_not_ok(thd, all_tables))
2420  {
2421  /* we warn the slave SQL thread */
2422  my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2423  if (thd->one_shot_set)
2424  reset_one_shot_variables(thd);
2425  DBUG_RETURN(0);
2426  }
2427 
2428  for (table=all_tables; table; table=table->next_global)
2429  table->updating= TRUE;
2430  }
2431 
2432  /*
2433  Check if statment should be skipped because of slave filtering
2434  rules
2435 
2436  Exceptions are:
2437  - UPDATE MULTI: For this statement, we want to check the filtering
2438  rules later in the code
2439  - SET: we always execute it (Not that many SET commands exists in
2440  the binary log anyway -- only 4.1 masters write SET statements,
2441  in 5.0 there are no SET statements in the binary log)
2442  - DROP TEMPORARY TABLE IF EXISTS: we always execute it (otherwise we
2443  have stale files on slave caused by exclusion of one tmp table).
2444  */
2445  if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) &&
2446  !(lex->sql_command == SQLCOM_SET_OPTION) &&
2447  !(lex->sql_command == SQLCOM_DROP_TABLE &&
2448  lex->drop_temporary && lex->drop_if_exists) &&
2449  all_tables_not_ok(thd, all_tables))
2450  {
2451  /* we warn the slave SQL thread */
2452  my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2453  if (thd->one_shot_set)
2454  {
2455  /*
2456  It's ok to check thd->one_shot_set here:
2457 
2458  The charsets in a MySQL 5.0 slave can change by both a binlogged
2459  SET ONE_SHOT statement and the event-internal charset setting,
2460  and these two ways to change charsets do not seems to work
2461  together.
2462 
2463  At least there seems to be problems in the rli cache for
2464  charsets if we are using ONE_SHOT. Note that this is normally no
2465  problem because either the >= 5.0 slave reads a 4.1 binlog (with
2466  ONE_SHOT) *or* or 5.0 binlog (without ONE_SHOT) but never both."
2467  */
2468  reset_one_shot_variables(thd);
2469  }
2470  DBUG_RETURN(0);
2471  }
2472  /*
2473  Execute deferred events first
2474  */
2475  if (slave_execute_deferred_events(thd))
2476  DBUG_RETURN(-1);
2477  }
2478  else
2479  {
2480 #endif /* HAVE_REPLICATION */
2481  /*
2482  When option readonly is set deny operations which change non-temporary
2483  tables. Except for the replication thread and the 'super' users.
2484  */
2485  if (deny_updates_if_read_only_option(thd, all_tables))
2486  {
2487  my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
2488  DBUG_RETURN(-1);
2489  }
2490 #ifdef HAVE_REPLICATION
2491  } /* endif unlikely slave */
2492 #endif
2493 
2494  status_var_increment(thd->status_var.com_stat[lex->sql_command]);
2495 
2496  Opt_trace_start ots(thd, all_tables, lex->sql_command, &lex->var_list,
2497  thd->query(), thd->query_length(), NULL,
2498  thd->variables.character_set_client);
2499 
2500  Opt_trace_object trace_command(&thd->opt_trace);
2501  Opt_trace_array trace_command_steps(&thd->opt_trace, "steps");
2502 
2503  DBUG_ASSERT(thd->transaction.stmt.cannot_safely_rollback() == FALSE);
2504 
2505  switch (gtid_pre_statement_checks(thd))
2506  {
2507  case GTID_STATEMENT_EXECUTE:
2508  break;
2509  case GTID_STATEMENT_CANCEL:
2510  DBUG_RETURN(-1);
2511  case GTID_STATEMENT_SKIP:
2512  my_ok(thd);
2513  DBUG_RETURN(0);
2514  }
2515 
2516  /*
2517  End a active transaction so that this command will have it's
2518  own transaction and will also sync the binary log. If a DDL is
2519  not run in it's own transaction it may simply never appear on
2520  the slave in case the outside transaction rolls back.
2521  */
2522  if (stmt_causes_implicit_commit(thd, CF_IMPLICIT_COMMIT_BEGIN))
2523  {
2524  /*
2525  Note that this should never happen inside of stored functions
2526  or triggers as all such statements prohibited there.
2527  */
2528  DBUG_ASSERT(! thd->in_sub_stmt);
2529  /* Statement transaction still should not be started. */
2530  DBUG_ASSERT(thd->transaction.stmt.is_empty());
2531 
2532  /*
2533  Implicit commit is not allowed with an active XA transaction.
2534  In this case we should not release metadata locks as the XA transaction
2535  will not be rolled back. Therefore we simply return here.
2536  */
2537  if (trans_check_state(thd))
2538  DBUG_RETURN(-1);
2539 
2540  /* Commit the normal transaction if one is active. */
2541  if (trans_commit_implicit(thd))
2542  goto error;
2543  /* Release metadata locks acquired in this transaction. */
2544  thd->mdl_context.release_transactional_locks();
2545  }
2546 
2547 #ifndef DBUG_OFF
2548  if (lex->sql_command != SQLCOM_SET_OPTION)
2549  DEBUG_SYNC(thd,"before_execute_sql_command");
2550 #endif
2551 
2552  /*
2553  Check if we are in a read-only transaction and we're trying to
2554  execute a statement which should always be disallowed in such cases.
2555 
2556  Note that this check is done after any implicit commits.
2557  */
2558  if (thd->tx_read_only &&
2559  (sql_command_flags[lex->sql_command] & CF_DISALLOW_IN_RO_TRANS))
2560  {
2561  my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0));
2562  goto error;
2563  }
2564 
2565  /*
2566  Close tables open by HANDLERs before executing DDL statement
2567  which is going to affect those tables.
2568 
2569  This should happen before temporary tables are pre-opened as
2570  otherwise we will get errors about attempt to re-open tables
2571  if table to be changed is open through HANDLER.
2572 
2573  Note that even although this is done before any privilege
2574  checks there is no security problem here as closing open
2575  HANDLER doesn't require any privileges anyway.
2576  */
2577  if (sql_command_flags[lex->sql_command] & CF_HA_CLOSE)
2578  mysql_ha_rm_tables(thd, all_tables);
2579 
2580  /*
2581  Pre-open temporary tables to simplify privilege checking
2582  for statements which need this.
2583  */
2584  if (sql_command_flags[lex->sql_command] & CF_PREOPEN_TMP_TABLES)
2585  {
2586  if (open_temporary_tables(thd, all_tables))
2587  goto error;
2588  }
2589 
2590  switch (lex->sql_command) {
2591 
2592  case SQLCOM_SHOW_STATUS:
2593  {
2594  system_status_var old_status_var= thd->status_var;
2595  thd->initial_status_var= &old_status_var;
2596 
2597  if (!(res= select_precheck(thd, lex, all_tables, first_table)))
2598  res= execute_sqlcom_select(thd, all_tables);
2599 
2600  /* Don't log SHOW STATUS commands to slow query log */
2601  thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED |
2602  SERVER_QUERY_NO_GOOD_INDEX_USED);
2603  /*
2604  restore status variables, as we don't want 'show status' to cause
2605  changes
2606  */
2607  mysql_mutex_lock(&LOCK_status);
2608  add_diff_to_status(&global_status_var, &thd->status_var,
2609  &old_status_var);
2610  thd->status_var= old_status_var;
2611  mysql_mutex_unlock(&LOCK_status);
2612  break;
2613  }
2614  case SQLCOM_SHOW_EVENTS:
2615 #ifndef HAVE_EVENT_SCHEDULER
2616  my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server");
2617  break;
2618 #endif
2619  case SQLCOM_SHOW_STATUS_PROC:
2620  case SQLCOM_SHOW_STATUS_FUNC:
2621  case SQLCOM_SHOW_DATABASES:
2622  case SQLCOM_SHOW_TABLES:
2623  case SQLCOM_SHOW_TRIGGERS:
2624  case SQLCOM_SHOW_TABLE_STATUS:
2625  case SQLCOM_SHOW_OPEN_TABLES:
2626  case SQLCOM_SHOW_PLUGINS:
2627  case SQLCOM_SHOW_FIELDS:
2628  case SQLCOM_SHOW_KEYS:
2629  case SQLCOM_SHOW_VARIABLES:
2630  case SQLCOM_SHOW_CHARSETS:
2631  case SQLCOM_SHOW_COLLATIONS:
2632  case SQLCOM_SHOW_STORAGE_ENGINES:
2633  case SQLCOM_SHOW_PROFILE:
2634  case SQLCOM_SELECT:
2635  {
2636  thd->status_var.last_query_cost= 0.0;
2637  thd->status_var.last_query_partial_plans= 0;
2638 
2639  if ((res= select_precheck(thd, lex, all_tables, first_table)))
2640  break;
2641 
2642  res= execute_sqlcom_select(thd, all_tables);
2643  break;
2644  }
2645 case SQLCOM_PREPARE:
2646  {
2648  break;
2649  }
2650  case SQLCOM_EXECUTE:
2651  {
2653  break;
2654  }
2655  case SQLCOM_DEALLOCATE_PREPARE:
2656  {
2657  mysql_sql_stmt_close(thd);
2658  break;
2659  }
2660  case SQLCOM_DO:
2661  if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)
2662  || open_and_lock_tables(thd, all_tables, TRUE, 0))
2663  goto error;
2664 
2665  res= mysql_do(thd, *lex->insert_list);
2666  break;
2667 
2668  case SQLCOM_EMPTY_QUERY:
2669  my_ok(thd);
2670  break;
2671 
2672  case SQLCOM_HELP:
2673  res= mysqld_help(thd,lex->help_arg);
2674  break;
2675 
2676 #ifndef EMBEDDED_LIBRARY
2677  case SQLCOM_PURGE:
2678  {
2679  if (check_global_access(thd, SUPER_ACL))
2680  goto error;
2681  /* PURGE MASTER LOGS TO 'file' */
2682  res = purge_master_logs(thd, lex->to_log);
2683  break;
2684  }
2685  case SQLCOM_PURGE_BEFORE:
2686  {
2687  Item *it;
2688 
2689  if (check_global_access(thd, SUPER_ACL))
2690  goto error;
2691  /* PURGE MASTER LOGS BEFORE 'data' */
2692  it= (Item *)lex->value_list.head();
2693  if ((!it->fixed && it->fix_fields(lex->thd, &it)) ||
2694  it->check_cols(1))
2695  {
2696  my_error(ER_WRONG_ARGUMENTS, MYF(0), "PURGE LOGS BEFORE");
2697  goto error;
2698  }
2699  it= new Item_func_unix_timestamp(it);
2700  /*
2701  it is OK only emulate fix_fieds, because we need only
2702  value of constant
2703  */
2704  it->quick_fix_field();
2705  res = purge_master_logs_before_date(thd, (ulong)it->val_int());
2706  break;
2707  }
2708 #endif
2709  case SQLCOM_SHOW_WARNS:
2710  {
2711  res= mysqld_show_warnings(thd, (ulong)
2712  ((1L << (uint) Sql_condition::WARN_LEVEL_NOTE) |
2713  (1L << (uint) Sql_condition::WARN_LEVEL_WARN) |
2714  (1L << (uint) Sql_condition::WARN_LEVEL_ERROR)
2715  ));
2716  break;
2717  }
2718  case SQLCOM_SHOW_ERRORS:
2719  {
2720  res= mysqld_show_warnings(thd, (ulong)
2721  (1L << (uint) Sql_condition::WARN_LEVEL_ERROR));
2722  break;
2723  }
2724  case SQLCOM_SHOW_PROFILES:
2725  {
2726 #if defined(ENABLED_PROFILING)
2727  thd->profiling.discard_current_query();
2728  res= thd->profiling.show_profiles();
2729  if (res)
2730  goto error;
2731 #else
2732  my_error(ER_FEATURE_DISABLED, MYF(0), "SHOW PROFILES", "enable-profiling");
2733  goto error;
2734 #endif
2735  break;
2736  }
2737 
2738 #ifdef HAVE_REPLICATION
2739  case SQLCOM_SHOW_SLAVE_HOSTS:
2740  {
2741  if (check_global_access(thd, REPL_SLAVE_ACL))
2742  goto error;
2743  res= show_slave_hosts(thd);
2744  break;
2745  }
2746  case SQLCOM_SHOW_RELAYLOG_EVENTS:
2747  {
2748  if (check_global_access(thd, REPL_SLAVE_ACL))
2749  goto error;
2750  res = mysql_show_relaylog_events(thd);
2751  break;
2752  }
2753  case SQLCOM_SHOW_BINLOG_EVENTS:
2754  {
2755  if (check_global_access(thd, REPL_SLAVE_ACL))
2756  goto error;
2757  res = mysql_show_binlog_events(thd);
2758  break;
2759  }
2760 #endif
2761 
2762  case SQLCOM_ASSIGN_TO_KEYCACHE:
2763  {
2764  DBUG_ASSERT(first_table == all_tables && first_table != 0);
2765  if (check_access(thd, INDEX_ACL, first_table->db,
2766  &first_table->grant.privilege,
2767  &first_table->grant.m_internal,
2768  0, 0))
2769  goto error;
2770  res= mysql_assign_to_keycache(thd, first_table, &lex->ident);
2771  break;
2772  }
2773  case SQLCOM_PRELOAD_KEYS:
2774  {
2775  DBUG_ASSERT(first_table == all_tables && first_table != 0);
2776  if (check_access(thd, INDEX_ACL, first_table->db,
2777  &first_table->grant.privilege,
2778  &first_table->grant.m_internal,
2779  0, 0))
2780  goto error;
2781  res = mysql_preload_keys(thd, first_table);
2782  break;
2783  }
2784 #ifdef HAVE_REPLICATION
2785  case SQLCOM_CHANGE_MASTER:
2786  {
2787  if (check_global_access(thd, SUPER_ACL))
2788  goto error;
2789  mysql_mutex_lock(&LOCK_active_mi);
2790  if (active_mi != NULL)
2791  res= change_master(thd, active_mi);
2792  else
2793  my_message(ER_SLAVE_CONFIGURATION, ER(ER_SLAVE_CONFIGURATION),
2794  MYF(0));
2795  mysql_mutex_unlock(&LOCK_active_mi);
2796  break;
2797  }
2798  case SQLCOM_SHOW_SLAVE_STAT:
2799  {
2800  /* Accept one of two privileges */
2801  if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
2802  goto error;
2803  mysql_mutex_lock(&LOCK_active_mi);
2804  res= show_slave_status(thd, active_mi);
2805  mysql_mutex_unlock(&LOCK_active_mi);
2806  break;
2807  }
2808  case SQLCOM_SHOW_MASTER_STAT:
2809  {
2810  /* Accept one of two privileges */
2811  if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
2812  goto error;
2813  res = show_master_status(thd);
2814  break;
2815  }
2816 
2817 #endif /* HAVE_REPLICATION */
2818  case SQLCOM_SHOW_ENGINE_STATUS:
2819  {
2820  if (check_global_access(thd, PROCESS_ACL))
2821  goto error;
2822  res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS);
2823  break;
2824  }
2825  case SQLCOM_SHOW_ENGINE_MUTEX:
2826  {
2827  if (check_global_access(thd, PROCESS_ACL))
2828  goto error;
2829  res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX);
2830  break;
2831  }
2832  case SQLCOM_CREATE_TABLE:
2833  {
2834  DBUG_ASSERT(first_table == all_tables && first_table != 0);
2835  bool link_to_local;
2836  TABLE_LIST *create_table= first_table;
2837  TABLE_LIST *select_tables= lex->create_last_non_select_table->next_global;
2838 
2839  /*
2840  Code below (especially in mysql_create_table() and select_create
2841  methods) may modify HA_CREATE_INFO structure in LEX, so we have to
2842  use a copy of this structure to make execution prepared statement-
2843  safe. A shallow copy is enough as this code won't modify any memory
2844  referenced from this structure.
2845  */
2846  HA_CREATE_INFO create_info(lex->create_info);
2847  /*
2848  We need to copy alter_info for the same reasons of re-execution
2849  safety, only in case of Alter_info we have to do (almost) a deep
2850  copy.
2851  */
2852  Alter_info alter_info(lex->alter_info, thd->mem_root);
2853 
2854  if (thd->is_fatal_error)
2855  {
2856  /* If out of memory when creating a copy of alter_info. */
2857  res= 1;
2858  goto end_with_restore_list;
2859  }
2860 
2861  if ((res= create_table_precheck(thd, select_tables, create_table)))
2862  goto end_with_restore_list;
2863 
2864  /* Might have been updated in create_table_precheck */
2865  create_info.alias= create_table->alias;
2866 
2867  /* Fix names if symlinked or relocated tables */
2868  if (append_file_to_dir(thd, &create_info.data_file_name,
2869  create_table->table_name) ||
2870  append_file_to_dir(thd, &create_info.index_file_name,
2871  create_table->table_name))
2872  goto end_with_restore_list;
2873 
2874  /*
2875  If no engine type was given, work out the default now
2876  rather than at parse-time.
2877  */
2878  if (!(create_info.used_fields & HA_CREATE_USED_ENGINE))
2879  create_info.db_type= create_info.options & HA_LEX_CREATE_TMP_TABLE ?
2881  /*
2882  If we are using SET CHARSET without DEFAULT, add an implicit
2883  DEFAULT to not confuse old users. (This may change).
2884  */
2885  if ((create_info.used_fields &
2886  (HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) ==
2887  HA_CREATE_USED_CHARSET)
2888  {
2889  create_info.used_fields&= ~HA_CREATE_USED_CHARSET;
2890  create_info.used_fields|= HA_CREATE_USED_DEFAULT_CHARSET;
2891  create_info.default_table_charset= create_info.table_charset;
2892  create_info.table_charset= 0;
2893  }
2894 
2895 #ifdef WITH_PARTITION_STORAGE_ENGINE
2896  {
2897  partition_info *part_info= thd->lex->part_info;
2898  if (part_info && !(part_info= thd->lex->part_info->get_clone()))
2899  {
2900  res= -1;
2901  goto end_with_restore_list;
2902  }
2903  thd->work_part_info= part_info;
2904  }
2905 #endif
2906 
2907  if (select_lex->item_list.elements) // With select
2908  {
2909  select_result *result;
2910 
2911  /*
2912  CREATE TABLE...IGNORE/REPLACE SELECT... can be unsafe, unless
2913  ORDER BY PRIMARY KEY clause is used in SELECT statement. We therefore
2914  use row based logging if mixed or row based logging is available.
2915  TODO: Check if the order of the output of the select statement is
2916  deterministic. Waiting for BUG#42415
2917  */
2918  if(lex->ignore)
2919  lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_CREATE_IGNORE_SELECT);
2920 
2921  if(lex->duplicates == DUP_REPLACE)
2922  lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_CREATE_REPLACE_SELECT);
2923 
2924  /*
2925  If:
2926  a) we inside an SP and there was NAME_CONST substitution,
2927  b) binlogging is on (STMT mode),
2928  c) we log the SP as separate statements
2929  raise a warning, as it may cause problems
2930  (see 'NAME_CONST issues' in 'Binary Logging of Stored Programs')
2931  */
2932  if (thd->query_name_consts &&
2933  mysql_bin_log.is_open() &&
2934  thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
2935  !mysql_bin_log.is_query_in_union(thd, thd->query_id))
2936  {
2937  List_iterator_fast<Item> it(select_lex->item_list);
2938  Item *item;
2939  uint splocal_refs= 0;
2940  /* Count SP local vars in the top-level SELECT list */
2941  while ((item= it++))
2942  {
2943  if (item->is_splocal())
2944  splocal_refs++;
2945  }
2946  /*
2947  If it differs from number of NAME_CONST substitution applied,
2948  we may have a SOME_FUNC(NAME_CONST()) in the SELECT list,
2949  that may cause a problem with binary log (see BUG#35383),
2950  raise a warning.
2951  */
2952  if (splocal_refs != thd->query_name_consts)
2953  push_warning(thd,
2954  Sql_condition::WARN_LEVEL_WARN,
2955  ER_UNKNOWN_ERROR,
2956 "Invoked routine ran a statement that may cause problems with "
2957 "binary log, see 'NAME_CONST issues' in 'Binary Logging of Stored Programs' "
2958 "section of the manual.");
2959  }
2960 
2961  select_lex->options|= SELECT_NO_UNLOCK;
2962  unit->set_limit(select_lex);
2963 
2964  /*
2965  Disable non-empty MERGE tables with CREATE...SELECT. Too
2966  complicated. See Bug #26379. Empty MERGE tables are read-only
2967  and don't allow CREATE...SELECT anyway.
2968  */
2969  if (create_info.used_fields & HA_CREATE_USED_UNION)
2970  {
2971  my_error(ER_WRONG_OBJECT, MYF(0), create_table->db,
2972  create_table->table_name, "BASE TABLE");
2973  res= 1;
2974  goto end_with_restore_list;
2975  }
2976 
2977  if (!(res= open_normal_and_derived_tables(thd, all_tables, 0)))
2978  {
2979  /* The table already exists */
2980  if (create_table->table || create_table->view)
2981  {
2982  if (create_info.options & HA_LEX_CREATE_IF_NOT_EXISTS)
2983  {
2984  push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
2985  ER_TABLE_EXISTS_ERROR,
2986  ER(ER_TABLE_EXISTS_ERROR),
2987  create_info.alias);
2988  my_ok(thd);
2989  }
2990  else
2991  {
2992  my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_info.alias);
2993  res= 1;
2994  }
2995  goto end_with_restore_list;
2996  }
2997 
2998  /*
2999  Remove target table from main select and name resolution
3000  context. This can't be done earlier as it will break view merging in
3001  statements like "CREATE TABLE IF NOT EXISTS existing_view SELECT".
3002  */
3003  lex->unlink_first_table(&link_to_local);
3004 
3005  /* Updating any other table is prohibited in CTS statement */
3006  for (TABLE_LIST *table= lex->query_tables; table;
3007  table= table->next_global)
3008  if (table->lock_type >= TL_WRITE_ALLOW_WRITE)
3009  {
3010  res= 1;
3011  my_error(ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT, MYF(0),
3012  table->table_name, create_info.alias);
3013  goto end_with_restore_list;
3014  }
3015 
3016  /*
3017  select_create is currently not re-execution friendly and
3018  needs to be created for every execution of a PS/SP.
3019  */
3020  if ((result= new select_create(create_table,
3021  &create_info,
3022  &alter_info,
3023  select_lex->item_list,
3024  lex->duplicates,
3025  lex->ignore,
3026  select_tables)))
3027  {
3028  /*
3029  CREATE from SELECT give its SELECT_LEX for SELECT,
3030  and item_list belong to SELECT
3031  */
3032  res= handle_select(thd, result, 0);
3033  delete result;
3034  }
3035 
3036  lex->link_first_table_back(create_table, link_to_local);
3037  }
3038  }
3039  else
3040  {
3041  /* regular create */
3042  if (create_info.options & HA_LEX_CREATE_TABLE_LIKE)
3043  {
3044  /* CREATE TABLE ... LIKE ... */
3045  res= mysql_create_like_table(thd, create_table, select_tables,
3046  &create_info);
3047  }
3048  else
3049  {
3050  /* Regular CREATE TABLE */
3051  res= mysql_create_table(thd, create_table,
3052  &create_info, &alter_info);
3053  }
3054  if (!res)
3055  my_ok(thd);
3056  }
3057 
3058 end_with_restore_list:
3059  break;
3060  }
3061  case SQLCOM_CREATE_INDEX:
3062  /* Fall through */
3063  case SQLCOM_DROP_INDEX:
3064  /*
3065  CREATE INDEX and DROP INDEX are implemented by calling ALTER
3066  TABLE with proper arguments.
3067 
3068  In the future ALTER TABLE will notice that the request is to
3069  only add indexes and create these one by one for the existing
3070  table without having to do a full rebuild.
3071  */
3072  {
3073  /* Prepare stack copies to be re-execution safe */
3074  HA_CREATE_INFO create_info;
3075  Alter_info alter_info(lex->alter_info, thd->mem_root);
3076 
3077  if (thd->is_fatal_error) /* out of memory creating a copy of alter_info */
3078  goto error;
3079 
3080  DBUG_ASSERT(first_table == all_tables && first_table != 0);
3081  if (check_one_table_access(thd, INDEX_ACL, all_tables))
3082  goto error; /* purecov: inspected */
3083  /*
3084  Currently CREATE INDEX or DROP INDEX cause a full table rebuild
3085  and thus classify as slow administrative statements just like
3086  ALTER TABLE.
3087  */
3088  thd->enable_slow_log= opt_log_slow_admin_statements;
3089 
3090  memset(&create_info, 0, sizeof(create_info));
3091  create_info.db_type= 0;
3092  create_info.row_type= ROW_TYPE_NOT_USED;
3093  create_info.default_table_charset= thd->variables.collation_database;
3094 
3095  res= mysql_alter_table(thd, first_table->db, first_table->table_name,
3096  &create_info, first_table, &alter_info,
3097  0, (ORDER*) 0, 0);
3098  break;
3099  }
3100 #ifdef HAVE_REPLICATION
3101  case SQLCOM_SLAVE_START:
3102  {
3103  mysql_mutex_lock(&LOCK_active_mi);
3104  if (active_mi != NULL)
3105  res= start_slave(thd, active_mi, 1 /* net report*/);
3106  else
3107  my_message(ER_SLAVE_CONFIGURATION, ER(ER_SLAVE_CONFIGURATION),
3108  MYF(0));
3109  mysql_mutex_unlock(&LOCK_active_mi);
3110  break;
3111  }
3112  case SQLCOM_SLAVE_STOP:
3113  /*
3114  If the client thread has locked tables, a deadlock is possible.
3115  Assume that
3116  - the client thread does LOCK TABLE t READ.
3117  - then the master updates t.
3118  - then the SQL slave thread wants to update t,
3119  so it waits for the client thread because t is locked by it.
3120  - then the client thread does SLAVE STOP.
3121  SLAVE STOP waits for the SQL slave thread to terminate its
3122  update t, which waits for the client thread because t is locked by it.
3123  To prevent that, refuse SLAVE STOP if the
3124  client thread has locked tables
3125  */
3126  if (thd->locked_tables_mode ||
3127  thd->in_active_multi_stmt_transaction() || thd->global_read_lock.is_acquired())
3128  {
3129  my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
3130  ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3131  goto error;
3132  }
3133  {
3134  mysql_mutex_lock(&LOCK_active_mi);
3135  if (active_mi != NULL)
3136  res= stop_slave(thd, active_mi, 1 /* net report*/);
3137  else
3138  my_message(ER_SLAVE_CONFIGURATION, ER(ER_SLAVE_CONFIGURATION),
3139  MYF(0));
3140  mysql_mutex_unlock(&LOCK_active_mi);
3141  break;
3142  }
3143 #endif /* HAVE_REPLICATION */
3144 
3145  case SQLCOM_RENAME_TABLE:
3146  {
3147  DBUG_ASSERT(first_table == all_tables && first_table != 0);
3148  TABLE_LIST *table;
3149  for (table= first_table; table; table= table->next_local->next_local)
3150  {
3151  if (check_access(thd, ALTER_ACL | DROP_ACL, table->db,
3152  &table->grant.privilege,
3153  &table->grant.m_internal,
3154  0, 0) ||
3155  check_access(thd, INSERT_ACL | CREATE_ACL, table->next_local->db,
3156  &table->next_local->grant.privilege,
3157  &table->next_local->grant.m_internal,
3158  0, 0))
3159  goto error;
3160  TABLE_LIST old_list, new_list;
3161  /*
3162  we do not need initialize old_list and new_list because we will
3163  come table[0] and table->next[0] there
3164  */
3165  old_list= table[0];
3166  new_list= table->next_local[0];
3167  if (check_grant(thd, ALTER_ACL | DROP_ACL, &old_list, FALSE, 1, FALSE) ||
3168  (!test_all_bits(table->next_local->grant.privilege,
3169  INSERT_ACL | CREATE_ACL) &&
3170  check_grant(thd, INSERT_ACL | CREATE_ACL, &new_list, FALSE, 1,
3171  FALSE)))
3172  goto error;
3173  }
3174 
3175  if (mysql_rename_tables(thd, first_table, 0))
3176  goto error;
3177  break;
3178  }
3179 #ifndef EMBEDDED_LIBRARY
3180  case SQLCOM_SHOW_BINLOGS:
3181 #ifdef DONT_ALLOW_SHOW_COMMANDS
3182  my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
3183  MYF(0)); /* purecov: inspected */
3184  goto error;
3185 #else
3186  {
3187  if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
3188  goto error;
3189  res = show_binlogs(thd);
3190  break;
3191  }
3192 #endif
3193 #endif /* EMBEDDED_LIBRARY */
3194  case SQLCOM_SHOW_CREATE:
3195  DBUG_ASSERT(first_table == all_tables && first_table != 0);
3196 #ifdef DONT_ALLOW_SHOW_COMMANDS
3197  my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
3198  MYF(0)); /* purecov: inspected */
3199  goto error;
3200 #else
3201  {
3202  /*
3203  Access check:
3204  SHOW CREATE TABLE require any privileges on the table level (ie
3205  effecting all columns in the table).
3206  SHOW CREATE VIEW require the SHOW_VIEW and SELECT ACLs on the table
3207  level.
3208  NOTE: SHOW_VIEW ACL is checked when the view is created.
3209  */
3210 
3211  DBUG_PRINT("debug", ("lex->only_view: %d, table: %s.%s",
3212  lex->only_view,
3213  first_table->db, first_table->table_name));
3214  if (lex->only_view)
3215  {
3216  if (check_table_access(thd, SELECT_ACL, first_table, FALSE, 1, FALSE))
3217  {
3218  DBUG_PRINT("debug", ("check_table_access failed"));
3219  my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
3220  "SHOW", thd->security_ctx->priv_user,
3221  thd->security_ctx->host_or_ip, first_table->alias);
3222  goto error;
3223  }
3224  DBUG_PRINT("debug", ("check_table_access succeeded"));
3225 
3226  /* Ignore temporary tables if this is "SHOW CREATE VIEW" */
3227  first_table->open_type= OT_BASE_ONLY;
3228 
3229  }
3230  else
3231  {
3232  /*
3233  Temporary tables should be opened for SHOW CREATE TABLE, but not
3234  for SHOW CREATE VIEW.
3235  */
3236  if (open_temporary_tables(thd, all_tables))
3237  goto error;
3238 
3239  /*
3240  The fact that check_some_access() returned FALSE does not mean that
3241  access is granted. We need to check if first_table->grant.privilege
3242  contains any table-specific privilege.
3243  */
3244  DBUG_PRINT("debug", ("first_table->grant.privilege: %lx",
3245  first_table->grant.privilege));
3246  if (check_some_access(thd, SHOW_CREATE_TABLE_ACLS, first_table) ||
3247  (first_table->grant.privilege & SHOW_CREATE_TABLE_ACLS) == 0)
3248  {
3249  my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
3250  "SHOW", thd->security_ctx->priv_user,
3251  thd->security_ctx->host_or_ip, first_table->alias);
3252  goto error;
3253  }
3254  }
3255 
3256  /* Access is granted. Execute the command. */
3257  res= mysqld_show_create(thd, first_table);
3258  break;
3259  }
3260 #endif
3261  case SQLCOM_CHECKSUM:
3262  {
3263  DBUG_ASSERT(first_table == all_tables && first_table != 0);
3264  if (check_table_access(thd, SELECT_ACL, all_tables,
3265  FALSE, UINT_MAX, FALSE))
3266  goto error; /* purecov: inspected */
3267 
3268  res = mysql_checksum_table(thd, first_table, &lex->check_opt);
3269  break;
3270  }
3271  case SQLCOM_UPDATE:
3272  {
3273  ha_rows found= 0, updated= 0;
3274  DBUG_ASSERT(first_table == all_tables && first_table != 0);
3275  if (update_precheck(thd, all_tables))
3276  break;
3277 
3278  /*
3279  UPDATE IGNORE can be unsafe. We therefore use row based
3280  logging if mixed or row based logging is available.
3281  TODO: Check if the order of the output of the select statement is
3282  deterministic. Waiting for BUG#42415
3283  */
3284  if (lex->ignore)
3285  lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_UPDATE_IGNORE);
3286 
3287  DBUG_ASSERT(select_lex->offset_limit == 0);
3288  unit->set_limit(select_lex);
3289  MYSQL_UPDATE_START(thd->query());
3290  res= (up_result= mysql_update(thd, all_tables,
3291  select_lex->item_list,
3292  lex->value_list,
3293  select_lex->where,
3294  select_lex->order_list.elements,
3295  select_lex->order_list.first,
3296  unit->select_limit_cnt,
3297  lex->duplicates, lex->ignore,
3298  &found, &updated));
3299  MYSQL_UPDATE_DONE(res, found, updated);
3300  /* mysql_update return 2 if we need to switch to multi-update */
3301  if (up_result != 2)
3302  break;
3303  /* Fall through */
3304  }
3305  case SQLCOM_UPDATE_MULTI:
3306  {
3307  DBUG_ASSERT(first_table == all_tables && first_table != 0);
3308  /* if we switched from normal update, rights are checked */
3309  if (up_result != 2)
3310  {
3311  if ((res= multi_update_precheck(thd, all_tables)))
3312  break;
3313  }
3314  else
3315  res= 0;
3316 
3317  res= mysql_multi_update_prepare(thd);
3318 
3319 #ifdef HAVE_REPLICATION
3320  /* Check slave filtering rules */
3321  if (unlikely(thd->slave_thread && !have_table_map_for_update))
3322  {
3323  if (all_tables_not_ok(thd, all_tables))
3324  {
3325  if (res!= 0)
3326  {
3327  res= 0; /* don't care of prev failure */
3328  thd->clear_error(); /* filters are of highest prior */
3329  }
3330  /* we warn the slave SQL thread */
3331  my_error(ER_SLAVE_IGNORED_TABLE, MYF(0));
3332  break;
3333  }
3334  if (res)
3335  break;
3336  }
3337  else
3338  {
3339 #endif /* HAVE_REPLICATION */
3340  if (res)
3341  break;
3342  if (opt_readonly &&
3343  !(thd->security_ctx->master_access & SUPER_ACL) &&
3344  some_non_temp_table_to_be_updated(thd, all_tables))
3345  {
3346  my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
3347  break;
3348  }
3349 #ifdef HAVE_REPLICATION
3350  } /* unlikely */
3351 #endif
3352  {
3353  multi_update *result_obj;
3354  MYSQL_MULTI_UPDATE_START(thd->query());
3355  res= mysql_multi_update(thd, all_tables,
3356  &select_lex->item_list,
3357  &lex->value_list,
3358  select_lex->where,
3359  select_lex->options,
3360  lex->duplicates,
3361  lex->ignore,
3362  unit,
3363  select_lex,
3364  &result_obj);
3365  if (result_obj)
3366  {
3367  MYSQL_MULTI_UPDATE_DONE(res, result_obj->num_found(),
3368  result_obj->num_updated());
3369  res= FALSE; /* Ignore errors here */
3370  delete result_obj;
3371  }
3372  else
3373  {
3374  MYSQL_MULTI_UPDATE_DONE(1, 0, 0);
3375  }
3376  }
3377  break;
3378  }
3379  case SQLCOM_REPLACE:
3380 #ifndef DBUG_OFF
3381  if (mysql_bin_log.is_open())
3382  {
3383  /*
3384  Generate an incident log event before writing the real event
3385  to the binary log. We put this event is before the statement
3386  since that makes it simpler to check that the statement was
3387  not executed on the slave (since incidents usually stop the
3388  slave).
3389 
3390  Observe that any row events that are generated will be
3391  generated before.
3392 
3393  This is only for testing purposes and will not be present in a
3394  release build.
3395  */
3396 
3397  Incident incident= INCIDENT_NONE;
3398  DBUG_PRINT("debug", ("Just before generate_incident()"));
3399  DBUG_EXECUTE_IF("incident_database_resync_on_replace",
3400  incident= INCIDENT_LOST_EVENTS;);
3401  if (incident)
3402  {
3403  Incident_log_event ev(thd, incident);
3404  if (mysql_bin_log.write_incident(&ev, true/*need_lock_log=true*/))
3405  {
3406  res= 1;
3407  break;
3408  }
3409  }
3410  DBUG_PRINT("debug", ("Just after generate_incident()"));
3411  }
3412 #endif
3413  case SQLCOM_INSERT:
3414  {
3415  DBUG_ASSERT(first_table == all_tables && first_table != 0);
3416 
3417  /*
3418  Since INSERT DELAYED doesn't support temporary tables, we could
3419  not pre-open temporary tables for SQLCOM_INSERT / SQLCOM_REPLACE.
3420  Open them here instead.
3421  */
3422  if (first_table->lock_type != TL_WRITE_DELAYED)
3423  {
3424  if ((res= open_temporary_tables(thd, all_tables)))
3425  break;
3426  }
3427 
3428  if ((res= insert_precheck(thd, all_tables)))
3429  break;
3430 
3431  MYSQL_INSERT_START(thd->query());
3432  res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
3433  lex->update_list, lex->value_list,
3434  lex->duplicates, lex->ignore);
3435  MYSQL_INSERT_DONE(res, (ulong) thd->get_row_count_func());
3436  /*
3437  If we have inserted into a VIEW, and the base table has
3438  AUTO_INCREMENT column, but this column is not accessible through
3439  a view, then we should restore LAST_INSERT_ID to the value it
3440  had before the statement.
3441  */
3442  if (first_table->view && !first_table->contain_auto_increment)
3443  thd->first_successful_insert_id_in_cur_stmt=
3444  thd->first_successful_insert_id_in_prev_stmt;
3445 
3446  DBUG_EXECUTE_IF("after_mysql_insert",
3447  {
3448  const char act[]=
3449  "now "
3450  "wait_for signal.continue";
3451  DBUG_ASSERT(opt_debug_sync_timeout > 0);
3452  DBUG_ASSERT(!debug_sync_set_action(current_thd,
3453  STRING_WITH_LEN(act)));
3454  };);
3455  break;
3456  }
3457  case SQLCOM_REPLACE_SELECT:
3458  case SQLCOM_INSERT_SELECT:
3459  {
3460  select_insert *sel_result;
3461  DBUG_ASSERT(first_table == all_tables && first_table != 0);
3462  if ((res= insert_precheck(thd, all_tables)))
3463  break;
3464  /*
3465  INSERT...SELECT...ON DUPLICATE KEY UPDATE/REPLACE SELECT/
3466  INSERT...IGNORE...SELECT can be unsafe, unless ORDER BY PRIMARY KEY
3467  clause is used in SELECT statement. We therefore use row based
3468  logging if mixed or row based logging is available.
3469  TODO: Check if the order of the output of the select statement is
3470  deterministic. Waiting for BUG#42415
3471  */
3472  if (lex->sql_command == SQLCOM_INSERT_SELECT &&
3473  lex->duplicates == DUP_UPDATE)
3474  lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_INSERT_SELECT_UPDATE);
3475 
3476  if (lex->sql_command == SQLCOM_INSERT_SELECT && lex->ignore)
3477  lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_INSERT_IGNORE_SELECT);
3478 
3479  if (lex->sql_command == SQLCOM_REPLACE_SELECT)
3480  lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_REPLACE_SELECT);
3481 
3482  /* Fix lock for first table */
3483  if (first_table->lock_type == TL_WRITE_DELAYED)
3484  first_table->lock_type= TL_WRITE;
3485 
3486  /* Don't unlock tables until command is written to binary log */
3487  select_lex->options|= SELECT_NO_UNLOCK;
3488 
3489  unit->set_limit(select_lex);
3490 
3491  if (!(res= open_normal_and_derived_tables(thd, all_tables, 0)))
3492  {
3493  MYSQL_INSERT_SELECT_START(thd->query());
3494  /* Skip first table, which is the table we are inserting in */
3495  TABLE_LIST *second_table= first_table->next_local;
3496  select_lex->table_list.first= second_table;
3497  select_lex->context.table_list=
3498  select_lex->context.first_name_resolution_table= second_table;
3499  res= mysql_insert_select_prepare(thd);
3500  if (!res && (sel_result= new select_insert(first_table,
3501  first_table->table,
3502  &lex->field_list,
3503  &lex->field_list,
3504  &lex->update_list,
3505  &lex->value_list,
3506  lex->duplicates,
3507  lex->ignore)))
3508  {
3509  if (lex->describe)
3510  res= explain_multi_table_modification(thd, sel_result);
3511  else
3512  {
3513  res= handle_select(thd, sel_result, OPTION_SETUP_TABLES_DONE);
3514  /*
3515  Invalidate the table in the query cache if something changed
3516  after unlocking when changes become visible.
3517  TODO: this is workaround. right way will be move invalidating in
3518  the unlock procedure.
3519  */
3520  if (!res && first_table->lock_type == TL_WRITE_CONCURRENT_INSERT &&
3521  thd->lock)
3522  {
3523  /* INSERT ... SELECT should invalidate only the very first table */
3524  TABLE_LIST *save_table= first_table->next_local;
3525  first_table->next_local= 0;
3526  query_cache_invalidate3(thd, first_table, 1);
3527  first_table->next_local= save_table;
3528  }
3529  }
3530  delete sel_result;
3531  }
3532  /* revert changes for SP */
3533  MYSQL_INSERT_SELECT_DONE(res, (ulong) thd->get_row_count_func());
3534  select_lex->table_list.first= first_table;
3535  }
3536  /*
3537  If we have inserted into a VIEW, and the base table has
3538  AUTO_INCREMENT column, but this column is not accessible through
3539  a view, then we should restore LAST_INSERT_ID to the value it
3540  had before the statement.
3541  */
3542  if (first_table->view && !first_table->contain_auto_increment)
3543  thd->first_successful_insert_id_in_cur_stmt=
3544  thd->first_successful_insert_id_in_prev_stmt;
3545 
3546  break;
3547  }
3548  case SQLCOM_DELETE:
3549  {
3550  DBUG_ASSERT(first_table == all_tables && first_table != 0);
3551  if ((res= delete_precheck(thd, all_tables)))
3552  break;
3553  DBUG_ASSERT(select_lex->offset_limit == 0);
3554  unit->set_limit(select_lex);
3555 
3556  MYSQL_DELETE_START(thd->query());
3557  res = mysql_delete(thd, all_tables, select_lex->where,
3558  &select_lex->order_list,
3559  unit->select_limit_cnt, select_lex->options);
3560  MYSQL_DELETE_DONE(res, (ulong) thd->get_row_count_func());
3561  break;
3562  }
3563  case SQLCOM_DELETE_MULTI:
3564  {
3565  DBUG_ASSERT(first_table == all_tables && first_table != 0);
3566  TABLE_LIST *aux_tables= thd->lex->auxiliary_table_list.first;
3567  uint del_table_count;
3568  multi_delete *del_result;
3569 
3570  if ((res= multi_delete_precheck(thd, all_tables)))
3571  break;
3572 
3573  /* condition will be TRUE on SP re-excuting */
3574  if (select_lex->item_list.elements != 0)
3575  select_lex->item_list.empty();
3576  if (add_item_to_list(thd, new Item_null()))
3577  goto error;
3578 
3579  THD_STAGE_INFO(thd, stage_init);
3580  if ((res= open_normal_and_derived_tables(thd, all_tables, 0)))
3581  break;
3582 
3583  MYSQL_MULTI_DELETE_START(thd->query());
3584  if ((res= mysql_multi_delete_prepare(thd, &del_table_count)))
3585  {
3586  MYSQL_MULTI_DELETE_DONE(1, 0);
3587  goto error;
3588  }
3589 
3590  if (!thd->is_fatal_error &&
3591  (del_result= new multi_delete(aux_tables, del_table_count)))
3592  {
3593  if (lex->describe)
3594  res= explain_multi_table_modification(thd, del_result);
3595  else
3596  {
3597  res= mysql_select(thd,
3598  select_lex->get_table_list(),
3599  select_lex->with_wild,
3600  select_lex->item_list,
3601  select_lex->where,
3602  (SQL_I_List<ORDER> *)NULL, (SQL_I_List<ORDER> *)NULL,
3603  (Item *)NULL,
3604  (select_lex->options | thd->variables.option_bits |
3605  SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
3606  OPTION_SETUP_TABLES_DONE) & ~OPTION_BUFFER_RESULT,
3607  del_result, unit, select_lex);
3608  res|= thd->is_error();
3609  if (res)
3610  del_result->abort_result_set();
3611  }
3612  MYSQL_MULTI_DELETE_DONE(res, del_result->num_deleted());
3613  delete del_result;
3614  }
3615  else
3616  {
3617  res= TRUE; // Error
3618  MYSQL_MULTI_DELETE_DONE(1, 0);
3619  }
3620  break;
3621  }
3622  case SQLCOM_DROP_TABLE:
3623  {
3624  DBUG_ASSERT(first_table == all_tables && first_table != 0);
3625  if (!lex->drop_temporary)
3626  {
3627  if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE))
3628  goto error; /* purecov: inspected */
3629  }
3630  /* DDL and binlog write order are protected by metadata locks. */
3631  res= mysql_rm_table(thd, first_table, lex->drop_if_exists,
3632  lex->drop_temporary);
3633  }
3634  break;
3635  case SQLCOM_SHOW_PROCESSLIST:
3636  if (!thd->security_ctx->priv_user[0] &&
3637  check_global_access(thd,PROCESS_ACL))
3638  break;
3639  mysqld_list_processes(thd,
3640  (thd->security_ctx->master_access & PROCESS_ACL ?
3641  NullS :
3642  thd->security_ctx->priv_user),
3643  lex->verbose);
3644  break;
3645  case SQLCOM_SHOW_PRIVILEGES:
3646  res= mysqld_show_privileges(thd);
3647  break;
3648  case SQLCOM_SHOW_ENGINE_LOGS:
3649 #ifdef DONT_ALLOW_SHOW_COMMANDS
3650  my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
3651  MYF(0)); /* purecov: inspected */
3652  goto error;
3653 #else
3654  {
3655  if (check_access(thd, FILE_ACL, any_db, NULL, NULL, 0, 0))
3656  goto error;
3657  res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS);
3658  break;
3659  }
3660 #endif
3661  case SQLCOM_CHANGE_DB:
3662  {
3663  LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) };
3664 
3665  if (!mysql_change_db(thd, &db_str, FALSE))
3666  my_ok(thd);
3667 
3668  break;
3669  }
3670 
3671  case SQLCOM_LOAD:
3672  {
3673  DBUG_ASSERT(first_table == all_tables && first_table != 0);
3674  uint privilege= (lex->duplicates == DUP_REPLACE ?
3675  INSERT_ACL | DELETE_ACL : INSERT_ACL) |
3676  (lex->local_file ? 0 : FILE_ACL);
3677 
3678  if (lex->local_file)
3679  {
3680  if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) ||
3681  !opt_local_infile)
3682  {
3683  my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0));
3684  goto error;
3685  }
3686  }
3687 
3688  if (check_one_table_access(thd, privilege, all_tables))
3689  goto error;
3690 
3691  res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
3692  lex->update_list, lex->value_list, lex->duplicates,
3693  lex->ignore, (bool) lex->local_file);
3694  break;
3695  }
3696 
3697  case SQLCOM_SET_OPTION:
3698  {
3699  List<set_var_base> *lex_var_list= &lex->var_list;
3700 
3701  if ((check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)
3702  || open_and_lock_tables(thd, all_tables, TRUE, 0)))
3703  goto error;
3704  if (!(res= sql_set_variables(thd, lex_var_list)))
3705  {
3706  /*
3707  If the previous command was a SET ONE_SHOT, we don't want to forget
3708  about the ONE_SHOT property of that SET. So we use a |= instead of = .
3709  */
3710  thd->one_shot_set|= lex->one_shot_set;
3711  my_ok(thd);
3712  }
3713  else
3714  {
3715  /*
3716  We encountered some sort of error, but no message was sent.
3717  Send something semi-generic here since we don't know which
3718  assignment in the list caused the error.
3719  */
3720  if (!thd->is_error())
3721  my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET");
3722  goto error;
3723  }
3724 
3725  break;
3726  }
3727 
3728  case SQLCOM_UNLOCK_TABLES:
3729  /*
3730  It is critical for mysqldump --single-transaction --master-data that
3731  UNLOCK TABLES does not implicitely commit a connection which has only
3732  done FLUSH TABLES WITH READ LOCK + BEGIN. If this assumption becomes
3733  false, mysqldump will not work.
3734  */
3735  if (thd->variables.option_bits & OPTION_TABLE_LOCK)
3736  {
3737  /*
3738  Can we commit safely? If not, return to avoid releasing
3739  transactional metadata locks.
3740  */
3741  if (trans_check_state(thd))
3742  DBUG_RETURN(-1);
3743  res= trans_commit_implicit(thd);
3744  thd->locked_tables_list.unlock_locked_tables(thd);
3745  thd->mdl_context.release_transactional_locks();
3746  thd->variables.option_bits&= ~(OPTION_TABLE_LOCK);
3747  }
3748  if (thd->global_read_lock.is_acquired())
3749  thd->global_read_lock.unlock_global_read_lock(thd);
3750  if (res)
3751  goto error;
3752  my_ok(thd);
3753  break;
3754  case SQLCOM_LOCK_TABLES:
3755  /*
3756  Can we commit safely? If not, return to avoid releasing
3757  transactional metadata locks.
3758  */
3759  if (trans_check_state(thd))
3760  DBUG_RETURN(-1);
3761  /* We must end the transaction first, regardless of anything */
3762  res= trans_commit_implicit(thd);
3763  thd->locked_tables_list.unlock_locked_tables(thd);
3764  /* Release transactional metadata locks. */
3765  thd->mdl_context.release_transactional_locks();
3766  if (res)
3767  goto error;
3768 
3769  /*
3770  Here we have to pre-open temporary tables for LOCK TABLES.
3771 
3772  CF_PREOPEN_TMP_TABLES is not set for this SQL statement simply
3773  because LOCK TABLES calls close_thread_tables() as a first thing
3774  (it's called from unlock_locked_tables() above). So even if
3775  CF_PREOPEN_TMP_TABLES was set and the tables would be pre-opened
3776  in a usual way, they would have been closed.
3777  */
3778 
3779  if (open_temporary_tables(thd, all_tables))
3780  goto error;
3781 
3782  if (lock_tables_precheck(thd, all_tables))
3783  goto error;
3784 
3785  thd->variables.option_bits|= OPTION_TABLE_LOCK;
3786 
3787  res= lock_tables_open_and_lock_tables(thd, all_tables);
3788 
3789  if (res)
3790  {
3791  thd->variables.option_bits&= ~(OPTION_TABLE_LOCK);
3792  }
3793  else
3794  {
3795 #ifdef HAVE_QUERY_CACHE
3796  if (thd->variables.query_cache_wlock_invalidate)
3797  query_cache.invalidate_locked_for_write(first_table);
3798 #endif /*HAVE_QUERY_CACHE*/
3799  my_ok(thd);
3800  }
3801  break;
3802  case SQLCOM_CREATE_DB:
3803  {
3804  /*
3805  As mysql_create_db() may modify HA_CREATE_INFO structure passed to
3806  it, we need to use a copy of LEX::create_info to make execution
3807  prepared statement- safe.
3808  */
3809  HA_CREATE_INFO create_info(lex->create_info);
3810  char *alias;
3811  if (!(alias=thd->strmake(lex->name.str, lex->name.length)) ||
3812  (check_and_convert_db_name(&lex->name, FALSE) != IDENT_NAME_OK))
3813  break;
3814  /*
3815  If in a slave thread :
3816  CREATE DATABASE DB was certainly not preceded by USE DB.
3817  For that reason, db_ok() in sql/slave.cc did not check the
3818  do_db/ignore_db. And as this query involves no tables, tables_ok()
3819  above was not called. So we have to check rules again here.
3820  */
3821 #ifdef HAVE_REPLICATION
3822  if (!db_stmt_db_ok(thd, lex->name.str))
3823  {
3824  my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3825  break;
3826  }
3827 #endif
3828  if (check_access(thd, CREATE_ACL, lex->name.str, NULL, NULL, 1, 0))
3829  break;
3830  res= mysql_create_db(thd,(lower_case_table_names == 2 ? alias :
3831  lex->name.str), &create_info, 0);
3832  break;
3833  }
3834  case SQLCOM_DROP_DB:
3835  {
3836  if (check_and_convert_db_name(&lex->name, FALSE) != IDENT_NAME_OK)
3837  break;
3838  /*
3839  If in a slave thread :
3840  DROP DATABASE DB may not be preceded by USE DB.
3841  For that reason, maybe db_ok() in sql/slave.cc did not check the
3842  do_db/ignore_db. And as this query involves no tables, tables_ok()
3843  above was not called. So we have to check rules again here.
3844  */
3845 #ifdef HAVE_REPLICATION
3846  if (!db_stmt_db_ok(thd, lex->name.str))
3847  {
3848  my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3849  break;
3850  }
3851 #endif
3852  if (check_access(thd, DROP_ACL, lex->name.str, NULL, NULL, 1, 0))
3853  break;
3854  res= mysql_rm_db(thd, lex->name.str, lex->drop_if_exists, 0);
3855  break;
3856  }
3857  case SQLCOM_ALTER_DB_UPGRADE:
3858  {
3859  LEX_STRING *db= & lex->name;
3860 #ifdef HAVE_REPLICATION
3861  if (!db_stmt_db_ok(thd, lex->name.str))
3862  {
3863  res= 1;
3864  my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3865  break;
3866  }
3867 #endif
3868  if (check_and_convert_db_name(db, FALSE) != IDENT_NAME_OK)
3869  break;
3870  if (check_access(thd, ALTER_ACL, db->str, NULL, NULL, 1, 0) ||
3871  check_access(thd, DROP_ACL, db->str, NULL, NULL, 1, 0) ||
3872  check_access(thd, CREATE_ACL, db->str, NULL, NULL, 1, 0))
3873  {
3874  res= 1;
3875  break;
3876  }
3877  res= mysql_upgrade_db(thd, db);
3878  if (!res)
3879  my_ok(thd);
3880  break;
3881  }
3882  case SQLCOM_ALTER_DB:
3883  {
3884  LEX_STRING *db= &lex->name;
3885  HA_CREATE_INFO create_info(lex->create_info);
3886  if (check_and_convert_db_name(db, FALSE) != IDENT_NAME_OK)
3887  break;
3888  /*
3889  If in a slave thread :
3890  ALTER DATABASE DB may not be preceded by USE DB.
3891  For that reason, maybe db_ok() in sql/slave.cc did not check the
3892  do_db/ignore_db. And as this query involves no tables, tables_ok()
3893  above was not called. So we have to check rules again here.
3894  */
3895 #ifdef HAVE_REPLICATION
3896  if (!db_stmt_db_ok(thd, lex->name.str))
3897  {
3898  my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3899  break;
3900  }
3901 #endif
3902  if (check_access(thd, ALTER_ACL, db->str, NULL, NULL, 1, 0))
3903  break;
3904  res= mysql_alter_db(thd, db->str, &create_info);
3905  break;
3906  }
3907  case SQLCOM_SHOW_CREATE_DB:
3908  {
3909  DBUG_EXECUTE_IF("4x_server_emul",
3910  my_error(ER_UNKNOWN_ERROR, MYF(0)); goto error;);
3911  if (check_and_convert_db_name(&lex->name, TRUE) != IDENT_NAME_OK)
3912  break;
3913  res= mysqld_show_create_db(thd, lex->name.str, &lex->create_info);
3914  break;
3915  }
3916  case SQLCOM_CREATE_EVENT:
3917  case SQLCOM_ALTER_EVENT:
3918  #ifdef HAVE_EVENT_SCHEDULER
3919  do
3920  {
3921  DBUG_ASSERT(lex->event_parse_data);
3922  if (lex->table_or_sp_used())
3923  {
3924  my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Usage of subqueries or stored "
3925  "function calls as part of this statement");
3926  break;
3927  }
3928 
3929  res= sp_process_definer(thd);
3930  if (res)
3931  break;
3932 
3933  switch (lex->sql_command) {
3934  case SQLCOM_CREATE_EVENT:
3935  {
3936  bool if_not_exists= (lex->create_info.options &
3937  HA_LEX_CREATE_IF_NOT_EXISTS);
3938  res= Events::create_event(thd, lex->event_parse_data, if_not_exists);
3939  break;
3940  }
3941  case SQLCOM_ALTER_EVENT:
3942  res= Events::update_event(thd, lex->event_parse_data,
3943  lex->spname ? &lex->spname->m_db : NULL,
3944  lex->spname ? &lex->spname->m_name : NULL);
3945  break;
3946  default:
3947  DBUG_ASSERT(0);
3948  }
3949  DBUG_PRINT("info",("DDL error code=%d", res));
3950  if (!res)
3951  my_ok(thd);
3952 
3953  } while (0);
3954  /* Don't do it, if we are inside a SP */
3955  if (!thd->sp_runtime_ctx)
3956  {
3957  delete lex->sphead;
3958  lex->sphead= NULL;
3959  }
3960  /* lex->unit.cleanup() is called outside, no need to call it here */
3961  break;
3962  case SQLCOM_SHOW_CREATE_EVENT:
3963  res= Events::show_create_event(thd, lex->spname->m_db,
3964  lex->spname->m_name);
3965  break;
3966  case SQLCOM_DROP_EVENT:
3967  if (!(res= Events::drop_event(thd,
3968  lex->spname->m_db, lex->spname->m_name,
3969  lex->drop_if_exists)))
3970  my_ok(thd);
3971  break;
3972 #else
3973  my_error(ER_NOT_SUPPORTED_YET,MYF(0),"embedded server");
3974  break;
3975 #endif
3976  case SQLCOM_CREATE_FUNCTION: // UDF function
3977  {
3978  if (check_access(thd, INSERT_ACL, "mysql", NULL, NULL, 1, 0))
3979  break;
3980 #ifdef HAVE_DLOPEN
3981  if (!(res = mysql_create_function(thd, &lex->udf)))
3982  my_ok(thd);
3983 #else
3984  my_error(ER_CANT_OPEN_LIBRARY, MYF(0), lex->udf.dl, 0, "feature disabled");
3985  res= TRUE;
3986 #endif
3987  break;
3988  }
3989 #ifndef NO_EMBEDDED_ACCESS_CHECKS
3990  case SQLCOM_CREATE_USER:
3991  {
3992  if (check_access(thd, INSERT_ACL, "mysql", NULL, NULL, 1, 1) &&
3993  check_global_access(thd,CREATE_USER_ACL))
3994  break;
3995  /* Conditionally writes to binlog */
3996  if (!(res= mysql_create_user(thd, lex->users_list)))
3997  my_ok(thd);
3998  break;
3999  }
4000  case SQLCOM_DROP_USER:
4001  {
4002  if (check_access(thd, DELETE_ACL, "mysql", NULL, NULL, 1, 1) &&
4003  check_global_access(thd,CREATE_USER_ACL))
4004  break;
4005  /* Conditionally writes to binlog */
4006  if (!(res= mysql_drop_user(thd, lex->users_list)))
4007  my_ok(thd);
4008  break;
4009  }
4010  case SQLCOM_RENAME_USER:
4011  {
4012  if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) &&
4013  check_global_access(thd,CREATE_USER_ACL))
4014  break;
4015  /* Conditionally writes to binlog */
4016  if (!(res= mysql_rename_user(thd, lex->users_list)))
4017  my_ok(thd);
4018  break;
4019  }
4020  case SQLCOM_REVOKE_ALL:
4021  {
4022  if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) &&
4023  check_global_access(thd,CREATE_USER_ACL))
4024  break;
4025 
4026  /* Replicate current user as grantor */
4027  thd->binlog_invoker();
4028 
4029  /* Conditionally writes to binlog */
4030  if (!(res = mysql_revoke_all(thd, lex->users_list)))
4031  my_ok(thd);
4032  break;
4033  }
4034  case SQLCOM_REVOKE:
4035  case SQLCOM_GRANT:
4036  {
4037  if (lex->type != TYPE_ENUM_PROXY &&
4038  check_access(thd, lex->grant | lex->grant_tot_col | GRANT_ACL,
4039  first_table ? first_table->db : select_lex->db,
4040  first_table ? &first_table->grant.privilege : NULL,
4041  first_table ? &first_table->grant.m_internal : NULL,
4042  first_table ? 0 : 1, 0))
4043  goto error;
4044 
4045  /* Replicate current user as grantor */
4046  thd->binlog_invoker();
4047 
4048  if (thd->security_ctx->user) // If not replication
4049  {
4050  LEX_USER *user, *tmp_user;
4051  bool first_user= TRUE;
4052 
4053  List_iterator <LEX_USER> user_list(lex->users_list);
4054  while ((tmp_user= user_list++))
4055  {
4056  if (!(user= get_current_user(thd, tmp_user)))
4057  goto error;
4058  if (specialflag & SPECIAL_NO_RESOLVE &&
4059  hostname_requires_resolving(user->host.str))
4060  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
4061  ER_WARN_HOSTNAME_WONT_WORK,
4062  ER(ER_WARN_HOSTNAME_WONT_WORK));
4063  // Are we trying to change a password of another user
4064  DBUG_ASSERT(user->host.str != 0);
4065 
4066  /*
4067  GRANT/REVOKE PROXY has the target user as a first entry in the list.
4068  */
4069  if (lex->type == TYPE_ENUM_PROXY && first_user)
4070  {
4071  first_user= FALSE;
4072  if (acl_check_proxy_grant_access (thd, user->host.str, user->user.str,
4073  lex->grant & GRANT_ACL))
4074  goto error;
4075  }
4076  else if (is_acl_user(user->host.str, user->user.str) &&
4077  user->password.str &&
4078  check_change_password (thd, user->host.str, user->user.str,
4079  user->password.str,
4080  user->password.length))
4081  goto error;
4082  }
4083  }
4084  if (first_table)
4085  {
4086  if (lex->type == TYPE_ENUM_PROCEDURE ||
4087  lex->type == TYPE_ENUM_FUNCTION)
4088  {
4089  uint grants= lex->all_privileges
4090  ? (PROC_ACLS & ~GRANT_ACL) | (lex->grant & GRANT_ACL)
4091  : lex->grant;
4092  if (check_grant_routine(thd, grants | GRANT_ACL, all_tables,
4093  lex->type == TYPE_ENUM_PROCEDURE, 0))
4094  goto error;
4095  /* Conditionally writes to binlog */
4096  res= mysql_routine_grant(thd, all_tables,
4097  lex->type == TYPE_ENUM_PROCEDURE,
4098  lex->users_list, grants,
4099  lex->sql_command == SQLCOM_REVOKE, TRUE);
4100  if (!res)
4101  my_ok(thd);
4102  }
4103  else
4104  {
4105  if (check_grant(thd,(lex->grant | lex->grant_tot_col | GRANT_ACL),
4106  all_tables, FALSE, UINT_MAX, FALSE))
4107  goto error;
4108  /* Conditionally writes to binlog */
4109  res= mysql_table_grant(thd, all_tables, lex->users_list,
4110  lex->columns, lex->grant,
4111  lex->sql_command == SQLCOM_REVOKE);
4112  }
4113  }
4114  else
4115  {
4116  if (lex->columns.elements || (lex->type && lex->type != TYPE_ENUM_PROXY))
4117  {
4118  my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
4119  MYF(0));
4120  goto error;
4121  }
4122  else
4123  {
4124  /* Conditionally writes to binlog */
4125  res = mysql_grant(thd, select_lex->db, lex->users_list, lex->grant,
4126  lex->sql_command == SQLCOM_REVOKE,
4127  lex->type == TYPE_ENUM_PROXY);
4128  }
4129  if (!res)
4130  {
4131  if (lex->sql_command == SQLCOM_GRANT)
4132  {
4133  List_iterator <LEX_USER> str_list(lex->users_list);
4134  LEX_USER *user, *tmp_user;
4135  while ((tmp_user=str_list++))
4136  {
4137  if (!(user= get_current_user(thd, tmp_user)))
4138  goto error;
4139  reset_mqh(user, 0);
4140  }
4141  }
4142  }
4143  }
4144  break;
4145  }
4146 #endif
4147  case SQLCOM_RESET:
4148  /*
4149  RESET commands are never written to the binary log, so we have to
4150  initialize this variable because RESET shares the same code as FLUSH
4151  */
4152  lex->no_write_to_binlog= 1;
4153  case SQLCOM_FLUSH:
4154  {
4155  int write_to_binlog;
4156  if (check_global_access(thd,RELOAD_ACL))
4157  goto error;
4158 
4159  if (first_table && lex->type & REFRESH_READ_LOCK)
4160  {
4161  /* Check table-level privileges. */
4162  if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, all_tables,
4163  FALSE, UINT_MAX, FALSE))
4164  goto error;
4165  if (flush_tables_with_read_lock(thd, all_tables))
4166  goto error;
4167  my_ok(thd);
4168  break;
4169  }
4170  else if (first_table && lex->type & REFRESH_FOR_EXPORT)
4171  {
4172  /* Check table-level privileges. */
4173  if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, all_tables,
4174  FALSE, UINT_MAX, FALSE))
4175  goto error;
4176  if (flush_tables_for_export(thd, all_tables))
4177  goto error;
4178  my_ok(thd);
4179  break;
4180  }
4181 
4182  /*
4183  reload_acl_and_cache() will tell us if we are allowed to write to the
4184  binlog or not.
4185  */
4186  if (!reload_acl_and_cache(thd, lex->type, first_table, &write_to_binlog))
4187  {
4188  /*
4189  We WANT to write and we CAN write.
4190  ! we write after unlocking the table.
4191  */
4192  /*
4193  Presumably, RESET and binlog writing doesn't require synchronization
4194  */
4195 
4196  if (write_to_binlog > 0) // we should write
4197  {
4198  if (!lex->no_write_to_binlog)
4199  res= write_bin_log(thd, FALSE, thd->query(), thd->query_length());
4200  } else if (write_to_binlog < 0)
4201  {
4202  /*
4203  We should not write, but rather report error because
4204  reload_acl_and_cache binlog interactions failed
4205  */
4206  res= 1;
4207  }
4208 
4209  if (!res)
4210  my_ok(thd);
4211  }
4212 
4213  break;
4214  }
4215  case SQLCOM_KILL:
4216  {
4217  Item *it= (Item *)lex->value_list.head();
4218 
4219  if (lex->table_or_sp_used())
4220  {
4221  my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Usage of subqueries or stored "
4222  "function calls as part of this statement");
4223  break;
4224  }
4225 
4226  if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1))
4227  {
4228  my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY),
4229  MYF(0));
4230  goto error;
4231  }
4232  sql_kill(thd, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY);
4233  break;
4234  }
4235 #ifndef NO_EMBEDDED_ACCESS_CHECKS
4236  case SQLCOM_SHOW_GRANTS:
4237  {
4238  LEX_USER *grant_user= get_current_user(thd, lex->grant_user);
4239  if (!grant_user)
4240  goto error;
4241  if ((thd->security_ctx->priv_user &&
4242  !strcmp(thd->security_ctx->priv_user, grant_user->user.str)) ||
4243  !check_access(thd, SELECT_ACL, "mysql", NULL, NULL, 1, 0))
4244  {
4245  res = mysql_show_grants(thd, grant_user);
4246  }
4247  break;
4248  }
4249 #endif
4250  case SQLCOM_BEGIN:
4251  if (trans_begin(thd, lex->start_transaction_opt))
4252  goto error;
4253  my_ok(thd);
4254  break;
4255  case SQLCOM_COMMIT:
4256  {
4257  DBUG_ASSERT(thd->lock == NULL ||
4258  thd->locked_tables_mode == LTM_LOCK_TABLES);
4259  bool tx_chain= (lex->tx_chain == TVL_YES ||
4260  (thd->variables.completion_type == 1 &&
4261  lex->tx_chain != TVL_NO));
4262  bool tx_release= (lex->tx_release == TVL_YES ||
4263  (thd->variables.completion_type == 2 &&
4264  lex->tx_release != TVL_NO));
4265  if (trans_commit(thd))
4266  goto error;
4267  thd->mdl_context.release_transactional_locks();
4268  /* Begin transaction with the same isolation level. */
4269  if (tx_chain)
4270  {
4271  if (trans_begin(thd))
4272  goto error;
4273  }
4274  else
4275  {
4276  /* Reset the isolation level and access mode if no chaining transaction.*/
4277  thd->tx_isolation= (enum_tx_isolation) thd->variables.tx_isolation;
4278  thd->tx_read_only= thd->variables.tx_read_only;
4279  }
4280  /* Disconnect the current client connection. */
4281  if (tx_release)
4282  thd->killed= THD::KILL_CONNECTION;
4283  my_ok(thd);
4284  break;
4285  }
4286  case SQLCOM_ROLLBACK:
4287  {
4288  DBUG_ASSERT(thd->lock == NULL ||
4289  thd->locked_tables_mode == LTM_LOCK_TABLES);
4290  bool tx_chain= (lex->tx_chain == TVL_YES ||
4291  (thd->variables.completion_type == 1 &&
4292  lex->tx_chain != TVL_NO));
4293  bool tx_release= (lex->tx_release == TVL_YES ||
4294  (thd->variables.completion_type == 2 &&
4295  lex->tx_release != TVL_NO));
4296  if (trans_rollback(thd))
4297  goto error;
4298  thd->mdl_context.release_transactional_locks();
4299  /* Begin transaction with the same isolation level. */
4300  if (tx_chain)
4301  {
4302  if (trans_begin(thd))
4303  goto error;
4304  }
4305  else
4306  {
4307  /* Reset the isolation level and access mode if no chaining transaction.*/
4308  thd->tx_isolation= (enum_tx_isolation) thd->variables.tx_isolation;
4309  thd->tx_read_only= thd->variables.tx_read_only;
4310  }
4311  /* Disconnect the current client connection. */
4312  if (tx_release)
4313  thd->killed= THD::KILL_CONNECTION;
4314  my_ok(thd);
4315  break;
4316  }
4317  case SQLCOM_RELEASE_SAVEPOINT:
4318  if (trans_release_savepoint(thd, lex->ident))
4319  goto error;
4320  my_ok(thd);
4321  break;
4322  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
4323  if (trans_rollback_to_savepoint(thd, lex->ident))
4324  goto error;
4325  my_ok(thd);
4326  break;
4327  case SQLCOM_SAVEPOINT:
4328  if (trans_savepoint(thd, lex->ident))
4329  goto error;
4330  my_ok(thd);
4331  break;
4332  case SQLCOM_CREATE_PROCEDURE:
4333  case SQLCOM_CREATE_SPFUNCTION:
4334  {
4335  uint namelen;
4336  char *name;
4337  int sp_result= SP_INTERNAL_ERROR;
4338 
4339  DBUG_ASSERT(lex->sphead != 0);
4340  DBUG_ASSERT(lex->sphead->m_db.str); /* Must be initialized in the parser */
4341  /*
4342  Verify that the database name is allowed, optionally
4343  lowercase it.
4344  */
4345  if (check_and_convert_db_name(&lex->sphead->m_db, FALSE) != IDENT_NAME_OK)
4346  goto create_sp_error;
4347 
4348  if (check_access(thd, CREATE_PROC_ACL, lex->sphead->m_db.str,
4349  NULL, NULL, 0, 0))
4350  goto create_sp_error;
4351 
4352  /*
4353  Check that a database directory with this name
4354  exists. Design note: This won't work on virtual databases
4355  like information_schema.
4356  */
4357  if (check_db_dir_existence(lex->sphead->m_db.str))
4358  {
4359  my_error(ER_BAD_DB_ERROR, MYF(0), lex->sphead->m_db.str);
4360  goto create_sp_error;
4361  }
4362 
4363  name= lex->sphead->name(&namelen);
4364 #ifdef HAVE_DLOPEN
4365  if (lex->sphead->m_type == SP_TYPE_FUNCTION)
4366  {
4367  udf_func *udf = find_udf(name, namelen);
4368 
4369  if (udf)
4370  {
4371  my_error(ER_UDF_EXISTS, MYF(0), name);
4372  goto create_sp_error;
4373  }
4374  }
4375 #endif
4376 
4377  if (sp_process_definer(thd))
4378  goto create_sp_error;
4379 
4380  res= (sp_result= sp_create_routine(thd, lex->sphead));
4381  switch (sp_result) {
4382  case SP_OK: {
4383 #ifndef NO_EMBEDDED_ACCESS_CHECKS
4384  /* only add privileges if really neccessary */
4385 
4386  Security_context security_context;
4387  bool restore_backup_context= false;
4388  Security_context *backup= NULL;
4389  LEX_USER *definer= thd->lex->definer;
4390  /*
4391  We're going to issue an implicit GRANT statement so we close all
4392  open tables. We have to keep metadata locks as this ensures that
4393  this statement is atomic against concurent FLUSH TABLES WITH READ
4394  LOCK. Deadlocks which can arise due to fact that this implicit
4395  statement takes metadata locks should be detected by a deadlock
4396  detector in MDL subsystem and reported as errors.
4397 
4398  No need to commit/rollback statement transaction, it's not started.
4399 
4400  TODO: Long-term we should either ensure that implicit GRANT statement
4401  is written into binary log as a separate statement or make both
4402  creation of routine and implicit GRANT parts of one fully atomic
4403  statement.
4404  */
4405  DBUG_ASSERT(thd->transaction.stmt.is_empty());
4406  close_thread_tables(thd);
4407  /*
4408  Check if the definer exists on slave,
4409  then use definer privilege to insert routine privileges to mysql.procs_priv.
4410 
4411  For current user of SQL thread has GLOBAL_ACL privilege,
4412  which doesn't any check routine privileges,
4413  so no routine privilege record will insert into mysql.procs_priv.
4414  */
4415  if (thd->slave_thread && is_acl_user(definer->host.str, definer->user.str))
4416  {
4417  security_context.change_security_context(thd,
4418  &thd->lex->definer->user,
4419  &thd->lex->definer->host,
4420  &thd->lex->sphead->m_db,
4421  &backup);
4422  restore_backup_context= true;
4423  }
4424 
4425  if (sp_automatic_privileges && !opt_noacl &&
4426  check_routine_access(thd, DEFAULT_CREATE_PROC_ACLS,
4427  lex->sphead->m_db.str, name,
4428  lex->sql_command == SQLCOM_CREATE_PROCEDURE, 1))
4429  {
4430  if (sp_grant_privileges(thd, lex->sphead->m_db.str, name,
4431  lex->sql_command == SQLCOM_CREATE_PROCEDURE))
4432  push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
4433  ER_PROC_AUTO_GRANT_FAIL, ER(ER_PROC_AUTO_GRANT_FAIL));
4434  thd->clear_error();
4435  }
4436 
4437  /*
4438  Restore current user with GLOBAL_ACL privilege of SQL thread
4439  */
4440  if (restore_backup_context)
4441  {
4442  DBUG_ASSERT(thd->slave_thread == 1);
4443  thd->security_ctx->restore_security_context(thd, backup);
4444  }
4445 
4446 #endif
4447  break;
4448  }
4449  case SP_WRITE_ROW_FAILED:
4450  my_error(ER_SP_ALREADY_EXISTS, MYF(0), SP_TYPE_STRING(lex), name);
4451  break;
4452  case SP_BAD_IDENTIFIER:
4453  my_error(ER_TOO_LONG_IDENT, MYF(0), name);
4454  break;
4455  case SP_BODY_TOO_LONG:
4456  my_error(ER_TOO_LONG_BODY, MYF(0), name);
4457  break;
4458  case SP_FLD_STORE_FAILED:
4459  my_error(ER_CANT_CREATE_SROUTINE, MYF(0), name);
4460  break;
4461  default:
4462  my_error(ER_SP_STORE_FAILED, MYF(0), SP_TYPE_STRING(lex), name);
4463  break;
4464  } /* end switch */
4465 
4466  /*
4467  Capture all errors within this CASE and
4468  clean up the environment.
4469  */
4470 create_sp_error:
4471  if (sp_result != SP_OK )
4472  goto error;
4473  my_ok(thd);
4474  break; /* break super switch */
4475  } /* end case group bracket */
4476  case SQLCOM_CALL:
4477  {
4478  sp_head *sp;
4479 
4480  /* Here we check for the execute privilege on stored procedure. */
4481  if (check_routine_access(thd, EXECUTE_ACL, lex->spname->m_db.str,
4482  lex->spname->m_name.str,
4483  lex->sql_command == SQLCOM_CALL, 0))
4484  goto error;
4485 
4486  /*
4487  This will cache all SP and SF and open and lock all tables
4488  required for execution.
4489  */
4490  if (check_table_access(thd, SELECT_ACL, all_tables, FALSE,
4491  UINT_MAX, FALSE) ||
4492  open_and_lock_tables(thd, all_tables, TRUE, 0))
4493  goto error;
4494 
4495  /*
4496  By this moment all needed SPs should be in cache so no need to look
4497  into DB.
4498  */
4499  if (!(sp= sp_find_routine(thd, SP_TYPE_PROCEDURE, lex->spname,
4500  &thd->sp_proc_cache, TRUE)))
4501  {
4502  my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PROCEDURE",
4503  lex->spname->m_qname.str);
4504  goto error;
4505  }
4506  else
4507  {
4508  ha_rows select_limit;
4509  /* bits that should be cleared in thd->server_status */
4510  uint bits_to_be_cleared= 0;
4511  /*
4512  Check that the stored procedure doesn't contain Dynamic SQL
4513  and doesn't return result sets: such stored procedures can't
4514  be called from a function or trigger.
4515  */
4516  if (thd->in_sub_stmt)
4517  {
4518  const char *where= (thd->in_sub_stmt & SUB_STMT_TRIGGER ?
4519  "trigger" : "function");
4520  if (sp->is_not_allowed_in_function(where))
4521  goto error;
4522  }
4523 
4524  if (sp->m_flags & sp_head::MULTI_RESULTS)
4525  {
4526  if (! (thd->client_capabilities & CLIENT_MULTI_RESULTS))
4527  {
4528  /*
4529  The client does not support multiple result sets being sent
4530  back
4531  */
4532  my_error(ER_SP_BADSELECT, MYF(0), sp->m_qname.str);
4533  goto error;
4534  }
4535  /*
4536  If SERVER_MORE_RESULTS_EXISTS is not set,
4537  then remember that it should be cleared
4538  */
4539  bits_to_be_cleared= (~thd->server_status &
4540  SERVER_MORE_RESULTS_EXISTS);
4541  thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
4542  }
4543 
4544  if (check_routine_access(thd, EXECUTE_ACL,
4545  sp->m_db.str, sp->m_name.str, TRUE, FALSE))
4546  {
4547  goto error;
4548  }
4549  select_limit= thd->variables.select_limit;
4550  thd->variables.select_limit= HA_POS_ERROR;
4551 
4552  /*
4553  We never write CALL statements into binlog:
4554  - If the mode is non-prelocked, each statement will be logged
4555  separately.
4556  - If the mode is prelocked, the invoking statement will care
4557  about writing into binlog.
4558  So just execute the statement.
4559  */
4560  res= sp->execute_procedure(thd, &lex->value_list);
4561 
4562  thd->variables.select_limit= select_limit;
4563 
4564  thd->server_status&= ~bits_to_be_cleared;
4565 
4566  if (!res)
4567  {
4568  my_ok(thd, (thd->get_row_count_func() < 0) ? 0 : thd->get_row_count_func());
4569  }
4570  else
4571  {
4572  DBUG_ASSERT(thd->is_error() || thd->killed);
4573  goto error; // Substatement should already have sent error
4574  }
4575  }
4576  break;
4577  }
4578  case SQLCOM_ALTER_PROCEDURE:
4579  case SQLCOM_ALTER_FUNCTION:
4580  {
4581  if (check_routine_access(thd, ALTER_PROC_ACL, lex->spname->m_db.str,
4582  lex->spname->m_name.str,
4583  lex->sql_command == SQLCOM_ALTER_PROCEDURE,
4584  false))
4585  goto error;
4586 
4587  enum_sp_type sp_type= (lex->sql_command == SQLCOM_ALTER_PROCEDURE) ?
4588  SP_TYPE_PROCEDURE : SP_TYPE_FUNCTION;
4589  /*
4590  Note that if you implement the capability of ALTER FUNCTION to
4591  alter the body of the function, this command should be made to
4592  follow the restrictions that log-bin-trust-function-creators=0
4593  already puts on CREATE FUNCTION.
4594  */
4595  /* Conditionally writes to binlog */
4596  int sp_result= sp_update_routine(thd, sp_type, lex->spname,
4597  &lex->sp_chistics);
4598  if (thd->killed)
4599  goto error;
4600  switch (sp_result)
4601  {
4602  case SP_OK:
4603  my_ok(thd);
4604  break;
4605  case SP_KEY_NOT_FOUND:
4606  my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
4607  SP_COM_STRING(lex), lex->spname->m_qname.str);
4608  goto error;
4609  default:
4610  my_error(ER_SP_CANT_ALTER, MYF(0),
4611  SP_COM_STRING(lex), lex->spname->m_qname.str);
4612  goto error;
4613  }
4614  break;
4615  }
4616  case SQLCOM_DROP_PROCEDURE:
4617  case SQLCOM_DROP_FUNCTION:
4618  {
4619 #ifdef HAVE_DLOPEN
4620  if (lex->sql_command == SQLCOM_DROP_FUNCTION &&
4621  ! lex->spname->m_explicit_name)
4622  {
4623  /* DROP FUNCTION <non qualified name> */
4624  udf_func *udf = find_udf(lex->spname->m_name.str,
4625  lex->spname->m_name.length);
4626  if (udf)
4627  {
4628  if (check_access(thd, DELETE_ACL, "mysql", NULL, NULL, 1, 0))
4629  goto error;
4630 
4631  if (!(res = mysql_drop_function(thd, &lex->spname->m_name)))
4632  {
4633  my_ok(thd);
4634  break;
4635  }
4636  my_error(ER_SP_DROP_FAILED, MYF(0),
4637  "FUNCTION (UDF)", lex->spname->m_name.str);
4638  goto error;
4639  }
4640 
4641  if (lex->spname->m_db.str == NULL)
4642  {
4643  if (lex->drop_if_exists)
4644  {
4645  push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
4646  ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST),
4647  "FUNCTION (UDF)", lex->spname->m_name.str);
4648  res= FALSE;
4649  my_ok(thd);
4650  break;
4651  }
4652  my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
4653  "FUNCTION (UDF)", lex->spname->m_name.str);
4654  goto error;
4655  }
4656  /* Fall thought to test for a stored function */
4657  }
4658 #endif
4659 
4660  char *db= lex->spname->m_db.str;
4661  char *name= lex->spname->m_name.str;
4662 
4663  if (check_routine_access(thd, ALTER_PROC_ACL, db, name,
4664  lex->sql_command == SQLCOM_DROP_PROCEDURE,
4665  false))
4666  goto error;
4667 
4668  enum_sp_type sp_type= (lex->sql_command == SQLCOM_DROP_PROCEDURE) ?
4669  SP_TYPE_PROCEDURE : SP_TYPE_FUNCTION;
4670 
4671  /* Conditionally writes to binlog */
4672  int sp_result= sp_drop_routine(thd, sp_type, lex->spname);
4673 
4674 #ifndef NO_EMBEDDED_ACCESS_CHECKS
4675  /*
4676  We're going to issue an implicit REVOKE statement so we close all
4677  open tables. We have to keep metadata locks as this ensures that
4678  this statement is atomic against concurent FLUSH TABLES WITH READ
4679  LOCK. Deadlocks which can arise due to fact that this implicit
4680  statement takes metadata locks should be detected by a deadlock
4681  detector in MDL subsystem and reported as errors.
4682 
4683  No need to commit/rollback statement transaction, it's not started.
4684 
4685  TODO: Long-term we should either ensure that implicit REVOKE statement
4686  is written into binary log as a separate statement or make both
4687  dropping of routine and implicit REVOKE parts of one fully atomic
4688  statement.
4689  */
4690  DBUG_ASSERT(thd->transaction.stmt.is_empty());
4691  close_thread_tables(thd);
4692 
4693  if (sp_result != SP_KEY_NOT_FOUND &&
4694  sp_automatic_privileges && !opt_noacl &&
4695  sp_revoke_privileges(thd, db, name,
4696  lex->sql_command == SQLCOM_DROP_PROCEDURE))
4697  {
4698  push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
4699  ER_PROC_AUTO_REVOKE_FAIL,
4700  ER(ER_PROC_AUTO_REVOKE_FAIL));
4701  /* If this happens, an error should have been reported. */
4702  goto error;
4703  }
4704 #endif
4705 
4706  res= sp_result;
4707  switch (sp_result) {
4708  case SP_OK:
4709  my_ok(thd);
4710  break;
4711  case SP_KEY_NOT_FOUND:
4712  if (lex->drop_if_exists)
4713  {
4714  res= write_bin_log(thd, TRUE, thd->query(), thd->query_length());
4715  push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
4716  ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST),
4717  SP_COM_STRING(lex), lex->spname->m_qname.str);
4718  if (!res)
4719  my_ok(thd);
4720  break;
4721  }
4722  my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
4723  SP_COM_STRING(lex), lex->spname->m_qname.str);
4724  goto error;
4725  default:
4726  my_error(ER_SP_DROP_FAILED, MYF(0),
4727  SP_COM_STRING(lex), lex->spname->m_qname.str);
4728  goto error;
4729  }
4730  break;
4731  }
4732  case SQLCOM_SHOW_CREATE_PROC:
4733  {
4734  if (sp_show_create_routine(thd, SP_TYPE_PROCEDURE, lex->spname))
4735  goto error;
4736  break;
4737  }
4738  case SQLCOM_SHOW_CREATE_FUNC:
4739  {
4740  if (sp_show_create_routine(thd, SP_TYPE_FUNCTION, lex->spname))
4741  goto error;
4742  break;
4743  }
4744  case SQLCOM_SHOW_PROC_CODE:
4745  case SQLCOM_SHOW_FUNC_CODE:
4746  {
4747 #ifndef DBUG_OFF
4748  sp_head *sp;
4749  enum_sp_type sp_type= (lex->sql_command == SQLCOM_SHOW_PROC_CODE) ?
4750  SP_TYPE_PROCEDURE : SP_TYPE_FUNCTION;
4751 
4752  if (sp_cache_routine(thd, sp_type, lex->spname, false, &sp))
4753  goto error;
4754  if (!sp || sp->show_routine_code(thd))
4755  {
4756  /* We don't distinguish between errors for now */
4757  my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
4758  SP_COM_STRING(lex), lex->spname->m_name.str);
4759  goto error;
4760  }
4761  break;
4762 #else
4763  my_error(ER_FEATURE_DISABLED, MYF(0),
4764  "SHOW PROCEDURE|FUNCTION CODE", "--with-debug");
4765  goto error;
4766 #endif // ifndef DBUG_OFF
4767  }
4768  case SQLCOM_SHOW_CREATE_TRIGGER:
4769  {
4770  if (lex->spname->m_name.length > NAME_LEN)
4771  {
4772  my_error(ER_TOO_LONG_IDENT, MYF(0), lex->spname->m_name.str);
4773  goto error;
4774  }
4775 
4776  if (show_create_trigger(thd, lex->spname))
4777  goto error; /* Error has been already logged. */
4778 
4779  break;
4780  }
4781  case SQLCOM_CREATE_VIEW:
4782  {
4783  /*
4784  Note: SQLCOM_CREATE_VIEW also handles 'ALTER VIEW' commands
4785  as specified through the thd->lex->create_view_mode flag.
4786  */
4787  res= mysql_create_view(thd, first_table, thd->lex->create_view_mode);
4788  break;
4789  }
4790  case SQLCOM_DROP_VIEW:
4791  {
4792  if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE))
4793  goto error;
4794  /* Conditionally writes to binlog. */
4795  res= mysql_drop_view(thd, first_table, thd->lex->drop_mode);
4796  break;
4797  }
4798  case SQLCOM_CREATE_TRIGGER:
4799  {
4800  /* Conditionally writes to binlog. */
4801  res= mysql_create_or_drop_trigger(thd, all_tables, 1);
4802 
4803  break;
4804  }
4805  case SQLCOM_DROP_TRIGGER:
4806  {
4807  /* Conditionally writes to binlog. */
4808  res= mysql_create_or_drop_trigger(thd, all_tables, 0);
4809  break;
4810  }
4811  case SQLCOM_XA_START:
4812  if (trans_xa_start(thd))
4813  goto error;
4814  my_ok(thd);
4815  break;
4816  case SQLCOM_XA_END:
4817  if (trans_xa_end(thd))
4818  goto error;
4819  my_ok(thd);
4820  break;
4821  case SQLCOM_XA_PREPARE:
4822  if (trans_xa_prepare(thd))
4823  goto error;
4824  my_ok(thd);
4825  break;
4826  case SQLCOM_XA_COMMIT:
4827  if (trans_xa_commit(thd))
4828  goto error;
4829  thd->mdl_context.release_transactional_locks();
4830  /*
4831  We've just done a commit, reset transaction
4832  isolation level and access mode to the session default.
4833  */
4834  thd->tx_isolation= (enum_tx_isolation) thd->variables.tx_isolation;
4835  thd->tx_read_only= thd->variables.tx_read_only;
4836  my_ok(thd);
4837  break;
4838  case SQLCOM_XA_ROLLBACK:
4839  if (trans_xa_rollback(thd))
4840  goto error;
4841  thd->mdl_context.release_transactional_locks();
4842  /*
4843  We've just done a rollback, reset transaction
4844  isolation level and access mode to the session default.
4845  */
4846  thd->tx_isolation= (enum_tx_isolation) thd->variables.tx_isolation;
4847  thd->tx_read_only= thd->variables.tx_read_only;
4848  my_ok(thd);
4849  break;
4850  case SQLCOM_XA_RECOVER:
4851  res= mysql_xa_recover(thd);
4852  break;
4853  case SQLCOM_ALTER_TABLESPACE:
4854  if (check_global_access(thd, CREATE_TABLESPACE_ACL))
4855  break;
4856  if (!(res= mysql_alter_tablespace(thd, lex->alter_tablespace_info)))
4857  my_ok(thd);
4858  break;
4859  case SQLCOM_INSTALL_PLUGIN:
4860  if (! (res= mysql_install_plugin(thd, &thd->lex->comment,
4861  &thd->lex->ident)))
4862  my_ok(thd);
4863  break;
4864  case SQLCOM_UNINSTALL_PLUGIN:
4865  if (! (res= mysql_uninstall_plugin(thd, &thd->lex->comment)))
4866  my_ok(thd);
4867  break;
4868  case SQLCOM_BINLOG_BASE64_EVENT:
4869  {
4870 #ifndef EMBEDDED_LIBRARY
4871  mysql_client_binlog_statement(thd);
4872 #else /* EMBEDDED_LIBRARY */
4873  my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "embedded");
4874 #endif /* EMBEDDED_LIBRARY */
4875  break;
4876  }
4877  case SQLCOM_CREATE_SERVER:
4878  {
4879  if (check_global_access(thd, SUPER_ACL))
4880  goto error;
4881 
4882  if (create_server(thd, &thd->lex->server_options))
4883  goto error;
4884 
4885  my_ok(thd, 1);
4886  break;
4887  }
4888  case SQLCOM_ALTER_SERVER:
4889  {
4890  if (check_global_access(thd, SUPER_ACL))
4891  goto error;
4892 
4893  if (alter_server(thd, &thd->lex->server_options))
4894  goto error;
4895 
4896  my_ok(thd, 1);
4897  break;
4898  }
4899  case SQLCOM_DROP_SERVER:
4900  {
4901  if (check_global_access(thd, SUPER_ACL))
4902  goto error;
4903 
4904  LEX *lex= thd->lex;
4905  if (drop_server(thd, &lex->server_options, lex->drop_if_exists))
4906  {
4907  /*
4908  drop_server() can fail without reporting an error
4909  due to IF EXISTS clause. In this case, call my_ok().
4910  */
4911  if (thd->is_error() || thd->killed)
4912  goto error;
4913  DBUG_ASSERT(lex->drop_if_exists);
4914  my_ok(thd, 0);
4915  break;
4916  }
4917 
4918  my_ok(thd, 1);
4919  break;
4920  }
4921  case SQLCOM_ANALYZE:
4922  case SQLCOM_CHECK:
4923  case SQLCOM_OPTIMIZE:
4924  case SQLCOM_REPAIR:
4925  case SQLCOM_TRUNCATE:
4926  case SQLCOM_ALTER_TABLE:
4927  case SQLCOM_HA_OPEN:
4928  case SQLCOM_HA_READ:
4929  case SQLCOM_HA_CLOSE:
4930  DBUG_ASSERT(first_table == all_tables && first_table != 0);
4931  /* fall through */
4932  case SQLCOM_SIGNAL:
4933  case SQLCOM_RESIGNAL:
4934  case SQLCOM_GET_DIAGNOSTICS:
4935  DBUG_ASSERT(lex->m_sql_cmd != NULL);
4936  res= lex->m_sql_cmd->execute(thd);
4937  break;
4938 
4939 #ifndef NO_EMBEDDED_ACCESS_CHECKS
4940  case SQLCOM_ALTER_USER:
4941  if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) &&
4942  check_global_access(thd, CREATE_USER_ACL))
4943  break;
4944  /* Conditionally writes to binlog */
4945  if (!(res= mysql_user_password_expire(thd, lex->users_list)))
4946  my_ok(thd);
4947  break;
4948 #endif
4949  default:
4950 #ifndef EMBEDDED_LIBRARY
4951  DBUG_ASSERT(0); /* Impossible */
4952 #endif
4953  my_ok(thd);
4954  break;
4955  }
4956  THD_STAGE_INFO(thd, stage_query_end);
4957 
4958  /*
4959  Binlog-related cleanup:
4960  Reset system variables temporarily modified by SET ONE SHOT.
4961 
4962  Exception: If this is a SET, do nothing. This is to allow
4963  mysqlbinlog to print many SET commands (in this case we want the
4964  charset temp setting to live until the real query). This is also
4965  needed so that SET CHARACTER_SET_CLIENT... does not cancel itself
4966  immediately.
4967  */
4968  if (thd->one_shot_set && lex->sql_command != SQLCOM_SET_OPTION)
4969  reset_one_shot_variables(thd);
4970 
4971  goto finish;
4972 
4973 error:
4974  res= TRUE;
4975 
4976 finish:
4977 
4978  DBUG_ASSERT(!thd->in_active_multi_stmt_transaction() ||
4979  thd->in_multi_stmt_transaction_mode());
4980 
4981  if (! thd->in_sub_stmt)
4982  {
4983  /* report error issued during command execution */
4984  if (thd->killed_errno())
4985  thd->send_kill_message();
4986  if (thd->killed == THD::KILL_QUERY || thd->killed == THD::KILL_BAD_DATA)
4987  {
4988  thd->killed= THD::NOT_KILLED;
4989  thd->mysys_var->abort= 0;
4990  }
4991  if (thd->is_error() || (thd->variables.option_bits & OPTION_MASTER_SQL_ERROR))
4992  trans_rollback_stmt(thd);
4993  else
4994  {
4995  /* If commit fails, we should be able to reset the OK status. */
4996  thd->get_stmt_da()->set_overwrite_status(true);
4997  trans_commit_stmt(thd);
4998  thd->get_stmt_da()->set_overwrite_status(false);
4999  }
5000  }
5001 
5002  lex->unit.cleanup();
5003  /* Free tables */
5004  THD_STAGE_INFO(thd, stage_closing_tables);
5005  close_thread_tables(thd);
5006 
5007 #ifndef DBUG_OFF
5008  if (lex->sql_command != SQLCOM_SET_OPTION && ! thd->in_sub_stmt)
5009  DEBUG_SYNC(thd, "execute_command_after_close_tables");
5010 #endif
5011 
5012  if (! thd->in_sub_stmt && thd->transaction_rollback_request)
5013  {
5014  /*
5015  We are not in sub-statement and transaction rollback was requested by
5016  one of storage engines (e.g. due to deadlock). Rollback transaction in
5017  all storage engines including binary log.
5018  */
5019  trans_rollback_implicit(thd);
5020  thd->mdl_context.release_transactional_locks();
5021  }
5022  else if (stmt_causes_implicit_commit(thd, CF_IMPLICIT_COMMIT_END))
5023  {
5024  /* No transaction control allowed in sub-statements. */
5025  DBUG_ASSERT(! thd->in_sub_stmt);
5026  /* If commit fails, we should be able to reset the OK status. */
5027  thd->get_stmt_da()->set_overwrite_status(true);
5028  /* Commit the normal transaction if one is active. */
5029  trans_commit_implicit(thd);
5030  thd->get_stmt_da()->set_overwrite_status(false);
5031  thd->mdl_context.release_transactional_locks();
5032  }
5033  else if (! thd->in_sub_stmt && ! thd->in_multi_stmt_transaction_mode())
5034  {
5035  /*
5036  - If inside a multi-statement transaction,
5037  defer the release of metadata locks until the current
5038  transaction is either committed or rolled back. This prevents
5039  other statements from modifying the table for the entire
5040  duration of this transaction. This provides commit ordering
5041  and guarantees serializability across multiple transactions.
5042  - If in autocommit mode, or outside a transactional context,
5043  automatically release metadata locks of the current statement.
5044  */
5045  thd->mdl_context.release_transactional_locks();
5046  }
5047  else if (! thd->in_sub_stmt)
5048  {
5049  thd->mdl_context.release_statement_locks();
5050  }
5051 
5052  DBUG_RETURN(res || thd->is_error());
5053 }
5054 
5055 static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables)
5056 {
5057  LEX *lex= thd->lex;
5058  select_result *result= lex->result;
5059  bool res;
5060  /* assign global limit variable if limit is not given */
5061  {
5062  SELECT_LEX *param= lex->unit.global_parameters;
5063  if (!param->explicit_limit)
5064  param->select_limit=
5065  new Item_int((ulonglong) thd->variables.select_limit);
5066  }
5067  if (!(res= open_normal_and_derived_tables(thd, all_tables, 0)))
5068  {
5069  if (lex->describe)
5070  {
5071  /*
5072  We always use select_send for EXPLAIN, even if it's an EXPLAIN
5073  for SELECT ... INTO OUTFILE: a user application should be able
5074  to prepend EXPLAIN to any query and receive output for it,
5075  even if the query itself redirects the output.
5076  */
5077  if (!(result= new select_send()))
5078  return 1; /* purecov: inspected */
5079  res= explain_query_expression(thd, result);
5080  delete result;
5081  }
5082  else
5083  {
5084  if (!result && !(result= new select_send()))
5085  return 1; /* purecov: inspected */
5086  select_result *save_result= result;
5087  select_result *analyse_result= NULL;
5088  if (lex->proc_analyse)
5089  {
5090  if ((result= analyse_result=
5091  new select_analyse(result, lex->proc_analyse)) == NULL)
5092  return true;
5093  }
5094  res= handle_select(thd, result, 0);
5095  delete analyse_result;
5096  if (save_result != lex->result)
5097  delete save_result;
5098  }
5099  }
5100  return res;
5101 }
5102 
5103 
5104 #ifndef NO_EMBEDDED_ACCESS_CHECKS
5105 
5120 bool check_single_table_access(THD *thd, ulong privilege,
5121  TABLE_LIST *all_tables, bool no_errors)
5122 {
5123  Security_context * backup_ctx= thd->security_ctx;
5124 
5125  /* we need to switch to the saved context (if any) */
5126  if (all_tables->security_ctx)
5127  thd->security_ctx= all_tables->security_ctx;
5128 
5129  const char *db_name;
5130  if ((all_tables->view || all_tables->field_translation) &&
5131  !all_tables->schema_table)
5132  db_name= all_tables->view_db.str;
5133  else
5134  db_name= all_tables->db;
5135 
5136  if (check_access(thd, privilege, db_name,
5137  &all_tables->grant.privilege,
5138  &all_tables->grant.m_internal,
5139  0, no_errors))
5140  goto deny;
5141 
5142  /* Show only 1 table for check_grant */
5143  if (!(all_tables->belong_to_view &&
5144  (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) &&
5145  check_grant(thd, privilege, all_tables, FALSE, 1, no_errors))
5146  goto deny;
5147 
5148  thd->security_ctx= backup_ctx;
5149  return 0;
5150 
5151 deny:
5152  thd->security_ctx= backup_ctx;
5153  return 1;
5154 }
5155 
5170 bool check_one_table_access(THD *thd, ulong privilege, TABLE_LIST *all_tables)
5171 {
5172  if (check_single_table_access (thd,privilege,all_tables, FALSE))
5173  return 1;
5174 
5175  /* Check rights on tables of subselects and implicitly opened tables */
5176  TABLE_LIST *subselects_tables, *view= all_tables->view ? all_tables : 0;
5177  if ((subselects_tables= all_tables->next_global))
5178  {
5179  /*
5180  Access rights asked for the first table of a view should be the same
5181  as for the view
5182  */
5183  if (view && subselects_tables->belong_to_view == view)
5184  {
5185  if (check_single_table_access (thd, privilege, subselects_tables, FALSE))
5186  return 1;
5187  subselects_tables= subselects_tables->next_global;
5188  }
5189  if (subselects_tables &&
5190  (check_table_access(thd, SELECT_ACL, subselects_tables, FALSE,
5191  UINT_MAX, FALSE)))
5192  return 1;
5193  }
5194  return 0;
5195 }
5196 
5197 
5225 bool
5226 check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv,
5227  GRANT_INTERNAL_INFO *grant_internal_info,
5228  bool dont_check_global_grants, bool no_errors)
5229 {
5230  Security_context *sctx= thd->security_ctx;
5231  ulong db_access;
5232 
5233  /*
5234  GRANT command:
5235  In case of database level grant the database name may be a pattern,
5236  in case of table|column level grant the database name can not be a pattern.
5237  We use 'dont_check_global_grants' as a flag to determine
5238  if it's database level grant command
5239  (see SQLCOM_GRANT case, mysql_execute_command() function) and
5240  set db_is_pattern according to 'dont_check_global_grants' value.
5241  */
5242  bool db_is_pattern= ((want_access & GRANT_ACL) && dont_check_global_grants);
5243  ulong dummy;
5244  DBUG_ENTER("check_access");
5245  DBUG_PRINT("enter",("db: %s want_access: %lu master_access: %lu",
5246  db ? db : "", want_access, sctx->master_access));
5247 
5248  if (save_priv)
5249  *save_priv=0;
5250  else
5251  {
5252  save_priv= &dummy;
5253  dummy= 0;
5254  }
5255 
5256  THD_STAGE_INFO(thd, stage_checking_permissions);
5257  if ((!db || !db[0]) && !thd->db && !dont_check_global_grants)
5258  {
5259  DBUG_PRINT("error",("No database"));
5260  if (!no_errors)
5261  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR),
5262  MYF(0)); /* purecov: tested */
5263  DBUG_RETURN(TRUE); /* purecov: tested */
5264  }
5265 
5266  if ((db != NULL) && (db != any_db))
5267  {
5268  const ACL_internal_schema_access *access;
5269  access= get_cached_schema_access(grant_internal_info, db);
5270  if (access)
5271  {
5272  switch (access->check(want_access, save_priv))
5273  {
5274  case ACL_INTERNAL_ACCESS_GRANTED:
5275  /*
5276  All the privileges requested have been granted internally.
5277  [out] *save_privileges= Internal privileges.
5278  */
5279  DBUG_RETURN(FALSE);
5280  case ACL_INTERNAL_ACCESS_DENIED:
5281  if (! no_errors)
5282  {
5283  my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
5284  sctx->priv_user, sctx->priv_host, db);
5285  }
5286  DBUG_RETURN(TRUE);
5287  case ACL_INTERNAL_ACCESS_CHECK_GRANT:
5288  /*
5289  Only some of the privilege requested have been granted internally,
5290  proceed with the remaining bits of the request (want_access).
5291  */
5292  want_access&= ~(*save_priv);
5293  break;
5294  }
5295  }
5296  }
5297 
5298  if ((sctx->master_access & want_access) == want_access)
5299  {
5300  /*
5301  1. If we don't have a global SELECT privilege, we have to get the
5302  database specific access rights to be able to handle queries of type
5303  UPDATE t1 SET a=1 WHERE b > 0
5304  2. Change db access if it isn't current db which is being addressed
5305  */
5306  if (!(sctx->master_access & SELECT_ACL))
5307  {
5308  if (db && (!thd->db || db_is_pattern || strcmp(db, thd->db)))
5309  db_access= acl_get(sctx->get_host()->ptr(), sctx->get_ip()->ptr(),
5310  sctx->priv_user, db, db_is_pattern);
5311  else
5312  {
5313  /* get access for current db */
5314  db_access= sctx->db_access;
5315  }
5316  /*
5317  The effective privileges are the union of the global privileges
5318  and the intersection of db- and host-privileges,
5319  plus the internal privileges.
5320  */
5321  *save_priv|= sctx->master_access | db_access;
5322  }
5323  else
5324  *save_priv|= sctx->master_access;
5325  DBUG_RETURN(FALSE);
5326  }
5327  if (((want_access & ~sctx->master_access) & ~DB_ACLS) ||
5328  (! db && dont_check_global_grants))
5329  { // We can never grant this
5330  DBUG_PRINT("error",("No possible access"));
5331  if (!no_errors)
5332  {
5333  if (thd->password == 2)
5334  my_error(ER_ACCESS_DENIED_NO_PASSWORD_ERROR, MYF(0),
5335  sctx->priv_user,
5336  sctx->priv_host);
5337  else
5338  my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
5339  sctx->priv_user,
5340  sctx->priv_host,
5341  (thd->password ?
5342  ER(ER_YES) :
5343  ER(ER_NO))); /* purecov: tested */
5344  }
5345  DBUG_RETURN(TRUE); /* purecov: tested */
5346  }
5347 
5348  if (db == any_db)
5349  {
5350  /*
5351  Access granted; Allow select on *any* db.
5352  [out] *save_privileges= 0
5353  */
5354  DBUG_RETURN(FALSE);
5355  }
5356 
5357  if (db && (!thd->db || db_is_pattern || strcmp(db,thd->db)))
5358  db_access= acl_get(sctx->get_host()->ptr(), sctx->get_ip()->ptr(),
5359  sctx->priv_user, db, db_is_pattern);
5360  else
5361  db_access= sctx->db_access;
5362  DBUG_PRINT("info",("db_access: %lu want_access: %lu",
5363  db_access, want_access));
5364 
5365  /*
5366  Save the union of User-table and the intersection between Db-table and
5367  Host-table privileges, with the already saved internal privileges.
5368  */
5369  db_access= (db_access | sctx->master_access);
5370  *save_priv|= db_access;
5371 
5372  /*
5373  We need to investigate column- and table access if all requested privileges
5374  belongs to the bit set of .
5375  */
5376  bool need_table_or_column_check=
5377  (want_access & (TABLE_ACLS | PROC_ACLS | db_access)) == want_access;
5378 
5379  /*
5380  Grant access if the requested access is in the intersection of
5381  host- and db-privileges (as retrieved from the acl cache),
5382  also grant access if all the requested privileges are in the union of
5383  TABLES_ACLS and PROC_ACLS; see check_grant.
5384  */
5385  if ( (db_access & want_access) == want_access ||
5386  (!dont_check_global_grants &&
5387  need_table_or_column_check))
5388  {
5389  /*
5390  Ok; but need to check table- and column privileges.
5391  [out] *save_privileges is (User-priv | (Db-priv & Host-priv) | Internal-priv)
5392  */
5393  DBUG_RETURN(FALSE);
5394  }
5395 
5396  /*
5397  Access is denied;
5398  [out] *save_privileges is (User-priv | (Db-priv & Host-priv) | Internal-priv)
5399  */
5400  DBUG_PRINT("error",("Access denied"));
5401  if (!no_errors)
5402  my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
5403  sctx->priv_user, sctx->priv_host,
5404  (db ? db : (thd->db ?
5405  thd->db :
5406  "unknown")));
5407  DBUG_RETURN(TRUE);
5408 
5409 }
5410 
5411 
5423 static bool check_show_access(THD *thd, TABLE_LIST *table)
5424 {
5425  switch (get_schema_table_idx(table->schema_table)) {
5426  case SCH_SCHEMATA:
5427  return (specialflag & SPECIAL_SKIP_SHOW_DB) &&
5428  check_global_access(thd, SHOW_DB_ACL);
5429 
5430  case SCH_TABLE_NAMES:
5431  case SCH_TABLES:
5432  case SCH_VIEWS:
5433  case SCH_TRIGGERS:
5434  case SCH_EVENTS:
5435  {
5436  const char *dst_db_name= table->schema_select_lex->db;
5437 
5438  DBUG_ASSERT(dst_db_name);
5439 
5440  if (check_access(thd, SELECT_ACL, dst_db_name,
5441  &thd->col_access, NULL, FALSE, FALSE))
5442  return TRUE;
5443 
5444  if (!thd->col_access && check_grant_db(thd, dst_db_name))
5445  {
5446  my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
5447  thd->security_ctx->priv_user,
5448  thd->security_ctx->priv_host,
5449  dst_db_name);
5450  return TRUE;
5451  }
5452 
5453  return FALSE;
5454  }
5455 
5456  case SCH_COLUMNS:
5457  case SCH_STATISTICS:
5458  {
5459  TABLE_LIST *dst_table;
5460  dst_table= table->schema_select_lex->table_list.first;
5461 
5462  DBUG_ASSERT(dst_table);
5463 
5464  /*
5465  Open temporary tables to be able to detect them during privilege check.
5466  */
5467  if (open_temporary_tables(thd, dst_table))
5468  return TRUE;
5469 
5470  if (check_access(thd, SELECT_ACL, dst_table->db,
5471  &dst_table->grant.privilege,
5472  &dst_table->grant.m_internal,
5473  FALSE, FALSE))
5474  return TRUE; /* Access denied */
5475 
5476  /*
5477  Check_grant will grant access if there is any column privileges on
5478  all of the tables thanks to the fourth parameter (bool show_table).
5479  */
5480  if (check_grant(thd, SELECT_ACL, dst_table, TRUE, UINT_MAX, FALSE))
5481  return TRUE; /* Access denied */
5482 
5483  close_thread_tables(thd);
5484  dst_table->table= NULL;
5485 
5486  /* Access granted */
5487  return FALSE;
5488  }
5489  default:
5490  break;
5491  }
5492 
5493  return FALSE;
5494 }
5495 
5496 
5497 
5533 bool
5534 check_table_access(THD *thd, ulong requirements,TABLE_LIST *tables,
5535  bool any_combination_of_privileges_will_do,
5536  uint number, bool no_errors)
5537 {
5538  TABLE_LIST *org_tables= tables;
5539  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
5540  uint i= 0;
5541  Security_context *sctx= thd->security_ctx, *backup_ctx= thd->security_ctx;
5542  /*
5543  The check that first_not_own_table is not reached is for the case when
5544  the given table list refers to the list for prelocking (contains tables
5545  of other queries). For simple queries first_not_own_table is 0.
5546  */
5547  for (; i < number && tables != first_not_own_table && tables;
5548  tables= tables->next_global, i++)
5549  {
5550  ulong want_access= requirements;
5551  if (tables->security_ctx)
5552  sctx= tables->security_ctx;
5553  else
5554  sctx= backup_ctx;
5555 
5556  /*
5557  Register access for view underlying table.
5558  Remove SHOW_VIEW_ACL, because it will be checked during making view
5559  */
5560  tables->grant.orig_want_privilege= (want_access & ~SHOW_VIEW_ACL);
5561 
5562  /*
5563  We should not encounter table list elements for reformed SHOW
5564  statements unless this is first table list element in the main
5565  select.
5566  Such table list elements require additional privilege check
5567  (see check_show_access()). This check is carried out by caller,
5568  but only for the first table list element from the main select.
5569  */
5570  DBUG_ASSERT(!tables->schema_table_reformed ||
5571  tables == thd->lex->select_lex.table_list.first);
5572 
5573  DBUG_PRINT("info", ("derived: %d view: %d", tables->derived != 0,
5574  tables->view != 0));
5575 
5576  if (tables->is_anonymous_derived_table())
5577  continue;
5578 
5579  thd->security_ctx= sctx;
5580 
5581  if (check_access(thd, want_access, tables->get_db_name(),
5582  &tables->grant.privilege,
5583  &tables->grant.m_internal,
5584  0, no_errors))
5585  goto deny;
5586  }
5587  thd->security_ctx= backup_ctx;
5588  return check_grant(thd,requirements,org_tables,
5589  any_combination_of_privileges_will_do,
5590  number, no_errors);
5591 deny:
5592  thd->security_ctx= backup_ctx;
5593  return TRUE;
5594 }
5595 
5596 
5597 bool
5598 check_routine_access(THD *thd, ulong want_access,char *db, char *name,
5599  bool is_proc, bool no_errors)
5600 {
5601  TABLE_LIST tables[1];
5602 
5603  memset(tables, 0, sizeof(TABLE_LIST));
5604  tables->db= db;
5605  tables->table_name= tables->alias= name;
5606 
5607  /*
5608  The following test is just a shortcut for check_access() (to avoid
5609  calculating db_access) under the assumption that it's common to
5610  give persons global right to execute all stored SP (but not
5611  necessary to create them).
5612  Note that this effectively bypasses the ACL_internal_schema_access checks
5613  that are implemented for the INFORMATION_SCHEMA and PERFORMANCE_SCHEMA,
5614  which are located in check_access().
5615  Since the I_S and P_S do not contain routines, this bypass is ok,
5616  as long as this code path is not abused to create routines.
5617  The assert enforce that.
5618  */
5619  DBUG_ASSERT((want_access & CREATE_PROC_ACL) == 0);
5620  if ((thd->security_ctx->master_access & want_access) == want_access)
5621  tables->grant.privilege= want_access;
5622  else if (check_access(thd, want_access, db,
5623  &tables->grant.privilege,
5624  &tables->grant.m_internal,
5625  0, no_errors))
5626  return TRUE;
5627 
5628  return check_grant_routine(thd, want_access, tables, is_proc, no_errors);
5629 }
5630 
5631 
5645 bool check_some_routine_access(THD *thd, const char *db, const char *name,
5646  bool is_proc)
5647 {
5648  ulong save_priv;
5649  /*
5650  The following test is just a shortcut for check_access() (to avoid
5651  calculating db_access)
5652  Note that this effectively bypasses the ACL_internal_schema_access checks
5653  that are implemented for the INFORMATION_SCHEMA and PERFORMANCE_SCHEMA,
5654  which are located in check_access().
5655  Since the I_S and P_S do not contain routines, this bypass is ok,
5656  as it only opens SHOW_PROC_ACLS.
5657  */
5658  if (thd->security_ctx->master_access & SHOW_PROC_ACLS)
5659  return FALSE;
5660  if (!check_access(thd, SHOW_PROC_ACLS, db, &save_priv, NULL, 0, 1) ||
5661  (save_priv & SHOW_PROC_ACLS))
5662  return FALSE;
5663  return check_routine_level_acl(thd, db, name, is_proc);
5664 }
5665 
5666 
5679 bool check_some_access(THD *thd, ulong want_access, TABLE_LIST *table)
5680 {
5681  ulong access;
5682  DBUG_ENTER("check_some_access");
5683 
5684  /* This loop will work as long as we have less than 32 privileges */
5685  for (access= 1; access < want_access ; access<<= 1)
5686  {
5687  if (access & want_access)
5688  {
5689  if (!check_access(thd, access, table->db,
5690  &table->grant.privilege,
5691  &table->grant.m_internal,
5692  0, 1) &&
5693  !check_grant(thd, access, table, FALSE, 1, TRUE))
5694  DBUG_RETURN(0);
5695  }
5696  }
5697  DBUG_PRINT("exit",("no matching access rights"));
5698  DBUG_RETURN(1);
5699 }
5700 
5701 #else
5702 
5703 static bool check_show_access(THD *thd, TABLE_LIST *table)
5704 {
5705  return false;
5706 }
5707 
5708 #endif /*NO_EMBEDDED_ACCESS_CHECKS*/
5709 
5710 
5729 bool check_global_access(THD *thd, ulong want_access)
5730 {
5731  DBUG_ENTER("check_global_access");
5732 #ifndef NO_EMBEDDED_ACCESS_CHECKS
5733  char command[128];
5734  if ((thd->security_ctx->master_access & want_access))
5735  DBUG_RETURN(0);
5736  get_privilege_desc(command, sizeof(command), want_access);
5737  my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), command);
5738  DBUG_RETURN(1);
5739 #else
5740  DBUG_RETURN(0);
5741 #endif
5742 }
5743 
5744 /****************************************************************************
5745  Check stack size; Send error if there isn't enough stack to continue
5746 ****************************************************************************/
5747 
5748 
5749 #if STACK_DIRECTION < 0
5750 #define used_stack(A,B) (long) (A - B)
5751 #else
5752 #define used_stack(A,B) (long) (B - A)
5753 #endif
5754 
5755 #ifndef DBUG_OFF
5756 long max_stack_used;
5757 #endif
5758 
5766 bool check_stack_overrun(THD *thd, long margin,
5767  uchar *buf __attribute__((unused)))
5768 {
5769  long stack_used;
5770  DBUG_ASSERT(thd == current_thd);
5771  if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >=
5772  (long) (my_thread_stack_size - margin))
5773  {
5774  /*
5775  Do not use stack for the message buffer to ensure correct
5776  behaviour in cases we have close to no stack left.
5777  */
5778  char* ebuff= new (std::nothrow) char[MYSQL_ERRMSG_SIZE];
5779  if (ebuff) {
5780  my_snprintf(ebuff, MYSQL_ERRMSG_SIZE, ER(ER_STACK_OVERRUN_NEED_MORE),
5781  stack_used, my_thread_stack_size, margin);
5782  my_message(ER_STACK_OVERRUN_NEED_MORE, ebuff, MYF(ME_FATALERROR));
5783  delete [] ebuff;
5784  }
5785  return 1;
5786  }
5787 #ifndef DBUG_OFF
5788  max_stack_used= max(max_stack_used, stack_used);
5789 #endif
5790  return 0;
5791 }
5792 
5793 
5794 #define MY_YACC_INIT 1000 // Start with big alloc
5795 #define MY_YACC_MAX 32000 // Because of 'short'
5796 
5797 bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
5798 {
5799  Yacc_state *state= & current_thd->m_parser_state->m_yacc;
5800  ulong old_info=0;
5801  DBUG_ASSERT(state);
5802  if ((uint) *yystacksize >= MY_YACC_MAX)
5803  return 1;
5804  if (!state->yacc_yyvs)
5805  old_info= *yystacksize;
5806  *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
5807  if (!(state->yacc_yyvs= (uchar*)
5808  my_realloc(state->yacc_yyvs,
5809  *yystacksize*sizeof(**yyvs),
5810  MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
5811  !(state->yacc_yyss= (uchar*)
5812  my_realloc(state->yacc_yyss,
5813  *yystacksize*sizeof(**yyss),
5814  MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
5815  return 1;
5816  if (old_info)
5817  {
5818  /*
5819  Only copy the old stack on the first call to my_yyoverflow(),
5820  when replacing a static stack (YYINITDEPTH) by a dynamic stack.
5821  For subsequent calls, my_realloc already did preserve the old stack.
5822  */
5823  memcpy(state->yacc_yyss, *yyss, old_info*sizeof(**yyss));
5824  memcpy(state->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs));
5825  }
5826  *yyss= (short*) state->yacc_yyss;
5827  *yyvs= (YYSTYPE*) state->yacc_yyvs;
5828  return 0;
5829 }
5830 
5831 
5846 {
5847  thd->reset_for_next_command();
5848 }
5849 
5850 void THD::reset_for_next_command()
5851 {
5852  // TODO: Why on earth is this here?! We should probably fix this
5853  // function and move it to the proper file. /Matz
5854  THD *thd= this;
5855  DBUG_ENTER("mysql_reset_thd_for_next_command");
5856  DBUG_ASSERT(!thd->sp_runtime_ctx); /* not for substatements of routines */
5857  DBUG_ASSERT(! thd->in_sub_stmt);
5858  thd->free_list= 0;
5859  thd->select_number= 1;
5860  /*
5861  Those two lines below are theoretically unneeded as
5862  THD::cleanup_after_query() should take care of this already.
5863  */
5864  thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
5865  thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
5866 
5867  thd->query_start_used= thd->query_start_usec_used= 0;
5868  thd->is_fatal_error= thd->time_zone_used= 0;
5869  /*
5870  Clear the status flag that are expected to be cleared at the
5871  beginning of each SQL statement.
5872  */
5873  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
5874  /*
5875  If in autocommit mode and not in a transaction, reset flag
5876  that identifies if a transaction has done some operations
5877  that cannot be safely rolled back.
5878 
5879  If the flag is set an warning message is printed out in
5880  ha_rollback_trans() saying that some tables couldn't be
5881  rolled back.
5882  */
5883  if (!thd->in_multi_stmt_transaction_mode())
5884  {
5885  thd->transaction.all.reset_unsafe_rollback_flags();
5886  }
5887  DBUG_ASSERT(thd->security_ctx== &thd->main_security_ctx);
5888  thd->thread_specific_used= FALSE;
5889 
5890  if (opt_bin_log)
5891  {
5892  reset_dynamic(&thd->user_var_events);
5893  thd->user_var_events_alloc= thd->mem_root;
5894  }
5895  thd->clear_error();
5896  thd->get_stmt_da()->reset_diagnostics_area();
5897  thd->get_stmt_da()->reset_for_next_command();
5898  thd->rand_used= 0;
5899  thd->m_sent_row_count= thd->m_examined_row_count= 0;
5900 
5901  thd->reset_current_stmt_binlog_format_row();
5902  thd->binlog_unsafe_warning_flags= 0;
5903 
5904  thd->m_trans_end_pos= 0;
5905  thd->m_trans_log_file= NULL;
5906  thd->m_trans_fixed_log_file= NULL;
5907  thd->commit_error= THD::CE_NONE;
5908  thd->durability_property= HA_REGULAR_DURABILITY;
5909  thd->set_trans_pos(NULL, 0);
5910 
5911  DBUG_PRINT("debug",
5912  ("is_current_stmt_binlog_format_row(): %d",
5913  thd->is_current_stmt_binlog_format_row()));
5914 
5915  DBUG_VOID_RETURN;
5916 }
5917 
5918 
5927 void
5929 {
5930  SELECT_LEX *select_lex= lex->current_select;
5931  select_lex->init_select();
5932  lex->wild= 0;
5933  if (select_lex == &lex->select_lex)
5934  {
5935  DBUG_ASSERT(lex->result == 0);
5936  lex->exchange= 0;
5937  }
5938 }
5939 
5940 
5953 bool
5954 mysql_new_select(LEX *lex, bool move_down)
5955 {
5956  SELECT_LEX *select_lex;
5957  THD *thd= lex->thd;
5958  Name_resolution_context *outer_context= lex->current_context();
5959  DBUG_ENTER("mysql_new_select");
5960 
5961  if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
5962  DBUG_RETURN(1);
5963  select_lex->select_number= ++thd->select_number;
5964  select_lex->parent_lex= lex; /* Used in init_query. */
5965  select_lex->init_query();
5966  select_lex->init_select();
5967  lex->nest_level++;
5968  if (lex->nest_level > (int) MAX_SELECT_NESTING)
5969  {
5970  my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT, MYF(0));
5971  DBUG_RETURN(1);
5972  }
5973  select_lex->nest_level= lex->nest_level;
5974  if (move_down)
5975  {
5976  SELECT_LEX_UNIT *unit;
5977  lex->subqueries= TRUE;
5978  /* first select_lex of subselect or derived table */
5979  if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
5980  DBUG_RETURN(1);
5981 
5982  unit->init_query();
5983  unit->init_select();
5984  unit->thd= thd;
5985  unit->include_down(lex->current_select);
5986  unit->link_next= 0;
5987  unit->link_prev= 0;
5988  select_lex->include_down(unit);
5989  /*
5990  By default we assume that it is usual subselect and we have outer name
5991  resolution context, if no we will assign it to 0 later
5992  */
5993  if (select_lex->outer_select()->parsing_place == IN_ON)
5994  /*
5995  This subquery is part of an ON clause, so we need to link the
5996  name resolution context for this subquery with the ON context.
5997 
5998  @todo outer_context is not the same as
5999  &select_lex->outer_select()->context in one case:
6000  (SELECT 1 as a) UNION (SELECT 2) ORDER BY (SELECT a);
6001  When we create the select_lex for the subquery in ORDER BY,
6002  1) outer_context is the context of the second SELECT of the
6003  UNION
6004  2) &select_lex->outer_select() is the fake select_lex, which context
6005  is the one of the first SELECT of the UNION (see
6006  st_select_lex_unit::add_fake_select_lex()).
6007  2) is the correct context, per the documentation. 1) is not, and using
6008  it leads to a resolving error for the query above.
6009  We should fix 1) and then use it unconditionally here.
6010  */
6011  select_lex->context.outer_context= outer_context;
6012  else
6013  select_lex->context.outer_context= &select_lex->outer_select()->context;
6014  }
6015  else
6016  {
6017  if (lex->current_select->order_list.first && !lex->current_select->braces)
6018  {
6019  my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY");
6020  DBUG_RETURN(1);
6021  }
6022  select_lex->include_neighbour(lex->current_select);
6023  SELECT_LEX_UNIT *unit= select_lex->master_unit();
6024  if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->thd))
6025  DBUG_RETURN(1);
6026  select_lex->context.outer_context=
6027  unit->first_select()->context.outer_context;
6028  }
6029 
6030  select_lex->master_unit()->global_parameters= select_lex;
6031  select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
6032  lex->current_select= select_lex;
6033  /*
6034  in subquery is SELECT query and we allow resolution of names in SELECT
6035  list
6036  */
6037  select_lex->context.resolve_in_select_list= TRUE;
6038  DBUG_RETURN(0);
6039 }
6040 
6051 void create_select_for_variable(const char *var_name)
6052 {
6053  THD *thd;
6054  LEX *lex;
6055  LEX_STRING tmp, null_lex_string;
6056  Item *var;
6057  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
6058  DBUG_ENTER("create_select_for_variable");
6059 
6060  thd= current_thd;
6061  lex= thd->lex;
6062  mysql_init_select(lex);
6063  lex->sql_command= SQLCOM_SELECT;
6064  tmp.str= (char*) var_name;
6065  tmp.length=strlen(var_name);
6066  memset(&null_lex_string, 0, sizeof(null_lex_string));
6067  /*
6068  We set the name of Item to @@session.var_name because that then is used
6069  as the column name in the output.
6070  */
6071  if ((var= get_system_var(thd, OPT_SESSION, tmp, null_lex_string)))
6072  {
6073  end= strxmov(buff, "@@session.", var_name, NullS);
6074  var->item_name.copy(buff, end - buff);
6075  add_item_to_list(thd, var);
6076  }
6077  DBUG_VOID_RETURN;
6078 }
6079 
6080 
6081 void mysql_init_multi_delete(LEX *lex)
6082 {
6083  lex->sql_command= SQLCOM_DELETE_MULTI;
6084  mysql_init_select(lex);
6085  lex->select_lex.select_limit= 0;
6086  lex->unit.select_limit_cnt= HA_POS_ERROR;
6087  lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list);
6088  lex->query_tables= 0;
6089  lex->query_tables_last= &lex->query_tables;
6090 }
6091 
6092 
6093 /*
6094  When you modify mysql_parse(), you may need to mofify
6095  mysql_test_parse_for_slave() in this same file.
6096 */
6097 
6108 void mysql_parse(THD *thd, char *rawbuf, uint length,
6109  Parser_state *parser_state)
6110 {
6111  int error __attribute__((unused));
6112  DBUG_ENTER("mysql_parse");
6113 
6114  DBUG_EXECUTE_IF("parser_debug", turn_parser_debug_on(););
6115 
6116  /*
6117  Warning.
6118  The purpose of query_cache_send_result_to_client() is to lookup the
6119  query in the query cache first, to avoid parsing and executing it.
6120  So, the natural implementation would be to:
6121  - first, call query_cache_send_result_to_client,
6122  - second, if caching failed, initialise the lexical and syntactic parser.
6123  The problem is that the query cache depends on a clean initialization
6124  of (among others) lex->safe_to_cache_query and thd->server_status,
6125  which are reset respectively in
6126  - lex_start()
6127  - mysql_reset_thd_for_next_command()
6128  So, initializing the lexical analyser *before* using the query cache
6129  is required for the cache to work properly.
6130  FIXME: cleanup the dependencies in the code to simplify this.
6131  */
6132  lex_start(thd);
6134 
6135  if (query_cache_send_result_to_client(thd, rawbuf, length) <= 0)
6136  {
6137  LEX *lex= thd->lex;
6138 
6139  bool err= parse_sql(thd, parser_state, NULL);
6140 
6141  const char *found_semicolon= parser_state->m_lip.found_semicolon;
6142  size_t qlen= found_semicolon
6143  ? (found_semicolon - thd->query())
6144  : thd->query_length();
6145 
6146  if (!err)
6147  {
6148  /*
6149  See whether we can do any query rewriting. opt_log_raw only controls
6150  writing to the general log, so rewriting still needs to happen because
6151  the other logs (binlog, slow query log, ...) can not be set to raw mode
6152  for security reasons.
6153  Query-cache only handles SELECT, which we don't rewrite, so it's no
6154  concern of ours.
6155  We're not general-logging if we're the slave, or if we've already
6156  done raw-logging earlier.
6157  Sub-routines of mysql_rewrite_query() should try to only rewrite when
6158  necessary (e.g. not do password obfuscation when query contains no
6159  password), but we can optimize out even those necessary rewrites when
6160  no logging happens at all. If rewriting does not happen here,
6161  thd->rewritten_query is still empty from being reset in alloc_query().
6162  */
6163  bool general= (opt_log && ! (opt_log_raw || thd->slave_thread));
6164 
6165  if (general || opt_slow_log || opt_bin_log)
6166  {
6167  mysql_rewrite_query(thd);
6168 
6169  if (thd->rewritten_query.length())
6170  lex->safe_to_cache_query= false; // see comments below
6171  }
6172 
6173  if (general)
6174  {
6175  if (thd->rewritten_query.length())
6176  general_log_write(thd, COM_QUERY, thd->rewritten_query.c_ptr_safe(),
6177  thd->rewritten_query.length());
6178  else
6179  general_log_write(thd, COM_QUERY, thd->query(), qlen);
6180  }
6181  }
6182 
6183  if (!err)
6184  {
6185  thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
6186  sql_statement_info[thd->lex->sql_command].m_key);
6187 
6188 #ifndef NO_EMBEDDED_ACCESS_CHECKS
6189  if (mqh_used && thd->get_user_connect() &&
6190  check_mqh(thd, lex->sql_command))
6191  {
6192  thd->net.error = 0;
6193  }
6194  else
6195 #endif
6196  {
6197  if (! thd->is_error())
6198  {
6199  /*
6200  Binlog logs a string starting from thd->query and having length
6201  thd->query_length; so we set thd->query_length correctly (to not
6202  log several statements in one event, when we executed only first).
6203  We set it to not see the ';' (otherwise it would get into binlog
6204  and Query_log_event::print() would give ';;' output).
6205  This also helps display only the current query in SHOW
6206  PROCESSLIST.
6207  Note that we don't need LOCK_thread_count to modify query_length.
6208  */
6209  if (found_semicolon && (ulong) (found_semicolon - thd->query()))
6210  thd->set_query_inner(thd->query(),
6211  (uint32) (found_semicolon -
6212  thd->query() - 1),
6213  thd->charset());
6214  /* Actually execute the query */
6215  if (found_semicolon)
6216  {
6217  lex->safe_to_cache_query= 0;
6218  thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
6219  }
6220  lex->set_trg_event_type_for_tables();
6221  MYSQL_QUERY_EXEC_START(thd->query(),
6222  thd->thread_id,
6223  (char *) (thd->db ? thd->db : ""),
6224  &thd->security_ctx->priv_user[0],
6225  (char *) thd->security_ctx->host_or_ip,
6226  0);
6227  if (unlikely(thd->security_ctx->password_expired &&
6228  !lex->is_change_password &&
6229  lex->sql_command != SQLCOM_SET_OPTION))
6230  {
6231  my_error(ER_MUST_CHANGE_PASSWORD, MYF(0));
6232  error= 1;
6233  }
6234  else
6235  error= mysql_execute_command(thd);
6236  if (error == 0 &&
6237  thd->variables.gtid_next.type == GTID_GROUP &&
6238  thd->owned_gtid.sidno != 0 &&
6239  (thd->lex->sql_command == SQLCOM_COMMIT ||
6240  stmt_causes_implicit_commit(thd, CF_IMPLICIT_COMMIT_END)))
6241  {
6242  // This is executed at the end of a DDL statement or after
6243  // COMMIT. It ensures that an empty group is logged if
6244  // needed.
6246  }
6247  MYSQL_QUERY_EXEC_DONE(error);
6248  }
6249  }
6250  }
6251  else
6252  {
6253  /* Instrument this broken statement as "statement/sql/error" */
6254  thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
6255  sql_statement_info[SQLCOM_END].m_key);
6256 
6257  DBUG_ASSERT(thd->is_error());
6258  DBUG_PRINT("info",("Command aborted. Fatal_error: %d",
6259  thd->is_fatal_error));
6260 
6261  query_cache_abort(&thd->query_cache_tls);
6262  }
6263 
6264  THD_STAGE_INFO(thd, stage_freeing_items);
6265  sp_cache_enforce_limit(thd->sp_proc_cache, stored_program_cache_size);
6266  sp_cache_enforce_limit(thd->sp_func_cache, stored_program_cache_size);
6267  thd->end_statement();
6268  thd->cleanup_after_query();
6269  DBUG_ASSERT(thd->change_list.is_empty());
6270  }
6271  else
6272  {
6273  /*
6274  Query cache hit. We need to write the general log here if
6275  we haven't already logged the statement earlier due to --log-raw.
6276  Right now, we only cache SELECT results; if the cache ever
6277  becomes more generic, we should also cache the rewritten
6278  query-string together with the original query-string (which
6279  we'd still use for the matching) when we first execute the
6280  query, and then use the obfuscated query-string for logging
6281  here when the query is given again.
6282  */
6283  thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
6284  sql_statement_info[SQLCOM_SELECT].m_key);
6285  if (!opt_log_raw)
6286  general_log_write(thd, COM_QUERY, thd->query(), thd->query_length());
6287  parser_state->m_lip.found_semicolon= NULL;
6288  }
6289 
6290  DBUG_VOID_RETURN;
6291 }
6292 
6293 
6294 #ifdef HAVE_REPLICATION
6295 /*
6296  Usable by the replication SQL thread only: just parse a query to know if it
6297  can be ignored because of replicate-*-table rules.
6298 
6299  @retval
6300  0 cannot be ignored
6301  @retval
6302  1 can be ignored
6303 */
6304 
6305 bool mysql_test_parse_for_slave(THD *thd, char *rawbuf, uint length)
6306 {
6307  LEX *lex= thd->lex;
6308  bool error= 0;
6309  PSI_statement_locker *parent_locker= thd->m_statement_psi;
6310  DBUG_ENTER("mysql_test_parse_for_slave");
6311 
6312  Parser_state parser_state;
6313  if (!(error= parser_state.init(thd, rawbuf, length)))
6314  {
6315  lex_start(thd);
6317 
6318  thd->m_statement_psi= NULL;
6319  if (!parse_sql(thd, & parser_state, NULL) &&
6320  all_tables_not_ok(thd, lex->select_lex.table_list.first))
6321  error= 1; /* Ignore question */
6322  thd->m_statement_psi= parent_locker;
6323  thd->end_statement();
6324  }
6325  thd->cleanup_after_query();
6326  DBUG_RETURN(error);
6327 }
6328 #endif
6329 
6330 
6331 
6339 bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum_field_types type,
6340  char *length, char *decimals,
6341  uint type_modifier,
6342  Item *default_value, Item *on_update_value,
6343  LEX_STRING *comment,
6344  char *change,
6345  List<String> *interval_list, const CHARSET_INFO *cs,
6346  uint uint_geom_type)
6347 {
6348  register Create_field *new_field;
6349  LEX *lex= thd->lex;
6350  uint8 datetime_precision= decimals ? atoi(decimals) : 0;
6351  DBUG_ENTER("add_field_to_list");
6352 
6353  if (check_string_char_length(field_name, "", NAME_CHAR_LEN,
6354  system_charset_info, 1))
6355  {
6356  my_error(ER_TOO_LONG_IDENT, MYF(0), field_name->str); /* purecov: inspected */
6357  DBUG_RETURN(1); /* purecov: inspected */
6358  }
6359  if (type_modifier & PRI_KEY_FLAG)
6360  {
6361  Key *key;
6362  lex->col_list.push_back(new Key_part_spec(*field_name, 0));
6363  key= new Key(Key::PRIMARY, null_lex_str,
6364  &default_key_create_info,
6365  0, lex->col_list);
6366  lex->alter_info.key_list.push_back(key);
6367  lex->col_list.empty();
6368  }
6369  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
6370  {
6371  Key *key;
6372  lex->col_list.push_back(new Key_part_spec(*field_name, 0));
6373  key= new Key(Key::UNIQUE, null_lex_str,
6374  &default_key_create_info, 0,
6375  lex->col_list);
6376  lex->alter_info.key_list.push_back(key);
6377  lex->col_list.empty();
6378  }
6379 
6380  if (default_value)
6381  {
6382  /*
6383  Default value should be literal => basic constants =>
6384  no need fix_fields()
6385 
6386  We allow only CURRENT_TIMESTAMP as function default for the TIMESTAMP or
6387  DATETIME types.
6388  */
6389  if (default_value->type() == Item::FUNC_ITEM &&
6390  (static_cast<Item_func*>(default_value)->functype() !=
6391  Item_func::NOW_FUNC ||
6392  (!real_type_with_now_as_default(type)) ||
6393  default_value->decimals != datetime_precision))
6394  {
6395  my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
6396  DBUG_RETURN(1);
6397  }
6398  else if (default_value->type() == Item::NULL_ITEM)
6399  {
6400  default_value= 0;
6401  if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
6402  NOT_NULL_FLAG)
6403  {
6404  my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
6405  DBUG_RETURN(1);
6406  }
6407  }
6408  else if (type_modifier & AUTO_INCREMENT_FLAG)
6409  {
6410  my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
6411  DBUG_RETURN(1);
6412  }
6413  }
6414 
6415  if (on_update_value &&
6416  (!real_type_with_now_on_update(type) ||
6417  on_update_value->decimals != datetime_precision))
6418  {
6419  my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
6420  DBUG_RETURN(1);
6421  }
6422 
6423  if (!(new_field= new Create_field()) ||
6424  new_field->init(thd, field_name->str, type, length, decimals, type_modifier,
6425  default_value, on_update_value, comment, change,
6426  interval_list, cs, uint_geom_type))
6427  DBUG_RETURN(1);
6428 
6429  lex->alter_info.create_list.push_back(new_field);
6430  lex->last_field=new_field;
6431  DBUG_RETURN(0);
6432 }
6433 
6434 
6437 void store_position_for_column(const char *name)
6438 {
6439  current_thd->lex->last_field->after=(char*) (name);
6440 }
6441 
6442 
6447 bool add_to_list(THD *thd, SQL_I_List<ORDER> &list, Item *item,bool asc)
6448 {
6449  ORDER *order;
6450  DBUG_ENTER("add_to_list");
6451  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER))))
6452  DBUG_RETURN(1);
6453  order->item_ptr= item;
6454  order->item= &order->item_ptr;
6455  order->direction= (asc ? ORDER::ORDER_ASC : ORDER::ORDER_DESC);
6456  order->used_alias= false;
6457  order->used=0;
6458  order->counter_used= 0;
6459  list.link_in_list(order, &order->next);
6460  DBUG_RETURN(0);
6461 }
6462 
6463 
6484 TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
6485  Table_ident *table,
6486  LEX_STRING *alias,
6487  ulong table_options,
6488  thr_lock_type lock_type,
6489  enum_mdl_type mdl_type,
6490  List<Index_hint> *index_hints_arg,
6491  List<String> *partition_names,
6492  LEX_STRING *option)
6493 {
6494  register TABLE_LIST *ptr;
6495  TABLE_LIST *previous_table_ref; /* The table preceding the current one. */
6496  char *alias_str;
6497  LEX *lex= thd->lex;
6498  DBUG_ENTER("add_table_to_list");
6499  LINT_INIT(previous_table_ref);
6500 
6501  if (!table)
6502  DBUG_RETURN(0); // End of memory
6503  alias_str= alias ? alias->str : table->table.str;
6504  if (!test(table_options & TL_OPTION_ALIAS))
6505  {
6506  enum_ident_name_check ident_check_status=
6507  check_table_name(table->table.str, table->table.length, FALSE);
6508  if (ident_check_status == IDENT_NAME_WRONG)
6509  {
6510  my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
6511  DBUG_RETURN(0);
6512  }
6513  else if (ident_check_status == IDENT_NAME_TOO_LONG)
6514  {
6515  my_error(ER_TOO_LONG_IDENT, MYF(0), table->table.str);
6516  DBUG_RETURN(0);
6517  }
6518  }
6519  if (table->is_derived_table() == FALSE && table->db.str &&
6520  (check_and_convert_db_name(&table->db, FALSE) != IDENT_NAME_OK))
6521  DBUG_RETURN(0);
6522 
6523  if (!alias) /* Alias is case sensitive */
6524  {
6525  if (table->sel)
6526  {
6527  my_message(ER_DERIVED_MUST_HAVE_ALIAS,
6528  ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
6529  DBUG_RETURN(0);
6530  }
6531  if (!(alias_str= (char*) thd->memdup(alias_str,table->table.length+1)))
6532  DBUG_RETURN(0);
6533  }
6534  if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST))))
6535  DBUG_RETURN(0); /* purecov: inspected */
6536  if (table->db.str)
6537  {
6538  ptr->is_fqtn= TRUE;
6539  ptr->db= table->db.str;
6540  ptr->db_length= table->db.length;
6541  }
6542  else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
6543  DBUG_RETURN(0);
6544  else
6545  ptr->is_fqtn= FALSE;
6546 
6547  ptr->alias= alias_str;
6548  ptr->is_alias= alias ? TRUE : FALSE;
6549  if (lower_case_table_names && table->table.length)
6550  table->table.length= my_casedn_str(files_charset_info, table->table.str);
6551  ptr->table_name=table->table.str;
6552  ptr->table_name_length=table->table.length;
6553  ptr->lock_type= lock_type;
6554  ptr->updating= test(table_options & TL_OPTION_UPDATING);
6555  /* TODO: remove TL_OPTION_FORCE_INDEX as it looks like it's not used */
6556  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
6557  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
6558  ptr->derived= table->sel;
6559  if (!ptr->derived && is_infoschema_db(ptr->db, ptr->db_length))
6560  {
6561  ST_SCHEMA_TABLE *schema_table;
6562  if (ptr->updating &&
6563  /* Special cases which are processed by commands itself */
6564  lex->sql_command != SQLCOM_CHECK &&
6565  lex->sql_command != SQLCOM_CHECKSUM)
6566  {
6567  my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
6568  thd->security_ctx->priv_user,
6569  thd->security_ctx->priv_host,
6570  INFORMATION_SCHEMA_NAME.str);
6571  DBUG_RETURN(0);
6572  }
6573  schema_table= find_schema_table(thd, ptr->table_name);
6574  if (!schema_table ||
6575  (schema_table->hidden &&
6576  ((sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0 ||
6577  /*
6578  this check is used for show columns|keys from I_S hidden table
6579  */
6580  lex->sql_command == SQLCOM_SHOW_FIELDS ||
6581  lex->sql_command == SQLCOM_SHOW_KEYS)))
6582  {
6583  my_error(ER_UNKNOWN_TABLE, MYF(0),
6584  ptr->table_name, INFORMATION_SCHEMA_NAME.str);
6585  DBUG_RETURN(0);
6586  }
6587  ptr->schema_table_name= ptr->table_name;
6588  ptr->schema_table= schema_table;
6589  }
6590  ptr->select_lex= lex->current_select;
6591  ptr->cacheable_table= 1;
6592  ptr->index_hints= index_hints_arg;
6593  ptr->option= option ? option->str : 0;
6594  /* check that used name is unique */
6595  if (lock_type != TL_IGNORE)
6596  {
6597  TABLE_LIST *first_table= table_list.first;
6598  if (lex->sql_command == SQLCOM_CREATE_VIEW)
6599  first_table= first_table ? first_table->next_local : NULL;
6600  for (TABLE_LIST *tables= first_table ;
6601  tables ;
6602  tables=tables->next_local)
6603  {
6604  if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
6605  !strcmp(ptr->db, tables->db))
6606  {
6607  my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
6608  DBUG_RETURN(0); /* purecov: tested */
6609  }
6610  }
6611  }
6612  /* Store the table reference preceding the current one. */
6613  if (table_list.elements > 0)
6614  {
6615  /*
6616  table_list.next points to the last inserted TABLE_LIST->next_local'
6617  element
6618  We don't use the offsetof() macro here to avoid warnings from gcc
6619  */
6620  previous_table_ref= (TABLE_LIST*) ((char*) table_list.next -
6621  ((char*) &(ptr->next_local) -
6622  (char*) ptr));
6623  /*
6624  Set next_name_resolution_table of the previous table reference to point
6625  to the current table reference. In effect the list
6626  TABLE_LIST::next_name_resolution_table coincides with
6627  TABLE_LIST::next_local. Later this may be changed in
6628  store_top_level_join_columns() for NATURAL/USING joins.
6629  */
6630  previous_table_ref->next_name_resolution_table= ptr;
6631  }
6632 
6633  /*
6634  Link the current table reference in a local list (list for current select).
6635  Notice that as a side effect here we set the next_local field of the
6636  previous table reference to 'ptr'. Here we also add one element to the
6637  list 'table_list'.
6638  */
6639  table_list.link_in_list(ptr, &ptr->next_local);
6640  ptr->next_name_resolution_table= NULL;
6641 #ifdef WITH_PARTITION_STORAGE_ENGINE
6642  ptr->partition_names= partition_names;
6643 #endif /* WITH_PARTITION_STORAGE_ENGINE */
6644  /* Link table in global list (all used tables) */
6645  lex->add_to_query_tables(ptr);
6646 
6647  // Pure table aliases do not need to be locked:
6648  if (!test(table_options & TL_OPTION_ALIAS))
6649  {
6650  ptr->mdl_request.init(MDL_key::TABLE, ptr->db, ptr->table_name, mdl_type,
6651  MDL_TRANSACTION);
6652  }
6653  if (table->is_derived_table())
6654  {
6655  ptr->effective_algorithm= DERIVED_ALGORITHM_TMPTABLE;
6656  ptr->derived_key_list.empty();
6657  }
6658  DBUG_RETURN(ptr);
6659 }
6660 
6661 
6681 bool st_select_lex::init_nested_join(THD *thd)
6682 {
6683  DBUG_ENTER("init_nested_join");
6684 
6685  TABLE_LIST *const ptr=
6686  TABLE_LIST::new_nested_join(thd->mem_root, "(nested_join)",
6687  embedding, join_list, this);
6688  if (ptr == NULL)
6689  DBUG_RETURN(true);
6690 
6691  join_list->push_front(ptr);
6692  embedding= ptr;
6693  join_list= &ptr->nested_join->join_list;
6694 
6695  DBUG_RETURN(false);
6696 }
6697 
6698 
6713 TABLE_LIST *st_select_lex::end_nested_join(THD *thd)
6714 {
6715  TABLE_LIST *ptr;
6716  NESTED_JOIN *nested_join;
6717  DBUG_ENTER("end_nested_join");
6718 
6719  DBUG_ASSERT(embedding);
6720  ptr= embedding;
6721  join_list= ptr->join_list;
6722  embedding= ptr->embedding;
6723  nested_join= ptr->nested_join;
6724  if (nested_join->join_list.elements == 1)
6725  {
6726  TABLE_LIST *embedded= nested_join->join_list.head();
6727  join_list->pop();
6728  embedded->join_list= join_list;
6729  embedded->embedding= embedding;
6730  join_list->push_front(embedded);
6731  ptr= embedded;
6732  }
6733  else if (nested_join->join_list.elements == 0)
6734  {
6735  join_list->pop();
6736  ptr= 0; // return value
6737  }
6738  DBUG_RETURN(ptr);
6739 }
6740 
6741 
6755 TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
6756 {
6757  DBUG_ENTER("nest_last_join");
6758 
6759  TABLE_LIST *const ptr=
6760  TABLE_LIST::new_nested_join(thd->mem_root, "(nest_last_join)",
6761  embedding, join_list, this);
6762  if (ptr == NULL)
6763  DBUG_RETURN(NULL);
6764 
6765  List<TABLE_LIST> *const embedded_list= &ptr->nested_join->join_list;
6766 
6767  for (uint i=0; i < 2; i++)
6768  {
6769  TABLE_LIST *table= join_list->pop();
6770  table->join_list= embedded_list;
6771  table->embedding= ptr;
6772  embedded_list->push_back(table);
6773  if (table->natural_join)
6774  {
6775  ptr->is_natural_join= TRUE;
6776  /*
6777  If this is a JOIN ... USING, move the list of joined fields to the
6778  table reference that describes the join.
6779  */
6780  if (prev_join_using)
6781  ptr->join_using_fields= prev_join_using;
6782  }
6783  }
6784  join_list->push_front(ptr);
6785 
6786  DBUG_RETURN(ptr);
6787 }
6788 
6789 
6804 void st_select_lex::add_joined_table(TABLE_LIST *table)
6805 {
6806  DBUG_ENTER("add_joined_table");
6807  join_list->push_front(table);
6808  table->join_list= join_list;
6809  table->embedding= embedding;
6810  DBUG_VOID_RETURN;
6811 }
6812 
6813 
6845 TABLE_LIST *st_select_lex::convert_right_join()
6846 {
6847  TABLE_LIST *tab2= join_list->pop();
6848  TABLE_LIST *tab1= join_list->pop();
6849  DBUG_ENTER("convert_right_join");
6850 
6851  join_list->push_front(tab2);
6852  join_list->push_front(tab1);
6853  tab1->outer_join|= JOIN_TYPE_RIGHT;
6854 
6855  DBUG_RETURN(tab1);
6856 }
6857 
6869 void st_select_lex::set_lock_for_tables(thr_lock_type lock_type)
6870 {
6871  bool for_update= lock_type >= TL_READ_NO_INSERT;
6872  DBUG_ENTER("set_lock_for_tables");
6873  DBUG_PRINT("enter", ("lock_type: %d for_update: %d", lock_type,
6874  for_update));
6875  for (TABLE_LIST *tables= table_list.first;
6876  tables;
6877  tables= tables->next_local)
6878  {
6879  tables->lock_type= lock_type;
6880  tables->updating= for_update;
6881  tables->mdl_request.set_type((lock_type >= TL_WRITE_ALLOW_WRITE) ?
6882  MDL_SHARED_WRITE : MDL_SHARED_READ);
6883  }
6884  DBUG_VOID_RETURN;
6885 }
6886 
6887 
6914 bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg)
6915 {
6916  SELECT_LEX *first_sl= first_select();
6917  DBUG_ENTER("add_fake_select_lex");
6918  DBUG_ASSERT(!fake_select_lex);
6919 
6920  if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX()))
6921  DBUG_RETURN(1);
6922  fake_select_lex->include_standalone(this,
6923  (SELECT_LEX_NODE**)&fake_select_lex);
6924  fake_select_lex->select_number= INT_MAX;
6925  fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */
6926  fake_select_lex->make_empty_select();
6927  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
6928  fake_select_lex->select_limit= 0;
6929 
6930  fake_select_lex->context.outer_context=first_sl->context.outer_context;
6931  /* allow item list resolving in fake select for ORDER BY */
6932  fake_select_lex->context.resolve_in_select_list= TRUE;
6933  fake_select_lex->context.select_lex= fake_select_lex;
6934 
6935  if (!is_union())
6936  {
6937  /*
6938  This works only for
6939  (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
6940  (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
6941  just before the parser starts processing order_list
6942  */
6943  global_parameters= fake_select_lex;
6944  fake_select_lex->no_table_names_allowed= 1;
6945  thd_arg->lex->current_select= fake_select_lex;
6946  }
6947  thd_arg->lex->pop_context();
6948  DBUG_RETURN(0);
6949 }
6950 
6951 
6974 bool
6975 push_new_name_resolution_context(THD *thd,
6976  TABLE_LIST *left_op, TABLE_LIST *right_op)
6977 {
6978  Name_resolution_context *on_context;
6979  if (!(on_context= new (thd->mem_root) Name_resolution_context))
6980  return TRUE;
6981  on_context->init();
6982  on_context->first_name_resolution_table=
6983  left_op->first_leaf_for_name_resolution();
6984  on_context->last_name_resolution_table=
6985  right_op->last_leaf_for_name_resolution();
6986  on_context->select_lex= thd->lex->current_select;
6987  // Save join nest's context in right_op, to find it later in view merging.
6988  DBUG_ASSERT(right_op->context_of_embedding == NULL);
6989  right_op->context_of_embedding= on_context;
6990  return thd->lex->push_context(on_context);
6991 }
6992 
6993 
7003 void add_join_on(TABLE_LIST *b, Item *expr)
7004 {
7005  if (expr)
7006  {
7007  if (!b->join_cond())
7008  b->set_join_cond(expr);
7009  else
7010  {
7011  /*
7012  If called from the parser, this happens if you have both a
7013  right and left join. If called later, it happens if we add more
7014  than one condition to the ON clause.
7015  */
7016  b->set_join_cond(new Item_cond_and(b->join_cond(), expr));
7017  }
7018  b->join_cond()->top_level_item();
7019  }
7020 }
7021 
7022 
7057  SELECT_LEX *lex)
7058 {
7059  b->natural_join= a;
7060  lex->prev_join_using= using_fields;
7061 }
7062 
7063 
7075 uint kill_one_thread(THD *thd, ulong id, bool only_kill_query)
7076 {
7077  THD *tmp= NULL;
7078  uint error=ER_NO_SUCH_THREAD;
7079  DBUG_ENTER("kill_one_thread");
7080  DBUG_PRINT("enter", ("id=%lu only_kill=%d", id, only_kill_query));
7081 
7082  mysql_mutex_lock(&LOCK_thread_count);
7083  Thread_iterator it= global_thread_list_begin();
7084  Thread_iterator end= global_thread_list_end();
7085  for (; it != end; ++it)
7086  {
7087  if ((*it)->get_command() == COM_DAEMON)
7088  continue;
7089  if ((*it)->thread_id == id)
7090  {
7091  tmp= *it;
7092  mysql_mutex_lock(&tmp->LOCK_thd_data); // Lock from delete
7093  break;
7094  }
7095  }
7096  mysql_mutex_unlock(&LOCK_thread_count);
7097  if (tmp)
7098  {
7099 
7100  /*
7101  If we're SUPER, we can KILL anything, including system-threads.
7102  No further checks.
7103 
7104  KILLer: thd->security_ctx->user could in theory be NULL while
7105  we're still in "unauthenticated" state. This is a theoretical
7106  case (the code suggests this could happen, so we play it safe).
7107 
7108  KILLee: tmp->security_ctx->user will be NULL for system threads.
7109  We need to check so Jane Random User doesn't crash the server
7110  when trying to kill a) system threads or b) unauthenticated users'
7111  threads (Bug#43748).
7112 
7113  If user of both killer and killee are non-NULL, proceed with
7114  slayage if both are string-equal.
7115  */
7116 
7117  if ((thd->security_ctx->master_access & SUPER_ACL) ||
7118  thd->security_ctx->user_matches(tmp->security_ctx))
7119  {
7120  /* process the kill only if thread is not already undergoing any kill
7121  connection.
7122  */
7123  if (tmp->killed != THD::KILL_CONNECTION)
7124  {
7125  tmp->awake(only_kill_query ? THD::KILL_QUERY : THD::KILL_CONNECTION);
7126  }
7127  error= 0;
7128  }
7129  else
7130  error=ER_KILL_DENIED_ERROR;
7131  mysql_mutex_unlock(&tmp->LOCK_thd_data);
7132  }
7133  DBUG_PRINT("exit", ("%d", error));
7134  DBUG_RETURN(error);
7135 }
7136 
7137 
7138 /*
7139  kills a thread and sends response
7140 
7141  SYNOPSIS
7142  sql_kill()
7143  thd Thread class
7144  id Thread id
7145  only_kill_query Should it kill the query or the connection
7146 */
7147 
7148 static
7149 void sql_kill(THD *thd, ulong id, bool only_kill_query)
7150 {
7151  uint error;
7152  if (!(error= kill_one_thread(thd, id, only_kill_query)))
7153  {
7154  if (! thd->killed)
7155  my_ok(thd);
7156  }
7157  else
7158  my_error(error, MYF(0), id);
7159 }
7160 
7161 
7164 bool append_file_to_dir(THD *thd, const char **filename_ptr,
7165  const char *table_name)
7166 {
7167  char buff[FN_REFLEN],*ptr, *end;
7168  if (!*filename_ptr)
7169  return 0; // nothing to do
7170 
7171  /* Check that the filename is not too long and it's a hard path */
7172  if (strlen(*filename_ptr)+strlen(table_name) >= FN_REFLEN-1 ||
7173  !test_if_hard_path(*filename_ptr))
7174  {
7175  my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
7176  return 1;
7177  }
7178  /* Fix is using unix filename format on dos */
7179  strmov(buff,*filename_ptr);
7180  end=convert_dirname(buff, *filename_ptr, NullS);
7181  if (!(ptr= (char*) thd->alloc((size_t) (end-buff) + strlen(table_name)+1)))
7182  return 1; // End of memory
7183  *filename_ptr=ptr;
7184  strxmov(ptr,buff,table_name,NullS);
7185  return 0;
7186 }
7187 
7188 
7199 {
7200  THD *thd= current_thd;
7201  LEX *lex= thd->lex;
7202  if (lex->current_select != &lex->select_lex)
7203  {
7204  char command[80];
7205  Lex_input_stream *lip= & thd->m_parser_state->m_lip;
7206  strmake(command, lip->yylval->symbol.str,
7207  min<size_t>(lip->yylval->symbol.length, sizeof(command)-1));
7208  my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
7209  return 1;
7210  }
7211  return 0;
7212 }
7213 
7214 
7215 Comp_creator *comp_eq_creator(bool invert)
7216 {
7217  return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
7218 }
7219 
7220 
7221 Comp_creator *comp_ge_creator(bool invert)
7222 {
7223  return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator;
7224 }
7225 
7226 
7227 Comp_creator *comp_gt_creator(bool invert)
7228 {
7229  return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator;
7230 }
7231 
7232 
7233 Comp_creator *comp_le_creator(bool invert)
7234 {
7235  return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator;
7236 }
7237 
7238 
7239 Comp_creator *comp_lt_creator(bool invert)
7240 {
7241  return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator;
7242 }
7243 
7244 
7245 Comp_creator *comp_ne_creator(bool invert)
7246 {
7247  return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
7248 }
7249 
7250 
7263  chooser_compare_func_creator cmp,
7264  bool all,
7265  SELECT_LEX *select_lex)
7266 {
7267  if ((cmp == &comp_eq_creator) && !all) // = ANY <=> IN
7268  return new Item_in_subselect(left_expr, select_lex);
7269 
7270  if ((cmp == &comp_ne_creator) && all) // <> ALL <=> NOT IN
7271  return new Item_func_not(new Item_in_subselect(left_expr, select_lex));
7272 
7274  new Item_allany_subselect(left_expr, cmp, select_lex, all);
7275  if (all)
7276  return it->upper_item= new Item_func_not_all(it); /* ALL */
7277 
7278  return it->upper_item= new Item_func_nop_all(it); /* ANY/SOME */
7279 }
7280 
7281 
7295 bool select_precheck(THD *thd, LEX *lex, TABLE_LIST *tables,
7296  TABLE_LIST *first_table)
7297 {
7298  bool res;
7299  /*
7300  lex->exchange != NULL implies SELECT .. INTO OUTFILE and this
7301  requires FILE_ACL access.
7302  */
7303  ulong privileges_requested= lex->exchange ? SELECT_ACL | FILE_ACL :
7304  SELECT_ACL;
7305 
7306  if (tables)
7307  {
7308  res= check_table_access(thd,
7309  privileges_requested,
7310  tables, FALSE, UINT_MAX, FALSE) ||
7311  (first_table && first_table->schema_table_reformed &&
7312  check_show_access(thd, first_table));
7313  }
7314  else
7315  res= check_access(thd, privileges_requested, any_db, NULL, NULL, 0, 0);
7316 
7317  return res;
7318 }
7319 
7320 
7333 bool multi_update_precheck(THD *thd, TABLE_LIST *tables)
7334 {
7335  const char *msg= 0;
7336  TABLE_LIST *table;
7337  LEX *lex= thd->lex;
7338  SELECT_LEX *select_lex= &lex->select_lex;
7339  DBUG_ENTER("multi_update_precheck");
7340 
7341  if (select_lex->item_list.elements != lex->value_list.elements)
7342  {
7343  my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
7344  DBUG_RETURN(TRUE);
7345  }
7346  /*
7347  Ensure that we have UPDATE or SELECT privilege for each table
7348  The exact privilege is checked in mysql_multi_update()
7349  */
7350  for (table= tables; table; table= table->next_local)
7351  {
7352  if (table->derived)
7353  table->grant.privilege= SELECT_ACL;
7354  else if ((check_access(thd, UPDATE_ACL, table->db,
7355  &table->grant.privilege,
7356  &table->grant.m_internal,
7357  0, 1) ||
7358  check_grant(thd, UPDATE_ACL, table, FALSE, 1, TRUE)) &&
7359  (check_access(thd, SELECT_ACL, table->db,
7360  &table->grant.privilege,
7361  &table->grant.m_internal,
7362  0, 0) ||
7363  check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE)))
7364  DBUG_RETURN(TRUE);
7365 
7366  table->table_in_first_from_clause= 1;
7367  }
7368  /*
7369  Is there tables of subqueries?
7370  */
7371  if (&lex->select_lex != lex->all_selects_list)
7372  {
7373  DBUG_PRINT("info",("Checking sub query list"));
7374  for (table= tables; table; table= table->next_global)
7375  {
7376  if (!table->table_in_first_from_clause)
7377  {
7378  if (check_access(thd, SELECT_ACL, table->db,
7379  &table->grant.privilege,
7380  &table->grant.m_internal,
7381  0, 0) ||
7382  check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE))
7383  DBUG_RETURN(TRUE);
7384  }
7385  }
7386  }
7387 
7388  if (select_lex->order_list.elements)
7389  msg= "ORDER BY";
7390  else if (select_lex->select_limit)
7391  msg= "LIMIT";
7392  if (msg)
7393  {
7394  my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
7395  DBUG_RETURN(TRUE);
7396  }
7397  DBUG_RETURN(FALSE);
7398 }
7399 
7412 bool multi_delete_precheck(THD *thd, TABLE_LIST *tables)
7413 {
7414  SELECT_LEX *select_lex= &thd->lex->select_lex;
7415  TABLE_LIST *aux_tables= thd->lex->auxiliary_table_list.first;
7416  TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
7417  DBUG_ENTER("multi_delete_precheck");
7418 
7419  /*
7420  Temporary tables are pre-opened in 'tables' list only. Here we need to
7421  initialize TABLE instances in 'aux_tables' list.
7422  */
7423  for (TABLE_LIST *tl= aux_tables; tl; tl= tl->next_global)
7424  {
7425  if (tl->table)
7426  continue;
7427 
7428  if (tl->correspondent_table)
7429  tl->table= tl->correspondent_table->table;
7430  }
7431 
7432  /* sql_yacc guarantees that tables and aux_tables are not zero */
7433  DBUG_ASSERT(aux_tables != 0);
7434  if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE))
7435  DBUG_RETURN(TRUE);
7436 
7437  /*
7438  Since aux_tables list is not part of LEX::query_tables list we
7439  have to juggle with LEX::query_tables_own_last value to be able
7440  call check_table_access() safely.
7441  */
7442  thd->lex->query_tables_own_last= 0;
7443  if (check_table_access(thd, DELETE_ACL, aux_tables, FALSE, UINT_MAX, FALSE))
7444  {
7445  thd->lex->query_tables_own_last= save_query_tables_own_last;
7446  DBUG_RETURN(TRUE);
7447  }
7448  thd->lex->query_tables_own_last= save_query_tables_own_last;
7449 
7450  if ((thd->variables.option_bits & OPTION_SAFE_UPDATES) && !select_lex->where)
7451  {
7452  my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
7453  ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
7454  DBUG_RETURN(TRUE);
7455  }
7456  DBUG_RETURN(FALSE);
7457 }
7458 
7459 
7460 /*
7461  Given a table in the source list, find a correspondent table in the
7462  table references list.
7463 
7464  @param lex Pointer to LEX representing multi-delete.
7465  @param src Source table to match.
7466  @param ref Table references list.
7467 
7468  @remark The source table list (tables listed before the FROM clause
7469  or tables listed in the FROM clause before the USING clause) may
7470  contain table names or aliases that must match unambiguously one,
7471  and only one, table in the target table list (table references list,
7472  after FROM/USING clause).
7473 
7474  @return Matching table, NULL otherwise.
7475 */
7476 
7477 static TABLE_LIST *multi_delete_table_match(LEX *lex, TABLE_LIST *tbl,
7478  TABLE_LIST *tables)
7479 {
7480  TABLE_LIST *match= NULL;
7481  DBUG_ENTER("multi_delete_table_match");
7482 
7483  for (TABLE_LIST *elem= tables; elem; elem= elem->next_local)
7484  {
7485  int cmp;
7486 
7487  if (tbl->is_fqtn && elem->is_alias)
7488  continue; /* no match */
7489  if (tbl->is_fqtn && elem->is_fqtn)
7490  cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) ||
7491  strcmp(tbl->db, elem->db);
7492  else if (elem->is_alias)
7493  cmp= my_strcasecmp(table_alias_charset, tbl->alias, elem->alias);
7494  else
7495  cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) ||
7496  strcmp(tbl->db, elem->db);
7497 
7498  if (cmp)
7499  continue;
7500 
7501  if (match)
7502  {
7503  my_error(ER_NONUNIQ_TABLE, MYF(0), elem->alias);
7504  DBUG_RETURN(NULL);
7505  }
7506 
7507  match= elem;
7508  }
7509 
7510  if (!match)
7511  my_error(ER_UNKNOWN_TABLE, MYF(0), tbl->table_name, "MULTI DELETE");
7512 
7513  DBUG_RETURN(match);
7514 }
7515 
7516 
7530 {
7531  TABLE_LIST *tables= lex->select_lex.table_list.first;
7532  TABLE_LIST *target_tbl;
7533  DBUG_ENTER("multi_delete_set_locks_and_link_aux_tables");
7534 
7535  for (target_tbl= lex->auxiliary_table_list.first;
7536  target_tbl; target_tbl= target_tbl->next_local)
7537  {
7538  /* All tables in aux_tables must be found in FROM PART */
7539  TABLE_LIST *walk= multi_delete_table_match(lex, target_tbl, tables);
7540  if (!walk)
7541  DBUG_RETURN(TRUE);
7542  if (!walk->derived)
7543  {
7544  target_tbl->table_name= walk->table_name;
7545  target_tbl->table_name_length= walk->table_name_length;
7546  }
7547  walk->updating= target_tbl->updating;
7548  walk->lock_type= target_tbl->lock_type;
7549  /* We can assume that tables to be deleted from are locked for write. */
7550  DBUG_ASSERT(walk->lock_type >= TL_WRITE_ALLOW_WRITE);
7551  walk->mdl_request.set_type(MDL_SHARED_WRITE);
7552  target_tbl->correspondent_table= walk; // Remember corresponding table
7553  }
7554  DBUG_RETURN(FALSE);
7555 }
7556 
7557 
7570 bool update_precheck(THD *thd, TABLE_LIST *tables)
7571 {
7572  DBUG_ENTER("update_precheck");
7573  if (thd->lex->select_lex.item_list.elements != thd->lex->value_list.elements)
7574  {
7575  my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
7576  DBUG_RETURN(TRUE);
7577  }
7578  DBUG_RETURN(check_one_table_access(thd, UPDATE_ACL, tables));
7579 }
7580 
7581 
7594 bool delete_precheck(THD *thd, TABLE_LIST *tables)
7595 {
7596  DBUG_ENTER("delete_precheck");
7597  if (check_one_table_access(thd, DELETE_ACL, tables))
7598  DBUG_RETURN(TRUE);
7599  /* Set privilege for the WHERE clause */
7600  tables->grant.want_privilege=(SELECT_ACL & ~tables->grant.privilege);
7601  DBUG_RETURN(FALSE);
7602 }
7603 
7604 
7617 bool insert_precheck(THD *thd, TABLE_LIST *tables)
7618 {
7619  LEX *lex= thd->lex;
7620  DBUG_ENTER("insert_precheck");
7621 
7622  /*
7623  Check that we have modify privileges for the first table and
7624  select privileges for the rest
7625  */
7626  ulong privilege= (INSERT_ACL |
7627  (lex->duplicates == DUP_REPLACE ? DELETE_ACL : 0) |
7628  (lex->value_list.elements ? UPDATE_ACL : 0));
7629 
7630  if (check_one_table_access(thd, privilege, tables))
7631  DBUG_RETURN(TRUE);
7632 
7633  if (lex->update_list.elements != lex->value_list.elements)
7634  {
7635  my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
7636  DBUG_RETURN(TRUE);
7637  }
7638  DBUG_RETURN(FALSE);
7639 }
7640 
7641 
7648 {
7649  TABLE_LIST *create_table= lex->query_tables;
7650 
7651  if (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE)
7652  create_table->open_type= OT_TEMPORARY_ONLY;
7653  else
7654  create_table->open_type= OT_BASE_ONLY;
7655 
7656  if (!lex->select_lex.item_list.elements)
7657  {
7658  /*
7659  Avoid opening and locking target table for ordinary CREATE TABLE
7660  or CREATE TABLE LIKE for write (unlike in CREATE ... SELECT we
7661  won't do any insertions in it anyway). Not doing this causes
7662  problems when running CREATE TABLE IF NOT EXISTS for already
7663  existing log table.
7664  */
7665  create_table->lock_type= TL_READ;
7666  }
7667 }
7668 
7669 
7683 bool create_table_precheck(THD *thd, TABLE_LIST *tables,
7685 {
7686  LEX *lex= thd->lex;
7687  SELECT_LEX *select_lex= &lex->select_lex;
7688  ulong want_priv;
7689  bool error= TRUE; // Error message is given
7690  DBUG_ENTER("create_table_precheck");
7691 
7692  /*
7693  Require CREATE [TEMPORARY] privilege on new table; for
7694  CREATE TABLE ... SELECT, also require INSERT.
7695  */
7696 
7697  want_priv= (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) ?
7698  CREATE_TMP_ACL :
7699  (CREATE_ACL | (select_lex->item_list.elements ? INSERT_ACL : 0));
7700 
7701  if (check_access(thd, want_priv, create_table->db,
7702  &create_table->grant.privilege,
7703  &create_table->grant.m_internal,
7704  0, 0))
7705  goto err;
7706 
7707  /* If it is a merge table, check privileges for merge children. */
7708  if (lex->create_info.merge_list.first)
7709  {
7710  /*
7711  The user must have (SELECT_ACL | UPDATE_ACL | DELETE_ACL) on the
7712  underlying base tables, even if there are temporary tables with the same
7713  names.
7714 
7715  From user's point of view, it might look as if the user must have these
7716  privileges on temporary tables to create a merge table over them. This is
7717  one of two cases when a set of privileges is required for operations on
7718  temporary tables (see also CREATE TABLE).
7719 
7720  The reason for this behavior stems from the following facts:
7721 
7722  - For merge tables, the underlying table privileges are checked only
7723  at CREATE TABLE / ALTER TABLE time.
7724 
7725  In other words, once a merge table is created, the privileges of
7726  the underlying tables can be revoked, but the user will still have
7727  access to the merge table (provided that the user has privileges on
7728  the merge table itself).
7729 
7730  - Temporary tables shadow base tables.
7731 
7732  I.e. there might be temporary and base tables with the same name, and
7733  the temporary table takes the precedence in all operations.
7734 
7735  - For temporary MERGE tables we do not track if their child tables are
7736  base or temporary. As result we can't guarantee that privilege check
7737  which was done in presence of temporary child will stay relevant later
7738  as this temporary table might be removed.
7739 
7740  If SELECT_ACL | UPDATE_ACL | DELETE_ACL privileges were not checked for
7741  the underlying *base* tables, it would create a security breach as in
7742  Bug#12771903.
7743  */
7744 
7745  if (check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL,
7746  lex->create_info.merge_list.first,
7747  FALSE, UINT_MAX, FALSE))
7748  goto err;
7749  }
7750 
7751  if (want_priv != CREATE_TMP_ACL &&
7752  check_grant(thd, want_priv, create_table, FALSE, 1, FALSE))
7753  goto err;
7754 
7755  if (select_lex->item_list.elements)
7756  {
7757  /* Check permissions for used tables in CREATE TABLE ... SELECT */
7758  if (tables && check_table_access(thd, SELECT_ACL, tables, FALSE,
7759  UINT_MAX, FALSE))
7760  goto err;
7761  }
7762  else if (lex->create_info.options & HA_LEX_CREATE_TABLE_LIKE)
7763  {
7764  if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE))
7765  goto err;
7766  }
7767  error= FALSE;
7768 
7769 err:
7770  DBUG_RETURN(error);
7771 }
7772 
7773 
7784 static bool lock_tables_precheck(THD *thd, TABLE_LIST *tables)
7785 {
7786  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
7787 
7788  for (TABLE_LIST *table= tables; table != first_not_own_table && table;
7789  table= table->next_global)
7790  {
7791  if (is_temporary_table(table))
7792  continue;
7793 
7794  if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, table,
7795  FALSE, 1, FALSE))
7796  return TRUE;
7797  }
7798 
7799  return FALSE;
7800 }
7801 
7802 
7813 Item *negate_expression(THD *thd, Item *expr)
7814 {
7815  Item *negated;
7816  if (expr->type() == Item::FUNC_ITEM &&
7817  ((Item_func *) expr)->functype() == Item_func::NOT_FUNC)
7818  {
7819  /* it is NOT(NOT( ... )) */
7820  Item *arg= ((Item_func *) expr)->arguments()[0];
7821  enum_parsing_place place= thd->lex->current_select->parsing_place;
7822  if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING)
7823  return arg;
7824  /*
7825  if it is not boolean function then we have to emulate value of
7826  not(not(a)), it will be a != 0
7827  */
7828  return new Item_func_ne(arg, new Item_int_0());
7829  }
7830 
7831  if ((negated= expr->neg_transformer(thd)) != 0)
7832  return negated;
7833  return new Item_func_not(expr);
7834 }
7835 
7844 void get_default_definer(THD *thd, LEX_USER *definer)
7845 {
7846  const Security_context *sctx= thd->security_ctx;
7847 
7848  definer->user.str= (char *) sctx->priv_user;
7849  definer->user.length= strlen(definer->user.str);
7850 
7851  definer->host.str= (char *) sctx->priv_host;
7852  definer->host.length= strlen(definer->host.str);
7853 
7854  definer->password= null_lex_str;
7855  definer->plugin= empty_lex_str;
7856  definer->auth= empty_lex_str;
7857  definer->uses_identified_with_clause= false;
7858  definer->uses_identified_by_clause= false;
7859  definer->uses_authentication_string_clause= false;
7860  definer->uses_identified_by_password_clause= false;
7861 }
7862 
7863 
7876 {
7877  LEX_USER *definer;
7878 
7879  if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER))))
7880  return 0;
7881 
7882  thd->get_definer(definer);
7883 
7884  return definer;
7885 }
7886 
7887 
7901 LEX_USER *create_definer(THD *thd, LEX_STRING *user_name, LEX_STRING *host_name)
7902 {
7903  LEX_USER *definer;
7904 
7905  /* Create and initialize. */
7906 
7907  if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER))))
7908  return 0;
7909 
7910  definer->user= *user_name;
7911  definer->host= *host_name;
7912  definer->password.str= NULL;
7913  definer->password.length= 0;
7914  definer->uses_authentication_string_clause= false;
7915  definer->uses_identified_by_clause= false;
7916  definer->uses_identified_by_password_clause= false;
7917  definer->uses_identified_with_clause= false;
7918  return definer;
7919 }
7920 
7921 
7935 {
7936  if (!user->user.str) // current_user
7937  {
7938  LEX_USER *default_definer= create_default_definer(thd);
7939  if (default_definer)
7940  {
7941  /*
7942  Inherit parser semantics from the statement in which the user parameter
7943  was used.
7944  This is needed because a st_lex_user is both used as a component in an
7945  AST and as a specifier for a particular user in the ACL subsystem.
7946  */
7947  default_definer->uses_authentication_string_clause=
7948  user->uses_authentication_string_clause;
7949  default_definer->uses_identified_by_clause=
7950  user->uses_identified_by_clause;
7951  default_definer->uses_identified_by_password_clause=
7952  user->uses_identified_by_password_clause;
7953  default_definer->uses_identified_with_clause=
7954  user->uses_identified_with_clause;
7955  default_definer->plugin.str= user->plugin.str;
7956  default_definer->plugin.length= user->plugin.length;
7957  default_definer->auth.str= user->auth.str;
7958  default_definer->auth.length= user->auth.length;
7959  return default_definer;
7960  }
7961  }
7962 
7963  return user;
7964 }
7965 
7966 
7983 bool check_string_byte_length(LEX_STRING *str, const char *err_msg,
7984  uint max_byte_length)
7985 {
7986  if (str->length <= max_byte_length)
7987  return FALSE;
7988 
7989  my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_byte_length);
7990 
7991  return TRUE;
7992 }
7993 
7994 
7995 /*
7996  Check that char length of a string does not exceed some limit.
7997 
7998  SYNOPSIS
7999  check_string_char_length()
8000  str string to be checked
8001  err_msg error message to be displayed if the string is too long
8002  max_char_length max length in symbols
8003  cs string charset
8004 
8005  RETURN
8006  FALSE the passed string is not longer than max_char_length
8007  TRUE the passed string is longer than max_char_length
8008 */
8009 
8010 
8011 bool check_string_char_length(LEX_STRING *str, const char *err_msg,
8012  uint max_char_length, const CHARSET_INFO *cs,
8013  bool no_error)
8014 {
8015  int well_formed_error;
8016  uint res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
8017  max_char_length, &well_formed_error);
8018 
8019  if (!well_formed_error && str->length == res)
8020  return FALSE;
8021 
8022  if (!no_error)
8023  {
8024  ErrConvString err(str->str, str->length, cs);
8025  my_error(ER_WRONG_STRING_LENGTH, MYF(0), err.ptr(), err_msg, max_char_length);
8026  }
8027  return TRUE;
8028 }
8029 
8030 
8031 /*
8032  Check if path does not contain mysql data home directory
8033  SYNOPSIS
8034  test_if_data_home_dir()
8035  dir directory
8036  conv_home_dir converted data home directory
8037  home_dir_len converted data home directory length
8038 
8039  RETURN VALUES
8040  0 ok
8041  1 error
8042 */
8043 C_MODE_START
8044 
8045 int test_if_data_home_dir(const char *dir)
8046 {
8047  char path[FN_REFLEN];
8048  int dir_len;
8049  DBUG_ENTER("test_if_data_home_dir");
8050 
8051  if (!dir)
8052  DBUG_RETURN(0);
8053 
8054  (void) fn_format(path, dir, "", "",
8055  (MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS));
8056  dir_len= strlen(path);
8057  if (mysql_unpacked_real_data_home_len<= dir_len)
8058  {
8059  if (dir_len > mysql_unpacked_real_data_home_len &&
8060  path[mysql_unpacked_real_data_home_len] != FN_LIBCHAR)
8061  DBUG_RETURN(0);
8062 
8063  if (lower_case_file_system)
8064  {
8065  if (!my_strnncoll(default_charset_info, (const uchar*) path,
8066  mysql_unpacked_real_data_home_len,
8067  (const uchar*) mysql_unpacked_real_data_home,
8068  mysql_unpacked_real_data_home_len))
8069  DBUG_RETURN(1);
8070  }
8071  else if (!memcmp(path, mysql_unpacked_real_data_home,
8072  mysql_unpacked_real_data_home_len))
8073  DBUG_RETURN(1);
8074  }
8075  DBUG_RETURN(0);
8076 }
8077 
8078 C_MODE_END
8079 
8080 
8093 {
8094  const char *name= str->str;
8095  const char *end= str->str + str->length;
8096  if (check_string_byte_length(str, ER(ER_HOSTNAME), HOSTNAME_LENGTH))
8097  return TRUE;
8098 
8099  while (name != end)
8100  {
8101  if (*name == '@')
8102  {
8103  my_printf_error(ER_UNKNOWN_ERROR,
8104  "Malformed hostname (illegal symbol: '%c')", MYF(0),
8105  *name);
8106  return TRUE;
8107  }
8108  name++;
8109  }
8110  return FALSE;
8111 }
8112 
8113 
8114 extern int MYSQLparse(void *thd); // from sql_yacc.cc
8115 
8116 
8130 bool parse_sql(THD *thd,
8131  Parser_state *parser_state,
8132  Object_creation_ctx *creation_ctx)
8133 {
8134  bool ret_value;
8135  DBUG_ASSERT(thd->m_parser_state == NULL);
8136  DBUG_ASSERT(thd->lex->m_sql_cmd == NULL);
8137 
8138  MYSQL_QUERY_PARSE_START(thd->query());
8139  /* Backup creation context. */
8140 
8141  Object_creation_ctx *backup_ctx= NULL;
8142 
8143  if (creation_ctx)
8144  backup_ctx= creation_ctx->set_n_backup(thd);
8145 
8146  /* Set parser state. */
8147 
8148  thd->m_parser_state= parser_state;
8149 
8150 #ifdef HAVE_PSI_STATEMENT_DIGEST_INTERFACE
8151  /* Start Digest */
8152  thd->m_parser_state->m_lip.m_digest_psi= MYSQL_DIGEST_START(thd->m_statement_psi);
8153 #endif
8154 
8155  /* Parse the query. */
8156 
8157  bool mysql_parse_status= MYSQLparse(thd) != 0;
8158 
8159  /*
8160  Check that if MYSQLparse() failed either thd->is_error() is set, or an
8161  internal error handler is set.
8162 
8163  The assert will not catch a situation where parsing fails without an
8164  error reported if an error handler exists. The problem is that the
8165  error handler might have intercepted the error, so thd->is_error() is
8166  not set. However, there is no way to be 100% sure here (the error
8167  handler might be for other errors than parsing one).
8168  */
8169 
8170  DBUG_ASSERT(!mysql_parse_status ||
8171  (mysql_parse_status && thd->is_error()) ||
8172  (mysql_parse_status && thd->get_internal_handler()));
8173 
8174  /* Reset parser state. */
8175 
8176  thd->m_parser_state= NULL;
8177 
8178  /* Restore creation context. */
8179 
8180  if (creation_ctx)
8181  creation_ctx->restore_env(thd, backup_ctx);
8182 
8183  /* That's it. */
8184 
8185  ret_value= mysql_parse_status || thd->is_fatal_error;
8186  MYSQL_QUERY_PARSE_DONE(ret_value);
8187  return ret_value;
8188 }
8189 
8213 const CHARSET_INFO*
8214 merge_charset_and_collation(const CHARSET_INFO *cs, const CHARSET_INFO *cl)
8215 {
8216  if (cl)
8217  {
8218  if (!my_charset_same(cs, cl))
8219  {
8220  my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0), cl->name, cs->csname);
8221  return NULL;
8222  }
8223  return cl;
8224  }
8225  return cs;
8226 }