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

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

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

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

16
#define MYSQL_LEX 1
bk@work.mysql.com's avatar
bk@work.mysql.com committed
17
#include "mysql_priv.h"
18
#include "sql_repl.h"
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
19
#include "rpl_filter.h"
20
#include "repl_failsafe.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
21 22 23
#include <m_ctype.h>
#include <myisam.h>
#include <my_dir.h>
He Zhenxing's avatar
He Zhenxing committed
24
#include "rpl_handler.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
25

26
#include "sp_head.h"
27
#include "sp.h"
28
#include "sp_cache.h"
29
#include "events.h"
30
#include "sql_trigger.h"
31
#include "sql_audit.h"
32
#include "sql_prepare.h"
33
#include "probes_mysql.h"
34
#include "set_var.h"
35

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

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

51
static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
52

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

andrey@example.com's avatar
andrey@example.com committed
55
const LEX_STRING command_name[]={
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  { C_STRING_WITH_LEN("Sleep") },
  { C_STRING_WITH_LEN("Quit") },
  { C_STRING_WITH_LEN("Init DB") },
  { C_STRING_WITH_LEN("Query") },
  { C_STRING_WITH_LEN("Field List") },
  { C_STRING_WITH_LEN("Create DB") },
  { C_STRING_WITH_LEN("Drop DB") },
  { C_STRING_WITH_LEN("Refresh") },
  { C_STRING_WITH_LEN("Shutdown") },
  { C_STRING_WITH_LEN("Statistics") },
  { C_STRING_WITH_LEN("Processlist") },
  { C_STRING_WITH_LEN("Connect") },
  { C_STRING_WITH_LEN("Kill") },
  { C_STRING_WITH_LEN("Debug") },
  { C_STRING_WITH_LEN("Ping") },
  { C_STRING_WITH_LEN("Time") },
  { C_STRING_WITH_LEN("Delayed insert") },
  { C_STRING_WITH_LEN("Change user") },
  { C_STRING_WITH_LEN("Binlog Dump") },
  { C_STRING_WITH_LEN("Table Dump") },
  { C_STRING_WITH_LEN("Connect Out") },
  { C_STRING_WITH_LEN("Register Slave") },
  { C_STRING_WITH_LEN("Prepare") },
  { C_STRING_WITH_LEN("Execute") },
  { C_STRING_WITH_LEN("Long Data") },
  { C_STRING_WITH_LEN("Close stmt") },
  { C_STRING_WITH_LEN("Reset stmt") },
  { C_STRING_WITH_LEN("Set option") },
  { C_STRING_WITH_LEN("Fetch") },
  { C_STRING_WITH_LEN("Daemon") },
  { C_STRING_WITH_LEN("Error") }  // Last command number
bk@work.mysql.com's avatar
bk@work.mysql.com committed
87 88
};

89
const char *xa_state_names[]={
90
  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED", "ROLLBACK ONLY"
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
/**
  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)
{
129 130 131 132 133 134 135 136
  /*
    Resource Manager error is meaningless at this point, as we perform
    explicit rollback request by user. We must reset rm_error before
    calling ha_rollback(), so thd->transaction.xid structure gets reset
    by ha_rollback()/THD::transaction::cleanup().
  */
  thd->transaction.xid_state.rm_error= 0;

137 138
  bool status= test(ha_rollback(thd));

139
  thd->variables.option_bits&= ~(ulong) OPTION_BEGIN;
140 141 142 143 144 145 146 147
  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;

  return status;
}

148 149 150 151 152
static void unlock_locked_tables(THD *thd)
{
  if (thd->locked_tables)
  {
    thd->lock=thd->locked_tables;
153
    thd->locked_tables=0;			// Will be automatically closed
154 155 156 157
    close_thread_tables(thd);			// Free tables
  }
}

158

159
bool end_active_trans(THD *thd)
160
{
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
161
  int error=0;
162
  DBUG_ENTER("end_active_trans");
163
  if (unlikely(thd->in_sub_stmt))
164 165 166 167
  {
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
    DBUG_RETURN(1);
  }
168 169 170 171 172 173
  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);
  }
174
  if (thd->variables.option_bits & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN |
175
		      OPTION_TABLE_LOCK))
176
  {
177
    DBUG_PRINT("info",("options: 0x%llx", thd->variables.option_bits));
178 179
    /* Safety if one did "drop table" on locked tables */
    if (!thd->locked_tables)
180
      thd->variables.option_bits&= ~OPTION_TABLE_LOCK;
181
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
182
    if (ha_commit(thd))
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
183
      error=1;
184
  }
185
  thd->variables.option_bits&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
186
  thd->transaction.all.modified_non_trans_table= FALSE;
187
  DBUG_RETURN(error);
188 189
}

190

cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
191
bool begin_trans(THD *thd)
192 193
{
  int error=0;
194
  if (unlikely(thd->in_sub_stmt))
195 196 197 198
  {
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
    return 1;
  }
199 200 201 202 203 204 205 206 207 208
  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
  {
209
    thd->variables.option_bits|= OPTION_BEGIN;
210 211 212 213
    thd->server_status|= SERVER_STATUS_IN_TRANS;
  }
  return error;
}
214

monty@mysql.com's avatar
monty@mysql.com committed
215
#ifdef HAVE_REPLICATION
216 217
/**
  Returns true if all tables should be ignored.
218
*/
219 220
inline bool all_tables_not_ok(THD *thd, TABLE_LIST *tables)
{
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
221 222
  return rpl_filter->is_on() && tables && !thd->spcont &&
         !rpl_filter->tables_ok(thd->db, tables);
223
}
monty@mysql.com's avatar
monty@mysql.com committed
224
#endif
225 226


227 228 229 230 231 232 233 234 235 236 237 238
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;
}

239

240 241 242 243
/**
  Mark all commands that somehow changes a table.

  This is used to check number of updates / hour.
kent@mysql.com's avatar
kent@mysql.com committed
244 245 246

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

248
  See COMMAND_FLAG_xxx for different type of commands
249 250
     2  - query that returns meaningful ROW_COUNT() -
          a number of modified rows
251 252
*/

253
uint sql_command_flags[SQLCOM_END+1];
254 255 256

void init_update_queries(void)
{
257
  bzero((uchar*) &sql_command_flags, sizeof(sql_command_flags));
258

259
  sql_command_flags[SQLCOM_CREATE_TABLE]=   CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE;
260
  sql_command_flags[SQLCOM_CREATE_INDEX]=   CF_CHANGES_DATA;
261 262
  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;
263
  sql_command_flags[SQLCOM_DROP_TABLE]=     CF_CHANGES_DATA;
264
  sql_command_flags[SQLCOM_LOAD]=           CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE;
265 266 267 268
  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_DROP_INDEX]=     CF_CHANGES_DATA;
269
  sql_command_flags[SQLCOM_CREATE_VIEW]=    CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE;
270 271 272
  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;
273
  sql_command_flags[SQLCOM_DROP_EVENT]=     CF_CHANGES_DATA;
274

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

   sql_command_flags[SQLCOM_SHOW_TABLES]=       (CF_STATUS_COMMAND |
337 338
                                                 CF_SHOW_TABLE_COMMAND |
                                                 CF_REEXECUTION_FRAGILE);
339
  sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND |
340 341
                                                CF_SHOW_TABLE_COMMAND |
                                                CF_REEXECUTION_FRAGILE);
342 343 344 345 346 347 348

  /*
    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.
  */
349
  sql_command_flags[SQLCOM_CALL]= 		CF_HAS_ROW_COUNT | CF_REEXECUTION_FRAGILE;
350
  sql_command_flags[SQLCOM_EXECUTE]= 		CF_HAS_ROW_COUNT;
351 352 353 354 355 356 357 358

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

361

362 363
bool is_update_query(enum enum_sql_command command)
{
kent@mysql.com's avatar
kent@mysql.com committed
364
  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
365
  return (sql_command_flags[command] & CF_CHANGES_DATA) != 0;
366
}
367

368 369 370 371 372 373 374 375 376 377
/**
  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;
}
378

379
void execute_init_command(THD *thd, LEX_STRING *init_command,
Marc Alff's avatar
Marc Alff committed
380
                          mysql_rwlock_t *var_lock)
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
381 382 383 384
{
  Vio* save_vio;
  ulong save_client_capabilities;

Marc Alff's avatar
Marc Alff committed
385
  mysql_rwlock_rdlock(var_lock);
386 387
  if (!init_command->length)
  {
Marc Alff's avatar
Marc Alff committed
388
    mysql_rwlock_unlock(var_lock);
389 390 391 392 393 394 395 396 397 398
    return;
  }

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

401
#if defined(ENABLED_PROFILING)
402
  thd->profiling.start_new_query();
403
  thd->profiling.set_query_source(buf, len);
404 405
#endif

406
  thd_proc_info(thd, "Execution of init_command");
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
407 408
  save_client_capabilities= thd->client_capabilities;
  thd->client_capabilities|= CLIENT_MULTI_QUERIES;
409 410 411 412
  /*
    We don't need return result of execution to client side.
    To forbid this we should set thd->net.vio to 0.
  */
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
413 414
  save_vio= thd->net.vio;
  thd->net.vio= 0;
415
  dispatch_command(COM_QUERY, thd, buf, len);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
416 417
  thd->client_capabilities= save_client_capabilities;
  thd->net.vio= save_vio;
418

419
#if defined(ENABLED_PROFILING)
420 421
  thd->profiling.finish_current_query();
#endif
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
422 423 424
}


425
static void handle_bootstrap_impl(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
426
{
Marc Alff's avatar
Marc Alff committed
427
  MYSQL_FILE *file= bootstrap_file;
428
  char *buff;
429
  const char* found_semicolon= NULL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
430

431 432
  DBUG_ENTER("handle_bootstrap");

hf@deer.(none)'s avatar
hf@deer.(none) committed
433
#ifndef EMBEDDED_LIBRARY
434 435
  pthread_detach_this_thread();
  thd->thread_stack= (char*) &thd;
hf@deer.(none)'s avatar
hf@deer.(none) committed
436
#endif /* EMBEDDED_LIBRARY */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
437

438
  thd_proc_info(thd, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
439
  thd->version=refresh_version;
440 441
  thd->security_ctx->priv_user=
    thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME));
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
442
  thd->security_ctx->priv_host[0]=0;
443 444 445 446 447 448
  /*
    Make the "client" handle multiple results. This is necessary
    to enable stored procedures with SELECTs and Dynamic SQL
    in init-file.
  */
  thd->client_capabilities|= CLIENT_MULTI_RESULTS;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
449

450
  buff= (char*) thd->net.buff;
451
  thd->init_for_queries();
Marc Alff's avatar
Marc Alff committed
452
  while (mysql_file_fgets(buff, thd->net.max_packet, file))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
453
  {
Marc Alff's avatar
Marc Alff committed
454 455
    char *query;
    /* strlen() can't be deleted because mysql_file_fgets() doesn't return length */
456
    ulong length= (ulong) strlen(buff);
Marc Alff's avatar
Marc Alff committed
457
    while (buff[length-1] != '\n' && !mysql_file_feof(file))
458 459 460 461 462 463 464 465
    {
      /*
        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))
      {
466
        thd->protocol->end_statement();
467
        bootstrap_error= 1;
468 469 470
        break;
      }
      buff= (char*) thd->net.buff;
Marc Alff's avatar
Marc Alff committed
471
      mysql_file_fgets(buff + length, thd->net.max_packet - length, file);
472 473 474
      length+= (ulong) strlen(buff + length);
      /* purecov: end */
    }
475
    if (bootstrap_error)
476
      break;                                    /* purecov: inspected */
monty@mishka.local's avatar
monty@mishka.local committed
477

478
    while (length && (my_isspace(thd->charset(), buff[length-1]) ||
479
                      buff[length-1] == ';'))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
480 481
      length--;
    buff[length]=0;
482 483 484 485 486

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

Gleb Shchepa's avatar
Gleb Shchepa committed
487 488 489
    query= (char *) thd->memdup_w_gap(buff, length + 1,
                                      thd->db_length + 1 +
                                      QUERY_CACHE_FLAGS_SIZE);
490
    thd->set_query_and_id(query, length, next_query_id());
491
    DBUG_PRINT("query",("%-.4096s",thd->query()));
492
#if defined(ENABLED_PROFILING)
493
    thd->profiling.start_new_query();
494
    thd->profiling.set_query_source(thd->query(), length);
495 496
#endif

497 498 499 500
    /*
      We don't need to obtain LOCK_thread_count here because in bootstrap
      mode we have only one thread.
    */
501
    thd->set_time();
502
    mysql_parse(thd, thd->query(), length, & found_semicolon);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
503
    close_thread_tables(thd);			// Free tables
504

505
    bootstrap_error= thd->is_error();
506
    thd->protocol->end_statement();
507

508
#if defined(ENABLED_PROFILING)
509 510 511
    thd->profiling.finish_current_query();
#endif

512
    if (bootstrap_error)
513 514
      break;

515
    free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
516
    free_root(&thd->transaction.mem_root,MYF(MY_KEEP_PREALLOC));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
517
  }
518

519 520 521 522 523 524 525 526 527 528 529 530 531 532
  DBUG_VOID_RETURN;
}


/**
  Execute commands from bootstrap_file.

  Used when creating the initial grant tables.
*/

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

Marc Alff's avatar
Marc Alff committed
533 534 535 536 537 538 539 540
  mysql_thread_set_psi_id(thd->thread_id);

  do_handle_bootstrap(thd);
  return 0;
}

void do_handle_bootstrap(THD *thd)
{
541 542 543 544 545 546 547 548 549 550 551 552 553
  /* The following must be called before DBUG_ENTER */
  thd->thread_stack= (char*) &thd;
  if (my_thread_init() || thd->store_globals())
  {
#ifndef EMBEDDED_LIBRARY
    close_connection(thd, ER_OUT_OF_RESOURCES, 1);
#endif
    thd->fatal_error();
    goto end;
  }

  handle_bootstrap_impl(thd);

554
end:
555 556 557 558
  net_end(&thd->net);
  thd->cleanup();
  delete thd;

hf@deer.(none)'s avatar
hf@deer.(none) committed
559
#ifndef EMBEDDED_LIBRARY
Marc Alff's avatar
Marc Alff committed
560
  mysql_mutex_lock(&LOCK_thread_count);
561
  thread_count--;
562
  in_bootstrap= FALSE;
Marc Alff's avatar
Marc Alff committed
563 564
  mysql_cond_broadcast(&COND_thread_count);
  mysql_mutex_unlock(&LOCK_thread_count);
565 566
  my_thread_end();
  pthread_exit(0);
hf@deer.(none)'s avatar
hf@deer.(none) committed
567
#endif
568

Marc Alff's avatar
Marc Alff committed
569
  return;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
570 571 572
}


573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
/**
  @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.
*/
590
#ifndef NO_EMBEDDED_ACCESS_CHECKS
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
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,
607
                              table_list, FALSE, UINT_MAX, FALSE);
608 609 610
  }
  return error;
}
611
#endif
612

613 614 615 616 617 618 619 620 621 622 623 624 625 626
/* 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;
}

627 628 629 630
/**
   This works because items are allocated with sql_alloc().
   @note The function also handles null pointers (empty list).
*/
631 632
void cleanup_items(Item *item)
{
monty@mysql.com's avatar
monty@mysql.com committed
633
  DBUG_ENTER("cleanup_items");  
634 635
  for (; item ; item=item->next)
    item->cleanup();
monty@mysql.com's avatar
monty@mysql.com committed
636
  DBUG_VOID_RETURN;
637 638
}

639 640
/**
  Ends the current transaction and (maybe) begin the next.
641

642 643
  @param thd            Current thread
  @param completion     Completion type
644

645 646
  @retval
    0   OK
647 648
*/

649
int end_trans(THD *thd, enum enum_mysql_completiontype completion)
650 651 652
{
  bool do_release= 0;
  int res= 0;
653
  DBUG_ENTER("end_trans");
654

655
  if (unlikely(thd->in_sub_stmt))
656 657 658 659
  {
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
    DBUG_RETURN(1);
  }
660 661 662 663 664 665
  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);
  }
666 667 668 669 670 671 672 673
  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;
674
    res= ha_commit(thd);
675
    thd->variables.option_bits&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
676
    thd->transaction.all.modified_non_trans_table= FALSE;
677 678
    break;
  case COMMIT_RELEASE:
serg@serg.mylan's avatar
serg@serg.mylan committed
679
    do_release= 1; /* fall through */
680 681 682 683 684 685
  case COMMIT_AND_CHAIN:
    res= end_active_trans(thd);
    if (!res && completion == COMMIT_AND_CHAIN)
      res= begin_trans(thd);
    break;
  case ROLLBACK_RELEASE:
serg@serg.mylan's avatar
serg@serg.mylan committed
686
    do_release= 1; /* fall through */
687 688 689 690
  case ROLLBACK:
  case ROLLBACK_AND_CHAIN:
  {
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
serg@serg.mylan's avatar
serg@serg.mylan committed
691
    if (ha_rollback(thd))
692
      res= -1;
693
    thd->variables.option_bits&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
694
    thd->transaction.all.modified_non_trans_table= FALSE;
695 696 697 698 699 700 701 702 703
    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);
  }
serg@serg.mylan's avatar
serg@serg.mylan committed
704

705 706 707
  if (res < 0)
    my_error(thd->killed_errno(), MYF(0));
  else if ((res == 0) && do_release)
serg@serg.mylan's avatar
serg@serg.mylan committed
708 709
    thd->killed= THD::KILL_CONNECTION;

710 711
  DBUG_RETURN(res);
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
712

713
#ifndef EMBEDDED_LIBRARY
714

715
/**
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
716
  Read one command from connection and execute it (query or simple command).
717
  This function is called in loop from thread function.
718 719 720

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

721
  @retval
722
    0  success
723
  @retval
724 725 726
    1  request of thread shutdown (see dispatch_command() description)
*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
727 728
bool do_command(THD *thd)
{
729
  bool return_value;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
730
  char *packet= 0;
731
  ulong packet_length;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
732
  NET *net= &thd->net;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
733 734 735
  enum enum_server_command command;
  DBUG_ENTER("do_command");

736 737 738 739
  /*
    indicator of uninitialized lex => normal flow of errors handling
    (see my_message_sql)
  */
740
  thd->lex->current_select= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
741

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
742 743 744 745
  /*
    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"
746
    number of seconds has passed.
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
747
  */
748
  my_net_set_read_timeout(net, thd->variables.net_wait_timeout);
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
749

750 751 752 753
  /*
    XXX: this code is here only to clear possible errors of init_connect. 
    Consider moving to init_connect() instead.
  */
754
  thd->clear_error();				// Clear error message
Marc Alff's avatar
Marc Alff committed
755
  thd->stmt_da->reset_diagnostics_area();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
756 757

  net_new_transaction(net);
758

Konstantin Osipov's avatar
Konstantin Osipov committed
759
  if ((packet_length= my_net_read(net)) == packet_error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
760
  {
761 762 763
    DBUG_PRINT("info",("Got error %d reading command from socket %s",
		       net->error,
		       vio_description(net->vio)));
764

765
    /* Check if we can continue without closing the connection */
766

767 768
    /* The error must be set. */
    DBUG_ASSERT(thd->is_error());
769
    thd->protocol->end_statement();
770

771
    if (net->error != 3)
772
    {
773
      return_value= TRUE;                       // We have to close it.
774 775
      goto out;
    }
776

777
    net->error= 0;
778 779
    return_value= FALSE;
    goto out;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
780
  }
781 782 783 784 785 786 787 788 789 790 791

  packet= (char*) net->read_pos;
  /*
    'packet_length' contains length of data, as it was stored in packet
    header. In case of malformed header, my_net_read returns zero.
    If packet_length is not zero, my_net_read ensures that the returned
    number of bytes was actually read from network.
    There is also an extra safety measure in my_net_read:
    it sets packet[packet_length]= 0, but only for non-zero packets.
  */
  if (packet_length == 0)                       /* safety */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
792
  {
793 794 795
    /* Initialize with COM_SLEEP packet */
    packet[0]= (uchar) COM_SLEEP;
    packet_length= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
796
  }
797 798 799 800 801 802 803 804 805 806 807
  /* Do not rely on my_net_read, extra safety against programming errors. */
  packet[packet_length]= '\0';                  /* safety */

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

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

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

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

812
  DBUG_ASSERT(packet_length);
813 814 815 816
  return_value= dispatch_command(command, thd, packet+1, (uint) (packet_length-1));

out:
  DBUG_RETURN(return_value);
817
}
818
#endif  /* EMBEDDED_LIBRARY */
819

820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
/**
  @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);

851
  if (!(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA))
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
    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);
}
887

888 889
/**
  Perform one connection-level (COM_XXXX) command.
890

891 892 893 894 895 896 897 898
  @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
899 900 901
    set thd->lex->sql_command to SQLCOM_END here.
  @todo
    The following has to be changed to an 8 byte integer
902 903

  @retval
904
    0   ok
905
  @retval
906 907 908
    1   request of thread shutdown, i. e. if command is
        COM_QUIT/COM_SHUTDOWN
*/
909 910 911 912
bool dispatch_command(enum enum_server_command command, THD *thd,
		      char* packet, uint packet_length)
{
  NET *net= &thd->net;
913
  bool error= 0;
914
  DBUG_ENTER("dispatch_command");
915
  DBUG_PRINT("info",("packet: '%*.s'; command: %d", packet_length, packet, command));
916

Konstantin Osipov's avatar
Konstantin Osipov committed
917 918 919
#if defined(ENABLED_PROFILING)
  thd->profiling.start_new_query();
#endif
920 921 922 923
  MYSQL_COMMAND_START(thd->thread_id, command,
                      thd->security_ctx->priv_user,
                      (char *) thd->security_ctx->host_or_ip);
  
924
  thd->command=command;
925
  /*
926 927
    Commands which always take a long time are logged into
    the slow log only if opt_log_slow_admin_statements is set.
928
  */
929
  thd->enable_slow_log= TRUE;
930
  thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
931
  thd->set_time();
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
  {
    query_id_t query_id;
    switch( command ) {
    /* Ignore these statements. */
    case COM_STATISTICS:
    case COM_PING:
      query_id= get_query_id();
      break;
    /* Only increase id on these statements but don't count them. */
    case COM_STMT_PREPARE: 
    case COM_STMT_CLOSE:
    case COM_STMT_RESET:
      query_id= next_query_id() - 1;
      break;
    /* Increase id and count all other statements. */
    default:
      statistic_increment(thd->status_var.questions, &LOCK_status);
      query_id= next_query_id() - 1;
    }
951
    thd->set_query_id(query_id);
952
  }
953
  inc_thread_running();
954
  /* TODO: set thd->lex->sql_command to SQLCOM_END here */
955

956 957 958 959 960
  /**
    Clear the set of flags that are expected to be cleared at the
    beginning of each command.
  */
  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
961
  switch (command) {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
962
  case COM_INIT_DB:
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
963 964
  {
    LEX_STRING tmp;
965
    status_var_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB]);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
966
    thd->convert_string(&tmp, system_charset_info,
967
			packet, packet_length, thd->charset());
968
    if (!mysql_change_db(thd, &tmp, FALSE))
969
    {
970
      general_log_write(thd, command, thd->db, thd->db_length);
971
      my_ok(thd);
972
    }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
973 974
    break;
  }
975
#ifdef HAVE_REPLICATION
976 977
  case COM_REGISTER_SLAVE:
  {
978
    if (!register_slave(thd, (uchar*)packet, packet_length))
979
      my_ok(thd);
980 981
    break;
  }
982
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
983 984
  case COM_CHANGE_USER:
  {
985
    status_var_increment(thd->status_var.com_other);
986 987
    char *user= (char*) packet, *packet_end= packet + packet_length;
    /* Safe because there is always a trailing \0 at the end of the packet */
988 989
    char *passwd= strend(user)+1;

990
    thd->change_user();
991
    thd->clear_error();                         // if errors from rollback
992

993
    /*
994 995 996
      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).
997 998 999

      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.
1000
    */
1001
    char db_buff[NAME_LEN+1];                 // buffer to store db in utf8
1002
    char *db= passwd;
1003
    char *save_db;
1004 1005 1006 1007 1008 1009 1010 1011 1012
    /*
      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;
    }
1013
    uint passwd_len= (thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
1014
                      (uchar)(*passwd++) : strlen(passwd));
1015 1016
    uint dummy_errors, save_db_length, db_length;
    int res;
1017 1018 1019
    Security_context save_security_ctx= *thd->security_ctx;
    USER_CONN *save_user_connect;

1020
    db+= passwd_len + 1;
1021 1022 1023 1024 1025
    /*
      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)
1026
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1027
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1028 1029
      break;
    }
1030 1031
    db_length= strlen(db);

1032
    char *ptr= db + db_length + 1;
1033 1034
    uint cs_number= 0;

1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    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);
    }
1045

1046
    /* Convert database name to utf8 */
1047
    db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
1048
                             system_charset_info, db, db_length,
1049
                             thd->charset(), &dummy_errors)]= 0;
1050
    db= db_buff;
peter@mysql.com's avatar
peter@mysql.com committed
1051

1052
    /* Save user and privileges */
1053 1054 1055
    save_db_length= thd->db_length;
    save_db= thd->db;
    save_user_connect= thd->user_connect;
1056 1057

    if (!(thd->security_ctx->user= my_strdup(user, MYF(0))))
1058
    {
1059
      thd->security_ctx->user= save_security_ctx.user;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1060
      my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
1061 1062
      break;
    }
peter@mysql.com's avatar
peter@mysql.com committed
1063

1064 1065
    /* Clear variables that are allocated */
    thd->user_connect= 0;
1066
    thd->security_ctx->priv_user= thd->security_ctx->user;
1067
    res= check_user(thd, COM_CHANGE_USER, passwd, passwd_len, db, FALSE);
peter@mysql.com's avatar
peter@mysql.com committed
1068

1069 1070
    if (res)
    {
1071 1072
      x_free(thd->security_ctx->user);
      *thd->security_ctx= save_security_ctx;
1073
      thd->user_connect= save_user_connect;
1074 1075 1076 1077 1078
      thd->db= save_db;
      thd->db_length= save_db_length;
    }
    else
    {
1079
#ifndef NO_EMBEDDED_ACCESS_CHECKS
1080
      /* we've authenticated new user */
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1081 1082
      if (save_user_connect)
	decrease_user_connections(save_user_connect);
1083
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
1084 1085
      x_free(save_db);
      x_free(save_security_ctx.user);
1086 1087 1088 1089 1090 1091

      if (cs_number)
      {
        thd_init_client_charset(thd, cs_number);
        thd->update_charset();
      }
1092
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1093 1094
    break;
  }
1095
  case COM_STMT_EXECUTE:
1096
  {
1097
    mysqld_stmt_execute(thd, packet, packet_length);
1098 1099
    break;
  }
1100
  case COM_STMT_FETCH:
1101
  {
1102
    mysqld_stmt_fetch(thd, packet, packet_length);
1103 1104
    break;
  }
1105
  case COM_STMT_SEND_LONG_DATA:
1106
  {
1107
    mysql_stmt_get_longdata(thd, packet, packet_length);
1108 1109
    break;
  }
1110
  case COM_STMT_PREPARE:
1111
  {
1112
    mysqld_stmt_prepare(thd, packet, packet_length);
1113 1114
    break;
  }
1115
  case COM_STMT_CLOSE:
1116
  {
1117
    mysqld_stmt_close(thd, packet);
1118 1119
    break;
  }
1120
  case COM_STMT_RESET:
1121
  {
1122
    mysqld_stmt_reset(thd, packet);
1123 1124
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1125 1126
  case COM_QUERY:
  {
1127 1128
    if (alloc_query(thd, packet, packet_length))
      break;					// fatal error is set
1129
    MYSQL_QUERY_START(thd->query(), thd->thread_id,
1130 1131 1132
                      (char *) (thd->db ? thd->db : ""),
                      thd->security_ctx->priv_user,
                      (char *) thd->security_ctx->host_or_ip);
1133
    char *packet_end= thd->query() + thd->query_length();
1134
    /* 'b' stands for 'buffer' parameter', special for 'my_snprintf' */
1135
    const char* end_of_stmt= NULL;
1136

1137 1138
    general_log_write(thd, command, thd->query(), thd->query_length());
    DBUG_PRINT("query",("%-.4096s",thd->query()));
1139
#if defined(ENABLED_PROFILING)
1140
    thd->profiling.set_query_source(thd->query(), thd->query_length());
1141
#endif
1142

1143
    mysql_parse(thd, thd->query(), thd->query_length(), &end_of_stmt);
1144

1145
    while (!thd->killed && (end_of_stmt != NULL) && ! thd->is_error())
1146
    {
1147
      char *beginning_of_next_stmt= (char*) end_of_stmt;
1148

1149
      thd->protocol->end_statement();
1150
      query_cache_end_of_result(thd);
1151
      /*
1152 1153
        Multiple queries exits, execute them individually
      */
1154
      close_thread_tables(thd);
1155
      ulong length= (ulong)(packet_end - beginning_of_next_stmt);
1156

1157
      log_slow_statement(thd);
1158

1159
      /* Remove garbage at start of query */
1160
      while (length > 0 && my_isspace(thd->charset(), *beginning_of_next_stmt))
1161
      {
1162
        beginning_of_next_stmt++;
1163 1164
        length--;
      }
1165

1166 1167 1168 1169 1170
      if (MYSQL_QUERY_DONE_ENABLED())
      {
        MYSQL_QUERY_DONE(thd->is_error());
      }

1171
#if defined(ENABLED_PROFILING)
1172 1173 1174 1175 1176
      thd->profiling.finish_current_query();
      thd->profiling.start_new_query("continuing");
      thd->profiling.set_query_source(beginning_of_next_stmt, length);
#endif

1177
      MYSQL_QUERY_START(beginning_of_next_stmt, thd->thread_id,
1178 1179 1180 1181
                        (char *) (thd->db ? thd->db : ""),
                        thd->security_ctx->priv_user,
                        (char *) thd->security_ctx->host_or_ip);

1182
      thd->set_query_and_id(beginning_of_next_stmt, length, next_query_id());
1183 1184 1185 1186
      /*
        Count each statement from the client.
      */
      statistic_increment(thd->status_var.questions, &LOCK_status);
1187
      thd->set_time(); /* Reset the query start time. */
1188
      /* TODO: set thd->lex->sql_command to SQLCOM_END here */
1189
      mysql_parse(thd, beginning_of_next_stmt, length, &end_of_stmt);
1190 1191
    }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1192 1193 1194
    DBUG_PRINT("info",("query ready"));
    break;
  }
1195
  case COM_FIELD_LIST:				// This isn't actually needed
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1196
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1197 1198
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1199 1200 1201
    break;
#else
  {
1202
    char *fields, *packet_end= packet + packet_length, *arg_end;
1203
    /* Locked closure of all tables */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1204
    TABLE_LIST table_list;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1205
    LEX_STRING conv_name;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1206

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1207
    /* used as fields initializator */
1208
    lex_start(thd);
1209

1210
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1211
    bzero((char*) &table_list,sizeof(table_list));
1212
    if (thd->copy_db_to(&table_list.db, &table_list.db_length))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1213
      break;
1214 1215 1216 1217
    /*
      We have name + wildcard in packet, separated by endzero
    */
    arg_end= strend(packet);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1218
    thd->convert_string(&conv_name, system_charset_info,
1219
			packet, (uint) (arg_end - packet), thd->charset());
1220
    table_list.alias= table_list.table_name= conv_name.str;
1221
    packet= arg_end + 1;
1222

1223
    if (is_infoschema_db(table_list.db, table_list.db_length))
1224 1225 1226 1227 1228 1229
    {
      ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, table_list.alias);
      if (schema_table)
        table_list.schema_table= schema_table;
    }

Gleb Shchepa's avatar
Gleb Shchepa committed
1230 1231
    uint query_length= (uint) (packet_end - packet); // Don't count end \0
    if (!(fields= (char *) thd->memdup(packet, query_length + 1)))
1232
      break;
1233
    thd->set_query(fields, query_length);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1234
    general_log_print(thd, command, "%s %s", table_list.table_name, fields);
1235
    if (lower_case_table_names)
1236
      my_casedn_str(files_charset_info, table_list.table_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1237

Marc Alff's avatar
Marc Alff committed
1238 1239 1240 1241
    if (check_access(thd, SELECT_ACL, table_list.db,
                     &table_list.grant.privilege,
                     &table_list.grant.m_internal,
                     0, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1242
      break;
1243
    if (check_grant(thd, SELECT_ACL, &table_list, TRUE, UINT_MAX, FALSE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1244
      break;
1245 1246
    /* init structures for VIEW processing */
    table_list.select_lex= &(thd->lex->select_lex);
1247 1248 1249 1250

    lex_start(thd);
    mysql_reset_thd_for_next_command(thd);

1251
    thd->lex->
1252 1253
      select_lex.table_list.link_in_list((uchar*) &table_list,
                                         (uchar**) &table_list.next_local);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
1254
    thd->lex->add_to_query_tables(&table_list);
1255

1256 1257
    /* switch on VIEW optimisation: do not fill temporary tables */
    thd->lex->sql_command= SQLCOM_SHOW_FIELDS;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1258
    mysqld_list_fields(thd,&table_list,fields);
1259
    thd->lex->unit.cleanup();
1260
    thd->cleanup_after_query();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1261 1262 1263 1264
    break;
  }
#endif
  case COM_QUIT:
1265
    /* We don't calculate statistics for this command */
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1266
    general_log_print(thd, command, NullS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1267
    net->error=0;				// Don't give 'abort' message
Marc Alff's avatar
Marc Alff committed
1268
    thd->stmt_da->disable_status();              // Don't send anything back
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1269 1270
    error=TRUE;					// End server
    break;
1271
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1272 1273
  case COM_BINLOG_DUMP:
    {
monty@mysql.com's avatar
monty@mysql.com committed
1274 1275 1276 1277
      ulong pos;
      ushort flags;
      uint32 slave_server_id;

1278
      status_var_increment(thd->status_var.com_other);
1279
      thd->enable_slow_log= opt_log_slow_admin_statements;
1280
      if (check_global_access(thd, REPL_SLAVE_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1281
	break;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1282

1283
      /* TODO: The following has to be changed to an 8 byte integer */
1284 1285
      pos = uint4korr(packet);
      flags = uint2korr(packet + 4);
1286
      thd->server_id=0; /* avoid suicide */
1287
      if ((slave_server_id= uint4korr(packet+6))) // mysqlbinlog.server_id==0
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
1288
	kill_zombie_dump_threads(slave_server_id);
1289
      thd->server_id = slave_server_id;
monty@mysql.com's avatar
monty@mysql.com committed
1290

cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1291
      general_log_print(thd, command, "Log: '%s'  Pos: %ld", packet+10,
monty@mysql.com's avatar
monty@mysql.com committed
1292
                      (long) pos);
1293
      mysql_binlog_send(thd, thd->strdup(packet + 10), (my_off_t) pos, flags);
1294
      unregister_slave(thd,1,1);
monty@mysql.com's avatar
monty@mysql.com committed
1295
      /*  fake COM_QUIT -- if we get here, the thread needs to terminate */
1296
      error = TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1297 1298
      break;
    }
1299
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1300
  case COM_REFRESH:
1301 1302
  {
    bool not_used;
1303
    status_var_increment(thd->status_var.com_stat[SQLCOM_FLUSH]);
1304 1305
    ulong options= (ulong) (uchar) packet[0];
    if (check_global_access(thd,RELOAD_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1306
      break;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1307
    general_log_print(thd, command, NullS);
1308
#ifndef DBUG_OFF
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    bool debug_simulate= FALSE;
    DBUG_EXECUTE_IF("simulate_detached_thread_refresh", debug_simulate= TRUE;);
    if (debug_simulate)
    {
      /*
        Simulate a reload without a attached thread session.
        Provides a environment similar to that of when the
        server receives a SIGHUP signal and reloads caches
        and flushes tables.
      */
      bool res;
      my_pthread_setspecific_ptr(THR_THD, NULL);
      res= reload_acl_and_cache(NULL, options | REFRESH_FAST,
                                NULL, &not_used);
      my_pthread_setspecific_ptr(THR_THD, thd);
      if (!res)
Davi Arnaut's avatar
Davi Arnaut committed
1325
        my_ok(thd);
1326 1327
      break;
    }
1328
#endif
Davi Arnaut's avatar
Davi Arnaut committed
1329
    if (!reload_acl_and_cache(thd, options, NULL, &not_used))
1330
      my_ok(thd);
1331 1332
    break;
  }
1333
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1334
  case COM_SHUTDOWN:
1335
  {
1336
    status_var_increment(thd->status_var.com_other);
1337
    if (check_global_access(thd,SHUTDOWN_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1338
      break; /* purecov: inspected */
1339
    /*
1340
      If the client is < 4.1.3, it is going to send us no argument; then
1341
      packet_length is 0, packet[0] is the end 0 of the packet. Note that
1342 1343
      SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in
      packet[0].
1344
    */
1345 1346
    enum mysql_enum_shutdown_level level=
      (enum mysql_enum_shutdown_level) (uchar) packet[0];
1347 1348 1349 1350 1351 1352 1353
    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;
    }
1354
    DBUG_PRINT("quit",("Got shutdown command for level %u", level));
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1355
    general_log_print(thd, command, NullS);
1356
    my_eof(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1357 1358 1359 1360
    close_thread_tables(thd);			// Free before kill
    kill_mysql();
    error=TRUE;
    break;
1361
  }
1362
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1363 1364
  case COM_STATISTICS:
  {
1365 1366 1367
    STATUS_VAR current_global_status_var;
    ulong uptime;
    uint length;
1368
    ulonglong queries_per_second1000;
1369 1370
    char buff[250];
    uint buff_len= sizeof(buff);
1371

1372
    general_log_print(thd, command, NullS);
1373
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]);
1374
    calc_sum_of_all_status(&current_global_status_var);
1375 1376 1377 1378 1379
    if (!(uptime= (ulong) (thd->start_time - server_start_time)))
      queries_per_second1000= 0;
    else
      queries_per_second1000= thd->query_id * LL(1000) / uptime;

1380 1381 1382
    length= my_snprintf((char*) buff, buff_len - 1,
                        "Uptime: %lu  Threads: %d  Questions: %lu  "
                        "Slow queries: %lu  Opens: %lu  Flush tables: %lu  "
1383
                        "Open tables: %u  Queries per second avg: %u.%u",
1384 1385 1386 1387 1388 1389
                        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(),
1390 1391
                        (uint) (queries_per_second1000 / 1000),
                        (uint) (queries_per_second1000 % 1000));
1392 1393
#ifdef EMBEDDED_LIBRARY
    /* Store the buffer in permanent memory */
1394
    my_ok(thd, 0, 0, buff);
1395
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1396
#ifdef SAFEMALLOC
1397
    if (sf_malloc_cur_memory)				// Using SAFEMALLOC
1398 1399 1400 1401 1402 1403 1404
    {
      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);
    }
hf@deer.(none)'s avatar
hf@deer.(none) committed
1405 1406
#endif
#ifndef EMBEDDED_LIBRARY
Konstantin Osipov's avatar
Konstantin Osipov committed
1407 1408
    (void) my_net_write(net, (uchar*) buff, length);
    (void) net_flush(net);
Marc Alff's avatar
Marc Alff committed
1409
    thd->stmt_da->disable_status();
hf@deer.(none)'s avatar
hf@deer.(none) committed
1410
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1411 1412 1413
    break;
  }
  case COM_PING:
1414
    status_var_increment(thd->status_var.com_other);
1415
    my_ok(thd);				// Tell client we are alive
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1416 1417
    break;
  case COM_PROCESS_INFO:
1418
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]);
1419 1420
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd, PROCESS_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1421
      break;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1422
    general_log_print(thd, command, NullS);
hf@deer.(none)'s avatar
hf@deer.(none) committed
1423
    mysqld_list_processes(thd,
1424 1425
			  thd->security_ctx->master_access & PROCESS_ACL ? 
			  NullS : thd->security_ctx->priv_user, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1426 1427 1428
    break;
  case COM_PROCESS_KILL:
  {
1429
    status_var_increment(thd->status_var.com_stat[SQLCOM_KILL]);
1430
    ulong id=(ulong) uint4korr(packet);
1431
    sql_kill(thd,id,false);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1432 1433
    break;
  }
1434 1435
  case COM_SET_OPTION:
  {
1436
    status_var_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION]);
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
1437 1438 1439 1440
    uint opt_command= uint2korr(packet);

    switch (opt_command) {
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON:
1441
      thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
1442
      my_eof(thd);
1443
      break;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
1444
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF:
1445
      thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
1446
      my_eof(thd);
1447 1448
      break;
    default:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1449
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1450 1451 1452 1453
      break;
    }
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1454
  case COM_DEBUG:
1455
    status_var_increment(thd->status_var.com_other);
1456
    if (check_global_access(thd, SUPER_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1457
      break;					/* purecov: inspected */
1458
    mysql_print_status();
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1459
    general_log_print(thd, command, NullS);
1460
    my_eof(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1461 1462 1463 1464 1465
    break;
  case COM_SLEEP:
  case COM_CONNECT:				// Impossible here
  case COM_TIME:				// Impossible from client
  case COM_DELAYED_INSERT:
1466
  case COM_END:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1467
  default:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1468
    my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1469 1470
    break;
  }
1471

1472
  /* report error issued during command execution */
1473 1474
  if (thd->killed_errno())
  {
Marc Alff's avatar
Marc Alff committed
1475
    if (! thd->stmt_da->is_set())
1476 1477 1478 1479 1480 1481 1482 1483
      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;
  }

1484
  /* If commit fails, we should be able to reset the OK status. */
Marc Alff's avatar
Marc Alff committed
1485
  thd->stmt_da->can_overwrite_status= TRUE;
1486
  ha_autocommit_or_rollback(thd, thd->is_error());
Marc Alff's avatar
Marc Alff committed
1487
  thd->stmt_da->can_overwrite_status= FALSE;
1488 1489 1490

  thd->transaction.stmt.reset();

1491
  thd->protocol->end_statement();
1492
  query_cache_end_of_result(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1493

1494 1495 1496 1497
  thd->proc_info= "closing tables";
  /* Free tables */
  close_thread_tables(thd);

1498
  if (!thd->is_error() && !thd->killed_errno())
1499
    mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_RESULT, 0, 0);
1500

1501
  log_slow_statement(thd);
1502

1503
  thd_proc_info(thd, "cleaning up");
1504
  thd->set_query(NULL, 0);
1505
  thd->command=COM_SLEEP;
1506
  dec_thread_running();
1507
  thd_proc_info(thd, 0);
1508 1509
  thd->packet.shrink(thd->variables.net_buffer_length);	// Reclaim some memory
  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
1510

Konstantin Osipov's avatar
Konstantin Osipov committed
1511 1512 1513
#if defined(ENABLED_PROFILING)
  thd->profiling.finish_current_query();
#endif
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
  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);
  }
1524 1525 1526 1527
  DBUG_RETURN(error);
}


1528
void log_slow_statement(THD *thd)
1529
{
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1530
  DBUG_ENTER("log_slow_statement");
1531 1532 1533 1534 1535 1536 1537

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

1540 1541
  /*
    Do not log administrative statements unless the appropriate option is
1542
    set.
1543
  */
1544
  if (thd->enable_slow_log)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1545
  {
1546
    ulonglong end_utime_of_query= thd->current_utime();
1547
    thd_proc_info(thd, "logging slow query");
1548

1549 1550 1551 1552
    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)) &&
1553 1554
          opt_log_queries_not_using_indexes &&
           !(sql_command_flags[thd->lex->sql_command] & CF_STATUS_COMMAND))) &&
1555
        thd->examined_row_count >= thd->variables.min_examined_row_limit)
1556
    {
1557
      thd_proc_info(thd, "logging slow query");
1558
      thd->status_var.long_query_count++;
1559 1560
      slow_log_print(thd, thd->query(), thd->query_length(), 
                     end_utime_of_query);
1561
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1562
  }
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1563
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1564 1565
}

1566

1567
/**
1568 1569 1570 1571 1572 1573 1574
  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.

1575 1576 1577 1578 1579 1580 1581
  @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
1582 1583 1584 1585
    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).

1586
  @retval
1587
    0                 success
1588
  @retval
1589 1590 1591 1592
    1                 out of memory or SHOW commands are not allowed
                      in this version of the server.
*/

1593 1594 1595
int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident,
                         enum enum_schema_tables schema_table_idx)
{
1596
  SELECT_LEX *schema_select_lex= NULL;
1597
  DBUG_ENTER("prepare_schema_table");
1598

1599
  switch (schema_table_idx) {
1600 1601
  case SCH_SCHEMATA:
#if defined(DONT_ALLOW_SHOW_COMMANDS)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1602 1603
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0));   /* purecov: inspected */
1604 1605 1606 1607
    DBUG_RETURN(1);
#else
    break;
#endif
1608

1609 1610 1611
  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
1612
  case SCH_TRIGGERS:
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1613
  case SCH_EVENTS:
1614
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1615 1616
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1617 1618 1619
    DBUG_RETURN(1);
#else
    {
1620
      LEX_STRING db;
1621
      size_t dummy;
1622
      if (lex->select_lex.db == NULL &&
1623
          lex->copy_db_to(&lex->select_lex.db, &dummy))
1624
      {
1625
        DBUG_RETURN(1);
1626
      }
1627 1628 1629
      schema_select_lex= new SELECT_LEX();
      db.str= schema_select_lex->db= lex->select_lex.db;
      schema_select_lex->table_list.first= NULL;
1630
      db.length= strlen(db.str);
1631

1632
      if (check_db_name(&db))
1633
      {
1634
        my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
1635 1636 1637 1638 1639 1640 1641
        DBUG_RETURN(1);
      }
      break;
    }
#endif
  case SCH_COLUMNS:
  case SCH_STATISTICS:
1642
  {
1643
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1644 1645
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
1646 1647
    DBUG_RETURN(1);
#else
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
    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;
  }
1659
#endif
1660 1661 1662 1663 1664
  case SCH_PROFILES:
    /* 
      Mark this current profiling record to be discarded.  We don't
      wish to have SHOW commands show up in profiling.
    */
1665
#if defined(ENABLED_PROFILING)
1666
    thd->profiling.discard_current_query();
1667 1668
#endif
    break;
1669 1670 1671
  case SCH_OPEN_TABLES:
  case SCH_VARIABLES:
  case SCH_STATUS:
1672 1673
  case SCH_PROCEDURES:
  case SCH_CHARSETS:
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1674
  case SCH_ENGINES:
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
  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;
1693
  table_list->schema_select_lex= schema_select_lex;
1694
  table_list->schema_table_reformed= 1;
1695 1696 1697 1698
  DBUG_RETURN(0);
}


1699 1700 1701
/**
  Read query from packet and store in thd->query.
  Used in COM_QUERY and COM_STMT_PREPARE.
1702 1703

    Sets the following THD variables:
1704 1705
  - query
  - query_length
1706

1707
  @retval
1708
    FALSE ok
1709
  @retval
1710
    TRUE  error;  In this case thd->fatal_error is set
1711 1712
*/

1713
bool alloc_query(THD *thd, const char *packet, uint packet_length)
1714
{
1715
  char *query;
1716
  /* Remove garbage at start and end of query */
1717
  while (packet_length > 0 && my_isspace(thd->charset(), packet[0]))
1718 1719 1720 1721
  {
    packet++;
    packet_length--;
  }
1722
  const char *pos= packet + packet_length;     // Point at end null
peter@mysql.com's avatar
peter@mysql.com committed
1723
  while (packet_length > 0 &&
1724
	 (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1])))
1725 1726 1727 1728 1729
  {
    pos--;
    packet_length--;
  }
  /* We must allocate some extra memory for query cache */
1730 1731 1732 1733 1734 1735 1736
  if (! (query= (char*) thd->memdup_w_gap(packet,
                                          packet_length,
                                          1 + thd->db_length +
                                          QUERY_CACHE_FLAGS_SIZE)))
      return TRUE;
  query[packet_length]= '\0';
  thd->set_query(query, packet_length);
1737 1738 1739 1740

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

1742
  return FALSE;
1743 1744
}

1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
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;
1758
  thd->variables.lc_time_names= &my_locale_en_US;
1759 1760 1761
  thd->one_shot_set= 0;
}

1762

1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
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);

1809
    if (thd->slave_thread && lex->sphead)
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
      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);
}


1848 1849
/**
  Execute command saved in thd and lex->sql_command.
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860

    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.

1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
  @param thd                       Thread handle

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

  @retval
1871
    FALSE       OK
1872
  @retval
1873 1874
    TRUE        Error
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1875

1876
int
1877
mysql_execute_command(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1878
{
1879
  int res= FALSE;
1880
  bool need_start_waiting= FALSE; // have protection against global read lock
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
1881
  int  up_result= 0;
1882
  LEX  *lex= thd->lex;
monty@mysql.com's avatar
monty@mysql.com committed
1883
  /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1884
  SELECT_LEX *select_lex= &lex->select_lex;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1885
  /* first table of first SELECT_LEX */
monty@mysql.com's avatar
monty@mysql.com committed
1886
  TABLE_LIST *first_table= (TABLE_LIST*) select_lex->table_list.first;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1887 1888 1889
  /* list of all tables in query */
  TABLE_LIST *all_tables;
  /* most outer SELECT_LEX_UNIT of query */
1890
  SELECT_LEX_UNIT *unit= &lex->unit;
1891 1892 1893 1894
#ifdef HAVE_REPLICATION
  /* have table map for update for multi-update statement (BUG#37051) */
  bool have_table_map_for_update= FALSE;
#endif
1895
  /* Saved variable value */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1896
  DBUG_ENTER("mysql_execute_command");
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
1897 1898 1899
#ifdef WITH_PARTITION_STORAGE_ENGINE
  thd->work_part_info= 0;
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1900

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916
  /*
    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();
1917
  /* should be assigned after making first tables same */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1918
  all_tables= lex->query_tables;
1919 1920 1921 1922
  /* 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);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1923

1924 1925 1926 1927 1928 1929
  /*
    Reset warning count for each query that uses tables
    A better approach would be to reset this for any commands
    that is not a SHOW command or a select that only access local
    variables, but for now this is probably good enough.
  */
Marc Alff's avatar
Marc Alff committed
1930 1931 1932 1933 1934 1935 1936 1937
  if ((sql_command_flags[lex->sql_command] & CF_DIAGNOSTIC_STMT) != 0)
    thd->warning_info->set_read_only(TRUE);
  else
  {
    thd->warning_info->set_read_only(FALSE);
    if (all_tables)
      thd->warning_info->opt_clear_warning_info(thd->query_id);
  }
1938

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1939
#ifdef HAVE_REPLICATION
1940
  if (unlikely(thd->slave_thread))
1941
  {
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
    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;
    }
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006

    /*
      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;
    }
2007
    
peter@mysql.com's avatar
peter@mysql.com committed
2008
    /*
2009 2010
      Check if statment should be skipped because of slave filtering
      rules
2011 2012

      Exceptions are:
2013 2014
      - UPDATE MULTI: For this statement, we want to check the filtering
        rules later in the code
2015
      - SET: we always execute it (Not that many SET commands exists in
lars@mysql.com's avatar
lars@mysql.com committed
2016 2017
        the binary log anyway -- only 4.1 masters write SET statements,
	in 5.0 there are no SET statements in the binary log)
2018 2019
      - DROP TEMPORARY TABLE IF EXISTS: we always execute it (otherwise we
        have stale files on slave caused by exclusion of one tmp table).
monty@hundin.mysql.fi's avatar
merge  
monty@hundin.mysql.fi committed
2020
    */
2021 2022
    if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) &&
	!(lex->sql_command == SQLCOM_SET_OPTION) &&
2023
	!(lex->sql_command == SQLCOM_DROP_TABLE &&
2024
          lex->drop_temporary && lex->drop_if_exists) &&
guilhem@mysql.com's avatar
Merge  
guilhem@mysql.com committed
2025
        all_tables_not_ok(thd, all_tables))
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2026 2027
    {
      /* we warn the slave SQL thread */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2028
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
      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);
      }
2046
      DBUG_RETURN(0);
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2047
    }
2048
  }
2049
  else
2050
  {
2051
#endif /* HAVE_REPLICATION */
2052 2053 2054 2055
    /*
      When option readonly is set deny operations which change non-temporary
      tables. Except for the replication thread and the 'super' users.
    */
2056
    if (deny_updates_if_read_only_option(thd, all_tables))
2057 2058 2059 2060 2061 2062 2063
    {
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
      DBUG_RETURN(-1);
    }
#ifdef HAVE_REPLICATION
  } /* endif unlikely slave */
#endif
2064
  status_var_increment(thd->status_var.com_stat[lex->sql_command]);
2065

2066 2067
  DBUG_ASSERT(thd->transaction.stmt.modified_non_trans_table == FALSE);
  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2068
  switch (lex->sql_command) {
2069

2070
  case SQLCOM_SHOW_EVENTS:
2071 2072 2073 2074
#ifndef HAVE_EVENT_SCHEDULER
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server");
    break;
#endif
2075 2076
  case SQLCOM_SHOW_STATUS_PROC:
  case SQLCOM_SHOW_STATUS_FUNC:
2077 2078
    if (!(res= check_table_access(thd, SELECT_ACL, all_tables, FALSE,
                                  UINT_MAX, FALSE)))
2079
      res= execute_sqlcom_select(thd, all_tables);
2080 2081 2082 2083 2084
    break;
  case SQLCOM_SHOW_STATUS:
  {
    system_status_var old_status_var= thd->status_var;
    thd->initial_status_var= &old_status_var;
2085 2086
    if (!(res= check_table_access(thd, SELECT_ACL, all_tables, FALSE,
                                  UINT_MAX, FALSE)))
2087
      res= execute_sqlcom_select(thd, all_tables);
2088 2089 2090 2091 2092 2093 2094
    /* Don't log SHOW STATUS commands to slow query log */
    thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED |
                           SERVER_QUERY_NO_GOOD_INDEX_USED);
    /*
      restore status variables, as we don't want 'show status' to cause
      changes
    */
Marc Alff's avatar
Marc Alff committed
2095
    mysql_mutex_lock(&LOCK_status);
2096 2097 2098
    add_diff_to_status(&global_status_var, &thd->status_var,
                       &old_status_var);
    thd->status_var= old_status_var;
Marc Alff's avatar
Marc Alff committed
2099
    mysql_mutex_unlock(&LOCK_status);
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
    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:
2113
  case SQLCOM_SHOW_STORAGE_ENGINES:
2114
  case SQLCOM_SHOW_PROFILE:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2115
  case SQLCOM_SELECT:
2116
  {
2117
    thd->status_var.last_query_cost= 0.0;
2118 2119 2120 2121 2122 2123 2124 2125

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2126
    if (all_tables)
2127
      res= check_table_access(thd,
2128 2129
                              privileges_requested,
                              all_tables, FALSE, UINT_MAX, FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2130
    else
Marc Alff's avatar
Marc Alff committed
2131
      res= check_access(thd, privileges_requested, any_db, NULL, NULL, 0, 0);
2132

2133 2134 2135 2136 2137 2138 2139 2140
    if (res)
      break;

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

    res= execute_sqlcom_select(thd, all_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2141
    break;
2142 2143
  }
case SQLCOM_PREPARE:
2144
  {
2145
    mysql_sql_stmt_prepare(thd);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
2146 2147 2148 2149
    break;
  }
  case SQLCOM_EXECUTE:
  {
2150
    mysql_sql_stmt_execute(thd);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
2151 2152 2153 2154
    break;
  }
  case SQLCOM_DEALLOCATE_PREPARE:
  {
2155
    mysql_sql_stmt_close(thd);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
2156 2157
    break;
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2158
  case SQLCOM_DO:
2159 2160
    if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)
        || open_and_lock_tables(thd, all_tables))
2161
      goto error;
2162 2163

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

2166
  case SQLCOM_EMPTY_QUERY:
2167
    my_ok(thd);
2168 2169
    break;

2170 2171 2172 2173
  case SQLCOM_HELP:
    res= mysqld_help(thd,lex->help_arg);
    break;

2174
#ifndef EMBEDDED_LIBRARY
2175
  case SQLCOM_PURGE:
2176
  {
2177
    if (check_global_access(thd, SUPER_ACL))
2178
      goto error;
monty@mysql.com's avatar
monty@mysql.com committed
2179
    /* PURGE MASTER LOGS TO 'file' */
2180 2181 2182
    res = purge_master_logs(thd, lex->to_log);
    break;
  }
2183 2184
  case SQLCOM_PURGE_BEFORE:
  {
2185 2186
    Item *it;

2187 2188
    if (check_global_access(thd, SUPER_ACL))
      goto error;
monty@mysql.com's avatar
monty@mysql.com committed
2189
    /* PURGE MASTER LOGS BEFORE 'data' */
2190
    it= (Item *)lex->value_list.head();
2191
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) ||
2192
        it->check_cols(1))
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
    {
      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());
2204 2205
    break;
  }
2206
#endif
2207 2208
  case SQLCOM_SHOW_WARNS:
  {
2209 2210
    res= mysqld_show_warnings(thd, (ulong)
			      ((1L << (uint) MYSQL_ERROR::WARN_LEVEL_NOTE) |
2211 2212 2213
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_WARN) |
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR)
			       ));
2214 2215 2216 2217
    break;
  }
  case SQLCOM_SHOW_ERRORS:
  {
2218 2219
    res= mysqld_show_warnings(thd, (ulong)
			      (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR));
2220 2221
    break;
  }
