sql_parse.cc 222 KB
Newer Older
Marc Alff's avatar
Marc Alff committed
1
/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
2

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3 4
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6

bk@work.mysql.com's avatar
bk@work.mysql.com committed
7 8 9 10
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
11

bk@work.mysql.com's avatar
bk@work.mysql.com committed
12 13 14 15
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

16
#define MYSQL_LEX 1
17
#include "my_global.h"
18 19 20
#include "sql_priv.h"
#include "unireg.h"                    // REQUIRED: for other includes
#include "sql_parse.h"        // sql_kill, *_precheck, *_prepare
21
#include "lock.h"             // try_transactional_lock,
22 23 24 25 26 27 28 29 30 31 32 33
                              // check_transactional_lock,
                              // set_handler_table_locks,
                              // lock_global_read_lock,
                              // make_global_read_lock_block_commit
#include "sql_base.h"         // find_temporary_tablesx
#include "sql_cache.h"        // QUERY_CACHE_FLAGS_SIZE, query_cache_*
#include "sql_show.h"         // mysqld_list_*, mysqld_show_*,
                              // calc_sum_of_all_status
#include "mysqld.h"
#include "sql_locale.h"                         // my_locale_en_US
#include "log.h"                                // flush_error_log
#include "sql_view.h"         // mysql_create_view, mysql_drop_view
34
#include "sql_delete.h"       // mysql_delete
35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include "sql_insert.h"       // mysql_insert
#include "sql_update.h"       // mysql_update, mysql_multi_update
#include "sql_partition.h"    // struct partition_info
#include "sql_db.h"           // mysql_change_db, mysql_create_db,
                              // mysql_rm_db, mysql_upgrade_db,
                              // mysql_alter_db,
                              // check_db_dir_existence,
                              // my_dbopt_cleanup
#include "sql_table.h"        // mysql_create_like_table,
                              // mysql_create_table,
                              // mysql_alter_table,
                              // mysql_recreate_table,
                              // mysql_backup_table,
                              // mysql_restore_table
49
#include "sql_reload.h"       // reload_acl_and_cache
50
#include "sql_admin.h"        // mysql_assign_to_keycache
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
#include "sql_connect.h"      // check_user,
                              // decrease_user_connections,
                              // thd_init_client_charset, check_mqh,
                              // reset_mqh
#include "sql_rename.h"       // mysql_rename_table
#include "sql_tablespace.h"   // mysql_alter_tablespace
#include "hostname.h"         // hostname_cache_refresh
#include "sql_acl.h"          // *_ACL, check_grant, is_acl_user,
                              // has_any_table_level_privileges,
                              // mysql_drop_user, mysql_rename_user,
                              // check_grant_routine,
                              // mysql_routine_grant,
                              // mysql_show_grants,
                              // sp_grant_privileges, ...
#include "sql_test.h"         // mysql_print_status
#include "sql_select.h"       // handle_select, mysql_select,
                              // mysql_explain_union
#include "sql_load.h"         // mysql_load
#include "sql_servers.h"      // create_servers, alter_servers,
                              // drop_servers, servers_reload
#include "sql_handler.h"      // mysql_ha_open, mysql_ha_close,
                              // mysql_ha_read
#include "sql_binlog.h"       // mysql_client_binlog_statement
#include "sql_do.h"           // mysql_do
#include "sql_help.h"         // mysqld_help
#include "rpl_constants.h"    // Incident, INCIDENT_LOST_EVENTS
#include "log_event.h"
78
#include "sql_repl.h"
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
79
#include "rpl_filter.h"
80
#include "repl_failsafe.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
81 82 83
#include <m_ctype.h>
#include <myisam.h>
#include <my_dir.h>
He Zhenxing's avatar
He Zhenxing committed
84
#include "rpl_handler.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
85

86
#include "sp_head.h"
87
#include "sp.h"
88
#include "sp_cache.h"
89
#include "events.h"
90
#include "sql_trigger.h"
Konstantin Osipov's avatar
Konstantin Osipov committed
91
#include "transaction.h"
92
#include "sql_audit.h"
93
#include "sql_prepare.h"
94
#include "debug_sync.h"
95
#include "probes_mysql.h"
96
#include "set_var.h"
97

98 99
#define FLAGSTR(V,F) ((V)&(F)?#F" ":"")

100 101 102 103 104
/**
  @defgroup Runtime_Environment Runtime Environment
  @{
*/

105 106 107 108 109 110
/* Used in error handling only */
#define SP_TYPE_STRING(LP) \
  ((LP)->sphead->m_type == TYPE_ENUM_FUNCTION ? "FUNCTION" : "PROCEDURE")
#define SP_COM_STRING(LP) \
  ((LP)->sql_command == SQLCOM_CREATE_SPFUNCTION || \
   (LP)->sql_command == SQLCOM_ALTER_FUNCTION || \
111
   (LP)->sql_command == SQLCOM_SHOW_CREATE_FUNC || \
112 113 114
   (LP)->sql_command == SQLCOM_DROP_FUNCTION ? \
   "FUNCTION" : "PROCEDURE")

115
static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables);
116
static void sql_kill(THD *thd, ulong id, bool only_kill_query);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
117

118
const char *any_db="*any*";	// Special symbol for check_access
bk@work.mysql.com's avatar
bk@work.mysql.com committed
119

andrey@example.com's avatar
andrey@example.com committed
120
const LEX_STRING command_name[]={
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
  { C_STRING_WITH_LEN("Sleep") },
  { C_STRING_WITH_LEN("Quit") },
  { C_STRING_WITH_LEN("Init DB") },
  { C_STRING_WITH_LEN("Query") },
  { C_STRING_WITH_LEN("Field List") },
  { C_STRING_WITH_LEN("Create DB") },
  { C_STRING_WITH_LEN("Drop DB") },
  { C_STRING_WITH_LEN("Refresh") },
  { C_STRING_WITH_LEN("Shutdown") },
  { C_STRING_WITH_LEN("Statistics") },
  { C_STRING_WITH_LEN("Processlist") },
  { C_STRING_WITH_LEN("Connect") },
  { C_STRING_WITH_LEN("Kill") },
  { C_STRING_WITH_LEN("Debug") },
  { C_STRING_WITH_LEN("Ping") },
  { C_STRING_WITH_LEN("Time") },
  { C_STRING_WITH_LEN("Delayed insert") },
  { C_STRING_WITH_LEN("Change user") },
  { C_STRING_WITH_LEN("Binlog Dump") },
  { C_STRING_WITH_LEN("Table Dump") },
  { C_STRING_WITH_LEN("Connect Out") },
  { C_STRING_WITH_LEN("Register Slave") },
  { C_STRING_WITH_LEN("Prepare") },
  { C_STRING_WITH_LEN("Execute") },
  { C_STRING_WITH_LEN("Long Data") },
  { C_STRING_WITH_LEN("Close stmt") },
  { C_STRING_WITH_LEN("Reset stmt") },
  { C_STRING_WITH_LEN("Set option") },
  { C_STRING_WITH_LEN("Fetch") },
  { C_STRING_WITH_LEN("Daemon") },
  { C_STRING_WITH_LEN("Error") }  // Last command number
bk@work.mysql.com's avatar
bk@work.mysql.com committed
152 153
};

154
const char *xa_state_names[]={
155
  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED", "ROLLBACK ONLY"
156 157
};

158

monty@mysql.com's avatar
monty@mysql.com committed
159
#ifdef HAVE_REPLICATION
160 161
/**
  Returns true if all tables should be ignored.
162
*/
163 164
inline bool all_tables_not_ok(THD *thd, TABLE_LIST *tables)
{
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
165 166
  return rpl_filter->is_on() && tables && !thd->spcont &&
         !rpl_filter->tables_ok(thd->db, tables);
167
}
monty@mysql.com's avatar
monty@mysql.com committed
168
#endif
169 170


171 172 173 174 175
static bool some_non_temp_table_to_be_updated(THD *thd, TABLE_LIST *tables)
{
  for (TABLE_LIST *table= tables; table; table= table->next_global)
  {
    DBUG_ASSERT(table->db && table->table_name);
176
    if (table->updating && !find_temporary_table(thd, table))
177 178 179 180 181
      return 1;
  }
  return 0;
}

182

Konstantin Osipov's avatar
Konstantin Osipov committed
183 184 185 186 187 188 189
/*
  Implicitly commit a active transaction if statement requires so.

  @param thd    Thread handle.
  @param mask   Bitmask used for the SQL command match.

*/
190
static bool stmt_causes_implicit_commit(THD *thd, uint mask)
Konstantin Osipov's avatar
Konstantin Osipov committed
191 192
{
  LEX *lex= thd->lex;
193 194
  bool skip= FALSE;
  DBUG_ENTER("stmt_causes_implicit_commit");
Konstantin Osipov's avatar
Konstantin Osipov committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214

  if (!(sql_command_flags[lex->sql_command] & mask))
    DBUG_RETURN(FALSE);

  switch (lex->sql_command) {
  case SQLCOM_DROP_TABLE:
    skip= lex->drop_temporary;
    break;
  case SQLCOM_ALTER_TABLE:
  case SQLCOM_CREATE_TABLE:
    /* If CREATE TABLE of non-temporary table, do implicit commit */
    skip= (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE);
    break;
  case SQLCOM_SET_OPTION:
    skip= lex->autocommit ? FALSE : TRUE;
    break;
  default:
    break;
  }

215
  DBUG_RETURN(!skip);
Konstantin Osipov's avatar
Konstantin Osipov committed
216 217 218
}


219 220 221 222
/**
  Mark all commands that somehow changes a table.

  This is used to check number of updates / hour.
kent@mysql.com's avatar
kent@mysql.com committed
223 224 225

  sql_command is actually set to SQLCOM_END sometimes
  so we need the +1 to include it in the array.
226

227
  See COMMAND_FLAG_xxx for different type of commands
228 229
     2  - query that returns meaningful ROW_COUNT() -
          a number of modified rows
230 231
*/

232
uint sql_command_flags[SQLCOM_END+1];
Konstantin Osipov's avatar
Konstantin Osipov committed
233
uint server_command_flags[COM_END+1];
234 235 236

void init_update_queries(void)
{
Konstantin Osipov's avatar
Konstantin Osipov committed
237 238 239 240 241 242 243 244 245 246 247 248
  /* Initialize the server command flags array. */
  memset(server_command_flags, 0, sizeof(server_command_flags));

  server_command_flags[COM_STATISTICS]= CF_SKIP_QUERY_ID | CF_SKIP_QUESTIONS;
  server_command_flags[COM_PING]=       CF_SKIP_QUERY_ID | CF_SKIP_QUESTIONS;
  server_command_flags[COM_STMT_PREPARE]= CF_SKIP_QUESTIONS;
  server_command_flags[COM_STMT_CLOSE]=   CF_SKIP_QUESTIONS;
  server_command_flags[COM_STMT_RESET]=   CF_SKIP_QUESTIONS;

  /* Initialize the sql command flags array. */
  memset(sql_command_flags, 0, sizeof(sql_command_flags));

249 250 251 252 253 254 255 256 257 258
  /*
    In general, DDL statements do not generate row events and do not go
    through a cache before being written to the binary log. However, the
    CREATE TABLE...SELECT is an exception because it may generate row
    events. For that reason,  the SQLCOM_CREATE_TABLE  which represents
    a CREATE TABLE, including the CREATE TABLE...SELECT, has the
    CF_CAN_GENERATE_ROW_EVENTS flag. The distinction between a regular
    CREATE TABLE and the CREATE TABLE...SELECT is made in other parts of
    the code, in particular in the Query_log_event's constructor.
  */
Konstantin Osipov's avatar
Konstantin Osipov committed
259
  sql_command_flags[SQLCOM_CREATE_TABLE]=   CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
260
                                            CF_AUTO_COMMIT_TRANS |
261
                                            CF_CAN_GENERATE_ROW_EVENTS;
Konstantin Osipov's avatar
Konstantin Osipov committed
262 263
  sql_command_flags[SQLCOM_CREATE_INDEX]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_TABLE]=    CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
264
                                            CF_AUTO_COMMIT_TRANS;
Konstantin Osipov's avatar
Konstantin Osipov committed
265
  sql_command_flags[SQLCOM_TRUNCATE]=       CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
266
                                            CF_AUTO_COMMIT_TRANS;
Konstantin Osipov's avatar
Konstantin Osipov committed
267
  sql_command_flags[SQLCOM_DROP_TABLE]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
268
  sql_command_flags[SQLCOM_LOAD]=           CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
269
                                            CF_CAN_GENERATE_ROW_EVENTS;
270 271 272 273
  sql_command_flags[SQLCOM_CREATE_DB]=      CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_DB]=        CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_DB_UPGRADE]= CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_DB]=       CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
Konstantin Osipov's avatar
Konstantin Osipov committed
274 275 276 277 278
  sql_command_flags[SQLCOM_RENAME_TABLE]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_INDEX]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_CREATE_VIEW]=    CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_VIEW]=      CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
279 280
  sql_command_flags[SQLCOM_CREATE_TRIGGER]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_TRIGGER]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
Konstantin Osipov's avatar
Konstantin Osipov committed
281 282 283
  sql_command_flags[SQLCOM_CREATE_EVENT]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_EVENT]=    CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_EVENT]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
284

285
  sql_command_flags[SQLCOM_UPDATE]=	    CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
286
                                            CF_CAN_GENERATE_ROW_EVENTS;
287
  sql_command_flags[SQLCOM_UPDATE_MULTI]=   CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
288
                                            CF_CAN_GENERATE_ROW_EVENTS;
289
  sql_command_flags[SQLCOM_INSERT]=	    CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
290
                                            CF_CAN_GENERATE_ROW_EVENTS;
291
  sql_command_flags[SQLCOM_INSERT_SELECT]=  CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
292
                                            CF_CAN_GENERATE_ROW_EVENTS;
293
  sql_command_flags[SQLCOM_DELETE]=         CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
294
                                            CF_CAN_GENERATE_ROW_EVENTS;
295
  sql_command_flags[SQLCOM_DELETE_MULTI]=   CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
296 297 298 299 300 301 302
                                            CF_CAN_GENERATE_ROW_EVENTS;
  sql_command_flags[SQLCOM_REPLACE]=        CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS;
  sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS;
  sql_command_flags[SQLCOM_SELECT]=         CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS;
303
  sql_command_flags[SQLCOM_SET_OPTION]=     CF_REEXECUTION_FRAGILE | CF_AUTO_COMMIT_TRANS;
304 305
  sql_command_flags[SQLCOM_DO]=             CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS;
306 307 308 309 310 311 312

  sql_command_flags[SQLCOM_SHOW_STATUS_PROC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_STATUS]=      CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_DATABASES]=   CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_TRIGGERS]=    CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_EVENTS]=      CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_OPEN_TABLES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
313
  sql_command_flags[SQLCOM_SHOW_PLUGINS]=     CF_STATUS_COMMAND;
314 315 316 317 318
  sql_command_flags[SQLCOM_SHOW_FIELDS]=      CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_KEYS]=        CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_VARIABLES]=   CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_CHARSETS]=    CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_COLLATIONS]=  CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
319 320
  sql_command_flags[SQLCOM_SHOW_NEW_MASTER]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_BINLOGS]=     CF_STATUS_COMMAND;
321 322 323
  sql_command_flags[SQLCOM_SHOW_SLAVE_HOSTS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_BINLOG_EVENTS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_STORAGE_ENGINES]= CF_STATUS_COMMAND;
324
  sql_command_flags[SQLCOM_SHOW_AUTHORS]=     CF_STATUS_COMMAND;
325
  sql_command_flags[SQLCOM_SHOW_CONTRIBUTORS]= CF_STATUS_COMMAND;
326 327 328
  sql_command_flags[SQLCOM_SHOW_PRIVILEGES]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_WARNS]=       CF_STATUS_COMMAND | CF_DIAGNOSTIC_STMT;
  sql_command_flags[SQLCOM_SHOW_ERRORS]=      CF_STATUS_COMMAND | CF_DIAGNOSTIC_STMT;
329 330 331 332
  sql_command_flags[SQLCOM_SHOW_ENGINE_STATUS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_ENGINE_MUTEX]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_ENGINE_LOGS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PROCESSLIST]= CF_STATUS_COMMAND;
333 334
  sql_command_flags[SQLCOM_SHOW_GRANTS]=      CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_DB]=   CF_STATUS_COMMAND;
335
  sql_command_flags[SQLCOM_SHOW_CREATE]=  CF_STATUS_COMMAND;
336
  sql_command_flags[SQLCOM_SHOW_MASTER_STAT]= CF_STATUS_COMMAND;
337
  sql_command_flags[SQLCOM_SHOW_SLAVE_STAT]=  CF_STATUS_COMMAND;
338 339
  sql_command_flags[SQLCOM_SHOW_CREATE_PROC]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_FUNC]= CF_STATUS_COMMAND;
340
  sql_command_flags[SQLCOM_SHOW_CREATE_TRIGGER]=  CF_STATUS_COMMAND;
341 342 343 344 345 346 347
  sql_command_flags[SQLCOM_SHOW_STATUS_FUNC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_PROC_CODE]=   CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_FUNC_CODE]=   CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_EVENT]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PROFILES]=    CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PROFILE]=     CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_BINLOG_BASE64_EVENT]= CF_STATUS_COMMAND;
348 349

   sql_command_flags[SQLCOM_SHOW_TABLES]=       (CF_STATUS_COMMAND |
350 351
                                                 CF_SHOW_TABLE_COMMAND |
                                                 CF_REEXECUTION_FRAGILE);
352
  sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND |
353 354
                                                CF_SHOW_TABLE_COMMAND |
                                                CF_REEXECUTION_FRAGILE);
355

356

357 358 359
  sql_command_flags[SQLCOM_CREATE_USER]=       CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_RENAME_USER]=       CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_DROP_USER]=         CF_CHANGES_DATA;
360 361 362
  sql_command_flags[SQLCOM_GRANT]=             CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_REVOKE]=            CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_OPTIMIZE]=          CF_CHANGES_DATA;
Konstantin Osipov's avatar
Konstantin Osipov committed
363
  sql_command_flags[SQLCOM_CREATE_FUNCTION]=   CF_CHANGES_DATA;
364 365 366 367 368 369
  sql_command_flags[SQLCOM_CREATE_PROCEDURE]=  CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_CREATE_SPFUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_PROCEDURE]=    CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_FUNCTION]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_PROCEDURE]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_FUNCTION]=    CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
370 371 372
  sql_command_flags[SQLCOM_INSTALL_PLUGIN]=    CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_UNINSTALL_PLUGIN]=  CF_CHANGES_DATA;

373 374 375 376 377 378
  /*
    The following is used to preserver CF_ROW_COUNT during the
    a CALL or EXECUTE statement, so the value generated by the
    last called (or executed) statement is preserved.
    See mysql_execute_command() for how CF_ROW_COUNT is used.
  */
379 380 381
  sql_command_flags[SQLCOM_CALL]=      CF_REEXECUTION_FRAGILE |
                                       CF_CAN_GENERATE_ROW_EVENTS;
  sql_command_flags[SQLCOM_EXECUTE]=   CF_CAN_GENERATE_ROW_EVENTS;
382 383 384 385 386

  /*
    The following admin table operations are allowed
    on log tables.
  */
387 388 389
  sql_command_flags[SQLCOM_REPAIR]=    CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_OPTIMIZE]|= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ANALYZE]=   CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS;
390
  sql_command_flags[SQLCOM_CHECK]=     CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS;
391 392 393 394 395 396 397 398

  sql_command_flags[SQLCOM_CREATE_USER]|=       CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_USER]|=         CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_RENAME_USER]|=       CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_REVOKE_ALL]=         CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_REVOKE]|=            CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_GRANT]|=             CF_AUTO_COMMIT_TRANS;

Konstantin Osipov's avatar
Konstantin Osipov committed
399 400 401 402
  sql_command_flags[SQLCOM_ASSIGN_TO_KEYCACHE]= CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_PRELOAD_KEYS]=       CF_AUTO_COMMIT_TRANS;

  sql_command_flags[SQLCOM_FLUSH]=              CF_AUTO_COMMIT_TRANS;
403
  sql_command_flags[SQLCOM_RESET]=              CF_AUTO_COMMIT_TRANS;
404 405 406
  sql_command_flags[SQLCOM_CREATE_SERVER]=      CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_SERVER]=       CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_SERVER]=        CF_AUTO_COMMIT_TRANS;
407 408
}

409 410 411 412 413 414
bool sqlcom_can_generate_row_events(const THD *thd)
{
  return (sql_command_flags[thd->lex->sql_command] &
          CF_CAN_GENERATE_ROW_EVENTS);
}
 
415 416
bool is_update_query(enum enum_sql_command command)
{
kent@mysql.com's avatar
kent@mysql.com committed
417
  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
418
  return (sql_command_flags[command] & CF_CHANGES_DATA) != 0;
419
}
420

421 422 423 424 425 426 427 428 429 430
/**
  Check if a sql command is allowed to write to log tables.
  @param command The SQL command
  @return true if writing is allowed
*/
bool is_log_table_write_query(enum enum_sql_command command)
{
  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
  return (sql_command_flags[command] & CF_WRITE_LOGS_COMMAND) != 0;
}
431

432
void execute_init_command(THD *thd, LEX_STRING *init_command,
Marc Alff's avatar
Marc Alff committed
433
                          mysql_rwlock_t *var_lock)
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
434 435 436 437
{
  Vio* save_vio;
  ulong save_client_capabilities;

Marc Alff's avatar
Marc Alff committed
438
  mysql_rwlock_rdlock(var_lock);
439 440
  if (!init_command->length)
  {
Marc Alff's avatar
Marc Alff committed
441
    mysql_rwlock_unlock(var_lock);
442 443 444 445 446 447 448 449 450 451
    return;
  }

  /*
    copy the value under a lock, and release the lock.
    init_command has to be executed without a lock held,
    as it may try to change itself
  */
  size_t len= init_command->length;
  char *buf= thd->strmake(init_command->str, len);
Marc Alff's avatar
Marc Alff committed
452
  mysql_rwlock_unlock(var_lock);
453

454
#if defined(ENABLED_PROFILING)
455
  thd->profiling.start_new_query();
456
  thd->profiling.set_query_source(buf, len);
457 458
#endif

459
  thd_proc_info(thd, "Execution of init_command");
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
460 461
  save_client_capabilities= thd->client_capabilities;
  thd->client_capabilities|= CLIENT_MULTI_QUERIES;
462 463 464 465
  /*
    We don't need return result of execution to client side.
    To forbid this we should set thd->net.vio to 0.
  */
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
466 467
  save_vio= thd->net.vio;
  thd->net.vio= 0;
468
  dispatch_command(COM_QUERY, thd, buf, len);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
469 470
  thd->client_capabilities= save_client_capabilities;
  thd->net.vio= save_vio;
471

472
#if defined(ENABLED_PROFILING)
473 474
  thd->profiling.finish_current_query();
#endif
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
475 476 477
}


478
static void handle_bootstrap_impl(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
479
{
Marc Alff's avatar
Marc Alff committed
480
  MYSQL_FILE *file= bootstrap_file;
481
  char *buff;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
482

483 484
  DBUG_ENTER("handle_bootstrap");

hf@deer.(none)'s avatar
hf@deer.(none) committed
485
#ifndef EMBEDDED_LIBRARY
486 487
  pthread_detach_this_thread();
  thd->thread_stack= (char*) &thd;
hf@deer.(none)'s avatar
hf@deer.(none) committed
488
#endif /* EMBEDDED_LIBRARY */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
489

490
  thd_proc_info(thd, 0);
491 492
  thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME));
  thd->security_ctx->priv_user[0]= thd->security_ctx->priv_host[0]=0;
493 494 495 496 497 498
  /*
    Make the "client" handle multiple results. This is necessary
    to enable stored procedures with SELECTs and Dynamic SQL
    in init-file.
  */
  thd->client_capabilities|= CLIENT_MULTI_RESULTS;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
499

500
  buff= (char*) thd->net.buff;
501
  thd->init_for_queries();
Marc Alff's avatar
Marc Alff committed
502
  while (mysql_file_fgets(buff, thd->net.max_packet, file))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
503
  {
Marc Alff's avatar
Marc Alff committed
504 505
    char *query;
    /* strlen() can't be deleted because mysql_file_fgets() doesn't return length */
506
    ulong length= (ulong) strlen(buff);
Marc Alff's avatar
Marc Alff committed
507
    while (buff[length-1] != '\n' && !mysql_file_feof(file))
508 509 510 511 512 513 514 515
    {
      /*
        We got only a part of the current string. Will try to increase
        net buffer then read the rest of the current string.
      */
      /* purecov: begin tested */
      if (net_realloc(&(thd->net), 2 * thd->net.max_packet))
      {
516
        thd->protocol->end_statement();
517
        bootstrap_error= 1;
518 519 520
        break;
      }
      buff= (char*) thd->net.buff;
Marc Alff's avatar
Marc Alff committed
521
      mysql_file_fgets(buff + length, thd->net.max_packet - length, file);
522 523 524
      length+= (ulong) strlen(buff + length);
      /* purecov: end */
    }
525
    if (bootstrap_error)
526
      break;                                    /* purecov: inspected */
monty@mishka.local's avatar
monty@mishka.local committed
527

528
    while (length && (my_isspace(thd->charset(), buff[length-1]) ||
529
                      buff[length-1] == ';'))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
530 531
      length--;
    buff[length]=0;
532 533 534 535 536

    /* Skip lines starting with delimiter */
    if (strncmp(buff, STRING_WITH_LEN("delimiter")) == 0)
      continue;

Gleb Shchepa's avatar
Gleb Shchepa committed
537 538 539
    query= (char *) thd->memdup_w_gap(buff, length + 1,
                                      thd->db_length + 1 +
                                      QUERY_CACHE_FLAGS_SIZE);
540
    thd->set_query_and_id(query, length, thd->charset(), next_query_id());
541
    DBUG_PRINT("query",("%-.4096s",thd->query()));
542
#if defined(ENABLED_PROFILING)
543
    thd->profiling.start_new_query();
544
    thd->profiling.set_query_source(thd->query(), length);
545 546
#endif

547 548 549 550
    /*
      We don't need to obtain LOCK_thread_count here because in bootstrap
      mode we have only one thread.
    */
551
    thd->set_time();
552 553 554 555 556 557 558 559
    Parser_state parser_state;
    if (parser_state.init(thd, thd->query(), length))
    {
      thd->protocol->end_statement();
      bootstrap_error= 1;
      break;
    }

560
    mysql_parse(thd, thd->query(), length, &parser_state);
561

562
    bootstrap_error= thd->is_error();
563
    thd->protocol->end_statement();
564

565
#if defined(ENABLED_PROFILING)
566 567 568
    thd->profiling.finish_current_query();
#endif

569
    if (bootstrap_error)
570 571
      break;

572
    free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
573
    free_root(&thd->transaction.mem_root,MYF(MY_KEEP_PREALLOC));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
574
  }
575

576 577 578 579 580 581 582 583 584 585 586 587 588 589
  DBUG_VOID_RETURN;
}


/**
  Execute commands from bootstrap_file.

  Used when creating the initial grant tables.
*/

pthread_handler_t handle_bootstrap(void *arg)
{
  THD *thd=(THD*) arg;

Marc Alff's avatar
Marc Alff committed
590 591 592 593 594 595 596 597
  mysql_thread_set_psi_id(thd->thread_id);

  do_handle_bootstrap(thd);
  return 0;
}

void do_handle_bootstrap(THD *thd)
{
598 599 600 601 602 603 604 605 606 607 608 609 610
  /* The following must be called before DBUG_ENTER */
  thd->thread_stack= (char*) &thd;
  if (my_thread_init() || thd->store_globals())
  {
#ifndef EMBEDDED_LIBRARY
    close_connection(thd, ER_OUT_OF_RESOURCES, 1);
#endif
    thd->fatal_error();
    goto end;
  }

  handle_bootstrap_impl(thd);

611
end:
612 613 614 615
  net_end(&thd->net);
  thd->cleanup();
  delete thd;

hf@deer.(none)'s avatar
hf@deer.(none) committed
616
#ifndef EMBEDDED_LIBRARY
Marc Alff's avatar
Marc Alff committed
617
  mysql_mutex_lock(&LOCK_thread_count);
618
  thread_count--;
619
  in_bootstrap= FALSE;
Marc Alff's avatar
Marc Alff committed
620 621
  mysql_cond_broadcast(&COND_thread_count);
  mysql_mutex_unlock(&LOCK_thread_count);
622 623
  my_thread_end();
  pthread_exit(0);
hf@deer.(none)'s avatar
hf@deer.(none) committed
624
#endif
625

Marc Alff's avatar
Marc Alff committed
626
  return;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
627 628 629
}


630 631 632 633 634 635 636 637 638 639 640 641 642 643
/* This works because items are allocated with sql_alloc() */

void free_items(Item *item)
{
  Item *next;
  DBUG_ENTER("free_items");
  for (; item ; item=next)
  {
    next=item->next;
    item->delete_self();
  }
  DBUG_VOID_RETURN;
}

644 645 646 647
/**
   This works because items are allocated with sql_alloc().
   @note The function also handles null pointers (empty list).
*/
648 649
void cleanup_items(Item *item)
{
monty@mysql.com's avatar
monty@mysql.com committed
650
  DBUG_ENTER("cleanup_items");  
651 652
  for (; item ; item=item->next)
    item->cleanup();
monty@mysql.com's avatar
monty@mysql.com committed
653
  DBUG_VOID_RETURN;
654 655
}

656
#ifndef EMBEDDED_LIBRARY
657

658
/**
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
659
  Read one command from connection and execute it (query or simple command).
660
  This function is called in loop from thread function.
661 662 663

  For profiling to work, it must never be called recursively.

664
  @retval
665
    0  success
666
  @retval
667 668 669
    1  request of thread shutdown (see dispatch_command() description)
*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
670 671
bool do_command(THD *thd)
{
672
  bool return_value;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
673
  char *packet= 0;
674
  ulong packet_length;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
675
  NET *net= &thd->net;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
676 677 678
  enum enum_server_command command;
  DBUG_ENTER("do_command");

679 680 681 682
  /*
    indicator of uninitialized lex => normal flow of errors handling
    (see my_message_sql)
  */
683
  thd->lex->current_select= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
684

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
685 686 687 688
  /*
    This thread will do a blocking read from the client which
    will be interrupted when the next command is received from
    the client, the connection is closed or "net_wait_timeout"
689
    number of seconds has passed.
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
690
  */
691
  my_net_set_read_timeout(net, thd->variables.net_wait_timeout);
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
692

693 694 695 696
  /*
    XXX: this code is here only to clear possible errors of init_connect. 
    Consider moving to init_connect() instead.
  */
697
  thd->clear_error();				// Clear error message
Marc Alff's avatar
Marc Alff committed
698
  thd->stmt_da->reset_diagnostics_area();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
699 700

  net_new_transaction(net);
701

702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
  /*
    Synchronization point for testing of KILL_CONNECTION.
    This sync point can wait here, to simulate slow code execution
    between the last test of thd->killed and blocking in read().

    The goal of this test is to verify that a connection does not
    hang, if it is killed at this point of execution.
    (Bug#37780 - main.kill fails randomly)

    Note that the sync point wait itself will be terminated by a
    kill. In this case it consumes a condition broadcast, but does
    not change anything else. The consumed broadcast should not
    matter here, because the read/recv() below doesn't use it.
  */
  DEBUG_SYNC(thd, "before_do_command_net_read");

Konstantin Osipov's avatar
Konstantin Osipov committed
718
  if ((packet_length= my_net_read(net)) == packet_error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
719
  {
720 721 722
    DBUG_PRINT("info",("Got error %d reading command from socket %s",
		       net->error,
		       vio_description(net->vio)));
723

724
    /* Check if we can continue without closing the connection */
725

726 727
    /* The error must be set. */
    DBUG_ASSERT(thd->is_error());
728
    thd->protocol->end_statement();
729

730
    if (net->error != 3)
731
    {
732
      return_value= TRUE;                       // We have to close it.
733 734
      goto out;
    }
735

736
    net->error= 0;
737 738
    return_value= FALSE;
    goto out;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
739
  }
740 741 742 743 744 745 746 747 748 749 750

  packet= (char*) net->read_pos;
  /*
    'packet_length' contains length of data, as it was stored in packet
    header. In case of malformed header, my_net_read returns zero.
    If packet_length is not zero, my_net_read ensures that the returned
    number of bytes was actually read from network.
    There is also an extra safety measure in my_net_read:
    it sets packet[packet_length]= 0, but only for non-zero packets.
  */
  if (packet_length == 0)                       /* safety */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
751
  {
752 753 754
    /* Initialize with COM_SLEEP packet */
    packet[0]= (uchar) COM_SLEEP;
    packet_length= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
755
  }
756 757 758 759 760 761 762 763 764 765 766
  /* Do not rely on my_net_read, extra safety against programming errors. */
  packet[packet_length]= '\0';                  /* safety */

  command= (enum enum_server_command) (uchar) packet[0];

  if (command >= COM_END)
    command= COM_END;				// Wrong command

  DBUG_PRINT("info",("Command on %s = %d (%s)",
                     vio_description(net->vio), command,
                     command_name[command].str));
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
767 768

  /* Restore read timeout value */
769
  my_net_set_read_timeout(net, thd->variables.net_read_timeout);
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
770

771
  DBUG_ASSERT(packet_length);
772 773 774 775
  return_value= dispatch_command(command, thd, packet+1, (uint) (packet_length-1));

out:
  DBUG_RETURN(return_value);
776
}
777
#endif  /* EMBEDDED_LIBRARY */
778

779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
/**
  @brief Determine if an attempt to update a non-temporary table while the
    read-only option was enabled has been made.

  This is a helper function to mysql_execute_command.

  @note SQLCOM_MULTI_UPDATE is an exception and delt with elsewhere.

  @see mysql_execute_command
  @returns Status code
    @retval TRUE The statement should be denied.
    @retval FALSE The statement isn't updating any relevant tables.
*/

