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

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

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

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

16
#define MYSQL_LEX 1
unknown's avatar
unknown committed
17
#include "mysql_priv.h"
18
#include "sql_repl.h"
unknown's avatar
unknown committed
19
#include "rpl_filter.h"
20
#include "repl_failsafe.h"
unknown's avatar
unknown committed
21 22 23 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
const char *xa_state_names[]={
86
  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED", "ROLLBACK ONLY"
unknown's avatar
unknown committed
87 88
};

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
/**
  Mark a XA transaction as rollback-only if the RM unilaterally
  rolled back the transaction branch.

  @note If a rollback was requested by the RM, this function sets
        the appropriate rollback error code and transits the state
        to XA_ROLLBACK_ONLY.

  @return TRUE if transaction was rolled back or if the transaction
          state is XA_ROLLBACK_ONLY. FALSE otherwise.
*/
static bool xa_trans_rolled_back(XID_STATE *xid_state)
{
  if (xid_state->rm_error)
  {
    switch (xid_state->rm_error) {
    case ER_LOCK_WAIT_TIMEOUT:
      my_error(ER_XA_RBTIMEOUT, MYF(0));
      break;
    case ER_LOCK_DEADLOCK:
      my_error(ER_XA_RBDEADLOCK, MYF(0));
      break;
    default:
      my_error(ER_XA_RBROLLBACK, MYF(0));
    }
    xid_state->xa_state= XA_ROLLBACK_ONLY;
  }

  return (xid_state->xa_state == XA_ROLLBACK_ONLY);
}

/**
  Rollback work done on behalf of at ransaction branch.
*/
static bool xa_trans_rollback(THD *thd)
{
  bool status= test(ha_rollback(thd));

  thd->options&= ~(ulong) OPTION_BEGIN;
  thd->transaction.all.modified_non_trans_table= FALSE;
  thd->server_status&= ~SERVER_STATUS_IN_TRANS;
  xid_cache_delete(&thd->transaction.xid_state);
  thd->transaction.xid_state.xa_state= XA_NOTR;
  thd->transaction.xid_state.rm_error= 0;

  return status;
}

unknown's avatar
unknown committed
137 138 139 140 141
static void unlock_locked_tables(THD *thd)
{
  if (thd->locked_tables)
  {
    thd->lock=thd->locked_tables;
142
    thd->locked_tables=0;			// Will be automatically closed
unknown's avatar
unknown committed
143 144 145 146
    close_thread_tables(thd);			// Free tables
  }
}

147

148
bool end_active_trans(THD *thd)
149
{
unknown's avatar
unknown committed
150
  int error=0;
151
  DBUG_ENTER("end_active_trans");
152
  if (unlikely(thd->in_sub_stmt))
153 154 155 156
  {
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
    DBUG_RETURN(1);
  }
157 158 159 160 161 162
  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
163
  if (thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN |
unknown's avatar
unknown committed
164
		      OPTION_TABLE_LOCK))
165
  {
166
    DBUG_PRINT("info",("options: 0x%llx", thd->options));
167 168 169
    /* Safety if one did "drop table" on locked tables */
    if (!thd->locked_tables)
      thd->options&= ~OPTION_TABLE_LOCK;
170
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
171
    if (ha_commit(thd))
unknown's avatar
unknown committed
172
      error=1;
173
  }
174
  thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
unknown's avatar
unknown committed
175
  thd->transaction.all.modified_non_trans_table= FALSE;
176
  DBUG_RETURN(error);
177 178
}

179

unknown's avatar
unknown committed
180
bool begin_trans(THD *thd)
unknown's avatar
unknown committed
181 182
{
  int error=0;
183
  if (unlikely(thd->in_sub_stmt))
184 185 186 187
  {
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
    return 1;
  }
unknown's avatar
unknown committed
188 189 190 191 192 193 194 195 196 197
  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
  {
198
    thd->options|= OPTION_BEGIN;
unknown's avatar
unknown committed
199 200 201 202
    thd->server_status|= SERVER_STATUS_IN_TRANS;
  }
  return error;
}
203

unknown's avatar
unknown committed
204
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
205 206
/**
  Returns true if all tables should be ignored.
207
*/
208 209
inline bool all_tables_not_ok(THD *thd, TABLE_LIST *tables)
{
unknown's avatar
unknown committed
210 211
  return rpl_filter->is_on() && tables && !thd->spcont &&
         !rpl_filter->tables_ok(thd->db, tables);
212
}
unknown's avatar
unknown committed
213
#endif
214 215


216 217 218 219 220 221 222 223 224 225 226 227
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;
}

228

unknown's avatar
unknown committed
229 230 231 232
/**
  Mark all commands that somehow changes a table.

  This is used to check number of updates / hour.
unknown's avatar
unknown committed
233 234 235

  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
236

237
  See COMMAND_FLAG_xxx for different type of commands
unknown's avatar
unknown committed
238 239
     2  - query that returns meaningful ROW_COUNT() -
          a number of modified rows
240 241
*/

242
uint sql_command_flags[SQLCOM_END+1];
243 244 245

void init_update_queries(void)
{
246
  bzero((uchar*) &sql_command_flags, sizeof(sql_command_flags));
247

248
  sql_command_flags[SQLCOM_CREATE_TABLE]=   CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE;
249
  sql_command_flags[SQLCOM_CREATE_INDEX]=   CF_CHANGES_DATA;
250 251
  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;
252
  sql_command_flags[SQLCOM_DROP_TABLE]=     CF_CHANGES_DATA;
253
  sql_command_flags[SQLCOM_LOAD]=           CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE;
254 255 256 257 258 259
  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;
260
  sql_command_flags[SQLCOM_CREATE_VIEW]=    CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE;
261 262 263
  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;
264
  sql_command_flags[SQLCOM_DROP_EVENT]=     CF_CHANGES_DATA;
265

unknown's avatar
unknown committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
  sql_command_flags[SQLCOM_UPDATE]=	    CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
                                            CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_UPDATE_MULTI]=   CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
                                            CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_INSERT]=	    CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
                                            CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_INSERT_SELECT]=  CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
                                            CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_DELETE]=         CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
                                            CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_DELETE_MULTI]=   CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
                                            CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_REPLACE]=        CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
                                            CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT |
                                            CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SELECT]=         CF_REEXECUTION_FRAGILE;
283 284 285 286 287 288 289 290 291
  sql_command_flags[SQLCOM_SET_OPTION]=     CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_DO]=             CF_REEXECUTION_FRAGILE;

  sql_command_flags[SQLCOM_SHOW_STATUS_PROC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_STATUS]=      CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_DATABASES]=   CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_TRIGGERS]=    CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_EVENTS]=      CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_OPEN_TABLES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
292
  sql_command_flags[SQLCOM_SHOW_PLUGINS]=     CF_STATUS_COMMAND;
293 294 295 296 297
  sql_command_flags[SQLCOM_SHOW_FIELDS]=      CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_KEYS]=        CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_VARIABLES]=   CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_CHARSETS]=    CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_COLLATIONS]=  CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
  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;
321
  sql_command_flags[SQLCOM_SHOW_STATUS_FUNC]=  CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
322 323 324
  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;
325 326
  sql_command_flags[SQLCOM_SHOW_PROFILES]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PROFILE]= CF_STATUS_COMMAND;
327 328

   sql_command_flags[SQLCOM_SHOW_TABLES]=       (CF_STATUS_COMMAND |
329 330
                                                 CF_SHOW_TABLE_COMMAND |
                                                 CF_REEXECUTION_FRAGILE);
331
  sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND |
332 333
                                                CF_SHOW_TABLE_COMMAND |
                                                CF_REEXECUTION_FRAGILE);
334 335 336 337 338 339 340

  /*
    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.
  */
341
  sql_command_flags[SQLCOM_CALL]= 		CF_HAS_ROW_COUNT | CF_REEXECUTION_FRAGILE;
342
  sql_command_flags[SQLCOM_EXECUTE]= 		CF_HAS_ROW_COUNT;
343 344 345 346 347 348 349 350

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

353

unknown's avatar
unknown committed
354 355
bool is_update_query(enum enum_sql_command command)
{
unknown's avatar
unknown committed
356
  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
357
  return (sql_command_flags[command] & CF_CHANGES_DATA) != 0;
unknown's avatar
unknown committed
358
}
359

360 361 362 363 364 365 366 367 368 369
/**
  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;
}
370

371 372
void execute_init_command(THD *thd, sys_var_str *init_command_var,
			  rw_lock_t *var_mutex)
unknown's avatar
unknown committed
373 374 375 376
{
  Vio* save_vio;
  ulong save_client_capabilities;

377 378 379 380 381 382
#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
  thd->profiling.start_new_query();
  thd->profiling.set_query_source(init_command_var->value,
                                  init_command_var->value_length);
#endif

383
  thd_proc_info(thd, "Execution of init_command");
384 385 386 387 388 389
  /*
    We need to lock init_command_var because
    during execution of init_command_var query
    values of init_command_var can't be changed
  */
  rw_rdlock(var_mutex);
unknown's avatar
unknown committed
390 391
  save_client_capabilities= thd->client_capabilities;
  thd->client_capabilities|= CLIENT_MULTI_QUERIES;
392 393 394 395
  /*
    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
396 397
  save_vio= thd->net.vio;
  thd->net.vio= 0;
398 399 400
  dispatch_command(COM_QUERY, thd,
                   init_command_var->value,
                   init_command_var->value_length);
401
  rw_unlock(var_mutex);
unknown's avatar
unknown committed
402 403
  thd->client_capabilities= save_client_capabilities;
  thd->net.vio= save_vio;
404 405 406 407

#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
  thd->profiling.finish_current_query();
#endif
unknown's avatar
unknown committed
408 409 410
}


411
static void handle_bootstrap_impl(THD *thd)
unknown's avatar
unknown committed
412
{
413 414
  FILE *file=bootstrap_file;
  char *buff;
415
  const char* found_semicolon= NULL;
unknown's avatar
unknown committed
416

417 418
  DBUG_ENTER("handle_bootstrap");

unknown's avatar
unknown committed
419
#ifndef EMBEDDED_LIBRARY
420 421
  pthread_detach_this_thread();
  thd->thread_stack= (char*) &thd;
unknown's avatar
unknown committed
422
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
423

424
  if (thd->variables.max_join_size == HA_POS_ERROR)
unknown's avatar
unknown committed
425 426
    thd->options |= OPTION_BIG_SELECTS;

427
  thd_proc_info(thd, 0);
unknown's avatar
unknown committed
428
  thd->version=refresh_version;
429 430
  thd->security_ctx->priv_user=
    thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME));
unknown's avatar
unknown committed
431
  thd->security_ctx->priv_host[0]=0;
432 433 434 435 436 437
  /*
    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
438

439
  buff= (char*) thd->net.buff;
440
  thd->init_for_queries();
unknown's avatar
unknown committed
441 442
  while (fgets(buff, thd->net.max_packet, file))
  {
443
    char *query, *res;
444 445 446 447 448 449 450 451 452 453 454
    /* 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))
      {
455 456
        net_end_statement(thd);
        bootstrap_error= 1;
457 458 459
        break;
      }
      buff= (char*) thd->net.buff;
Staale Smedseng's avatar
Staale Smedseng committed
460
      res= fgets(buff + length, thd->net.max_packet - length, file);
461 462 463
      length+= (ulong) strlen(buff + length);
      /* purecov: end */
    }
464
    if (bootstrap_error)
465
      break;                                    /* purecov: inspected */
unknown's avatar
unknown committed
466

unknown's avatar
unknown committed
467
    while (length && (my_isspace(thd->charset(), buff[length-1]) ||
468
                      buff[length-1] == ';'))
unknown's avatar
unknown committed
469 470
      length--;
    buff[length]=0;
unknown's avatar
unknown committed
471 472 473 474 475

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

Gleb Shchepa's avatar
Gleb Shchepa committed
476 477 478
    query= (char *) thd->memdup_w_gap(buff, length + 1,
                                      thd->db_length + 1 +
                                      QUERY_CACHE_FLAGS_SIZE);
479
    thd->set_query(query, length);
480
    DBUG_PRINT("query",("%-.4096s",thd->query));
481
#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
482
    thd->profiling.start_new_query();
483 484 485
    thd->profiling.set_query_source(thd->query, length);
#endif

486 487 488 489
    /*
      We don't need to obtain LOCK_thread_count here because in bootstrap
      mode we have only one thread.
    */
490
    thd->query_id=next_query_id();
491
    thd->set_time();
492
    mysql_parse(thd, thd->query, length, & found_semicolon);
unknown's avatar
unknown committed
493
    close_thread_tables(thd);			// Free tables
494

495 496
    bootstrap_error= thd->is_error();
    net_end_statement(thd);
497

498 499 500 501
#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
    thd->profiling.finish_current_query();
#endif

502
    if (bootstrap_error)
503 504
      break;

unknown's avatar
unknown committed
505
    free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
506
#ifdef USING_TRANSACTIONS
507
    free_root(&thd->transaction.mem_root,MYF(MY_KEEP_PREALLOC));
508
#endif
unknown's avatar
unknown committed
509
  }
510

511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
  DBUG_VOID_RETURN;
}


/**
  Execute commands from bootstrap_file.

  Used when creating the initial grant tables.
*/

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

  /* The following must be called before DBUG_ENTER */
  thd->thread_stack= (char*) &thd;
  if (my_thread_init() || thd->store_globals())
  {
#ifndef EMBEDDED_LIBRARY
    close_connection(thd, ER_OUT_OF_RESOURCES, 1);
#endif
    thd->fatal_error();
    goto end;
  }

  handle_bootstrap_impl(thd);

538
end:
539 540 541 542
  net_end(&thd->net);
  thd->cleanup();
  delete thd;

unknown's avatar
unknown committed
543
#ifndef EMBEDDED_LIBRARY
544 545
  (void) pthread_mutex_lock(&LOCK_thread_count);
  thread_count--;
546
  in_bootstrap= FALSE;
547
  (void) pthread_cond_broadcast(&COND_thread_count);
548
  (void) pthread_mutex_unlock(&LOCK_thread_count);
549 550
  my_thread_end();
  pthread_exit(0);
unknown's avatar
unknown committed
551
#endif
552 553

  return 0;
unknown's avatar
unknown committed
554 555 556
}


557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
/**
  @brief Check access privs for a MERGE table and fix children lock types.

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

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

  @detail
    This function is used for write access to MERGE tables only
    (CREATE TABLE, ALTER TABLE ... UNION=(...)). Set TL_WRITE for
    every child. Set 'db' for every child if not present.
*/
unknown's avatar
unknown committed
574
#ifndef NO_EMBEDDED_ACCESS_CHECKS
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
static bool check_merge_table_access(THD *thd, char *db,
                                     TABLE_LIST *table_list)
{
  int error= 0;

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

    for (tlist= table_list; tlist; tlist= tlist->next_local)
    {
      if (!tlist->db || !tlist->db[0])
        tlist->db= db; /* purecov: inspected */
    }
    error= check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL,
591
                              table_list, UINT_MAX, FALSE);
592 593 594
  }
  return error;
}
unknown's avatar
unknown committed
595
#endif
596

unknown's avatar
unknown committed
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
/* 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() */
612 613 614

void cleanup_items(Item *item)
{
unknown's avatar
unknown committed
615
  DBUG_ENTER("cleanup_items");  
616 617
  for (; item ; item=item->next)
    item->cleanup();
unknown's avatar
unknown committed
618
  DBUG_VOID_RETURN;
619 620
}

unknown's avatar
unknown committed
621 622
/**
  Handle COM_TABLE_DUMP command.
unknown's avatar
unknown committed
623

unknown's avatar
unknown committed
624 625 626 627
  @param thd           thread handle
  @param db            database name or an empty string. If empty,
                       the current database of the connection is used
  @param tbl_name      name of the table to dump
unknown's avatar
unknown committed
628

unknown's avatar
unknown committed
629
  @note
unknown's avatar
unknown committed
630 631
    This function is written to handle one specific command only.

unknown's avatar
unknown committed
632
  @retval
unknown's avatar
unknown committed
633
    0               success
unknown's avatar
unknown committed
634
  @retval
unknown's avatar
unknown committed
635 636 637 638
    1               error, the error message is set in THD
*/

static
639
int mysql_table_dump(THD *thd, LEX_STRING *db, char *tbl_name)
unknown's avatar
unknown committed
640 641 642 643 644
{
  TABLE* table;
  TABLE_LIST* table_list;
  int error = 0;
  DBUG_ENTER("mysql_table_dump");
645 646 647 648 649
  if (db->length == 0)
  {
    db->str= thd->db;            /* purecov: inspected */
    db->length= thd->db_length;  /* purecov: inspected */
  }
650
  if (!(table_list = (TABLE_LIST*) thd->calloc(sizeof(TABLE_LIST))))
unknown's avatar
unknown committed
651
    DBUG_RETURN(1); // out of memory
652
  table_list->db= db->str;
653
  table_list->table_name= table_list->alias= tbl_name;
unknown's avatar
VIEW  
unknown committed
654 655
  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
656

657
  if (check_db_name(db))
658
  {
659 660
    /* purecov: begin inspected */
    my_error(ER_WRONG_DB_NAME ,MYF(0), db->str ? db->str : "NULL");
661
    goto err;
662
    /* purecov: end */
663
  }
664
  if (lower_case_table_names)
665
    my_casedn_str(files_charset_info, tbl_name);
666

667
  if (!(table=open_ltable(thd, table_list, TL_READ_NO_INSERT, 0)))
668 669
    DBUG_RETURN(1);

unknown's avatar
unknown committed
670
  if (check_one_table_access(thd, SELECT_ACL, table_list))
unknown's avatar
unknown committed
671 672
    goto err;
  thd->free_list = 0;
673
  thd->set_query(tbl_name, (uint) strlen(tbl_name));
unknown's avatar
unknown committed
674
  if ((error = mysqld_dump_create_info(thd, table_list, -1)))
675
  {
676
    my_error(ER_GET_ERRNO, MYF(0), my_errno);
677 678
    goto err;
  }
unknown's avatar
unknown committed
679
  net_flush(&thd->net);
unknown's avatar
unknown committed
680
  if ((error= table->file->dump(thd,-1)))
681
    my_error(ER_GET_ERRNO, MYF(0), error);
unknown's avatar
unknown committed
682

unknown's avatar
unknown committed
683
err:
unknown's avatar
unknown committed
684
  DBUG_RETURN(error);
unknown's avatar
unknown committed
685 686
}

unknown's avatar
unknown committed
687 688
/**
  Ends the current transaction and (maybe) begin the next.
unknown's avatar
unknown committed
689

unknown's avatar
unknown committed
690 691
  @param thd            Current thread
  @param completion     Completion type
unknown's avatar
unknown committed
692

unknown's avatar
unknown committed
693 694
  @retval
    0   OK
unknown's avatar
unknown committed
695 696
*/

697
int end_trans(THD *thd, enum enum_mysql_completiontype completion)
unknown's avatar
unknown committed
698 699 700
{
  bool do_release= 0;
  int res= 0;
701
  DBUG_ENTER("end_trans");
unknown's avatar
unknown committed
702

703
  if (unlikely(thd->in_sub_stmt))
704 705 706 707
  {
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
    DBUG_RETURN(1);
  }
708 709 710 711 712 713
  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
714 715 716 717 718 719 720 721
  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;
722
    res= ha_commit(thd);
723
    thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
unknown's avatar
unknown committed
724
    thd->transaction.all.modified_non_trans_table= FALSE;
unknown's avatar
unknown committed
725 726
    break;
  case COMMIT_RELEASE:
unknown's avatar
unknown committed
727
    do_release= 1; /* fall through */
unknown's avatar
unknown committed
728 729 730 731 732 733
  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
734
    do_release= 1; /* fall through */
unknown's avatar
unknown committed
735 736 737 738
  case ROLLBACK:
  case ROLLBACK_AND_CHAIN:
  {
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
unknown's avatar
unknown committed
739
    if (ha_rollback(thd))
unknown's avatar
unknown committed
740
      res= -1;
741
    thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
unknown's avatar
unknown committed
742
    thd->transaction.all.modified_non_trans_table= FALSE;
unknown's avatar
unknown committed
743 744 745 746 747 748 749 750 751
    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
752

unknown's avatar
unknown committed
753 754 755
  if (res < 0)
    my_error(thd->killed_errno(), MYF(0));
  else if ((res == 0) && do_release)
unknown's avatar
unknown committed
756 757
    thd->killed= THD::KILL_CONNECTION;

unknown's avatar
unknown committed
758 759
  DBUG_RETURN(res);
}
unknown's avatar
unknown committed
760

761
#ifndef EMBEDDED_LIBRARY
762

unknown's avatar
unknown committed
763
/**
unknown's avatar
unknown committed
764
  Read one command from connection and execute it (query or simple command).
765
  This function is called in loop from thread function.
766 767 768

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

unknown's avatar
unknown committed
769
  @retval
770
    0  success
unknown's avatar
unknown committed
771
  @retval
772 773 774
    1  request of thread shutdown (see dispatch_command() description)
*/

unknown's avatar
unknown committed
775 776
bool do_command(THD *thd)
{
777
  bool return_value;
unknown's avatar
unknown committed
778
  char *packet= 0;
unknown's avatar
unknown committed
779
  ulong packet_length;
unknown's avatar
unknown committed
780
  NET *net= &thd->net;
unknown's avatar
unknown committed
781 782 783
  enum enum_server_command command;
  DBUG_ENTER("do_command");

unknown's avatar
unknown committed
784 785 786 787
  /*
    indicator of uninitialized lex => normal flow of errors handling
    (see my_message_sql)
  */
788
  thd->lex->current_select= 0;
unknown's avatar
unknown committed
789

unknown's avatar
unknown committed
790 791 792 793 794 795
  /*
    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
  */
796
  my_net_set_read_timeout(net, thd->variables.net_wait_timeout);
unknown's avatar
unknown committed
797

798 799 800 801
  /*
    XXX: this code is here only to clear possible errors of init_connect. 
    Consider moving to init_connect() instead.
  */
unknown's avatar
unknown committed
802
  thd->clear_error();				// Clear error message
803
  thd->main_da.reset_diagnostics_area();
unknown's avatar
unknown committed
804 805

  net_new_transaction(net);
806 807 808 809 810 811

  packet_length= my_net_read(net);
#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
  thd->profiling.start_new_query();
#endif
  if (packet_length == packet_error)
unknown's avatar
unknown committed
812
  {
813 814 815
    DBUG_PRINT("info",("Got error %d reading command from socket %s",
		       net->error,
		       vio_description(net->vio)));
816

817
    /* Check if we can continue without closing the connection */
818

819 820 821 822
    /* The error must be set. */
    DBUG_ASSERT(thd->is_error());
    net_end_statement(thd);

823
    if (net->error != 3)
824
    {
825
      return_value= TRUE;                       // We have to close it.
826 827
      goto out;
    }
828

829
    net->error= 0;
830 831
    return_value= FALSE;
    goto out;
unknown's avatar
unknown committed
832
  }
833 834 835 836 837 838 839 840 841 842 843

  packet= (char*) net->read_pos;
  /*
    'packet_length' contains length of data, as it was stored in packet
    header. In case of malformed header, my_net_read returns zero.
    If packet_length is not zero, my_net_read ensures that the returned
    number of bytes was actually read from network.
    There is also an extra safety measure in my_net_read:
    it sets packet[packet_length]= 0, but only for non-zero packets.
  */
  if (packet_length == 0)                       /* safety */
unknown's avatar
unknown committed
844
  {
845 846 847
    /* Initialize with COM_SLEEP packet */
    packet[0]= (uchar) COM_SLEEP;
    packet_length= 1;
unknown's avatar
unknown committed
848
  }
849 850 851 852 853 854 855 856 857 858 859
  /* Do not rely on my_net_read, extra safety against programming errors. */
  packet[packet_length]= '\0';                  /* safety */

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

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

  DBUG_PRINT("info",("Command on %s = %d (%s)",
                     vio_description(net->vio), command,
                     command_name[command].str));
unknown's avatar
unknown committed
860 861

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

864
  DBUG_ASSERT(packet_length);
865 866 867 868 869 870 871
  return_value= dispatch_command(command, thd, packet+1, (uint) (packet_length-1));

out:
#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
  thd->profiling.finish_current_query();
#endif
  DBUG_RETURN(return_value);
872
}
873
#endif  /* EMBEDDED_LIBRARY */
874

875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
/**
  @brief Determine if an attempt to update a non-temporary table while the
    read-only option was enabled has been made.

  This is a helper function to mysql_execute_command.

  @note SQLCOM_MULTI_UPDATE is an exception and delt with elsewhere.

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

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

  if (!opt_readonly)
    DBUG_RETURN(FALSE);

  LEX *lex= thd->lex;

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

  if (user_is_super)
    DBUG_RETURN(FALSE);

906
  if (!(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA))
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
    DBUG_RETURN(FALSE);

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

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

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

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


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

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


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

unknown's avatar
unknown committed
943 944
/**
  Perform one connection-level (COM_XXXX) command.
945

unknown's avatar
unknown committed
946 947 948 949 950 951 952 953
  @param command         type of command to perform
  @param thd             connection handle
  @param packet          data for the command, packet is always null-terminated
  @param packet_length   length of packet + 1 (to show that data is
                         null-terminated) except for COM_SLEEP, where it
                         can be zero.

  @todo
954 955 956
    set thd->lex->sql_command to SQLCOM_END here.
  @todo
    The following has to be changed to an 8 byte integer
unknown's avatar
unknown committed
957 958

  @retval
959
    0   ok
unknown's avatar
unknown committed
960
  @retval
961 962 963
    1   request of thread shutdown, i. e. if command is
        COM_QUIT/COM_SHUTDOWN
*/
964 965 966 967
bool dispatch_command(enum enum_server_command command, THD *thd,
		      char* packet, uint packet_length)
{
  NET *net= &thd->net;
968
  bool error= 0;
969
  DBUG_ENTER("dispatch_command");
970
  DBUG_PRINT("info",("packet: '%*.s'; command: %d", packet_length, packet, command));
971

972
  thd->command=command;
unknown's avatar
unknown committed
973
  /*
974 975
    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
976
  */
977
  thd->enable_slow_log= TRUE;
978
  thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
unknown's avatar
unknown committed
979
  thd->set_time();
unknown's avatar
unknown committed
980
  VOID(pthread_mutex_lock(&LOCK_thread_count));
unknown's avatar
unknown committed
981
  thd->query_id= global_query_id;
982 983 984 985 986 987 988 989 990 991

  switch( command ) {
  /* Ignore these statements. */
  case COM_STATISTICS:
  case COM_PING:
    break;
  /* Only increase id on these statements but don't count them. */
  case COM_STMT_PREPARE: 
  case COM_STMT_CLOSE:
  case COM_STMT_RESET:
992
    next_query_id();
993 994 995 996 997 998 999
    break;
  /* Increase id and count all other statements. */
  default:
    statistic_increment(thd->status_var.questions, &LOCK_status);
    next_query_id();
  }

unknown's avatar
unknown committed
1000
  thread_running++;
1001
  /* TODO: set thd->lex->sql_command to SQLCOM_END here */
unknown's avatar
unknown committed
1002
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
unknown's avatar
unknown committed
1003

1004 1005 1006 1007 1008
  /**
    Clear the set of flags that are expected to be cleared at the
    beginning of each command.
  */
  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
1009
  switch (command) {
unknown's avatar
unknown committed
1010
  case COM_INIT_DB:
unknown's avatar
unknown committed
1011 1012
  {
    LEX_STRING tmp;
1013
    status_var_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB]);
unknown's avatar
unknown committed
1014
    thd->convert_string(&tmp, system_charset_info,
1015
			packet, packet_length, thd->charset());
unknown's avatar
unknown committed
1016
    if (!mysql_change_db(thd, &tmp, FALSE))
1017
    {
1018
      general_log_write(thd, command, thd->db, thd->db_length);
1019
      my_ok(thd);
1020
    }
unknown's avatar
unknown committed
1021 1022
    break;
  }
unknown's avatar
unknown committed
1023
#ifdef HAVE_REPLICATION
1024 1025
  case COM_REGISTER_SLAVE:
  {
1026
    if (!register_slave(thd, (uchar*)packet, packet_length))
1027
      my_ok(thd);
1028 1029
    break;
  }
1030
#endif
unknown's avatar
unknown committed
1031
  case COM_TABLE_DUMP:
1032
  {
1033 1034
    char *tbl_name;
    LEX_STRING db;
1035
    /* Safe because there is always a trailing \0 at the end of the packet */
1036
    uint db_len= *(uchar*) packet;
1037
    if (db_len + 1 > packet_length || db_len > NAME_LEN)
unknown's avatar
unknown committed
1038
    {
unknown's avatar
unknown committed
1039
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
unknown's avatar
unknown committed
1040 1041
      break;
    }
1042
    /* Safe because there is always a trailing \0 at the end of the packet */
1043
    uint tbl_len= *(uchar*) (packet + db_len + 1);
1044
    if (db_len + tbl_len + 2 > packet_length || tbl_len > NAME_LEN)
unknown's avatar
unknown committed
1045
    {
unknown's avatar
unknown committed
1046
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
unknown's avatar
unknown committed
1047 1048
      break;
    }
1049

1050
    status_var_increment(thd->status_var.com_other);
1051
    thd->enable_slow_log= opt_log_slow_admin_statements;
1052
    db.str= (char*) thd->alloc(db_len + tbl_len + 2);
1053
    if (!db.str)
1054 1055 1056 1057
    {
      my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
      break;
    }
1058
    db.length= db_len;
1059
    tbl_name= strmake(db.str, packet + 1, db_len)+1;
1060
    strmake(tbl_name, packet + db_len + 2, tbl_len);
1061 1062
    if (mysql_table_dump(thd, &db, tbl_name) == 0)
      thd->main_da.disable_status();
1063 1064
    break;
  }
unknown's avatar
unknown committed
1065 1066
  case COM_CHANGE_USER:
  {
1067
    status_var_increment(thd->status_var.com_other);
1068 1069
    char *user= (char*) packet, *packet_end= packet + packet_length;
    /* Safe because there is always a trailing \0 at the end of the packet */
1070 1071
    char *passwd= strend(user)+1;

unknown's avatar
unknown committed
1072
    thd->change_user();
1073
    thd->clear_error();                         // if errors from rollback
unknown's avatar
unknown committed
1074

1075
    /*
unknown's avatar
unknown committed
1076 1077 1078
      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).
1079 1080 1081

      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
1082
    */
1083
    char db_buff[NAME_LEN+1];                 // buffer to store db in utf8
unknown's avatar
unknown committed
1084
    char *db= passwd;
1085
    char *save_db;
1086 1087 1088 1089 1090 1091 1092 1093 1094
    /*
      If there is no password supplied, the packet must contain '\0',
      in any type of handshake (4.1 or pre-4.1).
     */
    if (passwd >= packet_end)
    {
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
      break;
    }
1095
    uint passwd_len= (thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
1096
                      (uchar)(*passwd++) : strlen(passwd));
1097 1098
    uint dummy_errors, save_db_length, db_length;
    int res;
1099 1100 1101
    Security_context save_security_ctx= *thd->security_ctx;
    USER_CONN *save_user_connect;

unknown's avatar
unknown committed
1102
    db+= passwd_len + 1;
1103 1104 1105 1106 1107
    /*
      Database name is always NUL-terminated, so in case of empty database
      the packet must contain at least the trailing '\0'.
    */
    if (db >= packet_end)
1108
    {
unknown's avatar
unknown committed
1109
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1110 1111
      break;
    }
1112 1113
    db_length= strlen(db);

1114
    char *ptr= db + db_length + 1;
1115 1116
    uint cs_number= 0;

1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
    if (ptr < packet_end)
    {
      if (ptr + 2 > packet_end)
      {
        my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
        break;
      }

      cs_number= uint2korr(ptr);
    }
1127

1128
    /* Convert database name to utf8 */
1129
    db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
1130
                             system_charset_info, db, db_length,
1131
                             thd->charset(), &dummy_errors)]= 0;
1132
    db= db_buff;
unknown's avatar
unknown committed
1133

1134
    /* Save user and privileges */
1135 1136 1137
    save_db_length= thd->db_length;
    save_db= thd->db;
    save_user_connect= thd->user_connect;
1138 1139

    if (!(thd->security_ctx->user= my_strdup(user, MYF(0))))
