sql_parse.cc 230 KB
Newer Older
1
/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
2

unknown's avatar
unknown 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
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
6

unknown's avatar
unknown 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

unknown's avatar
unknown 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
unknown's avatar
unknown committed
17
#include "mysql_priv.h"
18
#include "sql_repl.h"
unknown's avatar
unknown committed
19
#include "rpl_filter.h"
20
#include "repl_failsafe.h"
unknown's avatar
unknown committed
21 22 23
#include <m_ctype.h>
#include <myisam.h>
#include <my_dir.h>
He Zhenxing's avatar
He Zhenxing committed
24
#include "rpl_handler.h"
unknown's avatar
unknown committed
25

26
#include "sp_head.h"
27
#include "sp.h"
28
#include "sp_cache.h"
29
#include "events.h"
30
#include "sql_trigger.h"
Konstantin Osipov's avatar
Konstantin Osipov committed
31
#include "transaction.h"
32
#include "sql_prepare.h"
33
#include "probes_mysql.h"
34

35 36 37 38 39
/**
  @defgroup Runtime_Environment Runtime Environment
  @{
*/

40 41 42 43 44 45
/* 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 || \
46
   (LP)->sql_command == SQLCOM_SHOW_CREATE_FUNC || \
47 48 49
   (LP)->sql_command == SQLCOM_DROP_FUNCTION ? \
   "FUNCTION" : "PROCEDURE")

50
static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables);
unknown's avatar
unknown committed
51

52
const char *any_db="*any*";	// Special symbol for check_access
unknown's avatar
unknown committed
53

unknown's avatar
unknown committed
54
const LEX_STRING command_name[]={
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
  { 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
unknown's avatar
unknown committed
86 87
};

unknown's avatar
unknown committed
88
const char *xa_state_names[]={
89
  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED", "ROLLBACK ONLY"
unknown's avatar
unknown committed
90 91
};

92

unknown's avatar
unknown committed
93
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
94 95
/**
  Returns true if all tables should be ignored.
96
*/
97 98
inline bool all_tables_not_ok(THD *thd, TABLE_LIST *tables)
{
unknown's avatar
unknown committed
99 100
  return rpl_filter->is_on() && tables && !thd->spcont &&
         !rpl_filter->tables_ok(thd->db, tables);
101
}
unknown's avatar
unknown committed
102
#endif
103 104


105 106 107 108 109 110 111 112 113 114 115 116
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);
    if (table->updating &&
        !find_temporary_table(thd, table->db, table->table_name))
      return 1;
  }
  return 0;
}

117

Konstantin Osipov's avatar
Konstantin Osipov committed
118 119 120 121 122 123 124
/*
  Implicitly commit a active transaction if statement requires so.

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

*/
125
static bool stmt_causes_implicit_commit(THD *thd, uint mask)
Konstantin Osipov's avatar
Konstantin Osipov committed
126 127
{
  LEX *lex= thd->lex;
128 129
  bool skip= FALSE;
  DBUG_ENTER("stmt_causes_implicit_commit");
Konstantin Osipov's avatar
Konstantin Osipov committed
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

  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;
  }

150
  DBUG_RETURN(!skip);
Konstantin Osipov's avatar
Konstantin Osipov committed
151 152 153
}


unknown's avatar
unknown committed
154 155 156 157
/**
  Mark all commands that somehow changes a table.

  This is used to check number of updates / hour.
unknown's avatar
unknown committed
158 159 160

  sql_command is actually set to SQLCOM_END sometimes
  so we need the +1 to include it in the array.
unknown's avatar
unknown committed
161

162
  See COMMAND_FLAG_xxx for different type of commands
unknown's avatar
unknown committed
163 164
     2  - query that returns meaningful ROW_COUNT() -
          a number of modified rows
165 166
*/

167
uint sql_command_flags[SQLCOM_END+1];
Konstantin Osipov's avatar
Konstantin Osipov committed
168
uint server_command_flags[COM_END+1];
169 170 171

void init_update_queries(void)
{
Konstantin Osipov's avatar
Konstantin Osipov committed
172 173 174 175 176 177 178 179 180 181 182 183 184
  /* 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));

  sql_command_flags[SQLCOM_CREATE_TABLE]=   CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
185
                                            CF_AUTO_COMMIT_TRANS | CF_PROTECT_AGAINST_GRL;
Konstantin Osipov's avatar
Konstantin Osipov committed
186 187
  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 |
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
188
                                            CF_AUTO_COMMIT_TRANS | CF_PROTECT_AGAINST_GRL;
Konstantin Osipov's avatar
Konstantin Osipov committed
189 190 191
  sql_command_flags[SQLCOM_TRUNCATE]=       CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
                                            CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_TABLE]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
192 193
  sql_command_flags[SQLCOM_LOAD]=           CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_PROTECT_AGAINST_GRL;
Konstantin Osipov's avatar
Konstantin Osipov committed
194 195
  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;
196 197
  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
198 199 200 201 202
  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;
203 204
  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
205 206 207 208 209
  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;
  sql_command_flags[SQLCOM_CREATE_TRIGGER]= CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_TRIGGER]=   CF_AUTO_COMMIT_TRANS;
210

unknown's avatar
unknown committed
211
  sql_command_flags[SQLCOM_UPDATE]=	    CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
212
                                            CF_REEXECUTION_FRAGILE | CF_PROTECT_AGAINST_GRL;
unknown's avatar
unknown committed
213
  sql_command_flags[SQLCOM_UPDATE_MULTI]=   CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
214
                                            CF_REEXECUTION_FRAGILE | CF_PROTECT_AGAINST_GRL;
unknown's avatar
unknown committed
215
  sql_command_flags[SQLCOM_INSERT]=	    CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
216
                                            CF_REEXECUTION_FRAGILE | CF_PROTECT_AGAINST_GRL;
unknown's avatar
unknown committed
217
  sql_command_flags[SQLCOM_INSERT_SELECT]=  CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
218
                                            CF_REEXECUTION_FRAGILE | CF_PROTECT_AGAINST_GRL;
unknown's avatar
unknown committed
219
  sql_command_flags[SQLCOM_DELETE]=         CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
220
                                            CF_REEXECUTION_FRAGILE | CF_PROTECT_AGAINST_GRL;
unknown's avatar
unknown committed
221
  sql_command_flags[SQLCOM_DELETE_MULTI]=   CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
222
                                            CF_REEXECUTION_FRAGILE | CF_PROTECT_AGAINST_GRL;
unknown's avatar
unknown committed
223 224 225 226 227
  sql_command_flags[SQLCOM_REPLACE]=        CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
                                            CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
                                            CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SELECT]=         CF_REEXECUTION_FRAGILE;
228
  sql_command_flags[SQLCOM_SET_OPTION]=     CF_REEXECUTION_FRAGILE | CF_AUTO_COMMIT_TRANS;
229 230 231 232 233 234 235 236
  sql_command_flags[SQLCOM_DO]=             CF_REEXECUTION_FRAGILE;

  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;
237
  sql_command_flags[SQLCOM_SHOW_PLUGINS]=     CF_STATUS_COMMAND;
238 239 240 241 242
  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;
243 244
  sql_command_flags[SQLCOM_SHOW_NEW_MASTER]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_BINLOGS]=     CF_STATUS_COMMAND;
245 246 247
  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;
248
  sql_command_flags[SQLCOM_SHOW_AUTHORS]=     CF_STATUS_COMMAND;
249
  sql_command_flags[SQLCOM_SHOW_CONTRIBUTORS]= CF_STATUS_COMMAND;
250 251 252
  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;
253 254 255 256
  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;
257 258
  sql_command_flags[SQLCOM_SHOW_GRANTS]=      CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_DB]=   CF_STATUS_COMMAND;
259
  sql_command_flags[SQLCOM_SHOW_CREATE]=  CF_STATUS_COMMAND;
260
  sql_command_flags[SQLCOM_SHOW_MASTER_STAT]= CF_STATUS_COMMAND;
261
  sql_command_flags[SQLCOM_SHOW_SLAVE_STAT]=  CF_STATUS_COMMAND;
262 263
  sql_command_flags[SQLCOM_SHOW_CREATE_PROC]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_FUNC]= CF_STATUS_COMMAND;
264
  sql_command_flags[SQLCOM_SHOW_CREATE_TRIGGER]=  CF_STATUS_COMMAND;
265 266 267 268 269 270 271
  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;
272 273

   sql_command_flags[SQLCOM_SHOW_TABLES]=       (CF_STATUS_COMMAND |
274 275
                                                 CF_SHOW_TABLE_COMMAND |
                                                 CF_REEXECUTION_FRAGILE);
276
  sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND |
277 278
                                                CF_SHOW_TABLE_COMMAND |
                                                CF_REEXECUTION_FRAGILE);
279

280

Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
281 282 283
  sql_command_flags[SQLCOM_CREATE_USER]=       CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL;
  sql_command_flags[SQLCOM_RENAME_USER]=       CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL;
  sql_command_flags[SQLCOM_DROP_USER]=         CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL;
284 285
  sql_command_flags[SQLCOM_GRANT]=             CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_REVOKE]=            CF_CHANGES_DATA;
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
286
  sql_command_flags[SQLCOM_REVOKE_ALL]=        CF_PROTECT_AGAINST_GRL;
287
  sql_command_flags[SQLCOM_OPTIMIZE]=          CF_CHANGES_DATA;
Konstantin Osipov's avatar
Konstantin Osipov committed
288 289 290 291 292 293 294
  sql_command_flags[SQLCOM_CREATE_FUNCTION]=   CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_CREATE_PROCEDURE]=  CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_CREATE_SPFUNCTION]= CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_PROCEDURE]=    CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_FUNCTION]=     CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_PROCEDURE]=   CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_FUNCTION]=    CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL | CF_AUTO_COMMIT_TRANS;
295 296 297
  sql_command_flags[SQLCOM_INSTALL_PLUGIN]=    CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_UNINSTALL_PLUGIN]=  CF_CHANGES_DATA;

298 299 300 301 302 303
  /*
    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.
  */
304 305
  sql_command_flags[SQLCOM_CALL]=      CF_HAS_ROW_COUNT | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_EXECUTE]=   CF_HAS_ROW_COUNT;
306 307 308 309 310

  /*
    The following admin table operations are allowed
    on log tables.
  */
311 312 313 314 315 316 317 318 319 320 321
  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;

  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
322 323 324 325 326
  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;
  sql_command_flags[SQLCOM_CHECK]=              CF_AUTO_COMMIT_TRANS;
327 328
}

329

unknown's avatar
unknown committed
330 331
bool is_update_query(enum enum_sql_command command)
{
unknown's avatar
unknown committed
332
  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
333
  return (sql_command_flags[command] & CF_CHANGES_DATA) != 0;
unknown's avatar
unknown committed
334
}
335

336 337 338 339 340 341 342 343 344 345
/**
  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;
}
346

347 348
void execute_init_command(THD *thd, sys_var_str *init_command_var,
			  rw_lock_t *var_mutex)
unknown's avatar
unknown committed
349 350 351 352
{
  Vio* save_vio;
  ulong save_client_capabilities;

353
#if defined(ENABLED_PROFILING)
354 355 356 357 358
  thd->profiling.start_new_query();
  thd->profiling.set_query_source(init_command_var->value,
                                  init_command_var->value_length);
#endif

359
  thd_proc_info(thd, "Execution of init_command");
360 361 362 363 364 365
  /*
    We need to lock init_command_var because
    during execution of init_command_var query
    values of init_command_var can't be changed
  */
  rw_rdlock(var_mutex);
unknown's avatar
unknown committed
366 367
  save_client_capabilities= thd->client_capabilities;
  thd->client_capabilities|= CLIENT_MULTI_QUERIES;
368 369 370 371
  /*
    We don't need return result of execution to client side.
    To forbid this we should set thd->net.vio to 0.
  */
unknown's avatar
unknown committed
372 373
  save_vio= thd->net.vio;
  thd->net.vio= 0;
374 375 376
  dispatch_command(COM_QUERY, thd,
                   init_command_var->value,
                   init_command_var->value_length);
377
  rw_unlock(var_mutex);
unknown's avatar
unknown committed
378 379
  thd->client_capabilities= save_client_capabilities;
  thd->net.vio= save_vio;
380

381
#if defined(ENABLED_PROFILING)
382 383
  thd->profiling.finish_current_query();
#endif
unknown's avatar
unknown committed
384 385 386
}


387
static void handle_bootstrap_impl(THD *thd)
unknown's avatar
unknown committed
388
{
389 390
  FILE *file=bootstrap_file;
  char *buff;
391
  const char* found_semicolon= NULL;
unknown's avatar
unknown committed
392

393 394
  DBUG_ENTER("handle_bootstrap");

unknown's avatar
unknown committed
395
#ifndef EMBEDDED_LIBRARY
396 397
  pthread_detach_this_thread();
  thd->thread_stack= (char*) &thd;
unknown's avatar
unknown committed
398
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
399

400
  if (thd->variables.max_join_size == HA_POS_ERROR)
unknown's avatar
unknown committed
401 402
    thd->options |= OPTION_BIG_SELECTS;

403
  thd_proc_info(thd, 0);
unknown's avatar
unknown committed
404
  thd->version=refresh_version;
405 406
  thd->security_ctx->priv_user=
    thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME));
unknown's avatar
unknown committed
407
  thd->security_ctx->priv_host[0]=0;
408 409 410 411 412 413
  /*
    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;
unknown's avatar
unknown committed
414

415
  buff= (char*) thd->net.buff;
416
  thd->init_for_queries();
unknown's avatar
unknown committed
417 418
  while (fgets(buff, thd->net.max_packet, file))
  {
419
    char *query, *res;
420 421 422 423 424 425 426 427 428 429 430
    /* strlen() can't be deleted because fgets() doesn't return length */
    ulong length= (ulong) strlen(buff);
    while (buff[length-1] != '\n' && !feof(file))
    {
      /*
        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))
      {
431
        thd->protocol->end_statement();
432
        bootstrap_error= 1;
433 434 435
        break;
      }
      buff= (char*) thd->net.buff;
Staale Smedseng's avatar
Staale Smedseng committed
436
      res= fgets(buff + length, thd->net.max_packet - length, file);
437 438 439
      length+= (ulong) strlen(buff + length);
      /* purecov: end */
    }
440
    if (bootstrap_error)
441
      break;                                    /* purecov: inspected */
unknown's avatar
unknown committed
442

unknown's avatar
unknown committed
443
    while (length && (my_isspace(thd->charset(), buff[length-1]) ||
444
                      buff[length-1] == ';'))
unknown's avatar
unknown committed
445 446
      length--;
    buff[length]=0;
unknown's avatar
unknown committed
447 448 449 450 451

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

Gleb Shchepa's avatar
Gleb Shchepa committed
452 453 454
    query= (char *) thd->memdup_w_gap(buff, length + 1,
                                      thd->db_length + 1 +
                                      QUERY_CACHE_FLAGS_SIZE);
455
    thd->set_query(query, length);
456
    DBUG_PRINT("query",("%-.4096s",thd->query()));
457
#if defined(ENABLED_PROFILING)
458
    thd->profiling.start_new_query();
459
    thd->profiling.set_query_source(thd->query(), length);
460 461
#endif

462 463 464 465
    /*
      We don't need to obtain LOCK_thread_count here because in bootstrap
      mode we have only one thread.
    */
466
    thd->query_id=next_query_id();
467
    thd->set_time();
468
    mysql_parse(thd, thd->query(), length, & found_semicolon);
unknown's avatar
unknown committed
469
    close_thread_tables(thd);			// Free tables
470

471
    bootstrap_error= thd->is_error();
472
    thd->protocol->end_statement();
473

474
#if defined(ENABLED_PROFILING)
475 476 477
    thd->profiling.finish_current_query();
#endif

478
    if (bootstrap_error)
479 480
      break;

unknown's avatar
unknown committed
481
    free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
482
    free_root(&thd->transaction.mem_root,MYF(MY_KEEP_PREALLOC));
unknown's avatar
unknown committed
483
  }
484

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
  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;

  /* 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);

512
end:
513 514 515 516
  net_end(&thd->net);
  thd->cleanup();
  delete thd;

unknown's avatar
unknown committed
517
#ifndef EMBEDDED_LIBRARY
518 519
  (void) pthread_mutex_lock(&LOCK_thread_count);
  thread_count--;
520
  in_bootstrap= FALSE;
521
  (void) pthread_cond_broadcast(&COND_thread_count);
522
  (void) pthread_mutex_unlock(&LOCK_thread_count);
523 524
  my_thread_end();
  pthread_exit(0);
unknown's avatar
unknown committed
525
#endif
526 527

  return 0;
unknown's avatar
unknown committed
528 529 530
}


531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
/**
  @brief Check access privs for a MERGE table and fix children lock types.

  @param[in]        thd         thread handle
  @param[in]        db          database name
  @param[in,out]    table_list  list of child tables (merge_list)
                                lock_type and optionally db set per table

  @return           status
    @retval         0           OK
    @retval         != 0        Error

  @detail
    This function is used for write access to MERGE tables only
    (CREATE TABLE, ALTER TABLE ... UNION=(...)). Set TL_WRITE for
    every child. Set 'db' for every child if not present.
*/
unknown's avatar
unknown committed
548
#ifndef NO_EMBEDDED_ACCESS_CHECKS
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
static bool check_merge_table_access(THD *thd, char *db,
                                     TABLE_LIST *table_list)
{
  int error= 0;

  if (table_list)
  {
    /* Check that all tables use the current database */
    TABLE_LIST *tlist;

    for (tlist= table_list; tlist; tlist= tlist->next_local)
    {
      if (!tlist->db || !tlist->db[0])
        tlist->db= db; /* purecov: inspected */
    }
    error= check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL,
565
                              table_list, FALSE, UINT_MAX, FALSE);
566 567 568
  }
  return error;
}
unknown's avatar
unknown committed
569
#endif
570

unknown's avatar
unknown committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
/* 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;
}

/* This works because items are allocated with sql_alloc() */
586 587 588

void cleanup_items(Item *item)
{
unknown's avatar
unknown committed
589
  DBUG_ENTER("cleanup_items");  
590 591
  for (; item ; item=item->next)
    item->cleanup();
unknown's avatar
unknown committed
592
  DBUG_VOID_RETURN;
593 594
}

595
#ifndef EMBEDDED_LIBRARY
596

unknown's avatar
unknown committed
597
/**
unknown's avatar
unknown committed
598
  Read one command from connection and execute it (query or simple command).
599
  This function is called in loop from thread function.
600 601 602

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

unknown's avatar
unknown committed
603
  @retval
604
    0  success
unknown's avatar
unknown committed
605
  @retval
606 607 608
    1  request of thread shutdown (see dispatch_command() description)
*/

unknown's avatar
unknown committed
609 610
bool do_command(THD *thd)
{
611
  bool return_value;
unknown's avatar
unknown committed
612
  char *packet= 0;
unknown's avatar
unknown committed
613
  ulong packet_length;
unknown's avatar
unknown committed
614
  NET *net= &thd->net;
unknown's avatar
unknown committed
615 616 617
  enum enum_server_command command;
  DBUG_ENTER("do_command");

unknown's avatar
unknown committed
618 619 620 621
  /*
    indicator of uninitialized lex => normal flow of errors handling
    (see my_message_sql)
  */
622
  thd->lex->current_select= 0;
unknown's avatar
unknown committed
623

unknown's avatar
unknown committed
624 625 626 627 628 629
  /*
    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"
    number of seconds has passed
  */
630
  my_net_set_read_timeout(net, thd->variables.net_wait_timeout);
unknown's avatar
unknown committed
631

632 633 634 635
  /*
    XXX: this code is here only to clear possible errors of init_connect. 
    Consider moving to init_connect() instead.
  */
unknown's avatar
unknown committed
636
  thd->clear_error();				// Clear error message
Marc Alff's avatar
Marc Alff committed
637
  thd->stmt_da->reset_diagnostics_area();
unknown's avatar
unknown committed
638 639

  net_new_transaction(net);
640

Konstantin Osipov's avatar
Konstantin Osipov committed
641
  if ((packet_length= my_net_read(net)) == packet_error)
unknown's avatar
unknown committed
642
  {
643 644 645
    DBUG_PRINT("info",("Got error %d reading command from socket %s",
		       net->error,
		       vio_description(net->vio)));
646

647
    /* Check if we can continue without closing the connection */
648

649 650
    /* The error must be set. */
    DBUG_ASSERT(thd->is_error());
651
    thd->protocol->end_statement();
652

653
    if (net->error != 3)
654
    {
655
      return_value= TRUE;                       // We have to close it.
656 657
      goto out;
    }
658

659
    net->error= 0;
660 661
    return_value= FALSE;
    goto out;
unknown's avatar
unknown committed
662
  }
663 664 665 666 667 668 669 670 671 672 673

  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 */
unknown's avatar
unknown committed
674
  {
675 676 677
    /* Initialize with COM_SLEEP packet */
    packet[0]= (uchar) COM_SLEEP;
    packet_length= 1;
unknown's avatar
unknown committed
678
  }
679 680 681 682 683 684 685 686 687 688 689
  /* 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));
unknown's avatar
unknown committed
690 691

  /* Restore read timeout value */
692
  my_net_set_read_timeout(net, thd->variables.net_read_timeout);
unknown's avatar
unknown committed
693

694
  DBUG_ASSERT(packet_length);
695 696 697 698
  return_value= dispatch_command(command, thd, packet+1, (uint) (packet_length-1));

out:
  DBUG_RETURN(return_value);
699
}
700
#endif  /* EMBEDDED_LIBRARY */
701

702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
/**
  @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);

733
  if (!(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA))
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    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);
}
769

unknown's avatar
unknown committed
770 771
/**
  Perform one connection-level (COM_XXXX) command.
772

unknown's avatar
unknown committed
773 774 775 776 777 778 779 780
  @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
781 782 783
    set thd->lex->sql_command to SQLCOM_END here.
  @todo
    The following has to be changed to an 8 byte integer
unknown's avatar
unknown committed
784 785

  @retval
786
    0   ok
unknown's avatar
unknown committed
787
  @retval
788 789 790
    1   request of thread shutdown, i. e. if command is
        COM_QUIT/COM_SHUTDOWN
*/
791 792 793 794
bool dispatch_command(enum enum_server_command command, THD *thd,
		      char* packet, uint packet_length)
{
  NET *net= &thd->net;
795
  bool error= 0;
796
  DBUG_ENTER("dispatch_command");
797
  DBUG_PRINT("info",("packet: '%*.s'; command: %d", packet_length, packet, command));
798

Konstantin Osipov's avatar
Konstantin Osipov committed
799 800 801
#if defined(ENABLED_PROFILING)
  thd->profiling.start_new_query();
#endif
802 803 804 805
  MYSQL_COMMAND_START(thd->thread_id, command,
                      thd->security_ctx->priv_user,
                      (char *) thd->security_ctx->host_or_ip);
  
806
  thd->command=command;
unknown's avatar
unknown committed
807
  /*
808 809
    Commands which always take a long time are logged into
    the slow log only if opt_log_slow_admin_statements is set.
unknown's avatar
unknown committed
810
  */
811
  thd->enable_slow_log= TRUE;
812
  thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
unknown's avatar
unknown committed
813
  thd->set_time();
Konstantin Osipov's avatar
Konstantin Osipov committed
814
  pthread_mutex_lock(&LOCK_thread_count);
unknown's avatar
unknown committed
815
  thd->query_id= global_query_id;
Konstantin Osipov's avatar
Konstantin Osipov committed
816
  if (!(server_command_flags[command] & CF_SKIP_QUERY_ID))
817
    next_query_id();
unknown's avatar
unknown committed
818
  thread_running++;
Konstantin Osipov's avatar
Konstantin Osipov committed
819
  pthread_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
820

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

824 825 826 827 828
  /**
    Clear the set of flags that are expected to be cleared at the
    beginning of each command.
  */
  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
829
  switch (command) {
unknown's avatar
unknown committed
830
  case COM_INIT_DB:
unknown's avatar
unknown committed
831 832
  {
    LEX_STRING tmp;
833
    status_var_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB]);
unknown's avatar
unknown committed
834
    thd->convert_string(&tmp, system_charset_info,
835
			packet, packet_length, thd->charset());
unknown's avatar
unknown committed
836
    if (!mysql_change_db(thd, &tmp, FALSE))
837
    {
838
      general_log_write(thd, command, thd->db, thd->db_length);
839
      my_ok(thd);
840
    }
unknown's avatar
unknown committed
841 842
    break;
  }
unknown's avatar
unknown committed
843
#ifdef HAVE_REPLICATION
844 845
  case COM_REGISTER_SLAVE:
  {
846
    if (!register_slave(thd, (uchar*)packet, packet_length))
847
      my_ok(thd);
848 849
    break;
  }
850
#endif
unknown's avatar
unknown committed
851 852
  case COM_CHANGE_USER:
  {
853
    status_var_increment(thd->status_var.com_other);
854 855
    char *user= (char*) packet, *packet_end= packet + packet_length;
    /* Safe because there is always a trailing \0 at the end of the packet */
856 857
    char *passwd= strend(user)+1;

unknown's avatar
unknown committed
858
    thd->change_user();
859
    thd->clear_error();                         // if errors from rollback
unknown's avatar
unknown committed
860

861
    /*
unknown's avatar
unknown committed
862 863 864
      Old clients send null-terminated string ('\0' for empty string) for
      password.  New clients send the size (1 byte) + string (not null
      terminated, so also '\0' for empty string).
865 866 867

      Cast *passwd to an unsigned char, so that it doesn't extend the sign
      for *passwd > 127 and become 2**32-127 after casting to uint.
unknown's avatar
unknown committed
868
    */
869
    char db_buff[NAME_LEN+1];                 // buffer to store db in utf8
unknown's avatar
unknown committed
870
    char *db= passwd;
871
    char *save_db;
872 873 874 875 876 877 878 879 880
    /*
      If there is no password supplied, the packet must contain '\0',
      in any type of handshake (4.1 or pre-4.1).
     */
    if (passwd >= packet_end)
    {
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
      break;
    }
881
    uint passwd_len= (thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
882
                      (uchar)(*passwd++) : strlen(passwd));
883 884
    uint dummy_errors, save_db_length, db_length;
    int res;
885 886 887
    Security_context save_security_ctx= *thd->security_ctx;
    USER_CONN *save_user_connect;

unknown's avatar
unknown committed
888
    db+= passwd_len + 1;
889 890 891 892 893
    /*
      Database name is always NUL-terminated, so in case of empty database
      the packet must contain at least the trailing '\0'.
    */
    if (db >= packet_end)
894
    {
unknown's avatar
unknown committed
895
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
896 897
      break;
    }
898 899
    db_length= strlen(db);

900
    char *ptr= db + db_length + 1;
901 902
    uint cs_number= 0;

903 904 905 906 907 908 909 910 911 912
    if (ptr < packet_end)
    {
      if (ptr + 2 > packet_end)
      {
        my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
        break;
      }

      cs_number= uint2korr(ptr);
    }
913

914
    /* Convert database name to utf8 */
915
    db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
916
                             system_charset_info, db, db_length,
917
                             thd->charset(), &dummy_errors)]= 0;
918
    db= db_buff;
unknown's avatar
unknown committed
919

920
    /* Save user and privileges */
921 922 923
    save_db_length= thd->db_length;
    save_db= thd->db;
    save_user_connect= thd->user_connect;
924 925

    if (!(thd->security_ctx->user= my_strdup(user, MYF(0))))
926
    {
927
      thd->security_ctx->user= save_security_ctx.user;
unknown's avatar
unknown committed
928
      my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
929 930
      break;
    }
unknown's avatar
unknown committed
931

unknown's avatar
unknown committed
932 933
    /* Clear variables that are allocated */
    thd->user_connect= 0;
934
    thd->security_ctx->priv_user= thd->security_ctx->user;
935
    res= check_user(thd, COM_CHANGE_USER, passwd, passwd_len, db, FALSE);
unknown's avatar
unknown committed
936

937 938
    if (res)
    {
939 940
      x_free(thd->security_ctx->user);
      *thd->security_ctx= save_security_ctx;
unknown's avatar
unknown committed
941
      thd->user_connect= save_user_connect;
942 943 944 945 946
      thd->db= save_db;
      thd->db_length= save_db_length;
    }
    else
    {
947
#ifndef NO_EMBEDDED_ACCESS_CHECKS
948
      /* we've authenticated new user */
unknown's avatar
unknown committed
949 950
      if (save_user_connect)
	decrease_user_connections(save_user_connect);
951
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
952 953
      x_free(save_db);
      x_free(save_security_ctx.user);
954 955 956 957 958 959

      if (cs_number)
      {
        thd_init_client_charset(thd, cs_number);
        thd->update_charset();
      }
960
    }
unknown's avatar
unknown committed
961 962
    break;
  }
963
  case COM_STMT_EXECUTE:
unknown's avatar
unknown committed
964
  {
965
    mysqld_stmt_execute(thd, packet, packet_length);
unknown's avatar
unknown committed
966 967
    break;
  }
968
  case COM_STMT_FETCH:
969
  {
970
    mysqld_stmt_fetch(thd, packet, packet_length);
971 972
    break;
  }
973
  case COM_STMT_SEND_LONG_DATA:
unknown's avatar
unknown committed
974
  {
975
    mysql_stmt_get_longdata(thd, packet, packet_length);
unknown's avatar
unknown committed
976 977
    break;
  }
978
  case COM_STMT_PREPARE:
unknown's avatar
unknown committed
979
  {
980
    mysqld_stmt_prepare(thd, packet, packet_length);
unknown's avatar
unknown committed
981 982
    break;
  }
983
  case COM_STMT_CLOSE:
unknown's avatar
unknown committed
984
  {
985
    mysqld_stmt_close(thd, packet);
unknown's avatar
unknown committed
986 987
    break;
  }
988
  case COM_STMT_RESET:
989
  {
990
    mysqld_stmt_reset(thd, packet);
991 992
    break;
  }
unknown's avatar
unknown committed
993 994
  case COM_QUERY:
  {
995 996
    if (alloc_query(thd, packet, packet_length))
      break;					// fatal error is set
997
    MYSQL_QUERY_START(thd->query(), thd->thread_id,
998 999 1000
                      (char *) (thd->db ? thd->db : ""),
                      thd->security_ctx->priv_user,
                      (char *) thd->security_ctx->host_or_ip);
1001
    char *packet_end= thd->query() + thd->query_length();
unknown's avatar
unknown committed
1002
    /* 'b' stands for 'buffer' parameter', special for 'my_snprintf' */
1003
    const char* end_of_stmt= NULL;
1004

1005 1006
    general_log_write(thd, command, thd->query(), thd->query_length());
    DBUG_PRINT("query",("%-.4096s",thd->query()));
1007
#if defined(ENABLED_PROFILING)
1008
    thd->profiling.set_query_source(thd->query(), thd->query_length());
1009
#endif
1010

1011
    mysql_parse(thd, thd->query(), thd->query_length(), &end_of_stmt);
1012

1013
    while (!thd->killed && (end_of_stmt != NULL) && ! thd->is_error())
1014
    {
1015
      char *beginning_of_next_stmt= (char*) end_of_stmt;
1016

1017
      thd->protocol->end_statement();
1018
      query_cache_end_of_result(thd);
1019
      /*
1020 1021
        Multiple queries exits, execute them individually
      */
1022
      close_thread_tables(thd);
1023
      ulong length= (ulong)(packet_end - beginning_of_next_stmt);
1024

1025
      log_slow_statement(thd);
1026

1027
      /* Remove garbage at start of query */
1028
      while (length > 0 && my_isspace(thd->charset(), *beginning_of_next_stmt))
1029
      {
1030
        beginning_of_next_stmt++;
1031 1032
        length--;
      }
1033

1034 1035 1036 1037 1038
      if (MYSQL_QUERY_DONE_ENABLED())
      {
        MYSQL_QUERY_DONE(thd->is_error());
      }

1039
#if defined(ENABLED_PROFILING)
1040 1041 1042 1043 1044
      thd->profiling.finish_current_query();
      thd->profiling.start_new_query("continuing");
      thd->profiling.set_query_source(beginning_of_next_stmt, length);
#endif

1045
      MYSQL_QUERY_START(beginning_of_next_stmt, thd->thread_id,
1046 1047 1048 1049
                        (char *) (thd->db ? thd->db : ""),
                        thd->security_ctx->priv_user,
                        (char *) thd->security_ctx->host_or_ip);

Gleb Shchepa's avatar
Gleb Shchepa committed
1050
      thd->set_query(beginning_of_next_stmt, length);
Konstantin Osipov's avatar
Konstantin Osipov committed
1051
      pthread_mutex_lock(&LOCK_thread_count);
1052 1053 1054 1055
      /*
        Count each statement from the client.
      */
      statistic_increment(thd->status_var.questions, &LOCK_status);
1056
      thd->query_id= next_query_id();
1057
      thd->set_time(); /* Reset the query start time. */
1058
      /* TODO: set thd->lex->sql_command to SQLCOM_END here */
Konstantin Osipov's avatar
Konstantin Osipov committed
1059
      pthread_mutex_unlock(&LOCK_thread_count);
1060
      mysql_parse(thd, beginning_of_next_stmt, length, &end_of_stmt);
1061 1062
    }

unknown's avatar
unknown committed
1063 1064 1065
    DBUG_PRINT("info",("query ready"));
    break;
  }
