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

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

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

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

16
#define MYSQL_LEX 1
unknown's avatar
unknown committed
17
#include "mysql_priv.h"
18
#include "sql_repl.h"
unknown's avatar
unknown committed
19
#include "rpl_filter.h"
20
#include "repl_failsafe.h"
unknown's avatar
unknown committed
21 22 23 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
#include "probes_mysql.h"
31

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

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

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

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

unknown's avatar
unknown committed
52
const LEX_STRING command_name[]={
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 83
  { 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
84 85
};

unknown's avatar
unknown committed
86
const char *xa_state_names[]={
87
  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED", "ROLLBACK ONLY"
unknown's avatar
unknown committed
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 137
/**
  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
138 139 140 141 142
static void unlock_locked_tables(THD *thd)
{
  if (thd->locked_tables)
  {
    thd->lock=thd->locked_tables;
143
    thd->locked_tables=0;			// Will be automatically closed
unknown's avatar
unknown committed
144 145 146 147
    close_thread_tables(thd);			// Free tables
  }
}

148

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

180

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

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


220 221 222 223 224 225 226 227 228 229 230 231
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;
}

232

unknown's avatar
unknown committed
233 234 235 236
/**
  Mark all commands that somehow changes a table.

  This is used to check number of updates / hour.
unknown's avatar
unknown committed
237 238 239

  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
240

241
  See COMMAND_FLAG_xxx for different type of commands
unknown's avatar
unknown committed
242 243
     2  - query that returns meaningful ROW_COUNT() -
          a number of modified rows
244 245
*/

246
uint sql_command_flags[SQLCOM_END+1];
247 248 249

void init_update_queries(void)
{
250
  bzero((uchar*) &sql_command_flags, sizeof(sql_command_flags));
251

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

unknown's avatar
unknown committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
  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;
287 288 289 290 291 292 293 294 295
  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;
296
  sql_command_flags[SQLCOM_SHOW_PLUGINS]=     CF_STATUS_COMMAND;
297 298 299 300 301
  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;
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
  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;
325
  sql_command_flags[SQLCOM_SHOW_STATUS_FUNC]=  CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
326 327 328
  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;
329 330
  sql_command_flags[SQLCOM_SHOW_PROFILES]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PROFILE]= CF_STATUS_COMMAND;
331 332

   sql_command_flags[SQLCOM_SHOW_TABLES]=       (CF_STATUS_COMMAND |
333 334
                                                 CF_SHOW_TABLE_COMMAND |
                                                 CF_REEXECUTION_FRAGILE);
335
  sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND |
336 337
                                                CF_SHOW_TABLE_COMMAND |
                                                CF_REEXECUTION_FRAGILE);
338 339 340 341 342 343 344

  /*
    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.
  */
345
  sql_command_flags[SQLCOM_CALL]= 		CF_HAS_ROW_COUNT | CF_REEXECUTION_FRAGILE;
346
  sql_command_flags[SQLCOM_EXECUTE]= 		CF_HAS_ROW_COUNT;
347 348 349 350 351 352 353 354

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

357

unknown's avatar
unknown committed
358 359
bool is_update_query(enum enum_sql_command command)
{
unknown's avatar
unknown committed
360
  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
361
  return (sql_command_flags[command] & CF_CHANGES_DATA) != 0;
unknown's avatar
unknown committed
362
}
363

364 365 366 367 368 369 370 371 372 373
/**
  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;
}
374

375 376
void execute_init_command(THD *thd, sys_var_str *init_command_var,
			  rw_lock_t *var_mutex)
unknown's avatar
unknown committed
377 378 379 380
{
  Vio* save_vio;
  ulong save_client_capabilities;

381 382 383 384 385 386
#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

387
  thd_proc_info(thd, "Execution of init_command");
388 389 390 391 392 393
  /*
    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
394 395
  save_client_capabilities= thd->client_capabilities;
  thd->client_capabilities|= CLIENT_MULTI_QUERIES;
396 397 398 399
  /*
    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
400 401
  save_vio= thd->net.vio;
  thd->net.vio= 0;
402 403 404
  dispatch_command(COM_QUERY, thd,
                   init_command_var->value,
                   init_command_var->value_length);
405
  rw_unlock(var_mutex);
unknown's avatar
unknown committed
406 407
  thd->client_capabilities= save_client_capabilities;
  thd->net.vio= save_vio;
408 409 410 411

#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
  thd->profiling.finish_current_query();
#endif
unknown's avatar
unknown committed
412 413 414
}


unknown's avatar
unknown committed
415
/**
416
  Execute commands from bootstrap_file.
unknown's avatar
unknown committed
417 418

  Used when creating the initial grant tables.
419
*/
unknown's avatar
unknown committed
420

421
pthread_handler_t handle_bootstrap(void *arg)
unknown's avatar
unknown committed
422
{
423 424 425
  THD *thd=(THD*) arg;
  FILE *file=bootstrap_file;
  char *buff;
426
  const char* found_semicolon= NULL;
unknown's avatar
unknown committed
427

428
  /* The following must be called before DBUG_ENTER */
429
  thd->thread_stack= (char*) &thd;
430
  if (my_thread_init() || thd->store_globals())
unknown's avatar
unknown committed
431
  {
unknown's avatar
unknown committed
432
#ifndef EMBEDDED_LIBRARY
433
    close_connection(thd, ER_OUT_OF_RESOURCES, 1);
unknown's avatar
unknown committed
434
#endif
435
    thd->fatal_error();
436
    goto end;
unknown's avatar
unknown committed
437
  }
438 439
  DBUG_ENTER("handle_bootstrap");

unknown's avatar
unknown committed
440
#ifndef EMBEDDED_LIBRARY
441 442
  pthread_detach_this_thread();
  thd->thread_stack= (char*) &thd;
unknown's avatar
unknown committed
443
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
444

445
  if (thd->variables.max_join_size == HA_POS_ERROR)
unknown's avatar
unknown committed
446 447
    thd->options |= OPTION_BIG_SELECTS;

448
  thd_proc_info(thd, 0);
unknown's avatar
unknown committed
449
  thd->version=refresh_version;
450 451
  thd->security_ctx->priv_user=
    thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME));
unknown's avatar
unknown committed
452
  thd->security_ctx->priv_host[0]=0;
453 454 455 456 457 458
  /*
    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
459

460
  buff= (char*) thd->net.buff;
461
  thd->init_for_queries();
unknown's avatar
unknown committed
462 463
  while (fgets(buff, thd->net.max_packet, file))
  {
464 465 466 467 468 469 470 471 472 473 474
    /* 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))
      {
475 476
        net_end_statement(thd);
        bootstrap_error= 1;
477 478 479 480 481 482 483
        break;
      }
      buff= (char*) thd->net.buff;
      fgets(buff + length, thd->net.max_packet - length, file);
      length+= (ulong) strlen(buff + length);
      /* purecov: end */
    }
484
    if (bootstrap_error)
485
      break;                                    /* purecov: inspected */
unknown's avatar
unknown committed
486

unknown's avatar
unknown committed
487
    while (length && (my_isspace(thd->charset(), buff[length-1]) ||
488
                      buff[length-1] == ';'))
unknown's avatar
unknown committed
489 490
      length--;
    buff[length]=0;
unknown's avatar
unknown committed
491 492 493 494 495

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

496
    thd->query_length=length;
497 498 499
    thd->query= (char*) thd->memdup_w_gap(buff, length+1, 
                                          thd->db_length+1+
                                          QUERY_CACHE_FLAGS_SIZE);
unknown's avatar
unknown committed
500
    thd->query[length] = '\0';
501
    DBUG_PRINT("query",("%-.4096s",thd->query));
502
#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
503
    thd->profiling.start_new_query();
504 505 506
    thd->profiling.set_query_source(thd->query, length);
#endif

507 508 509 510
    /*
      We don't need to obtain LOCK_thread_count here because in bootstrap
      mode we have only one thread.
    */
511
    thd->query_id=next_query_id();
512
    thd->set_time();
513
    mysql_parse(thd, thd->query, length, & found_semicolon);
unknown's avatar
unknown committed
514
    close_thread_tables(thd);			// Free tables
515

516 517
    bootstrap_error= thd->is_error();
    net_end_statement(thd);
518

519 520 521 522
#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
    thd->profiling.finish_current_query();
#endif

523
    if (bootstrap_error)
524 525
      break;

unknown's avatar
unknown committed
526
    free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
527
#ifdef USING_TRANSACTIONS
528
    free_root(&thd->transaction.mem_root,MYF(MY_KEEP_PREALLOC));
529
#endif
unknown's avatar
unknown committed
530
  }
531 532

end:
533 534 535 536
  net_end(&thd->net);
  thd->cleanup();
  delete thd;

unknown's avatar
unknown committed
537
#ifndef EMBEDDED_LIBRARY
538 539 540
  (void) pthread_mutex_lock(&LOCK_thread_count);
  thread_count--;
  (void) pthread_mutex_unlock(&LOCK_thread_count);
541
  (void) pthread_cond_broadcast(&COND_thread_count);
542 543
  my_thread_end();
  pthread_exit(0);
unknown's avatar
unknown committed
544
#endif
545
  DBUG_RETURN(0);
unknown's avatar
unknown committed
546 547 548
}


549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
/**
  @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
566
#ifndef NO_EMBEDDED_ACCESS_CHECKS
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
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,
583
                              table_list, UINT_MAX, FALSE);
584 585 586
  }
  return error;
}
unknown's avatar
unknown committed
587
#endif
588

unknown's avatar
unknown committed
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
/* 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() */
604 605 606

void cleanup_items(Item *item)
{
unknown's avatar
unknown committed
607
  DBUG_ENTER("cleanup_items");  
608 609
  for (; item ; item=item->next)
    item->cleanup();
unknown's avatar
unknown committed
610
  DBUG_VOID_RETURN;
611 612
}

unknown's avatar
unknown committed
613 614
/**
  Handle COM_TABLE_DUMP command.
unknown's avatar
unknown committed
615

unknown's avatar
unknown committed
616 617 618 619
  @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
620

unknown's avatar
unknown committed
621
  @note
unknown's avatar
unknown committed
622 623
    This function is written to handle one specific command only.

unknown's avatar
unknown committed
624
  @retval
unknown's avatar
unknown committed
625
    0               success
unknown's avatar
unknown committed
626
  @retval
unknown's avatar
unknown committed
627 628 629 630
    1               error, the error message is set in THD
*/

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

649
  if (check_db_name(db))
650
  {
651 652
    /* purecov: begin inspected */
    my_error(ER_WRONG_DB_NAME ,MYF(0), db->str ? db->str : "NULL");
653
    goto err;
654
    /* purecov: end */
655
  }
656
  if (lower_case_table_names)
657
    my_casedn_str(files_charset_info, tbl_name);
658

659
  if (!(table=open_ltable(thd, table_list, TL_READ_NO_INSERT, 0)))
660 661
    DBUG_RETURN(1);

unknown's avatar
unknown committed
662
  if (check_one_table_access(thd, SELECT_ACL, table_list))
unknown's avatar
unknown committed
663 664
    goto err;
  thd->free_list = 0;
unknown's avatar
unknown committed
665
  thd->query_length=(uint) strlen(tbl_name);
unknown's avatar
unknown committed
666
  thd->query = tbl_name;
unknown's avatar
unknown committed
667
  if ((error = mysqld_dump_create_info(thd, table_list, -1)))
668
  {
669
    my_error(ER_GET_ERRNO, MYF(0), my_errno);
670 671
    goto err;
  }
unknown's avatar
unknown committed
672
  net_flush(&thd->net);
unknown's avatar
unknown committed
673
  if ((error= table->file->dump(thd,-1)))
674
    my_error(ER_GET_ERRNO, MYF(0), error);
unknown's avatar
unknown committed
675

unknown's avatar
unknown committed
676
err:
unknown's avatar
unknown committed
677
  DBUG_RETURN(error);
unknown's avatar
unknown committed
678 679
}

unknown's avatar
unknown committed
680 681
/**
  Ends the current transaction and (maybe) begin the next.
unknown's avatar
unknown committed
682

unknown's avatar
unknown committed
683 684
  @param thd            Current thread
  @param completion     Completion type
unknown's avatar
unknown committed
685

unknown's avatar
unknown committed
686 687
  @retval
    0   OK
unknown's avatar
unknown committed
688 689
*/

690
int end_trans(THD *thd, enum enum_mysql_completiontype completion)
unknown's avatar
unknown committed
691 692 693
{
  bool do_release= 0;
  int res= 0;
694
  DBUG_ENTER("end_trans");
unknown's avatar
unknown committed
695

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

unknown's avatar
unknown committed
746 747 748
  if (res < 0)
    my_error(thd->killed_errno(), MYF(0));
  else if ((res == 0) && do_release)
unknown's avatar
unknown committed
749 750
    thd->killed= THD::KILL_CONNECTION;

unknown's avatar
unknown committed
751 752
  DBUG_RETURN(res);
}
unknown's avatar
unknown committed
753

754
#ifndef EMBEDDED_LIBRARY
755

unknown's avatar
unknown committed
756
/**
unknown's avatar
unknown committed
757
  Read one command from connection and execute it (query or simple command).
758
  This function is called in loop from thread function.
759 760 761

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

unknown's avatar
unknown committed
762
  @retval
763
    0  success
unknown's avatar
unknown committed
764
  @retval
765 766 767
    1  request of thread shutdown (see dispatch_command() description)
*/

unknown's avatar
unknown committed
768 769
bool do_command(THD *thd)
{
770
  bool return_value;
unknown's avatar
unknown committed
771
  char *packet= 0;
unknown's avatar
unknown committed
772
  ulong packet_length;
unknown's avatar
unknown committed
773
  NET *net= &thd->net;
unknown's avatar
unknown committed
774 775 776
  enum enum_server_command command;
  DBUG_ENTER("do_command");

unknown's avatar
unknown committed
777 778 779 780
  /*
    indicator of uninitialized lex => normal flow of errors handling
    (see my_message_sql)
  */
781
  thd->lex->current_select= 0;
unknown's avatar
unknown committed
782

unknown's avatar
unknown committed
783 784 785 786 787 788
  /*
    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
  */
789
  my_net_set_read_timeout(net, thd->variables.net_wait_timeout);
unknown's avatar
unknown committed
790

791 792 793 794
  /*
    XXX: this code is here only to clear possible errors of init_connect. 
    Consider moving to init_connect() instead.
  */
unknown's avatar
unknown committed
795
  thd->clear_error();				// Clear error message
796
  thd->main_da.reset_diagnostics_area();
unknown's avatar
unknown committed
797 798

  net_new_transaction(net);
799 800 801 802 803 804

  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
805
  {
806 807 808
    DBUG_PRINT("info",("Got error %d reading command from socket %s",
		       net->error,
		       vio_description(net->vio)));
809

810
    /* Check if we can continue without closing the connection */
811

812 813 814 815
    /* The error must be set. */
    DBUG_ASSERT(thd->is_error());
    net_end_statement(thd);

816
    if (net->error != 3)
817
    {
818
      return_value= TRUE;                       // We have to close it.
819 820
      goto out;
    }
821

822
    net->error= 0;
823 824
    return_value= FALSE;
    goto out;
unknown's avatar
unknown committed
825
  }
826 827 828 829 830 831 832 833 834 835 836

  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
837
  {
838 839 840
    /* Initialize with COM_SLEEP packet */
    packet[0]= (uchar) COM_SLEEP;
    packet_length= 1;
unknown's avatar
unknown committed
841
  }
842 843 844 845 846 847 848 849 850 851 852
  /* 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
853 854

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

857
  DBUG_ASSERT(packet_length);
858 859 860 861 862 863 864
  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);
865
}
866
#endif  /* EMBEDDED_LIBRARY */
867

868 869 870 871 872 873 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
/**
  @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);

899
  if (!(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA))
900 901 902 903 904 905 906 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
    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);
}
935

unknown's avatar
unknown committed
936 937
/**
  Perform one connection-level (COM_XXXX) command.
938

unknown's avatar
unknown committed
939 940 941 942 943 944 945 946
  @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
947 948 949
    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
950 951

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

965 966 967 968
  MYSQL_COMMAND_START(thd->thread_id, command,
                      thd->security_ctx->priv_user,
                      (char *) thd->security_ctx->host_or_ip);
  
969
  thd->command=command;
unknown's avatar
unknown committed
970
  /*
971 972
    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
973
  */
974
  thd->enable_slow_log= TRUE;
975
  thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
unknown's avatar
unknown committed
976
  thd->set_time();
unknown's avatar
unknown committed
977
  VOID(pthread_mutex_lock(&LOCK_thread_count));
unknown's avatar
unknown committed
978
  thd->query_id= global_query_id;
979 980 981 982 983 984 985 986 987 988

  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:
989
    next_query_id();
990 991 992 993 994 995 996
    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
997
  thread_running++;
998
  /* TODO: set thd->lex->sql_command to SQLCOM_END here */
unknown's avatar
unknown committed
999
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
unknown's avatar
unknown committed
1000

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

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

unknown's avatar
unknown committed
1069
    thd->change_user();
1070
    thd->clear_error();                         // if errors from rollback
unknown's avatar
unknown committed
1071

1072
    /*
unknown's avatar
unknown committed
1073 1074 1075
      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).
1076 1077 1078

      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
1079
    */
1080
    char db_buff[NAME_LEN+1];                 // buffer to store db in utf8
unknown's avatar
unknown committed
1081
    char *db= passwd;
1082
    char *save_db;
1083 1084 1085 1086 1087 1088 1089 1090 1091
    /*
      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;
    }
1092
    uint passwd_len= (thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
1093
                      (uchar)(*passwd++) : strlen(passwd));
1094 1095
    uint dummy_errors, save_db_length, db_length;
    int res;
1096 1097 1098
    Security_context save_security_ctx= *thd->security_ctx;
    USER_CONN *save_user_connect;

unknown's avatar
unknown committed
1099
    db+= passwd_len + 1;
1100 1101 1102 1103 1104
    /*
      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)
1105
    {
unknown's avatar
unknown committed
1106
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1107 1108
      break;
    }
1109 1110
    db_length= strlen(db);

1111
    char *ptr= db + db_length + 1;
1112 1113
    uint cs_number= 0;

1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    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);
    }
1124

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

1131
    /* Save user and privileges */
1132 1133 1134
    save_db_length= thd->db_length;
    save_db= thd->db;
    save_user_connect= thd->user_connect;
1135 1136

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

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

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

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

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

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

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

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

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

1239
      log_slow_statement(thd);
1240

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

1248 1249 1250 1251 1252
      if (MYSQL_QUERY_DONE_ENABLED())
      {
        MYSQL_QUERY_DONE(thd->is_error());
      }

1253 1254 1255 1256 1257 1258
#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

1259 1260 1261 1262 1263
      MYSQL_QUERY_START(thd->query, thd->thread_id,
                        (char *) (thd->db ? thd->db : ""),
                        thd->security_ctx->priv_user,
                        (char *) thd->security_ctx->host_or_ip);

unknown's avatar
unknown committed
1264
      VOID(pthread_mutex_lock(&LOCK_thread_count));
1265
      thd->query_length= length;
1266
      thd->query= beginning_of_next_stmt;
1267 1268 1269 1270
      /*
        Count each statement from the client.
      */
      statistic_increment(thd->status_var.questions, &LOCK_status);
1271
      thd->query_id= next_query_id();
1272
      thd->set_time(); /* Reset the query start time. */
1273
      /* TODO: set thd->lex->sql_command to SQLCOM_END here */
1274
      VOID(pthread_mutex_unlock(&LOCK_thread_count));
1275
      mysql_parse(thd, beginning_of_next_stmt, length, &end_of_stmt);
1276 1277
    }

unknown's avatar
unknown committed
1278 1279 1280 1281 1282
    if (!(specialflag & SPECIAL_NO_PRIOR))
      my_pthread_setprio(pthread_self(),WAIT_PRIOR);
    DBUG_PRINT("info",("query ready"));
    break;
  }
1283
  case COM_FIELD_LIST:				// This isn't actually needed
unknown's avatar
unknown committed
1284
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
1285 1286
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
unknown's avatar
unknown committed
1287 1288 1289
    break;
#else
  {
1290
    char *fields, *packet_end= packet + packet_length, *arg_end;
1291
    /* Locked closure of all tables */
unknown's avatar
unknown committed
1292
    TABLE_LIST table_list;
unknown's avatar
unknown committed
1293
    LEX_STRING conv_name;
unknown's avatar
unknown committed
1294

unknown's avatar
unknown committed
1295
    /* used as fields initializator */
1296
    lex_start(thd);
1297

1298
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
unknown's avatar
unknown committed
1299
    bzero((char*) &table_list,sizeof(table_list));
1300
    if (thd->copy_db_to(&table_list.db, &table_list.db_length))
unknown's avatar
unknown committed
1301
      break;
1302 1303 1304 1305
    /*
      We have name + wildcard in packet, separated by endzero
    */
    arg_end= strend(packet);
unknown's avatar
unknown committed
1306
    thd->convert_string(&conv_name, system_charset_info,
1307
			packet, (uint) (arg_end - packet), thd->charset());
1308
    table_list.alias= table_list.table_name= conv_name.str;
1309
    packet= arg_end + 1;
1310 1311

    if (!my_strcasecmp(system_charset_info, table_list.db,
1312
                       INFORMATION_SCHEMA_NAME.str))
1313 1314 1315 1316 1317 1318
    {
      ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, table_list.alias);
      if (schema_table)
        table_list.schema_table= schema_table;
    }

1319
    thd->query_length= (uint) (packet_end - packet); // Don't count end \0
1320
    if (!(thd->query=fields= (char*) thd->memdup(packet,thd->query_length+1)))
unknown's avatar
unknown committed
1321
      break;
unknown's avatar
unknown committed
1322
    general_log_print(thd, command, "%s %s", table_list.table_name, fields);
1323
    if (lower_case_table_names)
1324
      my_casedn_str(files_charset_info, table_list.table_name);
unknown's avatar
unknown committed
1325

unknown's avatar
unknown committed
1326
    if (check_access(thd,SELECT_ACL,table_list.db,&table_list.grant.privilege,
1327
		     0, 0, test(table_list.schema_table)))
unknown's avatar
unknown committed
1328
      break;
1329
    if (check_grant(thd, SELECT_ACL, &table_list, 2, UINT_MAX, 0))
unknown's avatar
unknown committed
1330
      break;
1331 1332
    /* init structures for VIEW processing */
    table_list.select_lex= &(thd->lex->select_lex);
1333 1334 1335 1336

    lex_start(thd);
    mysql_reset_thd_for_next_command(thd);

1337
    thd->lex->
1338 1339
      select_lex.table_list.link_in_list((uchar*) &table_list,
                                         (uchar**) &table_list.next_local);
unknown's avatar
unknown committed
1340
    thd->lex->add_to_query_tables(&table_list);
1341

1342 1343
    /* switch on VIEW optimisation: do not fill temporary tables */
    thd->lex->sql_command= SQLCOM_SHOW_FIELDS;
unknown's avatar
unknown committed
1344
    mysqld_list_fields(thd,&table_list,fields);
1345
    thd->lex->unit.cleanup();
1346
    thd->cleanup_after_query();
unknown's avatar
unknown committed
1347 1348 1349 1350
    break;
  }
#endif
  case COM_QUIT:
1351
    /* We don't calculate statistics for this command */
unknown's avatar
unknown committed
1352
    general_log_print(thd, command, NullS);
unknown's avatar
unknown committed
1353
    net->error=0;				// Don't give 'abort' message
1354
    thd->main_da.disable_status();              // Don't send anything back
unknown's avatar
unknown committed
1355 1356 1357
    error=TRUE;					// End server
    break;

1358
#ifdef REMOVED
unknown's avatar
unknown committed
1359
  case COM_CREATE_DB:				// QQ: To be removed
