sql_parse.cc 214 KB
Newer Older
1
/* Copyright (C) 2000-2003 MySQL AB
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 24
#include <m_ctype.h>
#include <myisam.h>
#include <my_dir.h>

25
#include "sp_head.h"
26
#include "sp.h"
27
#include "sp_cache.h"
28
#include "events.h"
29
#include "sql_trigger.h"
30

31 32 33 34 35
/**
  @defgroup Runtime_Environment Runtime Environment
  @{
*/

36 37 38 39 40 41
/* 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 || \
42
   (LP)->sql_command == SQLCOM_SHOW_CREATE_FUNC || \
43 44 45
   (LP)->sql_command == SQLCOM_DROP_FUNCTION ? \
   "FUNCTION" : "PROCEDURE")

46
static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables);
unknown's avatar
unknown committed
47
static bool check_show_create_table_access(THD *thd, TABLE_LIST *table);
unknown's avatar
unknown committed
48

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

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

unknown's avatar
unknown committed
85 86 87 88
const char *xa_state_names[]={
  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED"
};

unknown's avatar
unknown committed
89

unknown's avatar
unknown committed
90 91 92 93 94
static void unlock_locked_tables(THD *thd)
{
  if (thd->locked_tables)
  {
    thd->lock=thd->locked_tables;
95
    thd->locked_tables=0;			// Will be automatically closed
unknown's avatar
unknown committed
96 97 98 99
    close_thread_tables(thd);			// Free tables
  }
}

100

101
bool end_active_trans(THD *thd)
102
{
unknown's avatar
unknown committed
103
  int error=0;
104
  DBUG_ENTER("end_active_trans");
105
  if (unlikely(thd->in_sub_stmt))
106 107 108 109
  {
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
    DBUG_RETURN(1);
  }
110 111 112 113 114 115
  if (thd->transaction.xid_state.xa_state != XA_NOTR)
  {
    my_error(ER_XAER_RMFAIL, MYF(0),
             xa_state_names[thd->transaction.xid_state.xa_state]);
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
116
  if (thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN |
unknown's avatar
unknown committed
117
		      OPTION_TABLE_LOCK))
118
  {
119 120 121 122
    DBUG_PRINT("info",("options: 0x%lx", (ulong) thd->options));
    /* Safety if one did "drop table" on locked tables */
    if (!thd->locked_tables)
      thd->options&= ~OPTION_TABLE_LOCK;
123
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
124
    if (ha_commit(thd))
unknown's avatar
unknown committed
125
      error=1;
126
  }
127
  thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
unknown's avatar
unknown committed
128
  thd->transaction.all.modified_non_trans_table= FALSE;
129
  DBUG_RETURN(error);
130 131
}

132

unknown's avatar
unknown committed
133
bool begin_trans(THD *thd)
unknown's avatar
unknown committed
134 135
{
  int error=0;
136
  if (unlikely(thd->in_sub_stmt))
137 138 139 140
  {
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
    return 1;
  }
unknown's avatar
unknown committed
141 142 143 144 145 146 147 148 149 150
  if (thd->locked_tables)
  {
    thd->lock=thd->locked_tables;
    thd->locked_tables=0;			// Will be automatically closed
    close_thread_tables(thd);			// Free tables
  }
  if (end_active_trans(thd))
    error= -1;
  else
  {
151
    LEX *lex= thd->lex;
152
    thd->options|= OPTION_BEGIN;
unknown's avatar
unknown committed
153 154
    thd->server_status|= SERVER_STATUS_IN_TRANS;
    if (lex->start_transaction_opt & MYSQL_START_TRANS_OPT_WITH_CONS_SNAPSHOT)
unknown's avatar
unknown committed
155
      error= ha_start_consistent_snapshot(thd);
unknown's avatar
unknown committed
156 157 158
  }
  return error;
}
159

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


172 173 174 175 176 177 178 179 180 181 182 183
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;
}

184

185 186 187
/*
  Mark all commands that somehow changes a table
  This is used to check number of updates / hour
unknown's avatar
unknown committed
188 189 190

  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
191

192
  See COMMAND_FLAG_xxx for different type of commands
unknown's avatar
unknown committed
193 194
     2  - query that returns meaningful ROW_COUNT() -
          a number of modified rows
195 196
*/

197
uint sql_command_flags[SQLCOM_END+1];
198 199 200

void init_update_queries(void)
{
201
  bzero((uchar*) &sql_command_flags, sizeof(sql_command_flags));
202 203 204

  sql_command_flags[SQLCOM_CREATE_TABLE]=   CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_CREATE_INDEX]=   CF_CHANGES_DATA;
205 206
  sql_command_flags[SQLCOM_ALTER_TABLE]=    CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
  sql_command_flags[SQLCOM_TRUNCATE]=       CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
207 208 209 210 211 212 213 214 215 216 217 218
  sql_command_flags[SQLCOM_DROP_TABLE]=     CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_LOAD]=           CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_CREATE_DB]=      CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_DROP_DB]=        CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_RENAME_TABLE]=   CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_BACKUP_TABLE]=   CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_RESTORE_TABLE]=  CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_DROP_INDEX]=     CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_CREATE_VIEW]=    CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_DROP_VIEW]=      CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_CREATE_EVENT]=   CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_ALTER_EVENT]=    CF_CHANGES_DATA;
219
  sql_command_flags[SQLCOM_DROP_EVENT]=     CF_CHANGES_DATA;
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

  sql_command_flags[SQLCOM_UPDATE]=	    CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
  sql_command_flags[SQLCOM_UPDATE_MULTI]=   CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
  sql_command_flags[SQLCOM_INSERT]=	    CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
  sql_command_flags[SQLCOM_INSERT_SELECT]=  CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
  sql_command_flags[SQLCOM_DELETE]=         CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
  sql_command_flags[SQLCOM_DELETE_MULTI]=   CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
  sql_command_flags[SQLCOM_REPLACE]=        CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
  sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;

  sql_command_flags[SQLCOM_SHOW_STATUS_PROC]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_STATUS]=      CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_DATABASES]=   CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_TRIGGERS]=    CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_EVENTS]=      CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_OPEN_TABLES]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PLUGINS]=     CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_FIELDS]=      CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_KEYS]=        CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_VARIABLES]=   CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CHARSETS]=    CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_COLLATIONS]=  CF_STATUS_COMMAND;
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  sql_command_flags[SQLCOM_SHOW_NEW_MASTER]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_BINLOGS]= CF_STATUS_COMMAND;
  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_COLUMN_TYPES]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_STORAGE_ENGINES]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_AUTHORS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CONTRIBUTORS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PRIVILEGES]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_WARNS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_ERRORS]= CF_STATUS_COMMAND;
  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;
  sql_command_flags[SQLCOM_SHOW_GRANTS]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_DB]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_MASTER_STAT]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_SLAVE_STAT]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_PROC]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_FUNC]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_TRIGGER]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_STATUS_FUNC]=  CF_STATUS_COMMAND;
  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_TABLES]=       (CF_STATUS_COMMAND |
                                               CF_SHOW_TABLE_COMMAND);
272 273 274 275 276 277 278 279 280 281 282
  sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND |
                                                CF_SHOW_TABLE_COMMAND);

  /*
    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.
  */
  sql_command_flags[SQLCOM_CALL]= 		CF_HAS_ROW_COUNT;
  sql_command_flags[SQLCOM_EXECUTE]= 		CF_HAS_ROW_COUNT;
283 284 285 286 287 288 289 290

  /*
    The following admin table operations are allowed
    on log tables.
  */
  sql_command_flags[SQLCOM_REPAIR]=           CF_WRITE_LOGS_COMMAND;
  sql_command_flags[SQLCOM_OPTIMIZE]=         CF_WRITE_LOGS_COMMAND;
  sql_command_flags[SQLCOM_ANALYZE]=          CF_WRITE_LOGS_COMMAND;
291 292
}

293

unknown's avatar
unknown committed
294 295
bool is_update_query(enum enum_sql_command command)
{
unknown's avatar
unknown committed
296
  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
297
  return (sql_command_flags[command] & CF_CHANGES_DATA) != 0;
unknown's avatar
unknown committed
298
}
299

300 301 302 303 304 305 306 307 308 309 310
/**
  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;
}

311 312
void execute_init_command(THD *thd, sys_var_str *init_command_var,
			  rw_lock_t *var_mutex)
unknown's avatar
unknown committed
313 314 315 316
{
  Vio* save_vio;
  ulong save_client_capabilities;

317 318 319 320 321 322 323 324 325
  thd->proc_info= "Execution of init_command";
  /*
    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);
  thd->query= init_command_var->value;
  thd->query_length= init_command_var->value_length;
unknown's avatar
unknown committed
326 327
  save_client_capabilities= thd->client_capabilities;
  thd->client_capabilities|= CLIENT_MULTI_QUERIES;
328 329 330 331
  /*
    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
332 333
  save_vio= thd->net.vio;
  thd->net.vio= 0;
334
  thd->net.no_send_error= 0;
unknown's avatar
unknown committed
335
  dispatch_command(COM_QUERY, thd, thd->query, thd->query_length+1);
336
  rw_unlock(var_mutex);
unknown's avatar
unknown committed
337 338 339 340 341
  thd->client_capabilities= save_client_capabilities;
  thd->net.vio= save_vio;
}


342 343 344 345
/*
  Execute commands from bootstrap_file.
  Used when creating the initial grant tables
*/
unknown's avatar
unknown committed
346

347
pthread_handler_t handle_bootstrap(void *arg)
unknown's avatar
unknown committed
348
{
349 350 351
  THD *thd=(THD*) arg;
  FILE *file=bootstrap_file;
  char *buff;
352
  const char* found_semicolon= NULL;
unknown's avatar
unknown committed
353

354
  /* The following must be called before DBUG_ENTER */
355
  thd->thread_stack= (char*) &thd;
356
  if (my_thread_init() || thd->store_globals())
unknown's avatar
unknown committed
357
  {
unknown's avatar
unknown committed
358
#ifndef EMBEDDED_LIBRARY
359
    close_connection(thd, ER_OUT_OF_RESOURCES, 1);
unknown's avatar
unknown committed
360
#endif
361
    thd->fatal_error();
362
    goto end;
unknown's avatar
unknown committed
363
  }
364 365
  DBUG_ENTER("handle_bootstrap");

unknown's avatar
unknown committed
366
#ifndef EMBEDDED_LIBRARY
367 368
  pthread_detach_this_thread();
  thd->thread_stack= (char*) &thd;
unknown's avatar
unknown committed
369
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
370

371
  if (thd->variables.max_join_size == HA_POS_ERROR)
unknown's avatar
unknown committed
372 373 374 375
    thd->options |= OPTION_BIG_SELECTS;

  thd->proc_info=0;
  thd->version=refresh_version;
376 377
  thd->security_ctx->priv_user=
    thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME));
unknown's avatar
unknown committed
378
  thd->security_ctx->priv_host[0]=0;
379 380 381 382 383 384
  /*
    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
385

386
  buff= (char*) thd->net.buff;
387
  thd->init_for_queries();
unknown's avatar
unknown committed
388 389
  while (fgets(buff, thd->net.max_packet, file))
  {
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    /* 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))
      {
        net_send_error(thd, ER_NET_PACKET_TOO_LARGE, NullS);
        thd->fatal_error();
        break;
      }
      buff= (char*) thd->net.buff;
      fgets(buff + length, thd->net.max_packet - length, file);
      length+= (ulong) strlen(buff + length);
      /* purecov: end */
    }
    if (thd->is_fatal_error)
      break;                                    /* purecov: inspected */
unknown's avatar
unknown committed
412

unknown's avatar
unknown committed
413
    while (length && (my_isspace(thd->charset(), buff[length-1]) ||
414
                      buff[length-1] == ';'))
unknown's avatar
unknown committed
415 416
      length--;
    buff[length]=0;
unknown's avatar
unknown committed
417 418 419 420 421

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

422
    thd->query_length=length;
423 424 425
    thd->query= (char*) thd->memdup_w_gap(buff, length+1, 
                                          thd->db_length+1+
                                          QUERY_CACHE_FLAGS_SIZE);
unknown's avatar
unknown committed
426
    thd->query[length] = '\0';
427
    DBUG_PRINT("query",("%-.4096s",thd->query));
428 429 430 431
    /*
      We don't need to obtain LOCK_thread_count here because in bootstrap
      mode we have only one thread.
    */
432
    thd->query_id=next_query_id();
433
    thd->set_time();
434
    mysql_parse(thd, thd->query, length, & found_semicolon);
unknown's avatar
unknown committed
435
    close_thread_tables(thd);			// Free tables
436

437
    if (thd->is_fatal_error)
438
      break;
439 440 441 442 443 444 445 446 447

    if (thd->net.report_error)
    {
      /* The query failed, send error to log and abort bootstrap */
      net_send_error(thd);
      thd->fatal_error();
      break;
    }

unknown's avatar
unknown committed
448
    free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
449
#ifdef USING_TRANSACTIONS
450
    free_root(&thd->transaction.mem_root,MYF(MY_KEEP_PREALLOC));
451
#endif
unknown's avatar
unknown committed
452
  }
453 454

end:
455
  /* Remember the exit code of bootstrap */
456 457 458 459 460 461
  bootstrap_error= thd->is_fatal_error;

  net_end(&thd->net);
  thd->cleanup();
  delete thd;

unknown's avatar
unknown committed
462
#ifndef EMBEDDED_LIBRARY
463 464 465
  (void) pthread_mutex_lock(&LOCK_thread_count);
  thread_count--;
  (void) pthread_mutex_unlock(&LOCK_thread_count);
466
  (void) pthread_cond_broadcast(&COND_thread_count);
467 468
  my_thread_end();
  pthread_exit(0);
unknown's avatar
unknown committed
469
#endif
470
  DBUG_RETURN(0);
unknown's avatar
unknown committed
471 472 473
}


unknown's avatar
unknown committed
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
/* 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() */
489 490 491

void cleanup_items(Item *item)
{
unknown's avatar
unknown committed
492
  DBUG_ENTER("cleanup_items");  
493 494
  for (; item ; item=item->next)
    item->cleanup();
unknown's avatar
unknown committed
495
  DBUG_VOID_RETURN;
496 497
}

unknown's avatar
unknown committed
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
/*
  Handle COM_TABLE_DUMP command

  SYNOPSIS
    mysql_table_dump
      thd           thread handle
      db            database name or an empty string. If empty,
                    the current database of the connection is used
      tbl_name      name of the table to dump

  NOTES
    This function is written to handle one specific command only.

  RETURN VALUE
    0               success
    1               error, the error message is set in THD
*/

static
517
int mysql_table_dump(THD *thd, LEX_STRING *db, char *tbl_name)
unknown's avatar
unknown committed
518 519 520 521 522
{
  TABLE* table;
  TABLE_LIST* table_list;
  int error = 0;
  DBUG_ENTER("mysql_table_dump");
523 524 525 526 527
  if (db->length == 0)
  {
    db->str= thd->db;            /* purecov: inspected */
    db->length= thd->db_length;  /* purecov: inspected */
  }
528
  if (!(table_list = (TABLE_LIST*) thd->calloc(sizeof(TABLE_LIST))))
unknown's avatar
unknown committed
529
    DBUG_RETURN(1); // out of memory
530
  table_list->db= db->str;
531
  table_list->table_name= table_list->alias= tbl_name;
unknown's avatar
VIEW  
unknown committed
532 533
  table_list->lock_type= TL_READ_NO_INSERT;
  table_list->prev_global= &table_list;	// can be removed after merge with 4.1
unknown's avatar
unknown committed
534

535
  if (check_db_name(db))
536
  {
537 538
    /* purecov: begin inspected */
    my_error(ER_WRONG_DB_NAME ,MYF(0), db->str ? db->str : "NULL");
539
    goto err;
540
    /* purecov: end */
541
  }
542
  if (lower_case_table_names)
543
    my_casedn_str(files_charset_info, tbl_name);
544

545
  if (!(table=open_ltable(thd, table_list, TL_READ_NO_INSERT, 0)))
546 547
    DBUG_RETURN(1);

unknown's avatar
unknown committed
548
  if (check_one_table_access(thd, SELECT_ACL, table_list))
unknown's avatar
unknown committed
549 550
    goto err;
  thd->free_list = 0;
unknown's avatar
unknown committed
551
  thd->query_length=(uint) strlen(tbl_name);
unknown's avatar
unknown committed
552
  thd->query = tbl_name;
unknown's avatar
unknown committed
553
  if ((error = mysqld_dump_create_info(thd, table_list, -1)))
554
  {
555
    my_error(ER_GET_ERRNO, MYF(0), my_errno);
556 557
    goto err;
  }
unknown's avatar
unknown committed
558
  net_flush(&thd->net);
unknown's avatar
unknown committed
559
  if ((error= table->file->dump(thd,-1)))
560
    my_error(ER_GET_ERRNO, MYF(0), error);
unknown's avatar
unknown committed
561

unknown's avatar
unknown committed
562
err:
unknown's avatar
unknown committed
563
  DBUG_RETURN(error);
unknown's avatar
unknown committed
564 565
}

unknown's avatar
unknown committed
566 567 568 569
/*
  Ends the current transaction and (maybe) begin the next

  SYNOPSIS
570
    end_trans()
unknown's avatar
unknown committed
571 572 573 574 575 576 577
      thd            Current thread
      completion     Completion type

  RETURN
    0 - OK
*/

578
int end_trans(THD *thd, enum enum_mysql_completiontype completion)
unknown's avatar
unknown committed
579 580 581
{
  bool do_release= 0;
  int res= 0;
582
  DBUG_ENTER("end_trans");
unknown's avatar
unknown committed
583

584
  if (unlikely(thd->in_sub_stmt))
585 586 587 588
  {
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
    DBUG_RETURN(1);
  }
589 590 591 592 593 594
  if (thd->transaction.xid_state.xa_state != XA_NOTR)
  {
    my_error(ER_XAER_RMFAIL, MYF(0),
             xa_state_names[thd->transaction.xid_state.xa_state]);
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
595 596 597 598 599 600 601 602
  switch (completion) {
  case COMMIT:
    /*
     We don't use end_active_trans() here to ensure that this works
     even if there is a problem with the OPTION_AUTO_COMMIT flag
     (Which of course should never happen...)
    */
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
603
    res= ha_commit(thd);
604
    thd->options&= ~(ulong) (OPTION_BEGIN | OPTION_KEEP_LOG);
unknown's avatar
unknown committed
605
    thd->transaction.all.modified_non_trans_table= FALSE;
unknown's avatar
unknown committed
606 607
    break;
  case COMMIT_RELEASE:
unknown's avatar
unknown committed
608
    do_release= 1; /* fall through */
unknown's avatar
unknown committed
609 610 611 612 613 614
  case COMMIT_AND_CHAIN:
    res= end_active_trans(thd);
    if (!res && completion == COMMIT_AND_CHAIN)
      res= begin_trans(thd);
    break;
  case ROLLBACK_RELEASE:
unknown's avatar
unknown committed
615
    do_release= 1; /* fall through */
unknown's avatar
unknown committed
616 617 618 619
  case ROLLBACK:
  case ROLLBACK_AND_CHAIN:
  {
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
unknown's avatar
unknown committed
620
    if (ha_rollback(thd))
unknown's avatar
unknown committed
621
      res= -1;
622
    thd->options&= ~(ulong) (OPTION_BEGIN | OPTION_KEEP_LOG);
unknown's avatar
unknown committed
623
    thd->transaction.all.modified_non_trans_table= FALSE;
unknown's avatar
unknown committed
624 625 626 627 628 629 630 631 632
    if (!res && (completion == ROLLBACK_AND_CHAIN))
      res= begin_trans(thd);
    break;
  }
  default:
    res= -1;
    my_error(ER_UNKNOWN_COM_ERROR, MYF(0));
    DBUG_RETURN(-1);
  }
unknown's avatar
unknown committed
633

unknown's avatar
unknown committed
634 635 636
  if (res < 0)
    my_error(thd->killed_errno(), MYF(0));
  else if ((res == 0) && do_release)
unknown's avatar
unknown committed
637 638
    thd->killed= THD::KILL_CONNECTION;

unknown's avatar
unknown committed
639 640
  DBUG_RETURN(res);
}
unknown's avatar
unknown committed
641

642
#ifndef EMBEDDED_LIBRARY
643 644

/*
unknown's avatar
unknown committed
645
  Read one command from connection and execute it (query or simple command).
646 647 648 649 650 651 652 653
  This function is called in loop from thread function.
  SYNOPSIS
    do_command()
  RETURN VALUE
    0  success
    1  request of thread shutdown (see dispatch_command() description)
*/

unknown's avatar
unknown committed
654 655
bool do_command(THD *thd)
{
unknown's avatar
unknown committed
656
  char *packet= 0;
unknown's avatar
unknown committed
657
  ulong packet_length;
unknown's avatar
unknown committed
658
  NET *net= &thd->net;
unknown's avatar
unknown committed
659 660 661
  enum enum_server_command command;
  DBUG_ENTER("do_command");

unknown's avatar
unknown committed
662 663 664 665
  /*
    indicator of uninitialized lex => normal flow of errors handling
    (see my_message_sql)
  */
666
  thd->lex->current_select= 0;
unknown's avatar
unknown committed
667

unknown's avatar
unknown committed
668 669 670 671 672 673
  /*
    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
  */
674
  my_net_set_read_timeout(net, thd->variables.net_wait_timeout);
unknown's avatar
unknown committed
675

unknown's avatar
unknown committed
676
  thd->clear_error();				// Clear error message
unknown's avatar
unknown committed
677 678 679 680

  net_new_transaction(net);
  if ((packet_length=my_net_read(net)) == packet_error)
  {
681 682 683 684 685
    DBUG_PRINT("info",("Got error %d reading command from socket %s",
		       net->error,
		       vio_description(net->vio)));
    /* Check if we can continue without closing the connection */
    if (net->error != 3)
686 687
    {
      statistic_increment(aborted_threads,&LOCK_status);
688
      DBUG_RETURN(TRUE);			// We have to close it.
689
    }
690
    net_send_error(thd, net->last_errno, NullS);
691
    net->error= 0;
692
    DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
693 694 695 696 697
  }
  else
  {
    packet=(char*) net->read_pos;
    command = (enum enum_server_command) (uchar) packet[0];
698 699
    if (command >= COM_END)
      command= COM_END;				// Wrong command
unknown's avatar
unknown committed
700 701
    DBUG_PRINT("info",("Command on %s = %d (%s)",
		       vio_description(net->vio), command,
unknown's avatar
unknown committed
702
		       command_name[command].str));
unknown's avatar
unknown committed
703
  }
unknown's avatar
unknown committed
704 705

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

708 709 710 711 712 713 714 715 716
  /*
    packet_length contains length of data, as it was stored in packet
    header. In case of malformed header, packet_length can be zero.
    If packet_length is not zero, my_net_read ensures that this number
    of bytes was actually read from network. Additionally my_net_read
    sets packet[packet_length]= 0 (thus if packet_length == 0,
    command == packet[0] == COM_SLEEP).
    In dispatch_command packet[packet_length] points beyond the end of packet.
  */
unknown's avatar
unknown committed
717
  DBUG_RETURN(dispatch_command(command,thd, packet+1, (uint) packet_length));
718
}
719
#endif  /* EMBEDDED_LIBRARY */
720

721

722 723
/*
   Perform one connection-level (COM_XXXX) command.
724

725 726 727 728 729 730 731 732 733 734 735 736 737
  SYNOPSIS
    dispatch_command()
    thd             connection handle
    command         type of command to perform 
    packet          data for the command, packet is always null-terminated
    packet_length   length of packet + 1 (to show that data is
                    null-terminated) except for COM_SLEEP, where it
                    can be zero.
  RETURN VALUE
    0   ok
    1   request of thread shutdown, i. e. if command is
        COM_QUIT/COM_SHUTDOWN
*/
738

739 740 741 742
bool dispatch_command(enum enum_server_command command, THD *thd,
		      char* packet, uint packet_length)
{
  NET *net= &thd->net;
743
  bool error= 0;
744 745
  DBUG_ENTER("dispatch_command");

746
  if (thd->killed == THD::KILL_QUERY || thd->killed == THD::KILL_BAD_DATA)
747
  {
748
    thd->killed= THD::NOT_KILLED;
749 750
    thd->mysys_var->abort= 0;
  }
751

752
  thd->command=command;
unknown's avatar
unknown committed
753
  /*
754 755
    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
756
  */
757
  thd->enable_slow_log= TRUE;
758
  thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
unknown's avatar
unknown committed
759
  thd->set_time();
unknown's avatar
unknown committed
760
  VOID(pthread_mutex_lock(&LOCK_thread_count));
unknown's avatar
unknown committed
761
  thd->query_id= global_query_id;
unknown's avatar
unknown committed
762
  if (command != COM_STATISTICS && command != COM_PING)
763
    next_query_id();
unknown's avatar
unknown committed
764
  thread_running++;
765
  /* TODO: set thd->lex->sql_command to SQLCOM_END here */
unknown's avatar
unknown committed
766
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
unknown's avatar
unknown committed
767

768 769
  thd->server_status&=
           ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
770
  switch (command) {
unknown's avatar
unknown committed
771
  case COM_INIT_DB:
unknown's avatar
unknown committed
772 773
  {
    LEX_STRING tmp;
774
    status_var_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB]);
unknown's avatar
unknown committed
775
    thd->convert_string(&tmp, system_charset_info,
776
			packet, packet_length-1, thd->charset());
unknown's avatar
unknown committed
777
    if (!mysql_change_db(thd, &tmp, FALSE))
778
    {
unknown's avatar
unknown committed
779
      general_log_print(thd, command, "%s",thd->db);
780 781
      send_ok(thd);
    }
unknown's avatar
unknown committed
782 783
    break;
  }
unknown's avatar
unknown committed
784
#ifdef HAVE_REPLICATION
785 786
  case COM_REGISTER_SLAVE:
  {
787
    if (!register_slave(thd, (uchar*)packet, packet_length))
788
      send_ok(thd);
789 790
    break;
  }
791
#endif
unknown's avatar
unknown committed
792
  case COM_TABLE_DUMP:
793
  {
794 795
    char *tbl_name;
    LEX_STRING db;
796
    uint db_len= *(uchar*) packet;
unknown's avatar
unknown committed
797
    if (db_len >= packet_length || db_len > NAME_LEN)
unknown's avatar
unknown committed
798
    {
unknown's avatar
unknown committed
799
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
unknown's avatar
unknown committed
800 801
      break;
    }
802
    uint tbl_len= *(uchar*) (packet + db_len + 1);
unknown's avatar
unknown committed
803 804
    if (db_len+tbl_len+2 > packet_length || tbl_len > NAME_LEN)
    {
unknown's avatar
unknown committed
805
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
unknown's avatar
unknown committed
806 807
      break;
    }
808

809
    status_var_increment(thd->status_var.com_other);
810
    thd->enable_slow_log= opt_log_slow_admin_statements;
811
    db.str= (char*) thd->alloc(db_len + tbl_len + 2);
812
    if (!db.str)
813 814 815 816
    {
      my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
      break;
    }
817
    db.length= db_len;
818
    tbl_name= strmake(db.str, packet + 1, db_len)+1;
819
    strmake(tbl_name, packet + db_len + 2, tbl_len);
820
    mysql_table_dump(thd, &db, tbl_name);
821 822
    break;
  }
unknown's avatar
unknown committed
823 824
  case COM_CHANGE_USER:
  {
825
    status_var_increment(thd->status_var.com_other);
826 827 828
    char *user= (char*) packet, *packet_end= packet+ packet_length;
    char *passwd= strend(user)+1;

unknown's avatar
unknown committed
829
    thd->change_user();
830
    thd->clear_error();                         // if errors from rollback
unknown's avatar
unknown committed
831

832
    /*
unknown's avatar
unknown committed
833 834 835
      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).
836 837 838

      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
839
    */
840
    char db_buff[NAME_LEN+1];                 // buffer to store db in utf8
unknown's avatar
unknown committed
841
    char *db= passwd;
842 843
    char *save_db;
    uint passwd_len= (thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
844
                      (uchar)(*passwd++) : strlen(passwd));
845 846
    uint dummy_errors, save_db_length, db_length;
    int res;
847 848 849
    Security_context save_security_ctx= *thd->security_ctx;
    USER_CONN *save_user_connect;

unknown's avatar
unknown committed
850
    db+= passwd_len + 1;
851
#ifndef EMBEDDED_LIBRARY
852
    /* Small check for incoming packet */
unknown's avatar
unknown committed
853
    if ((uint) ((uchar*) db - net->read_pos) > packet_length)
854
    {
unknown's avatar
unknown committed
855
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
856 857
      break;
    }
858
#endif
859
    /* Convert database name to utf8 */
860 861 862 863 864 865 866
    /*
      Handle problem with old bug in client protocol where db had an extra
      \0
    */
    db_length= (packet_end - db);
    if (db_length > 0 && db[db_length-1] == 0)
      db_length--;
867
    db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
868
                             system_charset_info, db, db_length,
869
                             thd->charset(), &dummy_errors)]= 0;
870
    db= db_buff;
unknown's avatar
unknown committed
871

872
    /* Save user and privileges */
873 874 875
    save_db_length= thd->db_length;
    save_db= thd->db;
    save_user_connect= thd->user_connect;
876 877

    if (!(thd->security_ctx->user= my_strdup(user, MYF(0))))
878
    {
879
      thd->security_ctx->user= save_security_ctx.user;
unknown's avatar
unknown committed
880
      my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
881 882
      break;
    }
unknown's avatar
unknown committed
883

unknown's avatar
unknown committed
884 885
    /* Clear variables that are allocated */
    thd->user_connect= 0;
886
    res= check_user(thd, COM_CHANGE_USER, passwd, passwd_len, db, FALSE);
unknown's avatar
unknown committed
887

888 889
    if (res)
    {
890
      /* authentication failure, we shall restore old user */
891
      if (res > 0)
unknown's avatar
unknown committed
892
        my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
893 894
      else
        thd->clear_error();                     // Error already sent to client
895 896
      x_free(thd->security_ctx->user);
      *thd->security_ctx= save_security_ctx;
unknown's avatar
unknown committed
897
      thd->user_connect= save_user_connect;
898 899 900 901 902
      thd->db= save_db;
      thd->db_length= save_db_length;
    }
    else
    {
903
#ifndef NO_EMBEDDED_ACCESS_CHECKS
904
      /* we've authenticated new user */
unknown's avatar
unknown committed
905 906
      if (save_user_connect)
	decrease_user_connections(save_user_connect);
907
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
908 909
      x_free((uchar*) save_db);
      x_free((uchar*)  save_security_ctx.user);
910
    }
unknown's avatar
unknown committed
911 912
    break;
  }
913
  case COM_STMT_EXECUTE:
unknown's avatar
unknown committed
914
  {
915
    mysql_stmt_execute(thd, packet, packet_length);
unknown's avatar
unknown committed
916 917
    break;
  }