2222 2223
  case SQLCOM_SHOW_PROFILES:
  {
2224
#if defined(ENABLED_PROFILING)
2225
    thd->profiling.discard_current_query();
2226
    res= thd->profiling.show_profiles();
2227 2228 2229
    if (res)
      goto error;
#else
2230
    my_error(ER_FEATURE_DISABLED, MYF(0), "SHOW PROFILES", "enable-profiling");
2231 2232
    goto error;
#endif
2233 2234
    break;
  }
2235 2236
  case SQLCOM_SHOW_NEW_MASTER:
  {
2237
    if (check_global_access(thd, REPL_SLAVE_ACL))
2238
      goto error;
2239
    /* This query don't work now. See comment in repl_failsafe.cc */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2240
#ifndef WORKING_NEW_MASTER
2241 2242
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "SHOW NEW MASTER");
    goto error;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2243
#else
2244 2245
    res = show_new_master(thd);
    break;
2246
#endif
2247
  }
2248

2249
#ifdef HAVE_REPLICATION
2250 2251
  case SQLCOM_SHOW_SLAVE_HOSTS:
  {
2252
    if (check_global_access(thd, REPL_SLAVE_ACL))
2253 2254 2255 2256
      goto error;
    res = show_slave_hosts(thd);
    break;
  }
2257
  case SQLCOM_SHOW_RELAYLOG_EVENTS: /* fall through */
2258 2259
  case SQLCOM_SHOW_BINLOG_EVENTS:
  {
2260
    if (check_global_access(thd, REPL_SLAVE_ACL))
2261
      goto error;
2262
    res = mysql_show_binlog_events(thd);
2263 2264
    break;
  }
2265 2266
#endif

igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2267 2268
  case SQLCOM_ASSIGN_TO_KEYCACHE:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2269
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2270
    if (check_access(thd, INDEX_ACL, first_table->db,
Marc Alff's avatar
Marc Alff committed
2271 2272 2273
                     &first_table->grant.privilege,
                     &first_table->grant.m_internal,
                     0, 0))
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2274
      goto error;
2275
    res= mysql_assign_to_keycache(thd, first_table, &lex->ident);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2276 2277
    break;
  }
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2278 2279
  case SQLCOM_PRELOAD_KEYS:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2280
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2281
    if (check_access(thd, INDEX_ACL, first_table->db,
Marc Alff's avatar
Marc Alff committed
2282 2283 2284
                     &first_table->grant.privilege,
                     &first_table->grant.m_internal,
                     0, 0))
2285
      goto error;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2286
    res = mysql_preload_keys(thd, first_table);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2287 2288
    break;
  }
2289
#ifdef HAVE_REPLICATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2290
  case SQLCOM_CHANGE_MASTER:
2291
  {
2292
    if (check_global_access(thd, SUPER_ACL))
2293
      goto error;
Marc Alff's avatar
Marc Alff committed
2294
    mysql_mutex_lock(&LOCK_active_mi);
2295
    res = change_master(thd,active_mi);
Marc Alff's avatar
Marc Alff committed
2296
    mysql_mutex_unlock(&LOCK_active_mi);
2297 2298
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2299
  case SQLCOM_SHOW_SLAVE_STAT:
2300
  {
2301 2302
    /* Accept one of two privileges */
    if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
2303
      goto error;
Marc Alff's avatar
Marc Alff committed
2304
    mysql_mutex_lock(&LOCK_active_mi);
2305 2306 2307 2308 2309 2310
    if (active_mi != NULL)
    {
      res = show_master_info(thd, active_mi);
    }
    else
    {
2311 2312
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                   WARN_NO_MASTER_INFO, ER(WARN_NO_MASTER_INFO));
2313
      my_ok(thd);
2314
    }
Marc Alff's avatar
Marc Alff committed
2315
    mysql_mutex_unlock(&LOCK_active_mi);
2316 2317
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2318
  case SQLCOM_SHOW_MASTER_STAT:
2319
  {
2320 2321
    /* Accept one of two privileges */
    if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
2322 2323 2324 2325
      goto error;
    res = show_binlog_info(thd);
    break;
  }
peter@mysql.com's avatar
peter@mysql.com committed
2326

2327
#endif /* HAVE_REPLICATION */
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2328
  case SQLCOM_SHOW_ENGINE_STATUS:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2329
    {
2330
      if (check_global_access(thd, PROCESS_ACL))
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2331 2332
        goto error;
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2333 2334
      break;
    }
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2335
  case SQLCOM_SHOW_ENGINE_MUTEX:
vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
2336
    {
2337
      if (check_global_access(thd, PROCESS_ACL))
vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
2338
        goto error;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2339
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX);
vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
2340 2341
      break;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2342
  case SQLCOM_CREATE_TABLE:
2343
  {
2344
    /* If CREATE TABLE of non-temporary table, do implicit commit */
2345 2346 2347 2348 2349 2350 2351 2352
    if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
    {
      if (end_active_trans(thd))
      {
	res= -1;
	break;
      }
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2353 2354 2355 2356 2357
    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;
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
    /*
      Code below (especially in mysql_create_table() and select_create
      methods) may modify HA_CREATE_INFO structure in LEX, so we have to
      use a copy of this structure to make execution prepared statement-
      safe. A shallow copy is enough as this code won't modify any memory
      referenced from this structure.
    */
    HA_CREATE_INFO create_info(lex->create_info);
    /*
      We need to copy alter_info for the same reasons of re-execution
      safety, only in case of Alter_info we have to do (almost) a deep
      copy.
    */
    Alter_info alter_info(lex->alter_info, thd->mem_root);

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

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

2383 2384 2385
    /* Might have been updated in create_table_precheck */
    create_info.alias= create_table->alias;

2386
#ifdef HAVE_READLINK
2387
    /* Fix names if symlinked tables */
2388
    if (append_file_to_dir(thd, &create_info.data_file_name,
2389
			   create_table->table_name) ||
2390
	append_file_to_dir(thd, &create_info.index_file_name,
2391
			   create_table->table_name))
monty@mysql.com's avatar
monty@mysql.com committed
2392
      goto end_with_restore_list;
2393
#endif
2394
    /*
2395
      If we are using SET CHARSET without DEFAULT, add an implicit
2396 2397
      DEFAULT to not confuse old users. (This may change).
    */
2398
    if ((create_info.used_fields &
2399 2400 2401
	 (HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) ==
	HA_CREATE_USED_CHARSET)
    {
2402 2403 2404 2405
      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;
2406
    }
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
    /*
      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.
    */
2420 2421
    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
2422
    {
monty@mysql.com's avatar
monty@mysql.com committed
2423 2424
      res= 1;
      goto end_with_restore_list;
2425
    }
2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
#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
2437
    if (select_lex->item_list.elements)		// With select
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2438 2439
    {
      select_result *result;
2440

2441 2442 2443
      /*
        If:
        a) we inside an SP and there was NAME_CONST substitution,
Ramil Kalimullin's avatar
Ramil Kalimullin committed
2444
        b) binlogging is on (STMT mode),
2445 2446 2447 2448 2449 2450
        c) we log the SP as separate statements
        raise a warning, as it may cause problems
        (see 'NAME_CONST issues' in 'Binary Logging of Stored Programs')
       */
      if (thd->query_name_consts && 
          mysql_bin_log.is_open() &&
Ramil Kalimullin's avatar
Ramil Kalimullin committed
2451
          thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
          !mysql_bin_log.is_query_in_union(thd, thd->query_id))
      {
        List_iterator_fast<Item> it(select_lex->item_list);
        Item *item;
        uint splocal_refs= 0;
        /* Count SP local vars in the top-level SELECT list */
        while ((item= it++))
        {
          if (item->is_splocal())
            splocal_refs++;
        }
        /*
          If it differs from number of NAME_CONST substitution applied,
          we may have a SOME_FUNC(NAME_CONST()) in the SELECT list,
          that may cause a problem with binary log (see BUG#35383),
          raise a warning. 
        */
        if (splocal_refs != thd->query_name_consts)
          push_warning(thd, 
                       MYSQL_ERROR::WARN_LEVEL_WARN,
                       ER_UNKNOWN_ERROR,
"Invoked routine ran a statement that may cause problems with "
"binary log, see 'NAME_CONST issues' in 'Binary Logging of Stored Programs' "
"section of the manual.");
      }
      
2478
      select_lex->options|= SELECT_NO_UNLOCK;
2479
      unit->set_limit(select_lex);
2480

2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
      /*
        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;
      }

2494
      if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
dlenev@mockturtle.local's avatar
dlenev@mockturtle.local committed
2495 2496 2497
      {
        lex->link_first_table_back(create_table, link_to_local);
        create_table->create= TRUE;
2498 2499
        /* Base table and temporary table are not in the same name space. */
        create_table->skip_temporary= 1;
dlenev@mockturtle.local's avatar
dlenev@mockturtle.local committed
2500 2501 2502
      }

      if (!(res= open_and_lock_tables(thd, lex->query_tables)))
2503
      {
2504 2505 2506 2507
        /*
          Is table which we are changing used somewhere in other parts
          of query
        */
2508
        if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
2509
        {
2510
          TABLE_LIST *duplicate;
dlenev@mockturtle.local's avatar
dlenev@mockturtle.local committed
2511
          create_table= lex->unlink_first_table(&link_to_local);
2512
          if ((duplicate= unique_table(thd, create_table, select_tables, 0)))
2513 2514 2515
          {
            update_non_unique_table_error(create_table, "CREATE", duplicate);
            res= 1;
2516
            goto end_with_restore_list;
2517
          }
2518
        }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2519
        /* If we create merge table, we have to test tables in merge, too */
2520
        if (create_info.used_fields & HA_CREATE_USED_UNION)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2521 2522
        {
          TABLE_LIST *tab;
2523
          for (tab= (TABLE_LIST*) create_info.merge_list.first;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2524 2525 2526
               tab;
               tab= tab->next_local)
          {
2527
            TABLE_LIST *duplicate;
2528
            if ((duplicate= unique_table(thd, tab, select_tables, 0)))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2529
            {
2530
              update_non_unique_table_error(tab, "CREATE", duplicate);
monty@mysql.com's avatar
monty@mysql.com committed
2531
              res= 1;
2532
              goto end_with_restore_list;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2533 2534 2535
            }
          }
        }
2536

dlenev@mockturtle.local's avatar
dlenev@mockturtle.local committed
2537
        /*
2538 2539
          select_create is currently not re-execution friendly and
          needs to be created for every execution of a PS/SP.
dlenev@mockturtle.local's avatar
dlenev@mockturtle.local committed
2540
        */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2541
        if ((result= new select_create(create_table,
2542 2543 2544 2545
                                       &create_info,
                                       &alter_info,
                                       select_lex->item_list,
                                       lex->duplicates,
2546
                                       lex->ignore,
2547
                                       select_tables)))
2548 2549 2550 2551 2552
        {
          /*
            CREATE from SELECT give its SELECT_LEX for SELECT,
            and item_list belong to SELECT
          */
2553
          res= handle_select(thd, lex, result, 0);
2554
          delete result;
2555
        }
2556
      }
2557
      else if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
dlenev@mockturtle.local's avatar
dlenev@mockturtle.local committed
2558 2559
        create_table= lex->unlink_first_table(&link_to_local);

2560
    }
monty@mysql.com's avatar
monty@mysql.com committed
2561
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2562
    {
2563
      /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
2564
      if (create_info.options & HA_LEX_CREATE_TMP_TABLE)
2565
        thd->variables.option_bits|= OPTION_KEEP_LOG;
monty@mysql.com's avatar
monty@mysql.com committed
2566
      /* regular create */
2567
      if (create_info.options & HA_LEX_CREATE_TABLE_LIKE)
2568
        res= mysql_create_like_table(thd, create_table, select_tables,
2569
                                     &create_info);
venu@myvenu.com's avatar
venu@myvenu.com committed
2570
      else
2571
      {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2572
        res= mysql_create_table(thd, create_table->db,
2573 2574
                                create_table->table_name, &create_info,
                                &alter_info, 0, 0);
2575
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2576
      if (!res)
2577
	my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2578
    }
2579

monty@mysql.com's avatar
monty@mysql.com committed
2580
    /* put tables back for PS rexecuting */
monty@mysql.com's avatar
monty@mysql.com committed
2581
end_with_restore_list:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2582
    lex->link_first_table_back(create_table, link_to_local);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2583
    break;
2584
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2585
  case SQLCOM_CREATE_INDEX:
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603
    /* Fall through */
  case SQLCOM_DROP_INDEX:
  /*
    CREATE INDEX and DROP INDEX are implemented by calling ALTER
    TABLE with proper arguments.

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

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2604 2605
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_one_table_access(thd, INDEX_ACL, all_tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2606
      goto error; /* purecov: inspected */
2607
    if (end_active_trans(thd))
2608
      goto error;
2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
    /*
      Currently CREATE INDEX or DROP INDEX cause a full table rebuild
      and thus classify as slow administrative statements just like
      ALTER TABLE.
    */
    thd->enable_slow_log= opt_log_slow_admin_statements;

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

2621 2622 2623 2624 2625
    res= mysql_alter_table(thd, first_table->db, first_table->table_name,
                           &create_info, first_table, &alter_info,
                           0, (ORDER*) 0, 0);
    break;
  }
2626
#ifdef HAVE_REPLICATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2627
  case SQLCOM_SLAVE_START:
2628
  {
Marc Alff's avatar
Marc Alff committed
2629
    mysql_mutex_lock(&LOCK_active_mi);
2630
    start_slave(thd,active_mi,1 /* net report*/);
Marc Alff's avatar
Marc Alff committed
2631
    mysql_mutex_unlock(&LOCK_active_mi);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2632
    break;
2633
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2634
  case SQLCOM_SLAVE_STOP:
2635 2636 2637 2638 2639 2640
  /*
    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,
2641
      so it waits for the client thread because t is locked by it.
2642
    - then the client thread does SLAVE STOP.
2643 2644
      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.
2645 2646 2647
    To prevent that, refuse SLAVE STOP if the
    client thread has locked tables
  */
2648
  if (thd->locked_tables || thd->active_transaction() || thd->global_read_lock)
2649
  {
2650 2651
    my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
               ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2652
    goto error;
2653
  }
2654
  {
Marc Alff's avatar
Marc Alff committed
2655
    mysql_mutex_lock(&LOCK_active_mi);
2656
    stop_slave(thd,active_mi,1/* net report*/);
Marc Alff's avatar
Marc Alff committed
2657
    mysql_mutex_unlock(&LOCK_active_mi);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2658
    break;
2659
  }
2660
#endif /* HAVE_REPLICATION */
2661

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2662
  case SQLCOM_ALTER_TABLE:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2663
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2664
    {
2665
      ulong priv=0;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2666
      ulong priv_needed= ALTER_ACL;
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
      /*
        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;
2678 2679 2680 2681
      /*
        We also require DROP priv for ALTER TABLE ... DROP PARTITION, as well
        as for RENAME TO, as being done by SQLCOM_RENAME_TABLE
      */
2682
      if (alter_info.flags & (ALTER_DROP_PARTITION | ALTER_RENAME))
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2683 2684
        priv_needed|= DROP_ACL;

2685 2686
      /* Must be set in the parser */
      DBUG_ASSERT(select_lex->db);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2687
      if (check_access(thd, priv_needed, first_table->db,
Marc Alff's avatar
Marc Alff committed
2688 2689 2690 2691 2692 2693 2694
                       &first_table->grant.privilege,
                       &first_table->grant.m_internal,
                       0, 0) ||
          check_access(thd, INSERT_ACL | CREATE_ACL, select_lex->db,
                       &priv,
                       NULL, /* Do not use first_table->grant with select_lex->db */
                       0, 0) ||
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2695
	  check_merge_table_access(thd, first_table->db,
2696
				   (TABLE_LIST *)
2697
				   create_info.merge_list.first))
2698
	goto error;				/* purecov: inspected */
2699
      if (check_grant(thd, priv_needed, all_tables, FALSE, UINT_MAX, FALSE))
2700 2701 2702 2703 2704 2705 2706 2707
        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;
2708 2709
          if (check_grant(thd, INSERT_ACL | CREATE_ACL, &tmp_table, FALSE,
              UINT_MAX, FALSE))
2710
            goto error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2711
      }
2712

2713
      /* Don't yet allow changing of symlinks with ALTER TABLE */
2714
      if (create_info.data_file_name)
2715 2716 2717
        push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                            WARN_OPTION_IGNORED, ER(WARN_OPTION_IGNORED),
                            "DATA DIRECTORY");
2718
      if (create_info.index_file_name)
2719 2720 2721
        push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                            WARN_OPTION_IGNORED, ER(WARN_OPTION_IGNORED),
                            "INDEX DIRECTORY");
2722
      create_info.data_file_name= create_info.index_file_name= NULL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2723
      /* ALTER TABLE ends previous transaction */
2724
      if (end_active_trans(thd))
2725
	goto error;
2726

2727 2728 2729 2730 2731
      if (!thd->locked_tables &&
          !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      {
        res= 1;
        break;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2732
      }
2733

2734
      thd->enable_slow_log= opt_log_slow_admin_statements;
2735
      res= mysql_alter_table(thd, select_lex->db, lex->name.str,
2736 2737 2738
                             &create_info,
                             first_table,
                             &alter_info,
2739 2740
                             select_lex->order_list.elements,
                             (ORDER *) select_lex->order_list.first,
2741
                             lex->ignore);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2742 2743
      break;
    }
2744
  case SQLCOM_RENAME_TABLE:
2745
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2746
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2747
    TABLE_LIST *table;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2748
    for (table= first_table; table; table= table->next_local->next_local)
2749
    {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2750
      if (check_access(thd, ALTER_ACL | DROP_ACL, table->db,
Marc Alff's avatar
Marc Alff committed
2751 2752 2753 2754 2755 2756 2757
                       &table->grant.privilege,
                       &table->grant.m_internal,
                       0, 0) ||
          check_access(thd, INSERT_ACL | CREATE_ACL, table->next_local->db,
                       &table->next_local->grant.privilege,
                       &table->next_local->grant.m_internal,
                       0, 0))
2758
	goto error;
2759 2760 2761 2762 2763 2764 2765
      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];
2766
      if (check_grant(thd, ALTER_ACL | DROP_ACL, &old_list, FALSE, 1, FALSE) ||
2767 2768
         (!test_all_bits(table->next_local->grant.privilege,
                         INSERT_ACL | CREATE_ACL) &&
2769 2770
          check_grant(thd, INSERT_ACL | CREATE_ACL, &new_list, FALSE, 1,
                      FALSE)))
2771
        goto error;
2772
    }
2773

cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
2774
    if (end_active_trans(thd) || mysql_rename_tables(thd, first_table, 0))
2775
      goto error;
2776
    break;
2777
  }
2778
#ifndef EMBEDDED_LIBRARY
2779 2780
  case SQLCOM_SHOW_BINLOGS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2781 2782
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2783
    goto error;
2784 2785
#else
    {
2786
      if (check_global_access(thd, SUPER_ACL))
2787 2788 2789 2790
	goto error;
      res = show_binlogs(thd);
      break;
    }
peter@mysql.com's avatar
peter@mysql.com committed
2791
#endif
2792
#endif /* EMBEDDED_LIBRARY */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2793
  case SQLCOM_SHOW_CREATE:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2794
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2795
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2796 2797
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2798
    goto error;
2799
#else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2800
    {
2801 2802 2803 2804 2805 2806 2807 2808 2809
     /*
        Access check:
        SHOW CREATE TABLE require any privileges on the table level (ie
        effecting all columns in the table).
        SHOW CREATE VIEW require the SHOW_VIEW and SELECT ACLs on the table
        level.
        NOTE: SHOW_VIEW ACL is checked when the view is created.
      */

2810
      if (lex->only_view)
2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
      {
        if (check_table_access(thd, SELECT_ACL, first_table, FALSE, 1, FALSE))
        {
          my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
                  "SHOW", thd->security_ctx->priv_user,
                  thd->security_ctx->host_or_ip, first_table->alias);
          goto error;
        }

        /* Ignore temporary tables if this is "SHOW CREATE VIEW" */
2821
        first_table->skip_temporary= 1;
2822 2823 2824 2825
      }
      else
      {
        /*
Marc Alff's avatar
Marc Alff committed
2826 2827 2828
          The fact that check_some_access() returned FALSE does not mean that
          access is granted. We need to check if first_table->grant.privilege
          contains any table-specific privilege.
2829
        */
Marc Alff's avatar
Marc Alff committed
2830 2831
        if (check_some_access(thd, SHOW_CREATE_TABLE_ACLS, first_table) ||
            (first_table->grant.privilege & SHOW_CREATE_TABLE_ACLS) == 0)
2832 2833 2834 2835 2836 2837 2838 2839
        {
          my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
                  "SHOW", thd->security_ctx->priv_user,
                  thd->security_ctx->host_or_ip, first_table->alias);
          goto error;
        }
      }

2840
      /* Access is granted. Execute the command.  */
monty@mishka.local's avatar
monty@mishka.local committed
2841
      res= mysqld_show_create(thd, first_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2842 2843
      break;
    }
2844
#endif
2845 2846
  case SQLCOM_CHECKSUM:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2847
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2848 2849
    if (check_table_access(thd, SELECT_ACL, all_tables,
                           FALSE, UINT_MAX, FALSE))
2850
      goto error; /* purecov: inspected */
2851

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2852
    res = mysql_checksum_table(thd, first_table, &lex->check_opt);
2853 2854
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2855
  case SQLCOM_REPAIR:
2856
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2857
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2858
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables,
2859
                           FALSE, UINT_MAX, FALSE))
2860
      goto error; /* purecov: inspected */
2861
    thd->enable_slow_log= opt_log_slow_admin_statements;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2862
    res= mysql_repair_table(thd, first_table, &lex->check_opt);
2863 2864 2865
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2866 2867 2868
      /*
        Presumably, REPAIR and binlog writing doesn't require synchronization
      */
2869
      res= write_bin_log(thd, TRUE, thd->query(), thd->query_length());
2870
    }
2871
    select_lex->table_list.first= (uchar*) first_table;
2872
    lex->query_tables=all_tables;
2873 2874
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2875
  case SQLCOM_CHECK:
2876
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2877
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2878 2879
    if (check_table_access(thd, SELECT_ACL, all_tables,
                           TRUE, UINT_MAX, FALSE))
2880
      goto error; /* purecov: inspected */
2881
    thd->enable_slow_log= opt_log_slow_admin_statements;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2882
    res = mysql_check_table(thd, first_table, &lex->check_opt);
2883
    select_lex->table_list.first= (uchar*) first_table;
2884
    lex->query_tables=all_tables;
2885 2886
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2887 2888
  case SQLCOM_ANALYZE:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2889
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2890
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables,
2891
                           FALSE, UINT_MAX, FALSE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2892
      goto error; /* purecov: inspected */
2893
    thd->enable_slow_log= opt_log_slow_admin_statements;
2894
    res= mysql_analyze_table(thd, first_table, &lex->check_opt);
2895 2896 2897
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2898 2899 2900
      /*
        Presumably, ANALYZE and binlog writing doesn't require synchronization
      */
2901
      res= write_bin_log(thd, TRUE, thd->query(), thd->query_length());
2902
    }
2903
    select_lex->table_list.first= (uchar*) first_table;
2904
    lex->query_tables=all_tables;
2905
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2906
  }
2907

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2908 2909
  case SQLCOM_OPTIMIZE:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2910
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2911
    if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables,
2912
                           FALSE, UINT_MAX, FALSE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2913
      goto error; /* purecov: inspected */
2914
    thd->enable_slow_log= opt_log_slow_admin_statements;
2915
    res= (specialflag & (SPECIAL_SAFE_MODE | SPECIAL_NO_NEW_FUNC)) ?
2916
      mysql_recreate_table(thd, first_table) :
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2917
      mysql_optimize_table(thd, first_table, &lex->check_opt);
2918 2919 2920
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
2921 2922 2923
      /*
        Presumably, OPTIMIZE and binlog writing doesn't require synchronization
      */
2924
      res= write_bin_log(thd, TRUE, thd->query(), thd->query_length());
2925
    }
2926
    select_lex->table_list.first= (uchar*) first_table;
2927
    lex->query_tables=all_tables;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2928 2929 2930
    break;
  }
  case SQLCOM_UPDATE:
2931 2932
  {
    ha_rows found= 0, updated= 0;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2933 2934
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (update_precheck(thd, all_tables))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2935
      break;
2936 2937 2938
    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      goto error;
2939 2940
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
2941
    MYSQL_UPDATE_START(thd->query());
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2942 2943 2944 2945 2946 2947 2948
    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,
2949 2950 2951
                                  lex->duplicates, lex->ignore,
                                  &found, &updated));
    MYSQL_UPDATE_DONE(res, found, updated);
2952
    /* mysql_update return 2 if we need to switch to multi-update */
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2953
    if (up_result != 2)
2954
      break;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2955
    /* Fall through */
2956
  }
2957
  case SQLCOM_UPDATE_MULTI:
2958 2959 2960
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    /* if we switched from normal update, rights are checked */
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
2961
    if (up_result != 2)
2962
    {
2963 2964 2965 2966 2967
      if ((res= multi_update_precheck(thd, all_tables)))
        break;
    }
    else
      res= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2968

2969 2970 2971 2972 2973 2974 2975 2976 2977
    /*
      Protection might have already been risen if its a fall through
      from the SQLCOM_UPDATE case above.
    */
    if (!thd->locked_tables &&
        lex->sql_command == SQLCOM_UPDATE_MULTI &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      goto error;

2978
    res= mysql_multi_update_prepare(thd);
2979

2980
#ifdef HAVE_REPLICATION
2981
    /* Check slave filtering rules */
2982
    if (unlikely(thd->slave_thread && !have_table_map_for_update))
2983
    {
2984 2985
      if (all_tables_not_ok(thd, all_tables))
      {
2986 2987 2988 2989 2990
        if (res!= 0)
        {
          res= 0;             /* don't care of prev failure  */
          thd->clear_error(); /* filters are of highest prior */
        }
2991 2992 2993 2994
        /* we warn the slave SQL thread */
        my_error(ER_SLAVE_IGNORED_TABLE, MYF(0));
        break;
      }
2995 2996
      if (res)
        break;
2997
    }
2998 2999
    else
    {
3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012
#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
3013 3014
    {
      multi_update *result_obj;
3015
      MYSQL_MULTI_UPDATE_START(thd->query());
3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037
      res= mysql_multi_update(thd, all_tables,
                              &select_lex->item_list,
                              &lex->value_list,
                              select_lex->where,
                              select_lex->options,
                              lex->duplicates,
                              lex->ignore,
                              unit,
                              select_lex,
                              &result_obj);
      if (result_obj)
      {
        MYSQL_MULTI_UPDATE_DONE(res, result_obj->num_found(),
                                result_obj->num_updated());
        res= FALSE; /* Ignore errors here */
        delete result_obj;
      }
      else
      {
        MYSQL_MULTI_UPDATE_DONE(1, 0, 0);
      }
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3038
    break;
monty@mysql.com's avatar
monty@mysql.com committed
3039
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3040
  case SQLCOM_REPLACE:
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064
#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);
3065
        (void) mysql_bin_log.write(&ev);        /* error is ignored */
3066 3067 3068 3069 3070
        mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
      }
      DBUG_PRINT("debug", ("Just after generate_incident()"));
    }
#endif
3071 3072
  case SQLCOM_INSERT:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3073
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
monty@mysql.com's avatar
monty@mysql.com committed
3074
    if ((res= insert_precheck(thd, all_tables)))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3075
      break;
3076 3077 3078 3079 3080 3081 3082

    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
    {
      res= 1;
      break;
    }
3083
    MYSQL_INSERT_START(thd->query());
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3084
    res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
monty@mishka.local's avatar
monty@mishka.local committed
3085
		      lex->update_list, lex->value_list,
3086
                      lex->duplicates, lex->ignore);
3087
    MYSQL_INSERT_DONE(res, (ulong) thd->row_count_func);
3088 3089 3090 3091 3092 3093
    /*
      If we have inserted into a VIEW, and the base table has
      AUTO_INCREMENT column, but this column is not accessible through
      a view, then we should restore LAST_INSERT_ID to the value it
      had before the statement.
    */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3094
    if (first_table->view && !first_table->contain_auto_increment)
3095 3096
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
3097

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3098
    break;