unknown's avatar
unknown committed
1360
    {
1361
      LEX_STRING db, alias;
1362
      HA_CREATE_INFO create_info;
unknown's avatar
unknown committed
1363

1364
      status_var_increment(thd->status_var.com_stat[SQLCOM_CREATE_DB]);
1365
      if (thd->make_lex_string(&db, packet, packet_length, FALSE) ||
1366
          thd->make_lex_string(&alias, db.str, db.length, FALSE) ||
1367
          check_db_name(&db))
1368
      {
1369
	my_error(ER_WRONG_DB_NAME, MYF(0), db.str ? db.str : "NULL");
1370 1371
	break;
      }
1372 1373
      if (check_access(thd, CREATE_ACL, db.str , 0, 1, 0,
                       is_schema_db(db.str)))
unknown's avatar
unknown committed
1374
	break;
unknown's avatar
unknown committed
1375
      general_log_print(thd, command, packet);
1376
      bzero(&create_info, sizeof(create_info));
1377
      mysql_create_db(thd, (lower_case_table_names == 2 ? alias.str : db.str),
1378
                      &create_info, 0);
unknown's avatar
unknown committed
1379 1380
      break;
    }
unknown's avatar
unknown committed
1381
  case COM_DROP_DB:				// QQ: To be removed
unknown's avatar
unknown committed
1382
    {
1383
      status_var_increment(thd->status_var.com_stat[SQLCOM_DROP_DB]);
1384 1385
      LEX_STRING db;

1386
      if (thd->make_lex_string(&db, packet, packet_length, FALSE) ||
1387
          check_db_name(&db))
1388
      {
1389
	my_error(ER_WRONG_DB_NAME, MYF(0), db.str ? db.str : "NULL");
1390 1391
	break;
      }
1392
      if (check_access(thd, DROP_ACL, db.str, 0, 1, 0, is_schema_db(db.str)))
1393
	break;
unknown's avatar
unknown committed
1394 1395
      if (thd->locked_tables || thd->active_transaction())
      {
unknown's avatar
unknown committed
1396 1397
	my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                   ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
unknown's avatar
unknown committed
1398
	break;
unknown's avatar
unknown committed
1399
      }
1400
      general_log_write(thd, command, db.str, db.length);
1401
      mysql_rm_db(thd, db.str, 0, 0);
unknown's avatar
unknown committed
1402 1403
      break;
    }
1404
#endif
1405
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
1406 1407
  case COM_BINLOG_DUMP:
    {
unknown's avatar
unknown committed
1408 1409 1410 1411
      ulong pos;
      ushort flags;
      uint32 slave_server_id;

1412
      status_var_increment(thd->status_var.com_other);
1413
      thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
unknown committed
1414
      if (check_global_access(thd, REPL_SLAVE_ACL))
unknown's avatar
unknown committed
1415
	break;
unknown's avatar
unknown committed
1416

1417
      /* TODO: The following has to be changed to an 8 byte integer */
1418 1419
      pos = uint4korr(packet);
      flags = uint2korr(packet + 4);
unknown's avatar
unknown committed
1420
      thd->server_id=0; /* avoid suicide */
unknown's avatar
unknown committed
1421
      if ((slave_server_id= uint4korr(packet+6))) // mysqlbinlog.server_id==0
unknown's avatar
unknown committed
1422
	kill_zombie_dump_threads(slave_server_id);
1423
      thd->server_id = slave_server_id;
unknown's avatar
unknown committed
1424

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

1485
    general_log_print(thd, command, NullS);
1486
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]);
1487
    calc_sum_of_all_status(&current_global_status_var);
1488 1489 1490 1491 1492
    if (!(uptime= (ulong) (thd->start_time - server_start_time)))
      queries_per_second1000= 0;
    else
      queries_per_second1000= thd->query_id * LL(1000) / uptime;

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

    switch (opt_command) {
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON:
1554
      thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
1555
      my_eof(thd);
1556
      break;
unknown's avatar
unknown committed
1557
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF:
1558
      thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
1559
      my_eof(thd);
1560 1561
      break;
    default:
unknown's avatar
unknown committed
1562
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1563 1564 1565 1566
      break;
    }
    break;
  }
unknown's avatar
unknown committed
1567
  case COM_DEBUG:
1568
    status_var_increment(thd->status_var.com_other);
unknown's avatar
unknown committed
1569
    if (check_global_access(thd, SUPER_ACL))
unknown's avatar
unknown committed
1570
      break;					/* purecov: inspected */
1571
    mysql_print_status();
unknown's avatar
unknown committed
1572
    general_log_print(thd, command, NullS);
1573
    my_eof(thd);
unknown's avatar
unknown committed
1574 1575 1576 1577 1578
    break;
  case COM_SLEEP:
  case COM_CONNECT:				// Impossible here
  case COM_TIME:				// Impossible from client
  case COM_DELAYED_INSERT:
1579
  case COM_END:
unknown's avatar
unknown committed
1580
  default:
unknown's avatar
unknown committed
1581
    my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
unknown's avatar
unknown committed
1582 1583
    break;
  }
1584

1585 1586 1587 1588 1589 1590
  /* 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();
1591

unknown's avatar
unknown committed
1592

unknown's avatar
unknown committed
1593
  /* report error issued during command execution */
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
  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;
  }

  net_end_statement(thd);
  query_cache_end_of_result(thd);
unknown's avatar
unknown committed
1607

1608 1609 1610 1611
  thd->proc_info= "closing tables";
  /* Free tables */
  close_thread_tables(thd);

1612
  log_slow_statement(thd);
1613

1614
  thd_proc_info(thd, "cleaning up");
1615
  VOID(pthread_mutex_lock(&LOCK_thread_count)); // For process list
1616
  thd_proc_info(thd, 0);
1617 1618 1619 1620 1621 1622 1623
  thd->command=COM_SLEEP;
  thd->query=0;
  thd->query_length=0;
  thread_running--;
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
  thd->packet.shrink(thd->variables.net_buffer_length);	// Reclaim some memory
  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634

  if (MYSQL_QUERY_DONE_ENABLED() || MYSQL_COMMAND_DONE_ENABLED())
  {
    int res;
    res= (int) thd->is_error();
    if (command == COM_QUERY)
    {
      MYSQL_QUERY_DONE(res);
    }
    MYSQL_COMMAND_DONE(res);
  }
1635 1636 1637 1638
  DBUG_RETURN(error);
}


1639
void log_slow_statement(THD *thd)
1640
{
unknown's avatar
unknown committed
1641
  DBUG_ENTER("log_slow_statement");
1642 1643 1644 1645 1646 1647 1648

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

1651 1652 1653 1654 1655
  /*
    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
1656
  {
1657
    ulonglong end_utime_of_query= thd->current_utime();
1658
    thd_proc_info(thd, "logging slow query");
1659

1660 1661 1662 1663
    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)) &&
1664 1665
          opt_log_queries_not_using_indexes &&
           !(sql_command_flags[thd->lex->sql_command] & CF_STATUS_COMMAND))) &&
1666
        thd->examined_row_count >= thd->variables.min_examined_row_limit)
1667
    {
1668
      thd_proc_info(thd, "logging slow query");
1669
      thd->status_var.long_query_count++;
1670
      slow_log_print(thd, thd->query, thd->query_length, end_utime_of_query);
1671
    }
unknown's avatar
unknown committed
1672
  }
unknown's avatar
unknown committed
1673
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1674 1675
}

1676

unknown's avatar
unknown committed
1677
/**
unknown's avatar
unknown committed
1678 1679 1680 1681 1682 1683 1684
  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
1685 1686 1687 1688 1689 1690 1691
  @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
1692 1693 1694 1695
    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
1696
  @retval
unknown's avatar
unknown committed
1697
    0                 success
unknown's avatar
unknown committed
1698
  @retval
unknown's avatar
unknown committed
1699 1700 1701 1702
    1                 out of memory or SHOW commands are not allowed
                      in this version of the server.
*/

1703 1704 1705
int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident,
                         enum enum_schema_tables schema_table_idx)
{
1706
  SELECT_LEX *schema_select_lex= NULL;
1707
  DBUG_ENTER("prepare_schema_table");
1708

1709
  switch (schema_table_idx) {
1710 1711
  case SCH_SCHEMATA:
#if defined(DONT_ALLOW_SHOW_COMMANDS)
unknown's avatar
unknown committed
1712 1713
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0));   /* purecov: inspected */
1714 1715 1716 1717
    DBUG_RETURN(1);
#else
    break;
#endif
1718

1719 1720 1721
  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
1722
  case SCH_TRIGGERS:
unknown's avatar
unknown committed
1723
  case SCH_EVENTS:
1724
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
1725 1726
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1727 1728 1729
    DBUG_RETURN(1);
#else
    {
1730
      LEX_STRING db;
1731
      size_t dummy;
unknown's avatar
unknown committed
1732
      if (lex->select_lex.db == NULL &&
1733
          lex->copy_db_to(&lex->select_lex.db, &dummy))
1734
      {
unknown's avatar
unknown committed
1735
        DBUG_RETURN(1);
1736
      }
1737 1738 1739
      schema_select_lex= new SELECT_LEX();
      db.str= schema_select_lex->db= lex->select_lex.db;
      schema_select_lex->table_list.first= NULL;
1740
      db.length= strlen(db.str);
unknown's avatar
unknown committed
1741

1742
      if (check_db_name(&db))
1743
      {
1744
        my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
1745 1746 1747 1748 1749 1750 1751
        DBUG_RETURN(1);
      }
      break;
    }
#endif
  case SCH_COLUMNS:
  case SCH_STATISTICS:
unknown's avatar
unknown committed
1752
  {
1753
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
1754 1755
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1756 1757
    DBUG_RETURN(1);
#else
unknown's avatar
unknown committed
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
    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;
  }
1769
#endif
1770 1771 1772 1773 1774
  case SCH_PROFILES:
    /* 
      Mark this current profiling record to be discarded.  We don't
      wish to have SHOW commands show up in profiling.
    */
1775 1776
#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
    thd->profiling.discard_current_query();
1777 1778
#endif
    break;
1779 1780 1781
  case SCH_OPEN_TABLES:
  case SCH_VARIABLES:
  case SCH_STATUS:
1782 1783
  case SCH_PROCEDURES:
  case SCH_CHARSETS:
unknown's avatar
unknown committed
1784
  case SCH_ENGINES:
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
  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
1803
  table_list->schema_select_lex= schema_select_lex;
1804
  table_list->schema_table_reformed= 1;
1805 1806 1807 1808
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
1809 1810 1811
/**
  Read query from packet and store in thd->query.
  Used in COM_QUERY and COM_STMT_PREPARE.
1812 1813

    Sets the following THD variables:
unknown's avatar
unknown committed
1814 1815
  - query
  - query_length
1816

unknown's avatar
unknown committed
1817
  @retval
unknown's avatar
unknown committed
1818
    FALSE ok
unknown's avatar
unknown committed
1819
  @retval
unknown's avatar
unknown committed
1820
    TRUE  error;  In this case thd->fatal_error is set
1821 1822
*/

1823
bool alloc_query(THD *thd, const char *packet, uint packet_length)
1824
{
1825
  /* Remove garbage at start and end of query */
1826
  while (packet_length > 0 && my_isspace(thd->charset(), packet[0]))
1827 1828 1829 1830
  {
    packet++;
    packet_length--;
  }
1831
  const char *pos= packet + packet_length;     // Point at end null
unknown's avatar
unknown committed
1832
  while (packet_length > 0 &&
unknown's avatar
unknown committed
1833
	 (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1])))
1834 1835 1836 1837 1838
  {
    pos--;
    packet_length--;
  }
  /* We must allocate some extra memory for query cache */
unknown's avatar
unknown committed
1839
  thd->query_length= 0;                        // Extra safety: Avoid races
1840
  if (!(thd->query= (char*) thd->memdup_w_gap((uchar*) (packet),
1841
					      packet_length,
1842 1843
					      thd->db_length+ 1 +
					      QUERY_CACHE_FLAGS_SIZE)))
unknown's avatar
unknown committed
1844
    return TRUE;
1845 1846
  thd->query[packet_length]=0;
  thd->query_length= packet_length;
1847 1848 1849 1850

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

unknown's avatar
unknown committed
1852
  return FALSE;
1853 1854
}

1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
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;
1868
  thd->variables.lc_time_names= &my_locale_en_US;
1869 1870 1871
  thd->one_shot_set= 0;
}

1872

1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
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);

1919
    if (thd->slave_thread && lex->sphead)
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
      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
1958 1959
/**
  Execute command saved in thd and lex->sql_command.
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970

    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
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
  @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
1983
    FALSE       OK
unknown's avatar
unknown committed
1984
  @retval
1985 1986
    TRUE        Error
*/
unknown's avatar
unknown committed
1987

1988
int
1989
mysql_execute_command(THD *thd)
unknown's avatar
unknown committed
1990
{
1991
  int res= FALSE;
1992
  bool need_start_waiting= FALSE; // have protection against global read lock
unknown's avatar
unknown committed
1993
  int  up_result= 0;
1994
  LEX  *lex= thd->lex;
unknown's avatar
unknown committed
1995
  /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
unknown's avatar
unknown committed
1996
  SELECT_LEX *select_lex= &lex->select_lex;
unknown's avatar
VIEW  
unknown committed
1997
  /* first table of first SELECT_LEX */
unknown's avatar
unknown committed
1998
  TABLE_LIST *first_table= (TABLE_LIST*) select_lex->table_list.first;
unknown's avatar
VIEW  
unknown committed
1999 2000 2001
  /* list of all tables in query */
  TABLE_LIST *all_tables;
  /* most outer SELECT_LEX_UNIT of query */
2002
  SELECT_LEX_UNIT *unit= &lex->unit;
2003 2004 2005 2006
#ifdef HAVE_REPLICATION
  /* have table map for update for multi-update statement (BUG#37051) */
  bool have_table_map_for_update= FALSE;
#endif
2007
  /* Saved variable value */
unknown's avatar
unknown committed
2008
  DBUG_ENTER("mysql_execute_command");
unknown's avatar
unknown committed
2009 2010 2011
#ifdef WITH_PARTITION_STORAGE_ENGINE
  thd->work_part_info= 0;
#endif
unknown's avatar
unknown committed
2012

unknown's avatar
VIEW  
unknown committed
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
  /*
    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();
2029
  /* should be assigned after making first tables same */
unknown's avatar
VIEW  
unknown committed
2030
  all_tables= lex->query_tables;
2031 2032 2033 2034
  /* 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
2035

2036 2037 2038 2039 2040
  /*
    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.
2041
    Don't reset warnings when executing a stored routine.
2042
  */
2043
  if ((all_tables || !lex->is_single_level_stmt()) && !thd->spcont)
unknown's avatar
unknown committed
2044
    mysql_reset_errors(thd, 0);
2045

unknown's avatar
SCRUM  
unknown committed
2046
#ifdef HAVE_REPLICATION
2047
  if (unlikely(thd->slave_thread))
2048
  {
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
    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;
    }
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113

    /*
      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;
    }
2114
    
unknown's avatar
unknown committed
2115
    /*
unknown's avatar
unknown committed
2116 2117
      Check if statment should be skipped because of slave filtering
      rules
2118 2119

      Exceptions are:
unknown's avatar
unknown committed
2120 2121
      - UPDATE MULTI: For this statement, we want to check the filtering
        rules later in the code
2122
      - SET: we always execute it (Not that many SET commands exists in
unknown's avatar
unknown committed
2123 2124
        the binary log anyway -- only 4.1 masters write SET statements,
	in 5.0 there are no SET statements in the binary log)
2125 2126
      - 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
2127
    */
unknown's avatar
unknown committed
2128 2129
    if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) &&
	!(lex->sql_command == SQLCOM_SET_OPTION) &&
2130
	!(lex->sql_command == SQLCOM_DROP_TABLE &&
2131
          lex->drop_temporary && lex->drop_if_exists) &&
unknown's avatar
Merge  
unknown committed
2132
        all_tables_not_ok(thd, all_tables))
unknown's avatar
unknown committed
2133 2134
    {
      /* we warn the slave SQL thread */
unknown's avatar
unknown committed
2135
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
      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);
      }
2153
      DBUG_RETURN(0);
unknown's avatar
unknown committed
2154
    }
2155
  }
2156
  else
2157
  {
2158
#endif /* HAVE_REPLICATION */
2159 2160 2161 2162
    /*
      When option readonly is set deny operations which change non-temporary
      tables. Except for the replication thread and the 'super' users.
    */
2163
    if (deny_updates_if_read_only_option(thd, all_tables))
2164 2165 2166 2167 2168 2169 2170
    {
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
      DBUG_RETURN(-1);
    }
#ifdef HAVE_REPLICATION
  } /* endif unlikely slave */
#endif
2171
  status_var_increment(thd->status_var.com_stat[lex->sql_command]);
2172

unknown's avatar
unknown committed
2173 2174
  DBUG_ASSERT(thd->transaction.stmt.modified_non_trans_table == FALSE);
  
unknown's avatar
unknown committed
2175
  switch (lex->sql_command) {
2176

2177
  case SQLCOM_SHOW_EVENTS:
2178 2179 2180 2181
#ifndef HAVE_EVENT_SCHEDULER
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server");
    break;
#endif
2182 2183
  case SQLCOM_SHOW_STATUS_PROC:
  case SQLCOM_SHOW_STATUS_FUNC:
2184 2185
    if (!(res= check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE)))
      res= execute_sqlcom_select(thd, all_tables);
2186 2187 2188 2189 2190
    break;
  case SQLCOM_SHOW_STATUS:
  {
    system_status_var old_status_var= thd->status_var;
    thd->initial_status_var= &old_status_var;
2191 2192
    if (!(res= check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE)))
      res= execute_sqlcom_select(thd, all_tables);
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
    /* 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:
2218
  case SQLCOM_SHOW_STORAGE_ENGINES:
2219
  case SQLCOM_SHOW_PROFILE:
unknown's avatar
unknown committed
2220
  case SQLCOM_SELECT:
2221
    thd->status_var.last_query_cost= 0.0;
unknown's avatar
VIEW  
unknown committed
2222
    if (all_tables)
unknown's avatar
unknown committed
2223
    {
2224 2225 2226
      res= check_table_access(thd,
                              lex->exchange ? SELECT_ACL | FILE_ACL :
                              SELECT_ACL,
2227
                              all_tables, UINT_MAX, FALSE);
unknown's avatar
unknown committed
2228 2229
    }
    else
unknown's avatar
VIEW  
unknown committed
2230
      res= check_access(thd,
2231 2232 2233 2234
                        lex->exchange ? SELECT_ACL | FILE_ACL : SELECT_ACL,
                        any_db, 0, 0, 0, 0);
    if (!res)
      res= execute_sqlcom_select(thd, all_tables);
unknown's avatar
unknown committed
2235
    break;
unknown's avatar
unknown committed
2236
  case SQLCOM_PREPARE:
2237
  {
2238
    mysql_sql_stmt_prepare(thd);
unknown's avatar
unknown committed
2239 2240 2241 2242
    break;
  }
  case SQLCOM_EXECUTE:
  {
2243
    mysql_sql_stmt_execute(thd);
unknown's avatar
unknown committed
2244 2245 2246 2247
    break;
  }
  case SQLCOM_DEALLOCATE_PREPARE:
  {
2248
    mysql_sql_stmt_close(thd);
unknown's avatar
unknown committed
2249 2250
    break;
  }
unknown's avatar
unknown committed
2251
  case SQLCOM_DO:
2252
    if (check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE) ||
2253
        open_and_lock_tables(thd, all_tables))
unknown's avatar
unknown committed
2254
      goto error;
unknown's avatar
unknown committed
2255 2256

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

2259
  case SQLCOM_EMPTY_QUERY:
2260
    my_ok(thd);
2261 2262
    break;

unknown's avatar
unknown committed
2263 2264 2265 2266
  case SQLCOM_HELP:
    res= mysqld_help(thd,lex->help_arg);
    break;

2267
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2268
  case SQLCOM_PURGE:
2269
  {
unknown's avatar
unknown committed
2270
    if (check_global_access(thd, SUPER_ACL))
2271
      goto error;
unknown's avatar
unknown committed
2272
    /* PURGE MASTER LOGS TO 'file' */
2273 2274 2275
    res = purge_master_logs(thd, lex->to_log);
    break;
  }
2276 2277
  case SQLCOM_PURGE_BEFORE:
  {
2278 2279
    Item *it;

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

unknown's avatar
unknown committed
2342
#ifdef HAVE_REPLICATION
2343 2344
  case SQLCOM_SHOW_SLAVE_HOSTS:
  {
unknown's avatar
unknown committed
2345
    if (check_global_access(thd, REPL_SLAVE_ACL))
2346 2347 2348 2349
      goto error;
    res = show_slave_hosts(thd);
    break;
  }
unknown's avatar
unknown committed
2350 2351
  case SQLCOM_SHOW_BINLOG_EVENTS:
  {
unknown's avatar
unknown committed
2352
    if (check_global_access(thd, REPL_SLAVE_ACL))
unknown's avatar
unknown committed
2353
      goto error;
2354
    res = mysql_show_binlog_events(thd);
unknown's avatar
unknown committed
2355 2356
    break;
  }
2357 2358
#endif

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

2441
  case SQLCOM_LOAD_MASTER_DATA: // sync with master
unknown's avatar
unknown committed
2442
    if (check_global_access(thd, SUPER_ACL))
2443
      goto error;
2444
    if (end_active_trans(thd))
unknown's avatar
unknown committed
2445
      goto error;
2446
    res = load_master_data(thd);
2447
    break;
unknown's avatar
unknown committed
2448
#endif /* HAVE_REPLICATION */
unknown's avatar
unknown committed
2449
  case SQLCOM_SHOW_ENGINE_STATUS:
unknown's avatar
unknown committed
2450
    {
2451
      if (check_global_access(thd, PROCESS_ACL))
unknown's avatar
unknown committed
2452 2453
        goto error;
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS);
unknown's avatar
unknown committed
2454 2455
      break;
    }
unknown's avatar
unknown committed
2456
  case SQLCOM_SHOW_ENGINE_MUTEX:
unknown's avatar
unknown committed
2457
    {
2458
      if (check_global_access(thd, PROCESS_ACL))
unknown's avatar
unknown committed
2459
        goto error;
unknown's avatar
unknown committed
2460
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX);
unknown's avatar
unknown committed
2461 2462
      break;
    }
unknown's avatar
unknown committed
2463
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
2464
  case SQLCOM_LOAD_MASTER_TABLE:
2465
  {
unknown's avatar
VIEW  
unknown committed
2466
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2467 2468
    DBUG_ASSERT(first_table->db); /* Must be set in the parser */

unknown's avatar
VIEW  
unknown committed
2469
    if (check_access(thd, CREATE_ACL, first_table->db,
2470 2471
		     &first_table->grant.privilege, 0, 0,
                     test(first_table->schema_table)))
unknown's avatar
unknown committed
2472
      goto error;				/* purecov: inspected */
2473 2474 2475 2476
    /* Check that the first table has CREATE privilege */
    if (check_grant(thd, CREATE_ACL, all_tables, 0, 1, 0))
      goto error;

2477
    pthread_mutex_lock(&LOCK_active_mi);
2478 2479 2480 2481
    /*
      fetch_master_table will send the error to the client on failure.
      Give error if the table already exists.
    */
2482
    if (!fetch_master_table(thd, first_table->db, first_table->table_name,
2483
			    active_mi, 0, 0))
2484
    {
2485
      my_ok(thd);
2486
    }
2487
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
2488
    break;
2489
  }
unknown's avatar
unknown committed
2490
#endif /* HAVE_REPLICATION */
2491

unknown's avatar
unknown committed
2492
  case SQLCOM_CREATE_TABLE:
unknown's avatar
unknown committed
2493
  {
2494
    /* If CREATE TABLE of non-temporary table, do implicit commit */
2495 2496 2497 2498 2499 2500 2501 2502
    if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
    {
      if (end_active_trans(thd))
      {
	res= -1;
	break;
      }
    }
unknown's avatar
VIEW  
unknown committed
2503 2504 2505 2506 2507
    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;
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
    /*
      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
2529

unknown's avatar
VIEW  
unknown committed
2530
    if ((res= create_table_precheck(thd, select_tables, create_table)))
unknown's avatar
unknown committed
2531
      goto end_with_restore_list;
unknown's avatar
unknown committed
2532

2533 2534 2535
    /* Might have been updated in create_table_precheck */
    create_info.alias= create_table->alias;

2536
#ifdef HAVE_READLINK
2537
    /* Fix names if symlinked tables */
2538
    if (append_file_to_dir(thd, &create_info.data_file_name,
2539
			   create_table->table_name) ||
2540
	append_file_to_dir(thd, &create_info.index_file_name,
2541
			   create_table->table_name))
unknown's avatar
unknown committed
2542
      goto end_with_restore_list;
2543
#endif
2544
    /*
2545
      If we are using SET CHARSET without DEFAULT, add an implicit
2546 2547
      DEFAULT to not confuse old users. (This may change).
    */
2548
    if ((create_info.used_fields &
2549 2550 2551
	 (HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) ==
	HA_CREATE_USED_CHARSET)
    {
2552 2553 2554 2555
      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;
2556
    }
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569
    /*
      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.
    */
2570 2571
    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
2572
    {
unknown's avatar
unknown committed
2573 2574
      res= 1;
      goto end_with_restore_list;
2575
    }
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586
#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
2587
    if (select_lex->item_list.elements)		// With select
unknown's avatar
unknown committed
2588 2589
    {
      select_result *result;
2590

2591
      select_lex->options|= SELECT_NO_UNLOCK;
2592
      unit->set_limit(select_lex);
2593

2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
      /*
        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;
      }

2607
      if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
unknown's avatar
unknown committed
2608 2609 2610 2611 2612 2613
      {
        lex->link_first_table_back(create_table, link_to_local);
        create_table->create= TRUE;
      }

      if (!(res= open_and_lock_tables(thd, lex->query_tables)))
2614
      {
2615 2616 2617 2618
        /*
          Is table which we are changing used somewhere in other parts
          of query
        */
2619
        if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
2620
        {
2621
          TABLE_LIST *duplicate;
unknown's avatar
unknown committed
2622
          create_table= lex->unlink_first_table(&link_to_local);
2623
          if ((duplicate= unique_table(thd, create_table, select_tables, 0)))
2624 2625 2626
          {
            update_non_unique_table_error(create_table, "CREATE", duplicate);
            res= 1;
2627
            goto end_with_restore_list;
2628
          }
2629
        }
unknown's avatar
unknown committed
2630
        /* If we create merge table, we have to test tables in merge, too */
2631
        if (create_info.used_fields & HA_CREATE_USED_UNION)
unknown's avatar
unknown committed
2632 2633
        {
          TABLE_LIST *tab;
2634
          for (tab= (TABLE_LIST*) create_info.merge_list.first;
unknown's avatar
unknown committed
2635 2636 2637
               tab;
               tab= tab->next_local)
          {
2638
            TABLE_LIST *duplicate;
2639
            if ((duplicate= unique_table(thd, tab, select_tables, 0)))
unknown's avatar
unknown committed
2640
            {
2641
              update_non_unique_table_error(tab, "CREATE", duplicate);
unknown's avatar
unknown committed
2642
              res= 1;
2643
              goto end_with_restore_list;
unknown's avatar
unknown committed
2644 2645 2646
            }
          }
        }
2647

unknown's avatar
unknown committed
2648
        /*
2649 2650
          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
2651
        */
unknown's avatar
VIEW  
unknown committed
2652
        if ((result= new select_create(create_table,
2653 2654 2655 2656
                                       &create_info,
                                       &alter_info,
                                       select_lex->item_list,
                                       lex->duplicates,
2657
                                       lex->ignore,
2658
                                       select_tables)))
2659 2660 2661 2662 2663
        {
          /*
            CREATE from SELECT give its SELECT_LEX for SELECT,
            and item_list belong to SELECT
          */
2664
          res= handle_select(thd, lex, result, 0);
2665
          delete result;
2666
        }
2667
      }
2668
      else if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
unknown's avatar
unknown committed
2669 2670
        create_table= lex->unlink_first_table(&link_to_local);

2671
    }
unknown's avatar
unknown committed
2672
    else
unknown's avatar
unknown committed
2673
    {
2674
      /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
2675
      if (create_info.options & HA_LEX_CREATE_TMP_TABLE)
2676
        thd->options|= OPTION_KEEP_LOG;
unknown's avatar
unknown committed
2677
      /* regular create */
2678
      if (create_info.options & HA_LEX_CREATE_TABLE_LIKE)
unknown's avatar
unknown committed
2679
        res= mysql_create_like_table(thd, create_table, select_tables,
2680
                                     &create_info);
unknown's avatar
unknown committed
2681
      else
2682
      {
unknown's avatar
VIEW  
unknown committed
2683
        res= mysql_create_table(thd, create_table->db,
2684 2685
                                create_table->table_name, &create_info,
                                &alter_info, 0, 0);
2686
      }
unknown's avatar
unknown committed
2687
      if (!res)
2688
	my_ok(thd);
unknown's avatar
unknown committed
2689
    }
2690

unknown's avatar
unknown committed
2691
    /* put tables back for PS rexecuting */
unknown's avatar
unknown committed
2692
end_with_restore_list:
unknown's avatar
VIEW  
unknown committed
2693
    lex->link_first_table_back(create_table, link_to_local);
unknown's avatar
unknown committed
2694
    break;
unknown's avatar
unknown committed
2695
  }
unknown's avatar
unknown committed
2696
  case SQLCOM_CREATE_INDEX:
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714
    /* 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
2715 2716
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_one_table_access(thd, INDEX_ACL, all_tables))
unknown's avatar
unknown committed
2717
      goto error; /* purecov: inspected */
2718
    if (end_active_trans(thd))
unknown's avatar
unknown committed
2719
      goto error;
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
    /*
      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
2731

2732 2733 2734 2735 2736
    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
2737
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
2738
  case SQLCOM_SLAVE_START:
2739
  {
2740
    pthread_mutex_lock(&LOCK_active_mi);
2741
    start_slave(thd,active_mi,1 /* net report*/);
2742
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
2743
    break;
2744
  }
unknown's avatar
unknown committed
2745
  case SQLCOM_SLAVE_STOP:
2746 2747 2748 2749 2750 2751
  /*
    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,
2752
      so it waits for the client thread because t is locked by it.
2753
    - then the client thread does SLAVE STOP.
2754 2755
      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.
2756 2757 2758
    To prevent that, refuse SLAVE STOP if the
    client thread has locked tables
  */
2759
  if (thd->locked_tables || thd->active_transaction() || thd->global_read_lock)
2760
  {
2761 2762
    my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
               ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2763
    goto error;
2764
  }
2765
  {
2766
    pthread_mutex_lock(&LOCK_active_mi);
2767
    stop_slave(thd,active_mi,1/* net report*/);
2768
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
2769
    break;
2770
  }
unknown's avatar
unknown committed
2771
#endif /* HAVE_REPLICATION */
2772

unknown's avatar
unknown committed
2773
  case SQLCOM_ALTER_TABLE:
unknown's avatar
VIEW  
unknown committed
2774
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2775
    {
unknown's avatar
unknown committed
2776
      ulong priv=0;
unknown's avatar
unknown committed
2777
      ulong priv_needed= ALTER_ACL;
2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788
      /*
        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;
2789 2790 2791 2792
      /*
        We also require DROP priv for ALTER TABLE ... DROP PARTITION, as well
        as for RENAME TO, as being done by SQLCOM_RENAME_TABLE
      */
2793
      if (alter_info.flags & (ALTER_DROP_PARTITION | ALTER_RENAME))
unknown's avatar
unknown committed
2794 2795
        priv_needed|= DROP_ACL;

unknown's avatar
unknown committed
2796 2797
      /* Must be set in the parser */
      DBUG_ASSERT(select_lex->db);
unknown's avatar
unknown committed
2798
      if (check_access(thd, priv_needed, first_table->db,
2799 2800 2801 2802
		       &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
2803
	  check_merge_table_access(thd, first_table->db,
2804
				   (TABLE_LIST *)
2805
				   create_info.merge_list.first))
2806
	goto error;				/* purecov: inspected */
2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818
      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
2819
      }
2820

2821
      /* Don't yet allow changing of symlinks with ALTER TABLE */
2822
      if (create_info.data_file_name)
2823 2824 2825
        push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                            WARN_OPTION_IGNORED, ER(WARN_OPTION_IGNORED),
                            "DATA DIRECTORY");
2826
      if (create_info.index_file_name)
2827 2828 2829
        push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                            WARN_OPTION_IGNORED, ER(WARN_OPTION_IGNORED),
                            "INDEX DIRECTORY");
2830
      create_info.data_file_name= create_info.index_file_name= NULL;
unknown's avatar
unknown committed
2831
      /* ALTER TABLE ends previous transaction */
2832
      if (end_active_trans(thd))
unknown's avatar
unknown committed
2833
	goto error;
2834

2835 2836 2837 2838 2839
      if (!thd->locked_tables &&
          !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      {
        res= 1;
        break;
unknown's avatar
unknown committed
2840
      }
2841

2842
      thd->enable_slow_log= opt_log_slow_admin_statements;
2843
      res= mysql_alter_table(thd, select_lex->db, lex->name.str,
2844 2845 2846
                             &create_info,
                             first_table,
                             &alter_info,
2847 2848
                             select_lex->order_list.elements,
                             (ORDER *) select_lex->order_list.first,
2849
                             lex->ignore);
unknown's avatar
unknown committed
2850 2851
      break;
    }
unknown's avatar
unknown committed
2852
  case SQLCOM_RENAME_TABLE:
unknown's avatar
unknown committed
2853
  {
unknown's avatar
VIEW  
unknown committed
2854
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2855
    TABLE_LIST *table;
unknown's avatar
VIEW  
unknown committed
2856
    for (table= first_table; table; table= table->next_local->next_local)
unknown's avatar
unknown committed
2857
    {
unknown's avatar
unknown committed
2858
      if (check_access(thd, ALTER_ACL | DROP_ACL, table->db,
2859
		       &table->grant.privilege,0,0, test(table->schema_table)) ||
unknown's avatar
VIEW  
unknown committed
2860
	  check_access(thd, INSERT_ACL | CREATE_ACL, table->next_local->db,
2861 2862
		       &table->next_local->grant.privilege, 0, 0,
                       test(table->next_local->schema_table)))
unknown's avatar
unknown committed
2863
	goto error;
2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875
      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
2876
    }
2877

unknown's avatar
unknown committed
2878
    if (end_active_trans(thd) || mysql_rename_tables(thd, first_table, 0))
unknown's avatar
unknown committed
2879
      goto error;
unknown's avatar
unknown committed
2880
    break;
unknown's avatar
unknown committed
2881
  }
2882
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2883 2884
  case SQLCOM_SHOW_BINLOGS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
2885 2886
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2887
    goto error;
unknown's avatar
unknown committed
2888 2889
#else
    {
unknown's avatar
unknown committed
2890
      if (check_global_access(thd, SUPER_ACL))
unknown's avatar
unknown committed
2891 2892 2893 2894
	goto error;
      res = show_binlogs(thd);
      break;
    }
unknown's avatar
unknown committed
2895
#endif
2896
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
2897
  case SQLCOM_SHOW_CREATE:
unknown's avatar
VIEW  
unknown committed
2898
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
2899
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
2900 2901
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2902
    goto error;
unknown's avatar
unknown committed
2903
#else
unknown's avatar
unknown committed
2904
    {
2905 2906 2907
      /* Ignore temporary tables if this is "SHOW CREATE VIEW" */
      if (lex->only_view)
        first_table->skip_temporary= 1;
unknown's avatar
unknown committed
2908
      if (check_show_create_table_access(thd, first_table))
2909
	goto error;
unknown's avatar
unknown committed
2910
      res= mysqld_show_create(thd, first_table);
unknown's avatar
unknown committed
2911 2912
      break;
    }
unknown's avatar
unknown committed
2913
#endif
2914 2915
  case SQLCOM_CHECKSUM:
  {
unknown's avatar
VIEW  
unknown committed
2916
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2917 2918
    if (check_table_access(thd, SELECT_ACL | EXTRA_ACL, all_tables,
                           UINT_MAX, FALSE))
2919
      goto error; /* purecov: inspected */
unknown's avatar
VIEW  
unknown committed
2920
    res = mysql_checksum_table(thd, first_table, &lex->check_opt);
2921 2922
    break;
  }
unknown's avatar
unknown committed
2923
  case SQLCOM_REPAIR:
2924
  {
unknown's avatar
VIEW  
unknown committed
2925
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2926 2927
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables,
                           UINT_MAX, FALSE))
2928
      goto error; /* purecov: inspected */
2929
    thd->enable_slow_log= opt_log_slow_admin_statements;
unknown's avatar
VIEW  
unknown committed
2930
    res= mysql_repair_table(thd, first_table, &lex->check_opt);
2931 2932 2933
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2934 2935 2936
      /*
        Presumably, REPAIR and binlog writing doesn't require synchronization
      */
2937
      write_bin_log(thd, TRUE, thd->query, thd->query_length);
2938
    }
2939
    select_lex->table_list.first= (uchar*) first_table;
2940
    lex->query_tables=all_tables;
2941 2942
    break;
  }
unknown's avatar
unknown committed
2943
  case SQLCOM_CHECK:
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 | EXTRA_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_check_table(thd, first_table, &lex->check_opt);
2951
    select_lex->table_list.first= (uchar*) first_table;
2952
    lex->query_tables=all_tables;
2953 2954
    break;
  }
unknown's avatar
unknown committed
2955 2956
  case SQLCOM_ANALYZE:
  {
unknown's avatar
VIEW  
unknown committed
2957
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2958 2959
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables,
                           UINT_MAX, FALSE))
unknown's avatar
unknown committed
2960
      goto error; /* purecov: inspected */
2961
    thd->enable_slow_log= opt_log_slow_admin_statements;
2962
    res= mysql_analyze_table(thd, first_table, &lex->check_opt);
2963 2964 2965
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2966 2967 2968
      /*
        Presumably, ANALYZE and binlog writing doesn't require synchronization
      */
2969
      write_bin_log(thd, TRUE, thd->query, thd->query_length);
2970
    }
2971
    select_lex->table_list.first= (uchar*) first_table;
2972
    lex->query_tables=all_tables;
unknown's avatar
unknown committed
2973
    break;
unknown's avatar
unknown committed
2974
  }
2975

unknown's avatar
unknown committed
2976 2977
  case SQLCOM_OPTIMIZE:
  {
unknown's avatar
VIEW  
unknown committed
2978
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2979 2980
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables,
                           UINT_MAX, FALSE))
unknown's avatar
unknown committed
2981
      goto error; /* purecov: inspected */
2982
    thd->enable_slow_log= opt_log_slow_admin_statements;
2983
    res= (specialflag & (SPECIAL_SAFE_MODE | SPECIAL_NO_NEW_FUNC)) ?
2984
      mysql_recreate_table(thd, first_table) :
unknown's avatar
VIEW  
unknown committed
2985
      mysql_optimize_table(thd, first_table, &lex->check_opt);
2986 2987 2988
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2989 2990 2991
      /*
        Presumably, OPTIMIZE and binlog writing doesn't require synchronization
      */
2992
      write_bin_log(thd, TRUE, thd->query, thd->query_length);
2993
    }
2994
    select_lex->table_list.first= (uchar*) first_table;
2995
    lex->query_tables=all_tables;
unknown's avatar
unknown committed
2996 2997 2998
    break;
  }
  case SQLCOM_UPDATE:
2999 3000
  {
    ha_rows found= 0, updated= 0;
unknown's avatar
VIEW  
unknown committed
3001 3002
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (update_precheck(thd, all_tables))
unknown's avatar
unknown committed
3003
      break;
3004 3005
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
3006
    MYSQL_UPDATE_START(thd->query);
unknown's avatar
unknown committed
3007 3008 3009 3010 3011 3012 3013
    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,
3014 3015 3016
                                  lex->duplicates, lex->ignore,
                                  &found, &updated));
    MYSQL_UPDATE_DONE(res, found, updated);
3017
    /* mysql_update return 2 if we need to switch to multi-update */
unknown's avatar
unknown committed
3018
    if (up_result != 2)
3019
      break;
unknown's avatar
unknown committed
3020
    /* Fall through */
3021
  }
3022
  case SQLCOM_UPDATE_MULTI:
unknown's avatar
unknown committed
3023 3024 3025
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    /* if we switched from normal update, rights are checked */
unknown's avatar
unknown committed
3026
    if (up_result != 2)
3027
    {
unknown's avatar
unknown committed
3028 3029 3030 3031 3032
      if ((res= multi_update_precheck(thd, all_tables)))
        break;
    }
    else
      res= 0;
unknown's avatar
unknown committed
3033

3034
    res= mysql_multi_update_prepare(thd);
unknown's avatar
unknown committed
3035

3036
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
3037
    /* Check slave filtering rules */
3038
    if (unlikely(thd->slave_thread && !have_table_map_for_update))
unknown's avatar
unknown committed
3039
    {
3040 3041
      if (all_tables_not_ok(thd, all_tables))
      {
3042 3043 3044 3045 3046
        if (res!= 0)
        {
          res= 0;             /* don't care of prev failure  */
          thd->clear_error(); /* filters are of highest prior */
        }
3047 3048 3049 3050
        /* we warn the slave SQL thread */
        my_error(ER_SLAVE_IGNORED_TABLE, MYF(0));
        break;
      }
3051 3052
      if (res)
        break;
unknown's avatar
unknown committed
3053
    }
3054 3055
    else
    {
3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068
#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
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
    {
      multi_update *result_obj;
      MYSQL_MULTI_UPDATE_START(thd->query);
      res= mysql_multi_update(thd, all_tables,
                              &select_lex->item_list,
                              &lex->value_list,
                              select_lex->where,
                              select_lex->options,
                              lex->duplicates,
                              lex->ignore,
                              unit,
                              select_lex,
                              &result_obj);
      if (result_obj)
      {
        MYSQL_MULTI_UPDATE_DONE(res, result_obj->num_found(),
                                result_obj->num_updated());
        res= FALSE; /* Ignore errors here */
        delete result_obj;
      }
      else
      {
        MYSQL_MULTI_UPDATE_DONE(1, 0, 0);
      }
    }
unknown's avatar
unknown committed
3094
    break;
unknown's avatar
unknown committed
3095
  }
unknown's avatar
unknown committed
3096
  case SQLCOM_REPLACE:
3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126
#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
3127 3128
  case SQLCOM_INSERT:
  {
unknown's avatar
VIEW  
unknown committed
3129
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
3130
    if ((res= insert_precheck(thd, all_tables)))
unknown's avatar
unknown committed
3131
      break;
3132 3133 3134 3135 3136 3137 3138

    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
    {
      res= 1;
      break;
    }
3139
    MYSQL_INSERT_START(thd->query);
unknown's avatar
VIEW  
unknown committed
3140
    res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
unknown's avatar
unknown committed
3141
		      lex->update_list, lex->value_list,
3142
                      lex->duplicates, lex->ignore);
3143
    MYSQL_INSERT_DONE(res, (ulong) thd->row_count_func);
3144 3145 3146 3147 3148 3149
    /*
      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
3150
    if (first_table->view && !first_table->contain_auto_increment)
3151 3152
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
3153

unknown's avatar
unknown committed
3154
    break;
3155
  }
unknown's avatar
unknown committed
3156 3157 3158
  case SQLCOM_REPLACE_SELECT:
  case SQLCOM_INSERT_SELECT:
  {
unknown's avatar
unknown committed
3159
    select_result *sel_result;
unknown's avatar
VIEW  
unknown committed
3160
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
3161
    if ((res= insert_precheck(thd, all_tables)))
3162
      break;
unknown's avatar
unknown committed
3163

3164
    /* Fix lock for first table */
unknown's avatar
VIEW  
unknown committed
3165 3166
    if (first_table->lock_type == TL_WRITE_DELAYED)
      first_table->lock_type= TL_WRITE;
3167

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

3171
    unit->set_limit(select_lex);
3172 3173 3174 3175 3176 3177 3178

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

unknown's avatar
unknown committed
3228 3229
    break;
  }
3230
  case SQLCOM_TRUNCATE:
3231 3232 3233 3234 3235
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
unknown's avatar
VIEW  
unknown committed
3236
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
3237
    if (check_one_table_access(thd, DROP_ACL, all_tables))
unknown's avatar
unknown committed
3238
      goto error;
3239 3240 3241 3242
    /*
      Don't allow this within a transaction because we want to use
      re-generate table
    */
3243
    if (thd->locked_tables || thd->active_transaction())
3244
    {
unknown's avatar
unknown committed
3245 3246
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3247 3248
      goto error;
    }
unknown's avatar
VIEW  
unknown committed
3249

unknown's avatar
unknown committed
3250
    res= mysql_truncate(thd, first_table, 0);
3251
    break;
unknown's avatar
unknown committed
3252
  case SQLCOM_DELETE:
unknown's avatar
unknown committed
3253
  {
unknown's avatar
VIEW  
unknown committed
3254 3255
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if ((res= delete_precheck(thd, all_tables)))
unknown's avatar
unknown committed
3256
      break;
3257 3258
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
3259 3260 3261 3262 3263 3264 3265

    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
    {
      res= 1;
      break;
    }
3266
    MYSQL_DELETE_START(thd->query);
unknown's avatar
VIEW  
unknown committed
3267
    res = mysql_delete(thd, all_tables, select_lex->where,
3268
                       &select_lex->order_list,
unknown's avatar
unknown committed
3269 3270
                       unit->select_limit_cnt, select_lex->options,
                       FALSE);
3271
    MYSQL_DELETE_DONE(res, (ulong) thd->row_count_func);
unknown's avatar
unknown committed
3272 3273
    break;
  }
3274
  case SQLCOM_DELETE_MULTI:
unknown's avatar
unknown committed
3275
  {
unknown's avatar
VIEW  
unknown committed
3276
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3277
    TABLE_LIST *aux_tables=
unknown's avatar
unknown committed
3278
      (TABLE_LIST *)thd->lex->auxiliary_table_list.first;
unknown's avatar
unknown committed
3279
    multi_delete *del_result;
unknown's avatar
unknown committed
3280

3281 3282 3283 3284 3285 3286 3287
    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
    {
      res= 1;
      break;
    }

3288
    if ((res= multi_delete_precheck(thd, all_tables)))
3289
      break;
unknown's avatar
unknown committed
3290

unknown's avatar
unknown committed
3291
    /* condition will be TRUE on SP re-excuting */
3292 3293
    if (select_lex->item_list.elements != 0)
      select_lex->item_list.empty();
unknown's avatar
unknown committed
3294
    if (add_item_to_list(thd, new Item_null()))
unknown's avatar
unknown committed
3295
      goto error;
3296

3297
    thd_proc_info(thd, "init");
unknown's avatar
VIEW  
unknown committed
3298 3299 3300
    if ((res= open_and_lock_tables(thd, all_tables)))
      break;

3301
    MYSQL_MULTI_DELETE_START(thd->query);
unknown's avatar
VIEW  
unknown committed
3302
    if ((res= mysql_multi_delete_prepare(thd)))
3303 3304
    {
      MYSQL_MULTI_DELETE_DONE(1, 0);
unknown's avatar
unknown committed
3305
      goto error;
3306
    }
3307

unknown's avatar
unknown committed
3308 3309
    if (!thd->is_fatal_error &&
        (del_result= new multi_delete(aux_tables, lex->table_count)))
unknown's avatar
unknown committed
3310
    {
3311 3312 3313
      res= mysql_select(thd, &select_lex->ref_pointer_array,
			select_lex->get_table_list(),
			select_lex->with_wild,
3314
			select_lex->item_list,
unknown's avatar
unknown committed
3315
			select_lex->where,
3316
			0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL,
unknown's avatar
unknown committed
3317 3318
			(ORDER *)NULL,
			select_lex->options | thd->options |
3319 3320
			SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
                        OPTION_SETUP_TABLES_DONE,
unknown's avatar
unknown committed
3321
			del_result, unit, select_lex);
3322
      res|= thd->is_error();
3323
      MYSQL_MULTI_DELETE_DONE(res, del_result->num_deleted());
3324
      if (res)
3325
        del_result->abort();
unknown's avatar
unknown committed
3326
      delete del_result;
unknown's avatar
unknown committed
3327 3328
    }
    else
3329
    {
3330
      res= TRUE;                                // Error
3331 3332
      MYSQL_MULTI_DELETE_DONE(1, 0);
    }
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;

unknown's avatar
VIEW  
unknown committed
3431
    res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
unknown's avatar
unknown committed
3432
                    lex->update_list, lex->value_list, lex->duplicates,
3433
                    lex->ignore, (bool) lex->local_file);