1140
    {
1141
      thd->security_ctx->user= save_security_ctx.user;
unknown's avatar
unknown committed
1142
      my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
1143 1144
      break;
    }
unknown's avatar
unknown committed
1145

unknown's avatar
unknown committed
1146 1147
    /* Clear variables that are allocated */
    thd->user_connect= 0;
1148
    thd->security_ctx->priv_user= thd->security_ctx->user;
1149
    res= check_user(thd, COM_CHANGE_USER, passwd, passwd_len, db, FALSE);
unknown's avatar
unknown committed
1150

1151 1152
    if (res)
    {
1153 1154
      x_free(thd->security_ctx->user);
      *thd->security_ctx= save_security_ctx;
unknown's avatar
unknown committed
1155
      thd->user_connect= save_user_connect;
1156 1157 1158 1159 1160
      thd->db= save_db;
      thd->db_length= save_db_length;
    }
    else
    {
1161
#ifndef NO_EMBEDDED_ACCESS_CHECKS
1162
      /* we've authenticated new user */
unknown's avatar
unknown committed
1163 1164
      if (save_user_connect)
	decrease_user_connections(save_user_connect);
1165
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
1166 1167
      x_free(save_db);
      x_free(save_security_ctx.user);
1168 1169 1170 1171 1172 1173

      if (cs_number)
      {
        thd_init_client_charset(thd, cs_number);
        thd->update_charset();
      }
1174
    }
unknown's avatar
unknown committed
1175 1176
    break;
  }
1177
  case COM_STMT_EXECUTE:
unknown's avatar
unknown committed
1178
  {
1179
    mysqld_stmt_execute(thd, packet, packet_length);
unknown's avatar
unknown committed
1180 1181
    break;
  }
1182
  case COM_STMT_FETCH:
1183
  {
1184
    mysqld_stmt_fetch(thd, packet, packet_length);
1185 1186
    break;
  }
1187
  case COM_STMT_SEND_LONG_DATA:
unknown's avatar
unknown committed
1188
  {
1189
    mysql_stmt_get_longdata(thd, packet, packet_length);
unknown's avatar
unknown committed
1190 1191
    break;
  }
1192
  case COM_STMT_PREPARE:
unknown's avatar
unknown committed
1193
  {
1194
    mysqld_stmt_prepare(thd, packet, packet_length);
unknown's avatar
unknown committed
1195 1196
    break;
  }
1197
  case COM_STMT_CLOSE:
unknown's avatar
unknown committed
1198
  {
1199
    mysqld_stmt_close(thd, packet);
unknown's avatar
unknown committed
1200 1201
    break;
  }
1202
  case COM_STMT_RESET:
1203
  {
1204
    mysqld_stmt_reset(thd, packet);
1205 1206
    break;
  }
unknown's avatar
unknown committed
1207 1208
  case COM_QUERY:
  {
1209 1210
    if (alloc_query(thd, packet, packet_length))
      break;					// fatal error is set
1211
    char *packet_end= thd->query + thd->query_length;
unknown's avatar
unknown committed
1212
    /* 'b' stands for 'buffer' parameter', special for 'my_snprintf' */
1213
    const char* end_of_stmt= NULL;
1214

1215
    general_log_write(thd, command, thd->query, thd->query_length);
1216
    DBUG_PRINT("query",("%-.4096s",thd->query));
1217 1218 1219
#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
    thd->profiling.set_query_source(thd->query, thd->query_length);
#endif
1220 1221 1222 1223

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

1224
    mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt);
1225

1226
    while (!thd->killed && (end_of_stmt != NULL) && ! thd->is_error())
1227
    {
1228
      char *beginning_of_next_stmt= (char*) end_of_stmt;
1229 1230 1231

      net_end_statement(thd);
      query_cache_end_of_result(thd);
1232
      /*
1233 1234
        Multiple queries exits, execute them individually
      */
1235
      close_thread_tables(thd);
1236
      ulong length= (ulong)(packet_end - beginning_of_next_stmt);
1237

1238
      log_slow_statement(thd);
1239

1240
      /* Remove garbage at start of query */
1241
      while (length > 0 && my_isspace(thd->charset(), *beginning_of_next_stmt))
1242
      {
1243
        beginning_of_next_stmt++;
1244 1245
        length--;
      }
1246 1247 1248 1249 1250 1251 1252

#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
      thd->profiling.finish_current_query();
      thd->profiling.start_new_query("continuing");
      thd->profiling.set_query_source(beginning_of_next_stmt, length);
#endif

Gleb Shchepa's avatar
Gleb Shchepa committed
1253
      thd->set_query(beginning_of_next_stmt, length);
unknown's avatar
unknown committed
1254
      VOID(pthread_mutex_lock(&LOCK_thread_count));
1255 1256 1257 1258
      /*
        Count each statement from the client.
      */
      statistic_increment(thd->status_var.questions, &LOCK_status);
1259
      thd->query_id= next_query_id();
1260
      thd->set_time(); /* Reset the query start time. */
1261
      /* TODO: set thd->lex->sql_command to SQLCOM_END here */
1262
      VOID(pthread_mutex_unlock(&LOCK_thread_count));
1263
      mysql_parse(thd, beginning_of_next_stmt, length, &end_of_stmt);
1264 1265
    }

unknown's avatar
unknown committed
1266 1267 1268 1269 1270
    if (!(specialflag & SPECIAL_NO_PRIOR))
      my_pthread_setprio(pthread_self(),WAIT_PRIOR);
    DBUG_PRINT("info",("query ready"));
    break;
  }
1271
  case COM_FIELD_LIST:				// This isn't actually needed
unknown's avatar
unknown committed
1272
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
1273 1274
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
unknown's avatar
unknown committed
1275 1276 1277
    break;
#else
  {
1278
    char *fields, *packet_end= packet + packet_length, *arg_end;
1279
    /* Locked closure of all tables */
unknown's avatar
unknown committed
1280
    TABLE_LIST table_list;
unknown's avatar
unknown committed
1281
    LEX_STRING conv_name;
unknown's avatar
unknown committed
1282

unknown's avatar
unknown committed
1283
    /* used as fields initializator */
1284
    lex_start(thd);
1285

1286
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
unknown's avatar
unknown committed
1287
    bzero((char*) &table_list,sizeof(table_list));
1288
    if (thd->copy_db_to(&table_list.db, &table_list.db_length))
unknown's avatar
unknown committed
1289
      break;
1290 1291 1292 1293
    /*
      We have name + wildcard in packet, separated by endzero
    */
    arg_end= strend(packet);
unknown's avatar
unknown committed
1294
    thd->convert_string(&conv_name, system_charset_info,
1295
			packet, (uint) (arg_end - packet), thd->charset());
1296
    table_list.alias= table_list.table_name= conv_name.str;
1297
    packet= arg_end + 1;
1298 1299

    if (!my_strcasecmp(system_charset_info, table_list.db,
1300
                       INFORMATION_SCHEMA_NAME.str))
1301 1302 1303 1304 1305 1306
    {
      ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, table_list.alias);
      if (schema_table)
        table_list.schema_table= schema_table;
    }

Gleb Shchepa's avatar
Gleb Shchepa committed
1307 1308
    uint query_length= (uint) (packet_end - packet); // Don't count end \0
    if (!(fields= (char *) thd->memdup(packet, query_length + 1)))
unknown's avatar
unknown committed
1309
      break;
1310
    thd->set_query(fields, query_length);
unknown's avatar
unknown committed
1311
    general_log_print(thd, command, "%s %s", table_list.table_name, fields);
1312
    if (lower_case_table_names)
1313
      my_casedn_str(files_charset_info, table_list.table_name);
unknown's avatar
unknown committed
1314

unknown's avatar
unknown committed
1315
    if (check_access(thd,SELECT_ACL,table_list.db,&table_list.grant.privilege,
1316
		     0, 0, test(table_list.schema_table)))
unknown's avatar
unknown committed
1317
      break;
1318
    if (check_grant(thd, SELECT_ACL, &table_list, 2, UINT_MAX, 0))
unknown's avatar
unknown committed
1319
      break;
1320 1321
    /* init structures for VIEW processing */
    table_list.select_lex= &(thd->lex->select_lex);
1322 1323 1324 1325

    lex_start(thd);
    mysql_reset_thd_for_next_command(thd);

1326
    thd->lex->
1327 1328
      select_lex.table_list.link_in_list((uchar*) &table_list,
                                         (uchar**) &table_list.next_local);
unknown's avatar
unknown committed
1329
    thd->lex->add_to_query_tables(&table_list);
1330

1331 1332
    /* switch on VIEW optimisation: do not fill temporary tables */
    thd->lex->sql_command= SQLCOM_SHOW_FIELDS;
unknown's avatar
unknown committed
1333
    mysqld_list_fields(thd,&table_list,fields);
1334
    thd->lex->unit.cleanup();
1335
    thd->cleanup_after_query();
unknown's avatar
unknown committed
1336 1337 1338 1339
    break;
  }
#endif
  case COM_QUIT:
1340
    /* We don't calculate statistics for this command */
unknown's avatar
unknown committed
1341
    general_log_print(thd, command, NullS);
unknown's avatar
unknown committed
1342
    net->error=0;				// Don't give 'abort' message
1343
    thd->main_da.disable_status();              // Don't send anything back
unknown's avatar
unknown committed
1344 1345 1346
    error=TRUE;					// End server
    break;

1347
#ifdef REMOVED
unknown's avatar
unknown committed
1348
  case COM_CREATE_DB:				// QQ: To be removed
unknown's avatar
unknown committed
1349
    {
1350
      LEX_STRING db, alias;
1351
      HA_CREATE_INFO create_info;
unknown's avatar
unknown committed
1352

1353
      status_var_increment(thd->status_var.com_stat[SQLCOM_CREATE_DB]);
1354
      if (thd->make_lex_string(&db, packet, packet_length, FALSE) ||
1355
          thd->make_lex_string(&alias, db.str, db.length, FALSE) ||
1356
          check_db_name(&db))
1357
      {
1358
	my_error(ER_WRONG_DB_NAME, MYF(0), db.str ? db.str : "NULL");
1359 1360
	break;
      }
1361 1362
      if (check_access(thd, CREATE_ACL, db.str , 0, 1, 0,
                       is_schema_db(db.str)))
unknown's avatar
unknown committed
1363
	break;
Staale Smedseng's avatar
Staale Smedseng committed
1364
      general_log_print(thd, command, "%.*s", db.length, db.str);
1365
      bzero(&create_info, sizeof(create_info));
1366
      mysql_create_db(thd, (lower_case_table_names == 2 ? alias.str : db.str),
1367
                      &create_info, 0);
unknown's avatar
unknown committed
1368 1369
      break;
    }
unknown's avatar
unknown committed
1370
  case COM_DROP_DB:				// QQ: To be removed
unknown's avatar
unknown committed
1371
    {
1372
      status_var_increment(thd->status_var.com_stat[SQLCOM_DROP_DB]);
1373 1374
      LEX_STRING db;

1375
      if (thd->make_lex_string(&db, packet, packet_length, FALSE) ||
1376
          check_db_name(&db))
1377
      {
1378
	my_error(ER_WRONG_DB_NAME, MYF(0), db.str ? db.str : "NULL");
1379 1380
	break;
      }
1381
      if (check_access(thd, DROP_ACL, db.str, 0, 1, 0, is_schema_db(db.str)))
1382
	break;
unknown's avatar
unknown committed
1383 1384
      if (thd->locked_tables || thd->active_transaction())
      {
unknown's avatar
unknown committed
1385 1386
	my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                   ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
unknown's avatar
unknown committed
1387
	break;
unknown's avatar
unknown committed
1388
      }
Staale Smedseng's avatar
Staale Smedseng committed
1389
      general_log_write(thd, command, "%.*s", db.length, db.str);
1390
      mysql_rm_db(thd, db.str, 0, 0);
unknown's avatar
unknown committed
1391 1392
      break;
    }
1393
#endif
1394
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
1395 1396
  case COM_BINLOG_DUMP:
    {
unknown's avatar
unknown committed
1397 1398 1399 1400
      ulong pos;
      ushort flags;
      uint32 slave_server_id;

1401
      status_var_increment(thd->status_var.com_other);
1402
      thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
unknown committed
1403
      if (check_global_access(thd, REPL_SLAVE_ACL))
unknown's avatar
unknown committed
1404
	break;
unknown's avatar
unknown committed
1405

1406
      /* TODO: The following has to be changed to an 8 byte integer */
1407 1408
      pos = uint4korr(packet);
      flags = uint2korr(packet + 4);
unknown's avatar
unknown committed
1409
      thd->server_id=0; /* avoid suicide */
unknown's avatar
unknown committed
1410
      if ((slave_server_id= uint4korr(packet+6))) // mysqlbinlog.server_id==0
unknown's avatar
unknown committed
1411
	kill_zombie_dump_threads(slave_server_id);
1412
      thd->server_id = slave_server_id;
unknown's avatar
unknown committed
1413

unknown's avatar
unknown committed
1414
      general_log_print(thd, command, "Log: '%s'  Pos: %ld", packet+10,
unknown's avatar
unknown committed
1415
                      (long) pos);
1416
      mysql_binlog_send(thd, thd->strdup(packet + 10), (my_off_t) pos, flags);
unknown's avatar
unknown committed
1417
      unregister_slave(thd,1,1);
unknown's avatar
unknown committed
1418
      /*  fake COM_QUIT -- if we get here, the thread needs to terminate */
1419
      error = TRUE;
unknown's avatar
unknown committed
1420 1421
      break;
    }
1422
#endif
unknown's avatar
unknown committed
1423
  case COM_REFRESH:
unknown's avatar
unknown committed
1424 1425
  {
    bool not_used;
1426
    status_var_increment(thd->status_var.com_stat[SQLCOM_FLUSH]);
unknown's avatar
unknown committed
1427 1428
    ulong options= (ulong) (uchar) packet[0];
    if (check_global_access(thd,RELOAD_ACL))
unknown's avatar
unknown committed
1429
      break;
unknown's avatar
unknown committed
1430
    general_log_print(thd, command, NullS);
unknown's avatar
unknown committed
1431
    if (!reload_acl_and_cache(thd, options, (TABLE_LIST*) 0, &not_used))
1432
      my_ok(thd);
unknown's avatar
unknown committed
1433 1434
    break;
  }
1435
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
1436
  case COM_SHUTDOWN:
1437
  {
1438
    status_var_increment(thd->status_var.com_other);
unknown's avatar
unknown committed
1439
    if (check_global_access(thd,SHUTDOWN_ACL))
unknown's avatar
unknown committed
1440
      break; /* purecov: inspected */
1441
    /*
1442
      If the client is < 4.1.3, it is going to send us no argument; then
1443
      packet_length is 0, packet[0] is the end 0 of the packet. Note that
1444 1445
      SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in
      packet[0].
1446
    */
1447 1448
    enum mysql_enum_shutdown_level level=
      (enum mysql_enum_shutdown_level) (uchar) packet[0];
1449 1450 1451 1452 1453 1454 1455
    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;
    }
1456
    DBUG_PRINT("quit",("Got shutdown command for level %u", level));
unknown's avatar
unknown committed
1457
    general_log_print(thd, command, NullS);
1458
    my_eof(thd);
unknown's avatar
unknown committed
1459 1460 1461 1462
    close_thread_tables(thd);			// Free before kill
    kill_mysql();
    error=TRUE;
    break;
1463
  }
1464
#endif
unknown's avatar
unknown committed
1465 1466
  case COM_STATISTICS:
  {
1467 1468 1469
    STATUS_VAR current_global_status_var;
    ulong uptime;
    uint length;
1470
    ulonglong queries_per_second1000;
1471 1472
    char buff[250];
    uint buff_len= sizeof(buff);
1473

1474
    general_log_print(thd, command, NullS);
1475
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]);
1476
    calc_sum_of_all_status(&current_global_status_var);
1477 1478 1479 1480 1481
    if (!(uptime= (ulong) (thd->start_time - server_start_time)))
      queries_per_second1000= 0;
    else
      queries_per_second1000= thd->query_id * LL(1000) / uptime;

1482 1483 1484
    length= my_snprintf((char*) buff, buff_len - 1,
                        "Uptime: %lu  Threads: %d  Questions: %lu  "
                        "Slow queries: %lu  Opens: %lu  Flush tables: %lu  "
1485
                        "Open tables: %u  Queries per second avg: %u.%u",
1486 1487 1488 1489 1490 1491
                        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(),
1492 1493
                        (uint) (queries_per_second1000 / 1000),
                        (uint) (queries_per_second1000 % 1000));
1494 1495
#ifdef EMBEDDED_LIBRARY
    /* Store the buffer in permanent memory */
1496
    my_ok(thd, 0, 0, buff);
1497
#endif
unknown's avatar
unknown committed
1498
#ifdef SAFEMALLOC
1499
    if (sf_malloc_cur_memory)				// Using SAFEMALLOC
1500 1501 1502 1503 1504 1505 1506
    {
      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
1507 1508
#endif
#ifndef EMBEDDED_LIBRARY
1509
    VOID(my_net_write(net, (uchar*) buff, length));
1510 1511
    VOID(net_flush(net));
    thd->main_da.disable_status();
unknown's avatar
unknown committed
1512
#endif
unknown's avatar
unknown committed
1513 1514 1515
    break;
  }
  case COM_PING:
1516
    status_var_increment(thd->status_var.com_other);
1517
    my_ok(thd);				// Tell client we are alive
unknown's avatar
unknown committed
1518 1519
    break;
  case COM_PROCESS_INFO:
1520
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]);
1521 1522
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd, PROCESS_ACL))
unknown's avatar
unknown committed
1523
      break;
unknown's avatar
unknown committed
1524
    general_log_print(thd, command, NullS);
unknown's avatar
unknown committed
1525
    mysqld_list_processes(thd,
1526 1527
			  thd->security_ctx->master_access & PROCESS_ACL ? 
			  NullS : thd->security_ctx->priv_user, 0);
unknown's avatar
unknown committed
1528 1529 1530
    break;
  case COM_PROCESS_KILL:
  {
1531
    status_var_increment(thd->status_var.com_stat[SQLCOM_KILL]);
1532
    ulong id=(ulong) uint4korr(packet);
1533
    sql_kill(thd,id,false);
unknown's avatar
unknown committed
1534 1535
    break;
  }
1536 1537
  case COM_SET_OPTION:
  {
1538
    status_var_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION]);
unknown's avatar
unknown committed
1539 1540 1541 1542
    uint opt_command= uint2korr(packet);

    switch (opt_command) {
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON:
1543
      thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
1544
      my_eof(thd);
1545
      break;
unknown's avatar
unknown committed
1546
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF:
1547
      thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
1548
      my_eof(thd);
1549 1550
      break;
    default:
unknown's avatar
unknown committed
1551
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1552 1553 1554 1555
      break;
    }
    break;
  }
unknown's avatar
unknown committed
1556
  case COM_DEBUG:
1557
    status_var_increment(thd->status_var.com_other);
unknown's avatar
unknown committed
1558
    if (check_global_access(thd, SUPER_ACL))
unknown's avatar
unknown committed
1559
      break;					/* purecov: inspected */
1560
    mysql_print_status();
unknown's avatar
unknown committed
1561
    general_log_print(thd, command, NullS);
1562
    my_eof(thd);
unknown's avatar
unknown committed
1563 1564 1565 1566 1567
    break;
  case COM_SLEEP:
  case COM_CONNECT:				// Impossible here
  case COM_TIME:				// Impossible from client
  case COM_DELAYED_INSERT:
1568
  case COM_END:
unknown's avatar
unknown committed
1569
  default:
unknown's avatar
unknown committed
1570
    my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
unknown's avatar
unknown committed
1571 1572
    break;
  }
1573

unknown's avatar
unknown committed
1574
  /* report error issued during command execution */
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
  if (thd->killed_errno())
  {
    if (! thd->main_da.is_set())
      thd->send_kill_message();
  }
  if (thd->killed == THD::KILL_QUERY || thd->killed == THD::KILL_BAD_DATA)
  {
    thd->killed= THD::NOT_KILLED;
    thd->mysys_var->abort= 0;
  }

1586 1587 1588 1589 1590 1591 1592
  /* If commit fails, we should be able to reset the OK status. */
  thd->main_da.can_overwrite_status= TRUE;
  ha_autocommit_or_rollback(thd, thd->is_error());
  thd->main_da.can_overwrite_status= FALSE;

  thd->transaction.stmt.reset();

1593 1594
  net_end_statement(thd);
  query_cache_end_of_result(thd);
unknown's avatar
unknown committed
1595

1596 1597 1598 1599
  thd->proc_info= "closing tables";
  /* Free tables */
  close_thread_tables(thd);

1600
  log_slow_statement(thd);
1601

1602
  thd_proc_info(thd, "cleaning up");
1603
  thd->set_query(NULL, 0);
1604
  thd->command=COM_SLEEP;
1605
  VOID(pthread_mutex_lock(&LOCK_thread_count)); // For process list
1606 1607
  thread_running--;
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
1608
  thd_proc_info(thd, 0);
1609 1610 1611 1612 1613 1614
  thd->packet.shrink(thd->variables.net_buffer_length);	// Reclaim some memory
  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
  DBUG_RETURN(error);
}


1615
void log_slow_statement(THD *thd)
1616
{
unknown's avatar
unknown committed
1617
  DBUG_ENTER("log_slow_statement");
1618 1619 1620 1621 1622 1623 1624

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

1627 1628 1629 1630 1631
  /*
    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
1632
  {
1633
    ulonglong end_utime_of_query= thd->current_utime();
1634
    thd_proc_info(thd, "logging slow query");
1635

1636 1637 1638 1639
    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)) &&
1640 1641
          opt_log_queries_not_using_indexes &&
           !(sql_command_flags[thd->lex->sql_command] & CF_STATUS_COMMAND))) &&
1642
        thd->examined_row_count >= thd->variables.min_examined_row_limit)
1643
    {
1644
      thd_proc_info(thd, "logging slow query");
1645
      thd->status_var.long_query_count++;
1646
      slow_log_print(thd, thd->query, thd->query_length, end_utime_of_query);
1647
    }
unknown's avatar
unknown committed
1648
  }
unknown's avatar
unknown committed
1649
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1650 1651
}

1652

unknown's avatar
unknown committed
1653
/**
unknown's avatar
unknown committed
1654 1655 1656 1657 1658 1659 1660
  Create a TABLE_LIST object for an INFORMATION_SCHEMA table.

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

unknown's avatar
unknown committed
1661 1662 1663 1664 1665 1666 1667
  @param thd              thread handle
  @param lex              current lex
  @param table_ident      table alias if it's used
  @param schema_table_idx the type of the INFORMATION_SCHEMA table to be
                          created

  @note
unknown's avatar
unknown committed
1668 1669 1670 1671
    Due to the way this function works with memory and LEX it cannot
    be used outside the parser (parse tree transformations outside
    the parser break PS and SP).

unknown's avatar
unknown committed
1672
  @retval
unknown's avatar
unknown committed
1673
    0                 success
unknown's avatar
unknown committed
1674
  @retval
unknown's avatar
unknown committed
1675 1676 1677 1678
    1                 out of memory or SHOW commands are not allowed
                      in this version of the server.
*/

1679 1680 1681
int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident,
                         enum enum_schema_tables schema_table_idx)
{
1682
  SELECT_LEX *schema_select_lex= NULL;
1683
  DBUG_ENTER("prepare_schema_table");
1684

1685
  switch (schema_table_idx) {
1686 1687
  case SCH_SCHEMATA:
#if defined(DONT_ALLOW_SHOW_COMMANDS)
unknown's avatar
unknown committed
1688 1689
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0));   /* purecov: inspected */
1690 1691 1692 1693
    DBUG_RETURN(1);
#else
    break;
#endif
1694

1695 1696 1697
  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
1698
  case SCH_TRIGGERS:
unknown's avatar
unknown committed
1699
  case SCH_EVENTS:
1700
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
1701 1702
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1703 1704 1705
    DBUG_RETURN(1);
#else
    {
1706
      LEX_STRING db;
1707
      size_t dummy;
unknown's avatar
unknown committed
1708
      if (lex->select_lex.db == NULL &&
1709
          lex->copy_db_to(&lex->select_lex.db, &dummy))
1710
      {
unknown's avatar
unknown committed
1711
        DBUG_RETURN(1);
1712
      }
1713 1714 1715
      schema_select_lex= new SELECT_LEX();
      db.str= schema_select_lex->db= lex->select_lex.db;
      schema_select_lex->table_list.first= NULL;
1716
      db.length= strlen(db.str);
unknown's avatar
unknown committed
1717

1718
      if (check_db_name(&db))
1719
      {
1720
        my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
1721 1722 1723 1724 1725 1726 1727
        DBUG_RETURN(1);
      }
      break;
    }
#endif
  case SCH_COLUMNS:
  case SCH_STATISTICS:
unknown's avatar
unknown committed
1728
  {
1729
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
1730 1731
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1732 1733
    DBUG_RETURN(1);
#else
unknown's avatar
unknown committed
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
    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;
  }
1745
#endif
1746 1747 1748 1749 1750
  case SCH_PROFILES:
    /* 
      Mark this current profiling record to be discarded.  We don't
      wish to have SHOW commands show up in profiling.
    */
1751 1752
#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
    thd->profiling.discard_current_query();
1753 1754
#endif
    break;
1755 1756 1757
  case SCH_OPEN_TABLES:
  case SCH_VARIABLES:
  case SCH_STATUS:
1758 1759
  case SCH_PROCEDURES:
  case SCH_CHARSETS:
unknown's avatar
unknown committed
1760
  case SCH_ENGINES:
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
  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
1779
  table_list->schema_select_lex= schema_select_lex;
1780
  table_list->schema_table_reformed= 1;
1781 1782 1783 1784
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
1785 1786 1787
/**
  Read query from packet and store in thd->query.
  Used in COM_QUERY and COM_STMT_PREPARE.
1788 1789

    Sets the following THD variables:
unknown's avatar
unknown committed
1790 1791
  - query
  - query_length
1792

unknown's avatar
unknown committed
1793
  @retval
unknown's avatar
unknown committed
1794
    FALSE ok
unknown's avatar
unknown committed
1795
  @retval
unknown's avatar
unknown committed
1796
    TRUE  error;  In this case thd->fatal_error is set
1797 1798
*/

1799
bool alloc_query(THD *thd, const char *packet, uint packet_length)
1800
{
1801
  char *query;
1802
  /* Remove garbage at start and end of query */
1803
  while (packet_length > 0 && my_isspace(thd->charset(), packet[0]))
1804 1805 1806 1807
  {
    packet++;
    packet_length--;
  }
1808
  const char *pos= packet + packet_length;     // Point at end null
unknown's avatar
unknown committed
1809
  while (packet_length > 0 &&
unknown's avatar
unknown committed
1810
	 (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1])))
1811 1812 1813 1814 1815
  {
    pos--;
    packet_length--;
  }
  /* We must allocate some extra memory for query cache */
1816 1817 1818 1819 1820 1821 1822
  if (! (query= (char*) thd->memdup_w_gap(packet,
                                          packet_length,
                                          1 + thd->db_length +
                                          QUERY_CACHE_FLAGS_SIZE)))
      return TRUE;
  query[packet_length]= '\0';
  thd->set_query(query, packet_length);
1823 1824 1825 1826

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

unknown's avatar
unknown committed
1828
  return FALSE;
1829 1830
}

1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
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;
1844
  thd->variables.lc_time_names= &my_locale_en_US;
1845 1846 1847
  thd->one_shot_set= 0;
}

1848

1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
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);

1895
    if (thd->slave_thread && lex->sphead)
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
      lex->sphead->m_chistics->suid= SP_IS_NOT_SUID;
  }
  else
  {
    /*
      If the specified definer differs from the current user, we
      should check that the current user has SUPER privilege (in order
      to create a stored routine under another user one must have
      SUPER privilege).
    */
    if ((strcmp(lex->definer->user.str, thd->security_ctx->priv_user) ||
         my_strcasecmp(system_charset_info, lex->definer->host.str,
                       thd->security_ctx->priv_host)) &&
        check_global_access(thd, SUPER_ACL))
    {
      my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "SUPER");
      DBUG_RETURN(TRUE);
    }
  }

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

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

  DBUG_RETURN(FALSE);
}


unknown's avatar
unknown committed
1934 1935
/**
  Execute command saved in thd and lex->sql_command.
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946

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

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

unknown's avatar
unknown committed
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
  @param thd                       Thread handle

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

  @retval
1959
    FALSE       OK
unknown's avatar
unknown committed
1960
  @retval
1961 1962
    TRUE        Error
*/
unknown's avatar
unknown committed
1963

1964
int
1965
mysql_execute_command(THD *thd)
unknown's avatar
unknown committed
1966
{
1967
  int res= FALSE;
1968
  bool need_start_waiting= FALSE; // have protection against global read lock
unknown's avatar
unknown committed
1969
  int  up_result= 0;
1970
  LEX  *lex= thd->lex;
unknown's avatar
unknown committed
1971
  /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
unknown's avatar
unknown committed
1972
  SELECT_LEX *select_lex= &lex->select_lex;
unknown's avatar
VIEW  
unknown committed
1973
  /* first table of first SELECT_LEX */
unknown's avatar
unknown committed
1974
  TABLE_LIST *first_table= (TABLE_LIST*) select_lex->table_list.first;
unknown's avatar
VIEW  
unknown committed
1975 1976 1977
  /* list of all tables in query */
  TABLE_LIST *all_tables;
  /* most outer SELECT_LEX_UNIT of query */
1978
  SELECT_LEX_UNIT *unit= &lex->unit;
1979 1980 1981 1982
#ifdef HAVE_REPLICATION
  /* have table map for update for multi-update statement (BUG#37051) */
  bool have_table_map_for_update= FALSE;
#endif
1983
  /* Saved variable value */
unknown's avatar
unknown committed
1984
  DBUG_ENTER("mysql_execute_command");
unknown's avatar
unknown committed
1985 1986 1987
#ifdef WITH_PARTITION_STORAGE_ENGINE
  thd->work_part_info= 0;
#endif
unknown's avatar
unknown committed
1988

unknown's avatar
VIEW  
unknown committed
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
  /*
    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();
2005
  /* should be assigned after making first tables same */
unknown's avatar
VIEW  
unknown committed
2006
  all_tables= lex->query_tables;
2007 2008 2009 2010
  /* 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
2011

2012 2013 2014 2015 2016
  /*
    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.
2017
    Don't reset warnings when executing a stored routine.
2018
  */
2019
  if ((all_tables || !lex->is_single_level_stmt()) && !thd->spcont)
unknown's avatar
unknown committed
2020
    mysql_reset_errors(thd, 0);
2021

unknown's avatar
SCRUM  
unknown committed
2022
#ifdef HAVE_REPLICATION
2023
  if (unlikely(thd->slave_thread))
2024
  {
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
    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;
    }
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089

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

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

      if (all_tables_not_ok(thd, all_tables))
      {
        /* we warn the slave SQL thread */
        my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
        if (thd->one_shot_set)
          reset_one_shot_variables(thd);
        DBUG_RETURN(0);
      }
      
      for (table=all_tables; table; table=table->next_global)
        table->updating= TRUE;
    }
2090
    
unknown's avatar
unknown committed
2091
    /*
unknown's avatar
unknown committed
2092 2093
      Check if statment should be skipped because of slave filtering
      rules
2094 2095

      Exceptions are:
unknown's avatar
unknown committed
2096 2097
      - UPDATE MULTI: For this statement, we want to check the filtering
        rules later in the code
2098
      - SET: we always execute it (Not that many SET commands exists in
unknown's avatar
unknown committed
2099 2100
        the binary log anyway -- only 4.1 masters write SET statements,
	in 5.0 there are no SET statements in the binary log)
2101 2102
      - 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
2103
    */
unknown's avatar
unknown committed
2104 2105
    if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) &&
	!(lex->sql_command == SQLCOM_SET_OPTION) &&
2106
	!(lex->sql_command == SQLCOM_DROP_TABLE &&
2107
          lex->drop_temporary && lex->drop_if_exists) &&
unknown's avatar
Merge  
unknown committed
2108
        all_tables_not_ok(thd, all_tables))
unknown's avatar
unknown committed
2109 2110
    {
      /* we warn the slave SQL thread */
unknown's avatar
unknown committed
2111
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
      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);
      }