3099
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3100 3101 3102
  case SQLCOM_REPLACE_SELECT:
  case SQLCOM_INSERT_SELECT:
  {
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3103
    select_result *sel_result;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3104
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
monty@mishka.local's avatar
monty@mishka.local committed
3105
    if ((res= insert_precheck(thd, all_tables)))
3106
      break;
monty@mysql.com's avatar
monty@mysql.com committed
3107

3108
    /* Fix lock for first table */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3109 3110
    if (first_table->lock_type == TL_WRITE_DELAYED)
      first_table->lock_type= TL_WRITE;
3111

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

3115
    unit->set_limit(select_lex);
3116 3117 3118 3119 3120 3121 3122

    if (! thd->locked_tables &&
        ! (need_start_waiting= ! wait_if_global_read_lock(thd, 0, 1)))
    {
      res= 1;
      break;
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3123
    if (!(res= open_and_lock_tables(thd, all_tables)))
3124
    {
3125
      MYSQL_INSERT_SELECT_START(thd->query());
3126
      /* Skip first table, which is the table we are inserting in */
3127
      TABLE_LIST *second_table= first_table->next_local;
3128
      select_lex->table_list.first= (uchar*) second_table;
3129 3130
      select_lex->context.table_list= 
        select_lex->context.first_name_resolution_table= second_table;
3131
      res= mysql_insert_select_prepare(thd);
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3132 3133 3134 3135 3136 3137 3138
      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)))
3139
      {
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3140
	res= handle_select(thd, lex, sel_result, OPTION_SETUP_TABLES_DONE);
3141 3142 3143 3144 3145 3146 3147 3148 3149
        /*
          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)
        {
3150 3151 3152
          /* INSERT ... SELECT should invalidate only the very first table */
          TABLE_LIST *save_table= first_table->next_local;
          first_table->next_local= 0;
3153
          query_cache_invalidate3(thd, first_table, 1);
3154
          first_table->next_local= save_table;
3155
        }
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3156
        delete sel_result;
3157
      }
3158
      /* revert changes for SP */
3159
      MYSQL_INSERT_SELECT_DONE(res, (ulong) thd->row_count_func);
3160
      select_lex->table_list.first= (uchar*) first_table;
3161
    }
3162 3163 3164 3165 3166 3167
    /*
      If we have inserted into a VIEW, and the base table has
      AUTO_INCREMENT column, but this column is not accessible through
      a view, then we should restore LAST_INSERT_ID to the value it
      had before the statement.
    */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3168
    if (first_table->view && !first_table->contain_auto_increment)
3169 3170
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
3171

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3172 3173
    break;
  }
3174
  case SQLCOM_TRUNCATE:
3175 3176 3177 3178 3179
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3180
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3181
    if (check_one_table_access(thd, DROP_ACL, all_tables))
3182
      goto error;
3183 3184 3185 3186
    /*
      Don't allow this within a transaction because we want to use
      re-generate table
    */
3187
    if (thd->locked_tables || thd->active_transaction())
3188
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3189 3190
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3191 3192
      goto error;
    }
3193 3194
    if (!(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      goto error;
monty@mysql.com's avatar
monty@mysql.com committed
3195
    res= mysql_truncate(thd, first_table, 0);
3196
    break;
3197
  case SQLCOM_DELETE:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3198
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3199 3200
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if ((res= delete_precheck(thd, all_tables)))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3201
      break;
3202 3203
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
3204 3205 3206 3207 3208 3209 3210

    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
    {
      res= 1;
      break;
    }
3211
    MYSQL_DELETE_START(thd->query());
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3212
    res = mysql_delete(thd, all_tables, select_lex->where,
3213
                       &select_lex->order_list,
osku@127.(none)'s avatar
osku@127.(none) committed
3214 3215
                       unit->select_limit_cnt, select_lex->options,
                       FALSE);
3216
    MYSQL_DELETE_DONE(res, (ulong) thd->row_count_func);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3217 3218
    break;
  }
3219
  case SQLCOM_DELETE_MULTI:
3220
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3221
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3222
    TABLE_LIST *aux_tables=
3223
      (TABLE_LIST *)thd->lex->auxiliary_table_list.first;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3224
    multi_delete *del_result;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3225

3226 3227 3228 3229 3230 3231 3232
    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
    {
      res= 1;
      break;
    }

3233
    if ((res= multi_delete_precheck(thd, all_tables)))
3234
      break;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3235

3236
    /* condition will be TRUE on SP re-excuting */
3237 3238
    if (select_lex->item_list.elements != 0)
      select_lex->item_list.empty();
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3239
    if (add_item_to_list(thd, new Item_null()))
3240
      goto error;
3241

3242
    thd_proc_info(thd, "init");
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3243 3244 3245
    if ((res= open_and_lock_tables(thd, all_tables)))
      break;

3246
    MYSQL_MULTI_DELETE_START(thd->query());
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3247
    if ((res= mysql_multi_delete_prepare(thd)))
3248 3249
    {
      MYSQL_MULTI_DELETE_DONE(1, 0);
3250
      goto error;
3251
    }
3252

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3253 3254
    if (!thd->is_fatal_error &&
        (del_result= new multi_delete(aux_tables, lex->table_count)))
3255
    {
3256 3257 3258
      res= mysql_select(thd, &select_lex->ref_pointer_array,
			select_lex->get_table_list(),
			select_lex->with_wild,
3259
			select_lex->item_list,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3260
			select_lex->where,
3261
			0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3262
			(ORDER *)NULL,
3263
			select_lex->options | thd->variables.option_bits |
3264 3265
			SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
                        OPTION_SETUP_TABLES_DONE,
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3266
			del_result, unit, select_lex);
3267
      res|= thd->is_error();
3268
      MYSQL_MULTI_DELETE_DONE(res, del_result->num_deleted());
3269
      if (res)
3270
        del_result->abort();
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
3271
      delete del_result;
3272 3273
    }
    else
3274
    {
3275
      res= TRUE;                                // Error
3276 3277
      MYSQL_MULTI_DELETE_DONE(1, 0);
    }
3278 3279
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3280
  case SQLCOM_DROP_TABLE:
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
3281
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3282
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3283 3284
    if (!lex->drop_temporary)
    {
3285
      if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE))
3286 3287
	goto error;				/* purecov: inspected */
      if (end_active_trans(thd))
3288
        goto error;
3289
    }
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
3290
    else
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3291
    {
3292
      /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
3293
      thd->variables.option_bits|= OPTION_KEEP_LOG;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3294
    }
3295
    /* DDL and binlog write order protected by LOCK_open */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3296 3297
    res= mysql_rm_table(thd, first_table, lex->drop_if_exists,
			lex->drop_temporary);
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
3298 3299
  }
  break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3300
  case SQLCOM_SHOW_PROCESSLIST:
3301 3302
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd,PROCESS_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3303
      break;
hf@deer.(none)'s avatar
hf@deer.(none) committed
3304
    mysqld_list_processes(thd,
3305 3306 3307 3308
			  (thd->security_ctx->master_access & PROCESS_ACL ?
                           NullS :
                           thd->security_ctx->priv_user),
                          lex->verbose);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3309
    break;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3310 3311 3312
  case SQLCOM_SHOW_AUTHORS:
    res= mysqld_show_authors(thd);
    break;
3313 3314 3315
  case SQLCOM_SHOW_CONTRIBUTORS:
    res= mysqld_show_contributors(thd);
    break;
3316 3317 3318
  case SQLCOM_SHOW_PRIVILEGES:
    res= mysqld_show_privileges(thd);
    break;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3319
  case SQLCOM_SHOW_ENGINE_LOGS:
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
3320
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3321 3322
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
3323
    goto error;
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
3324 3325
#else
    {
Marc Alff's avatar
Marc Alff committed
3326
      if (check_access(thd, FILE_ACL, any_db, NULL, NULL, 0, 0))
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
3327
	goto error;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3328
      res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS);
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
3329 3330
      break;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3331 3332
#endif
  case SQLCOM_CHANGE_DB:
3333 3334 3335 3336
  {
    LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) };

    if (!mysql_change_db(thd, &db_str, FALSE))
3337
      my_ok(thd);
3338

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3339
    break;
3340
  }
3341

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3342 3343
  case SQLCOM_LOAD:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3344
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3345
    uint privilege= (lex->duplicates == DUP_REPLACE ?
3346 3347
		     INSERT_ACL | DELETE_ACL : INSERT_ACL) |
                    (lex->local_file ? 0 : FILE_ACL);
3348

3349
    if (lex->local_file)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3350
    {
3351
      if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) ||
3352
          !opt_local_infile)
3353
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3354
	my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0));
3355 3356
	goto error;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3357
    }
3358 3359 3360 3361

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

3362 3363 3364 3365
    if (!thd->locked_tables &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      goto error;

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3366
    res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
3367
                    lex->update_list, lex->value_list, lex->duplicates,
3368
                    lex->ignore, (bool) lex->local_file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3369 3370
    break;
  }
3371

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3372
  case SQLCOM_SET_OPTION:
3373 3374
  {
    List<set_var_base> *lex_var_list= &lex->var_list;
3375 3376 3377 3378

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

3379 3380
    if ((check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)
         || open_and_lock_tables(thd, all_tables)))
3381
      goto error;
3382 3383 3384 3385 3386 3387 3388
    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;
3389
      my_ok(thd);
3390
    }
3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402
    else
    {
      /*
        We encountered some sort of error, but no message was sent.
        Send something semi-generic here since we don't know which
        assignment in the list caused the error.
      */
      if (!thd->is_error())
        my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET");
      goto error;
    }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3403
    break;
3404
  }
3405

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3406
  case SQLCOM_UNLOCK_TABLES:
3407 3408 3409 3410 3411 3412
    /*
      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.
    */
3413
    unlock_locked_tables(thd);
3414
    if (thd->variables.option_bits & OPTION_TABLE_LOCK)
3415
    {
3416
      end_active_trans(thd);
3417
      thd->variables.option_bits&= ~OPTION_TABLE_LOCK;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3418 3419
    }
    if (thd->global_read_lock)
3420
      unlock_global_read_lock(thd);
3421
    my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3422 3423
    break;
  case SQLCOM_LOCK_TABLES:
3424
    unlock_locked_tables(thd);
3425
    /* we must end the trasaction first, regardless of anything */
3426
    if (end_active_trans(thd))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3427
      goto error;
3428
    if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, all_tables,
3429
                           FALSE, UINT_MAX, FALSE))
3430
      goto error;
3431 3432 3433
    if (lex->protect_against_global_read_lock &&
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
      goto error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3434
    thd->in_lock_tables=1;
3435
    thd->variables.option_bits |= OPTION_TABLE_LOCK;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3436

3437
    if (!(res= simple_open_n_lock_tables(thd, all_tables)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3438
    {
3439 3440
#ifdef HAVE_QUERY_CACHE
      if (thd->variables.query_cache_wlock_invalidate)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3441
	query_cache.invalidate_locked_for_write(first_table);
3442
#endif /*HAVE_QUERY_CACHE*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3443 3444
      thd->locked_tables=thd->lock;
      thd->lock=0;
3445
      my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3446
    }
3447
    else
3448 3449 3450 3451 3452 3453
    {
      /* 
        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
      */
3454
      ha_autocommit_or_rollback(thd, 1);
3455 3456
      end_active_trans(thd);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3457 3458 3459
    thd->in_lock_tables=0;
    break;
  case SQLCOM_CREATE_DB:
3460
  {
3461 3462 3463 3464 3465 3466
    /*
      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);
3467 3468 3469 3470 3471
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
3472
    char *alias;
3473 3474
    if (!(alias=thd->strmake(lex->name.str, lex->name.length)) ||
        check_db_name(&lex->name))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3475
    {
3476
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3477 3478
      break;
    }
3479 3480 3481
    /*
      If in a slave thread :
      CREATE DATABASE DB was certainly not preceded by USE DB.
3482
      For that reason, db_ok() in sql/slave.cc did not check the
3483 3484 3485
      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.
    */
3486
#ifdef HAVE_REPLICATION
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3487
    if (thd->slave_thread && 
3488 3489
	(!rpl_filter->db_ok(lex->name.str) ||
	 !rpl_filter->db_ok_with_wild_table(lex->name.str)))
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3490
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3491
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3492
      break;
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3493
    }
3494
#endif
Marc Alff's avatar
Marc Alff committed
3495
    if (check_access(thd, CREATE_ACL, lex->name.str, NULL, NULL, 1, 0))
3496
      break;
3497
    res= mysql_create_db(thd,(lower_case_table_names == 2 ? alias :
3498
                              lex->name.str), &create_info, 0);
3499 3500
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3501
  case SQLCOM_DROP_DB:
3502
  {
3503 3504 3505 3506 3507
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
3508
    if (check_db_name(&lex->name))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3509
    {
3510
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3511 3512
      break;
    }
3513 3514 3515 3516 3517 3518 3519
    /*
      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.
    */
3520
#ifdef HAVE_REPLICATION
3521
    if (thd->slave_thread && 
3522 3523
	(!rpl_filter->db_ok(lex->name.str) ||
	 !rpl_filter->db_ok_with_wild_table(lex->name.str)))
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3524
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3525
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3526
      break;
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3527
    }
3528
#endif
Marc Alff's avatar
Marc Alff committed
3529
    if (check_access(thd, DROP_ACL, lex->name.str, NULL, NULL, 1, 0))
3530
      break;
3531 3532
    if (thd->locked_tables || thd->active_transaction())
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3533 3534
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3535 3536
      goto error;
    }
3537
    res= mysql_rm_db(thd, lex->name.str, lex->drop_if_exists, 0);
3538 3539
    break;
  }
3540
  case SQLCOM_ALTER_DB_UPGRADE:
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3541
  {
3542
    LEX_STRING *db= & lex->name;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3543 3544 3545 3546 3547 3548 3549
    if (end_active_trans(thd))
    {
      res= 1;
      break;
    }
#ifdef HAVE_REPLICATION
    if (thd->slave_thread && 
3550 3551
       (!rpl_filter->db_ok(db->str) ||
        !rpl_filter->db_ok_with_wild_table(db->str)))
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3552 3553 3554 3555 3556 3557
    {
      res= 1;
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
      break;
    }
#endif
3558
    if (check_db_name(db))
3559
    {
3560
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
3561 3562
      break;
    }
Marc Alff's avatar
Marc Alff committed
3563 3564 3565
    if (check_access(thd, ALTER_ACL, db->str, NULL, NULL, 1, 0) ||
        check_access(thd, DROP_ACL, db->str, NULL, NULL, 1, 0) ||
        check_access(thd, CREATE_ACL, db->str, NULL, NULL, 1, 0))
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576
    {
      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;
    }
3577 3578

    res= mysql_upgrade_db(thd, db);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3579
    if (!res)
3580
      my_ok(thd);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3581 3582
    break;
  }
3583 3584
  case SQLCOM_ALTER_DB:
  {
3585
    LEX_STRING *db= &lex->name;
3586
    HA_CREATE_INFO create_info(lex->create_info);
3587
    if (check_db_name(db))
3588
    {
3589
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
3590 3591
      break;
    }
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3592 3593 3594
    /*
      If in a slave thread :
      ALTER DATABASE DB may not be preceded by USE DB.
3595
      For that reason, maybe db_ok() in sql/slave.cc did not check the
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3596 3597 3598 3599
      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
3600
    if (thd->slave_thread &&
3601 3602
	(!rpl_filter->db_ok(db->str) ||
	 !rpl_filter->db_ok_with_wild_table(db->str)))
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3603
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3604
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3605 3606 3607
      break;
    }
#endif
Marc Alff's avatar
Marc Alff committed
3608
    if (check_access(thd, ALTER_ACL, db->str, NULL, NULL, 1, 0))
3609 3610 3611
      break;
    if (thd->locked_tables || thd->active_transaction())
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3612 3613
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3614 3615
      goto error;
    }
3616
    res= mysql_alter_db(thd, db->str, &create_info);
3617 3618
    break;
  }
3619 3620
  case SQLCOM_SHOW_CREATE_DB:
  {
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
3621 3622
    DBUG_EXECUTE_IF("4x_server_emul",
                    my_error(ER_UNKNOWN_ERROR, MYF(0)); goto error;);
3623
    if (check_db_name(&lex->name))
3624
    {
3625
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
3626 3627
      break;
    }
3628
    res= mysqld_show_create_db(thd, lex->name.str, &lex->create_info);
3629 3630
    break;
  }
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3631 3632
  case SQLCOM_CREATE_EVENT:
  case SQLCOM_ALTER_EVENT:
3633
  #ifdef HAVE_EVENT_SCHEDULER
3634
  do
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3635
  {
3636
    DBUG_ASSERT(lex->event_parse_data);
3637 3638 3639 3640 3641 3642
    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;
    }
3643 3644 3645 3646 3647

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

3648 3649
    switch (lex->sql_command) {
    case SQLCOM_CREATE_EVENT:
3650 3651 3652 3653
    {
      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);
3654
      break;
3655
    }
3656
    case SQLCOM_ALTER_EVENT:
3657 3658 3659
      res= Events::update_event(thd, lex->event_parse_data,
                                lex->spname ? &lex->spname->m_db : NULL,
                                lex->spname ? &lex->spname->m_name : NULL);
3660
      break;
3661 3662
    default:
      DBUG_ASSERT(0);
3663
    }
3664
    DBUG_PRINT("info",("DDL error code=%d", res));
3665
    if (!res)
3666
      my_ok(thd);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3667

3668 3669 3670 3671 3672 3673
  } while (0);
  /* Don't do it, if we are inside a SP */
  if (!thd->spcont)
  {
    delete lex->sphead;
    lex->sphead= NULL;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3674
  }
3675 3676
  /* lex->unit.cleanup() is called outside, no need to call it here */
  break;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
3677
  case SQLCOM_SHOW_CREATE_EVENT:
3678 3679 3680 3681 3682 3683 3684
    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)))
3685
      my_ok(thd);
3686
    break;
3687 3688 3689 3690
#else
    my_error(ER_NOT_SUPPORTED_YET,MYF(0),"embedded server");
    break;
#endif
monty@mysql.com's avatar
monty@mysql.com committed
3691
  case SQLCOM_CREATE_FUNCTION:                  // UDF function
monty@mysql.com's avatar
monty@mysql.com committed
3692
  {
Marc Alff's avatar
Marc Alff committed
3693
    if (check_access(thd, INSERT_ACL, "mysql", NULL, NULL, 1, 0))
monty@mysql.com's avatar
monty@mysql.com committed
3694
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3695
#ifdef HAVE_DLOPEN
3696
    if (!(res = mysql_create_function(thd, &lex->udf)))
3697
      my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3698
#else
hf@deer.(none)'s avatar
hf@deer.(none) committed
3699
    my_error(ER_CANT_OPEN_LIBRARY, MYF(0), lex->udf.dl, 0, "feature disabled");
3700
    res= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3701 3702
#endif
    break;
monty@mysql.com's avatar
monty@mysql.com committed
3703
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
3704
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3705 3706
  case SQLCOM_CREATE_USER:
  {
Marc Alff's avatar
Marc Alff committed
3707
    if (check_access(thd, INSERT_ACL, "mysql", NULL, NULL, 1, 1) &&
3708
        check_global_access(thd,CREATE_USER_ACL))
3709
      break;
3710 3711
    if (end_active_trans(thd))
      goto error;
3712
    /* Conditionally writes to binlog */
3713
    if (!(res= mysql_create_user(thd, lex->users_list)))
3714
      my_ok(thd);
3715 3716
    break;
  }
3717 3718
  case SQLCOM_DROP_USER:
  {
Marc Alff's avatar
Marc Alff committed
3719
    if (check_access(thd, DELETE_ACL, "mysql", NULL, NULL, 1, 1) &&
3720
        check_global_access(thd,CREATE_USER_ACL))
3721
      break;
3722 3723
    if (end_active_trans(thd))
      goto error;
3724
    /* Conditionally writes to binlog */
3725
    if (!(res= mysql_drop_user(thd, lex->users_list)))
3726
      my_ok(thd);
3727 3728 3729 3730
    break;
  }
  case SQLCOM_RENAME_USER:
  {
Marc Alff's avatar
Marc Alff committed
3731
    if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) &&
3732
        check_global_access(thd,CREATE_USER_ACL))
3733
      break;
3734 3735
    if (end_active_trans(thd))
      goto error;
3736
    /* Conditionally writes to binlog */
3737
    if (!(res= mysql_rename_user(thd, lex->users_list)))
3738
      my_ok(thd);
3739 3740 3741 3742
    break;
  }
  case SQLCOM_REVOKE_ALL:
  {
3743 3744
    if (end_active_trans(thd))
      goto error;
Marc Alff's avatar
Marc Alff committed
3745
    if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) &&
3746
        check_global_access(thd,CREATE_USER_ACL))
3747
      break;
3748
    /* Conditionally writes to binlog */
3749
    if (!(res = mysql_revoke_all(thd, lex->users_list)))
3750
      my_ok(thd);
3751 3752
    break;
  }
3753 3754 3755
  case SQLCOM_REVOKE:
  case SQLCOM_GRANT:
  {
3756 3757 3758
    if (end_active_trans(thd))
      goto error;

3759
    if (check_access(thd, lex->grant | lex->grant_tot_col | GRANT_ACL,
Marc Alff's avatar
Marc Alff committed
3760 3761 3762 3763
                     first_table ?  first_table->db : select_lex->db,
                     first_table ? &first_table->grant.privilege : NULL,
                     first_table ? &first_table->grant.m_internal : NULL,
                     first_table ? 0 : 1, 0))
3764 3765
      goto error;

3766
    if (thd->security_ctx->user)              // If not replication
3767
    {
3768
      LEX_USER *user, *tmp_user;
3769

3770
      List_iterator <LEX_USER> user_list(lex->users_list);
3771
      while ((tmp_user= user_list++))
3772
      {
3773 3774
        if (!(user= get_current_user(thd, tmp_user)))
          goto error;
3775 3776 3777 3778 3779 3780 3781 3782
        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);
3783
        if (strcmp(thd->security_ctx->user, user->user.str) ||
3784
            my_strcasecmp(system_charset_info,
3785
                          user->host.str, thd->security_ctx->host_or_ip))
3786 3787
        {
          // TODO: use check_change_password()
3788 3789
          if (is_acl_user(user->host.str, user->user.str) &&
              user->password.str &&
Marc Alff's avatar
Marc Alff committed
3790
              check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1))
3791 3792 3793 3794 3795 3796
          {
            my_message(ER_PASSWORD_NOT_ALLOWED,
                       ER(ER_PASSWORD_NOT_ALLOWED), MYF(0));
            goto error;
          }
        }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3797 3798
      }
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3799
    if (first_table)
3800
    {
3801 3802
      if (lex->type == TYPE_ENUM_PROCEDURE ||
          lex->type == TYPE_ENUM_FUNCTION)
3803 3804 3805 3806
      {
        uint grants= lex->all_privileges 
		   ? (PROC_ACLS & ~GRANT_ACL) | (lex->grant & GRANT_ACL)
		   : lex->grant;
3807
        if (check_grant_routine(thd, grants | GRANT_ACL, all_tables,
3808
                                lex->type == TYPE_ENUM_PROCEDURE, 0))
3809
	  goto error;
3810
        /* Conditionally writes to binlog */
3811 3812 3813
        res= mysql_routine_grant(thd, all_tables,
                                 lex->type == TYPE_ENUM_PROCEDURE, 
                                 lex->users_list, grants,
3814 3815 3816
                                 lex->sql_command == SQLCOM_REVOKE, TRUE);
        if (!res)
          my_ok(thd);
3817 3818 3819
      }
      else
      {
3820
	if (check_grant(thd,(lex->grant | lex->grant_tot_col | GRANT_ACL),
3821
                        all_tables, FALSE, UINT_MAX, FALSE))
3822
	  goto error;
3823
        /* Conditionally writes to binlog */
3824 3825 3826 3827
        res= mysql_table_grant(thd, all_tables, lex->users_list,
			       lex->columns, lex->grant,
			       lex->sql_command == SQLCOM_REVOKE);
      }
3828 3829 3830
    }
    else
    {
3831
      if (lex->columns.elements || lex->type)
3832
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3833 3834
	my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
                   MYF(0));
3835
        goto error;
3836 3837
      }
      else
3838
	/* Conditionally writes to binlog */
3839 3840 3841 3842
	res = mysql_grant(thd, select_lex->db, lex->users_list, lex->grant,
			  lex->sql_command == SQLCOM_REVOKE);
      if (!res)
      {
3843
	if (lex->sql_command == SQLCOM_GRANT)
3844
	{
3845
	  List_iterator <LEX_USER> str_list(lex->users_list);
3846 3847 3848 3849 3850
	  LEX_USER *user, *tmp_user;
	  while ((tmp_user=str_list++))
          {
            if (!(user= get_current_user(thd, tmp_user)))
              goto error;
3851
	    reset_mqh(user, 0);
3852
          }
3853
	}
3854 3855 3856 3857
      }
    }
    break;
  }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3858
#endif /*!NO_EMBEDDED_ACCESS_CHECKS*/
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
3859
  case SQLCOM_RESET:
3860 3861 3862
    /*
      RESET commands are never written to the binary log, so we have to
      initialize this variable because RESET shares the same code as FLUSH
3863 3864 3865 3866
    */
    lex->no_write_to_binlog= 1;
  case SQLCOM_FLUSH:
  {
3867
    bool write_to_binlog;
3868
    if (check_global_access(thd,RELOAD_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3869
      goto error;
3870

3871 3872 3873 3874
    /*
      reload_acl_and_cache() will tell us if we are allowed to write to the
      binlog or not.
    */
3875
    if (!reload_acl_and_cache(thd, lex->type, first_table, &write_to_binlog))
3876 3877 3878 3879 3880
    {
      /*
        We WANT to write and we CAN write.
        ! we write after unlocking the table.
      */
3881 3882 3883
      /*
        Presumably, RESET and binlog writing doesn't require synchronization
      */
3884 3885
      if (!lex->no_write_to_binlog && write_to_binlog)
      {
3886 3887
        if (res= write_bin_log(thd, FALSE, thd->query(), thd->query_length()))
          break;
3888
      }
3889
      my_ok(thd);
3890 3891
    } 
    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3892
    break;
3893
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3894
  case SQLCOM_KILL:
3895 3896 3897
  {
    Item *it= (Item *)lex->value_list.head();

3898 3899 3900 3901 3902 3903 3904
    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;
    }

3905
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1))
3906 3907 3908 3909 3910
    {
      my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY),
		 MYF(0));
      goto error;
    }
3911
    sql_kill(thd, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3912
    break;
3913
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
3914
#ifndef NO_EMBEDDED_ACCESS_CHECKS
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3915
  case SQLCOM_SHOW_GRANTS:
3916 3917 3918 3919
  {
    LEX_USER *grant_user= get_current_user(thd, lex->grant_user);
    if (!grant_user)
      goto error;
3920
    if ((thd->security_ctx->priv_user &&
3921
	 !strcmp(thd->security_ctx->priv_user, grant_user->user.str)) ||
Marc Alff's avatar
Marc Alff committed
3922
        !check_access(thd, SELECT_ACL, "mysql", NULL, NULL, 1, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3923
    {
3924
      res = mysql_show_grants(thd, grant_user);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3925 3926
    }
    break;
3927
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
3928
#endif
3929
  case SQLCOM_HA_OPEN:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3930
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3931
    if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE))
3932
      goto error;
monty@mysql.com's avatar
monty@mysql.com committed
3933
    res= mysql_ha_open(thd, first_table, 0);
3934 3935
    break;
  case SQLCOM_HA_CLOSE:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3936 3937
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    res= mysql_ha_close(thd, first_table);
3938 3939
    break;
  case SQLCOM_HA_READ:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3940
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3941 3942 3943 3944 3945
    /*
      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.
    */
3946
    unit->set_limit(select_lex);
3947
    res= mysql_ha_read(thd, first_table, lex->ha_read_mode, lex->ident.str,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3948
                       lex->insert_list, lex->ha_rkey_mode, select_lex->where,
3949
                       unit->select_limit_cnt, unit->offset_limit_cnt);
3950 3951
    break;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3952
  case SQLCOM_BEGIN:
3953 3954 3955 3956 3957 3958
    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;
    }
3959
    if (begin_trans(thd))
3960
      goto error;
3961 3962 3963 3964 3965
    if (lex->start_transaction_opt & MYSQL_START_TRANS_OPT_WITH_CONS_SNAPSHOT)
    {
      if (ha_start_consistent_snapshot(thd))
        goto error;
    }
3966
    my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3967 3968
    break;
  case SQLCOM_COMMIT:
3969
    if (end_trans(thd, lex->tx_release ? COMMIT_RELEASE :
serg@serg.mylan's avatar
serg@serg.mylan committed
3970
                              lex->tx_chain ? COMMIT_AND_CHAIN : COMMIT))
3971
      goto error;
3972
    my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3973 3974
    break;
  case SQLCOM_ROLLBACK:
3975
    if (end_trans(thd, lex->tx_release ? ROLLBACK_RELEASE :
serg@serg.mylan's avatar
serg@serg.mylan committed
3976
                              lex->tx_chain ? ROLLBACK_AND_CHAIN : ROLLBACK))
3977
      goto error;
3978
    my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3979
    break;
serg@serg.mylan's avatar
serg@serg.mylan committed
3980
  case SQLCOM_RELEASE_SAVEPOINT:
serg@serg.mylan's avatar
serg@serg.mylan committed
3981
  {
3982 3983
    SAVEPOINT *sv;
    for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
serg@serg.mylan's avatar
serg@serg.mylan committed
3984 3985 3986
    {
      if (my_strnncoll(system_charset_info,
                       (uchar *)lex->ident.str, lex->ident.length,
3987
                       (uchar *)sv->name, sv->length) == 0)
serg@serg.mylan's avatar
serg@serg.mylan committed
3988 3989
        break;
    }
3990
    if (sv)
serg@serg.mylan's avatar
serg@serg.mylan committed
3991
    {
3992
      if (ha_release_savepoint(thd, sv))
serg@serg.mylan's avatar
serg@serg.mylan committed
3993
        res= TRUE; // cannot happen
serg@serg.mylan's avatar
serg@serg.mylan committed
3994
      else
3995
        my_ok(thd);
3996
      thd->transaction.savepoints=sv->prev;
serg@serg.mylan's avatar
serg@serg.mylan committed
3997
    }
3998
    else
serg@serg.mylan's avatar
serg@serg.mylan committed
3999
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4000
    break;
serg@serg.mylan's avatar
serg@serg.mylan committed
4001
  }
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4002
  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
serg@serg.mylan's avatar
serg@serg.mylan committed
4003
  {
4004 4005
    SAVEPOINT *sv;
    for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
4006 4007 4008
    {
      if (my_strnncoll(system_charset_info,
                       (uchar *)lex->ident.str, lex->ident.length,
4009
                       (uchar *)sv->name, sv->length) == 0)
4010 4011
        break;
    }
4012
    if (sv)
4013
    {
4014
      if (ha_rollback_to_savepoint(thd, sv))
4015 4016
        res= TRUE; // cannot happen
      else
serg@serg.mylan's avatar
serg@serg.mylan committed
4017
      {
4018
        if (((thd->variables.option_bits & OPTION_KEEP_LOG) || 
4019
             thd->transaction.all.modified_non_trans_table) &&
serg@serg.mylan's avatar
serg@serg.mylan committed
4020 4021 4022 4023
            !thd->slave_thread)
          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                       ER_WARNING_NOT_COMPLETE_ROLLBACK,
                       ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
4024
        my_ok(thd);
serg@serg.mylan's avatar
serg@serg.mylan committed
4025
      }
4026
      thd->transaction.savepoints=sv;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4027 4028
    }
    else
4029
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4030
    break;
4031
  }
4032
  case SQLCOM_SAVEPOINT:
4033
    if (!(thd->variables.option_bits & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN) ||
4034
          thd->in_sub_stmt) || !opt_using_transactions)