918
  case COM_STMT_FETCH:
919 920 921 922
  {
    mysql_stmt_fetch(thd, packet, packet_length);
    break;
  }
923
  case COM_STMT_SEND_LONG_DATA:
unknown's avatar
unknown committed
924
  {
925
    mysql_stmt_get_longdata(thd, packet, packet_length);
unknown's avatar
unknown committed
926 927
    break;
  }
928
  case COM_STMT_PREPARE:
unknown's avatar
unknown committed
929
  {
930
    mysql_stmt_prepare(thd, packet, packet_length);
unknown's avatar
unknown committed
931 932
    break;
  }
933
  case COM_STMT_CLOSE:
unknown's avatar
unknown committed
934
  {
935
    mysql_stmt_close(thd, packet);
unknown's avatar
unknown committed
936 937
    break;
  }
938
  case COM_STMT_RESET:
939 940 941 942
  {
    mysql_stmt_reset(thd, packet);
    break;
  }
unknown's avatar
unknown committed
943 944
  case COM_QUERY:
  {
945 946
    if (alloc_query(thd, packet, packet_length))
      break;					// fatal error is set
947
    char *packet_end= thd->query + thd->query_length;
unknown's avatar
unknown committed
948 949
    /* 'b' stands for 'buffer' parameter', special for 'my_snprintf' */
    const char *format= "%.*b";
950 951
    const char* found_semicolon= NULL;

unknown's avatar
unknown committed
952
    general_log_print(thd, command, format, thd->query_length, thd->query);
953
    DBUG_PRINT("query",("%-.4096s",thd->query));
954 955 956 957

    if (!(specialflag & SPECIAL_NO_PRIOR))
      my_pthread_setprio(pthread_self(),QUERY_PRIOR);

958
    mysql_parse(thd, thd->query, thd->query_length, & found_semicolon);
959

960
    while (!thd->killed && found_semicolon && !thd->net.report_error)
961
    {
962
      char *next_packet= (char*) found_semicolon;
963
      net->no_send_error= 0;
964
      /*
965 966
        Multiple queries exits, execute them individually
      */
967 968
      if (thd->lock || thd->open_tables || thd->derived_tables ||
          thd->prelocked_mode)
969
        close_thread_tables(thd);
unknown's avatar
unknown committed
970
      ulong length= (ulong)(packet_end - next_packet);
971

972
      log_slow_statement(thd);
973

974
      /* Remove garbage at start of query */
unknown's avatar
unknown committed
975
      while (my_isspace(thd->charset(), *next_packet) && length > 0)
976
      {
unknown's avatar
unknown committed
977
        next_packet++;
978 979
        length--;
      }
unknown's avatar
unknown committed
980
      VOID(pthread_mutex_lock(&LOCK_thread_count));
981
      thd->query_length= length;
unknown's avatar
unknown committed
982
      thd->query= next_packet;
983
      thd->query_id= next_query_id();
984
      thd->set_time(); /* Reset the query start time. */
985
      /* TODO: set thd->lex->sql_command to SQLCOM_END here */
986
      VOID(pthread_mutex_unlock(&LOCK_thread_count));
987
      mysql_parse(thd, next_packet, length, & found_semicolon);
988 989
    }

unknown's avatar
unknown committed
990 991 992 993 994
    if (!(specialflag & SPECIAL_NO_PRIOR))
      my_pthread_setprio(pthread_self(),WAIT_PRIOR);
    DBUG_PRINT("info",("query ready"));
    break;
  }
995
  case COM_FIELD_LIST:				// This isn't actually needed
unknown's avatar
unknown committed
996
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
997 998
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
unknown's avatar
unknown committed
999 1000 1001
    break;
#else
  {
1002
    char *fields, *packet_end= packet + packet_length - 1, *arg_end;
1003
    /* Locked closure of all tables */
unknown's avatar
unknown committed
1004
    TABLE_LIST table_list;
unknown's avatar
unknown committed
1005
    LEX_STRING conv_name;
unknown's avatar
unknown committed
1006

unknown's avatar
unknown committed
1007
    /* used as fields initializator */
1008
    lex_start(thd);
1009

1010
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
unknown's avatar
unknown committed
1011
    bzero((char*) &table_list,sizeof(table_list));
1012
    if (thd->copy_db_to(&table_list.db, &table_list.db_length))
unknown's avatar
unknown committed
1013
      break;
1014 1015 1016 1017
    /*
      We have name + wildcard in packet, separated by endzero
    */
    arg_end= strend(packet);
unknown's avatar
unknown committed
1018
    thd->convert_string(&conv_name, system_charset_info,
1019
			packet, (uint) (arg_end - packet), thd->charset());
1020
    table_list.alias= table_list.table_name= conv_name.str;
1021
    packet= arg_end + 1;
1022 1023

    if (!my_strcasecmp(system_charset_info, table_list.db,
1024
                       INFORMATION_SCHEMA_NAME.str))
1025 1026 1027 1028 1029 1030
    {
      ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, table_list.alias);
      if (schema_table)
        table_list.schema_table= schema_table;
    }

1031
    thd->query_length= (uint) (packet_end - packet); // Don't count end \0
1032
    if (!(thd->query=fields= (char*) thd->memdup(packet,thd->query_length+1)))
unknown's avatar
unknown committed
1033
      break;
unknown's avatar
unknown committed
1034
    general_log_print(thd, command, "%s %s", table_list.table_name, fields);
1035
    if (lower_case_table_names)
1036
      my_casedn_str(files_charset_info, table_list.table_name);
unknown's avatar
unknown committed
1037

unknown's avatar
unknown committed
1038
    if (check_access(thd,SELECT_ACL,table_list.db,&table_list.grant.privilege,
1039
		     0, 0, test(table_list.schema_table)))
unknown's avatar
unknown committed
1040
      break;
1041
    if (check_grant(thd, SELECT_ACL, &table_list, 2, UINT_MAX, 0))
unknown's avatar
unknown committed
1042
      break;
1043 1044
    /* init structures for VIEW processing */
    table_list.select_lex= &(thd->lex->select_lex);
1045 1046 1047 1048

    lex_start(thd);
    mysql_reset_thd_for_next_command(thd);

1049
    thd->lex->
1050 1051
      select_lex.table_list.link_in_list((uchar*) &table_list,
                                         (uchar**) &table_list.next_local);
unknown's avatar
unknown committed
1052
    thd->lex->add_to_query_tables(&table_list);
1053

1054 1055
    /* switch on VIEW optimisation: do not fill temporary tables */
    thd->lex->sql_command= SQLCOM_SHOW_FIELDS;
unknown's avatar
unknown committed
1056
    mysqld_list_fields(thd,&table_list,fields);
1057
    thd->lex->unit.cleanup();
1058
    thd->cleanup_after_query();
unknown's avatar
unknown committed
1059 1060 1061 1062
    break;
  }
#endif
  case COM_QUIT:
1063
    /* We don't calculate statistics for this command */
unknown's avatar
unknown committed
1064
    general_log_print(thd, command, NullS);
unknown's avatar
unknown committed
1065 1066 1067 1068
    net->error=0;				// Don't give 'abort' message
    error=TRUE;					// End server
    break;

1069
#ifdef REMOVED
unknown's avatar
unknown committed
1070
  case COM_CREATE_DB:				// QQ: To be removed
unknown's avatar
unknown committed
1071
    {
1072
      LEX_STRING db, alias;
1073
      HA_CREATE_INFO create_info;
unknown's avatar
unknown committed
1074

1075
      status_var_increment(thd->status_var.com_stat[SQLCOM_CREATE_DB]);
1076 1077
      if (thd->make_lex_string(&db, packet, packet_length - 1, FALSE) ||
          thd->make_lex_string(&alias, db.str, db.length, FALSE) ||
1078
          check_db_name(&db))
1079
      {
1080
	my_error(ER_WRONG_DB_NAME, MYF(0), db.str ? db.str : "NULL");
1081 1082
	break;
      }
1083 1084
      if (check_access(thd, CREATE_ACL, db.str , 0, 1, 0,
                       is_schema_db(db.str)))
unknown's avatar
unknown committed
1085
	break;
unknown's avatar
unknown committed
1086
      general_log_print(thd, command, packet);
1087
      bzero(&create_info, sizeof(create_info));
1088
      mysql_create_db(thd, (lower_case_table_names == 2 ? alias.str : db.str),
1089
                      &create_info, 0);
unknown's avatar
unknown committed
1090 1091
      break;
    }
unknown's avatar
unknown committed
1092
  case COM_DROP_DB:				// QQ: To be removed
unknown's avatar
unknown committed
1093
    {
1094
      status_var_increment(thd->status_var.com_stat[SQLCOM_DROP_DB]);
1095 1096
      LEX_STRING db;

1097
      if (thd->make_lex_string(&db, packet, packet_length - 1, FALSE) ||
1098
          check_db_name(&db))
1099
      {
1100
	my_error(ER_WRONG_DB_NAME, MYF(0), db.str ? db.str : "NULL");
1101 1102
	break;
      }
1103
      if (check_access(thd, DROP_ACL, db.str, 0, 1, 0, is_schema_db(db.str)))
1104
	break;
unknown's avatar
unknown committed
1105 1106
      if (thd->locked_tables || thd->active_transaction())
      {
unknown's avatar
unknown committed
1107 1108
	my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                   ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
unknown's avatar
unknown committed
1109
	break;
unknown's avatar
unknown committed
1110
      }
1111 1112
      general_log_print(thd, command, db.str);
      mysql_rm_db(thd, db.str, 0, 0);
unknown's avatar
unknown committed
1113 1114
      break;
    }
1115
#endif
1116
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
1117 1118
  case COM_BINLOG_DUMP:
    {
unknown's avatar
unknown committed
1119 1120 1121 1122
      ulong pos;
      ushort flags;
      uint32 slave_server_id;

1123
      status_var_increment(thd->status_var.com_other);
1124
      thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
unknown committed
1125
      if (check_global_access(thd, REPL_SLAVE_ACL))
unknown's avatar
unknown committed
1126
	break;
unknown's avatar
unknown committed
1127

1128
      /* TODO: The following has to be changed to an 8 byte integer */
1129 1130
      pos = uint4korr(packet);
      flags = uint2korr(packet + 4);
unknown's avatar
unknown committed
1131
      thd->server_id=0; /* avoid suicide */
unknown's avatar
unknown committed
1132
      if ((slave_server_id= uint4korr(packet+6))) // mysqlbinlog.server_id==0
unknown's avatar
unknown committed
1133
	kill_zombie_dump_threads(slave_server_id);
1134
      thd->server_id = slave_server_id;
unknown's avatar
unknown committed
1135

unknown's avatar
unknown committed
1136
      general_log_print(thd, command, "Log: '%s'  Pos: %ld", packet+10,
unknown's avatar
unknown committed
1137
                      (long) pos);
1138
      mysql_binlog_send(thd, thd->strdup(packet + 10), (my_off_t) pos, flags);
unknown's avatar
unknown committed
1139
      unregister_slave(thd,1,1);
unknown's avatar
unknown committed
1140
      /*  fake COM_QUIT -- if we get here, the thread needs to terminate */
1141 1142
      error = TRUE;
      net->error = 0;
unknown's avatar
unknown committed
1143 1144
      break;
    }
1145
#endif
unknown's avatar
unknown committed
1146
  case COM_REFRESH:
unknown's avatar
unknown committed
1147 1148
  {
    bool not_used;
1149
    status_var_increment(thd->status_var.com_stat[SQLCOM_FLUSH]);
unknown's avatar
unknown committed
1150 1151
    ulong options= (ulong) (uchar) packet[0];
    if (check_global_access(thd,RELOAD_ACL))
unknown's avatar
unknown committed
1152
      break;
unknown's avatar
unknown committed
1153
    general_log_print(thd, command, NullS);
unknown's avatar
unknown committed
1154 1155 1156 1157
    if (!reload_acl_and_cache(thd, options, (TABLE_LIST*) 0, &not_used))
      send_ok(thd);
    break;
  }
1158
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
1159
  case COM_SHUTDOWN:
1160
  {
1161
    status_var_increment(thd->status_var.com_other);
unknown's avatar
unknown committed
1162
    if (check_global_access(thd,SHUTDOWN_ACL))
unknown's avatar
unknown committed
1163
      break; /* purecov: inspected */
1164
    /*
1165 1166 1167 1168
      If the client is < 4.1.3, it is going to send us no argument; then
      packet_length is 1, packet[0] is the end 0 of the packet. Note that
      SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in
      packet[0].
1169
    */
1170 1171
    enum mysql_enum_shutdown_level level=
      (enum mysql_enum_shutdown_level) (uchar) packet[0];
1172 1173 1174 1175 1176 1177 1178
    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;
    }
1179
    DBUG_PRINT("quit",("Got shutdown command for level %u", level));
unknown's avatar
unknown committed
1180
    general_log_print(thd, command, NullS);
1181
    send_eof(thd);
unknown's avatar
unknown committed
1182 1183 1184
#ifdef __WIN__
    sleep(1);					// must wait after eof()
#endif
1185 1186 1187 1188 1189 1190
    /*
      The client is next going to send a COM_QUIT request (as part of
      mysql_close()). Make the life simpler for the client by sending
      the response for the coming COM_QUIT in advance
    */
    send_eof(thd);
1191
    close_connection(thd, 0, 1);
unknown's avatar
unknown committed
1192 1193 1194 1195
    close_thread_tables(thd);			// Free before kill
    kill_mysql();
    error=TRUE;
    break;
1196
  }
1197
#endif
unknown's avatar
unknown committed
1198 1199
  case COM_STATISTICS:
  {
1200 1201 1202
    STATUS_VAR current_global_status_var;
    ulong uptime;
    uint length;
1203
    ulonglong queries_per_second1000;
unknown's avatar
unknown committed
1204
#ifndef EMBEDDED_LIBRARY
1205 1206
    char buff[250];
    uint buff_len= sizeof(buff);
unknown's avatar
unknown committed
1207 1208
#else
    char *buff= thd->net.last_error;
1209
    uint buff_len= sizeof(thd->net.last_error);
unknown's avatar
unknown committed
1210
#endif
1211

1212
    general_log_print(thd, command, NullS);
1213
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]);
1214
    calc_sum_of_all_status(&current_global_status_var);
1215 1216 1217 1218 1219
    if (!(uptime= (ulong) (thd->start_time - server_start_time)))
      queries_per_second1000= 0;
    else
      queries_per_second1000= thd->query_id * LL(1000) / uptime;

1220 1221 1222
    length= my_snprintf((char*) buff, buff_len - 1,
                        "Uptime: %lu  Threads: %d  Questions: %lu  "
                        "Slow queries: %lu  Opens: %lu  Flush tables: %lu  "
1223
                        "Open tables: %u  Queries per second avg: %u.%u",
1224 1225 1226 1227 1228 1229
                        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(),
1230 1231
                        (uint) (queries_per_second1000 / 1000),
                        (uint) (queries_per_second1000 % 1000));
unknown's avatar
unknown committed
1232
#ifdef SAFEMALLOC
1233
    if (sf_malloc_cur_memory)				// Using SAFEMALLOC
1234 1235 1236 1237 1238 1239 1240
    {
      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
1241 1242
#endif
#ifndef EMBEDDED_LIBRARY
1243
    VOID(my_net_write(net, (uchar*) buff, length));
1244
      VOID(net_flush(net));
unknown's avatar
unknown committed
1245
#endif
unknown's avatar
unknown committed
1246 1247 1248
    break;
  }
  case COM_PING:
1249
    status_var_increment(thd->status_var.com_other);
1250
    send_ok(thd);				// Tell client we are alive
unknown's avatar
unknown committed
1251 1252
    break;
  case COM_PROCESS_INFO:
1253
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]);
1254 1255
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd, PROCESS_ACL))
unknown's avatar
unknown committed
1256
      break;
unknown's avatar
unknown committed
1257
    general_log_print(thd, command, NullS);
unknown's avatar
unknown committed
1258
    mysqld_list_processes(thd,
1259 1260
			  thd->security_ctx->master_access & PROCESS_ACL ? 
			  NullS : thd->security_ctx->priv_user, 0);
unknown's avatar
unknown committed
1261 1262 1263
    break;
  case COM_PROCESS_KILL:
  {
1264
    status_var_increment(thd->status_var.com_stat[SQLCOM_KILL]);
1265
    ulong id=(ulong) uint4korr(packet);
1266
    sql_kill(thd,id,false);
unknown's avatar
unknown committed
1267 1268
    break;
  }
1269 1270
  case COM_SET_OPTION:
  {
1271
    status_var_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION]);
unknown's avatar
unknown committed
1272 1273 1274 1275
    uint opt_command= uint2korr(packet);

    switch (opt_command) {
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON:
1276
      thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
unknown's avatar
unknown committed
1277
      send_eof(thd);
1278
      break;
unknown's avatar
unknown committed
1279
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF:
1280
      thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
unknown's avatar
unknown committed
1281
      send_eof(thd);
1282 1283
      break;
    default:
unknown's avatar
unknown committed
1284
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1285 1286 1287 1288
      break;
    }
    break;
  }
unknown's avatar
unknown committed
1289
  case COM_DEBUG:
1290
    status_var_increment(thd->status_var.com_other);
unknown's avatar
unknown committed
1291
    if (check_global_access(thd, SUPER_ACL))
unknown's avatar
unknown committed
1292
      break;					/* purecov: inspected */
1293
    mysql_print_status();
unknown's avatar
unknown committed
1294
    general_log_print(thd, command, NullS);
1295
    send_eof(thd);
unknown's avatar
unknown committed
1296 1297 1298 1299 1300
    break;
  case COM_SLEEP:
  case COM_CONNECT:				// Impossible here
  case COM_TIME:				// Impossible from client
  case COM_DELAYED_INSERT:
1301
  case COM_END:
unknown's avatar
unknown committed
1302
  default:
unknown's avatar
unknown committed
1303
    my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
unknown's avatar
unknown committed
1304 1305
    break;
  }
1306 1307
  if (thd->lock || thd->open_tables || thd->derived_tables ||
      thd->prelocked_mode)
unknown's avatar
unknown committed
1308 1309 1310 1311
  {
    thd->proc_info="closing tables";
    close_thread_tables(thd);			/* Free tables */
  }
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
  /*
    assume handlers auto-commit (if some doesn't - transaction handling
    in MySQL should be redesigned to support it; it's a big change,
    and it's not worth it - better to commit explicitly only writing
    transactions, read-only ones should better take care of themselves.
    saves some work in 2pc too)
    see also sql_base.cc - close_thread_tables()
  */
  bzero(&thd->transaction.stmt, sizeof(thd->transaction.stmt));
  if (!thd->active_transaction())
1322
    thd->transaction.xid_state.xid.null();
unknown's avatar
unknown committed
1323

unknown's avatar
unknown committed
1324 1325 1326
  /* report error issued during command execution */
  if (thd->killed_errno() && !thd->net.report_error)
    thd->send_kill_message();
unknown's avatar
unknown committed
1327
  if (thd->net.report_error)
1328
    net_send_error(thd);
unknown's avatar
unknown committed
1329

1330
  log_slow_statement(thd);
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345

  thd->proc_info="cleaning up";
  VOID(pthread_mutex_lock(&LOCK_thread_count)); // For process list
  thd->proc_info=0;
  thd->command=COM_SLEEP;
  thd->query=0;
  thd->query_length=0;
  thread_running--;
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
  thd->packet.shrink(thd->variables.net_buffer_length);	// Reclaim some memory
  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
  DBUG_RETURN(error);
}


1346
void log_slow_statement(THD *thd)
1347
{
unknown's avatar
unknown committed
1348
  DBUG_ENTER("log_slow_statement");
1349 1350 1351 1352 1353 1354 1355

  /*
    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
1356
    DBUG_VOID_RETURN;                           // Don't set time for sub stmt
1357

1358 1359 1360 1361 1362
  /*
    Do not log administrative statements unless the appropriate option is
    set; do not log into slow log if reading from backup.
  */
  if (thd->enable_slow_log && !thd->user_time)
unknown's avatar
unknown committed
1363
  {
1364
    ulonglong end_utime_of_query= thd->current_utime();
1365

1366 1367 1368 1369 1370
    thd->proc_info="logging slow query";
    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)) &&
1371 1372
          opt_log_queries_not_using_indexes &&
           !(sql_command_flags[thd->lex->sql_command] & CF_STATUS_COMMAND))) &&
1373
        thd->examined_row_count >= thd->variables.min_examined_row_limit)
1374
    {
1375
      thd->status_var.long_query_count++;
1376
      slow_log_print(thd, thd->query, thd->query_length, end_utime_of_query);
1377
    }
unknown's avatar
unknown committed
1378
  }
unknown's avatar
unknown committed
1379
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1380 1381
}

1382

unknown's avatar
unknown committed
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
/*
  Create a TABLE_LIST object for an INFORMATION_SCHEMA table.

  SYNOPSIS
    prepare_schema_table()
      thd              thread handle
      lex              current lex
      table_ident      table alias if it's used
      schema_table_idx the type of the INFORMATION_SCHEMA table to be
                       created

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

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

  RETURN VALUE
    0                 success
    1                 out of memory or SHOW commands are not allowed
                      in this version of the server.
*/

1411 1412 1413
int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident,
                         enum enum_schema_tables schema_table_idx)
{
1414
  SELECT_LEX *schema_select_lex= NULL;
1415
  DBUG_ENTER("prepare_schema_table");
1416

1417
  switch (schema_table_idx) {
1418 1419
  case SCH_SCHEMATA:
#if defined(DONT_ALLOW_SHOW_COMMANDS)
unknown's avatar
unknown committed
1420 1421
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0));   /* purecov: inspected */
1422 1423 1424 1425
    DBUG_RETURN(1);
#else
    break;
#endif
1426

1427 1428 1429
  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
1430
  case SCH_TRIGGERS:
unknown's avatar
unknown committed
1431
  case SCH_EVENTS:
1432
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
1433 1434
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1435 1436 1437
    DBUG_RETURN(1);
#else
    {
1438
      LEX_STRING db;
1439
      size_t dummy;
unknown's avatar
unknown committed
1440
      if (lex->select_lex.db == NULL &&
1441
          lex->copy_db_to(&lex->select_lex.db, &dummy))
1442
      {
unknown's avatar
unknown committed
1443
        DBUG_RETURN(1);
1444
      }
1445 1446 1447
      schema_select_lex= new SELECT_LEX();
      db.str= schema_select_lex->db= lex->select_lex.db;
      schema_select_lex->table_list.first= NULL;
1448
      db.length= strlen(db.str);
unknown's avatar
unknown committed
1449

1450
      if (check_db_name(&db))
1451
      {
1452
        my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
1453 1454 1455 1456 1457 1458 1459
        DBUG_RETURN(1);
      }
      break;
    }
#endif
  case SCH_COLUMNS:
  case SCH_STATISTICS:
unknown's avatar
unknown committed
1460
  {
1461
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
1462 1463
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1464 1465
    DBUG_RETURN(1);
#else
unknown's avatar
unknown committed
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
    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;
  }
1477
#endif
1478 1479 1480
  case SCH_OPEN_TABLES:
  case SCH_VARIABLES:
  case SCH_STATUS:
1481 1482
  case SCH_PROCEDURES:
  case SCH_CHARSETS:
unknown's avatar
unknown committed
1483
  case SCH_ENGINES:
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
  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
1502
  table_list->schema_select_lex= schema_select_lex;
1503
  table_list->schema_table_reformed= 1;
1504 1505 1506 1507
  DBUG_RETURN(0);
}


1508 1509
/*
  Read query from packet and store in thd->query
1510
  Used in COM_QUERY and COM_STMT_PREPARE
1511 1512 1513 1514 1515 1516 1517

  DESCRIPTION
    Sets the following THD variables:
      query
      query_length

  RETURN VALUES
unknown's avatar
unknown committed
1518 1519
    FALSE ok
    TRUE  error;  In this case thd->fatal_error is set
1520 1521
*/

1522
bool alloc_query(THD *thd, const char *packet, uint packet_length)
1523 1524
{
  packet_length--;				// Remove end null
1525
  /* Remove garbage at start and end of query */
unknown's avatar
unknown committed
1526
  while (my_isspace(thd->charset(),packet[0]) && packet_length > 0)
1527 1528 1529 1530
  {
    packet++;
    packet_length--;
  }
1531
  const char *pos= packet + packet_length;     // Point at end null
unknown's avatar
unknown committed
1532
  while (packet_length > 0 &&
unknown's avatar
unknown committed
1533
	 (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1])))
1534 1535 1536 1537 1538
  {
    pos--;
    packet_length--;
  }
  /* We must allocate some extra memory for query cache */
unknown's avatar
unknown committed
1539
  thd->query_length= 0;                        // Extra safety: Avoid races
1540
  if (!(thd->query= (char*) thd->memdup_w_gap((uchar*) (packet),
1541
					      packet_length,
1542 1543
					      thd->db_length+ 1 +
					      QUERY_CACHE_FLAGS_SIZE)))
unknown's avatar
unknown committed
1544
    return TRUE;
1545 1546
  thd->query[packet_length]=0;
  thd->query_length= packet_length;
1547 1548 1549 1550

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

unknown's avatar
unknown committed
1552
  return FALSE;
1553 1554
}

1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
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;
1568
  thd->variables.lc_time_names= &my_locale_en_US;
1569 1570 1571
  thd->one_shot_set= 0;
}

1572

1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
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);

1619
    if (thd->slave_thread && lex->sphead)
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
      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);
}


1658
/*
1659
  Execute command saved in thd and lex->sql_command
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680

  SYNOPSIS
    mysql_execute_command()
      thd                       Thread handle

  IMPLEMENTATION

    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.

  RETURN
    FALSE       OK
    TRUE        Error
*/
unknown's avatar
unknown committed
1681

unknown's avatar
unknown committed
1682
bool
1683
mysql_execute_command(THD *thd)
unknown's avatar
unknown committed
1684
{
1685 1686
  bool res= FALSE;
  bool need_start_waiting= FALSE; // have protection against global read lock
unknown's avatar
unknown committed
1687
  int  up_result= 0;
1688
  LEX  *lex= thd->lex;
unknown's avatar
unknown committed
1689
  /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
unknown's avatar
unknown committed
1690
  SELECT_LEX *select_lex= &lex->select_lex;
unknown's avatar
VIEW  
unknown committed
1691
  /* first table of first SELECT_LEX */
unknown's avatar
unknown committed
1692
  TABLE_LIST *first_table= (TABLE_LIST*) select_lex->table_list.first;
unknown's avatar
VIEW  
unknown committed
1693 1694 1695
  /* list of all tables in query */
  TABLE_LIST *all_tables;
  /* most outer SELECT_LEX_UNIT of query */
1696
  SELECT_LEX_UNIT *unit= &lex->unit;
1697
  /* Saved variable value */
unknown's avatar
unknown committed
1698
  DBUG_ENTER("mysql_execute_command");
1699
  thd->net.no_send_error= 0;
unknown's avatar
unknown committed
1700 1701 1702
#ifdef WITH_PARTITION_STORAGE_ENGINE
  thd->work_part_info= 0;
#endif
unknown's avatar
unknown committed
1703

unknown's avatar
VIEW  
unknown committed
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
  /*
    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();
1720
  /* should be assigned after making first tables same */
unknown's avatar
VIEW  
unknown committed
1721
  all_tables= lex->query_tables;
1722 1723 1724 1725
  /* 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
1726

1727 1728 1729 1730 1731
  /*
    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.
1732
    Don't reset warnings when executing a stored routine.
1733
  */
1734
  if ((all_tables || !lex->is_single_level_stmt()) && !thd->spcont)
unknown's avatar
unknown committed
1735
    mysql_reset_errors(thd, 0);
1736

unknown's avatar
SCRUM  
unknown committed
1737
#ifdef HAVE_REPLICATION
1738
  if (unlikely(thd->slave_thread))
1739
  {
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
    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;
    }
    
unknown's avatar
unknown committed
1764
    /*
unknown's avatar
unknown committed
1765 1766
      Check if statment should be skipped because of slave filtering
      rules
1767 1768

      Exceptions are:
unknown's avatar
unknown committed
1769 1770
      - UPDATE MULTI: For this statement, we want to check the filtering
        rules later in the code
1771
      - SET: we always execute it (Not that many SET commands exists in
unknown's avatar
unknown committed
1772 1773
        the binary log anyway -- only 4.1 masters write SET statements,
	in 5.0 there are no SET statements in the binary log)
1774 1775
      - 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
1776
    */
unknown's avatar
unknown committed
1777 1778
    if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) &&
	!(lex->sql_command == SQLCOM_SET_OPTION) &&
1779
	!(lex->sql_command == SQLCOM_DROP_TABLE &&
1780
          lex->drop_temporary && lex->drop_if_exists) &&
unknown's avatar
Merge  
unknown committed
1781
        all_tables_not_ok(thd, all_tables))
unknown's avatar
unknown committed
1782 1783
    {
      /* we warn the slave SQL thread */
unknown's avatar
unknown committed
1784
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
      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);
      }
1802
      DBUG_RETURN(0);
unknown's avatar
unknown committed
1803
    }
1804
  }
1805
  else
1806
  {
1807
#endif /* HAVE_REPLICATION */
1808 1809 1810 1811 1812 1813
    /*
      When option readonly is set deny operations which change non-temporary
      tables. Except for the replication thread and the 'super' users.
    */
    if (opt_readonly &&
	!(thd->security_ctx->master_access & SUPER_ACL) &&
1814
	(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA) &&
1815 1816 1817 1818 1819
        !((lex->sql_command == SQLCOM_CREATE_TABLE) &&
          (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE)) &&
        !((lex->sql_command == SQLCOM_DROP_TABLE) && lex->drop_temporary) &&
        ((lex->sql_command != SQLCOM_UPDATE_MULTI) &&
          some_non_temp_table_to_be_updated(thd, all_tables)))
1820 1821 1822 1823 1824 1825 1826
    {
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
      DBUG_RETURN(-1);
    }
#ifdef HAVE_REPLICATION
  } /* endif unlikely slave */
#endif
1827
  status_var_increment(thd->status_var.com_stat[lex->sql_command]);
1828

unknown's avatar
unknown committed
1829 1830
  DBUG_ASSERT(thd->transaction.stmt.modified_non_trans_table == FALSE);
  