2129
      DBUG_RETURN(0);
unknown's avatar
unknown committed
2130
    }
2131
  }
2132
  else
2133
  {
2134
#endif /* HAVE_REPLICATION */
2135 2136 2137 2138
    /*
      When option readonly is set deny operations which change non-temporary
      tables. Except for the replication thread and the 'super' users.
    */
2139
    if (deny_updates_if_read_only_option(thd, all_tables))
2140 2141 2142 2143 2144 2145 2146
    {
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
      DBUG_RETURN(-1);
    }
#ifdef HAVE_REPLICATION
  } /* endif unlikely slave */
#endif
2147
  status_var_increment(thd->status_var.com_stat[lex->sql_command]);
2148

unknown's avatar
unknown committed
2149 2150
  DBUG_ASSERT(thd->transaction.stmt.modified_non_trans_table == FALSE);
  
unknown's avatar
unknown committed
2151
  switch (lex->sql_command) {
2152

2153
  case SQLCOM_SHOW_EVENTS:
2154 2155 2156 2157
#ifndef HAVE_EVENT_SCHEDULER
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server");
    break;
#endif
2158 2159
  case SQLCOM_SHOW_STATUS_PROC:
  case SQLCOM_SHOW_STATUS_FUNC:
2160 2161
    if (!(res= check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE)))
      res= execute_sqlcom_select(thd, all_tables);
2162 2163 2164 2165 2166
    break;
  case SQLCOM_SHOW_STATUS:
  {
    system_status_var old_status_var= thd->status_var;
    thd->initial_status_var= &old_status_var;
2167 2168
    if (!(res= check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE)))
      res= execute_sqlcom_select(thd, all_tables);
2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
    /* 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:
2194
  case SQLCOM_SHOW_STORAGE_ENGINES:
2195
  case SQLCOM_SHOW_PROFILE:
unknown's avatar
unknown committed
2196
  case SQLCOM_SELECT:
2197
    thd->status_var.last_query_cost= 0.0;
unknown's avatar
VIEW  
unknown committed
2198
    if (all_tables)
unknown's avatar
unknown committed
2199
    {
2200 2201 2202
      res= check_table_access(thd,
                              lex->exchange ? SELECT_ACL | FILE_ACL :
                              SELECT_ACL,
2203
                              all_tables, UINT_MAX, FALSE);
unknown's avatar
unknown committed
2204 2205
    }
    else
unknown's avatar
VIEW  
unknown committed
2206
      res= check_access(thd,
2207 2208
                        lex->exchange ? SELECT_ACL | FILE_ACL : SELECT_ACL,
                        any_db, 0, 0, 0, 0);
2209

2210 2211 2212 2213 2214 2215 2216 2217
    if (res)
      break;

    if (!thd->locked_tables && lex->protect_against_global_read_lock &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      break;

    res= execute_sqlcom_select(thd, all_tables);
unknown's avatar
unknown committed
2218
    break;
unknown's avatar
unknown committed
2219
  case SQLCOM_PREPARE:
2220
  {
2221
    mysql_sql_stmt_prepare(thd);
unknown's avatar
unknown committed
2222 2223 2224 2225
    break;
  }
  case SQLCOM_EXECUTE:
  {
2226
    mysql_sql_stmt_execute(thd);
unknown's avatar
unknown committed
2227 2228 2229 2230
    break;
  }
  case SQLCOM_DEALLOCATE_PREPARE:
  {
2231
    mysql_sql_stmt_close(thd);
unknown's avatar
unknown committed
2232 2233
    break;
  }
unknown's avatar
unknown committed
2234
  case SQLCOM_DO:
2235
    if (check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE) ||
2236
        open_and_lock_tables(thd, all_tables))
unknown's avatar
unknown committed
2237
      goto error;
unknown's avatar
unknown committed
2238 2239

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

2242
  case SQLCOM_EMPTY_QUERY:
2243
    my_ok(thd);
2244 2245
    break;

unknown's avatar
unknown committed
2246 2247 2248 2249
  case SQLCOM_HELP:
    res= mysqld_help(thd,lex->help_arg);
    break;

2250
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2251
  case SQLCOM_PURGE:
2252
  {
unknown's avatar
unknown committed
2253
    if (check_global_access(thd, SUPER_ACL))
2254
      goto error;
unknown's avatar
unknown committed
2255
    /* PURGE MASTER LOGS TO 'file' */
2256 2257 2258
    res = purge_master_logs(thd, lex->to_log);
    break;
  }
2259 2260
  case SQLCOM_PURGE_BEFORE:
  {
2261 2262
    Item *it;

2263 2264
    if (check_global_access(thd, SUPER_ACL))
      goto error;
unknown's avatar
unknown committed
2265
    /* PURGE MASTER LOGS BEFORE 'data' */
2266
    it= (Item *)lex->value_list.head();
2267
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) ||
unknown's avatar
unknown committed
2268
        it->check_cols(1))
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
    {
      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());
2280 2281
    break;
  }
2282
#endif
unknown's avatar
unknown committed
2283 2284
  case SQLCOM_SHOW_WARNS:
  {
2285 2286
    res= mysqld_show_warnings(thd, (ulong)
			      ((1L << (uint) MYSQL_ERROR::WARN_LEVEL_NOTE) |
2287 2288 2289
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_WARN) |
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR)
			       ));
unknown's avatar
unknown committed
2290 2291 2292 2293
    break;
  }
  case SQLCOM_SHOW_ERRORS:
  {
2294 2295
    res= mysqld_show_warnings(thd, (ulong)
			      (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR));
unknown's avatar
unknown committed
2296 2297
    break;
  }
unknown's avatar
unknown committed
2298 2299
  case SQLCOM_SHOW_PROFILES:
  {
2300
#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
2301
    thd->profiling.discard_current_query();
unknown's avatar
unknown committed
2302
    res= thd->profiling.show_profiles();
2303 2304 2305
    if (res)
      goto error;
#else
2306
    my_error(ER_FEATURE_DISABLED, MYF(0), "SHOW PROFILES", "enable-profiling");
2307 2308
    goto error;
#endif
unknown's avatar
unknown committed
2309 2310
    break;
  }
unknown's avatar
unknown committed
2311 2312
  case SQLCOM_SHOW_NEW_MASTER:
  {
unknown's avatar
unknown committed
2313
    if (check_global_access(thd, REPL_SLAVE_ACL))
unknown's avatar
unknown committed
2314
      goto error;
2315
    /* This query don't work now. See comment in repl_failsafe.cc */
unknown's avatar
unknown committed
2316
#ifndef WORKING_NEW_MASTER
unknown's avatar
unknown committed
2317 2318
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "SHOW NEW MASTER");
    goto error;
unknown's avatar
unknown committed
2319
#else
unknown's avatar
unknown committed
2320 2321
    res = show_new_master(thd);
    break;
unknown's avatar
unknown committed
2322
#endif
unknown's avatar
unknown committed
2323
  }
2324

unknown's avatar
unknown committed
2325
#ifdef HAVE_REPLICATION
2326 2327
  case SQLCOM_SHOW_SLAVE_HOSTS:
  {
unknown's avatar
unknown committed
2328
    if (check_global_access(thd, REPL_SLAVE_ACL))
2329 2330 2331 2332
      goto error;
    res = show_slave_hosts(thd);
    break;
  }
unknown's avatar
unknown committed
2333 2334
  case SQLCOM_SHOW_BINLOG_EVENTS:
  {
unknown's avatar
unknown committed
2335
    if (check_global_access(thd, REPL_SLAVE_ACL))
unknown's avatar
unknown committed
2336
      goto error;
2337
    res = mysql_show_binlog_events(thd);
unknown's avatar
unknown committed
2338 2339
    break;
  }
2340 2341
#endif

unknown's avatar
unknown committed
2342
  case SQLCOM_BACKUP_TABLE:
2343
  {
unknown's avatar
VIEW  
unknown committed
2344
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2345
    if (check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE) ||
unknown's avatar
unknown committed
2346
	check_global_access(thd, FILE_ACL))
2347
      goto error; /* purecov: inspected */
2348
    thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
VIEW  
unknown committed
2349
    res = mysql_backup_table(thd, first_table);
2350
    select_lex->table_list.first= (uchar*) first_table;
2351
    lex->query_tables=all_tables;
2352 2353
    break;
  }
unknown's avatar
unknown committed
2354
  case SQLCOM_RESTORE_TABLE:
2355
  {
unknown's avatar
VIEW  
unknown committed
2356
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2357
    if (check_table_access(thd, INSERT_ACL, all_tables, UINT_MAX, FALSE) ||
unknown's avatar
unknown committed
2358
	check_global_access(thd, FILE_ACL))
2359
      goto error; /* purecov: inspected */
2360
    thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
VIEW  
unknown committed
2361
    res = mysql_restore_table(thd, first_table);
2362
    select_lex->table_list.first= (uchar*) first_table;
2363
    lex->query_tables=all_tables;
2364 2365
    break;
  }
unknown's avatar
unknown committed
2366 2367
  case SQLCOM_ASSIGN_TO_KEYCACHE:
  {
unknown's avatar
VIEW  
unknown committed
2368
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2369
    if (check_access(thd, INDEX_ACL, first_table->db,
2370 2371
                     &first_table->grant.privilege, 0, 0,
                     test(first_table->schema_table)))
unknown's avatar
unknown committed
2372
      goto error;
2373
    res= mysql_assign_to_keycache(thd, first_table, &lex->ident);
unknown's avatar
unknown committed
2374 2375
    break;
  }
unknown's avatar
unknown committed
2376 2377
  case SQLCOM_PRELOAD_KEYS:
  {
unknown's avatar
VIEW  
unknown committed
2378
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2379
    if (check_access(thd, INDEX_ACL, first_table->db,
2380 2381
                     &first_table->grant.privilege, 0, 0,
                     test(first_table->schema_table)))
2382
      goto error;
unknown's avatar
VIEW  
unknown committed
2383
    res = mysql_preload_keys(thd, first_table);
unknown's avatar
unknown committed
2384 2385
    break;
  }
unknown's avatar
unknown committed
2386
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
2387
  case SQLCOM_CHANGE_MASTER:
2388
  {
unknown's avatar
unknown committed
2389
    if (check_global_access(thd, SUPER_ACL))
2390
      goto error;
2391
    pthread_mutex_lock(&LOCK_active_mi);
2392
    res = change_master(thd,active_mi);
2393
    pthread_mutex_unlock(&LOCK_active_mi);
2394 2395
    break;
  }
unknown's avatar
unknown committed
2396
  case SQLCOM_SHOW_SLAVE_STAT:
2397
  {
2398 2399
    /* Accept one of two privileges */
    if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
2400
      goto error;
2401
    pthread_mutex_lock(&LOCK_active_mi);
2402 2403 2404 2405 2406 2407
    if (active_mi != NULL)
    {
      res = show_master_info(thd, active_mi);
    }
    else
    {
2408 2409
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                   WARN_NO_MASTER_INFO, ER(WARN_NO_MASTER_INFO));
2410
      my_ok(thd);
2411
    }
2412
    pthread_mutex_unlock(&LOCK_active_mi);
2413 2414
    break;
  }
unknown's avatar
unknown committed
2415
  case SQLCOM_SHOW_MASTER_STAT:
2416
  {
2417 2418
    /* Accept one of two privileges */
    if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
2419 2420 2421 2422
      goto error;
    res = show_binlog_info(thd);
    break;
  }
unknown's avatar
unknown committed
2423

2424
  case SQLCOM_LOAD_MASTER_DATA: // sync with master
unknown's avatar
unknown committed
2425
    if (check_global_access(thd, SUPER_ACL))
2426
      goto error;
2427
    if (end_active_trans(thd))
unknown's avatar
unknown committed
2428
      goto error;
2429
    res = load_master_data(thd);
2430
    break;
unknown's avatar
unknown committed
2431
#endif /* HAVE_REPLICATION */
unknown's avatar
unknown committed
2432
  case SQLCOM_SHOW_ENGINE_STATUS:
unknown's avatar
unknown committed
2433
    {
2434
      if (check_global_access(thd, PROCESS_ACL))
unknown's avatar
unknown committed
2435 2436
        goto error;
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS);
unknown's avatar
unknown committed
2437 2438
      break;
    }
unknown's avatar
unknown committed
2439
  case SQLCOM_SHOW_ENGINE_MUTEX:
unknown's avatar
unknown committed
2440
    {
2441
      if (check_global_access(thd, PROCESS_ACL))
unknown's avatar
unknown committed
2442
        goto error;
unknown's avatar
unknown committed
2443
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX);
unknown's avatar
unknown committed
2444 2445
      break;
    }
unknown's avatar
unknown committed
2446
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
2447
  case SQLCOM_LOAD_MASTER_TABLE:
2448
  {
unknown's avatar
VIEW  
unknown committed
2449
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2450 2451
    DBUG_ASSERT(first_table->db); /* Must be set in the parser */

unknown's avatar
VIEW  
unknown committed
2452
    if (check_access(thd, CREATE_ACL, first_table->db,
2453 2454
		     &first_table->grant.privilege, 0, 0,
                     test(first_table->schema_table)))
unknown's avatar
unknown committed
2455
      goto error;				/* purecov: inspected */
2456 2457 2458 2459
    /* Check that the first table has CREATE privilege */
    if (check_grant(thd, CREATE_ACL, all_tables, 0, 1, 0))
      goto error;

2460
    pthread_mutex_lock(&LOCK_active_mi);
2461 2462 2463 2464
    /*
      fetch_master_table will send the error to the client on failure.
      Give error if the table already exists.
    */
2465
    if (!fetch_master_table(thd, first_table->db, first_table->table_name,
2466
			    active_mi, 0, 0))
2467
    {
2468
      my_ok(thd);
2469
    }
2470
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
2471
    break;
2472
  }
unknown's avatar
unknown committed
2473
#endif /* HAVE_REPLICATION */
2474

unknown's avatar
unknown committed
2475
  case SQLCOM_CREATE_TABLE:
unknown's avatar
unknown committed
2476
  {
2477
    /* If CREATE TABLE of non-temporary table, do implicit commit */
2478 2479 2480 2481 2482 2483 2484 2485
    if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
    {
      if (end_active_trans(thd))
      {
	res= -1;
	break;
      }
    }
unknown's avatar
VIEW  
unknown committed
2486 2487 2488 2489 2490
    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;
2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
    /*
      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
2512

unknown's avatar
VIEW  
unknown committed
2513
    if ((res= create_table_precheck(thd, select_tables, create_table)))
unknown's avatar
unknown committed
2514
      goto end_with_restore_list;
unknown's avatar
unknown committed
2515

2516 2517 2518
    /* Might have been updated in create_table_precheck */
    create_info.alias= create_table->alias;

2519
#ifdef HAVE_READLINK
2520
    /* Fix names if symlinked tables */
2521
    if (append_file_to_dir(thd, &create_info.data_file_name,
2522
			   create_table->table_name) ||
2523
	append_file_to_dir(thd, &create_info.index_file_name,
2524
			   create_table->table_name))
unknown's avatar
unknown committed
2525
      goto end_with_restore_list;
2526
#endif
2527
    /*
2528
      If we are using SET CHARSET without DEFAULT, add an implicit
2529 2530
      DEFAULT to not confuse old users. (This may change).
    */
2531
    if ((create_info.used_fields &
2532 2533 2534
	 (HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) ==
	HA_CREATE_USED_CHARSET)
    {
2535 2536 2537 2538
      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;
2539
    }
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
    /*
      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.
    */
2553 2554
    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
2555
    {
unknown's avatar
unknown committed
2556 2557
      res= 1;
      goto end_with_restore_list;
2558
    }
2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569
#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
2570
    if (select_lex->item_list.elements)		// With select
unknown's avatar
unknown committed
2571 2572
    {
      select_result *result;
2573

2574 2575 2576
      /*
        If:
        a) we inside an SP and there was NAME_CONST substitution,
Ramil Kalimullin's avatar
Ramil Kalimullin committed
2577
        b) binlogging is on (STMT mode),
2578 2579 2580 2581 2582 2583
        c) we log the SP as separate statements
        raise a warning, as it may cause problems
        (see 'NAME_CONST issues' in 'Binary Logging of Stored Programs')
       */
      if (thd->query_name_consts && 
          mysql_bin_log.is_open() &&
Ramil Kalimullin's avatar
Ramil Kalimullin committed
2584
          thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
          !mysql_bin_log.is_query_in_union(thd, thd->query_id))
      {
        List_iterator_fast<Item> it(select_lex->item_list);
        Item *item;
        uint splocal_refs= 0;
        /* Count SP local vars in the top-level SELECT list */
        while ((item= it++))
        {
          if (item->is_splocal())
            splocal_refs++;
        }
        /*
          If it differs from number of NAME_CONST substitution applied,
          we may have a SOME_FUNC(NAME_CONST()) in the SELECT list,
          that may cause a problem with binary log (see BUG#35383),
          raise a warning. 
        */
        if (splocal_refs != thd->query_name_consts)
          push_warning(thd, 
                       MYSQL_ERROR::WARN_LEVEL_WARN,
                       ER_UNKNOWN_ERROR,
"Invoked routine ran a statement that may cause problems with "
"binary log, see 'NAME_CONST issues' in 'Binary Logging of Stored Programs' "
"section of the manual.");
      }
      
2611
      select_lex->options|= SELECT_NO_UNLOCK;
2612
      unit->set_limit(select_lex);
2613

2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
      /*
        Disable non-empty MERGE tables with CREATE...SELECT. Too
        complicated. See Bug #26379. Empty MERGE tables are read-only
        and don't allow CREATE...SELECT anyway.
      */
      if (create_info.used_fields & HA_CREATE_USED_UNION)
      {
        my_error(ER_WRONG_OBJECT, MYF(0), create_table->db,
                 create_table->table_name, "BASE TABLE");
        res= 1;
        goto end_with_restore_list;
      }

2627
      if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
unknown's avatar
unknown committed
2628 2629 2630 2631 2632 2633
      {
        lex->link_first_table_back(create_table, link_to_local);
        create_table->create= TRUE;
      }

      if (!(res= open_and_lock_tables(thd, lex->query_tables)))
2634
      {
2635 2636 2637 2638
        /*
          Is table which we are changing used somewhere in other parts
          of query
        */
2639
        if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
2640
        {
2641
          TABLE_LIST *duplicate;
unknown's avatar
unknown committed
2642
          create_table= lex->unlink_first_table(&link_to_local);
2643
          if ((duplicate= unique_table(thd, create_table, select_tables, 0)))
2644 2645 2646
          {
            update_non_unique_table_error(create_table, "CREATE", duplicate);
            res= 1;
2647
            goto end_with_restore_list;
2648
          }
2649
        }
unknown's avatar
unknown committed
2650
        /* If we create merge table, we have to test tables in merge, too */
2651
        if (create_info.used_fields & HA_CREATE_USED_UNION)
unknown's avatar
unknown committed
2652 2653
        {
          TABLE_LIST *tab;
2654
          for (tab= (TABLE_LIST*) create_info.merge_list.first;
unknown's avatar
unknown committed
2655 2656 2657
               tab;
               tab= tab->next_local)
          {
2658
            TABLE_LIST *duplicate;
2659
            if ((duplicate= unique_table(thd, tab, select_tables, 0)))
unknown's avatar
unknown committed
2660
            {
2661
              update_non_unique_table_error(tab, "CREATE", duplicate);
unknown's avatar
unknown committed
2662
              res= 1;
2663
              goto end_with_restore_list;
unknown's avatar
unknown committed
2664 2665 2666
            }
          }
        }
2667

unknown's avatar
unknown committed
2668
        /*
2669 2670
          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
2671
        */
unknown's avatar
VIEW  
unknown committed
2672
        if ((result= new select_create(create_table,
2673 2674 2675 2676
                                       &create_info,
                                       &alter_info,
                                       select_lex->item_list,
                                       lex->duplicates,
2677
                                       lex->ignore,
2678
                                       select_tables)))
2679 2680 2681 2682 2683
        {
          /*
            CREATE from SELECT give its SELECT_LEX for SELECT,
            and item_list belong to SELECT
          */
2684
          res= handle_select(thd, lex, result, 0);
2685
          delete result;
2686
        }
2687
      }
2688
      else if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
unknown's avatar
unknown committed
2689 2690
        create_table= lex->unlink_first_table(&link_to_local);

2691
    }
unknown's avatar
unknown committed
2692
    else
unknown's avatar
unknown committed
2693
    {
2694
      /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
2695
      if (create_info.options & HA_LEX_CREATE_TMP_TABLE)
2696
        thd->options|= OPTION_KEEP_LOG;
unknown's avatar
unknown committed
2697
      /* regular create */
2698
      if (create_info.options & HA_LEX_CREATE_TABLE_LIKE)
unknown's avatar
unknown committed
2699
        res= mysql_create_like_table(thd, create_table, select_tables,
2700
                                     &create_info);
unknown's avatar
unknown committed
2701
      else
2702
      {
unknown's avatar
VIEW  
unknown committed
2703
        res= mysql_create_table(thd, create_table->db,
2704 2705
                                create_table->table_name, &create_info,
                                &alter_info, 0, 0);
2706
      }
unknown's avatar
unknown committed
2707
      if (!res)
2708
	my_ok(thd);
unknown's avatar
unknown committed
2709
    }
2710

unknown's avatar
unknown committed
2711
    /* put tables back for PS rexecuting */
unknown's avatar
unknown committed
2712
end_with_restore_list:
unknown's avatar
VIEW  
unknown committed
2713
    lex->link_first_table_back(create_table, link_to_local);
unknown's avatar
unknown committed
2714
    break;
unknown's avatar
unknown committed
2715
  }
unknown's avatar
unknown committed
2716
  case SQLCOM_CREATE_INDEX:
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734
    /* 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
2735 2736
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_one_table_access(thd, INDEX_ACL, all_tables))
unknown's avatar
unknown committed
2737
      goto error; /* purecov: inspected */
2738
    if (end_active_trans(thd))
unknown's avatar
unknown committed
2739
      goto error;
2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
    /*
      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
2751

2752 2753 2754 2755 2756
    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
2757
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
2758
  case SQLCOM_SLAVE_START:
2759
  {
2760
    pthread_mutex_lock(&LOCK_active_mi);
2761
    start_slave(thd,active_mi,1 /* net report*/);
2762
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
2763
    break;
2764
  }
unknown's avatar
unknown committed
2765
  case SQLCOM_SLAVE_STOP:
2766 2767 2768 2769 2770 2771
  /*
    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,
2772
      so it waits for the client thread because t is locked by it.
2773
    - then the client thread does SLAVE STOP.
2774 2775
      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.
2776 2777 2778
    To prevent that, refuse SLAVE STOP if the
    client thread has locked tables
  */
2779
  if (thd->locked_tables || thd->active_transaction() || thd->global_read_lock)
2780
  {
2781 2782
    my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
               ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2783
    goto error;
2784
  }
2785
  {
2786
    pthread_mutex_lock(&LOCK_active_mi);
2787
    stop_slave(thd,active_mi,1/* net report*/);
2788
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
2789
    break;
2790
  }
unknown's avatar
unknown committed
2791
#endif /* HAVE_REPLICATION */
2792

unknown's avatar
unknown committed
2793
  case SQLCOM_ALTER_TABLE:
unknown's avatar
VIEW  
unknown committed
2794
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2795
    {
unknown's avatar
unknown committed
2796
      ulong priv=0;
unknown's avatar
unknown committed
2797
      ulong priv_needed= ALTER_ACL;
2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808
      /*
        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;
2809 2810 2811 2812
      /*
        We also require DROP priv for ALTER TABLE ... DROP PARTITION, as well
        as for RENAME TO, as being done by SQLCOM_RENAME_TABLE
      */
2813
      if (alter_info.flags & (ALTER_DROP_PARTITION | ALTER_RENAME))
unknown's avatar
unknown committed
2814 2815
        priv_needed|= DROP_ACL;

unknown's avatar
unknown committed
2816 2817
      /* Must be set in the parser */
      DBUG_ASSERT(select_lex->db);
unknown's avatar
unknown committed
2818
      if (check_access(thd, priv_needed, first_table->db,
2819 2820 2821 2822
		       &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
2823
	  check_merge_table_access(thd, first_table->db,
2824
				   (TABLE_LIST *)
2825
				   create_info.merge_list.first))
2826
	goto error;				/* purecov: inspected */
2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
      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
2839
      }
2840

2841
      /* Don't yet allow changing of symlinks with ALTER TABLE */
2842
      if (create_info.data_file_name)
2843 2844 2845
        push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                            WARN_OPTION_IGNORED, ER(WARN_OPTION_IGNORED),
                            "DATA DIRECTORY");
2846
      if (create_info.index_file_name)
2847 2848 2849
        push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                            WARN_OPTION_IGNORED, ER(WARN_OPTION_IGNORED),
                            "INDEX DIRECTORY");
2850
      create_info.data_file_name= create_info.index_file_name= NULL;
unknown's avatar
unknown committed
2851
      /* ALTER TABLE ends previous transaction */
2852
      if (end_active_trans(thd))
unknown's avatar
unknown committed
2853
	goto error;
2854

2855 2856 2857 2858 2859
      if (!thd->locked_tables &&
          !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      {
        res= 1;
        break;
unknown's avatar
unknown committed
2860
      }
2861

2862
      thd->enable_slow_log= opt_log_slow_admin_statements;
2863
      res= mysql_alter_table(thd, select_lex->db, lex->name.str,
2864 2865 2866
                             &create_info,
                             first_table,
                             &alter_info,
2867 2868
                             select_lex->order_list.elements,
                             (ORDER *) select_lex->order_list.first,
2869
                             lex->ignore);
unknown's avatar
unknown committed
2870 2871
      break;
    }
unknown's avatar
unknown committed
2872
  case SQLCOM_RENAME_TABLE:
unknown's avatar
unknown committed
2873
  {
unknown's avatar
VIEW  
unknown committed
2874
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2875
    TABLE_LIST *table;
unknown's avatar
VIEW  
unknown committed
2876
    for (table= first_table; table; table= table->next_local->next_local)
unknown's avatar
unknown committed
2877
    {
unknown's avatar
unknown committed
2878
      if (check_access(thd, ALTER_ACL | DROP_ACL, table->db,
2879
		       &table->grant.privilege,0,0, test(table->schema_table)) ||
unknown's avatar
VIEW  
unknown committed
2880
	  check_access(thd, INSERT_ACL | CREATE_ACL, table->next_local->db,
2881 2882
		       &table->next_local->grant.privilege, 0, 0,
                       test(table->next_local->schema_table)))
unknown's avatar
unknown committed
2883
	goto error;
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895
      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
2896
    }
2897

unknown's avatar
unknown committed
2898
    if (end_active_trans(thd) || mysql_rename_tables(thd, first_table, 0))
unknown's avatar
unknown committed
2899
      goto error;
unknown's avatar
unknown committed
2900
    break;
unknown's avatar
unknown committed
2901
  }
2902
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2903 2904
  case SQLCOM_SHOW_BINLOGS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
2905 2906
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2907
    goto error;
unknown's avatar
unknown committed
2908 2909
#else
    {
unknown's avatar
unknown committed
2910
      if (check_global_access(thd, SUPER_ACL))
unknown's avatar
unknown committed
2911 2912 2913 2914
	goto error;
      res = show_binlogs(thd);
      break;
    }
unknown's avatar
unknown committed
2915
#endif
2916
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
2917
  case SQLCOM_SHOW_CREATE:
unknown's avatar
VIEW  
unknown committed
2918
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2919
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
2920 2921
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2922
    goto error;
unknown's avatar
unknown committed
2923
#else
unknown's avatar
unknown committed
2924
    {
2925 2926 2927
      /* Ignore temporary tables if this is "SHOW CREATE VIEW" */
      if (lex->only_view)
        first_table->skip_temporary= 1;
unknown's avatar
unknown committed
2928
      if (check_show_create_table_access(thd, first_table))
2929
	goto error;
unknown's avatar
unknown committed
2930
      res= mysqld_show_create(thd, first_table);
unknown's avatar
unknown committed
2931 2932
      break;
    }
unknown's avatar
unknown committed
2933
#endif
2934 2935
  case SQLCOM_CHECKSUM:
  {
unknown's avatar
VIEW  
unknown committed
2936
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2937 2938
    if (check_table_access(thd, SELECT_ACL | EXTRA_ACL, all_tables,
                           UINT_MAX, FALSE))
2939
      goto error; /* purecov: inspected */
unknown's avatar
VIEW  
unknown committed
2940
    res = mysql_checksum_table(thd, first_table, &lex->check_opt);
2941 2942
    break;
  }
unknown's avatar
unknown committed
2943
  case SQLCOM_REPAIR:
2944
  {
unknown's avatar
VIEW  
unknown committed
2945
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2946 2947
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables,
                           UINT_MAX, FALSE))
2948
      goto error; /* purecov: inspected */
2949
    thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
VIEW  
unknown committed
2950
    res= mysql_repair_table(thd, first_table, &lex->check_opt);
2951 2952 2953
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2954 2955 2956
      /*
        Presumably, REPAIR and binlog writing doesn't require synchronization
      */
2957
      write_bin_log(thd, TRUE, thd->query, thd->query_length);
2958
    }
2959
    select_lex->table_list.first= (uchar*) first_table;
2960
    lex->query_tables=all_tables;
2961 2962
    break;
  }
unknown's avatar
unknown committed
2963
  case SQLCOM_CHECK:
2964
  {
unknown's avatar
VIEW  
unknown committed
2965
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2966 2967
    if (check_table_access(thd, SELECT_ACL | EXTRA_ACL , all_tables,
                           UINT_MAX, FALSE))
2968
      goto error; /* purecov: inspected */
2969
    thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
VIEW  
unknown committed
2970
    res = mysql_check_table(thd, first_table, &lex->check_opt);
2971
    select_lex->table_list.first= (uchar*) first_table;
2972
    lex->query_tables=all_tables;
2973 2974
    break;
  }
unknown's avatar
unknown committed
2975 2976
  case SQLCOM_ANALYZE:
  {
unknown's avatar
VIEW  
unknown committed
2977
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2978 2979
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables,
                           UINT_MAX, FALSE))
unknown's avatar
unknown committed
2980
      goto error; /* purecov: inspected */
2981
    thd->enable_slow_log= opt_log_slow_admin_statements;
2982
    res= mysql_analyze_table(thd, first_table, &lex->check_opt);
2983 2984 2985
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2986 2987 2988
      /*
        Presumably, ANALYZE and binlog writing doesn't require synchronization
      */
2989
      write_bin_log(thd, TRUE, thd->query, thd->query_length);
2990
    }
2991
    select_lex->table_list.first= (uchar*) first_table;
2992
    lex->query_tables=all_tables;
unknown's avatar
unknown committed
2993
    break;
unknown's avatar
unknown committed
2994
  }
2995

unknown's avatar
unknown committed
2996 2997
  case SQLCOM_OPTIMIZE:
  {
unknown's avatar
VIEW  
unknown committed
2998
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2999 3000
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables,
                           UINT_MAX, FALSE))
unknown's avatar
unknown committed
3001
      goto error; /* purecov: inspected */
3002
    thd->enable_slow_log= opt_log_slow_admin_statements;
3003
    res= (specialflag & (SPECIAL_SAFE_MODE | SPECIAL_NO_NEW_FUNC)) ?
3004
      mysql_recreate_table(thd, first_table) :
unknown's avatar
VIEW  
unknown committed
3005
      mysql_optimize_table(thd, first_table, &lex->check_opt);
3006 3007 3008
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
3009 3010 3011
      /*
        Presumably, OPTIMIZE and binlog writing doesn't require synchronization
      */
3012
      write_bin_log(thd, TRUE, thd->query, thd->query_length);
3013
    }
3014
    select_lex->table_list.first= (uchar*) first_table;
3015
    lex->query_tables=all_tables;
unknown's avatar
unknown committed
3016 3017 3018
    break;
  }
  case SQLCOM_UPDATE:
unknown's avatar
VIEW  
unknown committed
3019 3020
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (update_precheck(thd, all_tables))
unknown's avatar
unknown committed
3021
      break;
3022 3023 3024
    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      goto error;
3025 3026
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
unknown's avatar
unknown committed
3027 3028 3029 3030 3031 3032 3033 3034
    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));
3035
    /* mysql_update return 2 if we need to switch to multi-update */
unknown's avatar
unknown committed
3036
    if (up_result != 2)