static my_bool deny_updates_if_read_only_option(THD *thd,
                                                TABLE_LIST *all_tables)
{
  DBUG_ENTER("deny_updates_if_read_only_option");

  if (!opt_readonly)
    DBUG_RETURN(FALSE);

  LEX *lex= thd->lex;

  const my_bool user_is_super=
    ((ulong)(thd->security_ctx->master_access & SUPER_ACL) ==
     (ulong)SUPER_ACL);

  if (user_is_super)
    DBUG_RETURN(FALSE);

810
  if (!(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA))
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
    DBUG_RETURN(FALSE);

  /* Multi update is an exception and is dealt with later. */
  if (lex->sql_command == SQLCOM_UPDATE_MULTI)
    DBUG_RETURN(FALSE);

  const my_bool create_temp_tables= 
    (lex->sql_command == SQLCOM_CREATE_TABLE) &&
    (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE);

  const my_bool drop_temp_tables= 
    (lex->sql_command == SQLCOM_DROP_TABLE) &&
    lex->drop_temporary;

  const my_bool update_real_tables=
    some_non_temp_table_to_be_updated(thd, all_tables) &&
    !(create_temp_tables || drop_temp_tables);


  const my_bool create_or_drop_databases=
    (lex->sql_command == SQLCOM_CREATE_DB) ||
    (lex->sql_command == SQLCOM_DROP_DB);

  if (update_real_tables || create_or_drop_databases)
  {
      /*
        An attempt was made to modify one or more non-temporary tables.
      */
      DBUG_RETURN(TRUE);
  }


  /* Assuming that only temporary tables are modified. */
  DBUG_RETURN(FALSE);
}
846

847 848
/**
  Perform one connection-level (COM_XXXX) command.
849

850 851 852 853 854 855 856 857
  @param command         type of command to perform
  @param thd             connection handle
  @param packet          data for the command, packet is always null-terminated
  @param packet_length   length of packet + 1 (to show that data is
                         null-terminated) except for COM_SLEEP, where it
                         can be zero.

  @todo
858 859 860
    set thd->lex->sql_command to SQLCOM_END here.
  @todo
    The following has to be changed to an 8 byte integer
861 862

  @retval
863
    0   ok
864
  @retval
865 866 867
    1   request of thread shutdown, i. e. if command is
        COM_QUIT/COM_SHUTDOWN
*/
868 869 870 871
bool dispatch_command(enum enum_server_command command, THD *thd,
		      char* packet, uint packet_length)
{
  NET *net= &thd->net;
872
  bool error= 0;
873
  DBUG_ENTER("dispatch_command");
874
  DBUG_PRINT("info",("packet: '%*.s'; command: %d", packet_length, packet, command));
875

Konstantin Osipov's avatar
Konstantin Osipov committed
876 877 878
#if defined(ENABLED_PROFILING)
  thd->profiling.start_new_query();
#endif
879 880 881 882
  MYSQL_COMMAND_START(thd->thread_id, command,
                      thd->security_ctx->priv_user,
                      (char *) thd->security_ctx->host_or_ip);
  
883
  thd->command=command;
884
  /*
885 886
    Commands which always take a long time are logged into
    the slow log only if opt_log_slow_admin_statements is set.
887
  */
888
  thd->enable_slow_log= TRUE;
889
  thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
890
  thd->set_time();
891 892 893 894 895 896 897 898 899 900 901 902
  if (!thd->is_valid_time())
  {
    /*
     If the time has got past 2038 we need to shut this server down
     We do this by making sure every command is a shutdown and we 
     have enough privileges to shut the server down

     TODO: remove this when we have full 64 bit my_time_t support
    */
    thd->security_ctx->master_access|= SHUTDOWN_ACL;
    command= COM_SHUTDOWN;
  }
903
  thd->set_query_id(get_query_id());
Konstantin Osipov's avatar
Konstantin Osipov committed
904
  if (!(server_command_flags[command] & CF_SKIP_QUERY_ID))
905
    next_query_id();
906
  inc_thread_running();
907

Konstantin Osipov's avatar
Konstantin Osipov committed
908 909 910
  if (!(server_command_flags[command] & CF_SKIP_QUESTIONS))
    statistic_increment(thd->status_var.questions, &LOCK_status);

911 912 913 914 915
  /**
    Clear the set of flags that are expected to be cleared at the
    beginning of each command.
  */
  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
916
  switch (command) {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
917
  case COM_INIT_DB:
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
918 919
  {
    LEX_STRING tmp;
920
    status_var_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB]);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
921
    thd->convert_string(&tmp, system_charset_info,
922
			packet, packet_length, thd->charset());
923
    if (!mysql_change_db(thd, &tmp, FALSE))
924
    {
925
      general_log_write(thd, command, thd->db, thd->db_length);
926
      my_ok(thd);
927
    }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
928 929
    break;
  }
930
#ifdef HAVE_REPLICATION
931 932
  case COM_REGISTER_SLAVE:
  {
933
    if (!register_slave(thd, (uchar*)packet, packet_length))
934
      my_ok(thd);
935 936
    break;
  }
937
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
938 939
  case COM_CHANGE_USER:
  {
940
    status_var_increment(thd->status_var.com_other);
941

942
    thd->change_user();
943
    thd->clear_error();                         // if errors from rollback
944

945 946
    /* acl_authenticate() takes the data from net->read_pos */
    net->read_pos= (uchar*)packet;
947

948 949 950
    uint save_db_length= thd->db_length;
    char *save_db= thd->db;
    USER_CONN *save_user_connect= thd->user_connect;
951
    Security_context save_security_ctx= *thd->security_ctx;
952 953 954 955 956 957
    CHARSET_INFO *save_character_set_client=
      thd->variables.character_set_client;
    CHARSET_INFO *save_collation_connection=
      thd->variables.collation_connection;
    CHARSET_INFO *save_character_set_results=
      thd->variables.character_set_results;
958

959
    if (acl_authenticate(thd, 0, packet_length))
960
    {
961
      my_free(thd->security_ctx->user);
962
      *thd->security_ctx= save_security_ctx;
963
      thd->user_connect= save_user_connect;
964 965 966 967 968
      thd->reset_db (save_db, save_db_length);
      thd->variables.character_set_client= save_character_set_client;
      thd->variables.collation_connection= save_collation_connection;
      thd->variables.character_set_results= save_character_set_results;
      thd->update_charset();
969 970 971
    }
    else
    {
972
#ifndef NO_EMBEDDED_ACCESS_CHECKS
973
      /* we've authenticated new user */
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
974 975
      if (save_user_connect)
	decrease_user_connections(save_user_connect);
976
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
977 978
      my_free(save_db);
      my_free(save_security_ctx.user);
979
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
980 981
    break;
  }
982
  case COM_STMT_EXECUTE:
983
  {
984
    mysqld_stmt_execute(thd, packet, packet_length);
985 986
    break;
  }
987
  case COM_STMT_FETCH:
988
  {
989
    mysqld_stmt_fetch(thd, packet, packet_length);
990 991
    break;
  }
992
  case COM_STMT_SEND_LONG_DATA:
993
  {
994
    mysql_stmt_get_longdata(thd, packet, packet_length);
995 996
    break;
  }
997
  case COM_STMT_PREPARE:
998
  {
999
    mysqld_stmt_prepare(thd, packet, packet_length);
1000 1001
    break;
  }
1002
  case COM_STMT_CLOSE:
1003
  {
1004
    mysqld_stmt_close(thd, packet);
1005 1006
    break;
  }
1007
  case COM_STMT_RESET:
1008
  {
1009
    mysqld_stmt_reset(thd, packet);
1010 1011
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1012 1013
  case COM_QUERY:
  {
1014 1015
    if (alloc_query(thd, packet, packet_length))
      break;					// fatal error is set
1016
    MYSQL_QUERY_START(thd->query(), thd->thread_id,
1017 1018 1019
                      (char *) (thd->db ? thd->db : ""),
                      thd->security_ctx->priv_user,
                      (char *) thd->security_ctx->host_or_ip);
1020
    char *packet_end= thd->query() + thd->query_length();
1021
    /* 'b' stands for 'buffer' parameter', special for 'my_snprintf' */
1022

1023 1024
    general_log_write(thd, command, thd->query(), thd->query_length());
    DBUG_PRINT("query",("%-.4096s",thd->query()));
1025
#if defined(ENABLED_PROFILING)
1026
    thd->profiling.set_query_source(thd->query(), thd->query_length());
1027
#endif
1028 1029 1030
    Parser_state parser_state;
    if (parser_state.init(thd, thd->query(), thd->query_length()))
      break;
1031

1032
    mysql_parse(thd, thd->query(), thd->query_length(), &parser_state);
1033

1034 1035
    while (!thd->killed && (parser_state.m_lip.found_semicolon != NULL) &&
           ! thd->is_error())
1036
    {
1037
      /*
1038 1039
        Multiple queries exits, execute them individually
      */
1040 1041 1042 1043
      char *beginning_of_next_stmt= (char*) parser_state.m_lip.found_semicolon;

      /* Finalize server status flags after executing a statement. */
      thd->update_server_status();
1044 1045
      thd->protocol->end_statement();
      query_cache_end_of_result(thd);
1046
      ulong length= (ulong)(packet_end - beginning_of_next_stmt);
1047

1048
      log_slow_statement(thd);
1049

1050
      /* Remove garbage at start of query */
1051
      while (length > 0 && my_isspace(thd->charset(), *beginning_of_next_stmt))
1052
      {
1053
        beginning_of_next_stmt++;
1054 1055
        length--;
      }
1056

1057 1058 1059 1060 1061
      if (MYSQL_QUERY_DONE_ENABLED())
      {
        MYSQL_QUERY_DONE(thd->is_error());
      }

1062
#if defined(ENABLED_PROFILING)
1063 1064 1065 1066 1067
      thd->profiling.finish_current_query();
      thd->profiling.start_new_query("continuing");
      thd->profiling.set_query_source(beginning_of_next_stmt, length);
#endif

1068
      MYSQL_QUERY_START(beginning_of_next_stmt, thd->thread_id,
1069 1070 1071 1072
                        (char *) (thd->db ? thd->db : ""),
                        thd->security_ctx->priv_user,
                        (char *) thd->security_ctx->host_or_ip);

1073 1074
      thd->set_query_and_id(beginning_of_next_stmt, length,
                            thd->charset(), next_query_id());
1075 1076 1077 1078
      /*
        Count each statement from the client.
      */
      statistic_increment(thd->status_var.questions, &LOCK_status);
1079
      thd->set_time(); /* Reset the query start time. */
1080
      parser_state.reset(beginning_of_next_stmt, length);
1081
      /* TODO: set thd->lex->sql_command to SQLCOM_END here */
1082
      mysql_parse(thd, beginning_of_next_stmt, length, &parser_state);
1083 1084
    }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1085 1086 1087
    DBUG_PRINT("info",("query ready"));
    break;
  }
1088
  case COM_FIELD_LIST:				// This isn't actually needed
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1089
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1090 1091
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1092 1093 1094
    break;
#else
  {
1095
    char *fields, *packet_end= packet + packet_length, *arg_end;
1096
    /* Locked closure of all tables */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1097
    TABLE_LIST table_list;
1098 1099 1100 1101 1102 1103
    LEX_STRING table_name;
    LEX_STRING db;
    /*
      SHOW statements should not add the used tables to the list of tables
      used in a transaction.
    */
1104
    MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
1105

1106
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
1107
    if (thd->copy_db_to(&db.str, &db.length))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1108
      break;
1109 1110 1111 1112
    /*
      We have name + wildcard in packet, separated by endzero
    */
    arg_end= strend(packet);
Ramil Kalimullin's avatar
Ramil Kalimullin committed
1113
    uint arg_length= arg_end - packet;
1114

1115 1116 1117 1118 1119 1120
    /* Check given table name length. */
    if (arg_length >= packet_length || arg_length > NAME_LEN)
    {
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
      break;
    }
1121
    thd->convert_string(&table_name, system_charset_info,
1122
			packet, arg_length, thd->charset());
1123
    if (check_table_name(table_name.str, table_name.length, FALSE))
1124 1125
    {
      /* this is OK due to convert_string() null-terminating the string */
1126
      my_error(ER_WRONG_TABLE_NAME, MYF(0), table_name.str);
1127 1128
      break;
    }
1129
    packet= arg_end + 1;
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
    mysql_reset_thd_for_next_command(thd);
    lex_start(thd);
    /* Must be before we init the table list. */
    if (lower_case_table_names)
      table_name.length= my_casedn_str(files_charset_info, table_name.str);
    table_list.init_one_table(db.str, db.length, table_name.str,
                              table_name.length, table_name.str, TL_READ);
    /*
      Init TABLE_LIST members necessary when the undelrying
      table is view.
    */
    table_list.select_lex= &(thd->lex->select_lex);
    thd->lex->
      select_lex.table_list.link_in_list(&table_list,
                                         &table_list.next_local);
    thd->lex->add_to_query_tables(&table_list);
1146

1147
    if (is_infoschema_db(table_list.db, table_list.db_length))
1148 1149 1150 1151 1152 1153
    {
      ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, table_list.alias);
      if (schema_table)
        table_list.schema_table= schema_table;
    }

Gleb Shchepa's avatar
Gleb Shchepa committed
1154 1155
    uint query_length= (uint) (packet_end - packet); // Don't count end \0
    if (!(fields= (char *) thd->memdup(packet, query_length + 1)))
1156
      break;
1157
    thd->set_query(fields, query_length);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1158
    general_log_print(thd, command, "%s %s", table_list.table_name, fields);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1159

1160 1161
    if (check_table_access(thd, SELECT_ACL, &table_list,
                           TRUE, UINT_MAX, FALSE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1162
      break;
1163 1164 1165 1166
    /*
      Turn on an optimization relevant if the underlying table
      is a view: do not fill derived tables.
    */
1167
    thd->lex->sql_command= SQLCOM_SHOW_FIELDS;
1168

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1169
    mysqld_list_fields(thd,&table_list,fields);
1170
    thd->lex->unit.cleanup();
1171 1172 1173 1174 1175
    /* No need to rollback statement transaction, it's not started. */
    DBUG_ASSERT(thd->transaction.stmt.is_empty());
    close_thread_tables(thd);
    thd->mdl_context.rollback_to_savepoint(mdl_savepoint);

1176
    thd->cleanup_after_query();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1177 1178 1179 1180
    break;
  }
#endif
  case COM_QUIT:
1181
    /* We don't calculate statistics for this command */
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1182
    general_log_print(thd, command, NullS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1183
    net->error=0;				// Don't give 'abort' message
Marc Alff's avatar
Marc Alff committed
1184
    thd->stmt_da->disable_status();              // Don't send anything back
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1185 1186
    error=TRUE;					// End server
    break;
1187
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1188 1189
  case COM_BINLOG_DUMP:
    {
monty@mysql.com's avatar
monty@mysql.com committed
1190 1191 1192 1193
      ulong pos;
      ushort flags;
      uint32 slave_server_id;

1194
      status_var_increment(thd->status_var.com_other);
1195
      thd->enable_slow_log= opt_log_slow_admin_statements;
1196
      if (check_global_access(thd, REPL_SLAVE_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1197
	break;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1198

1199
      /* TODO: The following has to be changed to an 8 byte integer */
1200 1201
      pos = uint4korr(packet);
      flags = uint2korr(packet + 4);
1202
      thd->server_id=0; /* avoid suicide */
1203
      if ((slave_server_id= uint4korr(packet+6))) // mysqlbinlog.server_id==0
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
1204
	kill_zombie_dump_threads(slave_server_id);
1205
      thd->server_id = slave_server_id;
monty@mysql.com's avatar
monty@mysql.com committed
1206

cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1207
      general_log_print(thd, command, "Log: '%s'  Pos: %ld", packet+10,
monty@mysql.com's avatar
monty@mysql.com committed
1208
                      (long) pos);
1209
      mysql_binlog_send(thd, thd->strdup(packet + 10), (my_off_t) pos, flags);
1210
      unregister_slave(thd,1,1);
monty@mysql.com's avatar
monty@mysql.com committed
1211
      /*  fake COM_QUIT -- if we get here, the thread needs to terminate */
1212
      error = TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1213 1214
      break;
    }
1215
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1216
  case COM_REFRESH:
1217 1218
  {
    bool not_used;
1219
    status_var_increment(thd->status_var.com_stat[SQLCOM_FLUSH]);
1220
    ulong options= (ulong) (uchar) packet[0];
Konstantin Osipov's avatar
Konstantin Osipov committed
1221
    if (trans_commit_implicit(thd))
Konstantin Osipov's avatar
Konstantin Osipov committed
1222
      break;
1223
    thd->mdl_context.release_transactional_locks();
1224
    if (check_global_access(thd,RELOAD_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1225
      break;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1226
    general_log_print(thd, command, NullS);
1227
#ifndef DBUG_OFF
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
    bool debug_simulate= FALSE;
    DBUG_EXECUTE_IF("simulate_detached_thread_refresh", debug_simulate= TRUE;);
    if (debug_simulate)
    {
      /*
        Simulate a reload without a attached thread session.
        Provides a environment similar to that of when the
        server receives a SIGHUP signal and reloads caches
        and flushes tables.
      */
      bool res;
      my_pthread_setspecific_ptr(THR_THD, NULL);
      res= reload_acl_and_cache(NULL, options | REFRESH_FAST,
                                NULL, &not_used);
      my_pthread_setspecific_ptr(THR_THD, thd);
Konstantin Osipov's avatar
Konstantin Osipov committed
1243 1244
      if (res)
        break;
1245
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
1246
    else
1247
#endif
Konstantin Osipov's avatar
Konstantin Osipov committed
1248 1249
    if (reload_acl_and_cache(thd, options, (TABLE_LIST*) 0, &not_used))
      break;
Konstantin Osipov's avatar
Konstantin Osipov committed
1250
    if (trans_commit_implicit(thd))
Konstantin Osipov's avatar
Konstantin Osipov committed
1251
      break;
1252
    close_thread_tables(thd);
1253
    thd->mdl_context.release_transactional_locks();
Konstantin Osipov's avatar
Konstantin Osipov committed
1254
    my_ok(thd);
1255 1256
    break;
  }
1257
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1258
  case COM_SHUTDOWN:
1259
  {
1260
    status_var_increment(thd->status_var.com_other);
1261
    if (check_global_access(thd,SHUTDOWN_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1262
      break; /* purecov: inspected */
1263
    /*
1264
      If the client is < 4.1.3, it is going to send us no argument; then
1265
      packet_length is 0, packet[0] is the end 0 of the packet. Note that
1266 1267
      SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in
      packet[0].
1268
    */
1269 1270 1271 1272 1273
    enum mysql_enum_shutdown_level level;
    if (!thd->is_valid_time())
      level= SHUTDOWN_DEFAULT;
    else
      level= (enum mysql_enum_shutdown_level) (uchar) packet[0];
1274 1275 1276 1277 1278 1279 1280
    if (level == SHUTDOWN_DEFAULT)
      level= SHUTDOWN_WAIT_ALL_BUFFERS; // soon default will be configurable
    else if (level != SHUTDOWN_WAIT_ALL_BUFFERS)
    {
      my_error(ER_NOT_SUPPORTED_YET, MYF(0), "this shutdown level");
      break;
    }
1281
    DBUG_PRINT("quit",("Got shutdown command for level %u", level));
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1282
    general_log_print(thd, command, NullS);
1283
    my_eof(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1284 1285 1286
    kill_mysql();
    error=TRUE;
    break;
1287
  }
1288
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1289 1290
  case COM_STATISTICS:
  {
1291 1292
    STATUS_VAR current_global_status_var;
    ulong uptime;
1293
    uint length __attribute__((unused));
1294
    ulonglong queries_per_second1000;
1295 1296
    char buff[250];
    uint buff_len= sizeof(buff);
1297

1298
    general_log_print(thd, command, NullS);
1299
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]);
1300
    calc_sum_of_all_status(&current_global_status_var);
1301 1302 1303 1304 1305
    if (!(uptime= (ulong) (thd->start_time - server_start_time)))
      queries_per_second1000= 0;
    else
      queries_per_second1000= thd->query_id * LL(1000) / uptime;

1306
    length= my_snprintf(buff, buff_len - 1,
1307 1308
                        "Uptime: %lu  Threads: %d  Questions: %lu  "
                        "Slow queries: %lu  Opens: %lu  Flush tables: %lu  "
1309
                        "Open tables: %u  Queries per second avg: %u.%u",
1310 1311 1312 1313 1314 1315
                        uptime,
                        (int) thread_count, (ulong) thd->query_id,
                        current_global_status_var.long_query_count,
                        current_global_status_var.opened_tables,
                        refresh_version,
                        cached_open_tables(),
1316 1317
                        (uint) (queries_per_second1000 / 1000),
                        (uint) (queries_per_second1000 % 1000));
1318 1319
#ifdef EMBEDDED_LIBRARY
    /* Store the buffer in permanent memory */
1320
    my_ok(thd, 0, 0, buff);
1321
#else
Konstantin Osipov's avatar
Konstantin Osipov committed
1322 1323
    (void) my_net_write(net, (uchar*) buff, length);
    (void) net_flush(net);
Marc Alff's avatar
Marc Alff committed
1324
    thd->stmt_da->disable_status();
hf@deer.(none)'s avatar
hf@deer.(none) committed
1325
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1326 1327 1328
    break;
  }
  case COM_PING:
1329
    status_var_increment(thd->status_var.com_other);
1330
    my_ok(thd);				// Tell client we are alive
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1331 1332
    break;
  case COM_PROCESS_INFO:
1333
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]);
1334 1335
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd, PROCESS_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1336
      break;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1337
    general_log_print(thd, command, NullS);
hf@deer.(none)'s avatar
hf@deer.(none) committed
1338
    mysqld_list_processes(thd,
1339 1340
			  thd->security_ctx->master_access & PROCESS_ACL ? 
			  NullS : thd->security_ctx->priv_user, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1341 1342 1343
    break;
  case COM_PROCESS_KILL:
  {
1344
    status_var_increment(thd->status_var.com_stat[SQLCOM_KILL]);
1345
    ulong id=(ulong) uint4korr(packet);
1346
    sql_kill(thd,id,false);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1347 1348
    break;
  }
1349 1350
  case COM_SET_OPTION:
  {
1351
    status_var_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION]);
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
1352 1353 1354 1355
    uint opt_command= uint2korr(packet);

    switch (opt_command) {
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON:
1356
      thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
1357
      my_eof(thd);
1358
      break;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
1359
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF:
1360
      thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
1361
      my_eof(thd);
1362 1363
      break;
    default:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1364
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1365 1366 1367 1368
      break;
    }
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1369
  case COM_DEBUG:
1370
    status_var_increment(thd->status_var.com_other);
1371
    if (check_global_access(thd, SUPER_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1372
      break;					/* purecov: inspected */
1373
    mysql_print_status();
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1374
    general_log_print(thd, command, NullS);
1375
    my_eof(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1376 1377 1378 1379 1380
    break;
  case COM_SLEEP:
  case COM_CONNECT:				// Impossible here
  case COM_TIME:				// Impossible from client
  case COM_DELAYED_INSERT:
1381
  case COM_END:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1382
  default:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1383
    my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1384 1385
    break;
  }
1386 1387 1388
  DBUG_ASSERT(thd->derived_tables == NULL &&
              (thd->open_tables == NULL ||
               (thd->locked_tables_mode == LTM_LOCK_TABLES)));
1389

1390 1391
  /* Finalize server status flags after executing a command. */
  thd->update_server_status();
1392
  thd->protocol->end_statement();
1393
  query_cache_end_of_result(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1394

1395
  if (!thd->is_error() && !thd->killed_errno())
1396
    mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_RESULT, 0, 0);
1397

1398
  log_slow_statement(thd);
1399

1400
  thd_proc_info(thd, "cleaning up");
1401
  thd->reset_query();
1402
  thd->command=COM_SLEEP;
1403
  dec_thread_running();
1404
  thd_proc_info(thd, 0);
1405 1406
  thd->packet.shrink(thd->variables.net_buffer_length);	// Reclaim some memory
  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
1407

Konstantin Osipov's avatar
Konstantin Osipov committed
1408 1409 1410
#if defined(ENABLED_PROFILING)
  thd->profiling.finish_current_query();
#endif
1411 1412
  if (MYSQL_QUERY_DONE_ENABLED() || MYSQL_COMMAND_DONE_ENABLED())
  {
1413
    int res __attribute__((unused));
1414 1415 1416 1417 1418 1419 1420
    res= (int) thd->is_error();
    if (command == COM_QUERY)
    {
      MYSQL_QUERY_DONE(res);
    }
    MYSQL_COMMAND_DONE(res);
  }
1421 1422 1423 1424
  DBUG_RETURN(error);
}


1425
void log_slow_statement(THD *thd)
1426
{
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1427
  DBUG_ENTER("log_slow_statement");
1428 1429 1430 1431 1432 1433 1434

  /*
    The following should never be true with our current code base,
    but better to keep this here so we don't accidently try to log a
    statement in a trigger or stored function
  */
  if (unlikely(thd->in_sub_stmt))
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1435
    DBUG_VOID_RETURN;                           // Don't set time for sub stmt
1436

1437 1438
  /*
    Do not log administrative statements unless the appropriate option is
1439
    set.
1440
  */
1441
  if (thd->enable_slow_log)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1442
  {
1443
    ulonglong end_utime_of_query= thd->current_utime();
1444
    thd_proc_info(thd, "logging slow query");
1445

1446
    if (((thd->server_status & SERVER_QUERY_WAS_SLOW) ||
1447 1448
         ((thd->server_status &
           (SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED)) &&
1449 1450
          opt_log_queries_not_using_indexes &&
           !(sql_command_flags[thd->lex->sql_command] & CF_STATUS_COMMAND))) &&
1451
        thd->examined_row_count >= thd->variables.min_examined_row_limit)
1452
    {
1453
      thd_proc_info(thd, "logging slow query");
1454
      thd->status_var.long_query_count++;
1455 1456
      slow_log_print(thd, thd->query(), thd->query_length(), 
                     end_utime_of_query);
1457
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1458
  }
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1459
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1460 1461
}

1462

1463
/**
1464 1465 1466 1467 1468 1469 1470
  Create a TABLE_LIST object for an INFORMATION_SCHEMA table.

    This function is used in the parser to convert a SHOW or DESCRIBE
    table_name command to a SELECT from INFORMATION_SCHEMA.
    It prepares a SELECT_LEX and a TABLE_LIST object to represent the
    given command as a SELECT parse tree.

1471 1472 1473 1474 1475 1476 1477
  @param thd              thread handle
  @param lex              current lex
  @param table_ident      table alias if it's used
  @param schema_table_idx the type of the INFORMATION_SCHEMA table to be
                          created

  @note
1478 1479 1480 1481
    Due to the way this function works with memory and LEX it cannot
    be used outside the parser (parse tree transformations outside
    the parser break PS and SP).

1482
  @retval
1483
    0                 success
1484
  @retval
1485 1486 1487 1488
    1                 out of memory or SHOW commands are not allowed
                      in this version of the server.
*/

1489 1490 1491
int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident,
                         enum enum_schema_tables schema_table_idx)
{
1492
  SELECT_LEX *schema_select_lex= NULL;
1493
  DBUG_ENTER("prepare_schema_table");
1494

1495
  switch (schema_table_idx) {
1496 1497
  case SCH_SCHEMATA:
#if defined(DONT_ALLOW_SHOW_COMMANDS)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1498 1499
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0));   /* purecov: inspected */
1500 1501 1502 1503
    DBUG_RETURN(1);
#else
    break;
#endif
1504

1505 1506 1507
  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
1508
  case SCH_TRIGGERS:
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1509
  case SCH_EVENTS:
1510
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1511 1512
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1513 1514 1515
    DBUG_RETURN(1);
#else
    {
1516
      LEX_STRING db;
1517
      size_t dummy;
1518
      if (lex->select_lex.db == NULL &&
1519
          lex->copy_db_to(&lex->select_lex.db, &dummy))
1520
      {
1521
        DBUG_RETURN(1);
1522
      }
1523 1524 1525
      schema_select_lex= new SELECT_LEX();
      db.str= schema_select_lex->db= lex->select_lex.db;
      schema_select_lex->table_list.first= NULL;
1526
      db.length= strlen(db.str);
1527

1528
      if (check_db_name(&db))
1529
      {
1530
        my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
1531 1532 1533 1534 1535 1536 1537
        DBUG_RETURN(1);
      }
      break;
    }
#endif
  case SCH_COLUMNS:
  case SCH_STATISTICS:
1538
  {
1539
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1540 1541
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1542 1543
    DBUG_RETURN(1);
#else
1544 1545 1546 1547 1548 1549
    DBUG_ASSERT(table_ident);
    TABLE_LIST **query_tables_last= lex->query_tables_last;
    schema_select_lex= new SELECT_LEX();
    /* 'parent_lex' is used in init_query() so it must be before it. */
    schema_select_lex->parent_lex= lex;
    schema_select_lex->init_query();
1550 1551
    if (!schema_select_lex->add_table_to_list(thd, table_ident, 0, 0, TL_READ,
                                              MDL_SHARED_READ))
1552 1553 1554 1555
      DBUG_RETURN(1);
    lex->query_tables_last= query_tables_last;
    break;
  }
1556
#endif
1557 1558 1559 1560 1561
  case SCH_PROFILES:
    /* 
      Mark this current profiling record to be discarded.  We don't
      wish to have SHOW commands show up in profiling.
    */
1562
#if defined(ENABLED_PROFILING)
1563
    thd->profiling.discard_current_query();
1564 1565
#endif
    break;
1566 1567 1568
  case SCH_OPEN_TABLES:
  case SCH_VARIABLES:
  case SCH_STATUS:
1569 1570
  case SCH_PROCEDURES:
  case SCH_CHARSETS:
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1571
  case SCH_ENGINES:
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
  case SCH_COLLATIONS:
  case SCH_COLLATION_CHARACTER_SET_APPLICABILITY:
  case SCH_USER_PRIVILEGES:
  case SCH_SCHEMA_PRIVILEGES:
  case SCH_TABLE_PRIVILEGES:
  case SCH_COLUMN_PRIVILEGES:
  case SCH_TABLE_CONSTRAINTS:
  case SCH_KEY_COLUMN_USAGE:
  default:
    break;
  }
  
  SELECT_LEX *select_lex= lex->current_select;
  if (make_schema_select(thd, select_lex, schema_table_idx))
  {
    DBUG_RETURN(1);
  }
1589
  TABLE_LIST *table_list= select_lex->table_list.first;
1590
  table_list->schema_select_lex= schema_select_lex;
1591
  table_list->schema_table_reformed= 1;
1592 1593 1594 1595
  DBUG_RETURN(0);
}


1596 1597 1598
/**
  Read query from packet and store in thd->query.
  Used in COM_QUERY and COM_STMT_PREPARE.
1599 1600

    Sets the following THD variables:
1601 1602
  - query
  - query_length
1603

1604
  @retval
1605
    FALSE ok
1606
  @retval
1607
    TRUE  error;  In this case thd->fatal_error is set
1608 1609
*/

1610
bool alloc_query(THD *thd, const char *packet, uint packet_length)
1611
{
1612
  char *query;
1613
  /* Remove garbage at start and end of query */
1614
  while (packet_length > 0 && my_isspace(thd->charset(), packet[0]))
1615 1616 1617 1618
  {
    packet++;
    packet_length--;
  }
1619
  const char *pos= packet + packet_length;     // Point at end null
peter@mysql.com's avatar
peter@mysql.com committed
1620
  while (packet_length > 0 &&
1621
	 (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1])))
1622 1623 1624 1625 1626
  {
    pos--;
    packet_length--;
  }
  /* We must allocate some extra memory for query cache */
1627 1628 1629 1630 1631 1632 1633
  if (! (query= (char*) thd->memdup_w_gap(packet,
                                          packet_length,
                                          1 + thd->db_length +
                                          QUERY_CACHE_FLAGS_SIZE)))
      return TRUE;
  query[packet_length]= '\0';
  thd->set_query(query, packet_length);
1634 1635 1636 1637

  /* Reclaim some memory */
  thd->packet.shrink(thd->variables.net_buffer_length);
  thd->convert_buffer.shrink(thd->variables.net_buffer_length);
1638

1639
  return FALSE;
1640 1641
}

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
static void reset_one_shot_variables(THD *thd) 
{
  thd->variables.character_set_client=
    global_system_variables.character_set_client;
  thd->variables.collation_connection=
    global_system_variables.collation_connection;
  thd->variables.collation_database=
    global_system_variables.collation_database;
  thd->variables.collation_server=
    global_system_variables.collation_server;
  thd->update_charset();
  thd->variables.time_zone=
    global_system_variables.time_zone;
1655
  thd->variables.lc_time_names= &my_locale_en_US;
1656 1657 1658
  thd->one_shot_set= 0;
}

1659

1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
static
bool sp_process_definer(THD *thd)
{
  DBUG_ENTER("sp_process_definer");

  LEX *lex= thd->lex;

  /*
    If the definer is not specified, this means that CREATE-statement missed
    DEFINER-clause. DEFINER-clause can be missed in two cases:

      - The user submitted a statement w/o the clause. This is a normal
        case, we should assign CURRENT_USER as definer.

      - Our slave received an updated from the master, that does not
        replicate definer for stored rountines. We should also assign
        CURRENT_USER as definer here, but also we should mark this routine
        as NON-SUID. This is essential for the sake of backward
        compatibility.

        The problem is the slave thread is running under "special" user (@),
        that actually does not exist. In the older versions we do not fail
        execution of a stored routine if its definer does not exist and
        continue the execution under the authorization of the invoker
        (BUG#13198). And now if we try to switch to slave-current-user (@),
        we will fail.

        Actually, this leads to the inconsistent state of master and
        slave (different definers, different SUID behaviour), but it seems,
        this is the best we can do.
  */

  if (!lex->definer)
  {
    Query_arena original_arena;
    Query_arena *ps_arena= thd->activate_stmt_arena_if_needed(&original_arena);

    lex->definer= create_default_definer(thd);

    if (ps_arena)
      thd->restore_active_arena(ps_arena, &original_arena);

    /* Error has been already reported. */
    if (lex->definer == NULL)
      DBUG_RETURN(TRUE);

1706
    if (thd->slave_thread && lex->sphead)
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
      lex->sphead->m_chistics->suid= SP_IS_NOT_SUID;
  }
  else
  {
    /*
      If the specified definer differs from the current user, we
      should check that the current user has SUPER privilege (in order
      to create a stored routine under another user one must have
      SUPER privilege).
    */
    if ((strcmp(lex->definer->user.str, thd->security_ctx->priv_user) ||
         my_strcasecmp(system_charset_info, lex->definer->host.str,
                       thd->security_ctx->priv_host)) &&
        check_global_access(thd, SUPER_ACL))
    {
      my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "SUPER");
      DBUG_RETURN(TRUE);
    }
  }

  /* Check that the specified definer exists. Emit a warning if not. */

#ifndef NO_EMBEDDED_ACCESS_CHECKS
  if (!is_acl_user(lex->definer->host.str, lex->definer->user.str))
  {
    push_warning_printf(thd,
                        MYSQL_ERROR::WARN_LEVEL_NOTE,
                        ER_NO_SUCH_USER,
                        ER(ER_NO_SUCH_USER),
                        lex->definer->user.str,
                        lex->definer->host.str);
  }
#endif /* NO_EMBEDDED_ACCESS_CHECKS */

  DBUG_RETURN(FALSE);
}


1745 1746
/**
  Execute command saved in thd and lex->sql_command.
1747

1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
  @param thd                       Thread handle

  @todo
    - Invalidate the table in the query cache if something changed
    after unlocking when changes become visible.
    TODO: this is workaround. right way will be move invalidating in
    the unlock procedure.
    - TODO: use check_change_password()

  @retval
1758
    FALSE       OK
1759
  @retval
1760 1761
    TRUE        Error
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1762

1763
int
1764
mysql_execute_command(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1765
{
1766
  int res= FALSE;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
1767
  int  up_result= 0;
1768
  LEX  *lex= thd->lex;
monty@mysql.com's avatar
monty@mysql.com committed
1769
  /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1770
  SELECT_LEX *select_lex= &lex->select_lex;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1771
  /* first table of first SELECT_LEX */
1772
  TABLE_LIST *first_table= select_lex->table_list.first;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1773 1774 1775
  /* list of all tables in query */
  TABLE_LIST *all_tables;
  /* most outer SELECT_LEX_UNIT of query */
1776
  SELECT_LEX_UNIT *unit= &lex->unit;
1777 1778 1779 1780
#ifdef HAVE_REPLICATION
  /* have table map for update for multi-update statement (BUG#37051) */
  bool have_table_map_for_update= FALSE;
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1781
  DBUG_ENTER("mysql_execute_command");
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1782 1783 1784
#ifdef WITH_PARTITION_STORAGE_ENGINE
  thd->work_part_info= 0;
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1785

1786
  DBUG_ASSERT(thd->transaction.stmt.is_empty() || thd->in_sub_stmt);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
  /*
    In many cases first table of main SELECT_LEX have special meaning =>
    check that it is first table in global list and relink it first in 
    queries_tables list if it is necessary (we need such relinking only
    for queries with subqueries in select list, in this case tables of
    subqueries will go to global list first)

    all_tables will differ from first_table only if most upper SELECT_LEX
    do not contain tables.

    Because of above in place where should be at least one table in most
    outer SELECT_LEX we have following check:
    DBUG_ASSERT(first_table == all_tables);
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
  */
  lex->first_lists_tables_same();
1803
  /* should be assigned after making first tables same */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1804
  all_tables= lex->query_tables;
1805 1806
  /* set context for commands which do not use setup_tables */
  select_lex->
1807
    context.resolve_in_table_list_only(select_lex->
1808
                                       table_list.first);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1809

1810 1811 1812 1813 1814 1815
  /*
    Reset warning count for each query that uses tables
    A better approach would be to reset this for any commands
    that is not a SHOW command or a select that only access local
    variables, but for now this is probably good enough.
  */
Marc Alff's avatar
Marc Alff committed
1816 1817 1818 1819 1820 1821 1822 1823
  if ((sql_command_flags[lex->sql_command] & CF_DIAGNOSTIC_STMT) != 0)
    thd->warning_info->set_read_only(TRUE);
  else
  {
    thd->warning_info->set_read_only(FALSE);
    if (all_tables)
      thd->warning_info->opt_clear_warning_info(thd->query_id);
  }
1824

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1825
#ifdef HAVE_REPLICATION
1826
  if (unlikely(thd->slave_thread))
1827
  {
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
    if (lex->sql_command == SQLCOM_DROP_TRIGGER)
    {
      /*
        When dropping a trigger, we need to load its table name
        before checking slave filter rules.
      */
      add_table_for_trigger(thd, thd->lex->spname, 1, &all_tables);
      
      if (!all_tables)
      {
        /*
          If table name cannot be loaded,
          it means the trigger does not exists possibly because
          CREATE TRIGGER was previously skipped for this trigger
          according to slave filtering rules.
          Returning success without producing any errors in this case.
        */
        DBUG_RETURN(0);
      }
      
      // force searching in slave.cc:tables_ok() 
      all_tables->updating= 1;
    }
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892

    /*
      For fix of BUG#37051, the master stores the table map for update
      in the Query_log_event, and the value is assigned to
      thd->variables.table_map_for_update before executing the update
      query.

      If thd->variables.table_map_for_update is set, then we are
      replicating from a new master, we can use this value to apply
      filter rules without opening all the tables. However If
      thd->variables.table_map_for_update is not set, then we are
      replicating from an old master, so we just skip this and
      continue with the old method. And of course, the bug would still
      exist for old masters.
    */
    if (lex->sql_command == SQLCOM_UPDATE_MULTI &&
        thd->table_map_for_update)
    {
      have_table_map_for_update= TRUE;
      table_map table_map_for_update= thd->table_map_for_update;
      uint nr= 0;
      TABLE_LIST *table;
      for (table=all_tables; table; table=table->next_global, nr++)
      {
        if (table_map_for_update & ((table_map)1 << nr))
          table->updating= TRUE;
        else
          table->updating= FALSE;
      }

      if (all_tables_not_ok(thd, all_tables))
      {
        /* we warn the slave SQL thread */
        my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
        if (thd->one_shot_set)
          reset_one_shot_variables(thd);
        DBUG_RETURN(0);
      }
      
      for (table=all_tables; table; table=table->next_global)
        table->updating= TRUE;
    }
1893
    
peter@mysql.com's avatar
peter@mysql.com committed
1894
    /*
1895 1896
      Check if statment should be skipped because of slave filtering
      rules
1897 1898

      Exceptions are:
1899 1900
      - UPDATE MULTI: For this statement, we want to check the filtering
        rules later in the code
1901
      - SET: we always execute it (Not that many SET commands exists in
lars@mysql.com's avatar
lars@mysql.com committed
1902 1903
        the binary log anyway -- only 4.1 masters write SET statements,
	in 5.0 there are no SET statements in the binary log)
1904 1905
      - DROP TEMPORARY TABLE IF EXISTS: we always execute it (otherwise we
        have stale files on slave caused by exclusion of one tmp table).
monty@hundin.mysql.fi's avatar
merge  
monty@hundin.mysql.fi committed
1906
    */
1907 1908
    if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) &&
	!(lex->sql_command == SQLCOM_SET_OPTION) &&
1909
	!(lex->sql_command == SQLCOM_DROP_TABLE &&
1910
          lex->drop_temporary && lex->drop_if_exists) &&
guilhem@mysql.com's avatar
Merge  
guilhem@mysql.com committed
1911
        all_tables_not_ok(thd, all_tables))
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1912 1913
    {
      /* we warn the slave SQL thread */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1914
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
      if (thd->one_shot_set)
      {
        /*
          It's ok to check thd->one_shot_set here:

          The charsets in a MySQL 5.0 slave can change by both a binlogged
          SET ONE_SHOT statement and the event-internal charset setting, 
          and these two ways to change charsets do not seems to work
          together.

          At least there seems to be problems in the rli cache for
          charsets if we are using ONE_SHOT.  Note that this is normally no
          problem because either the >= 5.0 slave reads a 4.1 binlog (with
          ONE_SHOT) *or* or 5.0 binlog (without ONE_SHOT) but never both."
        */
        reset_one_shot_variables(thd);
      }
1932
      DBUG_RETURN(0);
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1933
    }
1934
  }
1935
  else
1936
  {
1937
#endif /* HAVE_REPLICATION */
1938 1939 1940 1941
    /*
      When option readonly is set deny operations which change non-temporary
      tables. Except for the replication thread and the 'super' users.
    */
1942
    if (deny_updates_if_read_only_option(thd, all_tables))
1943 1944 1945 1946 1947 1948 1949
    {
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
      DBUG_RETURN(-1);
    }
#ifdef HAVE_REPLICATION
  } /* endif unlikely slave */
#endif
Konstantin Osipov's avatar
Konstantin Osipov committed
1950

1951
  status_var_increment(thd->status_var.com_stat[lex->sql_command]);
1952

1953
  DBUG_ASSERT(thd->transaction.stmt.modified_non_trans_table == FALSE);
Konstantin Osipov's avatar
Konstantin Osipov committed
1954 1955 1956 1957 1958 1959 1960

  /*
    End a active transaction so that this command will have it's
    own transaction and will also sync the binary log. If a DDL is
    not run in it's own transaction it may simply never appear on
    the slave in case the outside transaction rolls back.
  */
1961 1962 1963 1964 1965 1966 1967
  if (stmt_causes_implicit_commit(thd, CF_IMPLICT_COMMIT_BEGIN))
  {
    /* Commit or rollback the statement transaction. */
    thd->is_error() ? trans_rollback_stmt(thd) : trans_commit_stmt(thd);
    /* Commit the normal transaction if one is active. */
    if (trans_commit_implicit(thd))
      goto error;
1968
    /* Release metadata locks acquired in this transaction. */
1969
    thd->mdl_context.release_transactional_locks();
1970
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
1971

1972 1973 1974 1975 1976
#ifndef DBUG_OFF
  if (lex->sql_command != SQLCOM_SET_OPTION)
    DEBUG_SYNC(thd,"before_execute_sql_command");
#endif

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1977
  switch (lex->sql_command) {
1978

1979
  case SQLCOM_SHOW_EVENTS:
1980 1981 1982 1983
#ifndef HAVE_EVENT_SCHEDULER
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server");
    break;
#endif
1984 1985
  case SQLCOM_SHOW_STATUS_PROC:
  case SQLCOM_SHOW_STATUS_FUNC:
Konstantin Osipov's avatar
Konstantin Osipov committed
1986
    if ((res= check_table_access(thd, SELECT_ACL, all_tables, FALSE,
1987
                                  UINT_MAX, FALSE)))
Konstantin Osipov's avatar
Konstantin Osipov committed
1988 1989
      goto error;
    res= execute_sqlcom_select(thd, all_tables);
1990 1991 1992 1993 1994
    break;
  case SQLCOM_SHOW_STATUS:
  {
    system_status_var old_status_var= thd->status_var;
    thd->initial_status_var= &old_status_var;
1995 1996
    if (!(res= check_table_access(thd, SELECT_ACL, all_tables, FALSE,
                                  UINT_MAX, FALSE)))
1997
      res= execute_sqlcom_select(thd, all_tables);
1998 1999 2000 2001 2002 2003 2004
    /* Don't log SHOW STATUS commands to slow query log */
    thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED |
                           SERVER_QUERY_NO_GOOD_INDEX_USED);
    /*
      restore status variables, as we don't want 'show status' to cause
      changes
    */
Marc Alff's avatar
Marc Alff committed
2005
    mysql_mutex_lock(&LOCK_status);
2006 2007 2008
    add_diff_to_status(&global_status_var, &thd->status_var,
                       &old_status_var);
    thd->status_var= old_status_var;
Marc Alff's avatar
Marc Alff committed
2009
    mysql_mutex_unlock(&LOCK_status);
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
    break;
  }
  case SQLCOM_SHOW_DATABASES:
  case SQLCOM_SHOW_TABLES:
  case SQLCOM_SHOW_TRIGGERS:
  case SQLCOM_SHOW_TABLE_STATUS:
  case SQLCOM_SHOW_OPEN_TABLES:
  case SQLCOM_SHOW_PLUGINS:
  case SQLCOM_SHOW_FIELDS:
  case SQLCOM_SHOW_KEYS:
  case SQLCOM_SHOW_VARIABLES:
  case SQLCOM_SHOW_CHARSETS:
  case SQLCOM_SHOW_COLLATIONS:
2023
  case SQLCOM_SHOW_STORAGE_ENGINES:
2024
  case SQLCOM_SHOW_PROFILE:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2025
  case SQLCOM_SELECT:
2026
  {
2027
    thd->status_var.last_query_cost= 0.0;
2028 2029 2030 2031 2032 2033 2034 2035

    /*
      lex->exchange != NULL implies SELECT .. INTO OUTFILE and this
      requires FILE_ACL access.
    */
    ulong privileges_requested= lex->exchange ? SELECT_ACL | FILE_ACL :
      SELECT_ACL;

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2036
    if (all_tables)
2037
      res= check_table_access(thd,
2038 2039
                              privileges_requested,
                              all_tables, FALSE, UINT_MAX, FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2040
    else
Marc Alff's avatar
Marc Alff committed
2041
      res= check_access(thd, privileges_requested, any_db, NULL, NULL, 0, 0);
2042

2043 2044 2045 2046
    if (res)
      break;

    res= execute_sqlcom_select(thd, all_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2047
    break;
2048 2049
  }
case SQLCOM_PREPARE:
2050
  {
2051
    mysql_sql_stmt_prepare(thd);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
2052 2053 2054 2055
    break;
  }
  case SQLCOM_EXECUTE:
  {
2056
    mysql_sql_stmt_execute(thd);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
2057 2058 2059 2060
    break;
  }
  case SQLCOM_DEALLOCATE_PREPARE:
  {
2061
    mysql_sql_stmt_close(thd);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
2062 2063
    break;
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2064
  case SQLCOM_DO:
2065
    if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)
2066
        || open_and_lock_tables(thd, all_tables, TRUE, 0))
2067
      goto error;
2068 2069

    res= mysql_do(thd, *lex->insert_list);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2070 2071
    break;

2072
  case SQLCOM_EMPTY_QUERY:
2073
    my_ok(thd);
2074 2075
    break;

2076 2077 2078 2079
  case SQLCOM_HELP:
    res= mysqld_help(thd,lex->help_arg);
    break;

2080
#ifndef EMBEDDED_LIBRARY
2081
  case SQLCOM_PURGE:
2082
  {
2083
    if (check_global_access(thd, SUPER_ACL))
2084
      goto error;
monty@mysql.com's avatar
monty@mysql.com committed
2085
    /* PURGE MASTER LOGS TO 'file' */
2086 2087 2088
    res = purge_master_logs(thd, lex->to_log);
    break;
  }
2089 2090
  case SQLCOM_PURGE_BEFORE:
  {
2091 2092
    Item *it;

2093 2094
    if (check_global_access(thd, SUPER_ACL))
      goto error;
monty@mysql.com's avatar
monty@mysql.com committed
2095
    /* PURGE MASTER LOGS BEFORE 'data' */
2096
    it= (Item *)lex->value_list.head();
2097
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) ||
2098
        it->check_cols(1))
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
    {
      my_error(ER_WRONG_ARGUMENTS, MYF(0), "PURGE LOGS BEFORE");
      goto error;
    }
    it= new Item_func_unix_timestamp(it);
    /*
      it is OK only emulate fix_fieds, because we need only
      value of constant
    */
    it->quick_fix_field();
    res = purge_master_logs_before_date(thd, (ulong)it->val_int());
2110 2111
    break;
  }
2112
#endif
2113 2114
  case SQLCOM_SHOW_WARNS:
  {
2115 2116
    res= mysqld_show_warnings(thd, (ulong)
			      ((1L << (uint) MYSQL_ERROR::WARN_LEVEL_NOTE) |
2117 2118 2119
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_WARN) |
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR)
			       ));
2120 2121 2122 2123
    break;
  }
  case SQLCOM_SHOW_ERRORS:
  {
2124 2125
    res= mysqld_show_warnings(thd, (ulong)
			      (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR));
2126 2127
    break;
  }