4035
      my_ok(thd);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4036
    else
4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071
    {
      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;
4072
        my_ok(thd);
4073 4074
      }
    }
4075
    break;
4076 4077
  case SQLCOM_CREATE_PROCEDURE:
  case SQLCOM_CREATE_SPFUNCTION:
monty@mysql.com's avatar
monty@mysql.com committed
4078
  {
4079
    uint namelen;
4080
    char *name;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4081
    int sp_result= SP_INTERNAL_ERROR;
4082

4083
    DBUG_ASSERT(lex->sphead != 0);
4084
    DBUG_ASSERT(lex->sphead->m_db.str); /* Must be initialized in the parser */
4085 4086 4087 4088
    /*
      Verify that the database name is allowed, optionally
      lowercase it.
    */
4089
    if (check_db_name(&lex->sphead->m_db))
4090
    {
4091
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->sphead->m_db.str);
4092
      goto create_sp_error;
4093 4094
    }

4095
    /*
4096 4097 4098
      Check that a database directory with this name
      exists. Design note: This won't work on virtual databases
      like information_schema.
4099 4100
    */
    if (check_db_dir_existence(lex->sphead->m_db.str))
4101
    {
4102
      my_error(ER_BAD_DB_ERROR, MYF(0), lex->sphead->m_db.str);
4103
      goto create_sp_error;
4104
    }
4105

Marc Alff's avatar
Marc Alff committed
4106 4107
    if (check_access(thd, CREATE_PROC_ACL, lex->sphead->m_db.str,
                     NULL, NULL, 0, 0))
4108
      goto create_sp_error;
4109

4110 4111
    if (end_active_trans(thd))
      goto create_sp_error;
4112 4113

    name= lex->sphead->name(&namelen);
4114
#ifdef HAVE_DLOPEN
monty@mysql.com's avatar
monty@mysql.com committed
4115 4116 4117
    if (lex->sphead->m_type == TYPE_ENUM_FUNCTION)
    {
      udf_func *udf = find_udf(name, namelen);
4118

monty@mysql.com's avatar
monty@mysql.com committed
4119
      if (udf)
4120
      {
4121 4122
        my_error(ER_UDF_EXISTS, MYF(0), name);
        goto create_sp_error;
4123
      }
monty@mysql.com's avatar
monty@mysql.com committed
4124 4125 4126
    }
#endif

4127 4128
    if (sp_process_definer(thd))
      goto create_sp_error;
4129

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4130 4131
    res= (sp_result= lex->sphead->create(thd));
    switch (sp_result) {
4132
    case SP_OK: {
4133
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4134
      /* only add privileges if really neccessary */
4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157

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

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

4158
      if (sp_automatic_privileges && !opt_noacl &&
4159
          check_routine_access(thd, DEFAULT_CREATE_PROC_ACLS,
4160
                               lex->sphead->m_db.str, name,
4161
                               lex->sql_command == SQLCOM_CREATE_PROCEDURE, 1))
4162
      {
4163
        if (sp_grant_privileges(thd, lex->sphead->m_db.str, name,
4164
                                lex->sql_command == SQLCOM_CREATE_PROCEDURE))
4165 4166 4167
          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                       ER_PROC_AUTO_GRANT_FAIL,
                       ER(ER_PROC_AUTO_GRANT_FAIL));
4168
      }
4169 4170 4171 4172 4173 4174 4175 4176 4177 4178

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

4179
#endif
monty@mysql.com's avatar
monty@mysql.com committed
4180
    break;
4181
    }
4182 4183 4184 4185 4186 4187 4188 4189 4190
    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;
4191 4192 4193
    case SP_FLD_STORE_FAILED:
      my_error(ER_CANT_CREATE_SROUTINE, MYF(0), name);
      break;
4194 4195 4196 4197 4198 4199 4200 4201 4202 4203
    default:
      my_error(ER_SP_STORE_FAILED, MYF(0), SP_TYPE_STRING(lex), name);
    break;
    } /* end switch */

    /*
      Capture all errors within this CASE and
      clean up the environment.
    */
create_sp_error:
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4204
    if (sp_result != SP_OK )
4205
      goto error;
4206
    my_ok(thd);
4207 4208
    break; /* break super switch */
  } /* end case group bracket */
4209 4210 4211 4212
  case SQLCOM_CALL:
    {
      sp_head *sp;

4213 4214 4215 4216
      /*
        This will cache all SP and SF and open and lock all tables
        required for execution.
      */
4217 4218
      if (check_table_access(thd, SELECT_ACL, all_tables, FALSE,
                             UINT_MAX, FALSE) ||
4219 4220 4221 4222
	  open_and_lock_tables(thd, all_tables))
       goto error;

      /*
4223 4224
        By this moment all needed SPs should be in cache so no need to look 
        into DB. 
4225
      */
4226 4227
      if (!(sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                                &thd->sp_proc_cache, TRUE)))
4228
      {
4229
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PROCEDURE",
4230
                 lex->spname->m_qname.str);
4231
	goto error;
4232 4233 4234
      }
      else
      {
pem@mysql.comhem.se's avatar
pem@mysql.comhem.se committed
4235
	ha_rows select_limit;
monty@mysql.com's avatar
monty@mysql.com committed
4236 4237
        /* bits that should be cleared in thd->server_status */
	uint bits_to_be_cleared= 0;
4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249
        /*
          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;
        }
4250

4251
	if (sp->m_flags & sp_head::MULTI_RESULTS)
4252
	{
4253
	  if (! (thd->client_capabilities & CLIENT_MULTI_RESULTS))
4254
	  {
4255 4256 4257 4258
            /*
              The client does not support multiple result sets being sent
              back
            */
4259
	    my_error(ER_SP_BADSELECT, MYF(0), sp->m_qname.str);
4260 4261
	    goto error;
	  }
monty@mysql.com's avatar
monty@mysql.com committed
4262 4263 4264 4265 4266 4267 4268
          /*
            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;
4269 4270
	}

4271
	if (check_routine_access(thd, EXECUTE_ACL,
4272
				 sp->m_db.str, sp->m_name.str, TRUE, FALSE))
4273 4274 4275
	{
	  goto error;
	}
pem@mysql.comhem.se's avatar
pem@mysql.comhem.se committed
4276 4277
	select_limit= thd->variables.select_limit;
	thd->variables.select_limit= HA_POS_ERROR;
4278

4279
        /* 
4280
          We never write CALL statements into binlog:
4281 4282 4283 4284 4285
           - 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.
4286
        */
4287
	res= sp->execute_procedure(thd, &lex->value_list);
4288

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

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

4293
	if (!res)
4294 4295
          my_ok(thd, (ulong) (thd->row_count_func < 0 ? 0 :
                              thd->row_count_func));
4296
	else
4297
        {
4298
          DBUG_ASSERT(thd->is_error() || thd->killed);
4299
	  goto error;		// Substatement should already have sent error
4300
        }
4301
      }
4302
      break;
4303 4304
    }
  case SQLCOM_ALTER_PROCEDURE:
4305
  case SQLCOM_ALTER_FUNCTION:
4306
    {
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4307
      int sp_result;
4308 4309 4310 4311
      sp_head *sp;
      st_sp_chistics chistics;

      memcpy(&chistics, &lex->sp_chistics, sizeof(chistics));
4312
      if (lex->sql_command == SQLCOM_ALTER_PROCEDURE)
4313 4314
        sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                            &thd->sp_proc_cache, FALSE);
4315
      else
4316 4317
        sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                            &thd->sp_func_cache, FALSE);
Marc Alff's avatar
Marc Alff committed
4318
      thd->warning_info->opt_clear_warning_info(thd->query_id);
4319
      if (! sp)
4320 4321
      {
	if (lex->spname->m_db.str)
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4322
	  sp_result= SP_KEY_NOT_FOUND;
4323 4324 4325 4326 4327 4328
	else
	{
	  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
	  goto error;
	}
      }
4329 4330
      else
      {
4331 4332 4333
        if (check_routine_access(thd, ALTER_PROC_ACL, sp->m_db.str, 
				 sp->m_name.str,
                                 lex->sql_command == SQLCOM_ALTER_PROCEDURE, 0))
4334
	  goto error;
4335 4336 4337

        if (end_active_trans(thd)) 
          goto error;
4338
	memcpy(&lex->sp_chistics, &chistics, sizeof(lex->sp_chistics));
4339 4340
        if ((sp->m_type == TYPE_ENUM_FUNCTION) &&
            !trust_function_creators &&  mysql_bin_log.is_open() &&
4341 4342 4343 4344 4345 4346
            !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));
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4347
          sp_result= SP_INTERNAL_ERROR;
4348 4349 4350
        }
        else
        {
4351 4352 4353 4354 4355 4356
          /*
            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.
          */
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4357
          /* Conditionally writes to binlog */
anozdrin/alik@ibm's avatar
anozdrin/alik@ibm committed
4358 4359 4360 4361 4362 4363 4364 4365 4366

          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);
4367
        }
4368
      }
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4369
      switch (sp_result)
4370
      {
4371
      case SP_OK:
4372
	my_ok(thd);
4373 4374
	break;
      case SP_KEY_NOT_FOUND:
4375 4376
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4377 4378
	goto error;
      default:
4379 4380
	my_error(ER_SP_CANT_ALTER, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4381
	goto error;
4382
      }
4383
      break;
4384 4385
    }
  case SQLCOM_DROP_PROCEDURE:
4386
  case SQLCOM_DROP_FUNCTION:
4387
    {
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4388
      int sp_result;
4389 4390
      int type= (lex->sql_command == SQLCOM_DROP_PROCEDURE ?
                 TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION);
4391

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4392
      sp_result= sp_routine_exists_in_table(thd, type, lex->spname);
Marc Alff's avatar
Marc Alff committed
4393
      thd->warning_info->opt_clear_warning_info(thd->query_id);
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4394
      if (sp_result == SP_OK)
4395
      {
4396 4397 4398
        char *db= lex->spname->m_db.str;
	char *name= lex->spname->m_name.str;

4399 4400
	if (check_routine_access(thd, ALTER_PROC_ACL, db, name,
                                 lex->sql_command == SQLCOM_DROP_PROCEDURE, 0))
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
4401
          goto error;
4402 4403 4404

        if (end_active_trans(thd)) 
          goto error;
4405
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4406
	if (sp_automatic_privileges && !opt_noacl &&
4407 4408
	    sp_revoke_privileges(thd, db, name, 
                                 lex->sql_command == SQLCOM_DROP_PROCEDURE))
4409 4410 4411 4412 4413
	{
	  push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 
		       ER_PROC_AUTO_REVOKE_FAIL,
		       ER(ER_PROC_AUTO_REVOKE_FAIL));
	}
4414
#endif
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4415
        /* Conditionally writes to binlog */
anozdrin/alik@ibm's avatar
anozdrin/alik@ibm committed
4416 4417 4418 4419 4420 4421

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

        sp_result= sp_drop_routine(thd, type, lex->spname);
4422 4423 4424
      }
      else
      {
4425
#ifdef HAVE_DLOPEN
4426 4427 4428 4429 4430 4431
	if (lex->sql_command == SQLCOM_DROP_FUNCTION)
	{
          udf_func *udf = find_udf(lex->spname->m_name.str,
                                   lex->spname->m_name.length);
          if (udf)
          {
Marc Alff's avatar
Marc Alff committed
4432
            if (check_access(thd, DELETE_ACL, "mysql", NULL, NULL, 1, 0))
4433
	      goto error;
4434

4435
	    if (!(res = mysql_drop_function(thd, &lex->spname->m_name)))
4436
	    {
4437
	      my_ok(thd);
4438
	      break;
4439 4440
	    }
	  }
4441
	}
4442
#endif
4443
	if (lex->spname->m_db.str)
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4444
	  sp_result= SP_KEY_NOT_FOUND;
4445 4446 4447 4448 4449
	else
	{
	  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
	  goto error;
	}
4450
      }
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
4451 4452
      res= sp_result;
      switch (sp_result) {
4453
      case SP_OK:
4454
	my_ok(thd);
4455 4456
	break;
      case SP_KEY_NOT_FOUND:
4457 4458
	if (lex->drop_if_exists)
	{
4459
          res= write_bin_log(thd, TRUE, thd->query(), thd->query_length());
4460
	  push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
4461
			      ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST),
4462
			      SP_COM_STRING(lex), lex->spname->m_name.str);
4463 4464
          if (!res)
            my_ok(thd);
4465 4466
	  break;
	}
4467 4468
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4469 4470
	goto error;
      default:
4471 4472
	my_error(ER_SP_DROP_FAILED, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4473
	goto error;
4474
      }
4475
      break;
4476
    }
4477 4478
  case SQLCOM_SHOW_CREATE_PROC:
    {
anozdrin/alik@ibm's avatar
anozdrin/alik@ibm committed
4479 4480
      if (sp_show_create_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname))
      {
4481 4482
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
4483 4484 4485 4486 4487 4488
	goto error;
      }
      break;
    }
  case SQLCOM_SHOW_CREATE_FUNC:
    {
anozdrin/alik@ibm's avatar
anozdrin/alik@ibm committed
4489 4490
      if (sp_show_create_routine(thd, TYPE_ENUM_FUNCTION, lex->spname))
      {
4491 4492
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
4493 4494 4495 4496
	goto error;
      }
      break;
    }
pem@mysql.com's avatar
pem@mysql.com committed
4497 4498 4499
  case SQLCOM_SHOW_PROC_CODE:
  case SQLCOM_SHOW_FUNC_CODE:
    {
4500
#ifndef DBUG_OFF
pem@mysql.com's avatar
pem@mysql.com committed
4501 4502 4503
      sp_head *sp;

      if (lex->sql_command == SQLCOM_SHOW_PROC_CODE)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4504 4505
        sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                            &thd->sp_proc_cache, FALSE);
pem@mysql.com's avatar
pem@mysql.com committed
4506
      else
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4507 4508
        sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                            &thd->sp_func_cache, FALSE);
4509
      if (!sp || sp->show_routine_code(thd))
4510 4511
      {
        /* We don't distinguish between errors for now */
pem@mysql.com's avatar
pem@mysql.com committed
4512 4513 4514 4515 4516
        my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
        goto error;
      }
      break;
4517 4518 4519 4520
#else
      my_error(ER_FEATURE_DISABLED, MYF(0),
               "SHOW PROCEDURE|FUNCTION CODE", "--with-debug");
      goto error;
pem@mysql.com's avatar
pem@mysql.com committed
4521
#endif // ifndef DBUG_OFF
4522
    }
4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535
  case SQLCOM_SHOW_CREATE_TRIGGER:
    {
      if (lex->spname->m_name.length > NAME_LEN)
      {
        my_error(ER_TOO_LONG_IDENT, MYF(0), lex->spname->m_name.str);
        goto error;
      }

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

      break;
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4536 4537
  case SQLCOM_CREATE_VIEW:
    {
4538 4539 4540 4541
      /*
        Note: SQLCOM_CREATE_VIEW also handles 'ALTER VIEW' commands
        as specified through the thd->lex->create_view_mode flag.
      */
4542 4543 4544
      if (end_active_trans(thd))
        goto error;

4545
      res= mysql_create_view(thd, first_table, thd->lex->create_view_mode);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4546 4547 4548 4549
      break;
    }
  case SQLCOM_DROP_VIEW:
    {
4550 4551
      if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE)
          || end_active_trans(thd))
4552
        goto error;
4553 4554
      /* Conditionally writes to binlog. */
      res= mysql_drop_view(thd, first_table, thd->lex->drop_mode);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4555 4556
      break;
    }
4557 4558
  case SQLCOM_CREATE_TRIGGER:
  {
4559 4560 4561
    if (end_active_trans(thd))
      goto error;

4562
    /* Conditionally writes to binlog. */
4563 4564
    res= mysql_create_or_drop_trigger(thd, all_tables, 1);

4565 4566 4567 4568
    break;
  }
  case SQLCOM_DROP_TRIGGER:
  {
4569 4570 4571
    if (end_active_trans(thd))
      goto error;

4572
    /* Conditionally writes to binlog. */
4573 4574 4575
    res= mysql_create_or_drop_trigger(thd, all_tables, 0);
    break;
  }
4576
  case SQLCOM_XA_START:
4577 4578
    if (thd->transaction.xid_state.xa_state == XA_IDLE &&
        thd->lex->xa_opt == XA_RESUME)
4579
    {
4580
      if (! thd->transaction.xid_state.xid.eq(thd->lex->xid))
4581 4582 4583 4584
      {
        my_error(ER_XAER_NOTA, MYF(0));
        break;
      }
4585
      thd->transaction.xid_state.xa_state=XA_ACTIVE;
4586
      my_ok(thd);
4587 4588
      break;
    }
serg@serg.mylan's avatar
serg@serg.mylan committed
4589
    if (thd->lex->xa_opt != XA_NONE)
4590
    { /// @todo JOIN is not supported yet.
4591 4592 4593
      my_error(ER_XAER_INVAL, MYF(0));
      break;
    }
4594
    if (thd->transaction.xid_state.xa_state != XA_NOTR)
4595
    {
4596
      my_error(ER_XAER_RMFAIL, MYF(0),
4597
               xa_state_names[thd->transaction.xid_state.xa_state]);
4598 4599 4600 4601 4602 4603 4604
      break;
    }
    if (thd->active_transaction() || thd->locked_tables)
    {
      my_error(ER_XAER_OUTSIDE, MYF(0));
      break;
    }
4605 4606 4607 4608 4609 4610 4611
    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;
4612
    thd->transaction.xid_state.rm_error= 0;
4613 4614
    thd->transaction.xid_state.xid.set(thd->lex->xid);
    xid_cache_insert(&thd->transaction.xid_state);
4615
    thd->transaction.all.modified_non_trans_table= FALSE;
4616
    thd->variables.option_bits= ((thd->variables.option_bits & ~(OPTION_KEEP_LOG)) | OPTION_BEGIN);
4617
    thd->server_status|= SERVER_STATUS_IN_TRANS;
4618
    my_ok(thd);
4619 4620 4621 4622
    break;
  case SQLCOM_XA_END:
    /* fake it */
    if (thd->lex->xa_opt != XA_NONE)
4623
    { /// @todo SUSPEND and FOR MIGRATE are not supported yet.
4624 4625 4626
      my_error(ER_XAER_INVAL, MYF(0));
      break;
    }
4627
    if (thd->transaction.xid_state.xa_state != XA_ACTIVE)
4628
    {
4629
      my_error(ER_XAER_RMFAIL, MYF(0),
4630
               xa_state_names[thd->transaction.xid_state.xa_state]);
4631 4632
      break;
    }
4633
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4634 4635 4636 4637
    {
      my_error(ER_XAER_NOTA, MYF(0));
      break;
    }
4638 4639
    if (xa_trans_rolled_back(&thd->transaction.xid_state))
      break;
4640
    thd->transaction.xid_state.xa_state=XA_IDLE;
4641
    my_ok(thd);
4642 4643
    break;
  case SQLCOM_XA_PREPARE:
4644
    if (thd->transaction.xid_state.xa_state != XA_IDLE)
4645
    {
4646
      my_error(ER_XAER_RMFAIL, MYF(0),
4647
               xa_state_names[thd->transaction.xid_state.xa_state]);
4648 4649
      break;
    }
4650
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4651 4652 4653 4654 4655 4656 4657
    {
      my_error(ER_XAER_NOTA, MYF(0));
      break;
    }
    if (ha_prepare(thd))
    {
      my_error(ER_XA_RBROLLBACK, MYF(0));
4658 4659
      xid_cache_delete(&thd->transaction.xid_state);
      thd->transaction.xid_state.xa_state=XA_NOTR;
4660 4661
      break;
    }
4662
    thd->transaction.xid_state.xa_state=XA_PREPARED;
4663
    my_ok(thd);
4664 4665
    break;
  case SQLCOM_XA_COMMIT:
4666
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4667
    {
4668 4669
      XID_STATE *xs=xid_cache_search(thd->lex->xid);
      if (!xs || xs->in_thd)
4670
        my_error(ER_XAER_NOTA, MYF(0));
4671 4672 4673 4674 4675 4676
      else if (xa_trans_rolled_back(xs))
      {
        ha_commit_or_rollback_by_xid(thd->lex->xid, 0);
        xid_cache_delete(xs);
        break;
      }
serg@serg.mylan's avatar
serg@serg.mylan committed
4677
      else
4678 4679 4680
      {
        ha_commit_or_rollback_by_xid(thd->lex->xid, 1);
        xid_cache_delete(xs);
4681
        my_ok(thd);
4682
      }
4683 4684
      break;
    }
4685 4686 4687 4688 4689
    if (xa_trans_rolled_back(&thd->transaction.xid_state))
    {
      xa_trans_rollback(thd);
      break;
    }
4690
    if (thd->transaction.xid_state.xa_state == XA_IDLE &&
monty@mysql.com's avatar
monty@mysql.com committed
4691
        thd->lex->xa_opt == XA_ONE_PHASE)
4692
    {
4693 4694 4695
      int r;
      if ((r= ha_commit(thd)))
        my_error(r == 1 ? ER_XA_RBROLLBACK : ER_XAER_RMERR, MYF(0));
4696
      else
4697
        my_ok(thd);
4698
    }
4699
    else if (thd->transaction.xid_state.xa_state == XA_PREPARED &&
monty@mysql.com's avatar
monty@mysql.com committed
4700
             thd->lex->xa_opt == XA_NONE)
4701
    {
4702 4703 4704
      if (wait_if_global_read_lock(thd, 0, 0))
      {
        ha_rollback(thd);
4705
        my_error(ER_XAER_RMERR, MYF(0));
4706
      }
4707
      else
4708 4709 4710 4711
      {
        if (ha_commit_one_phase(thd, 1))
          my_error(ER_XAER_RMERR, MYF(0));
        else
4712
          my_ok(thd);
4713 4714
        start_waiting_global_read_lock(thd);
      }
4715 4716 4717
    }
    else
    {
4718
      my_error(ER_XAER_RMFAIL, MYF(0),
4719
               xa_state_names[thd->transaction.xid_state.xa_state]);
4720 4721
      break;
    }
4722
    thd->variables.option_bits&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
4723
    thd->transaction.all.modified_non_trans_table= FALSE;
4724
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
4725 4726
    xid_cache_delete(&thd->transaction.xid_state);
    thd->transaction.xid_state.xa_state=XA_NOTR;
4727 4728
    break;
  case SQLCOM_XA_ROLLBACK:
4729
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4730
    {
4731 4732
      XID_STATE *xs=xid_cache_search(thd->lex->xid);
      if (!xs || xs->in_thd)
4733
        my_error(ER_XAER_NOTA, MYF(0));
serg@serg.mylan's avatar
serg@serg.mylan committed
4734
      else
4735
      {
4736
        bool ok= !xa_trans_rolled_back(xs);
4737 4738
        ha_commit_or_rollback_by_xid(thd->lex->xid, 0);
        xid_cache_delete(xs);
4739
        if (ok)
4740
          my_ok(thd);
4741
      }
4742 4743
      break;
    }
4744
    if (thd->transaction.xid_state.xa_state != XA_IDLE &&
4745 4746
        thd->transaction.xid_state.xa_state != XA_PREPARED &&
        thd->transaction.xid_state.xa_state != XA_ROLLBACK_ONLY)
4747
    {
4748
      my_error(ER_XAER_RMFAIL, MYF(0),
4749
               xa_state_names[thd->transaction.xid_state.xa_state]);
4750 4751
      break;
    }
4752
    if (xa_trans_rollback(thd))
4753 4754
      my_error(ER_XAER_RMERR, MYF(0));
    else
4755
      my_ok(thd);
4756 4757
    break;
  case SQLCOM_XA_RECOVER:
4758
    res= mysql_xa_recover(thd);
4759
    break;
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
4760
  case SQLCOM_ALTER_TABLESPACE:
4761
    if (check_global_access(thd, CREATE_TABLESPACE_ACL))
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
4762 4763
      break;
    if (!(res= mysql_alter_tablespace(thd, lex->alter_tablespace_info)))
4764
      my_ok(thd);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
4765 4766 4767 4768
    break;
  case SQLCOM_INSTALL_PLUGIN:
    if (! (res= mysql_install_plugin(thd, &thd->lex->comment,
                                     &thd->lex->ident)))
4769
      my_ok(thd);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
4770 4771 4772
    break;
  case SQLCOM_UNINSTALL_PLUGIN:
    if (! (res= mysql_uninstall_plugin(thd, &thd->lex->comment)))
4773
      my_ok(thd);
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
4774 4775 4776 4777 4778 4779 4780 4781 4782 4783
    break;
  case SQLCOM_BINLOG_BASE64_EVENT:
  {
#ifndef EMBEDDED_LIBRARY
    mysql_client_binlog_statement(thd);
#else /* EMBEDDED_LIBRARY */
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "embedded");
#endif /* EMBEDDED_LIBRARY */
    break;
  }
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4784 4785 4786 4787 4788
  case SQLCOM_CREATE_SERVER:
  {
    int error;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_CREATE_SERVER"));
4789 4790 4791 4792

    if (check_global_access(thd, SUPER_ACL))
      break;

patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4793 4794
    if ((error= create_server(thd, &lex->server_options)))
    {
4795
      DBUG_PRINT("info", ("problem creating server <%s>",
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4796 4797 4798 4799
                          lex->server_options.server_name));
      my_error(error, MYF(0), lex->server_options.server_name);
      break;
    }
4800
    my_ok(thd, 1);
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4801 4802 4803 4804 4805 4806 4807
    break;
  }
  case SQLCOM_ALTER_SERVER:
  {
    int error;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_ALTER_SERVER"));
4808 4809 4810 4811

    if (check_global_access(thd, SUPER_ACL))
      break;

patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4812 4813
    if ((error= alter_server(thd, &lex->server_options)))
    {
4814
      DBUG_PRINT("info", ("problem altering server <%s>",
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4815 4816 4817 4818
                          lex->server_options.server_name));
      my_error(error, MYF(0), lex->server_options.server_name);
      break;
    }
4819
    my_ok(thd, 1);
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4820 4821 4822 4823 4824 4825 4826
    break;
  }
  case SQLCOM_DROP_SERVER:
  {
    int err_code;
    LEX *lex= thd->lex;
    DBUG_PRINT("info", ("case SQLCOM_DROP_SERVER"));
4827 4828 4829 4830

    if (check_global_access(thd, SUPER_ACL))
      break;

patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4831 4832
    if ((err_code= drop_server(thd, &lex->server_options)))
    {
4833
      if (! lex->drop_if_exists && err_code == ER_FOREIGN_SERVER_DOESNT_EXIST)
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4834 4835 4836 4837 4838 4839 4840
      {
        DBUG_PRINT("info", ("problem dropping server %s",
                            lex->server_options.server_name));
        my_error(err_code, MYF(0), lex->server_options.server_name);
      }
      else
      {
4841
        my_ok(thd, 0);
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4842 4843 4844
      }
      break;
    }
4845
    my_ok(thd, 1);
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
4846 4847
    break;
  }