3037
      break;
unknown's avatar
unknown committed
3038
    /* Fall through */
3039
  case SQLCOM_UPDATE_MULTI:
unknown's avatar
unknown committed
3040 3041 3042
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    /* if we switched from normal update, rights are checked */
unknown's avatar
unknown committed
3043
    if (up_result != 2)
3044
    {
unknown's avatar
unknown committed
3045 3046 3047 3048 3049
      if ((res= multi_update_precheck(thd, all_tables)))
        break;
    }
    else
      res= 0;
unknown's avatar
unknown committed
3050

3051 3052 3053 3054 3055 3056 3057 3058 3059
    /*
      Protection might have already been risen if its a fall through
      from the SQLCOM_UPDATE case above.
    */
    if (!thd->locked_tables &&
        lex->sql_command == SQLCOM_UPDATE_MULTI &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      goto error;

3060
    res= mysql_multi_update_prepare(thd);
unknown's avatar
unknown committed
3061

3062
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
3063
    /* Check slave filtering rules */
3064
    if (unlikely(thd->slave_thread && !have_table_map_for_update))
unknown's avatar
unknown committed
3065
    {
3066 3067
      if (all_tables_not_ok(thd, all_tables))
      {
3068 3069 3070 3071 3072
        if (res!= 0)
        {
          res= 0;             /* don't care of prev failure  */
          thd->clear_error(); /* filters are of highest prior */
        }
3073 3074 3075 3076
        /* we warn the slave SQL thread */
        my_error(ER_SLAVE_IGNORED_TABLE, MYF(0));
        break;
      }
3077 3078
      if (res)
        break;
unknown's avatar
unknown committed
3079
    }
3080 3081
    else
    {
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094
#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
3095

unknown's avatar
unknown committed
3096 3097 3098 3099 3100 3101
    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
3102
    break;
unknown's avatar
unknown committed
3103
  }
unknown's avatar
unknown committed
3104
  case SQLCOM_REPLACE:
3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134
#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
3135 3136
  case SQLCOM_INSERT:
  {
unknown's avatar
VIEW  
unknown committed
3137
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
3138
    if ((res= insert_precheck(thd, all_tables)))
unknown's avatar
unknown committed
3139
      break;
3140 3141 3142 3143 3144 3145 3146 3147

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

unknown's avatar
VIEW  
unknown committed
3148
    res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
unknown's avatar
unknown committed
3149
		      lex->update_list, lex->value_list,
3150
                      lex->duplicates, lex->ignore);
3151 3152 3153 3154 3155 3156 3157

    /*
      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
3158
    if (first_table->view && !first_table->contain_auto_increment)
3159 3160
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
3161

unknown's avatar
unknown committed
3162
    break;
3163
  }
unknown's avatar
unknown committed
3164 3165 3166
  case SQLCOM_REPLACE_SELECT:
  case SQLCOM_INSERT_SELECT:
  {
unknown's avatar
unknown committed
3167
    select_result *sel_result;
unknown's avatar
VIEW  
unknown committed
3168
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
3169
    if ((res= insert_precheck(thd, all_tables)))
3170
      break;
unknown's avatar
unknown committed
3171

3172
    /* Fix lock for first table */
unknown's avatar
VIEW  
unknown committed
3173 3174
    if (first_table->lock_type == TL_WRITE_DELAYED)
      first_table->lock_type= TL_WRITE;
3175

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

3179
    unit->set_limit(select_lex);
3180 3181 3182 3183 3184 3185 3186 3187

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

unknown's avatar
VIEW  
unknown committed
3188
    if (!(res= open_and_lock_tables(thd, all_tables)))
3189
    {
3190
      /* Skip first table, which is the table we are inserting in */
unknown's avatar
unknown committed
3191
      TABLE_LIST *second_table= first_table->next_local;
3192
      select_lex->table_list.first= (uchar*) second_table;
3193 3194
      select_lex->context.table_list= 
        select_lex->context.first_name_resolution_table= second_table;
3195
      res= mysql_insert_select_prepare(thd);
unknown's avatar
unknown committed
3196 3197 3198 3199 3200 3201 3202
      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)))
3203
      {
unknown's avatar
unknown committed
3204
	res= handle_select(thd, lex, sel_result, OPTION_SETUP_TABLES_DONE);
3205 3206 3207 3208 3209 3210 3211 3212 3213
        /*
          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)
        {
3214 3215 3216
          /* INSERT ... SELECT should invalidate only the very first table */
          TABLE_LIST *save_table= first_table->next_local;
          first_table->next_local= 0;
3217
          query_cache_invalidate3(thd, first_table, 1);
3218
          first_table->next_local= save_table;
3219
        }
unknown's avatar
unknown committed
3220
        delete sel_result;
3221
      }
3222
      /* revert changes for SP */
3223
      select_lex->table_list.first= (uchar*) first_table;
3224
    }
unknown's avatar
VIEW  
unknown committed
3225

3226 3227 3228 3229 3230 3231
    /*
      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
3232
    if (first_table->view && !first_table->contain_auto_increment)
3233 3234
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
3235

unknown's avatar
unknown committed
3236 3237
    break;
  }
3238
  case SQLCOM_TRUNCATE:
3239 3240 3241 3242 3243
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
unknown's avatar
VIEW  
unknown committed
3244
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
3245
    if (check_one_table_access(thd, DROP_ACL, all_tables))
unknown's avatar
unknown committed
3246
      goto error;
3247 3248 3249 3250
    /*
      Don't allow this within a transaction because we want to use
      re-generate table
    */
3251
    if (thd->locked_tables || thd->active_transaction())
3252
    {
unknown's avatar
unknown committed
3253 3254
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3255 3256
      goto error;
    }
3257 3258
    if (!(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      goto error;
unknown's avatar
unknown committed
3259
    res= mysql_truncate(thd, first_table, 0);
3260
    break;
unknown's avatar
unknown committed
3261
  case SQLCOM_DELETE:
unknown's avatar
unknown committed
3262
  {
unknown's avatar
VIEW  
unknown committed
3263 3264
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if ((res= delete_precheck(thd, all_tables)))
unknown's avatar
unknown committed
3265
      break;
3266 3267
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
3268 3269 3270 3271 3272 3273 3274 3275

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

unknown's avatar
VIEW  
unknown committed
3276
    res = mysql_delete(thd, all_tables, select_lex->where,
3277
                       &select_lex->order_list,
unknown's avatar
unknown committed
3278 3279
                       unit->select_limit_cnt, select_lex->options,
                       FALSE);
unknown's avatar
unknown committed
3280 3281
    break;
  }
3282
  case SQLCOM_DELETE_MULTI:
unknown's avatar
unknown committed
3283
  {
unknown's avatar
VIEW  
unknown committed
3284
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3285
    TABLE_LIST *aux_tables=
unknown's avatar
unknown committed
3286
      (TABLE_LIST *)thd->lex->auxiliary_table_list.first;
unknown's avatar
unknown committed
3287
    multi_delete *del_result;
unknown's avatar
unknown committed
3288

3289 3290 3291 3292 3293 3294 3295
    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
    {
      res= 1;
      break;
    }

3296
    if ((res= multi_delete_precheck(thd, all_tables)))
3297
      break;
unknown's avatar
unknown committed
3298

unknown's avatar
unknown committed
3299
    /* condition will be TRUE on SP re-excuting */
3300 3301
    if (select_lex->item_list.elements != 0)
      select_lex->item_list.empty();
unknown's avatar
unknown committed
3302
    if (add_item_to_list(thd, new Item_null()))
unknown's avatar
unknown committed
3303
      goto error;
3304

3305
    thd_proc_info(thd, "init");
unknown's avatar
VIEW  
unknown committed
3306 3307 3308 3309
    if ((res= open_and_lock_tables(thd, all_tables)))
      break;

    if ((res= mysql_multi_delete_prepare(thd)))
unknown's avatar
unknown committed
3310
      goto error;
3311

unknown's avatar
unknown committed
3312 3313
    if (!thd->is_fatal_error &&
        (del_result= new multi_delete(aux_tables, lex->table_count)))
unknown's avatar
unknown committed
3314
    {
3315 3316 3317
      res= mysql_select(thd, &select_lex->ref_pointer_array,
			select_lex->get_table_list(),
			select_lex->with_wild,
3318
			select_lex->item_list,
unknown's avatar
unknown committed
3319
			select_lex->where,
3320
			0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL,
unknown's avatar
unknown committed
3321 3322
			(ORDER *)NULL,
			select_lex->options | thd->options |
3323 3324
			SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
                        OPTION_SETUP_TABLES_DONE,
unknown's avatar
unknown committed
3325
			del_result, unit, select_lex);
3326 3327
      res|= thd->is_error();
      if (res)
3328
        del_result->abort();
unknown's avatar
unknown committed
3329
      delete del_result;
unknown's avatar
unknown committed
3330 3331
    }
    else
3332
      res= TRUE;                                // Error
unknown's avatar
unknown committed
3333 3334
    break;
  }
unknown's avatar
unknown committed
3335
  case SQLCOM_DROP_TABLE:
unknown's avatar
unknown committed
3336
  {
unknown's avatar
VIEW  
unknown committed
3337
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3338 3339
    if (!lex->drop_temporary)
    {
3340
      if (check_table_access(thd, DROP_ACL, all_tables, UINT_MAX, FALSE))
3341 3342
	goto error;				/* purecov: inspected */
      if (end_active_trans(thd))
unknown's avatar
unknown committed
3343
        goto error;
3344
    }
unknown's avatar
unknown committed
3345
    else
unknown's avatar
unknown committed
3346 3347 3348 3349 3350 3351
    {
      /*
	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
3352 3353
	To not generate such irrelevant "table does not exist errors",
	we silently add IF EXISTS if TEMPORARY was used.
unknown's avatar
unknown committed
3354 3355
      */
      if (thd->slave_thread)
3356
        lex->drop_if_exists= 1;
3357

unknown's avatar
unknown committed
3358
      /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
3359
      thd->options|= OPTION_KEEP_LOG;
unknown's avatar
unknown committed
3360
    }
3361
    /* DDL and binlog write order protected by LOCK_open */
unknown's avatar
VIEW  
unknown committed
3362 3363
    res= mysql_rm_table(thd, first_table, lex->drop_if_exists,
			lex->drop_temporary);
unknown's avatar
unknown committed
3364 3365
  }
  break;
unknown's avatar
unknown committed
3366
  case SQLCOM_SHOW_PROCESSLIST:
3367 3368
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd,PROCESS_ACL))
unknown's avatar
unknown committed
3369
      break;
unknown's avatar
unknown committed
3370
    mysqld_list_processes(thd,
3371 3372 3373 3374
			  (thd->security_ctx->master_access & PROCESS_ACL ?
                           NullS :
                           thd->security_ctx->priv_user),
                          lex->verbose);
unknown's avatar
unknown committed
3375
    break;
unknown's avatar
unknown committed
3376 3377 3378
  case SQLCOM_SHOW_AUTHORS:
    res= mysqld_show_authors(thd);
    break;
3379 3380 3381
  case SQLCOM_SHOW_CONTRIBUTORS:
    res= mysqld_show_contributors(thd);
    break;
unknown's avatar
unknown committed
3382 3383 3384 3385 3386 3387
  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
3388
  case SQLCOM_SHOW_ENGINE_LOGS:
unknown's avatar
unknown committed
3389
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
3390 3391
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
3392
    goto error;
unknown's avatar
unknown committed
3393 3394
#else
    {
3395
      if (check_access(thd, FILE_ACL, any_db,0,0,0,0))
unknown's avatar
unknown committed
3396
	goto error;
unknown's avatar
unknown committed
3397
      res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS);
unknown's avatar
unknown committed
3398 3399
      break;
    }
unknown's avatar
unknown committed
3400 3401
#endif
  case SQLCOM_CHANGE_DB:
3402 3403 3404 3405
  {
    LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) };

    if (!mysql_change_db(thd, &db_str, FALSE))
3406
      my_ok(thd);
3407

unknown's avatar
unknown committed
3408
    break;
3409
  }
3410

unknown's avatar
unknown committed
3411 3412
  case SQLCOM_LOAD:
  {
unknown's avatar
VIEW  
unknown committed
3413
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
3414
    uint privilege= (lex->duplicates == DUP_REPLACE ?
unknown's avatar
unknown committed
3415 3416
		     INSERT_ACL | DELETE_ACL : INSERT_ACL) |
                    (lex->local_file ? 0 : FILE_ACL);
3417

unknown's avatar
unknown committed
3418
    if (lex->local_file)
unknown's avatar
unknown committed
3419
    {
3420
      if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) ||
3421
          !opt_local_infile)
3422
      {
unknown's avatar
unknown committed
3423
	my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0));
3424 3425
	goto error;
      }
unknown's avatar
unknown committed
3426
    }
unknown's avatar
unknown committed
3427 3428 3429 3430

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

3431 3432 3433 3434
    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      goto error;

unknown's avatar
VIEW  
unknown committed
3435
    res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
unknown's avatar
unknown committed
3436
                    lex->update_list, lex->value_list, lex->duplicates,
3437
                    lex->ignore, (bool) lex->local_file);
unknown's avatar
unknown committed
3438 3439
    break;
  }
3440

unknown's avatar
unknown committed
3441
  case SQLCOM_SET_OPTION:
3442 3443
  {
    List<set_var_base> *lex_var_list= &lex->var_list;
3444 3445 3446 3447

    if (lex->autocommit && end_active_trans(thd))
      goto error;

3448
    if ((check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE) ||
unknown's avatar
unknown committed
3449 3450
	 open_and_lock_tables(thd, all_tables)))
      goto error;
3451 3452
    if (lex->one_shot_set && not_all_support_one_shot(lex_var_list))
    {
unknown's avatar
unknown committed
3453 3454
      my_error(ER_RESERVED_SYNTAX, MYF(0), "SET ONE_SHOT");
      goto error;
3455 3456 3457 3458 3459 3460 3461 3462
    }
    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;
3463
      my_ok(thd);
3464
    }
3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476
    else
    {
      /*
        We encountered some sort of error, but no message was sent.
        Send something semi-generic here since we don't know which
        assignment in the list caused the error.
      */
      if (!thd->is_error())
        my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET");
      goto error;
    }

unknown's avatar
unknown committed
3477
    break;
3478
  }
unknown's avatar
unknown committed
3479

unknown's avatar
unknown committed
3480
  case SQLCOM_UNLOCK_TABLES:
3481 3482 3483 3484 3485 3486
    /*
      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
3487
    unlock_locked_tables(thd);
unknown's avatar
unknown committed
3488 3489
    if (thd->options & OPTION_TABLE_LOCK)
    {
unknown's avatar
unknown committed
3490
      end_active_trans(thd);
3491
      thd->options&= ~(OPTION_TABLE_LOCK);
unknown's avatar
unknown committed
3492 3493
    }
    if (thd->global_read_lock)
3494
      unlock_global_read_lock(thd);
3495
    my_ok(thd);
unknown's avatar
unknown committed
3496 3497
    break;
  case SQLCOM_LOCK_TABLES:
unknown's avatar
unknown committed
3498
    unlock_locked_tables(thd);
3499
    /* we must end the trasaction first, regardless of anything */
unknown's avatar
unknown committed
3500
    if (end_active_trans(thd))
unknown's avatar
unknown committed
3501
      goto error;
3502 3503
    if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, all_tables,
                           UINT_MAX, FALSE))
3504
      goto error;
3505 3506 3507
    if (lex->protect_against_global_read_lock &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      goto error;
unknown's avatar
unknown committed
3508
    thd->in_lock_tables=1;
unknown's avatar
unknown committed
3509
    thd->options|= OPTION_TABLE_LOCK;
unknown's avatar
VIEW  
unknown committed
3510

3511
    if (!(res= simple_open_n_lock_tables(thd, all_tables)))
unknown's avatar
unknown committed
3512
    {
3513 3514
#ifdef HAVE_QUERY_CACHE
      if (thd->variables.query_cache_wlock_invalidate)
unknown's avatar
VIEW  
unknown committed
3515
	query_cache.invalidate_locked_for_write(first_table);
3516
#endif /*HAVE_QUERY_CACHE*/
unknown's avatar
unknown committed
3517 3518
      thd->locked_tables=thd->lock;
      thd->lock=0;
3519
      my_ok(thd);
unknown's avatar
unknown committed
3520
    }
unknown's avatar
unknown committed
3521
    else
3522 3523 3524 3525 3526 3527
    {
      /* 
        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
      */
3528
      ha_autocommit_or_rollback(thd, 1);
3529
      end_active_trans(thd);
3530
      thd->options&= ~(OPTION_TABLE_LOCK);
3531
    }
unknown's avatar
unknown committed
3532 3533 3534
    thd->in_lock_tables=0;
    break;
  case SQLCOM_CREATE_DB:
3535
  {
3536 3537 3538 3539 3540 3541
    /*
      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);
3542 3543 3544 3545 3546
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
unknown's avatar
unknown committed
3547
    char *alias;
3548 3549
    if (!(alias=thd->strmake(lex->name.str, lex->name.length)) ||
        check_db_name(&lex->name))
unknown's avatar
unknown committed
3550
    {
3551
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
unknown's avatar
unknown committed
3552 3553
      break;
    }
3554 3555 3556
    /*
      If in a slave thread :
      CREATE DATABASE DB was certainly not preceded by USE DB.
3557
      For that reason, db_ok() in sql/slave.cc did not check the
3558 3559 3560
      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.
    */
3561
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
3562
    if (thd->slave_thread && 
3563 3564
	(!rpl_filter->db_ok(lex->name.str) ||
	 !rpl_filter->db_ok_with_wild_table(lex->name.str)))
unknown's avatar
unknown committed
3565
    {
unknown's avatar
unknown committed
3566
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3567
      break;
unknown's avatar
unknown committed
3568
    }
3569
#endif
3570 3571
    if (check_access(thd,CREATE_ACL,lex->name.str, 0, 1, 0,
                     is_schema_db(lex->name.str)))
3572
      break;
3573
    res= mysql_create_db(thd,(lower_case_table_names == 2 ? alias :
3574
                              lex->name.str), &create_info, 0);
3575 3576
    break;
  }
unknown's avatar
unknown committed
3577
  case SQLCOM_DROP_DB:
3578
  {
3579 3580 3581 3582 3583
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
3584
    if (check_db_name(&lex->name))
unknown's avatar
unknown committed
3585
    {
3586
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
unknown's avatar
unknown committed
3587 3588
      break;
    }
3589 3590 3591 3592 3593 3594 3595
    /*
      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.
    */
3596
#ifdef HAVE_REPLICATION
3597
    if (thd->slave_thread && 
3598 3599
	(!rpl_filter->db_ok(lex->name.str) ||
	 !rpl_filter->db_ok_with_wild_table(lex->name.str)))
unknown's avatar
unknown committed
3600
    {
unknown's avatar
unknown committed
3601
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3602
      break;
unknown's avatar
unknown committed
3603
    }
3604
#endif
3605 3606
    if (check_access(thd,DROP_ACL,lex->name.str,0,1,0,
                     is_schema_db(lex->name.str)))
3607
      break;
3608 3609
    if (thd->locked_tables || thd->active_transaction())
    {
unknown's avatar
unknown committed
3610 3611
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3612 3613
      goto error;
    }
3614
    res= mysql_rm_db(thd, lex->name.str, lex->drop_if_exists, 0);
3615 3616
    break;
  }
3617
  case SQLCOM_ALTER_DB_UPGRADE:
unknown's avatar
unknown committed
3618
  {
3619
    LEX_STRING *db= & lex->name;
unknown's avatar
unknown committed
3620 3621 3622 3623 3624 3625 3626
    if (end_active_trans(thd))
    {
      res= 1;
      break;
    }
#ifdef HAVE_REPLICATION
    if (thd->slave_thread && 
3627 3628
       (!rpl_filter->db_ok(db->str) ||
        !rpl_filter->db_ok_with_wild_table(db->str)))
unknown's avatar
unknown committed
3629 3630 3631 3632 3633 3634
    {
      res= 1;
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
      break;
    }
#endif
3635
    if (check_db_name(db))
3636
    {
3637
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
3638 3639
      break;
    }
3640 3641 3642
    if (check_access(thd, ALTER_ACL, db->str, 0, 1, 0, is_schema_db(db->str)) ||
        check_access(thd, DROP_ACL, db->str, 0, 1, 0, is_schema_db(db->str)) ||
        check_access(thd, CREATE_ACL, db->str, 0, 1, 0, is_schema_db(db->str)))
unknown's avatar
unknown committed
3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653
    {
      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;
    }
3654 3655

    res= mysql_upgrade_db(thd, db);
unknown's avatar
unknown committed
3656
    if (!res)
3657
      my_ok(thd);
unknown's avatar
unknown committed
3658 3659
    break;
  }
3660 3661
  case SQLCOM_ALTER_DB:
  {
3662
    LEX_STRING *db= &lex->name;
3663
    HA_CREATE_INFO create_info(lex->create_info);
3664
    if (check_db_name(db))
3665
    {
3666
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
3667 3668
      break;
    }
unknown's avatar
unknown committed
3669 3670 3671
    /*
      If in a slave thread :
      ALTER DATABASE DB may not be preceded by USE DB.
3672
      For that reason, maybe db_ok() in sql/slave.cc did not check the
unknown's avatar
unknown committed
3673 3674 3675 3676
      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
3677
    if (thd->slave_thread &&
3678 3679
	(!rpl_filter->db_ok(db->str) ||
	 !rpl_filter->db_ok_with_wild_table(db->str)))
unknown's avatar
unknown committed
3680
    {
unknown's avatar
unknown committed
3681
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
unknown's avatar
unknown committed
3682 3683 3684
      break;
    }
#endif
3685
    if (check_access(thd, ALTER_ACL, db->str, 0, 1, 0, is_schema_db(db->str)))
3686 3687 3688
      break;
    if (thd->locked_tables || thd->active_transaction())
    {
unknown's avatar
unknown committed
3689 3690
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3691 3692
      goto error;
    }
3693
    res= mysql_alter_db(thd, db->str, &create_info);
3694 3695
    break;
  }
unknown's avatar
unknown committed
3696 3697
  case SQLCOM_SHOW_CREATE_DB:
  {
unknown's avatar
unknown committed
3698 3699
    DBUG_EXECUTE_IF("4x_server_emul",
                    my_error(ER_UNKNOWN_ERROR, MYF(0)); goto error;);
3700
    if (check_db_name(&lex->name))
unknown's avatar
unknown committed
3701
    {
3702
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
unknown's avatar
unknown committed
3703 3704
      break;
    }
3705
    res= mysqld_show_create_db(thd, lex->name.str, &lex->create_info);
unknown's avatar
unknown committed
3706 3707
    break;
  }
unknown's avatar
unknown committed
3708 3709
  case SQLCOM_CREATE_EVENT:
  case SQLCOM_ALTER_EVENT:
3710
  #ifdef HAVE_EVENT_SCHEDULER
3711
  do
unknown's avatar
unknown committed
3712
  {
unknown's avatar
unknown committed
3713
    DBUG_ASSERT(lex->event_parse_data);
unknown's avatar
unknown committed
3714 3715 3716 3717 3718 3719
    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;
    }
3720 3721 3722 3723 3724

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

unknown's avatar
unknown committed
3725 3726
    switch (lex->sql_command) {
    case SQLCOM_CREATE_EVENT:
3727 3728 3729 3730
    {
      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
3731
      break;
3732
    }
unknown's avatar
unknown committed
3733
    case SQLCOM_ALTER_EVENT:
3734 3735 3736
      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
3737
      break;
3738 3739
    default:
      DBUG_ASSERT(0);
unknown's avatar
unknown committed
3740
    }
3741
    DBUG_PRINT("info",("DDL error code=%d", res));
unknown's avatar
unknown committed
3742
    if (!res)
3743
      my_ok(thd);
unknown's avatar
unknown committed
3744

3745 3746 3747 3748 3749 3750
  } 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
3751
  }
3752 3753
  /* lex->unit.cleanup() is called outside, no need to call it here */
  break;
unknown's avatar
unknown committed
3754
  case SQLCOM_SHOW_CREATE_EVENT:
3755 3756 3757 3758 3759 3760 3761
    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)))
3762
      my_ok(thd);
3763
    break;
3764 3765 3766 3767
#else
    my_error(ER_NOT_SUPPORTED_YET,MYF(0),"embedded server");
    break;
#endif
unknown's avatar
unknown committed
3768
  case SQLCOM_CREATE_FUNCTION:                  // UDF function
unknown's avatar
unknown committed
3769
  {
3770
    if (check_access(thd,INSERT_ACL,"mysql",0,1,0,0))
unknown's avatar
unknown committed
3771
      break;
unknown's avatar
unknown committed
3772
#ifdef HAVE_DLOPEN
3773
    if (!(res = mysql_create_function(thd, &lex->udf)))
3774
      my_ok(thd);
unknown's avatar
unknown committed
3775
#else
unknown's avatar
unknown committed
3776
    my_error(ER_CANT_OPEN_LIBRARY, MYF(0), lex->udf.dl, 0, "feature disabled");
unknown's avatar
unknown committed
3777
    res= TRUE;
unknown's avatar
unknown committed
3778 3779
#endif
    break;
unknown's avatar
unknown committed
3780
  }
unknown's avatar
unknown committed
3781
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3782 3783
  case SQLCOM_CREATE_USER:
  {
3784
    if (check_access(thd, INSERT_ACL, "mysql", 0, 1, 1, 0) &&
3785
        check_global_access(thd,CREATE_USER_ACL))
3786
      break;
3787 3788
    if (end_active_trans(thd))
      goto error;
3789
    /* Conditionally writes to binlog */
3790
    if (!(res= mysql_create_user(thd, lex->users_list)))
3791
      my_ok(thd);
3792 3793
    break;
  }
3794 3795
  case SQLCOM_DROP_USER:
  {
3796
    if (check_access(thd, DELETE_ACL, "mysql", 0, 1, 1, 0) &&
3797
        check_global_access(thd,CREATE_USER_ACL))
3798
      break;
3799 3800
    if (end_active_trans(thd))
      goto error;
3801
    /* Conditionally writes to binlog */
3802
    if (!(res= mysql_drop_user(thd, lex->users_list)))
3803
      my_ok(thd);
3804 3805 3806 3807
    break;
  }
  case SQLCOM_RENAME_USER:
  {
3808
    if (check_access(thd, UPDATE_ACL, "mysql", 0, 1, 1, 0) &&
3809
        check_global_access(thd,CREATE_USER_ACL))
3810
      break;
3811 3812
    if (end_active_trans(thd))
      goto error;
3813
    /* Conditionally writes to binlog */
3814
    if (!(res= mysql_rename_user(thd, lex->users_list)))
3815
      my_ok(thd);
3816 3817 3818 3819
    break;
  }
  case SQLCOM_REVOKE_ALL:
  {
3820 3821
    if (end_active_trans(thd))
      goto error;
3822
    if (check_access(thd, UPDATE_ACL, "mysql", 0, 1, 1, 0) &&
3823
        check_global_access(thd,CREATE_USER_ACL))
3824
      break;
3825
    /* Conditionally writes to binlog */
3826
    if (!(res = mysql_revoke_all(thd, lex->users_list)))
3827
      my_ok(thd);
3828 3829
    break;
  }
3830 3831 3832
  case SQLCOM_REVOKE:
  case SQLCOM_GRANT:
  {
3833 3834 3835
    if (end_active_trans(thd))
      goto error;

3836
    if (check_access(thd, lex->grant | lex->grant_tot_col | GRANT_ACL,
unknown's avatar
unknown committed
3837
		     first_table ?  first_table->db : select_lex->db,
unknown's avatar
VIEW  
unknown committed
3838
		     first_table ? &first_table->grant.privilege : 0,
3839 3840 3841
		     first_table ? 0 : 1, 0,
                     first_table ? (bool) first_table->schema_table :
                     select_lex->db ? is_schema_db(select_lex->db) : 0))
3842 3843
      goto error;

3844
    if (thd->security_ctx->user)              // If not replication
unknown's avatar
unknown committed
3845
    {
3846
      LEX_USER *user, *tmp_user;
3847

unknown's avatar
unknown committed
3848
      List_iterator <LEX_USER> user_list(lex->users_list);
3849
      while ((tmp_user= user_list++))
unknown's avatar
unknown committed
3850
      {
3851 3852
        if (!(user= get_current_user(thd, tmp_user)))
          goto error;
3853 3854 3855 3856 3857 3858 3859 3860
        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);
3861
        if (strcmp(thd->security_ctx->user, user->user.str) ||
3862
            my_strcasecmp(system_charset_info,
3863
                          user->host.str, thd->security_ctx->host_or_ip))
3864 3865
        {
          // TODO: use check_change_password()
3866 3867
          if (is_acl_user(user->host.str, user->user.str) &&
              user->password.str &&
3868
              check_access(thd, UPDATE_ACL,"mysql",0,1,1,0))
3869 3870 3871 3872 3873 3874
          {
            my_message(ER_PASSWORD_NOT_ALLOWED,
                       ER(ER_PASSWORD_NOT_ALLOWED), MYF(0));
            goto error;
          }
        }
unknown's avatar
SCRUM  
unknown committed
3875 3876
      }
    }
unknown's avatar
VIEW  
unknown committed
3877
    if (first_table)
3878
    {
3879 3880
      if (lex->type == TYPE_ENUM_PROCEDURE ||
          lex->type == TYPE_ENUM_FUNCTION)
3881 3882 3883 3884
      {
        uint grants= lex->all_privileges 
		   ? (PROC_ACLS & ~GRANT_ACL) | (lex->grant & GRANT_ACL)
		   : lex->grant;
3885
        if (check_grant_routine(thd, grants | GRANT_ACL, all_tables,
3886
                                lex->type == TYPE_ENUM_PROCEDURE, 0))
3887
	  goto error;
3888
        /* Conditionally writes to binlog */
3889 3890 3891
        res= mysql_routine_grant(thd, all_tables,
                                 lex->type == TYPE_ENUM_PROCEDURE, 
                                 lex->users_list, grants,
3892 3893 3894
                                 lex->sql_command == SQLCOM_REVOKE, TRUE);
        if (!res)
          my_ok(thd);
3895 3896 3897
      }
      else
      {
3898 3899
	if (check_grant(thd,(lex->grant | lex->grant_tot_col | GRANT_ACL),
                        all_tables, 0, UINT_MAX, 0))
3900
	  goto error;
3901
        /* Conditionally writes to binlog */
3902 3903 3904 3905
        res= mysql_table_grant(thd, all_tables, lex->users_list,
			       lex->columns, lex->grant,
			       lex->sql_command == SQLCOM_REVOKE);
      }
3906 3907 3908
    }
    else
    {
3909
      if (lex->columns.elements || lex->type)
3910
      {
unknown's avatar
unknown committed
3911 3912
	my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
                   MYF(0));
unknown's avatar
unknown committed
3913
        goto error;
3914 3915
      }
      else
3916
	/* Conditionally writes to binlog */
3917 3918 3919 3920
	res = mysql_grant(thd, select_lex->db, lex->users_list, lex->grant,
			  lex->sql_command == SQLCOM_REVOKE);
      if (!res)
      {
3921
	if (lex->sql_command == SQLCOM_GRANT)
3922
	{
unknown's avatar
unknown committed
3923
	  List_iterator <LEX_USER> str_list(lex->users_list);
3924 3925 3926 3927 3928
	  LEX_USER *user, *tmp_user;
	  while ((tmp_user=str_list++))
          {
            if (!(user= get_current_user(thd, tmp_user)))
              goto error;
3929
	    reset_mqh(user, 0);
3930
          }
3931
	}
3932 3933 3934 3935
      }
    }
    break;
  }
unknown's avatar
SCRUM  
unknown committed
3936
#endif /*!NO_EMBEDDED_ACCESS_CHECKS*/
unknown's avatar
unknown committed
3937
  case SQLCOM_RESET:
3938 3939 3940
    /*
      RESET commands are never written to the binary log, so we have to
      initialize this variable because RESET shares the same code as FLUSH
3941 3942 3943 3944
    */
    lex->no_write_to_binlog= 1;
  case SQLCOM_FLUSH:
  {
unknown's avatar
unknown committed
3945
    bool write_to_binlog;
unknown's avatar
unknown committed
3946
    if (check_global_access(thd,RELOAD_ACL))
unknown's avatar
unknown committed
3947
      goto error;
3948

3949 3950 3951 3952
    /*
      reload_acl_and_cache() will tell us if we are allowed to write to the
      binlog or not.
    */
unknown's avatar
unknown committed
3953
    if (!reload_acl_and_cache(thd, lex->type, first_table, &write_to_binlog))
3954 3955 3956 3957 3958
    {
      /*
        We WANT to write and we CAN write.
        ! we write after unlocking the table.
      */
3959 3960 3961
      /*
        Presumably, RESET and binlog writing doesn't require synchronization
      */
3962 3963
      if (!lex->no_write_to_binlog && write_to_binlog)
      {
3964
        write_bin_log(thd, FALSE, thd->query, thd->query_length);
3965
      }
3966
      my_ok(thd);
3967 3968
    } 
    
unknown's avatar
unknown committed
3969
    break;
3970
  }
unknown's avatar
unknown committed
3971
  case SQLCOM_KILL:
3972 3973 3974
  {
    Item *it= (Item *)lex->value_list.head();

unknown's avatar
unknown committed
3975 3976 3977 3978 3979 3980 3981
    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;
    }

3982
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1))
3983 3984 3985 3986 3987
    {
      my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY),
		 MYF(0));
      goto error;
    }
3988
    sql_kill(thd, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY);
unknown's avatar
unknown committed
3989
    break;
3990
  }
unknown's avatar
unknown committed
3991
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
3992
  case SQLCOM_SHOW_GRANTS:
3993 3994 3995 3996
  {
    LEX_USER *grant_user= get_current_user(thd, lex->grant_user);
    if (!grant_user)
      goto error;
3997
    if ((thd->security_ctx->priv_user &&
3998
	 !strcmp(thd->security_ctx->priv_user, grant_user->user.str)) ||
3999
	!check_access(thd, SELECT_ACL, "mysql",0,1,0,0))
unknown's avatar
unknown committed
4000
    {
4001
      res = mysql_show_grants(thd, grant_user);
unknown's avatar
unknown committed
4002 4003
    }
    break;
4004
  }
unknown's avatar
unknown committed
4005
#endif
4006
  case SQLCOM_HA_OPEN:
unknown's avatar
VIEW  
unknown committed
4007
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
4008
    if (check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE))
4009
      goto error;
unknown's avatar
unknown committed
4010
    res= mysql_ha_open(thd, first_table, 0);
4011 4012
    break;
  case SQLCOM_HA_CLOSE:
unknown's avatar
VIEW  
unknown committed
4013 4014
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    res= mysql_ha_close(thd, first_table);
4015 4016
    break;
  case SQLCOM_HA_READ:
unknown's avatar
VIEW  
unknown committed
4017
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
4018 4019 4020 4021 4022
    /*
      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.
    */
4023
    unit->set_limit(select_lex);
4024
    res= mysql_ha_read(thd, first_table, lex->ha_read_mode, lex->ident.str,
unknown's avatar
VIEW  
unknown committed
4025
                       lex->insert_list, lex->ha_rkey_mode, select_lex->where,
4026
                       unit->select_limit_cnt, unit->offset_limit_cnt);
4027 4028
    break;

unknown's avatar
unknown committed
4029
  case SQLCOM_BEGIN:
4030 4031 4032 4033 4034 4035
    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
4036
    if (begin_trans(thd))
unknown's avatar
unknown committed
4037
      goto error;
4038 4039 4040 4041 4042
    if (lex->start_transaction_opt & MYSQL_START_TRANS_OPT_WITH_CONS_SNAPSHOT)
    {
      if (ha_start_consistent_snapshot(thd))
        goto error;
    }
4043
    my_ok(thd);
unknown's avatar
unknown committed
4044 4045
    break;
  case SQLCOM_COMMIT:
4046
    if (end_trans(thd, lex->tx_release ? COMMIT_RELEASE :
unknown's avatar
unknown committed
4047
                              lex->tx_chain ? COMMIT_AND_CHAIN : COMMIT))
unknown's avatar
unknown committed
4048
      goto error;
4049
    my_ok(thd);
unknown's avatar
unknown committed
4050 4051
    break;
  case SQLCOM_ROLLBACK:
4052
    if (end_trans(thd, lex->tx_release ? ROLLBACK_RELEASE :
unknown's avatar
unknown committed
4053
                              lex->tx_chain ? ROLLBACK_AND_CHAIN : ROLLBACK))
unknown's avatar
unknown committed
4054
      goto error;
4055
    my_ok(thd);
unknown's avatar
unknown committed
4056
    break;
unknown's avatar
unknown committed
4057
  case SQLCOM_RELEASE_SAVEPOINT:
unknown's avatar
unknown committed
4058
  {
4059 4060
    SAVEPOINT *sv;
    for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
unknown's avatar
unknown committed
4061 4062 4063
    {
      if (my_strnncoll(system_charset_info,
                       (uchar *)lex->ident.str, lex->ident.length,
4064
                       (uchar *)sv->name, sv->length) == 0)
unknown's avatar
unknown committed
4065 4066
        break;
    }
4067
    if (sv)
unknown's avatar
unknown committed
4068
    {
4069
      if (ha_release_savepoint(thd, sv))
unknown's avatar
unknown committed
4070
        res= TRUE; // cannot happen
unknown's avatar
unknown committed
4071
      else
4072
        my_ok(thd);
4073
      thd->transaction.savepoints=sv->prev;
unknown's avatar
unknown committed
4074
    }
4075
    else
unknown's avatar
unknown committed
4076
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
unknown's avatar
unknown committed
4077
    break;
unknown's avatar
unknown committed
4078
  }
unknown's avatar
unknown committed
4079
  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
unknown's avatar
unknown committed
4080
  {
4081 4082
    SAVEPOINT *sv;
    for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
4083 4084 4085
    {
      if (my_strnncoll(system_charset_info,
                       (uchar *)lex->ident.str, lex->ident.length,
4086
                       (uchar *)sv->name, sv->length) == 0)
4087 4088
        break;
    }
4089
    if (sv)
4090
    {
4091
      if (ha_rollback_to_savepoint(thd, sv))
4092 4093
        res= TRUE; // cannot happen
      else
unknown's avatar
unknown committed
4094
      {
unknown's avatar
unknown committed
4095 4096
        if (((thd->options & OPTION_KEEP_LOG) || 
             thd->transaction.all.modified_non_trans_table) &&
unknown's avatar
unknown committed
4097 4098 4099 4100
            !thd->slave_thread)
          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                       ER_WARNING_NOT_COMPLETE_ROLLBACK,
                       ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
4101
        my_ok(thd);
unknown's avatar
unknown committed
4102
      }
4103
      thd->transaction.savepoints=sv;
unknown's avatar
unknown committed
4104 4105
    }
    else
4106
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
unknown's avatar
unknown committed
4107
    break;
4108
  }
4109
  case SQLCOM_SAVEPOINT:
4110 4111
    if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN) ||
          thd->in_sub_stmt) || !opt_using_transactions)
4112
      my_ok(thd);
unknown's avatar
unknown committed
4113
    else
4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148
    {
      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;
4149
        my_ok(thd);
4150 4151
      }
    }
unknown's avatar
unknown committed
4152
    break;
4153 4154
  case SQLCOM_CREATE_PROCEDURE:
  case SQLCOM_CREATE_SPFUNCTION:
unknown's avatar
unknown committed
4155
  {
4156
    uint namelen;
unknown's avatar
unknown committed
4157
    char *name;
unknown's avatar
unknown committed
4158
    int sp_result= SP_INTERNAL_ERROR;
4159

4160
    DBUG_ASSERT(lex->sphead != 0);
unknown's avatar
unknown committed
4161
    DBUG_ASSERT(lex->sphead->m_db.str); /* Must be initialized in the parser */
4162 4163 4164 4165
    /*
      Verify that the database name is allowed, optionally
      lowercase it.
    */
4166
    if (check_db_name(&lex->sphead->m_db))
4167
    {
4168
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->sphead->m_db.str);
4169
      goto create_sp_error;
4170 4171
    }

4172
    /*
4173 4174 4175
      Check that a database directory with this name
      exists. Design note: This won't work on virtual databases
      like information_schema.
4176 4177
    */
    if (check_db_dir_existence(lex->sphead->m_db.str))
4178
    {
4179
      my_error(ER_BAD_DB_ERROR, MYF(0), lex->sphead->m_db.str);
4180
      goto create_sp_error;
4181
    }
4182

4183 4184
    if (check_access(thd, CREATE_PROC_ACL, lex->sphead->m_db.str, 0, 0, 0,
                     is_schema_db(lex->sphead->m_db.str)))
4185
      goto create_sp_error;
4186

4187 4188
    if (end_active_trans(thd))
      goto create_sp_error;
4189 4190

    name= lex->sphead->name(&namelen);
4191
#ifdef HAVE_DLOPEN
unknown's avatar
unknown committed
4192 4193 4194
    if (lex->sphead->m_type == TYPE_ENUM_FUNCTION)
    {
      udf_func *udf = find_udf(name, namelen);
4195

unknown's avatar
unknown committed
4196
      if (udf)
4197
      {
4198 4199
        my_error(ER_UDF_EXISTS, MYF(0), name);
        goto create_sp_error;
4200
      }
unknown's avatar
unknown committed
4201 4202 4203
    }
#endif

4204 4205
    if (sp_process_definer(thd))
      goto create_sp_error;
4206

unknown's avatar
unknown committed
4207 4208
    res= (sp_result= lex->sphead->create(thd));
    switch (sp_result) {
4209
    case SP_OK: {
unknown's avatar
unknown committed
4210
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4211
      /* only add privileges if really neccessary */
4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234

      Security_context security_context;
      bool restore_backup_context= false;
      Security_context *backup= NULL;
      LEX_USER *definer= thd->lex->definer;
      /*
        Check if the definer exists on slave, 
        then use definer privilege to insert routine privileges to mysql.procs_priv.

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

4235
      if (sp_automatic_privileges && !opt_noacl &&
4236
          check_routine_access(thd, DEFAULT_CREATE_PROC_ACLS,
4237
                               lex->sphead->m_db.str, name,
4238
                               lex->sql_command == SQLCOM_CREATE_PROCEDURE, 1))
4239
      {
unknown's avatar
unknown committed
4240
        if (sp_grant_privileges(thd, lex->sphead->m_db.str, name,
4241
                                lex->sql_command == SQLCOM_CREATE_PROCEDURE))
4242 4243 4244
          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                       ER_PROC_AUTO_GRANT_FAIL,
                       ER(ER_PROC_AUTO_GRANT_FAIL));
4245
      }
4246 4247 4248 4249 4250 4251 4252 4253 4254 4255

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

unknown's avatar
unknown committed
4256
#endif
unknown's avatar
unknown committed
4257
    break;
4258
    }
4259 4260 4261 4262 4263 4264 4265 4266 4267
    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;
4268 4269 4270
    case SP_FLD_STORE_FAILED:
      my_error(ER_CANT_CREATE_SROUTINE, MYF(0), name);
      break;
4271 4272 4273 4274 4275 4276 4277 4278 4279 4280
    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
4281
    if (sp_result != SP_OK )
4282
      goto error;
4283
    my_ok(thd);
4284 4285
    break; /* break super switch */
  } /* end case group bracket */
4286 4287 4288 4289
  case SQLCOM_CALL:
    {
      sp_head *sp;

4290 4291 4292 4293
      /*
        This will cache all SP and SF and open and lock all tables
        required for execution.
      */
4294
      if (check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE) ||
4295 4296 4297 4298
	  open_and_lock_tables(thd, all_tables))
       goto error;

      /*
4299 4300
        By this moment all needed SPs should be in cache so no need to look 
        into DB. 
4301
      */
4302 4303
      if (!(sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                                &thd->sp_proc_cache, TRUE)))
4304
      {
4305
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PROCEDURE",
unknown's avatar
unknown committed
4306
                 lex->spname->m_qname.str);
4307
	goto error;
4308 4309 4310
      }
      else
      {
unknown's avatar
unknown committed
4311
	ha_rows select_limit;
unknown's avatar
unknown committed
4312 4313
        /* bits that should be cleared in thd->server_status */
	uint bits_to_be_cleared= 0;
4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325
        /*
          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;
        }
4326

4327
	if (sp->m_flags & sp_head::MULTI_RESULTS)
4328
	{
4329
	  if (! (thd->client_capabilities & CLIENT_MULTI_RESULTS))
4330
	  {
4331 4332 4333 4334
            /*
              The client does not support multiple result sets being sent
              back
            */
4335
	    my_error(ER_SP_BADSELECT, MYF(0), sp->m_qname.str);
4336 4337
	    goto error;
	  }
unknown's avatar
unknown committed
4338 4339 4340 4341 4342 4343 4344
          /*
            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;
4345 4346
	}

4347
	if (check_routine_access(thd, EXECUTE_ACL,
4348
				 sp->m_db.str, sp->m_name.str, TRUE, FALSE))
4349 4350 4351
	{
	  goto error;
	}
unknown's avatar
unknown committed
4352 4353
	select_limit= thd->variables.select_limit;
	thd->variables.select_limit= HA_POS_ERROR;
4354

4355
        /* 
4356
          We never write CALL statements into binlog:
4357 4358 4359 4360 4361
           - 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.
4362
        */
4363
	res= sp->execute_procedure(thd, &lex->value_list);
4364 4365 4366
	/*
          If warnings have been cleared, we have to clear total_warn_count
          too, otherwise the clients get confused.
4367 4368 4369 4370
	 */
	if (thd->warn_list.is_empty())
	  thd->total_warn_count= 0;

unknown's avatar
unknown committed
4371
	thd->variables.select_limit= select_limit;
4372

unknown's avatar
unknown committed
4373
        thd->server_status&= ~bits_to_be_cleared;
4374

unknown's avatar
unknown committed
4375
	if (!res)
4376 4377
          my_ok(thd, (ulong) (thd->row_count_func < 0 ? 0 :
                              thd->row_count_func));
4378
	else
4379
        {
4380
          DBUG_ASSERT(thd->is_error() || thd->killed);
4381
	  goto error;		// Substatement should already have sent error
4382
        }
4383
      }
4384
      break;
4385 4386
    }
  case SQLCOM_ALTER_PROCEDURE:
4387
  case SQLCOM_ALTER_FUNCTION:
4388
    {
unknown's avatar
unknown committed
4389
      int sp_result;
4390 4391 4392 4393
      sp_head *sp;
      st_sp_chistics chistics;

      memcpy(&chistics, &lex->sp_chistics, sizeof(chistics));
unknown's avatar
unknown committed
4394
      if (lex->sql_command == SQLCOM_ALTER_PROCEDURE)
4395 4396
        sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                            &thd->sp_proc_cache, FALSE);
4397
      else
4398 4399
        sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                            &thd->sp_func_cache, FALSE);
unknown's avatar
unknown committed
4400
      mysql_reset_errors(thd, 0);
4401
      if (! sp)
4402 4403
      {
	if (lex->spname->m_db.str)
unknown's avatar
unknown committed
4404
	  sp_result= SP_KEY_NOT_FOUND;
4405 4406 4407 4408 4409 4410
	else
	{
	  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
	  goto error;
	}
      }
4411 4412
      else
      {
4413 4414 4415
        if (check_routine_access(thd, ALTER_PROC_ACL, sp->m_db.str, 
				 sp->m_name.str,
                                 lex->sql_command == SQLCOM_ALTER_PROCEDURE, 0))
4416
	  goto error;
4417 4418 4419

        if (end_active_trans(thd)) 
          goto error;
4420
	memcpy(&lex->sp_chistics, &chistics, sizeof(lex->sp_chistics));
4421 4422
        if ((sp->m_type == TYPE_ENUM_FUNCTION) &&
            !trust_function_creators &&  mysql_bin_log.is_open() &&
4423 4424 4425 4426 4427 4428
            !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
4429
          sp_result= SP_INTERNAL_ERROR;
4430 4431 4432
        }
        else
        {
4433 4434 4435 4436 4437 4438
          /*
            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
4439
          /* Conditionally writes to binlog */
unknown's avatar
unknown committed
4440 4441 4442 4443 4444 4445 4446 4447 4448

          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);
4449
        }
4450
      }
unknown's avatar
unknown committed
4451
      switch (sp_result)
4452
      {
unknown's avatar
unknown committed
4453
      case SP_OK:
4454
	my_ok(thd);
unknown's avatar
unknown committed
4455 4456
	break;
      case SP_KEY_NOT_FOUND:
4457 4458
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
unknown's avatar
unknown committed
4459 4460
	goto error;
      default:
4461 4462
	my_error(ER_SP_CANT_ALTER, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
unknown's avatar
unknown committed
4463
	goto error;
4464
      }
4465
      break;
4466 4467
    }
  case SQLCOM_DROP_PROCEDURE:
4468
  case SQLCOM_DROP_FUNCTION:
4469
    {
unknown's avatar
unknown committed
4470
      int sp_result;
4471 4472
      int type= (lex->sql_command == SQLCOM_DROP_PROCEDURE ?
                 TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION);
4473

unknown's avatar
unknown committed
4474
      sp_result= sp_routine_exists_in_table(thd, type, lex->spname);
unknown's avatar
unknown committed
4475
      mysql_reset_errors(thd, 0);
unknown's avatar
unknown committed
4476
      if (sp_result == SP_OK)
4477
      {
4478 4479 4480
        char *db= lex->spname->m_db.str;
	char *name= lex->spname->m_name.str;

4481 4482
	if (check_routine_access(thd, ALTER_PROC_ACL, db, name,
                                 lex->sql_command == SQLCOM_DROP_PROCEDURE, 0))
unknown's avatar
merge  
unknown committed
4483
          goto error;
4484 4485 4486

        if (end_active_trans(thd)) 
          goto error;
unknown's avatar
unknown committed
4487
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4488
	if (sp_automatic_privileges && !opt_noacl &&
4489 4490
	    sp_revoke_privileges(thd, db, name, 
                                 lex->sql_command == SQLCOM_DROP_PROCEDURE))
4491 4492 4493 4494 4495
	{
	  push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 
		       ER_PROC_AUTO_REVOKE_FAIL,
		       ER(ER_PROC_AUTO_REVOKE_FAIL));
	}
unknown's avatar
unknown committed
4496
#endif
unknown's avatar
unknown committed
4497
        /* Conditionally writes to binlog */
unknown's avatar
unknown committed
4498 4499 4500 4501 4502 4503

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

        sp_result= sp_drop_routine(thd, type, lex->spname);
4504 4505 4506
      }
      else
      {
4507
#ifdef HAVE_DLOPEN
4508 4509 4510 4511 4512 4513
	if (lex->sql_command == SQLCOM_DROP_FUNCTION)
	{
          udf_func *udf = find_udf(lex->spname->m_name.str,
                                   lex->spname->m_name.length);
          if (udf)
          {
4514
	    if (check_access(thd, DELETE_ACL, "mysql", 0, 1, 0, 0))
4515
	      goto error;
4516

4517
	    if (!(res = mysql_drop_function(thd, &lex->spname->m_name)))
4518
	    {
4519
	      my_ok(thd);
4520
	      break;
4521 4522
	    }
	  }
4523
	}
4524
#endif
4525
	if (lex->spname->m_db.str)
unknown's avatar
unknown committed
4526
	  sp_result= SP_KEY_NOT_FOUND;
4527 4528 4529 4530 4531
	else
	{
	  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
	  goto error;
	}
4532
      }
unknown's avatar
unknown committed
4533 4534
      res= sp_result;
      switch (sp_result) {
4535
      case SP_OK:
4536
	my_ok(thd);
4537 4538
	break;
      case SP_KEY_NOT_FOUND:
4539 4540
	if (lex->drop_if_exists)
	{
4541
          write_bin_log(thd, TRUE, thd->query, thd->query_length);
4542
	  push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
4543
			      ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST),
4544
			      SP_COM_STRING(lex), lex->spname->m_name.str);
unknown's avatar
unknown committed
4545
	  res= FALSE;
4546
	  my_ok(thd);
4547 4548
	  break;
	}
4549 4550
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4551 4552
	goto error;
      default:
4553 4554
	my_error(ER_SP_DROP_FAILED, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4555
	goto error;
4556
      }
4557
      break;
4558
    }
unknown's avatar
unknown committed
4559 4560
  case SQLCOM_SHOW_CREATE_PROC:
    {
unknown's avatar
unknown committed
4561 4562
      if (sp_show_create_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname))
      {
4563 4564
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
unknown's avatar
unknown committed
4565 4566 4567 4568 4569 4570
	goto error;
      }
      break;
    }
  case SQLCOM_SHOW_CREATE_FUNC:
    {
unknown's avatar
unknown committed
4571 4572
      if (sp_show_create_routine(thd, TYPE_ENUM_FUNCTION, lex->spname))
      {
4573 4574
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
unknown's avatar
unknown committed
4575 4576 4577 4578
	goto error;
      }
      break;
    }
unknown's avatar
unknown committed
4579 4580 4581 4582 4583 4584 4585
#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
4586 4587
        sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                            &thd->sp_proc_cache, FALSE);
unknown's avatar
unknown committed
4588
      else
unknown's avatar
unknown committed
4589 4590
        sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                            &thd->sp_func_cache, FALSE);
4591
      if (!sp || sp->show_routine_code(thd))
4592 4593
      {
        /* We don't distinguish between errors for now */
unknown's avatar
unknown committed
4594 4595 4596 4597 4598 4599 4600
        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
4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613
  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
4614 4615
  case SQLCOM_CREATE_VIEW:
    {
4616 4617 4618 4619
      /*
        Note: SQLCOM_CREATE_VIEW also handles 'ALTER VIEW' commands
        as specified through the thd->lex->create_view_mode flag.
      */
4620 4621 4622
      if (end_active_trans(thd))
        goto error;

4623
      res= mysql_create_view(thd, first_table, thd->lex->create_view_mode);
unknown's avatar
VIEW  
unknown committed
4624 4625 4626 4627
      break;
    }
  case SQLCOM_DROP_VIEW:
    {
4628
      if (check_table_access(thd, DROP_ACL, all_tables, UINT_MAX, FALSE) ||
unknown's avatar
unknown committed
4629 4630
          end_active_trans(thd))
        goto error;
4631 4632
      /* Conditionally writes to binlog. */
      res= mysql_drop_view(thd, first_table, thd->lex->drop_mode);
unknown's avatar
VIEW  
unknown committed
4633 4634
      break;
    }
4635 4636
  case SQLCOM_CREATE_TRIGGER:
  {
4637 4638 4639
    if (end_active_trans(thd))
      goto error;

4640
    /* Conditionally writes to binlog. */
4641 4642
    res= mysql_create_or_drop_trigger(thd, all_tables, 1);

4643 4644 4645 4646
    break;
  }
  case SQLCOM_DROP_TRIGGER:
  {
4647 4648 4649
    if (end_active_trans(thd))
      goto error;

4650
    /* Conditionally writes to binlog. */
4651 4652 4653
    res= mysql_create_or_drop_trigger(thd, all_tables, 0);
    break;
  }
4654
  case SQLCOM_XA_START:
4655 4656
    if (thd->transaction.xid_state.xa_state == XA_IDLE &&
        thd->lex->xa_opt == XA_RESUME)
4657
    {
4658
      if (! thd->transaction.xid_state.xid.eq(thd->lex->xid))
4659 4660 4661 4662
      {
        my_error(ER_XAER_NOTA, MYF(0));
        break;
      }
4663
      thd->transaction.xid_state.xa_state=XA_ACTIVE;
4664
      my_ok(thd);
4665 4666
      break;
    }
unknown's avatar
unknown committed
4667
    if (thd->lex->xa_opt != XA_NONE)
4668 4669 4670 4671
    { // JOIN is not supported yet. TODO
      my_error(ER_XAER_INVAL, MYF(0));
      break;
    }
4672
    if (thd->transaction.xid_state.xa_state != XA_NOTR)
4673
    {
unknown's avatar
unknown committed
4674
      my_error(ER_XAER_RMFAIL, MYF(0),
4675
               xa_state_names[thd->transaction.xid_state.xa_state]);
4676 4677 4678 4679 4680 4681 4682
      break;
    }
    if (thd->active_transaction() || thd->locked_tables)
    {
      my_error(ER_XAER_OUTSIDE, MYF(0));
      break;
    }
4683 4684 4685 4686 4687 4688 4689
    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;
4690
    thd->transaction.xid_state.rm_error= 0;
4691 4692
    thd->transaction.xid_state.xid.set(thd->lex->xid);
    xid_cache_insert(&thd->transaction.xid_state);
unknown's avatar
unknown committed
4693
    thd->transaction.all.modified_non_trans_table= FALSE;
4694
    thd->options= ((thd->options & ~(OPTION_KEEP_LOG)) | OPTION_BEGIN);
4695
    thd->server_status|= SERVER_STATUS_IN_TRANS;
4696
    my_ok(thd);
4697 4698 4699 4700 4701 4702 4703 4704
    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;
    }
4705
    if (thd->transaction.xid_state.xa_state != XA_ACTIVE)
4706
    {
unknown's avatar
unknown committed
4707
      my_error(ER_XAER_RMFAIL, MYF(0),
4708
               xa_state_names[thd->transaction.xid_state.xa_state]);
4709 4710
      break;
    }
4711
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4712 4713 4714 4715
    {
      my_error(ER_XAER_NOTA, MYF(0));
      break;
    }
4716 4717
    if (xa_trans_rolled_back(&thd->transaction.xid_state))
      break;
4718
    thd->transaction.xid_state.xa_state=XA_IDLE;
4719
    my_ok(thd);
4720 4721
    break;
  case SQLCOM_XA_PREPARE:
4722
    if (thd->transaction.xid_state.xa_state != XA_IDLE)
4723
    {
unknown's avatar
unknown committed
4724
      my_error(ER_XAER_RMFAIL, MYF(0),
4725
               xa_state_names[thd->transaction.xid_state.xa_state]);
4726 4727
      break;
    }
4728
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4729 4730 4731 4732 4733 4734 4735
    {
      my_error(ER_XAER_NOTA, MYF(0));
      break;
    }
    if (ha_prepare(thd))
    {
      my_error(ER_XA_RBROLLBACK, MYF(0));
4736 4737
      xid_cache_delete(&thd->transaction.xid_state);
      thd->transaction.xid_state.xa_state=XA_NOTR;
4738 4739
      break;
    }
4740
    thd->transaction.xid_state.xa_state=XA_PREPARED;
4741
    my_ok(thd);
4742 4743
    break;
  case SQLCOM_XA_COMMIT:
4744
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4745
    {
4746 4747
      XID_STATE *xs=xid_cache_search(thd->lex->xid);
      if (!xs || xs->in_thd)
4748
        my_error(ER_XAER_NOTA, MYF(0));
4749 4750 4751 4752 4753 4754
      else if (xa_trans_rolled_back(xs))
      {
        ha_commit_or_rollback_by_xid(thd->lex->xid, 0);
        xid_cache_delete(xs);
        break;
      }
unknown's avatar
unknown committed
4755
      else
4756 4757 4758
      {
        ha_commit_or_rollback_by_xid(thd->lex->xid, 1);
        xid_cache_delete(xs);
4759
        my_ok(thd);
4760
      }
4761 4762
      break;
    }
4763 4764 4765 4766 4767
    if (xa_trans_rolled_back(&thd->transaction.xid_state))
    {
      xa_trans_rollback(thd);
      break;
    }
4768
    if (thd->transaction.xid_state.xa_state == XA_IDLE &&
unknown's avatar
unknown committed
4769
        thd->lex->xa_opt == XA_ONE_PHASE)
4770
    {
unknown's avatar
unknown committed
4771 4772 4773
      int r;
      if ((r= ha_commit(thd)))
        my_error(r == 1 ? ER_XA_RBROLLBACK : ER_XAER_RMERR, MYF(0));
4774
      else
4775
        my_ok(thd);
4776
    }
4777
    else if (thd->transaction.xid_state.xa_state == XA_PREPARED &&
unknown's avatar
unknown committed
4778
             thd->lex->xa_opt == XA_NONE)
4779
    {
4780 4781 4782
      if (wait_if_global_read_lock(thd, 0, 0))
      {
        ha_rollback(thd);
4783
        my_error(ER_XAER_RMERR, MYF(0));
4784
      }
4785
      else
4786 4787 4788 4789
      {
        if (ha_commit_one_phase(thd, 1))
          my_error(ER_XAER_RMERR, MYF(0));
        else
4790
          my_ok(thd);
4791 4792
        start_waiting_global_read_lock(thd);
      }
4793 4794 4795
    }
    else
    {
unknown's avatar
unknown committed
4796
      my_error(ER_XAER_RMFAIL, MYF(0),
4797
               xa_state_names[thd->transaction.xid_state.xa_state]);
4798 4799
      break;
    }
unknown's avatar
unknown committed
4800
    thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
unknown's avatar
unknown committed
4801
    thd->transaction.all.modified_non_trans_table= FALSE;
4802
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
4803 4804
    xid_cache_delete(&thd->transaction.xid_state);
    thd->transaction.xid_state.xa_state=XA_NOTR;
4805 4806
    break;
  case SQLCOM_XA_ROLLBACK:
4807
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4808
    {
4809 4810
      XID_STATE *xs=xid_cache_search(thd->lex->xid);
      if (!xs || xs->in_thd)
4811
        my_error(ER_XAER_NOTA, MYF(0));
unknown's avatar
unknown committed
4812
      else
4813
      {
4814
        bool ok= !xa_trans_rolled_back(xs);
4815 4816
        ha_commit_or_rollback_by_xid(thd->lex->xid, 0);
        xid_cache_delete(xs);
4817
        if (ok)
4818
          my_ok(thd);
4819
      }
4820 4821
      break;
    }
4822
    if (thd->transaction.xid_state.xa_state != XA_IDLE &&
4823 4824
        thd->transaction.xid_state.xa_state != XA_PREPARED &&
        thd->transaction.xid_state.xa_state != XA_ROLLBACK_ONLY)
4825
    {
unknown's avatar
unknown committed
4826
      my_error(ER_XAER_RMFAIL, MYF(0),
4827
               xa_state_names[thd->transaction.xid_state.xa_state]);
4828 4829
      break;
    }
4830
    if (xa_trans_rollback(thd))
4831 4832
      my_error(ER_XAER_RMERR, MYF(0));
    else
4833
      my_ok(thd);
4834 4835
    break;
  case SQLCOM_XA_RECOVER:
4836
    res= mysql_xa_recover(thd);
4837
    break;
unknown's avatar
unknown committed
4838 4839 4840 4841
  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)))
4842
      my_ok(thd);
unknown's avatar
unknown committed
4843 4844 4845 4846
    break;
  case SQLCOM_INSTALL_PLUGIN:
    if (! (res= mysql_install_plugin(thd, &thd->lex->comment,
                                     &thd->lex->ident)))
4847
      my_ok(thd);
unknown's avatar
unknown committed
4848 4849 4850
    break;
  case SQLCOM_UNINSTALL_PLUGIN:
    if (! (res= mysql_uninstall_plugin(thd, &thd->lex->comment)))
4851
      my_ok(thd);
unknown's avatar
unknown committed
4852 4853 4854 4855 4856 4857 4858 4859 4860 4861
    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