unknown's avatar
unknown committed
3434 3435
    break;
  }
3436

unknown's avatar
unknown committed
3437
  case SQLCOM_SET_OPTION:
3438 3439
  {
    List<set_var_base> *lex_var_list= &lex->var_list;
3440 3441 3442 3443

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

3444
    if ((check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE) ||
unknown's avatar
unknown committed
3445 3446
	 open_and_lock_tables(thd, all_tables)))
      goto error;
3447 3448
    if (lex->one_shot_set && not_all_support_one_shot(lex_var_list))
    {
unknown's avatar
unknown committed
3449 3450
      my_error(ER_RESERVED_SYNTAX, MYF(0), "SET ONE_SHOT");
      goto error;
3451 3452 3453 3454 3455 3456 3457 3458
    }
    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;
3459
      my_ok(thd);
3460
    }
3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472
    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
3473
    break;
3474
  }
unknown's avatar
unknown committed
3475

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

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

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

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

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

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

3829
    if (check_access(thd, lex->grant | lex->grant_tot_col | GRANT_ACL,
unknown's avatar
unknown committed
3830
		     first_table ?  first_table->db : select_lex->db,
unknown's avatar
VIEW  
unknown committed
3831
		     first_table ? &first_table->grant.privilege : 0,
3832 3833 3834
		     first_table ? 0 : 1, 0,
                     first_table ? (bool) first_table->schema_table :
                     select_lex->db ? is_schema_db(select_lex->db) : 0))
3835 3836
      goto error;

3837
    if (thd->security_ctx->user)              // If not replication
unknown's avatar
unknown committed
3838
    {
3839
      LEX_USER *user, *tmp_user;
3840

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

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

unknown's avatar
unknown committed
3966 3967 3968 3969 3970 3971 3972
    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;
    }

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

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

4146
    DBUG_ASSERT(lex->sphead != 0);
unknown's avatar
unknown committed
4147
    DBUG_ASSERT(lex->sphead->m_db.str); /* Must be initialized in the parser */
4148 4149 4150 4151
    /*
      Verify that the database name is allowed, optionally
      lowercase it.
    */
4152
    if (check_db_name(&lex->sphead->m_db))
4153
    {
4154
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->sphead->m_db.str);
4155
      goto create_sp_error;
4156 4157
    }

4158
    /*
4159 4160 4161
      Check that a database directory with this name
      exists. Design note: This won't work on virtual databases
      like information_schema.
4162 4163
    */
    if (check_db_dir_existence(lex->sphead->m_db.str))
4164
    {
4165
      my_error(ER_BAD_DB_ERROR, MYF(0), lex->sphead->m_db.str);
4166
      goto create_sp_error;
4167
    }
4168

4169 4170
    if (check_access(thd, CREATE_PROC_ACL, lex->sphead->m_db.str, 0, 0, 0,
                     is_schema_db(lex->sphead->m_db.str)))
4171
      goto create_sp_error;
4172

4173 4174
    if (end_active_trans(thd))
      goto create_sp_error;
4175 4176

    name= lex->sphead->name(&namelen);
4177
#ifdef HAVE_DLOPEN
unknown's avatar
unknown committed
4178 4179 4180
    if (lex->sphead->m_type == TYPE_ENUM_FUNCTION)
    {
      udf_func *udf = find_udf(name, namelen);
4181

unknown's avatar
unknown committed
4182
      if (udf)
4183
      {
4184 4185
        my_error(ER_UDF_EXISTS, MYF(0), name);
        goto create_sp_error;
4186
      }
unknown's avatar
unknown committed
4187 4188 4189
    }
#endif

4190 4191
    if (sp_process_definer(thd))
      goto create_sp_error;
4192

unknown's avatar
unknown committed
4193 4194
    res= (sp_result= lex->sphead->create(thd));
    switch (sp_result) {
4195
    case SP_OK:
unknown's avatar
unknown committed
4196
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4197
      /* only add privileges if really neccessary */
4198
      if (sp_automatic_privileges && !opt_noacl &&
4199
          check_routine_access(thd, DEFAULT_CREATE_PROC_ACLS,
4200
                               lex->sphead->m_db.str, name,
4201
                               lex->sql_command == SQLCOM_CREATE_PROCEDURE, 1))
4202
      {
unknown's avatar
unknown committed
4203
        if (sp_grant_privileges(thd, lex->sphead->m_db.str, name,
4204
                                lex->sql_command == SQLCOM_CREATE_PROCEDURE))
4205 4206 4207
          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                       ER_PROC_AUTO_GRANT_FAIL,
                       ER(ER_PROC_AUTO_GRANT_FAIL));
4208
      }
unknown's avatar
unknown committed
4209
#endif
unknown's avatar
unknown committed
4210
    break;
4211 4212 4213 4214 4215 4216 4217 4218 4219
    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;
4220 4221 4222
    case SP_FLD_STORE_FAILED:
      my_error(ER_CANT_CREATE_SROUTINE, MYF(0), name);
      break;
4223 4224 4225 4226 4227 4228 4229 4230 4231 4232
    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
4233
    if (sp_result != SP_OK )
4234
      goto error;
4235
    my_ok(thd);
4236 4237
    break; /* break super switch */
  } /* end case group bracket */
4238 4239 4240 4241
  case SQLCOM_CALL:
    {
      sp_head *sp;

4242 4243 4244 4245
      /*
        This will cache all SP and SF and open and lock all tables
        required for execution.
      */
4246
      if (check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE) ||
4247 4248 4249 4250
	  open_and_lock_tables(thd, all_tables))
       goto error;

      /*
4251 4252
        By this moment all needed SPs should be in cache so no need to look 
        into DB. 
4253
      */
4254 4255
      if (!(sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                                &thd->sp_proc_cache, TRUE)))
4256
      {
4257
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PROCEDURE",
unknown's avatar
unknown committed
4258
                 lex->spname->m_qname.str);
4259
	goto error;
4260 4261 4262
      }
      else
      {
unknown's avatar
unknown committed
4263
	ha_rows select_limit;
unknown's avatar
unknown committed
4264 4265
        /* bits that should be cleared in thd->server_status */
	uint bits_to_be_cleared= 0;
4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277
        /*
          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;
        }
4278

4279
	if (sp->m_flags & sp_head::MULTI_RESULTS)
4280
	{
4281
	  if (! (thd->client_capabilities & CLIENT_MULTI_RESULTS))
4282
	  {
4283 4284 4285 4286
            /*
              The client does not support multiple result sets being sent
              back
            */
4287
	    my_error(ER_SP_BADSELECT, MYF(0), sp->m_qname.str);
4288 4289
	    goto error;
	  }
unknown's avatar
unknown committed
4290 4291 4292 4293 4294 4295 4296
          /*
            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;
4297 4298
	}

4299
	if (check_routine_access(thd, EXECUTE_ACL,
4300
				 sp->m_db.str, sp->m_name.str, TRUE, FALSE))
4301 4302 4303
	{
	  goto error;
	}
unknown's avatar
unknown committed
4304 4305
	select_limit= thd->variables.select_limit;
	thd->variables.select_limit= HA_POS_ERROR;
4306

4307
        /* 
4308
          We never write CALL statements into binlog:
4309 4310 4311 4312 4313
           - 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.
4314
        */
4315
	res= sp->execute_procedure(thd, &lex->value_list);
4316 4317 4318
	/*
          If warnings have been cleared, we have to clear total_warn_count
          too, otherwise the clients get confused.
4319 4320 4321 4322
	 */
	if (thd->warn_list.is_empty())
	  thd->total_warn_count= 0;

unknown's avatar
unknown committed
4323
	thd->variables.select_limit= select_limit;
4324

unknown's avatar
unknown committed
4325
        thd->server_status&= ~bits_to_be_cleared;
4326

unknown's avatar
unknown committed
4327
	if (!res)
4328 4329
          my_ok(thd, (ulong) (thd->row_count_func < 0 ? 0 :
                              thd->row_count_func));
4330
	else
4331
        {
4332
          DBUG_ASSERT(thd->is_error() || thd->killed);
4333
	  goto error;		// Substatement should already have sent error
4334
        }
4335
      }
4336
      break;
4337 4338
    }
  case SQLCOM_ALTER_PROCEDURE:
4339
  case SQLCOM_ALTER_FUNCTION:
4340
    {
unknown's avatar
unknown committed
4341
      int sp_result;
4342 4343 4344 4345
      sp_head *sp;
      st_sp_chistics chistics;

      memcpy(&chistics, &lex->sp_chistics, sizeof(chistics));
unknown's avatar
unknown committed
4346
      if (lex->sql_command == SQLCOM_ALTER_PROCEDURE)
4347 4348
        sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                            &thd->sp_proc_cache, FALSE);
4349
      else
4350 4351
        sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                            &thd->sp_func_cache, FALSE);
unknown's avatar
unknown committed
4352
      mysql_reset_errors(thd, 0);
4353
      if (! sp)
4354 4355
      {
	if (lex->spname->m_db.str)
unknown's avatar
unknown committed
4356
	  sp_result= SP_KEY_NOT_FOUND;
4357 4358 4359 4360 4361 4362
	else
	{
	  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
	  goto error;
	}
      }
4363 4364
      else
      {
4365 4366 4367
        if (check_routine_access(thd, ALTER_PROC_ACL, sp->m_db.str, 
				 sp->m_name.str,
                                 lex->sql_command == SQLCOM_ALTER_PROCEDURE, 0))
4368
	  goto error;
4369 4370 4371

        if (end_active_trans(thd)) 
          goto error;
4372
	memcpy(&lex->sp_chistics, &chistics, sizeof(lex->sp_chistics));
4373 4374
        if ((sp->m_type == TYPE_ENUM_FUNCTION) &&
            !trust_function_creators &&  mysql_bin_log.is_open() &&
4375 4376 4377 4378 4379 4380
            !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
4381
          sp_result= SP_INTERNAL_ERROR;
4382 4383 4384
        }
        else
        {
4385 4386 4387 4388 4389 4390
          /*
            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
4391
          /* Conditionally writes to binlog */
unknown's avatar
unknown committed
4392 4393 4394 4395 4396 4397 4398 4399 4400

          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);
4401
        }
4402
      }
unknown's avatar
unknown committed
4403
      switch (sp_result)
4404
      {
unknown's avatar
unknown committed
4405
      case SP_OK:
4406
	my_ok(thd);
unknown's avatar
unknown committed
4407 4408
	break;
      case SP_KEY_NOT_FOUND:
4409 4410
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
unknown's avatar
unknown committed
4411 4412
	goto error;
      default:
4413 4414
	my_error(ER_SP_CANT_ALTER, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
unknown's avatar
unknown committed
4415
	goto error;
4416
      }
4417
      break;
4418 4419
    }
  case SQLCOM_DROP_PROCEDURE:
4420
  case SQLCOM_DROP_FUNCTION:
4421
    {
unknown's avatar
unknown committed
4422
      int sp_result;
4423 4424
      int type= (lex->sql_command == SQLCOM_DROP_PROCEDURE ?
                 TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION);
4425

unknown's avatar
unknown committed
4426
      sp_result= sp_routine_exists_in_table(thd, type, lex->spname);
unknown's avatar
unknown committed
4427
      mysql_reset_errors(thd, 0);
unknown's avatar
unknown committed
4428
      if (sp_result == SP_OK)
4429
      {
4430 4431 4432
        char *db= lex->spname->m_db.str;
	char *name= lex->spname->m_name.str;

4433 4434
	if (check_routine_access(thd, ALTER_PROC_ACL, db, name,
                                 lex->sql_command == SQLCOM_DROP_PROCEDURE, 0))
unknown's avatar
merge  
unknown committed
4435
          goto error;
4436 4437 4438

        if (end_active_trans(thd)) 
          goto error;
unknown's avatar
unknown committed
4439
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4440
	if (sp_automatic_privileges && !opt_noacl &&
4441 4442
	    sp_revoke_privileges(thd, db, name, 
                                 lex->sql_command == SQLCOM_DROP_PROCEDURE))
4443 4444 4445 4446 4447
	{
	  push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 
		       ER_PROC_AUTO_REVOKE_FAIL,
		       ER(ER_PROC_AUTO_REVOKE_FAIL));
	}
unknown's avatar
unknown committed
4448
#endif
unknown's avatar
unknown committed
4449
        /* Conditionally writes to binlog */
unknown's avatar
unknown committed
4450 4451 4452 4453 4454 4455

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

        sp_result= sp_drop_routine(thd, type, lex->spname);
4456 4457 4458
      }
      else
      {
4459
#ifdef HAVE_DLOPEN
4460 4461 4462 4463 4464 4465
	if (lex->sql_command == SQLCOM_DROP_FUNCTION)
	{
          udf_func *udf = find_udf(lex->spname->m_name.str,
                                   lex->spname->m_name.length);
          if (udf)
          {
4466
	    if (check_access(thd, DELETE_ACL, "mysql", 0, 1, 0, 0))
4467
	      goto error;
4468

4469
	    if (!(res = mysql_drop_function(thd, &lex->spname->m_name)))
4470
	    {
4471
	      my_ok(thd);
4472
	      break;
4473 4474
	    }
	  }
4475
	}
4476
#endif
4477
	if (lex->spname->m_db.str)
unknown's avatar
unknown committed
4478
	  sp_result= SP_KEY_NOT_FOUND;
4479 4480 4481 4482 4483
	else
	{
	  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
	  goto error;
	}
4484
      }
unknown's avatar
unknown committed
4485 4486
      res= sp_result;
      switch (sp_result) {
4487
      case SP_OK:
4488
	my_ok(thd);
4489 4490
	break;
      case SP_KEY_NOT_FOUND:
4491 4492
	if (lex->drop_if_exists)
	{
4493
	  push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
4494
			      ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST),
4495
			      SP_COM_STRING(lex), lex->spname->m_name.str);
unknown's avatar
unknown committed
4496
	  res= FALSE;
4497
	  my_ok(thd);
4498 4499
	  break;
	}
4500 4501
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4502 4503
	goto error;
      default:
4504 4505
	my_error(ER_SP_DROP_FAILED, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4506
	goto error;
4507
      }
4508
      break;
4509
    }
unknown's avatar
unknown committed
4510 4511
  case SQLCOM_SHOW_CREATE_PROC:
    {
unknown's avatar
unknown committed
4512 4513
      if (sp_show_create_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname))
      {
4514 4515
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
unknown's avatar
unknown committed
4516 4517 4518 4519 4520 4521
	goto error;
      }
      break;
    }
  case SQLCOM_SHOW_CREATE_FUNC:
    {
unknown's avatar
unknown committed
4522 4523
      if (sp_show_create_routine(thd, TYPE_ENUM_FUNCTION, lex->spname))
      {
4524 4525
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
unknown's avatar
unknown committed
4526 4527 4528 4529
	goto error;
      }
      break;
    }
unknown's avatar
unknown committed
4530 4531 4532 4533 4534 4535 4536
#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
4537 4538
        sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                            &thd->sp_proc_cache, FALSE);
unknown's avatar
unknown committed
4539
      else
unknown's avatar
unknown committed
4540 4541
        sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                            &thd->sp_func_cache, FALSE);
4542
      if (!sp || sp->show_routine_code(thd))
4543 4544
      {
        /* We don't distinguish between errors for now */
unknown's avatar
unknown committed
4545 4546 4547 4548 4549 4550 4551
        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
4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564
  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
4565 4566
  case SQLCOM_CREATE_VIEW:
    {
4567 4568 4569 4570
      /*
        Note: SQLCOM_CREATE_VIEW also handles 'ALTER VIEW' commands
        as specified through the thd->lex->create_view_mode flag.
      */
4571 4572 4573
      if (end_active_trans(thd))
        goto error;

4574
      res= mysql_create_view(thd, first_table, thd->lex->create_view_mode);
unknown's avatar
VIEW  
unknown committed
4575 4576 4577 4578
      break;
    }
  case SQLCOM_DROP_VIEW:
    {
4579
      if (check_table_access(thd, DROP_ACL, all_tables, UINT_MAX, FALSE) ||
unknown's avatar
unknown committed
4580 4581
          end_active_trans(thd))
        goto error;
4582 4583
      /* Conditionally writes to binlog. */
      res= mysql_drop_view(thd, first_table, thd->lex->drop_mode);
unknown's avatar
VIEW  
unknown committed
4584 4585
      break;
    }
4586 4587
  case SQLCOM_CREATE_TRIGGER:
  {
4588 4589 4590
    if (end_active_trans(thd))
      goto error;

4591
    /* Conditionally writes to binlog. */
4592 4593
    res= mysql_create_or_drop_trigger(thd, all_tables, 1);

4594 4595 4596 4597
    break;
  }
  case SQLCOM_DROP_TRIGGER:
  {
4598 4599 4600
    if (end_active_trans(thd))
      goto error;

4601
    /* Conditionally writes to binlog. */
4602 4603 4604
    res= mysql_create_or_drop_trigger(thd, all_tables, 0);
    break;
  }
4605
  case SQLCOM_XA_START:
4606 4607
    if (thd->transaction.xid_state.xa_state == XA_IDLE &&
        thd->lex->xa_opt == XA_RESUME)
4608
    {
4609
      if (! thd->transaction.xid_state.xid.eq(thd->lex->xid))
4610 4611 4612 4613
      {
        my_error(ER_XAER_NOTA, MYF(0));
        break;
      }
4614
      thd->transaction.xid_state.xa_state=XA_ACTIVE;
4615
      my_ok(thd);
4616 4617
      break;
    }
unknown's avatar
unknown committed
4618
    if (thd->lex->xa_opt != XA_NONE)
4619 4620 4621 4622
    { // JOIN is not supported yet. TODO
      my_error(ER_XAER_INVAL, MYF(0));
      break;
    }
4623
    if (thd->transaction.xid_state.xa_state != XA_NOTR)
4624
    {
unknown's avatar
unknown committed
4625
      my_error(ER_XAER_RMFAIL, MYF(0),
4626
               xa_state_names[thd->transaction.xid_state.xa_state]);
4627 4628 4629 4630 4631 4632 4633
      break;
    }
    if (thd->active_transaction() || thd->locked_tables)
    {
      my_error(ER_XAER_OUTSIDE, MYF(0));
      break;
    }
4634 4635 4636 4637 4638 4639 4640
    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;
4641
    thd->transaction.xid_state.rm_error= 0;
4642 4643
    thd->transaction.xid_state.xid.set(thd->lex->xid);
    xid_cache_insert(&thd->transaction.xid_state);
unknown's avatar
unknown committed
4644
    thd->transaction.all.modified_non_trans_table= FALSE;
4645
    thd->options= ((thd->options & ~(OPTION_KEEP_LOG)) | OPTION_BEGIN);
4646
    thd->server_status|= SERVER_STATUS_IN_TRANS;
4647
    my_ok(thd);
4648 4649 4650 4651 4652 4653 4654 4655
    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;
    }
4656
    if (thd->transaction.xid_state.xa_state != XA_ACTIVE)
4657
    {
unknown's avatar
unknown committed
4658
      my_error(ER_XAER_RMFAIL, MYF(0),
4659
               xa_state_names[thd->transaction.xid_state.xa_state]);
4660 4661
      break;
    }
4662
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4663 4664 4665 4666
    {
      my_error(ER_XAER_NOTA, MYF(0));
      break;
    }
4667 4668
    if (xa_trans_rolled_back(&thd->transaction.xid_state))
      break;
4669
    thd->transaction.xid_state.xa_state=XA_IDLE;
4670
    my_ok(thd);
4671 4672
    break;
  case SQLCOM_XA_PREPARE:
4673
    if (thd->transaction.xid_state.xa_state != XA_IDLE)
4674
    {
unknown's avatar
unknown committed
4675
      my_error(ER_XAER_RMFAIL, MYF(0),
4676
               xa_state_names[thd->transaction.xid_state.xa_state]);
4677 4678
      break;
    }
4679
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4680 4681 4682 4683 4684 4685 4686
    {
      my_error(ER_XAER_NOTA, MYF(0));
      break;
    }
    if (ha_prepare(thd))
    {
      my_error(ER_XA_RBROLLBACK, MYF(0));
4687 4688
      xid_cache_delete(&thd->transaction.xid_state);
      thd->transaction.xid_state.xa_state=XA_NOTR;
4689 4690
      break;
    }
4691
    thd->transaction.xid_state.xa_state=XA_PREPARED;
4692
    my_ok(thd);
4693 4694
    break;
  case SQLCOM_XA_COMMIT:
4695
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4696
    {
4697 4698
      XID_STATE *xs=xid_cache_search(thd->lex->xid);
      if (!xs || xs->in_thd)
4699
        my_error(ER_XAER_NOTA, MYF(0));
4700 4701 4702 4703 4704 4705
      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
4706
      else
4707 4708 4709
      {
        ha_commit_or_rollback_by_xid(thd->lex->xid, 1);
        xid_cache_delete(xs);
4710
        my_ok(thd);
4711
      }
4712 4713
      break;
    }
4714 4715 4716 4717 4718
    if (xa_trans_rolled_back(&thd->transaction.xid_state))
    {
      xa_trans_rollback(thd);
      break;
    }
4719
    if (thd->transaction.xid_state.xa_state == XA_IDLE &&
unknown's avatar
unknown committed
4720
        thd->lex->xa_opt == XA_ONE_PHASE)
4721
    {
unknown's avatar
unknown committed
4722 4723 4724
      int r;
      if ((r= ha_commit(thd)))
        my_error(r == 1 ? ER_XA_RBROLLBACK : ER_XAER_RMERR, MYF(0));
4725
      else
4726
        my_ok(thd);
4727
    }
4728
    else if (thd->transaction.xid_state.xa_state == XA_PREPARED &&
unknown's avatar
unknown committed
4729
             thd->lex->xa_opt == XA_NONE)
4730
    {
4731 4732 4733
      if (wait_if_global_read_lock(thd, 0, 0))
      {
        ha_rollback(thd);
4734
        my_error(ER_XAER_RMERR, MYF(0));
4735
      }
4736
      else
4737 4738 4739 4740
      {
        if (ha_commit_one_phase(thd, 1))
          my_error(ER_XAER_RMERR, MYF(0));
        else
4741
          my_ok(thd);
4742 4743
        start_waiting_global_read_lock(thd);
      }
4744 4745 4746
    }
    else
    {
unknown's avatar
unknown committed
4747
      my_error(ER_XAER_RMFAIL, MYF(0),
4748
               xa_state_names[thd->transaction.xid_state.xa_state]);
4749 4750
      break;
    }
unknown's avatar
unknown committed
4751
    thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