unknown's avatar
unknown committed
1831
  switch (lex->sql_command) {
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 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
  case SQLCOM_SHOW_EVENTS:
    if ((res= check_access(thd, EVENT_ACL, thd->lex->select_lex.db, 0, 0, 0,
                           is_schema_db(thd->lex->select_lex.db))))
      break;
    /* fall through */
  case SQLCOM_SHOW_STATUS_PROC:
  case SQLCOM_SHOW_STATUS_FUNC:
    res= execute_sqlcom_select(thd, all_tables);
    break;
  case SQLCOM_SHOW_STATUS:
  {
    system_status_var old_status_var= thd->status_var;
    thd->initial_status_var= &old_status_var;
    res= execute_sqlcom_select(thd, all_tables);
    /* 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:
1871
  case SQLCOM_SHOW_STORAGE_ENGINES:
unknown's avatar
unknown committed
1872
  case SQLCOM_SELECT:
1873
    thd->status_var.last_query_cost= 0.0;
unknown's avatar
VIEW  
unknown committed
1874
    if (all_tables)
unknown's avatar
unknown committed
1875
    {
1876 1877 1878 1879
      res= check_table_access(thd,
                              lex->exchange ? SELECT_ACL | FILE_ACL :
                              SELECT_ACL,
                              all_tables, 0);
unknown's avatar
unknown committed
1880 1881
    }
    else
unknown's avatar
VIEW  
unknown committed
1882
      res= check_access(thd,
1883 1884 1885 1886
                        lex->exchange ? SELECT_ACL | FILE_ACL : SELECT_ACL,
                        any_db, 0, 0, 0, 0);
    if (!res)
      res= execute_sqlcom_select(thd, all_tables);
unknown's avatar
unknown committed
1887
    break;
unknown's avatar
unknown committed
1888
  case SQLCOM_PREPARE:
1889
  {
1890
    mysql_sql_stmt_prepare(thd);
unknown's avatar
unknown committed
1891 1892 1893 1894
    break;
  }
  case SQLCOM_EXECUTE:
  {
1895
    mysql_sql_stmt_execute(thd);
unknown's avatar
unknown committed
1896 1897 1898 1899
    break;
  }
  case SQLCOM_DEALLOCATE_PREPARE:
  {
1900
    mysql_sql_stmt_close(thd);
unknown's avatar
unknown committed
1901 1902
    break;
  }
unknown's avatar
unknown committed
1903
  case SQLCOM_DO:
1904 1905
    if (check_table_access(thd, SELECT_ACL, all_tables, 0) ||
        open_and_lock_tables(thd, all_tables))
unknown's avatar
unknown committed
1906
      goto error;
unknown's avatar
unknown committed
1907 1908

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

1911
  case SQLCOM_EMPTY_QUERY:
1912
    send_ok(thd);
1913 1914
    break;

unknown's avatar
unknown committed
1915 1916 1917 1918
  case SQLCOM_HELP:
    res= mysqld_help(thd,lex->help_arg);
    break;

1919
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
1920
  case SQLCOM_PURGE:
1921
  {
unknown's avatar
unknown committed
1922
    if (check_global_access(thd, SUPER_ACL))
1923
      goto error;
unknown's avatar
unknown committed
1924
    /* PURGE MASTER LOGS TO 'file' */
1925 1926 1927
    res = purge_master_logs(thd, lex->to_log);
    break;
  }
1928 1929
  case SQLCOM_PURGE_BEFORE:
  {
1930 1931
    Item *it;

1932 1933
    if (check_global_access(thd, SUPER_ACL))
      goto error;
unknown's avatar
unknown committed
1934
    /* PURGE MASTER LOGS BEFORE 'data' */
1935
    it= (Item *)lex->value_list.head();
1936
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) ||
unknown's avatar
unknown committed
1937
        it->check_cols(1))
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
    {
      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());
1949 1950
    break;
  }
1951
#endif
unknown's avatar
unknown committed
1952 1953
  case SQLCOM_SHOW_WARNS:
  {
1954 1955
    res= mysqld_show_warnings(thd, (ulong)
			      ((1L << (uint) MYSQL_ERROR::WARN_LEVEL_NOTE) |
1956 1957 1958
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_WARN) |
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR)
			       ));
unknown's avatar
unknown committed
1959 1960 1961 1962
    break;
  }
  case SQLCOM_SHOW_ERRORS:
  {
1963 1964
    res= mysqld_show_warnings(thd, (ulong)
			      (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR));
unknown's avatar
unknown committed
1965 1966
    break;
  }
unknown's avatar
unknown committed
1967 1968
  case SQLCOM_SHOW_NEW_MASTER:
  {
unknown's avatar
unknown committed
1969
    if (check_global_access(thd, REPL_SLAVE_ACL))
unknown's avatar
unknown committed
1970
      goto error;
1971
    /* This query don't work now. See comment in repl_failsafe.cc */
unknown's avatar
unknown committed
1972
#ifndef WORKING_NEW_MASTER
unknown's avatar
unknown committed
1973 1974
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "SHOW NEW MASTER");
    goto error;
unknown's avatar
unknown committed
1975
#else
unknown's avatar
unknown committed
1976 1977
    res = show_new_master(thd);
    break;
unknown's avatar
unknown committed
1978
#endif
unknown's avatar
unknown committed
1979
  }
1980

unknown's avatar
unknown committed
1981
#ifdef HAVE_REPLICATION
1982 1983
  case SQLCOM_SHOW_SLAVE_HOSTS:
  {
unknown's avatar
unknown committed
1984
    if (check_global_access(thd, REPL_SLAVE_ACL))
1985 1986 1987 1988
      goto error;
    res = show_slave_hosts(thd);
    break;
  }
unknown's avatar
unknown committed
1989 1990
  case SQLCOM_SHOW_BINLOG_EVENTS:
  {
unknown's avatar
unknown committed
1991
    if (check_global_access(thd, REPL_SLAVE_ACL))
unknown's avatar
unknown committed
1992
      goto error;
1993
    res = mysql_show_binlog_events(thd);
unknown's avatar
unknown committed
1994 1995
    break;
  }
1996 1997
#endif

unknown's avatar
unknown committed
1998
  case SQLCOM_BACKUP_TABLE:
1999
  {
unknown's avatar
VIEW  
unknown committed
2000
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2001
    if (check_table_access(thd, SELECT_ACL, all_tables, 0) ||
unknown's avatar
unknown committed
2002
	check_global_access(thd, FILE_ACL))
2003
      goto error; /* purecov: inspected */
2004
    thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
VIEW  
unknown committed
2005
    res = mysql_backup_table(thd, first_table);
2006
    select_lex->table_list.first= (uchar*) first_table;
2007
    lex->query_tables=all_tables;
2008 2009
    break;
  }
unknown's avatar
unknown committed
2010
  case SQLCOM_RESTORE_TABLE:
2011
  {
unknown's avatar
VIEW  
unknown committed
2012
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2013
    if (check_table_access(thd, INSERT_ACL, all_tables, 0) ||
unknown's avatar
unknown committed
2014
	check_global_access(thd, FILE_ACL))
2015
      goto error; /* purecov: inspected */
2016
    thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
VIEW  
unknown committed
2017
    res = mysql_restore_table(thd, first_table);
2018
    select_lex->table_list.first= (uchar*) first_table;
2019
    lex->query_tables=all_tables;
2020 2021
    break;
  }
unknown's avatar
unknown committed
2022 2023
  case SQLCOM_ASSIGN_TO_KEYCACHE:
  {
unknown's avatar
VIEW  
unknown committed
2024
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2025
    if (check_access(thd, INDEX_ACL, first_table->db,
2026 2027
                     &first_table->grant.privilege, 0, 0,
                     test(first_table->schema_table)))
unknown's avatar
unknown committed
2028
      goto error;
2029
    res= mysql_assign_to_keycache(thd, first_table, &lex->ident);
unknown's avatar
unknown committed
2030 2031
    break;
  }
unknown's avatar
unknown committed
2032 2033
  case SQLCOM_PRELOAD_KEYS:
  {
unknown's avatar
VIEW  
unknown committed
2034
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2035
    if (check_access(thd, INDEX_ACL, first_table->db,
2036 2037
                     &first_table->grant.privilege, 0, 0,
                     test(first_table->schema_table)))
2038
      goto error;
unknown's avatar
VIEW  
unknown committed
2039
    res = mysql_preload_keys(thd, first_table);
unknown's avatar
unknown committed
2040 2041
    break;
  }
unknown's avatar
unknown committed
2042
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
2043
  case SQLCOM_CHANGE_MASTER:
2044
  {
unknown's avatar
unknown committed
2045
    if (check_global_access(thd, SUPER_ACL))
2046
      goto error;
2047
    pthread_mutex_lock(&LOCK_active_mi);
2048
    res = change_master(thd,active_mi);
2049
    pthread_mutex_unlock(&LOCK_active_mi);
2050 2051
    break;
  }
unknown's avatar
unknown committed
2052
  case SQLCOM_SHOW_SLAVE_STAT:
2053
  {
2054 2055
    /* Accept one of two privileges */
    if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
2056
      goto error;
2057
    pthread_mutex_lock(&LOCK_active_mi);
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
    if (active_mi != NULL)
    {
      res = show_master_info(thd, active_mi);
    }
    else
    {
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0,
                   "the master info structure does not exist");
      send_ok(thd);
    }
2068
    pthread_mutex_unlock(&LOCK_active_mi);
2069 2070
    break;
  }
unknown's avatar
unknown committed
2071
  case SQLCOM_SHOW_MASTER_STAT:
2072
  {
2073 2074
    /* Accept one of two privileges */
    if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
2075 2076 2077 2078
      goto error;
    res = show_binlog_info(thd);
    break;
  }
unknown's avatar
unknown committed
2079

2080
  case SQLCOM_LOAD_MASTER_DATA: // sync with master
unknown's avatar
unknown committed
2081
    if (check_global_access(thd, SUPER_ACL))
2082
      goto error;
2083
    if (end_active_trans(thd))
unknown's avatar
unknown committed
2084
      goto error;
2085
    res = load_master_data(thd);
2086
    break;
unknown's avatar
unknown committed
2087
#endif /* HAVE_REPLICATION */
unknown's avatar
unknown committed
2088
  case SQLCOM_SHOW_ENGINE_STATUS:
unknown's avatar
unknown committed
2089
    {
2090
      if (check_global_access(thd, SUPER_ACL))
unknown's avatar
unknown committed
2091 2092
        goto error;
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS);
unknown's avatar
unknown committed
2093 2094
      break;
    }
unknown's avatar
unknown committed
2095
  case SQLCOM_SHOW_ENGINE_MUTEX:
unknown's avatar
unknown committed
2096 2097
    {
      if (check_global_access(thd, SUPER_ACL))
unknown's avatar
unknown committed
2098
        goto error;
unknown's avatar
unknown committed
2099
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX);
unknown's avatar
unknown committed
2100 2101
      break;
    }
unknown's avatar
unknown committed
2102
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
2103
  case SQLCOM_LOAD_MASTER_TABLE:
2104
  {
unknown's avatar
VIEW  
unknown committed
2105
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2106 2107
    DBUG_ASSERT(first_table->db); /* Must be set in the parser */

unknown's avatar
VIEW  
unknown committed
2108
    if (check_access(thd, CREATE_ACL, first_table->db,
2109 2110
		     &first_table->grant.privilege, 0, 0,
                     test(first_table->schema_table)))
unknown's avatar
unknown committed
2111
      goto error;				/* purecov: inspected */
2112 2113 2114 2115
    /* Check that the first table has CREATE privilege */
    if (check_grant(thd, CREATE_ACL, all_tables, 0, 1, 0))
      goto error;

2116
    pthread_mutex_lock(&LOCK_active_mi);
2117 2118 2119 2120
    /*
      fetch_master_table will send the error to the client on failure.
      Give error if the table already exists.
    */
2121
    if (!fetch_master_table(thd, first_table->db, first_table->table_name,
2122
			    active_mi, 0, 0))
2123
    {
2124
      send_ok(thd);
2125
    }
2126
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
2127
    break;
2128
  }
unknown's avatar
unknown committed
2129
#endif /* HAVE_REPLICATION */
2130

unknown's avatar
unknown committed
2131
  case SQLCOM_CREATE_TABLE:
unknown's avatar
unknown committed
2132
  {
2133
    /* If CREATE TABLE of non-temporary table, do implicit commit */
2134 2135 2136 2137 2138 2139 2140 2141
    if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
    {
      if (end_active_trans(thd))
      {
	res= -1;
	break;
      }
    }
unknown's avatar
VIEW  
unknown committed
2142 2143 2144 2145 2146
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    bool link_to_local;
    // Skip first table, which is the table we are creating
    TABLE_LIST *create_table= lex->unlink_first_table(&link_to_local);
    TABLE_LIST *select_tables= lex->query_tables;
2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
    /*
      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
2168

unknown's avatar
VIEW  
unknown committed
2169
    if ((res= create_table_precheck(thd, select_tables, create_table)))
unknown's avatar
unknown committed
2170
      goto end_with_restore_list;
unknown's avatar
unknown committed
2171

2172 2173 2174
    /* Might have been updated in create_table_precheck */
    create_info.alias= create_table->alias;

2175
#ifndef HAVE_READLINK
2176
    if (create_info.data_file_name)
2177 2178
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0,
                   "DATA DIRECTORY option ignored");
2179
    if (create_info.index_file_name)
2180 2181
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0,
                   "INDEX DIRECTORY option ignored");
2182
    create_info.data_file_name= create_info.index_file_name= NULL;
2183
#else
2184
    /* Fix names if symlinked tables */
2185
    if (append_file_to_dir(thd, &create_info.data_file_name,
2186
			   create_table->table_name) ||
2187
	append_file_to_dir(thd, &create_info.index_file_name,
2188
			   create_table->table_name))
unknown's avatar
unknown committed
2189
      goto end_with_restore_list;
2190
#endif
2191
    /*
2192
      If we are using SET CHARSET without DEFAULT, add an implicit
2193 2194
      DEFAULT to not confuse old users. (This may change).
    */
2195
    if ((create_info.used_fields &
2196 2197 2198
	 (HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) ==
	HA_CREATE_USED_CHARSET)
    {
2199 2200 2201 2202
      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;
2203
    }
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
    /*
      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
      created during a gobal read lock.
    */
2217 2218
    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
2219
    {
unknown's avatar
unknown committed
2220 2221
      res= 1;
      goto end_with_restore_list;
2222
    }
2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
#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
2234
    if (select_lex->item_list.elements)		// With select
unknown's avatar
unknown committed
2235 2236
    {
      select_result *result;
2237

2238
      select_lex->options|= SELECT_NO_UNLOCK;
2239
      unit->set_limit(select_lex);
2240

2241
      if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
unknown's avatar
unknown committed
2242 2243 2244 2245 2246 2247
      {
        lex->link_first_table_back(create_table, link_to_local);
        create_table->create= TRUE;
      }

      if (!(res= open_and_lock_tables(thd, lex->query_tables)))
2248
      {
2249 2250 2251 2252
        /*
          Is table which we are changing used somewhere in other parts
          of query
        */
2253
        if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
2254
        {
2255
          TABLE_LIST *duplicate;
unknown's avatar
unknown committed
2256
          create_table= lex->unlink_first_table(&link_to_local);
2257
          if ((duplicate= unique_table(thd, create_table, select_tables, 0)))
2258 2259 2260
          {
            update_non_unique_table_error(create_table, "CREATE", duplicate);
            res= 1;
2261
            goto end_with_restore_list;
2262
          }
2263
        }
unknown's avatar
unknown committed
2264
        /* If we create merge table, we have to test tables in merge, too */
2265
        if (create_info.used_fields & HA_CREATE_USED_UNION)
unknown's avatar
unknown committed
2266 2267
        {
          TABLE_LIST *tab;
2268
          for (tab= (TABLE_LIST*) create_info.merge_list.first;
unknown's avatar
unknown committed
2269 2270 2271
               tab;
               tab= tab->next_local)
          {
2272
            TABLE_LIST *duplicate;
2273
            if ((duplicate= unique_table(thd, tab, select_tables, 0)))
unknown's avatar
unknown committed
2274
            {
2275
              update_non_unique_table_error(tab, "CREATE", duplicate);
unknown's avatar
unknown committed
2276
              res= 1;
2277
              goto end_with_restore_list;
unknown's avatar
unknown committed
2278 2279 2280
            }
          }
        }
2281

unknown's avatar
unknown committed
2282
        /*
2283 2284
          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
2285
        */
unknown's avatar
VIEW  
unknown committed
2286
        if ((result= new select_create(create_table,
2287 2288 2289 2290
                                       &create_info,
                                       &alter_info,
                                       select_lex->item_list,
                                       lex->duplicates,
2291
                                       lex->ignore,
2292
                                       select_tables)))
2293 2294 2295 2296 2297
        {
          /*
            CREATE from SELECT give its SELECT_LEX for SELECT,
            and item_list belong to SELECT
          */
2298
          res= handle_select(thd, lex, result, 0);
2299
          delete result;
2300
        }
2301
      }
2302
      else if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
unknown's avatar
unknown committed
2303 2304
        create_table= lex->unlink_first_table(&link_to_local);

2305
    }
unknown's avatar
unknown committed
2306
    else
unknown's avatar
unknown committed
2307
    {
2308
      /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
2309
      if (create_info.options & HA_LEX_CREATE_TMP_TABLE)
2310
        thd->options|= OPTION_KEEP_LOG;
unknown's avatar
unknown committed
2311
      /* regular create */
2312
      if (create_info.options & HA_LEX_CREATE_TABLE_LIKE)
unknown's avatar
unknown committed
2313
        res= mysql_create_like_table(thd, create_table, select_tables,
2314
                                     &create_info);
unknown's avatar
unknown committed
2315
      else
2316
      {
unknown's avatar
VIEW  
unknown committed
2317
        res= mysql_create_table(thd, create_table->db,
2318 2319
                                create_table->table_name, &create_info,
                                &alter_info, 0, 0);
2320
      }
unknown's avatar
unknown committed
2321
      if (!res)
2322
	send_ok(thd);
unknown's avatar
unknown committed
2323
    }
2324

unknown's avatar
unknown committed
2325
    /* put tables back for PS rexecuting */
unknown's avatar
unknown committed
2326
end_with_restore_list:
unknown's avatar
VIEW  
unknown committed
2327
    lex->link_first_table_back(create_table, link_to_local);
unknown's avatar
unknown committed
2328
    break;
unknown's avatar
unknown committed
2329
  }
unknown's avatar
unknown committed
2330
  case SQLCOM_CREATE_INDEX:
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
    /* 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
2349 2350
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_one_table_access(thd, INDEX_ACL, all_tables))
unknown's avatar
unknown committed
2351
      goto error; /* purecov: inspected */
2352
    if (end_active_trans(thd))
unknown's avatar
unknown committed
2353
      goto error;
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
    /*
      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
2365

2366 2367 2368 2369 2370
    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
2371
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
2372
  case SQLCOM_SLAVE_START:
2373
  {
2374
    pthread_mutex_lock(&LOCK_active_mi);
2375
    start_slave(thd,active_mi,1 /* net report*/);
2376
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
2377
    break;
2378
  }
unknown's avatar
unknown committed
2379
  case SQLCOM_SLAVE_STOP:
2380 2381 2382 2383 2384 2385
  /*
    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,
2386
      so it waits for the client thread because t is locked by it.
2387
    - then the client thread does SLAVE STOP.
2388 2389
      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.
2390 2391 2392
    To prevent that, refuse SLAVE STOP if the
    client thread has locked tables
  */
2393
  if (thd->locked_tables || thd->active_transaction() || thd->global_read_lock)
2394
  {
2395 2396
    my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
               ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2397
    goto error;
2398
  }
2399
  {
2400
    pthread_mutex_lock(&LOCK_active_mi);
2401
    stop_slave(thd,active_mi,1/* net report*/);
2402
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
2403
    break;
2404
  }
unknown's avatar
unknown committed
2405
#endif /* HAVE_REPLICATION */
2406

unknown's avatar
unknown committed
2407
  case SQLCOM_ALTER_TABLE:
unknown's avatar
VIEW  
unknown committed
2408
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2409
    {
unknown's avatar
unknown committed
2410
      ulong priv=0;
unknown's avatar
unknown committed
2411
      ulong priv_needed= ALTER_ACL;
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
      /*
        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;
2423 2424 2425 2426
      /*
        We also require DROP priv for ALTER TABLE ... DROP PARTITION, as well
        as for RENAME TO, as being done by SQLCOM_RENAME_TABLE
      */
2427
      if (alter_info.flags & (ALTER_DROP_PARTITION | ALTER_RENAME))
unknown's avatar
unknown committed
2428 2429
        priv_needed|= DROP_ACL;

unknown's avatar
unknown committed
2430 2431
      /* Must be set in the parser */
      DBUG_ASSERT(select_lex->db);
unknown's avatar
unknown committed
2432
      if (check_access(thd, priv_needed, first_table->db,
2433 2434 2435 2436
		       &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
2437
	  check_merge_table_access(thd, first_table->db,
2438
				   (TABLE_LIST *)
2439
				   create_info.merge_list.first))
2440
	goto error;				/* purecov: inspected */
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452
      if (check_grant(thd, priv_needed, all_tables, 0, UINT_MAX, 0))
        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;
          if (check_grant(thd, INSERT_ACL | CREATE_ACL, &tmp_table, 0,
              UINT_MAX, 0))
            goto error;
unknown's avatar
unknown committed
2453
      }
2454

2455
      /* Don't yet allow changing of symlinks with ALTER TABLE */
2456
      if (create_info.data_file_name)
2457 2458
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0,
                     "DATA DIRECTORY option ignored");
2459
      if (create_info.index_file_name)
2460 2461
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0,
                     "INDEX DIRECTORY option ignored");
2462
      create_info.data_file_name= create_info.index_file_name= NULL;
unknown's avatar
unknown committed
2463
      /* ALTER TABLE ends previous transaction */
2464
      if (end_active_trans(thd))
unknown's avatar
unknown committed
2465
	goto error;
2466

2467 2468 2469 2470 2471
      if (!thd->locked_tables &&
          !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      {
        res= 1;
        break;
unknown's avatar
unknown committed
2472
      }
2473

2474
      thd->enable_slow_log= opt_log_slow_admin_statements;
2475
      res= mysql_alter_table(thd, select_lex->db, lex->name.str,
2476 2477 2478
                             &create_info,
                             first_table,
                             &alter_info,
2479 2480
                             select_lex->order_list.elements,
                             (ORDER *) select_lex->order_list.first,
2481
                             lex->ignore);
unknown's avatar
unknown committed
2482 2483
      break;
    }
unknown's avatar
unknown committed
2484
  case SQLCOM_RENAME_TABLE:
unknown's avatar
unknown committed
2485
  {
unknown's avatar
VIEW  
unknown committed
2486
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2487
    TABLE_LIST *table;
unknown's avatar
VIEW  
unknown committed
2488
    for (table= first_table; table; table= table->next_local->next_local)
unknown's avatar
unknown committed
2489
    {
unknown's avatar
unknown committed
2490
      if (check_access(thd, ALTER_ACL | DROP_ACL, table->db,
2491
		       &table->grant.privilege,0,0, test(table->schema_table)) ||
unknown's avatar
VIEW  
unknown committed
2492
	  check_access(thd, INSERT_ACL | CREATE_ACL, table->next_local->db,
2493 2494
		       &table->next_local->grant.privilege, 0, 0,
                       test(table->next_local->schema_table)))
unknown's avatar
unknown committed
2495
	goto error;
2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
      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];
      if (check_grant(thd, ALTER_ACL | DROP_ACL, &old_list, 0, 1, 0) ||
         (!test_all_bits(table->next_local->grant.privilege,
                         INSERT_ACL | CREATE_ACL) &&
          check_grant(thd, INSERT_ACL | CREATE_ACL, &new_list, 0, 1, 0)))
        goto error;
unknown's avatar
unknown committed
2508
    }
2509

unknown's avatar
unknown committed
2510
    if (end_active_trans(thd) || mysql_rename_tables(thd, first_table, 0))
unknown's avatar
unknown committed
2511
      goto error;
unknown's avatar
unknown committed
2512
    break;
unknown's avatar
unknown committed
2513
  }
2514
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2515 2516
  case SQLCOM_SHOW_BINLOGS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
2517 2518
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2519
    goto error;
unknown's avatar
unknown committed
2520 2521
#else
    {
unknown's avatar
unknown committed
2522
      if (check_global_access(thd, SUPER_ACL))
unknown's avatar
unknown committed
2523 2524 2525 2526
	goto error;
      res = show_binlogs(thd);
      break;
    }
unknown's avatar
unknown committed
2527
#endif
2528
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
2529
  case SQLCOM_SHOW_CREATE:
unknown's avatar
VIEW  
unknown committed
2530
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2531
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
2532 2533
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2534
    goto error;
unknown's avatar
unknown committed
2535
#else
unknown's avatar
unknown committed
2536
    {
2537 2538 2539
      /* Ignore temporary tables if this is "SHOW CREATE VIEW" */
      if (lex->only_view)
        first_table->skip_temporary= 1;
unknown's avatar
unknown committed
2540
      if (check_show_create_table_access(thd, first_table))
2541
	goto error;
unknown's avatar
unknown committed
2542
      res= mysqld_show_create(thd, first_table);
unknown's avatar
unknown committed
2543 2544
      break;
    }
unknown's avatar
unknown committed
2545
#endif
2546 2547
  case SQLCOM_CHECKSUM:
  {
unknown's avatar
VIEW  
unknown committed
2548
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2549
    if (check_table_access(thd, SELECT_ACL | EXTRA_ACL, all_tables, 0))
2550
      goto error; /* purecov: inspected */
unknown's avatar
VIEW  
unknown committed
2551
    res = mysql_checksum_table(thd, first_table, &lex->check_opt);
2552 2553
    break;
  }
unknown's avatar
unknown committed
2554
  case SQLCOM_REPAIR:
2555
  {
unknown's avatar
VIEW  
unknown committed
2556
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2557
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables, 0))
2558
      goto error; /* purecov: inspected */
2559
    thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
VIEW  
unknown committed
2560
    res= mysql_repair_table(thd, first_table, &lex->check_opt);
2561 2562 2563
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2564 2565 2566
      /*
        Presumably, REPAIR and binlog writing doesn't require synchronization
      */
2567
      write_bin_log(thd, TRUE, thd->query, thd->query_length);
2568
    }
2569
    select_lex->table_list.first= (uchar*) first_table;
2570
    lex->query_tables=all_tables;
2571 2572
    break;
  }
unknown's avatar
unknown committed
2573
  case SQLCOM_CHECK:
2574
  {
unknown's avatar
VIEW  
unknown committed
2575
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2576
    if (check_table_access(thd, SELECT_ACL | EXTRA_ACL , all_tables, 0))
2577
      goto error; /* purecov: inspected */
2578
    thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
VIEW  
unknown committed
2579
    res = mysql_check_table(thd, first_table, &lex->check_opt);
2580
    select_lex->table_list.first= (uchar*) first_table;
2581
    lex->query_tables=all_tables;
2582 2583
    break;
  }
unknown's avatar
unknown committed
2584 2585
  case SQLCOM_ANALYZE:
  {
unknown's avatar
VIEW  
unknown committed
2586
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2587
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables, 0))
unknown's avatar
unknown committed
2588
      goto error; /* purecov: inspected */
2589
    thd->enable_slow_log= opt_log_slow_admin_statements;
2590
    res= mysql_analyze_table(thd, first_table, &lex->check_opt);
2591 2592 2593
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2594 2595 2596
      /*
        Presumably, ANALYZE and binlog writing doesn't require synchronization
      */
2597
      write_bin_log(thd, TRUE, thd->query, thd->query_length);
2598
    }
2599
    select_lex->table_list.first= (uchar*) first_table;
2600
    lex->query_tables=all_tables;
unknown's avatar
unknown committed
2601
    break;
unknown's avatar
unknown committed
2602
  }
2603

unknown's avatar
unknown committed
2604 2605
  case SQLCOM_OPTIMIZE:
  {
unknown's avatar
VIEW  
unknown committed
2606
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2607
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables, 0))
unknown's avatar
unknown committed
2608
      goto error; /* purecov: inspected */
2609
    thd->enable_slow_log= opt_log_slow_admin_statements;
2610
    res= (specialflag & (SPECIAL_SAFE_MODE | SPECIAL_NO_NEW_FUNC)) ?
2611
      mysql_recreate_table(thd, first_table) :
unknown's avatar
VIEW  
unknown committed
2612
      mysql_optimize_table(thd, first_table, &lex->check_opt);
2613 2614 2615
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2616 2617 2618
      /*
        Presumably, OPTIMIZE and binlog writing doesn't require synchronization
      */
2619
      write_bin_log(thd, TRUE, thd->query, thd->query_length);
2620
    }
2621
    select_lex->table_list.first= (uchar*) first_table;
2622
    lex->query_tables=all_tables;
unknown's avatar
unknown committed
2623 2624 2625
    break;
  }
  case SQLCOM_UPDATE:
unknown's avatar
VIEW  
unknown committed
2626 2627
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (update_precheck(thd, all_tables))
unknown's avatar
unknown committed
2628
      break;
2629 2630
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
unknown's avatar
unknown committed
2631 2632 2633 2634 2635 2636 2637 2638
    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,
                                  lex->duplicates, lex->ignore));
2639
    /* mysql_update return 2 if we need to switch to multi-update */
unknown's avatar
unknown committed
2640
    if (up_result != 2)
2641
      break;
unknown's avatar
unknown committed
2642
    /* Fall through */
2643
  case SQLCOM_UPDATE_MULTI:
unknown's avatar
unknown committed
2644 2645 2646
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    /* if we switched from normal update, rights are checked */
unknown's avatar
unknown committed
2647
    if (up_result != 2)
2648
    {
unknown's avatar
unknown committed
2649 2650 2651 2652 2653
      if ((res= multi_update_precheck(thd, all_tables)))
        break;
    }
    else
      res= 0;
unknown's avatar
unknown committed
2654

2655
    res= mysql_multi_update_prepare(thd);
unknown's avatar
unknown committed
2656

2657
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
2658
    /* Check slave filtering rules */
2659
    if (unlikely(thd->slave_thread))
unknown's avatar
unknown committed
2660
    {
2661 2662
      if (all_tables_not_ok(thd, all_tables))
      {
2663 2664 2665 2666 2667
        if (res!= 0)
        {
          res= 0;             /* don't care of prev failure  */
          thd->clear_error(); /* filters are of highest prior */
        }
2668 2669 2670 2671
        /* we warn the slave SQL thread */
        my_error(ER_SLAVE_IGNORED_TABLE, MYF(0));
        break;
      }
2672 2673
      if (res)
        break;
unknown's avatar
unknown committed
2674
    }
2675 2676
    else
    {
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689
#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
unknown's avatar
unknown committed
2690

unknown's avatar
unknown committed
2691 2692 2693 2694 2695 2696
    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);
unknown's avatar
unknown committed
2697
    break;
unknown's avatar
unknown committed
2698
  }
unknown's avatar
unknown committed
2699
  case SQLCOM_REPLACE:
2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
#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
2730 2731
  case SQLCOM_INSERT:
  {
unknown's avatar
VIEW  
unknown committed
2732
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2733
    if ((res= insert_precheck(thd, all_tables)))
unknown's avatar
unknown committed
2734
      break;
2735 2736 2737 2738 2739 2740 2741 2742

    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
    {
      res= 1;
      break;
    }

unknown's avatar
VIEW  
unknown committed
2743
    res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
unknown's avatar
unknown committed
2744
		      lex->update_list, lex->value_list,
2745
                      lex->duplicates, lex->ignore);