4862 4863 4864 4865 4866
  case SQLCOM_CREATE_SERVER:
  {
    int error;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_CREATE_SERVER"));
unknown's avatar
unknown committed
4867 4868 4869 4870

    if (check_global_access(thd, SUPER_ACL))
      break;

unknown's avatar
unknown committed
4871 4872
    if ((error= create_server(thd, &lex->server_options)))
    {
4873
      DBUG_PRINT("info", ("problem creating server <%s>",
unknown's avatar
unknown committed
4874 4875 4876 4877
                          lex->server_options.server_name));
      my_error(error, MYF(0), lex->server_options.server_name);
      break;
    }
4878
    my_ok(thd, 1);
unknown's avatar
unknown committed
4879 4880 4881 4882 4883 4884 4885
    break;
  }
  case SQLCOM_ALTER_SERVER:
  {
    int error;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_ALTER_SERVER"));
unknown's avatar
unknown committed
4886 4887 4888 4889

    if (check_global_access(thd, SUPER_ACL))
      break;

unknown's avatar
unknown committed
4890 4891
    if ((error= alter_server(thd, &lex->server_options)))
    {
4892
      DBUG_PRINT("info", ("problem altering server <%s>",
unknown's avatar
unknown committed
4893 4894 4895 4896
                          lex->server_options.server_name));
      my_error(error, MYF(0), lex->server_options.server_name);
      break;
    }
4897
    my_ok(thd, 1);
unknown's avatar
unknown committed
4898 4899 4900 4901 4902 4903 4904
    break;
  }
  case SQLCOM_DROP_SERVER:
  {
    int err_code;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_DROP_SERVER"));
unknown's avatar
unknown committed
4905 4906 4907 4908

    if (check_global_access(thd, SUPER_ACL))
      break;

unknown's avatar
unknown committed
4909 4910
    if ((err_code= drop_server(thd, &lex->server_options)))
    {
unknown's avatar
unknown committed
4911
      if (! lex->drop_if_exists && err_code == ER_FOREIGN_SERVER_DOESNT_EXIST)
unknown's avatar
unknown committed
4912 4913 4914 4915 4916 4917 4918
      {
        DBUG_PRINT("info", ("problem dropping server %s",
                            lex->server_options.server_name));
        my_error(err_code, MYF(0), lex->server_options.server_name);
      }
      else
      {
4919
        my_ok(thd, 0);
unknown's avatar
unknown committed
4920 4921 4922
      }
      break;
    }
4923
    my_ok(thd, 1);
unknown's avatar
unknown committed
4924 4925
    break;
  }
4926
  default:
4927
#ifndef EMBEDDED_LIBRARY
4928
    DBUG_ASSERT(0);                             /* Impossible */
4929
#endif
4930
    my_ok(thd);
unknown's avatar
unknown committed
4931 4932
    break;
  }
4933
  thd_proc_info(thd, "query end");
4934 4935

  /*
unknown's avatar
unknown committed
4936
    Binlog-related cleanup:
4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947
    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);

4948
  /*
4949 4950
    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
4951 4952 4953 4954
    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))
4955
    thd->row_count_func= -1;
4956

4957
  goto finish;
unknown's avatar
unknown committed
4958 4959

error:
4960 4961
  res= TRUE;

4962
finish:
4963 4964 4965 4966 4967 4968 4969 4970
  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);
  }
4971
  DBUG_RETURN(res || thd->is_error());
unknown's avatar
unknown committed
4972 4973 4974
}


4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997
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()))
4998
        return 1;                               /* purecov: inspected */
4999 5000 5001 5002 5003 5004 5005
      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);
5006
        thd->lex->unit.print(&str, QT_ORDINARY);
5007 5008 5009 5010
        str.append('\0');
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
                     ER_YES, str.ptr());
      }
5011 5012 5013 5014
      if (res)
        result->abort();
      else
        result->send_eof();
5015 5016 5017 5018 5019
      delete result;
    }
    else
    {
      if (!result && !(result= new select_send()))
5020
        return 1;                               /* purecov: inspected */
5021 5022 5023 5024 5025 5026 5027 5028 5029 5030
      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
5031
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
5032
/**
5033
  Check grants for commands which work only with one table.
unknown's avatar
unknown committed
5034

5035 5036 5037
  @param thd                    Thread handler
  @param privilege              requested privilege
  @param all_tables             global table list of query
unknown's avatar
unknown committed
5038
  @param no_errors              FALSE/TRUE - report/don't report error to
5039
                            the client (using my_error() call).
unknown's avatar
unknown committed
5040 5041 5042 5043 5044

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

5047
bool check_single_table_access(THD *thd, ulong privilege, 
5048
                               TABLE_LIST *all_tables, bool no_errors)
unknown's avatar
unknown committed
5049
{
5050 5051 5052 5053 5054 5055
  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;

5056 5057 5058 5059 5060 5061 5062 5063
  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,
5064
		   &all_tables->grant.privilege, 0, no_errors,
5065
                   test(all_tables->schema_table)))
5066
    goto deny;
unknown's avatar
unknown committed
5067

unknown's avatar
unknown committed
5068
  /* Show only 1 table for check_grant */
5069
  if (!(all_tables->belong_to_view &&
5070
        (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) &&
5071
      !(all_tables->view &&
5072
        all_tables->effective_algorithm == VIEW_ALGORITHM_TMPTABLE) &&
5073
      check_grant(thd, privilege, all_tables, 0, 1, no_errors))
5074 5075 5076
    goto deny;

  thd->security_ctx= backup_ctx;
5077 5078 5079 5080 5081 5082 5083
  return 0;

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

unknown's avatar
unknown committed
5084
/**
5085 5086 5087
  Check grants for commands which work only with one table and all other
  tables belonging to subselects or implicitly opened tables.

unknown's avatar
unknown committed
5088 5089 5090 5091 5092 5093 5094 5095
  @param thd			Thread handler
  @param privilege		requested privilege
  @param all_tables		global table list of query

  @retval
    0   OK
  @retval
    1   access denied, error is sent to client
5096 5097 5098 5099
*/

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

5103
  /* Check rights on tables of subselects and implictly opened tables */
unknown's avatar
unknown committed
5104
  TABLE_LIST *subselects_tables, *view= all_tables->view ? all_tables : 0;
unknown's avatar
VIEW  
unknown committed
5105
  if ((subselects_tables= all_tables->next_global))
unknown's avatar
unknown committed
5106
  {
unknown's avatar
unknown committed
5107 5108 5109 5110 5111 5112
    /*
      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)
    {
5113
      if (check_single_table_access (thd, privilege, subselects_tables, FALSE))
unknown's avatar
unknown committed
5114 5115 5116 5117
        return 1;
      subselects_tables= subselects_tables->next_global;
    }
    if (subselects_tables &&
5118
        (check_table_access(thd, SELECT_ACL, subselects_tables, UINT_MAX, FALSE)))
5119
      return 1;
unknown's avatar
unknown committed
5120 5121
  }
  return 0;
unknown's avatar
unknown committed
5122 5123 5124
}


unknown's avatar
unknown committed
5125 5126
/**
  Get the user (global) and database privileges for all used tables.
unknown's avatar
unknown committed
5127

unknown's avatar
unknown committed
5128 5129 5130 5131
  @param 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 is enough to satisfy the request and the
                      global grants contains a SELECT grant.
unknown's avatar
unknown committed
5132

unknown's avatar
unknown committed
5133
  @note
unknown's avatar
unknown committed
5134 5135 5136 5137 5138
    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.

unknown's avatar
unknown committed
5139
  @retval
unknown's avatar
unknown committed
5140
    0  ok
unknown's avatar
unknown committed
5141 5142 5143 5144
  @retval
    1  If we can't get the privileges and we don't use table/column
    grants.
*/
unknown's avatar
unknown committed
5145
bool
unknown's avatar
unknown committed
5146
check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv,
5147
	     bool dont_check_global_grants, bool no_errors, bool schema_db)
unknown's avatar
unknown committed
5148
{
5149
  Security_context *sctx= thd->security_ctx;
unknown's avatar
unknown committed
5150
  ulong db_access;
5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161
  /*
    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
5162
  ulong dummy;
5163 5164
  DBUG_ENTER("check_access");
  DBUG_PRINT("enter",("db: %s  want_access: %lu  master_access: %lu",
5165
                      db ? db : "", want_access, sctx->master_access));
unknown's avatar
unknown committed
5166 5167 5168 5169 5170
  if (save_priv)
    *save_priv=0;
  else
    save_priv= &dummy;

5171
  thd_proc_info(thd, "checking permissions");
5172
  if ((!db || !db[0]) && !thd->db && !dont_check_global_grants)
unknown's avatar
unknown committed
5173
  {
5174
    DBUG_PRINT("error",("No database"));
5175
    if (!no_errors)
unknown's avatar
unknown committed
5176 5177
      my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR),
                 MYF(0));                       /* purecov: tested */
unknown's avatar
unknown committed
5178
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
5179 5180
  }

5181 5182
  if (schema_db)
  {
5183
    if ((!(sctx->master_access & FILE_ACL) && (want_access & FILE_ACL)) ||
5184
        (want_access & ~(SELECT_ACL | EXTRA_ACL | FILE_ACL)))
5185 5186
    {
      if (!no_errors)
5187 5188
      {
        const char *db_name= db ? db : thd->db;
5189
        my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
5190 5191
                 sctx->priv_user, sctx->priv_host, db_name);
      }
5192 5193 5194 5195 5196 5197 5198 5199 5200
      DBUG_RETURN(TRUE);
    }
    else
    {
      *save_priv= SELECT_ACL;
      DBUG_RETURN(FALSE);
    }
  }

5201
  if ((sctx->master_access & want_access) == want_access)
unknown's avatar
unknown committed
5202
  {
5203 5204 5205 5206 5207
    /*
      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
    */
5208 5209
    db_access= sctx->db_access;
    if (!(sctx->master_access & SELECT_ACL) &&
unknown's avatar
unknown committed
5210
	(db && (!thd->db || db_is_pattern || strcmp(db,thd->db))))
5211 5212 5213
      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
5214
    DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
5215
  }
5216
  if (((want_access & ~sctx->master_access) & ~(DB_ACLS | EXTRA_ACL)) ||
5217
      (! db && dont_check_global_grants))
unknown's avatar
unknown committed
5218
  {						// We can never grant this
5219
    DBUG_PRINT("error",("No possible access"));
5220
    if (!no_errors)
5221
      my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
5222 5223
               sctx->priv_user,
               sctx->priv_host,
5224 5225 5226
               (thd->password ?
                ER(ER_YES) :
                ER(ER_NO)));                    /* purecov: tested */
unknown's avatar
unknown committed
5227
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
5228 5229 5230
  }

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

unknown's avatar
unknown committed
5233
  if (db && (!thd->db || db_is_pattern || strcmp(db,thd->db)))
5234 5235
    db_access= acl_get(sctx->host, sctx->ip, sctx->priv_user, db,
                       db_is_pattern);
unknown's avatar
unknown committed
5236
  else
5237
    db_access= sctx->db_access;
5238
  DBUG_PRINT("info",("db_access: %lu", db_access));
unknown's avatar
unknown committed
5239
  /* Remove SHOW attribute and access rights we already have */
5240
  want_access &= ~(sctx->master_access | EXTRA_ACL);
5241 5242
  DBUG_PRINT("info",("db_access: %lu  want_access: %lu",
                     db_access, want_access));
5243
  db_access= ((*save_priv=(db_access | sctx->master_access)) & want_access);
5244

unknown's avatar
unknown committed
5245
  if (db_access == want_access ||
5246
      (!dont_check_global_grants &&
5247
       !(want_access & ~(db_access | TABLE_ACLS | PROC_ACLS))))
unknown's avatar
unknown committed
5248
    DBUG_RETURN(FALSE);				/* Ok */
5249 5250

  DBUG_PRINT("error",("Access denied"));
5251
  if (!no_errors)
5252
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
5253
             sctx->priv_user, sctx->priv_host,
5254 5255 5256
             (db ? db : (thd->db ?
                         thd->db :
                         "unknown")));          /* purecov: tested */
unknown's avatar
unknown committed
5257
  DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
5258 5259 5260
}


5261 5262
static bool check_show_access(THD *thd, TABLE_LIST *table)
{
unknown's avatar
unknown committed
5263
  switch (get_schema_table_idx(table->schema_table)) {
5264 5265
  case SCH_SCHEMATA:
    return (specialflag & SPECIAL_SKIP_SHOW_DB) &&
unknown's avatar
unknown committed
5266
      check_global_access(thd, SHOW_DB_ACL);
5267 5268 5269 5270 5271

  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
  case SCH_TRIGGERS:
unknown's avatar
unknown committed
5272 5273 5274
  case SCH_EVENTS:
  {
    const char *dst_db_name= table->schema_select_lex->db;
5275

unknown's avatar
unknown committed
5276
    DBUG_ASSERT(dst_db_name);
5277

unknown's avatar
unknown committed
5278 5279 5280 5281
    if (check_access(thd, SELECT_ACL, dst_db_name,
                     &thd->col_access, FALSE, FALSE,
                     is_schema_db(dst_db_name)))
      return TRUE;
5282

unknown's avatar
unknown committed
5283 5284 5285 5286 5287 5288 5289
    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;
5290 5291
    }

unknown's avatar
unknown committed
5292 5293 5294
    return FALSE;
  }

5295 5296
  case SCH_COLUMNS:
  case SCH_STATISTICS:
unknown's avatar
unknown committed
5297 5298 5299
  {
    TABLE_LIST *dst_table;
    dst_table= (TABLE_LIST *) table->schema_select_lex->table_list.first;
5300

unknown's avatar
unknown committed
5301
    DBUG_ASSERT(dst_table);
5302

unknown's avatar
unknown committed
5303 5304 5305 5306 5307 5308
    if (check_access(thd, SELECT_ACL | EXTRA_ACL,
                     dst_table->db,
                     &dst_table->grant.privilege,
                     FALSE, FALSE,
                     test(dst_table->schema_table)))
      return FALSE;
5309

5310
    return (check_grant(thd, SELECT_ACL, dst_table, 2, UINT_MAX, FALSE));
unknown's avatar
unknown committed
5311 5312
  }
  default:
5313 5314 5315 5316 5317 5318 5319
    break;
  }

  return FALSE;
}


unknown's avatar
unknown committed
5320
/**
5321 5322
  Check the privilege for all used tables.

5323 5324 5325 5326 5327 5328
  @param    thd          Thread context
  @param    want_access  Privileges requested
  @param    tables       List of tables to be checked
  @param    number       Check at most this number of tables.
  @param    no_errors    FALSE/TRUE - report/don't report error to
                         the client (using my_error() call).
5329

unknown's avatar
unknown committed
5330
  @note
5331 5332 5333 5334 5335 5336
    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).

5337 5338
  @retval  FALSE   OK
  @retval  TRUE    Access denied
unknown's avatar
unknown committed
5339 5340
*/

5341
bool
unknown's avatar
unknown committed
5342
check_table_access(THD *thd, ulong want_access,TABLE_LIST *tables,
5343
		   uint number, bool no_errors)
unknown's avatar
unknown committed
5344
{
5345 5346
  TABLE_LIST *org_tables= tables;
  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
5347
  uint i= 0;
5348
  Security_context *sctx= thd->security_ctx, *backup_ctx= thd->security_ctx;
5349
  /*
unknown's avatar
unknown committed
5350 5351 5352
    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.
5353
  */
5354 5355
  for (; i < number && tables != first_not_own_table;
       tables= tables->next_global, i++)
unknown's avatar
unknown committed
5356
  {
5357 5358 5359 5360 5361
    if (tables->security_ctx)
      sctx= tables->security_ctx;
    else
      sctx= backup_ctx;

5362
    if (tables->schema_table && 
5363
        (want_access & ~(SELECT_ACL | EXTRA_ACL | FILE_ACL)))
5364 5365 5366
    {
      if (!no_errors)
        my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
5367
                 sctx->priv_user, sctx->priv_host,
5368
                 INFORMATION_SCHEMA_NAME.str);
5369 5370
      return TRUE;
    }
5371 5372 5373 5374 5375
    /*
       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
5376 5377 5378 5379 5380 5381 5382 5383 5384

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

      continue;
    }

5385
    if (tables->is_anonymous_derived_table() ||
5386
        (tables->table && (int)tables->table->s->tmp_table))
unknown's avatar
unknown committed
5387
      continue;
5388 5389
    thd->security_ctx= sctx;
    if ((sctx->master_access & want_access) ==
5390
        (want_access & ~EXTRA_ACL) &&
unknown's avatar
unknown committed
5391
	thd->db)
unknown's avatar
unknown committed
5392
      tables->grant.privilege= want_access;
unknown's avatar
unknown committed
5393
    else if (tables->db && thd->db && strcmp(tables->db, thd->db) == 0)
unknown's avatar
unknown committed
5394
    {
5395 5396 5397
      if (check_access(thd, want_access, tables->get_db_name(),
                       &tables->grant.privilege, 0, no_errors, 
                       test(tables->schema_table)))
5398
        goto deny;                            // Access denied
unknown's avatar
unknown committed
5399
    }
5400 5401 5402
    else if (check_access(thd, want_access, tables->get_db_name(),
                          &tables->grant.privilege, 0, no_errors, 
                          test(tables->schema_table)))
5403
      goto deny;
unknown's avatar
unknown committed
5404
  }
5405
  thd->security_ctx= backup_ctx;
5406
  return check_grant(thd,want_access & ~EXTRA_ACL,org_tables,
5407
		       test(want_access & EXTRA_ACL), number, no_errors);
5408 5409 5410
deny:
  thd->security_ctx= backup_ctx;
  return TRUE;
unknown's avatar
unknown committed
5411 5412
}

5413

5414
bool
5415 5416
check_routine_access(THD *thd, ulong want_access,char *db, char *name,
		     bool is_proc, bool no_errors)
5417 5418 5419 5420 5421
{
  TABLE_LIST tables[1];
  
  bzero((char *)tables, sizeof(TABLE_LIST));
  tables->db= db;
5422
  tables->table_name= tables->alias= name;
5423
  
unknown's avatar
unknown committed
5424 5425 5426 5427 5428 5429 5430
  /*
    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)
5431 5432
    tables->grant.privilege= want_access;
  else if (check_access(thd,want_access,db,&tables->grant.privilege,
unknown's avatar
unknown committed
5433
			0, no_errors, 0))
5434 5435
    return TRUE;
  
5436
    return check_grant_routine(thd, want_access, tables, is_proc, no_errors);
5437 5438
}

5439

unknown's avatar
unknown committed
5440 5441
/**
  Check if the routine has any of the routine privileges.
5442

unknown's avatar
unknown committed
5443 5444 5445
  @param thd	       Thread handler
  @param db           Database name
  @param name         Routine name
5446

unknown's avatar
unknown committed
5447
  @retval
5448
    0            ok
unknown's avatar
unknown committed
5449
  @retval
5450 5451 5452
    1            error
*/

5453 5454
bool check_some_routine_access(THD *thd, const char *db, const char *name,
                               bool is_proc)
5455 5456
{
  ulong save_priv;
5457
  if (thd->security_ctx->master_access & SHOW_PROC_ACLS)
5458
    return FALSE;
5459 5460 5461 5462 5463
  /*
    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) ||
5464 5465
      (save_priv & SHOW_PROC_ACLS))
    return FALSE;
5466
  return check_routine_level_acl(thd, db, name, is_proc);
5467 5468 5469
}


5470 5471 5472
/*
  Check if the given table has any of the asked privileges

unknown's avatar
unknown committed
5473 5474
  @param thd		 Thread handler
  @param want_access	 Bitmap of possible privileges to check for
5475

unknown's avatar
unknown committed
5476
  @retval
5477
    0  ok
unknown's avatar
unknown committed
5478
  @retval
5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492
    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,
5493 5494
                        &table->grant.privilege, 0, 1,
                        test(table->schema_table)) &&
Staale Smedseng's avatar
Staale Smedseng committed
5495
           !check_grant(thd, access, table, 0, 1, 1))
5496 5497 5498 5499 5500 5501 5502
        DBUG_RETURN(0);
    }
  }
  DBUG_PRINT("exit",("no matching access rights"));
  DBUG_RETURN(1);
}

unknown's avatar
unknown committed
5503
#endif /*NO_EMBEDDED_ACCESS_CHECKS*/
5504

5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537

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

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

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

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

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

unknown's avatar
unknown committed
5538 5539 5540 5541
/****************************************************************************
	Check stack size; Send error if there isn't enough stack to continue
****************************************************************************/

5542 5543
#ifndef EMBEDDED_LIBRARY

unknown's avatar
unknown committed
5544 5545 5546 5547 5548 5549
#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
5550 5551 5552 5553
#ifndef DBUG_OFF
long max_stack_used;
#endif

unknown's avatar
unknown committed
5554 5555
/**
  @note
5556 5557 5558 5559
  Note: The 'buf' parameter is necessary, even if it is unused here.
  - fix_fields functions has a "dummy" buffer large enough for the
    corresponding exec. (Thus we only have to check in fix_fields.)
  - Passing to check_stack_overrun() prevents the compiler from removing it.
unknown's avatar
unknown committed
5560
*/
5561
bool check_stack_overrun(THD *thd, long margin,
5562
			 uchar *buf __attribute__((unused)))
unknown's avatar
unknown committed
5563 5564
{
  long stack_used;
5565
  DBUG_ASSERT(thd == current_thd);
unknown's avatar
unknown committed
5566
  if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >=
5567
      (long) (my_thread_stack_size - margin))
unknown's avatar
unknown committed
5568
  {
5569 5570 5571 5572
    char ebuff[MYSQL_ERRMSG_SIZE];
    my_snprintf(ebuff, sizeof(ebuff), ER(ER_STACK_OVERRUN_NEED_MORE),
                stack_used, my_thread_stack_size, margin);
    my_message(ER_STACK_OVERRUN_NEED_MORE, ebuff, MYF(ME_FATALERROR));
5573
    thd->fatal_error();
unknown's avatar
unknown committed
5574 5575
    return 1;
  }
unknown's avatar
unknown committed
5576 5577 5578
#ifndef DBUG_OFF
  max_stack_used= max(max_stack_used, stack_used);
#endif
unknown's avatar
unknown committed
5579 5580
  return 0;
}
5581
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
5582 5583 5584 5585

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

5586
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
unknown's avatar
unknown committed
5587
{
5588
  Yacc_state *state= & current_thd->m_parser_state->m_yacc;
5589
  ulong old_info=0;
5590
  DBUG_ASSERT(state);
unknown's avatar
unknown committed
5591 5592
  if ((uint) *yystacksize >= MY_YACC_MAX)
    return 1;
5593
  if (!state->yacc_yyvs)
unknown's avatar
unknown committed
5594 5595
    old_info= *yystacksize;
  *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
5596
  if (!(state->yacc_yyvs= (uchar*)
5597
        my_realloc(state->yacc_yyvs,
5598 5599 5600
                   *yystacksize*sizeof(**yyvs),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
      !(state->yacc_yyss= (uchar*)
5601
        my_realloc(state->yacc_yyss,
5602 5603
                   *yystacksize*sizeof(**yyss),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
unknown's avatar
unknown committed
5604 5605
    return 1;
  if (old_info)
5606 5607 5608 5609 5610 5611 5612 5613
  {
    /*
      Only copy the old stack on the first call to my_yyoverflow(),
      when replacing a static stack (YYINITDEPTH) by a dynamic stack.
      For subsequent calls, my_realloc already did preserve the old stack.
    */
    memcpy(state->yacc_yyss, *yyss, old_info*sizeof(**yyss));
    memcpy(state->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs));
unknown's avatar
unknown committed
5614
  }
5615 5616
  *yyss= (short*) state->yacc_yyss;
  *yyvs= (YYSTYPE*) state->yacc_yyvs;
unknown's avatar
unknown committed
5617 5618 5619 5620
  return 0;
}


unknown's avatar
unknown committed
5621
/**
5622 5623 5624 5625
 Reset THD part responsible for command processing state.

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

unknown's avatar
unknown committed
5628
  @todo
5629 5630
   Make it a method of THD and align its name with the rest of
   reset/end/start/init methods.
unknown's avatar
unknown committed
5631
  @todo
5632 5633 5634 5635 5636 5637
   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");
5638
  DBUG_ASSERT(!thd->spcont); /* not for substatements of routines */
5639
  DBUG_ASSERT(! thd->in_sub_stmt);
5640
  thd->free_list= 0;
5641
  thd->select_number= 1;
5642 5643 5644 5645
  /*
    Those two lines below are theoretically unneeded as
    THD::cleanup_after_query() should take care of this already.
  */
5646
  thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
5647 5648 5649
  thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;

  thd->query_start_used= 0;
5650
  thd->is_fatal_error= thd->time_zone_used= 0;
5651 5652 5653 5654 5655
  /*
    Clear the status flag that are expected to be cleared at the
    beginning of each SQL statement.
  */
  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
5656 5657 5658 5659 5660 5661
  /*
    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
5662 5663
  {
    thd->options&= ~OPTION_KEEP_LOG;
5664
    thd->transaction.all.modified_non_trans_table= FALSE;
unknown's avatar
unknown committed
5665
  }
5666
  DBUG_ASSERT(thd->security_ctx== &thd->main_security_ctx);
unknown's avatar
unknown committed
5667
  thd->thread_specific_used= FALSE;
5668 5669

  if (opt_bin_log)
5670
  {
5671 5672
    reset_dynamic(&thd->user_var_events);
    thd->user_var_events_alloc= thd->mem_root;
5673
  }
5674 5675 5676 5677 5678 5679
  thd->clear_error();
  thd->main_da.reset_diagnostics_area();
  thd->total_warn_count=0;			// Warnings for this query
  thd->rand_used= 0;
  thd->sent_row_count= thd->examined_row_count= 0;

5680 5681 5682 5683
  /*
    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
5684 5685
  thd->reset_current_stmt_binlog_row_based();

5686 5687 5688 5689
  DBUG_PRINT("debug",
             ("current_stmt_binlog_row_based: %d",
              thd->current_stmt_binlog_row_based));

unknown's avatar
unknown committed
5690 5691 5692
  DBUG_VOID_RETURN;
}

5693

5694 5695 5696 5697 5698 5699 5700 5701
/**
  Resets the lex->current_select object.
  @note It is assumed that lex->current_select != NULL

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

5702 5703 5704
void
mysql_init_select(LEX *lex)
{
unknown's avatar
unknown committed
5705
  SELECT_LEX *select_lex= lex->current_select;
unknown's avatar
unknown committed
5706
  select_lex->init_select();
5707
  lex->wild= 0;
5708 5709
  if (select_lex == &lex->select_lex)
  {
5710
    DBUG_ASSERT(lex->result == 0);
5711 5712
    lex->exchange= 0;
  }
5713 5714
}

5715

5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727
/**
  Used to allocate a new SELECT_LEX object on the current thd mem_root and
  link it into the relevant lists.

  This function is always followed by mysql_init_select.

  @see mysql_init_select

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

unknown's avatar
unknown committed
5728
bool
unknown's avatar
unknown committed
5729
mysql_new_select(LEX *lex, bool move_down)
5730
{
unknown's avatar
unknown committed
5731
  SELECT_LEX *select_lex;
5732
  THD *thd= lex->thd;
unknown's avatar
unknown committed
5733 5734
  DBUG_ENTER("mysql_new_select");

5735
  if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
unknown's avatar
unknown committed
5736
    DBUG_RETURN(1);
5737
  select_lex->select_number= ++thd->select_number;
unknown's avatar
unknown committed
5738
  select_lex->parent_lex= lex; /* Used in init_query. */
unknown's avatar
unknown committed
5739 5740
  select_lex->init_query();
  select_lex->init_select();
unknown's avatar
unknown committed
5741
  lex->nest_level++;
unknown's avatar
unknown committed
5742 5743 5744 5745 5746
  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
5747
  select_lex->nest_level= lex->nest_level;
5748 5749 5750
  /*
    Don't evaluate this subquery during statement prepare even if
    it's a constant one. The flag is switched off in the end of
5751
    mysqld_stmt_prepare.
5752
  */
unknown's avatar
unknown committed
5753
  if (thd->stmt_arena->is_stmt_prepare())
5754
    select_lex->uncacheable|= UNCACHEABLE_PREPARE;
unknown's avatar
unknown committed
5755 5756
  if (move_down)
  {
unknown's avatar
unknown committed
5757
    SELECT_LEX_UNIT *unit;
5758
    lex->subqueries= TRUE;
unknown's avatar
unknown committed
5759
    /* first select_lex of subselect or derived table */
5760
    if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
unknown's avatar
unknown committed
5761
      DBUG_RETURN(1);
unknown's avatar
unknown committed
5762

unknown's avatar
unknown committed
5763 5764
    unit->init_query();
    unit->init_select();
5765
    unit->thd= thd;
unknown's avatar
unknown committed
5766
    unit->include_down(lex->current_select);
unknown's avatar
unknown committed
5767 5768
    unit->link_next= 0;
    unit->link_prev= 0;
5769
    unit->return_to= lex->current_select;
unknown's avatar
unknown committed
5770
    select_lex->include_down(unit);
5771 5772 5773 5774 5775
    /*
      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
5776 5777
  }
  else
unknown's avatar
unknown committed
5778
  {
unknown's avatar
VIEW  
unknown committed
5779 5780
    if (lex->current_select->order_list.first && !lex->current_select->braces)
    {
unknown's avatar
unknown committed
5781
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY");
unknown's avatar
unknown committed
5782
      DBUG_RETURN(1);
unknown's avatar
VIEW  
unknown committed
5783
    }
5784
    select_lex->include_neighbour(lex->current_select);
5785 5786 5787 5788 5789
    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
5790
  }
unknown's avatar
unknown committed
5791

5792
  select_lex->master_unit()->global_parameters= select_lex;
5793
  select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
5794
  lex->current_select= select_lex;
5795 5796 5797 5798 5799
  /*
    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
5800
  DBUG_RETURN(0);
5801
}
unknown's avatar
unknown committed
5802

unknown's avatar
unknown committed
5803
/**
5804 5805
  Create a select to return the same output as 'SELECT @@var_name'.

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

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

unknown's avatar
unknown committed
5810
  @param var_name		Variable name
5811 5812 5813 5814
*/

void create_select_for_variable(const char *var_name)
{
5815
  THD *thd;
5816
  LEX *lex;
5817
  LEX_STRING tmp, null_lex_string;
5818 5819
  Item *var;
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
5820
  DBUG_ENTER("create_select_for_variable");
5821 5822

  thd= current_thd;
unknown's avatar
unknown committed
5823
  lex= thd->lex;
5824 5825 5826 5827
  mysql_init_select(lex);
  lex->sql_command= SQLCOM_SELECT;
  tmp.str= (char*) var_name;
  tmp.length=strlen(var_name);
5828
  bzero((char*) &null_lex_string.str, sizeof(null_lex_string));
5829 5830 5831 5832
  /*
    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
5833 5834 5835 5836 5837 5838
  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);
  }
5839 5840 5841
  DBUG_VOID_RETURN;
}

5842

unknown's avatar
unknown committed
5843 5844
void mysql_init_multi_delete(LEX *lex)
{
unknown's avatar
unknown committed
5845
  lex->sql_command=  SQLCOM_DELETE_MULTI;
unknown's avatar
unknown committed
5846
  mysql_init_select(lex);
5847 5848
  lex->select_lex.select_limit= 0;
  lex->unit.select_limit_cnt= HA_POS_ERROR;
unknown's avatar
unknown committed
5849
  lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list);
5850
  lex->lock_option= TL_READ_DEFAULT;
unknown's avatar
VIEW  
unknown committed
5851 5852
  lex->query_tables= 0;
  lex->query_tables_last= &lex->query_tables;
unknown's avatar
unknown committed
5853
}
unknown's avatar
unknown committed
5854

5855

5856 5857 5858 5859
/*
  When you modify mysql_parse(), you may need to mofify
  mysql_test_parse_for_slave() in this same file.
*/
unknown's avatar
unknown committed
5860

5861 5862
/**
  Parse a query.
unknown's avatar
unknown committed
5863 5864 5865 5866 5867 5868

  @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.
5869 5870 5871 5872
*/

void mysql_parse(THD *thd, const char *inBuf, uint length,
                 const char ** found_semicolon)
unknown's avatar
unknown committed
5873 5874
{
  DBUG_ENTER("mysql_parse");
5875 5876 5877

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

5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895
  /*
    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);
5896

5897
  if (query_cache_send_result_to_client(thd, (char*) inBuf, length) <= 0)
unknown's avatar
unknown committed
5898
  {
unknown's avatar
unknown committed
5899
    LEX *lex= thd->lex;
5900

5901 5902
    sp_cache_flush_obsolete(&thd->sp_proc_cache);
    sp_cache_flush_obsolete(&thd->sp_func_cache);
5903

5904
    Parser_state parser_state(thd, inBuf, length);
5905

5906
    bool err= parse_sql(thd, & parser_state, NULL);
5907
    *found_semicolon= parser_state.m_lip.found_semicolon;
5908

5909
    if (!err)
unknown's avatar
unknown committed
5910
    {
unknown's avatar
unknown committed
5911
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5912
      if (mqh_used && thd->user_connect &&
5913
	  check_mqh(thd, lex->sql_command))
5914 5915 5916 5917
      {
	thd->net.error = 0;
      }
      else
unknown's avatar
unknown committed
5918
#endif
5919
      {
5920
	if (! thd->is_error())
unknown's avatar
unknown committed
5921
	{
5922 5923 5924 5925 5926 5927 5928 5929 5930 5931
          /*
            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.
          */
5932 5933
          if (*found_semicolon &&
              (thd->query_length= (ulong)(*found_semicolon - thd->query)))
5934 5935
            thd->query_length--;
          /* Actually execute the query */
5936 5937 5938 5939 5940
          if (*found_semicolon)
          {
            lex->safe_to_cache_query= 0;
            thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
          }
5941 5942
          lex->set_trg_event_type_for_tables();
          mysql_execute_command(thd);
unknown's avatar
unknown committed
5943
	}
5944
      }
unknown's avatar
unknown committed
5945 5946
    }
    else
5947
    {
5948
      DBUG_ASSERT(thd->is_error());
5949
      DBUG_PRINT("info",("Command aborted. Fatal_error: %d",
5950
			 thd->is_fatal_error));
5951 5952

      query_cache_abort(&thd->net);
5953
    }
5954 5955 5956 5957 5958 5959
    if (thd->lex->sphead)
    {
      delete thd->lex->sphead;
      thd->lex->sphead= 0;
    }
    lex->unit.cleanup();
5960
    thd_proc_info(thd, "freeing items");
5961
    thd->end_statement();
5962
    thd->cleanup_after_query();
5963
    DBUG_ASSERT(thd->change_list.is_empty());
unknown's avatar
unknown committed
5964
  }
5965 5966 5967 5968 5969 5970
  else
  {
    /* There are no multi queries in the cache. */
    *found_semicolon= NULL;
  }

unknown's avatar
unknown committed
5971 5972 5973 5974
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
5975
#ifdef HAVE_REPLICATION
5976 5977 5978 5979
/*
  Usable by the replication SQL thread only: just parse a query to know if it
  can be ignored because of replicate-*-table rules.

unknown's avatar
unknown committed
5980
  @retval
5981
    0	cannot be ignored
unknown's avatar
unknown committed
5982
  @retval
5983 5984 5985 5986 5987
    1	can be ignored
*/

bool mysql_test_parse_for_slave(THD *thd, char *inBuf, uint length)
{
unknown's avatar
unknown committed
5988
  LEX *lex= thd->lex;
5989
  bool error= 0;
unknown's avatar
unknown committed
5990
  DBUG_ENTER("mysql_test_parse_for_slave");
5991

5992
  Parser_state parser_state(thd, inBuf, length);
5993 5994 5995
  lex_start(thd);
  mysql_reset_thd_for_next_command(thd);

5996
  if (!parse_sql(thd, & parser_state, NULL) &&
5997
      all_tables_not_ok(thd,(TABLE_LIST*) lex->select_lex.table_list.first))
unknown's avatar
unknown committed
5998
    error= 1;                  /* Ignore question */
5999
  thd->end_statement();
6000
  thd->cleanup_after_query();
unknown's avatar
unknown committed
6001
  DBUG_RETURN(error);
6002
}
unknown's avatar
unknown committed
6003
#endif
unknown's avatar
unknown committed
6004

6005

unknown's avatar
unknown committed
6006

unknown's avatar
unknown committed
6007 6008 6009 6010 6011 6012
/**
  Store field definition for create.

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

6014
bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum_field_types type,
unknown's avatar
unknown committed
6015
		       char *length, char *decimals,
6016
		       uint type_modifier,
6017 6018
		       Item *default_value, Item *on_update_value,
                       LEX_STRING *comment,
6019 6020
		       char *change,
                       List<String> *interval_list, CHARSET_INFO *cs,
unknown's avatar
unknown committed
6021
		       uint uint_geom_type)
unknown's avatar
unknown committed
6022
{
unknown's avatar
unknown committed
6023
  register Create_field *new_field;
unknown's avatar
unknown committed
6024
  LEX  *lex= thd->lex;
unknown's avatar
unknown committed
6025 6026
  DBUG_ENTER("add_field_to_list");

6027 6028
  if (check_string_char_length(field_name, "", NAME_CHAR_LEN,
                               system_charset_info, 1))
unknown's avatar
unknown committed
6029
  {
6030
    my_error(ER_TOO_LONG_IDENT, MYF(0), field_name->str); /* purecov: inspected */
unknown's avatar
unknown committed
6031 6032 6033 6034
    DBUG_RETURN(1);				/* purecov: inspected */
  }
  if (type_modifier & PRI_KEY_FLAG)
  {
6035
    Key *key;
unknown's avatar
unknown committed
6036
    lex->col_list.push_back(new Key_part_spec(field_name->str, 0));
6037 6038 6039 6040
    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
6041 6042 6043 6044
    lex->col_list.empty();
  }
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
  {
6045
    Key *key;
unknown's avatar
unknown committed
6046
    lex->col_list.push_back(new Key_part_spec(field_name->str, 0));
6047 6048 6049 6050
    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
6051 6052 6053
    lex->col_list.empty();
  }

6054
  if (default_value)
unknown's avatar
unknown committed
6055
  {
6056
    /* 
unknown's avatar
unknown committed
6057 6058
      Default value should be literal => basic constants =>
      no need fix_fields()
6059 6060 6061
      
      We allow only one function as part of default value - 
      NOW() as default for TIMESTAMP type.
6062
    */
6063 6064
    if (default_value->type() == Item::FUNC_ITEM && 
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
6065
         type == MYSQL_TYPE_TIMESTAMP))
6066
    {
6067
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
6068 6069 6070
      DBUG_RETURN(1);
    }
    else if (default_value->type() == Item::NULL_ITEM)
unknown's avatar
unknown committed
6071
    {
6072
      default_value= 0;
6073 6074 6075
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
	  NOT_NULL_FLAG)
      {
6076
	my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
6077 6078 6079 6080 6081
	DBUG_RETURN(1);
      }
    }
    else if (type_modifier & AUTO_INCREMENT_FLAG)
    {
6082
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
unknown's avatar
unknown committed
6083 6084 6085
      DBUG_RETURN(1);
    }
  }
6086

6087
  if (on_update_value && type != MYSQL_TYPE_TIMESTAMP)
6088
  {
6089
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
6090 6091
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
6092

6093
  if (type == MYSQL_TYPE_TIMESTAMP && length)
6094 6095 6096 6097 6098
  {
    /* 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
6099
    char buf[32];
6100
    my_snprintf(buf, sizeof(buf), "TIMESTAMP(%s)", length);
6101
    WARN_DEPRECATED(thd, "6.0", buf, "'TIMESTAMP'");
6102 6103
  }

unknown's avatar
unknown committed
6104
  if (!(new_field= new Create_field()) ||
6105
      new_field->init(thd, field_name->str, type, length, decimals, type_modifier,
6106 6107
                      default_value, on_update_value, comment, change,
                      interval_list, cs, uint_geom_type))
unknown's avatar
unknown committed
6108
    DBUG_RETURN(1);
unknown's avatar
unknown committed
6109

6110
  lex->alter_info.create_list.push_back(new_field);
unknown's avatar
unknown committed
6111 6112 6113 6114
  lex->last_field=new_field;
  DBUG_RETURN(0);
}

6115

unknown's avatar
unknown committed
6116
/** Store position for column in ALTER TABLE .. ADD column. */
unknown's avatar
unknown committed
6117 6118 6119

void store_position_for_column(const char *name)
{
6120
  current_thd->lex->last_field->after=my_const_cast(char*) (name);
unknown's avatar
unknown committed
6121 6122 6123
}

bool
unknown's avatar
unknown committed
6124
add_proc_to_list(THD* thd, Item *item)
unknown's avatar
unknown committed
6125 6126 6127 6128
{
  ORDER *order;
  Item	**item_ptr;

unknown's avatar
unknown committed
6129
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*))))
unknown's avatar
unknown committed
6130 6131 6132 6133 6134
    return 1;
  item_ptr = (Item**) (order+1);
  *item_ptr= item;
  order->item=item_ptr;
  order->free_me=0;