unknown's avatar
unknown committed
4752
    thd->transaction.all.modified_non_trans_table= FALSE;
4753
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
4754 4755
    xid_cache_delete(&thd->transaction.xid_state);
    thd->transaction.xid_state.xa_state=XA_NOTR;
4756 4757
    break;
  case SQLCOM_XA_ROLLBACK:
4758
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4759
    {
4760 4761
      XID_STATE *xs=xid_cache_search(thd->lex->xid);
      if (!xs || xs->in_thd)
4762
        my_error(ER_XAER_NOTA, MYF(0));
unknown's avatar
unknown committed
4763
      else
4764
      {
4765
        bool ok= !xa_trans_rolled_back(xs);
4766 4767
        ha_commit_or_rollback_by_xid(thd->lex->xid, 0);
        xid_cache_delete(xs);
4768
        if (ok)
4769
          my_ok(thd);
4770
      }
4771 4772
      break;
    }
4773
    if (thd->transaction.xid_state.xa_state != XA_IDLE &&
4774 4775
        thd->transaction.xid_state.xa_state != XA_PREPARED &&
        thd->transaction.xid_state.xa_state != XA_ROLLBACK_ONLY)
4776
    {
unknown's avatar
unknown committed
4777
      my_error(ER_XAER_RMFAIL, MYF(0),
4778
               xa_state_names[thd->transaction.xid_state.xa_state]);
4779 4780
      break;
    }
4781
    if (xa_trans_rollback(thd))
4782 4783
      my_error(ER_XAER_RMERR, MYF(0));
    else
4784
      my_ok(thd);
4785 4786
    break;
  case SQLCOM_XA_RECOVER:
4787
    res= mysql_xa_recover(thd);
4788
    break;
unknown's avatar
unknown committed
4789 4790 4791 4792
  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)))
4793
      my_ok(thd);
unknown's avatar
unknown committed
4794 4795 4796 4797
    break;
  case SQLCOM_INSTALL_PLUGIN:
    if (! (res= mysql_install_plugin(thd, &thd->lex->comment,
                                     &thd->lex->ident)))
4798
      my_ok(thd);
unknown's avatar
unknown committed
4799 4800 4801
    break;
  case SQLCOM_UNINSTALL_PLUGIN:
    if (! (res= mysql_uninstall_plugin(thd, &thd->lex->comment)))
4802
      my_ok(thd);
unknown's avatar
unknown committed
4803 4804 4805 4806 4807 4808 4809 4810 4811 4812
    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
4813 4814 4815 4816 4817
  case SQLCOM_CREATE_SERVER:
  {
    int error;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_CREATE_SERVER"));
unknown's avatar
unknown committed
4818 4819 4820 4821

    if (check_global_access(thd, SUPER_ACL))
      break;

unknown's avatar
unknown committed
4822 4823
    if ((error= create_server(thd, &lex->server_options)))
    {
4824
      DBUG_PRINT("info", ("problem creating server <%s>",
unknown's avatar
unknown committed
4825 4826 4827 4828
                          lex->server_options.server_name));
      my_error(error, MYF(0), lex->server_options.server_name);
      break;
    }
4829
    my_ok(thd, 1);
unknown's avatar
unknown committed
4830 4831 4832 4833 4834 4835 4836
    break;
  }
  case SQLCOM_ALTER_SERVER:
  {
    int error;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_ALTER_SERVER"));
unknown's avatar
unknown committed
4837 4838 4839 4840

    if (check_global_access(thd, SUPER_ACL))
      break;

unknown's avatar
unknown committed
4841 4842
    if ((error= alter_server(thd, &lex->server_options)))
    {
4843
      DBUG_PRINT("info", ("problem altering server <%s>",
unknown's avatar
unknown committed
4844 4845 4846 4847
                          lex->server_options.server_name));
      my_error(error, MYF(0), lex->server_options.server_name);
      break;
    }
4848
    my_ok(thd, 1);
unknown's avatar
unknown committed
4849 4850 4851 4852 4853 4854 4855
    break;
  }
  case SQLCOM_DROP_SERVER:
  {
    int err_code;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_DROP_SERVER"));
unknown's avatar
unknown committed
4856 4857 4858 4859

    if (check_global_access(thd, SUPER_ACL))
      break;

unknown's avatar
unknown committed
4860 4861
    if ((err_code= drop_server(thd, &lex->server_options)))
    {
unknown's avatar
unknown committed
4862
      if (! lex->drop_if_exists && err_code == ER_FOREIGN_SERVER_DOESNT_EXIST)
unknown's avatar
unknown committed
4863 4864 4865 4866 4867 4868 4869
      {
        DBUG_PRINT("info", ("problem dropping server %s",
                            lex->server_options.server_name));
        my_error(err_code, MYF(0), lex->server_options.server_name);
      }
      else
      {
4870
        my_ok(thd, 0);
unknown's avatar
unknown committed
4871 4872 4873
      }
      break;
    }
4874
    my_ok(thd, 1);
unknown's avatar
unknown committed
4875 4876
    break;
  }
4877
  default:
4878
#ifndef EMBEDDED_LIBRARY
4879
    DBUG_ASSERT(0);                             /* Impossible */
4880
#endif
4881
    my_ok(thd);
unknown's avatar
unknown committed
4882 4883
    break;
  }
4884
  thd_proc_info(thd, "query end");
4885 4886

  /*
unknown's avatar
unknown committed
4887
    Binlog-related cleanup:
4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898
    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);

4899
  /*
4900 4901
    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
4902 4903 4904 4905
    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))
4906
    thd->row_count_func= -1;
4907

4908
  goto finish;
unknown's avatar
unknown committed
4909 4910

error:
4911 4912
  res= TRUE;

4913
finish:
4914 4915 4916 4917 4918 4919 4920 4921
  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);
  }
4922
  DBUG_RETURN(res || thd->is_error());
unknown's avatar
unknown committed
4923 4924 4925
}


4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948
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()))
4949
        return 1;                               /* purecov: inspected */
4950 4951 4952 4953 4954 4955 4956
      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);
4957
        thd->lex->unit.print(&str, QT_ORDINARY);
4958 4959 4960 4961
        str.append('\0');
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
                     ER_YES, str.ptr());
      }
4962 4963 4964 4965
      if (res)
        result->abort();
      else
        result->send_eof();
4966 4967 4968 4969 4970
      delete result;
    }
    else
    {
      if (!result && !(result= new select_send()))
4971
        return 1;                               /* purecov: inspected */
4972 4973 4974 4975 4976 4977 4978 4979 4980 4981
      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
4982
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
4983
/**
4984
  Check grants for commands which work only with one table.
unknown's avatar
unknown committed
4985

4986 4987 4988
  @param thd                    Thread handler
  @param privilege              requested privilege
  @param all_tables             global table list of query
unknown's avatar
unknown committed
4989
  @param no_errors              FALSE/TRUE - report/don't report error to
4990
                            the client (using my_error() call).
unknown's avatar
unknown committed
4991 4992 4993 4994 4995

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

4998
bool check_single_table_access(THD *thd, ulong privilege, 
4999
                               TABLE_LIST *all_tables, bool no_errors)
unknown's avatar
unknown committed
5000
{
5001 5002 5003 5004 5005 5006
  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;

5007 5008 5009 5010 5011 5012 5013 5014
  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,
5015
		   &all_tables->grant.privilege, 0, no_errors,
5016
                   test(all_tables->schema_table)))
5017
    goto deny;
unknown's avatar
unknown committed
5018

unknown's avatar
unknown committed
5019
  /* Show only 1 table for check_grant */
5020
  if (!(all_tables->belong_to_view &&
5021
        (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) &&
5022 5023
      !(all_tables->view &&
        all_tables->effective_algorithm == VIEW_ALGORITHM_TMPTABLE) &&
5024
      check_grant(thd, privilege, all_tables, 0, 1, no_errors))
5025 5026 5027
    goto deny;

  thd->security_ctx= backup_ctx;
5028 5029 5030 5031 5032 5033 5034
  return 0;

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

unknown's avatar
unknown committed
5035
/**
5036 5037 5038
  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
5039 5040 5041 5042 5043 5044 5045 5046
  @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
5047 5048 5049 5050
*/

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

5054
  /* Check rights on tables of subselects and implictly opened tables */
unknown's avatar
unknown committed
5055
  TABLE_LIST *subselects_tables, *view= all_tables->view ? all_tables : 0;
unknown's avatar
VIEW  
unknown committed
5056
  if ((subselects_tables= all_tables->next_global))
unknown's avatar
unknown committed
5057
  {
unknown's avatar
unknown committed
5058 5059 5060 5061 5062 5063
    /*
      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)
    {
5064
      if (check_single_table_access (thd, privilege, subselects_tables, FALSE))
unknown's avatar
unknown committed
5065 5066 5067 5068
        return 1;
      subselects_tables= subselects_tables->next_global;
    }
    if (subselects_tables &&
5069
        (check_table_access(thd, SELECT_ACL, subselects_tables, UINT_MAX, FALSE)))
5070
      return 1;
unknown's avatar
unknown committed
5071 5072
  }
  return 0;
unknown's avatar
unknown committed
5073 5074 5075
}


unknown's avatar
unknown committed
5076 5077
/**
  Get the user (global) and database privileges for all used tables.
unknown's avatar
unknown committed
5078

unknown's avatar
unknown committed
5079 5080 5081 5082
  @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
5083

unknown's avatar
unknown committed
5084
  @note
unknown's avatar
unknown committed
5085 5086 5087 5088 5089
    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
5090
  @retval
unknown's avatar
unknown committed
5091
    0  ok
unknown's avatar
unknown committed
5092 5093 5094 5095
  @retval
    1  If we can't get the privileges and we don't use table/column
    grants.
*/
unknown's avatar
unknown committed
5096
bool
unknown's avatar
unknown committed
5097
check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv,
5098
	     bool dont_check_global_grants, bool no_errors, bool schema_db)
unknown's avatar
unknown committed
5099
{
5100
  Security_context *sctx= thd->security_ctx;
unknown's avatar
unknown committed
5101
  ulong db_access;
5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112
  /*
    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
5113
  ulong dummy;
5114 5115
  DBUG_ENTER("check_access");
  DBUG_PRINT("enter",("db: %s  want_access: %lu  master_access: %lu",
5116
                      db ? db : "", want_access, sctx->master_access));
unknown's avatar
unknown committed
5117 5118 5119 5120 5121
  if (save_priv)
    *save_priv=0;
  else
    save_priv= &dummy;

5122
  thd_proc_info(thd, "checking permissions");
5123
  if ((!db || !db[0]) && !thd->db && !dont_check_global_grants)
unknown's avatar
unknown committed
5124
  {
5125
    DBUG_PRINT("error",("No database"));
5126
    if (!no_errors)
unknown's avatar
unknown committed
5127 5128
      my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR),
                 MYF(0));                       /* purecov: tested */
unknown's avatar
unknown committed
5129
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
5130 5131
  }

5132 5133
  if (schema_db)
  {
5134 5135
    if (!(sctx->master_access & FILE_ACL) && (want_access & FILE_ACL) ||
        (want_access & ~(SELECT_ACL | EXTRA_ACL | FILE_ACL)))
5136 5137
    {
      if (!no_errors)
5138 5139
      {
        const char *db_name= db ? db : thd->db;
5140
        my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
5141 5142
                 sctx->priv_user, sctx->priv_host, db_name);
      }
5143 5144 5145 5146 5147 5148 5149 5150 5151
      DBUG_RETURN(TRUE);
    }
    else
    {
      *save_priv= SELECT_ACL;
      DBUG_RETURN(FALSE);
    }
  }

5152
  if ((sctx->master_access & want_access) == want_access)
unknown's avatar
unknown committed
5153
  {
5154 5155 5156 5157 5158
    /*
      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
    */
5159 5160
    db_access= sctx->db_access;
    if (!(sctx->master_access & SELECT_ACL) &&
unknown's avatar
unknown committed
5161
	(db && (!thd->db || db_is_pattern || strcmp(db,thd->db))))
5162 5163 5164
      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
5165
    DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
5166
  }
5167
  if (((want_access & ~sctx->master_access) & ~(DB_ACLS | EXTRA_ACL)) ||
5168
      ! db && dont_check_global_grants)
unknown's avatar
unknown committed
5169
  {						// We can never grant this
5170
    DBUG_PRINT("error",("No possible access"));
5171
    if (!no_errors)
5172
      my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
5173 5174
               sctx->priv_user,
               sctx->priv_host,
5175 5176 5177
               (thd->password ?
                ER(ER_YES) :
                ER(ER_NO)));                    /* purecov: tested */
unknown's avatar
unknown committed
5178
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
5179 5180 5181
  }

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

unknown's avatar
unknown committed
5184
  if (db && (!thd->db || db_is_pattern || strcmp(db,thd->db)))
5185 5186
    db_access= acl_get(sctx->host, sctx->ip, sctx->priv_user, db,
                       db_is_pattern);
unknown's avatar
unknown committed
5187
  else
5188
    db_access= sctx->db_access;
5189
  DBUG_PRINT("info",("db_access: %lu", db_access));
unknown's avatar
unknown committed
5190
  /* Remove SHOW attribute and access rights we already have */
5191
  want_access &= ~(sctx->master_access | EXTRA_ACL);
5192 5193
  DBUG_PRINT("info",("db_access: %lu  want_access: %lu",
                     db_access, want_access));
5194
  db_access= ((*save_priv=(db_access | sctx->master_access)) & want_access);
5195

unknown's avatar
unknown committed
5196
  if (db_access == want_access ||
5197
      (!dont_check_global_grants &&
5198
       !(want_access & ~(db_access | TABLE_ACLS | PROC_ACLS))))
unknown's avatar
unknown committed
5199
    DBUG_RETURN(FALSE);				/* Ok */
5200 5201

  DBUG_PRINT("error",("Access denied"));
5202
  if (!no_errors)
5203
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
5204
             sctx->priv_user, sctx->priv_host,
5205 5206 5207
             (db ? db : (thd->db ?
                         thd->db :
                         "unknown")));          /* purecov: tested */
unknown's avatar
unknown committed
5208
  DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
5209 5210 5211
}


5212 5213
static bool check_show_access(THD *thd, TABLE_LIST *table)
{
unknown's avatar
unknown committed
5214
  switch (get_schema_table_idx(table->schema_table)) {
5215 5216
  case SCH_SCHEMATA:
    return (specialflag & SPECIAL_SKIP_SHOW_DB) &&
unknown's avatar
unknown committed
5217
      check_global_access(thd, SHOW_DB_ACL);
5218 5219 5220 5221 5222

  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
  case SCH_TRIGGERS:
unknown's avatar
unknown committed
5223 5224 5225
  case SCH_EVENTS:
  {
    const char *dst_db_name= table->schema_select_lex->db;
5226

unknown's avatar
unknown committed
5227
    DBUG_ASSERT(dst_db_name);
5228

unknown's avatar
unknown committed
5229 5230 5231 5232
    if (check_access(thd, SELECT_ACL, dst_db_name,
                     &thd->col_access, FALSE, FALSE,
                     is_schema_db(dst_db_name)))
      return TRUE;
5233

unknown's avatar
unknown committed
5234 5235 5236 5237 5238 5239 5240
    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;
5241 5242
    }

unknown's avatar
unknown committed
5243 5244 5245
    return FALSE;
  }

5246 5247
  case SCH_COLUMNS:
  case SCH_STATISTICS:
unknown's avatar
unknown committed
5248 5249 5250
  {
    TABLE_LIST *dst_table;
    dst_table= (TABLE_LIST *) table->schema_select_lex->table_list.first;
5251

unknown's avatar
unknown committed
5252
    DBUG_ASSERT(dst_table);
5253

unknown's avatar
unknown committed
5254 5255 5256 5257 5258 5259
    if (check_access(thd, SELECT_ACL | EXTRA_ACL,
                     dst_table->db,
                     &dst_table->grant.privilege,
                     FALSE, FALSE,
                     test(dst_table->schema_table)))
      return FALSE;
5260

5261
    return (check_grant(thd, SELECT_ACL, dst_table, 2, UINT_MAX, FALSE));
unknown's avatar
unknown committed
5262 5263
  }
  default:
5264 5265 5266 5267 5268 5269 5270
    break;
  }

  return FALSE;
}


unknown's avatar
unknown committed
5271
/**
5272 5273
  Check the privilege for all used tables.

5274 5275 5276 5277 5278 5279
  @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).
5280

unknown's avatar
unknown committed
5281
  @note
5282 5283 5284 5285 5286 5287
    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).

5288 5289
  @retval  FALSE   OK
  @retval  TRUE    Access denied
unknown's avatar
unknown committed
5290 5291
*/

5292
bool
unknown's avatar
unknown committed
5293
check_table_access(THD *thd, ulong want_access,TABLE_LIST *tables,
5294
		   uint number, bool no_errors)
unknown's avatar
unknown committed
5295
{
5296 5297
  TABLE_LIST *org_tables= tables;
  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
5298
  uint i= 0;
5299
  Security_context *sctx= thd->security_ctx, *backup_ctx= thd->security_ctx;
5300
  /*
unknown's avatar
unknown committed
5301 5302 5303
    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.
5304
  */
5305 5306
  for (; i < number && tables != first_not_own_table;
       tables= tables->next_global, i++)
unknown's avatar
unknown committed
5307
  {
5308 5309 5310 5311 5312
    if (tables->security_ctx)
      sctx= tables->security_ctx;
    else
      sctx= backup_ctx;

5313
    if (tables->schema_table && 
5314
        (want_access & ~(SELECT_ACL | EXTRA_ACL | FILE_ACL)))
5315 5316 5317
    {
      if (!no_errors)
        my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
5318
                 sctx->priv_user, sctx->priv_host,
5319
                 INFORMATION_SCHEMA_NAME.str);
5320 5321
      return TRUE;
    }
5322 5323 5324 5325 5326
    /*
       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
5327 5328 5329 5330 5331 5332 5333 5334 5335

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

      continue;
    }

5336
    if (tables->is_anonymous_derived_table() ||
5337
        (tables->table && (int)tables->table->s->tmp_table))
unknown's avatar
unknown committed
5338
      continue;
5339 5340
    thd->security_ctx= sctx;
    if ((sctx->master_access & want_access) ==
5341
        (want_access & ~EXTRA_ACL) &&
unknown's avatar
unknown committed
5342
	thd->db)
unknown's avatar
unknown committed
5343
      tables->grant.privilege= want_access;
unknown's avatar
unknown committed
5344
    else if (tables->db && thd->db && strcmp(tables->db, thd->db) == 0)
unknown's avatar
unknown committed
5345
    {
5346 5347 5348
      if (check_access(thd, want_access, tables->get_db_name(),
                       &tables->grant.privilege, 0, no_errors, 
                       test(tables->schema_table)))
5349
        goto deny;                            // Access denied
unknown's avatar
unknown committed
5350
    }
5351 5352 5353
    else if (check_access(thd, want_access, tables->get_db_name(),
                          &tables->grant.privilege, 0, no_errors, 
                          test(tables->schema_table)))
5354
      goto deny;
unknown's avatar
unknown committed
5355
  }
5356
  thd->security_ctx= backup_ctx;
5357
  return check_grant(thd,want_access & ~EXTRA_ACL,org_tables,
5358
		       test(want_access & EXTRA_ACL), number, no_errors);
5359 5360 5361
deny:
  thd->security_ctx= backup_ctx;
  return TRUE;
unknown's avatar
unknown committed
5362 5363
}

5364

5365
bool
5366 5367
check_routine_access(THD *thd, ulong want_access,char *db, char *name,
		     bool is_proc, bool no_errors)
5368 5369 5370 5371 5372
{
  TABLE_LIST tables[1];
  
  bzero((char *)tables, sizeof(TABLE_LIST));
  tables->db= db;
5373
  tables->table_name= tables->alias= name;
5374
  
unknown's avatar
unknown committed
5375 5376 5377 5378 5379 5380 5381
  /*
    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)
5382 5383
    tables->grant.privilege= want_access;
  else if (check_access(thd,want_access,db,&tables->grant.privilege,
unknown's avatar
unknown committed
5384
			0, no_errors, 0))
5385 5386
    return TRUE;
  
5387
    return check_grant_routine(thd, want_access, tables, is_proc, no_errors);
5388 5389
}

5390

unknown's avatar
unknown committed
5391 5392
/**
  Check if the routine has any of the routine privileges.
5393

unknown's avatar
unknown committed
5394 5395 5396
  @param thd	       Thread handler
  @param db           Database name
  @param name         Routine name
5397

unknown's avatar
unknown committed
5398
  @retval
5399
    0            ok
unknown's avatar
unknown committed
5400
  @retval
5401 5402 5403
    1            error
*/

5404 5405
bool check_some_routine_access(THD *thd, const char *db, const char *name,
                               bool is_proc)
5406 5407
{
  ulong save_priv;
5408
  if (thd->security_ctx->master_access & SHOW_PROC_ACLS)
5409
    return FALSE;
5410 5411 5412 5413 5414
  /*
    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) ||
5415 5416
      (save_priv & SHOW_PROC_ACLS))
    return FALSE;
5417
  return check_routine_level_acl(thd, db, name, is_proc);
5418 5419 5420
}


5421 5422 5423
/*
  Check if the given table has any of the asked privileges

unknown's avatar
unknown committed
5424 5425
  @param thd		 Thread handler
  @param want_access	 Bitmap of possible privileges to check for
5426

unknown's avatar
unknown committed
5427
  @retval
5428
    0  ok
unknown's avatar
unknown committed
5429
  @retval
5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443
    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,
5444 5445
                        &table->grant.privilege, 0, 1,
                        test(table->schema_table)) &&
5446
          !check_grant(thd, access, table, 0, 1, 1))
5447 5448 5449 5450 5451 5452 5453
        DBUG_RETURN(0);
    }
  }
  DBUG_PRINT("exit",("no matching access rights"));
  DBUG_RETURN(1);
}

unknown's avatar
unknown committed
5454
#endif /*NO_EMBEDDED_ACCESS_CHECKS*/
5455

5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488

/**
  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
5489 5490 5491 5492
/****************************************************************************
	Check stack size; Send error if there isn't enough stack to continue
****************************************************************************/

5493 5494
#ifndef EMBEDDED_LIBRARY

unknown's avatar
unknown committed
5495 5496 5497 5498 5499 5500
#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
5501 5502 5503 5504
#ifndef DBUG_OFF
long max_stack_used;
#endif

unknown's avatar
unknown committed
5505 5506
/**
  @note
5507 5508 5509 5510
  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
5511
*/
5512
bool check_stack_overrun(THD *thd, long margin,
5513
			 uchar *buf __attribute__((unused)))
unknown's avatar
unknown committed
5514 5515
{
  long stack_used;
5516
  DBUG_ASSERT(thd == current_thd);
unknown's avatar
unknown committed
5517
  if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >=
5518
      (long) (my_thread_stack_size - margin))
unknown's avatar
unknown committed
5519
  {
5520 5521 5522 5523
    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));
5524
    thd->fatal_error();
unknown's avatar
unknown committed
5525 5526
    return 1;
  }
unknown's avatar
unknown committed
5527 5528 5529
#ifndef DBUG_OFF
  max_stack_used= max(max_stack_used, stack_used);
#endif
unknown's avatar
unknown committed
5530 5531
  return 0;
}
5532
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
5533 5534 5535 5536

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