Marc Alff's avatar
Marc Alff committed
4848 4849 4850 4851 4852
  case SQLCOM_SIGNAL:
  case SQLCOM_RESIGNAL:
    DBUG_ASSERT(lex->m_stmt != NULL);
    res= lex->m_stmt->execute(thd);
    break;
4853
  default:
4854
#ifndef EMBEDDED_LIBRARY
4855
    DBUG_ASSERT(0);                             /* Impossible */
4856
#endif
4857
    my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4858 4859
    break;
  }
4860
  thd_proc_info(thd, "query end");
4861 4862

  /*
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
4863
    Binlog-related cleanup:
4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874
    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);

4875
  /*
4876 4877
    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
4878 4879 4880 4881
    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))
4882
    thd->row_count_func= -1;
4883

4884
  goto finish;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4885 4886

error:
4887 4888
  res= TRUE;

4889
finish:
4890 4891 4892 4893 4894 4895 4896 4897
  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);
  }
4898
  DBUG_RETURN(res || thd->is_error());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4899 4900 4901
}


4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924
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()))
4925
        return 1;                               /* purecov: inspected */
4926 4927 4928 4929 4930 4931 4932
      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);
4933
        thd->lex->unit.print(&str, QT_ORDINARY);
4934 4935 4936 4937
        str.append('\0');
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
                     ER_YES, str.ptr());
      }
4938 4939 4940 4941
      if (res)
        result->abort();
      else
        result->send_eof();
4942 4943 4944 4945 4946
      delete result;
    }
    else
    {
      if (!result && !(result= new select_send()))
4947
        return 1;                               /* purecov: inspected */
4948 4949 4950 4951 4952 4953 4954 4955 4956 4957
      query_cache_store_query(thd, all_tables);
      res= handle_select(thd, lex, result, 0);
      if (result != lex->result)
        delete result;
    }
  }
  return res;
}


4958
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4959
/**
4960
  Check grants for commands which work only with one table.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4961

4962 4963 4964
  @param thd                    Thread handler
  @param privilege              requested privilege
  @param all_tables             global table list of query
4965
  @param no_errors              FALSE/TRUE - report/don't report error to
4966
                            the client (using my_error() call).
4967 4968 4969 4970 4971

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

4974
bool check_single_table_access(THD *thd, ulong privilege, 
4975
                               TABLE_LIST *all_tables, bool no_errors)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4976
{
4977 4978 4979 4980 4981 4982
  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;

4983 4984 4985 4986 4987 4988 4989 4990
  const char *db_name;
  if ((all_tables->view || all_tables->field_translation) &&
      !all_tables->schema_table)
    db_name= all_tables->view_db.str;
  else
    db_name= all_tables->db;

  if (check_access(thd, privilege, db_name,
Marc Alff's avatar
Marc Alff committed
4991 4992 4993
                   &all_tables->grant.privilege,
                   &all_tables->grant.m_internal,
                   0, no_errors))
4994
    goto deny;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4995

4996
  /* Show only 1 table for check_grant */
4997
  if (!(all_tables->belong_to_view &&
4998
        (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) &&
4999
      check_grant(thd, privilege, all_tables, FALSE, 1, no_errors))
5000 5001 5002
    goto deny;

  thd->security_ctx= backup_ctx;
5003 5004 5005 5006 5007 5008 5009
  return 0;

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

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

5014 5015 5016 5017 5018 5019 5020 5021
  @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
5022 5023 5024 5025
*/

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

5029
  /* Check rights on tables of subselects and implictly opened tables */
5030
  TABLE_LIST *subselects_tables, *view= all_tables->view ? all_tables : 0;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5031
  if ((subselects_tables= all_tables->next_global))
monty@mysql.com's avatar
monty@mysql.com committed
5032
  {
5033 5034 5035 5036 5037 5038
    /*
      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)
    {
5039
      if (check_single_table_access (thd, privilege, subselects_tables, FALSE))
5040 5041 5042 5043
        return 1;
      subselects_tables= subselects_tables->next_global;
    }
    if (subselects_tables &&
5044 5045
        (check_table_access(thd, SELECT_ACL, subselects_tables, FALSE,
                            UINT_MAX, FALSE)))
5046
      return 1;
monty@mysql.com's avatar
monty@mysql.com committed
5047 5048
  }
  return 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5049 5050 5051
}


5052
/**
5053 5054 5055 5056 5057 5058
  @brief Compare requested privileges with the privileges acquired from the
    User- and Db-tables.
  @param thd          Thread handler
  @param want_access  The requested access privileges.
  @param db           A pointer to the Db name.
  @param[out] save_priv A pointer to the granted privileges will be stored.
Marc Alff's avatar
Marc Alff committed
5059
  @param grant_internal_info A pointer to the internal grant cache.
5060 5061 5062 5063 5064 5065 5066 5067
  @param dont_check_global_grants True if no global grants are checked.
  @param no_error     True if no errors should be sent to the client.

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

Marc Alff's avatar
Marc Alff committed
5068 5069
  For internal databases (INFORMATION_SCHEMA, PERFORMANCE_SCHEMA),
  additional rules apply, see ACL_internal_schema_access.
5070 5071 5072 5073 5074 5075 5076

  @see check_grant

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5079
bool
5080
check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv,
Marc Alff's avatar
Marc Alff committed
5081 5082
             GRANT_INTERNAL_INFO *grant_internal_info,
             bool dont_check_global_grants, bool no_errors)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5083
{
5084
  Security_context *sctx= thd->security_ctx;
5085
  ulong db_access;
5086

5087 5088 5089 5090 5091
  /*
    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
5092
    if it's database level grant command
5093 5094 5095
    (see SQLCOM_GRANT case, mysql_execute_command() function) and
    set db_is_pattern according to 'dont_check_global_grants' value.
  */
5096
  bool  db_is_pattern= ((want_access & GRANT_ACL) && dont_check_global_grants);
5097
  ulong dummy;
5098 5099
  DBUG_ENTER("check_access");
  DBUG_PRINT("enter",("db: %s  want_access: %lu  master_access: %lu",
5100
                      db ? db : "", want_access, sctx->master_access));
5101

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5102 5103 5104
  if (save_priv)
    *save_priv=0;
  else
Marc Alff's avatar
Marc Alff committed
5105
  {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5106
    save_priv= &dummy;
Marc Alff's avatar
Marc Alff committed
5107 5108
    dummy= 0;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5109

5110
  thd_proc_info(thd, "checking permissions");
5111
  if ((!db || !db[0]) && !thd->db && !dont_check_global_grants)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5112
  {
5113
    DBUG_PRINT("error",("No database"));
5114
    if (!no_errors)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5115 5116
      my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR),
                 MYF(0));                       /* purecov: tested */
5117
    DBUG_RETURN(TRUE);				/* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5118 5119
  }

Marc Alff's avatar
Marc Alff committed
5120
  if ((db != NULL) && (db != any_db))
5121
  {
Marc Alff's avatar
Marc Alff committed
5122 5123 5124
    const ACL_internal_schema_access *access;
    access= get_cached_schema_access(grant_internal_info, db);
    if (access)
5125
    {
Marc Alff's avatar
Marc Alff committed
5126
      switch (access->check(want_access, save_priv))
5127
      {
Marc Alff's avatar
Marc Alff committed
5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147
      case ACL_INTERNAL_ACCESS_GRANTED:
        /*
          All the privileges requested have been granted internally.
          [out] *save_privileges= Internal privileges.
        */
        DBUG_RETURN(FALSE);
      case ACL_INTERNAL_ACCESS_DENIED:
        if (! no_errors)
        {
          my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
                   sctx->priv_user, sctx->priv_host, db);
        }
        DBUG_RETURN(TRUE);
      case ACL_INTERNAL_ACCESS_CHECK_GRANT:
        /*
          Only some of the privilege requested have been granted internally,
          proceed with the remaining bits of the request (want_access).
        */
        want_access&= ~(*save_priv);
        break;
5148
      }
5149 5150 5151
    }
  }

5152
  if ((sctx->master_access & want_access) == want_access)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5153
  {
5154
    /*
5155 5156
      1. If we don't have a global SELECT privilege, we have to get the
      database specific access rights to be able to handle queries of type
5157
      UPDATE t1 SET a=1 WHERE b > 0
5158
      2. Change db access if it isn't current db which is being addressed
5159
    */
Marc Alff's avatar
Marc Alff committed
5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178
    if (!(sctx->master_access & SELECT_ACL))
    {
      if (db && (!thd->db || db_is_pattern || strcmp(db, thd->db)))
        db_access= acl_get(sctx->host, sctx->ip, sctx->priv_user, db,
                           db_is_pattern);
      else
      {
        /* get access for current db */
        db_access= sctx->db_access;
      }
      /*
        The effective privileges are the union of the global privileges
        and the intersection of db- and host-privileges,
        plus the internal privileges.
      */
      *save_priv|= sctx->master_access | db_access;
    }
    else
      *save_priv|= sctx->master_access;
5179
    DBUG_RETURN(FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5180
  }
5181
  if (((want_access & ~sctx->master_access) & ~DB_ACLS) ||
5182
      (! db && dont_check_global_grants))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5183
  {						// We can never grant this
5184
    DBUG_PRINT("error",("No possible access"));
5185
    if (!no_errors)
5186
      my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
5187 5188
               sctx->priv_user,
               sctx->priv_host,
5189 5190 5191
               (thd->password ?
                ER(ER_YES) :
                ER(ER_NO)));                    /* purecov: tested */
5192
    DBUG_RETURN(TRUE);				/* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5193 5194 5195
  }

  if (db == any_db)
5196 5197 5198 5199 5200 5201 5202
  {
    /*
      Access granted; Allow select on *any* db.
      [out] *save_privileges= 0
    */
    DBUG_RETURN(FALSE);
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5203

5204
  if (db && (!thd->db || db_is_pattern || strcmp(db,thd->db)))
5205 5206
    db_access= acl_get(sctx->host, sctx->ip, sctx->priv_user, db,
                       db_is_pattern);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5207
  else
5208
    db_access= sctx->db_access;
5209 5210
  DBUG_PRINT("info",("db_access: %lu  want_access: %lu",
                     db_access, want_access));
5211

5212 5213
  /*
    Save the union of User-table and the intersection between Db-table and
Marc Alff's avatar
Marc Alff committed
5214
    Host-table privileges, with the already saved internal privileges.
5215 5216
  */
  db_access= (db_access | sctx->master_access);
Marc Alff's avatar
Marc Alff committed
5217
  *save_priv|= db_access;
5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232

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

  /*
    Grant access if the requested access is in the intersection of
    host- and db-privileges (as retrieved from the acl cache),
    also grant access if all the requested privileges are in the union of
    TABLES_ACLS and PROC_ACLS; see check_grant.
  */
  if ( (db_access & want_access) == want_access ||
5233
      (!dont_check_global_grants &&
5234 5235 5236 5237
       need_table_or_column_check))
  {
    /*
       Ok; but need to check table- and column privileges.
Marc Alff's avatar
Marc Alff committed
5238
       [out] *save_privileges is (User-priv | (Db-priv & Host-priv) | Internal-priv)
5239 5240 5241
    */
    DBUG_RETURN(FALSE);
  }
5242

5243 5244
  /*
    Access is denied;
Marc Alff's avatar
Marc Alff committed
5245
    [out] *save_privileges is (User-priv | (Db-priv & Host-priv) | Internal-priv)
5246
  */
5247
  DBUG_PRINT("error",("Access denied"));
5248
  if (!no_errors)
5249
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
5250
             sctx->priv_user, sctx->priv_host,
5251 5252
             (db ? db : (thd->db ?
                         thd->db :
5253 5254 5255
                         "unknown")));
  DBUG_RETURN(TRUE);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5256 5257 5258
}


5259 5260
static bool check_show_access(THD *thd, TABLE_LIST *table)
{
Marc Alff's avatar
Marc Alff committed
5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272
  /*
    This is a SHOW command using an INFORMATION_SCHEMA table.
    check_access() has not been called for 'table',
    and SELECT is currently always granted on the I_S, so we automatically
    grant SELECT on table here, to bypass a call to check_access().
    Note that not calling check_access(table) is an optimization,
    which needs to be revisited if the INFORMATION_SCHEMA does
    not always automatically grant SELECT but use the grant tables.
    See Bug#38837 need a way to disable information_schema for security
  */
  table->grant.privilege= SELECT_ACL;

5273
  switch (get_schema_table_idx(table->schema_table)) {
5274 5275
  case SCH_SCHEMATA:
    return (specialflag & SPECIAL_SKIP_SHOW_DB) &&
5276
      check_global_access(thd, SHOW_DB_ACL);
5277 5278 5279 5280 5281

  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
  case SCH_TRIGGERS:
5282 5283 5284
  case SCH_EVENTS:
  {
    const char *dst_db_name= table->schema_select_lex->db;
5285

5286
    DBUG_ASSERT(dst_db_name);
5287

5288
    if (check_access(thd, SELECT_ACL, dst_db_name,
Marc Alff's avatar
Marc Alff committed
5289
                     &thd->col_access, NULL, FALSE, FALSE))
5290
      return TRUE;
5291

5292 5293 5294 5295 5296 5297 5298
    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;
5299 5300
    }

5301 5302 5303
    return FALSE;
  }

5304 5305
  case SCH_COLUMNS:
  case SCH_STATISTICS:
5306 5307 5308
  {
    TABLE_LIST *dst_table;
    dst_table= (TABLE_LIST *) table->schema_select_lex->table_list.first;
5309

5310
    DBUG_ASSERT(dst_table);
5311

5312
    if (check_access(thd, SELECT_ACL, dst_table->db,
Marc Alff's avatar
Marc Alff committed
5313 5314 5315
                     &dst_table->grant.privilege,
                     &dst_table->grant.m_internal,
                     FALSE, FALSE))
5316 5317 5318 5319 5320 5321 5322 5323
          return TRUE; /* Access denied */

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

5325 5326
    /* Access granted */
    return FALSE;
5327 5328
  }
  default:
5329 5330 5331 5332 5333 5334 5335
    break;
  }

  return FALSE;
}


5336

5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364
/**
  @brief Check if the requested privileges exists in either User-, Host- or
    Db-tables.
  @param thd          Thread context
  @param want_access  Privileges requested
  @param tables       List of tables to be compared against
  @param no_errors    Don't report error to the client (using my_error() call).
  @param any_combination_of_privileges_will_do TRUE if any privileges on any
    column combination is enough.
  @param number       Only the first 'number' tables in the linked list are
                      relevant.

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

  @see check_access
  @see check_grant

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

5366 5367 5368 5369
  @return
    @retval FALSE OK
    @retval TRUE  Access denied; But column or routine privileges might need to
      be checked also.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5370 5371
*/

5372
bool
5373 5374 5375
check_table_access(THD *thd, ulong requirements,TABLE_LIST *tables,
		   bool any_combination_of_privileges_will_do,
                   uint number, bool no_errors)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5376
{
5377 5378
  TABLE_LIST *org_tables= tables;
  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
5379
  uint i= 0;
5380
  Security_context *sctx= thd->security_ctx, *backup_ctx= thd->security_ctx;
5381
  /*
5382 5383 5384
    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.
5385
  */
5386
  for (; i < number && tables != first_not_own_table && tables;
5387
       tables= tables->next_global, i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5388
  {
5389
    ulong want_access= requirements;
5390 5391 5392 5393 5394
    if (tables->security_ctx)
      sctx= tables->security_ctx;
    else
      sctx= backup_ctx;

5395 5396 5397 5398 5399
    /*
       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);
5400 5401 5402 5403 5404 5405 5406 5407

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

5408 5409
    DBUG_PRINT("info", ("derived: %d  view: %d", tables->derived != 0,
                        tables->view != 0));
5410
    if (tables->is_anonymous_derived_table() ||
5411 5412
        (tables->table && tables->table->s &&
         (int)tables->table->s->tmp_table))
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
5413
      continue;
5414
    thd->security_ctx= sctx;
Marc Alff's avatar
Marc Alff committed
5415 5416 5417 5418 5419

    if (check_access(thd, want_access, tables->get_db_name(),
                     &tables->grant.privilege,
                     &tables->grant.m_internal,
                     0, no_errors))
5420
      goto deny;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5421
  }
5422
  thd->security_ctx= backup_ctx;
5423 5424 5425
  return check_grant(thd,requirements,org_tables,
                     any_combination_of_privileges_will_do,
                     number, no_errors);
5426 5427 5428
deny:
  thd->security_ctx= backup_ctx;
  return TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5429 5430
}

5431

5432
bool
5433 5434
check_routine_access(THD *thd, ulong want_access,char *db, char *name,
		     bool is_proc, bool no_errors)
5435 5436 5437 5438 5439
{
  TABLE_LIST tables[1];
  
  bzero((char *)tables, sizeof(TABLE_LIST));
  tables->db= db;
5440
  tables->table_name= tables->alias= name;
5441
  
monty@mysql.com's avatar
monty@mysql.com committed
5442 5443 5444 5445 5446
  /*
    The following test is just a shortcut for check_access() (to avoid
    calculating db_access) under the assumption that it's common to
    give persons global right to execute all stored SP (but not
    necessary to create them).
Marc Alff's avatar
Marc Alff committed
5447 5448 5449 5450 5451 5452
    Note that this effectively bypasses the ACL_internal_schema_access checks
    that are implemented for the INFORMATION_SCHEMA and PERFORMANCE_SCHEMA,
    which are located in check_access().
    Since the I_S and P_S do not contain routines, this bypass is ok,
    as long as this code path is not abused to create routines.
    The assert enforce that.
monty@mysql.com's avatar
monty@mysql.com committed
5453
  */
Marc Alff's avatar
Marc Alff committed
5454
  DBUG_ASSERT((want_access & CREATE_PROC_ACL) == 0);
monty@mysql.com's avatar
monty@mysql.com committed
5455
  if ((thd->security_ctx->master_access & want_access) == want_access)
5456
    tables->grant.privilege= want_access;
Marc Alff's avatar
Marc Alff committed
5457 5458 5459 5460
  else if (check_access(thd, want_access, db,
                        &tables->grant.privilege,
                        &tables->grant.m_internal,
                        0, no_errors))
5461 5462
    return TRUE;
  
5463
  return check_grant_routine(thd, want_access, tables, is_proc, no_errors);
5464 5465
}

5466

5467 5468
/**
  Check if the routine has any of the routine privileges.
5469

5470 5471 5472
  @param thd	       Thread handler
  @param db           Database name
  @param name         Routine name
5473

5474
  @retval
5475
    0            ok
5476
  @retval
5477 5478 5479
    1            error
*/

5480 5481
bool check_some_routine_access(THD *thd, const char *db, const char *name,
                               bool is_proc)
5482 5483
{
  ulong save_priv;
5484
  /*
Marc Alff's avatar
Marc Alff committed
5485 5486 5487 5488 5489 5490 5491
    The following test is just a shortcut for check_access() (to avoid
    calculating db_access)
    Note that this effectively bypasses the ACL_internal_schema_access checks
    that are implemented for the INFORMATION_SCHEMA and PERFORMANCE_SCHEMA,
    which are located in check_access().
    Since the I_S and P_S do not contain routines, this bypass is ok,
    as it only opens SHOW_PROC_ACLS.
5492
  */
Marc Alff's avatar
Marc Alff committed
5493 5494 5495
  if (thd->security_ctx->master_access & SHOW_PROC_ACLS)
    return FALSE;
  if (!check_access(thd, SHOW_PROC_ACLS, db, &save_priv, NULL, 0, 1) ||
5496 5497
      (save_priv & SHOW_PROC_ACLS))
    return FALSE;
5498
  return check_routine_level_acl(thd, db, name, is_proc);
5499 5500 5501
}


5502 5503 5504
/*
  Check if the given table has any of the asked privileges

5505 5506
  @param thd		 Thread handler
  @param want_access	 Bitmap of possible privileges to check for
5507

5508
  @retval
5509
    0  ok
5510
  @retval
5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524
    1  error
*/

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

  /* This loop will work as long as we have less than 32 privileges */
  for (access= 1; access < want_access ; access<<= 1)
  {
    if (access & want_access)
    {
      if (!check_access(thd, access, table->db,
Marc Alff's avatar
Marc Alff committed
5525 5526 5527
                        &table->grant.privilege,
                        &table->grant.m_internal,
                        0, 1) &&
5528
           !check_grant(thd, access, table, FALSE, 1, TRUE))
5529 5530 5531 5532 5533 5534 5535
        DBUG_RETURN(0);
    }
  }
  DBUG_PRINT("exit",("no matching access rights"));
  DBUG_RETURN(1);
}

5536
#endif /*NO_EMBEDDED_ACCESS_CHECKS*/
5537

5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570

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

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

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

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

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5571 5572 5573 5574
/****************************************************************************
	Check stack size; Send error if there isn't enough stack to continue
****************************************************************************/

5575 5576
#ifndef EMBEDDED_LIBRARY

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5577 5578 5579 5580 5581 5582
#if STACK_DIRECTION < 0
#define used_stack(A,B) (long) (A - B)
#else
#define used_stack(A,B) (long) (B - A)
#endif

monty@mysql.com's avatar
monty@mysql.com committed
5583 5584 5585 5586
#ifndef DBUG_OFF
long max_stack_used;
#endif

5587 5588
/**
  @note
5589 5590 5591 5592
  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.
5593
*/
5594
bool check_stack_overrun(THD *thd, long margin,
5595
			 uchar *buf __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5596 5597
{
  long stack_used;
5598
  DBUG_ASSERT(thd == current_thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5599
  if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >=
5600
      (long) (my_thread_stack_size - margin))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5601
  {
5602 5603 5604 5605
    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));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5606 5607
    return 1;
  }
monty@mysql.com's avatar
monty@mysql.com committed
5608 5609 5610
#ifndef DBUG_OFF
  max_stack_used= max(max_stack_used, stack_used);
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5611 5612
  return 0;
}
5613
#endif /* EMBEDDED_LIBRARY */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5614 5615 5616 5617

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