1066
  case COM_FIELD_LIST:				// This isn't actually needed
unknown's avatar
unknown committed
1067
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
1068 1069
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
unknown's avatar
unknown committed
1070 1071 1072
    break;
#else
  {
1073
    char *fields, *packet_end= packet + packet_length, *arg_end;
1074
    /* Locked closure of all tables */
unknown's avatar
unknown committed
1075
    TABLE_LIST table_list;
unknown's avatar
unknown committed
1076
    LEX_STRING conv_name;
unknown's avatar
unknown committed
1077

unknown's avatar
unknown committed
1078
    /* used as fields initializator */
1079
    lex_start(thd);
1080

1081
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
unknown's avatar
unknown committed
1082
    bzero((char*) &table_list,sizeof(table_list));
1083
    if (thd->copy_db_to(&table_list.db, &table_list.db_length))
unknown's avatar
unknown committed
1084
      break;
1085 1086 1087 1088
    /*
      We have name + wildcard in packet, separated by endzero
    */
    arg_end= strend(packet);
unknown's avatar
unknown committed
1089
    thd->convert_string(&conv_name, system_charset_info,
1090
			packet, (uint) (arg_end - packet), thd->charset());
1091
    table_list.alias= table_list.table_name= conv_name.str;
1092
    packet= arg_end + 1;
1093 1094

    if (!my_strcasecmp(system_charset_info, table_list.db,
1095
                       INFORMATION_SCHEMA_NAME.str))
1096 1097 1098 1099 1100 1101
    {
      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
1102 1103
    uint query_length= (uint) (packet_end - packet); // Don't count end \0
    if (!(fields= (char *) thd->memdup(packet, query_length + 1)))
unknown's avatar
unknown committed
1104
      break;
1105
    thd->set_query(fields, query_length);
unknown's avatar
unknown committed
1106
    general_log_print(thd, command, "%s %s", table_list.table_name, fields);
1107
    if (lower_case_table_names)
1108
      my_casedn_str(files_charset_info, table_list.table_name);
unknown's avatar
unknown committed
1109

unknown's avatar
unknown committed
1110
    if (check_access(thd,SELECT_ACL,table_list.db,&table_list.grant.privilege,
1111
		     0, 0, test(table_list.schema_table)))
unknown's avatar
unknown committed
1112
      break;
1113
    if (check_grant(thd, SELECT_ACL, &table_list, TRUE, UINT_MAX, FALSE))
unknown's avatar
unknown committed
1114
      break;
1115 1116
    /* init structures for VIEW processing */
    table_list.select_lex= &(thd->lex->select_lex);
1117 1118 1119 1120

    lex_start(thd);
    mysql_reset_thd_for_next_command(thd);

1121
    thd->lex->
1122 1123
      select_lex.table_list.link_in_list((uchar*) &table_list,
                                         (uchar**) &table_list.next_local);
unknown's avatar
unknown committed
1124
    thd->lex->add_to_query_tables(&table_list);
Konstantin Osipov's avatar
Konstantin Osipov committed
1125
    init_mdl_requests(&table_list);
1126

1127 1128
    /* switch on VIEW optimisation: do not fill temporary tables */
    thd->lex->sql_command= SQLCOM_SHOW_FIELDS;
unknown's avatar
unknown committed
1129
    mysqld_list_fields(thd,&table_list,fields);
1130
    thd->lex->unit.cleanup();
1131
    thd->cleanup_after_query();
unknown's avatar
unknown committed
1132 1133 1134 1135
    break;
  }
#endif
  case COM_QUIT:
1136
    /* We don't calculate statistics for this command */
unknown's avatar
unknown committed
1137
    general_log_print(thd, command, NullS);
unknown's avatar
unknown committed
1138
    net->error=0;				// Don't give 'abort' message
Marc Alff's avatar
Marc Alff committed
1139
    thd->stmt_da->disable_status();              // Don't send anything back
unknown's avatar
unknown committed
1140 1141
    error=TRUE;					// End server
    break;
1142
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
1143 1144
  case COM_BINLOG_DUMP:
    {
unknown's avatar
unknown committed
1145 1146 1147 1148
      ulong pos;
      ushort flags;
      uint32 slave_server_id;

1149
      status_var_increment(thd->status_var.com_other);
1150
      thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
unknown committed
1151
      if (check_global_access(thd, REPL_SLAVE_ACL))
unknown's avatar
unknown committed
1152
	break;
unknown's avatar
unknown committed
1153

1154
      /* TODO: The following has to be changed to an 8 byte integer */
1155 1156
      pos = uint4korr(packet);
      flags = uint2korr(packet + 4);
unknown's avatar
unknown committed
1157
      thd->server_id=0; /* avoid suicide */
unknown's avatar
unknown committed
1158
      if ((slave_server_id= uint4korr(packet+6))) // mysqlbinlog.server_id==0
unknown's avatar
unknown committed
1159
	kill_zombie_dump_threads(slave_server_id);
1160
      thd->server_id = slave_server_id;
unknown's avatar
unknown committed
1161

unknown's avatar
unknown committed
1162
      general_log_print(thd, command, "Log: '%s'  Pos: %ld", packet+10,
unknown's avatar
unknown committed
1163
                      (long) pos);
1164
      mysql_binlog_send(thd, thd->strdup(packet + 10), (my_off_t) pos, flags);
unknown's avatar
unknown committed
1165
      unregister_slave(thd,1,1);
unknown's avatar
unknown committed
1166
      /*  fake COM_QUIT -- if we get here, the thread needs to terminate */
1167
      error = TRUE;
unknown's avatar
unknown committed
1168 1169
      break;
    }
1170
#endif
unknown's avatar
unknown committed
1171
  case COM_REFRESH:
unknown's avatar
unknown committed
1172 1173
  {
    bool not_used;
1174
    status_var_increment(thd->status_var.com_stat[SQLCOM_FLUSH]);
unknown's avatar
unknown committed
1175
    ulong options= (ulong) (uchar) packet[0];
Konstantin Osipov's avatar
Konstantin Osipov committed
1176
    if (trans_commit_implicit(thd))
Konstantin Osipov's avatar
Konstantin Osipov committed
1177
      break;
1178
    close_thread_tables(thd);
1179
    thd->mdl_context.release_transactional_locks();
unknown's avatar
unknown committed
1180
    if (check_global_access(thd,RELOAD_ACL))
unknown's avatar
unknown committed
1181
      break;
unknown's avatar
unknown committed
1182
    general_log_print(thd, command, NullS);
1183
#ifndef DBUG_OFF
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    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
1199 1200
      if (res)
        break;
1201
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
1202
    else
1203
#endif
Konstantin Osipov's avatar
Konstantin Osipov committed
1204 1205
    if (reload_acl_and_cache(thd, options, (TABLE_LIST*) 0, &not_used))
      break;
Konstantin Osipov's avatar
Konstantin Osipov committed
1206
    if (trans_commit_implicit(thd))
Konstantin Osipov's avatar
Konstantin Osipov committed
1207
      break;
1208
    close_thread_tables(thd);
1209
    thd->mdl_context.release_transactional_locks();
Konstantin Osipov's avatar
Konstantin Osipov committed
1210
    my_ok(thd);
unknown's avatar
unknown committed
1211 1212
    break;
  }
1213
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
1214
  case COM_SHUTDOWN:
1215
  {
1216
    status_var_increment(thd->status_var.com_other);
unknown's avatar
unknown committed
1217
    if (check_global_access(thd,SHUTDOWN_ACL))
unknown's avatar
unknown committed
1218
      break; /* purecov: inspected */
1219
    /*
1220
      If the client is < 4.1.3, it is going to send us no argument; then
1221
      packet_length is 0, packet[0] is the end 0 of the packet. Note that
1222 1223
      SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in
      packet[0].
1224
    */
1225 1226
    enum mysql_enum_shutdown_level level=
      (enum mysql_enum_shutdown_level) (uchar) packet[0];
1227 1228 1229 1230 1231 1232 1233
    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;
    }
1234
    DBUG_PRINT("quit",("Got shutdown command for level %u", level));
unknown's avatar
unknown committed
1235
    general_log_print(thd, command, NullS);
1236
    my_eof(thd);
unknown's avatar
unknown committed
1237 1238 1239 1240
    close_thread_tables(thd);			// Free before kill
    kill_mysql();
    error=TRUE;
    break;
1241
  }
1242
#endif
unknown's avatar
unknown committed
1243 1244
  case COM_STATISTICS:
  {
1245 1246 1247
    STATUS_VAR current_global_status_var;
    ulong uptime;
    uint length;
1248
    ulonglong queries_per_second1000;
1249 1250
    char buff[250];
    uint buff_len= sizeof(buff);
1251

1252
    general_log_print(thd, command, NullS);
1253
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]);
1254
    calc_sum_of_all_status(&current_global_status_var);
1255 1256 1257 1258 1259
    if (!(uptime= (ulong) (thd->start_time - server_start_time)))
      queries_per_second1000= 0;
    else
      queries_per_second1000= thd->query_id * LL(1000) / uptime;

1260 1261 1262
    length= my_snprintf((char*) buff, buff_len - 1,
                        "Uptime: %lu  Threads: %d  Questions: %lu  "
                        "Slow queries: %lu  Opens: %lu  Flush tables: %lu  "
1263
                        "Open tables: %u  Queries per second avg: %u.%u",
1264 1265 1266 1267 1268 1269
                        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(),
1270 1271
                        (uint) (queries_per_second1000 / 1000),
                        (uint) (queries_per_second1000 % 1000));
1272 1273
#ifdef EMBEDDED_LIBRARY
    /* Store the buffer in permanent memory */
1274
    my_ok(thd, 0, 0, buff);
1275
#endif
unknown's avatar
unknown committed
1276
#ifdef SAFEMALLOC
1277
    if (sf_malloc_cur_memory)				// Using SAFEMALLOC
1278 1279 1280 1281 1282 1283 1284
    {
      char *end= buff + length;
      length+= my_snprintf(end, buff_len - length - 1,
                           end,"  Memory in use: %ldK  Max memory used: %ldK",
                           (sf_malloc_cur_memory+1023L)/1024L,
                           (sf_malloc_max_memory+1023L)/1024L);
    }
unknown's avatar
unknown committed
1285 1286
#endif
#ifndef EMBEDDED_LIBRARY
Konstantin Osipov's avatar
Konstantin Osipov committed
1287 1288
    (void) my_net_write(net, (uchar*) buff, length);
    (void) net_flush(net);
Marc Alff's avatar
Marc Alff committed
1289
    thd->stmt_da->disable_status();
unknown's avatar
unknown committed
1290
#endif
unknown's avatar
unknown committed
1291 1292 1293
    break;
  }
  case COM_PING:
1294
    status_var_increment(thd->status_var.com_other);
1295
    my_ok(thd);				// Tell client we are alive
unknown's avatar
unknown committed
1296 1297
    break;
  case COM_PROCESS_INFO:
1298
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]);
1299 1300
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd, PROCESS_ACL))
unknown's avatar
unknown committed
1301
      break;
unknown's avatar
unknown committed
1302
    general_log_print(thd, command, NullS);
unknown's avatar
unknown committed
1303
    mysqld_list_processes(thd,
1304 1305
			  thd->security_ctx->master_access & PROCESS_ACL ? 
			  NullS : thd->security_ctx->priv_user, 0);
unknown's avatar
unknown committed
1306 1307 1308
    break;
  case COM_PROCESS_KILL:
  {
1309
    status_var_increment(thd->status_var.com_stat[SQLCOM_KILL]);
1310
    ulong id=(ulong) uint4korr(packet);
1311
    sql_kill(thd,id,false);
unknown's avatar
unknown committed
1312 1313
    break;
  }
1314 1315
  case COM_SET_OPTION:
  {
1316
    status_var_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION]);
unknown's avatar
unknown committed
1317 1318 1319 1320
    uint opt_command= uint2korr(packet);

    switch (opt_command) {
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON:
1321
      thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
1322
      my_eof(thd);
1323
      break;
unknown's avatar
unknown committed
1324
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF:
1325
      thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
1326
      my_eof(thd);
1327 1328
      break;
    default:
unknown's avatar
unknown committed
1329
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1330 1331 1332 1333
      break;
    }
    break;
  }
unknown's avatar
unknown committed
1334
  case COM_DEBUG:
1335
    status_var_increment(thd->status_var.com_other);
unknown's avatar
unknown committed
1336
    if (check_global_access(thd, SUPER_ACL))
unknown's avatar
unknown committed
1337
      break;					/* purecov: inspected */
1338
    mysql_print_status();
unknown's avatar
unknown committed
1339
    general_log_print(thd, command, NullS);
1340
    my_eof(thd);
unknown's avatar
unknown committed
1341 1342 1343 1344 1345
    break;
  case COM_SLEEP:
  case COM_CONNECT:				// Impossible here
  case COM_TIME:				// Impossible from client
  case COM_DELAYED_INSERT:
1346
  case COM_END:
unknown's avatar
unknown committed
1347
  default:
unknown's avatar
unknown committed
1348
    my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
unknown's avatar
unknown committed
1349 1350
    break;
  }
1351

unknown's avatar
unknown committed
1352
  /* report error issued during command execution */
1353 1354
  if (thd->killed_errno())
  {
Marc Alff's avatar
Marc Alff committed
1355
    if (! thd->stmt_da->is_set())
1356 1357 1358 1359 1360 1361 1362 1363
      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;
  }

1364
  /* If commit fails, we should be able to reset the OK status. */
Marc Alff's avatar
Marc Alff committed
1365
  thd->stmt_da->can_overwrite_status= TRUE;
Konstantin Osipov's avatar
Konstantin Osipov committed
1366
  thd->is_error() ? trans_rollback_stmt(thd) : trans_commit_stmt(thd);
Marc Alff's avatar
Marc Alff committed
1367
  thd->stmt_da->can_overwrite_status= FALSE;
1368 1369 1370

  thd->transaction.stmt.reset();

1371
  thd->protocol->end_statement();
1372
  query_cache_end_of_result(thd);
unknown's avatar
unknown committed
1373

1374 1375 1376 1377
  thd->proc_info= "closing tables";
  /* Free tables */
  close_thread_tables(thd);

1378
  log_slow_statement(thd);
1379

1380
  thd_proc_info(thd, "cleaning up");
1381
  thd->set_query(NULL, 0);
1382
  thd->command=COM_SLEEP;
Konstantin Osipov's avatar
Konstantin Osipov committed
1383
  pthread_mutex_lock(&LOCK_thread_count); // For process list
1384
  thread_running--;
Konstantin Osipov's avatar
Konstantin Osipov committed
1385
  pthread_mutex_unlock(&LOCK_thread_count);
1386
  thd_proc_info(thd, 0);
1387 1388
  thd->packet.shrink(thd->variables.net_buffer_length);	// Reclaim some memory
  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
1389

Konstantin Osipov's avatar
Konstantin Osipov committed
1390 1391 1392
#if defined(ENABLED_PROFILING)
  thd->profiling.finish_current_query();
#endif
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
  if (MYSQL_QUERY_DONE_ENABLED() || MYSQL_COMMAND_DONE_ENABLED())
  {
    int res;
    res= (int) thd->is_error();
    if (command == COM_QUERY)
    {
      MYSQL_QUERY_DONE(res);
    }
    MYSQL_COMMAND_DONE(res);
  }
1403 1404 1405 1406
  DBUG_RETURN(error);
}


1407
void log_slow_statement(THD *thd)
1408
{
unknown's avatar
unknown committed
1409
  DBUG_ENTER("log_slow_statement");
1410 1411 1412 1413 1414 1415 1416

  /*
    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))
unknown's avatar
unknown committed
1417
    DBUG_VOID_RETURN;                           // Don't set time for sub stmt
1418

1419 1420
  /*
    Do not log administrative statements unless the appropriate option is
1421
    set.
1422
  */
1423
  if (thd->enable_slow_log)
unknown's avatar
unknown committed
1424
  {
1425
    ulonglong end_utime_of_query= thd->current_utime();
1426
    thd_proc_info(thd, "logging slow query");
1427

1428 1429 1430 1431
    if (((end_utime_of_query - thd->utime_after_lock) >
         thd->variables.long_query_time ||
         ((thd->server_status &
           (SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED)) &&
1432 1433
          opt_log_queries_not_using_indexes &&
           !(sql_command_flags[thd->lex->sql_command] & CF_STATUS_COMMAND))) &&
1434
        thd->examined_row_count >= thd->variables.min_examined_row_limit)
1435
    {
1436
      thd_proc_info(thd, "logging slow query");
1437
      thd->status_var.long_query_count++;
1438 1439
      slow_log_print(thd, thd->query(), thd->query_length(), 
                     end_utime_of_query);
1440
    }
unknown's avatar
unknown committed
1441
  }
unknown's avatar
unknown committed
1442
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1443 1444
}

1445

unknown's avatar
unknown committed
1446
/**
unknown's avatar
unknown committed
1447 1448 1449 1450 1451 1452 1453
  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.

unknown's avatar
unknown committed
1454 1455 1456 1457 1458 1459 1460
  @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
unknown's avatar
unknown committed
1461 1462 1463 1464
    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).

unknown's avatar
unknown committed
1465
  @retval
unknown's avatar
unknown committed
1466
    0                 success
unknown's avatar
unknown committed
1467
  @retval
unknown's avatar
unknown committed
1468 1469 1470 1471
    1                 out of memory or SHOW commands are not allowed
                      in this version of the server.
*/

1472 1473 1474
int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident,
                         enum enum_schema_tables schema_table_idx)
{
1475
  SELECT_LEX *schema_select_lex= NULL;
1476
  DBUG_ENTER("prepare_schema_table");
1477

1478
  switch (schema_table_idx) {
1479 1480
  case SCH_SCHEMATA:
#if defined(DONT_ALLOW_SHOW_COMMANDS)
unknown's avatar
unknown committed
1481 1482
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0));   /* purecov: inspected */
1483 1484 1485 1486
    DBUG_RETURN(1);
#else
    break;
#endif
1487

1488 1489 1490
  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
1491
  case SCH_TRIGGERS:
unknown's avatar
unknown committed
1492
  case SCH_EVENTS:
1493
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
1494 1495
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1496 1497 1498
    DBUG_RETURN(1);
#else
    {
1499
      LEX_STRING db;
1500
      size_t dummy;
unknown's avatar
unknown committed
1501
      if (lex->select_lex.db == NULL &&
1502
          lex->copy_db_to(&lex->select_lex.db, &dummy))
1503
      {
unknown's avatar
unknown committed
1504
        DBUG_RETURN(1);
1505
      }
1506 1507 1508
      schema_select_lex= new SELECT_LEX();
      db.str= schema_select_lex->db= lex->select_lex.db;
      schema_select_lex->table_list.first= NULL;
1509
      db.length= strlen(db.str);
unknown's avatar
unknown committed
1510

1511
      if (check_db_name(&db))
1512
      {
1513
        my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
1514 1515 1516 1517 1518 1519 1520
        DBUG_RETURN(1);
      }
      break;
    }
#endif
  case SCH_COLUMNS:
  case SCH_STATISTICS:
unknown's avatar
unknown committed
1521
  {
1522
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
1523 1524
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1525 1526
    DBUG_RETURN(1);
#else
unknown's avatar
unknown committed
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
    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();
    if (!schema_select_lex->add_table_to_list(thd, table_ident, 0, 0, TL_READ))
      DBUG_RETURN(1);
    lex->query_tables_last= query_tables_last;
    break;
  }
1538
#endif
1539 1540 1541 1542 1543
  case SCH_PROFILES:
    /* 
      Mark this current profiling record to be discarded.  We don't
      wish to have SHOW commands show up in profiling.
    */
1544
#if defined(ENABLED_PROFILING)
1545
    thd->profiling.discard_current_query();
1546 1547
#endif
    break;
1548 1549 1550
  case SCH_OPEN_TABLES:
  case SCH_VARIABLES:
  case SCH_STATUS:
1551 1552
  case SCH_PROCEDURES:
  case SCH_CHARSETS:
unknown's avatar
unknown committed
1553
  case SCH_ENGINES:
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
  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);
  }
  TABLE_LIST *table_list= (TABLE_LIST*) select_lex->table_list.first;
unknown's avatar
unknown committed
1572
  table_list->schema_select_lex= schema_select_lex;
1573
  table_list->schema_table_reformed= 1;
1574 1575 1576 1577
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
1578 1579 1580
/**
  Read query from packet and store in thd->query.
  Used in COM_QUERY and COM_STMT_PREPARE.
1581 1582

    Sets the following THD variables:
unknown's avatar
unknown committed
1583 1584
  - query
  - query_length
1585

unknown's avatar
unknown committed
1586
  @retval
unknown's avatar
unknown committed
1587
    FALSE ok
unknown's avatar
unknown committed
1588
  @retval
unknown's avatar
unknown committed
1589
    TRUE  error;  In this case thd->fatal_error is set
1590 1591
*/

1592
bool alloc_query(THD *thd, const char *packet, uint packet_length)
1593
{
1594
  char *query;
1595
  /* Remove garbage at start and end of query */
1596
  while (packet_length > 0 && my_isspace(thd->charset(), packet[0]))
1597 1598 1599 1600
  {
    packet++;
    packet_length--;
  }
1601
  const char *pos= packet + packet_length;     // Point at end null
unknown's avatar
unknown committed
1602
  while (packet_length > 0 &&
unknown's avatar
unknown committed
1603
	 (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1])))
1604 1605 1606 1607 1608
  {
    pos--;
    packet_length--;
  }
  /* We must allocate some extra memory for query cache */
1609 1610 1611 1612 1613 1614 1615
  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);
1616 1617 1618 1619

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

unknown's avatar
unknown committed
1621
  return FALSE;
1622 1623
}

1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
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;
1637
  thd->variables.lc_time_names= &my_locale_en_US;
1638 1639 1640
  thd->one_shot_set= 0;
}

1641

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 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
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);

1688
    if (thd->slave_thread && lex->sphead)
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
      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);
}


unknown's avatar
unknown committed
1727 1728
/**
  Execute command saved in thd and lex->sql_command.
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739

    Before every operation that can request a write lock for a table
    wait if a global read lock exists. However do not wait if this
    thread has locked tables already. No new locks can be requested
    until the other locks are released. The thread that requests the
    global read lock waits for write locked tables to become unlocked.

    Note that wait_if_global_read_lock() sets a protection against a new
    global read lock when it succeeds. This needs to be released by
    start_waiting_global_read_lock() after the operation.

unknown's avatar
unknown committed
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
  @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()
    - JOIN is not supported yet. TODO
    - SUSPEND and FOR MIGRATE are not supported yet. TODO

  @retval
1752
    FALSE       OK
unknown's avatar
unknown committed
1753
  @retval
1754 1755
    TRUE        Error
*/
unknown's avatar
unknown committed
1756

1757
int
1758
mysql_execute_command(THD *thd)
unknown's avatar
unknown committed
1759
{
1760
  int res= FALSE;
unknown's avatar
unknown committed
1761
  int  up_result= 0;
1762
  LEX  *lex= thd->lex;
unknown's avatar
unknown committed
1763
  /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
unknown's avatar
unknown committed
1764
  SELECT_LEX *select_lex= &lex->select_lex;
unknown's avatar
VIEW  
unknown committed
1765
  /* first table of first SELECT_LEX */
unknown's avatar
unknown committed
1766
  TABLE_LIST *first_table= (TABLE_LIST*) select_lex->table_list.first;
unknown's avatar
VIEW  
unknown committed
1767 1768 1769
  /* list of all tables in query */
  TABLE_LIST *all_tables;
  /* most outer SELECT_LEX_UNIT of query */
1770
  SELECT_LEX_UNIT *unit= &lex->unit;
1771 1772 1773 1774
#ifdef HAVE_REPLICATION
  /* have table map for update for multi-update statement (BUG#37051) */
  bool have_table_map_for_update= FALSE;
#endif
1775
  /* Saved variable value */
unknown's avatar
unknown committed
1776
  DBUG_ENTER("mysql_execute_command");
unknown's avatar
unknown committed
1777 1778 1779
#ifdef WITH_PARTITION_STORAGE_ENGINE
  thd->work_part_info= 0;
#endif
unknown's avatar
unknown committed
1780

unknown's avatar
VIEW  
unknown committed
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
  /*
    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();
1797
  /* should be assigned after making first tables same */
unknown's avatar
VIEW  
unknown committed
1798
  all_tables= lex->query_tables;
1799 1800 1801 1802
  /* set context for commands which do not use setup_tables */
  select_lex->
    context.resolve_in_table_list_only((TABLE_LIST*)select_lex->
                                       table_list.first);
unknown's avatar
VIEW  
unknown committed
1803

1804 1805 1806 1807 1808 1809
  /*
    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
1810 1811 1812 1813 1814 1815 1816 1817
  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);
  }
1818

unknown's avatar
SCRUM  
unknown committed
1819
#ifdef HAVE_REPLICATION
1820
  if (unlikely(thd->slave_thread))
1821
  {
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
    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;
    }
1845 1846 1847 1848 1849 1850 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

    /*
      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;
    }
1887
    
unknown's avatar
unknown committed
1888
    /*
unknown's avatar
unknown committed
1889 1890
      Check if statment should be skipped because of slave filtering
      rules
1891 1892

      Exceptions are:
unknown's avatar
unknown committed
1893 1894
      - UPDATE MULTI: For this statement, we want to check the filtering
        rules later in the code
1895
      - SET: we always execute it (Not that many SET commands exists in
unknown's avatar
unknown committed
1896 1897
        the binary log anyway -- only 4.1 masters write SET statements,
	in 5.0 there are no SET statements in the binary log)
1898 1899
      - DROP TEMPORARY TABLE IF EXISTS: we always execute it (otherwise we
        have stale files on slave caused by exclusion of one tmp table).
unknown's avatar
merge  
unknown committed
1900
    */
unknown's avatar
unknown committed
1901 1902
    if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) &&
	!(lex->sql_command == SQLCOM_SET_OPTION) &&
1903
	!(lex->sql_command == SQLCOM_DROP_TABLE &&
1904
          lex->drop_temporary && lex->drop_if_exists) &&
unknown's avatar
Merge  
unknown committed
1905
        all_tables_not_ok(thd, all_tables))
unknown's avatar
unknown committed
1906 1907
    {
      /* we warn the slave SQL thread */
unknown's avatar
unknown committed
1908
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
      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);
      }
1926
      DBUG_RETURN(0);
unknown's avatar
unknown committed
1927
    }
1928
  }
1929
  else
1930
  {
1931
#endif /* HAVE_REPLICATION */
1932 1933 1934 1935
    /*
      When option readonly is set deny operations which change non-temporary
      tables. Except for the replication thread and the 'super' users.
    */
1936
    if (deny_updates_if_read_only_option(thd, all_tables))
1937 1938 1939 1940 1941 1942 1943
    {
      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
1944

1945
  status_var_increment(thd->status_var.com_stat[lex->sql_command]);
1946

unknown's avatar
unknown committed
1947
  DBUG_ASSERT(thd->transaction.stmt.modified_non_trans_table == FALSE);
Konstantin Osipov's avatar
Konstantin Osipov committed
1948 1949 1950 1951 1952 1953 1954

  /*
    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.
  */
1955 1956 1957 1958 1959 1960 1961 1962 1963
  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;
    /* Close tables and release metadata locks. */
    close_thread_tables(thd);
1964
    thd->mdl_context.release_transactional_locks();
1965
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
1966

Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
  /*
    Check if this command needs protection against the global read lock
    to avoid deadlock. See CF_PROTECT_AGAINST_GRL.
    start_waiting_global_read_lock() is called at the end of
    mysql_execute_command().
  */
  if (((sql_command_flags[lex->sql_command] & CF_PROTECT_AGAINST_GRL) != 0) &&
      !thd->locked_tables_mode)
    if (wait_if_global_read_lock(thd, FALSE, TRUE))
      goto error;

unknown's avatar
unknown committed
1978
  switch (lex->sql_command) {
1979

1980
  case SQLCOM_SHOW_EVENTS:
1981 1982 1983 1984
#ifndef HAVE_EVENT_SCHEDULER
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server");
    break;
#endif
1985 1986
  case SQLCOM_SHOW_STATUS_PROC:
  case SQLCOM_SHOW_STATUS_FUNC:
Konstantin Osipov's avatar
Konstantin Osipov committed
1987
    if ((res= check_table_access(thd, SELECT_ACL, all_tables, FALSE,
1988
                                  UINT_MAX, FALSE)))
Konstantin Osipov's avatar
Konstantin Osipov committed
1989 1990
      goto error;
    res= execute_sqlcom_select(thd, all_tables);
1991 1992 1993 1994 1995
    break;
  case SQLCOM_SHOW_STATUS:
  {
    system_status_var old_status_var= thd->status_var;
    thd->initial_status_var= &old_status_var;
1996 1997
    if (!(res= check_table_access(thd, SELECT_ACL, all_tables, FALSE,
                                  UINT_MAX, FALSE)))
1998
      res= execute_sqlcom_select(thd, all_tables);
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
    /* 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
    */
    pthread_mutex_lock(&LOCK_status);
    add_diff_to_status(&global_status_var, &thd->status_var,
                       &old_status_var);
    thd->status_var= old_status_var;
    pthread_mutex_unlock(&LOCK_status);
    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:
2024
  case SQLCOM_SHOW_STORAGE_ENGINES:
2025
  case SQLCOM_SHOW_PROFILE:
unknown's avatar
unknown committed
2026
  case SQLCOM_SELECT:
2027
  {
2028
    thd->status_var.last_query_cost= 0.0;
2029 2030 2031 2032 2033 2034 2035 2036

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

unknown's avatar
VIEW  
unknown committed
2037
    if (all_tables)
2038
      res= check_table_access(thd,
2039 2040
                              privileges_requested,
                              all_tables, FALSE, UINT_MAX, FALSE);
unknown's avatar
unknown committed
2041
    else
2042
      res= check_access(thd, privileges_requested, any_db, 0, 0, 0, 0);
2043

2044 2045 2046
    if (res)
      break;

Konstantin Osipov's avatar
Konstantin Osipov committed
2047
    if (!thd->locked_tables_mode && lex->protect_against_global_read_lock &&
2048
        wait_if_global_read_lock(thd, 0, 1))
2049 2050 2051
      break;

    res= execute_sqlcom_select(thd, all_tables);
unknown's avatar
unknown committed
2052
    break;
2053 2054
  }
case SQLCOM_PREPARE:
2055
  {
2056
    mysql_sql_stmt_prepare(thd);
unknown's avatar
unknown committed
2057 2058 2059 2060
    break;
  }
  case SQLCOM_EXECUTE:
  {
2061
    mysql_sql_stmt_execute(thd);
unknown's avatar
unknown committed
2062 2063 2064 2065
    break;
  }
  case SQLCOM_DEALLOCATE_PREPARE:
  {
2066
    mysql_sql_stmt_close(thd);
unknown's avatar
unknown committed
2067 2068
    break;
  }
unknown's avatar
unknown committed
2069
  case SQLCOM_DO:
2070 2071
    if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)
        || open_and_lock_tables(thd, all_tables))
unknown's avatar
unknown committed
2072
      goto error;
unknown's avatar
unknown committed
2073 2074

    res= mysql_do(thd, *lex->insert_list);
unknown's avatar
unknown committed
2075 2076
    break;

2077
  case SQLCOM_EMPTY_QUERY:
2078
    my_ok(thd);
2079 2080
    break;

unknown's avatar
unknown committed
2081 2082 2083 2084
  case SQLCOM_HELP:
    res= mysqld_help(thd,lex->help_arg);
    break;

2085
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2086
  case SQLCOM_PURGE:
2087
  {
unknown's avatar
unknown committed
2088
    if (check_global_access(thd, SUPER_ACL))
2089
      goto error;
unknown's avatar
unknown committed
2090
    /* PURGE MASTER LOGS TO 'file' */
2091 2092 2093
    res = purge_master_logs(thd, lex->to_log);
    break;
  }
2094 2095
  case SQLCOM_PURGE_BEFORE:
  {
2096 2097
    Item *it;

2098 2099
    if (check_global_access(thd, SUPER_ACL))
      goto error;
unknown's avatar
unknown committed
2100
    /* PURGE MASTER LOGS BEFORE 'data' */
2101
    it= (Item *)lex->value_list.head();
2102
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) ||
unknown's avatar
unknown committed
2103
        it->check_cols(1))
2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
    {
      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());
2115 2116
    break;
  }