2128 2129
  case SQLCOM_SHOW_PROFILES:
  {
2130
#if defined(ENABLED_PROFILING)
2131
    thd->profiling.discard_current_query();
2132
    res= thd->profiling.show_profiles();
2133 2134 2135
    if (res)
      goto error;
#else
2136
    my_error(ER_FEATURE_DISABLED, MYF(0), "SHOW PROFILES", "enable-profiling");
2137 2138
    goto error;
#endif
2139 2140
    break;
  }
2141 2142
  case SQLCOM_SHOW_NEW_MASTER:
  {
2143
    if (check_global_access(thd, REPL_SLAVE_ACL))
2144
      goto error;
2145
    /* This query don't work now. See comment in repl_failsafe.cc */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2146
#ifndef WORKING_NEW_MASTER
2147 2148
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "SHOW NEW MASTER");
    goto error;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2149
#else
2150 2151
    res = show_new_master(thd);
    break;
2152
#endif
2153
  }
2154

2155
#ifdef HAVE_REPLICATION
2156 2157
  case SQLCOM_SHOW_SLAVE_HOSTS:
  {
2158
    if (check_global_access(thd, REPL_SLAVE_ACL))
2159 2160 2161 2162
      goto error;
    res = show_slave_hosts(thd);
    break;
  }
2163
  case SQLCOM_SHOW_RELAYLOG_EVENTS: /* fall through */
2164 2165
  case SQLCOM_SHOW_BINLOG_EVENTS:
  {
2166
    if (check_global_access(thd, REPL_SLAVE_ACL))
2167
      goto error;
2168
    res = mysql_show_binlog_events(thd);
2169 2170
    break;
  }
2171 2172
#endif

igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2173 2174
  case SQLCOM_ASSIGN_TO_KEYCACHE:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2175
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2176
    if (check_access(thd, INDEX_ACL, first_table->db,
Marc Alff's avatar
Marc Alff committed
2177 2178 2179
                     &first_table->grant.privilege,
                     &first_table->grant.m_internal,
                     0, 0))
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2180
      goto error;
2181
    res= mysql_assign_to_keycache(thd, first_table, &lex->ident);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2182 2183
    break;
  }
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2184 2185
  case SQLCOM_PRELOAD_KEYS:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2186
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2187
    if (check_access(thd, INDEX_ACL, first_table->db,
Marc Alff's avatar
Marc Alff committed
2188 2189 2190
                     &first_table->grant.privilege,
                     &first_table->grant.m_internal,
                     0, 0))
2191
      goto error;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2192
    res = mysql_preload_keys(thd, first_table);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2193 2194
    break;
  }
2195
#ifdef HAVE_REPLICATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2196
  case SQLCOM_CHANGE_MASTER:
2197
  {
2198
    if (check_global_access(thd, SUPER_ACL))
2199
      goto error;
Marc Alff's avatar
Marc Alff committed
2200
    mysql_mutex_lock(&LOCK_active_mi);
2201
    res = change_master(thd,active_mi);
Marc Alff's avatar
Marc Alff committed
2202
    mysql_mutex_unlock(&LOCK_active_mi);
2203 2204
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2205
  case SQLCOM_SHOW_SLAVE_STAT:
2206
  {
2207 2208
    /* Accept one of two privileges */
    if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
2209
      goto error;
Marc Alff's avatar
Marc Alff committed
2210
    mysql_mutex_lock(&LOCK_active_mi);
2211 2212 2213 2214 2215 2216
    if (active_mi != NULL)
    {
      res = show_master_info(thd, active_mi);
    }
    else
    {
2217 2218
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                   WARN_NO_MASTER_INFO, ER(WARN_NO_MASTER_INFO));
2219
      my_ok(thd);
2220
    }
Marc Alff's avatar
Marc Alff committed
2221
    mysql_mutex_unlock(&LOCK_active_mi);
2222 2223
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2224
  case SQLCOM_SHOW_MASTER_STAT:
2225
  {
2226 2227
    /* Accept one of two privileges */
    if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
2228 2229 2230 2231
      goto error;
    res = show_binlog_info(thd);
    break;
  }
peter@mysql.com's avatar
peter@mysql.com committed
2232

2233
#endif /* HAVE_REPLICATION */
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2234
  case SQLCOM_SHOW_ENGINE_STATUS:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2235
    {
2236
      if (check_global_access(thd, PROCESS_ACL))
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2237 2238
        goto error;
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2239 2240
      break;
    }
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2241
  case SQLCOM_SHOW_ENGINE_MUTEX:
vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
2242
    {
2243
      if (check_global_access(thd, PROCESS_ACL))
vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
2244
        goto error;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2245
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX);
vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
2246 2247
      break;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2248
  case SQLCOM_CREATE_TABLE:
2249
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2250 2251
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    bool link_to_local;
2252 2253 2254
    TABLE_LIST *create_table= first_table;
    TABLE_LIST *select_tables= lex->create_last_non_select_table->next_global;

2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275
    /*
      Code below (especially in mysql_create_table() and select_create
      methods) may modify HA_CREATE_INFO structure in LEX, so we have to
      use a copy of this structure to make execution prepared statement-
      safe. A shallow copy is enough as this code won't modify any memory
      referenced from this structure.
    */
    HA_CREATE_INFO create_info(lex->create_info);
    /*
      We need to copy alter_info for the same reasons of re-execution
      safety, only in case of Alter_info we have to do (almost) a deep
      copy.
    */
    Alter_info alter_info(lex->alter_info, thd->mem_root);

    if (thd->is_fatal_error)
    {
      /* If out of memory when creating a copy of alter_info. */
      res= 1;
      goto end_with_restore_list;
    }
monty@mysql.com's avatar
monty@mysql.com committed
2276

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2277
    if ((res= create_table_precheck(thd, select_tables, create_table)))
monty@mysql.com's avatar
monty@mysql.com committed
2278
      goto end_with_restore_list;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2279

2280 2281 2282
    /* Might have been updated in create_table_precheck */
    create_info.alias= create_table->alias;

2283
#ifdef HAVE_READLINK
2284
    /* Fix names if symlinked tables */
2285
    if (append_file_to_dir(thd, &create_info.data_file_name,
2286
			   create_table->table_name) ||
2287
	append_file_to_dir(thd, &create_info.index_file_name,
2288
			   create_table->table_name))
monty@mysql.com's avatar
monty@mysql.com committed
2289
      goto end_with_restore_list;
2290
#endif
2291
    /*
2292
      If we are using SET CHARSET without DEFAULT, add an implicit
2293 2294
      DEFAULT to not confuse old users. (This may change).
    */
2295
    if ((create_info.used_fields &
2296 2297 2298
	 (HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) ==
	HA_CREATE_USED_CHARSET)
    {
2299 2300 2301 2302
      create_info.used_fields&= ~HA_CREATE_USED_CHARSET;
      create_info.used_fields|= HA_CREATE_USED_DEFAULT_CHARSET;
      create_info.default_table_charset= create_info.table_charset;
      create_info.table_charset= 0;
2303
    }
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
2304

2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315
#ifdef WITH_PARTITION_STORAGE_ENGINE
    {
      partition_info *part_info= thd->lex->part_info;
      if (part_info && !(part_info= thd->lex->part_info->get_clone()))
      {
        res= -1;
        goto end_with_restore_list;
      }
      thd->work_part_info= part_info;
    }
#endif
2316

2317
    /* Close any open handlers for the table. */
2318 2319
    mysql_ha_rm_tables(thd, create_table);

2320
    if (select_lex->item_list.elements)		// With select
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2321 2322
    {
      select_result *result;
2323

2324 2325 2326
      /*
        If:
        a) we inside an SP and there was NAME_CONST substitution,
Ramil Kalimullin's avatar
Ramil Kalimullin committed
2327
        b) binlogging is on (STMT mode),
2328 2329 2330 2331 2332 2333
        c) we log the SP as separate statements
        raise a warning, as it may cause problems
        (see 'NAME_CONST issues' in 'Binary Logging of Stored Programs')
       */
      if (thd->query_name_consts && 
          mysql_bin_log.is_open() &&
Ramil Kalimullin's avatar
Ramil Kalimullin committed
2334
          thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
          !mysql_bin_log.is_query_in_union(thd, thd->query_id))
      {
        List_iterator_fast<Item> it(select_lex->item_list);
        Item *item;
        uint splocal_refs= 0;
        /* Count SP local vars in the top-level SELECT list */
        while ((item= it++))
        {
          if (item->is_splocal())
            splocal_refs++;
        }
        /*
          If it differs from number of NAME_CONST substitution applied,
          we may have a SOME_FUNC(NAME_CONST()) in the SELECT list,
          that may cause a problem with binary log (see BUG#35383),
          raise a warning. 
        */
        if (splocal_refs != thd->query_name_consts)
          push_warning(thd, 
                       MYSQL_ERROR::WARN_LEVEL_WARN,
                       ER_UNKNOWN_ERROR,
"Invoked routine ran a statement that may cause problems with "
"binary log, see 'NAME_CONST issues' in 'Binary Logging of Stored Programs' "
"section of the manual.");
      }
      
2361
      select_lex->options|= SELECT_NO_UNLOCK;
2362
      unit->set_limit(select_lex);
2363

2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
      /*
        Disable non-empty MERGE tables with CREATE...SELECT. Too
        complicated. See Bug #26379. Empty MERGE tables are read-only
        and don't allow CREATE...SELECT anyway.
      */
      if (create_info.used_fields & HA_CREATE_USED_UNION)
      {
        my_error(ER_WRONG_OBJECT, MYF(0), create_table->db,
                 create_table->table_name, "BASE TABLE");
        res= 1;
        goto end_with_restore_list;
      }

2377
      if (!(res= open_and_lock_tables(thd, lex->query_tables, TRUE, 0)))
2378
      {
2379 2380
        /* The table already exists */
        if (create_table->table)
2381
        {
2382
          if (create_info.options & HA_LEX_CREATE_IF_NOT_EXISTS)
2383
          {
2384 2385 2386 2387 2388
            push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
                                ER_TABLE_EXISTS_ERROR,
                                ER(ER_TABLE_EXISTS_ERROR),
                                create_info.alias);
            my_ok(thd);
2389
          }
2390
          else
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2391
          {
2392 2393
            my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_info.alias);
            res= 1;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2394
          }
2395
          goto end_with_restore_list;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2396
        }
2397

2398 2399 2400 2401 2402 2403 2404
        /*
          Remove target table from main select and name resolution
          context. This can't be done earlier as it will break view merging in
          statements like "CREATE TABLE IF NOT EXISTS existing_view SELECT".
        */
        lex->unlink_first_table(&link_to_local);

2405 2406 2407 2408
        /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
        if (create_info.options & HA_LEX_CREATE_TMP_TABLE)
          thd->variables.option_bits|= OPTION_KEEP_LOG;

dlenev@mockturtle.local's avatar
dlenev@mockturtle.local committed
2409
        /*
2410 2411
          select_create is currently not re-execution friendly and
          needs to be created for every execution of a PS/SP.
dlenev@mockturtle.local's avatar
dlenev@mockturtle.local committed
2412
        */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2413
        if ((result= new select_create(create_table,
2414 2415 2416 2417
                                       &create_info,
                                       &alter_info,
                                       select_lex->item_list,
                                       lex->duplicates,
2418
                                       lex->ignore,
2419
                                       select_tables)))
2420 2421 2422 2423 2424
        {
          /*
            CREATE from SELECT give its SELECT_LEX for SELECT,
            and item_list belong to SELECT
          */
2425
          res= handle_select(thd, lex, result, 0);
2426
          delete result;
2427
        }
2428

2429
        lex->link_first_table_back(create_table, link_to_local);
2430 2431
      }
    }