2746 2747 2748 2749 2750 2751 2752

    /*
      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
2753
    if (first_table->view && !first_table->contain_auto_increment)
2754 2755
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
2756

unknown's avatar
unknown committed
2757
    break;
2758
  }
unknown's avatar
unknown committed
2759 2760 2761
  case SQLCOM_REPLACE_SELECT:
  case SQLCOM_INSERT_SELECT:
  {
unknown's avatar
unknown committed
2762
    select_result *sel_result;
unknown's avatar
VIEW  
unknown committed
2763
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2764
    if ((res= insert_precheck(thd, all_tables)))
2765
      break;
unknown's avatar
unknown committed
2766

2767
    /* Fix lock for first table */
unknown's avatar
VIEW  
unknown committed
2768 2769
    if (first_table->lock_type == TL_WRITE_DELAYED)
      first_table->lock_type= TL_WRITE;
2770

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

2774
    unit->set_limit(select_lex);
2775 2776 2777 2778 2779 2780 2781 2782

    if (! thd->locked_tables &&
        ! (need_start_waiting= ! wait_if_global_read_lock(thd, 0, 1)))
    {
      res= 1;
      break;
    }

unknown's avatar
VIEW  
unknown committed
2783
    if (!(res= open_and_lock_tables(thd, all_tables)))
2784
    {
2785
      /* Skip first table, which is the table we are inserting in */
unknown's avatar
unknown committed
2786
      TABLE_LIST *second_table= first_table->next_local;
2787
      select_lex->table_list.first= (uchar*) second_table;
2788 2789
      select_lex->context.table_list= 
        select_lex->context.first_name_resolution_table= second_table;
2790
      res= mysql_insert_select_prepare(thd);
unknown's avatar
unknown committed
2791 2792 2793 2794 2795 2796 2797
      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)))
2798
      {
unknown's avatar
unknown committed
2799
	res= handle_select(thd, lex, sel_result, OPTION_SETUP_TABLES_DONE);
2800 2801 2802 2803 2804 2805 2806 2807 2808
        /*
          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)
        {
2809 2810 2811
          /* INSERT ... SELECT should invalidate only the very first table */
          TABLE_LIST *save_table= first_table->next_local;
          first_table->next_local= 0;
2812 2813
          mysql_unlock_tables(thd, thd->lock);
          query_cache_invalidate3(thd, first_table, 1);
2814
          first_table->next_local= save_table;
2815 2816
          thd->lock=0;
        }
unknown's avatar
unknown committed
2817
        delete sel_result;
2818
      }
2819
      /* revert changes for SP */
2820
      select_lex->table_list.first= (uchar*) first_table;
2821
    }
unknown's avatar
VIEW  
unknown committed
2822

2823 2824 2825 2826 2827 2828
    /*
      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
2829
    if (first_table->view && !first_table->contain_auto_increment)
2830 2831
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
2832

unknown's avatar
unknown committed
2833 2834
    break;
  }
2835
  case SQLCOM_TRUNCATE:
2836 2837 2838 2839 2840
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
unknown's avatar
VIEW  
unknown committed
2841
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2842
    if (check_one_table_access(thd, DROP_ACL, all_tables))
unknown's avatar
unknown committed
2843
      goto error;
2844 2845 2846 2847
    /*
      Don't allow this within a transaction because we want to use
      re-generate table
    */
2848
    if (thd->locked_tables || thd->active_transaction())
2849
    {
unknown's avatar
unknown committed
2850 2851
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2852 2853
      goto error;
    }
unknown's avatar
VIEW  
unknown committed
2854

unknown's avatar
unknown committed
2855
    res= mysql_truncate(thd, first_table, 0);
2856
    break;
unknown's avatar
unknown committed
2857
  case SQLCOM_DELETE:
unknown's avatar
unknown committed
2858
  {
unknown's avatar
VIEW  
unknown committed
2859 2860
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if ((res= delete_precheck(thd, all_tables)))
unknown's avatar
unknown committed
2861
      break;
2862 2863
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
2864 2865 2866 2867 2868 2869 2870 2871

    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
    {
      res= 1;
      break;
    }

unknown's avatar
VIEW  
unknown committed
2872
    res = mysql_delete(thd, all_tables, select_lex->where,
2873
                       &select_lex->order_list,
unknown's avatar
unknown committed
2874 2875
                       unit->select_limit_cnt, select_lex->options,
                       FALSE);
unknown's avatar
unknown committed
2876 2877
    break;
  }
2878
  case SQLCOM_DELETE_MULTI:
unknown's avatar
unknown committed
2879
  {
unknown's avatar
VIEW  
unknown committed
2880
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2881
    TABLE_LIST *aux_tables=
unknown's avatar
unknown committed
2882
      (TABLE_LIST *)thd->lex->auxiliary_table_list.first;
unknown's avatar
unknown committed
2883
    multi_delete *del_result;
unknown's avatar
unknown committed
2884

2885 2886 2887 2888 2889 2890 2891
    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
    {
      res= 1;
      break;
    }

2892
    if ((res= multi_delete_precheck(thd, all_tables)))
2893
      break;
unknown's avatar
unknown committed
2894

unknown's avatar
unknown committed
2895
    /* condition will be TRUE on SP re-excuting */
2896 2897
    if (select_lex->item_list.elements != 0)
      select_lex->item_list.empty();
unknown's avatar
unknown committed
2898
    if (add_item_to_list(thd, new Item_null()))
unknown's avatar
unknown committed
2899
      goto error;
2900

unknown's avatar
unknown committed
2901
    thd->proc_info="init";
unknown's avatar
VIEW  
unknown committed
2902 2903 2904 2905
    if ((res= open_and_lock_tables(thd, all_tables)))
      break;

    if ((res= mysql_multi_delete_prepare(thd)))
unknown's avatar
unknown committed
2906
      goto error;
2907

unknown's avatar
unknown committed
2908 2909
    if (!thd->is_fatal_error &&
        (del_result= new multi_delete(aux_tables, lex->table_count)))
unknown's avatar
unknown committed
2910
    {
2911 2912 2913
      res= mysql_select(thd, &select_lex->ref_pointer_array,
			select_lex->get_table_list(),
			select_lex->with_wild,
2914
			select_lex->item_list,
unknown's avatar
unknown committed
2915
			select_lex->where,
2916
			0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL,
unknown's avatar
unknown committed
2917 2918
			(ORDER *)NULL,
			select_lex->options | thd->options |
2919 2920
			SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
                        OPTION_SETUP_TABLES_DONE,
unknown's avatar
unknown committed
2921
			del_result, unit, select_lex);
2922 2923 2924 2925 2926 2927 2928
      res|= thd->net.report_error;
      if (unlikely(res))
      {
        /* If we had a another error reported earlier then this will be ignored */
        del_result->send_error(ER_UNKNOWN_ERROR, "Execution of the query failed");
        del_result->abort();
      }
unknown's avatar
unknown committed
2929
      delete del_result;
unknown's avatar
unknown committed
2930 2931
    }
    else
2932
      res= TRUE;                                // Error
unknown's avatar
unknown committed
2933 2934
    break;
  }
unknown's avatar
unknown committed
2935
  case SQLCOM_DROP_TABLE:
unknown's avatar
unknown committed
2936
  {
unknown's avatar
VIEW  
unknown committed
2937
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2938 2939
    if (!lex->drop_temporary)
    {
unknown's avatar
VIEW  
unknown committed
2940
      if (check_table_access(thd, DROP_ACL, all_tables, 0))
2941 2942
	goto error;				/* purecov: inspected */
      if (end_active_trans(thd))
unknown's avatar
unknown committed
2943
        goto error;
2944
    }
unknown's avatar
unknown committed
2945
    else
unknown's avatar
unknown committed
2946 2947 2948 2949 2950 2951
    {
      /*
	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
2952 2953
	To not generate such irrelevant "table does not exist errors",
	we silently add IF EXISTS if TEMPORARY was used.
unknown's avatar
unknown committed
2954 2955
      */
      if (thd->slave_thread)
2956
        lex->drop_if_exists= 1;
2957

unknown's avatar
unknown committed
2958
      /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
2959
      thd->options|= OPTION_KEEP_LOG;
unknown's avatar
unknown committed
2960
    }
2961
    /* DDL and binlog write order protected by LOCK_open */
unknown's avatar
VIEW  
unknown committed
2962 2963
    res= mysql_rm_table(thd, first_table, lex->drop_if_exists,
			lex->drop_temporary);
unknown's avatar
unknown committed
2964 2965
  }
  break;
unknown's avatar
unknown committed
2966
  case SQLCOM_SHOW_PROCESSLIST:
2967 2968
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd,PROCESS_ACL))
unknown's avatar
unknown committed
2969
      break;
unknown's avatar
unknown committed
2970
    mysqld_list_processes(thd,
2971 2972 2973 2974
			  (thd->security_ctx->master_access & PROCESS_ACL ?
                           NullS :
                           thd->security_ctx->priv_user),
                          lex->verbose);
unknown's avatar
unknown committed
2975
    break;
unknown's avatar
unknown committed
2976 2977 2978
  case SQLCOM_SHOW_AUTHORS:
    res= mysqld_show_authors(thd);
    break;
2979 2980 2981
  case SQLCOM_SHOW_CONTRIBUTORS:
    res= mysqld_show_contributors(thd);
    break;
unknown's avatar
unknown committed
2982 2983 2984 2985 2986 2987
  case SQLCOM_SHOW_PRIVILEGES:
    res= mysqld_show_privileges(thd);
    break;
  case SQLCOM_SHOW_COLUMN_TYPES:
    res= mysqld_show_column_types(thd);
    break;
unknown's avatar
unknown committed
2988
  case SQLCOM_SHOW_ENGINE_LOGS:
unknown's avatar
unknown committed
2989
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
2990 2991
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
2992
    goto error;
unknown's avatar
unknown committed
2993 2994
#else
    {
2995
      if (check_access(thd, FILE_ACL, any_db,0,0,0,0))
unknown's avatar
unknown committed
2996
	goto error;
unknown's avatar
unknown committed
2997
      res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS);
unknown's avatar
unknown committed
2998 2999
      break;
    }
unknown's avatar
unknown committed
3000 3001
#endif
  case SQLCOM_CHANGE_DB:
3002 3003 3004 3005
  {
    LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) };

    if (!mysql_change_db(thd, &db_str, FALSE))
3006
      send_ok(thd);
3007

unknown's avatar
unknown committed
3008
    break;
3009
  }
3010

unknown's avatar
unknown committed
3011 3012
  case SQLCOM_LOAD:
  {
unknown's avatar
VIEW  
unknown committed
3013
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
3014
    uint privilege= (lex->duplicates == DUP_REPLACE ?
unknown's avatar
unknown committed
3015 3016
		     INSERT_ACL | DELETE_ACL : INSERT_ACL) |
                    (lex->local_file ? 0 : FILE_ACL);
3017

unknown's avatar
unknown committed
3018
    if (lex->local_file)
unknown's avatar
unknown committed
3019
    {
3020
      if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) ||
3021
          !opt_local_infile)
3022
      {
unknown's avatar
unknown committed
3023
	my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0));
3024 3025
	goto error;
      }
unknown's avatar
unknown committed
3026
    }
unknown's avatar
unknown committed
3027 3028 3029 3030

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

unknown's avatar
VIEW  
unknown committed
3031
    res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
unknown's avatar
unknown committed
3032
                    lex->update_list, lex->value_list, lex->duplicates,
3033
                    lex->ignore, (bool) lex->local_file);
unknown's avatar
unknown committed
3034 3035
    break;
  }
3036

unknown's avatar
unknown committed
3037
  case SQLCOM_SET_OPTION:
3038 3039
  {
    List<set_var_base> *lex_var_list= &lex->var_list;
3040
    if ((check_table_access(thd, SELECT_ACL, all_tables, 0) ||
unknown's avatar
unknown committed
3041 3042
	 open_and_lock_tables(thd, all_tables)))
      goto error;
3043 3044
    if (lex->one_shot_set && not_all_support_one_shot(lex_var_list))
    {
unknown's avatar
unknown committed
3045 3046
      my_error(ER_RESERVED_SYNTAX, MYF(0), "SET ONE_SHOT");
      goto error;
3047 3048 3049 3050 3051 3052 3053 3054
    }
    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;
3055
      send_ok(thd);
3056
    }
unknown's avatar
unknown committed
3057
    break;
3058
  }
unknown's avatar
unknown committed
3059

unknown's avatar
unknown committed
3060
  case SQLCOM_UNLOCK_TABLES:
3061 3062 3063 3064 3065 3066
    /*
      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.
    */
unknown's avatar
unknown committed
3067
    unlock_locked_tables(thd);
unknown's avatar
unknown committed
3068 3069
    if (thd->options & OPTION_TABLE_LOCK)
    {
unknown's avatar
unknown committed
3070
      end_active_trans(thd);
unknown's avatar
unknown committed
3071
      thd->options&= ~(ulong) (OPTION_TABLE_LOCK);
unknown's avatar
unknown committed
3072 3073
    }
    if (thd->global_read_lock)
3074
      unlock_global_read_lock(thd);
3075
    send_ok(thd);
unknown's avatar
unknown committed
3076 3077
    break;
  case SQLCOM_LOCK_TABLES:
unknown's avatar
unknown committed
3078
    unlock_locked_tables(thd);
3079
    /* we must end the trasaction first, regardless of anything */
unknown's avatar
unknown committed
3080
    if (end_active_trans(thd))
unknown's avatar
unknown committed
3081
      goto error;
unknown's avatar
VIEW  
unknown committed
3082
    if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, all_tables, 0))
3083
      goto error;
unknown's avatar
unknown committed
3084
    thd->in_lock_tables=1;
unknown's avatar
unknown committed
3085
    thd->options|= OPTION_TABLE_LOCK;
unknown's avatar
VIEW  
unknown committed
3086

3087
    if (!(res= simple_open_n_lock_tables(thd, all_tables)))
unknown's avatar
unknown committed
3088
    {
3089 3090
#ifdef HAVE_QUERY_CACHE
      if (thd->variables.query_cache_wlock_invalidate)
unknown's avatar
VIEW  
unknown committed
3091
	query_cache.invalidate_locked_for_write(first_table);
3092
#endif /*HAVE_QUERY_CACHE*/
unknown's avatar
unknown committed
3093 3094
      thd->locked_tables=thd->lock;
      thd->lock=0;
3095
      send_ok(thd);
unknown's avatar
unknown committed
3096
    }
unknown's avatar
unknown committed
3097
    else
3098 3099 3100 3101 3102 3103 3104
    {
      /* 
        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
      */
      end_active_trans(thd);
unknown's avatar
unknown committed
3105
      thd->options&= ~(ulong) (OPTION_TABLE_LOCK);
3106
    }
unknown's avatar
unknown committed
3107 3108 3109
    thd->in_lock_tables=0;
    break;
  case SQLCOM_CREATE_DB:
3110
  {
3111 3112 3113 3114 3115 3116
    /*
      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);
3117 3118 3119 3120 3121
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
unknown's avatar
unknown committed
3122
    char *alias;
3123 3124
    if (!(alias=thd->strmake(lex->name.str, lex->name.length)) ||
        check_db_name(&lex->name))
unknown's avatar
unknown committed
3125
    {
3126
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
unknown's avatar
unknown committed
3127 3128
      break;
    }
3129 3130 3131
    /*
      If in a slave thread :
      CREATE DATABASE DB was certainly not preceded by USE DB.
3132
      For that reason, db_ok() in sql/slave.cc did not check the
3133 3134 3135
      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.
    */
3136
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
3137
    if (thd->slave_thread && 
3138 3139
	(!rpl_filter->db_ok(lex->name.str) ||
	 !rpl_filter->db_ok_with_wild_table(lex->name.str)))
unknown's avatar
unknown committed
3140
    {
unknown's avatar
unknown committed
3141
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3142
      break;
unknown's avatar
unknown committed
3143
    }
3144
#endif
3145 3146
    if (check_access(thd,CREATE_ACL,lex->name.str, 0, 1, 0,
                     is_schema_db(lex->name.str)))
3147
      break;
3148
    res= mysql_create_db(thd,(lower_case_table_names == 2 ? alias :
3149
                              lex->name.str), &create_info, 0);
3150 3151
    break;
  }
unknown's avatar
unknown committed
3152
  case SQLCOM_DROP_DB:
3153
  {
3154 3155 3156 3157 3158
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
3159
    if (check_db_name(&lex->name))
unknown's avatar
unknown committed
3160
    {
3161
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
unknown's avatar
unknown committed
3162 3163
      break;
    }
3164 3165 3166 3167 3168 3169 3170
    /*
      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.
    */
3171
#ifdef HAVE_REPLICATION
3172
    if (thd->slave_thread && 
3173 3174
	(!rpl_filter->db_ok(lex->name.str) ||
	 !rpl_filter->db_ok_with_wild_table(lex->name.str)))
unknown's avatar
unknown committed
3175
    {
unknown's avatar
unknown committed
3176
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3177
      break;
unknown's avatar
unknown committed
3178
    }
3179
#endif
3180 3181
    if (check_access(thd,DROP_ACL,lex->name.str,0,1,0,
                     is_schema_db(lex->name.str)))
3182
      break;
3183 3184
    if (thd->locked_tables || thd->active_transaction())
    {
unknown's avatar
unknown committed
3185 3186
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3187 3188
      goto error;
    }
3189
    res= mysql_rm_db(thd, lex->name.str, lex->drop_if_exists, 0);
3190 3191
    break;
  }
unknown's avatar
unknown committed
3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214
  case SQLCOM_RENAME_DB:
  {
    LEX_STRING *olddb, *newdb;
    List_iterator <LEX_STRING> db_list(lex->db_list);
    olddb= db_list++;
    newdb= db_list++;
    if (end_active_trans(thd))
    {
      res= 1;
      break;
    }
#ifdef HAVE_REPLICATION
    if (thd->slave_thread && 
       (!rpl_filter->db_ok(olddb->str) ||
        !rpl_filter->db_ok(newdb->str) ||
        !rpl_filter->db_ok_with_wild_table(olddb->str) ||
        !rpl_filter->db_ok_with_wild_table(newdb->str)))
    {
      res= 1;
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
      break;
    }
#endif
3215 3216 3217 3218 3219
    if (check_db_name(newdb))
    {
      my_error(ER_WRONG_DB_NAME, MYF(0), newdb->str);
      break;
    }
unknown's avatar
unknown committed
3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238
    if (check_access(thd,ALTER_ACL,olddb->str,0,1,0,is_schema_db(olddb->str)) ||
        check_access(thd,DROP_ACL,olddb->str,0,1,0,is_schema_db(olddb->str)) ||
        check_access(thd,CREATE_ACL,newdb->str,0,1,0,is_schema_db(newdb->str)))
    {
      res= 1;
      break;
    }
    if (thd->locked_tables || thd->active_transaction())
    {
      res= 1;
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
      goto error;
    }
    res= mysql_rename_db(thd, olddb, newdb);
    if (!res)
      send_ok(thd);
    break;
  }
3239 3240
  case SQLCOM_ALTER_DB:
  {
3241
    LEX_STRING *db= &lex->name;
3242
    HA_CREATE_INFO create_info(lex->create_info);
3243
    if (check_db_name(db))
3244
    {
3245
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
3246 3247
      break;
    }
unknown's avatar
unknown committed
3248 3249 3250
    /*
      If in a slave thread :
      ALTER DATABASE DB may not be preceded by USE DB.
3251
      For that reason, maybe db_ok() in sql/slave.cc did not check the
unknown's avatar
unknown committed
3252 3253 3254 3255
      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
3256
    if (thd->slave_thread &&
3257 3258
	(!rpl_filter->db_ok(db->str) ||
	 !rpl_filter->db_ok_with_wild_table(db->str)))
unknown's avatar
unknown committed
3259
    {
unknown's avatar
unknown committed
3260
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
unknown's avatar
unknown committed
3261 3262 3263
      break;
    }
#endif
3264
    if (check_access(thd, ALTER_ACL, db->str, 0, 1, 0, is_schema_db(db->str)))
3265 3266 3267
      break;
    if (thd->locked_tables || thd->active_transaction())
    {
unknown's avatar
unknown committed
3268 3269
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3270 3271
      goto error;
    }
3272
    res= mysql_alter_db(thd, db->str, &create_info);
3273 3274
    break;
  }
unknown's avatar
unknown committed
3275 3276
  case SQLCOM_SHOW_CREATE_DB:
  {
unknown's avatar
unknown committed
3277 3278
    DBUG_EXECUTE_IF("4x_server_emul",
                    my_error(ER_UNKNOWN_ERROR, MYF(0)); goto error;);
3279
    if (check_db_name(&lex->name))
unknown's avatar
unknown committed
3280
    {
3281
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
unknown's avatar
unknown committed
3282 3283
      break;
    }
3284
    res= mysqld_show_create_db(thd, lex->name.str, &lex->create_info);
unknown's avatar
unknown committed
3285 3286
    break;
  }
unknown's avatar
unknown committed
3287 3288
  case SQLCOM_CREATE_EVENT:
  case SQLCOM_ALTER_EVENT:
3289
  do
unknown's avatar
unknown committed
3290
  {
unknown's avatar
unknown committed
3291
    DBUG_ASSERT(lex->event_parse_data);
unknown's avatar
unknown committed
3292 3293 3294 3295 3296 3297
    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;
    }
3298 3299 3300 3301 3302

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

unknown's avatar
unknown committed
3303 3304
    switch (lex->sql_command) {
    case SQLCOM_CREATE_EVENT:
3305 3306 3307 3308
    {
      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
3309
      break;
3310
    }
unknown's avatar
unknown committed
3311
    case SQLCOM_ALTER_EVENT:
3312 3313 3314
      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
3315
      break;
3316 3317
    default:
      DBUG_ASSERT(0);
unknown's avatar
unknown committed
3318
    }
3319
    DBUG_PRINT("info",("DDL error code=%d", res));
unknown's avatar
unknown committed
3320
    if (!res)
3321
      send_ok(thd);
unknown's avatar
unknown committed
3322

3323 3324 3325 3326 3327 3328
  } 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
3329
  }
3330 3331
  /* lex->unit.cleanup() is called outside, no need to call it here */
  break;
unknown's avatar
unknown committed
3332
  case SQLCOM_SHOW_CREATE_EVENT:
3333 3334 3335 3336 3337 3338 3339 3340
    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)))
      send_ok(thd);
3341
    break;
unknown's avatar
unknown committed
3342
  case SQLCOM_CREATE_FUNCTION:                  // UDF function
unknown's avatar
unknown committed
3343
  {
3344
    if (check_access(thd,INSERT_ACL,"mysql",0,1,0,0))
unknown's avatar
unknown committed
3345
      break;
unknown's avatar
unknown committed
3346
#ifdef HAVE_DLOPEN
3347 3348
    if (sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                        &thd->sp_func_cache, FALSE))
unknown's avatar
unknown committed
3349
    {
3350
      my_error(ER_UDF_EXISTS, MYF(0), lex->spname->m_name.str);
unknown's avatar
unknown committed
3351 3352
      goto error;
    }
3353
    if (!(res = mysql_create_function(thd, &lex->udf)))
unknown's avatar
unknown committed
3354
      send_ok(thd);
unknown's avatar
unknown committed
3355
#else
unknown's avatar
unknown committed
3356
    my_error(ER_CANT_OPEN_LIBRARY, MYF(0), lex->udf.dl, 0, "feature disabled");
unknown's avatar
unknown committed
3357
    res= TRUE;
unknown's avatar
unknown committed
3358 3359
#endif
    break;
unknown's avatar
unknown committed
3360
  }
unknown's avatar
unknown committed
3361
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3362 3363
  case SQLCOM_CREATE_USER:
  {
3364
    if (check_access(thd, INSERT_ACL, "mysql", 0, 1, 1, 0) &&
3365
        check_global_access(thd,CREATE_USER_ACL))
3366
      break;
3367 3368
    if (end_active_trans(thd))
      goto error;
3369
    /* Conditionally writes to binlog */
3370 3371 3372 3373
    if (!(res= mysql_create_user(thd, lex->users_list)))
      send_ok(thd);
    break;
  }
3374 3375
  case SQLCOM_DROP_USER:
  {
3376
    if (check_access(thd, DELETE_ACL, "mysql", 0, 1, 1, 0) &&
3377
        check_global_access(thd,CREATE_USER_ACL))
3378
      break;
3379 3380
    if (end_active_trans(thd))
      goto error;
3381
    /* Conditionally writes to binlog */
3382
    if (!(res= mysql_drop_user(thd, lex->users_list)))
3383 3384 3385 3386 3387
      send_ok(thd);
    break;
  }
  case SQLCOM_RENAME_USER:
  {
3388
    if (check_access(thd, UPDATE_ACL, "mysql", 0, 1, 1, 0) &&
3389
        check_global_access(thd,CREATE_USER_ACL))
3390
      break;
3391 3392
    if (end_active_trans(thd))
      goto error;
3393
    /* Conditionally writes to binlog */
3394
    if (!(res= mysql_rename_user(thd, lex->users_list)))
3395 3396 3397 3398 3399
      send_ok(thd);
    break;
  }
  case SQLCOM_REVOKE_ALL:
  {
3400 3401
    if (end_active_trans(thd))
      goto error;
3402
    if (check_access(thd, UPDATE_ACL, "mysql", 0, 1, 1, 0) &&
3403
        check_global_access(thd,CREATE_USER_ACL))
3404
      break;
3405
    /* Conditionally writes to binlog */
3406 3407 3408 3409
    if (!(res = mysql_revoke_all(thd, lex->users_list)))
      send_ok(thd);
    break;
  }
3410 3411 3412
  case SQLCOM_REVOKE:
  case SQLCOM_GRANT:
  {
3413 3414 3415
    if (end_active_trans(thd))
      goto error;

3416
    if (check_access(thd, lex->grant | lex->grant_tot_col | GRANT_ACL,
unknown's avatar
unknown committed
3417
		     first_table ?  first_table->db : select_lex->db,
unknown's avatar
VIEW  
unknown committed
3418
		     first_table ? &first_table->grant.privilege : 0,
3419 3420 3421
		     first_table ? 0 : 1, 0,
                     first_table ? (bool) first_table->schema_table :
                     select_lex->db ? is_schema_db(select_lex->db) : 0))
3422 3423
      goto error;

3424
    if (thd->security_ctx->user)              // If not replication
unknown's avatar
unknown committed
3425
    {
3426
      LEX_USER *user, *tmp_user;
3427

unknown's avatar
unknown committed
3428
      List_iterator <LEX_USER> user_list(lex->users_list);
3429
      while ((tmp_user= user_list++))
unknown's avatar
unknown committed
3430
      {
3431 3432
        if (!(user= get_current_user(thd, tmp_user)))
          goto error;
3433 3434 3435 3436 3437 3438 3439 3440
        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);
3441
        if (strcmp(thd->security_ctx->user, user->user.str) ||
3442
            my_strcasecmp(system_charset_info,
3443
                          user->host.str, thd->security_ctx->host_or_ip))
3444 3445
        {
          // TODO: use check_change_password()
3446 3447
          if (is_acl_user(user->host.str, user->user.str) &&
              user->password.str &&
3448
              check_access(thd, UPDATE_ACL,"mysql",0,1,1,0))
3449 3450 3451 3452 3453 3454
          {
            my_message(ER_PASSWORD_NOT_ALLOWED,
                       ER(ER_PASSWORD_NOT_ALLOWED), MYF(0));
            goto error;
          }
        }
unknown's avatar
SCRUM  
unknown committed
3455 3456
      }
    }
unknown's avatar
VIEW  
unknown committed
3457
    if (first_table)
3458
    {
3459 3460
      if (lex->type == TYPE_ENUM_PROCEDURE ||
          lex->type == TYPE_ENUM_FUNCTION)
3461 3462 3463 3464
      {
        uint grants= lex->all_privileges 
		   ? (PROC_ACLS & ~GRANT_ACL) | (lex->grant & GRANT_ACL)
		   : lex->grant;
3465
        if (check_grant_routine(thd, grants | GRANT_ACL, all_tables,
3466
                                lex->type == TYPE_ENUM_PROCEDURE, 0))
3467
	  goto error;
3468
        /* Conditionally writes to binlog */
3469 3470 3471 3472
        res= mysql_routine_grant(thd, all_tables,
                                 lex->type == TYPE_ENUM_PROCEDURE, 
                                 lex->users_list, grants,
                                 lex->sql_command == SQLCOM_REVOKE, 0);
3473 3474 3475
      }
      else
      {
3476 3477
	if (check_grant(thd,(lex->grant | lex->grant_tot_col | GRANT_ACL),
                        all_tables, 0, UINT_MAX, 0))
3478
	  goto error;
3479
        /* Conditionally writes to binlog */
3480 3481 3482 3483
        res= mysql_table_grant(thd, all_tables, lex->users_list,
			       lex->columns, lex->grant,
			       lex->sql_command == SQLCOM_REVOKE);
      }
3484 3485 3486
    }
    else
    {
3487
      if (lex->columns.elements || lex->type)
3488
      {
unknown's avatar
unknown committed
3489 3490
	my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
                   MYF(0));
unknown's avatar
unknown committed
3491
        goto error;
3492 3493
      }
      else
3494
	/* Conditionally writes to binlog */
3495 3496 3497 3498
	res = mysql_grant(thd, select_lex->db, lex->users_list, lex->grant,
			  lex->sql_command == SQLCOM_REVOKE);
      if (!res)
      {
3499
	if (lex->sql_command == SQLCOM_GRANT)
3500
	{
unknown's avatar
unknown committed
3501
	  List_iterator <LEX_USER> str_list(lex->users_list);
3502 3503 3504 3505 3506
	  LEX_USER *user, *tmp_user;
	  while ((tmp_user=str_list++))
          {
            if (!(user= get_current_user(thd, tmp_user)))
              goto error;
3507
	    reset_mqh(user, 0);
3508
          }
3509
	}
3510 3511 3512 3513
      }
    }
    break;
  }
unknown's avatar
SCRUM  
unknown committed
3514
#endif /*!NO_EMBEDDED_ACCESS_CHECKS*/
unknown's avatar
unknown committed
3515
  case SQLCOM_RESET:
3516 3517 3518
    /*
      RESET commands are never written to the binary log, so we have to
      initialize this variable because RESET shares the same code as FLUSH
3519 3520 3521 3522
    */
    lex->no_write_to_binlog= 1;
  case SQLCOM_FLUSH:
  {
unknown's avatar
unknown committed
3523
    bool write_to_binlog;
unknown's avatar
unknown committed
3524
    if (check_global_access(thd,RELOAD_ACL))
unknown's avatar
unknown committed
3525
      goto error;
3526

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

unknown's avatar
unknown committed
3553 3554 3555 3556 3557 3558 3559
    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;
    }