5618
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5619
{
5620
  Yacc_state *state= & current_thd->m_parser_state->m_yacc;
5621
  ulong old_info=0;
5622
  DBUG_ASSERT(state);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5623 5624
  if ((uint) *yystacksize >= MY_YACC_MAX)
    return 1;
5625
  if (!state->yacc_yyvs)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5626 5627
    old_info= *yystacksize;
  *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
5628
  if (!(state->yacc_yyvs= (uchar*)
5629
        my_realloc(state->yacc_yyvs,
5630 5631 5632
                   *yystacksize*sizeof(**yyvs),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
      !(state->yacc_yyss= (uchar*)
5633
        my_realloc(state->yacc_yyss,
5634 5635
                   *yystacksize*sizeof(**yyss),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5636 5637
    return 1;
  if (old_info)
5638 5639 5640 5641 5642 5643 5644 5645
  {
    /*
      Only copy the old stack on the first call to my_yyoverflow(),
      when replacing a static stack (YYINITDEPTH) by a dynamic stack.
      For subsequent calls, my_realloc already did preserve the old stack.
    */
    memcpy(state->yacc_yyss, *yyss, old_info*sizeof(**yyss));
    memcpy(state->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5646
  }
5647 5648
  *yyss= (short*) state->yacc_yyss;
  *yyvs= (YYSTYPE*) state->yacc_yyvs;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5649 5650 5651 5652
  return 0;
}


5653
/**
5654 5655
  Reset the part of THD responsible for the state of command
  processing.
5656

5657 5658 5659
  This needs to be called before execution of every statement
  (prepared or conventional).  It is not called by substatements of
  routines.
5660

5661 5662
  @todo Remove mysql_reset_thd_for_next_command and only use the
  member function.
5663

5664 5665
  @todo Call it after we use THD for queries, not before.
*/
5666 5667
void mysql_reset_thd_for_next_command(THD *thd)
{
5668 5669 5670 5671 5672 5673
  thd->reset_for_next_command();
}

void THD::reset_for_next_command()
{
  THD *thd= this;
5674
  DBUG_ENTER("mysql_reset_thd_for_next_command");
5675
  DBUG_ASSERT(!thd->spcont); /* not for substatements of routines */
5676
  DBUG_ASSERT(! thd->in_sub_stmt);
5677
  thd->free_list= 0;
5678
  thd->select_number= 1;
5679 5680 5681 5682
  /*
    Those two lines below are theoretically unneeded as
    THD::cleanup_after_query() should take care of this already.
  */
5683
  thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
5684 5685 5686
  thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;

  thd->query_start_used= 0;
5687
  thd->is_fatal_error= thd->time_zone_used= 0;
5688 5689 5690 5691 5692
  /*
    Clear the status flag that are expected to be cleared at the
    beginning of each SQL statement.
  */
  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
5693 5694 5695 5696 5697
  /*
    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.
  */
5698
  if (!(thd->variables.option_bits & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)))
5699
  {
5700
    thd->variables.option_bits&= ~OPTION_KEEP_LOG;
5701
    thd->transaction.all.modified_non_trans_table= FALSE;
5702
  }
5703
  DBUG_ASSERT(thd->security_ctx== &thd->main_security_ctx);
5704
  thd->thread_specific_used= FALSE;
5705 5706

  if (opt_bin_log)
5707
  {
5708 5709
    reset_dynamic(&thd->user_var_events);
    thd->user_var_events_alloc= thd->mem_root;
5710
  }
5711
  thd->clear_error();
Marc Alff's avatar
Marc Alff committed
5712 5713
  thd->stmt_da->reset_diagnostics_area();
  thd->warning_info->reset_for_next_command();
5714 5715 5716
  thd->rand_used= 0;
  thd->sent_row_count= thd->examined_row_count= 0;

5717
  thd->reset_current_stmt_binlog_format_row();
5718
  thd->binlog_unsafe_warning_flags= 0;
5719

5720
  DBUG_PRINT("debug",
5721
             ("is_current_stmt_binlog_format_row(): %d",
5722
              thd->is_current_stmt_binlog_format_row()));
5723

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5724 5725 5726
  DBUG_VOID_RETURN;
}

5727

5728 5729 5730 5731 5732 5733 5734 5735
/**
  Resets the lex->current_select object.
  @note It is assumed that lex->current_select != NULL

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

5736 5737 5738
void
mysql_init_select(LEX *lex)
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5739
  SELECT_LEX *select_lex= lex->current_select;
5740
  select_lex->init_select();
5741
  lex->wild= 0;
5742 5743
  if (select_lex == &lex->select_lex)
  {
5744
    DBUG_ASSERT(lex->result == 0);
5745 5746
    lex->exchange= 0;
  }
5747 5748
}

5749

5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761
/**
  Used to allocate a new SELECT_LEX object on the current thd mem_root and
  link it into the relevant lists.

  This function is always followed by mysql_init_select.

  @see mysql_init_select

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

5762
bool
5763
mysql_new_select(LEX *lex, bool move_down)
5764
{
5765
  SELECT_LEX *select_lex;
5766
  THD *thd= lex->thd;
5767 5768
  DBUG_ENTER("mysql_new_select");

5769
  if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
5770
    DBUG_RETURN(1);
5771
  select_lex->select_number= ++thd->select_number;
5772
  select_lex->parent_lex= lex; /* Used in init_query. */
5773 5774
  select_lex->init_query();
  select_lex->init_select();
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
5775
  lex->nest_level++;
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
5776 5777 5778 5779 5780
  if (lex->nest_level > (int) MAX_SELECT_NESTING)
  {
    my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
    DBUG_RETURN(1);
  }
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
5781
  select_lex->nest_level= lex->nest_level;
5782 5783 5784
  /*
    Don't evaluate this subquery during statement prepare even if
    it's a constant one. The flag is switched off in the end of
5785
    mysqld_stmt_prepare.
5786
  */
konstantin@mysql.com's avatar
konstantin@mysql.com committed
5787
  if (thd->stmt_arena->is_stmt_prepare())
5788
    select_lex->uncacheable|= UNCACHEABLE_PREPARE;
5789 5790
  if (move_down)
  {
5791
    SELECT_LEX_UNIT *unit;
5792
    lex->subqueries= TRUE;
5793
    /* first select_lex of subselect or derived table */
5794
    if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
5795
      DBUG_RETURN(1);
5796

5797 5798
    unit->init_query();
    unit->init_select();
5799
    unit->thd= thd;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5800
    unit->include_down(lex->current_select);
5801 5802
    unit->link_next= 0;
    unit->link_prev= 0;
5803
    unit->return_to= lex->current_select;
5804
    select_lex->include_down(unit);
5805 5806 5807 5808 5809
    /*
      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;
5810 5811
  }
  else
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5812
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5813 5814
    if (lex->current_select->order_list.first && !lex->current_select->braces)
    {
5815
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY");
5816
      DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5817
    }
5818
    select_lex->include_neighbour(lex->current_select);
5819 5820 5821 5822 5823
    SELECT_LEX_UNIT *unit= select_lex->master_unit();                              
    if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->thd))
      DBUG_RETURN(1);
    select_lex->context.outer_context= 
                unit->first_select()->context.outer_context;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5824
  }
peter@mysql.com's avatar
peter@mysql.com committed
5825

5826
  select_lex->master_unit()->global_parameters= select_lex;
5827
  select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
5828
  lex->current_select= select_lex;
5829 5830 5831 5832 5833
  /*
    in subquery is SELECT query and we allow resolution of names in SELECT
    list
  */
  select_lex->context.resolve_in_select_list= TRUE;
5834
  DBUG_RETURN(0);
5835
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5836

5837
/**
5838 5839
  Create a select to return the same output as 'SELECT @@var_name'.

5840
  Used for SHOW COUNT(*) [ WARNINGS | ERROR].
5841

5842
  This will crash with a core dump if the variable doesn't exists.
5843

5844
  @param var_name		Variable name
5845 5846 5847 5848
*/

void create_select_for_variable(const char *var_name)
{
5849
  THD *thd;
5850
  LEX *lex;
5851
  LEX_STRING tmp, null_lex_string;
5852 5853
  Item *var;
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
5854
  DBUG_ENTER("create_select_for_variable");
5855 5856

  thd= current_thd;
pem@mysql.telia.com's avatar
pem@mysql.telia.com committed
5857
  lex= thd->lex;
5858 5859 5860 5861
  mysql_init_select(lex);
  lex->sql_command= SQLCOM_SELECT;
  tmp.str= (char*) var_name;
  tmp.length=strlen(var_name);
5862
  bzero((char*) &null_lex_string.str, sizeof(null_lex_string));
5863 5864 5865 5866
  /*
    We set the name of Item to @@session.var_name because that then is used
    as the column name in the output.
  */
monty@mysql.com's avatar
monty@mysql.com committed
5867 5868 5869 5870 5871 5872
  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);
  }
5873 5874 5875
  DBUG_VOID_RETURN;
}

5876

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5877 5878
void mysql_init_multi_delete(LEX *lex)
{
5879
  lex->sql_command=  SQLCOM_DELETE_MULTI;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5880
  mysql_init_select(lex);
5881 5882
  lex->select_lex.select_limit= 0;
  lex->unit.select_limit_cnt= HA_POS_ERROR;
5883
  lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list);
5884
  lex->lock_option= TL_READ_DEFAULT;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5885 5886
  lex->query_tables= 0;
  lex->query_tables_last= &lex->query_tables;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5887
}
5888

5889

5890 5891 5892 5893
/*
  When you modify mysql_parse(), you may need to mofify
  mysql_test_parse_for_slave() in this same file.
*/
5894

5895 5896
/**
  Parse a query.
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
5897 5898 5899 5900 5901 5902

  @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.
5903 5904 5905 5906
*/

void mysql_parse(THD *thd, const char *inBuf, uint length,
                 const char ** found_semicolon)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5907
{
5908
  int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5909
  DBUG_ENTER("mysql_parse");
5910 5911 5912

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

5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930
  /*
    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);
5931

5932
  if (query_cache_send_result_to_client(thd, (char*) inBuf, length) <= 0)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5933
  {
5934
    LEX *lex= thd->lex;
5935

5936 5937
    sp_cache_flush_obsolete(&thd->sp_proc_cache);
    sp_cache_flush_obsolete(&thd->sp_func_cache);
5938

5939
    Parser_state parser_state(thd, inBuf, length);
5940

5941
    bool err= parse_sql(thd, & parser_state, NULL);
5942
    *found_semicolon= parser_state.m_lip.found_semicolon;
5943

5944
    if (!err)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5945
    {
hf@deer.(none)'s avatar
hf@deer.(none) committed
5946
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5947
      if (mqh_used && thd->user_connect &&
5948
	  check_mqh(thd, lex->sql_command))
5949 5950 5951 5952
      {
	thd->net.error = 0;
      }
      else
hf@deer.(none)'s avatar
hf@deer.(none) committed
5953
#endif
5954
      {
5955
	if (! thd->is_error())
5956
	{
5957 5958 5959 5960 5961 5962 5963 5964 5965 5966
          /*
            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.
          */
5967 5968 5969 5970
          if (*found_semicolon && (ulong) (*found_semicolon - thd->query()))
            thd->set_query_inner(thd->query(),
                                 (uint32) (*found_semicolon -
                                           thd->query() - 1));
5971
          /* Actually execute the query */
5972 5973 5974 5975 5976
          if (*found_semicolon)
          {
            lex->safe_to_cache_query= 0;
            thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
          }
5977
          lex->set_trg_event_type_for_tables();
5978
          MYSQL_QUERY_EXEC_START(thd->query(),
5979 5980 5981 5982 5983 5984 5985 5986
                                 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);
5987
	}
5988
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5989 5990
    }
    else
5991
    {
5992
      DBUG_ASSERT(thd->is_error());
5993
      DBUG_PRINT("info",("Command aborted. Fatal_error: %d",
5994
			 thd->is_fatal_error));
5995

5996
      query_cache_abort(&thd->query_cache_tls);
5997
    }
5998 5999 6000 6001 6002 6003
    if (thd->lex->sphead)
    {
      delete thd->lex->sphead;
      thd->lex->sphead= 0;
    }
    lex->unit.cleanup();
6004
    thd_proc_info(thd, "freeing items");
6005
    thd->end_statement();
6006
    thd->cleanup_after_query();
6007
    DBUG_ASSERT(thd->change_list.is_empty());
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6008
  }
6009 6010 6011 6012 6013 6014
  else
  {
    /* There are no multi queries in the cache. */
    *found_semicolon= NULL;
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
6015 6016 6017 6018
  DBUG_VOID_RETURN;
}


monty@mysql.com's avatar
monty@mysql.com committed
6019
#ifdef HAVE_REPLICATION
6020 6021 6022 6023
/*
  Usable by the replication SQL thread only: just parse a query to know if it
  can be ignored because of replicate-*-table rules.

6024
  @retval
6025
    0	cannot be ignored
6026
  @retval
6027 6028 6029 6030 6031
    1	can be ignored
*/

bool mysql_test_parse_for_slave(THD *thd, char *inBuf, uint length)
{
6032
  LEX *lex= thd->lex;
6033
  bool error= 0;
monty@mysql.com's avatar
monty@mysql.com committed
6034
  DBUG_ENTER("mysql_test_parse_for_slave");
6035

6036
  Parser_state parser_state(thd, inBuf, length);
6037 6038 6039
  lex_start(thd);
  mysql_reset_thd_for_next_command(thd);

6040
  if (!parse_sql(thd, & parser_state, NULL) &&
6041
      all_tables_not_ok(thd,(TABLE_LIST*) lex->select_lex.table_list.first))
monty@mysql.com's avatar
monty@mysql.com committed
6042
    error= 1;                  /* Ignore question */
6043
  thd->end_statement();
6044
  thd->cleanup_after_query();
monty@mysql.com's avatar
monty@mysql.com committed
6045
  DBUG_RETURN(error);
6046
}
monty@mysql.com's avatar
monty@mysql.com committed
6047
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6048

6049

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

6051 6052 6053 6054 6055 6056
/**
  Store field definition for create.

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

6058
bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum_field_types type,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6059
		       char *length, char *decimals,
6060
		       uint type_modifier,
6061 6062
		       Item *default_value, Item *on_update_value,
                       LEX_STRING *comment,
6063 6064
		       char *change,
                       List<String> *interval_list, CHARSET_INFO *cs,
6065
		       uint uint_geom_type)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6066
{
6067
  register Create_field *new_field;
6068
  LEX  *lex= thd->lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6069 6070
  DBUG_ENTER("add_field_to_list");

6071 6072
  if (check_string_char_length(field_name, "", NAME_CHAR_LEN,
                               system_charset_info, 1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6073
  {
6074
    my_error(ER_TOO_LONG_IDENT, MYF(0), field_name->str); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6075 6076 6077 6078
    DBUG_RETURN(1);				/* purecov: inspected */
  }
  if (type_modifier & PRI_KEY_FLAG)
  {
6079
    Key *key;
6080 6081
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
    key= new Key(Key::PRIMARY, null_lex_str,
6082 6083 6084
                      &default_key_create_info,
                      0, lex->col_list);
    lex->alter_info.key_list.push_back(key);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6085 6086 6087 6088
    lex->col_list.empty();
  }
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
  {
6089
    Key *key;
6090 6091
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
    key= new Key(Key::UNIQUE, null_lex_str,
6092 6093 6094
                 &default_key_create_info, 0,
                 lex->col_list);
    lex->alter_info.key_list.push_back(key);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6095 6096 6097
    lex->col_list.empty();
  }

6098
  if (default_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6099
  {
6100
    /* 
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6101 6102
      Default value should be literal => basic constants =>
      no need fix_fields()
6103 6104 6105
      
      We allow only one function as part of default value - 
      NOW() as default for TIMESTAMP type.
6106
    */
6107 6108
    if (default_value->type() == Item::FUNC_ITEM && 
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
6109
         type == MYSQL_TYPE_TIMESTAMP))
6110
    {
6111
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
6112 6113 6114
      DBUG_RETURN(1);
    }
    else if (default_value->type() == Item::NULL_ITEM)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6115
    {
6116
      default_value= 0;
6117 6118 6119
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
	  NOT_NULL_FLAG)
      {
6120
	my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
6121 6122 6123 6124 6125
	DBUG_RETURN(1);
      }
    }
    else if (type_modifier & AUTO_INCREMENT_FLAG)
    {
6126
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6127 6128 6129
      DBUG_RETURN(1);
    }
  }
6130

6131
  if (on_update_value && type != MYSQL_TYPE_TIMESTAMP)
6132
  {
6133
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
6134 6135
    DBUG_RETURN(1);
  }
6136

6137
  if (!(new_field= new Create_field()) ||
6138
      new_field->init(thd, field_name->str, type, length, decimals, type_modifier,
6139 6140
                      default_value, on_update_value, comment, change,
                      interval_list, cs, uint_geom_type))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6141
    DBUG_RETURN(1);
6142

6143
  lex->alter_info.create_list.push_back(new_field);
6144 6145 6146 6147
  lex->last_field=new_field;
  DBUG_RETURN(0);
}

6148

6149
/** Store position for column in ALTER TABLE .. ADD column. */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6150 6151 6152

void store_position_for_column(const char *name)
{
6153
  current_thd->lex->last_field->after=my_const_cast(char*) (name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6154 6155 6156
}

bool
6157
add_proc_to_list(THD* thd, Item *item)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6158 6159 6160 6161
{
  ORDER *order;
  Item	**item_ptr;

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6162
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6163 6164 6165 6166 6167
    return 1;
  item_ptr = (Item**) (order+1);
  *item_ptr= item;
  order->item=item_ptr;
  order->free_me=0;
6168
  thd->lex->proc_list.link_in_list((uchar*) order,(uchar**) &order->next);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6169 6170 6171 6172
  return 0;
}


6173 6174 6175
/**
  save order by and tables in own lists.
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6176

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6177
bool add_to_list(THD *thd, SQL_LIST &list,Item *item,bool asc)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6178 6179 6180
{
  ORDER *order;
  DBUG_ENTER("add_to_list");
6181
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6182
    DBUG_RETURN(1);
6183 6184
  order->item_ptr= item;
  order->item= &order->item_ptr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6185 6186 6187
  order->asc = asc;
  order->free_me=0;
  order->used=0;
6188
  order->counter_used= 0;
6189
  list.link_in_list((uchar*) order,(uchar**) &order->next);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6190 6191 6192 6193
  DBUG_RETURN(0);
}


6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207
/**
  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
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6208
      0		Error
6209 6210
  @retval
    \#	Pointer to TABLE_LIST element added to the total table list
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6211 6212
*/

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6213 6214
TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
					     Table_ident *table,
6215
					     LEX_STRING *alias,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6216 6217
					     ulong table_options,
					     thr_lock_type lock_type,
6218
					     List<Index_hint> *index_hints_arg,
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6219
                                             LEX_STRING *option)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6220 6221
{
  register TABLE_LIST *ptr;
6222
  TABLE_LIST *previous_table_ref; /* The table preceding the current one. */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6223
  char *alias_str;
6224
  LEX *lex= thd->lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6225
  DBUG_ENTER("add_table_to_list");
6226
  LINT_INIT(previous_table_ref);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6227 6228 6229 6230

  if (!table)
    DBUG_RETURN(0);				// End of memory
  alias_str= alias ? alias->str : table->table.str;
6231 6232
  if (!test(table_options & TL_OPTION_ALIAS) && 
      check_table_name(table->table.str, table->table.length))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6233
  {
6234
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6235 6236
    DBUG_RETURN(0);
  }
6237 6238

  if (table->is_derived_table() == FALSE && table->db.str &&
6239
      check_db_name(&table->db))
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
6240 6241 6242 6243
  {
    my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
    DBUG_RETURN(0);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6244 6245

  if (!alias)					/* Alias is case sensitive */
6246 6247 6248
  {
    if (table->sel)
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6249 6250
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
                 ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
6251 6252
      DBUG_RETURN(0);
    }
6253
    if (!(alias_str= (char*) thd->memdup(alias_str,table->table.length+1)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6254
      DBUG_RETURN(0);
6255
  }
6256
  if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6257
    DBUG_RETURN(0);				/* purecov: inspected */
peter@mysql.com's avatar
peter@mysql.com committed
6258
  if (table->db.str)
6259
  {
6260
    ptr->is_fqtn= TRUE;
6261 6262 6263
    ptr->db= table->db.str;
    ptr->db_length= table->db.length;
  }
6264
  else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
6265
    DBUG_RETURN(0);
6266 6267
  else
    ptr->is_fqtn= FALSE;
peter@mysql.com's avatar
peter@mysql.com committed
6268

6269
  ptr->alias= alias_str;
6270
  ptr->is_alias= alias ? TRUE : FALSE;
6271
  if (lower_case_table_names && table->table.length)
6272
    table->table.length= my_casedn_str(files_charset_info, table->table.str);
6273 6274
  ptr->table_name=table->table.str;
  ptr->table_name_length=table->table.length;
6275
  ptr->lock_type=   lock_type;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6276
  ptr->updating=    test(table_options & TL_OPTION_UPDATING);
6277
  /* TODO: remove TL_OPTION_FORCE_INDEX as it looks like it's not used */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6278
  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6279
  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
6280
  ptr->derived=	    table->sel;
6281
  if (!ptr->derived && is_infoschema_db(ptr->db, ptr->db_length))
6282
  {
6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295
    ST_SCHEMA_TABLE *schema_table;
    if (ptr->updating &&
        /* Special cases which are processed by commands itself */
        lex->sql_command != SQLCOM_CHECK &&
        lex->sql_command != SQLCOM_CHECKSUM)
    {
      my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
               thd->security_ctx->priv_user,
               thd->security_ctx->priv_host,
               INFORMATION_SCHEMA_NAME.str);
      DBUG_RETURN(0);
    }
    schema_table= find_schema_table(thd, ptr->table_name);
6296 6297
    if (!schema_table ||
        (schema_table->hidden && 
gluh@eagle.(none)'s avatar
gluh@eagle.(none) committed
6298
         ((sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0 || 
6299 6300 6301
          /*
            this check is used for show columns|keys from I_S hidden table
          */
6302 6303
          lex->sql_command == SQLCOM_SHOW_FIELDS ||
          lex->sql_command == SQLCOM_SHOW_KEYS)))
6304
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6305
      my_error(ER_UNKNOWN_TABLE, MYF(0),
6306
               ptr->table_name, INFORMATION_SCHEMA_NAME.str);
6307 6308
      DBUG_RETURN(0);
    }
6309
    ptr->schema_table_name= ptr->table_name;
6310 6311
    ptr->schema_table= schema_table;
  }
6312
  ptr->select_lex=  lex->current_select;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6313
  ptr->cacheable_table= 1;
6314
  ptr->index_hints= index_hints_arg;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6315
  ptr->option= option ? option->str : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6316
  /* check that used name is unique */
6317
  if (lock_type != TL_IGNORE)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6318
  {
timour@mysql.com's avatar
timour@mysql.com committed
6319 6320 6321 6322
    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 ;
6323
	 tables ;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6324
	 tables=tables->next_local)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6325
    {
6326 6327
      if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
	  !strcmp(ptr->db, tables->db))
6328
      {
6329
	my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
6330 6331
	DBUG_RETURN(0);				/* purecov: tested */
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6332 6333
    }
  }
6334 6335 6336
  /* Store the table reference preceding the current one. */
  if (table_list.elements > 0)
  {
6337 6338 6339
    /*
      table_list.next points to the last inserted TABLE_LIST->next_local'
      element
6340
      We don't use the offsetof() macro here to avoid warnings from gcc
6341
    */
6342 6343 6344
    previous_table_ref= (TABLE_LIST*) ((char*) table_list.next -
                                       ((char*) &(ptr->next_local) -
                                        (char*) ptr));
6345 6346 6347 6348 6349 6350 6351 6352
    /*
      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;
6353
  }
6354

6355 6356 6357 6358 6359 6360
  /*
    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'.
  */
6361
  table_list.link_in_list((uchar*) ptr, (uchar**) &ptr->next_local);
6362
  ptr->next_name_resolution_table= NULL;
6363
  /* Link table in global list (all used tables) */
6364
  lex->add_to_query_tables(ptr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6365 6366 6367
  DBUG_RETURN(ptr);
}

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

6369 6370
/**
  Initialize a new table list for a nested join.
6371

6372 6373 6374 6375 6376 6377 6378 6379
    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.

6380 6381 6382 6383 6384 6385
  @param thd         current thread

  @retval
    0   if success
  @retval
    1   otherwise
6386 6387 6388 6389 6390 6391 6392
*/

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

6394 6395
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
6396
    DBUG_RETURN(1);
6397
  nested_join= ptr->nested_join=
6398
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
6399

6400 6401 6402
  join_list->push_front(ptr);
  ptr->embedding= embedding;
  ptr->join_list= join_list;
6403
  ptr->alias= (char*) "(nested_join)";
6404 6405 6406 6407 6408 6409 6410
  embedding= ptr;
  join_list= &nested_join->join_list;
  join_list->empty();
  DBUG_RETURN(0);
}


6411 6412
/**
  End a nested join table list.
6413 6414 6415

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

6418 6419 6420 6421 6422
  @param thd         current thread

  @return
    - Pointer to TABLE_LIST element added to the total table list, if success
    - 0, otherwise
6423 6424 6425 6426 6427
*/

TABLE_LIST *st_select_lex::end_nested_join(THD *thd)
{
  TABLE_LIST *ptr;
6428
  NESTED_JOIN *nested_join;
6429
  DBUG_ENTER("end_nested_join");
6430

6431
  DBUG_ASSERT(embedding);
6432 6433 6434
  ptr= embedding;
  join_list= ptr->join_list;
  embedding= ptr->embedding;
6435
  nested_join= ptr->nested_join;
6436 6437 6438 6439 6440 6441 6442 6443 6444
  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;
  }
6445
  else if (nested_join->join_list.elements == 0)
6446 6447
  {
    join_list->pop();
6448
    ptr= 0;                                     // return value
6449
  }
6450 6451 6452 6453
  DBUG_RETURN(ptr);
}


6454 6455
/**
  Nest last join operation.
6456 6457 6458

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

6459
  @param thd         current thread
6460

6461
  @retval
6462
    0  Error
6463 6464
  @retval
    \#  Pointer to TABLE_LIST element created for the new nested join
6465 6466 6467 6468 6469 6470
*/

TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
6471
  List<TABLE_LIST> *embedded_list;
6472
  DBUG_ENTER("nest_last_join");
6473

6474 6475
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
6476
    DBUG_RETURN(0);
6477
  nested_join= ptr->nested_join=
6478
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
6479

6480 6481
  ptr->embedding= embedding;
  ptr->join_list= join_list;
6482
  ptr->alias= (char*) "(nest_last_join)";
6483
  embedded_list= &nested_join->join_list;
6484
  embedded_list->empty();
6485 6486

  for (uint i=0; i < 2; i++)
6487 6488 6489 6490 6491
  {
    TABLE_LIST *table= join_list->pop();
    table->join_list= embedded_list;
    table->embedding= ptr;
    embedded_list->push_back(table);
6492 6493 6494 6495 6496 6497 6498
    if (table->natural_join)
    {
      ptr->is_natural_join= TRUE;
      /*
        If this is a JOIN ... USING, move the list of joined fields to the
        table reference that describes the join.
      */
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6499 6500
      if (prev_join_using)
        ptr->join_using_fields= prev_join_using;
6501
    }
6502 6503 6504 6505 6506 6507 6508
  }
  join_list->push_front(ptr);
  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
  DBUG_RETURN(ptr);
}


6509 6510
/**
  Add a table to the current join list.
6511 6512 6513 6514 6515 6516

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

6517 6518 6519
  @param table       the table to add

  @return
6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532
    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;
}


6533 6534
/**
  Convert a right join into equivalent left join.
6535 6536

    The function takes the current join list t[0],t[1] ... and
6537 6538 6539 6540 6541 6542
    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
6543
  @verbatim
6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554
    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
6555
   @endverbatim
6556

6557
  @param thd         current thread
6558

6559 6560 6561
  @return
    - Pointer to the table representing the inner table, if success
    - 0, otherwise
6562 6563
*/

6564
TABLE_LIST *st_select_lex::convert_right_join()
6565 6566
{
  TABLE_LIST *tab2= join_list->pop();
6567
  TABLE_LIST *tab1= join_list->pop();
6568 6569 6570 6571 6572 6573 6574 6575 6576
  DBUG_ENTER("convert_right_join");

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

  DBUG_RETURN(tab1);
}

6577 6578
/**
  Set lock for all tables in current select level.
6579

6580
  @param lock_type			Lock to set for tables
6581

6582
  @note
6583 6584 6585 6586 6587
    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
*/

6588
void st_select_lex::set_lock_for_tables(thr_lock_type lock_type)
6589 6590 6591 6592 6593
{
  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));
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6594 6595 6596
  for (TABLE_LIST *tables= (TABLE_LIST*) table_list.first;
       tables;
       tables= tables->next_local)
6597 6598 6599 6600 6601 6602 6603
  {
    tables->lock_type= lock_type;
    tables->updating=  for_update;
  }
  DBUG_VOID_RETURN;
}

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

6605 6606
/**
  Create a fake SELECT_LEX for a unit.
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6607 6608 6609 6610

    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
6611
    @verbatim
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6612
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ... 
6613
    @endvarbatim
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6614
    or of the form
6615
    @varbatim
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6616
    (SELECT ... ORDER BY LIMIT n) ORDER BY ...
6617
    @endvarbatim
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6618
  
6619 6620 6621
  @param thd_arg		   thread handle

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

6625
  @retval
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6626
    1     on failure to create the object
6627
  @retval
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6628 6629 6630
    0     on success
*/

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6631
bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg)
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6632 6633 6634 6635
{
  SELECT_LEX *first_sl= first_select();
  DBUG_ENTER("add_fake_select_lex");
  DBUG_ASSERT(!fake_select_lex);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6636

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6637
  if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX()))
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6638 6639 6640 6641
      DBUG_RETURN(1);
  fake_select_lex->include_standalone(this, 
                                      (SELECT_LEX_NODE**)&fake_select_lex);
  fake_select_lex->select_number= INT_MAX;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6642
  fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6643 6644
  fake_select_lex->make_empty_select();
  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
6645 6646
  fake_select_lex->select_limit= 0;

igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6647
  fake_select_lex->context.outer_context=first_sl->context.outer_context;
6648 6649 6650
  /* allow item list resolving in fake select for ORDER BY */
  fake_select_lex->context.resolve_in_select_list= TRUE;
  fake_select_lex->context.select_lex= fake_select_lex;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6651

6652
  if (!is_union())
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6653 6654 6655 6656 6657 6658 6659 6660 6661
  {
    /* 
      This works only for 
      (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
      (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
      just before the parser starts processing order_list
    */ 
    global_parameters= fake_select_lex;
    fake_select_lex->no_table_names_allowed= 1;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6662
    thd_arg->lex->current_select= fake_select_lex;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6663
  }
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6664
  thd_arg->lex->pop_context();
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
6665 6666 6667
  DBUG_RETURN(0);
}

6668

6669
/**
6670 6671
  Push a new name resolution context for a JOIN ... ON clause to the
  context stack of a query block.
6672 6673

    Create a new name resolution context for a JOIN ... ON clause,
6674 6675 6676
    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.
6677

6678 6679 6680 6681 6682
  @param thd       pointer to current thread
  @param left_op   left  operand of the JOIN
  @param right_op  rigth operand of the JOIN

  @retval
6683
    FALSE  if all is OK
6684
  @retval
6685
    TRUE   if a memory allocation error occured
6686 6687
*/

6688 6689 6690
bool
push_new_name_resolution_context(THD *thd,
                                 TABLE_LIST *left_op, TABLE_LIST *right_op)
6691 6692
{
  Name_resolution_context *on_context;
6693
  if (!(on_context= new (thd->mem_root) Name_resolution_context))
6694
    return TRUE;
6695 6696 6697 6698 6699
  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();
6700
  return thd->lex->push_context(on_context);
6701 6702 6703
}


6704
/**
6705 6706 6707 6708
  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.

6709 6710
  @param b     the second operand of a JOIN ... ON
  @param expr  the condition to be added to the ON clause
6711

6712
  @retval
6713
    FALSE  if there was some error
6714
  @retval
6715 6716 6717 6718
    TRUE   if all is OK
*/