monty@mysql.com's avatar
monty@mysql.com committed
2432
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2433
    {
2434
      /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
2435
      if (create_info.options & HA_LEX_CREATE_TMP_TABLE)
2436
        thd->variables.option_bits|= OPTION_KEEP_LOG;
monty@mysql.com's avatar
monty@mysql.com committed
2437
      /* regular create */
2438
      if (create_info.options & HA_LEX_CREATE_TABLE_LIKE)
2439 2440
      {
        /* CREATE TABLE ... LIKE ... */
2441
        res= mysql_create_like_table(thd, create_table, select_tables,
2442
                                     &create_info);
2443
      }
venu@myvenu.com's avatar
venu@myvenu.com committed
2444
      else
2445
      {
2446 2447 2448
        /* Regular CREATE TABLE */
        res= mysql_create_table(thd, create_table,
                                &create_info, &alter_info);
2449
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2450
      if (!res)
2451
        my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2452
    }
2453

monty@mysql.com's avatar
monty@mysql.com committed
2454
end_with_restore_list:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2455
    break;
2456
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2457
  case SQLCOM_CREATE_INDEX:
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475
    /* Fall through */
  case SQLCOM_DROP_INDEX:
  /*
    CREATE INDEX and DROP INDEX are implemented by calling ALTER
    TABLE with proper arguments.

    In the future ALTER TABLE will notice that the request is to
    only add indexes and create these one by one for the existing
    table without having to do a full rebuild.
  */
  {
    /* Prepare stack copies to be re-execution safe */
    HA_CREATE_INFO create_info;
    Alter_info alter_info(lex->alter_info, thd->mem_root);

    if (thd->is_fatal_error) /* out of memory creating a copy of alter_info */
      goto error;

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2476 2477
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_one_table_access(thd, INDEX_ACL, all_tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2478
      goto error; /* purecov: inspected */
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489
    /*
      Currently CREATE INDEX or DROP INDEX cause a full table rebuild
      and thus classify as slow administrative statements just like
      ALTER TABLE.
    */
    thd->enable_slow_log= opt_log_slow_admin_statements;

    bzero((char*) &create_info, sizeof(create_info));
    create_info.db_type= 0;
    create_info.row_type= ROW_TYPE_NOT_USED;
    create_info.default_table_charset= thd->variables.collation_database;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2490

2491 2492 2493 2494 2495
    res= mysql_alter_table(thd, first_table->db, first_table->table_name,
                           &create_info, first_table, &alter_info,
                           0, (ORDER*) 0, 0);
    break;
  }
2496
#ifdef HAVE_REPLICATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2497
  case SQLCOM_SLAVE_START:
2498
  {
Marc Alff's avatar
Marc Alff committed
2499
    mysql_mutex_lock(&LOCK_active_mi);
2500
    start_slave(thd,active_mi,1 /* net report*/);
Marc Alff's avatar
Marc Alff committed
2501
    mysql_mutex_unlock(&LOCK_active_mi);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2502
    break;
2503
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2504
  case SQLCOM_SLAVE_STOP:
2505 2506 2507 2508 2509 2510
  /*
    If the client thread has locked tables, a deadlock is possible.
    Assume that
    - the client thread does LOCK TABLE t READ.
    - then the master updates t.
    - then the SQL slave thread wants to update t,
2511
      so it waits for the client thread because t is locked by it.
2512
    - then the client thread does SLAVE STOP.
2513 2514
      SLAVE STOP waits for the SQL slave thread to terminate its
      update t, which waits for the client thread because t is locked by it.
2515 2516 2517
    To prevent that, refuse SLAVE STOP if the
    client thread has locked tables
  */
Konstantin Osipov's avatar
Konstantin Osipov committed
2518
  if (thd->locked_tables_mode ||
2519
      thd->in_active_multi_stmt_transaction() || thd->global_read_lock.is_acquired())
2520
  {
2521 2522
    my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
               ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2523
    goto error;
2524
  }
2525
  {
Marc Alff's avatar
Marc Alff committed
2526
    mysql_mutex_lock(&LOCK_active_mi);
2527
    stop_slave(thd,active_mi,1/* net report*/);
Marc Alff's avatar
Marc Alff committed
2528
    mysql_mutex_unlock(&LOCK_active_mi);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2529
    break;
2530
  }
2531
#endif /* HAVE_REPLICATION */
2532

2533
  case SQLCOM_RENAME_TABLE:
2534
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2535
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2536
    TABLE_LIST *table;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2537
    for (table= first_table; table; table= table->next_local->next_local)
2538
    {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2539
      if (check_access(thd, ALTER_ACL | DROP_ACL, table->db,
Marc Alff's avatar
Marc Alff committed
2540 2541 2542 2543 2544 2545 2546
                       &table->grant.privilege,
                       &table->grant.m_internal,
                       0, 0) ||
          check_access(thd, INSERT_ACL | CREATE_ACL, table->next_local->db,
                       &table->next_local->grant.privilege,
                       &table->next_local->grant.m_internal,
                       0, 0))
2547
	goto error;
2548 2549 2550 2551 2552 2553 2554
      TABLE_LIST old_list, new_list;
      /*
        we do not need initialize old_list and new_list because we will
        come table[0] and table->next[0] there
      */
      old_list= table[0];
      new_list= table->next_local[0];
2555
      if (check_grant(thd, ALTER_ACL | DROP_ACL, &old_list, FALSE, 1, FALSE) ||
2556 2557
         (!test_all_bits(table->next_local->grant.privilege,
                         INSERT_ACL | CREATE_ACL) &&
2558 2559
          check_grant(thd, INSERT_ACL | CREATE_ACL, &new_list, FALSE, 1,
                      FALSE)))
2560
        goto error;
2561
    }
2562

Konstantin Osipov's avatar
Konstantin Osipov committed
2563
    if (mysql_rename_tables(thd, first_table, 0))
2564
      goto error;
2565
    break;
2566
  }
2567
#ifndef EMBEDDED_LIBRARY
2568 2569
  case SQLCOM_SHOW_BINLOGS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2570 2571
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2572
    goto error;
2573 2574
#else
    {
2575
      if (check_global_access(thd, SUPER_ACL))
2576 2577 2578 2579
	goto error;
      res = show_binlogs(thd);
      break;
    }
peter@mysql.com's avatar
peter@mysql.com committed
2580
#endif
2581
#endif /* EMBEDDED_LIBRARY */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2582
  case SQLCOM_SHOW_CREATE:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2583
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2584
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2585 2586
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2587
    goto error;
2588
#else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2589
    {
2590 2591 2592 2593 2594 2595 2596 2597 2598
     /*
        Access check:
        SHOW CREATE TABLE require any privileges on the table level (ie
        effecting all columns in the table).
        SHOW CREATE VIEW require the SHOW_VIEW and SELECT ACLs on the table
        level.
        NOTE: SHOW_VIEW ACL is checked when the view is created.
      */

2599 2600 2601
      DBUG_PRINT("debug", ("lex->only_view: %d, table: %s.%s",
                           lex->only_view,
                           first_table->db, first_table->table_name));
2602
      if (lex->only_view)
2603 2604 2605
      {
        if (check_table_access(thd, SELECT_ACL, first_table, FALSE, 1, FALSE))
        {
2606
          DBUG_PRINT("debug", ("check_table_access failed"));
2607 2608 2609 2610 2611
          my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
                  "SHOW", thd->security_ctx->priv_user,
                  thd->security_ctx->host_or_ip, first_table->alias);
          goto error;
        }
2612
        DBUG_PRINT("debug", ("check_table_access succeeded"));
2613 2614

        /* Ignore temporary tables if this is "SHOW CREATE VIEW" */
2615 2616
        first_table->open_type= OT_BASE_ONLY;

2617 2618 2619 2620
      }
      else
      {
        /*
Marc Alff's avatar
Marc Alff committed
2621 2622 2623
          The fact that check_some_access() returned FALSE does not mean that
          access is granted. We need to check if first_table->grant.privilege
          contains any table-specific privilege.
2624
        */
Mattias Jonsson's avatar
Mattias Jonsson committed
2625
        DBUG_PRINT("debug", ("first_table->grant.privilege: %lx",
2626
                             first_table->grant.privilege));
Marc Alff's avatar
Marc Alff committed
2627 2628
        if (check_some_access(thd, SHOW_CREATE_TABLE_ACLS, first_table) ||
            (first_table->grant.privilege & SHOW_CREATE_TABLE_ACLS) == 0)
2629 2630 2631 2632 2633 2634 2635 2636
        {
          my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
                  "SHOW", thd->security_ctx->priv_user,
                  thd->security_ctx->host_or_ip, first_table->alias);
          goto error;
        }
      }

2637
      /* Access is granted. Execute the command.  */
monty@mishka.local's avatar
monty@mishka.local committed
2638
      res= mysqld_show_create(thd, first_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2639 2640
      break;
    }
2641
#endif
2642 2643
  case SQLCOM_CHECKSUM:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2644
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2645 2646
    if (check_table_access(thd, SELECT_ACL, all_tables,
                           FALSE, UINT_MAX, FALSE))
2647
      goto error; /* purecov: inspected */
2648

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2649
    res = mysql_checksum_table(thd, first_table, &lex->check_opt);
2650 2651
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2652
  case SQLCOM_UPDATE:
2653 2654
  {
    ha_rows found= 0, updated= 0;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2655 2656
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (update_precheck(thd, all_tables))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2657
      break;
2658 2659
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
2660
    MYSQL_UPDATE_START(thd->query());
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2661 2662 2663 2664 2665
    res= (up_result= mysql_update(thd, all_tables,
                                  select_lex->item_list,
                                  lex->value_list,
                                  select_lex->where,
                                  select_lex->order_list.elements,
2666
                                  select_lex->order_list.first,
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2667
                                  unit->select_limit_cnt,
2668 2669 2670
                                  lex->duplicates, lex->ignore,
                                  &found, &updated));
    MYSQL_UPDATE_DONE(res, found, updated);
2671
    /* mysql_update return 2 if we need to switch to multi-update */
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2672
    if (up_result != 2)
2673
      break;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2674
    /* Fall through */
2675
  }
2676
  case SQLCOM_UPDATE_MULTI:
2677 2678 2679
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    /* if we switched from normal update, rights are checked */
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2680
    if (up_result != 2)
2681
    {
2682 2683 2684 2685 2686
      if ((res= multi_update_precheck(thd, all_tables)))
        break;
    }
    else
      res= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2687

2688
    res= mysql_multi_update_prepare(thd);
2689

2690
#ifdef HAVE_REPLICATION
2691
    /* Check slave filtering rules */
2692
    if (unlikely(thd->slave_thread && !have_table_map_for_update))
2693
    {
2694 2695
      if (all_tables_not_ok(thd, all_tables))
      {
2696 2697 2698 2699 2700
        if (res!= 0)
        {
          res= 0;             /* don't care of prev failure  */
          thd->clear_error(); /* filters are of highest prior */
        }
2701 2702 2703 2704
        /* we warn the slave SQL thread */
        my_error(ER_SLAVE_IGNORED_TABLE, MYF(0));
        break;
      }
2705 2706
      if (res)
        break;
2707
    }
2708 2709
    else
    {
2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722
#endif /* HAVE_REPLICATION */
      if (res)
        break;
      if (opt_readonly &&
	  !(thd->security_ctx->master_access & SUPER_ACL) &&
	  some_non_temp_table_to_be_updated(thd, all_tables))
      {
	my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
	break;
      }
#ifdef HAVE_REPLICATION
    }  /* unlikely */
#endif
2723 2724
    {
      multi_update *result_obj;
2725
      MYSQL_MULTI_UPDATE_START(thd->query());
2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
      res= mysql_multi_update(thd, all_tables,
                              &select_lex->item_list,
                              &lex->value_list,
                              select_lex->where,
                              select_lex->options,
                              lex->duplicates,
                              lex->ignore,
                              unit,
                              select_lex,
                              &result_obj);
      if (result_obj)
      {
        MYSQL_MULTI_UPDATE_DONE(res, result_obj->num_found(),
                                result_obj->num_updated());
        res= FALSE; /* Ignore errors here */
        delete result_obj;
      }
      else
      {
        MYSQL_MULTI_UPDATE_DONE(1, 0, 0);
      }
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2748
    break;
monty@mysql.com's avatar
monty@mysql.com committed
2749
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2750
  case SQLCOM_REPLACE:
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
#ifndef DBUG_OFF
    if (mysql_bin_log.is_open())
    {
      /*
        Generate an incident log event before writing the real event
        to the binary log.  We put this event is before the statement
        since that makes it simpler to check that the statement was
        not executed on the slave (since incidents usually stop the
        slave).

        Observe that any row events that are generated will be
        generated before.

        This is only for testing purposes and will not be present in a
        release build.
      */

      Incident incident= INCIDENT_NONE;
      DBUG_PRINT("debug", ("Just before generate_incident()"));
      DBUG_EXECUTE_IF("incident_database_resync_on_replace",
                      incident= INCIDENT_LOST_EVENTS;);
      if (incident)
      {
        Incident_log_event ev(thd, incident);
2775
        (void) mysql_bin_log.write(&ev);        /* error is ignored */
2776 2777 2778 2779 2780
        mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
      }
      DBUG_PRINT("debug", ("Just after generate_incident()"));
    }
#endif
2781 2782
  case SQLCOM_INSERT:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2783
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
monty@mysql.com's avatar
monty@mysql.com committed
2784
    if ((res= insert_precheck(thd, all_tables)))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2785
      break;
2786

2787
    MYSQL_INSERT_START(thd->query());
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2788
    res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
monty@mishka.local's avatar
monty@mishka.local committed
2789
		      lex->update_list, lex->value_list,
2790
                      lex->duplicates, lex->ignore);
2791
    MYSQL_INSERT_DONE(res, (ulong) thd->get_row_count_func());
2792 2793 2794 2795 2796 2797
    /*
      If we have inserted into a VIEW, and the base table has
      AUTO_INCREMENT column, but this column is not accessible through
      a view, then we should restore LAST_INSERT_ID to the value it
      had before the statement.
    */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2798
    if (first_table->view && !first_table->contain_auto_increment)
2799 2800
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
2801

2802 2803 2804 2805 2806 2807 2808 2809 2810
    DBUG_EXECUTE_IF("after_mysql_insert",
                    {
                      const char act[]=
                        "now "
                        "wait_for signal.continue";
                      DBUG_ASSERT(opt_debug_sync_timeout > 0);
                      DBUG_ASSERT(!debug_sync_set_action(current_thd,
                                                         STRING_WITH_LEN(act)));
                    };);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2811
    break;
2812
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2813 2814 2815
  case SQLCOM_REPLACE_SELECT:
  case SQLCOM_INSERT_SELECT:
  {
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2816
    select_result *sel_result;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2817
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
monty@mishka.local's avatar
monty@mishka.local committed
2818
    if ((res= insert_precheck(thd, all_tables)))
2819
      break;
monty@mysql.com's avatar
monty@mysql.com committed
2820

2821
    /* Fix lock for first table */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2822 2823
    if (first_table->lock_type == TL_WRITE_DELAYED)
      first_table->lock_type= TL_WRITE;
2824

2825 2826
    /* Don't unlock tables until command is written to binary log */
    select_lex->options|= SELECT_NO_UNLOCK;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2827

2828
    unit->set_limit(select_lex);
2829

2830
    if (!(res= open_and_lock_tables(thd, all_tables, TRUE, 0)))
2831
    {
2832
      MYSQL_INSERT_SELECT_START(thd->query());
2833
      /* Skip first table, which is the table we are inserting in */
2834
      TABLE_LIST *second_table= first_table->next_local;
2835
      select_lex->table_list.first= second_table;
2836 2837
      select_lex->context.table_list= 
        select_lex->context.first_name_resolution_table= second_table;
2838
      res= mysql_insert_select_prepare(thd);
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2839 2840 2841 2842 2843 2844 2845
      if (!res && (sel_result= new select_insert(first_table,
                                                 first_table->table,
                                                 &lex->field_list,
                                                 &lex->update_list,
                                                 &lex->value_list,
                                                 lex->duplicates,
                                                 lex->ignore)))
2846
      {
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2847
	res= handle_select(thd, lex, sel_result, OPTION_SETUP_TABLES_DONE);
2848 2849 2850 2851 2852 2853
        /*
          Invalidate the table in the query cache if something changed
          after unlocking when changes become visible.
          TODO: this is workaround. right way will be move invalidating in
          the unlock procedure.
        */
2854
        if (!res && first_table->lock_type ==  TL_WRITE_CONCURRENT_INSERT &&
2855 2856
            thd->lock)
        {
2857 2858 2859
          /* INSERT ... SELECT should invalidate only the very first table */
          TABLE_LIST *save_table= first_table->next_local;
          first_table->next_local= 0;
2860
          query_cache_invalidate3(thd, first_table, 1);
2861
          first_table->next_local= save_table;
2862
        }
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2863
        delete sel_result;
2864
      }
2865
      /* revert changes for SP */
2866
      MYSQL_INSERT_SELECT_DONE(res, (ulong) thd->get_row_count_func());
2867
      select_lex->table_list.first= first_table;
2868
    }
2869 2870 2871 2872 2873 2874
    /*
      If we have inserted into a VIEW, and the base table has
      AUTO_INCREMENT column, but this column is not accessible through
      a view, then we should restore LAST_INSERT_ID to the value it
      had before the statement.
    */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2875
    if (first_table->view && !first_table->contain_auto_increment)
2876 2877
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
2878

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2879 2880
    break;
  }
2881
  case SQLCOM_DELETE:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2882
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2883 2884
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if ((res= delete_precheck(thd, all_tables)))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2885
      break;
2886 2887
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
2888

2889
    MYSQL_DELETE_START(thd->query());
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2890
    res = mysql_delete(thd, all_tables, select_lex->where,
2891
                       &select_lex->order_list,
2892
                       unit->select_limit_cnt, select_lex->options);
2893
    MYSQL_DELETE_DONE(res, (ulong) thd->get_row_count_func());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2894 2895
    break;
  }
2896
  case SQLCOM_DELETE_MULTI:
2897
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2898
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2899
    TABLE_LIST *aux_tables= thd->lex->auxiliary_table_list.first;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2900
    multi_delete *del_result;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2901

2902
    if ((res= multi_delete_precheck(thd, all_tables)))
2903
      break;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2904

2905
    /* condition will be TRUE on SP re-excuting */
2906 2907
    if (select_lex->item_list.elements != 0)
      select_lex->item_list.empty();
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2908
    if (add_item_to_list(thd, new Item_null()))
2909
      goto error;
2910

2911
    thd_proc_info(thd, "init");
2912
    if ((res= open_and_lock_tables(thd, all_tables, TRUE, 0)))
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2913 2914
      break;

2915
    MYSQL_MULTI_DELETE_START(thd->query());
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2916
    if ((res= mysql_multi_delete_prepare(thd)))
2917 2918
    {
      MYSQL_MULTI_DELETE_DONE(1, 0);
2919
      goto error;
2920
    }
2921

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2922 2923
    if (!thd->is_fatal_error &&
        (del_result= new multi_delete(aux_tables, lex->table_count)))
2924
    {
2925 2926 2927
      res= mysql_select(thd, &select_lex->ref_pointer_array,
			select_lex->get_table_list(),
			select_lex->with_wild,
2928
			select_lex->item_list,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2929
			select_lex->where,
2930
			0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2931
			(ORDER *)NULL,
2932
			(select_lex->options | thd->variables.option_bits |
2933
			SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
2934
                        OPTION_SETUP_TABLES_DONE) & ~OPTION_BUFFER_RESULT,
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2935
			del_result, unit, select_lex);
2936
      res|= thd->is_error();
2937
      MYSQL_MULTI_DELETE_DONE(res, del_result->num_deleted());
2938
      if (res)
2939
        del_result->abort_result_set();
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2940
      delete del_result;
2941 2942
    }
    else
2943
    {
2944
      res= TRUE;                                // Error
2945 2946
      MYSQL_MULTI_DELETE_DONE(1, 0);
    }
2947 2948
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2949
  case SQLCOM_DROP_TABLE:
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
2950
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2951
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2952 2953
    if (!lex->drop_temporary)
    {
2954
      if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE))
2955 2956
	goto error;				/* purecov: inspected */
    }
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
2957
    else
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2958
    {
2959
      /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
2960
      thd->variables.option_bits|= OPTION_KEEP_LOG;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2961
    }
2962
    /* DDL and binlog write order are protected by metadata locks. */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2963 2964
    res= mysql_rm_table(thd, first_table, lex->drop_if_exists,
			lex->drop_temporary);
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
2965 2966
  }
  break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2967
  case SQLCOM_SHOW_PROCESSLIST:
2968 2969
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd,PROCESS_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2970
      break;
hf@deer.(none)'s avatar
hf@deer.(none) committed
2971
    mysqld_list_processes(thd,
2972 2973 2974 2975
			  (thd->security_ctx->master_access & PROCESS_ACL ?
                           NullS :
                           thd->security_ctx->priv_user),
                          lex->verbose);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2976
    break;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2977 2978 2979
  case SQLCOM_SHOW_AUTHORS:
    res= mysqld_show_authors(thd);
    break;
2980 2981 2982
  case SQLCOM_SHOW_CONTRIBUTORS:
    res= mysqld_show_contributors(thd);
    break;
2983 2984 2985
  case SQLCOM_SHOW_PRIVILEGES:
    res= mysqld_show_privileges(thd);
    break;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2986
  case SQLCOM_SHOW_ENGINE_LOGS:
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
2987
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2988 2989
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
2990
    goto error;
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
2991 2992
#else
    {
Marc Alff's avatar
Marc Alff committed
2993
      if (check_access(thd, FILE_ACL, any_db, NULL, NULL, 0, 0))
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
2994
	goto error;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2995
      res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS);
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
2996 2997
      break;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2998 2999
#endif
  case SQLCOM_CHANGE_DB:
3000 3001 3002 3003
  {
    LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) };

    if (!mysql_change_db(thd, &db_str, FALSE))
3004
      my_ok(thd);
3005

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3006
    break;
3007
  }
3008

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3009 3010
  case SQLCOM_LOAD:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3011
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3012
    uint privilege= (lex->duplicates == DUP_REPLACE ?
3013 3014
		     INSERT_ACL | DELETE_ACL : INSERT_ACL) |
                    (lex->local_file ? 0 : FILE_ACL);
3015

3016
    if (lex->local_file)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3017
    {
3018
      if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) ||
3019
          !opt_local_infile)
3020
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3021
	my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0));
3022 3023
	goto error;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3024
    }
3025 3026 3027 3028

    if (check_one_table_access(thd, privilege, all_tables))
      goto error;

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3029
    res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
3030
                    lex->update_list, lex->value_list, lex->duplicates,
3031
                    lex->ignore, (bool) lex->local_file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3032 3033
    break;
  }
3034

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3035
  case SQLCOM_SET_OPTION:
3036 3037
  {
    List<set_var_base> *lex_var_list= &lex->var_list;
3038

3039
    if ((check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)
3040
         || open_and_lock_tables(thd, all_tables, TRUE, 0)))
3041
      goto error;
3042 3043 3044 3045 3046 3047 3048
    if (!(res= sql_set_variables(thd, lex_var_list)))
    {
      /*
        If the previous command was a SET ONE_SHOT, we don't want to forget
        about the ONE_SHOT property of that SET. So we use a |= instead of = .
      */
      thd->one_shot_set|= lex->one_shot_set;
3049
      my_ok(thd);
3050
    }
3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062
    else
    {
      /*
        We encountered some sort of error, but no message was sent.
        Send something semi-generic here since we don't know which
        assignment in the list caused the error.
      */
      if (!thd->is_error())
        my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET");
      goto error;
    }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3063
    break;
3064
  }
3065

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3066
  case SQLCOM_UNLOCK_TABLES:
3067 3068 3069 3070 3071 3072
    /*
      It is critical for mysqldump --single-transaction --master-data that
      UNLOCK TABLES does not implicitely commit a connection which has only
      done FLUSH TABLES WITH READ LOCK + BEGIN. If this assumption becomes
      false, mysqldump will not work.
    */
3073
    if (thd->variables.option_bits & OPTION_TABLE_LOCK)
3074
    {
3075 3076
      res= trans_commit_implicit(thd);
      thd->locked_tables_list.unlock_locked_tables(thd);
3077
      thd->mdl_context.release_transactional_locks();
3078
      thd->variables.option_bits&= ~(OPTION_TABLE_LOCK);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3079
    }
3080 3081
    if (thd->global_read_lock.is_acquired())
      thd->global_read_lock.unlock_global_read_lock(thd);
3082 3083
    if (res)
      goto error;
3084
    my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3085 3086
    break;
  case SQLCOM_LOCK_TABLES:
3087 3088
    /* We must end the transaction first, regardless of anything */
    res= trans_commit_implicit(thd);
Konstantin Osipov's avatar
Konstantin Osipov committed
3089
    thd->locked_tables_list.unlock_locked_tables(thd);
3090
    /* Release transactional metadata locks. */
3091
    thd->mdl_context.release_transactional_locks();
3092 3093
    if (res)
      goto error;
3094
    if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, all_tables,
3095
                           FALSE, UINT_MAX, FALSE))
3096
      goto error;
Konstantin Osipov's avatar
Konstantin Osipov committed
3097

3098
    thd->variables.option_bits|= OPTION_TABLE_LOCK;
Konstantin Osipov's avatar
Konstantin Osipov committed
3099
    thd->in_lock_tables=1;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3100

Konstantin Osipov's avatar
Konstantin Osipov committed
3101 3102 3103
    {
      Lock_tables_prelocking_strategy lock_tables_prelocking_strategy;

3104
      res= (open_and_lock_tables(thd, all_tables, FALSE, 0,
3105
                                 &lock_tables_prelocking_strategy) ||
Konstantin Osipov's avatar
Konstantin Osipov committed
3106 3107
            thd->locked_tables_list.init_locked_tables(thd));
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
3108 3109 3110 3111

    thd->in_lock_tables= 0;

    if (res)
3112
    {
3113
      trans_rollback_stmt(thd);
Konstantin Osipov's avatar
Konstantin Osipov committed
3114
      /*
3115 3116 3117 3118
        Need to end the current transaction, so the storage engine (InnoDB)
        can free its locks if LOCK TABLES locked some tables before finding
        that it can't lock a table in its list
      */
Konstantin Osipov's avatar
Konstantin Osipov committed
3119
      trans_commit_implicit(thd);
3120
      /* Close tables and release metadata locks. */
3121 3122
      close_thread_tables(thd);
      DBUG_ASSERT(!thd->locked_tables_mode);
3123
      thd->mdl_context.release_transactional_locks();
3124
      thd->variables.option_bits&= ~(OPTION_TABLE_LOCK);
3125
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
3126 3127 3128 3129 3130 3131 3132 3133
    else
    {
#ifdef HAVE_QUERY_CACHE
      if (thd->variables.query_cache_wlock_invalidate)
        query_cache.invalidate_locked_for_write(first_table);
#endif /*HAVE_QUERY_CACHE*/
      my_ok(thd);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3134 3135
    break;
  case SQLCOM_CREATE_DB:
3136
  {
3137 3138 3139 3140 3141 3142
    /*
      As mysql_create_db() may modify HA_CREATE_INFO structure passed to
      it, we need to use a copy of LEX::create_info to make execution
      prepared statement- safe.
    */
    HA_CREATE_INFO create_info(lex->create_info);
3143
    char *alias;
3144 3145
    if (!(alias=thd->strmake(lex->name.str, lex->name.length)) ||
        check_db_name(&lex->name))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3146
    {
3147
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3148 3149
      break;
    }
3150 3151 3152
    /*
      If in a slave thread :
      CREATE DATABASE DB was certainly not preceded by USE DB.
3153
      For that reason, db_ok() in sql/slave.cc did not check the
3154 3155 3156
      do_db/ignore_db. And as this query involves no tables, tables_ok()
      above was not called. So we have to check rules again here.
    */
3157
#ifdef HAVE_REPLICATION
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3158
    if (thd->slave_thread && 
3159 3160
	(!rpl_filter->db_ok(lex->name.str) ||
	 !rpl_filter->db_ok_with_wild_table(lex->name.str)))
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3161
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3162
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3163
      break;
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3164
    }
3165
#endif
Marc Alff's avatar
Marc Alff committed
3166
    if (check_access(thd, CREATE_ACL, lex->name.str, NULL, NULL, 1, 0))
3167
      break;
3168
    res= mysql_create_db(thd,(lower_case_table_names == 2 ? alias :
3169
                              lex->name.str), &create_info, 0);
3170 3171
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3172
  case SQLCOM_DROP_DB:
3173
  {
3174
    if (check_db_name(&lex->name))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3175
    {
3176
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3177 3178
      break;
    }
3179 3180 3181 3182 3183 3184 3185
    /*
      If in a slave thread :
      DROP DATABASE DB may not be preceded by USE DB.
      For that reason, maybe db_ok() in sql/slave.cc did not check the 
      do_db/ignore_db. And as this query involves no tables, tables_ok()
      above was not called. So we have to check rules again here.
    */
3186
#ifdef HAVE_REPLICATION
3187
    if (thd->slave_thread && 
3188 3189
	(!rpl_filter->db_ok(lex->name.str) ||
	 !rpl_filter->db_ok_with_wild_table(lex->name.str)))
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3190
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3191
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3192
      break;
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3193
    }
3194
#endif
Marc Alff's avatar
Marc Alff committed
3195
    if (check_access(thd, DROP_ACL, lex->name.str, NULL, NULL, 1, 0))
3196
      break;
3197
    res= mysql_rm_db(thd, lex->name.str, lex->drop_if_exists, 0);
3198 3199
    break;
  }
3200
  case SQLCOM_ALTER_DB_UPGRADE:
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3201
  {
3202
    LEX_STRING *db= & lex->name;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3203 3204
#ifdef HAVE_REPLICATION
    if (thd->slave_thread && 
3205 3206
       (!rpl_filter->db_ok(db->str) ||
        !rpl_filter->db_ok_with_wild_table(db->str)))
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3207 3208 3209 3210 3211 3212
    {
      res= 1;
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
      break;
    }
#endif
3213
    if (check_db_name(db))
3214
    {
3215
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
3216 3217
      break;
    }
Marc Alff's avatar
Marc Alff committed
3218 3219 3220
    if (check_access(thd, ALTER_ACL, db->str, NULL, NULL, 1, 0) ||
        check_access(thd, DROP_ACL, db->str, NULL, NULL, 1, 0) ||
        check_access(thd, CREATE_ACL, db->str, NULL, NULL, 1, 0))
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3221 3222 3223 3224
    {
      res= 1;
      break;
    }
3225
    res= mysql_upgrade_db(thd, db);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3226
    if (!res)
3227
      my_ok(thd);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3228 3229
    break;
  }
3230 3231
  case SQLCOM_ALTER_DB:
  {
3232
    LEX_STRING *db= &lex->name;
3233
    HA_CREATE_INFO create_info(lex->create_info);
3234
    if (check_db_name(db))
3235
    {
3236
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
3237 3238
      break;
    }
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3239 3240 3241
    /*
      If in a slave thread :
      ALTER DATABASE DB may not be preceded by USE DB.
3242
      For that reason, maybe db_ok() in sql/slave.cc did not check the
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3243 3244 3245 3246
      do_db/ignore_db. And as this query involves no tables, tables_ok()
      above was not called. So we have to check rules again here.
    */
#ifdef HAVE_REPLICATION
3247
    if (thd->slave_thread &&
3248 3249
	(!rpl_filter->db_ok(db->str) ||
	 !rpl_filter->db_ok_with_wild_table(db->str)))
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3250
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3251
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3252 3253 3254
      break;
    }
#endif
Marc Alff's avatar
Marc Alff committed
3255
    if (check_access(thd, ALTER_ACL, db->str, NULL, NULL, 1, 0))
3256
      break;
3257
    res= mysql_alter_db(thd, db->str, &create_info);
3258 3259
    break;
  }
3260 3261
  case SQLCOM_SHOW_CREATE_DB:
  {
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
3262 3263
    DBUG_EXECUTE_IF("4x_server_emul",
                    my_error(ER_UNKNOWN_ERROR, MYF(0)); goto error;);
3264
    if (check_db_name(&lex->name))
3265
    {
3266
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
3267 3268
      break;
    }
3269
    res= mysqld_show_create_db(thd, lex->name.str, &lex->create_info);
3270 3271
    break;
  }
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3272 3273
  case SQLCOM_CREATE_EVENT:
  case SQLCOM_ALTER_EVENT:
3274
  #ifdef HAVE_EVENT_SCHEDULER
3275
  do
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3276
  {
3277
    DBUG_ASSERT(lex->event_parse_data);
3278 3279 3280 3281 3282 3283
    if (lex->table_or_sp_used())
    {
      my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Usage of subqueries or stored "
               "function calls as part of this statement");
      break;
    }
3284 3285 3286 3287 3288

    res= sp_process_definer(thd);
    if (res)
      break;

3289 3290
    switch (lex->sql_command) {
    case SQLCOM_CREATE_EVENT:
3291 3292 3293 3294
    {
      bool if_not_exists= (lex->create_info.options &
                           HA_LEX_CREATE_IF_NOT_EXISTS);
      res= Events::create_event(thd, lex->event_parse_data, if_not_exists);
3295
      break;
3296
    }
3297
    case SQLCOM_ALTER_EVENT:
3298 3299 3300
      res= Events::update_event(thd, lex->event_parse_data,
                                lex->spname ? &lex->spname->m_db : NULL,
                                lex->spname ? &lex->spname->m_name : NULL);
3301
      break;
3302 3303
    default:
      DBUG_ASSERT(0);
3304
    }
3305
    DBUG_PRINT("info",("DDL error code=%d", res));
3306
    if (!res)
3307
      my_ok(thd);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3308

3309 3310 3311 3312 3313 3314
  } while (0);
  /* Don't do it, if we are inside a SP */
  if (!thd->spcont)
  {
    delete lex->sphead;
    lex->sphead= NULL;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3315
  }
3316 3317
  /* lex->unit.cleanup() is called outside, no need to call it here */
  break;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3318
  case SQLCOM_SHOW_CREATE_EVENT:
3319 3320 3321 3322 3323 3324 3325
    res= Events::show_create_event(thd, lex->spname->m_db,
                                   lex->spname->m_name);
    break;
  case SQLCOM_DROP_EVENT:
    if (!(res= Events::drop_event(thd,
                                  lex->spname->m_db, lex->spname->m_name,
                                  lex->drop_if_exists)))
3326
      my_ok(thd);
3327
    break;
3328 3329 3330 3331
#else
    my_error(ER_NOT_SUPPORTED_YET,MYF(0),"embedded server");
    break;
#endif
monty@mysql.com's avatar
monty@mysql.com committed
3332
  case SQLCOM_CREATE_FUNCTION:                  // UDF function
monty@mysql.com's avatar
monty@mysql.com committed
3333
  {
Marc Alff's avatar
Marc Alff committed
3334
    if (check_access(thd, INSERT_ACL, "mysql", NULL, NULL, 1, 0))
monty@mysql.com's avatar
monty@mysql.com committed
3335
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3336
#ifdef HAVE_DLOPEN
3337
    if (!(res = mysql_create_function(thd, &lex->udf)))
3338
      my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3339
#else
hf@deer.(none)'s avatar
hf@deer.(none) committed
3340
    my_error(ER_CANT_OPEN_LIBRARY, MYF(0), lex->udf.dl, 0, "feature disabled");
3341
    res= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3342 3343
#endif
    break;
monty@mysql.com's avatar
monty@mysql.com committed
3344
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
3345
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3346 3347
  case SQLCOM_CREATE_USER:
  {
Marc Alff's avatar
Marc Alff committed
3348
    if (check_access(thd, INSERT_ACL, "mysql", NULL, NULL, 1, 1) &&
3349
        check_global_access(thd,CREATE_USER_ACL))
3350
      break;
3351
    /* Conditionally writes to binlog */
3352
    if (!(res= mysql_create_user(thd, lex->users_list)))
3353
      my_ok(thd);
3354 3355
    break;
  }
3356 3357
  case SQLCOM_DROP_USER:
  {
Marc Alff's avatar
Marc Alff committed
3358
    if (check_access(thd, DELETE_ACL, "mysql", NULL, NULL, 1, 1) &&
3359
        check_global_access(thd,CREATE_USER_ACL))
3360
      break;
3361
    /* Conditionally writes to binlog */
3362
    if (!(res= mysql_drop_user(thd, lex->users_list)))
3363
      my_ok(thd);
3364 3365 3366 3367
    break;
  }
  case SQLCOM_RENAME_USER:
  {
Marc Alff's avatar
Marc Alff committed
3368
    if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) &&
3369
        check_global_access(thd,CREATE_USER_ACL))
3370
      break;
3371
    /* Conditionally writes to binlog */
3372
    if (!(res= mysql_rename_user(thd, lex->users_list)))
3373
      my_ok(thd);
3374 3375 3376 3377
    break;
  }
  case SQLCOM_REVOKE_ALL:
  {
Marc Alff's avatar
Marc Alff committed
3378
    if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) &&
3379
        check_global_access(thd,CREATE_USER_ACL))
3380
      break;
3381 3382 3383 3384

    /* Replicate current user as grantor */
    thd->binlog_invoker();

3385
    /* Conditionally writes to binlog */
3386
    if (!(res = mysql_revoke_all(thd, lex->users_list)))
3387
      my_ok(thd);
3388 3389
    break;
  }
3390 3391 3392
  case SQLCOM_REVOKE:
  case SQLCOM_GRANT:
  {
3393 3394
    if (lex->type != TYPE_ENUM_PROXY &&
        check_access(thd, lex->grant | lex->grant_tot_col | GRANT_ACL,
Marc Alff's avatar
Marc Alff committed
3395 3396 3397 3398
                     first_table ?  first_table->db : select_lex->db,
                     first_table ? &first_table->grant.privilege : NULL,
                     first_table ? &first_table->grant.m_internal : NULL,
                     first_table ? 0 : 1, 0))
3399 3400
      goto error;

3401 3402 3403
    /* Replicate current user as grantor */
    thd->binlog_invoker();

3404
    if (thd->security_ctx->user)              // If not replication
3405
    {
3406
      LEX_USER *user, *tmp_user;
3407
      bool first_user= TRUE;
3408

3409
      List_iterator <LEX_USER> user_list(lex->users_list);
3410
      while ((tmp_user= user_list++))
3411
      {
3412 3413
        if (!(user= get_current_user(thd, tmp_user)))
          goto error;
3414 3415 3416 3417 3418 3419 3420 3421
        if (specialflag & SPECIAL_NO_RESOLVE &&
            hostname_requires_resolving(user->host.str))
          push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                              ER_WARN_HOSTNAME_WONT_WORK,
                              ER(ER_WARN_HOSTNAME_WONT_WORK),
                              user->host.str);
        // Are we trying to change a password of another user
        DBUG_ASSERT(user->host.str != 0);
3422 3423 3424 3425 3426

        /*
          GRANT/REVOKE PROXY has the target user as a first entry in the list. 
         */
        if (lex->type == TYPE_ENUM_PROXY && first_user)
3427
        {
3428 3429 3430
          first_user= FALSE;
          if (acl_check_proxy_grant_access (thd, user->host.str, user->user.str,
                                        lex->grant & GRANT_ACL))
3431
            goto error;
3432 3433 3434 3435 3436 3437 3438
        } 
        else if (is_acl_user(user->host.str, user->user.str) &&
                 user->password.str &&
                 check_change_password (thd, user->host.str, user->user.str, 
                                        user->password.str, 
                                        user->password.length))
          goto error;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3439 3440
      }
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3441
    if (first_table)
3442
    {
3443 3444
      if (lex->type == TYPE_ENUM_PROCEDURE ||
          lex->type == TYPE_ENUM_FUNCTION)
3445 3446 3447 3448
      {
        uint grants= lex->all_privileges 
		   ? (PROC_ACLS & ~GRANT_ACL) | (lex->grant & GRANT_ACL)
		   : lex->grant;
3449
        if (check_grant_routine(thd, grants | GRANT_ACL, all_tables,
3450
                                lex->type == TYPE_ENUM_PROCEDURE, 0))
3451
	  goto error;
3452
        /* Conditionally writes to binlog */
3453 3454 3455
        res= mysql_routine_grant(thd, all_tables,
                                 lex->type == TYPE_ENUM_PROCEDURE, 
                                 lex->users_list, grants,
3456 3457 3458
                                 lex->sql_command == SQLCOM_REVOKE, TRUE);
        if (!res)
          my_ok(thd);
3459 3460 3461
      }
      else
      {
3462
	if (check_grant(thd,(lex->grant | lex->grant_tot_col | GRANT_ACL),
3463
                        all_tables, FALSE, UINT_MAX, FALSE))
3464
	  goto error;
3465
        /* Conditionally writes to binlog */
3466 3467 3468 3469
        res= mysql_table_grant(thd, all_tables, lex->users_list,
			       lex->columns, lex->grant,
			       lex->sql_command == SQLCOM_REVOKE);
      }
3470 3471 3472
    }
    else
    {
3473
      if (lex->columns.elements || (lex->type && lex->type != TYPE_ENUM_PROXY))
3474
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3475 3476
	my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
                   MYF(0));
3477
        goto error;
3478 3479
      }
      else