3560
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1))
3561 3562 3563 3564 3565
    {
      my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY),
		 MYF(0));
      goto error;
    }
3566
    sql_kill(thd, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY);
unknown's avatar
unknown committed
3567
    break;
3568
  }
unknown's avatar
unknown committed
3569
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
3570
  case SQLCOM_SHOW_GRANTS:
3571 3572 3573 3574
  {
    LEX_USER *grant_user= get_current_user(thd, lex->grant_user);
    if (!grant_user)
      goto error;
3575
    if ((thd->security_ctx->priv_user &&
3576
	 !strcmp(thd->security_ctx->priv_user, grant_user->user.str)) ||
3577
	!check_access(thd, SELECT_ACL, "mysql",0,1,0,0))
unknown's avatar
unknown committed
3578
    {
3579
      res = mysql_show_grants(thd, grant_user);
unknown's avatar
unknown committed
3580 3581
    }
    break;
3582
  }
unknown's avatar
unknown committed
3583
#endif
3584
  case SQLCOM_HA_OPEN:
unknown's avatar
VIEW  
unknown committed
3585
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
3586
    if (check_table_access(thd, SELECT_ACL, all_tables, 0))
3587
      goto error;
unknown's avatar
unknown committed
3588
    res= mysql_ha_open(thd, first_table, 0);
3589 3590
    break;
  case SQLCOM_HA_CLOSE:
unknown's avatar
VIEW  
unknown committed
3591 3592
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    res= mysql_ha_close(thd, first_table);
3593 3594
    break;
  case SQLCOM_HA_READ:
unknown's avatar
VIEW  
unknown committed
3595
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3596 3597 3598 3599 3600
    /*
      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.
    */
3601
    unit->set_limit(select_lex);
3602
    res= mysql_ha_read(thd, first_table, lex->ha_read_mode, lex->ident.str,
unknown's avatar
VIEW  
unknown committed
3603
                       lex->insert_list, lex->ha_rkey_mode, select_lex->where,
3604
                       unit->select_limit_cnt, unit->offset_limit_cnt);
3605 3606
    break;

unknown's avatar
unknown committed
3607
  case SQLCOM_BEGIN:
3608 3609 3610 3611 3612 3613
    if (thd->transaction.xid_state.xa_state != XA_NOTR)
    {
      my_error(ER_XAER_RMFAIL, MYF(0),
               xa_state_names[thd->transaction.xid_state.xa_state]);
      break;
    }
unknown's avatar
unknown committed
3614
    if (begin_trans(thd))
unknown's avatar
unknown committed
3615
      goto error;
unknown's avatar
unknown committed
3616
    send_ok(thd);
unknown's avatar
unknown committed
3617 3618
    break;
  case SQLCOM_COMMIT:
3619
    if (end_trans(thd, lex->tx_release ? COMMIT_RELEASE :
unknown's avatar
unknown committed
3620
                              lex->tx_chain ? COMMIT_AND_CHAIN : COMMIT))
unknown's avatar
unknown committed
3621
      goto error;
3622
    send_ok(thd);
unknown's avatar
unknown committed
3623 3624
    break;
  case SQLCOM_ROLLBACK:
3625
    if (end_trans(thd, lex->tx_release ? ROLLBACK_RELEASE :
unknown's avatar
unknown committed
3626
                              lex->tx_chain ? ROLLBACK_AND_CHAIN : ROLLBACK))
unknown's avatar
unknown committed
3627
      goto error;
3628
    send_ok(thd);
unknown's avatar
unknown committed
3629
    break;
unknown's avatar
unknown committed
3630
  case SQLCOM_RELEASE_SAVEPOINT:
unknown's avatar
unknown committed
3631
  {
3632 3633
    SAVEPOINT *sv;
    for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
unknown's avatar
unknown committed
3634 3635 3636
    {
      if (my_strnncoll(system_charset_info,
                       (uchar *)lex->ident.str, lex->ident.length,
3637
                       (uchar *)sv->name, sv->length) == 0)
unknown's avatar
unknown committed
3638 3639
        break;
    }
3640
    if (sv)
unknown's avatar
unknown committed
3641
    {
3642
      if (ha_release_savepoint(thd, sv))
unknown's avatar
unknown committed
3643
        res= TRUE; // cannot happen
unknown's avatar
unknown committed
3644 3645
      else
        send_ok(thd);
3646
      thd->transaction.savepoints=sv->prev;
unknown's avatar
unknown committed
3647
    }
3648
    else
unknown's avatar
unknown committed
3649
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
unknown's avatar
unknown committed
3650
    break;
unknown's avatar
unknown committed
3651
  }
unknown's avatar
unknown committed
3652
  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
unknown's avatar
unknown committed
3653
  {
3654 3655
    SAVEPOINT *sv;
    for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
3656 3657 3658
    {
      if (my_strnncoll(system_charset_info,
                       (uchar *)lex->ident.str, lex->ident.length,
3659
                       (uchar *)sv->name, sv->length) == 0)
3660 3661
        break;
    }
3662
    if (sv)
3663
    {
3664
      if (ha_rollback_to_savepoint(thd, sv))
3665 3666
        res= TRUE; // cannot happen
      else
unknown's avatar
unknown committed
3667
      {
unknown's avatar
unknown committed
3668 3669
        if (((thd->options & OPTION_KEEP_LOG) || 
             thd->transaction.all.modified_non_trans_table) &&
unknown's avatar
unknown committed
3670 3671 3672 3673 3674 3675
            !thd->slave_thread)
          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                       ER_WARNING_NOT_COMPLETE_ROLLBACK,
                       ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
        send_ok(thd);
      }
3676
      thd->transaction.savepoints=sv;
unknown's avatar
unknown committed
3677 3678
    }
    else
3679
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
unknown's avatar
unknown committed
3680
    break;
3681
  }
3682
  case SQLCOM_SAVEPOINT:
3683 3684
    if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN) ||
          thd->in_sub_stmt) || !opt_using_transactions)
unknown's avatar
unknown committed
3685
      send_ok(thd);
unknown's avatar
unknown committed
3686
    else
3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724
    {
      SAVEPOINT **sv, *newsv;
      for (sv=&thd->transaction.savepoints; *sv; sv=&(*sv)->prev)
      {
        if (my_strnncoll(system_charset_info,
                         (uchar *)lex->ident.str, lex->ident.length,
                         (uchar *)(*sv)->name, (*sv)->length) == 0)
          break;
      }
      if (*sv) /* old savepoint of the same name exists */
      {
        newsv=*sv;
        ha_release_savepoint(thd, *sv); // it cannot fail
        *sv=(*sv)->prev;
      }
      else if ((newsv=(SAVEPOINT *) alloc_root(&thd->transaction.mem_root,
                                               savepoint_alloc_size)) == 0)
      {
        my_error(ER_OUT_OF_RESOURCES, MYF(0));
        break;
      }
      newsv->name=strmake_root(&thd->transaction.mem_root,
                               lex->ident.str, lex->ident.length);
      newsv->length=lex->ident.length;
      /*
        if we'll get an error here, don't add new savepoint to the list.
        we'll lose a little bit of memory in transaction mem_root, but it'll
        be free'd when transaction ends anyway
      */
      if (ha_savepoint(thd, newsv))
        res= TRUE;
      else
      {
        newsv->prev=thd->transaction.savepoints;
        thd->transaction.savepoints=newsv;
        send_ok(thd);
      }
    }
unknown's avatar
unknown committed
3725
    break;
3726 3727
  case SQLCOM_CREATE_PROCEDURE:
  case SQLCOM_CREATE_SPFUNCTION:
unknown's avatar
unknown committed
3728
  {
3729
    uint namelen;
unknown's avatar
unknown committed
3730
    char *name;
unknown's avatar
unknown committed
3731
    int sp_result= SP_INTERNAL_ERROR;
3732

3733
    DBUG_ASSERT(lex->sphead != 0);
unknown's avatar
unknown committed
3734
    DBUG_ASSERT(lex->sphead->m_db.str); /* Must be initialized in the parser */
3735 3736 3737 3738
    /*
      Verify that the database name is allowed, optionally
      lowercase it.
    */
3739
    if (check_db_name(&lex->sphead->m_db))
3740
    {
3741
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->sphead->m_db.str);
3742
      goto create_sp_error;
3743 3744
    }

3745
    /*
3746 3747 3748
      Check that a database directory with this name
      exists. Design note: This won't work on virtual databases
      like information_schema.
3749 3750
    */
    if (check_db_dir_existence(lex->sphead->m_db.str))
3751
    {
3752
      my_error(ER_BAD_DB_ERROR, MYF(0), lex->sphead->m_db.str);
3753
      goto create_sp_error;
3754
    }
3755

3756 3757
    if (check_access(thd, CREATE_PROC_ACL, lex->sphead->m_db.str, 0, 0, 0,
                     is_schema_db(lex->sphead->m_db.str)))
3758
      goto create_sp_error;
3759

3760 3761
    if (end_active_trans(thd))
      goto create_sp_error;
3762 3763

    name= lex->sphead->name(&namelen);
3764
#ifdef HAVE_DLOPEN
unknown's avatar
unknown committed
3765 3766 3767
    if (lex->sphead->m_type == TYPE_ENUM_FUNCTION)
    {
      udf_func *udf = find_udf(name, namelen);
3768

unknown's avatar
unknown committed
3769
      if (udf)
3770
      {
3771 3772
        my_error(ER_UDF_EXISTS, MYF(0), name);
        goto create_sp_error;
3773
      }
unknown's avatar
unknown committed
3774 3775 3776
    }
#endif

3777 3778
    if (sp_process_definer(thd))
      goto create_sp_error;
3779

unknown's avatar
unknown committed
3780 3781
    res= (sp_result= lex->sphead->create(thd));
    switch (sp_result) {
3782
    case SP_OK:
unknown's avatar
unknown committed
3783
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3784
      /* only add privileges if really neccessary */
3785
      if (sp_automatic_privileges && !opt_noacl &&
3786
          check_routine_access(thd, DEFAULT_CREATE_PROC_ACLS,
3787
                               lex->sphead->m_db.str, name,
3788
                               lex->sql_command == SQLCOM_CREATE_PROCEDURE, 1))
3789
      {
unknown's avatar
unknown committed
3790
        if (sp_grant_privileges(thd, lex->sphead->m_db.str, name,
3791
                                lex->sql_command == SQLCOM_CREATE_PROCEDURE))
3792 3793 3794
          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                       ER_PROC_AUTO_GRANT_FAIL,
                       ER(ER_PROC_AUTO_GRANT_FAIL));
unknown's avatar
unknown committed
3795
        close_thread_tables(thd);
3796
      }
unknown's avatar
unknown committed
3797
#endif
unknown's avatar
unknown committed
3798
    break;
3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817
    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;
    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
3818
    if (sp_result != SP_OK )
3819 3820 3821 3822
      goto error;
    send_ok(thd);
    break; /* break super switch */
  } /* end case group bracket */
3823 3824 3825 3826
  case SQLCOM_CALL:
    {
      sp_head *sp;

3827 3828 3829 3830 3831 3832 3833 3834 3835
      /*
        This will cache all SP and SF and open and lock all tables
        required for execution.
      */
      if (check_table_access(thd, SELECT_ACL, all_tables, 0) ||
	  open_and_lock_tables(thd, all_tables))
       goto error;

      /*
3836 3837
        By this moment all needed SPs should be in cache so no need to look 
        into DB. 
3838
      */
3839 3840
      if (!(sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                                &thd->sp_proc_cache, TRUE)))
3841
      {
3842
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PROCEDURE",
unknown's avatar
unknown committed
3843
                 lex->spname->m_qname.str);
3844
	goto error;
3845 3846 3847
      }
      else
      {
unknown's avatar
unknown committed
3848
	ha_rows select_limit;
unknown's avatar
unknown committed
3849 3850
        /* bits that should be cleared in thd->server_status */
	uint bits_to_be_cleared= 0;
3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862
        /*
          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;
        }
3863

3864
	my_bool save_no_send_ok= thd->net.no_send_ok;
3865
	thd->net.no_send_ok= TRUE;
3866
	if (sp->m_flags & sp_head::MULTI_RESULTS)
3867
	{
3868
	  if (! (thd->client_capabilities & CLIENT_MULTI_RESULTS))
3869
	  {
3870 3871 3872 3873
            /*
              The client does not support multiple result sets being sent
              back
            */
3874
	    my_error(ER_SP_BADSELECT, MYF(0), sp->m_qname.str);
3875
	    thd->net.no_send_ok= save_no_send_ok;
3876 3877
	    goto error;
	  }
unknown's avatar
unknown committed
3878 3879 3880 3881 3882 3883 3884
          /*
            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;
3885 3886
	}

3887
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3888
	if (check_routine_access(thd, EXECUTE_ACL,
3889
				 sp->m_db.str, sp->m_name.str, TRUE, FALSE))
3890
	{
3891
	  thd->net.no_send_ok= save_no_send_ok;
3892 3893
	  goto error;
	}
3894
#endif
unknown's avatar
unknown committed
3895 3896
	select_limit= thd->variables.select_limit;
	thd->variables.select_limit= HA_POS_ERROR;
3897

3898
        /* 
3899
          We never write CALL statements into binlog:
3900 3901 3902 3903 3904
           - 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.
3905
        */
3906
	res= sp->execute_procedure(thd, &lex->value_list);
3907 3908 3909
	/*
          If warnings have been cleared, we have to clear total_warn_count
          too, otherwise the clients get confused.
3910 3911 3912 3913
	 */
	if (thd->warn_list.is_empty())
	  thd->total_warn_count= 0;

unknown's avatar
unknown committed
3914
	thd->variables.select_limit= select_limit;
3915

3916
	thd->net.no_send_ok= save_no_send_ok;
unknown's avatar
unknown committed
3917
        thd->server_status&= ~bits_to_be_cleared;
3918

unknown's avatar
unknown committed
3919
	if (!res)
unknown's avatar
unknown committed
3920 3921
	  send_ok(thd, (ulong) (thd->row_count_func < 0 ? 0 :
                                thd->row_count_func));
3922
	else
3923 3924
        {
          DBUG_ASSERT(thd->net.report_error == 1 || thd->killed);
3925
	  goto error;		// Substatement should already have sent error
3926
        }
3927
      }
3928
      break;
3929 3930
    }
  case SQLCOM_ALTER_PROCEDURE:
3931
  case SQLCOM_ALTER_FUNCTION:
3932
    {
unknown's avatar
unknown committed
3933
      int sp_result;
3934 3935 3936 3937
      sp_head *sp;
      st_sp_chistics chistics;

      memcpy(&chistics, &lex->sp_chistics, sizeof(chistics));
unknown's avatar
unknown committed
3938
      if (lex->sql_command == SQLCOM_ALTER_PROCEDURE)
3939 3940
        sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                            &thd->sp_proc_cache, FALSE);
3941
      else
3942 3943
        sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                            &thd->sp_func_cache, FALSE);
unknown's avatar
unknown committed
3944
      mysql_reset_errors(thd, 0);
3945
      if (! sp)
3946 3947
      {
	if (lex->spname->m_db.str)
unknown's avatar
unknown committed
3948
	  sp_result= SP_KEY_NOT_FOUND;
3949 3950 3951 3952 3953 3954
	else
	{
	  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
	  goto error;
	}
      }
3955 3956
      else
      {
3957 3958 3959
        if (check_routine_access(thd, ALTER_PROC_ACL, sp->m_db.str, 
				 sp->m_name.str,
                                 lex->sql_command == SQLCOM_ALTER_PROCEDURE, 0))
3960
	  goto error;
3961 3962 3963

        if (end_active_trans(thd)) 
          goto error;
3964
	memcpy(&lex->sp_chistics, &chistics, sizeof(lex->sp_chistics));
3965 3966
        if ((sp->m_type == TYPE_ENUM_FUNCTION) &&
            !trust_function_creators &&  mysql_bin_log.is_open() &&
3967 3968 3969 3970 3971 3972
            !sp->m_chistics->detistic &&
            (chistics.daccess == SP_CONTAINS_SQL ||
             chistics.daccess == SP_MODIFIES_SQL_DATA))
        {
          my_message(ER_BINLOG_UNSAFE_ROUTINE,
		     ER(ER_BINLOG_UNSAFE_ROUTINE), MYF(0));
unknown's avatar
unknown committed
3973
          sp_result= SP_INTERNAL_ERROR;
3974 3975 3976
        }
        else
        {
3977 3978 3979 3980 3981 3982
          /*
            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.
          */
unknown's avatar
unknown committed
3983
          /* Conditionally writes to binlog */
unknown's avatar
unknown committed
3984 3985 3986 3987 3988 3989 3990 3991 3992

          int type= lex->sql_command == SQLCOM_ALTER_PROCEDURE ?
                    TYPE_ENUM_PROCEDURE :
                    TYPE_ENUM_FUNCTION;

          sp_result= sp_update_routine(thd,
                                       type,
                                       lex->spname,
                                       &lex->sp_chistics);
3993
        }
3994
      }
unknown's avatar
unknown committed
3995
      switch (sp_result)
3996
      {
unknown's avatar
unknown committed
3997
      case SP_OK:
3998
	send_ok(thd);
unknown's avatar
unknown committed
3999 4000
	break;
      case SP_KEY_NOT_FOUND:
4001 4002
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
unknown's avatar
unknown committed
4003 4004
	goto error;
      default:
4005 4006
	my_error(ER_SP_CANT_ALTER, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
unknown's avatar
unknown committed
4007
	goto error;
4008
      }
4009
      break;
4010 4011
    }
  case SQLCOM_DROP_PROCEDURE:
4012
  case SQLCOM_DROP_FUNCTION:
4013
    {
unknown's avatar
unknown committed
4014
      int sp_result;
4015 4016
      int type= (lex->sql_command == SQLCOM_DROP_PROCEDURE ?
                 TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION);
4017

unknown's avatar
unknown committed
4018
      sp_result= sp_routine_exists_in_table(thd, type, lex->spname);
unknown's avatar
unknown committed
4019
      mysql_reset_errors(thd, 0);
unknown's avatar
unknown committed
4020
      if (sp_result == SP_OK)
4021
      {
4022 4023 4024
        char *db= lex->spname->m_db.str;
	char *name= lex->spname->m_name.str;

4025 4026
	if (check_routine_access(thd, ALTER_PROC_ACL, db, name,
                                 lex->sql_command == SQLCOM_DROP_PROCEDURE, 0))
unknown's avatar
merge  
unknown committed
4027
          goto error;
4028 4029 4030

        if (end_active_trans(thd)) 
          goto error;
unknown's avatar
unknown committed
4031
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4032
	if (sp_automatic_privileges && !opt_noacl &&
4033 4034
	    sp_revoke_privileges(thd, db, name, 
                                 lex->sql_command == SQLCOM_DROP_PROCEDURE))
4035 4036 4037 4038 4039
	{
	  push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 
		       ER_PROC_AUTO_REVOKE_FAIL,
		       ER(ER_PROC_AUTO_REVOKE_FAIL));
	}
unknown's avatar
unknown committed
4040
#endif
unknown's avatar
unknown committed
4041
        /* Conditionally writes to binlog */
unknown's avatar
unknown committed
4042 4043 4044 4045 4046 4047

        int type= lex->sql_command == SQLCOM_DROP_PROCEDURE ?
                  TYPE_ENUM_PROCEDURE :
                  TYPE_ENUM_FUNCTION;

        sp_result= sp_drop_routine(thd, type, lex->spname);
4048 4049 4050
      }
      else
      {
4051
#ifdef HAVE_DLOPEN
4052 4053 4054 4055 4056 4057
	if (lex->sql_command == SQLCOM_DROP_FUNCTION)
	{
          udf_func *udf = find_udf(lex->spname->m_name.str,
                                   lex->spname->m_name.length);
          if (udf)
          {
4058
	    if (check_access(thd, DELETE_ACL, "mysql", 0, 1, 0, 0))
4059
	      goto error;
4060

4061
	    if (!(res = mysql_drop_function(thd, &lex->spname->m_name)))
4062
	    {
4063 4064
	      send_ok(thd);
	      break;
4065 4066
	    }
	  }
4067
	}
4068
#endif
4069
	if (lex->spname->m_db.str)
unknown's avatar
unknown committed
4070
	  sp_result= SP_KEY_NOT_FOUND;
4071 4072 4073 4074 4075
	else
	{
	  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
	  goto error;
	}
4076
      }
unknown's avatar
unknown committed
4077 4078
      res= sp_result;
      switch (sp_result) {
4079
      case SP_OK:
4080
	send_ok(thd);
4081 4082
	break;
      case SP_KEY_NOT_FOUND:
4083 4084
	if (lex->drop_if_exists)
	{
4085
	  push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
4086
			      ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST),
4087
			      SP_COM_STRING(lex), lex->spname->m_name.str);
unknown's avatar
unknown committed
4088
	  res= FALSE;
4089 4090 4091
	  send_ok(thd);
	  break;
	}
4092 4093
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4094 4095
	goto error;
      default:
4096 4097
	my_error(ER_SP_DROP_FAILED, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4098
	goto error;
4099
      }
4100
      break;
4101
    }
unknown's avatar
unknown committed
4102 4103
  case SQLCOM_SHOW_CREATE_PROC:
    {
unknown's avatar
unknown committed
4104 4105
      if (sp_show_create_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname))
      {
4106 4107
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
unknown's avatar
unknown committed
4108 4109 4110 4111 4112 4113
	goto error;
      }
      break;
    }
  case SQLCOM_SHOW_CREATE_FUNC:
    {
unknown's avatar
unknown committed
4114 4115
      if (sp_show_create_routine(thd, TYPE_ENUM_FUNCTION, lex->spname))
      {
4116 4117
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
unknown's avatar
unknown committed
4118 4119 4120 4121
	goto error;
      }
      break;
    }
4122
#ifdef NOT_USED
unknown's avatar
unknown committed
4123 4124
  case SQLCOM_SHOW_STATUS_PROC:
    {
unknown's avatar
unknown committed
4125 4126
      res= sp_show_status_routine(thd, TYPE_ENUM_PROCEDURE,
                                  (lex->wild ? lex->wild->ptr() : NullS));
unknown's avatar
unknown committed
4127 4128 4129 4130
      break;
    }
  case SQLCOM_SHOW_STATUS_FUNC:
    {
unknown's avatar
unknown committed
4131 4132
      res= sp_show_status_routine(thd, TYPE_ENUM_FUNCTION,
                                  (lex->wild ? lex->wild->ptr() : NullS));
unknown's avatar
unknown committed
4133 4134
      break;
    }
4135
#endif
unknown's avatar
unknown committed
4136 4137 4138 4139 4140 4141 4142
#ifndef DBUG_OFF
  case SQLCOM_SHOW_PROC_CODE:
  case SQLCOM_SHOW_FUNC_CODE:
    {
      sp_head *sp;

      if (lex->sql_command == SQLCOM_SHOW_PROC_CODE)
unknown's avatar
unknown committed
4143 4144
        sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                            &thd->sp_proc_cache, FALSE);
unknown's avatar
unknown committed
4145
      else
unknown's avatar
unknown committed
4146 4147
        sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                            &thd->sp_func_cache, FALSE);
4148
      if (!sp || sp->show_routine_code(thd))
4149 4150
      {
        /* We don't distinguish between errors for now */
unknown's avatar
unknown committed
4151 4152 4153 4154 4155 4156 4157
        my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
        goto error;
      }
      break;
    }
#endif // ifndef DBUG_OFF
unknown's avatar
unknown committed
4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170
  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
4171 4172
  case SQLCOM_CREATE_VIEW:
    {
4173 4174 4175 4176
      /*
        Note: SQLCOM_CREATE_VIEW also handles 'ALTER VIEW' commands
        as specified through the thd->lex->create_view_mode flag.
      */
4177 4178 4179
      if (end_active_trans(thd))
        goto error;

4180
      res= mysql_create_view(thd, first_table, thd->lex->create_view_mode);
unknown's avatar
VIEW  
unknown committed
4181 4182 4183 4184
      break;
    }
  case SQLCOM_DROP_VIEW:
    {
unknown's avatar
unknown committed
4185 4186 4187
      if (check_table_access(thd, DROP_ACL, all_tables, 0) ||
          end_active_trans(thd))
        goto error;
4188 4189
      /* Conditionally writes to binlog. */
      res= mysql_drop_view(thd, first_table, thd->lex->drop_mode);
unknown's avatar
VIEW  
unknown committed
4190 4191
      break;
    }
4192 4193
  case SQLCOM_CREATE_TRIGGER:
  {
4194 4195 4196
    if (end_active_trans(thd))
      goto error;

4197
    /* Conditionally writes to binlog. */
4198 4199
    res= mysql_create_or_drop_trigger(thd, all_tables, 1);

4200 4201 4202 4203
    break;
  }
  case SQLCOM_DROP_TRIGGER:
  {
4204 4205 4206
    if (end_active_trans(thd))
      goto error;

4207
    /* Conditionally writes to binlog. */
4208 4209 4210
    res= mysql_create_or_drop_trigger(thd, all_tables, 0);
    break;
  }
4211
  case SQLCOM_XA_START:
4212 4213
    if (thd->transaction.xid_state.xa_state == XA_IDLE &&
        thd->lex->xa_opt == XA_RESUME)
4214
    {
4215
      if (! thd->transaction.xid_state.xid.eq(thd->lex->xid))
4216 4217 4218 4219
      {
        my_error(ER_XAER_NOTA, MYF(0));
        break;
      }
4220
      thd->transaction.xid_state.xa_state=XA_ACTIVE;
4221 4222 4223
      send_ok(thd);
      break;
    }
unknown's avatar
unknown committed
4224
    if (thd->lex->xa_opt != XA_NONE)
4225 4226 4227 4228
    { // JOIN is not supported yet. TODO
      my_error(ER_XAER_INVAL, MYF(0));
      break;
    }
4229
    if (thd->transaction.xid_state.xa_state != XA_NOTR)
4230
    {
unknown's avatar
unknown committed
4231
      my_error(ER_XAER_RMFAIL, MYF(0),
4232
               xa_state_names[thd->transaction.xid_state.xa_state]);
4233 4234 4235 4236 4237 4238 4239
      break;
    }
    if (thd->active_transaction() || thd->locked_tables)
    {
      my_error(ER_XAER_OUTSIDE, MYF(0));
      break;
    }
4240 4241 4242 4243 4244 4245 4246 4247 4248
    if (xid_cache_search(thd->lex->xid))
    {
      my_error(ER_XAER_DUPID, MYF(0));
      break;
    }
    DBUG_ASSERT(thd->transaction.xid_state.xid.is_null());
    thd->transaction.xid_state.xa_state=XA_ACTIVE;
    thd->transaction.xid_state.xid.set(thd->lex->xid);
    xid_cache_insert(&thd->transaction.xid_state);
unknown's avatar
unknown committed
4249
    thd->transaction.all.modified_non_trans_table= FALSE;
4250
    thd->options= ((thd->options & ~(OPTION_KEEP_LOG)) | OPTION_BEGIN);
4251 4252 4253 4254 4255 4256 4257 4258 4259 4260
    thd->server_status|= SERVER_STATUS_IN_TRANS;
    send_ok(thd);
    break;
  case SQLCOM_XA_END:
    /* fake it */
    if (thd->lex->xa_opt != XA_NONE)
    { // SUSPEND and FOR MIGRATE are not supported yet. TODO
      my_error(ER_XAER_INVAL, MYF(0));
      break;
    }
4261
    if (thd->transaction.xid_state.xa_state != XA_ACTIVE)
4262
    {
unknown's avatar
unknown committed
4263
      my_error(ER_XAER_RMFAIL, MYF(0),
4264
               xa_state_names[thd->transaction.xid_state.xa_state]);
4265 4266
      break;
    }
4267
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4268 4269 4270 4271
    {
      my_error(ER_XAER_NOTA, MYF(0));
      break;
    }
4272
    thd->transaction.xid_state.xa_state=XA_IDLE;
4273 4274 4275
    send_ok(thd);
    break;
  case SQLCOM_XA_PREPARE:
4276
    if (thd->transaction.xid_state.xa_state != XA_IDLE)
4277
    {
unknown's avatar
unknown committed
4278
      my_error(ER_XAER_RMFAIL, MYF(0),
4279
               xa_state_names[thd->transaction.xid_state.xa_state]);
4280 4281
      break;
    }
4282
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4283 4284 4285 4286 4287 4288 4289
    {
      my_error(ER_XAER_NOTA, MYF(0));
      break;
    }
    if (ha_prepare(thd))
    {
      my_error(ER_XA_RBROLLBACK, MYF(0));
4290 4291
      xid_cache_delete(&thd->transaction.xid_state);
      thd->transaction.xid_state.xa_state=XA_NOTR;
4292 4293
      break;
    }
4294
    thd->transaction.xid_state.xa_state=XA_PREPARED;
4295 4296 4297
    send_ok(thd);
    break;
  case SQLCOM_XA_COMMIT:
4298
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4299
    {
4300 4301
      XID_STATE *xs=xid_cache_search(thd->lex->xid);
      if (!xs || xs->in_thd)
4302
        my_error(ER_XAER_NOTA, MYF(0));
unknown's avatar
unknown committed
4303
      else
4304 4305 4306
      {
        ha_commit_or_rollback_by_xid(thd->lex->xid, 1);
        xid_cache_delete(xs);
unknown's avatar
unknown committed
4307
        send_ok(thd);
4308
      }
4309 4310
      break;
    }
4311
    if (thd->transaction.xid_state.xa_state == XA_IDLE &&
unknown's avatar
unknown committed
4312
        thd->lex->xa_opt == XA_ONE_PHASE)
4313
    {
unknown's avatar
unknown committed
4314 4315 4316
      int r;
      if ((r= ha_commit(thd)))
        my_error(r == 1 ? ER_XA_RBROLLBACK : ER_XAER_RMERR, MYF(0));
4317 4318 4319
      else
        send_ok(thd);
    }
4320
    else if (thd->transaction.xid_state.xa_state == XA_PREPARED &&
unknown's avatar
unknown committed
4321
             thd->lex->xa_opt == XA_NONE)
4322
    {
4323 4324 4325
      if (wait_if_global_read_lock(thd, 0, 0))
      {
        ha_rollback(thd);
4326
        my_error(ER_XAER_RMERR, MYF(0));
4327
      }
4328
      else
4329 4330 4331 4332 4333 4334 4335
      {
        if (ha_commit_one_phase(thd, 1))
          my_error(ER_XAER_RMERR, MYF(0));
        else
          send_ok(thd);
        start_waiting_global_read_lock(thd);
      }
4336 4337 4338
    }
    else
    {
unknown's avatar
unknown committed
4339
      my_error(ER_XAER_RMFAIL, MYF(0),
4340
               xa_state_names[thd->transaction.xid_state.xa_state]);
4341 4342
      break;
    }