5537
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
unknown's avatar
unknown committed
5538
{
5539
  Yacc_state *state= & current_thd->m_parser_state->m_yacc;
5540
  ulong old_info=0;
5541
  DBUG_ASSERT(state);
unknown's avatar
unknown committed
5542 5543
  if ((uint) *yystacksize >= MY_YACC_MAX)
    return 1;
5544
  if (!state->yacc_yyvs)
unknown's avatar
unknown committed
5545 5546
    old_info= *yystacksize;
  *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
5547
  if (!(state->yacc_yyvs= (uchar*)
5548
        my_realloc(state->yacc_yyvs,
5549 5550 5551
                   *yystacksize*sizeof(**yyvs),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
      !(state->yacc_yyss= (uchar*)
5552
        my_realloc(state->yacc_yyss,
5553 5554
                   *yystacksize*sizeof(**yyss),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
unknown's avatar
unknown committed
5555 5556
    return 1;
  if (old_info)
5557 5558 5559 5560 5561 5562 5563 5564
  {
    /*
      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
5565
  }
5566 5567
  *yyss= (short*) state->yacc_yyss;
  *yyvs= (YYSTYPE*) state->yacc_yyvs;
unknown's avatar
unknown committed
5568 5569 5570 5571
  return 0;
}


unknown's avatar
unknown committed
5572
/**
5573 5574 5575 5576
 Reset THD part responsible for command processing state.

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

unknown's avatar
unknown committed
5579
  @todo
5580 5581
   Make it a method of THD and align its name with the rest of
   reset/end/start/init methods.
unknown's avatar
unknown committed
5582
  @todo
5583 5584 5585 5586 5587 5588
   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");
5589
  DBUG_ASSERT(!thd->spcont); /* not for substatements of routines */
5590
  DBUG_ASSERT(! thd->in_sub_stmt);
5591
  thd->free_list= 0;
5592
  thd->select_number= 1;
5593 5594 5595 5596
  /*
    Those two lines below are theoretically unneeded as
    THD::cleanup_after_query() should take care of this already.
  */
5597
  thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
5598 5599 5600
  thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;

  thd->query_start_used= 0;
5601
  thd->is_fatal_error= thd->time_zone_used= 0;
5602 5603 5604 5605 5606
  /*
    Clear the status flag that are expected to be cleared at the
    beginning of each SQL statement.
  */
  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
5607 5608 5609 5610 5611 5612
  /*
    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
5613 5614
  {
    thd->options&= ~OPTION_KEEP_LOG;
5615
    thd->transaction.all.modified_non_trans_table= FALSE;
unknown's avatar
unknown committed
5616
  }
5617
  DBUG_ASSERT(thd->security_ctx== &thd->main_security_ctx);
unknown's avatar
unknown committed
5618
  thd->thread_specific_used= FALSE;
5619 5620

  if (opt_bin_log)
5621
  {
5622 5623
    reset_dynamic(&thd->user_var_events);
    thd->user_var_events_alloc= thd->mem_root;
5624
  }
5625 5626 5627 5628 5629 5630
  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;

5631 5632 5633 5634
  /*
    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
5635 5636
  thd->reset_current_stmt_binlog_row_based();

5637 5638 5639 5640
  DBUG_PRINT("debug",
             ("current_stmt_binlog_row_based: %d",
              thd->current_stmt_binlog_row_based));

unknown's avatar
unknown committed
5641 5642 5643
  DBUG_VOID_RETURN;
}

5644

5645 5646 5647
void
mysql_init_select(LEX *lex)
{
unknown's avatar
unknown committed
5648
  SELECT_LEX *select_lex= lex->current_select;
unknown's avatar
unknown committed
5649
  select_lex->init_select();
5650
  lex->wild= 0;
5651 5652
  if (select_lex == &lex->select_lex)
  {
5653
    DBUG_ASSERT(lex->result == 0);
5654 5655
    lex->exchange= 0;
  }
5656 5657
}

5658

unknown's avatar
unknown committed
5659
bool
unknown's avatar
unknown committed
5660
mysql_new_select(LEX *lex, bool move_down)
5661
{
unknown's avatar
unknown committed
5662
  SELECT_LEX *select_lex;
5663
  THD *thd= lex->thd;
unknown's avatar
unknown committed
5664 5665
  DBUG_ENTER("mysql_new_select");

5666
  if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
unknown's avatar
unknown committed
5667
    DBUG_RETURN(1);
5668
  select_lex->select_number= ++thd->select_number;
unknown's avatar
unknown committed
5669
  select_lex->parent_lex= lex; /* Used in init_query. */
unknown's avatar
unknown committed
5670 5671
  select_lex->init_query();
  select_lex->init_select();
unknown's avatar
unknown committed
5672
  lex->nest_level++;
unknown's avatar
unknown committed
5673 5674 5675 5676 5677
  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
5678
  select_lex->nest_level= lex->nest_level;
5679 5680 5681 5682 5683
  /*
    Don't evaluate this subquery during statement prepare even if
    it's a constant one. The flag is switched off in the end of
    mysql_stmt_prepare.
  */
unknown's avatar
unknown committed
5684
  if (thd->stmt_arena->is_stmt_prepare())
5685
    select_lex->uncacheable|= UNCACHEABLE_PREPARE;
unknown's avatar
unknown committed
5686 5687
  if (move_down)
  {
unknown's avatar
unknown committed
5688
    SELECT_LEX_UNIT *unit;
5689
    lex->subqueries= TRUE;
unknown's avatar
unknown committed
5690
    /* first select_lex of subselect or derived table */
5691
    if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
unknown's avatar
unknown committed
5692
      DBUG_RETURN(1);
unknown's avatar
unknown committed
5693

unknown's avatar
unknown committed
5694 5695
    unit->init_query();
    unit->init_select();
5696
    unit->thd= thd;
unknown's avatar
unknown committed
5697
    unit->include_down(lex->current_select);
unknown's avatar
unknown committed
5698 5699
    unit->link_next= 0;
    unit->link_prev= 0;
5700
    unit->return_to= lex->current_select;
unknown's avatar
unknown committed
5701
    select_lex->include_down(unit);
5702 5703 5704 5705 5706
    /*
      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
5707 5708
  }
  else
unknown's avatar
unknown committed
5709
  {
unknown's avatar
VIEW  
unknown committed
5710 5711
    if (lex->current_select->order_list.first && !lex->current_select->braces)
    {
unknown's avatar
unknown committed
5712
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY");
unknown's avatar
unknown committed
5713
      DBUG_RETURN(1);
unknown's avatar
VIEW  
unknown committed
5714
    }
5715
    select_lex->include_neighbour(lex->current_select);
5716 5717 5718 5719 5720
    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
5721
  }
unknown's avatar
unknown committed
5722

5723
  select_lex->master_unit()->global_parameters= select_lex;
5724
  select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
5725
  lex->current_select= select_lex;
5726 5727 5728 5729 5730
  /*
    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
5731
  DBUG_RETURN(0);
5732
}
unknown's avatar
unknown committed
5733

unknown's avatar
unknown committed
5734
/**
5735 5736
  Create a select to return the same output as 'SELECT @@var_name'.

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

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

unknown's avatar
unknown committed
5741
  @param var_name		Variable name
5742 5743 5744 5745
*/

void create_select_for_variable(const char *var_name)
{
5746
  THD *thd;
5747
  LEX *lex;
5748
  LEX_STRING tmp, null_lex_string;
5749 5750
  Item *var;
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
5751
  DBUG_ENTER("create_select_for_variable");
5752 5753

  thd= current_thd;
unknown's avatar
unknown committed
5754
  lex= thd->lex;
5755 5756 5757 5758
  mysql_init_select(lex);
  lex->sql_command= SQLCOM_SELECT;
  tmp.str= (char*) var_name;
  tmp.length=strlen(var_name);
5759
  bzero((char*) &null_lex_string.str, sizeof(null_lex_string));
5760 5761 5762 5763
  /*
    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
5764 5765 5766 5767 5768 5769
  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);
  }
5770 5771 5772
  DBUG_VOID_RETURN;
}

5773

unknown's avatar
unknown committed
5774 5775
void mysql_init_multi_delete(LEX *lex)
{
unknown's avatar
unknown committed
5776
  lex->sql_command=  SQLCOM_DELETE_MULTI;
unknown's avatar
unknown committed
5777
  mysql_init_select(lex);
5778 5779
  lex->select_lex.select_limit= 0;
  lex->unit.select_limit_cnt= HA_POS_ERROR;
unknown's avatar
unknown committed
5780
  lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list);
5781
  lex->lock_option= TL_READ_DEFAULT;
unknown's avatar
VIEW  
unknown committed
5782 5783
  lex->query_tables= 0;
  lex->query_tables_last= &lex->query_tables;
unknown's avatar
unknown committed
5784
}
unknown's avatar
unknown committed
5785

5786

5787 5788 5789 5790
/*
  When you modify mysql_parse(), you may need to mofify
  mysql_test_parse_for_slave() in this same file.
*/
unknown's avatar
unknown committed
5791

5792 5793
/**
  Parse a query.
unknown's avatar
unknown committed
5794 5795 5796 5797 5798 5799

  @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.
5800 5801 5802 5803
*/

void mysql_parse(THD *thd, const char *inBuf, uint length,
                 const char ** found_semicolon)
unknown's avatar
unknown committed
5804
{
5805
  int error;
unknown's avatar
unknown committed
5806
  DBUG_ENTER("mysql_parse");
5807 5808 5809

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

5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827
  /*
    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);
5828

5829
  if (query_cache_send_result_to_client(thd, (char*) inBuf, length) <= 0)
unknown's avatar
unknown committed
5830
  {
unknown's avatar
unknown committed
5831
    LEX *lex= thd->lex;
5832

5833 5834
    sp_cache_flush_obsolete(&thd->sp_proc_cache);
    sp_cache_flush_obsolete(&thd->sp_func_cache);
5835

5836
    Parser_state parser_state(thd, inBuf, length);
5837

5838
    bool err= parse_sql(thd, & parser_state, NULL);
5839
    *found_semicolon= parser_state.m_lip.found_semicolon;
5840

5841
    if (!err)
unknown's avatar
unknown committed
5842
    {
unknown's avatar
unknown committed
5843
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5844
      if (mqh_used && thd->user_connect &&
5845
	  check_mqh(thd, lex->sql_command))
5846 5847 5848 5849
      {
	thd->net.error = 0;
      }
      else
unknown's avatar
unknown committed
5850
#endif
5851
      {
5852
	if (! thd->is_error())
unknown's avatar
unknown committed
5853
	{
5854 5855 5856 5857 5858 5859 5860 5861 5862 5863
          /*
            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.
          */
5864 5865
          if (*found_semicolon &&
              (thd->query_length= (ulong)(*found_semicolon - thd->query)))
5866 5867
            thd->query_length--;
          /* Actually execute the query */
5868 5869 5870 5871 5872
          if (*found_semicolon)
          {
            lex->safe_to_cache_query= 0;
            thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
          }
5873
          lex->set_trg_event_type_for_tables();
5874 5875 5876 5877 5878 5879 5880 5881 5882
          MYSQL_QUERY_EXEC_START(thd->query,
                                 thd->thread_id,
                                 (char *) (thd->db ? thd->db : ""),
                                 thd->security_ctx->priv_user,
                                 (char *) thd->security_ctx->host_or_ip,
                                 0);

          error= mysql_execute_command(thd);
          MYSQL_QUERY_EXEC_DONE(error);
unknown's avatar
unknown committed
5883
	}
5884
      }
unknown's avatar
unknown committed
5885 5886
    }
    else
5887
    {
5888
      DBUG_ASSERT(thd->is_error());
5889
      DBUG_PRINT("info",("Command aborted. Fatal_error: %d",
5890
			 thd->is_fatal_error));
5891 5892

      query_cache_abort(&thd->net);
5893
    }
5894 5895 5896 5897 5898 5899
    if (thd->lex->sphead)
    {
      delete thd->lex->sphead;
      thd->lex->sphead= 0;
    }
    lex->unit.cleanup();
5900
    thd_proc_info(thd, "freeing items");
5901
    thd->end_statement();
5902
    thd->cleanup_after_query();
5903
    DBUG_ASSERT(thd->change_list.is_empty());
unknown's avatar
unknown committed
5904
  }
5905 5906 5907 5908 5909 5910
  else
  {
    /* There are no multi queries in the cache. */
    *found_semicolon= NULL;
  }

unknown's avatar
unknown committed
5911 5912 5913 5914
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
5915
#ifdef HAVE_REPLICATION
5916 5917 5918 5919
/*
  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
5920
  @retval
5921
    0	cannot be ignored
unknown's avatar
unknown committed
5922
  @retval
5923 5924 5925 5926 5927
    1	can be ignored
*/

bool mysql_test_parse_for_slave(THD *thd, char *inBuf, uint length)
{
unknown's avatar
unknown committed
5928
  LEX *lex= thd->lex;
5929
  bool error= 0;
unknown's avatar
unknown committed
5930
  DBUG_ENTER("mysql_test_parse_for_slave");
5931

5932
  Parser_state parser_state(thd, inBuf, length);
5933 5934 5935
  lex_start(thd);
  mysql_reset_thd_for_next_command(thd);

5936
  if (!parse_sql(thd, & parser_state, NULL) &&
5937
      all_tables_not_ok(thd,(TABLE_LIST*) lex->select_lex.table_list.first))
unknown's avatar
unknown committed
5938
    error= 1;                  /* Ignore question */
5939
  thd->end_statement();
5940
  thd->cleanup_after_query();
unknown's avatar
unknown committed
5941
  DBUG_RETURN(error);
5942
}
unknown's avatar
unknown committed
5943
#endif
unknown's avatar
unknown committed
5944

5945

unknown's avatar
unknown committed
5946

unknown's avatar
unknown committed
5947 5948 5949 5950 5951 5952
/**
  Store field definition for create.

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

5954
bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum_field_types type,
unknown's avatar
unknown committed
5955
		       char *length, char *decimals,
5956
		       uint type_modifier,
5957 5958
		       Item *default_value, Item *on_update_value,
                       LEX_STRING *comment,
5959 5960
		       char *change,
                       List<String> *interval_list, CHARSET_INFO *cs,
unknown's avatar
unknown committed
5961
		       uint uint_geom_type)
unknown's avatar
unknown committed
5962
{
unknown's avatar
unknown committed
5963
  register Create_field *new_field;
unknown's avatar
unknown committed
5964
  LEX  *lex= thd->lex;
unknown's avatar
unknown committed
5965 5966
  DBUG_ENTER("add_field_to_list");

5967 5968
  if (check_string_char_length(field_name, "", NAME_CHAR_LEN,
                               system_charset_info, 1))
unknown's avatar
unknown committed
5969
  {
5970
    my_error(ER_TOO_LONG_IDENT, MYF(0), field_name->str); /* purecov: inspected */
unknown's avatar
unknown committed
5971 5972 5973 5974
    DBUG_RETURN(1);				/* purecov: inspected */
  }
  if (type_modifier & PRI_KEY_FLAG)
  {
5975
    Key *key;
unknown's avatar
unknown committed
5976
    lex->col_list.push_back(new Key_part_spec(field_name->str, 0));
5977 5978 5979 5980
    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
5981 5982 5983 5984
    lex->col_list.empty();
  }
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
  {
5985
    Key *key;
unknown's avatar
unknown committed
5986
    lex->col_list.push_back(new Key_part_spec(field_name->str, 0));
5987 5988 5989 5990
    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
5991 5992 5993
    lex->col_list.empty();
  }

5994
  if (default_value)
unknown's avatar
unknown committed
5995
  {
5996
    /* 
unknown's avatar
unknown committed
5997 5998
      Default value should be literal => basic constants =>
      no need fix_fields()
5999 6000 6001
      
      We allow only one function as part of default value - 
      NOW() as default for TIMESTAMP type.
6002
    */
6003 6004
    if (default_value->type() == Item::FUNC_ITEM && 
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
6005
         type == MYSQL_TYPE_TIMESTAMP))
6006
    {
6007
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
6008 6009 6010
      DBUG_RETURN(1);
    }
    else if (default_value->type() == Item::NULL_ITEM)
unknown's avatar
unknown committed
6011
    {
6012
      default_value= 0;
6013 6014 6015
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
	  NOT_NULL_FLAG)
      {
6016
	my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
6017 6018 6019 6020 6021
	DBUG_RETURN(1);
      }
    }
    else if (type_modifier & AUTO_INCREMENT_FLAG)
    {
6022
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
unknown's avatar
unknown committed
6023 6024 6025
      DBUG_RETURN(1);
    }
  }
6026

6027
  if (on_update_value && type != MYSQL_TYPE_TIMESTAMP)
6028
  {
6029
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
6030 6031
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
6032

6033
  if (type == MYSQL_TYPE_TIMESTAMP && length)
6034 6035 6036 6037 6038
  {
    /* 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
6039
    char buf[32];
6040
    my_snprintf(buf, sizeof(buf), "TIMESTAMP(%s)", length);
6041
    WARN_DEPRECATED(thd, "6.0", buf, "'TIMESTAMP'");
6042 6043
  }

unknown's avatar
unknown committed
6044
  if (!(new_field= new Create_field()) ||
6045
      new_field->init(thd, field_name->str, type, length, decimals, type_modifier,
6046 6047
                      default_value, on_update_value, comment, change,
                      interval_list, cs, uint_geom_type))
unknown's avatar
unknown committed
6048
    DBUG_RETURN(1);
unknown's avatar
unknown committed
6049

6050
  lex->alter_info.create_list.push_back(new_field);
unknown's avatar
unknown committed
6051 6052 6053 6054
  lex->last_field=new_field;
  DBUG_RETURN(0);
}

6055

unknown's avatar
unknown committed
6056
/** Store position for column in ALTER TABLE .. ADD column. */
unknown's avatar
unknown committed
6057 6058 6059

void store_position_for_column(const char *name)
{
6060
  current_thd->lex->last_field->after=my_const_cast(char*) (name);
unknown's avatar
unknown committed
6061 6062 6063
}

bool
unknown's avatar
unknown committed
6064
add_proc_to_list(THD* thd, Item *item)
unknown's avatar
unknown committed
6065 6066 6067 6068
{
  ORDER *order;
  Item	**item_ptr;

unknown's avatar
unknown committed
6069
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*))))
unknown's avatar
unknown committed
6070 6071 6072 6073 6074
    return 1;
  item_ptr = (Item**) (order+1);
  *item_ptr= item;
  order->item=item_ptr;
  order->free_me=0;
6075
  thd->lex->proc_list.link_in_list((uchar*) order,(uchar**) &order->next);
unknown's avatar
unknown committed
6076 6077 6078 6079
  return 0;
}


unknown's avatar
unknown committed
6080 6081 6082
/**
  save order by and tables in own lists.
*/
unknown's avatar
unknown committed
6083

unknown's avatar
unknown committed
6084
bool add_to_list(THD *thd, SQL_LIST &list,Item *item,bool asc)
unknown's avatar
unknown committed
6085 6086 6087
{
  ORDER *order;
  DBUG_ENTER("add_to_list");
unknown's avatar
unknown committed
6088
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER))))
unknown's avatar
unknown committed
6089
    DBUG_RETURN(1);
unknown's avatar
unknown committed
6090 6091
  order->item_ptr= item;
  order->item= &order->item_ptr;
unknown's avatar
unknown committed
6092 6093 6094
  order->asc = asc;
  order->free_me=0;
  order->used=0;
6095
  order->counter_used= 0;
6096
  list.link_in_list((uchar*) order,(uchar**) &order->next);
unknown's avatar
unknown committed
6097 6098 6099 6100
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114
/**
  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
6115
      0		Error
unknown's avatar
unknown committed
6116 6117
  @retval
    \#	Pointer to TABLE_LIST element added to the total table list
unknown's avatar
unknown committed
6118 6119
*/

unknown's avatar
unknown committed
6120 6121
TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
					     Table_ident *table,
6122
					     LEX_STRING *alias,
unknown's avatar
unknown committed
6123 6124
					     ulong table_options,
					     thr_lock_type lock_type,
unknown's avatar
unknown committed
6125
					     List<Index_hint> *index_hints_arg,
unknown's avatar
unknown committed
6126
                                             LEX_STRING *option)
unknown's avatar
unknown committed
6127 6128
{
  register TABLE_LIST *ptr;
unknown's avatar
unknown committed
6129
  TABLE_LIST *previous_table_ref; /* The table preceding the current one. */
unknown's avatar
unknown committed
6130
  char *alias_str;
6131
  LEX *lex= thd->lex;
unknown's avatar
unknown committed
6132
  DBUG_ENTER("add_table_to_list");
6133
  LINT_INIT(previous_table_ref);
unknown's avatar
unknown committed
6134 6135 6136 6137

  if (!table)
    DBUG_RETURN(0);				// End of memory
  alias_str= alias ? alias->str : table->table.str;
6138 6139
  if (!test(table_options & TL_OPTION_ALIAS) && 
      check_table_name(table->table.str, table->table.length))
unknown's avatar
unknown committed
6140
  {
6141
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
unknown's avatar
unknown committed
6142 6143
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
6144 6145

  if (table->is_derived_table() == FALSE && table->db.str &&
6146
      check_db_name(&table->db))
unknown's avatar
unknown committed
6147 6148 6149 6150
  {
    my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
6151 6152

  if (!alias)					/* Alias is case sensitive */
6153 6154 6155
  {
    if (table->sel)
    {
unknown's avatar
unknown committed
6156 6157
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
                 ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
6158 6159
      DBUG_RETURN(0);
    }
6160
    if (!(alias_str= (char*) thd->memdup(alias_str,table->table.length+1)))
unknown's avatar
unknown committed
6161
      DBUG_RETURN(0);
6162
  }
unknown's avatar
unknown committed
6163
  if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST))))
unknown's avatar
unknown committed
6164
    DBUG_RETURN(0);				/* purecov: inspected */
unknown's avatar
unknown committed
6165
  if (table->db.str)
6166 6167 6168 6169
  {
    ptr->db= table->db.str;
    ptr->db_length= table->db.length;
  }
6170
  else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
unknown's avatar
unknown committed
6171
    DBUG_RETURN(0);
unknown's avatar
unknown committed
6172

6173
  ptr->alias= alias_str;
6174
  if (lower_case_table_names && table->table.length)
6175
    table->table.length= my_casedn_str(files_charset_info, table->table.str);
6176 6177
  ptr->table_name=table->table.str;
  ptr->table_name_length=table->table.length;
6178
  ptr->lock_type=   lock_type;
unknown's avatar
unknown committed
6179 6180
  ptr->updating=    test(table_options & TL_OPTION_UPDATING);
  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
unknown's avatar
unknown committed
6181
  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
6182
  ptr->derived=	    table->sel;
6183
  if (!ptr->derived && !my_strcasecmp(system_charset_info, ptr->db,
6184
                                      INFORMATION_SCHEMA_NAME.str))
6185
  {
6186
    ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, ptr->table_name);
6187 6188
    if (!schema_table ||
        (schema_table->hidden && 
unknown's avatar
unknown committed
6189
         ((sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0 || 
6190 6191 6192
          /*
            this check is used for show columns|keys from I_S hidden table
          */
unknown's avatar
unknown committed
6193 6194
          lex->sql_command == SQLCOM_SHOW_FIELDS ||
          lex->sql_command == SQLCOM_SHOW_KEYS)))
6195
    {
unknown's avatar
unknown committed
6196
      my_error(ER_UNKNOWN_TABLE, MYF(0),
6197
               ptr->table_name, INFORMATION_SCHEMA_NAME.str);
6198 6199
      DBUG_RETURN(0);
    }
6200
    ptr->schema_table_name= ptr->table_name;
6201 6202
    ptr->schema_table= schema_table;
  }
6203
  ptr->select_lex=  lex->current_select;
unknown's avatar
unknown committed
6204
  ptr->cacheable_table= 1;
6205
  ptr->index_hints= index_hints_arg;
unknown's avatar
unknown committed
6206
  ptr->option= option ? option->str : 0;
unknown's avatar
unknown committed
6207
  /* check that used name is unique */
6208
  if (lock_type != TL_IGNORE)
unknown's avatar
unknown committed
6209
  {
unknown's avatar
unknown committed
6210 6211 6212 6213
    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
6214
	 tables ;
unknown's avatar
VIEW  
unknown committed
6215
	 tables=tables->next_local)