6135
  thd->lex->proc_list.link_in_list((uchar*) order,(uchar**) &order->next);
unknown's avatar
unknown committed
6136 6137 6138 6139
  return 0;
}


unknown's avatar
unknown committed
6140 6141 6142
/**
  save order by and tables in own lists.
*/
unknown's avatar
unknown committed
6143

unknown's avatar
unknown committed
6144
bool add_to_list(THD *thd, SQL_LIST &list,Item *item,bool asc)
unknown's avatar
unknown committed
6145 6146 6147
{
  ORDER *order;
  DBUG_ENTER("add_to_list");
unknown's avatar
unknown committed
6148
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER))))
unknown's avatar
unknown committed
6149
    DBUG_RETURN(1);
unknown's avatar
unknown committed
6150 6151
  order->item_ptr= item;
  order->item= &order->item_ptr;
unknown's avatar
unknown committed
6152 6153 6154
  order->asc = asc;
  order->free_me=0;
  order->used=0;
6155
  order->counter_used= 0;
6156
  list.link_in_list((uchar*) order,(uchar**) &order->next);
unknown's avatar
unknown committed
6157 6158 6159 6160
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174
/**
  Add a table to list of used tables.

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

  @retval
unknown's avatar
unknown committed
6175
      0		Error
unknown's avatar
unknown committed
6176 6177
  @retval
    \#	Pointer to TABLE_LIST element added to the total table list
unknown's avatar
unknown committed
6178 6179
*/

unknown's avatar
unknown committed
6180 6181
TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
					     Table_ident *table,
6182
					     LEX_STRING *alias,
unknown's avatar
unknown committed
6183 6184
					     ulong table_options,
					     thr_lock_type lock_type,
unknown's avatar
unknown committed
6185
					     List<Index_hint> *index_hints_arg,
unknown's avatar
unknown committed
6186
                                             LEX_STRING *option)
unknown's avatar
unknown committed
6187 6188
{
  register TABLE_LIST *ptr;
unknown's avatar
unknown committed
6189
  TABLE_LIST *previous_table_ref; /* The table preceding the current one. */
unknown's avatar
unknown committed
6190
  char *alias_str;
6191
  LEX *lex= thd->lex;
unknown's avatar
unknown committed
6192
  DBUG_ENTER("add_table_to_list");
6193
  LINT_INIT(previous_table_ref);
unknown's avatar
unknown committed
6194 6195 6196 6197

  if (!table)
    DBUG_RETURN(0);				// End of memory
  alias_str= alias ? alias->str : table->table.str;
6198 6199
  if (!test(table_options & TL_OPTION_ALIAS) && 
      check_table_name(table->table.str, table->table.length))
unknown's avatar
unknown committed
6200
  {
6201
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
unknown's avatar
unknown committed
6202 6203
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
6204 6205

  if (table->is_derived_table() == FALSE && table->db.str &&
6206
      check_db_name(&table->db))
unknown's avatar
unknown committed
6207 6208 6209 6210
  {
    my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
6211 6212

  if (!alias)					/* Alias is case sensitive */
6213 6214 6215
  {
    if (table->sel)
    {
unknown's avatar
unknown committed
6216 6217
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
                 ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
6218 6219
      DBUG_RETURN(0);
    }
6220
    if (!(alias_str= (char*) thd->memdup(alias_str,table->table.length+1)))
unknown's avatar
unknown committed
6221
      DBUG_RETURN(0);
6222
  }
unknown's avatar
unknown committed
6223
  if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST))))
unknown's avatar
unknown committed
6224
    DBUG_RETURN(0);				/* purecov: inspected */
unknown's avatar
unknown committed
6225
  if (table->db.str)
6226 6227 6228 6229
  {
    ptr->db= table->db.str;
    ptr->db_length= table->db.length;
  }
6230
  else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
unknown's avatar
unknown committed
6231
    DBUG_RETURN(0);
unknown's avatar
unknown committed
6232

6233
  ptr->alias= alias_str;
6234
  if (lower_case_table_names && table->table.length)
6235
    table->table.length= my_casedn_str(files_charset_info, table->table.str);
6236 6237
  ptr->table_name=table->table.str;
  ptr->table_name_length=table->table.length;
6238
  ptr->lock_type=   lock_type;
unknown's avatar
unknown committed
6239 6240
  ptr->updating=    test(table_options & TL_OPTION_UPDATING);
  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
unknown's avatar
unknown committed
6241
  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
6242
  ptr->derived=	    table->sel;
6243
  if (!ptr->derived && !my_strcasecmp(system_charset_info, ptr->db,
6244
                                      INFORMATION_SCHEMA_NAME.str))
6245
  {
6246
    ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, ptr->table_name);
6247 6248
    if (!schema_table ||
        (schema_table->hidden && 
unknown's avatar
unknown committed
6249
         ((sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0 || 
6250 6251 6252
          /*
            this check is used for show columns|keys from I_S hidden table
          */
unknown's avatar
unknown committed
6253 6254
          lex->sql_command == SQLCOM_SHOW_FIELDS ||
          lex->sql_command == SQLCOM_SHOW_KEYS)))
6255
    {
unknown's avatar
unknown committed
6256
      my_error(ER_UNKNOWN_TABLE, MYF(0),
6257
               ptr->table_name, INFORMATION_SCHEMA_NAME.str);
6258 6259
      DBUG_RETURN(0);
    }
6260
    ptr->schema_table_name= ptr->table_name;
6261 6262
    ptr->schema_table= schema_table;
  }
6263
  ptr->select_lex=  lex->current_select;
unknown's avatar
unknown committed
6264
  ptr->cacheable_table= 1;
6265
  ptr->index_hints= index_hints_arg;
unknown's avatar
unknown committed
6266
  ptr->option= option ? option->str : 0;
unknown's avatar
unknown committed
6267
  /* check that used name is unique */
6268
  if (lock_type != TL_IGNORE)
unknown's avatar
unknown committed
6269
  {
unknown's avatar
unknown committed
6270 6271 6272 6273
    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
6274
	 tables ;
unknown's avatar
VIEW  
unknown committed
6275
	 tables=tables->next_local)
unknown's avatar
unknown committed
6276
    {
6277 6278
      if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
	  !strcmp(ptr->db, tables->db))
unknown's avatar
unknown committed
6279
      {
6280
	my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
unknown's avatar
unknown committed
6281 6282
	DBUG_RETURN(0);				/* purecov: tested */
      }
unknown's avatar
unknown committed
6283 6284
    }
  }
unknown's avatar
unknown committed
6285 6286 6287
  /* Store the table reference preceding the current one. */
  if (table_list.elements > 0)
  {
6288 6289 6290
    /*
      table_list.next points to the last inserted TABLE_LIST->next_local'
      element
6291
      We don't use the offsetof() macro here to avoid warnings from gcc
6292
    */
6293 6294 6295
    previous_table_ref= (TABLE_LIST*) ((char*) table_list.next -
                                       ((char*) &(ptr->next_local) -
                                        (char*) ptr));
6296 6297 6298 6299 6300 6301 6302 6303
    /*
      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
6304
  }
6305

unknown's avatar
unknown committed
6306 6307 6308 6309 6310 6311
  /*
    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'.
  */
6312
  table_list.link_in_list((uchar*) ptr, (uchar**) &ptr->next_local);
unknown's avatar
unknown committed
6313
  ptr->next_name_resolution_table= NULL;
6314
  /* Link table in global list (all used tables) */
6315
  lex->add_to_query_tables(ptr);
unknown's avatar
unknown committed
6316 6317 6318
  DBUG_RETURN(ptr);
}

unknown's avatar
unknown committed
6319

unknown's avatar
unknown committed
6320 6321
/**
  Initialize a new table list for a nested join.
6322

6323 6324 6325 6326 6327 6328 6329 6330
    The function initializes a structure of the TABLE_LIST type
    for a nested join. It sets up its nested join list as empty.
    The created structure is added to the front of the current
    join list in the st_select_lex object. Then the function
    changes the current nest level for joins to refer to the newly
    created empty list after having saved the info on the old level
    in the initialized structure.

unknown's avatar
unknown committed
6331 6332 6333 6334 6335 6336
  @param thd         current thread

  @retval
    0   if success
  @retval
    1   otherwise
6337 6338 6339 6340 6341 6342 6343
*/

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

6345 6346
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
6347
    DBUG_RETURN(1);
6348
  nested_join= ptr->nested_join=
6349
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
6350

6351 6352 6353
  join_list->push_front(ptr);
  ptr->embedding= embedding;
  ptr->join_list= join_list;
6354
  ptr->alias= (char*) "(nested_join)";
6355 6356 6357 6358 6359 6360 6361
  embedding= ptr;
  join_list= &nested_join->join_list;
  join_list->empty();
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
6362 6363
/**
  End a nested join table list.
6364 6365 6366

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

unknown's avatar
unknown committed
6369 6370 6371 6372 6373
  @param thd         current thread

  @return
    - Pointer to TABLE_LIST element added to the total table list, if success
    - 0, otherwise
6374 6375 6376 6377 6378
*/

TABLE_LIST *st_select_lex::end_nested_join(THD *thd)
{
  TABLE_LIST *ptr;
6379
  NESTED_JOIN *nested_join;
6380
  DBUG_ENTER("end_nested_join");
6381

unknown's avatar
unknown committed
6382
  DBUG_ASSERT(embedding);
6383 6384 6385
  ptr= embedding;
  join_list= ptr->join_list;
  embedding= ptr->embedding;
6386
  nested_join= ptr->nested_join;
6387 6388 6389 6390 6391 6392 6393 6394 6395
  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;
  }
6396
  else if (nested_join->join_list.elements == 0)
unknown's avatar
unknown committed
6397 6398
  {
    join_list->pop();
6399
    ptr= 0;                                     // return value
unknown's avatar
unknown committed
6400
  }
6401 6402 6403 6404
  DBUG_RETURN(ptr);
}


unknown's avatar
unknown committed
6405 6406
/**
  Nest last join operation.
6407 6408 6409

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

unknown's avatar
unknown committed
6410
  @param thd         current thread
6411

unknown's avatar
unknown committed
6412
  @retval
6413
    0  Error
unknown's avatar
unknown committed
6414 6415
  @retval
    \#  Pointer to TABLE_LIST element created for the new nested join
6416 6417 6418 6419 6420 6421
*/

TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
6422
  List<TABLE_LIST> *embedded_list;
6423
  DBUG_ENTER("nest_last_join");
6424

6425 6426
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
6427
    DBUG_RETURN(0);
6428
  nested_join= ptr->nested_join=
6429
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
6430

6431 6432
  ptr->embedding= embedding;
  ptr->join_list= join_list;
6433
  ptr->alias= (char*) "(nest_last_join)";
6434
  embedded_list= &nested_join->join_list;
6435
  embedded_list->empty();
6436 6437

  for (uint i=0; i < 2; i++)
6438 6439 6440 6441 6442
  {
    TABLE_LIST *table= join_list->pop();
    table->join_list= embedded_list;
    table->embedding= ptr;
    embedded_list->push_back(table);
unknown's avatar
unknown committed
6443 6444 6445 6446 6447 6448 6449
    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
6450 6451
      if (prev_join_using)
        ptr->join_using_fields= prev_join_using;
unknown's avatar
unknown committed
6452
    }
6453 6454 6455 6456 6457 6458 6459
  }
  join_list->push_front(ptr);
  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
  DBUG_RETURN(ptr);
}


unknown's avatar
unknown committed
6460 6461
/**
  Add a table to the current join list.
6462 6463 6464 6465 6466 6467

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

unknown's avatar
unknown committed
6468 6469 6470
  @param table       the table to add

  @return
6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483
    None
*/

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


unknown's avatar
unknown committed
6484 6485
/**
  Convert a right join into equivalent left join.
6486 6487

    The function takes the current join list t[0],t[1] ... and
6488 6489 6490 6491 6492 6493
    effectively converts it into the list t[1],t[0] ...
    Although the outer_join flag for the new nested table contains
    JOIN_TYPE_RIGHT, it will be handled as the inner table of a left join
    operation.

  EXAMPLES
unknown's avatar
unknown committed
6494
  @verbatim
6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505
    SELECT * FROM t1 RIGHT JOIN t2 ON on_expr =>
      SELECT * FROM t2 LEFT JOIN t1 ON on_expr

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

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

    SELECT * FROM t1 LEFT JOIN t2 ON on_expr1 RIGHT JOIN t3  ON on_expr2 =>
      SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1
unknown's avatar
unknown committed
6506
   @endverbatim
6507

unknown's avatar
unknown committed
6508
  @param thd         current thread
6509

unknown's avatar
unknown committed
6510 6511 6512
  @return
    - Pointer to the table representing the inner table, if success
    - 0, otherwise
6513 6514
*/

6515
TABLE_LIST *st_select_lex::convert_right_join()
6516 6517
{
  TABLE_LIST *tab2= join_list->pop();
6518
  TABLE_LIST *tab1= join_list->pop();
6519 6520 6521 6522 6523 6524 6525 6526 6527
  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
6528 6529
/**
  Set lock for all tables in current select level.
unknown's avatar
unknown committed
6530

unknown's avatar
unknown committed
6531
  @param lock_type			Lock to set for tables
unknown's avatar
unknown committed
6532

unknown's avatar
unknown committed
6533
  @note
unknown's avatar
unknown committed
6534 6535 6536 6537 6538
    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
6539
void st_select_lex::set_lock_for_tables(thr_lock_type lock_type)
unknown's avatar
unknown committed
6540 6541 6542 6543 6544
{
  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
6545 6546 6547
  for (TABLE_LIST *tables= (TABLE_LIST*) table_list.first;
       tables;
       tables= tables->next_local)
unknown's avatar
unknown committed
6548 6549 6550 6551 6552 6553 6554
  {
    tables->lock_type= lock_type;
    tables->updating=  for_update;
  }
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
6555

unknown's avatar
unknown committed
6556 6557
/**
  Create a fake SELECT_LEX for a unit.
unknown's avatar
unknown committed
6558 6559 6560 6561

    The method create a fake SELECT_LEX object for a unit.
    This object is created for any union construct containing a union
    operation and also for any single select union construct of the form
unknown's avatar
unknown committed
6562
    @verbatim
unknown's avatar
unknown committed
6563
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ... 
unknown's avatar
unknown committed
6564
    @endvarbatim
unknown's avatar
unknown committed
6565
    or of the form
unknown's avatar
unknown committed
6566
    @varbatim
unknown's avatar
unknown committed
6567
    (SELECT ... ORDER BY LIMIT n) ORDER BY ...
unknown's avatar
unknown committed
6568
    @endvarbatim
unknown's avatar
unknown committed
6569
  
unknown's avatar
unknown committed
6570 6571 6572
  @param thd_arg		   thread handle

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

unknown's avatar
unknown committed
6576
  @retval
unknown's avatar
unknown committed
6577
    1     on failure to create the object
unknown's avatar
unknown committed
6578
  @retval
unknown's avatar
unknown committed
6579 6580 6581
    0     on success
*/

unknown's avatar
unknown committed
6582
bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg)
unknown's avatar
unknown committed
6583 6584 6585 6586
{
  SELECT_LEX *first_sl= first_select();
  DBUG_ENTER("add_fake_select_lex");
  DBUG_ASSERT(!fake_select_lex);
unknown's avatar
unknown committed
6587

unknown's avatar
unknown committed
6588
  if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX()))
unknown's avatar
unknown committed
6589 6590 6591 6592
      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
6593
  fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */
unknown's avatar
unknown committed
6594 6595
  fake_select_lex->make_empty_select();
  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
6596 6597
  fake_select_lex->select_limit= 0;

unknown's avatar
unknown committed
6598
  fake_select_lex->context.outer_context=first_sl->context.outer_context;
6599 6600 6601
  /* 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
6602

6603
  if (!is_union())
unknown's avatar
unknown committed
6604 6605 6606 6607 6608 6609 6610 6611 6612
  {
    /* 
      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
6613
    thd_arg->lex->current_select= fake_select_lex;
unknown's avatar
unknown committed
6614
  }
unknown's avatar
unknown committed
6615
  thd_arg->lex->pop_context();
unknown's avatar
unknown committed
6616 6617 6618
  DBUG_RETURN(0);
}

6619

unknown's avatar
unknown committed
6620
/**
6621 6622
  Push a new name resolution context for a JOIN ... ON clause to the
  context stack of a query block.
unknown's avatar
unknown committed
6623 6624

    Create a new name resolution context for a JOIN ... ON clause,
6625 6626 6627
    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
6628

unknown's avatar
unknown committed
6629 6630 6631 6632 6633
  @param thd       pointer to current thread
  @param left_op   left  operand of the JOIN
  @param right_op  rigth operand of the JOIN

  @retval
6634
    FALSE  if all is OK
unknown's avatar
unknown committed
6635
  @retval
6636
    TRUE   if a memory allocation error occured
unknown's avatar
unknown committed
6637 6638
*/

6639 6640 6641
bool
push_new_name_resolution_context(THD *thd,
                                 TABLE_LIST *left_op, TABLE_LIST *right_op)
unknown's avatar
unknown committed
6642 6643
{
  Name_resolution_context *on_context;
6644
  if (!(on_context= new (thd->mem_root) Name_resolution_context))
6645
    return TRUE;
unknown's avatar
unknown committed
6646 6647 6648 6649 6650
  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();
6651
  return thd->lex->push_context(on_context);
unknown's avatar
unknown committed
6652 6653 6654
}


unknown's avatar
unknown committed
6655
/**
unknown's avatar
unknown committed
6656 6657 6658 6659
  Add an ON condition to the second operand of a JOIN ... ON.

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

unknown's avatar
unknown committed
6660 6661
  @param b     the second operand of a JOIN ... ON
  @param expr  the condition to be added to the ON clause
unknown's avatar
unknown committed
6662

unknown's avatar
unknown committed
6663
  @retval
unknown's avatar
unknown committed
6664
    FALSE  if there was some error
unknown's avatar
unknown committed
6665
  @retval
unknown's avatar
unknown committed
6666 6667 6668 6669
    TRUE   if all is OK
*/

void add_join_on(TABLE_LIST *b, Item *expr)
unknown's avatar
unknown committed
6670
{
6671
  if (expr)
6672
  {
6673
    if (!b->on_expr)
unknown's avatar
unknown committed
6674
      b->on_expr= expr;
6675 6676
    else
    {
unknown's avatar
unknown committed
6677 6678 6679 6680 6681 6682
      /*
        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);
6683 6684
    }
    b->on_expr->top_level_item();
6685
  }
unknown's avatar
unknown committed
6686 6687 6688
}


unknown's avatar
unknown committed
6689
/**
unknown's avatar
unknown committed
6690 6691
  Mark that there is a NATURAL JOIN or JOIN ... USING between two
  tables.
6692

unknown's avatar
unknown committed
6693 6694 6695 6696 6697 6698 6699 6700 6701 6702
    This function marks that table b should be joined with a either via
    a NATURAL JOIN or via JOIN ... USING. Both join types are special
    cases of each other, so we treat them together. The function
    setup_conds() creates a list of equal condition between all fields
    of the same name for NATURAL JOIN or the fields in 'using_fields'
    for JOIN ... USING. The list of equality conditions is stored
    either in b->on_expr, or in JOIN::conds, depending on whether there
    was an outer join.

  EXAMPLE
unknown's avatar
unknown committed
6703
  @verbatim
6704 6705 6706
    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
6707

unknown's avatar
unknown committed
6708 6709 6710
    SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond>
     <=>
    SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>)
unknown's avatar
unknown committed
6711

unknown's avatar
unknown committed
6712 6713 6714
    SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
     <=>
    SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
unknown's avatar
unknown committed
6715 6716 6717 6718 6719
   @endverbatim

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

unknown's avatar
unknown committed
6722 6723
void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields,
                      SELECT_LEX *lex)
unknown's avatar
unknown committed
6724
{
unknown's avatar
unknown committed
6725
  b->natural_join= a;
unknown's avatar
unknown committed
6726
  lex->prev_join_using= using_fields;
unknown's avatar
unknown committed
6727 6728
}

unknown's avatar
unknown committed
6729

6730
/**
6731 6732
  Reload/resets privileges and the different caches.

6733 6734 6735 6736
  @param thd Thread handler (can be NULL!)
  @param options What should be reset/reloaded (tables, privileges, slave...)
  @param tables Tables to flush (if any)
  @param write_to_binlog True if we can write to the binlog.
6737
               
6738 6739 6740 6741 6742 6743 6744 6745
  @note Depending on 'options', it may be very bad to write the
    query to the binlog (e.g. FLUSH SLAVE); this is a
    pointer where reload_acl_and_cache() will put 0 if
    it thinks we really should not write to the binlog.
    Otherwise it will put 1.

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

6749 6750
bool reload_acl_and_cache(THD *thd, ulong options, TABLE_LIST *tables,
                          bool *write_to_binlog)
unknown's avatar
unknown committed
6751 6752 6753
{
  bool result=0;
  select_errors=0;				/* Write if more errors */
6754
  bool tmp_write_to_binlog= 1;
6755

6756
  DBUG_ASSERT(!thd || !thd->in_sub_stmt);
6757

unknown's avatar
SCRUM  
unknown committed
6758
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
6759 6760
  if (options & REFRESH_GRANT)
  {
6761 6762 6763 6764 6765 6766
    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)))
6767 6768
    {
      thd->thread_stack= (char*) &tmp_thd;
6769
      thd->store_globals();
6770
      lex_start(thd);
6771
    }
6772
    
6773 6774
    if (thd)
    {
6775 6776
      bool reload_acl_failed= acl_reload(thd);
      bool reload_grants_failed= grant_reload(thd);
Kristofer Pettersson's avatar
Kristofer Pettersson committed
6777 6778 6779
      bool reload_servers_failed= servers_reload(thd);
      
      if (reload_acl_failed || reload_grants_failed || reload_servers_failed)
6780
      {
6781
        result= 1;
6782 6783 6784 6785 6786 6787
        /*
          When an error is returned, my_message may have not been called and
          the client will hang waiting for a response.
        */
        my_error(ER_UNKNOWN_ERROR, MYF(0), "FLUSH PRIVILEGES failed");
      }
6788
    }
6789

6790 6791 6792 6793 6794 6795 6796
    if (tmp_thd)
    {
      delete tmp_thd;
      /* Remember that we don't have a THD */
      my_pthread_setspecific_ptr(THR_THD,  0);
      thd= 0;
    }
6797
    reset_mqh((LEX_USER *)NULL, TRUE);
unknown's avatar
unknown committed
6798
  }
unknown's avatar
SCRUM  
unknown committed
6799
#endif
unknown's avatar
unknown committed
6800 6801
  if (options & REFRESH_LOG)
  {
6802
    /*
unknown's avatar
unknown committed
6803
      Flush the normal query log, the update log, the binary log,
unknown's avatar
unknown committed
6804 6805
      the slow query log, the relay log (if it exists) and the log
      tables.
6806
    */
unknown's avatar
unknown committed
6807

6808
    /*
unknown's avatar
unknown committed
6809 6810 6811 6812
      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)
6813 6814
    */
    tmp_write_to_binlog= 0;
6815 6816 6817 6818
    if( mysql_bin_log.is_open() )
    {
      mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
    }
unknown's avatar
unknown committed
6819
#ifdef HAVE_REPLICATION
6820
    pthread_mutex_lock(&LOCK_active_mi);
6821
    rotate_relay_log(active_mi);
6822
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
6823
#endif
unknown's avatar
unknown committed
6824 6825 6826 6827 6828

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

    if (ha_flush_logs(NULL))
unknown's avatar
unknown committed
6829
      result=1;
unknown's avatar
unknown committed
6830 6831
    if (flush_error_log())
      result=1;
unknown's avatar
unknown committed
6832
  }
unknown's avatar
unknown committed
6833
#ifdef HAVE_QUERY_CACHE
unknown's avatar
unknown committed
6834 6835
  if (options & REFRESH_QUERY_CACHE_FREE)
  {
unknown's avatar
unknown committed
6836
    query_cache.pack();				// FLUSH QUERY CACHE
6837
    options &= ~REFRESH_QUERY_CACHE;    // Don't flush cache, just free memory
unknown's avatar
unknown committed
6838 6839 6840
  }
  if (options & (REFRESH_TABLES | REFRESH_QUERY_CACHE))
  {
unknown's avatar
unknown committed
6841
    query_cache.flush();			// RESET QUERY CACHE
unknown's avatar
unknown committed
6842
  }