void add_join_on(TABLE_LIST *b, Item *expr)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6719
{
6720
  if (expr)
6721
  {
6722
    if (!b->on_expr)
6723
      b->on_expr= expr;
6724 6725
    else
    {
6726 6727 6728 6729 6730 6731
      /*
        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);
6732 6733
    }
    b->on_expr->top_level_item();
6734
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6735 6736 6737
}


6738
/**
6739 6740
  Mark that there is a NATURAL JOIN or JOIN ... USING between two
  tables.
6741

6742 6743 6744 6745 6746 6747 6748 6749 6750 6751
    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
6752
  @verbatim
6753 6754 6755
    SELECT * FROM t1 NATURAL LEFT JOIN t2
     <=>
    SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
6756

6757 6758 6759
    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>)
6760

6761 6762 6763
    SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
     <=>
    SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
6764 6765 6766 6767 6768
   @endverbatim

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

malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6771 6772
void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields,
                      SELECT_LEX *lex)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6773
{
6774
  b->natural_join= a;
malff/marcsql@weblab.(none)'s avatar
malff/marcsql@weblab.(none) committed
6775
  lex->prev_join_using= using_fields;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6776 6777
}

6778

6779
/**
6780 6781
  Reload/resets privileges and the different caches.

6782 6783 6784 6785
  @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.
6786
               
6787 6788 6789 6790 6791 6792 6793 6794
  @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
6795
    @retval !=0  Error; thd->killed is set or thd->is_error() is true
6796 6797
*/

6798 6799
bool reload_acl_and_cache(THD *thd, ulong options, TABLE_LIST *tables,
                          bool *write_to_binlog)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6800 6801 6802
{
  bool result=0;
  select_errors=0;				/* Write if more errors */
6803
  bool tmp_write_to_binlog= 1;
6804

6805
  DBUG_ASSERT(!thd || !thd->in_sub_stmt);
6806

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
6807
#ifndef NO_EMBEDDED_ACCESS_CHECKS
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6808 6809
  if (options & REFRESH_GRANT)
  {
6810 6811 6812 6813 6814 6815
    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)))
6816 6817
    {
      thd->thread_stack= (char*) &tmp_thd;
6818
      thd->store_globals();
6819
    }
6820

6821 6822
    if (thd)
    {
6823 6824
      bool reload_acl_failed= acl_reload(thd);
      bool reload_grants_failed= grant_reload(thd);
Kristofer Pettersson's avatar
Kristofer Pettersson committed
6825
      bool reload_servers_failed= servers_reload(thd);
6826

Kristofer Pettersson's avatar
Kristofer Pettersson committed
6827
      if (reload_acl_failed || reload_grants_failed || reload_servers_failed)
6828
      {
6829
        result= 1;
6830 6831 6832 6833 6834 6835
        /*
          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");
      }
6836
    }
6837

6838 6839 6840 6841 6842 6843 6844
    if (tmp_thd)
    {
      delete tmp_thd;
      /* Remember that we don't have a THD */
      my_pthread_setspecific_ptr(THR_THD,  0);
      thd= 0;
    }
6845
    reset_mqh((LEX_USER *)NULL, TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6846
  }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
6847
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6848 6849
  if (options & REFRESH_LOG)
  {
6850
    /*
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6851
      Flush the normal query log, the update log, the binary log,
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
6852 6853
      the slow query log, the relay log (if it exists) and the log
      tables.
6854
    */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6855

6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879
    options|= REFRESH_BINARY_LOG;
    options|= REFRESH_RELAY_LOG;
    options|= REFRESH_SLOW_LOG;
    options|= REFRESH_GENERAL_LOG;
    options|= REFRESH_ENGINE_LOG;
    options|= REFRESH_ERROR_LOG;
  }

  if (options & REFRESH_ERROR_LOG)
    if (flush_error_log())
      result= 1;

  if ((options & REFRESH_SLOW_LOG) && opt_slow_log)
    logger.flush_slow_log();

  if ((options & REFRESH_GENERAL_LOG) && opt_log)
    logger.flush_general_log();

  if (options & REFRESH_ENGINE_LOG)
    if (ha_flush_logs(NULL))
      result= 1;

  if (options & REFRESH_BINARY_LOG)
  {
6880
    /*
monty@mysql.com's avatar
monty@mysql.com committed
6881 6882 6883 6884
      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)
6885 6886
    */
    tmp_write_to_binlog= 0;
6887
    if (mysql_bin_log.is_open())
6888
      mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
6889 6890 6891
  }
  if (options & REFRESH_RELAY_LOG)
  {
6892
#ifdef HAVE_REPLICATION
Marc Alff's avatar
Marc Alff committed
6893
    mysql_mutex_lock(&LOCK_active_mi);
6894
    rotate_relay_log(active_mi);
Marc Alff's avatar
Marc Alff committed
6895
    mysql_mutex_unlock(&LOCK_active_mi);
6896
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6897
  }
6898
#ifdef HAVE_QUERY_CACHE
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6899 6900
  if (options & REFRESH_QUERY_CACHE_FREE)
  {
6901
    query_cache.pack();				// FLUSH QUERY CACHE
6902
    options &= ~REFRESH_QUERY_CACHE;    // Don't flush cache, just free memory
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6903 6904 6905
  }
  if (options & (REFRESH_TABLES | REFRESH_QUERY_CACHE))
  {
6906
    query_cache.flush();			// RESET QUERY CACHE
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6907
  }
6908
#endif /*HAVE_QUERY_CACHE*/
6909 6910 6911 6912 6913
  /*
    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)) 
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6914
  {
6915
    if ((options & REFRESH_READ_LOCK) && thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6916
    {
6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927
      /*
        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++)
monty@mysql.com's avatar
monty@mysql.com committed
6928
        {
6929
          if ((*lock_p)->type >= TL_WRITE_ALLOW_WRITE)
6930 6931 6932 6933
          {
            my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
            return 1;
          }
monty@mysql.com's avatar
monty@mysql.com committed
6934
        }
6935
      }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
6936 6937 6938 6939
      /*
	Writing to the binlog could cause deadlocks, as we don't log
	UNLOCK TABLES
      */
6940
      tmp_write_to_binlog= 0;
6941
      if (lock_global_read_lock(thd))
6942
	return 1;                               // Killed
Kristofer Pettersson's avatar
Kristofer Pettersson committed
6943
      if (close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ?
6944
                              FALSE : TRUE, TRUE))
6945 6946
          result= 1;
      
6947
      if (make_global_read_lock_block_commit(thd)) // Killed
6948 6949 6950 6951 6952
      {
        /* Don't leave things in a half-locked state */
        unlock_global_read_lock(thd);
        return 1;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6953
    }
6954
    else
6955
    {
Kristofer Pettersson's avatar
Kristofer Pettersson committed
6956
      if (close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ?
6957
                              FALSE : TRUE, FALSE))
6958 6959
        result= 1;
    }
6960
    my_dbopt_cleanup();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6961 6962 6963
  }
  if (options & REFRESH_HOSTS)
    hostname_cache_refresh();
monty@mysql.com's avatar
monty@mysql.com committed
6964
  if (thd && (options & REFRESH_STATUS))
6965
    refresh_status(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6966 6967
  if (options & REFRESH_THREADS)
    flush_thread_cache();
6968
#ifdef HAVE_REPLICATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6969
  if (options & REFRESH_MASTER)
6970
  {
6971
    DBUG_ASSERT(thd);
6972
    tmp_write_to_binlog= 0;
6973
    if (reset_master(thd))
6974
    {
6975
      result=1;
6976
    }
6977
  }
6978
#endif
6979
#ifdef OPENSSL
6980 6981
   if (options & REFRESH_DES_KEY_FILE)
   {
6982 6983
     if (des_key_file && load_des_key_file(des_key_file))
         result= 1;
6984 6985
   }
#endif
6986
#ifdef HAVE_REPLICATION
6987 6988
 if (options & REFRESH_SLAVE)
 {
6989
   tmp_write_to_binlog= 0;
Marc Alff's avatar
Marc Alff committed
6990
   mysql_mutex_lock(&LOCK_active_mi);
6991
   if (reset_slave(thd, active_mi))
6992
     result=1;
Marc Alff's avatar
Marc Alff committed
6993
   mysql_mutex_unlock(&LOCK_active_mi);
6994
 }
6995
#endif
6996
 if (options & REFRESH_USER_RESOURCES)
6997
   reset_mqh((LEX_USER *) NULL, 0);             /* purecov: inspected */
6998
 *write_to_binlog= tmp_write_to_binlog;
6999 7000 7001
 /*
   If the query was killed then this function must fail.
 */
7002
 return result || (thd ? thd->killed : 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7003 7004
}

7005

7006 7007
/**
  kill on thread.
7008

7009 7010 7011
  @param thd			Thread class
  @param id			Thread id
  @param only_kill_query        Should it kill the query or the connection
7012

7013
  @note
7014 7015 7016
    This is written such that we have a short lock on LOCK_thread_count
*/

7017
uint kill_one_thread(THD *thd, ulong id, bool only_kill_query)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7018 7019 7020
{
  THD *tmp;
  uint error=ER_NO_SUCH_THREAD;
7021 7022
  DBUG_ENTER("kill_one_thread");
  DBUG_PRINT("enter", ("id=%lu only_kill=%d", id, only_kill_query));
Marc Alff's avatar
Marc Alff committed
7023
  mysql_mutex_lock(&LOCK_thread_count); // For unlink from list
7024
  I_List_iterator<THD> it(threads);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7025 7026
  while ((tmp=it++))
  {
cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
7027 7028
    if (tmp->command == COM_DAEMON)
      continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7029 7030
    if (tmp->thread_id == id)
    {
Marc Alff's avatar
Marc Alff committed
7031
      mysql_mutex_lock(&tmp->LOCK_thd_data);    // Lock from delete
7032
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7033 7034
    }
  }
Marc Alff's avatar
Marc Alff committed
7035
  mysql_mutex_unlock(&LOCK_thread_count);
7036 7037
  if (tmp)
  {
7038 7039 7040 7041 7042

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

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

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

7052
      If user of both killer and killee are non-NULL, proceed with
7053 7054 7055
      slayage if both are string-equal.
    */

7056
    if ((thd->security_ctx->master_access & SUPER_ACL) ||
7057
        thd->security_ctx->user_matches(tmp->security_ctx))
7058
    {
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
7059
      tmp->awake(only_kill_query ? THD::KILL_QUERY : THD::KILL_CONNECTION);
7060 7061 7062 7063
      error=0;
    }
    else
      error=ER_KILL_DENIED_ERROR;
Marc Alff's avatar
Marc Alff committed
7064
    mysql_mutex_unlock(&tmp->LOCK_thd_data);
7065
  }
7066 7067 7068 7069
  DBUG_PRINT("exit", ("%d", error));
  DBUG_RETURN(error);
}

7070

7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084
/*
  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)))
7085
    my_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7086
  else
7087
    my_error(error, MYF(0), id);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7088 7089
}

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

7091
/** If pointer is not a null pointer, append filename to it. */
7092

cmiller@zippy.(none)'s avatar
cmiller@zippy.(none) committed
7093 7094
bool append_file_to_dir(THD *thd, const char **filename_ptr,
                        const char *table_name)
7095
{
7096
  char buff[FN_REFLEN],*ptr, *end;
7097 7098 7099 7100 7101 7102 7103
  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))
  {
7104
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
7105 7106 7107 7108
    return 1;
  }
  /* Fix is using unix filename format on dos */
  strmov(buff,*filename_ptr);
7109
  end=convert_dirname(buff, *filename_ptr, NullS);
7110
  if (!(ptr= (char*) thd->alloc((size_t) (end-buff) + strlen(table_name)+1)))
7111 7112
    return 1;					// End of memory
  *filename_ptr=ptr;
7113
  strxmov(ptr,buff,table_name,NullS);
7114 7115
  return 0;
}
7116

7117

7118 7119
/**
  Check if the select is a simple select (not an union).
7120

7121
  @retval
7122
    0	ok
7123
  @retval
7124 7125 7126 7127 7128 7129
    1	error	; In this case the error messege is sent to the client
*/

bool check_simple_select()
{
  THD *thd= current_thd;
7130 7131
  LEX *lex= thd->lex;
  if (lex->current_select != &lex->select_lex)
7132 7133
  {
    char command[80];
7134
    Lex_input_stream *lip= & thd->m_parser_state->m_lip;
7135 7136
    strmake(command, lip->yylval->symbol.str,
	    min(lip->yylval->symbol.length, sizeof(command)-1));
7137
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
7138 7139 7140 7141
    return 1;
  }
  return 0;
}
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7142

7143

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7144
Comp_creator *comp_eq_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7145
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7146
  return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7147 7148
}

7149

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7150
Comp_creator *comp_ge_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7151
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7152
  return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7153 7154
}

7155

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7156
Comp_creator *comp_gt_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7157
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7158
  return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7159 7160
}

7161

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7162
Comp_creator *comp_le_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7163
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7164
  return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7165 7166
}

7167

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7168
Comp_creator *comp_lt_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7169
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7170
  return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7171 7172
}

7173

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7174
Comp_creator *comp_ne_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7175
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7176
  return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7177
}
7178 7179


7180 7181
/**
  Construct ALL/ANY/SOME subquery Item.
7182

7183 7184 7185 7186
  @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
7187

7188
  @return
7189 7190 7191 7192 7193 7194 7195
    constructed Item (or 0 if out of memory)
*/
Item * all_any_subquery_creator(Item *left_expr,
				chooser_compare_func_creator cmp,
				bool all,
				SELECT_LEX *select_lex)
{
serg@serg.mylan's avatar
serg@serg.mylan committed
7196
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
7197
    return new Item_in_subselect(left_expr, select_lex);
serg@serg.mylan's avatar
serg@serg.mylan committed
7198 7199

  if ((cmp == &comp_ne_creator) && all)        // <> ALL <=> NOT IN
7200 7201 7202
    return new Item_func_not(new Item_in_subselect(left_expr, select_lex));

  Item_allany_subselect *it=
7203
    new Item_allany_subselect(left_expr, cmp, select_lex, all);
7204
  if (all)
7205
    return it->upper_item= new Item_func_not_all(it);	/* ALL */
7206

7207
  return it->upper_item= new Item_func_nop_all(it);      /* ANY/SOME */
7208
}
7209 7210


7211 7212
/**
  Multi update query pre-check.
7213

7214 7215
  @param thd		Thread handler
  @param tables	Global/local table list (have to be the same)
7216

7217
  @retval
7218
    FALSE OK
7219
  @retval
7220
    TRUE  Error
7221
*/
7222

7223
bool multi_update_precheck(THD *thd, TABLE_LIST *tables)
7224 7225 7226 7227 7228
{
  const char *msg= 0;
  TABLE_LIST *table;
  LEX *lex= thd->lex;
  SELECT_LEX *select_lex= &lex->select_lex;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
7229
  DBUG_ENTER("multi_update_precheck");
7230 7231 7232

  if (select_lex->item_list.elements != lex->value_list.elements)
  {
7233
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
7234
    DBUG_RETURN(TRUE);
7235 7236 7237 7238 7239
  }
  /*
    Ensure that we have UPDATE or SELECT privilege for each table
    The exact privilege is checked in mysql_multi_update()
  */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
7240
  for (table= tables; table; table= table->next_local)
7241
  {
7242 7243 7244
    if (table->derived)
      table->grant.privilege= SELECT_ACL;
    else if ((check_access(thd, UPDATE_ACL, table->db,
Marc Alff's avatar
Marc Alff committed
7245 7246 7247
                           &table->grant.privilege,
                           &table->grant.m_internal,
                           0, 1) ||
7248
              check_grant(thd, UPDATE_ACL, table, FALSE, 1, TRUE)) &&
monty@mysql.com's avatar
monty@mysql.com committed
7249
             (check_access(thd, SELECT_ACL, table->db,
Marc Alff's avatar
Marc Alff committed
7250 7251 7252
                           &table->grant.privilege,
                           &table->grant.m_internal,
                           0, 0) ||
7253
              check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE)))
7254
      DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7255

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
7256
    table->table_in_first_from_clause= 1;
7257
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7258 7259 7260
  /*
    Is there tables of subqueries?
  */
7261
  if (&lex->select_lex != lex->all_selects_list)
7262
  {
7263
    DBUG_PRINT("info",("Checking sub query list"));
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
7264
    for (table= tables; table; table= table->next_global)
7265
    {
7266
      if (!table->table_in_first_from_clause)
7267 7268
      {
	if (check_access(thd, SELECT_ACL, table->db,
Marc Alff's avatar
Marc Alff committed
7269 7270 7271
                         &table->grant.privilege,
                         &table->grant.m_internal,
                         0, 0) ||
7272
	    check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE))
7273
	  DBUG_RETURN(TRUE);
7274 7275 7276 7277 7278 7279
      }
    }
  }

  if (select_lex->order_list.elements)
    msg= "ORDER BY";
7280
  else if (select_lex->select_limit)
7281 7282 7283 7284
    msg= "LIMIT";
  if (msg)
  {
    my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
7285
    DBUG_RETURN(TRUE);
7286
  }
7287
  DBUG_RETURN(FALSE);
7288 7289
}

7290 7291
/**
  Multi delete query pre-check.
7292

7293 7294
  @param thd			Thread handler
  @param tables		Global/local table list
7295

7296
  @retval
7297
    FALSE OK
7298
  @retval
7299
    TRUE  error
7300
*/
7301

7302
bool multi_delete_precheck(THD *thd, TABLE_LIST *tables)
7303 7304 7305
{
  SELECT_LEX *select_lex= &thd->lex->select_lex;
  TABLE_LIST *aux_tables=
7306
    (TABLE_LIST *)thd->lex->auxiliary_table_list.first;
7307
  TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
7308
  DBUG_ENTER("multi_delete_precheck");
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7309

7310 7311
  /* sql_yacc guarantees that tables and aux_tables are not zero */
  DBUG_ASSERT(aux_tables != 0);
7312
  if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE))
7313 7314 7315 7316 7317 7318 7319 7320
    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;
7321
  if (check_table_access(thd, DELETE_ACL, aux_tables, FALSE, UINT_MAX, FALSE))
7322 7323
  {
    thd->lex->query_tables_own_last= save_query_tables_own_last;
7324
    DBUG_RETURN(TRUE);
7325 7326 7327
  }
  thd->lex->query_tables_own_last= save_query_tables_own_last;

7328
  if ((thd->variables.option_bits & OPTION_SAFE_UPDATES) && !select_lex->where)
7329
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7330 7331
    my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
               ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
7332
    DBUG_RETURN(TRUE);
7333
  }
7334 7335 7336 7337
  DBUG_RETURN(FALSE);
}


7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394
/*
  Given a table in the source list, find a correspondent table in the
  table references list.

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

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

  @return Matching table, NULL otherwise.
*/

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

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

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

    if (cmp)
      continue;

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

    match= elem;
  }

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

  DBUG_RETURN(match);
}


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

7399
  @param lex   pointer to LEX representing multi-delete
7400

7401 7402 7403 7404
  @retval
    FALSE   success
  @retval
    TRUE    error
7405 7406 7407 7408 7409 7410 7411 7412 7413 7414
*/

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;

7415
  for (target_tbl= (TABLE_LIST *)lex->auxiliary_table_list.first;
7416
       target_tbl; target_tbl= target_tbl->next_local)
7417
  {
7418
    lex->table_count++;
7419
    /* All tables in aux_tables must be found in FROM PART */
7420
    TABLE_LIST *walk= multi_delete_table_match(lex, target_tbl, tables);
7421
    if (!walk)
7422
      DBUG_RETURN(TRUE);
serg@serg.mylan's avatar
serg@serg.mylan committed
7423 7424 7425 7426 7427
    if (!walk->derived)
    {
      target_tbl->table_name= walk->table_name;
      target_tbl->table_name_length= walk->table_name_length;
    }
serg@serg.mylan's avatar
serg@serg.mylan committed
7428
    walk->updating= target_tbl->updating;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7429
    walk->lock_type= target_tbl->lock_type;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
7430
    target_tbl->correspondent_table= walk;	// Remember corresponding table
7431
  }
7432
  DBUG_RETURN(FALSE);
7433 7434 7435
}


7436 7437
/**
  simple UPDATE query pre-check.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7438

7439 7440
  @param thd		Thread handler
  @param tables	Global table list
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7441

7442
  @retval
7443
    FALSE OK
7444
  @retval
7445
    TRUE  Error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7446
*/
7447

7448
bool update_precheck(THD *thd, TABLE_LIST *tables)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7449 7450 7451 7452
{
  DBUG_ENTER("update_precheck");
  if (thd->lex->select_lex.item_list.elements != thd->lex->value_list.elements)
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7453
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
7454
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7455
  }
7456
  DBUG_RETURN(check_one_table_access(thd, UPDATE_ACL, tables));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7457 7458 7459
}


7460 7461
/**
  simple DELETE query pre-check.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7462

7463 7464
  @param thd		Thread handler
  @param tables	Global table list
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7465

7466
  @retval
7467
    FALSE  OK
7468
  @retval
7469
    TRUE   error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7470
*/
7471

7472
bool delete_precheck(THD *thd, TABLE_LIST *tables)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7473 7474 7475
{
  DBUG_ENTER("delete_precheck");
  if (check_one_table_access(thd, DELETE_ACL, tables))
7476
    DBUG_RETURN(TRUE);
7477
  /* Set privilege for the WHERE clause */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7478
  tables->grant.want_privilege=(SELECT_ACL & ~tables->grant.privilege);
7479
  DBUG_RETURN(FALSE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7480 7481 7482
}


7483 7484
/**
  simple INSERT query pre-check.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7485

7486 7487
  @param thd		Thread handler
  @param tables	Global table list
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7488

7489
  @retval
7490
    FALSE  OK
7491
  @retval
7492
    TRUE   error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7493
*/
7494

bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
7495
bool insert_precheck(THD *thd, TABLE_LIST *tables)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7496 7497 7498 7499
{
  LEX *lex= thd->lex;
  DBUG_ENTER("insert_precheck");

7500 7501 7502 7503
  /*
    Check that we have modify privileges for the first table and
    select privileges for the rest
  */
monty@mysql.com's avatar
monty@mysql.com committed
7504 7505 7506
  ulong privilege= (INSERT_ACL |
                    (lex->duplicates == DUP_REPLACE ? DELETE_ACL : 0) |
                    (lex->value_list.elements ? UPDATE_ACL : 0));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7507 7508

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

7511
  if (lex->update_list.elements != lex->value_list.elements)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7512
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7513
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
7514
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7515
  }
7516
  DBUG_RETURN(FALSE);
7517
}
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7518 7519


7520 7521
/**
  CREATE TABLE query pre-check.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7522

7523 7524 7525
  @param thd			Thread handler
  @param tables		Global table list
  @param create_table	        Table which will be created
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7526

7527
  @retval
7528
    FALSE   OK
7529
  @retval
7530
    TRUE   Error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7531
*/
7532

7533 7534
bool create_table_precheck(THD *thd, TABLE_LIST *tables,
                           TABLE_LIST *create_table)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7535 7536
{
  LEX *lex= thd->lex;
7537 7538
  SELECT_LEX *select_lex= &lex->select_lex;
  ulong want_priv;
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
7539
  bool error= TRUE;                                 // Error message is given
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7540
  DBUG_ENTER("create_table_precheck");
7541

7542 7543 7544 7545 7546
  /*
    Require CREATE [TEMPORARY] privilege on new table; for
    CREATE TABLE ... SELECT, also require INSERT.
  */

7547
  want_priv= ((lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) ?
7548 7549 7550
              CREATE_TMP_ACL : CREATE_ACL) |
             (select_lex->item_list.elements ? INSERT_ACL : 0);

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7551
  if (check_access(thd, want_priv, create_table->db,
Marc Alff's avatar
Marc Alff committed
7552 7553 7554
                   &create_table->grant.privilege,
                   &create_table->grant.m_internal,
                   0, 0) ||
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7555 7556 7557
      check_merge_table_access(thd, create_table->db,
			       (TABLE_LIST *)
			       lex->create_info.merge_list.first))
7558
    goto err;
7559
  if (want_priv != CREATE_TMP_ACL &&
7560
      check_grant(thd, want_priv, create_table, FALSE, 1, FALSE))
7561 7562 7563 7564 7565 7566
    goto err;

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

7567 7568
#ifdef NOT_NECESSARY_TO_CHECK_CREATE_TABLE_EXIST_WHEN_PREPARING_STATEMENT
    /* This code throws an ill error for CREATE TABLE t1 SELECT * FROM t1 */
7569
    /*
7570
      Only do the check for PS, because we on execute we have to check that
monty@mysql.com's avatar
monty@mysql.com committed
7571 7572
      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).
7573
    */
konstantin@mysql.com's avatar
konstantin@mysql.com committed
7574
    if (thd->stmt_arena->is_stmt_prepare_or_first_sp_execute())
7575
    {
monty@mysql.com's avatar
monty@mysql.com committed
7576 7577 7578 7579
      /*
        For temporary tables we don't have to check if the created table exists
      */
      if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) &&
monty@mysql.com's avatar
monty@mysql.com committed
7580
          find_table_in_global_list(tables, create_table->db,
7581
                                    create_table->table_name))
monty@mysql.com's avatar
monty@mysql.com committed
7582
      {
7583
	error= FALSE;
monty@mysql.com's avatar
monty@mysql.com committed
7584 7585 7586
        goto err;
      }
    }
7587
#endif
7588 7589
    if (tables && check_table_access(thd, SELECT_ACL, tables, FALSE,
                                     UINT_MAX, FALSE))
7590 7591
      goto err;
  }
7592 7593
  else if (lex->create_info.options & HA_LEX_CREATE_TABLE_LIKE)
  {
7594
    if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE))
7595 7596
      goto err;
  }
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
7597
  error= FALSE;
7598 7599 7600

err:
  DBUG_RETURN(error);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7601
}
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7602 7603


7604 7605
/**
  negate given expression.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7606

7607 7608
  @param thd  thread handler
  @param expr expression for negation
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7609

7610
  @return
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635
    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);
}
7636

7637 7638 7639
/**
  Set the specified definer to the default value, which is the
  current user in the thread.
7640
 
7641 7642
  @param[in]  thd       thread handler
  @param[out] definer   definer
7643 7644
*/
 
7645
void get_default_definer(THD *thd, LEX_USER *definer)
7646 7647 7648 7649 7650 7651 7652 7653
{
  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);
7654 7655 7656

  definer->password.str= NULL;
  definer->password.length= 0;
7657 7658
}

7659

7660
/**
7661
  Create default definer for the specified THD.
7662

7663
  @param[in] thd         thread handler
7664

7665 7666
  @return
    - On success, return a valid pointer to the created and initialized
7667
    LEX_USER, which contains definer information.
7668
    - On error, return 0.
7669 7670 7671 7672 7673 7674 7675 7676 7677
*/

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

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

7678
  get_default_definer(thd, definer);
7679 7680 7681 7682 7683

  return definer;
}


7684
/**
7685
  Create definer with the given user and host names.
7686

7687 7688 7689
  @param[in] thd          thread handler
  @param[in] user_name    user name
  @param[in] host_name    host name
7690

7691 7692
  @return
    - On success, return a valid pointer to the created and initialized
7693
    LEX_USER, which contains definer information.
7694
    - On error, return 0.
7695 7696
*/

7697
LEX_USER *create_definer(THD *thd, LEX_STRING *user_name, LEX_STRING *host_name)
7698
{
7699 7700 7701 7702
  LEX_USER *definer;

  /* Create and initialize. */

7703
  if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER))))
7704 7705 7706 7707
    return 0;

  definer->user= *user_name;
  definer->host= *host_name;
7708 7709
  definer->password.str= NULL;
  definer->password.length= 0;
7710 7711

  return definer;
7712
}
7713 7714


7715
/**
7716 7717
  Retuns information about user or current user.

7718 7719
  @param[in] thd          thread handler
  @param[in] user         user
7720

7721 7722
  @return
    - On success, return a valid pointer to initialized
7723
    LEX_USER, which contains user information.
7724
    - On error, return 0.
7725 7726 7727 7728 7729
*/

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

7732 7733
  return user;
}
7734 7735


7736
/**
7737
  Check that byte length of a string does not exceed some limit.
7738

7739 7740 7741
  @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
7742

7743
  @retval
7744
    FALSE   the passed string is not longer than max_length
7745
  @retval
7746
    TRUE    the passed string is longer than max_length
7747 7748 7749

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

7752 7753
bool check_string_byte_length(LEX_STRING *str, const char *err_msg,
                              uint max_byte_length)
7754
{
7755
  if (str->length <= max_byte_length)
7756
    return FALSE;
7757

7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789
  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;
7790

7791
  if (!no_error)
7792 7793 7794 7795
  {
    ErrConvString err(str->str, str->length, cs);
    my_error(ER_WRONG_STRING_LENGTH, MYF(0), err.ptr(), err_msg, max_char_length);
  }
7796 7797
  return TRUE;
}
7798 7799


7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811
/*
  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  
*/
7812
C_MODE_START
7813

7814
int test_if_data_home_dir(const char *dir)
7815
{
7816
  char path[FN_REFLEN];
Alexey Botchkov's avatar
Alexey Botchkov committed
7817
  int dir_len;
7818 7819 7820 7821 7822 7823 7824
  DBUG_ENTER("test_if_data_home_dir");

  if (!dir)
    DBUG_RETURN(0);

  (void) fn_format(path, dir, "", "",
                   (MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS));
7825 7826
  dir_len= strlen(path);
  if (mysql_unpacked_real_data_home_len<= dir_len)
7827
  {
7828 7829 7830 7831
    if (dir_len > mysql_unpacked_real_data_home_len &&
        path[mysql_unpacked_real_data_home_len] != FN_LIBCHAR)
      DBUG_RETURN(0);

7832 7833
    if (lower_case_file_system)
    {
7834 7835
      if (!my_strnncoll(default_charset_info, (const uchar*) path,
                        mysql_unpacked_real_data_home_len,
7836
                        (const uchar*) mysql_unpacked_real_data_home,
7837
                        mysql_unpacked_real_data_home_len))
7838 7839
        DBUG_RETURN(1);
    }
7840 7841
    else if (!memcmp(path, mysql_unpacked_real_data_home,
                     mysql_unpacked_real_data_home_len))
7842 7843 7844 7845 7846
      DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}

7847 7848
C_MODE_END

7849

7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864
/**
  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
7865
  if (check_string_byte_length(str, ER(ER_HOSTNAME), HOSTNAME_LENGTH))
7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880
    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
7881 7882


7883 7884 7885 7886 7887 7888 7889 7890
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.
7891
  @param parser_state Parser state.
7892
  @param creation_ctx Object creation context.
7893 7894 7895 7896 7897 7898

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

7899
bool parse_sql(THD *thd,
7900
               Parser_state *parser_state,
7901
               Object_creation_ctx *creation_ctx)
7902
{
7903
  bool ret_value;
7904
  DBUG_ASSERT(thd->m_parser_state == NULL);
7905

7906
  MYSQL_QUERY_PARSE_START(thd->query());
7907 7908 7909 7910 7911 7912 7913
  /* Backup creation context. */

  Object_creation_ctx *backup_ctx= NULL;

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

7914
  /* Set parser state. */
7915

7916
  thd->m_parser_state= parser_state;
7917

7918 7919
  /* Parse the query. */

7920 7921
  bool mysql_parse_status= MYSQLparse(thd) != 0;

7922
  /* Check that if MYSQLparse() failed, thd->is_error() is set. */
7923 7924

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

7927
  /* Reset parser state. */
7928

7929
  thd->m_parser_state= NULL;
7930

7931 7932 7933 7934 7935 7936 7937
  /* Restore creation context. */

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

  /* That's it. */

7938 7939 7940
  ret_value= mysql_parse_status || thd->is_fatal_error;
  MYSQL_QUERY_PARSE_DONE(ret_value);
  return ret_value;
7941
}
7942 7943 7944 7945

/**
  @} (end of group Runtime_Environment)
*/
Alexander Barkov's avatar
#  
Alexander Barkov committed
7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979



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

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

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

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


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