3480 3481 3482 3483 3484 3485
      {
        /* Conditionally writes to binlog */
        res = mysql_grant(thd, select_lex->db, lex->users_list, lex->grant,
                          lex->sql_command == SQLCOM_REVOKE,
                          lex->type == TYPE_ENUM_PROXY);
      }
3486 3487
      if (!res)
      {
3488
	if (lex->sql_command == SQLCOM_GRANT)
3489
	{
3490
	  List_iterator <LEX_USER> str_list(lex->users_list);
3491 3492 3493 3494 3495
	  LEX_USER *user, *tmp_user;
	  while ((tmp_user=str_list++))
          {
            if (!(user= get_current_user(thd, tmp_user)))
              goto error;
3496
	    reset_mqh(user, 0);
3497
          }
3498
	}
3499 3500 3501 3502
      }
    }
    break;
  }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3503
#endif /*!NO_EMBEDDED_ACCESS_CHECKS*/
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
3504
  case SQLCOM_RESET:
3505 3506 3507
    /*
      RESET commands are never written to the binary log, so we have to
      initialize this variable because RESET shares the same code as FLUSH
3508 3509 3510 3511
    */
    lex->no_write_to_binlog= 1;
  case SQLCOM_FLUSH:
  {
3512
    bool write_to_binlog;
3513

3514
    if (check_global_access(thd,RELOAD_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3515
      goto error;
3516

3517 3518
    if (first_table && lex->type & REFRESH_READ_LOCK)
    {
3519 3520 3521 3522
      /* Check table-level privileges. */
      if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, all_tables,
                             FALSE, UINT_MAX, FALSE))
        goto error;
3523 3524 3525 3526 3527 3528
      if (flush_tables_with_read_lock(thd, all_tables))
        goto error;
      my_ok(thd);
      break;
    }

3529 3530 3531 3532
    /*
      reload_acl_and_cache() will tell us if we are allowed to write to the
      binlog or not.
    */
3533
    if (!reload_acl_and_cache(thd, lex->type, first_table, &write_to_binlog))
3534 3535 3536 3537 3538
    {
      /*
        We WANT to write and we CAN write.
        ! we write after unlocking the table.
      */
3539 3540 3541
      /*
        Presumably, RESET and binlog writing doesn't require synchronization
      */
3542 3543
      if (!lex->no_write_to_binlog && write_to_binlog)
      {
Davi Arnaut's avatar
Davi Arnaut committed
3544
        if ((res= write_bin_log(thd, FALSE, thd->query(), thd->query_length())))
3545
          break;
3546
      }
3547
      my_ok(thd);
3548 3549
    } 
    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3550
    break;
3551
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3552
  case SQLCOM_KILL:
3553 3554 3555
  {
    Item *it= (Item *)lex->value_list.head();

3556 3557 3558 3559 3560 3561 3562
    if (lex->table_or_sp_used())
    {
      my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Usage of subqueries or stored "
               "function calls as part of this statement");
      break;
    }

3563
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1))
3564 3565 3566 3567 3568
    {
      my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY),
		 MYF(0));
      goto error;
    }
3569
    sql_kill(thd, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3570
    break;
3571
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
3572
#ifndef NO_EMBEDDED_ACCESS_CHECKS
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3573
  case SQLCOM_SHOW_GRANTS:
3574 3575 3576 3577
  {
    LEX_USER *grant_user= get_current_user(thd, lex->grant_user);
    if (!grant_user)
      goto error;
3578
    if ((thd->security_ctx->priv_user &&
3579
	 !strcmp(thd->security_ctx->priv_user, grant_user->user.str)) ||
Marc Alff's avatar
Marc Alff committed
3580
        !check_access(thd, SELECT_ACL, "mysql", NULL, NULL, 1, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3581
    {
3582
      res = mysql_show_grants(thd, grant_user);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3583 3584
    }
    break;
3585
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
3586
#endif
3587
  case SQLCOM_HA_OPEN:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3588
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3589
    if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE))
3590
      goto error;
monty@mysql.com's avatar
monty@mysql.com committed
3591
    res= mysql_ha_open(thd, first_table, 0);
3592 3593
    break;
  case SQLCOM_HA_CLOSE:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3594 3595
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    res= mysql_ha_close(thd, first_table);
3596 3597
    break;
  case SQLCOM_HA_READ:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3598
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3599 3600 3601 3602 3603
    /*
      There is no need to check for table permissions here, because
      if a user has no permissions to read a table, he won't be
      able to open it (with SQLCOM_HA_OPEN) in the first place.
    */
3604
    unit->set_limit(select_lex);
3605
    res= mysql_ha_read(thd, first_table, lex->ha_read_mode, lex->ident.str,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3606
                       lex->insert_list, lex->ha_rkey_mode, select_lex->where,
3607
                       unit->select_limit_cnt, unit->offset_limit_cnt);
3608 3609
    break;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3610
  case SQLCOM_BEGIN:
Konstantin Osipov's avatar
Konstantin Osipov committed
3611
    if (trans_begin(thd, lex->start_transaction_opt))
3612
      goto error;
3613
    my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3614 3615
    break;
  case SQLCOM_COMMIT:
3616
  {
3617 3618
    DBUG_ASSERT(thd->lock == NULL ||
                thd->locked_tables_mode == LTM_LOCK_TABLES);
3619 3620 3621 3622 3623 3624
    bool tx_chain= (lex->tx_chain == TVL_YES ||
                    (thd->variables.completion_type == 1 &&
                     lex->tx_chain != TVL_NO));
    bool tx_release= (lex->tx_release == TVL_YES ||
                      (thd->variables.completion_type == 2 &&
                       lex->tx_release != TVL_NO));
Konstantin Osipov's avatar
Konstantin Osipov committed
3625 3626
    if (trans_commit(thd))
      goto error;
3627
    thd->mdl_context.release_transactional_locks();
Konstantin Osipov's avatar
Konstantin Osipov committed
3628
    /* Begin transaction with the same isolation level. */
3629 3630 3631
    if (tx_chain)
    {
      if (trans_begin(thd))
3632
      goto error;
3633 3634 3635 3636 3637 3638
    }
    else
    {
      /* Reset the isolation level if no chaining transaction. */
      thd->tx_isolation= (enum_tx_isolation) thd->variables.tx_isolation;
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
3639
    /* Disconnect the current client connection. */
3640
    if (tx_release)
Konstantin Osipov's avatar
Konstantin Osipov committed
3641
      thd->killed= THD::KILL_CONNECTION;
3642
    my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3643
    break;
3644
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3645
  case SQLCOM_ROLLBACK:
3646
  {
3647 3648
    DBUG_ASSERT(thd->lock == NULL ||
                thd->locked_tables_mode == LTM_LOCK_TABLES);
3649 3650 3651 3652 3653 3654
    bool tx_chain= (lex->tx_chain == TVL_YES ||
                    (thd->variables.completion_type == 1 &&
                     lex->tx_chain != TVL_NO));
    bool tx_release= (lex->tx_release == TVL_YES ||
                      (thd->variables.completion_type == 2 &&
                       lex->tx_release != TVL_NO));
Konstantin Osipov's avatar
Konstantin Osipov committed
3655
    if (trans_rollback(thd))
3656
      goto error;
3657
    thd->mdl_context.release_transactional_locks();
Konstantin Osipov's avatar
Konstantin Osipov committed
3658
    /* Begin transaction with the same isolation level. */
3659 3660 3661 3662 3663 3664 3665 3666 3667 3668
    if (tx_chain)
    {
      if (trans_begin(thd))
        goto error;
    }
    else
    {
      /* Reset the isolation level if no chaining transaction. */
      thd->tx_isolation= (enum_tx_isolation) thd->variables.tx_isolation;
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
3669
    /* Disconnect the current client connection. */
3670
    if (tx_release)
Konstantin Osipov's avatar
Konstantin Osipov committed
3671
      thd->killed= THD::KILL_CONNECTION;
3672
    my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3673
    break;
3674
  }
serg@serg.mylan's avatar
serg@serg.mylan committed
3675
  case SQLCOM_RELEASE_SAVEPOINT:
Konstantin Osipov's avatar
Konstantin Osipov committed
3676 3677 3678
    if (trans_release_savepoint(thd, lex->ident))
      goto error;
    my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3679
    break;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3680
  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
Konstantin Osipov's avatar
Konstantin Osipov committed
3681 3682 3683
    if (trans_rollback_to_savepoint(thd, lex->ident))
      goto error;
    my_ok(thd);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3684
    break;
3685
  case SQLCOM_SAVEPOINT:
Konstantin Osipov's avatar
Konstantin Osipov committed
3686 3687 3688
    if (trans_savepoint(thd, lex->ident))
      goto error;
    my_ok(thd);
3689
    break;
3690 3691
  case SQLCOM_CREATE_PROCEDURE:
  case SQLCOM_CREATE_SPFUNCTION:
monty@mysql.com's avatar
monty@mysql.com committed
3692
  {
3693
    uint namelen;
3694
    char *name;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3695
    int sp_result= SP_INTERNAL_ERROR;
3696

3697
    DBUG_ASSERT(lex->sphead != 0);
3698
    DBUG_ASSERT(lex->sphead->m_db.str); /* Must be initialized in the parser */
3699 3700 3701 3702
    /*
      Verify that the database name is allowed, optionally
      lowercase it.
    */
3703
    if (check_db_name(&lex->sphead->m_db))
3704
    {
3705
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->sphead->m_db.str);
3706
      goto create_sp_error;
3707 3708
    }

3709
    /*
3710 3711 3712
      Check that a database directory with this name
      exists. Design note: This won't work on virtual databases
      like information_schema.
3713 3714
    */
    if (check_db_dir_existence(lex->sphead->m_db.str))
3715
    {
3716
      my_error(ER_BAD_DB_ERROR, MYF(0), lex->sphead->m_db.str);
3717
      goto create_sp_error;
3718
    }
3719

Marc Alff's avatar
Marc Alff committed
3720 3721
    if (check_access(thd, CREATE_PROC_ACL, lex->sphead->m_db.str,
                     NULL, NULL, 0, 0))
3722
      goto create_sp_error;
3723 3724

    name= lex->sphead->name(&namelen);
3725
#ifdef HAVE_DLOPEN
monty@mysql.com's avatar
monty@mysql.com committed
3726 3727 3728
    if (lex->sphead->m_type == TYPE_ENUM_FUNCTION)
    {
      udf_func *udf = find_udf(name, namelen);
3729

monty@mysql.com's avatar
monty@mysql.com committed
3730
      if (udf)
3731
      {
3732 3733
        my_error(ER_UDF_EXISTS, MYF(0), name);
        goto create_sp_error;
3734
      }
monty@mysql.com's avatar
monty@mysql.com committed
3735 3736 3737
    }
#endif

3738 3739
    if (sp_process_definer(thd))
      goto create_sp_error;
3740

Konstantin Osipov's avatar
Konstantin Osipov committed
3741
    res= (sp_result= sp_create_routine(thd, lex->sphead->m_type, lex->sphead));
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3742
    switch (sp_result) {
3743
    case SP_OK: {
3744
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3745
      /* only add privileges if really neccessary */
3746 3747 3748 3749 3750

      Security_context security_context;
      bool restore_backup_context= false;
      Security_context *backup= NULL;
      LEX_USER *definer= thd->lex->definer;
Konstantin Osipov's avatar
Konstantin Osipov committed
3751
      /*
3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764
        We're going to issue an implicit GRANT statement so we close all
        open tables. We have to keep metadata locks as this ensures that
        this statement is atomic against concurent FLUSH TABLES WITH READ
        LOCK. Deadlocks which can arise due to fact that this implicit
        statement takes metadata locks should be detected by a deadlock
        detector in MDL subsystem and reported as errors.

        No need to commit/rollback statement transaction, it's not started.

        TODO: Long-term we should either ensure that implicit GRANT statement
              is written into binary log as a separate statement or make both
              creation of routine and implicit GRANT parts of one fully atomic
              statement.
Konstantin Osipov's avatar
Konstantin Osipov committed
3765
      */
3766 3767
      DBUG_ASSERT(thd->transaction.stmt.is_empty());
      close_thread_tables(thd);
3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785
      /*
        Check if the definer exists on slave, 
        then use definer privilege to insert routine privileges to mysql.procs_priv.

        For current user of SQL thread has GLOBAL_ACL privilege, 
        which doesn't any check routine privileges, 
        so no routine privilege record  will insert into mysql.procs_priv.
      */
      if (thd->slave_thread && is_acl_user(definer->host.str, definer->user.str))
      {
        security_context.change_security_context(thd, 
                                                 &thd->lex->definer->user,
                                                 &thd->lex->definer->host,
                                                 &thd->lex->sphead->m_db,
                                                 &backup);
        restore_backup_context= true;
      }

3786
      if (sp_automatic_privileges && !opt_noacl &&
3787
          check_routine_access(thd, DEFAULT_CREATE_PROC_ACLS,
3788
                               lex->sphead->m_db.str, name,
3789
                               lex->sql_command == SQLCOM_CREATE_PROCEDURE, 1))
3790
      {
3791
        if (sp_grant_privileges(thd, lex->sphead->m_db.str, name,
3792
                                lex->sql_command == SQLCOM_CREATE_PROCEDURE))
3793
          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
3794 3795
                       ER_PROC_AUTO_GRANT_FAIL, ER(ER_PROC_AUTO_GRANT_FAIL));
        thd->clear_error();
3796
      }
3797 3798 3799 3800 3801 3802 3803 3804 3805 3806

      /*
        Restore current user with GLOBAL_ACL privilege of SQL thread
      */ 
      if (restore_backup_context)
      {
        DBUG_ASSERT(thd->slave_thread == 1);
        thd->security_ctx->restore_security_context(thd, backup);
      }

3807
#endif
monty@mysql.com's avatar
monty@mysql.com committed
3808
    break;
3809
    }
3810 3811 3812 3813 3814 3815 3816 3817 3818
    case SP_WRITE_ROW_FAILED:
      my_error(ER_SP_ALREADY_EXISTS, MYF(0), SP_TYPE_STRING(lex), name);
    break;
    case SP_BAD_IDENTIFIER:
      my_error(ER_TOO_LONG_IDENT, MYF(0), name);
    break;
    case SP_BODY_TOO_LONG:
      my_error(ER_TOO_LONG_BODY, MYF(0), name);
    break;
3819 3820 3821
    case SP_FLD_STORE_FAILED:
      my_error(ER_CANT_CREATE_SROUTINE, MYF(0), name);
      break;
3822 3823 3824 3825 3826 3827 3828 3829 3830 3831
    default:
      my_error(ER_SP_STORE_FAILED, MYF(0), SP_TYPE_STRING(lex), name);
    break;
    } /* end switch */

    /*
      Capture all errors within this CASE and
      clean up the environment.
    */
create_sp_error:
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3832
    if (sp_result != SP_OK )
3833
      goto error;
3834
    my_ok(thd);
3835 3836
    break; /* break super switch */
  } /* end case group bracket */
3837 3838 3839
  case SQLCOM_CALL:
    {
      sp_head *sp;
3840 3841 3842 3843
      /*
        This will cache all SP and SF and open and lock all tables
        required for execution.
      */
3844 3845
      if (check_table_access(thd, SELECT_ACL, all_tables, FALSE,
                             UINT_MAX, FALSE) ||
3846
          open_and_lock_tables(thd, all_tables, TRUE, 0))
3847 3848 3849
       goto error;

      /*
3850 3851
        By this moment all needed SPs should be in cache so no need to look 
        into DB. 
3852
      */
3853 3854
      if (!(sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                                &thd->sp_proc_cache, TRUE)))
3855
      {
3856
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PROCEDURE",
3857
                 lex->spname->m_qname.str);
3858
	goto error;
3859 3860 3861
      }
      else
      {
pem@mysql.comhem.se's avatar
pem@mysql.comhem.se committed
3862
	ha_rows select_limit;
monty@mysql.com's avatar
monty@mysql.com committed
3863 3864
        /* bits that should be cleared in thd->server_status */
	uint bits_to_be_cleared= 0;
3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876
        /*
          Check that the stored procedure doesn't contain Dynamic SQL
          and doesn't return result sets: such stored procedures can't
          be called from a function or trigger.
        */
        if (thd->in_sub_stmt)
        {
          const char *where= (thd->in_sub_stmt & SUB_STMT_TRIGGER ?
                              "trigger" : "function");
          if (sp->is_not_allowed_in_function(where))
            goto error;
        }
3877

3878
	if (sp->m_flags & sp_head::MULTI_RESULTS)
3879
	{
3880
	  if (! (thd->client_capabilities & CLIENT_MULTI_RESULTS))
3881
	  {
3882 3883 3884 3885
            /*
              The client does not support multiple result sets being sent
              back
            */
3886
	    my_error(ER_SP_BADSELECT, MYF(0), sp->m_qname.str);
3887 3888
	    goto error;
	  }
monty@mysql.com's avatar
monty@mysql.com committed
3889 3890 3891 3892 3893 3894 3895
          /*
            If SERVER_MORE_RESULTS_EXISTS is not set,
            then remember that it should be cleared
          */
	  bits_to_be_cleared= (~thd->server_status &
                               SERVER_MORE_RESULTS_EXISTS);
	  thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
3896 3897
	}

3898
	if (check_routine_access(thd, EXECUTE_ACL,
3899
				 sp->m_db.str, sp->m_name.str, TRUE, FALSE))
3900 3901 3902
	{
	  goto error;
	}
pem@mysql.comhem.se's avatar
pem@mysql.comhem.se committed
3903 3904
	select_limit= thd->variables.select_limit;
	thd->variables.select_limit= HA_POS_ERROR;
3905

3906
        /* 
3907
          We never write CALL statements into binlog:
3908 3909 3910 3911 3912
           - If the mode is non-prelocked, each statement will be logged
             separately.
           - If the mode is prelocked, the invoking statement will care
             about writing into binlog.
          So just execute the statement.
3913
        */
3914
	res= sp->execute_procedure(thd, &lex->value_list);
3915

pem@mysql.comhem.se's avatar
pem@mysql.comhem.se committed
3916
	thd->variables.select_limit= select_limit;
3917

monty@mysql.com's avatar
monty@mysql.com committed
3918
        thd->server_status&= ~bits_to_be_cleared;
3919

3920
	if (!res)
3921 3922 3923
        {
          my_ok(thd, (thd->get_row_count_func() < 0) ? 0 : thd->get_row_count_func());
        }
3924
	else
3925
        {
3926
          DBUG_ASSERT(thd->is_error() || thd->killed);
3927
	  goto error;		// Substatement should already have sent error
3928
        }
3929
      }
3930
      break;
3931 3932
    }
  case SQLCOM_ALTER_PROCEDURE:
3933
  case SQLCOM_ALTER_FUNCTION:
3934
    {
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3935
      int sp_result;
Konstantin Osipov's avatar
Konstantin Osipov committed
3936 3937
      int type= (lex->sql_command == SQLCOM_ALTER_PROCEDURE ?
                 TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION);
anozdrin/alik@ibm's avatar
anozdrin/alik@ibm committed
3938

Konstantin Osipov's avatar
Konstantin Osipov committed
3939 3940 3941 3942
      if (check_routine_access(thd, ALTER_PROC_ACL, lex->spname->m_db.str,
                               lex->spname->m_name.str,
                               lex->sql_command == SQLCOM_ALTER_PROCEDURE, 0))
        goto error;
anozdrin/alik@ibm's avatar
anozdrin/alik@ibm committed
3943

Konstantin Osipov's avatar
Konstantin Osipov committed
3944 3945 3946 3947 3948 3949 3950 3951
      /*
        Note that if you implement the capability of ALTER FUNCTION to
        alter the body of the function, this command should be made to
        follow the restrictions that log-bin-trust-function-creators=0
        already puts on CREATE FUNCTION.
      */
      /* Conditionally writes to binlog */
      sp_result= sp_update_routine(thd, type, lex->spname, &lex->sp_chistics);
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3952
      switch (sp_result)
3953
      {
3954
      case SP_OK:
3955
	my_ok(thd);
3956 3957
	break;
      case SP_KEY_NOT_FOUND:
3958 3959
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
3960 3961
	goto error;
      default:
3962 3963
	my_error(ER_SP_CANT_ALTER, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
3964
	goto error;
3965
      }
3966
      break;
3967 3968
    }
  case SQLCOM_DROP_PROCEDURE:
3969
  case SQLCOM_DROP_FUNCTION:
3970
    {
3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011
#ifdef HAVE_DLOPEN
      if (lex->sql_command == SQLCOM_DROP_FUNCTION &&
          ! lex->spname->m_explicit_name)
      {
        /* DROP FUNCTION <non qualified name> */
        udf_func *udf = find_udf(lex->spname->m_name.str,
                                 lex->spname->m_name.length);
        if (udf)
        {
          if (check_access(thd, DELETE_ACL, "mysql", NULL, NULL, 1, 0))
            goto error;

          if (!(res = mysql_drop_function(thd, &lex->spname->m_name)))
          {
            my_ok(thd);
            break;
          }
          my_error(ER_SP_DROP_FAILED, MYF(0),
                   "FUNCTION (UDF)", lex->spname->m_name.str);
          goto error;
        }

        if (lex->spname->m_db.str == NULL)
        {
          if (lex->drop_if_exists)
          {
            push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
                                ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST),
                                "FUNCTION (UDF)", lex->spname->m_name.str);
            res= FALSE;
            my_ok(thd);
            break;
          }
          my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                   "FUNCTION (UDF)", lex->spname->m_name.str);
          goto error;
        }
        /* Fall thought to test for a stored function */
      }
#endif

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4012
      int sp_result;
4013 4014
      int type= (lex->sql_command == SQLCOM_DROP_PROCEDURE ?
                 TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION);
4015 4016
      char *db= lex->spname->m_db.str;
      char *name= lex->spname->m_name.str;
4017

4018 4019 4020
      if (check_routine_access(thd, ALTER_PROC_ACL, db, name,
                               lex->sql_command == SQLCOM_DROP_PROCEDURE, 0))
        goto error;
4021

4022 4023
      /* Conditionally writes to binlog */
      sp_result= sp_drop_routine(thd, type, lex->spname);
4024

Konstantin Osipov's avatar
Konstantin Osipov committed
4025
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4026
      /*
4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039
        We're going to issue an implicit REVOKE statement so we close all
        open tables. We have to keep metadata locks as this ensures that
        this statement is atomic against concurent FLUSH TABLES WITH READ
        LOCK. Deadlocks which can arise due to fact that this implicit
        statement takes metadata locks should be detected by a deadlock
        detector in MDL subsystem and reported as errors.

        No need to commit/rollback statement transaction, it's not started.

        TODO: Long-term we should either ensure that implicit REVOKE statement
              is written into binary log as a separate statement or make both
              dropping of routine and implicit REVOKE parts of one fully atomic
              statement.
4040
      */
4041 4042
      DBUG_ASSERT(thd->transaction.stmt.is_empty());
      close_thread_tables(thd);
4043

4044 4045 4046 4047 4048 4049 4050 4051 4052 4053
      if (sp_result != SP_KEY_NOT_FOUND &&
          sp_automatic_privileges && !opt_noacl &&
          sp_revoke_privileges(thd, db, name,
                               lex->sql_command == SQLCOM_DROP_PROCEDURE))
      {
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                     ER_PROC_AUTO_REVOKE_FAIL,
                     ER(ER_PROC_AUTO_REVOKE_FAIL));
        /* If this happens, an error should have been reported. */
        goto error;
4054
      }
4055 4056
#endif

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4057 4058
      res= sp_result;
      switch (sp_result) {
4059
      case SP_OK:
4060
	my_ok(thd);
4061 4062
	break;
      case SP_KEY_NOT_FOUND:
4063 4064
	if (lex->drop_if_exists)
	{
4065
          res= write_bin_log(thd, TRUE, thd->query(), thd->query_length());
4066
	  push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
4067
			      ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST),
4068
                              SP_COM_STRING(lex), lex->spname->m_qname.str);
4069 4070
          if (!res)
            my_ok(thd);
4071 4072
	  break;
	}
4073 4074
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4075 4076
	goto error;
      default:
4077 4078
	my_error(ER_SP_DROP_FAILED, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4079
	goto error;
4080
      }
4081
      break;
4082
    }
4083 4084
  case SQLCOM_SHOW_CREATE_PROC:
    {
anozdrin/alik@ibm's avatar
anozdrin/alik@ibm committed
4085
      if (sp_show_create_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname))
Konstantin Osipov's avatar
Konstantin Osipov committed
4086
        goto error;
4087 4088 4089 4090
      break;
    }
  case SQLCOM_SHOW_CREATE_FUNC:
    {
anozdrin/alik@ibm's avatar
anozdrin/alik@ibm committed
4091
      if (sp_show_create_routine(thd, TYPE_ENUM_FUNCTION, lex->spname))
4092 4093 4094
	goto error;
      break;
    }
pem@mysql.com's avatar
pem@mysql.com committed
4095 4096 4097
  case SQLCOM_SHOW_PROC_CODE:
  case SQLCOM_SHOW_FUNC_CODE:
    {
4098
#ifndef DBUG_OFF
pem@mysql.com's avatar
pem@mysql.com committed
4099
      sp_head *sp;
Konstantin Osipov's avatar
Konstantin Osipov committed
4100 4101
      int type= (lex->sql_command == SQLCOM_SHOW_PROC_CODE ?
                 TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION);
pem@mysql.com's avatar
pem@mysql.com committed
4102

Konstantin Osipov's avatar
Konstantin Osipov committed
4103 4104
      if (sp_cache_routine(thd, type, lex->spname, FALSE, &sp))
        goto error;
4105
      if (!sp || sp->show_routine_code(thd))
4106 4107
      {
        /* We don't distinguish between errors for now */
pem@mysql.com's avatar
pem@mysql.com committed
4108 4109 4110 4111 4112
        my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
        goto error;
      }
      break;
4113 4114 4115 4116
#else
      my_error(ER_FEATURE_DISABLED, MYF(0),
               "SHOW PROCEDURE|FUNCTION CODE", "--with-debug");
      goto error;
pem@mysql.com's avatar
pem@mysql.com committed
4117
#endif // ifndef DBUG_OFF
4118
    }
4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131
  case SQLCOM_SHOW_CREATE_TRIGGER:
    {
      if (lex->spname->m_name.length > NAME_LEN)
      {
        my_error(ER_TOO_LONG_IDENT, MYF(0), lex->spname->m_name.str);
        goto error;
      }

      if (show_create_trigger(thd, lex->spname))
        goto error; /* Error has been already logged. */

      break;
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4132 4133
  case SQLCOM_CREATE_VIEW:
    {
4134 4135 4136 4137
      /*
        Note: SQLCOM_CREATE_VIEW also handles 'ALTER VIEW' commands
        as specified through the thd->lex->create_view_mode flag.
      */
4138
      res= mysql_create_view(thd, first_table, thd->lex->create_view_mode);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4139 4140 4141 4142
      break;
    }
  case SQLCOM_DROP_VIEW:
    {
Konstantin Osipov's avatar
Konstantin Osipov committed
4143
      if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE))
4144
        goto error;
4145 4146
      /* Conditionally writes to binlog. */
      res= mysql_drop_view(thd, first_table, thd->lex->drop_mode);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4147 4148
      break;
    }
4149 4150
  case SQLCOM_CREATE_TRIGGER:
  {
4151
    /* Conditionally writes to binlog. */
4152 4153
    res= mysql_create_or_drop_trigger(thd, all_tables, 1);

4154 4155 4156 4157
    break;
  }
  case SQLCOM_DROP_TRIGGER:
  {
4158
    /* Conditionally writes to binlog. */
4159 4160 4161
    res= mysql_create_or_drop_trigger(thd, all_tables, 0);
    break;
  }
4162
  case SQLCOM_XA_START:
Konstantin Osipov's avatar
Konstantin Osipov committed
4163 4164
    if (trans_xa_start(thd))
      goto error;
4165
    my_ok(thd);
4166 4167
    break;
  case SQLCOM_XA_END:
Konstantin Osipov's avatar
Konstantin Osipov committed
4168 4169
    if (trans_xa_end(thd))
      goto error;
4170
    my_ok(thd);
4171 4172
    break;
  case SQLCOM_XA_PREPARE:
Konstantin Osipov's avatar
Konstantin Osipov committed
4173 4174
    if (trans_xa_prepare(thd))
      goto error;
4175
    my_ok(thd);
4176 4177
    break;
  case SQLCOM_XA_COMMIT:
Konstantin Osipov's avatar
Konstantin Osipov committed
4178 4179
    if (trans_xa_commit(thd))
      goto error;
4180
    thd->mdl_context.release_transactional_locks();
4181 4182 4183 4184 4185
    /*
      We've just done a commit, reset transaction
      isolation level to the session default.
    */
    thd->tx_isolation= (enum_tx_isolation) thd->variables.tx_isolation;
Konstantin Osipov's avatar
Konstantin Osipov committed
4186
    my_ok(thd);
4187 4188
    break;
  case SQLCOM_XA_ROLLBACK:
Konstantin Osipov's avatar
Konstantin Osipov committed
4189 4190
    if (trans_xa_rollback(thd))
      goto error;
4191
    thd->mdl_context.release_transactional_locks();
4192 4193 4194 4195 4196
    /*
      We've just done a rollback, reset transaction
      isolation level to the session default.
    */
    thd->tx_isolation= (enum_tx_isolation) thd->variables.tx_isolation;
Konstantin Osipov's avatar
Konstantin Osipov committed
4197
    my_ok(thd);
4198 4199
    break;
  case SQLCOM_XA_RECOVER:
4200
    res= mysql_xa_recover(thd);
4201
    break;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
4202
  case SQLCOM_ALTER_TABLESPACE:
4203
    if (check_global_access(thd, CREATE_TABLESPACE_ACL))
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
4204 4205
      break;
    if (!(res= mysql_alter_tablespace(thd, lex->alter_tablespace_info)))
4206
      my_ok(thd);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
4207 4208 4209 4210
    break;
  case SQLCOM_INSTALL_PLUGIN:
    if (! (res= mysql_install_plugin(thd, &thd->lex->comment,
                                     &thd->lex->ident)))
4211
      my_ok(thd);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
4212 4213 4214
    break;
  case SQLCOM_UNINSTALL_PLUGIN:
    if (! (res= mysql_uninstall_plugin(thd, &thd->lex->comment)))
4215
      my_ok(thd);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
4216 4217 4218 4219 4220 4221 4222 4223 4224 4225
    break;
  case SQLCOM_BINLOG_BASE64_EVENT:
  {
#ifndef EMBEDDED_LIBRARY
    mysql_client_binlog_statement(thd);
#else /* EMBEDDED_LIBRARY */
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "embedded");
#endif /* EMBEDDED_LIBRARY */
    break;
  }
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4226 4227 4228 4229 4230
  case SQLCOM_CREATE_SERVER:
  {
    int error;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_CREATE_SERVER"));
4231 4232 4233 4234

    if (check_global_access(thd, SUPER_ACL))
      break;

patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4235 4236
    if ((error= create_server(thd, &lex->server_options)))
    {
4237
      DBUG_PRINT("info", ("problem creating server <%s>",
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4238 4239 4240 4241
                          lex->server_options.server_name));
      my_error(error, MYF(0), lex->server_options.server_name);
      break;
    }
4242
    my_ok(thd, 1);
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4243 4244 4245 4246 4247 4248 4249
    break;
  }
  case SQLCOM_ALTER_SERVER:
  {
    int error;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_ALTER_SERVER"));
4250 4251 4252 4253

    if (check_global_access(thd, SUPER_ACL))
      break;

patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4254 4255
    if ((error= alter_server(thd, &lex->server_options)))
    {
4256
      DBUG_PRINT("info", ("problem altering server <%s>",
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4257 4258 4259 4260
                          lex->server_options.server_name));
      my_error(error, MYF(0), lex->server_options.server_name);
      break;
    }
4261
    my_ok(thd, 1);
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4262 4263 4264 4265 4266 4267 4268
    break;
  }
  case SQLCOM_DROP_SERVER:
  {
    int err_code;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_DROP_SERVER"));
4269 4270 4271 4272

    if (check_global_access(thd, SUPER_ACL))
      break;

patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4273 4274
    if ((err_code= drop_server(thd, &lex->server_options)))
    {
4275
      if (! lex->drop_if_exists && err_code == ER_FOREIGN_SERVER_DOESNT_EXIST)
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4276 4277 4278 4279 4280 4281 4282
      {
        DBUG_PRINT("info", ("problem dropping server %s",
                            lex->server_options.server_name));
        my_error(err_code, MYF(0), lex->server_options.server_name);
      }
      else
      {
4283
        my_ok(thd, 0);
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4284 4285 4286
      }
      break;
    }
4287
    my_ok(thd, 1);
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4288 4289
    break;
  }
4290 4291 4292 4293 4294 4295 4296 4297
  case SQLCOM_ANALYZE:
  case SQLCOM_CHECK:
  case SQLCOM_OPTIMIZE:
  case SQLCOM_REPAIR:
  case SQLCOM_TRUNCATE:
  case SQLCOM_ALTER_TABLE:
      DBUG_ASSERT(first_table == all_tables && first_table != 0);
    /* fall through */
Marc Alff's avatar
Marc Alff committed
4298 4299 4300 4301 4302
  case SQLCOM_SIGNAL:
  case SQLCOM_RESIGNAL:
    DBUG_ASSERT(lex->m_stmt != NULL);
    res= lex->m_stmt->execute(thd);
    break;
4303
  default:
4304
#ifndef EMBEDDED_LIBRARY
4305
    DBUG_ASSERT(0);                             /* Impossible */
4306
#endif
4307
    my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4308 4309
    break;
  }
4310
  thd_proc_info(thd, "query end");