2117
#endif
unknown's avatar
unknown committed
2118 2119
  case SQLCOM_SHOW_WARNS:
  {
2120 2121
    res= mysqld_show_warnings(thd, (ulong)
			      ((1L << (uint) MYSQL_ERROR::WARN_LEVEL_NOTE) |
2122 2123 2124
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_WARN) |
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR)
			       ));
unknown's avatar
unknown committed
2125 2126 2127 2128
    break;
  }
  case SQLCOM_SHOW_ERRORS:
  {
2129 2130
    res= mysqld_show_warnings(thd, (ulong)
			      (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR));
unknown's avatar
unknown committed
2131 2132
    break;
  }
unknown's avatar
unknown committed
2133 2134
  case SQLCOM_SHOW_PROFILES:
  {
2135
#if defined(ENABLED_PROFILING)
2136
    thd->profiling.discard_current_query();
unknown's avatar
unknown committed
2137
    res= thd->profiling.show_profiles();
2138 2139 2140
    if (res)
      goto error;
#else
2141
    my_error(ER_FEATURE_DISABLED, MYF(0), "SHOW PROFILES", "enable-profiling");
2142 2143
    goto error;
#endif
unknown's avatar
unknown committed
2144 2145
    break;
  }
unknown's avatar
unknown committed
2146 2147
  case SQLCOM_SHOW_NEW_MASTER:
  {
unknown's avatar
unknown committed
2148
    if (check_global_access(thd, REPL_SLAVE_ACL))
unknown's avatar
unknown committed
2149
      goto error;
2150
    /* This query don't work now. See comment in repl_failsafe.cc */
unknown's avatar
unknown committed
2151
#ifndef WORKING_NEW_MASTER
unknown's avatar
unknown committed
2152 2153
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "SHOW NEW MASTER");
    goto error;
unknown's avatar
unknown committed
2154
#else
unknown's avatar
unknown committed
2155 2156
    res = show_new_master(thd);
    break;
unknown's avatar
unknown committed
2157
#endif
unknown's avatar
unknown committed
2158
  }
2159

unknown's avatar
unknown committed
2160
#ifdef HAVE_REPLICATION
2161 2162
  case SQLCOM_SHOW_SLAVE_HOSTS:
  {
unknown's avatar
unknown committed
2163
    if (check_global_access(thd, REPL_SLAVE_ACL))
2164 2165 2166 2167
      goto error;
    res = show_slave_hosts(thd);
    break;
  }
2168
  case SQLCOM_SHOW_RELAYLOG_EVENTS: /* fall through */
unknown's avatar
unknown committed
2169 2170
  case SQLCOM_SHOW_BINLOG_EVENTS:
  {
unknown's avatar
unknown committed
2171
    if (check_global_access(thd, REPL_SLAVE_ACL))
unknown's avatar
unknown committed
2172
      goto error;
2173
    res = mysql_show_binlog_events(thd);
unknown's avatar
unknown committed
2174 2175
    break;
  }
2176 2177
#endif

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

unknown's avatar
unknown committed
2236
#endif /* HAVE_REPLICATION */
unknown's avatar
unknown committed
2237
  case SQLCOM_SHOW_ENGINE_STATUS:
unknown's avatar
unknown committed
2238
    {
2239
      if (check_global_access(thd, PROCESS_ACL))
unknown's avatar
unknown committed
2240 2241
        goto error;
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS);
unknown's avatar
unknown committed
2242 2243
      break;
    }
unknown's avatar
unknown committed
2244
  case SQLCOM_SHOW_ENGINE_MUTEX:
unknown's avatar
unknown committed
2245
    {
2246
      if (check_global_access(thd, PROCESS_ACL))
unknown's avatar
unknown committed
2247
        goto error;
unknown's avatar
unknown committed
2248
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX);
unknown's avatar
unknown committed
2249 2250
      break;
    }
unknown's avatar
unknown committed
2251
  case SQLCOM_CREATE_TABLE:
unknown's avatar
unknown committed
2252
  {
unknown's avatar
VIEW  
unknown committed
2253 2254
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    bool link_to_local;
2255 2256 2257
    TABLE_LIST *create_table= first_table;
    TABLE_LIST *select_tables= lex->create_last_non_select_table->next_global;

2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
    /*
      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;
    }
unknown's avatar
unknown committed
2279

unknown's avatar
VIEW  
unknown committed
2280
    if ((res= create_table_precheck(thd, select_tables, create_table)))
unknown's avatar
unknown committed
2281
      goto end_with_restore_list;
unknown's avatar
unknown committed
2282

2283 2284 2285
    /* Might have been updated in create_table_precheck */
    create_info.alias= create_table->alias;

2286
#ifdef HAVE_READLINK
2287
    /* Fix names if symlinked tables */
2288
    if (append_file_to_dir(thd, &create_info.data_file_name,
2289
			   create_table->table_name) ||
2290
	append_file_to_dir(thd, &create_info.index_file_name,
2291
			   create_table->table_name))
unknown's avatar
unknown committed
2292
      goto end_with_restore_list;
2293
#endif
2294
    /*
2295
      If we are using SET CHARSET without DEFAULT, add an implicit
2296 2297
      DEFAULT to not confuse old users. (This may change).
    */
2298
    if ((create_info.used_fields &
2299 2300 2301
	 (HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) ==
	HA_CREATE_USED_CHARSET)
    {
2302 2303 2304 2305
      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;
2306
    }
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
    /*
      The create-select command will open and read-lock the select table
      and then create, open and write-lock the new table. If a global
      read lock steps in, we get a deadlock. The write lock waits for
      the global read lock, while the global read lock waits for the
      select table to be closed. So we wait until the global readlock is
      gone before starting both steps. Note that
      wait_if_global_read_lock() sets a protection against a new global
      read lock when it succeeds. This needs to be released by
      start_waiting_global_read_lock(). We protect the normal CREATE
      TABLE in the same way. That way we avoid that a new table is
2318
      created during a global read lock.
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
2319
      Protection against grl is covered by the CF_PROTECT_AGAINST_GRL flag.
2320
    */
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
2321

2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
#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
2333

2334 2335 2336 2337
    /* Set strategies: reset default or 'prepared' values. */
    create_table->open_strategy= TABLE_LIST::OPEN_IF_EXISTS;
    create_table->lock_strategy= TABLE_LIST::EXCLUSIVE_DOWNGRADABLE_MDL;

2338 2339 2340 2341 2342
    /*
      Close any open handlers for the table
    */
    mysql_ha_rm_tables(thd, create_table);

2343
    if (select_lex->item_list.elements)		// With select
unknown's avatar
unknown committed
2344 2345
    {
      select_result *result;
2346

2347 2348 2349
      /*
        If:
        a) we inside an SP and there was NAME_CONST substitution,
Ramil Kalimullin's avatar
Ramil Kalimullin committed
2350
        b) binlogging is on (STMT mode),
2351 2352 2353 2354 2355 2356
        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
2357
          thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383
          !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.");
      }
      
2384
      select_lex->options|= SELECT_NO_UNLOCK;
2385
      unit->set_limit(select_lex);
2386

2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
      /*
        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;
      }

2400 2401
      if (!(res= open_and_lock_tables_derived(thd, lex->query_tables, TRUE,
                                              MYSQL_OPEN_TAKE_UPGRADABLE_MDL)))
2402
      {
2403 2404 2405 2406
        /*
          Is table which we are changing used somewhere in other parts
          of query
        */
2407
        if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
2408
        {
2409
          TABLE_LIST *duplicate;
2410
          if ((duplicate= unique_table(thd, create_table, select_tables, 0)))
2411 2412 2413
          {
            update_non_unique_table_error(create_table, "CREATE", duplicate);
            res= 1;
2414
            goto end_with_restore_list;
2415
          }
2416
        }
unknown's avatar
unknown committed
2417
        /* If we create merge table, we have to test tables in merge, too */
2418
        if (create_info.used_fields & HA_CREATE_USED_UNION)
unknown's avatar
unknown committed
2419 2420
        {
          TABLE_LIST *tab;
2421
          for (tab= (TABLE_LIST*) create_info.merge_list.first;
unknown's avatar
unknown committed
2422 2423 2424
               tab;
               tab= tab->next_local)
          {
2425
            TABLE_LIST *duplicate;
2426
            if ((duplicate= unique_table(thd, tab, select_tables, 0)))
unknown's avatar
unknown committed
2427
            {
2428
              update_non_unique_table_error(tab, "CREATE", duplicate);
unknown's avatar
unknown committed
2429
              res= 1;
2430
              goto end_with_restore_list;
unknown's avatar
unknown committed
2431 2432 2433
            }
          }
        }
2434

2435 2436 2437 2438 2439 2440 2441
        /*
          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);

unknown's avatar
unknown committed
2442
        /*
2443 2444
          select_create is currently not re-execution friendly and
          needs to be created for every execution of a PS/SP.
unknown's avatar
unknown committed
2445
        */
unknown's avatar
VIEW  
unknown committed
2446
        if ((result= new select_create(create_table,
2447 2448 2449 2450
                                       &create_info,
                                       &alter_info,
                                       select_lex->item_list,
                                       lex->duplicates,
2451
                                       lex->ignore,
2452
                                       select_tables)))
2453 2454 2455 2456 2457
        {
          /*
            CREATE from SELECT give its SELECT_LEX for SELECT,
            and item_list belong to SELECT
          */
2458
          res= handle_select(thd, lex, result, 0);
2459
          delete result;
2460
        }
2461 2462
        
        lex->link_first_table_back(create_table, link_to_local);
2463 2464
      }
    }
unknown's avatar
unknown committed
2465
    else
unknown's avatar
unknown committed
2466
    {
2467
      /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
2468
      if (create_info.options & HA_LEX_CREATE_TMP_TABLE)
2469
        thd->options|= OPTION_KEEP_LOG;
2470
      if (create_info.options & HA_LEX_CREATE_TABLE_LIKE)
2471 2472
      {
        /* CREATE TABLE ... LIKE ... */
unknown's avatar
unknown committed
2473
        res= mysql_create_like_table(thd, create_table, select_tables,
2474
                                     &create_info);
2475
      }
unknown's avatar
unknown committed
2476
      else
2477
      {
2478 2479 2480
        /* Regular CREATE TABLE */
        res= mysql_create_table(thd, create_table,
                                &create_info, &alter_info);
2481
      }
unknown's avatar
unknown committed
2482
      if (!res)
2483
        my_ok(thd);
unknown's avatar
unknown committed
2484
    }
2485

unknown's avatar
unknown committed
2486
end_with_restore_list:
unknown's avatar
unknown committed
2487
    break;
unknown's avatar
unknown committed
2488
  }
unknown's avatar
unknown committed
2489
  case SQLCOM_CREATE_INDEX:
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
    /* 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;

unknown's avatar
VIEW  
unknown committed
2508 2509
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_one_table_access(thd, INDEX_ACL, all_tables))
unknown's avatar
unknown committed
2510
      goto error; /* purecov: inspected */
2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
    /*
      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;
unknown's avatar
unknown committed
2522

2523 2524 2525 2526 2527
    res= mysql_alter_table(thd, first_table->db, first_table->table_name,
                           &create_info, first_table, &alter_info,
                           0, (ORDER*) 0, 0);
    break;
  }
unknown's avatar
unknown committed
2528
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
2529
  case SQLCOM_SLAVE_START:
2530
  {
2531
    pthread_mutex_lock(&LOCK_active_mi);
2532
    start_slave(thd,active_mi,1 /* net report*/);
2533
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
2534
    break;
2535
  }
unknown's avatar
unknown committed
2536
  case SQLCOM_SLAVE_STOP:
2537 2538 2539 2540 2541 2542
  /*
    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,
2543
      so it waits for the client thread because t is locked by it.
2544
    - then the client thread does SLAVE STOP.
2545 2546
      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.
2547 2548 2549
    To prevent that, refuse SLAVE STOP if the
    client thread has locked tables
  */
Konstantin Osipov's avatar
Konstantin Osipov committed
2550 2551
  if (thd->locked_tables_mode ||
      thd->active_transaction() || thd->global_read_lock)
2552
  {
2553 2554
    my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
               ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2555
    goto error;
2556
  }
2557
  {
2558
    pthread_mutex_lock(&LOCK_active_mi);
2559
    stop_slave(thd,active_mi,1/* net report*/);
2560
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
2561
    break;
2562
  }
unknown's avatar
unknown committed
2563
#endif /* HAVE_REPLICATION */
2564

unknown's avatar
unknown committed
2565
  case SQLCOM_ALTER_TABLE:
unknown's avatar
VIEW  
unknown committed
2566
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2567
    {
unknown's avatar
unknown committed
2568
      ulong priv=0;
unknown's avatar
unknown committed
2569
      ulong priv_needed= ALTER_ACL;
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
      /*
        Code in mysql_alter_table() may modify its HA_CREATE_INFO argument,
        so we have to use a copy of this structure to make execution
        prepared statement- safe. A shallow copy is enough as no memory
        referenced from this structure will be modified.
      */
      HA_CREATE_INFO create_info(lex->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;
2581 2582 2583 2584
      /*
        We also require DROP priv for ALTER TABLE ... DROP PARTITION, as well
        as for RENAME TO, as being done by SQLCOM_RENAME_TABLE
      */
2585
      if (alter_info.flags & (ALTER_DROP_PARTITION | ALTER_RENAME))
unknown's avatar
unknown committed
2586 2587
        priv_needed|= DROP_ACL;

unknown's avatar
unknown committed
2588 2589
      /* Must be set in the parser */
      DBUG_ASSERT(select_lex->db);
unknown's avatar
unknown committed
2590
      if (check_access(thd, priv_needed, first_table->db,
2591 2592 2593 2594
		       &first_table->grant.privilege, 0, 0,
                       test(first_table->schema_table)) ||
	  check_access(thd,INSERT_ACL | CREATE_ACL,select_lex->db,&priv,0,0,
                       is_schema_db(select_lex->db))||
unknown's avatar
VIEW  
unknown committed
2595
	  check_merge_table_access(thd, first_table->db,
2596
				   (TABLE_LIST *)
2597
				   create_info.merge_list.first))
2598
	goto error;				/* purecov: inspected */
2599
      if (check_grant(thd, priv_needed, all_tables, FALSE, UINT_MAX, FALSE))
2600 2601 2602 2603 2604 2605 2606 2607
        goto error;
      if (lex->name.str && !test_all_bits(priv,INSERT_ACL | CREATE_ACL))
      { // Rename of table
          TABLE_LIST tmp_table;
          bzero((char*) &tmp_table,sizeof(tmp_table));
          tmp_table.table_name= lex->name.str;
          tmp_table.db=select_lex->db;
          tmp_table.grant.privilege=priv;
2608 2609
          if (check_grant(thd, INSERT_ACL | CREATE_ACL, &tmp_table, FALSE,
              UINT_MAX, FALSE))
2610
            goto error;
unknown's avatar
unknown committed
2611
      }
2612

2613
      /* Don't yet allow changing of symlinks with ALTER TABLE */
2614
      if (create_info.data_file_name)
2615 2616 2617
        push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                            WARN_OPTION_IGNORED, ER(WARN_OPTION_IGNORED),
                            "DATA DIRECTORY");
2618
      if (create_info.index_file_name)
2619 2620 2621
        push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                            WARN_OPTION_IGNORED, ER(WARN_OPTION_IGNORED),
                            "INDEX DIRECTORY");
2622
      create_info.data_file_name= create_info.index_file_name= NULL;
2623 2624

      thd->enable_slow_log= opt_log_slow_admin_statements;
2625
      res= mysql_alter_table(thd, select_lex->db, lex->name.str,
2626 2627 2628
                             &create_info,
                             first_table,
                             &alter_info,
2629 2630
                             select_lex->order_list.elements,
                             (ORDER *) select_lex->order_list.first,
2631
                             lex->ignore);
unknown's avatar
unknown committed
2632 2633
      break;
    }
unknown's avatar
unknown committed
2634
  case SQLCOM_RENAME_TABLE:
unknown's avatar
unknown committed
2635
  {
unknown's avatar
VIEW  
unknown committed
2636
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2637
    TABLE_LIST *table;
unknown's avatar
VIEW  
unknown committed
2638
    for (table= first_table; table; table= table->next_local->next_local)
unknown's avatar
unknown committed
2639
    {
unknown's avatar
unknown committed
2640
      if (check_access(thd, ALTER_ACL | DROP_ACL, table->db,
2641
		       &table->grant.privilege,0,0, test(table->schema_table)) ||
unknown's avatar
VIEW  
unknown committed
2642
	  check_access(thd, INSERT_ACL | CREATE_ACL, table->next_local->db,
2643 2644
		       &table->next_local->grant.privilege, 0, 0,
                       test(table->next_local->schema_table)))
unknown's avatar
unknown committed
2645
	goto error;
2646 2647 2648 2649 2650 2651 2652
      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];
2653
      if (check_grant(thd, ALTER_ACL | DROP_ACL, &old_list, FALSE, 1, FALSE) ||
2654 2655
         (!test_all_bits(table->next_local->grant.privilege,
                         INSERT_ACL | CREATE_ACL) &&
2656 2657
          check_grant(thd, INSERT_ACL | CREATE_ACL, &new_list, FALSE, 1,
                      FALSE)))
2658
        goto error;
unknown's avatar
unknown committed
2659
    }
2660

Konstantin Osipov's avatar
Konstantin Osipov committed
2661
    if (mysql_rename_tables(thd, first_table, 0))
unknown's avatar
unknown committed
2662
      goto error;
unknown's avatar
unknown committed
2663
    break;
unknown's avatar
unknown committed
2664
  }
2665
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2666 2667
  case SQLCOM_SHOW_BINLOGS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
2668 2669
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2670
    goto error;
unknown's avatar
unknown committed
2671 2672
#else
    {
unknown's avatar
unknown committed
2673
      if (check_global_access(thd, SUPER_ACL))
unknown's avatar
unknown committed
2674 2675 2676 2677
	goto error;
      res = show_binlogs(thd);
      break;
    }
unknown's avatar
unknown committed
2678
#endif
2679
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
2680
  case SQLCOM_SHOW_CREATE:
unknown's avatar
VIEW  
unknown committed
2681
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2682
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
2683 2684
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2685
    goto error;
unknown's avatar
unknown committed
2686
#else
unknown's avatar
unknown committed
2687
    {
2688 2689 2690 2691 2692 2693 2694 2695 2696
     /*
        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.
      */

2697
      if (lex->only_view)
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707
      {
        if (check_table_access(thd, SELECT_ACL, first_table, FALSE, 1, FALSE))
        {
          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;
        }

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

2710 2711 2712 2713
      }
      else
      {
        ulong save_priv;
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728

        /*
          If it is an INFORMATION_SCHEMA table, SELECT_ACL privilege is the
          only privilege allowed. For any other privilege check_access()
          reports an error. That's how internal implementation protects
          INFORMATION_SCHEMA from updates.

          For ordinary tables any privilege from the SHOW_CREATE_TABLE_ACLS
          set is sufficient.
        */

        ulong check_privs= test(first_table->schema_table) ?
                           SELECT_ACL : SHOW_CREATE_TABLE_ACLS;

        if (check_access(thd, check_privs, first_table->db,
2729 2730 2731
                         &save_priv, FALSE, FALSE,
                         test(first_table->schema_table)))
          goto error;
2732

2733
        /*
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
          save_priv contains any privileges actually granted by check_access
          (i.e. save_priv contains global (user- and database-level)
          privileges).

          The fact that check_access() returned FALSE does not mean that
          access is granted. We need to check if save_priv contains any
          table-specific privilege. If not, we need to check table-level
          privileges.

          If there are no global privileges and no table-level privileges,
          access is denied.
2745
        */
2746 2747 2748

        if (!(save_priv & (SHOW_CREATE_TABLE_ACLS)) &&
            !has_any_table_level_privileges(thd, SHOW_CREATE_TABLE_ACLS, first_table))
2749 2750 2751 2752 2753 2754 2755 2756
        {
          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;
        }
      }

2757
      /* Access is granted. Execute the command.  */
unknown's avatar
unknown committed
2758
      res= mysqld_show_create(thd, first_table);
unknown's avatar
unknown committed
2759 2760
      break;
    }
unknown's avatar
unknown committed
2761
#endif
2762 2763
  case SQLCOM_CHECKSUM:
  {
unknown's avatar
VIEW  
unknown committed
2764
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2765 2766
    if (check_table_access(thd, SELECT_ACL, all_tables,
                           FALSE, UINT_MAX, FALSE))
2767
      goto error; /* purecov: inspected */
2768

unknown's avatar
VIEW  
unknown committed
2769
    res = mysql_checksum_table(thd, first_table, &lex->check_opt);
2770 2771
    break;
  }
unknown's avatar
unknown committed
2772
  case SQLCOM_REPAIR:
2773
  {
unknown's avatar
VIEW  
unknown committed
2774
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2775
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables,
2776
                           FALSE, UINT_MAX, FALSE))
2777
      goto error; /* purecov: inspected */
2778
    thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
VIEW  
unknown committed
2779
    res= mysql_repair_table(thd, first_table, &lex->check_opt);
2780 2781 2782
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2783 2784 2785
      /*
        Presumably, REPAIR and binlog writing doesn't require synchronization
      */
2786
      write_bin_log(thd, TRUE, thd->query(), thd->query_length());
2787
    }
2788
    select_lex->table_list.first= (uchar*) first_table;
2789
    lex->query_tables=all_tables;
2790 2791
    break;
  }
unknown's avatar
unknown committed
2792
  case SQLCOM_CHECK:
2793
  {
unknown's avatar
VIEW  
unknown committed
2794
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2795 2796
    if (check_table_access(thd, SELECT_ACL, all_tables,
                           TRUE, UINT_MAX, FALSE))
2797
      goto error; /* purecov: inspected */
2798
    thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
VIEW  
unknown committed
2799
    res = mysql_check_table(thd, first_table, &lex->check_opt);
2800
    select_lex->table_list.first= (uchar*) first_table;
2801
    lex->query_tables=all_tables;
2802 2803
    break;
  }
unknown's avatar
unknown committed
2804 2805
  case SQLCOM_ANALYZE:
  {
unknown's avatar
VIEW  
unknown committed
2806
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2807
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables,
2808
                           FALSE, UINT_MAX, FALSE))
unknown's avatar
unknown committed
2809
      goto error; /* purecov: inspected */
2810
    thd->enable_slow_log= opt_log_slow_admin_statements;
2811
    res= mysql_analyze_table(thd, first_table, &lex->check_opt);
2812 2813 2814
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2815 2816 2817
      /*
        Presumably, ANALYZE and binlog writing doesn't require synchronization
      */
2818
      write_bin_log(thd, TRUE, thd->query(), thd->query_length());
2819
    }
2820
    select_lex->table_list.first= (uchar*) first_table;
2821
    lex->query_tables=all_tables;
unknown's avatar
unknown committed
2822
    break;
unknown's avatar
unknown committed
2823
  }
2824

unknown's avatar
unknown committed
2825 2826
  case SQLCOM_OPTIMIZE:
  {
unknown's avatar
VIEW  
unknown committed
2827
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2828
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables,
2829
                           FALSE, UINT_MAX, FALSE))
unknown's avatar
unknown committed
2830
      goto error; /* purecov: inspected */
2831
    thd->enable_slow_log= opt_log_slow_admin_statements;
2832
    res= (specialflag & (SPECIAL_SAFE_MODE | SPECIAL_NO_NEW_FUNC)) ?
2833
      mysql_recreate_table(thd, first_table) :
unknown's avatar
VIEW  
unknown committed
2834
      mysql_optimize_table(thd, first_table, &lex->check_opt);
2835 2836 2837
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2838 2839 2840
      /*
        Presumably, OPTIMIZE and binlog writing doesn't require synchronization
      */
2841
      write_bin_log(thd, TRUE, thd->query(), thd->query_length());
2842
    }
2843
    select_lex->table_list.first= (uchar*) first_table;
2844
    lex->query_tables=all_tables;
unknown's avatar
unknown committed
2845 2846 2847
    break;
  }
  case SQLCOM_UPDATE:
2848 2849
  {
    ha_rows found= 0, updated= 0;
unknown's avatar
VIEW  
unknown committed
2850 2851
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (update_precheck(thd, all_tables))
unknown's avatar
unknown committed
2852
      break;
2853 2854
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
2855
    MYSQL_UPDATE_START(thd->query());
unknown's avatar
unknown committed
2856 2857 2858 2859 2860 2861 2862
    res= (up_result= mysql_update(thd, all_tables,
                                  select_lex->item_list,
                                  lex->value_list,
                                  select_lex->where,
                                  select_lex->order_list.elements,
                                  (ORDER *) select_lex->order_list.first,
                                  unit->select_limit_cnt,
2863 2864 2865
                                  lex->duplicates, lex->ignore,
                                  &found, &updated));
    MYSQL_UPDATE_DONE(res, found, updated);
2866
    /* mysql_update return 2 if we need to switch to multi-update */
unknown's avatar
unknown committed
2867
    if (up_result != 2)
2868
      break;
unknown's avatar
unknown committed
2869
    /* Fall through */
2870
  }
2871
  case SQLCOM_UPDATE_MULTI:
unknown's avatar
unknown committed
2872 2873 2874
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    /* if we switched from normal update, rights are checked */
unknown's avatar
unknown committed
2875
    if (up_result != 2)
2876
    {
unknown's avatar
unknown committed
2877 2878 2879 2880 2881
      if ((res= multi_update_precheck(thd, all_tables)))
        break;
    }
    else
      res= 0;
unknown's avatar
unknown committed
2882

2883
    res= mysql_multi_update_prepare(thd);
unknown's avatar
unknown committed
2884

2885
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
2886
    /* Check slave filtering rules */
2887
    if (unlikely(thd->slave_thread && !have_table_map_for_update))
unknown's avatar
unknown committed
2888
    {
2889 2890
      if (all_tables_not_ok(thd, all_tables))
      {
2891 2892 2893 2894 2895
        if (res!= 0)
        {
          res= 0;             /* don't care of prev failure  */
          thd->clear_error(); /* filters are of highest prior */
        }
2896 2897 2898 2899
        /* we warn the slave SQL thread */
        my_error(ER_SLAVE_IGNORED_TABLE, MYF(0));
        break;
      }
2900 2901
      if (res)
        break;
unknown's avatar
unknown committed
2902
    }
2903 2904
    else
    {
2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917
#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
2918 2919
    {
      multi_update *result_obj;
2920
      MYSQL_MULTI_UPDATE_START(thd->query());
2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
      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);
      }
    }
unknown's avatar
unknown committed
2943
    break;
unknown's avatar
unknown committed
2944
  }
unknown's avatar
unknown committed
2945
  case SQLCOM_REPLACE:
2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975
#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);
        mysql_bin_log.write(&ev);
        mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
      }
      DBUG_PRINT("debug", ("Just after generate_incident()"));
    }
#endif
2976 2977
  case SQLCOM_INSERT:
  {
unknown's avatar
VIEW  
unknown committed
2978
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2979
    if ((res= insert_precheck(thd, all_tables)))
unknown's avatar
unknown committed
2980
      break;
2981

2982
    MYSQL_INSERT_START(thd->query());
unknown's avatar
VIEW  
unknown committed
2983
    res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
unknown's avatar
unknown committed
2984
		      lex->update_list, lex->value_list,
2985
                      lex->duplicates, lex->ignore);
2986
    MYSQL_INSERT_DONE(res, (ulong) thd->row_count_func);
2987 2988 2989 2990 2991 2992
    /*
      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.
    */
unknown's avatar
VIEW  
unknown committed
2993
    if (first_table->view && !first_table->contain_auto_increment)
2994 2995
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
2996

unknown's avatar
unknown committed
2997
    break;
2998
  }
unknown's avatar
unknown committed
2999 3000 3001
  case SQLCOM_REPLACE_SELECT:
  case SQLCOM_INSERT_SELECT:
  {
unknown's avatar
unknown committed
3002
    select_result *sel_result;
unknown's avatar
VIEW  
unknown committed
3003
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
3004
    if ((res= insert_precheck(thd, all_tables)))
3005
      break;
unknown's avatar
unknown committed
3006

3007
    /* Fix lock for first table */
unknown's avatar
VIEW  
unknown committed
3008 3009
    if (first_table->lock_type == TL_WRITE_DELAYED)
      first_table->lock_type= TL_WRITE;
3010

3011 3012
    /* Don't unlock tables until command is written to binary log */
    select_lex->options|= SELECT_NO_UNLOCK;
unknown's avatar
unknown committed
3013

3014
    unit->set_limit(select_lex);
3015

unknown's avatar
VIEW  
unknown committed
3016
    if (!(res= open_and_lock_tables(thd, all_tables)))
3017
    {
3018
      MYSQL_INSERT_SELECT_START(thd->query());
3019
      /* Skip first table, which is the table we are inserting in */
unknown's avatar
unknown committed
3020
      TABLE_LIST *second_table= first_table->next_local;
3021
      select_lex->table_list.first= (uchar*) second_table;
3022 3023
      select_lex->context.table_list= 
        select_lex->context.first_name_resolution_table= second_table;
3024
      res= mysql_insert_select_prepare(thd);
unknown's avatar
unknown committed
3025 3026 3027 3028 3029 3030 3031
      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)))
3032
      {
unknown's avatar
unknown committed
3033
	res= handle_select(thd, lex, sel_result, OPTION_SETUP_TABLES_DONE);
3034 3035 3036 3037 3038 3039 3040 3041 3042
        /*
          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.
        */
        if (first_table->lock_type ==  TL_WRITE_CONCURRENT_INSERT &&
            thd->lock)
        {
3043 3044 3045
          /* INSERT ... SELECT should invalidate only the very first table */
          TABLE_LIST *save_table= first_table->next_local;
          first_table->next_local= 0;
3046
          query_cache_invalidate3(thd, first_table, 1);
3047
          first_table->next_local= save_table;
3048
        }
unknown's avatar
unknown committed
3049
        delete sel_result;
3050
      }