unknown's avatar
unknown committed
4343
    thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
unknown's avatar
unknown committed
4344
    thd->transaction.all.modified_non_trans_table= FALSE;
4345
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
4346 4347
    xid_cache_delete(&thd->transaction.xid_state);
    thd->transaction.xid_state.xa_state=XA_NOTR;
4348 4349
    break;
  case SQLCOM_XA_ROLLBACK:
4350
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4351
    {
4352 4353
      XID_STATE *xs=xid_cache_search(thd->lex->xid);
      if (!xs || xs->in_thd)
4354
        my_error(ER_XAER_NOTA, MYF(0));
unknown's avatar
unknown committed
4355
      else
4356 4357 4358
      {
        ha_commit_or_rollback_by_xid(thd->lex->xid, 0);
        xid_cache_delete(xs);
unknown's avatar
unknown committed
4359
        send_ok(thd);
4360
      }
4361 4362
      break;
    }
4363 4364
    if (thd->transaction.xid_state.xa_state != XA_IDLE &&
        thd->transaction.xid_state.xa_state != XA_PREPARED)
4365
    {
unknown's avatar
unknown committed
4366
      my_error(ER_XAER_RMFAIL, MYF(0),
4367
               xa_state_names[thd->transaction.xid_state.xa_state]);
4368 4369 4370 4371 4372 4373
      break;
    }
    if (ha_rollback(thd))
      my_error(ER_XAER_RMERR, MYF(0));
    else
      send_ok(thd);
4374
    thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
unknown's avatar
unknown committed
4375
    thd->transaction.all.modified_non_trans_table= FALSE;
4376
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
4377 4378
    xid_cache_delete(&thd->transaction.xid_state);
    thd->transaction.xid_state.xa_state=XA_NOTR;
4379 4380
    break;
  case SQLCOM_XA_RECOVER:
4381
    res= mysql_xa_recover(thd);
4382
    break;
unknown's avatar
unknown committed
4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406
  case SQLCOM_ALTER_TABLESPACE:
    if (check_access(thd, ALTER_ACL, thd->db, 0, 1, 0, thd->db ? is_schema_db(thd->db) : 0))
      break;
    if (!(res= mysql_alter_tablespace(thd, lex->alter_tablespace_info)))
      send_ok(thd);
    break;
  case SQLCOM_INSTALL_PLUGIN:
    if (! (res= mysql_install_plugin(thd, &thd->lex->comment,
                                     &thd->lex->ident)))
      send_ok(thd);
    break;
  case SQLCOM_UNINSTALL_PLUGIN:
    if (! (res= mysql_uninstall_plugin(thd, &thd->lex->comment)))
      send_ok(thd);
    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
4407 4408 4409 4410 4411
  case SQLCOM_CREATE_SERVER:
  {
    int error;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_CREATE_SERVER"));
unknown's avatar
unknown committed
4412 4413 4414 4415

    if (check_global_access(thd, SUPER_ACL))
      break;

unknown's avatar
unknown committed
4416 4417
    if ((error= create_server(thd, &lex->server_options)))
    {
4418
      DBUG_PRINT("info", ("problem creating server <%s>",
unknown's avatar
unknown committed
4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430
                          lex->server_options.server_name));
      my_error(error, MYF(0), lex->server_options.server_name);
      break;
    }
    send_ok(thd, 1);
    break;
  }
  case SQLCOM_ALTER_SERVER:
  {
    int error;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_ALTER_SERVER"));
unknown's avatar
unknown committed
4431 4432 4433 4434

    if (check_global_access(thd, SUPER_ACL))
      break;

unknown's avatar
unknown committed
4435 4436
    if ((error= alter_server(thd, &lex->server_options)))
    {
4437
      DBUG_PRINT("info", ("problem altering server <%s>",
unknown's avatar
unknown committed
4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449
                          lex->server_options.server_name));
      my_error(error, MYF(0), lex->server_options.server_name);
      break;
    }
    send_ok(thd, 1);
    break;
  }
  case SQLCOM_DROP_SERVER:
  {
    int err_code;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_DROP_SERVER"));
unknown's avatar
unknown committed
4450 4451 4452 4453

    if (check_global_access(thd, SUPER_ACL))
      break;

unknown's avatar
unknown committed
4454 4455
    if ((err_code= drop_server(thd, &lex->server_options)))
    {
unknown's avatar
unknown committed
4456
      if (! lex->drop_if_exists && err_code == ER_FOREIGN_SERVER_DOESNT_EXIST)
unknown's avatar
unknown committed
4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470
      {
        DBUG_PRINT("info", ("problem dropping server %s",
                            lex->server_options.server_name));
        my_error(err_code, MYF(0), lex->server_options.server_name);
      }
      else
      {
        send_ok(thd, 0);
      }
      break;
    }
    send_ok(thd, 1);
    break;
  }
4471
  default:
4472
#ifndef EMBEDDED_LIBRARY
4473
    DBUG_ASSERT(0);                             /* Impossible */
4474
#endif
4475
    send_ok(thd);
unknown's avatar
unknown committed
4476 4477
    break;
  }
unknown's avatar
unknown committed
4478

unknown's avatar
unknown committed
4479
  thd->proc_info="query end";
4480 4481

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

4494
  /*
4495 4496
    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
4497 4498 4499 4500
    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))
4501
    thd->row_count_func= -1;
4502

4503
  goto finish;
unknown's avatar
unknown committed
4504 4505

error:
4506 4507
  res= TRUE;

4508
finish:
4509 4510 4511 4512 4513 4514 4515 4516 4517
  if (need_start_waiting)
  {
    /*
      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);
  }
  DBUG_RETURN(res || thd->net.report_error);
unknown's avatar
unknown committed
4518 4519 4520
}


4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543
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()))
4544
        return 1;                               /* purecov: inspected */
4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562
      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);
        thd->lex->unit.print(&str);
        str.append('\0');
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
                     ER_YES, str.ptr());
      }
      result->send_eof();
      delete result;
    }
    else
    {
      if (!result && !(result= new select_send()))
4563
        return 1;                               /* purecov: inspected */
4564 4565 4566 4567 4568 4569 4570 4571 4572 4573
      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
4574
/*
4575
  Check grants for commands which work only with one table.
unknown's avatar
unknown committed
4576

4577
  SYNOPSIS
4578
    check_single_table_access()
unknown's avatar
unknown committed
4579
    thd			Thread handler
4580
    privilege		requested privilege
unknown's avatar
VIEW  
unknown committed
4581
    all_tables		global table list of query
4582 4583
    no_errors           FALSE/TRUE - report/don't report error to
                            the client (using my_error() call).
unknown's avatar
unknown committed
4584 4585 4586

  RETURN
    0 - OK
unknown's avatar
unknown committed
4587
    1 - access denied, error is sent to client
unknown's avatar
unknown committed
4588 4589
*/

4590
bool check_single_table_access(THD *thd, ulong privilege, 
4591
                               TABLE_LIST *all_tables, bool no_errors)
unknown's avatar
unknown committed
4592
{
4593 4594 4595 4596 4597 4598
  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;

4599 4600 4601 4602 4603 4604 4605 4606
  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,
4607
		   &all_tables->grant.privilege, 0, no_errors,
4608
                   test(all_tables->schema_table)))
4609
    goto deny;
unknown's avatar
unknown committed
4610

unknown's avatar
unknown committed
4611
  /* Show only 1 table for check_grant */
4612
  if (!(all_tables->belong_to_view &&
4613
        (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) &&
4614
      check_grant(thd, privilege, all_tables, 0, 1, no_errors))
4615 4616 4617
    goto deny;

  thd->security_ctx= backup_ctx;
4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641
  return 0;

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

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

  SYNOPSIS
    check_one_table_access()
    thd			Thread handler
    privilege		requested privilege
    all_tables		global table list of query

  RETURN
    0 - OK
    1 - access denied, error is sent to client
*/

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

4645
  /* Check rights on tables of subselects and implictly opened tables */
unknown's avatar
unknown committed
4646
  TABLE_LIST *subselects_tables, *view= all_tables->view ? all_tables : 0;
unknown's avatar
VIEW  
unknown committed
4647
  if ((subselects_tables= all_tables->next_global))
unknown's avatar
unknown committed
4648
  {
unknown's avatar
unknown committed
4649 4650 4651 4652 4653 4654
    /*
      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)
    {
4655
      if (check_single_table_access (thd, privilege, subselects_tables, FALSE))
unknown's avatar
unknown committed
4656 4657 4658 4659 4660
        return 1;
      subselects_tables= subselects_tables->next_global;
    }
    if (subselects_tables &&
        (check_table_access(thd, SELECT_ACL, subselects_tables, 0)))
4661
      return 1;
unknown's avatar
unknown committed
4662 4663
  }
  return 0;
unknown's avatar
unknown committed
4664 4665 4666
}


unknown's avatar
unknown committed
4667
/****************************************************************************
unknown's avatar
unknown committed
4668
  Get the user (global) and database privileges for all used tables
unknown's avatar
unknown committed
4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681

  NOTES
    The idea of EXTRA_ACL is that one will be granted access to the table if
    one has the asked privilege on any column combination of the table; For
    example to be able to check a table one needs to have SELECT privilege on
    any column of the table.

  RETURN
    0  ok
    1  If we can't get the privileges and we don't use table/column grants.

    save_priv	In this we store global and db level grants for the table
		Note that we don't store db level grants if the global grants
unknown's avatar
unknown committed
4682 4683
                is enough to satisfy the request and the global grants contains
                a SELECT grant.
unknown's avatar
unknown committed
4684 4685 4686
****************************************************************************/

bool
unknown's avatar
unknown committed
4687
check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv,
4688
	     bool dont_check_global_grants, bool no_errors, bool schema_db)
unknown's avatar
unknown committed
4689
{
4690
  Security_context *sctx= thd->security_ctx;
unknown's avatar
unknown committed
4691 4692
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  ulong db_access;
4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703
  /*
    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
    if it's database level grant command 
    (see SQLCOM_GRANT case, mysql_execute_command() function) and
    set db_is_pattern according to 'dont_check_global_grants' value.
  */
  bool  db_is_pattern= (test(want_access & GRANT_ACL) &&
                        dont_check_global_grants);
unknown's avatar
unknown committed
4704 4705
#endif
  ulong dummy;
4706 4707
  DBUG_ENTER("check_access");
  DBUG_PRINT("enter",("db: %s  want_access: %lu  master_access: %lu",
4708
                      db ? db : "", want_access, sctx->master_access));
unknown's avatar
unknown committed
4709 4710 4711 4712 4713
  if (save_priv)
    *save_priv=0;
  else
    save_priv= &dummy;

4714
  if ((!db || !db[0]) && !thd->db && !dont_check_global_grants)
unknown's avatar
unknown committed
4715
  {
4716
    DBUG_PRINT("error",("No database"));
4717
    if (!no_errors)
unknown's avatar
unknown committed
4718 4719
      my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR),
                 MYF(0));                       /* purecov: tested */
unknown's avatar
unknown committed
4720
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
4721 4722
  }

4723 4724
  if (schema_db)
  {
4725 4726
    if (!(sctx->master_access & FILE_ACL) && (want_access & FILE_ACL) ||
        (want_access & ~(SELECT_ACL | EXTRA_ACL | FILE_ACL)))
4727 4728
    {
      if (!no_errors)
4729 4730
      {
        const char *db_name= db ? db : thd->db;
4731
        my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
4732 4733
                 sctx->priv_user, sctx->priv_host, db_name);
      }
4734 4735 4736 4737 4738 4739 4740 4741 4742
      DBUG_RETURN(TRUE);
    }
    else
    {
      *save_priv= SELECT_ACL;
      DBUG_RETURN(FALSE);
    }
  }

unknown's avatar
unknown committed
4743 4744 4745
#ifdef NO_EMBEDDED_ACCESS_CHECKS
  DBUG_RETURN(0);
#else
4746
  if ((sctx->master_access & want_access) == want_access)
unknown's avatar
unknown committed
4747
  {
4748 4749 4750 4751 4752
    /*
      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
      UPDATE t1 SET a=1 WHERE b > 0
    */
4753 4754
    db_access= sctx->db_access;
    if (!(sctx->master_access & SELECT_ACL) &&
unknown's avatar
unknown committed
4755
	(db && (!thd->db || db_is_pattern || strcmp(db,thd->db))))
4756 4757 4758
      db_access=acl_get(sctx->host, sctx->ip, sctx->priv_user, db,
                        db_is_pattern);
    *save_priv=sctx->master_access | db_access;
unknown's avatar
unknown committed
4759
    DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
4760
  }
4761
  if (((want_access & ~sctx->master_access) & ~(DB_ACLS | EXTRA_ACL)) ||
4762
      ! db && dont_check_global_grants)
unknown's avatar
unknown committed
4763
  {						// We can never grant this
4764
    DBUG_PRINT("error",("No possible access"));
4765
    if (!no_errors)
4766
      my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
4767 4768
               sctx->priv_user,
               sctx->priv_host,
4769 4770 4771
               (thd->password ?
                ER(ER_YES) :
                ER(ER_NO)));                    /* purecov: tested */
unknown's avatar
unknown committed
4772
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
4773 4774 4775
  }

  if (db == any_db)
unknown's avatar
unknown committed
4776
    DBUG_RETURN(FALSE);				// Allow select on anything
unknown's avatar
unknown committed
4777

unknown's avatar
unknown committed
4778
  if (db && (!thd->db || db_is_pattern || strcmp(db,thd->db)))
4779 4780
    db_access= acl_get(sctx->host, sctx->ip, sctx->priv_user, db,
                       db_is_pattern);
unknown's avatar
unknown committed
4781
  else
4782
    db_access= sctx->db_access;
4783
  DBUG_PRINT("info",("db_access: %lu", db_access));
unknown's avatar
unknown committed
4784
  /* Remove SHOW attribute and access rights we already have */
4785
  want_access &= ~(sctx->master_access | EXTRA_ACL);
4786 4787
  DBUG_PRINT("info",("db_access: %lu  want_access: %lu",
                     db_access, want_access));
4788
  db_access= ((*save_priv=(db_access | sctx->master_access)) & want_access);
4789

unknown's avatar
unknown committed
4790
  if (db_access == want_access ||
4791
      (!dont_check_global_grants &&
4792
       !(want_access & ~(db_access | TABLE_ACLS | PROC_ACLS))))
unknown's avatar
unknown committed
4793
    DBUG_RETURN(FALSE);				/* Ok */
4794 4795

  DBUG_PRINT("error",("Access denied"));
4796
  if (!no_errors)
4797
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
4798
             sctx->priv_user, sctx->priv_host,
4799 4800 4801
             (db ? db : (thd->db ?
                         thd->db :
                         "unknown")));          /* purecov: tested */
unknown's avatar
unknown committed
4802
  DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
4803
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
unknown's avatar
unknown committed
4804 4805 4806
}


4807 4808 4809 4810 4811 4812 4813 4814 4815
/*
  check for global access and give descriptive error message if it fails

  SYNOPSIS
    check_global_access()
    thd			Thread handler
    want_access		Use should have any of these global rights

  WARNING
4816
    One gets access right if one has ANY of the rights in want_access
4817 4818 4819 4820 4821 4822 4823 4824
    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.

  RETURN
    0	ok
    1	Access denied.  In this case an error is sent to the client
*/
unknown's avatar
unknown committed
4825 4826

bool check_global_access(THD *thd, ulong want_access)
unknown's avatar
unknown committed
4827
{
unknown's avatar
unknown committed
4828 4829 4830
#ifdef NO_EMBEDDED_ACCESS_CHECKS
  return 0;
#else
unknown's avatar
unknown committed
4831
  char command[128];
4832
  if ((thd->security_ctx->master_access & want_access))
unknown's avatar
unknown committed
4833 4834
    return 0;
  get_privilege_desc(command, sizeof(command), want_access);
4835
  my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), command);
unknown's avatar
unknown committed
4836
  return 1;
unknown's avatar
unknown committed
4837
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
unknown's avatar
unknown committed
4838 4839 4840
}


4841 4842
static bool check_show_access(THD *thd, TABLE_LIST *table)
{
unknown's avatar
unknown committed
4843
  switch (get_schema_table_idx(table->schema_table)) {
4844 4845
  case SCH_SCHEMATA:
    return (specialflag & SPECIAL_SKIP_SHOW_DB) &&
unknown's avatar
unknown committed
4846
      check_global_access(thd, SHOW_DB_ACL);
4847 4848 4849 4850 4851

  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
  case SCH_TRIGGERS:
unknown's avatar
unknown committed
4852 4853 4854
  case SCH_EVENTS:
  {
    const char *dst_db_name= table->schema_select_lex->db;
4855

unknown's avatar
unknown committed
4856
    DBUG_ASSERT(dst_db_name);
4857

unknown's avatar
unknown committed
4858 4859 4860 4861
    if (check_access(thd, SELECT_ACL, dst_db_name,
                     &thd->col_access, FALSE, FALSE,
                     is_schema_db(dst_db_name)))
      return TRUE;
4862

unknown's avatar
unknown committed
4863 4864 4865 4866 4867 4868 4869
    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;
4870 4871
    }

unknown's avatar
unknown committed
4872 4873 4874
    return FALSE;
  }

4875 4876
  case SCH_COLUMNS:
  case SCH_STATISTICS:
unknown's avatar
unknown committed
4877 4878 4879
  {
    TABLE_LIST *dst_table;
    dst_table= (TABLE_LIST *) table->schema_select_lex->table_list.first;
4880

unknown's avatar
unknown committed
4881
    DBUG_ASSERT(dst_table);
4882

unknown's avatar
unknown committed
4883 4884 4885 4886 4887 4888
    if (check_access(thd, SELECT_ACL | EXTRA_ACL,
                     dst_table->db,
                     &dst_table->grant.privilege,
                     FALSE, FALSE,
                     test(dst_table->schema_table)))
      return FALSE;
4889

4890
    return (check_grant(thd, SELECT_ACL, dst_table, 2, UINT_MAX, FALSE));
unknown's avatar
unknown committed
4891 4892
  }
  default:
4893 4894 4895 4896 4897 4898 4899
    break;
  }

  return FALSE;
}


unknown's avatar
unknown committed
4900
/*
4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920
  Check the privilege for all used tables.

  SYNOPSYS
    check_table_access()
      thd          Thread context
      want_access  Privileges requested
      tables       List of tables to be checked
      no_errors    FALSE/TRUE - report/don't report error to
                   the client (using my_error() call).

  NOTES
    Table privileges are cached in the table list for GRANT checking.
    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).

  RETURN VALUE
    FALSE - OK
    TRUE  - Access denied
unknown's avatar
unknown committed
4921 4922
*/

4923
bool
unknown's avatar
unknown committed
4924
check_table_access(THD *thd, ulong want_access,TABLE_LIST *tables,
4925
		   bool no_errors)
unknown's avatar
unknown committed
4926
{
4927
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4928
  TABLE_LIST *org_tables= tables;
unknown's avatar
unknown committed
4929
#endif
4930
  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
4931
  Security_context *sctx= thd->security_ctx, *backup_ctx= thd->security_ctx;
4932
  /*
unknown's avatar
unknown committed
4933 4934 4935
    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.
4936
  */
unknown's avatar
unknown committed
4937
  for (; tables != first_not_own_table; tables= tables->next_global)
unknown's avatar
unknown committed
4938
  {
4939 4940 4941 4942 4943
    if (tables->security_ctx)
      sctx= tables->security_ctx;
    else
      sctx= backup_ctx;

4944
    if (tables->schema_table && 
4945
        (want_access & ~(SELECT_ACL | EXTRA_ACL | FILE_ACL)))
4946 4947 4948
    {
      if (!no_errors)
        my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
4949
                 sctx->priv_user, sctx->priv_host,
4950
                 INFORMATION_SCHEMA_NAME.str);
4951 4952
      return TRUE;
    }
4953 4954 4955 4956 4957
    /*
       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
4958 4959 4960 4961 4962 4963 4964 4965 4966 4967

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

      continue;
    }

    if (tables->derived ||
4968
        (tables->table && (int)tables->table->s->tmp_table))
unknown's avatar
unknown committed
4969
      continue;
4970 4971
    thd->security_ctx= sctx;
    if ((sctx->master_access & want_access) ==
4972
        (want_access & ~EXTRA_ACL) &&
unknown's avatar
unknown committed
4973
	thd->db)
unknown's avatar
unknown committed
4974
      tables->grant.privilege= want_access;
unknown's avatar
unknown committed
4975
    else if (tables->db && thd->db && strcmp(tables->db, thd->db) == 0)
unknown's avatar
unknown committed
4976
    {
4977
      if (check_access(thd,want_access,tables->db,&tables->grant.privilege,
4978
			 0, no_errors, test(tables->schema_table)))
4979
        goto deny;                            // Access denied
unknown's avatar
unknown committed
4980
    }
4981
    else if (check_access(thd,want_access,tables->db,&tables->grant.privilege,
4982
			  0, no_errors, test(tables->schema_table)))
4983
      goto deny;
unknown's avatar
unknown committed
4984
  }
4985
  thd->security_ctx= backup_ctx;
4986
  return check_grant(thd,want_access & ~EXTRA_ACL,org_tables,
unknown's avatar
unknown committed
4987
		       test(want_access & EXTRA_ACL), UINT_MAX, no_errors);
4988 4989 4990
deny:
  thd->security_ctx= backup_ctx;
  return TRUE;
unknown's avatar
unknown committed
4991 4992
}

4993

4994
bool
4995 4996
check_routine_access(THD *thd, ulong want_access,char *db, char *name,
		     bool is_proc, bool no_errors)
4997 4998 4999 5000 5001
{
  TABLE_LIST tables[1];
  
  bzero((char *)tables, sizeof(TABLE_LIST));
  tables->db= db;
5002
  tables->table_name= tables->alias= name;
5003
  
unknown's avatar
unknown committed
5004 5005 5006 5007 5008 5009 5010
  /*
    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)
5011 5012
    tables->grant.privilege= want_access;
  else if (check_access(thd,want_access,db,&tables->grant.privilege,
unknown's avatar
unknown committed
5013
			0, no_errors, 0))
5014 5015
    return TRUE;
  
unknown's avatar
unknown committed
5016
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5017
    return check_grant_routine(thd, want_access, tables, is_proc, no_errors);
5018
#else
5019
  return FALSE;
5020
#endif
5021 5022
}

5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037

/*
  Check if the routine has any of the routine privileges

  SYNOPSIS
    check_some_routine_access()
    thd		 Thread handler
    db           Database name
    name         Routine name

  RETURN
    0            ok
    1            error
*/

5038 5039
bool check_some_routine_access(THD *thd, const char *db, const char *name,
                               bool is_proc)
5040 5041
{
  ulong save_priv;
5042
  if (thd->security_ctx->master_access & SHOW_PROC_ACLS)
5043
    return FALSE;
5044 5045 5046 5047 5048
  /*
    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) ||
5049 5050
      (save_priv & SHOW_PROC_ACLS))
    return FALSE;
5051
  return check_routine_level_acl(thd, db, name, is_proc);
5052 5053 5054
}


5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079
/*
  Check if the given table has any of the asked privileges

  SYNOPSIS
    check_some_access()
    thd		 Thread handler
    want_access	 Bitmap of possible privileges to check for

  RETURN
    0  ok
    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,
5080 5081
                        &table->grant.privilege, 0, 1,
                        test(table->schema_table)) &&
5082
          !check_grant(thd, access, table, 0, 1, 1))
5083 5084 5085 5086 5087 5088 5089 5090
        DBUG_RETURN(0);
    }
  }
  DBUG_PRINT("exit",("no matching access rights"));
  DBUG_RETURN(1);
}


5091 5092
bool check_merge_table_access(THD *thd, char *db,
			      TABLE_LIST *table_list)
5093 5094 5095 5096
{
  int error=0;
  if (table_list)
  {
5097
    /* Check that all tables use the current database */
5098
    TABLE_LIST *tmp;
unknown's avatar
VIEW  
unknown committed
5099
    for (tmp= table_list; tmp; tmp= tmp->next_local)
5100 5101 5102 5103
    {
      if (!tmp->db || !tmp->db[0])
	tmp->db=db;
    }
5104
    error=check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL,
unknown's avatar
unknown committed
5105
			     table_list,0);
5106 5107 5108 5109
  }
  return error;
}

unknown's avatar
unknown committed
5110

unknown's avatar
unknown committed
5111 5112 5113 5114
/****************************************************************************
	Check stack size; Send error if there isn't enough stack to continue
****************************************************************************/

5115 5116
#ifndef EMBEDDED_LIBRARY

unknown's avatar
unknown committed
5117 5118 5119 5120 5121
#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
5122

unknown's avatar
unknown committed
5123 5124 5125 5126
#ifndef DBUG_OFF
long max_stack_used;
#endif

5127 5128 5129 5130 5131 5132 5133
/*
  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.
 */
bool check_stack_overrun(THD *thd, long margin,
5134
			 uchar *buf __attribute__((unused)))
unknown's avatar
unknown committed
5135 5136
{
  long stack_used;
5137
  DBUG_ASSERT(thd == current_thd);
unknown's avatar
unknown committed
5138
  if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >=
unknown's avatar
unknown committed
5139
      (long) (thread_stack - margin))
unknown's avatar
unknown committed
5140
  {
5141 5142 5143
    sprintf(errbuff[0],ER(ER_STACK_OVERRUN_NEED_MORE),
            stack_used,thread_stack,margin);
    my_message(ER_STACK_OVERRUN_NEED_MORE,errbuff[0],MYF(0));
5144
    thd->fatal_error();
unknown's avatar
unknown committed
5145 5146
    return 1;
  }
unknown's avatar
unknown committed
5147 5148 5149
#ifndef DBUG_OFF
  max_stack_used= max(max_stack_used, stack_used);
#endif
unknown's avatar
unknown committed
5150 5151
  return 0;
}
5152
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
5153 5154 5155 5156

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