4311 4312

  /*
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
4313
    Binlog-related cleanup:
4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324
    Reset system variables temporarily modified by SET ONE SHOT.

    Exception: If this is a SET, do nothing. This is to allow
    mysqlbinlog to print many SET commands (in this case we want the
    charset temp setting to live until the real query). This is also
    needed so that SET CHARACTER_SET_CLIENT... does not cancel itself
    immediately.
  */
  if (thd->one_shot_set && lex->sql_command != SQLCOM_SET_OPTION)
    reset_one_shot_variables(thd);

4325
  goto finish;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4326 4327

error:
4328 4329
  res= TRUE;

4330
finish:
Konstantin Osipov's avatar
Konstantin Osipov committed
4331

4332 4333 4334
  DBUG_ASSERT(!thd->in_active_multi_stmt_transaction() ||
               thd->in_multi_stmt_transaction_mode());

4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365

  if (! thd->in_sub_stmt)
  {
    /* report error issued during command execution */
    if (thd->killed_errno())
    {
      if (! thd->stmt_da->is_set())
        thd->send_kill_message();
    }
    if (thd->killed == THD::KILL_QUERY || thd->killed == THD::KILL_BAD_DATA)
    {
      thd->killed= THD::NOT_KILLED;
      thd->mysys_var->abort= 0;
    }
    if (thd->is_error() || (thd->variables.option_bits & OPTION_MASTER_SQL_ERROR))
      trans_rollback_stmt(thd);
    else
    {
      /* If commit fails, we should be able to reset the OK status. */
      thd->stmt_da->can_overwrite_status= TRUE;
      trans_commit_stmt(thd);
      thd->stmt_da->can_overwrite_status= FALSE;
    }
  }

  lex->unit.cleanup();
  /* Free tables */
  thd_proc_info(thd, "closing tables");
  close_thread_tables(thd);
  thd_proc_info(thd, 0);

4366 4367 4368 4369 4370
#ifndef DBUG_OFF
  if (lex->sql_command != SQLCOM_SET_OPTION && ! thd->in_sub_stmt)
    DEBUG_SYNC(thd, "execute_command_after_close_tables");
#endif

4371 4372
  if (stmt_causes_implicit_commit(thd, CF_IMPLICIT_COMMIT_END))
  {
4373 4374
    /* No transaction control allowed in sub-statements. */
    DBUG_ASSERT(! thd->in_sub_stmt);
4375 4376 4377 4378
    /* If commit fails, we should be able to reset the OK status. */
    thd->stmt_da->can_overwrite_status= TRUE;
    /* Commit the normal transaction if one is active. */
    trans_commit_implicit(thd);
4379
    thd->stmt_da->can_overwrite_status= FALSE;
4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393
    thd->mdl_context.release_transactional_locks();
  }
  else if (! thd->in_sub_stmt && ! thd->in_multi_stmt_transaction_mode())
  {
    /*
      - If inside a multi-statement transaction,
      defer the release of metadata locks until the current
      transaction is either committed or rolled back. This prevents
      other statements from modifying the table for the entire
      duration of this transaction.  This provides commit ordering
      and guarantees serializability across multiple transactions.
      - If in autocommit mode, or outside a transactional context,
      automatically release metadata locks of the current statement.
    */
4394
    thd->mdl_context.release_transactional_locks();
4395
  }
4396 4397 4398 4399
  else if (! thd->in_sub_stmt)
  {
    thd->mdl_context.release_statement_locks();
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
4400

4401
  DBUG_RETURN(res || thd->is_error());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4402 4403 4404
}


4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416
static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables)
{
  LEX	*lex= thd->lex;
  select_result *result=lex->result;
  bool res;
  /* assign global limit variable if limit is not given */
  {
    SELECT_LEX *param= lex->unit.global_parameters;
    if (!param->explicit_limit)
      param->select_limit=
        new Item_int((ulonglong) thd->variables.select_limit);
  }
4417
  if (!(res= open_and_lock_tables(thd, all_tables, TRUE, 0)))
4418 4419 4420 4421 4422 4423 4424 4425 4426 4427
  {
    if (lex->describe)
    {
      /*
        We always use select_send for EXPLAIN, even if it's an EXPLAIN
        for SELECT ... INTO OUTFILE: a user application should be able
        to prepend EXPLAIN to any query and receive output for it,
        even if the query itself redirects the output.
      */
      if (!(result= new select_send()))
4428
        return 1;                               /* purecov: inspected */
4429 4430 4431 4432 4433 4434 4435
      thd->send_explain_fields(result);
      res= mysql_explain_union(thd, &thd->lex->unit, result);
      if (lex->describe & DESCRIBE_EXTENDED)
      {
        char buff[1024];
        String str(buff,(uint32) sizeof(buff), system_charset_info);
        str.length(0);
4436
        thd->lex->unit.print(&str, QT_ORDINARY);
4437 4438 4439 4440
        str.append('\0');
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
                     ER_YES, str.ptr());
      }
4441
      if (res)
4442
        result->abort_result_set();
4443 4444
      else
        result->send_eof();
4445 4446 4447 4448 4449
      delete result;
    }
    else
    {
      if (!result && !(result= new select_send()))
4450
        return 1;                               /* purecov: inspected */
4451 4452 4453 4454 4455 4456 4457 4458 4459 4460
      query_cache_store_query(thd, all_tables);
      res= handle_select(thd, lex, result, 0);
      if (result != lex->result)
        delete result;
    }
  }
  return res;
}


4461
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4462
/**
4463
  Check grants for commands which work only with one table.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4464

4465 4466 4467
  @param thd                    Thread handler
  @param privilege              requested privilege
  @param all_tables             global table list of query
4468
  @param no_errors              FALSE/TRUE - report/don't report error to
4469
                            the client (using my_error() call).
4470 4471 4472 4473 4474

  @retval
    0   OK
  @retval
    1   access denied, error is sent to client
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4475 4476
*/

4477
bool check_single_table_access(THD *thd, ulong privilege, 
4478
                               TABLE_LIST *all_tables, bool no_errors)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4479
{
4480 4481 4482 4483 4484 4485
  Security_context * backup_ctx= thd->security_ctx;

  /* we need to switch to the saved context (if any) */
  if (all_tables->security_ctx)
    thd->security_ctx= all_tables->security_ctx;

4486 4487 4488 4489 4490 4491 4492 4493
  const char *db_name;
  if ((all_tables->view || all_tables->field_translation) &&
      !all_tables->schema_table)
    db_name= all_tables->view_db.str;
  else
    db_name= all_tables->db;

  if (check_access(thd, privilege, db_name,
Marc Alff's avatar
Marc Alff committed
4494 4495 4496
                   &all_tables->grant.privilege,
                   &all_tables->grant.m_internal,
                   0, no_errors))
4497
    goto deny;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4498

4499
  /* Show only 1 table for check_grant */
4500
  if (!(all_tables->belong_to_view &&
4501
        (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) &&
4502
      check_grant(thd, privilege, all_tables, FALSE, 1, no_errors))
4503 4504 4505
    goto deny;

  thd->security_ctx= backup_ctx;
4506 4507 4508 4509 4510 4511 4512
  return 0;

deny:
  thd->security_ctx= backup_ctx;
  return 1;
}

4513
/**
4514 4515 4516
  Check grants for commands which work only with one table and all other
  tables belonging to subselects or implicitly opened tables.

4517 4518 4519 4520 4521 4522 4523 4524
  @param thd			Thread handler
  @param privilege		requested privilege
  @param all_tables		global table list of query

  @retval
    0   OK
  @retval
    1   access denied, error is sent to client
4525 4526 4527 4528
*/

bool check_one_table_access(THD *thd, ulong privilege, TABLE_LIST *all_tables)
{
4529
  if (check_single_table_access (thd,privilege,all_tables, FALSE))
4530
    return 1;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4531

4532
  /* Check rights on tables of subselects and implictly opened tables */
4533
  TABLE_LIST *subselects_tables, *view= all_tables->view ? all_tables : 0;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4534
  if ((subselects_tables= all_tables->next_global))
monty@mysql.com's avatar
monty@mysql.com committed
4535
  {
4536 4537 4538 4539 4540 4541
    /*
      Access rights asked for the first table of a view should be the same
      as for the view
    */
    if (view && subselects_tables->belong_to_view == view)
    {
4542
      if (check_single_table_access (thd, privilege, subselects_tables, FALSE))
4543 4544 4545 4546
        return 1;
      subselects_tables= subselects_tables->next_global;
    }
    if (subselects_tables &&
4547 4548
        (check_table_access(thd, SELECT_ACL, subselects_tables, FALSE,
                            UINT_MAX, FALSE)))
4549
      return 1;
monty@mysql.com's avatar
monty@mysql.com committed
4550 4551
  }
  return 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4552 4553 4554
}


4555
/**
4556 4557 4558 4559 4560 4561
  @brief Compare requested privileges with the privileges acquired from the
    User- and Db-tables.
  @param thd          Thread handler
  @param want_access  The requested access privileges.
  @param db           A pointer to the Db name.
  @param[out] save_priv A pointer to the granted privileges will be stored.
Marc Alff's avatar
Marc Alff committed
4562
  @param grant_internal_info A pointer to the internal grant cache.
4563 4564 4565 4566 4567 4568 4569 4570
  @param dont_check_global_grants True if no global grants are checked.
  @param no_error     True if no errors should be sent to the client.

  'save_priv' is used to save the User-table (global) and Db-table grants for
  the supplied db name. Note that we don't store db level grants if the global
  grants is enough to satisfy the request AND the global grants contains a
  SELECT grant.

Marc Alff's avatar
Marc Alff committed
4571 4572
  For internal databases (INFORMATION_SCHEMA, PERFORMANCE_SCHEMA),
  additional rules apply, see ACL_internal_schema_access.
4573 4574 4575 4576 4577 4578 4579

  @see check_grant

  @return Status of denial of access by exclusive ACLs.
    @retval FALSE Access can't exclusively be denied by Db- and User-table
      access unless Column- and Table-grants are checked too.
    @retval TRUE Access denied.
4580
*/
4581

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4582
bool
4583
check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv,
Marc Alff's avatar
Marc Alff committed
4584 4585
             GRANT_INTERNAL_INFO *grant_internal_info,
             bool dont_check_global_grants, bool no_errors)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4586
{
4587
  Security_context *sctx= thd->security_ctx;
4588
  ulong db_access;
4589

4590 4591 4592 4593 4594
  /*
    GRANT command:
    In case of database level grant the database name may be a pattern,
    in case of table|column level grant the database name can not be a pattern.
    We use 'dont_check_global_grants' as a flag to determine
4595
    if it's database level grant command
4596 4597 4598
    (see SQLCOM_GRANT case, mysql_execute_command() function) and
    set db_is_pattern according to 'dont_check_global_grants' value.
  */
4599
  bool  db_is_pattern= ((want_access & GRANT_ACL) && dont_check_global_grants);
4600
  ulong dummy;
4601 4602
  DBUG_ENTER("check_access");
  DBUG_PRINT("enter",("db: %s  want_access: %lu  master_access: %lu",
4603
                      db ? db : "", want_access, sctx->master_access));
4604

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4605 4606 4607
  if (save_priv)
    *save_priv=0;
  else
Marc Alff's avatar
Marc Alff committed
4608
  {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4609
    save_priv= &dummy;
Marc Alff's avatar
Marc Alff committed
4610 4611
    dummy= 0;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4612

4613
  thd_proc_info(thd, "checking permissions");
4614
  if ((!db || !db[0]) && !thd->db && !dont_check_global_grants)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4615
  {
4616
    DBUG_PRINT("error",("No database"));
4617
    if (!no_errors)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4618 4619
      my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR),
                 MYF(0));                       /* purecov: tested */
4620
    DBUG_RETURN(TRUE);				/* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4621 4622
  }

Marc Alff's avatar
Marc Alff committed
4623
  if ((db != NULL) && (db != any_db))
4624
  {
Marc Alff's avatar
Marc Alff committed
4625 4626 4627
    const ACL_internal_schema_access *access;
    access= get_cached_schema_access(grant_internal_info, db);
    if (access)
4628
    {
Marc Alff's avatar
Marc Alff committed
4629
      switch (access->check(want_access, save_priv))
4630
      {
Marc Alff's avatar
Marc Alff committed
4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650
      case ACL_INTERNAL_ACCESS_GRANTED:
        /*
          All the privileges requested have been granted internally.
          [out] *save_privileges= Internal privileges.
        */
        DBUG_RETURN(FALSE);
      case ACL_INTERNAL_ACCESS_DENIED:
        if (! no_errors)
        {
          my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
                   sctx->priv_user, sctx->priv_host, db);
        }
        DBUG_RETURN(TRUE);
      case ACL_INTERNAL_ACCESS_CHECK_GRANT:
        /*
          Only some of the privilege requested have been granted internally,
          proceed with the remaining bits of the request (want_access).
        */
        want_access&= ~(*save_priv);
        break;
4651
      }
4652 4653 4654
    }
  }

4655
  if ((sctx->master_access & want_access) == want_access)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4656
  {
4657
    /*
4658 4659
      1. If we don't have a global SELECT privilege, we have to get the
      database specific access rights to be able to handle queries of type
4660
      UPDATE t1 SET a=1 WHERE b > 0
4661
      2. Change db access if it isn't current db which is being addressed
4662
    */
Marc Alff's avatar
Marc Alff committed
4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681
    if (!(sctx->master_access & SELECT_ACL))
    {
      if (db && (!thd->db || db_is_pattern || strcmp(db, thd->db)))
        db_access= acl_get(sctx->host, sctx->ip, sctx->priv_user, db,
                           db_is_pattern);
      else
      {
        /* get access for current db */
        db_access= sctx->db_access;
      }
      /*
        The effective privileges are the union of the global privileges
        and the intersection of db- and host-privileges,
        plus the internal privileges.
      */
      *save_priv|= sctx->master_access | db_access;
    }
    else
      *save_priv|= sctx->master_access;
4682
    DBUG_RETURN(FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4683
  }
4684
  if (((want_access & ~sctx->master_access) & ~DB_ACLS) ||
4685
      (! db && dont_check_global_grants))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4686
  {						// We can never grant this
4687
    DBUG_PRINT("error",("No possible access"));
4688
    if (!no_errors)
4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701
    {
      if (thd->password == 2)
        my_error(ER_ACCESS_DENIED_NO_PASSWORD_ERROR, MYF(0),
                 sctx->priv_user,
                 sctx->priv_host);
      else
        my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
                 sctx->priv_user,
                 sctx->priv_host,
                 (thd->password ?
                  ER(ER_YES) :
                  ER(ER_NO)));                    /* purecov: tested */
    }
4702
    DBUG_RETURN(TRUE);				/* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4703 4704 4705
  }

  if (db == any_db)
4706 4707 4708 4709 4710 4711 4712
  {
    /*
      Access granted; Allow select on *any* db.
      [out] *save_privileges= 0
    */
    DBUG_RETURN(FALSE);
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
4713

4714
  if (db && (!thd->db || db_is_pattern || strcmp(db,thd->db)))
4715 4716
    db_access= acl_get(sctx->host, sctx->ip, sctx->priv_user, db,
                       db_is_pattern);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4717
  else
4718
    db_access= sctx->db_access;
4719 4720
  DBUG_PRINT("info",("db_access: %lu  want_access: %lu",
                     db_access, want_access));
4721

4722 4723
  /*
    Save the union of User-table and the intersection between Db-table and
Marc Alff's avatar
Marc Alff committed
4724
    Host-table privileges, with the already saved internal privileges.
4725 4726
  */
  db_access= (db_access | sctx->master_access);
Marc Alff's avatar
Marc Alff committed
4727
  *save_priv|= db_access;
4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742

  /*
    We need to investigate column- and table access if all requested privileges
    belongs to the bit set of .
  */
  bool need_table_or_column_check=
    (want_access & (TABLE_ACLS | PROC_ACLS | db_access)) == want_access;

  /*
    Grant access if the requested access is in the intersection of
    host- and db-privileges (as retrieved from the acl cache),
    also grant access if all the requested privileges are in the union of
    TABLES_ACLS and PROC_ACLS; see check_grant.
  */
  if ( (db_access & want_access) == want_access ||
4743
      (!dont_check_global_grants &&
4744 4745 4746 4747
       need_table_or_column_check))
  {
    /*
       Ok; but need to check table- and column privileges.
Marc Alff's avatar
Marc Alff committed
4748
       [out] *save_privileges is (User-priv | (Db-priv & Host-priv) | Internal-priv)
4749 4750 4751
    */
    DBUG_RETURN(FALSE);
  }
4752

4753 4754
  /*
    Access is denied;
Marc Alff's avatar
Marc Alff committed
4755
    [out] *save_privileges is (User-priv | (Db-priv & Host-priv) | Internal-priv)
4756
  */
4757
  DBUG_PRINT("error",("Access denied"));
4758
  if (!no_errors)
4759
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
4760
             sctx->priv_user, sctx->priv_host,
4761 4762
             (db ? db : (thd->db ?
                         thd->db :
4763 4764 4765
                         "unknown")));
  DBUG_RETURN(TRUE);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4766 4767 4768
}


4769 4770
static bool check_show_access(THD *thd, TABLE_LIST *table)
{
Marc Alff's avatar
Marc Alff committed
4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782
  /*
    This is a SHOW command using an INFORMATION_SCHEMA table.
    check_access() has not been called for 'table',
    and SELECT is currently always granted on the I_S, so we automatically
    grant SELECT on table here, to bypass a call to check_access().
    Note that not calling check_access(table) is an optimization,
    which needs to be revisited if the INFORMATION_SCHEMA does
    not always automatically grant SELECT but use the grant tables.
    See Bug#38837 need a way to disable information_schema for security
  */
  table->grant.privilege= SELECT_ACL;

4783
  switch (get_schema_table_idx(table->schema_table)) {
4784 4785
  case SCH_SCHEMATA:
    return (specialflag & SPECIAL_SKIP_SHOW_DB) &&
4786
      check_global_access(thd, SHOW_DB_ACL);
4787 4788 4789 4790 4791

  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
  case SCH_TRIGGERS:
4792 4793 4794
  case SCH_EVENTS:
  {
    const char *dst_db_name= table->schema_select_lex->db;
4795

4796
    DBUG_ASSERT(dst_db_name);
4797

4798
    if (check_access(thd, SELECT_ACL, dst_db_name,
Marc Alff's avatar
Marc Alff committed
4799
                     &thd->col_access, NULL, FALSE, FALSE))
4800
      return TRUE;
4801

4802 4803 4804 4805 4806 4807 4808
    if (!thd->col_access && check_grant_db(thd, dst_db_name))
    {
      my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
               thd->security_ctx->priv_user,
               thd->security_ctx->priv_host,
               dst_db_name);
      return TRUE;
4809 4810
    }

4811 4812 4813
    return FALSE;
  }

4814 4815
  case SCH_COLUMNS:
  case SCH_STATISTICS:
4816 4817
  {
    TABLE_LIST *dst_table;
4818
    dst_table= table->schema_select_lex->table_list.first;
4819

4820
    DBUG_ASSERT(dst_table);
4821

4822
    if (check_access(thd, SELECT_ACL, dst_table->db,
Marc Alff's avatar
Marc Alff committed
4823 4824 4825
                     &dst_table->grant.privilege,
                     &dst_table->grant.m_internal,
                     FALSE, FALSE))
4826 4827 4828 4829 4830 4831 4832 4833
          return TRUE; /* Access denied */

    /*
      Check_grant will grant access if there is any column privileges on
      all of the tables thanks to the fourth parameter (bool show_table).
    */
    if (check_grant(thd, SELECT_ACL, dst_table, TRUE, UINT_MAX, FALSE))
      return TRUE; /* Access denied */
4834

4835 4836
    /* Access granted */
    return FALSE;
4837 4838
  }
  default:
4839 4840 4841 4842 4843 4844 4845
    break;
  }

  return FALSE;
}


4846

4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874
/**
  @brief Check if the requested privileges exists in either User-, Host- or
    Db-tables.
  @param thd          Thread context
  @param want_access  Privileges requested
  @param tables       List of tables to be compared against
  @param no_errors    Don't report error to the client (using my_error() call).
  @param any_combination_of_privileges_will_do TRUE if any privileges on any
    column combination is enough.
  @param number       Only the first 'number' tables in the linked list are
                      relevant.

  The suppled table list contains cached privileges. This functions calls the
  help functions check_access and check_grant to verify the first three steps
  in the privileges check queue:
  1. Global privileges
  2. OR (db privileges AND host privileges)
  3. OR table privileges
  4. OR column privileges (not checked by this function!)
  5. OR routine privileges (not checked by this function!)

  @see check_access
  @see check_grant

  @note This functions assumes that table list used and
  thd->lex->query_tables_own_last value correspond to each other
  (the latter should be either 0 or point to next_global member
  of one of elements of this table list).
4875

4876 4877 4878 4879
  @return
    @retval FALSE OK
    @retval TRUE  Access denied; But column or routine privileges might need to
      be checked also.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4880 4881
*/

4882
bool
4883 4884 4885
check_table_access(THD *thd, ulong requirements,TABLE_LIST *tables,
		   bool any_combination_of_privileges_will_do,
                   uint number, bool no_errors)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4886
{
4887 4888
  TABLE_LIST *org_tables= tables;
  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
4889
  uint i= 0;
4890
  Security_context *sctx= thd->security_ctx, *backup_ctx= thd->security_ctx;
4891
  /*
4892 4893 4894
    The check that first_not_own_table is not reached is for the case when
    the given table list refers to the list for prelocking (contains tables
    of other queries). For simple queries first_not_own_table is 0.
4895
  */
4896
  for (; i < number && tables != first_not_own_table && tables;
4897
       tables= tables->next_global, i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4898
  {
4899
    ulong want_access= requirements;
4900 4901 4902 4903 4904
    if (tables->security_ctx)
      sctx= tables->security_ctx;
    else
      sctx= backup_ctx;

4905 4906 4907 4908 4909
    /*
       Register access for view underlying table.
       Remove SHOW_VIEW_ACL, because it will be checked during making view
     */
    tables->grant.orig_want_privilege= (want_access & ~SHOW_VIEW_ACL);
4910 4911 4912 4913 4914 4915 4916 4917

    if (tables->schema_table_reformed)
    {
      if (check_show_access(thd, tables))
        goto deny;
      continue;
    }

4918 4919
    DBUG_PRINT("info", ("derived: %d  view: %d", tables->derived != 0,
                        tables->view != 0));
4920
    if (tables->is_anonymous_derived_table() ||
4921 4922
        (tables->table && tables->table->s &&
         (int)tables->table->s->tmp_table))
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
4923
      continue;
4924
    thd->security_ctx= sctx;
Marc Alff's avatar
Marc Alff committed
4925 4926 4927 4928 4929

    if (check_access(thd, want_access, tables->get_db_name(),
                     &tables->grant.privilege,
                     &tables->grant.m_internal,
                     0, no_errors))
4930
      goto deny;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4931
  }
4932
  thd->security_ctx= backup_ctx;
4933 4934 4935
  return check_grant(thd,requirements,org_tables,
                     any_combination_of_privileges_will_do,
                     number, no_errors);
4936 4937 4938
deny:
  thd->security_ctx= backup_ctx;
  return TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4939 4940
}

4941

4942
bool
4943 4944
check_routine_access(THD *thd, ulong want_access,char *db, char *name,
		     bool is_proc, bool no_errors)
4945 4946 4947 4948 4949
{
  TABLE_LIST tables[1];
  
  bzero((char *)tables, sizeof(TABLE_LIST));
  tables->db= db;
4950
  tables->table_name= tables->alias= name;
4951
  
monty@mysql.com's avatar
monty@mysql.com committed
4952 4953 4954 4955 4956
  /*
    The following test is just a shortcut for check_access() (to avoid
    calculating db_access) under the assumption that it's common to
    give persons global right to execute all stored SP (but not
    necessary to create them).
Marc Alff's avatar
Marc Alff committed
4957 4958 4959 4960 4961 4962
    Note that this effectively bypasses the ACL_internal_schema_access checks
    that are implemented for the INFORMATION_SCHEMA and PERFORMANCE_SCHEMA,
    which are located in check_access().
    Since the I_S and P_S do not contain routines, this bypass is ok,
    as long as this code path is not abused to create routines.
    The assert enforce that.
monty@mysql.com's avatar
monty@mysql.com committed
4963
  */
Marc Alff's avatar
Marc Alff committed
4964
  DBUG_ASSERT((want_access & CREATE_PROC_ACL) == 0);
monty@mysql.com's avatar
monty@mysql.com committed
4965
  if ((thd->security_ctx->master_access & want_access) == want_access)
4966
    tables->grant.privilege= want_access;
Marc Alff's avatar
Marc Alff committed
4967 4968 4969 4970
  else if (check_access(thd, want_access, db,
                        &tables->grant.privilege,
                        &tables->grant.m_internal,
                        0, no_errors))
4971 4972
    return TRUE;
  
4973
  return check_grant_routine(thd, want_access, tables, is_proc, no_errors);
4974 4975
}

4976

4977 4978
/**
  Check if the routine has any of the routine privileges.
4979

4980 4981 4982
  @param thd	       Thread handler
  @param db           Database name
  @param name         Routine name
4983

4984
  @retval
4985
    0            ok
4986
  @retval
4987 4988 4989
    1            error
*/

4990 4991
bool check_some_routine_access(THD *thd, const char *db, const char *name,
                               bool is_proc)
4992 4993
{
  ulong save_priv;
4994
  /*
Marc Alff's avatar
Marc Alff committed
4995 4996 4997 4998 4999 5000 5001
    The following test is just a shortcut for check_access() (to avoid
    calculating db_access)
    Note that this effectively bypasses the ACL_internal_schema_access checks
    that are implemented for the INFORMATION_SCHEMA and PERFORMANCE_SCHEMA,
    which are located in check_access().
    Since the I_S and P_S do not contain routines, this bypass is ok,
    as it only opens SHOW_PROC_ACLS.
5002
  */
Marc Alff's avatar
Marc Alff committed
5003 5004 5005
  if (thd->security_ctx->master_access & SHOW_PROC_ACLS)
    return FALSE;
  if (!check_access(thd, SHOW_PROC_ACLS, db, &save_priv, NULL, 0, 1) ||
5006 5007
      (save_priv & SHOW_PROC_ACLS))
    return FALSE;
5008
  return check_routine_level_acl(thd, db, name, is_proc);
5009 5010 5011
}


5012 5013 5014
/*
  Check if the given table has any of the asked privileges

5015 5016
  @param thd		 Thread handler
  @param want_access	 Bitmap of possible privileges to check for
5017

5018
  @retval
5019
    0  ok
5020
  @retval
5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034
    1  error
*/

bool check_some_access(THD *thd, ulong want_access, TABLE_LIST *table)
{
  ulong access;
  DBUG_ENTER("check_some_access");

  /* This loop will work as long as we have less than 32 privileges */
  for (access= 1; access < want_access ; access<<= 1)
  {
    if (access & want_access)
    {
      if (!check_access(thd, access, table->db,
Marc Alff's avatar
Marc Alff committed
5035 5036 5037
                        &table->grant.privilege,
                        &table->grant.m_internal,
                        0, 1) &&
5038
           !check_grant(thd, access, table, FALSE, 1, TRUE))
5039 5040 5041 5042 5043 5044 5045
        DBUG_RETURN(0);
    }
  }
  DBUG_PRINT("exit",("no matching access rights"));
  DBUG_RETURN(1);
}

5046
#endif /*NO_EMBEDDED_ACCESS_CHECKS*/
5047

5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080

/**
  check for global access and give descriptive error message if it fails.

  @param thd			Thread handler
  @param want_access		Use should have any of these global rights

  @warning
    One gets access right if one has ANY of the rights in want_access.
    This is useful as one in most cases only need one global right,
    but in some case we want to check if the user has SUPER or
    REPL_CLIENT_ACL rights.

  @retval
    0	ok
  @retval
    1	Access denied.  In this case an error is sent to the client
*/

bool check_global_access(THD *thd, ulong want_access)
{
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  char command[128];
  if ((thd->security_ctx->master_access & want_access))
    return 0;
  get_privilege_desc(command, sizeof(command), want_access);
  my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), command);
  return 1;
#else
  return 0;
#endif
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5081 5082 5083 5084
/****************************************************************************
	Check stack size; Send error if there isn't enough stack to continue
****************************************************************************/

5085

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5086 5087 5088 5089 5090 5091
#if STACK_DIRECTION < 0
#define used_stack(A,B) (long) (A - B)
#else
#define used_stack(A,B) (long) (B - A)
#endif

monty@mysql.com's avatar
monty@mysql.com committed
5092 5093 5094 5095
#ifndef DBUG_OFF
long max_stack_used;
#endif