3051
      /* revert changes for SP */
3052
      MYSQL_INSERT_SELECT_DONE(res, (ulong) thd->row_count_func);
3053
      select_lex->table_list.first= (uchar*) first_table;
3054
    }
3055 3056 3057 3058 3059 3060
    /*
      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.
    */
unknown's avatar
VIEW  
unknown committed
3061
    if (first_table->view && !first_table->contain_auto_increment)
3062 3063
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
3064

unknown's avatar
unknown committed
3065 3066
    break;
  }
3067
  case SQLCOM_TRUNCATE:
unknown's avatar
VIEW  
unknown committed
3068
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
3069
    if (check_one_table_access(thd, DROP_ACL, all_tables))
unknown's avatar
unknown committed
3070
      goto error;
3071 3072 3073 3074
    /*
      Don't allow this within a transaction because we want to use
      re-generate table
    */
Konstantin Osipov's avatar
Konstantin Osipov committed
3075
    if (thd->active_transaction())
3076
    {
unknown's avatar
unknown committed
3077 3078
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3079 3080
      goto error;
    }
3081
    if (wait_if_global_read_lock(thd, 0, 1))
3082
      goto error;
unknown's avatar
unknown committed
3083
    res= mysql_truncate(thd, first_table, 0);
3084
    break;
unknown's avatar
unknown committed
3085
  case SQLCOM_DELETE:
unknown's avatar
unknown committed
3086
  {
unknown's avatar
VIEW  
unknown committed
3087 3088
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if ((res= delete_precheck(thd, all_tables)))
unknown's avatar
unknown committed
3089
      break;
3090 3091
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
3092

3093
    MYSQL_DELETE_START(thd->query());
unknown's avatar
VIEW  
unknown committed
3094
    res = mysql_delete(thd, all_tables, select_lex->where,
3095
                       &select_lex->order_list,
unknown's avatar
unknown committed
3096 3097
                       unit->select_limit_cnt, select_lex->options,
                       FALSE);
3098
    MYSQL_DELETE_DONE(res, (ulong) thd->row_count_func);
unknown's avatar
unknown committed
3099 3100
    break;
  }
3101
  case SQLCOM_DELETE_MULTI:
unknown's avatar
unknown committed
3102
  {
unknown's avatar
VIEW  
unknown committed
3103
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3104
    TABLE_LIST *aux_tables=
unknown's avatar
unknown committed
3105
      (TABLE_LIST *)thd->lex->auxiliary_table_list.first;
unknown's avatar
unknown committed
3106
    multi_delete *del_result;
unknown's avatar
unknown committed
3107

3108
    if ((res= multi_delete_precheck(thd, all_tables)))
3109
      break;
unknown's avatar
unknown committed
3110

unknown's avatar
unknown committed
3111
    /* condition will be TRUE on SP re-excuting */
3112 3113
    if (select_lex->item_list.elements != 0)
      select_lex->item_list.empty();
unknown's avatar
unknown committed
3114
    if (add_item_to_list(thd, new Item_null()))
unknown's avatar
unknown committed
3115
      goto error;
3116

3117
    thd_proc_info(thd, "init");
unknown's avatar
VIEW  
unknown committed
3118 3119 3120
    if ((res= open_and_lock_tables(thd, all_tables)))
      break;

3121
    MYSQL_MULTI_DELETE_START(thd->query());
unknown's avatar
VIEW  
unknown committed
3122
    if ((res= mysql_multi_delete_prepare(thd)))
3123 3124
    {
      MYSQL_MULTI_DELETE_DONE(1, 0);
unknown's avatar
unknown committed
3125
      goto error;
3126
    }
3127

unknown's avatar
unknown committed
3128 3129
    if (!thd->is_fatal_error &&
        (del_result= new multi_delete(aux_tables, lex->table_count)))
unknown's avatar
unknown committed
3130
    {
3131 3132 3133
      res= mysql_select(thd, &select_lex->ref_pointer_array,
			select_lex->get_table_list(),
			select_lex->with_wild,
3134
			select_lex->item_list,
unknown's avatar
unknown committed
3135
			select_lex->where,
3136
			0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL,
unknown's avatar
unknown committed
3137 3138
			(ORDER *)NULL,
			select_lex->options | thd->options |
3139 3140
			SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
                        OPTION_SETUP_TABLES_DONE,
unknown's avatar
unknown committed
3141
			del_result, unit, select_lex);
3142
      res|= thd->is_error();
3143
      MYSQL_MULTI_DELETE_DONE(res, del_result->num_deleted());
3144
      if (res)
3145
        del_result->abort();
unknown's avatar
unknown committed
3146
      delete del_result;
unknown's avatar
unknown committed
3147 3148
    }
    else
3149
    {
3150
      res= TRUE;                                // Error
3151 3152
      MYSQL_MULTI_DELETE_DONE(1, 0);
    }
unknown's avatar
unknown committed
3153 3154
    break;
  }
unknown's avatar
unknown committed
3155
  case SQLCOM_DROP_TABLE:
unknown's avatar
unknown committed
3156
  {
unknown's avatar
VIEW  
unknown committed
3157
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3158 3159
    if (!lex->drop_temporary)
    {
3160
      if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE))
3161 3162
	goto error;				/* purecov: inspected */
    }
unknown's avatar
unknown committed
3163
    else
unknown's avatar
unknown committed
3164 3165 3166 3167 3168 3169
    {
      /*
	If this is a slave thread, we may sometimes execute some 
	DROP / * 40005 TEMPORARY * / TABLE
	that come from parts of binlogs (likely if we use RESET SLAVE or CHANGE
	MASTER TO), while the temporary table has already been dropped.
unknown's avatar
unknown committed
3170 3171
	To not generate such irrelevant "table does not exist errors",
	we silently add IF EXISTS if TEMPORARY was used.
unknown's avatar
unknown committed
3172 3173
      */
      if (thd->slave_thread)
3174
        lex->drop_if_exists= 1;
3175

unknown's avatar
unknown committed
3176
      /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
3177
      thd->options|= OPTION_KEEP_LOG;
unknown's avatar
unknown committed
3178
    }
3179
    /* DDL and binlog write order protected by LOCK_open */
unknown's avatar
VIEW  
unknown committed
3180 3181
    res= mysql_rm_table(thd, first_table, lex->drop_if_exists,
			lex->drop_temporary);
unknown's avatar
unknown committed
3182 3183
  }
  break;
unknown's avatar
unknown committed
3184
  case SQLCOM_SHOW_PROCESSLIST:
3185 3186
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd,PROCESS_ACL))
unknown's avatar
unknown committed
3187
      break;
unknown's avatar
unknown committed
3188
    mysqld_list_processes(thd,
3189 3190 3191 3192
			  (thd->security_ctx->master_access & PROCESS_ACL ?
                           NullS :
                           thd->security_ctx->priv_user),
                          lex->verbose);
unknown's avatar
unknown committed
3193
    break;
unknown's avatar
unknown committed
3194 3195 3196
  case SQLCOM_SHOW_AUTHORS:
    res= mysqld_show_authors(thd);
    break;
3197 3198 3199
  case SQLCOM_SHOW_CONTRIBUTORS:
    res= mysqld_show_contributors(thd);
    break;
unknown's avatar
unknown committed
3200 3201 3202
  case SQLCOM_SHOW_PRIVILEGES:
    res= mysqld_show_privileges(thd);
    break;
unknown's avatar
unknown committed
3203
  case SQLCOM_SHOW_ENGINE_LOGS:
unknown's avatar
unknown committed
3204
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
3205 3206
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
3207
    goto error;
unknown's avatar
unknown committed
3208 3209
#else
    {
3210
      if (check_access(thd, FILE_ACL, any_db,0,0,0,0))
unknown's avatar
unknown committed
3211
	goto error;
unknown's avatar
unknown committed
3212
      res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS);
unknown's avatar
unknown committed
3213 3214
      break;
    }
unknown's avatar
unknown committed
3215 3216
#endif
  case SQLCOM_CHANGE_DB:
3217 3218 3219 3220
  {
    LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) };

    if (!mysql_change_db(thd, &db_str, FALSE))
3221
      my_ok(thd);
3222

unknown's avatar
unknown committed
3223
    break;
3224
  }
3225

unknown's avatar
unknown committed
3226 3227
  case SQLCOM_LOAD:
  {
unknown's avatar
VIEW  
unknown committed
3228
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
3229
    uint privilege= (lex->duplicates == DUP_REPLACE ?
unknown's avatar
unknown committed
3230 3231
		     INSERT_ACL | DELETE_ACL : INSERT_ACL) |
                    (lex->local_file ? 0 : FILE_ACL);
3232

unknown's avatar
unknown committed
3233
    if (lex->local_file)
unknown's avatar
unknown committed
3234
    {
3235
      if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) ||
3236
          !opt_local_infile)
3237
      {
unknown's avatar
unknown committed
3238
	my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0));
3239 3240
	goto error;
      }
unknown's avatar
unknown committed
3241
    }
unknown's avatar
unknown committed
3242 3243 3244 3245

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

unknown's avatar
VIEW  
unknown committed
3246
    res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
unknown's avatar
unknown committed
3247
                    lex->update_list, lex->value_list, lex->duplicates,
3248
                    lex->ignore, (bool) lex->local_file);
unknown's avatar
unknown committed
3249 3250
    break;
  }
3251

unknown's avatar
unknown committed
3252
  case SQLCOM_SET_OPTION:
3253 3254
  {
    List<set_var_base> *lex_var_list= &lex->var_list;
3255

3256 3257
    if ((check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)
         || open_and_lock_tables(thd, all_tables)))
unknown's avatar
unknown committed
3258
      goto error;
3259 3260
    if (lex->one_shot_set && not_all_support_one_shot(lex_var_list))
    {
unknown's avatar
unknown committed
3261 3262
      my_error(ER_RESERVED_SYNTAX, MYF(0), "SET ONE_SHOT");
      goto error;
3263 3264 3265 3266 3267 3268 3269 3270
    }
    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;
3271
      my_ok(thd);
3272
    }
3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
    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;
    }

unknown's avatar
unknown committed
3285
    break;
3286
  }
unknown's avatar
unknown committed
3287

unknown's avatar
unknown committed
3288
  case SQLCOM_UNLOCK_TABLES:
3289 3290 3291 3292 3293 3294
    /*
      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.
    */
Konstantin Osipov's avatar
Konstantin Osipov committed
3295
    thd->locked_tables_list.unlock_locked_tables(thd);
unknown's avatar
unknown committed
3296 3297
    if (thd->options & OPTION_TABLE_LOCK)
    {
Konstantin Osipov's avatar
Konstantin Osipov committed
3298
      trans_commit_implicit(thd);
3299
      thd->mdl_context.release_transactional_locks();
3300
      thd->options&= ~(OPTION_TABLE_LOCK);
unknown's avatar
unknown committed
3301 3302
    }
    if (thd->global_read_lock)
3303
      unlock_global_read_lock(thd);
3304
    my_ok(thd);
unknown's avatar
unknown committed
3305 3306
    break;
  case SQLCOM_LOCK_TABLES:
Konstantin Osipov's avatar
Konstantin Osipov committed
3307
    thd->locked_tables_list.unlock_locked_tables(thd);
3308 3309 3310 3311 3312 3313 3314 3315
    /*
      As of 5.5, entering LOCK TABLES mode implicitly closes all
      open HANDLERs. Both HANDLER code and LOCK TABLES mode use
      the sentinel mechanism in MDL subsystem and thus could not be
      used at the same time. All HANDLER operations are prohibited
      under LOCK TABLES anyway.
    */
    mysql_ha_cleanup(thd);
3316
    /* we must end the trasaction first, regardless of anything */
Konstantin Osipov's avatar
Konstantin Osipov committed
3317
    if (trans_commit_implicit(thd))
unknown's avatar
unknown committed
3318
      goto error;
3319
    /* release transactional metadata locks. */
3320
    thd->mdl_context.release_transactional_locks();
3321
    if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, all_tables,
3322
                           FALSE, UINT_MAX, FALSE))
3323
      goto error;
3324
    if (lex->protect_against_global_read_lock &&
3325
        wait_if_global_read_lock(thd, 0, 1))
3326
      goto error;
Konstantin Osipov's avatar
Konstantin Osipov committed
3327

Konstantin Osipov's avatar
Konstantin Osipov committed
3328
    init_mdl_requests(all_tables);
Konstantin Osipov's avatar
Konstantin Osipov committed
3329

unknown's avatar
unknown committed
3330
    thd->options|= OPTION_TABLE_LOCK;
Konstantin Osipov's avatar
Konstantin Osipov committed
3331
    thd->in_lock_tables=1;
unknown's avatar
VIEW  
unknown committed
3332

Konstantin Osipov's avatar
Konstantin Osipov committed
3333 3334 3335 3336 3337 3338 3339 3340
    {
      Lock_tables_prelocking_strategy lock_tables_prelocking_strategy;

      res= (open_and_lock_tables_derived(thd, all_tables, FALSE,
                                         MYSQL_OPEN_TAKE_UPGRADABLE_MDL,
                                         &lock_tables_prelocking_strategy) ||
            thd->locked_tables_list.init_locked_tables(thd));
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
3341 3342 3343 3344

    thd->in_lock_tables= 0;

    if (res)
3345
    {
Konstantin Osipov's avatar
Konstantin Osipov committed
3346
      /*
3347 3348 3349 3350
        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
3351 3352
      trans_rollback_stmt(thd);
      trans_commit_implicit(thd);
3353 3354 3355 3356 3357 3358
      /*
        Close tables and release metadata locks otherwise a later call to
        close_thread_tables might not release the locks if autocommit is off.
      */
      close_thread_tables(thd);
      DBUG_ASSERT(!thd->locked_tables_mode);
3359
      thd->mdl_context.release_transactional_locks();
3360
      thd->options&= ~(OPTION_TABLE_LOCK);
3361
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
3362 3363 3364 3365 3366 3367 3368 3369
    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);
    }
unknown's avatar
unknown committed
3370 3371
    break;
  case SQLCOM_CREATE_DB:
3372
  {
3373 3374 3375 3376 3377 3378
    /*
      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);
unknown's avatar
unknown committed
3379
    char *alias;
3380 3381
    if (!(alias=thd->strmake(lex->name.str, lex->name.length)) ||
        check_db_name(&lex->name))
unknown's avatar
unknown committed
3382
    {
3383
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
unknown's avatar
unknown committed
3384 3385
      break;
    }
3386 3387 3388
    /*
      If in a slave thread :
      CREATE DATABASE DB was certainly not preceded by USE DB.
3389
      For that reason, db_ok() in sql/slave.cc did not check the
3390 3391 3392
      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.
    */
3393
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
3394
    if (thd->slave_thread && 
3395 3396
	(!rpl_filter->db_ok(lex->name.str) ||
	 !rpl_filter->db_ok_with_wild_table(lex->name.str)))
unknown's avatar
unknown committed
3397
    {
unknown's avatar
unknown committed
3398
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3399
      break;
unknown's avatar
unknown committed
3400
    }
3401
#endif
3402 3403
    if (check_access(thd,CREATE_ACL,lex->name.str, 0, 1, 0,
                     is_schema_db(lex->name.str)))
3404
      break;
3405 3406 3407 3408 3409 3410
    if (thd->locked_tables_mode)
    {
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
      goto error;
    }
3411
    res= mysql_create_db(thd,(lower_case_table_names == 2 ? alias :
3412
                              lex->name.str), &create_info, 0);
3413 3414
    break;
  }
unknown's avatar
unknown committed
3415
  case SQLCOM_DROP_DB:
3416
  {
3417
    if (check_db_name(&lex->name))
unknown's avatar
unknown committed
3418
    {
3419
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
unknown's avatar
unknown committed
3420 3421
      break;
    }
3422 3423 3424 3425 3426 3427 3428
    /*
      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.
    */
3429
#ifdef HAVE_REPLICATION
3430
    if (thd->slave_thread && 
3431 3432
	(!rpl_filter->db_ok(lex->name.str) ||
	 !rpl_filter->db_ok_with_wild_table(lex->name.str)))
unknown's avatar
unknown committed
3433
    {
unknown's avatar
unknown committed
3434
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3435
      break;
unknown's avatar
unknown committed
3436
    }
3437
#endif
3438 3439
    if (check_access(thd,DROP_ACL,lex->name.str,0,1,0,
                     is_schema_db(lex->name.str)))
3440
      break;
3441
    if (thd->locked_tables_mode)
3442
    {
unknown's avatar
unknown committed
3443 3444
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3445 3446
      goto error;
    }
3447
    res= mysql_rm_db(thd, lex->name.str, lex->drop_if_exists, 0);
3448 3449
    break;
  }
3450
  case SQLCOM_ALTER_DB_UPGRADE:
unknown's avatar
unknown committed
3451
  {
3452
    LEX_STRING *db= & lex->name;
unknown's avatar
unknown committed
3453 3454
#ifdef HAVE_REPLICATION
    if (thd->slave_thread && 
3455 3456
       (!rpl_filter->db_ok(db->str) ||
        !rpl_filter->db_ok_with_wild_table(db->str)))
unknown's avatar
unknown committed
3457 3458 3459 3460 3461 3462
    {
      res= 1;
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
      break;
    }
#endif
3463
    if (check_db_name(db))
3464
    {
3465
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
3466 3467
      break;
    }
3468 3469 3470
    if (check_access(thd, ALTER_ACL, db->str, 0, 1, 0, is_schema_db(db->str)) ||
        check_access(thd, DROP_ACL, db->str, 0, 1, 0, is_schema_db(db->str)) ||
        check_access(thd, CREATE_ACL, db->str, 0, 1, 0, is_schema_db(db->str)))
unknown's avatar
unknown committed
3471 3472 3473 3474
    {
      res= 1;
      break;
    }
3475
    if (thd->locked_tables_mode)
unknown's avatar
unknown committed
3476 3477 3478 3479 3480 3481
    {
      res= 1;
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
      goto error;
    }
3482 3483

    res= mysql_upgrade_db(thd, db);
unknown's avatar
unknown committed
3484
    if (!res)
3485
      my_ok(thd);
unknown's avatar
unknown committed
3486 3487
    break;
  }
3488 3489
  case SQLCOM_ALTER_DB:
  {
3490
    LEX_STRING *db= &lex->name;
3491
    HA_CREATE_INFO create_info(lex->create_info);
3492
    if (check_db_name(db))
3493
    {
3494
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
3495 3496
      break;
    }
unknown's avatar
unknown committed
3497 3498 3499
    /*
      If in a slave thread :
      ALTER DATABASE DB may not be preceded by USE DB.
3500
      For that reason, maybe db_ok() in sql/slave.cc did not check the
unknown's avatar
unknown committed
3501 3502 3503 3504
      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
3505
    if (thd->slave_thread &&
3506 3507
	(!rpl_filter->db_ok(db->str) ||
	 !rpl_filter->db_ok_with_wild_table(db->str)))
unknown's avatar
unknown committed
3508
    {
unknown's avatar
unknown committed
3509
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
unknown's avatar
unknown committed
3510 3511 3512
      break;
    }
#endif
3513
    if (check_access(thd, ALTER_ACL, db->str, 0, 1, 0, is_schema_db(db->str)))
3514
      break;
3515
    if (thd->locked_tables_mode)
3516
    {
unknown's avatar
unknown committed
3517 3518
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3519 3520
      goto error;
    }
3521
    res= mysql_alter_db(thd, db->str, &create_info);
3522 3523
    break;
  }
unknown's avatar
unknown committed
3524 3525
  case SQLCOM_SHOW_CREATE_DB:
  {
unknown's avatar
unknown committed
3526 3527
    DBUG_EXECUTE_IF("4x_server_emul",
                    my_error(ER_UNKNOWN_ERROR, MYF(0)); goto error;);
3528
    if (check_db_name(&lex->name))
unknown's avatar
unknown committed
3529
    {
3530
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
unknown's avatar
unknown committed
3531 3532
      break;
    }
3533
    res= mysqld_show_create_db(thd, lex->name.str, &lex->create_info);
unknown's avatar
unknown committed
3534 3535
    break;
  }
unknown's avatar
unknown committed
3536 3537
  case SQLCOM_CREATE_EVENT:
  case SQLCOM_ALTER_EVENT:
3538
  #ifdef HAVE_EVENT_SCHEDULER
3539
  do
unknown's avatar
unknown committed
3540
  {
unknown's avatar
unknown committed
3541
    DBUG_ASSERT(lex->event_parse_data);
unknown's avatar
unknown committed
3542 3543 3544 3545 3546 3547
    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;
    }
3548 3549 3550 3551 3552

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

unknown's avatar
unknown committed
3553 3554
    switch (lex->sql_command) {
    case SQLCOM_CREATE_EVENT:
3555 3556 3557 3558
    {
      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);
unknown's avatar
unknown committed
3559
      break;
3560
    }
unknown's avatar
unknown committed
3561
    case SQLCOM_ALTER_EVENT:
3562 3563 3564
      res= Events::update_event(thd, lex->event_parse_data,
                                lex->spname ? &lex->spname->m_db : NULL,
                                lex->spname ? &lex->spname->m_name : NULL);
unknown's avatar
unknown committed
3565
      break;
3566 3567
    default:
      DBUG_ASSERT(0);
unknown's avatar
unknown committed
3568
    }
3569
    DBUG_PRINT("info",("DDL error code=%d", res));
unknown's avatar
unknown committed
3570
    if (!res)
3571
      my_ok(thd);
unknown's avatar
unknown committed
3572

3573 3574 3575 3576 3577 3578
  } while (0);
  /* Don't do it, if we are inside a SP */
  if (!thd->spcont)
  {
    delete lex->sphead;
    lex->sphead= NULL;
unknown's avatar
unknown committed
3579
  }
3580 3581
  /* lex->unit.cleanup() is called outside, no need to call it here */
  break;
unknown's avatar
unknown committed
3582
  case SQLCOM_SHOW_CREATE_EVENT:
3583 3584 3585 3586 3587 3588 3589
    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)))
3590
      my_ok(thd);
3591
    break;
3592 3593 3594 3595
#else
    my_error(ER_NOT_SUPPORTED_YET,MYF(0),"embedded server");
    break;
#endif
unknown's avatar
unknown committed
3596
  case SQLCOM_CREATE_FUNCTION:                  // UDF function
unknown's avatar
unknown committed
3597
  {
3598
    if (check_access(thd,INSERT_ACL,"mysql",0,1,0,0))
unknown's avatar
unknown committed
3599
      break;
unknown's avatar
unknown committed
3600
#ifdef HAVE_DLOPEN
3601
    if (!(res = mysql_create_function(thd, &lex->udf)))
3602
      my_ok(thd);
unknown's avatar
unknown committed
3603
#else
unknown's avatar
unknown committed
3604
    my_error(ER_CANT_OPEN_LIBRARY, MYF(0), lex->udf.dl, 0, "feature disabled");
unknown's avatar
unknown committed
3605
    res= TRUE;
unknown's avatar
unknown committed
3606 3607
#endif
    break;
unknown's avatar
unknown committed
3608
  }
unknown's avatar
unknown committed
3609
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3610 3611
  case SQLCOM_CREATE_USER:
  {
3612
    if (check_access(thd, INSERT_ACL, "mysql", 0, 1, 1, 0) &&
3613
        check_global_access(thd,CREATE_USER_ACL))
3614
      break;
3615
    /* Conditionally writes to binlog */
3616
    if (!(res= mysql_create_user(thd, lex->users_list)))
3617
      my_ok(thd);
3618 3619
    break;
  }
3620 3621
  case SQLCOM_DROP_USER:
  {
3622
    if (check_access(thd, DELETE_ACL, "mysql", 0, 1, 1, 0) &&
3623
        check_global_access(thd,CREATE_USER_ACL))
3624
      break;
3625
    /* Conditionally writes to binlog */
3626
    if (!(res= mysql_drop_user(thd, lex->users_list)))
3627
      my_ok(thd);
3628 3629 3630 3631
    break;
  }
  case SQLCOM_RENAME_USER:
  {
3632
    if (check_access(thd, UPDATE_ACL, "mysql", 0, 1, 1, 0) &&
3633
        check_global_access(thd,CREATE_USER_ACL))
3634
      break;
3635
    /* Conditionally writes to binlog */
3636
    if (!(res= mysql_rename_user(thd, lex->users_list)))
3637
      my_ok(thd);
3638 3639 3640 3641
    break;
  }
  case SQLCOM_REVOKE_ALL:
  {
3642
    if (check_access(thd, UPDATE_ACL, "mysql", 0, 1, 1, 0) &&
3643
        check_global_access(thd,CREATE_USER_ACL))
3644
      break;
3645
    /* Conditionally writes to binlog */
3646
    if (!(res = mysql_revoke_all(thd, lex->users_list)))
3647
      my_ok(thd);
3648 3649
    break;
  }
3650 3651 3652 3653
  case SQLCOM_REVOKE:
  case SQLCOM_GRANT:
  {
    if (check_access(thd, lex->grant | lex->grant_tot_col | GRANT_ACL,
unknown's avatar
unknown committed
3654
		     first_table ?  first_table->db : select_lex->db,
unknown's avatar
VIEW  
unknown committed
3655
		     first_table ? &first_table->grant.privilege : 0,
3656 3657 3658
		     first_table ? 0 : 1, 0,
                     first_table ? (bool) first_table->schema_table :
                     select_lex->db ? is_schema_db(select_lex->db) : 0))
3659 3660
      goto error;

3661
    if (thd->security_ctx->user)              // If not replication
unknown's avatar
unknown committed
3662
    {
3663
      LEX_USER *user, *tmp_user;
3664

unknown's avatar
unknown committed
3665
      List_iterator <LEX_USER> user_list(lex->users_list);
3666
      while ((tmp_user= user_list++))
unknown's avatar
unknown committed
3667
      {
3668 3669
        if (!(user= get_current_user(thd, tmp_user)))
          goto error;
3670 3671 3672 3673 3674 3675 3676 3677
        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);
3678
        if (strcmp(thd->security_ctx->user, user->user.str) ||
3679
            my_strcasecmp(system_charset_info,
3680
                          user->host.str, thd->security_ctx->host_or_ip))
3681 3682
        {
          // TODO: use check_change_password()
3683 3684
          if (is_acl_user(user->host.str, user->user.str) &&
              user->password.str &&
3685
              check_access(thd, UPDATE_ACL,"mysql",0,1,1,0))
3686 3687 3688 3689 3690 3691
          {
            my_message(ER_PASSWORD_NOT_ALLOWED,
                       ER(ER_PASSWORD_NOT_ALLOWED), MYF(0));
            goto error;
          }
        }
unknown's avatar
SCRUM  
unknown committed
3692 3693
      }
    }
unknown's avatar
VIEW  
unknown committed
3694
    if (first_table)
3695
    {
3696 3697
      if (lex->type == TYPE_ENUM_PROCEDURE ||
          lex->type == TYPE_ENUM_FUNCTION)
3698 3699 3700 3701
      {
        uint grants= lex->all_privileges 
		   ? (PROC_ACLS & ~GRANT_ACL) | (lex->grant & GRANT_ACL)
		   : lex->grant;
3702
        if (check_grant_routine(thd, grants | GRANT_ACL, all_tables,
3703
                                lex->type == TYPE_ENUM_PROCEDURE, 0))
3704
	  goto error;
3705
        /* Conditionally writes to binlog */
3706 3707 3708
        res= mysql_routine_grant(thd, all_tables,
                                 lex->type == TYPE_ENUM_PROCEDURE, 
                                 lex->users_list, grants,
3709 3710 3711
                                 lex->sql_command == SQLCOM_REVOKE, TRUE);
        if (!res)
          my_ok(thd);
3712 3713 3714
      }
      else
      {
3715
	if (check_grant(thd,(lex->grant | lex->grant_tot_col | GRANT_ACL),
3716
                        all_tables, FALSE, UINT_MAX, FALSE))
3717
	  goto error;
3718
        /* Conditionally writes to binlog */
3719 3720 3721 3722
        res= mysql_table_grant(thd, all_tables, lex->users_list,
			       lex->columns, lex->grant,
			       lex->sql_command == SQLCOM_REVOKE);
      }
3723 3724 3725
    }
    else
    {
3726
      if (lex->columns.elements || lex->type)
3727
      {
unknown's avatar
unknown committed
3728 3729
	my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
                   MYF(0));
unknown's avatar
unknown committed
3730
        goto error;
3731 3732
      }
      else
3733
	/* Conditionally writes to binlog */
3734 3735 3736 3737
	res = mysql_grant(thd, select_lex->db, lex->users_list, lex->grant,
			  lex->sql_command == SQLCOM_REVOKE);
      if (!res)
      {
3738
	if (lex->sql_command == SQLCOM_GRANT)
3739
	{
unknown's avatar
unknown committed
3740
	  List_iterator <LEX_USER> str_list(lex->users_list);
3741 3742 3743 3744 3745
	  LEX_USER *user, *tmp_user;
	  while ((tmp_user=str_list++))
          {
            if (!(user= get_current_user(thd, tmp_user)))
              goto error;
3746
	    reset_mqh(user, 0);
3747
          }
3748
	}
3749 3750 3751 3752
      }
    }
    break;
  }
unknown's avatar
SCRUM  
unknown committed
3753
#endif /*!NO_EMBEDDED_ACCESS_CHECKS*/
unknown's avatar
unknown committed
3754
  case SQLCOM_RESET:
3755 3756 3757
    /*
      RESET commands are never written to the binary log, so we have to
      initialize this variable because RESET shares the same code as FLUSH
3758 3759 3760 3761
    */
    lex->no_write_to_binlog= 1;
  case SQLCOM_FLUSH:
  {
unknown's avatar
unknown committed
3762
    bool write_to_binlog;
unknown's avatar
unknown committed
3763
    if (check_global_access(thd,RELOAD_ACL))
unknown's avatar
unknown committed
3764
      goto error;
3765

3766 3767 3768 3769
    /*
      reload_acl_and_cache() will tell us if we are allowed to write to the
      binlog or not.
    */
unknown's avatar
unknown committed
3770
    if (!reload_acl_and_cache(thd, lex->type, first_table, &write_to_binlog))
3771 3772 3773 3774 3775
    {
      /*
        We WANT to write and we CAN write.
        ! we write after unlocking the table.
      */
3776 3777 3778
      /*
        Presumably, RESET and binlog writing doesn't require synchronization
      */
3779 3780
      if (!lex->no_write_to_binlog && write_to_binlog)
      {
3781
        write_bin_log(thd, FALSE, thd->query(), thd->query_length());
3782
      }
3783
      my_ok(thd);
3784 3785
    } 
    
unknown's avatar
unknown committed
3786
    break;
3787
  }
unknown's avatar
unknown committed
3788
  case SQLCOM_KILL:
3789 3790 3791
  {
    Item *it= (Item *)lex->value_list.head();

unknown's avatar
unknown committed
3792 3793 3794 3795 3796 3797 3798
    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;
    }

3799
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1))
3800 3801 3802 3803 3804
    {
      my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY),
		 MYF(0));
      goto error;
    }
3805
    sql_kill(thd, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY);
unknown's avatar
unknown committed
3806
    break;
3807
  }
unknown's avatar
unknown committed
3808
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
3809
  case SQLCOM_SHOW_GRANTS:
3810 3811 3812 3813
  {
    LEX_USER *grant_user= get_current_user(thd, lex->grant_user);
    if (!grant_user)
      goto error;
3814
    if ((thd->security_ctx->priv_user &&
3815
	 !strcmp(thd->security_ctx->priv_user, grant_user->user.str)) ||
3816
	!check_access(thd, SELECT_ACL, "mysql",0,1,0,0))
unknown's avatar
unknown committed
3817
    {
3818
      res = mysql_show_grants(thd, grant_user);
unknown's avatar
unknown committed
3819 3820
    }
    break;
3821
  }