5157
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
unknown's avatar
unknown committed
5158
{
5159
  LEX	*lex= current_thd->lex;
5160
  ulong old_info=0;
unknown's avatar
unknown committed
5161 5162 5163 5164 5165
  if ((uint) *yystacksize >= MY_YACC_MAX)
    return 1;
  if (!lex->yacc_yyvs)
    old_info= *yystacksize;
  *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
5166 5167
  if (!(lex->yacc_yyvs= (uchar*)
	my_realloc(lex->yacc_yyvs,
unknown's avatar
unknown committed
5168 5169
		   *yystacksize*sizeof(**yyvs),
		   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
5170 5171
      !(lex->yacc_yyss= (uchar*)
	my_realloc(lex->yacc_yyss,
unknown's avatar
unknown committed
5172 5173 5174 5175 5176
		   *yystacksize*sizeof(**yyss),
		   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
    return 1;
  if (old_info)
  {						// Copy old info from stack
5177 5178
    memcpy(lex->yacc_yyss, (uchar*) *yyss, old_info*sizeof(**yyss));
    memcpy(lex->yacc_yyvs, (uchar*) *yyvs, old_info*sizeof(**yyvs));
unknown's avatar
unknown committed
5179 5180 5181 5182 5183 5184 5185
  }
  *yyss=(short*) lex->yacc_yyss;
  *yyvs=(YYSTYPE*) lex->yacc_yyvs;
  return 0;
}


5186 5187 5188 5189 5190 5191
/*
 Reset THD part responsible for command processing state.

 DESCRIPTION
   This needs to be called before execution of every statement
   (prepared or conventional).
5192
   It is not called by substatements of routines.
5193 5194 5195 5196 5197 5198 5199 5200 5201 5202

 TODO
   Make it a method of THD and align its name with the rest of
   reset/end/start/init methods.
   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");
5203
  DBUG_ASSERT(!thd->spcont); /* not for substatements of routines */
5204
  thd->free_list= 0;
5205
  thd->select_number= 1;
5206 5207 5208 5209
  /*
    Those two lines below are theoretically unneeded as
    THD::cleanup_after_query() should take care of this already.
  */
5210
  thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
5211 5212 5213
  thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;

  thd->query_start_used= 0;
5214
  thd->is_fatal_error= thd->time_zone_used= 0;
unknown's avatar
unknown committed
5215
  thd->server_status&= ~ (SERVER_MORE_RESULTS_EXISTS | 
unknown's avatar
unknown committed
5216 5217
                          SERVER_QUERY_NO_INDEX_USED |
                          SERVER_QUERY_NO_GOOD_INDEX_USED);
5218 5219 5220 5221 5222 5223
  /*
    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.
  */
  if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)))
unknown's avatar
unknown committed
5224 5225
  {
    thd->options&= ~OPTION_KEEP_LOG;
5226
    thd->transaction.all.modified_non_trans_table= FALSE;
unknown's avatar
unknown committed
5227
  }
5228
  DBUG_ASSERT(thd->security_ctx== &thd->main_security_ctx);
unknown's avatar
unknown committed
5229
  thd->thread_specific_used= FALSE;
5230 5231
  if (!thd->in_sub_stmt)
  {
5232
    if (opt_bin_log)
5233
    {
5234
      reset_dynamic(&thd->user_var_events);
5235 5236
      thd->user_var_events_alloc= thd->mem_root;
    }
5237
    thd->clear_error();
5238 5239 5240 5241
    thd->total_warn_count=0;			// Warnings for this query
    thd->rand_used= 0;
    thd->sent_row_count= thd->examined_row_count= 0;
  }
5242 5243 5244 5245
  /*
    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
5246 5247
  thd->reset_current_stmt_binlog_row_based();

unknown's avatar
unknown committed
5248 5249 5250
  DBUG_VOID_RETURN;
}

5251

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

5265

unknown's avatar
unknown committed
5266
bool
unknown's avatar
unknown committed
5267
mysql_new_select(LEX *lex, bool move_down)
5268
{
unknown's avatar
unknown committed
5269
  SELECT_LEX *select_lex;
5270
  THD *thd= lex->thd;
unknown's avatar
unknown committed
5271 5272
  DBUG_ENTER("mysql_new_select");

5273
  if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
unknown's avatar
unknown committed
5274
    DBUG_RETURN(1);
5275
  select_lex->select_number= ++thd->select_number;
unknown's avatar
unknown committed
5276
  select_lex->parent_lex= lex; /* Used in init_query. */
unknown's avatar
unknown committed
5277 5278
  select_lex->init_query();
  select_lex->init_select();
unknown's avatar
unknown committed
5279
  lex->nest_level++;
unknown's avatar
unknown committed
5280 5281 5282 5283 5284
  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
5285
  select_lex->nest_level= lex->nest_level;
5286 5287 5288 5289 5290
  /*
    Don't evaluate this subquery during statement prepare even if
    it's a constant one. The flag is switched off in the end of
    mysql_stmt_prepare.
  */
unknown's avatar
unknown committed
5291
  if (thd->stmt_arena->is_stmt_prepare())
5292
    select_lex->uncacheable|= UNCACHEABLE_PREPARE;
unknown's avatar
unknown committed
5293 5294
  if (move_down)
  {
unknown's avatar
unknown committed
5295
    SELECT_LEX_UNIT *unit;
5296
    lex->subqueries= TRUE;
unknown's avatar
unknown committed
5297
    /* first select_lex of subselect or derived table */
5298
    if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
unknown's avatar
unknown committed
5299
      DBUG_RETURN(1);
unknown's avatar
unknown committed
5300

unknown's avatar
unknown committed
5301 5302
    unit->init_query();
    unit->init_select();
5303
    unit->thd= thd;
unknown's avatar
unknown committed
5304
    unit->include_down(lex->current_select);
unknown's avatar
unknown committed
5305 5306
    unit->link_next= 0;
    unit->link_prev= 0;
5307
    unit->return_to= lex->current_select;
unknown's avatar
unknown committed
5308
    select_lex->include_down(unit);
5309 5310 5311 5312 5313
    /*
      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
5314 5315
  }
  else
unknown's avatar
unknown committed
5316
  {
unknown's avatar
VIEW  
unknown committed
5317 5318
    if (lex->current_select->order_list.first && !lex->current_select->braces)
    {
unknown's avatar
unknown committed
5319
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY");
unknown's avatar
unknown committed
5320
      DBUG_RETURN(1);
unknown's avatar
VIEW  
unknown committed
5321
    }
5322
    select_lex->include_neighbour(lex->current_select);
5323 5324 5325 5326 5327
    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
5328
  }
unknown's avatar
unknown committed
5329

5330
  select_lex->master_unit()->global_parameters= select_lex;
5331
  select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
5332
  lex->current_select= select_lex;
5333 5334 5335 5336 5337
  /*
    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
5338
  DBUG_RETURN(0);
5339
}
unknown's avatar
unknown committed
5340

5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355
/*
  Create a select to return the same output as 'SELECT @@var_name'.

  SYNOPSIS
    create_select_for_variable()
    var_name		Variable name

  DESCRIPTION
    Used for SHOW COUNT(*) [ WARNINGS | ERROR]

    This will crash with a core dump if the variable doesn't exists
*/

void create_select_for_variable(const char *var_name)
{
5356
  THD *thd;
5357
  LEX *lex;
5358
  LEX_STRING tmp, null_lex_string;
5359 5360
  Item *var;
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
5361
  DBUG_ENTER("create_select_for_variable");
5362 5363

  thd= current_thd;
unknown's avatar
unknown committed
5364
  lex= thd->lex;
5365 5366 5367 5368
  mysql_init_select(lex);
  lex->sql_command= SQLCOM_SELECT;
  tmp.str= (char*) var_name;
  tmp.length=strlen(var_name);
5369
  bzero((char*) &null_lex_string.str, sizeof(null_lex_string));
5370 5371 5372 5373
  /*
    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
5374 5375 5376 5377 5378 5379
  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);
  }
5380 5381 5382
  DBUG_VOID_RETURN;
}

5383

unknown's avatar
unknown committed
5384 5385
void mysql_init_multi_delete(LEX *lex)
{
unknown's avatar
unknown committed
5386
  lex->sql_command=  SQLCOM_DELETE_MULTI;
unknown's avatar
unknown committed
5387
  mysql_init_select(lex);
5388 5389
  lex->select_lex.select_limit= 0;
  lex->unit.select_limit_cnt= HA_POS_ERROR;
unknown's avatar
unknown committed
5390
  lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list);
5391
  lex->lock_option= using_update_log ? TL_READ_NO_INSERT : TL_READ;
unknown's avatar
VIEW  
unknown committed
5392 5393
  lex->query_tables= 0;
  lex->query_tables_last= &lex->query_tables;
unknown's avatar
unknown committed
5394
}
unknown's avatar
unknown committed
5395

5396

5397 5398 5399 5400
/*
  When you modify mysql_parse(), you may need to mofify
  mysql_test_parse_for_slave() in this same file.
*/
unknown's avatar
unknown committed
5401

5402 5403
/**
  Parse a query.
unknown's avatar
unknown committed
5404 5405 5406 5407 5408 5409

  @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.
5410 5411 5412 5413
*/

void mysql_parse(THD *thd, const char *inBuf, uint length,
                 const char ** found_semicolon)
unknown's avatar
unknown committed
5414 5415
{
  DBUG_ENTER("mysql_parse");
5416 5417 5418

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

5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436
  /*
    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);
5437

5438
  if (query_cache_send_result_to_client(thd, (char*) inBuf, length) <= 0)
unknown's avatar
unknown committed
5439
  {
unknown's avatar
unknown committed
5440
    LEX *lex= thd->lex;
5441

5442 5443
    sp_cache_flush_obsolete(&thd->sp_proc_cache);
    sp_cache_flush_obsolete(&thd->sp_func_cache);
5444 5445 5446

    Lex_input_stream lip(thd, inBuf, length);

unknown's avatar
unknown committed
5447
    bool err= parse_sql(thd, &lip, NULL);
5448 5449
    *found_semicolon= lip.found_semicolon;

5450
    if (!err)
unknown's avatar
unknown committed
5451
    {
unknown's avatar
unknown committed
5452
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5453
      if (mqh_used && thd->user_connect &&
5454
	  check_mqh(thd, lex->sql_command))
5455 5456 5457 5458
      {
	thd->net.error = 0;
      }
      else
unknown's avatar
unknown committed
5459
#endif
5460
      {
5461
	if (! thd->net.report_error)
unknown's avatar
unknown committed
5462
	{
5463 5464 5465 5466 5467 5468 5469 5470 5471 5472
          /*
            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.
          */
5473 5474
          if (*found_semicolon &&
              (thd->query_length= (ulong)(*found_semicolon - thd->query)))
5475 5476
            thd->query_length--;
          /* Actually execute the query */
5477 5478 5479
          lex->set_trg_event_type_for_tables();
          mysql_execute_command(thd);
          query_cache_end_of_result(thd);
unknown's avatar
unknown committed
5480
	}
5481
      }
unknown's avatar
unknown committed
5482 5483
    }
    else
5484
    {
5485
      DBUG_ASSERT(thd->net.report_error);
5486
      DBUG_PRINT("info",("Command aborted. Fatal_error: %d",
5487
			 thd->is_fatal_error));
5488 5489

      query_cache_abort(&thd->net);
5490
    }
5491 5492 5493 5494 5495 5496
    if (thd->lex->sphead)
    {
      delete thd->lex->sphead;
      thd->lex->sphead= 0;
    }
    lex->unit.cleanup();
unknown's avatar
unknown committed
5497
    thd->proc_info="freeing items";
5498
    thd->end_statement();
5499
    thd->cleanup_after_query();
5500
    DBUG_ASSERT(thd->change_list.is_empty());
unknown's avatar
unknown committed
5501
  }
5502 5503 5504 5505 5506 5507
  else
  {
    /* There are no multi queries in the cache. */
    *found_semicolon= NULL;
  }

unknown's avatar
unknown committed
5508 5509 5510 5511
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
5512
#ifdef HAVE_REPLICATION
5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523
/*
  Usable by the replication SQL thread only: just parse a query to know if it
  can be ignored because of replicate-*-table rules.

  RETURN VALUES
    0	cannot be ignored
    1	can be ignored
*/

bool mysql_test_parse_for_slave(THD *thd, char *inBuf, uint length)
{
unknown's avatar
unknown committed
5524
  LEX *lex= thd->lex;
5525
  bool error= 0;
unknown's avatar
unknown committed
5526
  DBUG_ENTER("mysql_test_parse_for_slave");
5527

5528 5529 5530 5531
  Lex_input_stream lip(thd, inBuf, length);
  lex_start(thd);
  mysql_reset_thd_for_next_command(thd);

unknown's avatar
unknown committed
5532
  if (!parse_sql(thd, &lip, NULL) &&
5533
      all_tables_not_ok(thd,(TABLE_LIST*) lex->select_lex.table_list.first))
unknown's avatar
unknown committed
5534
    error= 1;                  /* Ignore question */
5535
  thd->end_statement();
5536
  thd->cleanup_after_query();
unknown's avatar
unknown committed
5537
  DBUG_RETURN(error);
5538
}
unknown's avatar
unknown committed
5539
#endif
unknown's avatar
unknown committed
5540

5541

unknown's avatar
unknown committed
5542

unknown's avatar
unknown committed
5543 5544 5545 5546 5547
/*****************************************************************************
** Store field definition for create
** Return 0 if ok
******************************************************************************/

5548
bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum_field_types type,
unknown's avatar
unknown committed
5549
		       char *length, char *decimals,
5550
		       uint type_modifier,
5551 5552
		       Item *default_value, Item *on_update_value,
                       LEX_STRING *comment,
5553 5554
		       char *change,
                       List<String> *interval_list, CHARSET_INFO *cs,
unknown's avatar
unknown committed
5555
		       uint uint_geom_type)
unknown's avatar
unknown committed
5556
{
unknown's avatar
unknown committed
5557
  register Create_field *new_field;
unknown's avatar
unknown committed
5558
  LEX  *lex= thd->lex;
unknown's avatar
unknown committed
5559 5560
  DBUG_ENTER("add_field_to_list");

5561 5562
  if (check_string_char_length(field_name, "", NAME_CHAR_LEN,
                               system_charset_info, 1))
unknown's avatar
unknown committed
5563
  {
5564
    my_error(ER_TOO_LONG_IDENT, MYF(0), field_name->str); /* purecov: inspected */
unknown's avatar
unknown committed
5565 5566 5567 5568
    DBUG_RETURN(1);				/* purecov: inspected */
  }
  if (type_modifier & PRI_KEY_FLAG)
  {
5569
    Key *key;
unknown's avatar
unknown committed
5570
    lex->col_list.push_back(new Key_part_spec(field_name->str, 0));
5571 5572 5573 5574
    key= new Key(Key::PRIMARY, NullS,
                      &default_key_create_info,
                      0, lex->col_list);
    lex->alter_info.key_list.push_back(key);
unknown's avatar
unknown committed
5575 5576 5577 5578
    lex->col_list.empty();
  }
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
  {
5579
    Key *key;
unknown's avatar
unknown committed
5580
    lex->col_list.push_back(new Key_part_spec(field_name->str, 0));
5581 5582 5583 5584
    key= new Key(Key::UNIQUE, NullS,
                 &default_key_create_info, 0,
                 lex->col_list);
    lex->alter_info.key_list.push_back(key);
unknown's avatar
unknown committed
5585 5586 5587
    lex->col_list.empty();
  }

5588
  if (default_value)
unknown's avatar
unknown committed
5589
  {
5590
    /* 
unknown's avatar
unknown committed
5591 5592
      Default value should be literal => basic constants =>
      no need fix_fields()
5593 5594 5595
      
      We allow only one function as part of default value - 
      NOW() as default for TIMESTAMP type.
5596
    */
5597 5598
    if (default_value->type() == Item::FUNC_ITEM && 
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
5599
         type == MYSQL_TYPE_TIMESTAMP))
5600
    {
5601
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
5602 5603 5604
      DBUG_RETURN(1);
    }
    else if (default_value->type() == Item::NULL_ITEM)
unknown's avatar
unknown committed
5605
    {
5606
      default_value= 0;
5607 5608 5609
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
	  NOT_NULL_FLAG)
      {
5610
	my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
5611 5612 5613 5614 5615
	DBUG_RETURN(1);
      }
    }
    else if (type_modifier & AUTO_INCREMENT_FLAG)
    {
5616
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
unknown's avatar
unknown committed
5617 5618 5619
      DBUG_RETURN(1);
    }
  }
5620

5621
  if (on_update_value && type != MYSQL_TYPE_TIMESTAMP)
5622
  {
5623
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
5624 5625
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
5626

5627
  if (type == MYSQL_TYPE_TIMESTAMP && length)
5628 5629 5630 5631 5632
  {
    /* Display widths are no longer supported for TIMSTAMP as of MySQL 4.1.
       In other words, for declarations such as TIMESTAMP(2), TIMESTAMP(4),
       and so on, the display width is ignored.
    */
unknown's avatar
unknown committed
5633
    char buf[32];
5634
    my_snprintf(buf, sizeof(buf), "TIMESTAMP(%s)", length);
unknown's avatar
unknown committed
5635
    WARN_DEPRECATED(thd, "5.2", buf, "'TIMESTAMP'");
5636 5637
  }

unknown's avatar
unknown committed
5638
  if (!(new_field= new Create_field()) ||
5639
      new_field->init(thd, field_name->str, type, length, decimals, type_modifier,
5640 5641
                      default_value, on_update_value, comment, change,
                      interval_list, cs, uint_geom_type))
unknown's avatar
unknown committed
5642
    DBUG_RETURN(1);
unknown's avatar
unknown committed
5643

5644
  lex->alter_info.create_list.push_back(new_field);
unknown's avatar
unknown committed
5645 5646 5647 5648
  lex->last_field=new_field;
  DBUG_RETURN(0);
}

5649

unknown's avatar
unknown committed
5650 5651 5652 5653
/* Store position for column in ALTER TABLE .. ADD column */

void store_position_for_column(const char *name)
{
5654
  current_thd->lex->last_field->after=my_const_cast(char*) (name);
unknown's avatar
unknown committed
5655 5656 5657
}

bool
unknown's avatar
unknown committed
5658
add_proc_to_list(THD* thd, Item *item)
unknown's avatar
unknown committed
5659 5660 5661 5662
{
  ORDER *order;
  Item	**item_ptr;

unknown's avatar
unknown committed
5663
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*))))
unknown's avatar
unknown committed
5664 5665 5666 5667 5668
    return 1;
  item_ptr = (Item**) (order+1);
  *item_ptr= item;
  order->item=item_ptr;
  order->free_me=0;
5669
  thd->lex->proc_list.link_in_list((uchar*) order,(uchar**) &order->next);
unknown's avatar
unknown committed
5670 5671 5672 5673 5674 5675 5676 5677 5678
  return 0;
}


/****************************************************************************
** save order by and tables in own lists
****************************************************************************/


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


unknown's avatar
unknown committed
5696 5697 5698 5699 5700 5701 5702 5703 5704 5705
/*
  Add a table to list of used tables

  SYNOPSIS
    add_table_to_list()
    table		Table to add
    alias		alias for table (or null if no alias)
    table_options	A set of the following bits:
			TL_OPTION_UPDATING	Table will be updated
			TL_OPTION_FORCE_INDEX	Force usage of index
5706
			TL_OPTION_ALIAS	        an alias in multi table DELETE
unknown's avatar
unknown committed
5707 5708 5709 5710 5711 5712 5713 5714 5715
    lock_type		How table should be locked
    use_index		List of indexed used in USE INDEX
    ignore_index	List of indexed used in IGNORE INDEX

    RETURN
      0		Error
      #		Pointer to TABLE_LIST element added to the total table list
*/

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

  if (!table)
    DBUG_RETURN(0);				// End of memory
  alias_str= alias ? alias->str : table->table.str;
5734 5735
  if (!test(table_options & TL_OPTION_ALIAS) && 
      check_table_name(table->table.str, table->table.length))
unknown's avatar
unknown committed
5736
  {
5737
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
unknown's avatar
unknown committed
5738 5739
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
5740 5741

  if (table->is_derived_table() == FALSE && table->db.str &&
5742
      check_db_name(&table->db))
unknown's avatar
unknown committed
5743 5744 5745 5746
  {
    my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
5747 5748

  if (!alias)					/* Alias is case sensitive */
5749 5750 5751
  {
    if (table->sel)
    {
unknown's avatar
unknown committed
5752 5753
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
                 ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
5754 5755
      DBUG_RETURN(0);
    }
5756
    if (!(alias_str= (char*) thd->memdup(alias_str,table->table.length+1)))
unknown's avatar
unknown committed
5757
      DBUG_RETURN(0);
5758
  }
unknown's avatar
unknown committed
5759
  if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST))))
unknown's avatar
unknown committed
5760
    DBUG_RETURN(0);				/* purecov: inspected */
unknown's avatar
unknown committed
5761
  if (table->db.str)
5762 5763 5764 5765
  {
    ptr->db= table->db.str;
    ptr->db_length= table->db.length;
  }
5766
  else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
unknown's avatar
unknown committed
5767
    DBUG_RETURN(0);
unknown's avatar
unknown committed
5768

5769
  ptr->alias= alias_str;
5770
  if (lower_case_table_names && table->table.length)
5771
    table->table.length= my_casedn_str(files_charset_info, table->table.str);
5772 5773
  ptr->table_name=table->table.str;
  ptr->table_name_length=table->table.length;
5774
  ptr->lock_type=   lock_type;
unknown's avatar
unknown committed
5775 5776
  ptr->updating=    test(table_options & TL_OPTION_UPDATING);
  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
unknown's avatar
unknown committed
5777
  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
5778
  ptr->derived=	    table->sel;
5779
  if (!ptr->derived && !my_strcasecmp(system_charset_info, ptr->db,
5780
                                      INFORMATION_SCHEMA_NAME.str))
5781
  {
5782
    ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, ptr->table_name);
5783 5784
    if (!schema_table ||
        (schema_table->hidden && 
5785
         (sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0))
5786
    {
unknown's avatar
unknown committed
5787
      my_error(ER_UNKNOWN_TABLE, MYF(0),
5788
               ptr->table_name, INFORMATION_SCHEMA_NAME.str);
5789 5790
      DBUG_RETURN(0);
    }
5791
    ptr->schema_table_name= ptr->table_name;
5792 5793
    ptr->schema_table= schema_table;
  }
5794
  ptr->select_lex=  lex->current_select;
unknown's avatar
unknown committed
5795
  ptr->cacheable_table= 1;
5796
  ptr->index_hints= index_hints_arg;
unknown's avatar
unknown committed
5797
  ptr->option= option ? option->str : 0;
unknown's avatar
unknown committed
5798
  /* check that used name is unique */
5799
  if (lock_type != TL_IGNORE)
unknown's avatar
unknown committed
5800
  {
unknown's avatar
unknown committed
5801 5802 5803 5804
    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
5805
	 tables ;
unknown's avatar
VIEW  
unknown committed
5806
	 tables=tables->next_local)
unknown's avatar
unknown committed
5807
    {
5808 5809
      if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
	  !strcmp(ptr->db, tables->db))
unknown's avatar
unknown committed
5810
      {
5811
	my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
unknown's avatar
unknown committed
5812 5813
	DBUG_RETURN(0);				/* purecov: tested */
      }
unknown's avatar
unknown committed
5814 5815
    }
  }
unknown's avatar
unknown committed
5816 5817 5818
  /* Store the table reference preceding the current one. */
  if (table_list.elements > 0)
  {
5819 5820 5821
    /*
      table_list.next points to the last inserted TABLE_LIST->next_local'
      element
5822
      We don't use the offsetof() macro here to avoid warnings from gcc
5823
    */
5824 5825 5826
    previous_table_ref= (TABLE_LIST*) ((char*) table_list.next -
                                       ((char*) &(ptr->next_local) -
                                        (char*) ptr));
5827 5828 5829 5830 5831 5832 5833 5834
    /*
      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
5835
  }
5836

unknown's avatar
unknown committed
5837 5838 5839 5840 5841 5842
  /*
    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'.
  */
5843
  table_list.link_in_list((uchar*) ptr, (uchar**) &ptr->next_local);
unknown's avatar
unknown committed
5844
  ptr->next_name_resolution_table= NULL;
5845
  /* Link table in global list (all used tables) */
5846
  lex->add_to_query_tables(ptr);
unknown's avatar
unknown committed
5847 5848 5849
  DBUG_RETURN(ptr);
}

unknown's avatar
unknown committed
5850

5851 5852 5853 5854
/*
  Initialize a new table list for a nested join

  SYNOPSIS
unknown's avatar
unknown committed
5855
    init_nested_join()
5856
    thd         current thread
5857

5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876
  DESCRIPTION
    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.

  RETURN VALUE
    0,  if success
    1,  otherwise
*/

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

5878 5879
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
5880
    DBUG_RETURN(1);
5881
  nested_join= ptr->nested_join=
5882
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
5883

5884 5885 5886
  join_list->push_front(ptr);
  ptr->embedding= embedding;
  ptr->join_list= join_list;
5887
  ptr->alias= (char*) "(nested_join)";
5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904
  embedding= ptr;
  join_list= &nested_join->join_list;
  join_list->empty();
  DBUG_RETURN(0);
}


/*
  End a nested join table list

  SYNOPSIS
    end_nested_join()
    thd         current thread

  DESCRIPTION
    The function returns to the previous join nest level.
    If the current level contains only one member, the function
5905
    moves it one level up, eliminating the nest.
5906 5907 5908 5909 5910 5911 5912 5913 5914

  RETURN VALUE
    Pointer to TABLE_LIST element added to the total table list, if success
    0, otherwise
*/

TABLE_LIST *st_select_lex::end_nested_join(THD *thd)
{
  TABLE_LIST *ptr;
5915
  NESTED_JOIN *nested_join;
5916
  DBUG_ENTER("end_nested_join");
5917

unknown's avatar
unknown committed
5918
  DBUG_ASSERT(embedding);
5919 5920 5921
  ptr= embedding;
  join_list= ptr->join_list;
  embedding= ptr->embedding;
5922
  nested_join= ptr->nested_join;
5923 5924 5925 5926 5927 5928 5929 5930 5931
  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;
  }
5932
  else if (nested_join->join_list.elements == 0)
unknown's avatar
unknown committed
5933 5934
  {
    join_list->pop();
5935
    ptr= 0;                                     // return value
unknown's avatar
unknown committed
5936
  }
5937 5938 5939 5940 5941 5942 5943 5944
  DBUG_RETURN(ptr);
}


/*
  Nest last join operation

  SYNOPSIS
5945
    nest_last_join()
5946 5947 5948 5949 5950 5951
    thd         current thread

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

  RETURN VALUE
5952 5953 5954
    0  Error
    #  Pointer to TABLE_LIST element created for the new nested join

5955 5956 5957 5958 5959 5960
*/

TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
5961
  List<TABLE_LIST> *embedded_list;
5962
  DBUG_ENTER("nest_last_join");
5963

5964 5965
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
5966
    DBUG_RETURN(0);
5967
  nested_join= ptr->nested_join=
5968
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
5969

5970 5971
  ptr->embedding= embedding;
  ptr->join_list= join_list;
5972
  ptr->alias= (char*) "(nest_last_join)";
5973
  embedded_list= &nested_join->join_list;
5974
  embedded_list->empty();
5975 5976

  for (uint i=0; i < 2; i++)
5977 5978 5979 5980 5981
  {
    TABLE_LIST *table= join_list->pop();
    table->join_list= embedded_list;
    table->embedding= ptr;
    embedded_list->push_back(table);
unknown's avatar
unknown committed
5982 5983 5984 5985 5986 5987 5988
    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
5989 5990
      if (prev_join_using)
        ptr->join_using_fields= prev_join_using;
unknown's avatar
unknown committed
5991
    }
5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031
  }
  join_list->push_front(ptr);
  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
  DBUG_RETURN(ptr);
}


/*
  Add a table to the current join list

  SYNOPSIS
    add_joined_table()
    table       the table to add

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

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


/*
  Convert a right join into equivalent left join

  SYNOPSIS
    convert_right_join()
    thd         current thread
6032 6033 6034

  DESCRIPTION
    The function takes the current join list t[0],t[1] ... and
6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057
    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
    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

  RETURN
    Pointer to the table representing the inner table, if success
    0, otherwise
*/

6058
TABLE_LIST *st_select_lex::convert_right_join()
6059 6060
{
  TABLE_LIST *tab2= join_list->pop();
6061
  TABLE_LIST *tab1= join_list->pop();
6062 6063 6064 6065 6066 6067 6068 6069 6070
  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
6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083
/*
  Set lock for all tables in current select level

  SYNOPSIS:
    set_lock_for_tables()
    lock_type			Lock to set for tables

  NOTE:
    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
6084
void st_select_lex::set_lock_for_tables(thr_lock_type lock_type)
unknown's avatar
unknown committed
6085 6086 6087 6088 6089 6090
{
  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
6091 6092 6093
  for (TABLE_LIST *tables= (TABLE_LIST*) table_list.first;
       tables;
       tables= tables->next_local)
unknown's avatar
unknown committed
6094 6095 6096 6097 6098 6099 6100
  {
    tables->lock_type= lock_type;
    tables->updating=  for_update;
  }
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
6101

unknown's avatar
unknown committed
6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125
/*
  Create a fake SELECT_LEX for a unit

  SYNOPSIS:
    add_fake_select_lex()
    thd			   thread handle

  DESCRIPTION
    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
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ... 
    or of the form
    (SELECT ... ORDER BY LIMIT n) ORDER BY ...
  
  NOTES
    The object is used to retrieve rows from the temporary table
    where the result on the union is obtained.

  RETURN VALUES
    1     on failure to create the object
    0     on success
*/

unknown's avatar
unknown committed
6126
bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg)
unknown's avatar
unknown committed
6127 6128 6129 6130
{
  SELECT_LEX *first_sl= first_select();
  DBUG_ENTER("add_fake_select_lex");
  DBUG_ASSERT(!fake_select_lex);
unknown's avatar
unknown committed
6131

unknown's avatar
unknown committed
6132
  if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX()))
unknown's avatar
unknown committed
6133 6134 6135 6136
      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
6137
  fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */
unknown's avatar
unknown committed
6138 6139
  fake_select_lex->make_empty_select();
  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
6140 6141
  fake_select_lex->select_limit= 0;

unknown's avatar
unknown committed
6142
  fake_select_lex->context.outer_context=first_sl->context.outer_context;
6143 6144 6145
  /* 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
6146

6147
  if (!is_union())
unknown's avatar
unknown committed
6148 6149 6150 6151 6152 6153 6154 6155 6156
  {
    /* 
      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
6157
    thd_arg->lex->current_select= fake_select_lex;
unknown's avatar
unknown committed
6158
  }
unknown's avatar
unknown committed
6159
  thd_arg->lex->pop_context();
unknown's avatar
unknown committed
6160 6161 6162
  DBUG_RETURN(0);
}

6163

unknown's avatar
unknown committed
6164
/*
6165 6166
  Push a new name resolution context for a JOIN ... ON clause to the
  context stack of a query block.
unknown's avatar
unknown committed
6167 6168

  SYNOPSIS
6169
    push_new_name_resolution_context()
unknown's avatar
unknown committed
6170
    thd       pointer to current thread
unknown's avatar
unknown committed
6171
    left_op   left  operand of the JOIN
unknown's avatar
unknown committed
6172 6173 6174 6175
    right_op  rigth operand of the JOIN

  DESCRIPTION
    Create a new name resolution context for a JOIN ... ON clause,
6176 6177 6178
    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
6179 6180

  RETURN
6181 6182
    FALSE  if all is OK
    TRUE   if a memory allocation error occured
unknown's avatar
unknown committed
6183 6184
*/

6185 6186 6187
bool
push_new_name_resolution_context(THD *thd,
                                 TABLE_LIST *left_op, TABLE_LIST *right_op)
unknown's avatar
unknown committed
6188 6189
{
  Name_resolution_context *on_context;
6190
  if (!(on_context= new (thd->mem_root) Name_resolution_context))
6191
    return TRUE;
unknown's avatar
unknown committed
6192 6193 6194 6195 6196
  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();
6197
  return thd->lex->push_context(on_context);
unknown's avatar
unknown committed
6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217
}


/*
  Add an ON condition to the second operand of a JOIN ... ON.

  SYNOPSIS
    add_join_on
    b     the second operand of a JOIN ... ON
    expr  the condition to be added to the ON clause

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

  RETURN
    FALSE  if there was some error
    TRUE   if all is OK
*/

void add_join_on(TABLE_LIST *b, Item *expr)
unknown's avatar
unknown committed
6218
{
6219
  if (expr)
6220
  {
6221
    if (!b->on_expr)
unknown's avatar
unknown committed
6222
      b->on_expr= expr;
6223 6224
    else
    {
unknown's avatar
unknown committed
6225 6226 6227 6228 6229 6230
      /*
        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);
6231 6232
    }
    b->on_expr->top_level_item();
6233
  }
unknown's avatar
unknown committed
6234 6235 6236
}


6237
/*
unknown's avatar
unknown committed
6238 6239
  Mark that there is a NATURAL JOIN or JOIN ... USING between two
  tables.
6240 6241 6242

  SYNOPSIS
    add_join_natural()
unknown's avatar
unknown committed
6243 6244 6245
    a			Left join argument
    b			Right join argument
    using_fields        Field names from USING clause
unknown's avatar
unknown committed
6246
    lex                 The current st_select_lex
unknown's avatar
unknown committed
6247
  
6248
  IMPLEMENTATION
unknown's avatar
unknown committed
6249 6250 6251 6252 6253 6254 6255 6256 6257 6258
    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
6259 6260 6261
    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
6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272

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

    SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
     <=>
    SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)

  RETURN
    None
6273 6274
*/

unknown's avatar
unknown committed
6275 6276
void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields,
                      SELECT_LEX *lex)
unknown's avatar
unknown committed
6277
{
unknown's avatar
unknown committed
6278
  b->natural_join= a;
unknown's avatar
unknown committed
6279
  lex->prev_join_using= using_fields;
unknown's avatar
unknown committed
6280 6281
}

unknown's avatar
unknown committed
6282

6283
/*
6284 6285 6286 6287
  Reload/resets privileges and the different caches.

  SYNOPSIS
    reload_acl_and_cache()
6288
    thd			Thread handler (can be NULL!)
6289 6290 6291 6292 6293
    options             What should be reset/reloaded (tables, privileges,
    slave...)
    tables              Tables to flush (if any)
    write_to_binlog     Depending on 'options', it may be very bad to write the
                        query to the binlog (e.g. FLUSH SLAVE); this is a
unknown's avatar
unknown committed
6294 6295 6296
                        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.
6297 6298 6299

  RETURN
    0	 ok
unknown's avatar
unknown committed
6300
    !=0  error.  thd->killed or thd->net.report_error is set
6301 6302
*/

6303 6304
bool reload_acl_and_cache(THD *thd, ulong options, TABLE_LIST *tables,
                          bool *write_to_binlog)
unknown's avatar
unknown committed
6305 6306 6307
{
  bool result=0;
  select_errors=0;				/* Write if more errors */
6308
  bool tmp_write_to_binlog= 1;
6309

6310
  DBUG_ASSERT(!thd || !thd->in_sub_stmt);
6311

unknown's avatar
SCRUM  
unknown committed
6312
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
6313 6314
  if (options & REFRESH_GRANT)
  {
6315 6316 6317 6318 6319 6320
    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)))
6321 6322
    {
      thd->thread_stack= (char*) &tmp_thd;
6323
      thd->store_globals();
6324
    }
6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336
    if (thd)
    {
      (void)acl_reload(thd);
      (void)grant_reload(thd);
    }
    if (tmp_thd)
    {
      delete tmp_thd;
      /* Remember that we don't have a THD */
      my_pthread_setspecific_ptr(THR_THD,  0);
      thd= 0;
    }
6337
    reset_mqh((LEX_USER *)NULL, TRUE);
unknown's avatar
unknown committed
6338
  }