5096 5097
/**
  @note
5098 5099 5100 5101
  Note: The 'buf' parameter is necessary, even if it is unused here.
  - fix_fields functions has a "dummy" buffer large enough for the
    corresponding exec. (Thus we only have to check in fix_fields.)
  - Passing to check_stack_overrun() prevents the compiler from removing it.
5102
*/
5103
bool check_stack_overrun(THD *thd, long margin,
5104
			 uchar *buf __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5105 5106
{
  long stack_used;
5107
  DBUG_ASSERT(thd == current_thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5108
  if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >=
5109
      (long) (my_thread_stack_size - margin))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5110
  {
5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121
    /*
      Do not use stack for the message buffer to ensure correct
      behaviour in cases we have close to no stack left.
    */
    char* ebuff= new char[MYSQL_ERRMSG_SIZE];
    if (ebuff) {
      my_snprintf(ebuff, MYSQL_ERRMSG_SIZE, ER(ER_STACK_OVERRUN_NEED_MORE),
                  stack_used, my_thread_stack_size, margin);
      my_message(ER_STACK_OVERRUN_NEED_MORE, ebuff, MYF(ME_FATALERROR));
      delete [] ebuff;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5122 5123
    return 1;
  }
monty@mysql.com's avatar
monty@mysql.com committed
5124 5125 5126
#ifndef DBUG_OFF
  max_stack_used= max(max_stack_used, stack_used);
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5127 5128
  return 0;
}
5129

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5130 5131 5132 5133

#define MY_YACC_INIT 1000			// Start with big alloc
#define MY_YACC_MAX  32000			// Because of 'short'

5134
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5135
{
5136
  Yacc_state *state= & current_thd->m_parser_state->m_yacc;
5137
  ulong old_info=0;
5138
  DBUG_ASSERT(state);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5139 5140
  if ((uint) *yystacksize >= MY_YACC_MAX)
    return 1;
5141
  if (!state->yacc_yyvs)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5142 5143
    old_info= *yystacksize;
  *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
5144
  if (!(state->yacc_yyvs= (uchar*)
5145
        my_realloc(state->yacc_yyvs,
5146 5147 5148
                   *yystacksize*sizeof(**yyvs),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
      !(state->yacc_yyss= (uchar*)
5149
        my_realloc(state->yacc_yyss,
5150 5151
                   *yystacksize*sizeof(**yyss),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5152 5153
    return 1;
  if (old_info)
5154 5155 5156 5157 5158 5159 5160 5161
  {
    /*
      Only copy the old stack on the first call to my_yyoverflow(),
      when replacing a static stack (YYINITDEPTH) by a dynamic stack.
      For subsequent calls, my_realloc already did preserve the old stack.
    */
    memcpy(state->yacc_yyss, *yyss, old_info*sizeof(**yyss));
    memcpy(state->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5162
  }
5163 5164
  *yyss= (short*) state->yacc_yyss;
  *yyvs= (YYSTYPE*) state->yacc_yyvs;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5165 5166 5167 5168
  return 0;
}


5169
/**
5170 5171
  Reset the part of THD responsible for the state of command
  processing.
5172

5173 5174 5175
  This needs to be called before execution of every statement
  (prepared or conventional).  It is not called by substatements of
  routines.
5176

5177 5178
  @todo Remove mysql_reset_thd_for_next_command and only use the
  member function.
5179

5180 5181
  @todo Call it after we use THD for queries, not before.
*/
5182 5183
void mysql_reset_thd_for_next_command(THD *thd)
{
5184 5185 5186 5187 5188 5189
  thd->reset_for_next_command();
}

void THD::reset_for_next_command()
{
  THD *thd= this;
5190
  DBUG_ENTER("mysql_reset_thd_for_next_command");
5191
  DBUG_ASSERT(!thd->spcont); /* not for substatements of routines */
5192
  DBUG_ASSERT(! thd->in_sub_stmt);
5193
  thd->free_list= 0;
5194
  thd->select_number= 1;
5195 5196 5197 5198
  /*
    Those two lines below are theoretically unneeded as
    THD::cleanup_after_query() should take care of this already.
  */
5199
  thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
5200 5201 5202
  thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;

  thd->query_start_used= 0;
5203
  thd->is_fatal_error= thd->time_zone_used= 0;
5204 5205 5206 5207 5208
  /*
    Clear the status flag that are expected to be cleared at the
    beginning of each SQL statement.
  */
  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
5209 5210 5211 5212 5213
  /*
    If in autocommit mode and not in a transaction, reset
    OPTION_STATUS_NO_TRANS_UPDATE | OPTION_KEEP_LOG to not get warnings
    in ha_rollback_trans() about some tables couldn't be rolled back.
  */
5214
  if (!thd->in_multi_stmt_transaction_mode())
5215
  {
5216
    thd->variables.option_bits&= ~OPTION_KEEP_LOG;
5217
    thd->transaction.all.modified_non_trans_table= FALSE;
5218
  }
5219
  DBUG_ASSERT(thd->security_ctx== &thd->main_security_ctx);
5220
  thd->thread_specific_used= FALSE;
5221 5222

  if (opt_bin_log)
5223
  {
5224 5225
    reset_dynamic(&thd->user_var_events);
    thd->user_var_events_alloc= thd->mem_root;
5226
  }
5227
  thd->clear_error();
Marc Alff's avatar
Marc Alff committed
5228 5229
  thd->stmt_da->reset_diagnostics_area();
  thd->warning_info->reset_for_next_command();
5230 5231 5232
  thd->rand_used= 0;
  thd->sent_row_count= thd->examined_row_count= 0;

5233
  thd->reset_current_stmt_binlog_format_row();
5234
  thd->binlog_unsafe_warning_flags= 0;
5235

5236
  DBUG_PRINT("debug",
5237
             ("is_current_stmt_binlog_format_row(): %d",
5238
              thd->is_current_stmt_binlog_format_row()));
5239

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5240 5241 5242
  DBUG_VOID_RETURN;
}

5243

5244 5245 5246 5247 5248 5249 5250 5251
/**
  Resets the lex->current_select object.
  @note It is assumed that lex->current_select != NULL

  This function is a wrapper around select_lex->init_select() with an added
  check for the special situation when using INTO OUTFILE and LOAD DATA.
*/

5252 5253 5254
void
mysql_init_select(LEX *lex)
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5255
  SELECT_LEX *select_lex= lex->current_select;
5256
  select_lex->init_select();
5257
  lex->wild= 0;
5258 5259
  if (select_lex == &lex->select_lex)
  {
5260
    DBUG_ASSERT(lex->result == 0);
5261 5262
    lex->exchange= 0;
  }
5263 5264
}

5265

5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277
/**
  Used to allocate a new SELECT_LEX object on the current thd mem_root and
  link it into the relevant lists.

  This function is always followed by mysql_init_select.

  @see mysql_init_select

  @retval TRUE An error occurred
  @retval FALSE The new SELECT_LEX was successfully allocated.
*/

5278
bool
5279
mysql_new_select(LEX *lex, bool move_down)
5280
{
5281
  SELECT_LEX *select_lex;
5282
  THD *thd= lex->thd;
5283 5284
  DBUG_ENTER("mysql_new_select");

5285
  if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
5286
    DBUG_RETURN(1);
5287
  select_lex->select_number= ++thd->select_number;
5288
  select_lex->parent_lex= lex; /* Used in init_query. */
5289 5290
  select_lex->init_query();
  select_lex->init_select();
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
5291
  lex->nest_level++;
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
5292 5293 5294 5295 5296
  if (lex->nest_level > (int) MAX_SELECT_NESTING)
  {
    my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
    DBUG_RETURN(1);
  }
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
5297
  select_lex->nest_level= lex->nest_level;
5298 5299 5300
  /*
    Don't evaluate this subquery during statement prepare even if
    it's a constant one. The flag is switched off in the end of
5301
    mysqld_stmt_prepare.
5302
  */
konstantin@mysql.com's avatar
konstantin@mysql.com committed
5303
  if (thd->stmt_arena->is_stmt_prepare())
5304
    select_lex->uncacheable|= UNCACHEABLE_PREPARE;
5305 5306
  if (move_down)
  {
5307
    SELECT_LEX_UNIT *unit;
5308
    lex->subqueries= TRUE;
5309
    /* first select_lex of subselect or derived table */
5310
    if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
5311
      DBUG_RETURN(1);
5312

5313 5314
    unit->init_query();
    unit->init_select();
5315
    unit->thd= thd;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5316
    unit->include_down(lex->current_select);
5317 5318
    unit->link_next= 0;
    unit->link_prev= 0;
5319
    unit->return_to= lex->current_select;
5320
    select_lex->include_down(unit);
5321 5322 5323 5324 5325
    /*
      By default we assume that it is usual subselect and we have outer name
      resolution context, if no we will assign it to 0 later
    */
    select_lex->context.outer_context= &select_lex->outer_select()->context;
5326 5327
  }
  else
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5328
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5329 5330
    if (lex->current_select->order_list.first && !lex->current_select->braces)
    {
5331
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY");
5332
      DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5333
    }
5334
    select_lex->include_neighbour(lex->current_select);
5335 5336 5337 5338 5339
    SELECT_LEX_UNIT *unit= select_lex->master_unit();                              
    if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->thd))
      DBUG_RETURN(1);
    select_lex->context.outer_context= 
                unit->first_select()->context.outer_context;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5340
  }
peter@mysql.com's avatar
peter@mysql.com committed
5341

5342
  select_lex->master_unit()->global_parameters= select_lex;
5343
  select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
5344
  lex->current_select= select_lex;
5345 5346 5347 5348 5349
  /*
    in subquery is SELECT query and we allow resolution of names in SELECT
    list
  */
  select_lex->context.resolve_in_select_list= TRUE;
5350
  DBUG_RETURN(0);
5351
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5352

5353
/**
5354 5355
  Create a select to return the same output as 'SELECT @@var_name'.

5356
  Used for SHOW COUNT(*) [ WARNINGS | ERROR].
5357

5358
  This will crash with a core dump if the variable doesn't exists.
5359

5360
  @param var_name		Variable name
5361 5362 5363 5364
*/

void create_select_for_variable(const char *var_name)
{
5365
  THD *thd;
5366
  LEX *lex;
5367
  LEX_STRING tmp, null_lex_string;
5368 5369
  Item *var;
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
5370
  DBUG_ENTER("create_select_for_variable");
5371 5372

  thd= current_thd;
pem@mysql.telia.com's avatar
pem@mysql.telia.com committed
5373
  lex= thd->lex;
5374 5375 5376 5377
  mysql_init_select(lex);
  lex->sql_command= SQLCOM_SELECT;
  tmp.str= (char*) var_name;
  tmp.length=strlen(var_name);
5378
  bzero((char*) &null_lex_string.str, sizeof(null_lex_string));
5379 5380 5381 5382
  /*
    We set the name of Item to @@session.var_name because that then is used
    as the column name in the output.
  */
monty@mysql.com's avatar
monty@mysql.com committed
5383 5384 5385 5386 5387 5388
  if ((var= get_system_var(thd, OPT_SESSION, tmp, null_lex_string)))
  {
    end= strxmov(buff, "@@session.", var_name, NullS);
    var->set_name(buff, end-buff, system_charset_info);
    add_item_to_list(thd, var);
  }
5389 5390 5391
  DBUG_VOID_RETURN;
}

5392

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5393 5394
void mysql_init_multi_delete(LEX *lex)
{
5395
  lex->sql_command=  SQLCOM_DELETE_MULTI;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5396
  mysql_init_select(lex);
5397 5398
  lex->select_lex.select_limit= 0;
  lex->unit.select_limit_cnt= HA_POS_ERROR;
5399
  lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5400 5401
  lex->query_tables= 0;
  lex->query_tables_last= &lex->query_tables;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5402
}
5403

5404

5405 5406 5407 5408
/*
  When you modify mysql_parse(), you may need to mofify
  mysql_test_parse_for_slave() in this same file.
*/
5409

5410 5411
/**
  Parse a query.
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
5412 5413

  @param       thd     Current thread
5414
  @param       rawbuf  Begining of the query text
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
5415 5416 5417
  @param       length  Length of the query text
  @param[out]  found_semicolon For multi queries, position of the character of
                               the next query in the query text.
5418 5419
*/

5420
void mysql_parse(THD *thd, char *rawbuf, uint length,
5421
                 Parser_state *parser_state)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5422
{
5423
  int error __attribute__((unused));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5424
  DBUG_ENTER("mysql_parse");
5425 5426 5427

  DBUG_EXECUTE_IF("parser_debug", turn_parser_debug_on(););

5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445
  /*
    Warning.
    The purpose of query_cache_send_result_to_client() is to lookup the
    query in the query cache first, to avoid parsing and executing it.
    So, the natural implementation would be to:
    - first, call query_cache_send_result_to_client,
    - second, if caching failed, initialise the lexical and syntactic parser.
    The problem is that the query cache depends on a clean initialization
    of (among others) lex->safe_to_cache_query and thd->server_status,
    which are reset respectively in
    - lex_start()
    - mysql_reset_thd_for_next_command()
    So, initializing the lexical analyser *before* using the query cache
    is required for the cache to work properly.
    FIXME: cleanup the dependencies in the code to simplify this.
  */
  lex_start(thd);
  mysql_reset_thd_for_next_command(thd);
5446

5447
  if (query_cache_send_result_to_client(thd, rawbuf, length) <= 0)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5448
  {
5449
    LEX *lex= thd->lex;
5450

5451
    bool err= parse_sql(thd, parser_state, NULL);
5452

5453
    if (!err)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5454
    {
hf@deer.(none)'s avatar
hf@deer.(none) committed
5455
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5456
      if (mqh_used && thd->user_connect &&
5457
	  check_mqh(thd, lex->sql_command))
5458 5459 5460 5461
      {
	thd->net.error = 0;
      }
      else
hf@deer.(none)'s avatar
hf@deer.(none) committed
5462
#endif
5463
      {
5464
	if (! thd->is_error())
5465
	{
5466
          const char *found_semicolon= parser_state->m_lip.found_semicolon;
5467 5468 5469 5470 5471 5472 5473 5474 5475 5476
          /*
            Binlog logs a string starting from thd->query and having length
            thd->query_length; so we set thd->query_length correctly (to not
            log several statements in one event, when we executed only first).
            We set it to not see the ';' (otherwise it would get into binlog
            and Query_log_event::print() would give ';;' output).
            This also helps display only the current query in SHOW
            PROCESSLIST.
            Note that we don't need LOCK_thread_count to modify query_length.
          */
5477
          if (found_semicolon && (ulong) (found_semicolon - thd->query()))
5478
            thd->set_query_inner(thd->query(),
5479
                                 (uint32) (found_semicolon -
5480 5481
                                           thd->query() - 1),
                                 thd->charset());
5482
          /* Actually execute the query */
5483
          if (found_semicolon)
5484 5485 5486 5487
          {
            lex->safe_to_cache_query= 0;
            thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
          }
5488
          lex->set_trg_event_type_for_tables();
5489
          MYSQL_QUERY_EXEC_START(thd->query(),
5490 5491 5492 5493 5494 5495 5496 5497
                                 thd->thread_id,
                                 (char *) (thd->db ? thd->db : ""),
                                 thd->security_ctx->priv_user,
                                 (char *) thd->security_ctx->host_or_ip,
                                 0);

          error= mysql_execute_command(thd);
          MYSQL_QUERY_EXEC_DONE(error);
5498
	}
5499
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5500 5501
    }
    else
5502
    {
5503
      DBUG_ASSERT(thd->is_error());
5504
      DBUG_PRINT("info",("Command aborted. Fatal_error: %d",
5505
			 thd->is_fatal_error));
5506

5507
      query_cache_abort(&thd->query_cache_tls);
5508
    }
5509
    thd_proc_info(thd, "freeing items");
5510
    thd->end_statement();
5511
    thd->cleanup_after_query();
5512
    DBUG_ASSERT(thd->change_list.is_empty());
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5513
  }
5514

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5515 5516 5517 5518
  DBUG_VOID_RETURN;
}


monty@mysql.com's avatar
monty@mysql.com committed
5519
#ifdef HAVE_REPLICATION
5520 5521 5522 5523
/*
  Usable by the replication SQL thread only: just parse a query to know if it
  can be ignored because of replicate-*-table rules.

5524
  @retval
5525
    0	cannot be ignored
5526
  @retval
5527 5528 5529
    1	can be ignored
*/

5530
bool mysql_test_parse_for_slave(THD *thd, char *rawbuf, uint length)
5531
{
5532
  LEX *lex= thd->lex;
5533
  bool error= 0;
monty@mysql.com's avatar
monty@mysql.com committed
5534
  DBUG_ENTER("mysql_test_parse_for_slave");
5535

5536
  Parser_state parser_state;
5537
  if (!(error= parser_state.init(thd, rawbuf, length)))
5538 5539 5540
  {
    lex_start(thd);
    mysql_reset_thd_for_next_command(thd);
5541

5542
    if (!parse_sql(thd, & parser_state, NULL) &&
5543
        all_tables_not_ok(thd, lex->select_lex.table_list.first))
5544 5545 5546
      error= 1;                  /* Ignore question */
    thd->end_statement();
  }
5547
  thd->cleanup_after_query();
monty@mysql.com's avatar
monty@mysql.com committed
5548
  DBUG_RETURN(error);
5549
}
monty@mysql.com's avatar
monty@mysql.com committed
5550
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5551

5552

monty@mysql.com's avatar
monty@mysql.com committed
5553

5554 5555 5556 5557 5558 5559
/**
  Store field definition for create.

  @return
    Return 0 if ok
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5560

5561
bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum_field_types type,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5562
		       char *length, char *decimals,
5563
		       uint type_modifier,
5564 5565
		       Item *default_value, Item *on_update_value,
                       LEX_STRING *comment,
5566 5567
		       char *change,
                       List<String> *interval_list, CHARSET_INFO *cs,
5568
		       uint uint_geom_type)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5569
{
5570
  register Create_field *new_field;
5571
  LEX  *lex= thd->lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5572 5573
  DBUG_ENTER("add_field_to_list");

5574 5575
  if (check_string_char_length(field_name, "", NAME_CHAR_LEN,
                               system_charset_info, 1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5576
  {
5577
    my_error(ER_TOO_LONG_IDENT, MYF(0), field_name->str); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5578 5579 5580 5581
    DBUG_RETURN(1);				/* purecov: inspected */
  }
  if (type_modifier & PRI_KEY_FLAG)
  {
5582
    Key *key;
5583 5584
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
    key= new Key(Key::PRIMARY, null_lex_str,
5585 5586 5587
                      &default_key_create_info,
                      0, lex->col_list);
    lex->alter_info.key_list.push_back(key);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5588 5589 5590 5591
    lex->col_list.empty();
  }
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
  {
5592
    Key *key;
5593 5594
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
    key= new Key(Key::UNIQUE, null_lex_str,
5595 5596 5597
                 &default_key_create_info, 0,
                 lex->col_list);
    lex->alter_info.key_list.push_back(key);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5598 5599 5600
    lex->col_list.empty();
  }

5601
  if (default_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5602
  {
5603
    /* 
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5604 5605
      Default value should be literal => basic constants =>
      no need fix_fields()
5606 5607 5608
      
      We allow only one function as part of default value - 
      NOW() as default for TIMESTAMP type.
5609
    */
5610 5611
    if (default_value->type() == Item::FUNC_ITEM && 
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
5612
         type == MYSQL_TYPE_TIMESTAMP))
5613
    {
5614
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
5615 5616 5617
      DBUG_RETURN(1);
    }
    else if (default_value->type() == Item::NULL_ITEM)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5618
    {
5619
      default_value= 0;
5620 5621 5622
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
	  NOT_NULL_FLAG)
      {
5623
	my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
5624 5625 5626 5627 5628
	DBUG_RETURN(1);
      }
    }
    else if (type_modifier & AUTO_INCREMENT_FLAG)
    {
5629
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5630 5631 5632
      DBUG_RETURN(1);
    }
  }
5633

5634
  if (on_update_value && type != MYSQL_TYPE_TIMESTAMP)
5635
  {
5636
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
5637 5638
    DBUG_RETURN(1);
  }
5639

5640
  if (!(new_field= new Create_field()) ||
5641
      new_field->init(thd, field_name->str, type, length, decimals, type_modifier,
5642 5643
                      default_value, on_update_value, comment, change,
                      interval_list, cs, uint_geom_type))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5644
    DBUG_RETURN(1);
5645

5646
  lex->alter_info.create_list.push_back(new_field);
5647 5648 5649 5650
  lex->last_field=new_field;
  DBUG_RETURN(0);
}

5651

5652
/** Store position for column in ALTER TABLE .. ADD column. */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5653 5654 5655

void store_position_for_column(const char *name)
{
5656
  current_thd->lex->last_field->after=(char*) (name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5657 5658 5659
}

bool
5660
add_proc_to_list(THD* thd, Item *item)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5661 5662 5663 5664
{
  ORDER *order;
  Item	**item_ptr;

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5665
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5666 5667 5668 5669 5670
    return 1;
  item_ptr = (Item**) (order+1);
  *item_ptr= item;
  order->item=item_ptr;
  order->free_me=0;
5671
  thd->lex->proc_list.link_in_list(order, &order->next);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5672 5673 5674 5675
  return 0;
}


5676 5677 5678
/**
  save order by and tables in own lists.
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5679

5680
bool add_to_list(THD *thd, SQL_I_List<ORDER> &list, Item *item,bool asc)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5681 5682 5683
{
  ORDER *order;
  DBUG_ENTER("add_to_list");
5684
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5685
    DBUG_RETURN(1);
5686 5687
  order->item_ptr= item;
  order->item= &order->item_ptr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5688 5689 5690
  order->asc = asc;
  order->free_me=0;
  order->used=0;
5691
  order->counter_used= 0;
5692
  list.link_in_list(order, &order->next);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5693 5694 5695 5696
  DBUG_RETURN(0);
}


5697 5698 5699 5700 5701 5702 5703 5704 5705 5706
/**
  Add a table to list of used tables.

  @param table		Table to add
  @param alias		alias for table (or null if no alias)
  @param table_options	A set of the following bits:
                         - TL_OPTION_UPDATING : Table will be updated
                         - TL_OPTION_FORCE_INDEX : Force usage of index
                         - TL_OPTION_ALIAS : an alias in multi table DELETE
  @param lock_type	How table should be locked
5707
  @param mdl_type       Type of metadata lock to acquire on the table.
5708 5709 5710 5711
  @param use_index	List of indexed used in USE INDEX
  @param ignore_index	List of indexed used in IGNORE INDEX

  @retval
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5712
      0		Error
5713 5714
  @retval
    \#	Pointer to TABLE_LIST element added to the total table list
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5715 5716
*/

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5717 5718
TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
					     Table_ident *table,
5719
					     LEX_STRING *alias,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5720 5721
					     ulong table_options,
					     thr_lock_type lock_type,
5722
					     enum_mdl_type mdl_type,
5723
					     List<Index_hint> *index_hints_arg,
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
5724
                                             LEX_STRING *option)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5725 5726
{
  register TABLE_LIST *ptr;
5727
  TABLE_LIST *previous_table_ref; /* The table preceding the current one. */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5728
  char *alias_str;
5729
  LEX *lex= thd->lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5730
  DBUG_ENTER("add_table_to_list");
5731
  LINT_INIT(previous_table_ref);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5732 5733 5734 5735

  if (!table)
    DBUG_RETURN(0);				// End of memory
  alias_str= alias ? alias->str : table->table.str;
5736
  if (!test(table_options & TL_OPTION_ALIAS) && 
5737
      check_table_name(table->table.str, table->table.length, FALSE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5738
  {
5739
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5740 5741
    DBUG_RETURN(0);
  }
5742 5743

  if (table->is_derived_table() == FALSE && table->db.str &&
5744
      check_db_name(&table->db))
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
5745 5746 5747 5748
  {
    my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
    DBUG_RETURN(0);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5749 5750

  if (!alias)					/* Alias is case sensitive */
5751 5752 5753
  {
    if (table->sel)
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5754 5755
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
                 ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
5756 5757
      DBUG_RETURN(0);
    }
5758
    if (!(alias_str= (char*) thd->memdup(alias_str,table->table.length+1)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5759
      DBUG_RETURN(0);
5760
  }
5761
  if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5762
    DBUG_RETURN(0);				/* purecov: inspected */
peter@mysql.com's avatar
peter@mysql.com committed
5763
  if (table->db.str)
5764
  {
5765
    ptr->is_fqtn= TRUE;
5766 5767 5768
    ptr->db= table->db.str;
    ptr->db_length= table->db.length;
  }
5769
  else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
5770
    DBUG_RETURN(0);
5771 5772
  else
    ptr->is_fqtn= FALSE;
peter@mysql.com's avatar
peter@mysql.com committed
5773

5774
  ptr->alias= alias_str;
5775
  ptr->is_alias= alias ? TRUE : FALSE;
5776
  if (lower_case_table_names && table->table.length)
5777
    table->table.length= my_casedn_str(files_charset_info, table->table.str);
5778 5779
  ptr->table_name=table->table.str;
  ptr->table_name_length=table->table.length;
5780
  ptr->lock_type=   lock_type;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5781
  ptr->updating=    test(table_options & TL_OPTION_UPDATING);
5782
  /* TODO: remove TL_OPTION_FORCE_INDEX as it looks like it's not used */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5783
  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
5784
  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
5785
  ptr->derived=	    table->sel;
5786
  if (!ptr->derived && is_infoschema_db(ptr->db, ptr->db_length))
5787
  {
5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800
    ST_SCHEMA_TABLE *schema_table;
    if (ptr->updating &&
        /* Special cases which are processed by commands itself */
        lex->sql_command != SQLCOM_CHECK &&
        lex->sql_command != SQLCOM_CHECKSUM)
    {
      my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
               thd->security_ctx->priv_user,
               thd->security_ctx->priv_host,
               INFORMATION_SCHEMA_NAME.str);
      DBUG_RETURN(0);
    }
    schema_table= find_schema_table(thd, ptr->table_name);
5801 5802
    if (!schema_table ||
        (schema_table->hidden && 
gluh@eagle.(none)'s avatar
gluh@eagle.(none) committed
5803
         ((sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0 || 
5804 5805 5806
          /*
            this check is used for show columns|keys from I_S hidden table
          */
5807 5808
          lex->sql_command == SQLCOM_SHOW_FIELDS ||
          lex->sql_command == SQLCOM_SHOW_KEYS)))
5809
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5810
      my_error(ER_UNKNOWN_TABLE, MYF(0),
5811
               ptr->table_name, INFORMATION_SCHEMA_NAME.str);
5812 5813
      DBUG_RETURN(0);
    }
5814
    ptr->schema_table_name= ptr->table_name;
5815 5816
    ptr->schema_table= schema_table;
  }
5817
  ptr->select_lex=  lex->current_select;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5818
  ptr->cacheable_table= 1;
5819
  ptr->index_hints= index_hints_arg;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
5820
  ptr->option= option ? option->str : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5821
  /* check that used name is unique */
5822
  if (lock_type != TL_IGNORE)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5823
  {
5824
    TABLE_LIST *first_table= table_list.first;
timour@mysql.com's avatar
timour@mysql.com committed
5825 5826 5827
    if (lex->sql_command == SQLCOM_CREATE_VIEW)
      first_table= first_table ? first_table->next_local : NULL;
    for (TABLE_LIST *tables= first_table ;
5828
	 tables ;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5829
	 tables=tables->next_local)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5830
    {
5831 5832
      if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
	  !strcmp(ptr->db, tables->db))
5833
      {
5834
	my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
5835 5836
	DBUG_RETURN(0);				/* purecov: tested */
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5837 5838
    }
  }
5839 5840 5841
  /* Store the table reference preceding the current one. */
  if (table_list.elements > 0)
  {
5842 5843 5844
    /*
      table_list.next points to the last inserted TABLE_LIST->next_local'
      element
5845
      We don't use the offsetof() macro here to avoid warnings from gcc
5846
    */
5847 5848 5849
    previous_table_ref= (TABLE_LIST*) ((char*) table_list.next -
                                       ((char*) &(ptr->next_local) -
                                        (char*) ptr));
5850 5851 5852 5853 5854 5855 5856 5857
    /*
      Set next_name_resolution_table of the previous table reference to point
      to the current table reference. In effect the list
      TABLE_LIST::next_name_resolution_table coincides with
      TABLE_LIST::next_local. Later this may be changed in
      store_top_level_join_columns() for NATURAL/USING joins.
    */
    previous_table_ref->next_name_resolution_table= ptr;
5858
  }
5859

5860 5861 5862 5863 5864 5865
  /*
    Link the current table reference in a local list (list for current select).
    Notice that as a side effect here we set the next_local field of the
    previous table reference to 'ptr'. Here we also add one element to the
    list 'table_list'.
  */
5866
  table_list.link_in_list(ptr, &ptr->next_local);
5867
  ptr->next_name_resolution_table= NULL;
5868
  /* Link table in global list (all used tables) */
5869
  lex->add_to_query_tables(ptr);
5870 5871
  ptr->mdl_request.init(MDL_key::TABLE, ptr->db, ptr->table_name, mdl_type,
                        MDL_TRANSACTION);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5872 5873 5874
  DBUG_RETURN(ptr);
}

monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
5875

5876 5877
/**
  Initialize a new table list for a nested join.
5878

5879 5880 5881 5882 5883 5884 5885 5886
    The function initializes a structure of the TABLE_LIST type
    for a nested join. It sets up its nested join list as empty.
    The created structure is added to the front of the current
    join list in the st_select_lex object. Then the function
    changes the current nest level for joins to refer to the newly
    created empty list after having saved the info on the old level
    in the initialized structure.

5887 5888 5889 5890 5891 5892
  @param thd         current thread

  @retval
    0   if success
  @retval
    1   otherwise
5893 5894 5895 5896 5897 5898 5899
*/

bool st_select_lex::init_nested_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
  DBUG_ENTER("init_nested_join");
5900

5901 5902
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
5903
    DBUG_RETURN(1);
5904
  nested_join= ptr->nested_join=
5905
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
5906

5907 5908 5909
  join_list->push_front(ptr);
  ptr->embedding= embedding;
  ptr->join_list= join_list;
5910
  ptr->alias= (char*) "(nested_join)";
5911 5912 5913 5914 5915 5916 5917
  embedding= ptr;
  join_list= &nested_join->join_list;
  join_list->empty();
  DBUG_RETURN(0);
}


5918 5919
/**
  End a nested join table list.
5920 5921 5922

    The function returns to the previous join nest level.
    If the current level contains only one member, the function
5923
    moves it one level up, eliminating the nest.
5924

5925 5926 5927 5928 5929
  @param thd         current thread

  @return
    - Pointer to TABLE_LIST element added to the total table list, if success
    - 0, otherwise
5930 5931 5932 5933 5934
*/

TABLE_LIST *st_select_lex::end_nested_join(THD *thd)
{
  TABLE_LIST *ptr;
5935
  NESTED_JOIN *nested_join;
5936
  DBUG_ENTER("end_nested_join");
5937

5938
  DBUG_ASSERT(embedding);
5939 5940 5941
  ptr= embedding;
  join_list= ptr->join_list;
  embedding= ptr->embedding;
5942
  nested_join= ptr->nested_join;
5943 5944 5945 5946 5947 5948 5949 5950 5951
  if (nested_join->join_list.elements == 1)
  {
    TABLE_LIST *embedded= nested_join->join_list.head();
    join_list->pop();
    embedded->join_list= join_list;
    embedded->embedding= embedding;
    join_list->push_front(embedded);
    ptr= embedded;
  }
5952
  else if (nested_join->join_list.elements == 0)
5953 5954
  {
    join_list->pop();
5955
    ptr= 0;                                     // return value
5956
  }
5957 5958 5959 5960
  DBUG_RETURN(ptr);
}


5961 5962
/**
  Nest last join operation.
5963 5964 5965

    The function nest last join operation as if it was enclosed in braces.

5966
  @param thd         current thread
5967

5968
  @retval
5969
    0  Error
5970 5971
  @retval
    \#  Pointer to TABLE_LIST element created for the new nested join
5972 5973 5974 5975 5976 5977
*/

TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
5978
  List<TABLE_LIST> *embedded_list;
5979
  DBUG_ENTER("nest_last_join");
5980

5981 5982
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
5983
    DBUG_RETURN(0);
5984
  nested_join= ptr->nested_join=
5985
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
5986

5987 5988
  ptr->embedding= embedding;
  ptr->join_list= join_list;
5989
  ptr->alias= (char*) "(nest_last_join)";
5990
  embedded_list= &nested_join->join_list;
5991
  embedded_list->empty();
5992 5993

  for (uint i=0; i < 2; i++)
5994 5995 5996 5997 5998
  {
    TABLE_LIST *table= join_list->pop();
    table->join_list= embedded_list;
    table->embedding= ptr;
    embedded_list->push_back(table);
5999 6000 6001 6002 6003 6004 6005
    if (table->natural_join)
    {
      ptr->is_natural_join= TRUE;
      /*
        If this is a JOIN ... USING, move the list of joined fields to the
        table reference that describes the join.
      */
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6006 6007
      if (prev_join_using)
        ptr->join_using_fields= prev_join_using;
6008
    }
6009 6010 6011 6012 6013 6014 6015
  }
  join_list->push_front(ptr);
  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
  DBUG_RETURN(ptr);
}


6016 6017
/**
  Add a table to the current join list.
6018 6019 6020 6021 6022 6023

    The function puts a table in front of the current join list
    of st_select_lex object.
    Thus, joined tables are put into this list in the reverse order
    (the most outer join operation follows first).

6024 6025 6026
  @param table       the table to add

  @return
6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039
    None
*/

void st_select_lex::add_joined_table(TABLE_LIST *table)
{
  DBUG_ENTER("add_joined_table");
  join_list->push_front(table);
  table->join_list= join_list;
  table->embedding= embedding;
  DBUG_VOID_RETURN;
}


6040 6041
/**
  Convert a right join into equivalent left join.
6042 6043

    The function takes the current join list t[0],t[1] ... and
6044 6045 6046 6047 6048 6049
    effectively converts it into the list t[1],t[0] ...
    Although the outer_join flag for the new nested table contains
    JOIN_TYPE_RIGHT, it will be handled as the inner table of a left join
    operation.

  EXAMPLES
6050
  @verbatim
6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061
    SELECT * FROM t1 RIGHT JOIN t2 ON on_expr =>
      SELECT * FROM t2 LEFT JOIN t1 ON on_expr

    SELECT * FROM t1,t2 RIGHT JOIN t3 ON on_expr =>
      SELECT * FROM t1,t3 LEFT JOIN t2 ON on_expr

    SELECT * FROM t1,t2 RIGHT JOIN (t3,t4) ON on_expr =>
      SELECT * FROM t1,(t3,t4) LEFT JOIN t2 ON on_expr

    SELECT * FROM t1 LEFT JOIN t2 ON on_expr1 RIGHT JOIN t3  ON on_expr2 =>
      SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1
6062
   @endverbatim
6063

6064
  @param thd         current thread
6065

6066 6067 6068
  @return
    - Pointer to the table representing the inner table, if success
    - 0, otherwise
6069 6070
*/

6071
TABLE_LIST *st_select_lex::convert_right_join()
6072 6073
{
  TABLE_LIST *tab2= join_list->pop();
6074
  TABLE_LIST *tab1= join_list->pop();
6075 6076 6077 6078 6079 6080 6081 6082 6083
  DBUG_ENTER("convert_right_join");

  join_list->push_front(tab2);
  join_list->push_front(tab1);
  tab1->outer_join|= JOIN_TYPE_RIGHT;

  DBUG_RETURN(tab1);
}

6084 6085
/**
  Set lock for all tables in current select level.
6086

6087
  @param lock_type			Lock to set for tables
6088

6089
  @note
6090 6091 6092 6093 6094
    If lock is a write lock, then tables->updating is set 1
    This is to get tables_ok to know that the table is updated by the
    query
*/

6095
void st_select_lex::set_lock_for_tables(thr_lock_type lock_type)
6096 6097 6098 6099 6100
{
  bool for_update= lock_type >= TL_READ_NO_INSERT;
  DBUG_ENTER("set_lock_for_tables");
  DBUG_PRINT("enter", ("lock_type: %d  for_update: %d", lock_type,
		       for_update));
6101
  for (TABLE_LIST *tables= table_list.first;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6102 6103
       tables;
       tables= tables->next_local)
6104 6105 6106
  {
    tables->lock_type= lock_type;
    tables->updating=  for_update;
6107 6108
    tables->mdl_request.set_type((lock_type >= TL_WRITE_ALLOW_WRITE) ?
                                 MDL_SHARED_WRITE : MDL_SHARED_READ);
6109 6110 6111 6112
  }
  DBUG_VOID_RETURN;
}

monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
6113

6114 6115
/**
  Create a fake SELECT_LEX for a unit.
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6116 6117 6118 6119

    The method create a fake SELECT_LEX object for a unit.
    This object is created for any union construct containing a union
    operation and also for any single select union construct of the form
6120
    @verbatim
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6121
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ... 
6122
    @endvarbatim
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6123
    or of the form
6124
    @varbatim
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6125
    (SELECT ... ORDER BY LIMIT n) ORDER BY ...
6126
    @endvarbatim
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6127
  
6128 6129 6130
  @param thd_arg		   thread handle

  @note
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6131 6132 6133
    The object is used to retrieve rows from the temporary table
    where the result on the union is obtained.

6134
  @retval
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6135
    1     on failure to create the object
6136
  @retval
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6137 6138 6139
    0     on success
*/

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6140
bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg)
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6141 6142 6143 6144
{
  SELECT_LEX *first_sl= first_select();
  DBUG_ENTER("add_fake_select_lex");
  DBUG_ASSERT(!fake_select_lex);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6145

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6146
  if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX()))
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6147 6148 6149 6150
      DBUG_RETURN(1);
  fake_select_lex->include_standalone(this, 
                                      (SELECT_LEX_NODE**)&fake_select_lex);
  fake_select_lex->select_number= INT_MAX;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6151
  fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6152 6153
  fake_select_lex->make_empty_select();
  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
6154 6155
  fake_select_lex->select_limit= 0;

igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6156
  fake_select_lex->context.outer_context=first_sl->context.outer_context;
6157 6158 6159
  /* allow item list resolving in fake select for ORDER BY */
  fake_select_lex->context.resolve_in_select_list= TRUE;
  fake_select_lex->context.select_lex= fake_select_lex;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6160

6161
  if (!is_union())
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6162 6163 6164 6165 6166 6167 6168 6169 6170
  {
    /* 
      This works only for 
      (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
      (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
      just before the parser starts processing order_list
    */ 
    global_parameters= fake_select_lex;
    fake_select_lex->no_table_names_allowed= 1;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6171
    thd_arg->lex->current_select= fake_select_lex;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6172
  }
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6173
  thd_arg->lex->pop_context();
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6174 6175 6176
  DBUG_RETURN(0);
}

6177

6178
/**
6179 6180
  Push a new name resolution context for a JOIN ... ON clause to the
  context stack of a query block.
6181 6182

    Create a new name resolution context for a JOIN ... ON clause,
6183 6184 6185
    set the first and last leaves of the list of table references
    to be used for name resolution, and push the newly created
    context to the stack of contexts of the query.
6186

6187 6188 6189 6190 6191
  @param thd       pointer to current thread
  @param left_op   left  operand of the JOIN
  @param right_op  rigth operand of the JOIN

  @retval
6192
    FALSE  if all is OK
6193
  @retval
6194
    TRUE   if a memory allocation error occured
6195 6196
*/

6197 6198 6199
bool
push_new_name_resolution_context(THD *thd,
                                 TABLE_LIST *left_op, TABLE_LIST *right_op)
6200 6201
{
  Name_resolution_context *on_context;
6202
  if (!(on_context= new (thd->mem_root) Name_resolution_context))
6203
    return TRUE;
6204 6205 6206 6207 6208
  on_context->init();
  on_context->first_name_resolution_table=
    left_op->first_leaf_for_name_resolution();
  on_context->last_name_resolution_table=
    right_op->last_leaf_for_name_resolution();
6209
  return thd->lex->push_context(on_context);
6210 6211 6212
}


6213
/**
6214 6215 6216 6217
  Add an ON condition to the second operand of a JOIN ... ON.

    Add an ON condition to the right operand of a JOIN ... ON clause.

6218 6219
  @param b     the second operand of a JOIN ... ON
  @param expr  the condition to be added to the ON clause
6220

6221
  @retval
6222
    FALSE  if there was some error
6223
  @retval
6224 6225 6226 6227
    TRUE   if all is OK
*/

void add_join_on(TABLE_LIST *b, Item *expr)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6228
{
6229
  if (expr)
6230
  {
6231
    if (!b->on_expr)
6232
      b->on_expr= expr;
6233 6234
    else
    {
6235 6236 6237 6238 6239 6240
      /*
        If called from the parser, this happens if you have both a
        right and left join. If called later, it happens if we add more
        than one condition to the ON clause.
      */
      b->on_expr= new Item_cond_and(b->on_expr,expr);
6241 6242
    }
    b->on_expr->top_level_item();
6243
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6244 6245 6246
}


6247
/**
6248 6249
  Mark that there is a NATURAL JOIN or JOIN ... USING between two
  tables.
6250

6251 6252 6253 6254 6255 6256 6257 6258 6259 6260
    This function marks that table b should be joined with a either via
    a NATURAL JOIN or via JOIN ... USING. Both join types are special
    cases of each other, so we treat them together. The function
    setup_conds() creates a list of equal condition between all fields
    of the same name for NATURAL JOIN or the fields in 'using_fields'
    for JOIN ... USING. The list of equality conditions is stored
    either in b->on_expr, or in JOIN::conds, depending on whether there
    was an outer join.

  EXAMPLE
6261
  @verbatim
6262 6263 6264
    SELECT * FROM t1 NATURAL LEFT JOIN t2
     <=>
    SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
6265

6266 6267 6268
    SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond>
     <=>
    SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>)
6269

6270 6271 6272
    SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
     <=>
    SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
6273 6274 6275 6276 6277
   @endverbatim

  @param a		  Left join argument
  @param b		  Right join argument
  @param using_fields    Field names from USING clause
6278 6279
*/

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6280 6281
void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields,
                      SELECT_LEX *lex)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6282
{
6283
  b->natural_join= a;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6284
  lex->prev_join_using= using_fields;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6285 6286
}

6287

6288 6289
/**
  kill on thread.
6290

6291 6292 6293
  @param thd			Thread class
  @param id			Thread id
  @param only_kill_query        Should it kill the query or the connection
6294

6295
  @note
6296 6297 6298
    This is written such that we have a short lock on LOCK_thread_count
*/

6299
uint kill_one_thread(THD *thd, ulong id, bool only_kill_query)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6300 6301 6302
{
  THD *tmp;
  uint error=ER_NO_SUCH_THREAD;
6303 6304
  DBUG_ENTER("kill_one_thread");
  DBUG_PRINT("enter", ("id=%lu only_kill=%d", id, only_kill_query));
Marc Alff's avatar
Marc Alff committed
6305
  mysql_mutex_lock(&LOCK_thread_count); // For unlink from list
6306
  I_List_iterator<THD> it(threads);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6307 6308
  while ((tmp=it++))
  {
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
6309 6310
    if (tmp->command == COM_DAEMON)
      continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6311 6312
    if (tmp->thread_id == id)
    {
Marc Alff's avatar
Marc Alff committed
6313
      mysql_mutex_lock(&tmp->LOCK_thd_data);    // Lock from delete
6314
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6315 6316
    }
  }
Marc Alff's avatar
Marc Alff committed
6317
  mysql_mutex_unlock(&LOCK_thread_count);
6318 6319
  if (tmp)
  {
6320 6321 6322 6323 6324

    /*
      If we're SUPER, we can KILL anything, including system-threads.
      No further checks.

6325 6326 6327
      KILLer: thd->security_ctx->user could in theory be NULL while
      we're still in "unauthenticated" state. This is a theoretical
      case (the code suggests this could happen, so we play it safe).
6328

6329
      KILLee: tmp->security_ctx->user will be NULL for system threads.
6330
      We need to check so Jane Random User doesn't crash the server
6331 6332
      when trying to kill a) system threads or b) unauthenticated users'
      threads (Bug#43748).
6333

6334
      If user of both killer and killee are non-NULL, proceed with
6335 6336 6337
      slayage if both are string-equal.
    */

6338
    if ((thd->security_ctx->master_access & SUPER_ACL) ||
6339
        thd->security_ctx->user_matches(tmp->security_ctx))
6340
    {
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
6341
      tmp->awake(only_kill_query ? THD::KILL_QUERY : THD::KILL_CONNECTION);
6342 6343 6344 6345
      error=0;
    }
    else
      error=ER_KILL_DENIED_ERROR;
Marc Alff's avatar
Marc Alff committed
6346
    mysql_mutex_unlock(&tmp->LOCK_thd_data);
6347
  }
6348 6349 6350 6351
  DBUG_PRINT("exit", ("%d", error));
  DBUG_RETURN(error);
}

6352

6353 6354 6355 6356 6357 6358 6359 6360 6361 6362
/*
  kills a thread and sends response

  SYNOPSIS
    sql_kill()
    thd			Thread class
    id			Thread id
    only_kill_query     Should it kill the query or the connection
*/

6363
static
6364 6365 6366 6367
void sql_kill(THD *thd, ulong id, bool only_kill_query)
{
  uint error;
  if (!(error= kill_one_thread(thd, id, only_kill_query)))
6368 6369 6370 6371
  {
    if (! thd->killed)
      my_ok(thd);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6372
  else
6373
    my_error(error, MYF(0), id);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6374 6375
}

timour@mysql.com's avatar
timour@mysql.com committed
6376

6377
/** If pointer is not a null pointer, append filename to it. */
6378

cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
6379 6380
bool append_file_to_dir(THD *thd, const char **filename_ptr,
                        const char *table_name)
6381
{
6382
  char buff[FN_REFLEN],*ptr, *end;
6383 6384 6385 6386 6387 6388 6389
  if (!*filename_ptr)
    return 0;					// nothing to do

  /* Check that the filename is not too long and it's a hard path */
  if (strlen(*filename_ptr)+strlen(table_name) >= FN_REFLEN-1 ||
      !test_if_hard_path(*filename_ptr))
  {
6390
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
6391 6392 6393 6394
    return 1;
  }
  /* Fix is using unix filename format on dos */
  strmov(buff,*filename_ptr);
6395
  end=convert_dirname(buff, *filename_ptr, NullS);
6396
  if (!(ptr= (char*) thd->alloc((size_t) (end-buff) + strlen(table_name)+1)))
6397 6398
    return 1;					// End of memory
  *filename_ptr=ptr;
6399
  strxmov(ptr,buff,table_name,NullS);
6400 6401
  return 0;
}
6402

6403

6404 6405
/**
  Check if the select is a simple select (not an union).
6406

6407
  @retval
6408
    0	ok
6409
  @retval
6410 6411 6412 6413 6414 6415
    1	error	; In this case the error messege is sent to the client
*/

bool check_simple_select()
{
  THD *thd= current_thd;
6416 6417
  LEX *lex= thd->lex;
  if (lex->current_select != &lex->select_lex)
6418 6419
  {
    char command[80];
6420
    Lex_input_stream *lip= & thd->m_parser_state->m_lip;
6421 6422
    strmake(command, lip->yylval->symbol.str,
	    min(lip->yylval->symbol.length, sizeof(command)-1));
6423
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
6424 6425 6426 6427
    return 1;
  }
  return 0;
}
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6428

6429

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6430
Comp_creator *comp_eq_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6431
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6432
  return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6433 6434
}

6435

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6436
Comp_creator *comp_ge_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6437
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6438
  return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6439 6440
}