unknown's avatar
unknown committed
6843
#endif /*HAVE_QUERY_CACHE*/
6844 6845 6846 6847 6848
  /*
    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
6849
  {
6850
    if ((options & REFRESH_READ_LOCK) && thd)
unknown's avatar
unknown committed
6851
    {
6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862
      /*
        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
6863
        {
6864
          if ((*lock_p)->type >= TL_WRITE_ALLOW_WRITE)
6865 6866 6867 6868
          {
            my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
            return 1;
          }
unknown's avatar
unknown committed
6869
        }
6870
      }
unknown's avatar
unknown committed
6871 6872 6873 6874
      /*
	Writing to the binlog could cause deadlocks, as we don't log
	UNLOCK TABLES
      */
6875
      tmp_write_to_binlog= 0;
6876
      if (lock_global_read_lock(thd))
unknown's avatar
unknown committed
6877
	return 1;                               // Killed
Kristofer Pettersson's avatar
Kristofer Pettersson committed
6878
      if (close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ?
6879
                              FALSE : TRUE, TRUE))
6880 6881
          result= 1;
      
unknown's avatar
unknown committed
6882
      if (make_global_read_lock_block_commit(thd)) // Killed
6883 6884 6885 6886 6887
      {
        /* Don't leave things in a half-locked state */
        unlock_global_read_lock(thd);
        return 1;
      }
unknown's avatar
unknown committed
6888
    }
6889
    else
6890
    {
Kristofer Pettersson's avatar
Kristofer Pettersson committed
6891
      if (close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ?
6892
                              FALSE : TRUE, FALSE))
6893 6894
        result= 1;
    }
unknown's avatar
unknown committed
6895
    my_dbopt_cleanup();
unknown's avatar
unknown committed
6896 6897 6898
  }
  if (options & REFRESH_HOSTS)
    hostname_cache_refresh();
unknown's avatar
unknown committed
6899
  if (thd && (options & REFRESH_STATUS))
unknown's avatar
unknown committed
6900
    refresh_status(thd);
unknown's avatar
unknown committed
6901 6902
  if (options & REFRESH_THREADS)
    flush_thread_cache();
unknown's avatar
unknown committed
6903
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
6904
  if (options & REFRESH_MASTER)
6905
  {
6906
    DBUG_ASSERT(thd);
6907
    tmp_write_to_binlog= 0;
6908
    if (reset_master(thd))
unknown's avatar
unknown committed
6909
    {
6910
      result=1;
unknown's avatar
unknown committed
6911
    }
6912
  }
6913
#endif
unknown's avatar
unknown committed
6914
#ifdef OPENSSL
6915 6916
   if (options & REFRESH_DES_KEY_FILE)
   {
6917 6918
     if (des_key_file && load_des_key_file(des_key_file))
         result= 1;
6919 6920
   }
#endif
unknown's avatar
unknown committed
6921
#ifdef HAVE_REPLICATION
6922 6923
 if (options & REFRESH_SLAVE)
 {
6924
   tmp_write_to_binlog= 0;
6925
   pthread_mutex_lock(&LOCK_active_mi);
6926
   if (reset_slave(thd, active_mi))
6927
     result=1;
6928
   pthread_mutex_unlock(&LOCK_active_mi);
6929
 }
6930
#endif
6931
 if (options & REFRESH_USER_RESOURCES)
6932
   reset_mqh((LEX_USER *) NULL, 0);             /* purecov: inspected */
unknown's avatar
unknown committed
6933
 *write_to_binlog= tmp_write_to_binlog;
6934
 return result;
unknown's avatar
unknown committed
6935 6936
}

6937

unknown's avatar
unknown committed
6938 6939
/**
  kill on thread.
6940

unknown's avatar
unknown committed
6941 6942 6943
  @param thd			Thread class
  @param id			Thread id
  @param only_kill_query        Should it kill the query or the connection
6944

unknown's avatar
unknown committed
6945
  @note
6946 6947 6948
    This is written such that we have a short lock on LOCK_thread_count
*/

6949
uint kill_one_thread(THD *thd, ulong id, bool only_kill_query)
unknown's avatar
unknown committed
6950 6951 6952
{
  THD *tmp;
  uint error=ER_NO_SUCH_THREAD;
6953 6954
  DBUG_ENTER("kill_one_thread");
  DBUG_PRINT("enter", ("id=%lu only_kill=%d", id, only_kill_query));
6955 6956
  VOID(pthread_mutex_lock(&LOCK_thread_count)); // For unlink from list
  I_List_iterator<THD> it(threads);
unknown's avatar
unknown committed
6957 6958
  while ((tmp=it++))
  {
unknown's avatar
unknown committed
6959 6960
    if (tmp->command == COM_DAEMON)
      continue;
unknown's avatar
unknown committed
6961 6962
    if (tmp->thread_id == id)
    {
6963
      pthread_mutex_lock(&tmp->LOCK_thd_data);	// Lock from delete
6964
      break;
unknown's avatar
unknown committed
6965 6966 6967
    }
  }
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
6968 6969
  if (tmp)
  {
6970 6971 6972 6973 6974

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

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

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

6984
      If user of both killer and killee are non-NULL, proceed with
6985 6986 6987
      slayage if both are string-equal.
    */

6988
    if ((thd->security_ctx->master_access & SUPER_ACL) ||
6989
        thd->security_ctx->user_matches(tmp->security_ctx))
6990
    {
unknown's avatar
SCRUM  
unknown committed
6991
      tmp->awake(only_kill_query ? THD::KILL_QUERY : THD::KILL_CONNECTION);
6992 6993 6994 6995
      error=0;
    }
    else
      error=ER_KILL_DENIED_ERROR;
6996
    pthread_mutex_unlock(&tmp->LOCK_thd_data);
6997
  }
6998 6999 7000 7001
  DBUG_PRINT("exit", ("%d", error));
  DBUG_RETURN(error);
}

7002

7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016
/*
  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)))
7017
    my_ok(thd);
unknown's avatar
unknown committed
7018
  else
unknown's avatar
unknown committed
7019
    my_error(error, MYF(0), id);
unknown's avatar
unknown committed
7020 7021
}

unknown's avatar
unknown committed
7022

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

unknown's avatar
unknown committed
7025 7026
bool append_file_to_dir(THD *thd, const char **filename_ptr,
                        const char *table_name)
7027
{
7028
  char buff[FN_REFLEN],*ptr, *end;
7029 7030 7031 7032 7033 7034 7035
  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))
  {
7036
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
7037 7038 7039 7040
    return 1;
  }
  /* Fix is using unix filename format on dos */
  strmov(buff,*filename_ptr);
7041
  end=convert_dirname(buff, *filename_ptr, NullS);
7042
  if (!(ptr= (char*) thd->alloc((size_t) (end-buff) + strlen(table_name)+1)))
7043 7044
    return 1;					// End of memory
  *filename_ptr=ptr;
7045
  strxmov(ptr,buff,table_name,NullS);
7046 7047
  return 0;
}
7048

7049

unknown's avatar
unknown committed
7050 7051
/**
  Check if the select is a simple select (not an union).
7052

unknown's avatar
unknown committed
7053
  @retval
7054
    0	ok
unknown's avatar
unknown committed
7055
  @retval
7056 7057 7058 7059 7060 7061
    1	error	; In this case the error messege is sent to the client
*/

bool check_simple_select()
{
  THD *thd= current_thd;
7062 7063
  LEX *lex= thd->lex;
  if (lex->current_select != &lex->select_lex)
7064 7065
  {
    char command[80];
7066
    Lex_input_stream *lip= & thd->m_parser_state->m_lip;
7067 7068
    strmake(command, lip->yylval->symbol.str,
	    min(lip->yylval->symbol.length, sizeof(command)-1));
7069
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
7070 7071 7072 7073
    return 1;
  }
  return 0;
}
unknown's avatar
unknown committed
7074

unknown's avatar
unknown committed
7075

unknown's avatar
unknown committed
7076
Comp_creator *comp_eq_creator(bool invert)
unknown's avatar
unknown committed
7077
{
unknown's avatar
unknown committed
7078
  return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
unknown's avatar
unknown committed
7079 7080
}

unknown's avatar
unknown committed
7081

unknown's avatar
unknown committed
7082
Comp_creator *comp_ge_creator(bool invert)
unknown's avatar
unknown committed
7083
{
unknown's avatar
unknown committed
7084
  return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator;
unknown's avatar
unknown committed
7085 7086
}

unknown's avatar
unknown committed
7087

unknown's avatar
unknown committed
7088
Comp_creator *comp_gt_creator(bool invert)
unknown's avatar
unknown committed
7089
{
unknown's avatar
unknown committed
7090
  return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator;
unknown's avatar
unknown committed
7091 7092
}

unknown's avatar
unknown committed
7093

unknown's avatar
unknown committed
7094
Comp_creator *comp_le_creator(bool invert)
unknown's avatar
unknown committed
7095
{
unknown's avatar
unknown committed
7096
  return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator;
unknown's avatar
unknown committed
7097 7098
}

unknown's avatar
unknown committed
7099

unknown's avatar
unknown committed
7100
Comp_creator *comp_lt_creator(bool invert)
unknown's avatar
unknown committed
7101
{
unknown's avatar
unknown committed
7102
  return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator;
unknown's avatar
unknown committed
7103 7104
}

unknown's avatar
unknown committed
7105

unknown's avatar
unknown committed
7106
Comp_creator *comp_ne_creator(bool invert)
unknown's avatar
unknown committed
7107
{
unknown's avatar
unknown committed
7108
  return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
unknown's avatar
unknown committed
7109
}
unknown's avatar
unknown committed
7110 7111


unknown's avatar
unknown committed
7112 7113
/**
  Construct ALL/ANY/SOME subquery Item.
unknown's avatar
unknown committed
7114

unknown's avatar
unknown committed
7115 7116 7117 7118
  @param left_expr   pointer to left expression
  @param cmp         compare function creator
  @param all         true if we create ALL subquery
  @param select_lex  pointer on parsed subquery structure
unknown's avatar
unknown committed
7119

unknown's avatar
unknown committed
7120
  @return
unknown's avatar
unknown committed
7121 7122 7123 7124 7125 7126 7127
    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
7128
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
unknown's avatar
unknown committed
7129
    return new Item_in_subselect(left_expr, select_lex);
unknown's avatar
unknown committed
7130 7131

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

  Item_allany_subselect *it=
7135
    new Item_allany_subselect(left_expr, cmp, select_lex, all);
unknown's avatar
unknown committed
7136
  if (all)
7137
    return it->upper_item= new Item_func_not_all(it);	/* ALL */
unknown's avatar
unknown committed
7138

7139
  return it->upper_item= new Item_func_nop_all(it);      /* ANY/SOME */
unknown's avatar
unknown committed
7140
}
7141 7142


unknown's avatar
unknown committed
7143 7144
/**
  Multi update query pre-check.
7145

unknown's avatar
unknown committed
7146 7147
  @param thd		Thread handler
  @param tables	Global/local table list (have to be the same)
7148

unknown's avatar
unknown committed
7149
  @retval
unknown's avatar
unknown committed
7150
    FALSE OK
unknown's avatar
unknown committed
7151
  @retval
unknown's avatar
unknown committed
7152
    TRUE  Error
7153
*/
unknown's avatar
unknown committed
7154

unknown's avatar
unknown committed
7155
bool multi_update_precheck(THD *thd, TABLE_LIST *tables)
7156 7157 7158 7159 7160
{
  const char *msg= 0;
  TABLE_LIST *table;
  LEX *lex= thd->lex;
  SELECT_LEX *select_lex= &lex->select_lex;
unknown's avatar
VIEW  
unknown committed
7161
  DBUG_ENTER("multi_update_precheck");
7162 7163 7164

  if (select_lex->item_list.elements != lex->value_list.elements)
  {
7165
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
7166
    DBUG_RETURN(TRUE);
7167 7168 7169 7170 7171
  }
  /*
    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
7172
  for (table= tables; table; table= table->next_local)
7173
  {
7174 7175 7176
    if (table->derived)
      table->grant.privilege= SELECT_ACL;
    else if ((check_access(thd, UPDATE_ACL, table->db,
7177 7178
                           &table->grant.privilege, 0, 1,
                           test(table->schema_table)) ||
7179
              check_grant(thd, UPDATE_ACL, table, 0, 1, 1)) &&
unknown's avatar
unknown committed
7180
             (check_access(thd, SELECT_ACL, table->db,
7181 7182
                           &table->grant.privilege, 0, 0,
                           test(table->schema_table)) ||
7183
              check_grant(thd, SELECT_ACL, table, 0, 1, 0)))
unknown's avatar
unknown committed
7184
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7185

unknown's avatar
VIEW  
unknown committed
7186
    table->table_in_first_from_clause= 1;
7187
  }
unknown's avatar
unknown committed
7188 7189 7190
  /*
    Is there tables of subqueries?
  */
7191
  if (&lex->select_lex != lex->all_selects_list)
7192
  {
7193
    DBUG_PRINT("info",("Checking sub query list"));
unknown's avatar
VIEW  
unknown committed
7194
    for (table= tables; table; table= table->next_global)
7195
    {
7196
      if (!table->table_in_first_from_clause)
7197 7198
      {
	if (check_access(thd, SELECT_ACL, table->db,
7199 7200
			 &table->grant.privilege, 0, 0,
                         test(table->schema_table)) ||
7201
	    check_grant(thd, SELECT_ACL, table, 0, 1, 0))
unknown's avatar
unknown committed
7202
	  DBUG_RETURN(TRUE);
7203 7204 7205 7206 7207 7208
      }
    }
  }

  if (select_lex->order_list.elements)
    msg= "ORDER BY";
7209
  else if (select_lex->select_limit)
7210 7211 7212 7213
    msg= "LIMIT";
  if (msg)
  {
    my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
unknown's avatar
unknown committed
7214
    DBUG_RETURN(TRUE);
7215
  }
unknown's avatar
unknown committed
7216
  DBUG_RETURN(FALSE);
7217 7218
}

unknown's avatar
unknown committed
7219 7220
/**
  Multi delete query pre-check.
7221

unknown's avatar
unknown committed
7222 7223
  @param thd			Thread handler
  @param tables		Global/local table list
7224

unknown's avatar
unknown committed
7225
  @retval
unknown's avatar
unknown committed
7226
    FALSE OK
unknown's avatar
unknown committed
7227
  @retval
unknown's avatar
unknown committed
7228
    TRUE  error
7229
*/
unknown's avatar
unknown committed
7230

7231
bool multi_delete_precheck(THD *thd, TABLE_LIST *tables)
7232 7233 7234
{
  SELECT_LEX *select_lex= &thd->lex->select_lex;
  TABLE_LIST *aux_tables=
unknown's avatar
unknown committed
7235
    (TABLE_LIST *)thd->lex->auxiliary_table_list.first;
7236
  TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
unknown's avatar
VIEW  
unknown committed
7237
  DBUG_ENTER("multi_delete_precheck");
unknown's avatar
unknown committed
7238

7239 7240
  /* sql_yacc guarantees that tables and aux_tables are not zero */
  DBUG_ASSERT(aux_tables != 0);
7241
  if (check_table_access(thd, SELECT_ACL, tables, UINT_MAX, FALSE))
7242 7243 7244 7245 7246 7247 7248 7249
    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;
7250
  if (check_table_access(thd, DELETE_ACL, aux_tables, UINT_MAX, FALSE))
7251 7252
  {
    thd->lex->query_tables_own_last= save_query_tables_own_last;
unknown's avatar
unknown committed
7253
    DBUG_RETURN(TRUE);
7254 7255 7256
  }
  thd->lex->query_tables_own_last= save_query_tables_own_last;

7257 7258
  if ((thd->options & OPTION_SAFE_UPDATES) && !select_lex->where)
  {
unknown's avatar
unknown committed
7259 7260
    my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
               ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
unknown's avatar
unknown committed
7261
    DBUG_RETURN(TRUE);
7262
  }
7263 7264 7265 7266
  DBUG_RETURN(FALSE);
}


unknown's avatar
unknown committed
7267
/**
7268 7269 7270
  Link tables in auxilary table list of multi-delete with corresponding
  elements in main table list, and set proper locks for them.

unknown's avatar
unknown committed
7271
  @param lex   pointer to LEX representing multi-delete
7272

unknown's avatar
unknown committed
7273 7274 7275 7276
  @retval
    FALSE   success
  @retval
    TRUE    error
7277 7278 7279 7280 7281 7282 7283 7284 7285 7286
*/

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
7287
  for (target_tbl= (TABLE_LIST *)lex->auxiliary_table_list.first;
7288
       target_tbl; target_tbl= target_tbl->next_local)
7289
  {
7290
    lex->table_count++;
7291 7292
    /* All tables in aux_tables must be found in FROM PART */
    TABLE_LIST *walk;
unknown's avatar
VIEW  
unknown committed
7293
    for (walk= tables; walk; walk= walk->next_local)
7294
    {
unknown's avatar
unknown committed
7295 7296 7297
      if (!my_strcasecmp(table_alias_charset,
			 target_tbl->alias, walk->alias) &&
	  !strcmp(walk->db, target_tbl->db))
7298 7299 7300 7301
	break;
    }
    if (!walk)
    {
7302
      my_error(ER_UNKNOWN_TABLE, MYF(0),
7303
               target_tbl->table_name, "MULTI DELETE");
unknown's avatar
unknown committed
7304
      DBUG_RETURN(TRUE);
7305
    }
unknown's avatar
unknown committed
7306 7307 7308 7309 7310
    if (!walk->derived)
    {
      target_tbl->table_name= walk->table_name;
      target_tbl->table_name_length= walk->table_name_length;
    }
unknown's avatar
unknown committed
7311
    walk->updating= target_tbl->updating;
unknown's avatar
unknown committed
7312
    walk->lock_type= target_tbl->lock_type;
unknown's avatar
VIEW  
unknown committed
7313
    target_tbl->correspondent_table= walk;	// Remember corresponding table
7314
  }
unknown's avatar
unknown committed
7315
  DBUG_RETURN(FALSE);
7316 7317 7318
}


unknown's avatar
unknown committed
7319 7320
/**
  simple UPDATE query pre-check.
unknown's avatar
unknown committed
7321

unknown's avatar
unknown committed
7322 7323
  @param thd		Thread handler
  @param tables	Global table list
unknown's avatar
unknown committed
7324

unknown's avatar
unknown committed
7325
  @retval
unknown's avatar
unknown committed
7326
    FALSE OK
unknown's avatar
unknown committed
7327
  @retval
unknown's avatar
unknown committed
7328
    TRUE  Error
unknown's avatar
unknown committed
7329
*/
unknown's avatar
unknown committed
7330

unknown's avatar
unknown committed
7331
bool update_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
7332 7333 7334 7335
{
  DBUG_ENTER("update_precheck");
  if (thd->lex->select_lex.item_list.elements != thd->lex->value_list.elements)
  {
unknown's avatar
unknown committed
7336
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
7337
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7338
  }
unknown's avatar
unknown committed
7339
  DBUG_RETURN(check_one_table_access(thd, UPDATE_ACL, tables));
unknown's avatar
unknown committed
7340 7341 7342
}


unknown's avatar
unknown committed
7343 7344
/**
  simple DELETE query pre-check.
unknown's avatar
unknown committed
7345

unknown's avatar
unknown committed
7346 7347
  @param thd		Thread handler
  @param tables	Global table list
unknown's avatar
unknown committed
7348

unknown's avatar
unknown committed
7349
  @retval
unknown's avatar
unknown committed
7350
    FALSE  OK
unknown's avatar
unknown committed
7351
  @retval
unknown's avatar
unknown committed
7352
    TRUE   error
unknown's avatar
unknown committed
7353
*/
unknown's avatar
unknown committed
7354

unknown's avatar
unknown committed
7355
bool delete_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
7356 7357 7358
{
  DBUG_ENTER("delete_precheck");
  if (check_one_table_access(thd, DELETE_ACL, tables))
unknown's avatar
unknown committed
7359
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7360
  /* Set privilege for the WHERE clause */
unknown's avatar
unknown committed
7361
  tables->grant.want_privilege=(SELECT_ACL & ~tables->grant.privilege);
unknown's avatar
unknown committed
7362
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
7363 7364 7365
}


unknown's avatar
unknown committed
7366 7367
/**
  simple INSERT query pre-check.
unknown's avatar
unknown committed
7368

unknown's avatar
unknown committed
7369 7370
  @param thd		Thread handler
  @param tables	Global table list
unknown's avatar
unknown committed
7371

unknown's avatar
unknown committed
7372
  @retval
unknown's avatar
unknown committed
7373
    FALSE  OK
unknown's avatar
unknown committed
7374
  @retval
unknown's avatar
unknown committed
7375
    TRUE   error
unknown's avatar
unknown committed
7376
*/
unknown's avatar
unknown committed
7377

unknown's avatar
merge  
unknown committed
7378
bool insert_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
7379 7380 7381 7382
{
  LEX *lex= thd->lex;
  DBUG_ENTER("insert_precheck");

unknown's avatar
unknown committed
7383 7384 7385 7386
  /*
    Check that we have modify privileges for the first table and
    select privileges for the rest
  */
unknown's avatar
unknown committed
7387 7388 7389
  ulong privilege= (INSERT_ACL |
                    (lex->duplicates == DUP_REPLACE ? DELETE_ACL : 0) |
                    (lex->value_list.elements ? UPDATE_ACL : 0));
unknown's avatar
unknown committed
7390 7391

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

unknown's avatar
unknown committed
7394
  if (lex->update_list.elements != lex->value_list.elements)
unknown's avatar
unknown committed
7395
  {
unknown's avatar
unknown committed
7396
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
7397
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7398
  }
unknown's avatar
unknown committed
7399
  DBUG_RETURN(FALSE);
7400
}
unknown's avatar
unknown committed
7401 7402


unknown's avatar
unknown committed
7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417
/**
    @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)) ||
7418
         check_grant(thd, SELECT_ACL, table, 2, UINT_MAX, 0);
unknown's avatar
unknown committed
7419 7420 7421
}


unknown's avatar
unknown committed
7422 7423
/**
  CREATE TABLE query pre-check.
unknown's avatar
unknown committed
7424

unknown's avatar
unknown committed
7425 7426 7427
  @param thd			Thread handler
  @param tables		Global table list
  @param create_table	        Table which will be created
unknown's avatar
unknown committed
7428

unknown's avatar
unknown committed
7429
  @retval
unknown's avatar
unknown committed
7430
    FALSE   OK
unknown's avatar
unknown committed
7431
  @retval
unknown's avatar
unknown committed
7432
    TRUE   Error
unknown's avatar
unknown committed
7433
*/
unknown's avatar
unknown committed
7434

unknown's avatar
unknown committed
7435 7436
bool create_table_precheck(THD *thd, TABLE_LIST *tables,
                           TABLE_LIST *create_table)
unknown's avatar
unknown committed
7437 7438
{
  LEX *lex= thd->lex;
7439 7440
  SELECT_LEX *select_lex= &lex->select_lex;
  ulong want_priv;
unknown's avatar
merge  
unknown committed
7441
  bool error= TRUE;                                 // Error message is given
unknown's avatar
unknown committed
7442
  DBUG_ENTER("create_table_precheck");
7443

7444 7445 7446 7447 7448
  /*
    Require CREATE [TEMPORARY] privilege on new table; for
    CREATE TABLE ... SELECT, also require INSERT.
  */

7449
  want_priv= ((lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) ?
7450 7451 7452
              CREATE_TMP_ACL : CREATE_ACL) |
             (select_lex->item_list.elements ? INSERT_ACL : 0);

unknown's avatar
unknown committed
7453
  if (check_access(thd, want_priv, create_table->db,
7454 7455
		   &create_table->grant.privilege, 0, 0,
                   test(create_table->schema_table)) ||
unknown's avatar
unknown committed
7456 7457 7458
      check_merge_table_access(thd, create_table->db,
			       (TABLE_LIST *)
			       lex->create_info.merge_list.first))
7459
    goto err;
7460
  if (want_priv != CREATE_TMP_ACL &&
7461
      check_grant(thd, want_priv, create_table, 0, 1, 0))
7462 7463 7464 7465 7466 7467
    goto err;

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

7468 7469
#ifdef NOT_NECESSARY_TO_CHECK_CREATE_TABLE_EXIST_WHEN_PREPARING_STATEMENT
    /* This code throws an ill error for CREATE TABLE t1 SELECT * FROM t1 */
7470
    /*
7471
      Only do the check for PS, because we on execute we have to check that
unknown's avatar
unknown committed
7472 7473
      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).
7474
    */
unknown's avatar
unknown committed
7475
    if (thd->stmt_arena->is_stmt_prepare_or_first_sp_execute())
7476
    {
unknown's avatar
unknown committed
7477 7478 7479 7480
      /*
        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
7481
          find_table_in_global_list(tables, create_table->db,
7482
                                    create_table->table_name))
unknown's avatar
unknown committed
7483
      {
7484
	error= FALSE;
unknown's avatar
unknown committed
7485 7486 7487
        goto err;
      }
    }
7488
#endif
7489
    if (tables && check_table_access(thd, SELECT_ACL, tables, UINT_MAX, FALSE))
7490 7491
      goto err;
  }
unknown's avatar
unknown committed
7492 7493 7494 7495 7496
  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
7497
  error= FALSE;
7498 7499 7500

err:
  DBUG_RETURN(error);
unknown's avatar
unknown committed
7501
}
unknown's avatar
unknown committed
7502 7503


unknown's avatar
unknown committed
7504 7505
/**
  negate given expression.
unknown's avatar
unknown committed
7506

unknown's avatar
unknown committed
7507 7508
  @param thd  thread handler
  @param expr expression for negation
unknown's avatar
unknown committed
7509

unknown's avatar
unknown committed
7510
  @return
unknown's avatar
unknown committed
7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535
    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);
}
7536

unknown's avatar
unknown committed
7537 7538 7539
/**
  Set the specified definer to the default value, which is the
  current user in the thread.
7540
 
unknown's avatar
unknown committed
7541 7542
  @param[in]  thd       thread handler
  @param[out] definer   definer
7543 7544
*/
 
7545
void get_default_definer(THD *thd, LEX_USER *definer)
7546 7547 7548 7549 7550 7551 7552 7553 7554 7555
{
  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);
}

7556

unknown's avatar
unknown committed
7557
/**
7558
  Create default definer for the specified THD.
7559

unknown's avatar
unknown committed
7560
  @param[in] thd         thread handler
7561

unknown's avatar
unknown committed
7562 7563
  @return
    - On success, return a valid pointer to the created and initialized
7564
    LEX_USER, which contains definer information.
unknown's avatar
unknown committed
7565
    - On error, return 0.
7566 7567 7568 7569 7570 7571 7572 7573 7574
*/

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

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

7575
  get_default_definer(thd, definer);
7576 7577 7578 7579 7580

  return definer;
}


unknown's avatar
unknown committed
7581
/**
7582
  Create definer with the given user and host names.
7583

unknown's avatar
unknown committed
7584 7585 7586
  @param[in] thd          thread handler
  @param[in] user_name    user name
  @param[in] host_name    host name
7587

unknown's avatar
unknown committed
7588 7589
  @return
    - On success, return a valid pointer to the created and initialized
7590
    LEX_USER, which contains definer information.
unknown's avatar
unknown committed
7591
    - On error, return 0.
7592 7593
*/

7594
LEX_USER *create_definer(THD *thd, LEX_STRING *user_name, LEX_STRING *host_name)
7595
{
7596 7597 7598 7599
  LEX_USER *definer;

  /* Create and initialize. */

unknown's avatar
unknown committed
7600
  if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER))))
7601 7602 7603 7604 7605 7606
    return 0;

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

  return definer;
7607
}
7608 7609


unknown's avatar
unknown committed
7610
/**
7611 7612
  Retuns information about user or current user.

unknown's avatar
unknown committed
7613 7614
  @param[in] thd          thread handler
  @param[in] user         user
7615

unknown's avatar
unknown committed
7616 7617
  @return
    - On success, return a valid pointer to initialized
7618
    LEX_USER, which contains user information.
unknown's avatar
unknown committed
7619
    - On error, return 0.
7620 7621 7622 7623 7624
*/

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

7627 7628
  return user;
}
7629 7630


unknown's avatar
unknown committed
7631
/**
7632
  Check that byte length of a string does not exceed some limit.
7633

unknown's avatar
unknown committed
7634 7635 7636
  @param str         string to be checked
  @param err_msg     error message to be displayed if the string is too long
  @param max_length  max length
7637

unknown's avatar
unknown committed
7638
  @retval
7639
    FALSE   the passed string is not longer than max_length
unknown's avatar
unknown committed
7640
  @retval
7641
    TRUE    the passed string is longer than max_length
7642 7643 7644

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

7647 7648
bool check_string_byte_length(LEX_STRING *str, const char *err_msg,
                              uint max_byte_length)
7649
{
7650
  if (str->length <= max_byte_length)
unknown's avatar
unknown committed
7651
    return FALSE;
7652

7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684
  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
7685

7686 7687
  if (!no_error)
    my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_char_length);
7688 7689
  return TRUE;
}
7690 7691


7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703
/*
  Check if path does not contain mysql data home directory
  SYNOPSIS
    test_if_data_home_dir()
    dir                     directory
    conv_home_dir           converted data home directory
    home_dir_len            converted data home directory length

  RETURN VALUES
    0	ok
    1	error  
*/
7704
C_MODE_START
7705

7706
int test_if_data_home_dir(const char *dir)
7707
{
7708
  char path[FN_REFLEN];
Alexey Botchkov's avatar
Alexey Botchkov committed
7709
  int dir_len;
7710 7711 7712 7713 7714 7715 7716
  DBUG_ENTER("test_if_data_home_dir");

  if (!dir)
    DBUG_RETURN(0);

  (void) fn_format(path, dir, "", "",
                   (MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS));
7717 7718
  dir_len= strlen(path);
  if (mysql_unpacked_real_data_home_len<= dir_len)
7719
  {
7720 7721 7722 7723
    if (dir_len > mysql_unpacked_real_data_home_len &&
        path[mysql_unpacked_real_data_home_len] != FN_LIBCHAR)
      DBUG_RETURN(0);

7724 7725
    if (lower_case_file_system)
    {
7726 7727
      if (!my_strnncoll(default_charset_info, (const uchar*) path,
                        mysql_unpacked_real_data_home_len,
7728
                        (const uchar*) mysql_unpacked_real_data_home,
7729
                        mysql_unpacked_real_data_home_len))
7730 7731
        DBUG_RETURN(1);
    }
7732 7733
    else if (!memcmp(path, mysql_unpacked_real_data_home,
                     mysql_unpacked_real_data_home_len))
7734 7735 7736 7737 7738
      DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}

7739 7740
C_MODE_END

7741

7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756
/**
  Check that host name string is valid.

  @param[in] str string to be checked

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

bool check_host_name(LEX_STRING *str)
{
  const char *name= str->str;
  const char *end= str->str + str->length;
Sergey Glukhov's avatar
Sergey Glukhov committed
7757
  if (check_string_byte_length(str, ER(ER_HOSTNAME), HOSTNAME_LENGTH))
7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772
    return TRUE;

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


7775 7776 7777 7778 7779 7780 7781 7782
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.
7783
  @param parser_state Parser state.
unknown's avatar
unknown committed
7784
  @param creation_ctx Object creation context.
7785 7786 7787 7788 7789 7790

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

unknown's avatar
unknown committed
7791
bool parse_sql(THD *thd,
7792
               Parser_state *parser_state,
unknown's avatar
unknown committed
7793
               Object_creation_ctx *creation_ctx)
7794
{
7795
  DBUG_ASSERT(thd->m_parser_state == NULL);
7796

unknown's avatar
unknown committed
7797 7798 7799 7800 7801 7802 7803
  /* Backup creation context. */

  Object_creation_ctx *backup_ctx= NULL;

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

7804
  /* Set parser state. */
unknown's avatar
unknown committed
7805

7806
  thd->m_parser_state= parser_state;
7807

unknown's avatar
unknown committed
7808 7809
  /* Parse the query. */

7810 7811
  bool mysql_parse_status= MYSQLparse(thd) != 0;

7812
  /* Check that if MYSQLparse() failed, thd->is_error() is set. */
7813 7814

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

7817
  /* Reset parser state. */
7818

7819
  thd->m_parser_state= NULL;
7820

unknown's avatar
unknown committed
7821 7822 7823 7824 7825 7826 7827
  /* Restore creation context. */

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

  /* That's it. */

7828
  return mysql_parse_status || thd->is_fatal_error;
7829
}
7830 7831 7832 7833

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