unknown's avatar
unknown committed
3822
#endif
3823
  case SQLCOM_HA_OPEN:
unknown's avatar
VIEW  
unknown committed
3824
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3825
    if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE))
3826
      goto error;
unknown's avatar
unknown committed
3827
    res= mysql_ha_open(thd, first_table, 0);
3828 3829
    break;
  case SQLCOM_HA_CLOSE:
unknown's avatar
VIEW  
unknown committed
3830 3831
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    res= mysql_ha_close(thd, first_table);
3832 3833
    break;
  case SQLCOM_HA_READ:
unknown's avatar
VIEW  
unknown committed
3834
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3835 3836 3837 3838 3839
    /*
      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.
    */
3840
    unit->set_limit(select_lex);
3841
    res= mysql_ha_read(thd, first_table, lex->ha_read_mode, lex->ident.str,
unknown's avatar
VIEW  
unknown committed
3842
                       lex->insert_list, lex->ha_rkey_mode, select_lex->where,
3843
                       unit->select_limit_cnt, unit->offset_limit_cnt);
3844 3845
    break;

unknown's avatar
unknown committed
3846
  case SQLCOM_BEGIN:
Konstantin Osipov's avatar
Konstantin Osipov committed
3847
    if (trans_begin(thd, lex->start_transaction_opt))
unknown's avatar
unknown committed
3848
      goto error;
3849
    my_ok(thd);
unknown's avatar
unknown committed
3850 3851
    break;
  case SQLCOM_COMMIT:
3852 3853
    DBUG_ASSERT(thd->lock == NULL ||
                thd->locked_tables_mode == LTM_LOCK_TABLES);
Konstantin Osipov's avatar
Konstantin Osipov committed
3854 3855
    if (trans_commit(thd))
      goto error;
3856
    thd->mdl_context.release_transactional_locks();
Konstantin Osipov's avatar
Konstantin Osipov committed
3857 3858
    /* Begin transaction with the same isolation level. */
    if (lex->tx_chain && trans_begin(thd))
unknown's avatar
unknown committed
3859
      goto error;
Konstantin Osipov's avatar
Konstantin Osipov committed
3860 3861 3862
    /* Disconnect the current client connection. */
    if (lex->tx_release)
      thd->killed= THD::KILL_CONNECTION;
3863
    my_ok(thd);
unknown's avatar
unknown committed
3864 3865
    break;
  case SQLCOM_ROLLBACK:
3866 3867
    DBUG_ASSERT(thd->lock == NULL ||
                thd->locked_tables_mode == LTM_LOCK_TABLES);
Konstantin Osipov's avatar
Konstantin Osipov committed
3868
    if (trans_rollback(thd))
unknown's avatar
unknown committed
3869
      goto error;
3870
    thd->mdl_context.release_transactional_locks();
Konstantin Osipov's avatar
Konstantin Osipov committed
3871 3872 3873 3874 3875 3876
    /* Begin transaction with the same isolation level. */
    if (lex->tx_chain && trans_begin(thd))
      goto error;
    /* Disconnect the current client connection. */
    if (lex->tx_release)
      thd->killed= THD::KILL_CONNECTION;
3877
    my_ok(thd);
unknown's avatar
unknown committed
3878
    break;
unknown's avatar
unknown committed
3879
  case SQLCOM_RELEASE_SAVEPOINT:
Konstantin Osipov's avatar
Konstantin Osipov committed
3880 3881 3882
    if (trans_release_savepoint(thd, lex->ident))
      goto error;
    my_ok(thd);
unknown's avatar
unknown committed
3883
    break;
unknown's avatar
unknown committed
3884
  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
Konstantin Osipov's avatar
Konstantin Osipov committed
3885 3886 3887
    if (trans_rollback_to_savepoint(thd, lex->ident))
      goto error;
    my_ok(thd);
unknown's avatar
unknown committed
3888
    break;
3889
  case SQLCOM_SAVEPOINT:
Konstantin Osipov's avatar
Konstantin Osipov committed
3890 3891 3892
    if (trans_savepoint(thd, lex->ident))
      goto error;
    my_ok(thd);
unknown's avatar
unknown committed
3893
    break;
3894 3895
  case SQLCOM_CREATE_PROCEDURE:
  case SQLCOM_CREATE_SPFUNCTION:
unknown's avatar
unknown committed
3896
  {
3897
    uint namelen;
unknown's avatar
unknown committed
3898
    char *name;
unknown's avatar
unknown committed
3899
    int sp_result= SP_INTERNAL_ERROR;
3900

3901
    DBUG_ASSERT(lex->sphead != 0);
unknown's avatar
unknown committed
3902
    DBUG_ASSERT(lex->sphead->m_db.str); /* Must be initialized in the parser */
3903 3904 3905 3906
    /*
      Verify that the database name is allowed, optionally
      lowercase it.
    */
3907
    if (check_db_name(&lex->sphead->m_db))
3908
    {
3909
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->sphead->m_db.str);
3910
      goto create_sp_error;
3911 3912
    }

3913
    /*
3914 3915 3916
      Check that a database directory with this name
      exists. Design note: This won't work on virtual databases
      like information_schema.
3917 3918
    */
    if (check_db_dir_existence(lex->sphead->m_db.str))
3919
    {
3920
      my_error(ER_BAD_DB_ERROR, MYF(0), lex->sphead->m_db.str);
3921
      goto create_sp_error;
3922
    }
3923

3924 3925
    if (check_access(thd, CREATE_PROC_ACL, lex->sphead->m_db.str, 0, 0, 0,
                     is_schema_db(lex->sphead->m_db.str)))
3926
      goto create_sp_error;
3927 3928

    name= lex->sphead->name(&namelen);
3929
#ifdef HAVE_DLOPEN
unknown's avatar
unknown committed
3930 3931 3932
    if (lex->sphead->m_type == TYPE_ENUM_FUNCTION)
    {
      udf_func *udf = find_udf(name, namelen);
3933

unknown's avatar
unknown committed
3934
      if (udf)
3935
      {
3936 3937
        my_error(ER_UDF_EXISTS, MYF(0), name);
        goto create_sp_error;
3938
      }
unknown's avatar
unknown committed
3939 3940 3941
    }
#endif

3942 3943
    if (sp_process_definer(thd))
      goto create_sp_error;
3944

Konstantin Osipov's avatar
Konstantin Osipov committed
3945
    res= (sp_result= sp_create_routine(thd, lex->sphead->m_type, lex->sphead));
unknown's avatar
unknown committed
3946
    switch (sp_result) {
3947
    case SP_OK: {
unknown's avatar
unknown committed
3948
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3949
      /* only add privileges if really neccessary */
3950 3951 3952 3953 3954

      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
3955 3956 3957 3958 3959 3960 3961 3962 3963 3964
      /*
        We're going to issue an implicit GRANT statement.
        It takes metadata locks and updates system tables.
        Make sure that sp_create_routine() did not leave any
        locks in the MDL context, so there is no risk to
        deadlock.
      */
      trans_commit_implicit(thd);
      close_thread_tables(thd);
      thd->mdl_context.release_transactional_locks();
3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982
      /*
        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;
      }

3983
      if (sp_automatic_privileges && !opt_noacl &&
3984
          check_routine_access(thd, DEFAULT_CREATE_PROC_ACLS,
3985
                               lex->sphead->m_db.str, name,
3986
                               lex->sql_command == SQLCOM_CREATE_PROCEDURE, 1))
3987
      {
unknown's avatar
unknown committed
3988
        if (sp_grant_privileges(thd, lex->sphead->m_db.str, name,
3989
                                lex->sql_command == SQLCOM_CREATE_PROCEDURE))
3990 3991 3992
          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                       ER_PROC_AUTO_GRANT_FAIL,
                       ER(ER_PROC_AUTO_GRANT_FAIL));
3993
      }
3994 3995 3996 3997 3998 3999 4000 4001 4002 4003

      /*
        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);
      }

unknown's avatar
unknown committed
4004
#endif
unknown's avatar
unknown committed
4005
    break;
4006
    }
4007 4008 4009 4010 4011 4012 4013 4014 4015
    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;
4016 4017 4018
    case SP_FLD_STORE_FAILED:
      my_error(ER_CANT_CREATE_SROUTINE, MYF(0), name);
      break;
4019 4020 4021 4022 4023 4024 4025 4026 4027 4028
    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:
unknown's avatar
unknown committed
4029
    if (sp_result != SP_OK )
4030
      goto error;
4031
    my_ok(thd);
4032 4033
    break; /* break super switch */
  } /* end case group bracket */
4034 4035 4036
  case SQLCOM_CALL:
    {
      sp_head *sp;
4037 4038 4039 4040
      /*
        This will cache all SP and SF and open and lock all tables
        required for execution.
      */
4041 4042
      if (check_table_access(thd, SELECT_ACL, all_tables, FALSE,
                             UINT_MAX, FALSE) ||
4043 4044 4045 4046
	  open_and_lock_tables(thd, all_tables))
       goto error;

      /*
4047 4048
        By this moment all needed SPs should be in cache so no need to look 
        into DB. 
4049
      */
4050 4051
      if (!(sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                                &thd->sp_proc_cache, TRUE)))
4052
      {
4053
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PROCEDURE",
unknown's avatar
unknown committed
4054
                 lex->spname->m_qname.str);
4055
	goto error;
4056 4057 4058
      }
      else
      {
unknown's avatar
unknown committed
4059
	ha_rows select_limit;
unknown's avatar
unknown committed
4060 4061
        /* bits that should be cleared in thd->server_status */
	uint bits_to_be_cleared= 0;
4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073
        /*
          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;
        }
4074

4075
	if (sp->m_flags & sp_head::MULTI_RESULTS)
4076
	{
4077
	  if (! (thd->client_capabilities & CLIENT_MULTI_RESULTS))
4078
	  {
4079 4080 4081 4082
            /*
              The client does not support multiple result sets being sent
              back
            */
4083
	    my_error(ER_SP_BADSELECT, MYF(0), sp->m_qname.str);
4084 4085
	    goto error;
	  }
unknown's avatar
unknown committed
4086 4087 4088 4089 4090 4091 4092
          /*
            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;
4093 4094
	}

4095
	if (check_routine_access(thd, EXECUTE_ACL,
4096
				 sp->m_db.str, sp->m_name.str, TRUE, FALSE))
4097 4098 4099
	{
	  goto error;
	}
unknown's avatar
unknown committed
4100 4101
	select_limit= thd->variables.select_limit;
	thd->variables.select_limit= HA_POS_ERROR;
4102

4103
        /* 
4104
          We never write CALL statements into binlog:
4105 4106 4107 4108 4109
           - 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.
4110
        */
4111
	res= sp->execute_procedure(thd, &lex->value_list);
4112

unknown's avatar
unknown committed
4113
	thd->variables.select_limit= select_limit;
4114

unknown's avatar
unknown committed
4115
        thd->server_status&= ~bits_to_be_cleared;
4116

unknown's avatar
unknown committed
4117
	if (!res)
4118 4119
          my_ok(thd, (ulong) (thd->row_count_func < 0 ? 0 :
                              thd->row_count_func));
4120
	else
4121
        {
4122
          DBUG_ASSERT(thd->is_error() || thd->killed);
4123
	  goto error;		// Substatement should already have sent error
4124
        }
4125
      }
4126
      break;
4127 4128
    }
  case SQLCOM_ALTER_PROCEDURE:
4129
  case SQLCOM_ALTER_FUNCTION:
4130
    {
unknown's avatar
unknown committed
4131
      int sp_result;
Konstantin Osipov's avatar
Konstantin Osipov committed
4132 4133
      int type= (lex->sql_command == SQLCOM_ALTER_PROCEDURE ?
                 TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION);
unknown's avatar
unknown committed
4134

Konstantin Osipov's avatar
Konstantin Osipov committed
4135 4136 4137 4138
      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;
unknown's avatar
unknown committed
4139

Konstantin Osipov's avatar
Konstantin Osipov committed
4140 4141 4142 4143 4144 4145 4146 4147
      /*
        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);
unknown's avatar
unknown committed
4148
      switch (sp_result)
4149
      {
unknown's avatar
unknown committed
4150
      case SP_OK:
4151
	my_ok(thd);
unknown's avatar
unknown committed
4152 4153
	break;
      case SP_KEY_NOT_FOUND:
4154 4155
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
unknown's avatar
unknown committed
4156 4157
	goto error;
      default:
4158 4159
	my_error(ER_SP_CANT_ALTER, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
unknown's avatar
unknown committed
4160
	goto error;
4161
      }
4162
      break;
4163 4164
    }
  case SQLCOM_DROP_PROCEDURE:
4165
  case SQLCOM_DROP_FUNCTION:
4166
    {
unknown's avatar
unknown committed
4167
      int sp_result;
4168 4169
      int type= (lex->sql_command == SQLCOM_DROP_PROCEDURE ?
                 TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION);
4170

Konstantin Osipov's avatar
Konstantin Osipov committed
4171 4172 4173 4174 4175 4176
      /*
        @todo: here we break the metadata locking protocol by
        looking up the information about the routine without
        a metadata lock. Rewrite this piece to make sp_drop_routine
        return whether the routine existed or not.
      */
unknown's avatar
unknown committed
4177
      sp_result= sp_routine_exists_in_table(thd, type, lex->spname);
Marc Alff's avatar
Marc Alff committed
4178
      thd->warning_info->opt_clear_warning_info(thd->query_id);
unknown's avatar
unknown committed
4179
      if (sp_result == SP_OK)
4180
      {
4181 4182 4183
        char *db= lex->spname->m_db.str;
	char *name= lex->spname->m_name.str;

4184 4185
	if (check_routine_access(thd, ALTER_PROC_ACL, db, name,
                                 lex->sql_command == SQLCOM_DROP_PROCEDURE, 0))
unknown's avatar
merge  
unknown committed
4186
          goto error;
4187

Konstantin Osipov's avatar
Konstantin Osipov committed
4188 4189
        /* Conditionally writes to binlog */
        sp_result= sp_drop_routine(thd, type, lex->spname);
4190

Konstantin Osipov's avatar
Konstantin Osipov committed
4191 4192 4193 4194 4195 4196 4197 4198 4199
#ifndef NO_EMBEDDED_ACCESS_CHECKS
        /*
          We're going to issue an implicit REVOKE statement.
          It takes metadata locks and updates system tables.
          Make sure that sp_create_routine() did not leave any
          locks in the MDL context, so there is no risk to
          deadlock.
        */
        trans_commit_implicit(thd);
4200
        close_thread_tables(thd);
4201
        thd->mdl_context.release_transactional_locks();
4202

4203
	if (sp_automatic_privileges && !opt_noacl &&
Konstantin Osipov's avatar
Konstantin Osipov committed
4204
	    sp_revoke_privileges(thd, db, name,
4205
                                 lex->sql_command == SQLCOM_DROP_PROCEDURE))
4206
	{
Konstantin Osipov's avatar
Konstantin Osipov committed
4207
	  push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
4208 4209 4210
		       ER_PROC_AUTO_REVOKE_FAIL,
		       ER(ER_PROC_AUTO_REVOKE_FAIL));
	}
unknown's avatar
unknown committed
4211
#endif
4212 4213 4214
      }
      else
      {
4215
#ifdef HAVE_DLOPEN
4216 4217 4218 4219 4220 4221
	if (lex->sql_command == SQLCOM_DROP_FUNCTION)
	{
          udf_func *udf = find_udf(lex->spname->m_name.str,
                                   lex->spname->m_name.length);
          if (udf)
          {
4222
	    if (check_access(thd, DELETE_ACL, "mysql", 0, 1, 0, 0))
4223
	      goto error;
4224

4225
	    if (!(res = mysql_drop_function(thd, &lex->spname->m_name)))
4226
	    {
4227
	      my_ok(thd);
4228
	      break;
4229 4230
	    }
	  }
4231
	}
4232
#endif
4233
	if (lex->spname->m_db.str)
unknown's avatar
unknown committed
4234
	  sp_result= SP_KEY_NOT_FOUND;
4235 4236 4237 4238 4239
	else
	{
	  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
	  goto error;
	}
4240
      }
unknown's avatar
unknown committed
4241 4242
      res= sp_result;
      switch (sp_result) {
4243
      case SP_OK:
4244
	my_ok(thd);
4245 4246
	break;
      case SP_KEY_NOT_FOUND:
4247 4248
	if (lex->drop_if_exists)
	{
4249
          write_bin_log(thd, TRUE, thd->query(), thd->query_length());
4250
	  push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
4251
			      ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST),
4252
			      SP_COM_STRING(lex), lex->spname->m_name.str);
unknown's avatar
unknown committed
4253
	  res= FALSE;
4254
	  my_ok(thd);
4255 4256
	  break;
	}
4257 4258
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4259 4260
	goto error;
      default:
4261 4262
	my_error(ER_SP_DROP_FAILED, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4263
	goto error;
4264
      }
4265
      break;
4266
    }
unknown's avatar
unknown committed
4267 4268
  case SQLCOM_SHOW_CREATE_PROC:
    {
unknown's avatar
unknown committed
4269
      if (sp_show_create_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname))
Konstantin Osipov's avatar
Konstantin Osipov committed
4270
        goto error;
unknown's avatar
unknown committed
4271 4272 4273 4274
      break;
    }
  case SQLCOM_SHOW_CREATE_FUNC:
    {
unknown's avatar
unknown committed
4275
      if (sp_show_create_routine(thd, TYPE_ENUM_FUNCTION, lex->spname))
unknown's avatar
unknown committed
4276 4277 4278
	goto error;
      break;
    }
unknown's avatar
unknown committed
4279 4280 4281
  case SQLCOM_SHOW_PROC_CODE:
  case SQLCOM_SHOW_FUNC_CODE:
    {
4282
#ifndef DBUG_OFF
unknown's avatar
unknown committed
4283
      sp_head *sp;
Konstantin Osipov's avatar
Konstantin Osipov committed
4284 4285
      int type= (lex->sql_command == SQLCOM_SHOW_PROC_CODE ?
                 TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION);
unknown's avatar
unknown committed
4286

Konstantin Osipov's avatar
Konstantin Osipov committed
4287 4288
      if (sp_cache_routine(thd, type, lex->spname, FALSE, &sp))
        goto error;
4289
      if (!sp || sp->show_routine_code(thd))
4290 4291
      {
        /* We don't distinguish between errors for now */
unknown's avatar
unknown committed
4292 4293 4294 4295 4296
        my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
        goto error;
      }
      break;
4297 4298 4299 4300
#else
      my_error(ER_FEATURE_DISABLED, MYF(0),
               "SHOW PROCEDURE|FUNCTION CODE", "--with-debug");
      goto error;
unknown's avatar
unknown committed
4301
#endif // ifndef DBUG_OFF
4302
    }
unknown's avatar
unknown committed
4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315
  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;
    }
unknown's avatar
VIEW  
unknown committed
4316 4317
  case SQLCOM_CREATE_VIEW:
    {
4318 4319 4320 4321
      /*
        Note: SQLCOM_CREATE_VIEW also handles 'ALTER VIEW' commands
        as specified through the thd->lex->create_view_mode flag.
      */
4322
      res= mysql_create_view(thd, first_table, thd->lex->create_view_mode);
unknown's avatar
VIEW  
unknown committed
4323 4324 4325 4326
      break;
    }
  case SQLCOM_DROP_VIEW:
    {
Konstantin Osipov's avatar
Konstantin Osipov committed
4327
      if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE))
unknown's avatar
unknown committed
4328
        goto error;
4329 4330
      /* Conditionally writes to binlog. */
      res= mysql_drop_view(thd, first_table, thd->lex->drop_mode);
unknown's avatar
VIEW  
unknown committed
4331 4332
      break;
    }
4333 4334
  case SQLCOM_CREATE_TRIGGER:
  {
4335
    /* Conditionally writes to binlog. */
4336 4337
    res= mysql_create_or_drop_trigger(thd, all_tables, 1);

4338 4339 4340 4341
    break;
  }
  case SQLCOM_DROP_TRIGGER:
  {
4342
    /* Conditionally writes to binlog. */
4343 4344 4345
    res= mysql_create_or_drop_trigger(thd, all_tables, 0);
    break;
  }
4346
  case SQLCOM_XA_START:
Konstantin Osipov's avatar
Konstantin Osipov committed
4347 4348
    if (trans_xa_start(thd))
      goto error;
4349
    my_ok(thd);
4350 4351
    break;
  case SQLCOM_XA_END:
Konstantin Osipov's avatar
Konstantin Osipov committed
4352 4353
    if (trans_xa_end(thd))
      goto error;
4354
    my_ok(thd);
4355 4356
    break;
  case SQLCOM_XA_PREPARE:
Konstantin Osipov's avatar
Konstantin Osipov committed
4357 4358
    if (trans_xa_prepare(thd))
      goto error;
4359
    my_ok(thd);
4360 4361
    break;
  case SQLCOM_XA_COMMIT:
Konstantin Osipov's avatar
Konstantin Osipov committed
4362 4363
    if (trans_xa_commit(thd))
      goto error;
4364
    thd->mdl_context.release_transactional_locks();
Konstantin Osipov's avatar
Konstantin Osipov committed
4365
    my_ok(thd);
4366 4367
    break;
  case SQLCOM_XA_ROLLBACK:
Konstantin Osipov's avatar
Konstantin Osipov committed
4368 4369
    if (trans_xa_rollback(thd))
      goto error;
4370
    thd->mdl_context.release_transactional_locks();
Konstantin Osipov's avatar
Konstantin Osipov committed
4371
    my_ok(thd);
4372 4373
    break;
  case SQLCOM_XA_RECOVER:
4374
    res= mysql_xa_recover(thd);
4375
    break;
unknown's avatar
unknown committed
4376
  case SQLCOM_ALTER_TABLESPACE:
4377
    if (check_global_access(thd, CREATE_TABLESPACE_ACL))
unknown's avatar
unknown committed
4378 4379
      break;
    if (!(res= mysql_alter_tablespace(thd, lex->alter_tablespace_info)))
4380
      my_ok(thd);
unknown's avatar
unknown committed
4381 4382 4383 4384
    break;
  case SQLCOM_INSTALL_PLUGIN:
    if (! (res= mysql_install_plugin(thd, &thd->lex->comment,
                                     &thd->lex->ident)))
4385
      my_ok(thd);
unknown's avatar
unknown committed
4386 4387 4388
    break;
  case SQLCOM_UNINSTALL_PLUGIN:
    if (! (res= mysql_uninstall_plugin(thd, &thd->lex->comment)))
4389
      my_ok(thd);
unknown's avatar
unknown committed
4390 4391 4392 4393 4394 4395 4396 4397 4398 4399
    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;
  }
unknown's avatar
unknown committed
4400 4401 4402 4403 4404
  case SQLCOM_CREATE_SERVER:
  {
    int error;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_CREATE_SERVER"));
unknown's avatar
unknown committed
4405 4406 4407 4408

    if (check_global_access(thd, SUPER_ACL))
      break;

unknown's avatar
unknown committed
4409 4410
    if ((error= create_server(thd, &lex->server_options)))
    {
4411
      DBUG_PRINT("info", ("problem creating server <%s>",
unknown's avatar
unknown committed
4412 4413 4414 4415
                          lex->server_options.server_name));
      my_error(error, MYF(0), lex->server_options.server_name);
      break;
    }
4416
    my_ok(thd, 1);
unknown's avatar
unknown committed
4417 4418 4419 4420 4421 4422 4423
    break;
  }
  case SQLCOM_ALTER_SERVER:
  {
    int error;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_ALTER_SERVER"));
unknown's avatar
unknown committed
4424 4425 4426 4427

    if (check_global_access(thd, SUPER_ACL))
      break;

unknown's avatar
unknown committed
4428 4429
    if ((error= alter_server(thd, &lex->server_options)))
    {
4430
      DBUG_PRINT("info", ("problem altering server <%s>",
unknown's avatar
unknown committed
4431 4432 4433 4434
                          lex->server_options.server_name));
      my_error(error, MYF(0), lex->server_options.server_name);
      break;
    }
4435
    my_ok(thd, 1);
unknown's avatar
unknown committed
4436 4437 4438 4439 4440 4441 4442
    break;
  }
  case SQLCOM_DROP_SERVER:
  {
    int err_code;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_DROP_SERVER"));
unknown's avatar
unknown committed
4443 4444 4445 4446

    if (check_global_access(thd, SUPER_ACL))
      break;

unknown's avatar
unknown committed
4447 4448
    if ((err_code= drop_server(thd, &lex->server_options)))
    {
unknown's avatar
unknown committed
4449
      if (! lex->drop_if_exists && err_code == ER_FOREIGN_SERVER_DOESNT_EXIST)
unknown's avatar
unknown committed
4450 4451 4452 4453 4454 4455 4456
      {
        DBUG_PRINT("info", ("problem dropping server %s",
                            lex->server_options.server_name));
        my_error(err_code, MYF(0), lex->server_options.server_name);
      }
      else
      {
4457
        my_ok(thd, 0);
unknown's avatar
unknown committed
4458 4459 4460
      }
      break;
    }
4461
    my_ok(thd, 1);
unknown's avatar
unknown committed
4462 4463
    break;
  }
Marc Alff's avatar
Marc Alff committed
4464 4465 4466 4467 4468
  case SQLCOM_SIGNAL:
  case SQLCOM_RESIGNAL:
    DBUG_ASSERT(lex->m_stmt != NULL);
    res= lex->m_stmt->execute(thd);
    break;
4469
  default:
4470
#ifndef EMBEDDED_LIBRARY
4471
    DBUG_ASSERT(0);                             /* Impossible */
4472
#endif
4473
    my_ok(thd);
unknown's avatar
unknown committed
4474 4475
    break;
  }
4476
  thd_proc_info(thd, "query end");
4477 4478

  /*
unknown's avatar
unknown committed
4479
    Binlog-related cleanup:
4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490
    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);

4491
  /*
4492 4493
    The return value for ROW_COUNT() is "implementation dependent" if the
    statement is not DELETE, INSERT or UPDATE, but -1 is what JDBC and ODBC
4494 4495 4496 4497
    wants. We also keep the last value in case of SQLCOM_CALL or
    SQLCOM_EXECUTE.
  */
  if (!(sql_command_flags[lex->sql_command] & CF_HAS_ROW_COUNT))
4498
    thd->row_count_func= -1;
4499

4500
  goto finish;
unknown's avatar
unknown committed
4501 4502

error:
4503 4504
  res= TRUE;

4505
finish:
4506
  if (thd->global_read_lock_protection > 0)
4507 4508 4509 4510 4511 4512 4513
  {
    /*
      Release the protection against the global read lock and wake
      everyone, who might want to set a global read lock.
    */
    start_waiting_global_read_lock(thd);
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
4514

4515 4516 4517 4518 4519 4520 4521 4522
  if (stmt_causes_implicit_commit(thd, CF_IMPLICIT_COMMIT_END))
  {
    /* If commit fails, we should be able to reset the OK status. */
    thd->stmt_da->can_overwrite_status= TRUE;
    /* 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. */
    trans_commit_implicit(thd);
4523
    thd->stmt_da->can_overwrite_status= FALSE;
4524 4525
    /* Close tables and release metadata locks. */
    close_thread_tables(thd);
4526
    thd->mdl_context.release_transactional_locks();
4527
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
4528

4529
  DBUG_RETURN(res || thd->is_error());
unknown's avatar
unknown committed
4530 4531 4532
}


4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555
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);
  }
  if (!(res= open_and_lock_tables(thd, all_tables)))
  {
    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()))
4556
        return 1;                               /* purecov: inspected */
4557 4558 4559 4560 4561 4562 4563
      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);
4564
        thd->lex->unit.print(&str, QT_ORDINARY);
4565 4566 4567 4568
        str.append('\0');
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
                     ER_YES, str.ptr());
      }
4569 4570 4571 4572
      if (res)
        result->abort();
      else
        result->send_eof();
4573 4574 4575 4576 4577
      delete result;
    }
    else
    {
      if (!result && !(result= new select_send()))
4578
        return 1;                               /* purecov: inspected */
4579 4580 4581 4582 4583 4584 4585 4586 4587 4588
      query_cache_store_query(thd, all_tables);
      res= handle_select(thd, lex, result, 0);
      if (result != lex->result)
        delete result;
    }
  }
  return res;
}


unknown's avatar
unknown committed
4589
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
4590
/**
4591
  Check grants for commands which work only with one table.
unknown's avatar
unknown committed
4592

4593 4594 4595
  @param thd                    Thread handler
  @param privilege              requested privilege
  @param all_tables             global table list of query
unknown's avatar
unknown committed
4596
  @param no_errors              FALSE/TRUE - report/don't report error to
4597
                            the client (using my_error() call).
unknown's avatar
unknown committed
4598 4599 4600 4601 4602

  @retval
    0   OK
  @retval
    1   access denied, error is sent to client
unknown's avatar
unknown committed
4603 4604
*/

4605
bool check_single_table_access(THD *thd, ulong privilege, 
4606
                               TABLE_LIST *all_tables, bool no_errors)
unknown's avatar
unknown committed
4607
{
4608 4609 4610 4611 4612 4613
  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;

4614 4615 4616 4617 4618 4619 4620 4621
  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,
4622
		   &all_tables->grant.privilege, 0, no_errors,
4623
                   test(all_tables->schema_table)))
4624
    goto deny;
unknown's avatar
unknown committed
4625

unknown's avatar
unknown committed
4626
  /* Show only 1 table for check_grant */
4627
  if (!(all_tables->belong_to_view &&
4628
        (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) &&
4629
      check_grant(thd, privilege, all_tables, FALSE, 1, no_errors))
4630 4631 4632
    goto deny;

  thd->security_ctx= backup_ctx;
4633 4634 4635 4636 4637 4638 4639
  return 0;

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

unknown's avatar
unknown committed
4640
/**
4641 4642 4643
  Check grants for commands which work only with one table and all other
  tables belonging to subselects or implicitly opened tables.

unknown's avatar
unknown committed
4644 4645 4646 4647 4648 4649 4650 4651
  @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
4652 4653 4654 4655
*/

bool check_one_table_access(THD *thd, ulong privilege, TABLE_LIST *all_tables)
{
4656
  if (check_single_table_access (thd,privilege,all_tables, FALSE))
4657
    return 1;
unknown's avatar
unknown committed
4658

4659
  /* Check rights on tables of subselects and implictly opened tables */
unknown's avatar
unknown committed
4660
  TABLE_LIST *subselects_tables, *view= all_tables->view ? all_tables : 0;
unknown's avatar
VIEW  
unknown committed
4661
  if ((subselects_tables= all_tables->next_global))
unknown's avatar
unknown committed
4662
  {
unknown's avatar
unknown committed
4663 4664 4665 4666 4667 4668
    /*
      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)
    {
4669
      if (check_single_table_access (thd, privilege, subselects_tables, FALSE))
unknown's avatar
unknown committed
4670 4671 4672 4673
        return 1;
      subselects_tables= subselects_tables->next_global;
    }
    if (subselects_tables &&
4674 4675
        (check_table_access(thd, SELECT_ACL, subselects_tables, FALSE,
                            UINT_MAX, FALSE)))
4676
      return 1;
unknown's avatar
unknown committed
4677 4678
  }
  return 0;
unknown's avatar
unknown committed
4679 4680 4681
}


unknown's avatar
unknown committed
4682
/**
4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706
  @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.
  @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.
  @param schema_db    True if the db specified belongs to the meta data tables.

  '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.

  A meta data table (from INFORMATION_SCHEMA) can always be accessed with
  a SELECT_ACL.

  @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.
unknown's avatar
unknown committed
4707
*/
4708

unknown's avatar
unknown committed
4709
bool
unknown's avatar
unknown committed
4710
check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv,
4711
	     bool dont_check_global_grants, bool no_errors, bool schema_db)
unknown's avatar
unknown committed
4712
{
4713
  Security_context *sctx= thd->security_ctx;
unknown's avatar
unknown committed
4714
  ulong db_access;
4715

4716 4717 4718 4719 4720
  /*
    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
4721
    if it's database level grant command
4722 4723 4724
    (see SQLCOM_GRANT case, mysql_execute_command() function) and
    set db_is_pattern according to 'dont_check_global_grants' value.
  */
4725
  bool  db_is_pattern= ((want_access & GRANT_ACL) && dont_check_global_grants);
unknown's avatar
unknown committed
4726
  ulong dummy;
4727 4728
  DBUG_ENTER("check_access");
  DBUG_PRINT("enter",("db: %s  want_access: %lu  master_access: %lu",
4729
                      db ? db : "", want_access, sctx->master_access));
4730

unknown's avatar
unknown committed
4731 4732 4733 4734 4735
  if (save_priv)
    *save_priv=0;
  else
    save_priv= &dummy;

4736
  thd_proc_info(thd, "checking permissions");
4737
  if ((!db || !db[0]) && !thd->db && !dont_check_global_grants)
unknown's avatar
unknown committed
4738
  {
4739
    DBUG_PRINT("error",("No database"));
4740
    if (!no_errors)
unknown's avatar
unknown committed
4741 4742
      my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR),
                 MYF(0));                       /* purecov: tested */
unknown's avatar
unknown committed
4743
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
4744 4745
  }

4746 4747
  if (schema_db)
  {
4748 4749 4750 4751 4752 4753
    /*
      We don't allow any simple privileges but SELECT_ACL or CREATE_VIEW_ACL
      on the information_schema database.
    */
    want_access &= ~SELECT_ACL;
    if (want_access & DB_ACLS)
4754 4755
    {
      if (!no_errors)
4756 4757
      {
        const char *db_name= db ? db : thd->db;
4758
        my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
4759 4760
                 sctx->priv_user, sctx->priv_host, db_name);
      }
4761 4762 4763 4764
      /*
        Access denied;
        [out] *save_privileges= 0
      */
4765 4766 4767 4768
      DBUG_RETURN(TRUE);
    }
    else
    {
4769
      /* Access granted */
4770 4771 4772 4773 4774
      *save_priv= SELECT_ACL;
      DBUG_RETURN(FALSE);
    }
  }