6441

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6442
Comp_creator *comp_gt_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6443
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6444
  return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6445 6446
}

6447

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6448
Comp_creator *comp_le_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6449
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6450
  return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6451 6452
}

6453

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6454
Comp_creator *comp_lt_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6455
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6456
  return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6457 6458
}

6459

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6460
Comp_creator *comp_ne_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6461
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6462
  return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6463
}
6464 6465


6466 6467
/**
  Construct ALL/ANY/SOME subquery Item.
6468

6469 6470 6471 6472
  @param left_expr   pointer to left expression
  @param cmp         compare function creator
  @param all         true if we create ALL subquery
  @param select_lex  pointer on parsed subquery structure
6473

6474
  @return
6475 6476 6477 6478 6479 6480 6481
    constructed Item (or 0 if out of memory)
*/
Item * all_any_subquery_creator(Item *left_expr,
				chooser_compare_func_creator cmp,
				bool all,
				SELECT_LEX *select_lex)
{
serg@serg.mylan's avatar
serg@serg.mylan committed
6482
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
6483
    return new Item_in_subselect(left_expr, select_lex);
serg@serg.mylan's avatar
serg@serg.mylan committed
6484 6485

  if ((cmp == &comp_ne_creator) && all)        // <> ALL <=> NOT IN
6486 6487 6488
    return new Item_func_not(new Item_in_subselect(left_expr, select_lex));

  Item_allany_subselect *it=
6489
    new Item_allany_subselect(left_expr, cmp, select_lex, all);
6490
  if (all)
6491
    return it->upper_item= new Item_func_not_all(it);	/* ALL */
6492

6493
  return it->upper_item= new Item_func_nop_all(it);      /* ANY/SOME */
6494
}
6495 6496


6497 6498
/**
  Multi update query pre-check.
6499

6500 6501
  @param thd		Thread handler
  @param tables	Global/local table list (have to be the same)
6502

6503
  @retval
6504
    FALSE OK
6505
  @retval
6506
    TRUE  Error
6507
*/
6508

6509
bool multi_update_precheck(THD *thd, TABLE_LIST *tables)
6510 6511 6512 6513 6514
{
  const char *msg= 0;
  TABLE_LIST *table;
  LEX *lex= thd->lex;
  SELECT_LEX *select_lex= &lex->select_lex;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6515
  DBUG_ENTER("multi_update_precheck");
6516 6517 6518

  if (select_lex->item_list.elements != lex->value_list.elements)
  {
6519
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
6520
    DBUG_RETURN(TRUE);
6521 6522 6523 6524 6525
  }
  /*
    Ensure that we have UPDATE or SELECT privilege for each table
    The exact privilege is checked in mysql_multi_update()
  */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6526
  for (table= tables; table; table= table->next_local)
6527
  {
6528 6529 6530
    if (table->derived)
      table->grant.privilege= SELECT_ACL;
    else if ((check_access(thd, UPDATE_ACL, table->db,
Marc Alff's avatar
Marc Alff committed
6531 6532 6533
                           &table->grant.privilege,
                           &table->grant.m_internal,
                           0, 1) ||
6534
              check_grant(thd, UPDATE_ACL, table, FALSE, 1, TRUE)) &&
monty@mysql.com's avatar
monty@mysql.com committed
6535
             (check_access(thd, SELECT_ACL, table->db,
Marc Alff's avatar
Marc Alff committed
6536 6537 6538
                           &table->grant.privilege,
                           &table->grant.m_internal,
                           0, 0) ||
6539
              check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE)))
6540
      DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6541

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6542
    table->table_in_first_from_clause= 1;
6543
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6544 6545 6546
  /*
    Is there tables of subqueries?
  */
6547
  if (&lex->select_lex != lex->all_selects_list)
6548
  {
6549
    DBUG_PRINT("info",("Checking sub query list"));
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6550
    for (table= tables; table; table= table->next_global)
6551
    {
6552
      if (!table->table_in_first_from_clause)
6553 6554
      {
	if (check_access(thd, SELECT_ACL, table->db,
Marc Alff's avatar
Marc Alff committed
6555 6556 6557
                         &table->grant.privilege,
                         &table->grant.m_internal,
                         0, 0) ||
6558
	    check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE))
6559
	  DBUG_RETURN(TRUE);
6560 6561 6562 6563 6564 6565
      }
    }
  }

  if (select_lex->order_list.elements)
    msg= "ORDER BY";
6566
  else if (select_lex->select_limit)
6567 6568 6569 6570
    msg= "LIMIT";
  if (msg)
  {
    my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
6571
    DBUG_RETURN(TRUE);
6572
  }
6573
  DBUG_RETURN(FALSE);
6574 6575
}

6576 6577
/**
  Multi delete query pre-check.
6578

6579 6580
  @param thd			Thread handler
  @param tables		Global/local table list
6581

6582
  @retval
6583
    FALSE OK
6584
  @retval
6585
    TRUE  error
6586
*/
6587

6588
bool multi_delete_precheck(THD *thd, TABLE_LIST *tables)
6589 6590
{
  SELECT_LEX *select_lex= &thd->lex->select_lex;
6591
  TABLE_LIST *aux_tables= thd->lex->auxiliary_table_list.first;
6592
  TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6593
  DBUG_ENTER("multi_delete_precheck");
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6594

6595 6596
  /* sql_yacc guarantees that tables and aux_tables are not zero */
  DBUG_ASSERT(aux_tables != 0);
6597
  if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE))
6598 6599 6600 6601 6602 6603 6604 6605
    DBUG_RETURN(TRUE);

  /*
    Since aux_tables list is not part of LEX::query_tables list we
    have to juggle with LEX::query_tables_own_last value to be able
    call check_table_access() safely.
  */
  thd->lex->query_tables_own_last= 0;
6606
  if (check_table_access(thd, DELETE_ACL, aux_tables, FALSE, UINT_MAX, FALSE))
6607 6608
  {
    thd->lex->query_tables_own_last= save_query_tables_own_last;
6609
    DBUG_RETURN(TRUE);
6610 6611 6612
  }
  thd->lex->query_tables_own_last= save_query_tables_own_last;

6613
  if ((thd->variables.option_bits & OPTION_SAFE_UPDATES) && !select_lex->where)
6614
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6615 6616
    my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
               ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
6617
    DBUG_RETURN(TRUE);
6618
  }
6619 6620 6621 6622
  DBUG_RETURN(FALSE);
}


6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679
/*
  Given a table in the source list, find a correspondent table in the
  table references list.

  @param lex Pointer to LEX representing multi-delete.
  @param src Source table to match.
  @param ref Table references list.

  @remark The source table list (tables listed before the FROM clause
  or tables listed in the FROM clause before the USING clause) may
  contain table names or aliases that must match unambiguously one,
  and only one, table in the target table list (table references list,
  after FROM/USING clause).

  @return Matching table, NULL otherwise.
*/

static TABLE_LIST *multi_delete_table_match(LEX *lex, TABLE_LIST *tbl,
                                            TABLE_LIST *tables)
{
  TABLE_LIST *match= NULL;
  DBUG_ENTER("multi_delete_table_match");

  for (TABLE_LIST *elem= tables; elem; elem= elem->next_local)
  {
    int cmp;

    if (tbl->is_fqtn && elem->is_alias)
      continue; /* no match */
    if (tbl->is_fqtn && elem->is_fqtn)
      cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) ||
           strcmp(tbl->db, elem->db);
    else if (elem->is_alias)
      cmp= my_strcasecmp(table_alias_charset, tbl->alias, elem->alias);
    else
      cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) ||
           strcmp(tbl->db, elem->db);

    if (cmp)
      continue;

    if (match)
    {
      my_error(ER_NONUNIQ_TABLE, MYF(0), elem->alias);
      DBUG_RETURN(NULL);
    }

    match= elem;
  }

  if (!match)
    my_error(ER_UNKNOWN_TABLE, MYF(0), tbl->table_name, "MULTI DELETE");

  DBUG_RETURN(match);
}


6680
/**
6681 6682 6683
  Link tables in auxilary table list of multi-delete with corresponding
  elements in main table list, and set proper locks for them.

6684
  @param lex   pointer to LEX representing multi-delete
6685

6686 6687 6688 6689
  @retval
    FALSE   success
  @retval
    TRUE    error
6690 6691 6692 6693
*/

bool multi_delete_set_locks_and_link_aux_tables(LEX *lex)
{
6694
  TABLE_LIST *tables= lex->select_lex.table_list.first;
6695 6696 6697 6698 6699
  TABLE_LIST *target_tbl;
  DBUG_ENTER("multi_delete_set_locks_and_link_aux_tables");

  lex->table_count= 0;

6700
  for (target_tbl= lex->auxiliary_table_list.first;
6701
       target_tbl; target_tbl= target_tbl->next_local)
6702
  {
6703
    lex->table_count++;
6704
    /* All tables in aux_tables must be found in FROM PART */
6705
    TABLE_LIST *walk= multi_delete_table_match(lex, target_tbl, tables);
6706
    if (!walk)
6707
      DBUG_RETURN(TRUE);
serg@serg.mylan's avatar
serg@serg.mylan committed
6708 6709 6710 6711 6712
    if (!walk->derived)
    {
      target_tbl->table_name= walk->table_name;
      target_tbl->table_name_length= walk->table_name_length;
    }
serg@serg.mylan's avatar
serg@serg.mylan committed
6713
    walk->updating= target_tbl->updating;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6714
    walk->lock_type= target_tbl->lock_type;
6715 6716 6717
    /* We can assume that tables to be deleted from are locked for write. */
    DBUG_ASSERT(walk->lock_type >= TL_WRITE_ALLOW_WRITE);
    walk->mdl_request.set_type(MDL_SHARED_WRITE);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6718
    target_tbl->correspondent_table= walk;	// Remember corresponding table
6719
  }
6720
  DBUG_RETURN(FALSE);
6721 6722 6723
}


6724 6725
/**
  simple UPDATE query pre-check.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6726

6727 6728
  @param thd		Thread handler
  @param tables	Global table list
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6729

6730
  @retval
6731
    FALSE OK
6732
  @retval
6733
    TRUE  Error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6734
*/
6735

6736
bool update_precheck(THD *thd, TABLE_LIST *tables)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6737 6738 6739 6740
{
  DBUG_ENTER("update_precheck");
  if (thd->lex->select_lex.item_list.elements != thd->lex->value_list.elements)
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6741
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
6742
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6743
  }
6744
  DBUG_RETURN(check_one_table_access(thd, UPDATE_ACL, tables));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6745 6746 6747
}


6748 6749
/**
  simple DELETE query pre-check.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6750

6751 6752
  @param thd		Thread handler
  @param tables	Global table list
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6753

6754
  @retval
6755
    FALSE  OK
6756
  @retval
6757
    TRUE   error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6758
*/
6759

6760
bool delete_precheck(THD *thd, TABLE_LIST *tables)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6761 6762 6763
{
  DBUG_ENTER("delete_precheck");
  if (check_one_table_access(thd, DELETE_ACL, tables))
6764
    DBUG_RETURN(TRUE);
6765
  /* Set privilege for the WHERE clause */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6766
  tables->grant.want_privilege=(SELECT_ACL & ~tables->grant.privilege);
6767
  DBUG_RETURN(FALSE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6768 6769 6770
}


6771 6772
/**
  simple INSERT query pre-check.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6773

6774 6775
  @param thd		Thread handler
  @param tables	Global table list
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6776

6777
  @retval
6778
    FALSE  OK
6779
  @retval
6780
    TRUE   error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6781
*/
6782

bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
6783
bool insert_precheck(THD *thd, TABLE_LIST *tables)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6784 6785 6786 6787
{
  LEX *lex= thd->lex;
  DBUG_ENTER("insert_precheck");

6788 6789 6790 6791
  /*
    Check that we have modify privileges for the first table and
    select privileges for the rest
  */
monty@mysql.com's avatar
monty@mysql.com committed
6792 6793 6794
  ulong privilege= (INSERT_ACL |
                    (lex->duplicates == DUP_REPLACE ? DELETE_ACL : 0) |
                    (lex->value_list.elements ? UPDATE_ACL : 0));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6795 6796

  if (check_one_table_access(thd, privilege, tables))
6797
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6798

6799
  if (lex->update_list.elements != lex->value_list.elements)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6800
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6801
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
6802
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6803
  }
6804
  DBUG_RETURN(FALSE);
6805
}
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6806 6807


6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818
/**
   Set proper open mode and table type for element representing target table
   of CREATE TABLE statement, also adjust statement table list if necessary.
*/

void create_table_set_open_action_and_adjust_tables(LEX *lex)
{
  TABLE_LIST *create_table= lex->query_tables;

  if (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE)
    create_table->open_type= OT_TEMPORARY_ONLY;
6819
  else
6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835
    create_table->open_type= OT_BASE_ONLY;

  if (!lex->select_lex.item_list.elements)
  {
    /*
      Avoid opening and locking target table for ordinary CREATE TABLE
      or CREATE TABLE LIKE for write (unlike in CREATE ... SELECT we
      won't do any insertions in it anyway). Not doing this causes
      problems when running CREATE TABLE IF NOT EXISTS for already
      existing log table.
    */
    create_table->lock_type= TL_READ;
  }
}


6836 6837
/**
  CREATE TABLE query pre-check.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6838

6839 6840 6841
  @param thd			Thread handler
  @param tables		Global table list
  @param create_table	        Table which will be created
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6842

6843
  @retval
6844
    FALSE   OK
6845
  @retval
6846
    TRUE   Error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6847
*/
6848

6849 6850
bool create_table_precheck(THD *thd, TABLE_LIST *tables,
                           TABLE_LIST *create_table)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6851 6852
{
  LEX *lex= thd->lex;
6853 6854
  SELECT_LEX *select_lex= &lex->select_lex;
  ulong want_priv;
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
6855
  bool error= TRUE;                                 // Error message is given
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6856
  DBUG_ENTER("create_table_precheck");
6857

6858 6859 6860 6861 6862
  /*
    Require CREATE [TEMPORARY] privilege on new table; for
    CREATE TABLE ... SELECT, also require INSERT.
  */

6863
  want_priv= ((lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) ?
6864 6865 6866
              CREATE_TMP_ACL : CREATE_ACL) |
             (select_lex->item_list.elements ? INSERT_ACL : 0);

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6867
  if (check_access(thd, want_priv, create_table->db,
Marc Alff's avatar
Marc Alff committed
6868 6869
                   &create_table->grant.privilege,
                   &create_table->grant.m_internal,
6870 6871 6872 6873 6874 6875 6876 6877
                   0, 0))
    goto err;

  /* If it is a merge table, check privileges for merge children. */
  if (lex->create_info.merge_list.first &&
      check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL,
                         lex->create_info.merge_list.first,
                         FALSE, UINT_MAX, FALSE))
6878
    goto err;
6879

6880
  if (want_priv != CREATE_TMP_ACL &&
6881
      check_grant(thd, want_priv, create_table, FALSE, 1, FALSE))
6882 6883 6884 6885 6886
    goto err;

  if (select_lex->item_list.elements)
  {
    /* Check permissions for used tables in CREATE TABLE ... SELECT */
6887 6888
    if (tables && check_table_access(thd, SELECT_ACL, tables, FALSE,
                                     UINT_MAX, FALSE))
6889 6890
      goto err;
  }
6891 6892
  else if (lex->create_info.options & HA_LEX_CREATE_TABLE_LIKE)
  {
6893
    if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE))
6894 6895
      goto err;
  }
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
6896
  error= FALSE;
6897 6898 6899

err:
  DBUG_RETURN(error);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6900
}
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6901 6902


6903 6904
/**
  negate given expression.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6905

6906 6907
  @param thd  thread handler
  @param expr expression for negation
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6908

6909
  @return
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934
    negated expression
*/

Item *negate_expression(THD *thd, Item *expr)
{
  Item *negated;
  if (expr->type() == Item::FUNC_ITEM &&
      ((Item_func *) expr)->functype() == Item_func::NOT_FUNC)
  {
    /* it is NOT(NOT( ... )) */
    Item *arg= ((Item_func *) expr)->arguments()[0];
    enum_parsing_place place= thd->lex->current_select->parsing_place;
    if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING)
      return arg;
    /*
      if it is not boolean function then we have to emulate value of
      not(not(a)), it will be a != 0
    */
    return new Item_func_ne(arg, new Item_int((char*) "0", 0, 1));
  }

  if ((negated= expr->neg_transformer(thd)) != 0)
    return negated;
  return new Item_func_not(expr);
}
6935

6936 6937 6938
/**
  Set the specified definer to the default value, which is the
  current user in the thread.
6939
 
6940 6941
  @param[in]  thd       thread handler
  @param[out] definer   definer
6942 6943
*/
 
6944
void get_default_definer(THD *thd, LEX_USER *definer)
6945 6946 6947 6948 6949 6950 6951 6952
{
  const Security_context *sctx= thd->security_ctx;

  definer->user.str= (char *) sctx->priv_user;
  definer->user.length= strlen(definer->user.str);

  definer->host.str= (char *) sctx->priv_host;
  definer->host.length= strlen(definer->host.str);
6953

6954 6955 6956
  definer->password= null_lex_str;
  definer->plugin= empty_lex_str;
  definer->auth= empty_lex_str;
6957 6958
}

6959

6960
/**
6961
  Create default definer for the specified THD.
6962

6963
  @param[in] thd         thread handler
6964

6965 6966
  @return
    - On success, return a valid pointer to the created and initialized
6967
    LEX_USER, which contains definer information.
6968
    - On error, return 0.
6969 6970 6971 6972 6973 6974 6975 6976 6977
*/

LEX_USER *create_default_definer(THD *thd)
{
  LEX_USER *definer;

  if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER))))
    return 0;

6978
  thd->get_definer(definer);
6979 6980 6981 6982 6983

  return definer;
}


6984
/**
6985
  Create definer with the given user and host names.
6986

6987 6988 6989
  @param[in] thd          thread handler
  @param[in] user_name    user name
  @param[in] host_name    host name
6990

6991 6992
  @return
    - On success, return a valid pointer to the created and initialized
6993
    LEX_USER, which contains definer information.
6994
    - On error, return 0.
6995 6996
*/

6997
LEX_USER *create_definer(THD *thd, LEX_STRING *user_name, LEX_STRING *host_name)
6998
{
6999 7000 7001 7002
  LEX_USER *definer;

  /* Create and initialize. */

7003
  if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER))))
7004 7005 7006 7007
    return 0;

  definer->user= *user_name;
  definer->host= *host_name;
7008 7009
  definer->password.str= NULL;
  definer->password.length= 0;
7010 7011

  return definer;
7012
}
7013 7014


7015
/**
7016 7017
  Retuns information about user or current user.

7018 7019
  @param[in] thd          thread handler
  @param[in] user         user
7020

7021 7022
  @return
    - On success, return a valid pointer to initialized
7023
    LEX_USER, which contains user information.
7024
    - On error, return 0.
7025 7026 7027 7028 7029
*/

LEX_USER *get_current_user(THD *thd, LEX_USER *user)
{
  if (!user->user.str)  // current_user
7030 7031
    return create_default_definer(thd);

7032 7033
  return user;
}
7034 7035


7036
/**
7037
  Check that byte length of a string does not exceed some limit.
7038

7039 7040 7041
  @param str         string to be checked
  @param err_msg     error message to be displayed if the string is too long
  @param max_length  max length
7042

7043
  @retval
7044
    FALSE   the passed string is not longer than max_length
7045
  @retval
7046
    TRUE    the passed string is longer than max_length
7047 7048 7049

  NOTE
    The function is not used in existing code but can be useful later?
7050 7051
*/

7052 7053
bool check_string_byte_length(LEX_STRING *str, const char *err_msg,
                              uint max_byte_length)
7054
{
7055
  if (str->length <= max_byte_length)
7056
    return FALSE;
7057

7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089
  my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_byte_length);

  return TRUE;
}


/*
  Check that char length of a string does not exceed some limit.

  SYNOPSIS
  check_string_char_length()
      str              string to be checked
      err_msg          error message to be displayed if the string is too long
      max_char_length  max length in symbols
      cs               string charset

  RETURN
    FALSE   the passed string is not longer than max_char_length
    TRUE    the passed string is longer than max_char_length
*/


bool check_string_char_length(LEX_STRING *str, const char *err_msg,
                              uint max_char_length, CHARSET_INFO *cs,
                              bool no_error)
{
  int well_formed_error;
  uint res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
                                      max_char_length, &well_formed_error);

  if (!well_formed_error &&  str->length == res)
    return FALSE;
7090

7091
  if (!no_error)
7092 7093 7094 7095
  {
    ErrConvString err(str->str, str->length, cs);
    my_error(ER_WRONG_STRING_LENGTH, MYF(0), err.ptr(), err_msg, max_char_length);
  }
7096 7097
  return TRUE;
}
7098 7099


7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111
/*
  Check if path does not contain mysql data home directory
  SYNOPSIS
    test_if_data_home_dir()
    dir                     directory
    conv_home_dir           converted data home directory
    home_dir_len            converted data home directory length

  RETURN VALUES
    0	ok
    1	error  
*/
7112
C_MODE_START
7113

7114
int test_if_data_home_dir(const char *dir)
7115
{
7116
  char path[FN_REFLEN];
Alexey Botchkov's avatar
Alexey Botchkov committed
7117
  int dir_len;
7118 7119 7120 7121 7122 7123 7124
  DBUG_ENTER("test_if_data_home_dir");

  if (!dir)
    DBUG_RETURN(0);

  (void) fn_format(path, dir, "", "",
                   (MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS));
7125 7126
  dir_len= strlen(path);
  if (mysql_unpacked_real_data_home_len<= dir_len)
7127
  {
7128 7129 7130 7131
    if (dir_len > mysql_unpacked_real_data_home_len &&
        path[mysql_unpacked_real_data_home_len] != FN_LIBCHAR)
      DBUG_RETURN(0);

7132 7133
    if (lower_case_file_system)
    {
7134 7135
      if (!my_strnncoll(default_charset_info, (const uchar*) path,
                        mysql_unpacked_real_data_home_len,
7136
                        (const uchar*) mysql_unpacked_real_data_home,
7137
                        mysql_unpacked_real_data_home_len))
7138 7139
        DBUG_RETURN(1);
    }
7140 7141
    else if (!memcmp(path, mysql_unpacked_real_data_home,
                     mysql_unpacked_real_data_home_len))
7142 7143 7144 7145 7146
      DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}

7147 7148
C_MODE_END

7149

7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164
/**
  Check that host name string is valid.

  @param[in] str string to be checked

  @return             Operation status
    @retval  FALSE    host name is ok
    @retval  TRUE     host name string is longer than max_length or
                      has invalid symbols
*/

bool check_host_name(LEX_STRING *str)
{
  const char *name= str->str;
  const char *end= str->str + str->length;
Sergey Glukhov's avatar
Sergey Glukhov committed
7165
  if (check_string_byte_length(str, ER(ER_HOSTNAME), HOSTNAME_LENGTH))
7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180
    return TRUE;

  while (name != end)
  {
    if (*name == '@')
    {
      my_printf_error(ER_UNKNOWN_ERROR, 
                      "Malformed hostname (illegal symbol: '%c')", MYF(0),
                      *name);
      return TRUE;
    }
    name++;
  }
  return FALSE;
}
Sergey Glukhov's avatar
Sergey Glukhov committed
7181 7182


7183 7184 7185 7186 7187 7188 7189 7190
extern int MYSQLparse(void *thd); // from sql_yacc.cc


/**
  This is a wrapper of MYSQLparse(). All the code should call parse_sql()
  instead of MYSQLparse().

  @param thd Thread context.
7191
  @param parser_state Parser state.
7192
  @param creation_ctx Object creation context.
7193 7194 7195 7196 7197 7198

  @return Error status.
    @retval FALSE on success.
    @retval TRUE on parsing error.
*/

7199
bool parse_sql(THD *thd,
7200
               Parser_state *parser_state,
7201
               Object_creation_ctx *creation_ctx)
7202
{
7203
  bool ret_value;
7204
  DBUG_ASSERT(thd->m_parser_state == NULL);
7205
  DBUG_ASSERT(thd->lex->m_stmt == NULL);
7206

7207
  MYSQL_QUERY_PARSE_START(thd->query());
7208 7209 7210 7211
  /* Backup creation context. */

  Object_creation_ctx *backup_ctx= NULL;

7212 7213 7214
  if (check_stack_overrun(thd, 2 * STACK_MIN_SIZE, (uchar*)&backup_ctx))
    return TRUE;

7215 7216 7217
  if (creation_ctx)
    backup_ctx= creation_ctx->set_n_backup(thd);

7218
  /* Set parser state. */
7219

7220
  thd->m_parser_state= parser_state;
7221

7222 7223
  /* Parse the query. */

7224 7225
  bool mysql_parse_status= MYSQLparse(thd) != 0;

7226
  /* Check that if MYSQLparse() failed, thd->is_error() is set. */
7227 7228

  DBUG_ASSERT(!mysql_parse_status ||
Staale Smedseng's avatar
Staale Smedseng committed
7229
              (mysql_parse_status && thd->is_error()));
7230

7231
  /* Reset parser state. */
7232

7233
  thd->m_parser_state= NULL;
7234

7235 7236 7237 7238 7239 7240 7241
  /* Restore creation context. */

  if (creation_ctx)
    creation_ctx->restore_env(thd, backup_ctx);

  /* That's it. */

7242 7243 7244
  ret_value= mysql_parse_status || thd->is_fatal_error;
  MYSQL_QUERY_PARSE_DONE(ret_value);
  return ret_value;
7245
}
7246 7247 7248 7249

/**
  @} (end of group Runtime_Environment)
*/
Alexander Barkov's avatar
#  
Alexander Barkov committed
7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283



/**
  Check and merge "CHARACTER SET cs [ COLLATE cl ]" clause

  @param cs character set pointer.
  @param cl collation pointer.

  Check if collation "cl" is applicable to character set "cs".

  If "cl" is NULL (e.g. when COLLATE clause is not specified),
  then simply "cs" is returned.
  
  @return Error status.
    @retval NULL, if "cl" is not applicable to "cs".
    @retval pointer to merged CHARSET_INFO on success.
*/


CHARSET_INFO*
merge_charset_and_collation(CHARSET_INFO *cs, CHARSET_INFO *cl)
{
  if (cl)
  {
    if (!my_charset_same(cs, cl))
    {
      my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0), cl->name, cs->csname);
      return NULL;
    }
    return cl;
  }
  return cs;
}