unknown's avatar
unknown committed
6216
    {
6217 6218
      if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
	  !strcmp(ptr->db, tables->db))
unknown's avatar
unknown committed
6219
      {
6220
	my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
unknown's avatar
unknown committed
6221 6222
	DBUG_RETURN(0);				/* purecov: tested */
      }
unknown's avatar
unknown committed
6223 6224
    }
  }
unknown's avatar
unknown committed
6225 6226 6227
  /* Store the table reference preceding the current one. */
  if (table_list.elements > 0)
  {
6228 6229 6230
    /*
      table_list.next points to the last inserted TABLE_LIST->next_local'
      element
6231
      We don't use the offsetof() macro here to avoid warnings from gcc
6232
    */
6233 6234 6235
    previous_table_ref= (TABLE_LIST*) ((char*) table_list.next -
                                       ((char*) &(ptr->next_local) -
                                        (char*) ptr));
6236 6237 6238 6239 6240 6241 6242 6243
    /*
      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
6244
  }
6245

unknown's avatar
unknown committed
6246 6247 6248 6249 6250 6251
  /*
    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'.
  */
6252
  table_list.link_in_list((uchar*) ptr, (uchar**) &ptr->next_local);
unknown's avatar
unknown committed
6253
  ptr->next_name_resolution_table= NULL;
6254
  /* Link table in global list (all used tables) */
6255
  lex->add_to_query_tables(ptr);
unknown's avatar
unknown committed
6256 6257 6258
  DBUG_RETURN(ptr);
}

unknown's avatar
unknown committed
6259

unknown's avatar
unknown committed
6260 6261
/**
  Initialize a new table list for a nested join.
6262

6263 6264 6265 6266 6267 6268 6269 6270
    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
6271 6272 6273 6274 6275 6276
  @param thd         current thread

  @retval
    0   if success
  @retval
    1   otherwise
6277 6278 6279 6280 6281 6282 6283
*/

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

6285 6286
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
6287
    DBUG_RETURN(1);
6288
  nested_join= ptr->nested_join=
6289
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
6290

6291 6292 6293
  join_list->push_front(ptr);
  ptr->embedding= embedding;
  ptr->join_list= join_list;
6294
  ptr->alias= (char*) "(nested_join)";
6295 6296 6297 6298 6299 6300 6301
  embedding= ptr;
  join_list= &nested_join->join_list;
  join_list->empty();
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
6302 6303
/**
  End a nested join table list.
6304 6305 6306

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

unknown's avatar
unknown committed
6309 6310 6311 6312 6313
  @param thd         current thread

  @return
    - Pointer to TABLE_LIST element added to the total table list, if success
    - 0, otherwise
6314 6315 6316 6317 6318
*/

TABLE_LIST *st_select_lex::end_nested_join(THD *thd)
{
  TABLE_LIST *ptr;
6319
  NESTED_JOIN *nested_join;
6320
  DBUG_ENTER("end_nested_join");
6321

unknown's avatar
unknown committed
6322
  DBUG_ASSERT(embedding);
6323 6324 6325
  ptr= embedding;
  join_list= ptr->join_list;
  embedding= ptr->embedding;
6326
  nested_join= ptr->nested_join;
6327 6328 6329 6330 6331 6332 6333 6334 6335
  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;
  }
6336
  else if (nested_join->join_list.elements == 0)
unknown's avatar
unknown committed
6337 6338
  {
    join_list->pop();
6339
    ptr= 0;                                     // return value
unknown's avatar
unknown committed
6340
  }
6341 6342 6343 6344
  DBUG_RETURN(ptr);
}


unknown's avatar
unknown committed
6345 6346
/**
  Nest last join operation.
6347 6348 6349

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

unknown's avatar
unknown committed
6350
  @param thd         current thread
6351

unknown's avatar
unknown committed
6352
  @retval
6353
    0  Error
unknown's avatar
unknown committed
6354 6355
  @retval
    \#  Pointer to TABLE_LIST element created for the new nested join
6356 6357 6358 6359 6360 6361
*/

TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
6362
  List<TABLE_LIST> *embedded_list;
6363
  DBUG_ENTER("nest_last_join");
6364

6365 6366
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
6367
    DBUG_RETURN(0);
6368
  nested_join= ptr->nested_join=
6369
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
6370

6371 6372
  ptr->embedding= embedding;
  ptr->join_list= join_list;
6373
  ptr->alias= (char*) "(nest_last_join)";
6374
  embedded_list= &nested_join->join_list;
6375
  embedded_list->empty();
6376 6377

  for (uint i=0; i < 2; i++)
6378 6379 6380 6381 6382
  {
    TABLE_LIST *table= join_list->pop();
    table->join_list= embedded_list;
    table->embedding= ptr;
    embedded_list->push_back(table);
unknown's avatar
unknown committed
6383 6384 6385 6386 6387 6388 6389
    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
6390 6391
      if (prev_join_using)
        ptr->join_using_fields= prev_join_using;
unknown's avatar
unknown committed
6392
    }
6393 6394 6395 6396 6397 6398 6399
  }
  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
6400 6401
/**
  Add a table to the current join list.
6402 6403 6404 6405 6406 6407

    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
6408 6409 6410
  @param table       the table to add

  @return
6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423
    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
6424 6425
/**
  Convert a right join into equivalent left join.
6426 6427

    The function takes the current join list t[0],t[1] ... and
6428 6429 6430 6431 6432 6433
    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
6434
  @verbatim
6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445
    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
6446
   @endverbatim
6447

unknown's avatar
unknown committed
6448
  @param thd         current thread
6449

unknown's avatar
unknown committed
6450 6451 6452
  @return
    - Pointer to the table representing the inner table, if success
    - 0, otherwise
6453 6454
*/

6455
TABLE_LIST *st_select_lex::convert_right_join()
6456 6457
{
  TABLE_LIST *tab2= join_list->pop();
6458
  TABLE_LIST *tab1= join_list->pop();
6459 6460 6461 6462 6463 6464 6465 6466 6467
  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
6468 6469
/**
  Set lock for all tables in current select level.
unknown's avatar
unknown committed
6470

unknown's avatar
unknown committed
6471
  @param lock_type			Lock to set for tables
unknown's avatar
unknown committed
6472

unknown's avatar
unknown committed
6473
  @note
unknown's avatar
unknown committed
6474 6475 6476 6477 6478
    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
6479
void st_select_lex::set_lock_for_tables(thr_lock_type lock_type)
unknown's avatar
unknown committed
6480 6481 6482 6483 6484 6485
{
  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
6486 6487 6488
  for (TABLE_LIST *tables= (TABLE_LIST*) table_list.first;
       tables;
       tables= tables->next_local)
unknown's avatar
unknown committed
6489 6490 6491 6492 6493 6494 6495
  {
    tables->lock_type= lock_type;
    tables->updating=  for_update;
  }
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
6496

unknown's avatar
unknown committed
6497 6498
/**
  Create a fake SELECT_LEX for a unit.
unknown's avatar
unknown committed
6499 6500 6501 6502

    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
6503
    @verbatim
unknown's avatar
unknown committed
6504
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ... 
unknown's avatar
unknown committed
6505
    @endvarbatim
unknown's avatar
unknown committed
6506
    or of the form
unknown's avatar
unknown committed
6507
    @varbatim
unknown's avatar
unknown committed
6508
    (SELECT ... ORDER BY LIMIT n) ORDER BY ...
unknown's avatar
unknown committed
6509
    @endvarbatim
unknown's avatar
unknown committed
6510
  
unknown's avatar
unknown committed
6511 6512 6513
  @param thd_arg		   thread handle

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

unknown's avatar
unknown committed
6517
  @retval
unknown's avatar
unknown committed
6518
    1     on failure to create the object
unknown's avatar
unknown committed
6519
  @retval
unknown's avatar
unknown committed
6520 6521 6522
    0     on success
*/

unknown's avatar
unknown committed
6523
bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg)
unknown's avatar
unknown committed
6524 6525 6526 6527
{
  SELECT_LEX *first_sl= first_select();
  DBUG_ENTER("add_fake_select_lex");
  DBUG_ASSERT(!fake_select_lex);
unknown's avatar
unknown committed
6528

unknown's avatar
unknown committed
6529
  if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX()))
unknown's avatar
unknown committed
6530 6531 6532 6533
      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
6534
  fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */
unknown's avatar
unknown committed
6535 6536
  fake_select_lex->make_empty_select();
  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
6537 6538
  fake_select_lex->select_limit= 0;

unknown's avatar
unknown committed
6539
  fake_select_lex->context.outer_context=first_sl->context.outer_context;
6540 6541 6542
  /* 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
6543

6544
  if (!is_union())
unknown's avatar
unknown committed
6545 6546 6547 6548 6549 6550 6551 6552 6553
  {
    /* 
      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
6554
    thd_arg->lex->current_select= fake_select_lex;
unknown's avatar
unknown committed
6555
  }
unknown's avatar
unknown committed
6556
  thd_arg->lex->pop_context();
unknown's avatar
unknown committed
6557 6558 6559
  DBUG_RETURN(0);
}

6560

unknown's avatar
unknown committed
6561
/**
6562 6563
  Push a new name resolution context for a JOIN ... ON clause to the
  context stack of a query block.
unknown's avatar
unknown committed
6564 6565

    Create a new name resolution context for a JOIN ... ON clause,
6566 6567 6568
    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
6569

unknown's avatar
unknown committed
6570 6571 6572 6573 6574
  @param thd       pointer to current thread
  @param left_op   left  operand of the JOIN
  @param right_op  rigth operand of the JOIN

  @retval
6575
    FALSE  if all is OK
unknown's avatar
unknown committed
6576
  @retval
6577
    TRUE   if a memory allocation error occured
unknown's avatar
unknown committed
6578 6579
*/

6580 6581 6582
bool
push_new_name_resolution_context(THD *thd,
                                 TABLE_LIST *left_op, TABLE_LIST *right_op)
unknown's avatar
unknown committed
6583 6584
{
  Name_resolution_context *on_context;
6585
  if (!(on_context= new (thd->mem_root) Name_resolution_context))
6586
    return TRUE;
unknown's avatar
unknown committed
6587 6588 6589 6590 6591
  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();
6592
  return thd->lex->push_context(on_context);
unknown's avatar
unknown committed
6593 6594 6595
}


unknown's avatar
unknown committed
6596
/**
unknown's avatar
unknown committed
6597 6598 6599 6600
  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
6601 6602
  @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
6603

unknown's avatar
unknown committed
6604
  @retval
unknown's avatar
unknown committed
6605
    FALSE  if there was some error
unknown's avatar
unknown committed
6606
  @retval
unknown's avatar
unknown committed
6607 6608 6609 6610
    TRUE   if all is OK
*/

void add_join_on(TABLE_LIST *b, Item *expr)
unknown's avatar
unknown committed
6611
{
6612
  if (expr)
6613
  {
6614
    if (!b->on_expr)
unknown's avatar
unknown committed
6615
      b->on_expr= expr;
6616 6617
    else
    {
unknown's avatar
unknown committed
6618 6619 6620 6621 6622 6623
      /*
        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);
6624 6625
    }
    b->on_expr->top_level_item();
6626
  }
unknown's avatar
unknown committed
6627 6628 6629
}


unknown's avatar
unknown committed
6630
/**
unknown's avatar
unknown committed
6631 6632
  Mark that there is a NATURAL JOIN or JOIN ... USING between two
  tables.
6633

unknown's avatar
unknown committed
6634 6635 6636 6637 6638 6639 6640 6641 6642 6643
    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
6644
  @verbatim
6645 6646 6647
    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
6648

unknown's avatar
unknown committed
6649 6650 6651
    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
6652

unknown's avatar
unknown committed
6653 6654 6655
    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
6656 6657 6658 6659 6660
   @endverbatim

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

unknown's avatar
unknown committed
6663 6664
void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields,
                      SELECT_LEX *lex)
unknown's avatar
unknown committed
6665
{
unknown's avatar
unknown committed
6666
  b->natural_join= a;
unknown's avatar
unknown committed
6667
  lex->prev_join_using= using_fields;
unknown's avatar
unknown committed
6668 6669
}

unknown's avatar
unknown committed
6670

6671
/**
6672 6673
  Reload/resets privileges and the different caches.

6674 6675 6676 6677
  @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.
6678
               
6679 6680 6681 6682 6683 6684 6685 6686
  @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
6687
    @retval !=0  Error; thd->killed is set or thd->is_error() is true
6688 6689
*/

6690 6691
bool reload_acl_and_cache(THD *thd, ulong options, TABLE_LIST *tables,
                          bool *write_to_binlog)
unknown's avatar
unknown committed
6692 6693 6694
{
  bool result=0;
  select_errors=0;				/* Write if more errors */
6695
  bool tmp_write_to_binlog= 1;
6696

6697
  DBUG_ASSERT(!thd || !thd->in_sub_stmt);
6698

unknown's avatar
SCRUM  
unknown committed
6699
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
6700 6701
  if (options & REFRESH_GRANT)
  {
6702 6703 6704 6705 6706 6707
    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)))
6708 6709
    {
      thd->thread_stack= (char*) &tmp_thd;
6710
      thd->store_globals();
6711
      lex_start(thd);
6712
    }
6713
    
6714 6715
    if (thd)
    {
6716 6717
      bool reload_acl_failed= acl_reload(thd);
      bool reload_grants_failed= grant_reload(thd);
Kristofer Pettersson's avatar
Kristofer Pettersson committed
6718 6719 6720
      bool reload_servers_failed= servers_reload(thd);
      
      if (reload_acl_failed || reload_grants_failed || reload_servers_failed)
6721
      {
6722
        result= 1;
6723 6724 6725 6726 6727 6728
        /*
          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");
      }
6729
    }
6730

6731 6732 6733 6734 6735 6736 6737
    if (tmp_thd)
    {
      delete tmp_thd;
      /* Remember that we don't have a THD */
      my_pthread_setspecific_ptr(THR_THD,  0);
      thd= 0;
    }
6738
    reset_mqh((LEX_USER *)NULL, TRUE);
unknown's avatar
unknown committed
6739
  }
unknown's avatar
SCRUM  
unknown committed
6740
#endif
unknown's avatar
unknown committed
6741 6742
  if (options & REFRESH_LOG)
  {
6743
    /*
unknown's avatar
unknown committed
6744
      Flush the normal query log, the update log, the binary log,
unknown's avatar
unknown committed
6745 6746
      the slow query log, the relay log (if it exists) and the log
      tables.
6747
    */
unknown's avatar
unknown committed
6748

6749
    /*
unknown's avatar
unknown committed
6750 6751 6752 6753
      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)
6754 6755
    */
    tmp_write_to_binlog= 0;
6756 6757 6758 6759
    if( mysql_bin_log.is_open() )
    {
      mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
    }
unknown's avatar
unknown committed
6760
#ifdef HAVE_REPLICATION
6761
    pthread_mutex_lock(&LOCK_active_mi);
6762
    rotate_relay_log(active_mi);
6763
    pthread_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
6764
#endif
unknown's avatar
unknown committed
6765 6766 6767 6768 6769

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

    if (ha_flush_logs(NULL))
unknown's avatar
unknown committed
6770
      result=1;
unknown's avatar
unknown committed
6771 6772
    if (flush_error_log())
      result=1;
unknown's avatar
unknown committed
6773
  }
unknown's avatar
unknown committed
6774
#ifdef HAVE_QUERY_CACHE
unknown's avatar
unknown committed
6775 6776
  if (options & REFRESH_QUERY_CACHE_FREE)
  {
unknown's avatar
unknown committed
6777
    query_cache.pack();				// FLUSH QUERY CACHE
6778
    options &= ~REFRESH_QUERY_CACHE;    // Don't flush cache, just free memory
unknown's avatar
unknown committed
6779 6780 6781
  }
  if (options & (REFRESH_TABLES | REFRESH_QUERY_CACHE))
  {
unknown's avatar
unknown committed
6782
    query_cache.flush();			// RESET QUERY CACHE
unknown's avatar
unknown committed
6783
  }
unknown's avatar
unknown committed
6784
#endif /*HAVE_QUERY_CACHE*/
6785 6786 6787 6788 6789
  /*
    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
6790
  {
6791
    if ((options & REFRESH_READ_LOCK) && thd)
unknown's avatar
unknown committed
6792
    {
6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803
      /*
        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
6804
        {
6805
          if ((*lock_p)->type >= TL_WRITE_ALLOW_WRITE)
6806 6807 6808 6809
          {
            my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
            return 1;
          }
unknown's avatar
unknown committed
6810
        }
6811
      }
unknown's avatar
unknown committed
6812 6813 6814 6815
      /*
	Writing to the binlog could cause deadlocks, as we don't log
	UNLOCK TABLES
      */
6816
      tmp_write_to_binlog= 0;
6817
      if (lock_global_read_lock(thd))
unknown's avatar
unknown committed
6818
	return 1;                               // Killed
Kristofer Pettersson's avatar
Kristofer Pettersson committed
6819
      if (close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ?
6820
                              FALSE : TRUE, TRUE))
6821 6822
          result= 1;
      
unknown's avatar
unknown committed
6823
      if (make_global_read_lock_block_commit(thd)) // Killed
6824 6825 6826 6827 6828
      {
        /* Don't leave things in a half-locked state */
        unlock_global_read_lock(thd);
        return 1;
      }
unknown's avatar
unknown committed
6829
    }
6830
    else
6831
    {
Kristofer Pettersson's avatar
Kristofer Pettersson committed
6832
      if (close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ?
6833
                              FALSE : TRUE, FALSE))
6834 6835
        result= 1;
    }
unknown's avatar
unknown committed
6836
    my_dbopt_cleanup();
unknown's avatar
unknown committed
6837 6838 6839
  }
  if (options & REFRESH_HOSTS)
    hostname_cache_refresh();
unknown's avatar
unknown committed
6840
  if (thd && (options & REFRESH_STATUS))
unknown's avatar
unknown committed
6841
    refresh_status(thd);
unknown's avatar
unknown committed
6842 6843
  if (options & REFRESH_THREADS)
    flush_thread_cache();
unknown's avatar
unknown committed
6844
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
6845
  if (options & REFRESH_MASTER)
6846
  {
6847
    DBUG_ASSERT(thd);
6848
    tmp_write_to_binlog= 0;
6849
    if (reset_master(thd))
unknown's avatar
unknown committed
6850
    {
6851
      result=1;
unknown's avatar
unknown committed
6852
    }
6853
  }
6854
#endif
unknown's avatar
unknown committed
6855
#ifdef OPENSSL
6856 6857
   if (options & REFRESH_DES_KEY_FILE)
   {
6858 6859
     if (des_key_file && load_des_key_file(des_key_file))
         result= 1;
6860 6861
   }
#endif
unknown's avatar
unknown committed
6862
#ifdef HAVE_REPLICATION
6863 6864
 if (options & REFRESH_SLAVE)
 {
6865
   tmp_write_to_binlog= 0;
6866
   pthread_mutex_lock(&LOCK_active_mi);
6867
   if (reset_slave(thd, active_mi))
6868
     result=1;
6869
   pthread_mutex_unlock(&LOCK_active_mi);
6870
 }
6871
#endif
6872
 if (options & REFRESH_USER_RESOURCES)
6873
   reset_mqh((LEX_USER *) NULL, 0);             /* purecov: inspected */
unknown's avatar
unknown committed
6874
 *write_to_binlog= tmp_write_to_binlog;
6875
 return result;
unknown's avatar
unknown committed
6876 6877
}

6878

unknown's avatar
unknown committed
6879 6880
/**
  kill on thread.
6881

unknown's avatar
unknown committed
6882 6883 6884
  @param thd			Thread class
  @param id			Thread id
  @param only_kill_query        Should it kill the query or the connection
6885

unknown's avatar
unknown committed
6886
  @note
6887 6888 6889
    This is written such that we have a short lock on LOCK_thread_count
*/

6890
uint kill_one_thread(THD *thd, ulong id, bool only_kill_query)
unknown's avatar
unknown committed
6891 6892 6893
{
  THD *tmp;
  uint error=ER_NO_SUCH_THREAD;
6894 6895
  DBUG_ENTER("kill_one_thread");
  DBUG_PRINT("enter", ("id=%lu only_kill=%d", id, only_kill_query));
6896 6897
  VOID(pthread_mutex_lock(&LOCK_thread_count)); // For unlink from list
  I_List_iterator<THD> it(threads);
unknown's avatar
unknown committed
6898 6899
  while ((tmp=it++))
  {
unknown's avatar
unknown committed
6900 6901
    if (tmp->command == COM_DAEMON)
      continue;
unknown's avatar
unknown committed
6902 6903
    if (tmp->thread_id == id)
    {
6904 6905
      pthread_mutex_lock(&tmp->LOCK_delete);	// Lock from delete
      break;
unknown's avatar
unknown committed
6906 6907 6908
    }
  }
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
6909 6910
  if (tmp)
  {
6911 6912
    if ((thd->security_ctx->master_access & SUPER_ACL) ||
	!strcmp(thd->security_ctx->user, tmp->security_ctx->user))
6913
    {
unknown's avatar
SCRUM  
unknown committed
6914
      tmp->awake(only_kill_query ? THD::KILL_QUERY : THD::KILL_CONNECTION);
6915 6916 6917 6918 6919 6920
      error=0;
    }
    else
      error=ER_KILL_DENIED_ERROR;
    pthread_mutex_unlock(&tmp->LOCK_delete);
  }
6921 6922 6923 6924
  DBUG_PRINT("exit", ("%d", error));
  DBUG_RETURN(error);
}

6925

6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939
/*
  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)))
6940
    my_ok(thd);
unknown's avatar
unknown committed
6941
  else
unknown's avatar
unknown committed
6942
    my_error(error, MYF(0), id);
unknown's avatar
unknown committed
6943 6944
}

unknown's avatar
unknown committed
6945

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

unknown's avatar
unknown committed
6948 6949
bool append_file_to_dir(THD *thd, const char **filename_ptr,
                        const char *table_name)
6950
{
6951
  char buff[FN_REFLEN],*ptr, *end;
6952 6953 6954 6955 6956 6957 6958
  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))
  {
6959
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
6960 6961 6962 6963
    return 1;
  }
  /* Fix is using unix filename format on dos */
  strmov(buff,*filename_ptr);
6964
  end=convert_dirname(buff, *filename_ptr, NullS);
6965
  if (!(ptr= (char*) thd->alloc((size_t) (end-buff) + strlen(table_name)+1)))
6966 6967
    return 1;					// End of memory
  *filename_ptr=ptr;
6968
  strxmov(ptr,buff,table_name,NullS);
6969 6970
  return 0;
}
6971

6972

unknown's avatar
unknown committed
6973 6974
/**
  Check if the select is a simple select (not an union).
6975

unknown's avatar
unknown committed
6976
  @retval
6977
    0	ok
unknown's avatar
unknown committed
6978
  @retval
6979 6980 6981 6982 6983 6984
    1	error	; In this case the error messege is sent to the client
*/

bool check_simple_select()
{
  THD *thd= current_thd;
6985 6986
  LEX *lex= thd->lex;
  if (lex->current_select != &lex->select_lex)
6987 6988
  {
    char command[80];
6989
    Lex_input_stream *lip= & thd->m_parser_state->m_lip;
6990 6991
    strmake(command, lip->yylval->symbol.str,
	    min(lip->yylval->symbol.length, sizeof(command)-1));
6992
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
6993 6994 6995 6996
    return 1;
  }
  return 0;
}
unknown's avatar
unknown committed
6997

unknown's avatar
unknown committed
6998

unknown's avatar
unknown committed
6999
Comp_creator *comp_eq_creator(bool invert)
unknown's avatar
unknown committed
7000
{
unknown's avatar
unknown committed
7001
  return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
unknown's avatar
unknown committed
7002 7003
}

unknown's avatar
unknown committed
7004