unknown's avatar
SCRUM  
unknown committed
6339
#endif
unknown's avatar
unknown committed
6340 6341
  if (options & REFRESH_LOG)
  {
6342
    /*
unknown's avatar
unknown committed
6343
      Flush the normal query log, the update log, the binary log,
unknown's avatar
unknown committed
6344 6345
      the slow query log, the relay log (if it exists) and the log
      tables.
6346
    */
unknown's avatar
unknown committed
6347

6348
    /*
unknown's avatar
unknown committed
6349 6350 6351 6352
      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)
6353 6354
    */
    tmp_write_to_binlog= 0;
6355 6356 6357 6358
    if( mysql_bin_log.is_open() )
    {
      mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
    }
unknown's avatar
unknown committed
6359
#ifdef HAVE_REPLICATION
6360
    pthread_mutex_lock(&LOCK_active_mi);
6361
    rotate_relay_log(active_mi);
6362
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
6363
#endif
unknown's avatar
unknown committed
6364 6365 6366 6367 6368

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

    if (ha_flush_logs(NULL))
unknown's avatar
unknown committed
6369
      result=1;
unknown's avatar
unknown committed
6370 6371
    if (flush_error_log())
      result=1;
unknown's avatar
unknown committed
6372
  }
unknown's avatar
unknown committed
6373
#ifdef HAVE_QUERY_CACHE
unknown's avatar
unknown committed
6374 6375
  if (options & REFRESH_QUERY_CACHE_FREE)
  {
unknown's avatar
unknown committed
6376
    query_cache.pack();				// FLUSH QUERY CACHE
6377
    options &= ~REFRESH_QUERY_CACHE;    // Don't flush cache, just free memory
unknown's avatar
unknown committed
6378 6379 6380
  }
  if (options & (REFRESH_TABLES | REFRESH_QUERY_CACHE))
  {
unknown's avatar
unknown committed
6381
    query_cache.flush();			// RESET QUERY CACHE
unknown's avatar
unknown committed
6382
  }
unknown's avatar
unknown committed
6383
#endif /*HAVE_QUERY_CACHE*/
6384 6385 6386 6387 6388
  /*
    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
6389
  {
6390
    if ((options & REFRESH_READ_LOCK) && thd)
unknown's avatar
unknown committed
6391
    {
6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402
      /*
        We must not try to aspire a global read lock if we have a write
        locked table. This would lead to a deadlock when trying to
        reopen (and re-lock) the table after the flush.
      */
      if (thd->locked_tables)
      {
        THR_LOCK_DATA **lock_p= thd->locked_tables->locks;
        THR_LOCK_DATA **end_p= lock_p + thd->locked_tables->lock_count;

        for (; lock_p < end_p; lock_p++)
unknown's avatar
unknown committed
6403
        {
6404 6405 6406 6407 6408
          if ((*lock_p)->type == TL_WRITE)
          {
            my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
            return 1;
          }
unknown's avatar
unknown committed
6409
        }
6410
      }
unknown's avatar
unknown committed
6411 6412 6413 6414
      /*
	Writing to the binlog could cause deadlocks, as we don't log
	UNLOCK TABLES
      */
6415
      tmp_write_to_binlog= 0;
6416
      if (lock_global_read_lock(thd))
unknown's avatar
unknown committed
6417
	return 1;                               // Killed
6418 6419
      result=close_cached_tables(thd,(options & REFRESH_FAST) ? 0 : 1,
                                 tables);
unknown's avatar
unknown committed
6420
      if (make_global_read_lock_block_commit(thd)) // Killed
6421 6422 6423 6424 6425
      {
        /* Don't leave things in a half-locked state */
        unlock_global_read_lock(thd);
        return 1;
      }
unknown's avatar
unknown committed
6426
    }
6427 6428
    else
      result=close_cached_tables(thd,(options & REFRESH_FAST) ? 0 : 1, tables);
unknown's avatar
unknown committed
6429
    my_dbopt_cleanup();
unknown's avatar
unknown committed
6430 6431 6432
  }
  if (options & REFRESH_HOSTS)
    hostname_cache_refresh();
unknown's avatar
unknown committed
6433
  if (thd && (options & REFRESH_STATUS))
unknown's avatar
unknown committed
6434
    refresh_status(thd);
unknown's avatar
unknown committed
6435 6436
  if (options & REFRESH_THREADS)
    flush_thread_cache();
unknown's avatar
unknown committed
6437
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
6438
  if (options & REFRESH_MASTER)
6439
  {
6440
    DBUG_ASSERT(thd);
6441
    tmp_write_to_binlog= 0;
6442
    if (reset_master(thd))
unknown's avatar
unknown committed
6443
    {
6444
      result=1;
unknown's avatar
unknown committed
6445 6446
      thd->fatal_error();                       // Ensure client get error
    }
6447
  }
6448
#endif
unknown's avatar
unknown committed
6449
#ifdef OPENSSL
6450 6451 6452 6453 6454 6455
   if (options & REFRESH_DES_KEY_FILE)
   {
     if (des_key_file)
       result=load_des_key_file(des_key_file);
   }
#endif
unknown's avatar
unknown committed
6456
#ifdef HAVE_REPLICATION
6457 6458
 if (options & REFRESH_SLAVE)
 {
6459
   tmp_write_to_binlog= 0;
6460
   pthread_mutex_lock(&LOCK_active_mi);
6461
   if (reset_slave(thd, active_mi))
6462
     result=1;
6463
   pthread_mutex_unlock(&LOCK_active_mi);
6464
 }
6465
#endif
6466
 if (options & REFRESH_USER_RESOURCES)
6467
   reset_mqh((LEX_USER *) NULL, 0);             /* purecov: inspected */
unknown's avatar
unknown committed
6468
 *write_to_binlog= tmp_write_to_binlog;
6469
 return result;
unknown's avatar
unknown committed
6470 6471
}

6472

6473
/*
6474
  kills a thread
6475 6476 6477 6478 6479

  SYNOPSIS
    kill_one_thread()
    thd			Thread class
    id			Thread id
6480
    only_kill_query     Should it kill the query or the connection
6481 6482 6483 6484 6485

  NOTES
    This is written such that we have a short lock on LOCK_thread_count
*/

6486
uint kill_one_thread(THD *thd, ulong id, bool only_kill_query)
unknown's avatar
unknown committed
6487 6488 6489
{
  THD *tmp;
  uint error=ER_NO_SUCH_THREAD;
6490 6491
  DBUG_ENTER("kill_one_thread");
  DBUG_PRINT("enter", ("id=%lu only_kill=%d", id, only_kill_query));
6492 6493
  VOID(pthread_mutex_lock(&LOCK_thread_count)); // For unlink from list
  I_List_iterator<THD> it(threads);
unknown's avatar
unknown committed
6494 6495
  while ((tmp=it++))
  {
unknown's avatar
unknown committed
6496 6497
    if (tmp->command == COM_DAEMON)
      continue;
unknown's avatar
unknown committed
6498 6499
    if (tmp->thread_id == id)
    {
6500 6501
      pthread_mutex_lock(&tmp->LOCK_delete);	// Lock from delete
      break;
unknown's avatar
unknown committed
6502 6503 6504
    }
  }
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
6505 6506
  if (tmp)
  {
6507 6508
    if ((thd->security_ctx->master_access & SUPER_ACL) ||
	!strcmp(thd->security_ctx->user, tmp->security_ctx->user))
6509
    {
unknown's avatar
SCRUM  
unknown committed
6510
      tmp->awake(only_kill_query ? THD::KILL_QUERY : THD::KILL_CONNECTION);
6511 6512 6513 6514 6515 6516
      error=0;
    }
    else
      error=ER_KILL_DENIED_ERROR;
    pthread_mutex_unlock(&tmp->LOCK_delete);
  }
6517 6518 6519 6520
  DBUG_PRINT("exit", ("%d", error));
  DBUG_RETURN(error);
}

6521

6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535
/*
  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)))
6536
    send_ok(thd);
unknown's avatar
unknown committed
6537
  else
unknown's avatar
unknown committed
6538
    my_error(error, MYF(0), id);
unknown's avatar
unknown committed
6539 6540
}

unknown's avatar
unknown committed
6541

6542 6543
	/* If pointer is not a null pointer, append filename to it */

unknown's avatar
unknown committed
6544 6545
bool append_file_to_dir(THD *thd, const char **filename_ptr,
                        const char *table_name)
6546
{
6547
  char buff[FN_REFLEN],*ptr, *end;
6548 6549 6550 6551 6552 6553 6554
  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))
  {
6555
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
6556 6557 6558 6559
    return 1;
  }
  /* Fix is using unix filename format on dos */
  strmov(buff,*filename_ptr);
6560
  end=convert_dirname(buff, *filename_ptr, NullS);
6561
  if (!(ptr= (char*) thd->alloc((size_t) (end-buff) + strlen(table_name)+1)))
6562 6563
    return 1;					// End of memory
  *filename_ptr=ptr;
6564
  strxmov(ptr,buff,table_name,NullS);
6565 6566
  return 0;
}
6567

6568

6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582
/*
  Check if the select is a simple select (not an union)

  SYNOPSIS
    check_simple_select()

  RETURN VALUES
    0	ok
    1	error	; In this case the error messege is sent to the client
*/

bool check_simple_select()
{
  THD *thd= current_thd;
6583 6584
  LEX *lex= thd->lex;
  if (lex->current_select != &lex->select_lex)
6585 6586
  {
    char command[80];
6587 6588 6589
    Lex_input_stream *lip= thd->m_lip;
    strmake(command, lip->yylval->symbol.str,
	    min(lip->yylval->symbol.length, sizeof(command)-1));
6590
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
6591 6592 6593 6594
    return 1;
  }
  return 0;
}
unknown's avatar
unknown committed
6595

unknown's avatar
unknown committed
6596

unknown's avatar
unknown committed
6597
Comp_creator *comp_eq_creator(bool invert)
unknown's avatar
unknown committed
6598
{
unknown's avatar
unknown committed
6599
  return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
unknown's avatar
unknown committed
6600 6601
}

unknown's avatar
unknown committed
6602

unknown's avatar
unknown committed
6603
Comp_creator *comp_ge_creator(bool invert)
unknown's avatar
unknown committed
6604
{
unknown's avatar
unknown committed
6605
  return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator;
unknown's avatar
unknown committed
6606 6607
}

unknown's avatar
unknown committed
6608

unknown's avatar
unknown committed
6609
Comp_creator *comp_gt_creator(bool invert)
unknown's avatar
unknown committed
6610
{
unknown's avatar
unknown committed
6611
  return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator;
unknown's avatar
unknown committed
6612 6613
}

unknown's avatar
unknown committed
6614

unknown's avatar
unknown committed
6615
Comp_creator *comp_le_creator(bool invert)
unknown's avatar
unknown committed
6616
{
unknown's avatar
unknown committed
6617
  return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator;
unknown's avatar
unknown committed
6618 6619
}

unknown's avatar
unknown committed
6620

unknown's avatar
unknown committed
6621
Comp_creator *comp_lt_creator(bool invert)
unknown's avatar
unknown committed
6622
{
unknown's avatar
unknown committed
6623
  return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator;
unknown's avatar
unknown committed
6624 6625
}

unknown's avatar
unknown committed
6626

unknown's avatar
unknown committed
6627
Comp_creator *comp_ne_creator(bool invert)
unknown's avatar
unknown committed
6628
{
unknown's avatar
unknown committed
6629
  return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
unknown's avatar
unknown committed
6630
}
unknown's avatar
unknown committed
6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650


/*
  Construct ALL/ANY/SOME subquery Item

  SYNOPSIS
    all_any_subquery_creator()
    left_expr - pointer to left expression
    cmp - compare function creator
    all - true if we create ALL subquery
    select_lex - pointer on parsed subquery structure

  RETURN VALUE
    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
6651
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
unknown's avatar
unknown committed
6652
    return new Item_in_subselect(left_expr, select_lex);
unknown's avatar
unknown committed
6653 6654

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

  Item_allany_subselect *it=
6658
    new Item_allany_subselect(left_expr, cmp, select_lex, all);
unknown's avatar
unknown committed
6659
  if (all)
6660
    return it->upper_item= new Item_func_not_all(it);	/* ALL */
unknown's avatar
unknown committed
6661

6662
  return it->upper_item= new Item_func_nop_all(it);      /* ANY/SOME */
unknown's avatar
unknown committed
6663
}
6664 6665 6666 6667 6668 6669 6670


/*
  Multi update query pre-check

  SYNOPSIS
    multi_update_precheck()
unknown's avatar
unknown committed
6671
    thd		Thread handler
unknown's avatar
VIEW  
unknown committed
6672
    tables	Global/local table list (have to be the same)
6673

unknown's avatar
unknown committed
6674
  RETURN VALUE
unknown's avatar
unknown committed
6675 6676
    FALSE OK
    TRUE  Error
6677
*/
unknown's avatar
unknown committed
6678

unknown's avatar
unknown committed
6679
bool multi_update_precheck(THD *thd, TABLE_LIST *tables)
6680 6681 6682 6683 6684
{
  const char *msg= 0;
  TABLE_LIST *table;
  LEX *lex= thd->lex;
  SELECT_LEX *select_lex= &lex->select_lex;
unknown's avatar
VIEW  
unknown committed
6685
  DBUG_ENTER("multi_update_precheck");
6686 6687 6688

  if (select_lex->item_list.elements != lex->value_list.elements)
  {
6689
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
6690
    DBUG_RETURN(TRUE);
6691 6692 6693 6694 6695
  }
  /*
    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
6696
  for (table= tables; table; table= table->next_local)
6697
  {
6698 6699 6700
    if (table->derived)
      table->grant.privilege= SELECT_ACL;
    else if ((check_access(thd, UPDATE_ACL, table->db,
6701 6702
                           &table->grant.privilege, 0, 1,
                           test(table->schema_table)) ||
6703
              check_grant(thd, UPDATE_ACL, table, 0, 1, 1)) &&
unknown's avatar
unknown committed
6704
             (check_access(thd, SELECT_ACL, table->db,
6705 6706
                           &table->grant.privilege, 0, 0,
                           test(table->schema_table)) ||
6707
              check_grant(thd, SELECT_ACL, table, 0, 1, 0)))
unknown's avatar
unknown committed
6708
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
6709

unknown's avatar
VIEW  
unknown committed
6710
    table->table_in_first_from_clause= 1;
6711
  }
unknown's avatar
unknown committed
6712 6713 6714
  /*
    Is there tables of subqueries?
  */
6715
  if (&lex->select_lex != lex->all_selects_list)
6716
  {
6717
    DBUG_PRINT("info",("Checking sub query list"));
unknown's avatar
VIEW  
unknown committed
6718
    for (table= tables; table; table= table->next_global)
6719
    {
6720
      if (!table->table_in_first_from_clause)
6721 6722
      {
	if (check_access(thd, SELECT_ACL, table->db,
6723 6724
			 &table->grant.privilege, 0, 0,
                         test(table->schema_table)) ||
6725
	    check_grant(thd, SELECT_ACL, table, 0, 1, 0))
unknown's avatar
unknown committed
6726
	  DBUG_RETURN(TRUE);
6727 6728 6729 6730 6731 6732
      }
    }
  }

  if (select_lex->order_list.elements)
    msg= "ORDER BY";
6733
  else if (select_lex->select_limit)
6734 6735 6736 6737
    msg= "LIMIT";
  if (msg)
  {
    my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
unknown's avatar
unknown committed
6738
    DBUG_RETURN(TRUE);
6739
  }
unknown's avatar
unknown committed
6740
  DBUG_RETURN(FALSE);
6741 6742 6743 6744 6745 6746 6747
}

/*
  Multi delete query pre-check

  SYNOPSIS
    multi_delete_precheck()
unknown's avatar
unknown committed
6748
    thd			Thread handler
unknown's avatar
VIEW  
unknown committed
6749
    tables		Global/local table list
6750

unknown's avatar
unknown committed
6751
  RETURN VALUE
unknown's avatar
unknown committed
6752 6753
    FALSE OK
    TRUE  error
6754
*/
unknown's avatar
unknown committed
6755

6756
bool multi_delete_precheck(THD *thd, TABLE_LIST *tables)
6757 6758 6759
{
  SELECT_LEX *select_lex= &thd->lex->select_lex;
  TABLE_LIST *aux_tables=
unknown's avatar
unknown committed
6760
    (TABLE_LIST *)thd->lex->auxiliary_table_list.first;
6761
  TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
unknown's avatar
VIEW  
unknown committed
6762
  DBUG_ENTER("multi_delete_precheck");
unknown's avatar
unknown committed
6763

6764 6765
  /* sql_yacc guarantees that tables and aux_tables are not zero */
  DBUG_ASSERT(aux_tables != 0);
unknown's avatar
unknown committed
6766
  if (check_table_access(thd, SELECT_ACL, tables, 0))
6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777
    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;
  if (check_table_access(thd, DELETE_ACL, aux_tables, 0))
  {
    thd->lex->query_tables_own_last= save_query_tables_own_last;
unknown's avatar
unknown committed
6778
    DBUG_RETURN(TRUE);
6779 6780 6781
  }
  thd->lex->query_tables_own_last= save_query_tables_own_last;

6782 6783
  if ((thd->options & OPTION_SAFE_UPDATES) && !select_lex->where)
  {
unknown's avatar
unknown committed
6784 6785
    my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
               ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
unknown's avatar
unknown committed
6786
    DBUG_RETURN(TRUE);
6787
  }
6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812
  DBUG_RETURN(FALSE);
}


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

  SYNOPSIS
    multi_delete_set_locks_and_link_aux_tables()
      lex - pointer to LEX representing multi-delete

  RETURN VALUE
    FALSE - success
    TRUE  - error
*/

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
6813
  for (target_tbl= (TABLE_LIST *)lex->auxiliary_table_list.first;
6814
       target_tbl; target_tbl= target_tbl->next_local)
6815
  {
6816
    lex->table_count++;
6817 6818
    /* All tables in aux_tables must be found in FROM PART */
    TABLE_LIST *walk;
unknown's avatar
VIEW  
unknown committed
6819
    for (walk= tables; walk; walk= walk->next_local)
6820
    {
unknown's avatar
unknown committed
6821 6822 6823
      if (!my_strcasecmp(table_alias_charset,
			 target_tbl->alias, walk->alias) &&
	  !strcmp(walk->db, target_tbl->db))
6824 6825 6826 6827
	break;
    }
    if (!walk)
    {
6828
      my_error(ER_UNKNOWN_TABLE, MYF(0),
6829
               target_tbl->table_name, "MULTI DELETE");
unknown's avatar
unknown committed
6830
      DBUG_RETURN(TRUE);
6831
    }
unknown's avatar
unknown committed
6832 6833 6834 6835 6836
    if (!walk->derived)
    {
      target_tbl->table_name= walk->table_name;
      target_tbl->table_name_length= walk->table_name_length;
    }
unknown's avatar
unknown committed
6837
    walk->updating= target_tbl->updating;
unknown's avatar
unknown committed
6838
    walk->lock_type= target_tbl->lock_type;
unknown's avatar
VIEW  
unknown committed
6839
    target_tbl->correspondent_table= walk;	// Remember corresponding table
6840
  }
unknown's avatar
unknown committed
6841
  DBUG_RETURN(FALSE);
6842 6843 6844
}


unknown's avatar
unknown committed
6845 6846 6847 6848 6849
/*
  simple UPDATE query pre-check

  SYNOPSIS
    update_precheck()
unknown's avatar
unknown committed
6850 6851
    thd		Thread handler
    tables	Global table list
unknown's avatar
unknown committed
6852 6853

  RETURN VALUE
unknown's avatar
unknown committed
6854 6855
    FALSE OK
    TRUE  Error
unknown's avatar
unknown committed
6856
*/
unknown's avatar
unknown committed
6857

unknown's avatar
unknown committed
6858
bool update_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
6859 6860 6861 6862
{
  DBUG_ENTER("update_precheck");
  if (thd->lex->select_lex.item_list.elements != thd->lex->value_list.elements)
  {
unknown's avatar
unknown committed
6863
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
6864
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
6865
  }
unknown's avatar
unknown committed
6866
  DBUG_RETURN(check_one_table_access(thd, UPDATE_ACL, tables));
unknown's avatar
unknown committed
6867 6868 6869 6870 6871 6872 6873 6874
}


/*
  simple DELETE query pre-check

  SYNOPSIS
    delete_precheck()
unknown's avatar
unknown committed
6875 6876
    thd		Thread handler
    tables	Global table list
unknown's avatar
unknown committed
6877 6878

  RETURN VALUE
unknown's avatar
unknown committed
6879 6880
    FALSE  OK
    TRUE   error
unknown's avatar
unknown committed
6881
*/
unknown's avatar
unknown committed
6882

unknown's avatar
unknown committed
6883
bool delete_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
6884 6885 6886
{
  DBUG_ENTER("delete_precheck");
  if (check_one_table_access(thd, DELETE_ACL, tables))
unknown's avatar
unknown committed
6887
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
6888
  /* Set privilege for the WHERE clause */
unknown's avatar
unknown committed
6889
  tables->grant.want_privilege=(SELECT_ACL & ~tables->grant.privilege);
unknown's avatar
unknown committed
6890
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
6891 6892 6893 6894 6895 6896 6897 6898
}


/*
  simple INSERT query pre-check

  SYNOPSIS
    insert_precheck()
unknown's avatar
unknown committed
6899 6900
    thd		Thread handler
    tables	Global table list
unknown's avatar
unknown committed
6901 6902

  RETURN VALUE
unknown's avatar
unknown committed
6903 6904
    FALSE  OK
    TRUE   error
unknown's avatar
unknown committed
6905
*/
unknown's avatar
unknown committed
6906

unknown's avatar
merge  
unknown committed
6907
bool insert_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
6908 6909 6910 6911
{
  LEX *lex= thd->lex;
  DBUG_ENTER("insert_precheck");

unknown's avatar
unknown committed
6912 6913 6914 6915
  /*
    Check that we have modify privileges for the first table and
    select privileges for the rest
  */
unknown's avatar
unknown committed
6916 6917 6918
  ulong privilege= (INSERT_ACL |
                    (lex->duplicates == DUP_REPLACE ? DELETE_ACL : 0) |
                    (lex->value_list.elements ? UPDATE_ACL : 0));
unknown's avatar
unknown committed
6919 6920

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

unknown's avatar
unknown committed
6923
  if (lex->update_list.elements != lex->value_list.elements)
unknown's avatar
unknown committed
6924
  {
unknown's avatar
unknown committed
6925
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
6926
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
6927
  }
unknown's avatar
unknown committed
6928
  DBUG_RETURN(FALSE);
6929
}
unknown's avatar
unknown committed
6930 6931


unknown's avatar
unknown committed
6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946
/**
    @brief  Check privileges for SHOW CREATE TABLE statement.

    @param  thd    Thread context
    @param  table  Target table

    @retval TRUE  Failure
    @retval FALSE Success
*/

static bool check_show_create_table_access(THD *thd, TABLE_LIST *table)
{
  return check_access(thd, SELECT_ACL | EXTRA_ACL, table->db,
                      &table->grant.privilege, 0, 0,
                      test(table->schema_table)) ||
6947
         check_grant(thd, SELECT_ACL, table, 2, UINT_MAX, 0);
unknown's avatar
unknown committed
6948 6949 6950
}


unknown's avatar
unknown committed
6951 6952 6953 6954 6955
/*
  CREATE TABLE query pre-check

  SYNOPSIS
    create_table_precheck()
unknown's avatar
unknown committed
6956 6957 6958
    thd			Thread handler
    tables		Global table list
    create_table	Table which will be created
unknown's avatar
unknown committed
6959 6960

  RETURN VALUE
unknown's avatar
unknown committed
6961 6962
    FALSE   OK
    TRUE   Error
unknown's avatar
unknown committed
6963
*/
unknown's avatar
unknown committed
6964

unknown's avatar
unknown committed
6965 6966
bool create_table_precheck(THD *thd, TABLE_LIST *tables,
                           TABLE_LIST *create_table)
unknown's avatar
unknown committed
6967 6968
{
  LEX *lex= thd->lex;
6969 6970
  SELECT_LEX *select_lex= &lex->select_lex;
  ulong want_priv;
unknown's avatar
merge  
unknown committed
6971
  bool error= TRUE;                                 // Error message is given
unknown's avatar
unknown committed
6972
  DBUG_ENTER("create_table_precheck");
6973 6974 6975

  want_priv= ((lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) ?
              CREATE_TMP_ACL : CREATE_ACL);
unknown's avatar
unknown committed
6976
  if (check_access(thd, want_priv, create_table->db,
6977 6978
		   &create_table->grant.privilege, 0, 0,
                   test(create_table->schema_table)) ||
unknown's avatar
unknown committed
6979 6980 6981
      check_merge_table_access(thd, create_table->db,
			       (TABLE_LIST *)
			       lex->create_info.merge_list.first))
6982
    goto err;
6983
  if (want_priv != CREATE_TMP_ACL &&
6984
      check_grant(thd, want_priv, create_table, 0, 1, 0))
6985 6986 6987 6988 6989 6990
    goto err;

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

6991 6992
#ifdef NOT_NECESSARY_TO_CHECK_CREATE_TABLE_EXIST_WHEN_PREPARING_STATEMENT
    /* This code throws an ill error for CREATE TABLE t1 SELECT * FROM t1 */
6993
    /*
6994
      Only do the check for PS, because we on execute we have to check that
unknown's avatar
unknown committed
6995 6996
      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).
6997
    */
unknown's avatar
unknown committed
6998
    if (thd->stmt_arena->is_stmt_prepare_or_first_sp_execute())
6999
    {
unknown's avatar
unknown committed
7000 7001 7002 7003
      /*
        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
7004
          find_table_in_global_list(tables, create_table->db,
7005
                                    create_table->table_name))
unknown's avatar
unknown committed
7006
      {
7007
	error= FALSE;
unknown's avatar
unknown committed
7008 7009 7010
        goto err;
      }
    }
7011
#endif
7012 7013 7014
    if (tables && check_table_access(thd, SELECT_ACL, tables,0))
      goto err;
  }
unknown's avatar
unknown committed
7015 7016 7017 7018 7019
  else if (lex->create_info.options & HA_LEX_CREATE_TABLE_LIKE)
  {
    if (check_show_create_table_access(thd, tables))
      goto err;
  }
unknown's avatar
merge  
unknown committed
7020
  error= FALSE;
7021 7022 7023

err:
  DBUG_RETURN(error);
unknown's avatar
unknown committed
7024
}
unknown's avatar
unknown committed
7025 7026 7027 7028 7029 7030 7031


/*
  negate given expression

  SYNOPSIS
    negate_expression()
7032
    thd  thread handler
unknown's avatar
unknown committed
7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060
    expr expression for negation

  RETURN
    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);
}
7061

7062 7063
/*
  Set the specified definer to the default value, which is the current user in
7064
  the thread.
7065 7066 7067 7068 7069 7070 7071
 
  SYNOPSIS
    get_default_definer()
    thd       [in] thread handler
    definer   [out] definer
*/
 
7072
void get_default_definer(THD *thd, LEX_USER *definer)
7073 7074 7075 7076 7077 7078 7079 7080 7081 7082
{
  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);
}

7083

7084
/*
7085
  Create default definer for the specified THD.
7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103

  SYNOPSIS
    create_default_definer()
    thd         [in] thread handler

  RETURN
    On success, return a valid pointer to the created and initialized
    LEX_USER, which contains definer information.
    On error, return 0.
*/

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

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

7104
  get_default_definer(thd, definer);
7105 7106 7107 7108 7109

  return definer;
}


7110
/*
7111
  Create definer with the given user and host names.
7112 7113

  SYNOPSIS
7114 7115 7116 7117
    create_definer()
    thd         [in] thread handler
    user_name   [in] user name
    host_name   [in] host name
7118 7119

  RETURN
7120
    On success, return a valid pointer to the created and initialized
7121
    LEX_USER, which contains definer information.
7122
    On error, return 0.
7123 7124
*/

7125
LEX_USER *create_definer(THD *thd, LEX_STRING *user_name, LEX_STRING *host_name)
7126
{
7127 7128 7129 7130
  LEX_USER *definer;

  /* Create and initialize. */

unknown's avatar
unknown committed
7131
  if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER))))
7132 7133 7134 7135 7136 7137
    return 0;

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

  return definer;
7138
}
7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157


/*
  Retuns information about user or current user.

  SYNOPSIS
    get_current_user()
    thd         [in] thread handler
    user        [in] user

  RETURN
    On success, return a valid pointer to initialized
    LEX_USER, which contains user information.
    On error, return 0.
*/

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

7160 7161
  return user;
}
7162 7163 7164


/*
7165
  Check that byte length of a string does not exceed some limit.
7166 7167

  SYNOPSIS
7168 7169 7170 7171
  check_string_byte_length()
      str              string to be checked
      err_msg          error message to be displayed if the string is too long
      max_byte_length  max length in bytes
7172 7173 7174 7175

  RETURN
    FALSE   the passed string is not longer than max_length
    TRUE    the passed string is longer than max_length
7176 7177 7178

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

7181 7182
bool check_string_byte_length(LEX_STRING *str, const char *err_msg,
                              uint max_byte_length)
7183
{
7184
  if (str->length <= max_byte_length)
unknown's avatar
unknown committed
7185
    return FALSE;
7186

7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218
  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
7219

7220 7221
  if (!no_error)
    my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_char_length);
7222 7223
  return TRUE;
}
7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234


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.
  @param lip Lexer context.
unknown's avatar
unknown committed
7235
  @param creation_ctx Object creation context.
7236 7237 7238 7239 7240 7241

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

unknown's avatar
unknown committed
7242 7243 7244
bool parse_sql(THD *thd,
               Lex_input_stream *lip,
               Object_creation_ctx *creation_ctx)
7245 7246 7247
{
  DBUG_ASSERT(thd->m_lip == NULL);

unknown's avatar
unknown committed
7248 7249 7250 7251 7252 7253 7254 7255 7256
  /* Backup creation context. */

  Object_creation_ctx *backup_ctx= NULL;

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

  /* Set Lex_input_stream. */

7257 7258
  thd->m_lip= lip;

unknown's avatar
unknown committed
7259 7260 7261 7262 7263
  /* Parse the query. */

  bool err_status= MYSQLparse(thd) != 0 || thd->is_fatal_error;

  /* Reset Lex_input_stream. */
7264 7265 7266

  thd->m_lip= NULL;

unknown's avatar
unknown committed
7267 7268 7269 7270 7271 7272 7273
  /* Restore creation context. */

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

  /* That's it. */

7274 7275
  return err_status;
}
7276 7277 7278 7279

/**
  @} (end of group Runtime_Environment)
*/