4775
  if ((sctx->master_access & want_access) == want_access)
unknown's avatar
unknown committed
4776
  {
4777 4778
    /* get access for current db */
    db_access= sctx->db_access;
4779
    /*
4780 4781
      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
4782
      UPDATE t1 SET a=1 WHERE b > 0
4783
      2. Change db access if it isn't current db which is being addressed
4784
    */
4785
    if (!(sctx->master_access & SELECT_ACL) &&
unknown's avatar
unknown committed
4786
	(db && (!thd->db || db_is_pattern || strcmp(db,thd->db))))
4787 4788
      db_access=acl_get(sctx->host, sctx->ip, sctx->priv_user, db,
                        db_is_pattern);
4789 4790 4791 4792 4793

    /*
      The effective privileges are the union of the global privileges
      and the the intersection of db- and host-privileges.
    */
4794
    *save_priv=sctx->master_access | db_access;
unknown's avatar
unknown committed
4795
    DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
4796
  }
4797
  if (((want_access & ~sctx->master_access) & ~DB_ACLS) ||
4798
      (! db && dont_check_global_grants))
unknown's avatar
unknown committed
4799
  {						// We can never grant this
4800
    DBUG_PRINT("error",("No possible access"));
4801
    if (!no_errors)
4802
      my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
4803 4804
               sctx->priv_user,
               sctx->priv_host,
4805 4806 4807
               (thd->password ?
                ER(ER_YES) :
                ER(ER_NO)));                    /* purecov: tested */
unknown's avatar
unknown committed
4808
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
4809 4810 4811
  }

  if (db == any_db)
4812 4813 4814 4815 4816 4817 4818
  {
    /*
      Access granted; Allow select on *any* db.
      [out] *save_privileges= 0
    */
    DBUG_RETURN(FALSE);
  }
unknown's avatar
unknown committed
4819

unknown's avatar
unknown committed
4820
  if (db && (!thd->db || db_is_pattern || strcmp(db,thd->db)))
4821 4822
    db_access= acl_get(sctx->host, sctx->ip, sctx->priv_user, db,
                       db_is_pattern);
unknown's avatar
unknown committed
4823
  else
4824
    db_access= sctx->db_access;
4825 4826
  DBUG_PRINT("info",("db_access: %lu  want_access: %lu",
                     db_access, want_access));
4827

4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848
  /*
    Save the union of User-table and the intersection between Db-table and
    Host-table privileges.
  */
  db_access= (db_access | sctx->master_access);
  *save_priv= db_access;

  /*
    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 ||
4849
      (!dont_check_global_grants &&
4850 4851 4852 4853 4854 4855 4856 4857
       need_table_or_column_check))
  {
    /*
       Ok; but need to check table- and column privileges.
       [out] *save_privileges is (User-priv | (Db-priv & Host-priv))
    */
    DBUG_RETURN(FALSE);
  }
4858

4859 4860 4861 4862
  /*
    Access is denied;
    [out] *save_privileges is (User-priv | (Db-priv & Host-priv))
  */
4863
  DBUG_PRINT("error",("Access denied"));
4864
  if (!no_errors)
4865
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
4866
             sctx->priv_user, sctx->priv_host,
4867 4868
             (db ? db : (thd->db ?
                         thd->db :
4869 4870 4871
                         "unknown")));
  DBUG_RETURN(TRUE);

unknown's avatar
unknown committed
4872 4873 4874
}


4875 4876
static bool check_show_access(THD *thd, TABLE_LIST *table)
{
unknown's avatar
unknown committed
4877
  switch (get_schema_table_idx(table->schema_table)) {
4878 4879
  case SCH_SCHEMATA:
    return (specialflag & SPECIAL_SKIP_SHOW_DB) &&
unknown's avatar
unknown committed
4880
      check_global_access(thd, SHOW_DB_ACL);
4881 4882 4883 4884 4885

  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
  case SCH_TRIGGERS:
unknown's avatar
unknown committed
4886 4887 4888
  case SCH_EVENTS:
  {
    const char *dst_db_name= table->schema_select_lex->db;
4889

unknown's avatar
unknown committed
4890
    DBUG_ASSERT(dst_db_name);
4891

unknown's avatar
unknown committed
4892 4893 4894 4895
    if (check_access(thd, SELECT_ACL, dst_db_name,
                     &thd->col_access, FALSE, FALSE,
                     is_schema_db(dst_db_name)))
      return TRUE;
4896

unknown's avatar
unknown committed
4897 4898 4899 4900 4901 4902 4903
    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;
4904 4905
    }

unknown's avatar
unknown committed
4906 4907 4908
    return FALSE;
  }

4909 4910
  case SCH_COLUMNS:
  case SCH_STATISTICS:
unknown's avatar
unknown committed
4911 4912 4913
  {
    TABLE_LIST *dst_table;
    dst_table= (TABLE_LIST *) table->schema_select_lex->table_list.first;
4914

unknown's avatar
unknown committed
4915
    DBUG_ASSERT(dst_table);
4916

4917 4918
    if (check_access(thd, SELECT_ACL, dst_table->db,
                     &dst_table->grant.privilege, FALSE, FALSE,
unknown's avatar
unknown committed
4919
                     test(dst_table->schema_table)))
4920 4921 4922 4923 4924 4925 4926 4927
          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 */
4928

4929 4930
    /* Access granted */
    return FALSE;
unknown's avatar
unknown committed
4931 4932
  }
  default:
4933 4934 4935 4936 4937 4938 4939
    break;
  }

  return FALSE;
}


4940

4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968
/**
  @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).
4969

4970 4971 4972 4973
  @return
    @retval FALSE OK
    @retval TRUE  Access denied; But column or routine privileges might need to
      be checked also.
unknown's avatar
unknown committed
4974 4975
*/

4976
bool
4977 4978 4979
check_table_access(THD *thd, ulong requirements,TABLE_LIST *tables,
		   bool any_combination_of_privileges_will_do,
                   uint number, bool no_errors)
unknown's avatar
unknown committed
4980
{
4981 4982
  TABLE_LIST *org_tables= tables;
  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
4983
  uint i= 0;
4984
  Security_context *sctx= thd->security_ctx, *backup_ctx= thd->security_ctx;
4985
  /*
unknown's avatar
unknown committed
4986 4987 4988
    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.
4989
  */
4990
  for (; i < number && tables != first_not_own_table && tables;
4991
       tables= tables->next_global, i++)
unknown's avatar
unknown committed
4992
  {
4993
    ulong want_access= requirements;
4994 4995 4996 4997 4998
    if (tables->security_ctx)
      sctx= tables->security_ctx;
    else
      sctx= backup_ctx;

4999 5000 5001 5002 5003 5004
    /*
      Always allow SELECT on schema tables. This is done by removing the
      required SELECT_ACL privilege in the want_access parameter.
      Disallow any other DDL or DML operation on any schema table.
    */
    if (tables->schema_table)
5005
    {
5006 5007 5008 5009 5010 5011 5012 5013 5014
      want_access &= ~SELECT_ACL;
      if (want_access & DB_ACLS)
      {
        if (!no_errors)
          my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
                  sctx->priv_user, sctx->priv_host,
                  INFORMATION_SCHEMA_NAME.str);
        goto deny;
      }
5015
    }
5016 5017 5018 5019 5020
    /*
       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);
unknown's avatar
unknown committed
5021 5022 5023 5024 5025 5026 5027 5028

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

5029 5030
    DBUG_PRINT("info", ("derived: %d  view: %d", tables->derived != 0,
                        tables->view != 0));
5031
    if (tables->is_anonymous_derived_table() ||
5032 5033
        (tables->table && tables->table->s &&
         (int)tables->table->s->tmp_table))
unknown's avatar
unknown committed
5034
      continue;
5035
    thd->security_ctx= sctx;
5036 5037
    if ((sctx->master_access & want_access) == want_access &&
        thd->db)
unknown's avatar
unknown committed
5038
      tables->grant.privilege= want_access;
unknown's avatar
unknown committed
5039
    else if (tables->db && thd->db && strcmp(tables->db, thd->db) == 0)
unknown's avatar
unknown committed
5040
    {
5041
      if (check_access(thd, want_access, tables->get_db_name(),
5042
                       &tables->grant.privilege, 0, no_errors,
5043
                       test(tables->schema_table)))
5044
        goto deny;                            // Access denied
unknown's avatar
unknown committed
5045
    }
5046
    else if (check_access(thd, want_access, tables->get_db_name(),
5047
                          &tables->grant.privilege, 0, no_errors, 0))
5048
      goto deny;
unknown's avatar
unknown committed
5049
  }
5050
  thd->security_ctx= backup_ctx;
5051 5052 5053
  return check_grant(thd,requirements,org_tables,
                     any_combination_of_privileges_will_do,
                     number, no_errors);
5054 5055 5056
deny:
  thd->security_ctx= backup_ctx;
  return TRUE;
unknown's avatar
unknown committed
5057 5058
}

5059

5060
bool
5061 5062
check_routine_access(THD *thd, ulong want_access,char *db, char *name,
		     bool is_proc, bool no_errors)
5063 5064 5065 5066 5067
{
  TABLE_LIST tables[1];
  
  bzero((char *)tables, sizeof(TABLE_LIST));
  tables->db= db;
5068
  tables->table_name= tables->alias= name;
5069
  
unknown's avatar
unknown committed
5070 5071 5072 5073 5074 5075 5076
  /*
    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).
  */
  if ((thd->security_ctx->master_access & want_access) == want_access)
5077 5078
    tables->grant.privilege= want_access;
  else if (check_access(thd,want_access,db,&tables->grant.privilege,
unknown's avatar
unknown committed
5079
			0, no_errors, 0))
5080 5081
    return TRUE;
  
5082
    return check_grant_routine(thd, want_access, tables, is_proc, no_errors);
5083 5084
}

5085

unknown's avatar
unknown committed
5086 5087
/**
  Check if the routine has any of the routine privileges.
5088

unknown's avatar
unknown committed
5089 5090 5091
  @param thd	       Thread handler
  @param db           Database name
  @param name         Routine name
5092

unknown's avatar
unknown committed
5093
  @retval
5094
    0            ok
unknown's avatar
unknown committed
5095
  @retval
5096 5097 5098
    1            error
*/

5099 5100
bool check_some_routine_access(THD *thd, const char *db, const char *name,
                               bool is_proc)
5101 5102
{
  ulong save_priv;
5103
  if (thd->security_ctx->master_access & SHOW_PROC_ACLS)
5104
    return FALSE;
5105 5106 5107 5108 5109
  /*
    There are no routines in information_schema db. So we can safely
    pass zero to last paramter of check_access function
  */
  if (!check_access(thd, SHOW_PROC_ACLS, db, &save_priv, 0, 1, 0) ||
5110 5111
      (save_priv & SHOW_PROC_ACLS))
    return FALSE;
5112
  return check_routine_level_acl(thd, db, name, is_proc);
5113 5114 5115
}


5116 5117 5118
/*
  Check if the given table has any of the asked privileges

unknown's avatar
unknown committed
5119 5120
  @param thd		 Thread handler
  @param want_access	 Bitmap of possible privileges to check for
5121

unknown's avatar
unknown committed
5122
  @retval
5123
    0  ok
unknown's avatar
unknown committed
5124
  @retval
5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138
    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,
5139 5140
                        &table->grant.privilege, 0, 1,
                        test(table->schema_table)) &&
5141
           !check_grant(thd, access, table, FALSE, 1, TRUE))
5142 5143 5144 5145 5146 5147 5148
        DBUG_RETURN(0);
    }
  }
  DBUG_PRINT("exit",("no matching access rights"));
  DBUG_RETURN(1);
}

unknown's avatar
unknown committed
5149
#endif /*NO_EMBEDDED_ACCESS_CHECKS*/
5150

5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183

/**
  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
}

unknown's avatar
unknown committed
5184 5185 5186 5187
/****************************************************************************
	Check stack size; Send error if there isn't enough stack to continue
****************************************************************************/

5188 5189
#ifndef EMBEDDED_LIBRARY

unknown's avatar
unknown committed
5190 5191 5192 5193 5194 5195
#if STACK_DIRECTION < 0
#define used_stack(A,B) (long) (A - B)
#else
#define used_stack(A,B) (long) (B - A)
#endif

unknown's avatar
unknown committed
5196 5197 5198 5199
#ifndef DBUG_OFF
long max_stack_used;
#endif

unknown's avatar
unknown committed
5200 5201
/**
  @note
5202 5203 5204 5205
  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.
unknown's avatar
unknown committed
5206
*/
5207
bool check_stack_overrun(THD *thd, long margin,
5208
			 uchar *buf __attribute__((unused)))
unknown's avatar
unknown committed
5209 5210
{
  long stack_used;
5211
  DBUG_ASSERT(thd == current_thd);
unknown's avatar
unknown committed
5212
  if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >=
5213
      (long) (my_thread_stack_size - margin))
unknown's avatar
unknown committed
5214
  {
5215 5216 5217 5218
    char ebuff[MYSQL_ERRMSG_SIZE];
    my_snprintf(ebuff, sizeof(ebuff), ER(ER_STACK_OVERRUN_NEED_MORE),
                stack_used, my_thread_stack_size, margin);
    my_message(ER_STACK_OVERRUN_NEED_MORE, ebuff, MYF(ME_FATALERROR));
unknown's avatar
unknown committed
5219 5220
    return 1;
  }
unknown's avatar
unknown committed
5221 5222 5223
#ifndef DBUG_OFF
  max_stack_used= max(max_stack_used, stack_used);
#endif
unknown's avatar
unknown committed
5224 5225
  return 0;
}
5226
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
5227 5228 5229 5230

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

5231
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
unknown's avatar
unknown committed
5232
{
5233
  Yacc_state *state= & current_thd->m_parser_state->m_yacc;
5234
  ulong old_info=0;
5235
  DBUG_ASSERT(state);
unknown's avatar
unknown committed
5236 5237
  if ((uint) *yystacksize >= MY_YACC_MAX)
    return 1;
5238
  if (!state->yacc_yyvs)
unknown's avatar
unknown committed
5239 5240
    old_info= *yystacksize;
  *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
5241
  if (!(state->yacc_yyvs= (uchar*)
5242
        my_realloc(state->yacc_yyvs,
5243 5244 5245
                   *yystacksize*sizeof(**yyvs),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
      !(state->yacc_yyss= (uchar*)
5246
        my_realloc(state->yacc_yyss,
5247 5248
                   *yystacksize*sizeof(**yyss),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
unknown's avatar
unknown committed
5249 5250
    return 1;
  if (old_info)
5251 5252 5253 5254 5255 5256 5257 5258
  {
    /*
      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));
unknown's avatar
unknown committed
5259
  }
5260 5261
  *yyss= (short*) state->yacc_yyss;
  *yyvs= (YYSTYPE*) state->yacc_yyvs;
unknown's avatar
unknown committed
5262 5263 5264 5265
  return 0;
}


unknown's avatar
unknown committed
5266
/**
5267 5268 5269 5270
 Reset THD part responsible for command processing state.

   This needs to be called before execution of every statement
   (prepared or conventional).
5271
   It is not called by substatements of routines.
5272

unknown's avatar
unknown committed
5273
  @todo
5274 5275
   Make it a method of THD and align its name with the rest of
   reset/end/start/init methods.
unknown's avatar
unknown committed
5276
  @todo
5277 5278 5279 5280 5281 5282
   Call it after we use THD for queries, not before.
*/

void mysql_reset_thd_for_next_command(THD *thd)
{
  DBUG_ENTER("mysql_reset_thd_for_next_command");
5283
  DBUG_ASSERT(!thd->spcont); /* not for substatements of routines */
5284
  DBUG_ASSERT(! thd->in_sub_stmt);
5285
  thd->free_list= 0;
5286
  thd->select_number= 1;
5287 5288 5289 5290
  /*
    Those two lines below are theoretically unneeded as
    THD::cleanup_after_query() should take care of this already.
  */
5291
  thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
5292 5293 5294
  thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;

  thd->query_start_used= 0;
5295
  thd->is_fatal_error= thd->time_zone_used= 0;
5296 5297 5298 5299 5300
  /*
    Clear the status flag that are expected to be cleared at the
    beginning of each SQL statement.
  */
  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
5301 5302 5303 5304 5305
  /*
    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.
  */
5306
  if (!thd->in_multi_stmt_transaction())
unknown's avatar
unknown committed
5307 5308
  {
    thd->options&= ~OPTION_KEEP_LOG;
5309
    thd->transaction.all.modified_non_trans_table= FALSE;
unknown's avatar
unknown committed
5310
  }
5311
  DBUG_ASSERT(thd->security_ctx== &thd->main_security_ctx);
unknown's avatar
unknown committed
5312
  thd->thread_specific_used= FALSE;
5313 5314

  if (opt_bin_log)
5315
  {
5316 5317
    reset_dynamic(&thd->user_var_events);
    thd->user_var_events_alloc= thd->mem_root;
5318
  }
5319
  thd->clear_error();
Marc Alff's avatar
Marc Alff committed
5320 5321
  thd->stmt_da->reset_diagnostics_area();
  thd->warning_info->reset_for_next_command();
5322 5323 5324
  thd->rand_used= 0;
  thd->sent_row_count= thd->examined_row_count= 0;

5325 5326 5327 5328
  /*
    Because we come here only for start of top-statements, binlog format is
    constant inside a complex statement (using stored functions) etc.
  */
unknown's avatar
unknown committed
5329 5330
  thd->reset_current_stmt_binlog_row_based();

5331 5332 5333 5334
  DBUG_PRINT("debug",
             ("current_stmt_binlog_row_based: %d",
              thd->current_stmt_binlog_row_based));

unknown's avatar
unknown committed
5335 5336 5337
  DBUG_VOID_RETURN;
}

5338

5339 5340 5341 5342 5343 5344 5345 5346
/**
  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.
*/

5347 5348 5349
void
mysql_init_select(LEX *lex)
{
unknown's avatar
unknown committed
5350
  SELECT_LEX *select_lex= lex->current_select;
unknown's avatar
unknown committed
5351
  select_lex->init_select();
5352
  lex->wild= 0;
5353 5354
  if (select_lex == &lex->select_lex)
  {
5355
    DBUG_ASSERT(lex->result == 0);
5356 5357
    lex->exchange= 0;
  }
5358 5359
}

5360

5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372
/**
  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.
*/

unknown's avatar
unknown committed
5373
bool
unknown's avatar
unknown committed
5374
mysql_new_select(LEX *lex, bool move_down)
5375
{
unknown's avatar
unknown committed
5376
  SELECT_LEX *select_lex;
5377
  THD *thd= lex->thd;
unknown's avatar
unknown committed
5378 5379
  DBUG_ENTER("mysql_new_select");

5380
  if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
unknown's avatar
unknown committed
5381
    DBUG_RETURN(1);
5382
  select_lex->select_number= ++thd->select_number;
unknown's avatar
unknown committed
5383
  select_lex->parent_lex= lex; /* Used in init_query. */
unknown's avatar
unknown committed
5384 5385
  select_lex->init_query();
  select_lex->init_select();
unknown's avatar
unknown committed
5386
  lex->nest_level++;
unknown's avatar
unknown committed
5387 5388 5389 5390 5391
  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);
  }
unknown's avatar
unknown committed
5392
  select_lex->nest_level= lex->nest_level;
5393 5394 5395
  /*
    Don't evaluate this subquery during statement prepare even if
    it's a constant one. The flag is switched off in the end of
5396
    mysqld_stmt_prepare.
5397
  */
unknown's avatar
unknown committed
5398
  if (thd->stmt_arena->is_stmt_prepare())
5399
    select_lex->uncacheable|= UNCACHEABLE_PREPARE;
unknown's avatar
unknown committed
5400 5401
  if (move_down)
  {
unknown's avatar
unknown committed
5402
    SELECT_LEX_UNIT *unit;
5403
    lex->subqueries= TRUE;
unknown's avatar
unknown committed
5404
    /* first select_lex of subselect or derived table */
5405
    if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
unknown's avatar
unknown committed
5406
      DBUG_RETURN(1);
unknown's avatar
unknown committed
5407

unknown's avatar
unknown committed
5408 5409
    unit->init_query();
    unit->init_select();
5410
    unit->thd= thd;
unknown's avatar
unknown committed
5411
    unit->include_down(lex->current_select);
unknown's avatar
unknown committed
5412 5413
    unit->link_next= 0;
    unit->link_prev= 0;
5414
    unit->return_to= lex->current_select;
unknown's avatar
unknown committed
5415
    select_lex->include_down(unit);
5416 5417 5418 5419 5420
    /*
      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;
unknown's avatar
unknown committed
5421 5422
  }
  else
unknown's avatar
unknown committed
5423
  {
unknown's avatar
VIEW  
unknown committed
5424 5425
    if (lex->current_select->order_list.first && !lex->current_select->braces)
    {
unknown's avatar
unknown committed
5426
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY");
unknown's avatar
unknown committed
5427
      DBUG_RETURN(1);
unknown's avatar
VIEW  
unknown committed
5428
    }
5429
    select_lex->include_neighbour(lex->current_select);
5430 5431 5432 5433 5434
    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;
unknown's avatar
unknown committed
5435
  }
unknown's avatar
unknown committed
5436

5437
  select_lex->master_unit()->global_parameters= select_lex;
5438
  select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
5439
  lex->current_select= select_lex;
5440 5441 5442 5443 5444
  /*
    in subquery is SELECT query and we allow resolution of names in SELECT
    list
  */
  select_lex->context.resolve_in_select_list= TRUE;
unknown's avatar
unknown committed
5445
  DBUG_RETURN(0);
5446
}
unknown's avatar
unknown committed
5447

unknown's avatar
unknown committed
5448
/**
5449 5450
  Create a select to return the same output as 'SELECT @@var_name'.

unknown's avatar
unknown committed
5451
  Used for SHOW COUNT(*) [ WARNINGS | ERROR].
5452

unknown's avatar
unknown committed
5453
  This will crash with a core dump if the variable doesn't exists.
5454

unknown's avatar
unknown committed
5455
  @param var_name		Variable name
5456 5457 5458 5459
*/

void create_select_for_variable(const char *var_name)
{
5460
  THD *thd;
5461
  LEX *lex;
5462
  LEX_STRING tmp, null_lex_string;
5463 5464
  Item *var;
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
5465
  DBUG_ENTER("create_select_for_variable");
5466 5467

  thd= current_thd;
unknown's avatar
unknown committed
5468
  lex= thd->lex;
5469 5470 5471 5472
  mysql_init_select(lex);
  lex->sql_command= SQLCOM_SELECT;
  tmp.str= (char*) var_name;
  tmp.length=strlen(var_name);
5473
  bzero((char*) &null_lex_string.str, sizeof(null_lex_string));
5474 5475 5476 5477
  /*
    We set the name of Item to @@session.var_name because that then is used
    as the column name in the output.
  */
unknown's avatar
unknown committed
5478 5479 5480 5481 5482 5483
  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);
  }
5484 5485 5486
  DBUG_VOID_RETURN;
}

5487

unknown's avatar
unknown committed
5488 5489
void mysql_init_multi_delete(LEX *lex)
{
unknown's avatar
unknown committed
5490
  lex->sql_command=  SQLCOM_DELETE_MULTI;
unknown's avatar
unknown committed
5491
  mysql_init_select(lex);
5492 5493
  lex->select_lex.select_limit= 0;
  lex->unit.select_limit_cnt= HA_POS_ERROR;
unknown's avatar
unknown committed
5494
  lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list);
5495
  lex->lock_option= TL_READ_DEFAULT;
unknown's avatar
VIEW  
unknown committed
5496 5497
  lex->query_tables= 0;
  lex->query_tables_last= &lex->query_tables;
unknown's avatar
unknown committed
5498
}
unknown's avatar
unknown committed
5499

5500

5501 5502 5503 5504
/*
  When you modify mysql_parse(), you may need to mofify
  mysql_test_parse_for_slave() in this same file.
*/
unknown's avatar
unknown committed
5505

5506 5507
/**
  Parse a query.
unknown's avatar
unknown committed
5508 5509 5510 5511 5512 5513

  @param       thd     Current thread
  @param       inBuf   Begining of the query text
  @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.
5514 5515 5516 5517
*/

void mysql_parse(THD *thd, const char *inBuf, uint length,
                 const char ** found_semicolon)
unknown's avatar
unknown committed
5518
{
5519
  int error;
unknown's avatar
unknown committed
5520
  DBUG_ENTER("mysql_parse");
5521 5522 5523

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

5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541
  /*
    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);
5542

5543
  if (query_cache_send_result_to_client(thd, (char*) inBuf, length) <= 0)
unknown's avatar
unknown committed
5544
  {
unknown's avatar
unknown committed
5545
    LEX *lex= thd->lex;
5546

5547
    Parser_state parser_state(thd, inBuf, length);
5548

5549
    bool err= parse_sql(thd, & parser_state, NULL);
5550
    *found_semicolon= parser_state.m_lip.found_semicolon;
5551

5552
    if (!err)
unknown's avatar
unknown committed
5553
    {
unknown's avatar
unknown committed
5554
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5555
      if (mqh_used && thd->user_connect &&
5556
	  check_mqh(thd, lex->sql_command))
5557 5558 5559 5560
      {
	thd->net.error = 0;
      }
      else
unknown's avatar
unknown committed
5561
#endif
5562
      {
5563
	if (! thd->is_error())
unknown's avatar
unknown committed
5564
	{
5565 5566 5567 5568 5569 5570 5571 5572 5573 5574
          /*
            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.
          */
5575 5576 5577 5578
          if (*found_semicolon && (ulong) (*found_semicolon - thd->query()))
            thd->set_query_inner(thd->query(),
                                 (uint32) (*found_semicolon -
                                           thd->query() - 1));
5579
          /* Actually execute the query */
5580 5581 5582 5583 5584
          if (*found_semicolon)
          {
            lex->safe_to_cache_query= 0;
            thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
          }
5585
          lex->set_trg_event_type_for_tables();
5586
          MYSQL_QUERY_EXEC_START(thd->query(),
5587 5588 5589 5590 5591 5592 5593 5594
                                 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);
unknown's avatar
unknown committed
5595
	}
5596
      }
unknown's avatar
unknown committed
5597 5598
    }
    else
5599
    {
5600
      DBUG_ASSERT(thd->is_error());
5601
      DBUG_PRINT("info",("Command aborted. Fatal_error: %d",
5602
			 thd->is_fatal_error));
5603

5604
      query_cache_abort(&thd->query_cache_tls);
5605
    }
5606 5607 5608 5609 5610 5611
    if (thd->lex->sphead)
    {
      delete thd->lex->sphead;
      thd->lex->sphead= 0;
    }
    lex->unit.cleanup();
5612
    thd_proc_info(thd, "freeing items");
5613
    thd->end_statement();
5614
    thd->cleanup_after_query();
5615
    DBUG_ASSERT(thd->change_list.is_empty());
unknown's avatar
unknown committed
5616
  }
5617 5618 5619 5620 5621 5622
  else
  {
    /* There are no multi queries in the cache. */
    *found_semicolon= NULL;
  }

unknown's avatar
unknown committed
5623 5624 5625 5626
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
5627
#ifdef HAVE_REPLICATION
5628 5629 5630 5631
/*
  Usable by the replication SQL thread only: just parse a query to know if it
  can be ignored because of replicate-*-table rules.

unknown's avatar
unknown committed
5632
  @retval
5633
    0	cannot be ignored
unknown's avatar
unknown committed
5634
  @retval
5635 5636 5637 5638 5639
    1	can be ignored
*/

bool mysql_test_parse_for_slave(THD *thd, char *inBuf, uint length)
{
unknown's avatar
unknown committed
5640
  LEX *lex= thd->lex;
5641
  bool error= 0;
unknown's avatar
unknown committed
5642
  DBUG_ENTER("mysql_test_parse_for_slave");
5643

5644
  Parser_state parser_state(thd, inBuf, length);
5645 5646 5647
  lex_start(thd);
  mysql_reset_thd_for_next_command(thd);

5648
  if (!parse_sql(thd, & parser_state, NULL) &&
5649
      all_tables_not_ok(thd,(TABLE_LIST*) lex->select_lex.table_list.first))
unknown's avatar
unknown committed
5650
    error= 1;                  /* Ignore question */
5651
  thd->end_statement();
5652
  thd->cleanup_after_query();
unknown's avatar
unknown committed
5653
  DBUG_RETURN(error);
5654
}
unknown's avatar
unknown committed
5655
#endif
unknown's avatar
unknown committed
5656

5657

unknown's avatar
unknown committed
5658

unknown's avatar
unknown committed
5659 5660 5661 5662 5663 5664
/**
  Store field definition for create.

  @return
    Return 0 if ok
*/
unknown's avatar
unknown committed
5665

5666
bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum_field_types type,
unknown's avatar
unknown committed
5667
		       char *length, char *decimals,
5668
		       uint type_modifier,
5669 5670
		       Item *default_value, Item *on_update_value,
                       LEX_STRING *comment,
5671 5672
		       char *change,
                       List<String> *interval_list, CHARSET_INFO *cs,
unknown's avatar
unknown committed
5673
		       uint uint_geom_type)