unknown's avatar
unknown committed
7005
Comp_creator *comp_ge_creator(bool invert)
unknown's avatar
unknown committed
7006
{
unknown's avatar
unknown committed
7007
  return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator;
unknown's avatar
unknown committed
7008 7009
}

unknown's avatar
unknown committed
7010

unknown's avatar
unknown committed
7011
Comp_creator *comp_gt_creator(bool invert)
unknown's avatar
unknown committed
7012
{
unknown's avatar
unknown committed
7013
  return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator;
unknown's avatar
unknown committed
7014 7015
}

unknown's avatar
unknown committed
7016

unknown's avatar
unknown committed
7017
Comp_creator *comp_le_creator(bool invert)
unknown's avatar
unknown committed
7018
{
unknown's avatar
unknown committed
7019
  return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator;
unknown's avatar
unknown committed
7020 7021
}

unknown's avatar
unknown committed
7022

unknown's avatar
unknown committed
7023
Comp_creator *comp_lt_creator(bool invert)
unknown's avatar
unknown committed
7024
{
unknown's avatar
unknown committed
7025
  return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator;
unknown's avatar
unknown committed
7026 7027
}

unknown's avatar
unknown committed
7028

unknown's avatar
unknown committed
7029
Comp_creator *comp_ne_creator(bool invert)
unknown's avatar
unknown committed
7030
{
unknown's avatar
unknown committed
7031
  return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
unknown's avatar
unknown committed
7032
}
unknown's avatar
unknown committed
7033 7034


unknown's avatar
unknown committed
7035 7036
/**
  Construct ALL/ANY/SOME subquery Item.
unknown's avatar
unknown committed
7037

unknown's avatar
unknown committed
7038 7039 7040 7041
  @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
7042

unknown's avatar
unknown committed
7043
  @return
unknown's avatar
unknown committed
7044 7045 7046 7047 7048 7049 7050
    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
7051
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
unknown's avatar
unknown committed
7052
    return new Item_in_subselect(left_expr, select_lex);
unknown's avatar
unknown committed
7053 7054

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

  Item_allany_subselect *it=
7058
    new Item_allany_subselect(left_expr, cmp, select_lex, all);
unknown's avatar
unknown committed
7059
  if (all)
7060
    return it->upper_item= new Item_func_not_all(it);	/* ALL */
unknown's avatar
unknown committed
7061

7062
  return it->upper_item= new Item_func_nop_all(it);      /* ANY/SOME */
unknown's avatar
unknown committed
7063
}
7064 7065


unknown's avatar
unknown committed
7066 7067
/**
  Multi update query pre-check.
7068

unknown's avatar
unknown committed
7069 7070
  @param thd		Thread handler
  @param tables	Global/local table list (have to be the same)
7071

unknown's avatar
unknown committed
7072
  @retval
unknown's avatar
unknown committed
7073
    FALSE OK
unknown's avatar
unknown committed
7074
  @retval
unknown's avatar
unknown committed
7075
    TRUE  Error
7076
*/
unknown's avatar
unknown committed
7077

unknown's avatar
unknown committed
7078
bool multi_update_precheck(THD *thd, TABLE_LIST *tables)
7079 7080 7081 7082 7083
{
  const char *msg= 0;
  TABLE_LIST *table;
  LEX *lex= thd->lex;
  SELECT_LEX *select_lex= &lex->select_lex;
unknown's avatar
VIEW  
unknown committed
7084
  DBUG_ENTER("multi_update_precheck");
7085 7086 7087

  if (select_lex->item_list.elements != lex->value_list.elements)
  {
7088
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
7089
    DBUG_RETURN(TRUE);
7090 7091 7092 7093 7094
  }
  /*
    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
7095
  for (table= tables; table; table= table->next_local)
7096
  {
7097 7098 7099
    if (table->derived)
      table->grant.privilege= SELECT_ACL;
    else if ((check_access(thd, UPDATE_ACL, table->db,
7100 7101
                           &table->grant.privilege, 0, 1,
                           test(table->schema_table)) ||
7102
              check_grant(thd, UPDATE_ACL, table, 0, 1, 1)) &&
unknown's avatar
unknown committed
7103
             (check_access(thd, SELECT_ACL, table->db,
7104 7105
                           &table->grant.privilege, 0, 0,
                           test(table->schema_table)) ||
7106
              check_grant(thd, SELECT_ACL, table, 0, 1, 0)))
unknown's avatar
unknown committed
7107
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7108

unknown's avatar
VIEW  
unknown committed
7109
    table->table_in_first_from_clause= 1;
7110
  }
unknown's avatar
unknown committed
7111 7112 7113
  /*
    Is there tables of subqueries?
  */
7114
  if (&lex->select_lex != lex->all_selects_list)
7115
  {
7116
    DBUG_PRINT("info",("Checking sub query list"));
unknown's avatar
VIEW  
unknown committed
7117
    for (table= tables; table; table= table->next_global)
7118
    {
7119
      if (!table->table_in_first_from_clause)
7120 7121
      {
	if (check_access(thd, SELECT_ACL, table->db,
7122 7123
			 &table->grant.privilege, 0, 0,
                         test(table->schema_table)) ||
7124
	    check_grant(thd, SELECT_ACL, table, 0, 1, 0))
unknown's avatar
unknown committed
7125
	  DBUG_RETURN(TRUE);
7126 7127 7128 7129 7130 7131
      }
    }
  }

  if (select_lex->order_list.elements)
    msg= "ORDER BY";
7132
  else if (select_lex->select_limit)
7133 7134 7135 7136
    msg= "LIMIT";
  if (msg)
  {
    my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
unknown's avatar
unknown committed
7137
    DBUG_RETURN(TRUE);
7138
  }
unknown's avatar
unknown committed
7139
  DBUG_RETURN(FALSE);
7140 7141
}

unknown's avatar
unknown committed
7142 7143
/**
  Multi delete query pre-check.
7144

unknown's avatar
unknown committed
7145 7146
  @param thd			Thread handler
  @param tables		Global/local table list
7147

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

7154
bool multi_delete_precheck(THD *thd, TABLE_LIST *tables)
7155 7156 7157
{
  SELECT_LEX *select_lex= &thd->lex->select_lex;
  TABLE_LIST *aux_tables=
unknown's avatar
unknown committed
7158
    (TABLE_LIST *)thd->lex->auxiliary_table_list.first;
7159
  TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
unknown's avatar
VIEW  
unknown committed
7160
  DBUG_ENTER("multi_delete_precheck");
unknown's avatar
unknown committed
7161

7162 7163
  /* sql_yacc guarantees that tables and aux_tables are not zero */
  DBUG_ASSERT(aux_tables != 0);
7164
  if (check_table_access(thd, SELECT_ACL, tables, UINT_MAX, FALSE))
7165 7166 7167 7168 7169 7170 7171 7172
    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;
7173
  if (check_table_access(thd, DELETE_ACL, aux_tables, UINT_MAX, FALSE))
7174 7175
  {
    thd->lex->query_tables_own_last= save_query_tables_own_last;
unknown's avatar
unknown committed
7176
    DBUG_RETURN(TRUE);
7177 7178 7179
  }
  thd->lex->query_tables_own_last= save_query_tables_own_last;

7180 7181
  if ((thd->options & OPTION_SAFE_UPDATES) && !select_lex->where)
  {
unknown's avatar
unknown committed
7182 7183
    my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
               ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
unknown's avatar
unknown committed
7184
    DBUG_RETURN(TRUE);
7185
  }
7186 7187 7188 7189
  DBUG_RETURN(FALSE);
}


unknown's avatar
unknown committed
7190
/**
7191 7192 7193
  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
7194
  @param lex   pointer to LEX representing multi-delete
7195

unknown's avatar
unknown committed
7196 7197 7198 7199
  @retval
    FALSE   success
  @retval
    TRUE    error
7200 7201 7202 7203 7204 7205 7206 7207 7208 7209
*/

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
7210
  for (target_tbl= (TABLE_LIST *)lex->auxiliary_table_list.first;
7211
       target_tbl; target_tbl= target_tbl->next_local)
7212
  {
7213
    lex->table_count++;
7214 7215
    /* All tables in aux_tables must be found in FROM PART */
    TABLE_LIST *walk;
unknown's avatar
VIEW  
unknown committed
7216
    for (walk= tables; walk; walk= walk->next_local)
7217
    {
unknown's avatar
unknown committed
7218 7219 7220
      if (!my_strcasecmp(table_alias_charset,
			 target_tbl->alias, walk->alias) &&
	  !strcmp(walk->db, target_tbl->db))
7221 7222 7223 7224
	break;
    }
    if (!walk)
    {
7225
      my_error(ER_UNKNOWN_TABLE, MYF(0),
7226
               target_tbl->table_name, "MULTI DELETE");
unknown's avatar
unknown committed
7227
      DBUG_RETURN(TRUE);
7228
    }
unknown's avatar
unknown committed
7229 7230 7231 7232 7233
    if (!walk->derived)
    {
      target_tbl->table_name= walk->table_name;
      target_tbl->table_name_length= walk->table_name_length;
    }
unknown's avatar
unknown committed
7234
    walk->updating= target_tbl->updating;
unknown's avatar
unknown committed
7235
    walk->lock_type= target_tbl->lock_type;
unknown's avatar
VIEW  
unknown committed
7236
    target_tbl->correspondent_table= walk;	// Remember corresponding table
7237
  }
unknown's avatar
unknown committed
7238
  DBUG_RETURN(FALSE);
7239 7240 7241
}


unknown's avatar
unknown committed
7242 7243
/**
  simple UPDATE query pre-check.
unknown's avatar
unknown committed
7244

unknown's avatar
unknown committed
7245 7246
  @param thd		Thread handler
  @param tables	Global table list
unknown's avatar
unknown committed
7247

unknown's avatar
unknown committed
7248
  @retval
unknown's avatar
unknown committed
7249
    FALSE OK
unknown's avatar
unknown committed
7250
  @retval
unknown's avatar
unknown committed
7251
    TRUE  Error
unknown's avatar
unknown committed
7252
*/
unknown's avatar
unknown committed
7253

unknown's avatar
unknown committed
7254
bool update_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
7255 7256 7257 7258
{
  DBUG_ENTER("update_precheck");
  if (thd->lex->select_lex.item_list.elements != thd->lex->value_list.elements)
  {
unknown's avatar
unknown committed
7259
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
7260
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7261
  }
unknown's avatar
unknown committed
7262
  DBUG_RETURN(check_one_table_access(thd, UPDATE_ACL, tables));
unknown's avatar
unknown committed
7263 7264 7265
}


unknown's avatar
unknown committed
7266 7267
/**
  simple DELETE query pre-check.
unknown's avatar
unknown committed
7268

unknown's avatar
unknown committed
7269 7270
  @param thd		Thread handler
  @param tables	Global table list
unknown's avatar
unknown committed
7271

unknown's avatar
unknown committed
7272
  @retval
unknown's avatar
unknown committed
7273
    FALSE  OK
unknown's avatar
unknown committed
7274
  @retval
unknown's avatar
unknown committed
7275
    TRUE   error
unknown's avatar
unknown committed
7276
*/
unknown's avatar
unknown committed
7277

unknown's avatar
unknown committed
7278
bool delete_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
7279 7280 7281
{
  DBUG_ENTER("delete_precheck");
  if (check_one_table_access(thd, DELETE_ACL, tables))
unknown's avatar
unknown committed
7282
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7283
  /* Set privilege for the WHERE clause */
unknown's avatar
unknown committed
7284
  tables->grant.want_privilege=(SELECT_ACL & ~tables->grant.privilege);
unknown's avatar
unknown committed
7285
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
7286 7287 7288
}


unknown's avatar
unknown committed
7289 7290
/**
  simple INSERT query pre-check.
unknown's avatar
unknown committed
7291

unknown's avatar
unknown committed
7292 7293
  @param thd		Thread handler
  @param tables	Global table list
unknown's avatar
unknown committed
7294

unknown's avatar
unknown committed
7295
  @retval
unknown's avatar
unknown committed
7296
    FALSE  OK
unknown's avatar
unknown committed
7297
  @retval
unknown's avatar
unknown committed
7298
    TRUE   error
unknown's avatar
unknown committed
7299
*/
unknown's avatar
unknown committed
7300

unknown's avatar
merge  
unknown committed
7301
bool insert_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
7302 7303 7304 7305
{
  LEX *lex= thd->lex;
  DBUG_ENTER("insert_precheck");

unknown's avatar
unknown committed
7306 7307 7308 7309
  /*
    Check that we have modify privileges for the first table and
    select privileges for the rest
  */
unknown's avatar
unknown committed
7310 7311 7312
  ulong privilege= (INSERT_ACL |
                    (lex->duplicates == DUP_REPLACE ? DELETE_ACL : 0) |
                    (lex->value_list.elements ? UPDATE_ACL : 0));
unknown's avatar
unknown committed
7313 7314

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

unknown's avatar
unknown committed
7317
  if (lex->update_list.elements != lex->value_list.elements)
unknown's avatar
unknown committed
7318
  {
unknown's avatar
unknown committed
7319
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
7320
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7321
  }
unknown's avatar
unknown committed
7322
  DBUG_RETURN(FALSE);
7323
}
unknown's avatar
unknown committed
7324 7325


unknown's avatar
unknown committed
7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340
/**
    @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)) ||
7341
         check_grant(thd, SELECT_ACL, table, 2, UINT_MAX, 0);
unknown's avatar
unknown committed
7342 7343 7344
}


unknown's avatar
unknown committed
7345 7346
/**
  CREATE TABLE query pre-check.
unknown's avatar
unknown committed
7347

unknown's avatar
unknown committed
7348 7349 7350
  @param thd			Thread handler
  @param tables		Global table list
  @param create_table	        Table which will be created
unknown's avatar
unknown committed
7351

unknown's avatar
unknown committed
7352
  @retval
unknown's avatar
unknown committed
7353
    FALSE   OK
unknown's avatar
unknown committed
7354
  @retval
unknown's avatar
unknown committed
7355
    TRUE   Error
unknown's avatar
unknown committed
7356
*/
unknown's avatar
unknown committed
7357

unknown's avatar
unknown committed
7358 7359
bool create_table_precheck(THD *thd, TABLE_LIST *tables,
                           TABLE_LIST *create_table)
unknown's avatar
unknown committed
7360 7361
{
  LEX *lex= thd->lex;
7362 7363
  SELECT_LEX *select_lex= &lex->select_lex;
  ulong want_priv;
unknown's avatar
merge  
unknown committed
7364
  bool error= TRUE;                                 // Error message is given
unknown's avatar
unknown committed
7365
  DBUG_ENTER("create_table_precheck");
7366

7367 7368 7369 7370 7371
  /*
    Require CREATE [TEMPORARY] privilege on new table; for
    CREATE TABLE ... SELECT, also require INSERT.
  */

7372
  want_priv= ((lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) ?
7373 7374 7375
              CREATE_TMP_ACL : CREATE_ACL) |
             (select_lex->item_list.elements ? INSERT_ACL : 0);

unknown's avatar
unknown committed
7376
  if (check_access(thd, want_priv, create_table->db,
7377 7378
		   &create_table->grant.privilege, 0, 0,
                   test(create_table->schema_table)) ||
unknown's avatar
unknown committed
7379 7380 7381
      check_merge_table_access(thd, create_table->db,
			       (TABLE_LIST *)
			       lex->create_info.merge_list.first))
7382
    goto err;
7383
  if (want_priv != CREATE_TMP_ACL &&
7384
      check_grant(thd, want_priv, create_table, 0, 1, 0))
7385 7386 7387 7388 7389 7390
    goto err;

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

7391 7392
#ifdef NOT_NECESSARY_TO_CHECK_CREATE_TABLE_EXIST_WHEN_PREPARING_STATEMENT
    /* This code throws an ill error for CREATE TABLE t1 SELECT * FROM t1 */
7393
    /*
7394
      Only do the check for PS, because we on execute we have to check that
unknown's avatar
unknown committed
7395 7396
      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).
7397
    */
unknown's avatar
unknown committed
7398
    if (thd->stmt_arena->is_stmt_prepare_or_first_sp_execute())
7399
    {
unknown's avatar
unknown committed
7400 7401 7402 7403
      /*
        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
7404
          find_table_in_global_list(tables, create_table->db,
7405
                                    create_table->table_name))
unknown's avatar
unknown committed
7406
      {
7407
	error= FALSE;
unknown's avatar
unknown committed
7408 7409 7410
        goto err;
      }
    }
7411
#endif
7412
    if (tables && check_table_access(thd, SELECT_ACL, tables, UINT_MAX, FALSE))
7413 7414
      goto err;
  }
unknown's avatar
unknown committed
7415 7416 7417 7418 7419
  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
7420
  error= FALSE;
7421 7422 7423

err:
  DBUG_RETURN(error);
unknown's avatar
unknown committed
7424
}
unknown's avatar
unknown committed
7425 7426


unknown's avatar
unknown committed
7427 7428
/**
  negate given expression.
unknown's avatar
unknown committed
7429

unknown's avatar
unknown committed
7430 7431
  @param thd  thread handler
  @param expr expression for negation
unknown's avatar
unknown committed
7432

unknown's avatar
unknown committed
7433
  @return
unknown's avatar
unknown committed
7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458
    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);
}
7459

unknown's avatar
unknown committed
7460 7461 7462
/**
  Set the specified definer to the default value, which is the
  current user in the thread.
7463
 
unknown's avatar
unknown committed
7464 7465
  @param[in]  thd       thread handler
  @param[out] definer   definer
7466 7467
*/
 
7468
void get_default_definer(THD *thd, LEX_USER *definer)
7469 7470 7471 7472 7473 7474 7475 7476 7477 7478
{
  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);
}

7479

unknown's avatar
unknown committed
7480
/**
7481
  Create default definer for the specified THD.
7482

unknown's avatar
unknown committed
7483
  @param[in] thd         thread handler
7484

unknown's avatar
unknown committed
7485 7486
  @return
    - On success, return a valid pointer to the created and initialized
7487
    LEX_USER, which contains definer information.
unknown's avatar
unknown committed
7488
    - On error, return 0.
7489 7490 7491 7492 7493 7494 7495 7496 7497
*/

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

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

7498
  get_default_definer(thd, definer);
7499 7500 7501 7502 7503

  return definer;
}


unknown's avatar
unknown committed
7504
/**
7505
  Create definer with the given user and host names.
7506

unknown's avatar
unknown committed
7507 7508 7509
  @param[in] thd          thread handler
  @param[in] user_name    user name
  @param[in] host_name    host name
7510

unknown's avatar
unknown committed
7511 7512
  @return
    - On success, return a valid pointer to the created and initialized
7513
    LEX_USER, which contains definer information.
unknown's avatar
unknown committed
7514
    - On error, return 0.
7515 7516
*/

7517
LEX_USER *create_definer(THD *thd, LEX_STRING *user_name, LEX_STRING *host_name)
7518
{
7519 7520 7521 7522
  LEX_USER *definer;

  /* Create and initialize. */

unknown's avatar
unknown committed
7523
  if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER))))
7524 7525 7526 7527 7528 7529
    return 0;

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

  return definer;
7530
}
7531 7532


unknown's avatar
unknown committed
7533
/**
7534 7535
  Retuns information about user or current user.

unknown's avatar
unknown committed
7536 7537
  @param[in] thd          thread handler
  @param[in] user         user
7538

unknown's avatar
unknown committed
7539 7540
  @return
    - On success, return a valid pointer to initialized
7541
    LEX_USER, which contains user information.
unknown's avatar
unknown committed
7542
    - On error, return 0.
7543 7544 7545 7546 7547
*/

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

7550 7551
  return user;
}
7552 7553


unknown's avatar
unknown committed
7554
/**
7555
  Check that byte length of a string does not exceed some limit.
7556

unknown's avatar
unknown committed
7557 7558 7559
  @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
7560

unknown's avatar
unknown committed
7561
  @retval
7562
    FALSE   the passed string is not longer than max_length
unknown's avatar
unknown committed
7563
  @retval
7564
    TRUE    the passed string is longer than max_length
7565 7566 7567

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

7570 7571
bool check_string_byte_length(LEX_STRING *str, const char *err_msg,
                              uint max_byte_length)
7572
{
7573
  if (str->length <= max_byte_length)
unknown's avatar
unknown committed
7574
    return FALSE;
7575

7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607
  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
7608

7609 7610
  if (!no_error)
    my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_char_length);
7611 7612
  return TRUE;
}
7613 7614


7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626
/*
  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  
*/
7627
C_MODE_START
7628

7629
int test_if_data_home_dir(const char *dir)
7630
{
7631
  char path[FN_REFLEN];
Alexey Botchkov's avatar
Alexey Botchkov committed
7632
  int dir_len;
7633 7634 7635 7636 7637 7638 7639
  DBUG_ENTER("test_if_data_home_dir");

  if (!dir)
    DBUG_RETURN(0);

  (void) fn_format(path, dir, "", "",
                   (MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS));
7640 7641
  dir_len= strlen(path);
  if (mysql_unpacked_real_data_home_len<= dir_len)
7642
  {
7643 7644 7645 7646
    if (dir_len > mysql_unpacked_real_data_home_len &&
        path[mysql_unpacked_real_data_home_len] != FN_LIBCHAR)
      DBUG_RETURN(0);

7647 7648
    if (lower_case_file_system)
    {
7649 7650
      if (!my_strnncoll(default_charset_info, (const uchar*) path,
                        mysql_unpacked_real_data_home_len,
7651
                        (const uchar*) mysql_unpacked_real_data_home,
7652
                        mysql_unpacked_real_data_home_len))
7653 7654
        DBUG_RETURN(1);
    }
7655 7656
    else if (!memcmp(path, mysql_unpacked_real_data_home,
                     mysql_unpacked_real_data_home_len))
7657 7658 7659 7660 7661
      DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}

7662 7663
C_MODE_END

7664

7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679
/**
  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
7680
  if (check_string_byte_length(str, ER(ER_HOSTNAME), HOSTNAME_LENGTH))
7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695
    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
7696 7697


7698 7699 7700 7701 7702 7703 7704 7705
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.
7706
  @param parser_state Parser state.
unknown's avatar
unknown committed
7707
  @param creation_ctx Object creation context.
7708 7709 7710 7711 7712 7713

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

unknown's avatar
unknown committed
7714
bool parse_sql(THD *thd,
7715
               Parser_state *parser_state,
unknown's avatar
unknown committed
7716
               Object_creation_ctx *creation_ctx)
7717
{
7718
  bool ret_value;
7719
  DBUG_ASSERT(thd->m_parser_state == NULL);
7720

7721
  MYSQL_QUERY_PARSE_START(thd->query);
unknown's avatar
unknown committed
7722 7723 7724 7725 7726 7727 7728
  /* Backup creation context. */

  Object_creation_ctx *backup_ctx= NULL;

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

7729
  /* Set parser state. */
unknown's avatar
unknown committed
7730

7731
  thd->m_parser_state= parser_state;
7732

unknown's avatar
unknown committed
7733 7734
  /* Parse the query. */

7735 7736
  bool mysql_parse_status= MYSQLparse(thd) != 0;

7737
  /* Check that if MYSQLparse() failed, thd->is_error() is set. */
7738 7739

  DBUG_ASSERT(!mysql_parse_status ||
7740
              mysql_parse_status && thd->is_error());
unknown's avatar
unknown committed
7741

7742
  /* Reset parser state. */
7743

7744
  thd->m_parser_state= NULL;
7745

unknown's avatar
unknown committed
7746 7747 7748 7749 7750 7751 7752
  /* Restore creation context. */

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

  /* That's it. */

7753 7754 7755
  ret_value= mysql_parse_status || thd->is_fatal_error;
  MYSQL_QUERY_PARSE_DONE(ret_value);
  return ret_value;
7756
}
7757 7758 7759 7760

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