unknown's avatar
unknown committed
5674
{
unknown's avatar
unknown committed
5675
  register Create_field *new_field;
unknown's avatar
unknown committed
5676
  LEX  *lex= thd->lex;
unknown's avatar
unknown committed
5677 5678
  DBUG_ENTER("add_field_to_list");

5679 5680
  if (check_string_char_length(field_name, "", NAME_CHAR_LEN,
                               system_charset_info, 1))
unknown's avatar
unknown committed
5681
  {
5682
    my_error(ER_TOO_LONG_IDENT, MYF(0), field_name->str); /* purecov: inspected */
unknown's avatar
unknown committed
5683 5684 5685 5686
    DBUG_RETURN(1);				/* purecov: inspected */
  }
  if (type_modifier & PRI_KEY_FLAG)
  {
5687
    Key *key;
5688 5689
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
    key= new Key(Key::PRIMARY, null_lex_str,
5690 5691 5692
                      &default_key_create_info,
                      0, lex->col_list);
    lex->alter_info.key_list.push_back(key);
unknown's avatar
unknown committed
5693 5694 5695 5696
    lex->col_list.empty();
  }
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
  {
5697
    Key *key;
5698 5699
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
    key= new Key(Key::UNIQUE, null_lex_str,
5700 5701 5702
                 &default_key_create_info, 0,
                 lex->col_list);
    lex->alter_info.key_list.push_back(key);
unknown's avatar
unknown committed
5703 5704 5705
    lex->col_list.empty();
  }

5706
  if (default_value)
unknown's avatar
unknown committed
5707
  {
5708
    /* 
unknown's avatar
unknown committed
5709 5710
      Default value should be literal => basic constants =>
      no need fix_fields()
5711 5712 5713
      
      We allow only one function as part of default value - 
      NOW() as default for TIMESTAMP type.
5714
    */
5715 5716
    if (default_value->type() == Item::FUNC_ITEM && 
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
5717
         type == MYSQL_TYPE_TIMESTAMP))
5718
    {
5719
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
5720 5721 5722
      DBUG_RETURN(1);
    }
    else if (default_value->type() == Item::NULL_ITEM)
unknown's avatar
unknown committed
5723
    {
5724
      default_value= 0;
5725 5726 5727
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
	  NOT_NULL_FLAG)
      {
5728
	my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
5729 5730 5731 5732 5733
	DBUG_RETURN(1);
      }
    }
    else if (type_modifier & AUTO_INCREMENT_FLAG)
    {
5734
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
unknown's avatar
unknown committed
5735 5736 5737
      DBUG_RETURN(1);
    }
  }
5738

5739
  if (on_update_value && type != MYSQL_TYPE_TIMESTAMP)
5740
  {
5741
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
5742 5743
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
5744

unknown's avatar
unknown committed
5745
  if (!(new_field= new Create_field()) ||
5746
      new_field->init(thd, field_name->str, type, length, decimals, type_modifier,
5747 5748
                      default_value, on_update_value, comment, change,
                      interval_list, cs, uint_geom_type))
unknown's avatar
unknown committed
5749
    DBUG_RETURN(1);
unknown's avatar
unknown committed
5750

5751
  lex->alter_info.create_list.push_back(new_field);
unknown's avatar
unknown committed
5752 5753 5754 5755
  lex->last_field=new_field;
  DBUG_RETURN(0);
}

5756

unknown's avatar
unknown committed
5757
/** Store position for column in ALTER TABLE .. ADD column. */
unknown's avatar
unknown committed
5758 5759 5760

void store_position_for_column(const char *name)
{
5761
  current_thd->lex->last_field->after=my_const_cast(char*) (name);
unknown's avatar
unknown committed
5762 5763 5764
}

bool
unknown's avatar
unknown committed
5765
add_proc_to_list(THD* thd, Item *item)
unknown's avatar
unknown committed
5766 5767 5768 5769
{
  ORDER *order;
  Item	**item_ptr;

unknown's avatar
unknown committed
5770
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*))))
unknown's avatar
unknown committed
5771 5772 5773 5774 5775
    return 1;
  item_ptr = (Item**) (order+1);
  *item_ptr= item;
  order->item=item_ptr;
  order->free_me=0;
5776
  thd->lex->proc_list.link_in_list((uchar*) order,(uchar**) &order->next);
unknown's avatar
unknown committed
5777 5778 5779 5780
  return 0;
}


unknown's avatar
unknown committed
5781 5782 5783
/**
  save order by and tables in own lists.
*/
unknown's avatar
unknown committed
5784

unknown's avatar
unknown committed
5785
bool add_to_list(THD *thd, SQL_LIST &list,Item *item,bool asc)
unknown's avatar
unknown committed
5786 5787 5788
{
  ORDER *order;
  DBUG_ENTER("add_to_list");
unknown's avatar
unknown committed
5789
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER))))
unknown's avatar
unknown committed
5790
    DBUG_RETURN(1);
unknown's avatar
unknown committed
5791 5792
  order->item_ptr= item;
  order->item= &order->item_ptr;
unknown's avatar
unknown committed
5793 5794 5795
  order->asc = asc;
  order->free_me=0;
  order->used=0;
5796
  order->counter_used= 0;
5797
  list.link_in_list((uchar*) order,(uchar**) &order->next);
unknown's avatar
unknown committed
5798 5799 5800 5801
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815
/**
  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
  @param use_index	List of indexed used in USE INDEX
  @param ignore_index	List of indexed used in IGNORE INDEX

  @retval
unknown's avatar
unknown committed
5816
      0		Error
unknown's avatar
unknown committed
5817 5818
  @retval
    \#	Pointer to TABLE_LIST element added to the total table list
unknown's avatar
unknown committed
5819 5820
*/

unknown's avatar
unknown committed
5821 5822
TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
					     Table_ident *table,
5823
					     LEX_STRING *alias,
unknown's avatar
unknown committed
5824 5825
					     ulong table_options,
					     thr_lock_type lock_type,
unknown's avatar
unknown committed
5826
					     List<Index_hint> *index_hints_arg,
unknown's avatar
unknown committed
5827
                                             LEX_STRING *option)
unknown's avatar
unknown committed
5828 5829
{
  register TABLE_LIST *ptr;
unknown's avatar
unknown committed
5830
  TABLE_LIST *previous_table_ref; /* The table preceding the current one. */
unknown's avatar
unknown committed
5831
  char *alias_str;
5832
  LEX *lex= thd->lex;
unknown's avatar
unknown committed
5833
  DBUG_ENTER("add_table_to_list");
5834
  LINT_INIT(previous_table_ref);
unknown's avatar
unknown committed
5835 5836 5837 5838

  if (!table)
    DBUG_RETURN(0);				// End of memory
  alias_str= alias ? alias->str : table->table.str;
5839 5840
  if (!test(table_options & TL_OPTION_ALIAS) && 
      check_table_name(table->table.str, table->table.length))
unknown's avatar
unknown committed
5841
  {
5842
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
unknown's avatar
unknown committed
5843 5844
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
5845 5846

  if (table->is_derived_table() == FALSE && table->db.str &&
5847
      check_db_name(&table->db))
unknown's avatar
unknown committed
5848 5849 5850 5851
  {
    my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
5852 5853

  if (!alias)					/* Alias is case sensitive */
5854 5855 5856
  {
    if (table->sel)
    {
unknown's avatar
unknown committed
5857 5858
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
                 ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
5859 5860
      DBUG_RETURN(0);
    }
5861
    if (!(alias_str= (char*) thd->memdup(alias_str,table->table.length+1)))
unknown's avatar
unknown committed
5862
      DBUG_RETURN(0);
5863
  }
unknown's avatar
unknown committed
5864
  if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST))))
unknown's avatar
unknown committed
5865
    DBUG_RETURN(0);				/* purecov: inspected */
unknown's avatar
unknown committed
5866
  if (table->db.str)
5867
  {
5868
    ptr->is_fqtn= TRUE;
5869 5870 5871
    ptr->db= table->db.str;
    ptr->db_length= table->db.length;
  }
5872
  else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
unknown's avatar
unknown committed
5873
    DBUG_RETURN(0);
5874 5875
  else
    ptr->is_fqtn= FALSE;
unknown's avatar
unknown committed
5876

5877
  ptr->alias= alias_str;
5878
  ptr->is_alias= alias ? TRUE : FALSE;
5879
  if (lower_case_table_names && table->table.length)
5880
    table->table.length= my_casedn_str(files_charset_info, table->table.str);
5881 5882
  ptr->table_name=table->table.str;
  ptr->table_name_length=table->table.length;
5883
  ptr->lock_type=   lock_type;
unknown's avatar
unknown committed
5884
  ptr->updating=    test(table_options & TL_OPTION_UPDATING);
5885
  /* TODO: remove TL_OPTION_FORCE_INDEX as it looks like it's not used */
unknown's avatar
unknown committed
5886
  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
unknown's avatar
unknown committed
5887
  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
5888
  ptr->derived=	    table->sel;
5889
  if (!ptr->derived && !my_strcasecmp(system_charset_info, ptr->db,
5890
                                      INFORMATION_SCHEMA_NAME.str))
5891
  {
5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904
    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);
5905 5906
    if (!schema_table ||
        (schema_table->hidden && 
unknown's avatar
unknown committed
5907
         ((sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0 || 
5908 5909 5910
          /*
            this check is used for show columns|keys from I_S hidden table
          */
unknown's avatar
unknown committed
5911 5912
          lex->sql_command == SQLCOM_SHOW_FIELDS ||
          lex->sql_command == SQLCOM_SHOW_KEYS)))
5913
    {
unknown's avatar
unknown committed
5914
      my_error(ER_UNKNOWN_TABLE, MYF(0),
5915
               ptr->table_name, INFORMATION_SCHEMA_NAME.str);
5916 5917
      DBUG_RETURN(0);
    }
5918
    ptr->schema_table_name= ptr->table_name;
5919 5920
    ptr->schema_table= schema_table;
  }
5921
  ptr->select_lex=  lex->current_select;
unknown's avatar
unknown committed
5922
  ptr->cacheable_table= 1;
5923
  ptr->index_hints= index_hints_arg;
unknown's avatar
unknown committed
5924
  ptr->option= option ? option->str : 0;
unknown's avatar
unknown committed
5925
  /* check that used name is unique */
5926
  if (lock_type != TL_IGNORE)
unknown's avatar
unknown committed
5927
  {
unknown's avatar
unknown committed
5928 5929 5930 5931
    TABLE_LIST *first_table= (TABLE_LIST*) table_list.first;
    if (lex->sql_command == SQLCOM_CREATE_VIEW)
      first_table= first_table ? first_table->next_local : NULL;
    for (TABLE_LIST *tables= first_table ;
unknown's avatar
unknown committed
5932
	 tables ;
unknown's avatar
VIEW  
unknown committed
5933
	 tables=tables->next_local)
unknown's avatar
unknown committed
5934
    {
5935 5936
      if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
	  !strcmp(ptr->db, tables->db))
unknown's avatar
unknown committed
5937
      {
5938
	my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
unknown's avatar
unknown committed
5939 5940
	DBUG_RETURN(0);				/* purecov: tested */
      }
unknown's avatar
unknown committed
5941 5942
    }
  }
unknown's avatar
unknown committed
5943 5944 5945
  /* Store the table reference preceding the current one. */
  if (table_list.elements > 0)
  {
5946 5947 5948
    /*
      table_list.next points to the last inserted TABLE_LIST->next_local'
      element
5949
      We don't use the offsetof() macro here to avoid warnings from gcc
5950
    */
5951 5952 5953
    previous_table_ref= (TABLE_LIST*) ((char*) table_list.next -
                                       ((char*) &(ptr->next_local) -
                                        (char*) ptr));
5954 5955 5956 5957 5958 5959 5960 5961
    /*
      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;
unknown's avatar
unknown committed
5962
  }
5963

unknown's avatar
unknown committed
5964 5965 5966 5967 5968 5969
  /*
    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'.
  */
5970
  table_list.link_in_list((uchar*) ptr, (uchar**) &ptr->next_local);
unknown's avatar
unknown committed
5971
  ptr->next_name_resolution_table= NULL;
5972
  /* Link table in global list (all used tables) */
5973
  lex->add_to_query_tables(ptr);
Konstantin Osipov's avatar
Konstantin Osipov committed
5974
  ptr->mdl_request.init(MDL_key::TABLE, ptr->db, ptr->table_name, MDL_SHARED);
unknown's avatar
unknown committed
5975 5976 5977
  DBUG_RETURN(ptr);
}

unknown's avatar
unknown committed
5978

unknown's avatar
unknown committed
5979 5980
/**
  Initialize a new table list for a nested join.
5981

5982 5983 5984 5985 5986 5987 5988 5989
    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.

unknown's avatar
unknown committed
5990 5991 5992 5993 5994 5995
  @param thd         current thread

  @retval
    0   if success
  @retval
    1   otherwise
5996 5997 5998 5999 6000 6001 6002
*/

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

6004 6005
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
6006
    DBUG_RETURN(1);
6007
  nested_join= ptr->nested_join=
6008
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
6009

6010 6011 6012
  join_list->push_front(ptr);
  ptr->embedding= embedding;
  ptr->join_list= join_list;
6013
  ptr->alias= (char*) "(nested_join)";
6014 6015 6016 6017 6018 6019 6020
  embedding= ptr;
  join_list= &nested_join->join_list;
  join_list->empty();
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
6021 6022
/**
  End a nested join table list.
6023 6024 6025

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

unknown's avatar
unknown committed
6028 6029 6030 6031 6032
  @param thd         current thread

  @return
    - Pointer to TABLE_LIST element added to the total table list, if success
    - 0, otherwise
6033 6034 6035 6036 6037
*/

TABLE_LIST *st_select_lex::end_nested_join(THD *thd)
{
  TABLE_LIST *ptr;
6038
  NESTED_JOIN *nested_join;
6039
  DBUG_ENTER("end_nested_join");
6040

unknown's avatar
unknown committed
6041
  DBUG_ASSERT(embedding);
6042 6043 6044
  ptr= embedding;
  join_list= ptr->join_list;
  embedding= ptr->embedding;
6045
  nested_join= ptr->nested_join;
6046 6047 6048 6049 6050 6051 6052 6053 6054
  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;
  }
6055
  else if (nested_join->join_list.elements == 0)
unknown's avatar
unknown committed
6056 6057
  {
    join_list->pop();
6058
    ptr= 0;                                     // return value
unknown's avatar
unknown committed
6059
  }
6060 6061 6062 6063
  DBUG_RETURN(ptr);
}


unknown's avatar
unknown committed
6064 6065
/**
  Nest last join operation.
6066 6067 6068

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

unknown's avatar
unknown committed
6069
  @param thd         current thread
6070

unknown's avatar
unknown committed
6071
  @retval
6072
    0  Error
unknown's avatar
unknown committed
6073 6074
  @retval
    \#  Pointer to TABLE_LIST element created for the new nested join
6075 6076 6077 6078 6079 6080
*/

TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
6081
  List<TABLE_LIST> *embedded_list;
6082
  DBUG_ENTER("nest_last_join");
6083

6084 6085
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
6086
    DBUG_RETURN(0);
6087
  nested_join= ptr->nested_join=
6088
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
6089

6090 6091
  ptr->embedding= embedding;
  ptr->join_list= join_list;
6092
  ptr->alias= (char*) "(nest_last_join)";
6093
  embedded_list= &nested_join->join_list;
6094
  embedded_list->empty();
6095 6096

  for (uint i=0; i < 2; i++)
6097 6098 6099 6100 6101
  {
    TABLE_LIST *table= join_list->pop();
    table->join_list= embedded_list;
    table->embedding= ptr;
    embedded_list->push_back(table);
unknown's avatar
unknown committed
6102 6103 6104 6105 6106 6107 6108
    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.
      */
unknown's avatar
unknown committed
6109 6110
      if (prev_join_using)
        ptr->join_using_fields= prev_join_using;
unknown's avatar
unknown committed
6111
    }
6112 6113 6114 6115 6116 6117 6118
  }
  join_list->push_front(ptr);
  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
  DBUG_RETURN(ptr);
}


unknown's avatar
unknown committed
6119 6120
/**
  Add a table to the current join list.
6121 6122 6123 6124 6125 6126

    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).

unknown's avatar
unknown committed
6127 6128 6129
  @param table       the table to add

  @return
6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142
    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;
}


unknown's avatar
unknown committed
6143 6144
/**
  Convert a right join into equivalent left join.
6145 6146

    The function takes the current join list t[0],t[1] ... and
6147 6148 6149 6150 6151 6152
    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
unknown's avatar
unknown committed
6153
  @verbatim
6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164
    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
unknown's avatar
unknown committed
6165
   @endverbatim
6166

unknown's avatar
unknown committed
6167
  @param thd         current thread
6168

unknown's avatar
unknown committed
6169 6170 6171
  @return
    - Pointer to the table representing the inner table, if success
    - 0, otherwise
6172 6173
*/

6174
TABLE_LIST *st_select_lex::convert_right_join()
6175 6176
{
  TABLE_LIST *tab2= join_list->pop();
6177
  TABLE_LIST *tab1= join_list->pop();
6178 6179 6180 6181 6182 6183 6184 6185 6186
  DBUG_ENTER("convert_right_join");

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

  DBUG_RETURN(tab1);
}

unknown's avatar
unknown committed
6187 6188
/**
  Set lock for all tables in current select level.
unknown's avatar
unknown committed
6189

unknown's avatar
unknown committed
6190
  @param lock_type			Lock to set for tables
unknown's avatar
unknown committed
6191

unknown's avatar
unknown committed
6192
  @note
unknown's avatar
unknown committed
6193 6194 6195 6196 6197
    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
*/

unknown's avatar
unknown committed
6198
void st_select_lex::set_lock_for_tables(thr_lock_type lock_type)
unknown's avatar
unknown committed
6199 6200 6201 6202 6203
{
  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));
unknown's avatar
VIEW  
unknown committed
6204 6205 6206
  for (TABLE_LIST *tables= (TABLE_LIST*) table_list.first;
       tables;
       tables= tables->next_local)
unknown's avatar
unknown committed
6207 6208 6209 6210 6211 6212 6213
  {
    tables->lock_type= lock_type;
    tables->updating=  for_update;
  }
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
6214

unknown's avatar
unknown committed
6215 6216
/**
  Create a fake SELECT_LEX for a unit.
unknown's avatar
unknown committed
6217 6218 6219 6220

    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
unknown's avatar
unknown committed
6221
    @verbatim
unknown's avatar
unknown committed
6222
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ... 
unknown's avatar
unknown committed
6223
    @endvarbatim
unknown's avatar
unknown committed
6224
    or of the form
unknown's avatar
unknown committed
6225
    @varbatim
unknown's avatar
unknown committed
6226
    (SELECT ... ORDER BY LIMIT n) ORDER BY ...
unknown's avatar
unknown committed
6227
    @endvarbatim
unknown's avatar
unknown committed
6228
  
unknown's avatar
unknown committed
6229 6230 6231
  @param thd_arg		   thread handle

  @note
unknown's avatar
unknown committed
6232 6233 6234
    The object is used to retrieve rows from the temporary table
    where the result on the union is obtained.

unknown's avatar
unknown committed
6235
  @retval
unknown's avatar
unknown committed
6236
    1     on failure to create the object
unknown's avatar
unknown committed
6237
  @retval
unknown's avatar
unknown committed
6238 6239 6240
    0     on success
*/

unknown's avatar
unknown committed
6241
bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg)
unknown's avatar
unknown committed
6242 6243 6244 6245
{
  SELECT_LEX *first_sl= first_select();
  DBUG_ENTER("add_fake_select_lex");
  DBUG_ASSERT(!fake_select_lex);
unknown's avatar
unknown committed
6246

unknown's avatar
unknown committed
6247
  if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX()))
unknown's avatar
unknown committed
6248 6249 6250 6251
      DBUG_RETURN(1);
  fake_select_lex->include_standalone(this, 
                                      (SELECT_LEX_NODE**)&fake_select_lex);
  fake_select_lex->select_number= INT_MAX;
unknown's avatar
unknown committed
6252
  fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */
unknown's avatar
unknown committed
6253 6254
  fake_select_lex->make_empty_select();
  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
6255 6256
  fake_select_lex->select_limit= 0;

unknown's avatar
unknown committed
6257
  fake_select_lex->context.outer_context=first_sl->context.outer_context;
6258 6259 6260
  /* 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;
unknown's avatar
unknown committed
6261

6262
  if (!is_union())
unknown's avatar
unknown committed
6263 6264 6265 6266 6267 6268 6269 6270 6271
  {
    /* 
      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;
unknown's avatar
unknown committed
6272
    thd_arg->lex->current_select= fake_select_lex;
unknown's avatar
unknown committed
6273
  }
unknown's avatar
unknown committed
6274
  thd_arg->lex->pop_context();
unknown's avatar
unknown committed
6275 6276 6277
  DBUG_RETURN(0);
}

6278

unknown's avatar
unknown committed
6279
/**
6280 6281
  Push a new name resolution context for a JOIN ... ON clause to the
  context stack of a query block.
unknown's avatar
unknown committed
6282 6283

    Create a new name resolution context for a JOIN ... ON clause,
6284 6285 6286
    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.
unknown's avatar
unknown committed
6287

unknown's avatar
unknown committed
6288 6289 6290 6291 6292
  @param thd       pointer to current thread
  @param left_op   left  operand of the JOIN
  @param right_op  rigth operand of the JOIN

  @retval
6293
    FALSE  if all is OK
unknown's avatar
unknown committed
6294
  @retval
6295
    TRUE   if a memory allocation error occured
unknown's avatar
unknown committed
6296 6297
*/

6298 6299 6300
bool
push_new_name_resolution_context(THD *thd,
                                 TABLE_LIST *left_op, TABLE_LIST *right_op)
unknown's avatar
unknown committed
6301 6302
{
  Name_resolution_context *on_context;
6303
  if (!(on_context= new (thd->mem_root) Name_resolution_context))
6304
    return TRUE;
unknown's avatar
unknown committed
6305 6306 6307 6308 6309
  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();
6310
  return thd->lex->push_context(on_context);
unknown's avatar
unknown committed
6311 6312 6313
}


unknown's avatar
unknown committed
6314
/**
unknown's avatar
unknown committed
6315 6316 6317 6318
  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.

unknown's avatar
unknown committed
6319 6320
  @param b     the second operand of a JOIN ... ON
  @param expr  the condition to be added to the ON clause
unknown's avatar
unknown committed
6321

unknown's avatar
unknown committed
6322
  @retval
unknown's avatar
unknown committed
6323
    FALSE  if there was some error
unknown's avatar
unknown committed
6324
  @retval
unknown's avatar
unknown committed
6325 6326 6327 6328
    TRUE   if all is OK
*/

void add_join_on(TABLE_LIST *b, Item *expr)
unknown's avatar
unknown committed
6329
{
6330
  if (expr)
6331
  {
6332
    if (!b->on_expr)
unknown's avatar
unknown committed
6333
      b->on_expr= expr;
6334 6335
    else
    {
unknown's avatar
unknown committed
6336 6337 6338 6339 6340 6341
      /*
        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);
6342 6343
    }
    b->on_expr->top_level_item();
6344
  }
unknown's avatar
unknown committed
6345 6346 6347
}


unknown's avatar
unknown committed
6348
/**
unknown's avatar
unknown committed
6349 6350
  Mark that there is a NATURAL JOIN or JOIN ... USING between two
  tables.
6351

unknown's avatar
unknown committed
6352 6353 6354 6355 6356 6357 6358 6359 6360 6361
    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
unknown's avatar
unknown committed
6362
  @verbatim
6363 6364 6365
    SELECT * FROM t1 NATURAL LEFT JOIN t2
     <=>
    SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
unknown's avatar
unknown committed
6366

unknown's avatar
unknown committed
6367 6368 6369
    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>)
unknown's avatar
unknown committed
6370

unknown's avatar
unknown committed
6371 6372 6373
    SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
     <=>
    SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
unknown's avatar
unknown committed
6374 6375 6376 6377 6378
   @endverbatim

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

unknown's avatar
unknown committed
6381 6382
void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields,
                      SELECT_LEX *lex)
unknown's avatar
unknown committed
6383
{
unknown's avatar
unknown committed
6384
  b->natural_join= a;
unknown's avatar
unknown committed
6385
  lex->prev_join_using= using_fields;
unknown's avatar
unknown committed
6386 6387
}

unknown's avatar
unknown committed
6388

6389
/**
6390 6391
  Reload/resets privileges and the different caches.

6392 6393 6394 6395
  @param thd Thread handler (can be NULL!)
  @param options What should be reset/reloaded (tables, privileges, slave...)
  @param tables Tables to flush (if any)
  @param write_to_binlog True if we can write to the binlog.
6396
               
6397 6398 6399 6400 6401 6402 6403 6404
  @note Depending on 'options', it may be very bad to write the
    query to the binlog (e.g. FLUSH SLAVE); this is a
    pointer where reload_acl_and_cache() will put 0 if
    it thinks we really should not write to the binlog.
    Otherwise it will put 1.

  @return Error status code
    @retval 0 Ok
6405
    @retval !=0  Error; thd->killed is set or thd->is_error() is true
6406 6407
*/

6408 6409
bool reload_acl_and_cache(THD *thd, ulong options, TABLE_LIST *tables,
                          bool *write_to_binlog)
unknown's avatar
unknown committed
6410 6411 6412
{
  bool result=0;
  select_errors=0;				/* Write if more errors */
6413
  bool tmp_write_to_binlog= 1;
6414

6415
  DBUG_ASSERT(!thd || !thd->in_sub_stmt);
6416

unknown's avatar
SCRUM  
unknown committed
6417
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
6418 6419
  if (options & REFRESH_GRANT)
  {
6420 6421 6422 6423 6424 6425
    THD *tmp_thd= 0;
    /*
      If reload_acl_and_cache() is called from SIGHUP handler we have to
      allocate temporary THD for execution of acl_reload()/grant_reload().
    */
    if (!thd && (thd= (tmp_thd= new THD)))
6426 6427
    {
      thd->thread_stack= (char*) &tmp_thd;
6428
      thd->store_globals();
6429
    }
6430
    
6431 6432
    if (thd)
    {
6433 6434
      bool reload_acl_failed= acl_reload(thd);
      bool reload_grants_failed= grant_reload(thd);
Kristofer Pettersson's avatar
Kristofer Pettersson committed
6435 6436 6437
      bool reload_servers_failed= servers_reload(thd);
      
      if (reload_acl_failed || reload_grants_failed || reload_servers_failed)
6438
      {
6439
        result= 1;
6440 6441 6442 6443 6444 6445
        /*
          When an error is returned, my_message may have not been called and
          the client will hang waiting for a response.
        */
        my_error(ER_UNKNOWN_ERROR, MYF(0), "FLUSH PRIVILEGES failed");
      }
6446
    }
6447

6448 6449 6450 6451 6452 6453 6454
    if (tmp_thd)
    {
      delete tmp_thd;
      /* Remember that we don't have a THD */
      my_pthread_setspecific_ptr(THR_THD,  0);
      thd= 0;
    }
6455
    reset_mqh((LEX_USER *)NULL, TRUE);
unknown's avatar
unknown committed
6456
  }
unknown's avatar
SCRUM  
unknown committed
6457
#endif
unknown's avatar
unknown committed
6458 6459
  if (options & REFRESH_LOG)
  {
6460
    /*
unknown's avatar
unknown committed
6461
      Flush the normal query log, the update log, the binary log,
unknown's avatar
unknown committed
6462 6463
      the slow query log, the relay log (if it exists) and the log
      tables.
6464
    */
unknown's avatar
unknown committed
6465

6466
    /*
unknown's avatar
unknown committed
6467 6468 6469 6470
      Writing this command to the binlog may result in infinite loops
      when doing mysqlbinlog|mysql, and anyway it does not really make
      sense to log it automatically (would cause more trouble to users
      than it would help them)
6471 6472
    */
    tmp_write_to_binlog= 0;
6473 6474 6475 6476
    if( mysql_bin_log.is_open() )
    {
      mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
    }
unknown's avatar
unknown committed
6477
#ifdef HAVE_REPLICATION
6478
    pthread_mutex_lock(&LOCK_active_mi);
6479
    rotate_relay_log(active_mi);
6480
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
6481
#endif
unknown's avatar
unknown committed
6482 6483 6484 6485 6486

    /* flush slow and general logs */
    logger.flush_logs(thd);

    if (ha_flush_logs(NULL))
unknown's avatar
unknown committed
6487
      result=1;
unknown's avatar
unknown committed
6488 6489
    if (flush_error_log())
      result=1;
unknown's avatar
unknown committed
6490
  }
unknown's avatar
unknown committed
6491
#ifdef HAVE_QUERY_CACHE
unknown's avatar
unknown committed
6492 6493
  if (options & REFRESH_QUERY_CACHE_FREE)
  {
unknown's avatar
unknown committed
6494
    query_cache.pack();				// FLUSH QUERY CACHE
6495
    options &= ~REFRESH_QUERY_CACHE;    // Don't flush cache, just free memory
unknown's avatar
unknown committed
6496 6497 6498
  }
  if (options & (REFRESH_TABLES | REFRESH_QUERY_CACHE))
  {
unknown's avatar
unknown committed
6499
    query_cache.flush();			// RESET QUERY CACHE
unknown's avatar
unknown committed
6500
  }
unknown's avatar
unknown committed
6501
#endif /*HAVE_QUERY_CACHE*/
6502

6503 6504 6505
  DBUG_ASSERT(!thd || thd->locked_tables_mode ||
              !thd->mdl_context.has_locks() ||
              thd->handler_tables_hash.records);
6506

6507 6508 6509 6510 6511
  /*
    Note that if REFRESH_READ_LOCK bit is set then REFRESH_TABLES is set too
    (see sql_yacc.yy)
  */
  if (options & (REFRESH_TABLES | REFRESH_READ_LOCK)) 
unknown's avatar
unknown committed
6512
  {
6513
    if ((options & REFRESH_READ_LOCK) && thd)
unknown's avatar
unknown committed
6514
    {
6515
      /*
6516 6517 6518 6519
        On the first hand we need write lock on the tables to be flushed,
        on the other hand we must not try to aspire a global read lock
        if we have a write locked table as this would lead to a deadlock
        when trying to reopen (and re-lock) the table after the flush.
6520
      */
Konstantin Osipov's avatar
Konstantin Osipov committed
6521
      if (thd->locked_tables_mode)
6522
      {
6523 6524
        my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
        return 1;
6525
      }
unknown's avatar
unknown committed
6526 6527 6528 6529
      /*
	Writing to the binlog could cause deadlocks, as we don't log
	UNLOCK TABLES
      */
6530
      tmp_write_to_binlog= 0;
6531
      if (lock_global_read_lock(thd))
unknown's avatar
unknown committed
6532
	return 1;                               // Killed
Kristofer Pettersson's avatar
Kristofer Pettersson committed
6533
      if (close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ?
6534
                              FALSE : TRUE))
6535 6536
          result= 1;
      
unknown's avatar
unknown committed
6537
      if (make_global_read_lock_block_commit(thd)) // Killed
6538 6539 6540 6541 6542
      {
        /* Don't leave things in a half-locked state */
        unlock_global_read_lock(thd);
        return 1;
      }
unknown's avatar
unknown committed
6543
    }
6544
    else
6545
    {
Konstantin Osipov's avatar
Konstantin Osipov committed
6546
      if (thd && thd->locked_tables_mode)
6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572
      {
        /*
          If we are under LOCK TABLES we should have a write
          lock on tables which we are going to flush.
        */
        if (tables)
        {
          for (TABLE_LIST *t= tables; t; t= t->next_local)
            if (!find_write_locked_table(thd->open_tables, t->db,
                                         t->table_name))
              return 1;
        }
        else
        {
          for (TABLE *tab= thd->open_tables; tab; tab= tab->next)
          {
            if (tab->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
            {
              my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0),
                       tab->s->table_name.str);
              return 1;
            }
          }
        }
      }

Kristofer Pettersson's avatar
Kristofer Pettersson committed
6573
      if (close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ?
6574
                              FALSE : TRUE))
6575 6576
        result= 1;
    }
unknown's avatar
unknown committed
6577
    my_dbopt_cleanup();
unknown's avatar
unknown committed
6578 6579 6580
  }
  if (options & REFRESH_HOSTS)
    hostname_cache_refresh();
unknown's avatar
unknown committed
6581
  if (thd && (options & REFRESH_STATUS))
unknown's avatar
unknown committed
6582
    refresh_status(thd);
unknown's avatar
unknown committed
6583 6584
  if (options & REFRESH_THREADS)
    flush_thread_cache();
unknown's avatar
unknown committed
6585
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
6586
  if (options & REFRESH_MASTER)
6587
  {
6588
    DBUG_ASSERT(thd);
6589
    tmp_write_to_binlog= 0;
6590
    if (reset_master(thd))
unknown's avatar
unknown committed
6591
    {
6592
      result=1;
unknown's avatar
unknown committed
6593
    }
6594
  }
6595
#endif
unknown's avatar
unknown committed
6596
#ifdef OPENSSL
6597 6598
   if (options & REFRESH_DES_KEY_FILE)
   {
6599 6600
     if (des_key_file && load_des_key_file(des_key_file))
         result= 1;
6601 6602
   }
#endif
unknown's avatar
unknown committed
6603
#ifdef HAVE_REPLICATION
6604 6605
 if (options & REFRESH_SLAVE)
 {
6606
   tmp_write_to_binlog= 0;
6607
   pthread_mutex_lock(&LOCK_active_mi);
6608
   if (reset_slave(thd, active_mi))
6609
     result=1;
6610
   pthread_mutex_unlock(&LOCK_active_mi);
6611
 }
6612
#endif
6613
 if (options & REFRESH_USER_RESOURCES)
6614
   reset_mqh((LEX_USER *) NULL, 0);             /* purecov: inspected */
unknown's avatar
unknown committed
6615
 *write_to_binlog= tmp_write_to_binlog;
6616
 return result;
unknown's avatar
unknown committed
6617 6618
}

6619

unknown's avatar
unknown committed
6620 6621
/**
  kill on thread.
6622

unknown's avatar
unknown committed
6623 6624 6625
  @param thd			Thread class
  @param id			Thread id
  @param only_kill_query        Should it kill the query or the connection
6626

unknown's avatar
unknown committed
6627
  @note
6628 6629 6630
    This is written such that we have a short lock on LOCK_thread_count
*/

6631
uint kill_one_thread(THD *thd, ulong id, bool only_kill_query)
unknown's avatar
unknown committed
6632 6633 6634
{
  THD *tmp;
  uint error=ER_NO_SUCH_THREAD;
6635 6636
  DBUG_ENTER("kill_one_thread");
  DBUG_PRINT("enter", ("id=%lu only_kill=%d", id, only_kill_query));
Konstantin Osipov's avatar
Konstantin Osipov committed
6637
  pthread_mutex_lock(&LOCK_thread_count); // For unlink from list
6638
  I_List_iterator<THD> it(threads);
unknown's avatar
unknown committed
6639 6640
  while ((tmp=it++))
  {
unknown's avatar
unknown committed
6641 6642
    if (tmp->command == COM_DAEMON)
      continue;
unknown's avatar
unknown committed
6643 6644
    if (tmp->thread_id == id)
    {
6645
      pthread_mutex_lock(&tmp->LOCK_thd_data);	// Lock from delete
6646
      break;
unknown's avatar
unknown committed
6647 6648
    }
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
6649
  pthread_mutex_unlock(&LOCK_thread_count);
6650 6651
  if (tmp)
  {
6652 6653 6654 6655 6656

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

6657 6658 6659
      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).
6660

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

6666
      If user of both killer and killee are non-NULL, proceed with
6667 6668 6669
      slayage if both are string-equal.
    */

6670
    if ((thd->security_ctx->master_access & SUPER_ACL) ||
6671
        thd->security_ctx->user_matches(tmp->security_ctx))
6672
    {
unknown's avatar
SCRUM  
unknown committed
6673
      tmp->awake(only_kill_query ? THD::KILL_QUERY : THD::KILL_CONNECTION);
6674 6675 6676 6677
      error=0;
    }
    else
      error=ER_KILL_DENIED_ERROR;
6678
    pthread_mutex_unlock(&tmp->LOCK_thd_data);
6679
  }
6680 6681 6682 6683
  DBUG_PRINT("exit", ("%d", error));
  DBUG_RETURN(error);
}

6684

6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698
/*
  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
*/

void sql_kill(THD *thd, ulong id, bool only_kill_query)
{
  uint error;
  if (!(error= kill_one_thread(thd, id, only_kill_query)))
6699
    my_ok(thd);
unknown's avatar
unknown committed
6700
  else
unknown's avatar
unknown committed
6701
    my_error(error, MYF(0), id);
unknown's avatar
unknown committed
6702 6703
}

unknown's avatar
unknown committed
6704

unknown's avatar
unknown committed
6705
/** If pointer is not a null pointer, append filename to it. */
6706

unknown's avatar
unknown committed
6707 6708
bool append_file_to_dir(THD *thd, const char **filename_ptr,
                        const char *table_name)
6709
{
6710
  char buff[FN_REFLEN],*ptr, *end;
6711 6712 6713 6714 6715 6716 6717
  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))
  {
6718
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
6719 6720 6721 6722
    return 1;
  }
  /* Fix is using unix filename format on dos */
  strmov(buff,*filename_ptr);
6723
  end=convert_dirname(buff, *filename_ptr, NullS);
6724
  if (!(ptr= (char*) thd->alloc((size_t) (end-buff) + strlen(table_name)+1)))
6725 6726
    return 1;					// End of memory
  *filename_ptr=ptr;
6727
  strxmov(ptr,buff,table_name,NullS);
6728 6729
  return 0;
}
6730

6731

unknown's avatar
unknown committed
6732 6733
/**
  Check if the select is a simple select (not an union).
6734

unknown's avatar
unknown committed
6735
  @retval
6736
    0	ok
unknown's avatar
unknown committed
6737
  @retval
6738 6739 6740 6741 6742 6743
    1	error	; In this case the error messege is sent to the client
*/

bool check_simple_select()
{
  THD *thd= current_thd;
6744 6745
  LEX *lex= thd->lex;
  if (lex->current_select != &lex->select_lex)
6746 6747
  {
    char command[80];
6748
    Lex_input_stream *lip= & thd->m_parser_state->m_lip;
6749 6750
    strmake(command, lip->yylval->symbol.str,
	    min(lip->yylval->symbol.length, sizeof(command)-1));
6751
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
6752 6753 6754 6755
    return 1;
  }
  return 0;
}
unknown's avatar
unknown committed
6756

unknown's avatar
unknown committed
6757

unknown's avatar
unknown committed
6758
Comp_creator *comp_eq_creator(bool invert)
unknown's avatar
unknown committed
6759
{
unknown's avatar
unknown committed
6760
  return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
unknown's avatar
unknown committed
6761 6762
}

unknown's avatar
unknown committed
6763

unknown's avatar
unknown committed
6764
Comp_creator *comp_ge_creator(bool invert)
unknown's avatar
unknown committed
6765
{
unknown's avatar
unknown committed
6766
  return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator;
unknown's avatar
unknown committed
6767 6768
}

unknown's avatar
unknown committed
6769

unknown's avatar
unknown committed
6770
Comp_creator *comp_gt_creator(bool invert)
unknown's avatar
unknown committed
6771
{
unknown's avatar
unknown committed
6772
  return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator;
unknown's avatar
unknown committed
6773 6774
}

unknown's avatar
unknown committed
6775

unknown's avatar
unknown committed
6776
Comp_creator *comp_le_creator(bool invert)
unknown's avatar
unknown committed
6777
{
unknown's avatar
unknown committed
6778
  return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator;
unknown's avatar
unknown committed
6779 6780
}

unknown's avatar
unknown committed
6781

unknown's avatar
unknown committed
6782
Comp_creator *comp_lt_creator(bool invert)
unknown's avatar
unknown committed
6783
{
unknown's avatar
unknown committed
6784
  return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator;
unknown's avatar
unknown committed
6785 6786
}

unknown's avatar
unknown committed
6787

unknown's avatar
unknown committed
6788
Comp_creator *comp_ne_creator(bool invert)
unknown's avatar
unknown committed
6789
{
unknown's avatar
unknown committed
6790
  return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
unknown's avatar
unknown committed
6791
}
unknown's avatar
unknown committed
6792 6793


unknown's avatar
unknown committed
6794 6795
/**
  Construct ALL/ANY/SOME subquery Item.
unknown's avatar
unknown committed
6796

unknown's avatar
unknown committed
6797 6798 6799 6800
  @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
unknown's avatar
unknown committed
6801

unknown's avatar
unknown committed
6802
  @return
unknown's avatar
unknown committed
6803 6804 6805 6806 6807 6808 6809
    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)
{
unknown's avatar
unknown committed
6810
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
unknown's avatar
unknown committed
6811
    return new Item_in_subselect(left_expr, select_lex);
unknown's avatar
unknown committed
6812 6813

  if ((cmp == &comp_ne_creator) && all)        // <> ALL <=> NOT IN
unknown's avatar
unknown committed
6814 6815 6816
    return new Item_func_not(new Item_in_subselect(left_expr, select_lex));

  Item_allany_subselect *it=
6817
    new Item_allany_subselect(left_expr, cmp, select_lex, all);
unknown's avatar
unknown committed
6818
  if (all)
6819
    return it->upper_item= new Item_func_not_all(it);	/* ALL */
unknown's avatar
unknown committed
6820

6821
  return it->upper_item= new Item_func_nop_all(it);      /* ANY/SOME */
unknown's avatar
unknown committed
6822
}
6823 6824


unknown's avatar
unknown committed
6825 6826
/**
  Multi update query pre-check.
6827

unknown's avatar
unknown committed
6828 6829
  @param thd		Thread handler
  @param tables	Global/local table list (have to be the same)
6830

unknown's avatar
unknown committed
6831
  @retval
unknown's avatar
unknown committed
6832
    FALSE OK
unknown's avatar
unknown committed
6833
  @retval
unknown's avatar
unknown committed
6834
    TRUE  Error
6835
*/
unknown's avatar
unknown committed
6836

unknown's avatar
unknown committed
6837
bool multi_update_precheck(THD *thd, TABLE_LIST *tables)
6838 6839 6840 6841 6842
{
  const char *msg= 0;
  TABLE_LIST *table;
  LEX *lex= thd->lex;
  SELECT_LEX *select_lex= &lex->select_lex;
unknown's avatar
VIEW  
unknown committed
6843
  DBUG_ENTER("multi_update_precheck");
6844 6845 6846

  if (select_lex->item_list.elements != lex->value_list.elements)
  {
6847
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
6848
    DBUG_RETURN(TRUE);
6849 6850 6851 6852 6853
  }
  /*
    Ensure that we have UPDATE or SELECT privilege for each table
    The exact privilege is checked in mysql_multi_update()
  */
unknown's avatar
VIEW  
unknown committed
6854
  for (table= tables; table; table= table->next_local)
6855
  {
6856 6857 6858
    if (table->derived)
      table->grant.privilege= SELECT_ACL;
    else if ((check_access(thd, UPDATE_ACL, table->db,
6859 6860
                           &table->grant.privilege, 0, 1,
                           test(table->schema_table)) ||
6861
              check_grant(thd, UPDATE_ACL, table, FALSE, 1, TRUE)) &&
unknown's avatar
unknown committed
6862
             (check_access(thd, SELECT_ACL, table->db,
6863 6864
                           &table->grant.privilege, 0, 0,
                           test(table->schema_table)) ||
6865
              check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE)))
unknown's avatar
unknown committed
6866
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
6867

unknown's avatar
VIEW  
unknown committed
6868
    table->table_in_first_from_clause= 1;
6869
  }
unknown's avatar
unknown committed
6870 6871 6872
  /*
    Is there tables of subqueries?
  */
6873
  if (&lex->select_lex != lex->all_selects_list)
6874
  {
6875
    DBUG_PRINT("info",("Checking sub query list"));
unknown's avatar
VIEW  
unknown committed
6876
    for (table= tables; table; table= table->next_global)
6877
    {
6878
      if (!table->table_in_first_from_clause)
6879 6880
      {
	if (check_access(thd, SELECT_ACL, table->db,
6881 6882
			 &table->grant.privilege, 0, 0,
                         test(table->schema_table)) ||
6883
	    check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE))
unknown's avatar
unknown committed
6884
	  DBUG_RETURN(TRUE);
6885 6886 6887 6888 6889 6890
      }
    }
  }

  if (select_lex->order_list.elements)
    msg= "ORDER BY";
6891
  else if (select_lex->select_limit)
6892 6893 6894 6895
    msg= "LIMIT";
  if (msg)
  {
    my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
unknown's avatar
unknown committed
6896
    DBUG_RETURN(TRUE);
6897
  }
unknown's avatar
unknown committed
6898
  DBUG_RETURN(FALSE);
6899 6900
}

unknown's avatar
unknown committed
6901 6902
/**
  Multi delete query pre-check.
6903

unknown's avatar
unknown committed
6904 6905
  @param thd			Thread handler
  @param tables		Global/local table list
6906

unknown's avatar
unknown committed
6907
  @retval
unknown's avatar
unknown committed
6908
    FALSE OK
unknown's avatar
unknown committed
6909
  @retval
unknown's avatar
unknown committed
6910
    TRUE  error
6911
*/
unknown's avatar
unknown committed
6912

6913
bool multi_delete_precheck(THD *thd, TABLE_LIST *tables)
6914 6915 6916
{
  SELECT_LEX *select_lex= &thd->lex->select_lex;
  TABLE_LIST *aux_tables=
unknown's avatar
unknown committed
6917
    (TABLE_LIST *)thd->lex->auxiliary_table_list.first;
6918
  TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
unknown's avatar
VIEW  
unknown committed
6919
  DBUG_ENTER("multi_delete_precheck");
unknown's avatar
unknown committed
6920

6921 6922
  /* sql_yacc guarantees that tables and aux_tables are not zero */
  DBUG_ASSERT(aux_tables != 0);
6923
  if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE))
6924 6925 6926 6927 6928 6929 6930 6931
    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;
6932
  if (check_table_access(thd, DELETE_ACL, aux_tables, FALSE, UINT_MAX, FALSE))
6933 6934
  {
    thd->lex->query_tables_own_last= save_query_tables_own_last;
unknown's avatar
unknown committed
6935
    DBUG_RETURN(TRUE);
6936 6937 6938
  }
  thd->lex->query_tables_own_last= save_query_tables_own_last;

6939 6940
  if ((thd->options & OPTION_SAFE_UPDATES) && !select_lex->where)
  {
unknown's avatar
unknown committed
6941 6942
    my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
               ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
unknown's avatar
unknown committed
6943
    DBUG_RETURN(TRUE);
6944
  }
6945 6946 6947 6948
  DBUG_RETURN(FALSE);
}


6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005
/*
  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);
}


unknown's avatar
unknown committed
7006
/**
7007 7008 7009
  Link tables in auxilary table list of multi-delete with corresponding
  elements in main table list, and set proper locks for them.

unknown's avatar
unknown committed
7010
  @param lex   pointer to LEX representing multi-delete
7011

unknown's avatar
unknown committed
7012 7013 7014 7015
  @retval
    FALSE   success
  @retval
    TRUE    error
7016 7017 7018 7019 7020 7021 7022 7023 7024 7025
*/

bool multi_delete_set_locks_and_link_aux_tables(LEX *lex)
{
  TABLE_LIST *tables= (TABLE_LIST*)lex->select_lex.table_list.first;
  TABLE_LIST *target_tbl;
  DBUG_ENTER("multi_delete_set_locks_and_link_aux_tables");

  lex->table_count= 0;

unknown's avatar
unknown committed
7026
  for (target_tbl= (TABLE_LIST *)lex->auxiliary_table_list.first;
7027
       target_tbl; target_tbl= target_tbl->next_local)
7028
  {
7029
    lex->table_count++;
7030
    /* All tables in aux_tables must be found in FROM PART */
7031
    TABLE_LIST *walk= multi_delete_table_match(lex, target_tbl, tables);
7032
    if (!walk)
unknown's avatar
unknown committed
7033
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7034 7035 7036 7037 7038
    if (!walk->derived)
    {
      target_tbl->table_name= walk->table_name;
      target_tbl->table_name_length= walk->table_name_length;
    }
unknown's avatar
unknown committed
7039
    walk->updating= target_tbl->updating;
unknown's avatar
unknown committed
7040
    walk->lock_type= target_tbl->lock_type;
unknown's avatar
VIEW  
unknown committed
7041
    target_tbl->correspondent_table= walk;	// Remember corresponding table
7042
  }
unknown's avatar
unknown committed
7043
  DBUG_RETURN(FALSE);
7044 7045 7046
}


unknown's avatar
unknown committed
7047 7048
/**
  simple UPDATE query pre-check.
unknown's avatar
unknown committed
7049

unknown's avatar
unknown committed
7050 7051
  @param thd		Thread handler
  @param tables	Global table list
unknown's avatar
unknown committed
7052

unknown's avatar
unknown committed
7053
  @retval
unknown's avatar
unknown committed
7054
    FALSE OK
unknown's avatar
unknown committed
7055
  @retval
unknown's avatar
unknown committed
7056
    TRUE  Error
unknown's avatar
unknown committed
7057
*/
unknown's avatar
unknown committed
7058

unknown's avatar
unknown committed
7059
bool update_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
7060 7061 7062 7063
{
  DBUG_ENTER("update_precheck");
  if (thd->lex->select_lex.item_list.elements != thd->lex->value_list.elements)
  {
unknown's avatar
unknown committed
7064
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
7065
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7066
  }
unknown's avatar
unknown committed
7067
  DBUG_RETURN(check_one_table_access(thd, UPDATE_ACL, tables));
unknown's avatar
unknown committed
7068 7069 7070
}


unknown's avatar
unknown committed
7071 7072
/**
  simple DELETE query pre-check.
unknown's avatar
unknown committed
7073

unknown's avatar
unknown committed
7074 7075
  @param thd		Thread handler
  @param tables	Global table list
unknown's avatar
unknown committed
7076

unknown's avatar
unknown committed
7077
  @retval
unknown's avatar
unknown committed
7078
    FALSE  OK
unknown's avatar
unknown committed
7079
  @retval
unknown's avatar
unknown committed
7080
    TRUE   error
unknown's avatar
unknown committed
7081
*/
unknown's avatar
unknown committed
7082

unknown's avatar
unknown committed
7083
bool delete_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
7084 7085 7086
{
  DBUG_ENTER("delete_precheck");
  if (check_one_table_access(thd, DELETE_ACL, tables))
unknown's avatar
unknown committed
7087
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7088
  /* Set privilege for the WHERE clause */
unknown's avatar
unknown committed
7089
  tables->grant.want_privilege=(SELECT_ACL & ~tables->grant.privilege);
unknown's avatar
unknown committed
7090
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
7091 7092 7093
}


unknown's avatar
unknown committed
7094 7095
/**
  simple INSERT query pre-check.
unknown's avatar
unknown committed
7096

unknown's avatar
unknown committed
7097 7098
  @param thd		Thread handler
  @param tables	Global table list
unknown's avatar
unknown committed
7099

unknown's avatar
unknown committed
7100
  @retval
unknown's avatar
unknown committed
7101
    FALSE  OK
unknown's avatar
unknown committed
7102
  @retval
unknown's avatar
unknown committed
7103
    TRUE   error
unknown's avatar
unknown committed
7104
*/
unknown's avatar
unknown committed
7105

unknown's avatar
merge  
unknown committed
7106
bool insert_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
7107 7108 7109 7110
{
  LEX *lex= thd->lex;
  DBUG_ENTER("insert_precheck");

unknown's avatar
unknown committed
7111 7112 7113 7114
  /*
    Check that we have modify privileges for the first table and
    select privileges for the rest
  */
unknown's avatar
unknown committed
7115 7116 7117
  ulong privilege= (INSERT_ACL |
                    (lex->duplicates == DUP_REPLACE ? DELETE_ACL : 0) |
                    (lex->value_list.elements ? UPDATE_ACL : 0));
unknown's avatar
unknown committed
7118 7119

  if (check_one_table_access(thd, privilege, tables))
unknown's avatar
unknown committed
7120
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7121

unknown's avatar
unknown committed
7122
  if (lex->update_list.elements != lex->value_list.elements)
unknown's avatar
unknown committed
7123
  {
unknown's avatar
unknown committed
7124
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
7125
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7126
  }
unknown's avatar
unknown committed
7127
  DBUG_RETURN(FALSE);
7128
}
unknown's avatar
unknown committed
7129 7130


7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158
/**
   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;
  else if (!lex->select_lex.item_list.elements)
    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;
  }
}


unknown's avatar
unknown committed
7159 7160
/**
  CREATE TABLE query pre-check.
unknown's avatar
unknown committed
7161

unknown's avatar
unknown committed
7162 7163 7164
  @param thd			Thread handler
  @param tables		Global table list
  @param create_table	        Table which will be created
unknown's avatar
unknown committed
7165

unknown's avatar
unknown committed
7166
  @retval
unknown's avatar
unknown committed
7167
    FALSE   OK
unknown's avatar
unknown committed
7168
  @retval
unknown's avatar
unknown committed
7169
    TRUE   Error
unknown's avatar
unknown committed
7170
*/
unknown's avatar
unknown committed
7171

unknown's avatar
unknown committed
7172 7173
bool create_table_precheck(THD *thd, TABLE_LIST *tables,
                           TABLE_LIST *create_table)
unknown's avatar
unknown committed
7174 7175
{
  LEX *lex= thd->lex;
7176 7177
  SELECT_LEX *select_lex= &lex->select_lex;
  ulong want_priv;
unknown's avatar
merge  
unknown committed
7178
  bool error= TRUE;                                 // Error message is given
unknown's avatar
unknown committed
7179
  DBUG_ENTER("create_table_precheck");
7180

7181 7182 7183 7184 7185
  /*
    Require CREATE [TEMPORARY] privilege on new table; for
    CREATE TABLE ... SELECT, also require INSERT.
  */

7186
  want_priv= ((lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) ?
7187 7188 7189
              CREATE_TMP_ACL : CREATE_ACL) |
             (select_lex->item_list.elements ? INSERT_ACL : 0);

unknown's avatar
unknown committed
7190
  if (check_access(thd, want_priv, create_table->db,
7191 7192
		   &create_table->grant.privilege, 0, 0,
                   test(create_table->schema_table)) ||
unknown's avatar
unknown committed
7193 7194 7195
      check_merge_table_access(thd, create_table->db,
			       (TABLE_LIST *)
			       lex->create_info.merge_list.first))
7196
    goto err;
7197
  if (want_priv != CREATE_TMP_ACL &&
7198
      check_grant(thd, want_priv, create_table, FALSE, 1, FALSE))
7199 7200 7201 7202 7203 7204
    goto err;

  if (select_lex->item_list.elements)
  {
    /* Check permissions for used tables in CREATE TABLE ... SELECT */

7205 7206
#ifdef NOT_NECESSARY_TO_CHECK_CREATE_TABLE_EXIST_WHEN_PREPARING_STATEMENT
    /* This code throws an ill error for CREATE TABLE t1 SELECT * FROM t1 */
7207
    /*
7208
      Only do the check for PS, because we on execute we have to check that
unknown's avatar
unknown committed
7209 7210
      against the opened tables to ensure we don't use a table that is part
      of the view (which can only be done after the table has been opened).
7211
    */
unknown's avatar
unknown committed
7212
    if (thd->stmt_arena->is_stmt_prepare_or_first_sp_execute())
7213
    {
unknown's avatar
unknown committed
7214 7215 7216 7217
      /*
        For temporary tables we don't have to check if the created table exists
      */
      if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) &&
unknown's avatar
unknown committed
7218
          find_table_in_global_list(tables, create_table->db,
7219
                                    create_table->table_name))
unknown's avatar
unknown committed
7220
      {
7221
	error= FALSE;
unknown's avatar
unknown committed
7222 7223 7224
        goto err;
      }
    }
7225
#endif
7226 7227
    if (tables && check_table_access(thd, SELECT_ACL, tables, FALSE,
                                     UINT_MAX, FALSE))
7228 7229
      goto err;
  }
unknown's avatar
unknown committed
7230 7231
  else if (lex->create_info.options & HA_LEX_CREATE_TABLE_LIKE)
  {
7232
    if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE))
unknown's avatar
unknown committed
7233 7234
      goto err;
  }
unknown's avatar
merge  
unknown committed
7235
  error= FALSE;
7236 7237 7238

err:
  DBUG_RETURN(error);
unknown's avatar
unknown committed
7239
}
unknown's avatar
unknown committed
7240 7241


unknown's avatar
unknown committed
7242 7243
/**
  negate given expression.
unknown's avatar
unknown committed
7244

unknown's avatar
unknown committed
7245 7246
  @param thd  thread handler
  @param expr expression for negation
unknown's avatar
unknown committed
7247

unknown's avatar
unknown committed
7248
  @return
unknown's avatar
unknown committed
7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273
    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);
}
7274

unknown's avatar
unknown committed
7275 7276 7277
/**
  Set the specified definer to the default value, which is the
  current user in the thread.
7278
 
unknown's avatar
unknown committed
7279 7280
  @param[in]  thd       thread handler
  @param[out] definer   definer
7281 7282
*/
 
7283
void get_default_definer(THD *thd, LEX_USER *definer)
7284 7285 7286 7287 7288 7289 7290 7291 7292 7293
{
  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);
}

7294

unknown's avatar
unknown committed
7295
/**
7296
  Create default definer for the specified THD.
7297

unknown's avatar
unknown committed
7298
  @param[in] thd         thread handler
7299

unknown's avatar
unknown committed
7300 7301
  @return
    - On success, return a valid pointer to the created and initialized
7302
    LEX_USER, which contains definer information.
unknown's avatar
unknown committed
7303
    - On error, return 0.
7304 7305 7306 7307 7308 7309 7310 7311 7312
*/

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

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

7313
  get_default_definer(thd, definer);
7314 7315 7316 7317 7318

  return definer;
}


unknown's avatar
unknown committed
7319
/**
7320
  Create definer with the given user and host names.
7321

unknown's avatar
unknown committed
7322 7323 7324
  @param[in] thd          thread handler
  @param[in] user_name    user name
  @param[in] host_name    host name
7325

unknown's avatar
unknown committed
7326 7327
  @return
    - On success, return a valid pointer to the created and initialized
7328
    LEX_USER, which contains definer information.
unknown's avatar
unknown committed
7329
    - On error, return 0.
7330 7331
*/

7332
LEX_USER *create_definer(THD *thd, LEX_STRING *user_name, LEX_STRING *host_name)
7333
{
7334 7335 7336 7337
  LEX_USER *definer;

  /* Create and initialize. */

unknown's avatar
unknown committed
7338
  if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER))))
7339 7340 7341 7342 7343 7344
    return 0;

  definer->user= *user_name;
  definer->host= *host_name;

  return definer;
7345
}
7346 7347


unknown's avatar
unknown committed
7348
/**
7349 7350
  Retuns information about user or current user.

unknown's avatar
unknown committed
7351 7352
  @param[in] thd          thread handler
  @param[in] user         user
7353

unknown's avatar
unknown committed
7354 7355
  @return
    - On success, return a valid pointer to initialized
7356
    LEX_USER, which contains user information.
unknown's avatar
unknown committed
7357
    - On error, return 0.
7358 7359 7360 7361 7362
*/

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

7365 7366
  return user;
}
7367 7368


unknown's avatar
unknown committed
7369
/**
7370
  Check that byte length of a string does not exceed some limit.
7371

unknown's avatar
unknown committed
7372 7373 7374
  @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
7375

unknown's avatar
unknown committed
7376
  @retval
7377
    FALSE   the passed string is not longer than max_length
unknown's avatar
unknown committed
7378
  @retval
7379
    TRUE    the passed string is longer than max_length
7380 7381 7382

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

7385 7386
bool check_string_byte_length(LEX_STRING *str, const char *err_msg,
                              uint max_byte_length)
7387
{
7388
  if (str->length <= max_byte_length)
unknown's avatar
unknown committed
7389
    return FALSE;
7390

7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422
  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;
unknown's avatar
unknown committed
7423

7424
  if (!no_error)
7425 7426 7427 7428
  {
    ErrConvString err(str->str, str->length, cs);
    my_error(ER_WRONG_STRING_LENGTH, MYF(0), err.ptr(), err_msg, max_char_length);
  }
7429 7430
  return TRUE;
}
7431 7432


7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444
/*
  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  
*/
7445
C_MODE_START
7446

7447
int test_if_data_home_dir(const char *dir)
7448
{
7449
  char path[FN_REFLEN];
Alexey Botchkov's avatar
Alexey Botchkov committed
7450
  int dir_len;
7451 7452 7453 7454 7455 7456 7457
  DBUG_ENTER("test_if_data_home_dir");

  if (!dir)
    DBUG_RETURN(0);

  (void) fn_format(path, dir, "", "",
                   (MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS));
7458 7459
  dir_len= strlen(path);
  if (mysql_unpacked_real_data_home_len<= dir_len)
7460
  {
7461 7462 7463 7464
    if (dir_len > mysql_unpacked_real_data_home_len &&
        path[mysql_unpacked_real_data_home_len] != FN_LIBCHAR)
      DBUG_RETURN(0);

7465 7466
    if (lower_case_file_system)
    {
7467 7468
      if (!my_strnncoll(default_charset_info, (const uchar*) path,
                        mysql_unpacked_real_data_home_len,
7469
                        (const uchar*) mysql_unpacked_real_data_home,
7470
                        mysql_unpacked_real_data_home_len))
7471 7472
        DBUG_RETURN(1);
    }
7473 7474
    else if (!memcmp(path, mysql_unpacked_real_data_home,
                     mysql_unpacked_real_data_home_len))
7475 7476 7477 7478 7479
      DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}

7480 7481
C_MODE_END

7482

7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497
/**
  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
7498
  if (check_string_byte_length(str, ER(ER_HOSTNAME), HOSTNAME_LENGTH))
7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513
    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
7514 7515


7516 7517 7518 7519 7520 7521 7522 7523
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.
7524
  @param parser_state Parser state.
unknown's avatar
unknown committed
7525
  @param creation_ctx Object creation context.
7526 7527 7528 7529 7530 7531

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

unknown's avatar
unknown committed
7532
bool parse_sql(THD *thd,
7533
               Parser_state *parser_state,
unknown's avatar
unknown committed
7534
               Object_creation_ctx *creation_ctx)
7535
{
7536
  bool ret_value;
7537
  DBUG_ASSERT(thd->m_parser_state == NULL);
7538

7539
  MYSQL_QUERY_PARSE_START(thd->query());
unknown's avatar
unknown committed
7540 7541 7542 7543 7544 7545 7546
  /* Backup creation context. */

  Object_creation_ctx *backup_ctx= NULL;

  if (creation_ctx)
    backup_ctx= creation_ctx->set_n_backup(thd);

7547
  /* Set parser state. */
unknown's avatar
unknown committed
7548

7549
  thd->m_parser_state= parser_state;
7550

unknown's avatar
unknown committed
7551 7552
  /* Parse the query. */

7553 7554
  bool mysql_parse_status= MYSQLparse(thd) != 0;

7555
  /* Check that if MYSQLparse() failed, thd->is_error() is set. */
7556 7557

  DBUG_ASSERT(!mysql_parse_status ||
Staale Smedseng's avatar
Staale Smedseng committed
7558
              (mysql_parse_status && thd->is_error()));
unknown's avatar
unknown committed
7559

7560
  /* Reset parser state. */
7561

7562
  thd->m_parser_state= NULL;
7563

unknown's avatar
unknown committed
7564 7565 7566 7567 7568 7569 7570
  /* Restore creation context. */

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

  /* That's it. */

7571 7572 7573
  ret_value= mysql_parse_status || thd->is_fatal_error;
  MYSQL_QUERY_PARSE_DONE(ret_value);
  return ret_value;
7574
}
7575 7576 7577 7578

/**
  @} (end of group Runtime_Environment)
*/
Alexander Barkov's avatar
#  
Alexander Barkov committed
7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612



/**
  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;
}