sql_parse.cc 213 KB
Newer Older
1
/* Copyright (C) 2000-2003 MySQL AB
2

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3 4 5 6
   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
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
7

bk@work.mysql.com's avatar
bk@work.mysql.com committed
8 9 10 11
   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.
12

bk@work.mysql.com's avatar
bk@work.mysql.com committed
13 14 15 16 17
   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 */

#include "mysql_priv.h"
18
#include "sql_repl.h"
19
#include "repl_failsafe.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
20 21 22 23
#include <m_ctype.h>
#include <myisam.h>
#include <my_dir.h>

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
24
#ifdef HAVE_INNOBASE_DB
25
#include "ha_innodb.h"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
26 27
#endif

28 29 30 31
#ifdef HAVE_NDBCLUSTER_DB
#include "ha_ndbcluster.h"
#endif

32
#include "sp_head.h"
33
#include "sp.h"
34
#include "sp_cache.h"
35

36 37 38 39 40 41 42 43 44 45 46
#ifdef HAVE_OPENSSL
/*
  Without SSL the handshake consists of one packet. This packet
  has both client capabilites and scrambled password.
  With SSL the handshake might consist of two packets. If the first
  packet (client capabilities) has CLIENT_SSL flag set, we have to
  switch to SSL and read the second packet. The scrambled password
  is in the second packet and client_capabilites field will be ignored.
  Maybe it is better to accept flags other than CLIENT_SSL from the
  second packet?
*/
47 48 49
#define SSL_HANDSHAKE_SIZE      2
#define NORMAL_HANDSHAKE_SIZE   6
#define MIN_HANDSHAKE_SIZE      2
50
#else
51
#define MIN_HANDSHAKE_SIZE      6
52
#endif /* HAVE_OPENSSL */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
53

54 55 56 57 58 59
/* 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 || \
60
   (LP)->sql_command == SQLCOM_SHOW_CREATE_FUNC || \
61 62 63
   (LP)->sql_command == SQLCOM_DROP_FUNCTION ? \
   "FUNCTION" : "PROCEDURE")

64 65 66
#ifdef SOLARIS
extern "C" int gethostname(char *name, int namelen);
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
67

68
static void time_out_user_resource_limits(THD *thd, USER_CONN *uc);
69
#ifndef NO_EMBEDDED_ACCESS_CHECKS
70
static int check_for_max_user_connections(THD *thd, USER_CONN *uc);
71
#endif
72
static void decrease_user_connections(USER_CONN *uc);
73
static bool check_db_used(THD *thd,TABLE_LIST *tables);
74
static bool check_multi_update_lock(THD *thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
75 76
static void remove_escape(char *name);
static void refresh_status(void);
77 78
static bool append_file_to_dir(THD *thd, const char **filename_ptr,
			       const char *table_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
79

80
const char *any_db="*any*";	// Special symbol for check_access
bk@work.mysql.com's avatar
bk@work.mysql.com committed
81 82 83 84

const char *command_name[]={
  "Sleep", "Quit", "Init DB", "Query", "Field List", "Create DB",
  "Drop DB", "Refresh", "Shutdown", "Statistics", "Processlist",
85
  "Connect","Kill","Debug","Ping","Time","Delayed insert","Change user",
86
  "Binlog Dump","Table Dump",  "Connect Out", "Register Slave",
87
  "Prepare", "Execute", "Long Data", "Close stmt",
88
  "Reset stmt", "Set option", "Fetch",
89
  "Error"					// Last command number
bk@work.mysql.com's avatar
bk@work.mysql.com committed
90 91
};

92 93 94 95
const char *xa_state_names[]={
  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED"
};

96
static char empty_c_string[1]= {0};		// Used for not defined 'db'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
97 98 99 100

#ifdef __WIN__
static void  test_signal(int sig_ptr)
{
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
101
#if !defined( DBUG_OFF)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
102 103
  MessageBox(NULL,"Test signal","DBUG",MB_OK);
#endif
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
104
#if defined(OS2)
105 106
  fprintf(stderr, "Test signal %d\n", sig_ptr);
  fflush(stderr);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
107
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
108 109 110 111
}
static void init_signals(void)
{
  int signals[7] = {SIGINT,SIGILL,SIGFPE,SIGSEGV,SIGTERM,SIGBREAK,SIGABRT } ;
112
  for (int i=0 ; i < 7 ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
113 114 115 116
    signal( signals[i], test_signal) ;
}
#endif

117 118 119 120 121
static void unlock_locked_tables(THD *thd)
{
  if (thd->locked_tables)
  {
    thd->lock=thd->locked_tables;
122
    thd->locked_tables=0;			// Will be automatically closed
123 124 125 126
    close_thread_tables(thd);			// Free tables
  }
}

127

128
static bool end_active_trans(THD *thd)
129
{
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
130
  int error=0;
131
  DBUG_ENTER("end_active_trans");
132
  if (unlikely(thd->in_sub_stmt))
133 134 135 136
  {
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
    DBUG_RETURN(1);
  }
137 138 139 140 141 142
  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);
  }
143
  if (thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN |
144
		      OPTION_TABLE_LOCK))
145
  {
146 147 148 149
    DBUG_PRINT("info",("options: 0x%lx", (ulong) thd->options));
    /* Safety if one did "drop table" on locked tables */
    if (!thd->locked_tables)
      thd->options&= ~OPTION_TABLE_LOCK;
150
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
151
    if (ha_commit(thd))
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
152
      error=1;
153
    thd->options&= ~(ulong) (OPTION_BEGIN | OPTION_STATUS_NO_TRANS_UPDATE);
154
  }
155
  DBUG_RETURN(error);
156 157
}

158 159 160
static bool begin_trans(THD *thd)
{
  int error=0;
161
  if (unlikely(thd->in_sub_stmt))
162 163 164 165
  {
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
    return 1;
  }
166 167 168 169 170 171 172 173 174 175
  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
  {
176
    LEX *lex= thd->lex;
177 178 179 180
    thd->options= ((thd->options & (ulong) ~(OPTION_STATUS_NO_TRANS_UPDATE)) |
		   OPTION_BEGIN);
    thd->server_status|= SERVER_STATUS_IN_TRANS;
    if (lex->start_transaction_opt & MYSQL_START_TRANS_OPT_WITH_CONS_SNAPSHOT)
serg@serg.mylan's avatar
serg@serg.mylan committed
181
      error= ha_start_consistent_snapshot(thd);
182 183 184
  }
  return error;
}
185

monty@mysql.com's avatar
monty@mysql.com committed
186
#ifdef HAVE_REPLICATION
187 188 189
/*
  Returns true if all tables should be ignored
*/
190 191
inline bool all_tables_not_ok(THD *thd, TABLE_LIST *tables)
{
serg@serg.mylan's avatar
serg@serg.mylan committed
192
  return table_rules_on && tables && !tables_ok(thd,tables);
193
}
monty@mysql.com's avatar
monty@mysql.com committed
194
#endif
195 196


197 198 199 200 201 202 203 204 205 206 207 208
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;
}

209 210
static HASH hash_user_connections;

211 212
static int get_or_create_user_conn(THD *thd, const char *user,
				   const char *host,
peter@mysql.com's avatar
peter@mysql.com committed
213
				   USER_RESOURCES *mqh)
214
{
215
  int return_val= 0;
216
  uint temp_len, user_len;
217
  char temp_user[USER_HOST_BUFF_SIZE];
218 219 220 221 222
  struct  user_conn *uc;

  DBUG_ASSERT(user != 0);
  DBUG_ASSERT(host != 0);

223
  user_len= strlen(user);
224
  temp_len= (strmov(strmov(temp_user, user)+1, host) - temp_user)+1;
225
  (void) pthread_mutex_lock(&LOCK_user_conn);
226 227
  if (!(uc = (struct  user_conn *) hash_search(&hash_user_connections,
					       (byte*) temp_user, temp_len)))
228
  {
229 230 231
    /* First connection for user; Create a user connection object */
    if (!(uc= ((struct user_conn*)
	       my_malloc(sizeof(struct user_conn) + temp_len+1,
232 233
			 MYF(MY_WME)))))
    {
234
      net_send_error(thd, 0, NullS);		// Out of memory
235
      return_val= 1;
236
      goto end;
237
    }
238 239
    uc->user=(char*) (uc+1);
    memcpy(uc->user,temp_user,temp_len+1);
240
    uc->host= uc->user + user_len +  1;
241
    uc->len= temp_len;
242
    uc->connections= uc->questions= uc->updates= uc->conn_per_hour= 0;
243 244
    uc->user_resources= *mqh;
    uc->intime= thd->thr_create_time;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
245
    if (my_hash_insert(&hash_user_connections, (byte*) uc))
246 247
    {
      my_free((char*) uc,0);
248
      net_send_error(thd, 0, NullS);		// Out of memory
249
      return_val= 1;
250 251 252 253
      goto end;
    }
  }
  thd->user_connect=uc;
254
  uc->connections++;
255 256 257
end:
  (void) pthread_mutex_unlock(&LOCK_user_conn);
  return return_val;
peter@mysql.com's avatar
peter@mysql.com committed
258

259
}
260 261 262


/*
263 264
  Check if user exist and password supplied is correct. 

265 266
  SYNOPSIS
    check_user()
267
    thd          thread handle, thd->security_ctx->{host,user,ip} are used
268 269 270
    command      originator of the check: now check_user is called
                 during connect and change user procedures; used for 
                 logging.
271
    passwd       scrambled password received from client
272 273 274 275
    passwd_len   length of scrambled password
    db           database name to connect to, may be NULL
    check_count  dont know exactly

276
    Note, that host, user and passwd may point to communication buffer.
277
    Current implementation does not depend on that, but future changes
278 279 280
    should be done with this in mind; 'thd' is INOUT, all other params
    are 'IN'.

281
  RETURN VALUE
282 283
    0  OK; thd->security_ctx->user/master_access/priv_user/db_access and
       thd->db are updated; OK is sent to client;
284 285
   -1  access denied or handshake error; error is sent to client;
   >0  error, not sent to client
bk@work.mysql.com's avatar
bk@work.mysql.com committed
286 287
*/

hf@deer.(none)'s avatar
hf@deer.(none) committed
288 289 290
int check_user(THD *thd, enum enum_server_command command, 
	       const char *passwd, uint passwd_len, const char *db,
	       bool check_count)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
291
{
292
  DBUG_ENTER("check_user");
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
293
  
monty@mysql.com's avatar
monty@mysql.com committed
294
#ifdef NO_EMBEDDED_ACCESS_CHECKS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
295
  thd->main_security_ctx.master_access= GLOBAL_ACLS;       // Full rights
296
  /* Change database if necessary */
297 298
  if (db && db[0])
  {
299 300 301 302
    /*
      thd->db is saved in caller and needs to be freed by caller if this
      function returns 0
    */
303 304
    thd->db= 0;
    thd->db_length= 0;
305
    if (mysql_change_db(thd, db, FALSE))
306
    {
307 308
      /* Send the error to the client */
      net_send_error(thd);
309 310 311 312 313
      if (thd->user_connect)
	decrease_user_connections(thd->user_connect);
      DBUG_RETURN(-1);
    }
  }
314
  send_ok(thd);
315
  DBUG_RETURN(0);
monty@mysql.com's avatar
monty@mysql.com committed
316 317
#else

318 319 320 321 322
  my_bool opt_secure_auth_local;
  pthread_mutex_lock(&LOCK_global_system_variables);
  opt_secure_auth_local= opt_secure_auth;
  pthread_mutex_unlock(&LOCK_global_system_variables);
  
323
  /*
324 325
    If the server is running in secure auth mode, short scrambles are 
    forbidden.
326
  */
327
  if (opt_secure_auth_local && passwd_len == SCRAMBLE_LENGTH_323)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
328
  {
329
    net_printf_error(thd, ER_NOT_SUPPORTED_AUTH_MODE);
330 331
    mysql_log.write(thd, COM_CONNECT, ER(ER_NOT_SUPPORTED_AUTH_MODE));
    DBUG_RETURN(-1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
332
  }
333 334 335 336
  if (passwd_len != 0 &&
      passwd_len != SCRAMBLE_LENGTH &&
      passwd_len != SCRAMBLE_LENGTH_323)
    DBUG_RETURN(ER_HANDSHAKE_ERROR);
peter@mysql.com's avatar
peter@mysql.com committed
337

338
  /*
339
    Clear thd->db as it points to something, that will be freed when 
340
    connection is closed. We don't want to accidentally free a wrong pointer
341 342
    if connect failed. Also in case of 'CHANGE USER' failure, current
    database will be switched to 'no database selected'.
343
  */
344 345
  thd->db= 0;
  thd->db_length= 0;
346
  
347
  USER_RESOURCES ur;
348
  int res= acl_getroot(thd, &ur, passwd, passwd_len);
hf@deer.(none)'s avatar
hf@deer.(none) committed
349
#ifndef EMBEDDED_LIBRARY
350
  if (res == -1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
351
  {
352 353 354 355 356 357
    /*
      This happens when client (new) sends password scrambled with
      scramble(), but database holds old value (scrambled with
      scramble_323()). Here we please client to send scrambled_password
      in old format.
    */
358
    NET *net= &thd->net;
359
    if (opt_secure_auth_local)
360
    {
361
      net_printf_error(thd, ER_SERVER_IS_IN_SECURE_AUTH_MODE,
362 363
                       thd->main_security_ctx.user,
                       thd->main_security_ctx.host_or_ip);
364
      mysql_log.write(thd, COM_CONNECT, ER(ER_SERVER_IS_IN_SECURE_AUTH_MODE),
365 366
                      thd->main_security_ctx.user,
                      thd->main_security_ctx.host_or_ip);
367 368
      DBUG_RETURN(-1);
    }
monty@mysql.com's avatar
monty@mysql.com committed
369
    /* We have to read very specific packet size */
370
    if (send_old_password_request(thd) ||
monty@mysql.com's avatar
monty@mysql.com committed
371
        my_net_read(net) != SCRAMBLE_LENGTH_323 + 1)
372
    {
373 374 375 376 377
      inc_host_errors(&thd->remote.sin_addr);
      DBUG_RETURN(ER_HANDSHAKE_ERROR);
    }
    /* Final attempt to check the user based on reply */
    /* So as passwd is short, errcode is always >= 0 */
378
    res= acl_getroot(thd, &ur, (char *) net->read_pos, SCRAMBLE_LENGTH_323);
379
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
380
#endif /*EMBEDDED_LIBRARY*/
381 382
  /* here res is always >= 0 */
  if (res == 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
383
  {
384 385
    if (!(thd->main_security_ctx.master_access &
          NO_ACCESS)) // authentication is OK
386
    {
387 388 389 390
      DBUG_PRINT("info",
                 ("Capabilities: %d  packet_length: %ld  Host: '%s'  "
                  "Login user: '%s' Priv_user: '%s'  Using password: %s "
                  "Access: %u  db: '%s'",
391 392 393 394 395
                  thd->client_capabilities,
                  thd->max_client_packet_length,
                  thd->main_security_ctx.host_or_ip,
                  thd->main_security_ctx.user,
                  thd->main_security_ctx.priv_user,
396
                  passwd_len ? "yes": "no",
397 398
                  thd->main_security_ctx.master_access,
                  (thd->db ? thd->db : "*none*")));
399 400

      if (check_count)
401
      {
402
        VOID(pthread_mutex_lock(&LOCK_thread_count));
serg@serg.mylan's avatar
serg@serg.mylan committed
403
        bool count_ok= thread_count <= max_connections + delayed_insert_threads
404
                       || (thd->main_security_ctx.master_access & SUPER_ACL);
405 406
        VOID(pthread_mutex_unlock(&LOCK_thread_count));
        if (!count_ok)
serg@serg.mylan's avatar
serg@serg.mylan committed
407
        {                                         // too many connections
408
          net_send_error(thd, ER_CON_COUNT_ERROR);
409 410
          DBUG_RETURN(-1);
        }
411
      }
peter@mysql.com's avatar
peter@mysql.com committed
412

413
      /* Why logging is performed before all checks've passed? */
414
      mysql_log.write(thd, command,
415 416
                      (thd->main_security_ctx.priv_user ==
                       thd->main_security_ctx.user ?
417 418
                       (char*) "%s@%s on %s" :
                       (char*) "%s@%s as anonymous on %s"),
419 420
                      thd->main_security_ctx.user,
                      thd->main_security_ctx.host_or_ip,
421 422
                      db ? db : (char*) "");

423
      /*
424 425 426
        This is the default access rights for the current database.  It's
        set to 0 here because we don't have an active database yet (and we
        may not have an active database to set.
427
      */
428
      thd->main_security_ctx.db_access=0;
429 430

      /* Don't allow user to connect if he has done too many queries */
431
      if ((ur.questions || ur.updates || ur.conn_per_hour || ur.user_conn ||
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
432
	   max_user_connections) &&
433
	  get_or_create_user_conn(thd,
434 435 436 437
            (opt_old_style_user_limits ? thd->main_security_ctx.user :
             thd->main_security_ctx.priv_user),
            (opt_old_style_user_limits ? thd->main_security_ctx.host_or_ip :
             thd->main_security_ctx.priv_host),
438
            &ur))
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
439 440
	DBUG_RETURN(-1);
      if (thd->user_connect &&
441 442
	  (thd->user_connect->user_resources.conn_per_hour ||
	   thd->user_connect->user_resources.user_conn ||
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
443 444 445
	   max_user_connections) &&
	  check_for_max_user_connections(thd, thd->user_connect))
	DBUG_RETURN(-1);
446

447
      /* Change database if necessary */
448
      if (db && db[0])
449
      {
450
        if (mysql_change_db(thd, db, FALSE))
451
        {
452 453
          /* Send error to the client */
          net_send_error(thd);
454 455 456 457
          if (thd->user_connect)
            decrease_user_connections(thd->user_connect);
          DBUG_RETURN(-1);
        }
458
      }
459
      send_ok(thd);
460 461 462
      thd->password= test(passwd_len);          // remember for error messages 
      /* Ready to handle queries */
      DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
463 464
    }
  }
465
  else if (res == 2) // client gave short hash, server has long hash
466
  {
467
    net_printf_error(thd, ER_NOT_SUPPORTED_AUTH_MODE);
468 469
    mysql_log.write(thd,COM_CONNECT,ER(ER_NOT_SUPPORTED_AUTH_MODE));
    DBUG_RETURN(-1);
470
  }
471
  net_printf_error(thd, ER_ACCESS_DENIED_ERROR,
472 473
                   thd->main_security_ctx.user,
                   thd->main_security_ctx.host_or_ip,
474
                   passwd_len ? ER(ER_YES) : ER(ER_NO));
475
  mysql_log.write(thd, COM_CONNECT, ER(ER_ACCESS_DENIED_ERROR),
476 477
                  thd->main_security_ctx.user,
                  thd->main_security_ctx.host_or_ip,
478 479
                  passwd_len ? ER(ER_YES) : ER(ER_NO));
  DBUG_RETURN(-1);
monty@mysql.com's avatar
monty@mysql.com committed
480
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
481 482
}

483
/*
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
484 485
  Check for maximum allowable user connections, if the mysqld server is
  started with corresponding variable that is greater then 0.
486 487
*/

488 489
extern "C" byte *get_key_conn(user_conn *buff, uint *length,
			      my_bool not_used __attribute__((unused)))
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
490 491 492 493 494
{
  *length=buff->len;
  return (byte*) buff->user;
}

495
extern "C" void free_user(struct user_conn *uc)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
496 497 498 499
{
  my_free((char*) uc,MYF(0));
}

peter@mysql.com's avatar
peter@mysql.com committed
500
void init_max_user_conn(void)
501
{
502 503
  (void) hash_init(&hash_user_connections,system_charset_info,max_connections,
		   0,0,
504
		   (hash_get_key) get_key_conn, (hash_free_key) free_user,
505
		   0);
506 507 508
}


monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
/*
  check if user has already too many connections
  
  SYNOPSIS
  check_for_max_user_connections()
  thd			Thread handle
  uc			User connect object

  NOTES
    If check fails, we decrease user connection count, which means one
    shouldn't call decrease_user_connections() after this function.

  RETURN
    0	ok
    1	error
*/

526 527
#ifndef NO_EMBEDDED_ACCESS_CHECKS

528
static int check_for_max_user_connections(THD *thd, USER_CONN *uc)
529
{
530
  int error=0;
531
  DBUG_ENTER("check_for_max_user_connections");
peter@mysql.com's avatar
peter@mysql.com committed
532

533
  (void) pthread_mutex_lock(&LOCK_user_conn);
534
  if (max_user_connections && !uc->user_resources.user_conn &&
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
535
      max_user_connections < (uint) uc->connections)
536
  {
537
    net_printf_error(thd, ER_TOO_MANY_USER_CONNECTIONS, uc->user);
538 539
    error=1;
    goto end;
540
  }
541
  time_out_user_resource_limits(thd, uc);
542 543 544 545 546 547 548 549 550 551 552
  if (uc->user_resources.user_conn &&
      uc->user_resources.user_conn < uc->connections)
  {
    net_printf_error(thd, ER_USER_LIMIT_REACHED, uc->user,
                     "max_user_connections",
                     (long) uc->user_resources.user_conn);
    error= 1;
    goto end;
  }
  if (uc->user_resources.conn_per_hour &&
      uc->user_resources.conn_per_hour <= uc->conn_per_hour)
553
  {
554
    net_printf_error(thd, ER_USER_LIMIT_REACHED, uc->user,
jimw@mysql.com's avatar
jimw@mysql.com committed
555
                     "max_connections_per_hour",
556
                     (long) uc->user_resources.conn_per_hour);
557 558 559
    error=1;
    goto end;
  }
560
  uc->conn_per_hour++;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
561 562

  end:
563 564
  if (error)
    uc->connections--; // no need for decrease_user_connections() here
565
  (void) pthread_mutex_unlock(&LOCK_user_conn);
566
  DBUG_RETURN(error);
567
}
568
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
569

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
/*
  Decrease user connection count

  SYNOPSIS
    decrease_user_connections()
    uc			User connection object

  NOTES
    If there is a n user connection object for a connection
    (which only happens if 'max_user_connections' is defined or
    if someone has created a resource grant for a user), then
    the connection count is always incremented on connect.

    The user connect object is not freed if some users has
    'max connections per hour' defined as we need to be able to hold
    count over the lifetime of the connection.
*/

588
static void decrease_user_connections(USER_CONN *uc)
589
{
590
  DBUG_ENTER("decrease_user_connections");
591 592 593
  (void) pthread_mutex_lock(&LOCK_user_conn);
  DBUG_ASSERT(uc->connections);
  if (!--uc->connections && !mqh_used)
594 595
  {
    /* Last connection for user; Delete it */
596
    (void) hash_delete(&hash_user_connections,(byte*) uc);
597
  }
598
  (void) pthread_mutex_unlock(&LOCK_user_conn);
599
  DBUG_VOID_RETURN;
600 601
}

602

603 604 605 606 607
void free_max_user_conn(void)
{
  hash_free(&hash_user_connections);
}

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
608

609 610 611
/*
  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
612 613 614

  sql_command is actually set to SQLCOM_END sometimes
  so we need the +1 to include it in the array.
615 616 617 618 619 620

  numbers are:
     0  - read-only query
  != 0  - query that may change a table
     2  - query that returns meaningful ROW_COUNT() -
          a number of modified rows
621 622
*/

kent@mysql.com's avatar
kent@mysql.com committed
623
char  uc_update_queries[SQLCOM_END+1];
624 625 626

void init_update_queries(void)
{
kent@mysql.com's avatar
kent@mysql.com committed
627 628
  bzero((gptr) &uc_update_queries, sizeof(uc_update_queries));

629 630 631
  uc_update_queries[SQLCOM_CREATE_TABLE]=1;
  uc_update_queries[SQLCOM_CREATE_INDEX]=1;
  uc_update_queries[SQLCOM_ALTER_TABLE]=1;
632 633 634 635 636 637
  uc_update_queries[SQLCOM_UPDATE]=2;
  uc_update_queries[SQLCOM_UPDATE_MULTI]=2;
  uc_update_queries[SQLCOM_INSERT]=2;
  uc_update_queries[SQLCOM_INSERT_SELECT]=2;
  uc_update_queries[SQLCOM_DELETE]=2;
  uc_update_queries[SQLCOM_DELETE_MULTI]=2;
638 639 640 641 642
  uc_update_queries[SQLCOM_TRUNCATE]=1;
  uc_update_queries[SQLCOM_DROP_TABLE]=1;
  uc_update_queries[SQLCOM_LOAD]=1;
  uc_update_queries[SQLCOM_CREATE_DB]=1;
  uc_update_queries[SQLCOM_DROP_DB]=1;
643 644
  uc_update_queries[SQLCOM_REPLACE]=2;
  uc_update_queries[SQLCOM_REPLACE_SELECT]=2;
645 646 647 648
  uc_update_queries[SQLCOM_RENAME_TABLE]=1;
  uc_update_queries[SQLCOM_BACKUP_TABLE]=1;
  uc_update_queries[SQLCOM_RESTORE_TABLE]=1;
  uc_update_queries[SQLCOM_DROP_INDEX]=1;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
649 650
  uc_update_queries[SQLCOM_CREATE_VIEW]=1;
  uc_update_queries[SQLCOM_DROP_VIEW]=1;
651 652
}

653 654
bool is_update_query(enum enum_sql_command command)
{
kent@mysql.com's avatar
kent@mysql.com committed
655
  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
656
  return uc_update_queries[command] != 0;
657
}
658

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
659
/*
660 661
  Reset per-hour user resource limits when it has been more than
  an hour since they were last checked
662

663 664 665 666
  SYNOPSIS:
    time_out_user_resource_limits()
    thd			Thread handler
    uc			User connection details
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
667

668 669 670 671
  NOTE:
    This assumes that the LOCK_user_conn mutex has been acquired, so it is
    safe to test and modify members of the USER_CONN structure.
*/
672

673
static void time_out_user_resource_limits(THD *thd, USER_CONN *uc)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
674
{
675
  time_t check_time = thd->start_time ?  thd->start_time : time(NULL);
676
  DBUG_ENTER("time_out_user_resource_limits");
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
677

678
  /* If more than a hour since last check, reset resource checking */
679 680 681 682 683 684 685
  if (check_time  - uc->intime >= 3600)
  {
    uc->questions=1;
    uc->updates=0;
    uc->conn_per_hour=0;
    uc->intime=check_time;
  }
686 687 688 689 690 691 692 693 694 695 696 697

  DBUG_VOID_RETURN;
}


/*
  Check if maximum queries per hour limit has been reached
  returns 0 if OK.
*/

static bool check_mqh(THD *thd, uint check_command)
{
698 699
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  bool error= 0;
700 701 702 703 704 705 706 707
  USER_CONN *uc=thd->user_connect;
  DBUG_ENTER("check_mqh");
  DBUG_ASSERT(uc != 0);

  (void) pthread_mutex_lock(&LOCK_user_conn);

  time_out_user_resource_limits(thd, uc);

708
  /* Check that we have not done too many questions / hour */
709 710 711
  if (uc->user_resources.questions &&
      uc->questions++ >= uc->user_resources.questions)
  {
712 713
    net_printf_error(thd, ER_USER_LIMIT_REACHED, uc->user, "max_questions",
                     (long) uc->user_resources.questions);
714 715 716
    error=1;
    goto end;
  }
717
  if (check_command < (uint) SQLCOM_END)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
718
  {
719 720 721 722
    /* Check that we have not done too many updates / hour */
    if (uc->user_resources.updates && uc_update_queries[check_command] &&
	uc->updates++ >= uc->user_resources.updates)
    {
723 724
      net_printf_error(thd, ER_USER_LIMIT_REACHED, uc->user, "max_updates",
                       (long) uc->user_resources.updates);
725 726 727
      error=1;
      goto end;
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
728 729
  }
end:
730
  (void) pthread_mutex_unlock(&LOCK_user_conn);
731
  DBUG_RETURN(error);
732 733
#else
  return (0);
monty@mysql.com's avatar
monty@mysql.com committed
734
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
735 736
}

737

monty@mysql.com's avatar
monty@mysql.com committed
738
static void reset_mqh(LEX_USER *lu, bool get_them= 0)
739
{
monty@mysql.com's avatar
monty@mysql.com committed
740
#ifndef NO_EMBEDDED_ACCESS_CHECKS
741
  (void) pthread_mutex_lock(&LOCK_user_conn);
peter@mysql.com's avatar
peter@mysql.com committed
742
  if (lu)  // for GRANT
743
  {
744
    USER_CONN *uc;
745
    uint temp_len=lu->user.length+lu->host.length+2;
746
    char temp_user[USER_HOST_BUFF_SIZE];
747

748 749
    memcpy(temp_user,lu->user.str,lu->user.length);
    memcpy(temp_user+lu->user.length+1,lu->host.str,lu->host.length);
750
    temp_user[lu->user.length]='\0'; temp_user[temp_len-1]=0;
751
    if ((uc = (struct  user_conn *) hash_search(&hash_user_connections,
752
						(byte*) temp_user, temp_len)))
753 754
    {
      uc->questions=0;
755
      get_mqh(temp_user,&temp_user[lu->user.length+1],uc);
756 757
      uc->updates=0;
      uc->conn_per_hour=0;
758 759
    }
  }
monty@mysql.com's avatar
monty@mysql.com committed
760
  else
761
  {
monty@mysql.com's avatar
monty@mysql.com committed
762
    /* for FLUSH PRIVILEGES and FLUSH USER_RESOURCES */
763
    for (uint idx=0;idx < hash_user_connections.records; idx++)
764
    {
monty@mysql.com's avatar
monty@mysql.com committed
765 766
      USER_CONN *uc=(struct user_conn *) hash_element(&hash_user_connections,
						      idx);
767 768 769 770 771
      if (get_them)
	get_mqh(uc->user,uc->host,uc);
      uc->questions=0;
      uc->updates=0;
      uc->conn_per_hour=0;
772 773
    }
  }
774
  (void) pthread_mutex_unlock(&LOCK_user_conn);
monty@mysql.com's avatar
monty@mysql.com committed
775
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
776
}
777

bk@work.mysql.com's avatar
bk@work.mysql.com committed
778
/*
779
    Perform handshake, authorize client and update thd ACL variables.
780
  SYNOPSIS
781
    check_connection()
782
    thd  thread handle
783 784

  RETURN
785
     0  success, OK is sent to user, thd is updated.
786 787
    -1  error, which is sent to user
   > 0  error code (not sent to user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
788 789
*/

hf@deer.(none)'s avatar
hf@deer.(none) committed
790 791
#ifndef EMBEDDED_LIBRARY
static int check_connection(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
792
{
793
  uint connect_errors= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
794
  NET *net= &thd->net;
monty@mysql.com's avatar
monty@mysql.com committed
795 796
  ulong pkt_len= 0;
  char *end;
797

798 799
  DBUG_PRINT("info",
             ("New connection received on %s", vio_description(net->vio)));
800
#ifdef SIGNAL_WITH_VIO_CLOSE
801
  thd->set_active_vio(net->vio);
802
#endif
803

804
  if (!thd->main_security_ctx.host)         // If TCP/IP connection
bk@work.mysql.com's avatar
bk@work.mysql.com committed
805
  {
806
    char ip[30];
807

808
    if (vio_peer_addr(net->vio, ip, &thd->peer_port))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
809
      return (ER_BAD_HOST_ERROR);
810
    if (!(thd->main_security_ctx.ip= my_strdup(ip,MYF(0))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
811
      return (ER_OUT_OF_RESOURCES);
812
    thd->main_security_ctx.host_or_ip= thd->main_security_ctx.ip;
monty@mysql.com's avatar
monty@mysql.com committed
813
    vio_in_addr(net->vio,&thd->remote.sin_addr);
814
    if (!(specialflag & SPECIAL_NO_RESOLVE))
815
    {
816
      vio_in_addr(net->vio,&thd->remote.sin_addr);
817 818
      thd->main_security_ctx.host=
        ip_to_hostname(&thd->remote.sin_addr, &connect_errors);
819
      /* Cut very long hostnames to avoid possible overflows */
820
      if (thd->main_security_ctx.host)
821
      {
822 823 824 825
        if (thd->main_security_ctx.host != my_localhost)
          thd->main_security_ctx.host[min(strlen(thd->main_security_ctx.host),
                                          HOSTNAME_LENGTH)]= 0;
        thd->main_security_ctx.host_or_ip= thd->main_security_ctx.host;
826
      }
827 828
      if (connect_errors > max_connect_errors)
        return(ER_HOST_IS_BLOCKED);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
829
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
830
    DBUG_PRINT("info",("Host: %s  ip: %s",
831 832 833 834 835
		       (thd->main_security_ctx.host ?
                        thd->main_security_ctx.host : "unknown host"),
		       (thd->main_security_ctx.ip ?
                        thd->main_security_ctx.ip : "unknown ip")));
    if (acl_check_host(thd->main_security_ctx.host, thd->main_security_ctx.ip))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
836 837
      return(ER_HOST_NOT_PRIVILEGED);
  }
838
  else /* Hostname given means that the connection was on a socket */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
839
  {
840 841 842
    DBUG_PRINT("info",("Host: %s", thd->main_security_ctx.host));
    thd->main_security_ctx.host_or_ip= thd->main_security_ctx.host;
    thd->main_security_ctx.ip= 0;
843 844
    /* Reset sin_addr */
    bzero((char*) &thd->remote, sizeof(thd->remote));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
845 846 847
  }
  vio_keepalive(net->vio, TRUE);
  {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
848
    /* buff[] needs to big enough to hold the server_version variable */
849
    char buff[SERVER_VERSION_LENGTH + SCRAMBLE_LENGTH + 64];
850 851
    ulong client_flags = (CLIENT_LONG_FLAG | CLIENT_CONNECT_WITH_DB |
			  CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION);
852

853 854 855 856 857
    if (opt_using_transactions)
      client_flags|=CLIENT_TRANSACTIONS;
#ifdef HAVE_COMPRESS
    client_flags |= CLIENT_COMPRESS;
#endif /* HAVE_COMPRESS */
858 859
#ifdef HAVE_OPENSSL
    if (ssl_acceptor_fd)
860
      client_flags |= CLIENT_SSL;       /* Wow, SSL is available! */
861
#endif /* HAVE_OPENSSL */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
862

863 864 865 866 867 868 869 870 871 872 873
    end= strnmov(buff, server_version, SERVER_VERSION_LENGTH) + 1;
    int4store((uchar*) end, thd->thread_id);
    end+= 4;
    /*
      So as check_connection is the only entry point to authorization
      procedure, scramble is set here. This gives us new scramble for
      each handshake.
    */
    create_random_string(thd->scramble, SCRAMBLE_LENGTH, &thd->rand);
    /*
      Old clients does not understand long scrambles, but can ignore packet
874
      tail: that's why first part of the scramble is placed here, and second
875 876
      part at the end of packet.
    */
877
    end= strmake(end, thd->scramble, SCRAMBLE_LENGTH_323) + 1;
878 879 880
   
    int2store(end, client_flags);
    /* write server characteristics: up to 16 bytes allowed */
881
    end[2]=(char) default_charset_info->number;
882 883 884 885 886 887 888 889 890
    int2store(end+3, thd->server_status);
    bzero(end+5, 13);
    end+= 18;
    /* write scramble tail */
    end= strmake(end, thd->scramble + SCRAMBLE_LENGTH_323, 
                 SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323) + 1;

    /* At this point we write connection message and read reply */
    if (net_write_command(net, (uchar) protocol_version, "", 0, buff,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
891
			  (uint) (end-buff)) ||
892
	(pkt_len= my_net_read(net)) == packet_error ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
893 894 895 896 897 898 899 900 901 902 903
	pkt_len < MIN_HANDSHAKE_SIZE)
    {
      inc_host_errors(&thd->remote.sin_addr);
      return(ER_HANDSHAKE_ERROR);
    }
  }
#ifdef _CUSTOMCONFIG_
#include "_cust_sql_parse.h"
#endif
  if (connect_errors)
    reset_host_errors(&thd->remote.sin_addr);
904
  if (thd->packet.alloc(thd->variables.net_buffer_length))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
905 906 907
    return(ER_OUT_OF_RESOURCES);

  thd->client_capabilities=uint2korr(net->read_pos);
908 909 910 911
  if (thd->client_capabilities & CLIENT_PROTOCOL_41)
  {
    thd->client_capabilities|= ((ulong) uint2korr(net->read_pos+2)) << 16;
    thd->max_client_packet_length= uint4korr(net->read_pos+4);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
912 913 914
    DBUG_PRINT("info", ("client_character_set: %d", (uint) net->read_pos[8]));
    /*
      Use server character set and collation if
915
      - opt_character_set_client_handshake is not set
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
916 917 918 919
      - client has not specified a character set
      - client character set is the same as the servers
      - client character set doesn't exists in server
    */
920
    if (!opt_character_set_client_handshake ||
921
        !(thd->variables.character_set_client=
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
922 923 924 925
	  get_charset((uint) net->read_pos[8], MYF(0))) ||
	!my_strcasecmp(&my_charset_latin1,
		       global_system_variables.character_set_client->name,
		       thd->variables.character_set_client->name))
926
    {
927 928
      thd->variables.character_set_client=
	global_system_variables.character_set_client;
929 930
      thd->variables.collation_connection=
	global_system_variables.collation_connection;
931 932
      thd->variables.character_set_results=
	global_system_variables.character_set_results;
933 934 935
    }
    else
    {
936
      thd->variables.character_set_results=
937 938 939
      thd->variables.collation_connection= 
	thd->variables.character_set_client;
    }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
940
    thd->update_charset();
941
    end= (char*) net->read_pos+32;
942 943 944 945 946 947 948
  }
  else
  {
    thd->max_client_packet_length= uint3korr(net->read_pos+2);
    end= (char*) net->read_pos+5;
  }

949
  if (thd->client_capabilities & CLIENT_IGNORE_SPACE)
950
    thd->variables.sql_mode|= MODE_IGNORE_SPACE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
951
#ifdef HAVE_OPENSSL
952
  DBUG_PRINT("info", ("client capabilities: %d", thd->client_capabilities));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
953 954 955
  if (thd->client_capabilities & CLIENT_SSL)
  {
    /* Do the SSL layering. */
956 957 958 959 960
    if (!ssl_acceptor_fd)
    {
      inc_host_errors(&thd->remote.sin_addr);
      return(ER_HANDSHAKE_ERROR);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
961
    DBUG_PRINT("info", ("IO layer change in progress..."));
962 963
    if (sslaccept(ssl_acceptor_fd, net->vio, thd->variables.net_wait_timeout))
    {
964
      DBUG_PRINT("error", ("Failed to accept new SSL connection"));
965
      inc_host_errors(&thd->remote.sin_addr);
peter@mysql.com's avatar
peter@mysql.com committed
966
      return(ER_HANDSHAKE_ERROR);
967
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
968
    DBUG_PRINT("info", ("Reading user information over SSL layer"));
969
    if ((pkt_len= my_net_read(net)) == packet_error ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
970 971
	pkt_len < NORMAL_HANDSHAKE_SIZE)
    {
972 973
      DBUG_PRINT("error", ("Failed to read user information (pkt_len= %lu)",
			   pkt_len));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
974 975 976 977
      inc_host_errors(&thd->remote.sin_addr);
      return(ER_HANDSHAKE_ERROR);
    }
  }
978 979 980
#endif

  if (end >= (char*) net->read_pos+ pkt_len +2)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
981
  {
982 983
    inc_host_errors(&thd->remote.sin_addr);
    return(ER_HANDSHAKE_ERROR);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
984 985 986
  }

  if (thd->client_capabilities & CLIENT_INTERACTIVE)
987
    thd->variables.net_wait_timeout= thd->variables.net_interactive_timeout;
988
  if ((thd->client_capabilities & CLIENT_TRANSACTIONS) &&
989 990
      opt_using_transactions)
    net->return_status= &thd->server_status;
991
  net->read_timeout=(uint) thd->variables.net_read_timeout;
peter@mysql.com's avatar
peter@mysql.com committed
992

993 994
  char *user= end;
  char *passwd= strend(user)+1;
995
  char *db= passwd;
996
  char db_buff[NAME_LEN+1];                     // buffer to store db in utf8
997
  char user_buff[USERNAME_LENGTH+1];		// buffer to store user in utf8
998 999 1000
  uint dummy_errors;

  /*
1001 1002 1003 1004
    Old clients send null-terminated string as password; new clients send
    the size (1 byte) + string (not null-terminated). Hence in case of empty
    password both send '\0'.
  */
1005
  uint passwd_len= thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
1006 1007 1008
    *passwd++ : strlen(passwd);
  db= thd->client_capabilities & CLIENT_CONNECT_WITH_DB ?
    db + passwd_len + 1 : 0;
peter@mysql.com's avatar
peter@mysql.com committed
1009

kostja@oak.local's avatar
kostja@oak.local committed
1010 1011
  /* Since 4.1 all database names are stored in utf8 */
  if (db)
peter@mysql.com's avatar
peter@mysql.com committed
1012
  {
1013 1014 1015
    db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
                             system_charset_info,
                             db, strlen(db),
1016
                             thd->charset(), &dummy_errors)]= 0;
1017
    db= db_buff;
kostja@oak.local's avatar
kostja@oak.local committed
1018
  }
peter@mysql.com's avatar
peter@mysql.com committed
1019

1020 1021 1022 1023
  user_buff[copy_and_convert(user_buff, sizeof(user_buff)-1,
                             system_charset_info, user, strlen(user),
                             thd->charset(), &dummy_errors)]= '\0';
  user= user_buff;
1024

1025 1026 1027
  if (thd->main_security_ctx.user)
    x_free(thd->main_security_ctx.user);
  if (!(thd->main_security_ctx.user= my_strdup(user, MYF(0))))
1028
    return (ER_OUT_OF_RESOURCES);
1029
  return check_user(thd, COM_CONNECT, passwd, passwd_len, db, TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1030 1031
}

1032

1033 1034
void execute_init_command(THD *thd, sys_var_str *init_command_var,
			  rw_lock_t *var_mutex)
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1035 1036 1037 1038
{
  Vio* save_vio;
  ulong save_client_capabilities;

1039 1040 1041 1042 1043 1044 1045 1046 1047
  thd->proc_info= "Execution of init_command";
  /*
    We need to lock init_command_var because
    during execution of init_command_var query
    values of init_command_var can't be changed
  */
  rw_rdlock(var_mutex);
  thd->query= init_command_var->value;
  thd->query_length= init_command_var->value_length;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1048 1049
  save_client_capabilities= thd->client_capabilities;
  thd->client_capabilities|= CLIENT_MULTI_QUERIES;
1050 1051 1052 1053
  /*
    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
1054 1055
  save_vio= thd->net.vio;
  thd->net.vio= 0;
1056
  thd->net.no_send_error= 0;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1057
  dispatch_command(COM_QUERY, thd, thd->query, thd->query_length+1);
1058
  rw_unlock(var_mutex);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1059 1060 1061 1062 1063
  thd->client_capabilities= save_client_capabilities;
  thd->net.vio= save_vio;
}


1064
pthread_handler_t handle_one_connection(void *arg)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1065 1066 1067
{
  THD *thd=(THD*) arg;
  uint launch_time  =
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1068
    (uint) ((thd->thr_create_time = time(NULL)) - thd->connect_time);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1069 1070 1071 1072 1073
  if (launch_time >= slow_launch_time)
    statistic_increment(slow_launch_threads,&LOCK_status );

  pthread_detach_this_thread();

1074
#if !defined( __WIN__) && !defined(OS2)	// Win32 calls this in pthread_create
monty@mysql.com's avatar
monty@mysql.com committed
1075
  /* The following calls needs to be done before we call DBUG_ macros */
1076
  if (!(test_flags & TEST_NO_THREADS) & my_thread_init())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1077
  {
1078
    close_connection(thd, ER_OUT_OF_RESOURCES, 1);
1079
    statistic_increment(aborted_connects,&LOCK_status);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1080 1081 1082 1083 1084
    end_thread(thd,0);
    return 0;
  }
#endif

1085 1086 1087 1088 1089 1090 1091
  /*
    handle_one_connection() is the only way a thread would start
    and would always be on top of the stack, therefore, the thread
    stack always starts at the address of the first local variable
    of handle_one_connection, which is thd. We need to know the
    start of the stack so that we could check for stack overruns.
  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1092 1093
  DBUG_PRINT("info", ("handle_one_connection called by thread %d\n",
		      thd->thread_id));
monty@mysql.com's avatar
monty@mysql.com committed
1094
  /* now that we've called my_thread_init(), it is safe to call DBUG_* */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1095

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1096
#if defined(__WIN__)
1097
  init_signals();
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1098
#elif !defined(OS2) && !defined(__NETWARE__)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1099 1100 1101 1102
  sigset_t set;
  VOID(sigemptyset(&set));			// Get mask in use
  VOID(pthread_sigmask(SIG_UNBLOCK,&set,&thd->block_signals));
#endif
1103
  thd->thread_stack= (char*) &thd;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1104 1105
  if (thd->store_globals())
  {
1106
    close_connection(thd, ER_OUT_OF_RESOURCES, 1);
1107
    statistic_increment(aborted_connects,&LOCK_status);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1108 1109 1110 1111 1112 1113 1114 1115
    end_thread(thd,0);
    return 0;
  }

  do
  {
    int error;
    NET *net= &thd->net;
1116
    Security_context *sctx= thd->security_ctx;
1117
    net->no_send_error= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1118

1119
    if ((error=check_connection(thd)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1120 1121
    {						// Wrong permissions
      if (error > 0)
1122
	net_printf_error(thd, error, sctx->host_or_ip);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1123 1124
#ifdef __NT__
      if (vio_type(net->vio) == VIO_TYPE_NAMEDPIPE)
1125
	my_sleep(1000);				/* must wait after eof() */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1126
#endif
1127
      statistic_increment(aborted_connects,&LOCK_status);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1128 1129
      goto end_thread;
    }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1130
#ifdef __NETWARE__
1131
    netware_reg_user(sctx->ip, sctx->user, "MySQL");
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1132
#endif
1133
    if (thd->variables.max_join_size == HA_POS_ERROR)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1134 1135 1136 1137
      thd->options |= OPTION_BIG_SELECTS;
    if (thd->client_capabilities & CLIENT_COMPRESS)
      net->compress=1;				// Use compression

gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1138
    thd->version= refresh_version;
1139
    thd->proc_info= 0;
1140
    thd->command= COM_SLEEP;
1141 1142
    thd->set_time();
    thd->init_for_queries();
monty@mysql.com's avatar
monty@mysql.com committed
1143

1144
    if (sys_init_connect.value_length && !(sctx->master_access & SUPER_ACL))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1145
    {
1146 1147
      execute_init_command(thd, &sys_init_connect, &LOCK_sys_init_connect);
      if (thd->query_error)
pem@mysql.comhem.se's avatar
pem@mysql.comhem.se committed
1148
	thd->killed= THD::KILL_CONNECTION;
1149 1150 1151
      thd->proc_info=0;
      thd->set_time();
      thd->init_for_queries();
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1152 1153
    }

1154 1155
    while (!net->error && net->vio != 0 &&
           !(thd->killed == THD::KILL_CONNECTION))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1156
    {
1157
      net->no_send_error= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1158 1159 1160
      if (do_command(thd))
	break;
    }
1161 1162
    if (thd->user_connect)
      decrease_user_connections(thd->user_connect);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1163
    if (net->error && net->vio != 0 && net->report_error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1164
    {
1165
      if (!thd->killed && thd->variables.log_warnings > 1)
monty@mysql.com's avatar
monty@mysql.com committed
1166
	sql_print_warning(ER(ER_NEW_ABORTING_CONNECTION),
serg@serg.mylan's avatar
serg@serg.mylan committed
1167
                          thd->thread_id,(thd->db ? thd->db : "unconnected"),
1168 1169
                          sctx->user ? sctx->user : "unauthenticated",
                          sctx->host_or_ip,
serg@serg.mylan's avatar
serg@serg.mylan committed
1170 1171
                          (net->last_errno ? ER(net->last_errno) :
                           ER(ER_UNKNOWN_ERROR)));
1172
      net_send_error(thd, net->last_errno, NullS);
1173
      statistic_increment(aborted_threads,&LOCK_status);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1174
    }
1175 1176 1177 1178
    else if (thd->killed)
    {
      statistic_increment(aborted_threads,&LOCK_status);
    }
1179
    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1180
end_thread:
1181
    close_connection(thd, 0, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1182 1183 1184 1185 1186 1187
    end_thread(thd,1);
    /*
      If end_thread returns, we are either running with --one-thread
      or this thread has been schedule to handle the next query
    */
    thd= current_thd;
1188
    thd->thread_stack= (char*) &thd;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1189 1190 1191 1192 1193
  } while (!(test_flags & TEST_NO_THREADS));
  /* The following is only executed if we are not using --one-thread */
  return(0);					/* purecov: deadcode */
}

hf@deer.(none)'s avatar
hf@deer.(none) committed
1194 1195
#endif /* EMBEDDED_LIBRARY */

1196 1197 1198 1199
/*
  Execute commands from bootstrap_file.
  Used when creating the initial grant tables
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1200

1201
pthread_handler_t handle_bootstrap(void *arg)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1202
{
1203 1204 1205
  THD *thd=(THD*) arg;
  FILE *file=bootstrap_file;
  char *buff;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1206

1207
  /* The following must be called before DBUG_ENTER */
1208
  thd->thread_stack= (char*) &thd;
1209
  if (my_thread_init() || thd->store_globals())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1210
  {
hf@deer.(none)'s avatar
hf@deer.(none) committed
1211
#ifndef EMBEDDED_LIBRARY
1212
    close_connection(thd, ER_OUT_OF_RESOURCES, 1);
hf@deer.(none)'s avatar
hf@deer.(none) committed
1213
#endif
1214
    thd->fatal_error();
1215
    goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1216
  }
1217 1218
  DBUG_ENTER("handle_bootstrap");

hf@deer.(none)'s avatar
hf@deer.(none) committed
1219
#ifndef EMBEDDED_LIBRARY
1220 1221
  pthread_detach_this_thread();
  thd->thread_stack= (char*) &thd;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1222
#if !defined(__WIN__) && !defined(OS2) && !defined(__NETWARE__)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1223
  sigset_t set;
1224 1225
  VOID(sigemptyset(&set));			// Get mask in use
  VOID(pthread_sigmask(SIG_UNBLOCK,&set,&thd->block_signals));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1226
#endif
hf@deer.(none)'s avatar
hf@deer.(none) committed
1227
#endif /* EMBEDDED_LIBRARY */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1228

1229
  if (thd->variables.max_join_size == HA_POS_ERROR)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1230 1231 1232 1233
    thd->options |= OPTION_BIG_SELECTS;

  thd->proc_info=0;
  thd->version=refresh_version;
1234 1235
  thd->security_ctx->priv_user=
    thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1236

1237
  buff= (char*) thd->net.buff;
1238
  thd->init_for_queries();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1239 1240
  while (fgets(buff, thd->net.max_packet, file))
  {
monty@mishka.local's avatar
monty@mishka.local committed
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
   ulong length= (ulong) strlen(buff);
   while (buff[length-1] != '\n' && !feof(file))
   {
     /*
       We got only a part of the current string. Will try to increase
       net buffer then read the rest of the current string.
     */
     if (net_realloc(&(thd->net), 2 * thd->net.max_packet))
     {
       net_send_error(thd, ER_NET_PACKET_TOO_LARGE, NullS);
       thd->fatal_error();
       break;
     }
     buff= (char*) thd->net.buff;
     fgets(buff + length, thd->net.max_packet - length, file);
     length+= (ulong) strlen(buff + length);
   }
   if (thd->is_fatal_error)
     break;

1261
    while (length && (my_isspace(thd->charset(), buff[length-1]) ||
1262
           buff[length-1] == ';'))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1263 1264
      length--;
    buff[length]=0;
1265
    thd->query_length=length;
1266 1267
    thd->query= thd->memdup_w_gap(buff, length+1, 
				  thd->db_length+1+QUERY_CACHE_FLAGS_SIZE);
1268
    thd->query[length] = '\0';
1269 1270 1271 1272
    /*
      We don't need to obtain LOCK_thread_count here because in bootstrap
      mode we have only one thread.
    */
1273
    thd->query_id=next_query_id();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1274 1275
    mysql_parse(thd,thd->query,length);
    close_thread_tables(thd);			// Free tables
1276
    if (thd->is_fatal_error)
1277
      break;
1278
    free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
1279
#ifdef USING_TRANSACTIONS
1280
    free_root(&thd->transaction.mem_root,MYF(MY_KEEP_PREALLOC));
1281
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1282
  }
1283 1284 1285

  /* thd->fatal_error should be set in case something went wrong */
end:
1286 1287 1288 1289 1290 1291
  bootstrap_error= thd->is_fatal_error;

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

hf@deer.(none)'s avatar
hf@deer.(none) committed
1292
#ifndef EMBEDDED_LIBRARY
1293 1294 1295
  (void) pthread_mutex_lock(&LOCK_thread_count);
  thread_count--;
  (void) pthread_mutex_unlock(&LOCK_thread_count);
1296
  (void) pthread_cond_broadcast(&COND_thread_count);
1297 1298
  my_thread_end();
  pthread_exit(0);
hf@deer.(none)'s avatar
hf@deer.(none) committed
1299
#endif
1300
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1301 1302
}

1303
    /* This works because items are allocated with sql_alloc() */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1304

1305
void free_items(Item *item)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1306
{
1307
  Item *next;
monty@mysql.com's avatar
monty@mysql.com committed
1308
  DBUG_ENTER("free_items");
1309 1310 1311
  for (; item ; item=next)
  {
    next=item->next;
1312
    item->delete_self();
1313
  }
monty@mysql.com's avatar
monty@mysql.com committed
1314
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1315 1316
}

1317 1318 1319 1320
    /* This works because items are allocated with sql_alloc() */

void cleanup_items(Item *item)
{
monty@mysql.com's avatar
monty@mysql.com committed
1321
  DBUG_ENTER("cleanup_items");  
1322 1323
  for (; item ; item=item->next)
    item->cleanup();
monty@mysql.com's avatar
monty@mysql.com committed
1324
  DBUG_VOID_RETURN;
1325 1326
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1327 1328 1329 1330 1331 1332 1333
int mysql_table_dump(THD* thd, char* db, char* tbl_name, int fd)
{
  TABLE* table;
  TABLE_LIST* table_list;
  int error = 0;
  DBUG_ENTER("mysql_table_dump");
  db = (db && db[0]) ? db : thd->db;
1334
  if (!(table_list = (TABLE_LIST*) thd->calloc(sizeof(TABLE_LIST))))
1335
    DBUG_RETURN(1); // out of memory
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1336
  table_list->db= db;
1337
  table_list->table_name= table_list->alias= tbl_name;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1338 1339
  table_list->lock_type= TL_READ_NO_INSERT;
  table_list->prev_global= &table_list;	// can be removed after merge with 4.1
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1340

1341 1342
  if (!db || check_db_name(db))
  {
1343
    my_error(ER_WRONG_DB_NAME ,MYF(0), db ? db : "NULL");
1344 1345
    goto err;
  }
1346
  if (lower_case_table_names)
1347
    my_casedn_str(files_charset_info, tbl_name);
1348
  remove_escape(table_list->table_name);
1349 1350 1351 1352

  if (!(table=open_ltable(thd, table_list, TL_READ_NO_INSERT)))
    DBUG_RETURN(1);

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1353
  if (check_one_table_access(thd, SELECT_ACL, table_list))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1354 1355
    goto err;
  thd->free_list = 0;
1356
  thd->query_length=(uint) strlen(tbl_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1357
  thd->query = tbl_name;
1358
  if ((error = mysqld_dump_create_info(thd, table_list, -1)))
1359
  {
1360
    my_error(ER_GET_ERRNO, MYF(0), my_errno);
1361 1362
    goto err;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1363
  net_flush(&thd->net);
1364
  if ((error= table->file->dump(thd,fd)))
1365
    my_error(ER_GET_ERRNO, MYF(0), error);
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1366

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1367
err:
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1368
  DBUG_RETURN(error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1369 1370
}

1371 1372 1373 1374
/*
  Ends the current transaction and (maybe) begin the next

  SYNOPSIS
1375
    end_trans()
1376 1377 1378 1379 1380 1381 1382
      thd            Current thread
      completion     Completion type

  RETURN
    0 - OK
*/

1383
int end_trans(THD *thd, enum enum_mysql_completiontype completion)
1384 1385 1386
{
  bool do_release= 0;
  int res= 0;
1387
  DBUG_ENTER("end_trans");
1388

1389
  if (unlikely(thd->in_sub_stmt))
1390 1391 1392 1393
  {
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
    DBUG_RETURN(1);
  }
1394 1395 1396 1397 1398 1399
  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);
  }
1400 1401 1402 1403 1404 1405 1406 1407
  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;
1408
    res= ha_commit(thd);
1409
    thd->options&= ~(ulong) (OPTION_BEGIN | OPTION_STATUS_NO_TRANS_UPDATE);
1410 1411
    break;
  case COMMIT_RELEASE:
serg@serg.mylan's avatar
serg@serg.mylan committed
1412
    do_release= 1; /* fall through */
1413 1414 1415 1416 1417 1418
  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
1419
    do_release= 1; /* fall through */
1420 1421 1422 1423
  case ROLLBACK:
  case ROLLBACK_AND_CHAIN:
  {
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
serg@serg.mylan's avatar
serg@serg.mylan committed
1424
    if (ha_rollback(thd))
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
      res= -1;
    thd->options&= ~(ulong) (OPTION_BEGIN | OPTION_STATUS_NO_TRANS_UPDATE);
    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
1436

1437 1438 1439
  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
1440 1441
    thd->killed= THD::KILL_CONNECTION;

1442 1443
  DBUG_RETURN(res);
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1444

1445
#ifndef EMBEDDED_LIBRARY
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456

/*
  Read one command from socket and execute it (query or simple command).
  This function is called in loop from thread function.
  SYNOPSIS
    do_command()
  RETURN VALUE
    0  success
    1  request of thread shutdown (see dispatch_command() description)
*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1457 1458 1459
bool do_command(THD *thd)
{
  char *packet;
1460 1461
  uint old_timeout;
  ulong packet_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1462 1463 1464 1465 1466
  NET *net;
  enum enum_server_command command;
  DBUG_ENTER("do_command");

  net= &thd->net;
1467 1468 1469 1470
  /*
    indicator of uninitialized lex => normal flow of errors handling
    (see my_message_sql)
  */
1471
  thd->lex->current_select= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1472 1473

  packet=0;
1474
  old_timeout=net->read_timeout;
monty@mysql.com's avatar
monty@mysql.com committed
1475
  /* Wait max for 8 hours */
1476
  net->read_timeout=(uint) thd->variables.net_wait_timeout;
1477
  thd->clear_error();				// Clear error message
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1478 1479 1480 1481

  net_new_transaction(net);
  if ((packet_length=my_net_read(net)) == packet_error)
  {
1482 1483 1484 1485 1486
    DBUG_PRINT("info",("Got error %d reading command from socket %s",
		       net->error,
		       vio_description(net->vio)));
    /* Check if we can continue without closing the connection */
    if (net->error != 3)
1487 1488
    {
      statistic_increment(aborted_threads,&LOCK_status);
1489
      DBUG_RETURN(TRUE);			// We have to close it.
1490
    }
1491
    net_send_error(thd, net->last_errno, NullS);
1492
    net->error= 0;
1493
    DBUG_RETURN(FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1494 1495 1496 1497 1498
  }
  else
  {
    packet=(char*) net->read_pos;
    command = (enum enum_server_command) (uchar) packet[0];
1499 1500
    if (command >= COM_END)
      command= COM_END;				// Wrong command
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1501 1502 1503
    DBUG_PRINT("info",("Command on %s = %d (%s)",
		       vio_description(net->vio), command,
		       command_name[command]));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1504
  }
1505
  net->read_timeout=old_timeout;		// restore it
1506 1507 1508 1509 1510 1511 1512 1513 1514
  /*
    packet_length contains length of data, as it was stored in packet
    header. In case of malformed header, packet_length can be zero.
    If packet_length is not zero, my_net_read ensures that this number
    of bytes was actually read from network. Additionally my_net_read
    sets packet[packet_length]= 0 (thus if packet_length == 0,
    command == packet[0] == COM_SLEEP).
    In dispatch_command packet[packet_length] points beyond the end of packet.
  */
1515
  DBUG_RETURN(dispatch_command(command,thd, packet+1, (uint) packet_length));
1516
}
1517
#endif  /* EMBEDDED_LIBRARY */
1518

1519

1520 1521
/*
   Perform one connection-level (COM_XXXX) command.
1522

1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
  SYNOPSIS
    dispatch_command()
    thd             connection handle
    command         type of command to perform 
    packet          data for the command, packet is always null-terminated
    packet_length   length of packet + 1 (to show that data is
                    null-terminated) except for COM_SLEEP, where it
                    can be zero.
  RETURN VALUE
    0   ok
    1   request of thread shutdown, i. e. if command is
        COM_QUIT/COM_SHUTDOWN
*/
1536

1537 1538 1539 1540
bool dispatch_command(enum enum_server_command command, THD *thd,
		      char* packet, uint packet_length)
{
  NET *net= &thd->net;
1541
  bool error= 0;
1542 1543
  DBUG_ENTER("dispatch_command");

1544 1545 1546
  if (thd->killed == THD::KILL_QUERY || thd->killed == THD::KILL_BAD_DATA)
    thd->killed= THD::NOT_KILLED;

1547
  thd->command=command;
1548
  /*
1549 1550
    Commands which always take a long time are logged into
    the slow log only if opt_log_slow_admin_statements is set.
1551
  */
1552
  thd->enable_slow_log= TRUE;
1553
  thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
1554
  thd->set_time();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1555 1556 1557
  VOID(pthread_mutex_lock(&LOCK_thread_count));
  thd->query_id=query_id;
  if (command != COM_STATISTICS && command != COM_PING)
1558
    next_query_id();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1559
  thread_running++;
1560
  /* TODO: set thd->lex->sql_command to SQLCOM_END here */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1561
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
1562

1563 1564
  thd->server_status&=
           ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
1565
  switch (command) {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1566
  case COM_INIT_DB:
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1567 1568
  {
    LEX_STRING tmp;
1569 1570
    statistic_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB],
			&LOCK_status);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1571 1572
    thd->convert_string(&tmp, system_charset_info,
			packet, strlen(packet), thd->charset());
1573 1574
    if (!mysql_change_db(thd, tmp.str, FALSE))
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1575
      mysql_log.write(thd,command,"%s",thd->db);
1576 1577
      send_ok(thd);
    }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1578 1579
    break;
  }
1580
#ifdef HAVE_REPLICATION
1581 1582
  case COM_REGISTER_SLAVE:
  {
1583
    if (!register_slave(thd, (uchar*)packet, packet_length))
1584
      send_ok(thd);
1585 1586
    break;
  }
1587
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1588
  case COM_TABLE_DUMP:
1589 1590 1591 1592 1593
  {
    char *db, *tbl_name;
    uint db_len= *(uchar*) packet;
    uint tbl_len= *(uchar*) (packet + db_len + 1);

1594
    statistic_increment(thd->status_var.com_other, &LOCK_status);
1595
    thd->enable_slow_log= opt_log_slow_admin_statements;
1596 1597 1598
    db= thd->alloc(db_len + tbl_len + 2);
    tbl_name= strmake(db, packet + 1, db_len)+1;
    strmake(tbl_name, packet + db_len + 2, tbl_len);
1599
    mysql_table_dump(thd, db, tbl_name, -1);
1600 1601
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1602 1603
  case COM_CHANGE_USER:
  {
1604
    thd->change_user();
1605
    thd->clear_error();                         // if errors from rollback
1606

1607
    statistic_increment(thd->status_var.com_other, &LOCK_status);
1608
    char *user= (char*) packet;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1609
    char *passwd= strend(user)+1;
1610 1611 1612 1613 1614
    /* 
      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).
    */
1615
    char db_buff[NAME_LEN+1];                 // buffer to store db in utf8 
1616 1617 1618 1619
    char *db= passwd;
    uint passwd_len= thd->client_capabilities & CLIENT_SECURE_CONNECTION ? 
      *passwd++ : strlen(passwd);
    db+= passwd_len + 1;
1620
#ifndef EMBEDDED_LIBRARY
1621
    /* Small check for incoming packet */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1622
    if ((uint) ((uchar*) db - net->read_pos) > packet_length)
1623
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1624
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1625 1626
      break;
    }
1627
#endif
1628
    /* Convert database name to utf8 */
1629
    uint dummy_errors;
1630 1631
    db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
                             system_charset_info, db, strlen(db),
1632
                             thd->charset(), &dummy_errors)]= 0;
1633
    db= db_buff;
peter@mysql.com's avatar
peter@mysql.com committed
1634

1635 1636 1637
    /* Save user and privileges */
    uint save_db_length= thd->db_length;
    char *save_db= thd->db;
1638
    Security_context save_security_ctx= *thd->security_ctx;
1639
    USER_CONN *save_user_connect= thd->user_connect;
1640 1641

    if (!(thd->security_ctx->user= my_strdup(user, MYF(0))))
1642
    {
1643
      thd->security_ctx->user= save_security_ctx.user;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1644
      my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
1645 1646
      break;
    }
peter@mysql.com's avatar
peter@mysql.com committed
1647

1648 1649
    /* Clear variables that are allocated */
    thd->user_connect= 0;
monty@mysql.com's avatar
monty@mysql.com committed
1650
    int res= check_user(thd, COM_CHANGE_USER, passwd, passwd_len, db, FALSE);
peter@mysql.com's avatar
peter@mysql.com committed
1651

1652 1653
    if (res)
    {
1654
      /* authentication failure, we shall restore old user */
1655
      if (res > 0)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1656
        my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1657 1658
      x_free(thd->security_ctx->user);
      *thd->security_ctx= save_security_ctx;
1659
      thd->user_connect= save_user_connect;
1660 1661 1662 1663 1664 1665
      thd->db= save_db;
      thd->db_length= save_db_length;
    }
    else
    {
      /* we've authenticated new user */
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1666 1667
      if (save_user_connect)
	decrease_user_connections(save_user_connect);
1668
      x_free((gptr) save_db);
1669
      x_free((gptr)  save_security_ctx.user);
1670
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1671 1672
    break;
  }
1673
  case COM_STMT_EXECUTE:
1674
  {
1675
    mysql_stmt_execute(thd, packet, packet_length);
1676 1677
    break;
  }
1678
  case COM_STMT_FETCH:
1679 1680 1681 1682
  {
    mysql_stmt_fetch(thd, packet, packet_length);
    break;
  }
1683
  case COM_STMT_SEND_LONG_DATA:
1684
  {
1685
    mysql_stmt_get_longdata(thd, packet, packet_length);
1686 1687
    break;
  }
1688
  case COM_STMT_PREPARE:
1689
  {
1690
    mysql_stmt_prepare(thd, packet, packet_length);
1691 1692
    break;
  }
1693
  case COM_STMT_CLOSE:
1694
  {
1695
    mysql_stmt_close(thd, packet);
1696 1697
    break;
  }
1698
  case COM_STMT_RESET:
1699 1700 1701 1702
  {
    mysql_stmt_reset(thd, packet);
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1703 1704
  case COM_QUERY:
  {
1705 1706
    if (alloc_query(thd, packet, packet_length))
      break;					// fatal error is set
1707
    char *packet_end= thd->query + thd->query_length;
1708
    mysql_log.write(thd,command,"%s",thd->query);
1709
    DBUG_PRINT("query",("%-.4096s",thd->query));
1710 1711 1712 1713

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

1714
    mysql_parse(thd,thd->query, thd->query_length);
1715

1716
    while (!thd->killed && thd->lex->found_semicolon && !thd->net.report_error)
1717
    {
1718
      char *packet= thd->lex->found_semicolon;
1719
      net->no_send_error= 0;
1720
      /*
1721
        Multiple queries exits, execute them individually
1722
	in embedded server - just store them to be executed later 
1723
      */
1724
#ifndef EMBEDDED_LIBRARY
1725 1726
      if (thd->lock || thd->open_tables || thd->derived_tables ||
          thd->prelocked_mode)
1727
        close_thread_tables(thd);
1728
#endif
1729
      ulong length= (ulong)(packet_end-packet);
1730

1731
      log_slow_statement(thd);
1732

1733
      /* Remove garbage at start of query */
1734
      while (my_isspace(thd->charset(), *packet) && length > 0)
1735 1736 1737 1738
      {
        packet++;
        length--;
      }
monty@mysql.com's avatar
monty@mysql.com committed
1739
      VOID(pthread_mutex_lock(&LOCK_thread_count));
1740
      thd->query_length= length;
1741
      thd->query= packet;
1742
      thd->query_id= next_query_id();
1743
      thd->set_time(); /* Reset the query start time. */
1744
      /* TODO: set thd->lex->sql_command to SQLCOM_END here */
1745
      VOID(pthread_mutex_unlock(&LOCK_thread_count));
1746
#ifndef EMBEDDED_LIBRARY
1747
      mysql_parse(thd, packet, length);
1748
#else
hf@deer.(none)'s avatar
hf@deer.(none) committed
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
      /*
	'packet' can point inside the query_rest's buffer
	so we have to do memmove here
       */
      if (thd->query_rest.length() > length)
      {
	memmove(thd->query_rest.c_ptr(), packet, length);
	thd->query_rest.length(length);
      }
      else
1759
	thd->query_rest.copy(packet, length, thd->query_rest.charset());
1760 1761 1762

      thd->server_status&= ~ (SERVER_QUERY_NO_INDEX_USED |
                              SERVER_QUERY_NO_GOOD_INDEX_USED);
1763 1764
      break;
#endif /*EMBEDDED_LIBRARY*/
1765 1766
    }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1767 1768 1769 1770 1771
    if (!(specialflag & SPECIAL_NO_PRIOR))
      my_pthread_setprio(pthread_self(),WAIT_PRIOR);
    DBUG_PRINT("info",("query ready"));
    break;
  }
1772
  case COM_FIELD_LIST:				// This isn't actually needed
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1773
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1774 1775
    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
1776 1777 1778
    break;
#else
  {
1779
    char *fields, *pend;
1780 1781
    /* Locked closure of all tables */
    TABLE_LIST *locked_tables= NULL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1782
    TABLE_LIST table_list;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1783
    LEX_STRING conv_name;
1784
    /* Saved variable value */
1785 1786
    my_bool old_innodb_table_locks= 
              IF_INNOBASE_DB(thd->variables.innodb_table_locks, FALSE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1787 1788
    /* used as fields initializator */
    lex_start(thd, 0, 0);
1789

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1790

1791 1792
    statistic_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS],
			&LOCK_status);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1793 1794 1795
    bzero((char*) &table_list,sizeof(table_list));
    if (!(table_list.db=thd->db))
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1796
      my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1797 1798
      break;
    }
1799
    pend= strend(packet);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1800 1801
    thd->convert_string(&conv_name, system_charset_info,
			packet, (uint) (pend-packet), thd->charset());
1802
    table_list.alias= table_list.table_name= conv_name.str;
1803
    packet= pend+1;
1804 1805 1806 1807 1808 1809 1810 1811 1812

    if (!my_strcasecmp(system_charset_info, table_list.db,
                       information_schema_name.str))
    {
      ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, table_list.alias);
      if (schema_table)
        table_list.schema_table= schema_table;
    }

1813
    thd->query_length= strlen(packet);       // for simplicity: don't optimize
1814 1815
    if (!(thd->query=fields=thd->memdup(packet,thd->query_length+1)))
      break;
1816
    mysql_log.write(thd,command,"%s %s",table_list.table_name, fields);
1817
    if (lower_case_table_names)
1818 1819
      my_casedn_str(files_charset_info, table_list.table_name);
    remove_escape(table_list.table_name);	// This can't have wildcards
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1820

monty@mysql.com's avatar
monty@mysql.com committed
1821
    if (check_access(thd,SELECT_ACL,table_list.db,&table_list.grant.privilege,
1822
		     0, 0, test(table_list.schema_table)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1823
      break;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1824 1825
    if (grant_option &&
	check_grant(thd, SELECT_ACL, &table_list, 2, UINT_MAX, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1826
      break;
1827 1828 1829 1830 1831 1832
    /* init structures for VIEW processing */
    table_list.select_lex= &(thd->lex->select_lex);
    mysql_init_query(thd, (uchar*)"", 0);
    thd->lex->
      select_lex.table_list.link_in_list((byte*) &table_list,
                                         (byte**) &table_list.next_local);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
1833
    thd->lex->add_to_query_tables(&table_list);
1834

1835 1836
    /* 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
1837
    mysqld_list_fields(thd,&table_list,fields);
1838
    thd->lex->unit.cleanup();
1839
    thd->cleanup_after_query();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1840 1841 1842 1843
    break;
  }
#endif
  case COM_QUIT:
1844
    /* We don't calculate statistics for this command */
1845
    mysql_log.write(thd,command,NullS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1846 1847 1848 1849
    net->error=0;				// Don't give 'abort' message
    error=TRUE;					// End server
    break;

1850
  case COM_CREATE_DB:				// QQ: To be removed
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1851
    {
1852
      char *db=thd->strdup(packet), *alias;
1853
      HA_CREATE_INFO create_info;
1854

1855 1856
      statistic_increment(thd->status_var.com_stat[SQLCOM_CREATE_DB],
			  &LOCK_status);
1857
      // null test to handle EOM
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
1858
      if (!db || !(alias= thd->strdup(db)) || check_db_name(db))
1859
      {
1860
	my_error(ER_WRONG_DB_NAME, MYF(0), db ? db : "NULL");
1861 1862
	break;
      }
1863
      if (check_access(thd,CREATE_ACL,db,0,1,0,is_schema_db(db)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1864
	break;
1865
      mysql_log.write(thd,command,packet);
1866
      bzero(&create_info, sizeof(create_info));
1867 1868
      mysql_create_db(thd, (lower_case_table_names == 2 ? alias : db),
                      &create_info, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1869 1870
      break;
    }
1871
  case COM_DROP_DB:				// QQ: To be removed
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1872
    {
1873 1874
      statistic_increment(thd->status_var.com_stat[SQLCOM_DROP_DB],
			  &LOCK_status);
1875
      char *db=thd->strdup(packet);
monty@mysql.com's avatar
monty@mysql.com committed
1876
      /*  null test to handle EOM */
1877
      if (!db || check_db_name(db))
1878
      {
1879
	my_error(ER_WRONG_DB_NAME, MYF(0), db ? db : "NULL");
1880 1881
	break;
      }
1882
      if (check_access(thd,DROP_ACL,db,0,1,0,is_schema_db(db)))
1883
	break;
1884 1885
      if (thd->locked_tables || thd->active_transaction())
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1886 1887
	my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                   ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1888
	break;
1889
      }
1890
      mysql_log.write(thd,command,db);
1891
      mysql_rm_db(thd, db, 0, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1892 1893
      break;
    }
1894
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1895 1896
  case COM_BINLOG_DUMP:
    {
monty@mysql.com's avatar
monty@mysql.com committed
1897 1898 1899 1900
      ulong pos;
      ushort flags;
      uint32 slave_server_id;

1901
      statistic_increment(thd->status_var.com_other,&LOCK_status);
1902
      thd->enable_slow_log= opt_log_slow_admin_statements;
1903
      if (check_global_access(thd, REPL_SLAVE_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1904
	break;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1905

1906
      /* TODO: The following has to be changed to an 8 byte integer */
1907 1908
      pos = uint4korr(packet);
      flags = uint2korr(packet + 4);
1909
      thd->server_id=0; /* avoid suicide */
1910
      if ((slave_server_id= uint4korr(packet+6))) // mysqlbinlog.server_id==0
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
1911
	kill_zombie_dump_threads(slave_server_id);
1912
      thd->server_id = slave_server_id;
monty@mysql.com's avatar
monty@mysql.com committed
1913 1914 1915

      mysql_log.write(thd, command, "Log: '%s'  Pos: %ld", packet+10,
                      (long) pos);
1916
      mysql_binlog_send(thd, thd->strdup(packet + 10), (my_off_t) pos, flags);
1917
      unregister_slave(thd,1,1);
monty@mysql.com's avatar
monty@mysql.com committed
1918
      /*  fake COM_QUIT -- if we get here, the thread needs to terminate */
1919 1920
      error = TRUE;
      net->error = 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1921 1922
      break;
    }
1923
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1924
  case COM_REFRESH:
1925 1926 1927 1928 1929 1930
  {
    bool not_used;
    statistic_increment(thd->status_var.com_stat[SQLCOM_FLUSH],
                        &LOCK_status);
    ulong options= (ulong) (uchar) packet[0];
    if (check_global_access(thd,RELOAD_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1931
      break;
1932 1933 1934 1935 1936
    mysql_log.write(thd,command,NullS);
    if (!reload_acl_and_cache(thd, options, (TABLE_LIST*) 0, &not_used))
      send_ok(thd);
    break;
  }
1937
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1938
  case COM_SHUTDOWN:
1939
  {
1940
    statistic_increment(thd->status_var.com_other, &LOCK_status);
1941
    if (check_global_access(thd,SHUTDOWN_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1942
      break; /* purecov: inspected */
1943
    /*
1944 1945 1946 1947
      If the client is < 4.1.3, it is going to send us no argument; then
      packet_length is 1, packet[0] is the end 0 of the packet. Note that
      SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in
      packet[0].
1948
    */
1949 1950
    enum mysql_enum_shutdown_level level=
      (enum mysql_enum_shutdown_level) (uchar) packet[0];
1951
    DBUG_PRINT("quit",("Got shutdown command for level %u", level));
1952 1953 1954 1955 1956 1957 1958
    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;
    }
1959
    DBUG_PRINT("quit",("Got shutdown command for level %u", level));
1960
    mysql_log.write(thd,command,NullS);
1961
    send_eof(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1962 1963 1964
#ifdef __WIN__
    sleep(1);					// must wait after eof()
#endif
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1965
#ifndef OS2
1966
    send_eof(thd);				// This is for 'quit request'
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1967
#endif
1968
    close_connection(thd, 0, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1969 1970 1971 1972
    close_thread_tables(thd);			// Free before kill
    kill_mysql();
    error=TRUE;
    break;
1973
  }
1974
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1975 1976
  case COM_STATISTICS:
  {
1977
    mysql_log.write(thd,command,NullS);
1978 1979
    statistic_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS],
			&LOCK_status);
hf@deer.(none)'s avatar
hf@deer.(none) committed
1980
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1981
    char buff[200];
hf@deer.(none)'s avatar
hf@deer.(none) committed
1982 1983 1984
#else
    char *buff= thd->net.last_error;
#endif
1985
    ulong uptime = (ulong) (thd->start_time - start_time);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1986
    sprintf((char*) buff,
1987
	    "Uptime: %lu  Threads: %d  Questions: %lu  Slow queries: %lu  Opens: %lu  Flush tables: %lu  Open tables: %u  Queries per second avg: %.3f",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1988
	    uptime,
1989 1990 1991
	    (int) thread_count, (ulong) thd->query_id,
            (ulong) thd->status_var.long_query_count,
	    thd->status_var.opened_tables, refresh_version, cached_tables(),
1992 1993
	    (uptime ? (ulonglong2double(thd->query_id) / (double) uptime) :
	     (double) 0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1994
#ifdef SAFEMALLOC
1995
    if (sf_malloc_cur_memory)				// Using SAFEMALLOC
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1996
      sprintf(strend(buff), "  Memory in use: %ldK  Max memory used: %ldK",
1997 1998
	      (sf_malloc_cur_memory+1023L)/1024L,
	      (sf_malloc_max_memory+1023L)/1024L);
hf@deer.(none)'s avatar
hf@deer.(none) committed
1999 2000
#endif
#ifndef EMBEDDED_LIBRARY
2001
    VOID(my_net_write(net, buff,(uint) strlen(buff)));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2002
    VOID(net_flush(net));
hf@deer.(none)'s avatar
hf@deer.(none) committed
2003
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2004 2005 2006
    break;
  }
  case COM_PING:
2007
    statistic_increment(thd->status_var.com_other, &LOCK_status);
2008
    send_ok(thd);				// Tell client we are alive
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2009 2010
    break;
  case COM_PROCESS_INFO:
2011 2012
    statistic_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST],
			&LOCK_status);
2013 2014
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd, PROCESS_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2015
      break;
2016
    mysql_log.write(thd,command,NullS);
hf@deer.(none)'s avatar
hf@deer.(none) committed
2017
    mysqld_list_processes(thd,
2018 2019
			  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
2020 2021 2022
    break;
  case COM_PROCESS_KILL:
  {
2023
    statistic_increment(thd->status_var.com_stat[SQLCOM_KILL], &LOCK_status);
2024
    ulong id=(ulong) uint4korr(packet);
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
2025
    kill_one_thread(thd,id,false);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2026 2027
    break;
  }
2028 2029
  case COM_SET_OPTION:
  {
2030 2031
    statistic_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION],
			&LOCK_status);
2032 2033 2034 2035
    enum_mysql_set_option command= (enum_mysql_set_option) uint2korr(packet);
    switch (command) {
    case MYSQL_OPTION_MULTI_STATEMENTS_ON:
      thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
2036
      send_eof(thd);
2037 2038 2039
      break;
    case MYSQL_OPTION_MULTI_STATEMENTS_OFF:
      thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
2040
      send_eof(thd);
2041 2042
      break;
    default:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2043
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
2044 2045 2046 2047
      break;
    }
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2048
  case COM_DEBUG:
2049
    statistic_increment(thd->status_var.com_other, &LOCK_status);
2050
    if (check_global_access(thd, SUPER_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2051
      break;					/* purecov: inspected */
2052
    mysql_print_status();
2053
    mysql_log.write(thd,command,NullS);
2054
    send_eof(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2055 2056 2057 2058 2059
    break;
  case COM_SLEEP:
  case COM_CONNECT:				// Impossible here
  case COM_TIME:				// Impossible from client
  case COM_DELAYED_INSERT:
2060
  case COM_END:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2061
  default:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2062
    my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2063 2064
    break;
  }
2065 2066
  if (thd->lock || thd->open_tables || thd->derived_tables ||
      thd->prelocked_mode)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2067 2068 2069 2070
  {
    thd->proc_info="closing tables";
    close_thread_tables(thd);			/* Free tables */
  }
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
  /*
    assume handlers auto-commit (if some doesn't - transaction handling
    in MySQL should be redesigned to support it; it's a big change,
    and it's not worth it - better to commit explicitly only writing
    transactions, read-only ones should better take care of themselves.
    saves some work in 2pc too)
    see also sql_base.cc - close_thread_tables()
  */
  bzero(&thd->transaction.stmt, sizeof(thd->transaction.stmt));
  if (!thd->active_transaction())
2081
    thd->transaction.xid_state.xid.null();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2082

2083 2084 2085
  /* report error issued during command execution */
  if (thd->killed_errno() && !thd->net.report_error)
    thd->send_kill_message();
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2086
  if (thd->net.report_error)
2087
    net_send_error(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2088

2089
  log_slow_statement(thd);
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104

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


2105
void log_slow_statement(THD *thd)
2106
{
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
  time_t start_of_query;

  /*
    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))
    return;                                     // Don't set time for sub stmt

  start_of_query= thd->start_time;
2118
  thd->end_time();				// Set start time
2119

2120 2121 2122 2123 2124
  /*
    Do not log administrative statements unless the appropriate option is
    set; do not log into slow log if reading from backup.
  */
  if (thd->enable_slow_log && !thd->user_time)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2125
  {
2126 2127
    thd->proc_info="logging slow query";

2128 2129
    if ((ulong) (thd->start_time - thd->time_after_lock) >
	thd->variables.long_query_time ||
2130 2131
	((thd->server_status &
	  (SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED)) &&
2132
	 (specialflag & SPECIAL_LOG_QUERIES_NOT_USING_INDEXES)))
2133
    {
2134
      thd->status_var.long_query_count++;
2135 2136
      mysql_slow_log.write(thd, thd->query, thd->query_length, start_of_query);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2137 2138 2139
  }
}

2140

2141 2142 2143 2144 2145
int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident,
                         enum enum_schema_tables schema_table_idx)
{
  DBUG_ENTER("prepare_schema_table");
  SELECT_LEX *sel= 0;
2146
  switch (schema_table_idx) {
2147 2148
  case SCH_SCHEMATA:
#if defined(DONT_ALLOW_SHOW_COMMANDS)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2149 2150
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0));   /* purecov: inspected */
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
    DBUG_RETURN(1);
#else
    if ((specialflag & SPECIAL_SKIP_SHOW_DB) &&
	check_global_access(thd, SHOW_DB_ACL))
      DBUG_RETURN(1);
    break;
#endif
  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
2161
  case SCH_TRIGGERS:
2162
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2163 2164
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
2165 2166 2167 2168 2169 2170
    DBUG_RETURN(1);
#else
    {
      char *db= lex->select_lex.db ? lex->select_lex.db : thd->db;
      if (!db)
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2171 2172
	my_message(ER_NO_DB_ERROR,
                   ER(ER_NO_DB_ERROR), MYF(0)); /* purecov: inspected */
2173 2174 2175 2176 2177
        DBUG_RETURN(1);				/* purecov: inspected */
      }
      remove_escape(db);				// Fix escaped '_'
      if (check_db_name(db))
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2178
        my_error(ER_WRONG_DB_NAME, MYF(0), db);
2179 2180
        DBUG_RETURN(1);
      }
2181 2182
      if (check_access(thd, SELECT_ACL, db, &thd->col_access, 0, 0,
                       is_schema_db(db)))
2183 2184 2185
        DBUG_RETURN(1);			        /* purecov: inspected */
      if (!thd->col_access && check_grant_db(thd,db))
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2186
	my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
2187 2188
                 thd->security_ctx->priv_user, thd->security_ctx->priv_host,
                 db);
2189 2190
	DBUG_RETURN(1);
      }
2191 2192 2193 2194 2195
      /*
        We need to do a copy to make this prepared statement safe if this
        was thd->db
      */
      lex->select_lex.db= thd->strdup(db);
2196 2197 2198 2199 2200 2201
      break;
    }
#endif
  case SCH_COLUMNS:
  case SCH_STATISTICS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2202 2203
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */
2204 2205 2206 2207 2208 2209
    DBUG_RETURN(1);
#else
    if (table_ident)
    {
      TABLE_LIST **query_tables_last= lex->query_tables_last;
      sel= new SELECT_LEX();
2210 2211
      /* 'parent_lex' is used in init_query() so it must be before it. */
      sel->parent_lex= lex;
2212
      sel->init_query();
monty@mishka.local's avatar
monty@mishka.local committed
2213
      if (!sel->add_table_to_list(thd, table_ident, 0, 0, TL_READ, 
2214 2215 2216 2217 2218 2219
                                 (List<String> *) 0, (List<String> *) 0))
        DBUG_RETURN(1);
      lex->query_tables_last= query_tables_last;
      TABLE_LIST *table_list= (TABLE_LIST*) sel->table_list.first;
      char *db= table_list->db;
      remove_escape(db);			// Fix escaped '_'
2220
      remove_escape(table_list->table_name);
2221
      if (check_access(thd,SELECT_ACL | EXTRA_ACL,db,
2222 2223
                       &table_list->grant.privilege, 0, 0,
                       test(table_list->schema_table)))
2224 2225 2226 2227 2228 2229 2230
        DBUG_RETURN(1);				/* purecov: inspected */
      if (grant_option && check_grant(thd, SELECT_ACL, table_list, 2,
                                      UINT_MAX, 0))
        DBUG_RETURN(1);
      break;
    }
#endif
2231 2232 2233
  case SCH_OPEN_TABLES:
  case SCH_VARIABLES:
  case SCH_STATUS:
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254
  case SCH_PROCEDURES:
  case SCH_CHARSETS:
  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;
  table_list->schema_select_lex= sel;
2255
  table_list->schema_table_reformed= 1;
2256 2257
  statistic_increment(thd->status_var.com_stat[lex->orig_sql_command],
                      &LOCK_status);
2258 2259 2260 2261
  DBUG_RETURN(0);
}


2262 2263
/*
  Read query from packet and store in thd->query
2264
  Used in COM_QUERY and COM_STMT_PREPARE
2265 2266 2267 2268 2269 2270 2271

  DESCRIPTION
    Sets the following THD variables:
      query
      query_length

  RETURN VALUES
2272 2273
    FALSE ok
    TRUE  error;  In this case thd->fatal_error is set
2274 2275
*/

2276
bool alloc_query(THD *thd, const char *packet, uint packet_length)
2277 2278
{
  packet_length--;				// Remove end null
2279
  /* Remove garbage at start and end of query */
2280
  while (my_isspace(thd->charset(),packet[0]) && packet_length > 0)
2281 2282 2283 2284
  {
    packet++;
    packet_length--;
  }
2285
  const char *pos= packet + packet_length;     // Point at end null
peter@mysql.com's avatar
peter@mysql.com committed
2286
  while (packet_length > 0 &&
2287
	 (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1])))
2288 2289 2290 2291 2292
  {
    pos--;
    packet_length--;
  }
  /* We must allocate some extra memory for query cache */
monty@mysql.com's avatar
monty@mysql.com committed
2293
  thd->query_length= 0;                        // Extra safety: Avoid races
2294 2295
  if (!(thd->query= (char*) thd->memdup_w_gap((gptr) (packet),
					      packet_length,
2296 2297
					      thd->db_length+ 1 +
					      QUERY_CACHE_FLAGS_SIZE)))
2298
    return TRUE;
2299 2300
  thd->query[packet_length]=0;
  thd->query_length= packet_length;
2301 2302 2303 2304

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

2306
  return FALSE;
2307 2308
}

2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
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;
  thd->one_shot_set= 0;
}

2325

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2326 2327 2328 2329 2330
/****************************************************************************
** mysql_execute_command
** Execute command saved in thd and current_lex->sql_command
****************************************************************************/

2331
bool
2332
mysql_execute_command(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2333
{
2334
  bool	res= FALSE;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2335
  int result= 0;
2336
  LEX	*lex= thd->lex;
monty@mysql.com's avatar
monty@mysql.com committed
2337
  /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2338
  SELECT_LEX *select_lex= &lex->select_lex;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2339
  /* first table of first SELECT_LEX */
monty@mysql.com's avatar
monty@mysql.com committed
2340
  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
2341 2342 2343
  /* list of all tables in query */
  TABLE_LIST *all_tables;
  /* most outer SELECT_LEX_UNIT of query */
2344
  SELECT_LEX_UNIT *unit= &lex->unit;
2345
  /* Saved variable value */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2346
  DBUG_ENTER("mysql_execute_command");
2347
  thd->net.no_send_error= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2348

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
  /*
    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();
2365
  /* should be assigned after making first tables same */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2366
  all_tables= lex->query_tables;
2367 2368 2369 2370
  /* 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
2371

2372 2373 2374 2375 2376
  /*
    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.
2377
    Don't reset warnings when executing a stored routine.
2378
  */
2379
  if ((all_tables || &lex->select_lex != lex->all_selects_list ||
2380
       lex->sroutines.records) && !thd->spcont ||
2381
      lex->time_zone_tables_used)
monty@mysql.com's avatar
monty@mysql.com committed
2382
    mysql_reset_errors(thd, 0);
2383

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2384
#ifdef HAVE_REPLICATION
2385
  if (unlikely(thd->slave_thread))
2386
  {
peter@mysql.com's avatar
peter@mysql.com committed
2387
    /*
2388 2389
      Check if statment should be skipped because of slave filtering
      rules
2390 2391

      Exceptions are:
2392 2393
      - UPDATE MULTI: For this statement, we want to check the filtering
        rules later in the code
2394
      - SET: we always execute it (Not that many SET commands exists in
lars@mysql.com's avatar
lars@mysql.com committed
2395 2396
        the binary log anyway -- only 4.1 masters write SET statements,
	in 5.0 there are no SET statements in the binary log)
2397 2398
      - 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
2399
    */
2400 2401
    if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) &&
	!(lex->sql_command == SQLCOM_SET_OPTION) &&
2402
	!(lex->sql_command == SQLCOM_DROP_TABLE &&
2403
          lex->drop_temporary && lex->drop_if_exists) &&
guilhem@mysql.com's avatar
Merge  
guilhem@mysql.com committed
2404
        all_tables_not_ok(thd, all_tables))
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2405 2406
    {
      /* we warn the slave SQL thread */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2407
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2408
      reset_one_shot_variables(thd);
2409
      DBUG_RETURN(0);
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2410
    }
2411
  }
2412
  else
2413
#endif /* HAVE_REPLICATION */
2414

2415
  /*
2416 2417
    When option readonly is set deny operations which change non-temporary
    tables. Except for the replication thread and the 'super' users.
2418 2419
  */
  if (opt_readonly &&
2420 2421 2422 2423 2424 2425
      !(thd->security_ctx->master_access & SUPER_ACL) &&
      uc_update_queries[lex->sql_command] &&
      !((lex->sql_command == SQLCOM_CREATE_TABLE) &&
        (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE)) &&
      ((lex->sql_command != SQLCOM_UPDATE_MULTI) &&
       some_non_temp_table_to_be_updated(thd, all_tables)))
2426
  {
2427
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
2428
    DBUG_RETURN(-1);
2429
  }
2430 2431 2432
  if(lex->orig_sql_command == SQLCOM_END)
    statistic_increment(thd->status_var.com_stat[lex->sql_command],
                        &LOCK_status);
2433

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2434 2435 2436
  switch (lex->sql_command) {
  case SQLCOM_SELECT:
  {
2437 2438 2439 2440
    /* assign global limit variable if limit is not given */
    {
      SELECT_LEX *param= lex->unit.global_parameters;
      if (!param->explicit_limit)
2441 2442
	param->select_limit=
          new Item_int((ulonglong)thd->variables.select_limit);
2443 2444
    }

2445
    select_result *result=lex->result;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2446
    if (all_tables)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2447
    {
2448 2449 2450 2451 2452 2453
      if (lex->orig_sql_command != SQLCOM_SHOW_STATUS_PROC &&
          lex->orig_sql_command != SQLCOM_SHOW_STATUS_FUNC)
        res= check_table_access(thd,
                                lex->exchange ? SELECT_ACL | FILE_ACL :
                                SELECT_ACL,
                                all_tables, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2454 2455
    }
    else
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2456 2457
      res= check_access(thd,
			lex->exchange ? SELECT_ACL | FILE_ACL : SELECT_ACL,
2458
			any_db, 0, 0, 0, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2459
    if (res)
2460
      goto error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2461

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2462
    if (!(res= open_and_lock_tables(thd, all_tables)))
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2463
    {
2464
      if (lex->describe)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2465
      {
2466 2467 2468 2469 2470 2471
        /*
          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.
        */
2472
	if (!(result= new select_send()))
2473
	  goto error;
2474 2475
	else
	  thd->send_explain_fields(result);
2476
	res= mysql_explain_union(thd, &thd->lex->unit, result);
2477 2478 2479 2480 2481
	if (lex->describe & DESCRIBE_EXTENDED)
	{
	  char buff[1024];
	  String str(buff,(uint32) sizeof(buff), system_charset_info);
	  str.length(0);
pem@mysql.comhem.se's avatar
pem@mysql.comhem.se committed
2482
	  thd->lex->unit.print(&str);
2483 2484 2485 2486
	  str.append('\0');
	  push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
		       ER_YES, str.ptr());
	}
2487
	result->send_eof();
2488
        delete result;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2489 2490 2491
      }
      else
      {
2492
	if (!result && !(result= new select_send()))
2493
          goto error;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2494
	query_cache_store_query(thd, all_tables);
2495
	res= handle_select(thd, lex, result, 0);
2496 2497
        if (result != lex->result)
          delete result;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2498
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2499
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2500 2501
    break;
  }
sergefp@mysql.com's avatar
sergefp@mysql.com committed
2502
  case SQLCOM_PREPARE:
2503
  {
2504
    mysql_sql_stmt_prepare(thd);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
2505 2506 2507 2508
    break;
  }
  case SQLCOM_EXECUTE:
  {
2509
    mysql_sql_stmt_execute(thd);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
2510 2511 2512 2513
    break;
  }
  case SQLCOM_DEALLOCATE_PREPARE:
  {
2514
    mysql_sql_stmt_close(thd);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
2515 2516
    break;
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2517
  case SQLCOM_DO:
2518 2519
    if (check_table_access(thd, SELECT_ACL, all_tables, 0) ||
        open_and_lock_tables(thd, all_tables))
2520
      goto error;
2521 2522

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

2525
  case SQLCOM_EMPTY_QUERY:
2526
    send_ok(thd);
2527 2528
    break;

2529 2530 2531 2532
  case SQLCOM_HELP:
    res= mysqld_help(thd,lex->help_arg);
    break;

2533
#ifndef EMBEDDED_LIBRARY
2534
  case SQLCOM_PURGE:
2535
  {
2536
    if (check_global_access(thd, SUPER_ACL))
2537
      goto error;
monty@mysql.com's avatar
monty@mysql.com committed
2538
    /* PURGE MASTER LOGS TO 'file' */
2539 2540 2541
    res = purge_master_logs(thd, lex->to_log);
    break;
  }
2542 2543
  case SQLCOM_PURGE_BEFORE:
  {
2544 2545
    Item *it;

2546 2547
    if (check_global_access(thd, SUPER_ACL))
      goto error;
monty@mysql.com's avatar
monty@mysql.com committed
2548
    /* PURGE MASTER LOGS BEFORE 'data' */
2549
    it= (Item *)lex->value_list.head();
2550
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) ||
2551
        it->check_cols(1))
2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
    {
      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());
2563 2564
    break;
  }
2565
#endif
2566 2567
  case SQLCOM_SHOW_WARNS:
  {
2568 2569
    res= mysqld_show_warnings(thd, (ulong)
			      ((1L << (uint) MYSQL_ERROR::WARN_LEVEL_NOTE) |
2570 2571 2572
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_WARN) |
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR)
			       ));
2573 2574 2575 2576
    break;
  }
  case SQLCOM_SHOW_ERRORS:
  {
2577 2578
    res= mysqld_show_warnings(thd, (ulong)
			      (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR));
2579 2580
    break;
  }
2581 2582
  case SQLCOM_SHOW_NEW_MASTER:
  {
2583
    if (check_global_access(thd, REPL_SLAVE_ACL))
2584
      goto error;
2585
    /* This query don't work now. See comment in repl_failsafe.cc */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2586
#ifndef WORKING_NEW_MASTER
2587 2588
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "SHOW NEW MASTER");
    goto error;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2589
#else
2590 2591
    res = show_new_master(thd);
    break;
2592
#endif
2593
  }
2594

2595
#ifdef HAVE_REPLICATION
2596 2597
  case SQLCOM_SHOW_SLAVE_HOSTS:
  {
2598
    if (check_global_access(thd, REPL_SLAVE_ACL))
2599 2600 2601 2602
      goto error;
    res = show_slave_hosts(thd);
    break;
  }
2603 2604
  case SQLCOM_SHOW_BINLOG_EVENTS:
  {
2605
    if (check_global_access(thd, REPL_SLAVE_ACL))
2606
      goto error;
2607
    res = mysql_show_binlog_events(thd);
2608 2609
    break;
  }
2610 2611
#endif

2612
  case SQLCOM_BACKUP_TABLE:
2613
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2614 2615 2616
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_db_used(thd, all_tables) ||
	check_table_access(thd, SELECT_ACL, all_tables, 0) ||
2617
	check_global_access(thd, FILE_ACL))
2618
      goto error; /* purecov: inspected */
2619
    thd->enable_slow_log= opt_log_slow_admin_statements;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2620
    res = mysql_backup_table(thd, first_table);
2621
    select_lex->table_list.first= (byte*) first_table;
2622
    lex->query_tables=all_tables;
2623 2624
    break;
  }
2625
  case SQLCOM_RESTORE_TABLE:
2626
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2627 2628 2629
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_db_used(thd, all_tables) ||
	check_table_access(thd, INSERT_ACL, all_tables, 0) ||
2630
	check_global_access(thd, FILE_ACL))
2631
      goto error; /* purecov: inspected */
2632
    thd->enable_slow_log= opt_log_slow_admin_statements;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2633
    res = mysql_restore_table(thd, first_table);
2634
    select_lex->table_list.first= (byte*) first_table;
2635
    lex->query_tables=all_tables;
2636 2637
    break;
  }
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2638 2639
  case SQLCOM_ASSIGN_TO_KEYCACHE:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2640 2641 2642
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_db_used(thd, all_tables) ||
        check_access(thd, INDEX_ACL, first_table->db,
2643 2644
                     &first_table->grant.privilege, 0, 0,
                     test(first_table->schema_table)))
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2645
      goto error;
2646
    res= mysql_assign_to_keycache(thd, first_table, &lex->ident);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2647 2648
    break;
  }
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2649 2650
  case SQLCOM_PRELOAD_KEYS:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2651 2652 2653
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_db_used(thd, all_tables) ||
	check_access(thd, INDEX_ACL, first_table->db,
2654 2655
                     &first_table->grant.privilege, 0, 0,
                     test(first_table->schema_table)))
2656
      goto error;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2657
    res = mysql_preload_keys(thd, first_table);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2658 2659
    break;
  }
2660
#ifdef HAVE_REPLICATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2661
  case SQLCOM_CHANGE_MASTER:
2662
  {
2663
    if (check_global_access(thd, SUPER_ACL))
2664
      goto error;
2665
    pthread_mutex_lock(&LOCK_active_mi);
2666
    res = change_master(thd,active_mi);
2667
    pthread_mutex_unlock(&LOCK_active_mi);
2668 2669
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2670
  case SQLCOM_SHOW_SLAVE_STAT:
2671
  {
2672 2673
    /* Accept one of two privileges */
    if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
2674
      goto error;
2675
    pthread_mutex_lock(&LOCK_active_mi);
2676
    res = show_master_info(thd,active_mi);
2677
    pthread_mutex_unlock(&LOCK_active_mi);
2678 2679
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2680
  case SQLCOM_SHOW_MASTER_STAT:
2681
  {
2682 2683
    /* Accept one of two privileges */
    if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL))
2684 2685 2686 2687
      goto error;
    res = show_binlog_info(thd);
    break;
  }
peter@mysql.com's avatar
peter@mysql.com committed
2688

2689
  case SQLCOM_LOAD_MASTER_DATA: // sync with master
2690
    if (check_global_access(thd, SUPER_ACL))
2691
      goto error;
2692
    if (end_active_trans(thd))
2693
      goto error;
2694 2695
    else
      res = load_master_data(thd);
2696
    break;
2697
#endif /* HAVE_REPLICATION */
2698 2699 2700 2701 2702 2703 2704
#ifdef HAVE_NDBCLUSTER_DB
  case SQLCOM_SHOW_NDBCLUSTER_STATUS:
    {
      res = ndbcluster_show_status(thd);
      break;
    }
#endif
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2705 2706 2707
#ifdef HAVE_INNOBASE_DB
  case SQLCOM_SHOW_INNODB_STATUS:
    {
2708
      if (check_global_access(thd, SUPER_ACL))
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2709 2710 2711 2712
	goto error;
      res = innodb_show_status(thd);
      break;
    }
vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
2713 2714 2715
  case SQLCOM_SHOW_MUTEX_STATUS:
    {
      if (check_global_access(thd, SUPER_ACL))
vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
2716
        goto error;
vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
2717 2718 2719
      res = innodb_mutex_show_status(thd);
      break;
    }
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2720
#endif
2721
#ifdef HAVE_REPLICATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2722
  case SQLCOM_LOAD_MASTER_TABLE:
2723
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2724 2725 2726 2727
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (!first_table->db)
      first_table->db= thd->db;
    if (check_access(thd, CREATE_ACL, first_table->db,
2728 2729
		     &first_table->grant.privilege, 0, 0,
                     test(first_table->schema_table)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2730 2731 2732 2733
      goto error;				/* purecov: inspected */
    if (grant_option)
    {
      /* Check that the first table has CREATE privilege */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2734
      if (check_grant(thd, CREATE_ACL, all_tables, 0, 1, 0))
2735
	goto error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2736
    }
2737
    if (strlen(first_table->table_name) > NAME_LEN)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2738
    {
2739
      my_error(ER_WRONG_TABLE_NAME, MYF(0), first_table->table_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2740 2741
      break;
    }
2742
    pthread_mutex_lock(&LOCK_active_mi);
2743 2744 2745 2746
    /*
      fetch_master_table will send the error to the client on failure.
      Give error if the table already exists.
    */
2747
    if (!fetch_master_table(thd, first_table->db, first_table->table_name,
2748
			    active_mi, 0, 0))
2749
    {
2750
      send_ok(thd);
2751
    }
2752
    pthread_mutex_unlock(&LOCK_active_mi);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2753
    break;
2754
  }
2755
#endif /* HAVE_REPLICATION */
2756

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2757
  case SQLCOM_CREATE_TABLE:
2758
  {
2759
    /* If CREATE TABLE of non-temporary table, do implicit commit */
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769
    if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
    {
      if (end_active_trans(thd))
      {
	res= -1;
	break;
      }
    }
    else 
    {
2770 2771
      /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
      thd->options|= OPTION_STATUS_NO_TRANS_UPDATE;
2772
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2773 2774 2775 2776 2777
    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;
monty@mysql.com's avatar
monty@mysql.com committed
2778

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

2782 2783 2784
#ifndef HAVE_READLINK
    lex->create_info.data_file_name=lex->create_info.index_file_name=0;
#else
2785
    /* Fix names if symlinked tables */
2786
    if (append_file_to_dir(thd, &lex->create_info.data_file_name,
2787
			   create_table->table_name) ||
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2788
	append_file_to_dir(thd, &lex->create_info.index_file_name,
2789
			   create_table->table_name))
monty@mysql.com's avatar
monty@mysql.com committed
2790
      goto end_with_restore_list;
2791
#endif
2792
    /*
2793
      If we are using SET CHARSET without DEFAULT, add an implicit
2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804
      DEFAULT to not confuse old users. (This may change).
    */
    if ((lex->create_info.used_fields & 
	 (HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) ==
	HA_CREATE_USED_CHARSET)
    {
      lex->create_info.used_fields&= ~HA_CREATE_USED_CHARSET;
      lex->create_info.used_fields|= HA_CREATE_USED_DEFAULT_CHARSET;
      lex->create_info.default_table_charset= lex->create_info.table_charset;
      lex->create_info.table_charset= 0;
    }
2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
    /*
      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.
    */
    if (wait_if_global_read_lock(thd, 0, 1))
    {
monty@mysql.com's avatar
monty@mysql.com committed
2820 2821
      res= 1;
      goto end_with_restore_list;
2822
    }
2823
    if (select_lex->item_list.elements)		// With select
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2824 2825
    {
      select_result *result;
2826

2827
      select_lex->options|= SELECT_NO_UNLOCK;
2828
      unit->set_limit(select_lex);
2829

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2830
      if (!(res= open_and_lock_tables(thd, select_tables)))
2831
      {
2832 2833 2834 2835
        /*
          Is table which we are changing used somewhere in other parts
          of query
        */
2836
        if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
2837
        {
2838
          TABLE_LIST *duplicate;
2839
          if ((duplicate= unique_table(thd, create_table, select_tables)))
2840 2841 2842 2843 2844
          {
            update_non_unique_table_error(create_table, "CREATE", duplicate);
            res= 1;
            goto end_with_restart_wait;
          }
2845
        }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2846 2847 2848 2849 2850 2851 2852 2853
        /* If we create merge table, we have to test tables in merge, too */
        if (lex->create_info.used_fields & HA_CREATE_USED_UNION)
        {
          TABLE_LIST *tab;
          for (tab= (TABLE_LIST*) lex->create_info.merge_list.first;
               tab;
               tab= tab->next_local)
          {
2854
            TABLE_LIST *duplicate;
2855
            if ((duplicate= unique_table(thd, tab, select_tables)))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2856
            {
2857
              update_non_unique_table_error(tab, "CREATE", duplicate);
monty@mysql.com's avatar
monty@mysql.com committed
2858 2859
              res= 1;
              goto end_with_restart_wait;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2860 2861 2862
            }
          }
        }
2863

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2864 2865 2866 2867 2868
        if ((result= new select_create(create_table,
				       &lex->create_info,
				       lex->create_list,
				       lex->key_list,
				       select_lex->item_list,
2869 2870
				       lex->duplicates,
				       lex->ignore)))
2871 2872 2873 2874 2875
        {
          /*
            CREATE from SELECT give its SELECT_LEX for SELECT,
            and item_list belong to SELECT
          */
2876
          res= handle_select(thd, lex, result, 0);
2877
          delete result;
2878
        }
monty@mysql.com's avatar
monty@mysql.com committed
2879
	/* reset for PS */
2880 2881
	lex->create_list.empty();
	lex->key_list.empty();
2882 2883
      }
    }
monty@mysql.com's avatar
monty@mysql.com committed
2884
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2885
    {
monty@mysql.com's avatar
monty@mysql.com committed
2886
      /* regular create */
venu@myvenu.com's avatar
venu@myvenu.com committed
2887
      if (lex->name)
monty@mysql.com's avatar
monty@mysql.com committed
2888
        res= mysql_create_like_table(thd, create_table, &lex->create_info, 
venu@myvenu.com's avatar
venu@myvenu.com committed
2889 2890
                                     (Table_ident *)lex->name); 
      else
2891
      {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2892
        res= mysql_create_table(thd, create_table->db,
2893
				create_table->table_name, &lex->create_info,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2894
				lex->create_list,
monty@mysql.com's avatar
monty@mysql.com committed
2895
				lex->key_list, 0, 0);
2896
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2897
      if (!res)
2898
	send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2899
    }
2900

monty@mysql.com's avatar
monty@mysql.com committed
2901
end_with_restart_wait:
2902 2903 2904 2905 2906 2907
    /*
      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);

monty@mysql.com's avatar
monty@mysql.com committed
2908
    /* put tables back for PS rexecuting */
monty@mysql.com's avatar
monty@mysql.com committed
2909
end_with_restore_list:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2910
    lex->link_first_table_back(create_table, link_to_local);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2911
    break;
2912
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2913
  case SQLCOM_CREATE_INDEX:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2914 2915
    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
2916
      goto error; /* purecov: inspected */
2917
    thd->enable_slow_log= opt_log_slow_admin_statements;
2918
    if (end_active_trans(thd))
2919
      goto error;
2920
    else
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2921
      res = mysql_create_index(thd, first_table, lex->key_list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2922 2923
    break;

2924
#ifdef HAVE_REPLICATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2925
  case SQLCOM_SLAVE_START:
2926
  {
2927
    pthread_mutex_lock(&LOCK_active_mi);
2928
    start_slave(thd,active_mi,1 /* net report*/);
2929
    pthread_mutex_unlock(&LOCK_active_mi);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2930
    break;
2931
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2932
  case SQLCOM_SLAVE_STOP:
2933 2934 2935 2936 2937 2938
  /*
    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,
2939
      so it waits for the client thread because t is locked by it.
2940
    - then the client thread does SLAVE STOP.
2941 2942
      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.
2943 2944 2945
    To prevent that, refuse SLAVE STOP if the
    client thread has locked tables
  */
2946
  if (thd->locked_tables || thd->active_transaction() || thd->global_read_lock)
2947
  {
2948 2949
    my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
               ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2950
    goto error;
2951
  }
2952
  {
2953
    pthread_mutex_lock(&LOCK_active_mi);
2954
    stop_slave(thd,active_mi,1/* net report*/);
2955
    pthread_mutex_unlock(&LOCK_active_mi);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2956
    break;
2957
  }
2958
#endif /* HAVE_REPLICATION */
2959

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2960
  case SQLCOM_ALTER_TABLE:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2961
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2962
#if defined(DONT_ALLOW_SHOW_COMMANDS)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2963 2964
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
2965
    goto error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2966 2967
#else
    {
2968
      ulong priv=0;
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
2969
      if (lex->name && (!lex->name[0] || strlen(lex->name) > NAME_LEN))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2970
      {
2971
	my_error(ER_WRONG_TABLE_NAME, MYF(0), lex->name);
2972
        goto error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2973
      }
2974
      if (!select_lex->db)
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984
      {
        /*
          In the case of ALTER TABLE ... RENAME we should supply the
          default database if the new name is not explicitly qualified
          by a database. (Bug #11493)
        */
        if (lex->alter_info.flags & ALTER_RENAME)
        {
          if (! thd->db)
          {
ingo@mysql.com's avatar
ingo@mysql.com committed
2985
            my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
2986 2987 2988 2989 2990
            goto error;
          }
          select_lex->db= thd->db;
        }
        else
2991
          select_lex->db= first_table->db;
2992
      }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2993
      if (check_access(thd, ALTER_ACL, first_table->db,
2994 2995 2996 2997
		       &first_table->grant.privilege, 0, 0,
                       test(first_table->schema_table)) ||
	  check_access(thd,INSERT_ACL | CREATE_ACL,select_lex->db,&priv,0,0,
                       is_schema_db(select_lex->db))||
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2998
	  check_merge_table_access(thd, first_table->db,
2999 3000 3001
				   (TABLE_LIST *)
				   lex->create_info.merge_list.first))
	goto error;				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3002 3003
      if (grant_option)
      {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3004
	if (check_grant(thd, ALTER_ACL, all_tables, 0, UINT_MAX, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3005 3006 3007 3008 3009
	  goto error;
	if (lex->name && !test_all_bits(priv,INSERT_ACL | CREATE_ACL))
	{					// Rename of table
	  TABLE_LIST tmp_table;
	  bzero((char*) &tmp_table,sizeof(tmp_table));
3010
	  tmp_table.table_name=lex->name;
3011
	  tmp_table.db=select_lex->db;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3012
	  tmp_table.grant.privilege=priv;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3013 3014
	  if (check_grant(thd, INSERT_ACL | CREATE_ACL, &tmp_table, 0,
			  UINT_MAX, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3015 3016 3017
	    goto error;
	}
      }
3018 3019
      /* Don't yet allow changing of symlinks with ALTER TABLE */
      lex->create_info.data_file_name=lex->create_info.index_file_name=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3020
      /* ALTER TABLE ends previous transaction */
3021
      if (end_active_trans(thd))
3022
	goto error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3023
      else
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3024
      {
3025
        thd->enable_slow_log= opt_log_slow_admin_statements;
3026
	res= mysql_alter_table(thd, select_lex->db, lex->name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3027
			       &lex->create_info,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3028
			       first_table, lex->create_list,
3029
			       lex->key_list,
3030
			       select_lex->order_list.elements,
3031
                               (ORDER *) select_lex->order_list.first,
monty@mysql.com's avatar
monty@mysql.com committed
3032 3033
			       lex->duplicates, lex->ignore, &lex->alter_info,
                               1);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3034
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3035 3036
      break;
    }
hf@deer.(none)'s avatar
hf@deer.(none) committed
3037
#endif /*DONT_ALLOW_SHOW_COMMANDS*/
3038
  case SQLCOM_RENAME_TABLE:
3039
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3040
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3041
    TABLE_LIST *table;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3042
    if (check_db_used(thd, all_tables))
3043
      goto error;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3044
    for (table= first_table; table; table= table->next_local->next_local)
3045
    {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
3046
      if (check_access(thd, ALTER_ACL | DROP_ACL, table->db,
3047
		       &table->grant.privilege,0,0, test(table->schema_table)) ||
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3048
	  check_access(thd, INSERT_ACL | CREATE_ACL, table->next_local->db,
3049 3050
		       &table->next_local->grant.privilege, 0, 0,
                       test(table->next_local->schema_table)))
3051 3052 3053
	goto error;
      if (grant_option)
      {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3054
	TABLE_LIST old_list, new_list;
3055 3056 3057 3058
	/*
	  we do not need initialize old_list and new_list because we will
	  come table[0] and table->next[0] there
	*/
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3059 3060 3061 3062
	old_list= table[0];
	new_list= table->next_local[0];
	if (check_grant(thd, ALTER_ACL, &old_list, 0, 1, 0) ||
	    (!test_all_bits(table->next_local->grant.privilege,
3063
			    INSERT_ACL | CREATE_ACL) &&
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3064
	     check_grant(thd, INSERT_ACL | CREATE_ACL, &new_list, 0, 1, 0)))
3065 3066 3067
	  goto error;
      }
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3068
    query_cache_invalidate3(thd, first_table, 0);
3069 3070
    if (end_active_trans(thd) || mysql_rename_tables(thd, first_table))
      goto error;
3071
    break;
3072
  }
3073
#ifndef EMBEDDED_LIBRARY
3074 3075
  case SQLCOM_SHOW_BINLOGS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3076 3077
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
3078
    goto error;
3079 3080
#else
    {
3081
      if (check_global_access(thd, SUPER_ACL))
3082 3083 3084 3085
	goto error;
      res = show_binlogs(thd);
      break;
    }
peter@mysql.com's avatar
peter@mysql.com committed
3086
#endif
3087
#endif /* EMBEDDED_LIBRARY */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3088
  case SQLCOM_SHOW_CREATE:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3089
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3090
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3091 3092
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
3093
    goto error;
3094
#else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3095
    {
3096 3097 3098 3099
      /* Ignore temporary tables if this is "SHOW CREATE VIEW" */
      if (lex->only_view)
        first_table->skip_temporary= 1;

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3100 3101
      if (check_db_used(thd, all_tables) ||
	  check_access(thd, SELECT_ACL | EXTRA_ACL, first_table->db,
3102 3103
		       &first_table->grant.privilege, 0, 0, 
                       test(first_table->schema_table)))
3104
	goto error;
monty@mishka.local's avatar
monty@mishka.local committed
3105
      if (grant_option && check_grant(thd, SELECT_ACL, all_tables, 2, UINT_MAX, 0))
3106
	goto error;
monty@mishka.local's avatar
monty@mishka.local committed
3107
      res= mysqld_show_create(thd, first_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3108 3109
      break;
    }
3110
#endif
3111 3112
  case SQLCOM_CHECKSUM:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3113 3114 3115
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_db_used(thd, all_tables) ||
	check_table_access(thd, SELECT_ACL | EXTRA_ACL, all_tables, 0))
3116
      goto error; /* purecov: inspected */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3117
    res = mysql_checksum_table(thd, first_table, &lex->check_opt);
3118 3119
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3120
  case SQLCOM_REPAIR:
3121
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3122 3123 3124
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_db_used(thd, all_tables) ||
	check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables, 0))
3125
      goto error; /* purecov: inspected */
3126
    thd->enable_slow_log= opt_log_slow_admin_statements;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3127
    res= mysql_repair_table(thd, first_table, &lex->check_opt);
3128 3129 3130 3131 3132
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
      if (mysql_bin_log.is_open())
      {
3133
	thd->clear_error(); // No binlog error generated
3134
        Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
3135 3136 3137
        mysql_bin_log.write(&qinfo);
      }
    }
3138
    select_lex->table_list.first= (byte*) first_table;
3139
    lex->query_tables=all_tables;
3140 3141
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3142
  case SQLCOM_CHECK:
3143
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3144 3145 3146
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_db_used(thd, all_tables) ||
	check_table_access(thd, SELECT_ACL | EXTRA_ACL , all_tables, 0))
3147
      goto error; /* purecov: inspected */
3148
    thd->enable_slow_log= opt_log_slow_admin_statements;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3149
    res = mysql_check_table(thd, first_table, &lex->check_opt);
3150
    select_lex->table_list.first= (byte*) first_table;
3151
    lex->query_tables=all_tables;
3152 3153
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3154 3155
  case SQLCOM_ANALYZE:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3156 3157 3158
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_db_used(thd, all_tables) ||
	check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3159
      goto error; /* purecov: inspected */
3160
    thd->enable_slow_log= opt_log_slow_admin_statements;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3161
    res = mysql_analyze_table(thd, first_table, &lex->check_opt);
3162 3163 3164 3165 3166
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
      if (mysql_bin_log.is_open())
      {
3167
	thd->clear_error(); // No binlog error generated
3168
        Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
3169 3170 3171
        mysql_bin_log.write(&qinfo);
      }
    }
3172
    select_lex->table_list.first= (byte*) first_table;
3173
    lex->query_tables=all_tables;
3174
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3175
  }
3176

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3177 3178
  case SQLCOM_OPTIMIZE:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3179 3180 3181
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_db_used(thd, all_tables) ||
	check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3182
      goto error; /* purecov: inspected */
3183
    thd->enable_slow_log= opt_log_slow_admin_statements;
3184
    res= (specialflag & (SPECIAL_SAFE_MODE | SPECIAL_NO_NEW_FUNC)) ?
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3185 3186
      mysql_recreate_table(thd, first_table, 1) :
      mysql_optimize_table(thd, first_table, &lex->check_opt);
3187 3188 3189 3190 3191
    /* ! we write after unlocking the table */
    if (!res && !lex->no_write_to_binlog)
    {
      if (mysql_bin_log.is_open())
      {
3192
	thd->clear_error(); // No binlog error generated
3193
        Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
3194 3195 3196
        mysql_bin_log.write(&qinfo);
      }
    }
3197
    select_lex->table_list.first= (byte*) first_table;
3198
    lex->query_tables=all_tables;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3199 3200 3201
    break;
  }
  case SQLCOM_UPDATE:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3202 3203
    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
3204
      break;
3205 3206
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3207 3208 3209 3210 3211 3212
    res= (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,
3213
                               unit->select_limit_cnt,
3214
                               lex->duplicates, lex->ignore));
3215
    /* mysql_update return 2 if we need to switch to multi-update */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3216
    if (result != 2)
3217
      break;
3218
  case SQLCOM_UPDATE_MULTI:
3219 3220 3221 3222
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    /* if we switched from normal update, rights are checked */
    if (result != 2)
3223
    {
3224 3225 3226 3227 3228
      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
3229

3230 3231
    if ((res= mysql_multi_update_prepare(thd)))
      break;
3232

3233
#ifdef HAVE_REPLICATION
3234
    /* Check slave filtering rules */
3235
    if (unlikely(thd->slave_thread))
3236
    {
3237 3238 3239 3240 3241 3242
      if (all_tables_not_ok(thd, all_tables))
      {
        /* we warn the slave SQL thread */
        my_error(ER_SLAVE_IGNORED_TABLE, MYF(0));
        break;
      }
3243
    }
3244
    else
3245
#endif /* HAVE_REPLICATION */
3246 3247 3248 3249 3250 3251 3252
    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;
    }
3253

3254 3255 3256 3257 3258 3259
    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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3260
    break;
monty@mysql.com's avatar
monty@mysql.com committed
3261
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3262
  case SQLCOM_REPLACE:
3263 3264
  case SQLCOM_INSERT:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3265
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
monty@mysql.com's avatar
monty@mysql.com committed
3266
    if ((res= insert_precheck(thd, all_tables)))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3267
      break;
3268 3269
    /* Skip first table, which is the table we are inserting in */
    select_lex->context.table_list= first_table->next_local;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3270
    res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
monty@mishka.local's avatar
monty@mishka.local committed
3271
		      lex->update_list, lex->value_list,
3272
                      lex->duplicates, lex->ignore);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3273 3274
    if (first_table->view && !first_table->contain_auto_increment)
      thd->last_insert_id= 0; // do not show last insert ID if VIEW have not it
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3275
    break;
3276
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3277 3278 3279
  case SQLCOM_REPLACE_SELECT:
  case SQLCOM_INSERT_SELECT:
  {
monty@mysql.com's avatar
monty@mysql.com committed
3280
    select_result *result;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3281
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
monty@mishka.local's avatar
monty@mishka.local committed
3282
    if ((res= insert_precheck(thd, all_tables)))
3283
      break;
monty@mysql.com's avatar
monty@mysql.com committed
3284

3285
    /* Fix lock for first table */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3286 3287
    if (first_table->lock_type == TL_WRITE_DELAYED)
      first_table->lock_type= TL_WRITE;
3288

3289 3290
    /* 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
3291

3292
    unit->set_limit(select_lex);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3293
    if (!(res= open_and_lock_tables(thd, all_tables)))
3294
    {
3295
      /* Skip first table, which is the table we are inserting in */
3296 3297
      TABLE_LIST *second_table= first_table->next_local;
      select_lex->table_list.first= (byte*) second_table;
3298 3299
      select_lex->context.table_list= 
        select_lex->context.first_name_resolution_table= second_table;
3300 3301 3302
      res= mysql_insert_select_prepare(thd);
      if (!res && (result= new select_insert(first_table, first_table->table,
                                             &lex->field_list,
3303 3304
                                             &lex->update_list,
                                             &lex->value_list,
3305
                                             lex->duplicates, lex->ignore)))
3306
      {
3307 3308 3309 3310 3311 3312 3313
        /*
          Skip first table, which is the table we are inserting in.
          Below we set context.table_list again because the call above to
          mysql_insert_select_prepare() calls resolve_in_table_list_only(),
          which in turn resets context.table_list and
          context.first_name_resolution_table.
        */
3314 3315
        select_lex->context.table_list= 
          select_lex->context.first_name_resolution_table= second_table;
3316
	res= handle_select(thd, lex, result, OPTION_SETUP_TABLES_DONE);
3317 3318
        delete result;
      }
3319
      /* revert changes for SP */
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
3320
      select_lex->table_list.first= (byte*) first_table;
3321
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3322 3323 3324

    if (first_table->view && !first_table->contain_auto_increment)
      thd->last_insert_id= 0; // do not show last insert ID if VIEW have not it
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3325 3326
    break;
  }
3327
  case SQLCOM_TRUNCATE:
3328 3329 3330 3331 3332
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3333 3334
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_one_table_access(thd, DELETE_ACL, all_tables))
3335
      goto error;
3336 3337 3338 3339
    /*
      Don't allow this within a transaction because we want to use
      re-generate table
    */
3340
    if ((thd->locked_tables && !lex->sphead) || thd->active_transaction())
3341
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3342 3343
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3344 3345
      goto error;
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3346

monty@mysql.com's avatar
monty@mysql.com committed
3347
    res= mysql_truncate(thd, first_table, 0);
3348
    break;
3349
  case SQLCOM_DELETE:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3350
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3351 3352
    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
3353
      break;
3354 3355
    DBUG_ASSERT(select_lex->offset_limit == 0);
    unit->set_limit(select_lex);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3356
    res = mysql_delete(thd, all_tables, select_lex->where,
3357
                       &select_lex->order_list,
osku@127.(none)'s avatar
osku@127.(none) committed
3358 3359
                       unit->select_limit_cnt, select_lex->options,
                       FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3360 3361
    break;
  }
3362
  case SQLCOM_DELETE_MULTI:
3363
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3364
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3365 3366
    TABLE_LIST *aux_tables=
      (TABLE_LIST *)thd->lex->auxilliary_table_list.first;
3367
    multi_delete *result;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3368

3369
    if ((res= multi_delete_precheck(thd, all_tables)))
3370
      break;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3371

3372
    /* condition will be TRUE on SP re-excuting */
3373 3374
    if (select_lex->item_list.elements != 0)
      select_lex->item_list.empty();
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3375
    if (add_item_to_list(thd, new Item_null()))
3376
      goto error;
3377

3378
    thd->proc_info="init";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3379 3380 3381 3382
    if ((res= open_and_lock_tables(thd, all_tables)))
      break;

    if ((res= mysql_multi_delete_prepare(thd)))
3383
      goto error;
3384

3385
    if (!thd->is_fatal_error && (result= new multi_delete(aux_tables,
3386
							  lex->table_count)))
3387
    {
3388 3389 3390
      res= mysql_select(thd, &select_lex->ref_pointer_array,
			select_lex->get_table_list(),
			select_lex->with_wild,
3391
			select_lex->item_list,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3392
			select_lex->where,
3393
			0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3394 3395
			(ORDER *)NULL,
			select_lex->options | thd->options |
3396 3397
			SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
                        OPTION_SETUP_TABLES_DONE,
3398
			result, unit, select_lex);
3399
      delete result;
3400 3401
    }
    else
3402
      res= TRUE;                                // Error
3403 3404
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3405
  case SQLCOM_DROP_TABLE:
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
3406
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3407
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3408 3409
    if (!lex->drop_temporary)
    {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3410
      if (check_table_access(thd, DROP_ACL, all_tables, 0))
3411 3412
	goto error;				/* purecov: inspected */
      if (end_active_trans(thd))
3413
        goto error;
3414
    }
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
3415
    else
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3416 3417 3418 3419 3420 3421
    {
      /*
	If this is a slave thread, we may sometimes execute some 
	DROP / * 40005 TEMPORARY * / TABLE
	that come from parts of binlogs (likely if we use RESET SLAVE or CHANGE
	MASTER TO), while the temporary table has already been dropped.
monty@mysql.com's avatar
monty@mysql.com committed
3422 3423
	To not generate such irrelevant "table does not exist errors",
	we silently add IF EXISTS if TEMPORARY was used.
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3424 3425 3426
      */
      if (thd->slave_thread)
	lex->drop_if_exists= 1;
3427

3428 3429
      /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
      thd->options|= OPTION_STATUS_NO_TRANS_UPDATE;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3430
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3431 3432
    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
3433 3434
  }
  break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3435
  case SQLCOM_DROP_INDEX:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3436 3437
    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
3438
      goto error;				/* purecov: inspected */
3439
    if (end_active_trans(thd))
3440
      goto error;
3441
    else
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3442
      res = mysql_drop_index(thd, first_table, &lex->alter_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3443 3444
    break;
  case SQLCOM_SHOW_PROCESSLIST:
3445 3446
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd,PROCESS_ACL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3447
      break;
hf@deer.(none)'s avatar
hf@deer.(none) committed
3448
    mysqld_list_processes(thd,
3449 3450 3451 3452
			  (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
3453
    break;
3454 3455
  case SQLCOM_SHOW_STORAGE_ENGINES:
    res= mysqld_show_storage_engines(thd);
3456 3457 3458 3459 3460 3461 3462
    break;
  case SQLCOM_SHOW_PRIVILEGES:
    res= mysqld_show_privileges(thd);
    break;
  case SQLCOM_SHOW_COLUMN_TYPES:
    res= mysqld_show_column_types(thd);
    break;
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
3463 3464
  case SQLCOM_SHOW_LOGS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3465 3466
    my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
3467
    goto error;
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
3468 3469
#else
    {
3470
      if (grant_option && check_access(thd, FILE_ACL, any_db,0,0,0,0))
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
3471 3472 3473 3474
	goto error;
      res= mysqld_show_logs(thd);
      break;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3475 3476
#endif
  case SQLCOM_CHANGE_DB:
3477 3478
    if (!mysql_change_db(thd,select_lex->db,FALSE))
      send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3479
    break;
3480

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3481 3482
  case SQLCOM_LOAD:
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3483
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3484
    uint privilege= (lex->duplicates == DUP_REPLACE ?
3485 3486
		     INSERT_ACL | DELETE_ACL : INSERT_ACL) |
                    (lex->local_file ? 0 : FILE_ACL);
3487

3488
    if (lex->local_file)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3489
    {
3490
      if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) ||
3491
          !opt_local_infile)
3492
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3493
	my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0));
3494 3495
	goto error;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3496
    }
3497 3498 3499 3500

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3501
    res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
3502
                    lex->update_list, lex->value_list, lex->duplicates,
3503
                    lex->ignore, (bool) lex->local_file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3504 3505
    break;
  }
3506

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3507
  case SQLCOM_SET_OPTION:
3508 3509
  {
    List<set_var_base> *lex_var_list= &lex->var_list;
3510
    if ((check_table_access(thd, SELECT_ACL, all_tables, 0) ||
3511 3512
	 open_and_lock_tables(thd, all_tables)))
      goto error;
3513 3514
    if (lex->one_shot_set && not_all_support_one_shot(lex_var_list))
    {
3515 3516
      my_error(ER_RESERVED_SYNTAX, MYF(0), "SET ONE_SHOT");
      goto error;
3517 3518 3519 3520 3521 3522 3523 3524
    }
    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;
3525
      send_ok(thd);
3526
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3527
    break;
3528
  }
3529

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3530
  case SQLCOM_UNLOCK_TABLES:
3531 3532 3533 3534 3535 3536
    /*
      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.
    */
3537
    unlock_locked_tables(thd);
3538 3539
    if (thd->options & OPTION_TABLE_LOCK)
    {
3540
      end_active_trans(thd);
3541
      thd->options&= ~(ulong) (OPTION_TABLE_LOCK);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3542 3543
    }
    if (thd->global_read_lock)
3544
      unlock_global_read_lock(thd);
3545
    send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3546 3547
    break;
  case SQLCOM_LOCK_TABLES:
3548
    unlock_locked_tables(thd);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3549
    if (check_db_used(thd, all_tables) || end_active_trans(thd))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3550
      goto error;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3551
    if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, all_tables, 0))
3552
      goto error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3553
    thd->in_lock_tables=1;
3554
    thd->options|= OPTION_TABLE_LOCK;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3555

3556
    if (!(res= simple_open_n_lock_tables(thd, all_tables)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3557
    {
3558 3559
#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
3560
	query_cache.invalidate_locked_for_write(first_table);
3561
#endif /*HAVE_QUERY_CACHE*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3562 3563
      thd->locked_tables=thd->lock;
      thd->lock=0;
3564
      send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3565
    }
3566 3567
    else
      thd->options&= ~(ulong) (OPTION_TABLE_LOCK);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3568 3569 3570
    thd->in_lock_tables=0;
    break;
  case SQLCOM_CREATE_DB:
3571
  {
3572 3573 3574 3575 3576
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
3577
    char *alias;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
3578
    if (!(alias=thd->strdup(lex->name)) || check_db_name(lex->name))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3579
    {
3580
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3581 3582
      break;
    }
3583 3584 3585
    /*
      If in a slave thread :
      CREATE DATABASE DB was certainly not preceded by USE DB.
3586
      For that reason, db_ok() in sql/slave.cc did not check the
3587 3588 3589
      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.
    */
3590
#ifdef HAVE_REPLICATION
3591
    if (thd->slave_thread &&
3592 3593
	(!db_ok(lex->name, replicate_do_db, replicate_ignore_db) ||
	 !db_ok_with_wild_table(lex->name)))
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3594
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3595
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3596
      break;
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3597
    }
3598
#endif
3599
    if (check_access(thd,CREATE_ACL,lex->name,0,1,0,is_schema_db(lex->name)))
3600
      break;
monty@mysql.com's avatar
monty@mysql.com committed
3601
    res= mysql_create_db(thd,(lower_case_table_names == 2 ? alias : lex->name),
monty@mysql.com's avatar
monty@mysql.com committed
3602
			 &lex->create_info, 0);
3603 3604
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3605
  case SQLCOM_DROP_DB:
3606
  {
3607 3608 3609 3610 3611
    if (end_active_trans(thd))
    {
      res= -1;
      break;
    }
3612
    if (check_db_name(lex->name))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3613
    {
3614
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3615 3616
      break;
    }
3617 3618 3619 3620 3621 3622 3623
    /*
      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.
    */
3624
#ifdef HAVE_REPLICATION
3625 3626 3627
    if (thd->slave_thread && 
	(!db_ok(lex->name, replicate_do_db, replicate_ignore_db) ||
	 !db_ok_with_wild_table(lex->name)))
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3628
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3629
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
3630
      break;
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3631
    }
3632
#endif
3633
    if (check_access(thd,DROP_ACL,lex->name,0,1,0,is_schema_db(lex->name)))
3634
      break;
3635 3636
    if (thd->locked_tables || thd->active_transaction())
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3637 3638
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3639 3640
      goto error;
    }
3641
    res= mysql_rm_db(thd, lex->name, lex->drop_if_exists, 0);
3642 3643
    break;
  }
3644 3645
  case SQLCOM_ALTER_DB:
  {
3646 3647
    char *db= lex->name ? lex->name : thd->db;
    if (!db)
3648
    {
monty@mishka.local's avatar
monty@mishka.local committed
3649 3650
      my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
      break;
3651 3652
    }
    if (!strip_sp(db) || check_db_name(db))
3653
    {
3654
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name);
3655 3656
      break;
    }
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3657 3658 3659
    /*
      If in a slave thread :
      ALTER DATABASE DB may not be preceded by USE DB.
3660
      For that reason, maybe db_ok() in sql/slave.cc did not check the
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3661 3662 3663 3664
      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
3665
    if (thd->slave_thread &&
3666 3667
	(!db_ok(db, replicate_do_db, replicate_ignore_db) ||
	 !db_ok_with_wild_table(db)))
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3668
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3669
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3670 3671 3672
      break;
    }
#endif
3673
    if (check_access(thd, ALTER_ACL, db, 0, 1, 0, is_schema_db(db)))
3674 3675 3676
      break;
    if (thd->locked_tables || thd->active_transaction())
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3677 3678
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
3679 3680
      goto error;
    }
3681
    res= mysql_alter_db(thd, db, &lex->create_info);
3682 3683
    break;
  }
3684 3685 3686 3687
  case SQLCOM_SHOW_CREATE_DB:
  {
    if (!strip_sp(lex->name) || check_db_name(lex->name))
    {
3688
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name);
3689 3690
      break;
    }
3691
    if (check_access(thd,SELECT_ACL,lex->name,0,1,0,is_schema_db(lex->name)))
3692
      break;
3693
    res=mysqld_show_create_db(thd,lex->name,&lex->create_info);
3694 3695
    break;
  }
monty@mysql.com's avatar
monty@mysql.com committed
3696
  case SQLCOM_CREATE_FUNCTION:                  // UDF function
monty@mysql.com's avatar
monty@mysql.com committed
3697
  {
3698
    if (check_access(thd,INSERT_ACL,"mysql",0,1,0,0))
monty@mysql.com's avatar
monty@mysql.com committed
3699
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3700
#ifdef HAVE_DLOPEN
3701 3702
    if (sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                        &thd->sp_func_cache, FALSE))
monty@mysql.com's avatar
monty@mysql.com committed
3703
    {
3704
      my_error(ER_UDF_EXISTS, MYF(0), lex->spname->m_name.str);
monty@mysql.com's avatar
monty@mysql.com committed
3705 3706
      goto error;
    }
3707
    if (!(res = mysql_create_function(thd, &lex->udf)))
monty@mysql.com's avatar
monty@mysql.com committed
3708
      send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3709
#else
hf@deer.(none)'s avatar
hf@deer.(none) committed
3710
    my_error(ER_CANT_OPEN_LIBRARY, MYF(0), lex->udf.dl, 0, "feature disabled");
3711
    res= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3712 3713
#endif
    break;
monty@mysql.com's avatar
monty@mysql.com committed
3714
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
3715
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3716 3717
  case SQLCOM_CREATE_USER:
  {
3718
    if (check_access(thd, INSERT_ACL, "mysql", 0, 1, 1, 0) &&
3719
        check_global_access(thd,CREATE_USER_ACL))
3720
      break;
3721 3722
    if (end_active_trans(thd))
      goto error;
3723 3724 3725 3726
    if (!(res= mysql_create_user(thd, lex->users_list)))
    {
      if (mysql_bin_log.is_open())
      {
monty@mysql.com's avatar
monty@mysql.com committed
3727
        Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
3728 3729 3730 3731 3732 3733
        mysql_bin_log.write(&qinfo);
      }
      send_ok(thd);
    }
    break;
  }
3734 3735
  case SQLCOM_DROP_USER:
  {
3736
    if (check_access(thd, DELETE_ACL, "mysql", 0, 1, 1, 0) &&
3737
        check_global_access(thd,CREATE_USER_ACL))
3738
      break;
3739 3740
    if (end_active_trans(thd))
      goto error;
3741 3742 3743 3744
    if (!(res= mysql_drop_user(thd, lex->users_list)))
    {
      if (mysql_bin_log.is_open())
      {
monty@mysql.com's avatar
monty@mysql.com committed
3745
        Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
3746 3747 3748 3749 3750 3751 3752 3753
        mysql_bin_log.write(&qinfo);
      }
      send_ok(thd);
    }
    break;
  }
  case SQLCOM_RENAME_USER:
  {
3754
    if (check_access(thd, UPDATE_ACL, "mysql", 0, 1, 1, 0) &&
3755
        check_global_access(thd,CREATE_USER_ACL))
3756
      break;
3757 3758
    if (end_active_trans(thd))
      goto error;
3759 3760 3761 3762
    if (!(res= mysql_rename_user(thd, lex->users_list)))
    {
      if (mysql_bin_log.is_open())
      {
monty@mysql.com's avatar
monty@mysql.com committed
3763
        Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
3764
        mysql_bin_log.write(&qinfo);
3765 3766 3767 3768 3769 3770 3771
      }
      send_ok(thd);
    }
    break;
  }
  case SQLCOM_REVOKE_ALL:
  {
3772
    if (check_access(thd, UPDATE_ACL, "mysql", 0, 1, 1, 0) &&
3773
        check_global_access(thd,CREATE_USER_ACL))
3774 3775 3776 3777 3778
      break;
    if (!(res = mysql_revoke_all(thd, lex->users_list)))
    {
      if (mysql_bin_log.is_open())
      {
3779
	Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
3780 3781 3782 3783 3784 3785
	mysql_bin_log.write(&qinfo);
      }
      send_ok(thd);
    }
    break;
  }
3786 3787 3788 3789
  case SQLCOM_REVOKE:
  case SQLCOM_GRANT:
  {
    if (check_access(thd, lex->grant | lex->grant_tot_col | GRANT_ACL,
serg@serg.mylan's avatar
serg@serg.mylan committed
3790
		     first_table ?  first_table->db : select_lex->db,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3791
		     first_table ? &first_table->grant.privilege : 0,
3792 3793 3794
		     first_table ? 0 : 1, 0,
                     first_table ? (bool) first_table->schema_table :
                     select_lex->db ? is_schema_db(select_lex->db) : 0))
3795 3796
      goto error;

3797
    if (thd->security_ctx->user)              // If not replication
3798 3799
    {
      LEX_USER *user;
3800 3801
      uint counter;

3802
      List_iterator <LEX_USER> user_list(lex->users_list);
3803
      while ((user= user_list++))
3804
      {
3805 3806 3807 3808 3809 3810 3811 3812
        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);
3813
        if (strcmp(thd->security_ctx->user, user->user.str) ||
3814
            my_strcasecmp(system_charset_info,
3815
                          user->host.str, thd->security_ctx->host_or_ip))
3816 3817 3818
        {
          // TODO: use check_change_password()
          if (check_acl_user(user, &counter) && user->password.str &&
3819
              check_access(thd, UPDATE_ACL,"mysql",0,1,1,0))
3820 3821 3822 3823 3824 3825
          {
            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
3826 3827
      }
    }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3828
    if (first_table)
3829
    {
3830 3831
      if (lex->type == TYPE_ENUM_PROCEDURE ||
          lex->type == TYPE_ENUM_FUNCTION)
3832 3833 3834 3835 3836
      {
        uint grants= lex->all_privileges 
		   ? (PROC_ACLS & ~GRANT_ACL) | (lex->grant & GRANT_ACL)
		   : lex->grant;
        if (grant_option && 
3837 3838
	    check_grant_routine(thd, grants | GRANT_ACL, all_tables,
                                lex->type == TYPE_ENUM_PROCEDURE, 0))
3839
	  goto error;
3840 3841 3842 3843
        res= mysql_routine_grant(thd, all_tables,
                                 lex->type == TYPE_ENUM_PROCEDURE, 
                                 lex->users_list, grants,
                                 lex->sql_command == SQLCOM_REVOKE, 0);
3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856
      }
      else
      {
	if (grant_option && check_grant(thd,
					(lex->grant | lex->grant_tot_col |
					 GRANT_ACL),
					all_tables, 0, UINT_MAX, 0))
	  goto error;
        res= mysql_table_grant(thd, all_tables, lex->users_list,
			       lex->columns, lex->grant,
			       lex->sql_command == SQLCOM_REVOKE);
      }
      if (!res && mysql_bin_log.is_open())
3857
      {
pem@mysql.com's avatar
pem@mysql.com committed
3858
        thd->clear_error();
monty@mysql.com's avatar
monty@mysql.com committed
3859
        Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
3860
        mysql_bin_log.write(&qinfo);
3861 3862 3863 3864
      }
    }
    else
    {
3865
      if (lex->columns.elements || lex->type)
3866
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3867 3868
	my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
                   MYF(0));
3869
        goto error;
3870 3871 3872 3873 3874 3875 3876 3877
      }
      else
	res = mysql_grant(thd, select_lex->db, lex->users_list, lex->grant,
			  lex->sql_command == SQLCOM_REVOKE);
      if (!res)
      {
	if (mysql_bin_log.is_open())
	{
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3878
          thd->clear_error();
3879
	  Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
3880 3881
	  mysql_bin_log.write(&qinfo);
	}
3882
	if (lex->sql_command == SQLCOM_GRANT)
3883
	{
3884 3885 3886
	  List_iterator <LEX_USER> str_list(lex->users_list);
	  LEX_USER *user;
	  while ((user=str_list++))
monty@mysql.com's avatar
monty@mysql.com committed
3887
	    reset_mqh(user);
3888
	}
3889 3890 3891 3892
      }
    }
    break;
  }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3893
#endif /*!NO_EMBEDDED_ACCESS_CHECKS*/
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
3894
  case SQLCOM_RESET:
3895 3896 3897
    /*
      RESET commands are never written to the binary log, so we have to
      initialize this variable because RESET shares the same code as FLUSH
3898 3899 3900 3901
    */
    lex->no_write_to_binlog= 1;
  case SQLCOM_FLUSH:
  {
3902
    bool write_to_binlog;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3903
    if (check_global_access(thd,RELOAD_ACL) || check_db_used(thd, all_tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3904
      goto error;
3905 3906 3907 3908
    /*
      reload_acl_and_cache() will tell us if we are allowed to write to the
      binlog or not.
    */
3909
    if (!reload_acl_and_cache(thd, lex->type, first_table, &write_to_binlog))
3910 3911 3912 3913 3914 3915 3916 3917 3918
    {
      /*
        We WANT to write and we CAN write.
        ! we write after unlocking the table.
      */
      if (!lex->no_write_to_binlog && write_to_binlog)
      {
        if (mysql_bin_log.is_open())
        {
3919
          Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
3920 3921 3922 3923 3924
          mysql_bin_log.write(&qinfo);
        }
      }
      send_ok(thd);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3925
    break;
3926
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3927
  case SQLCOM_KILL:
3928 3929 3930
  {
    Item *it= (Item *)lex->value_list.head();

3931
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1))
3932 3933 3934 3935 3936 3937
    {
      my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY),
		 MYF(0));
      goto error;
    }
    kill_one_thread(thd, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3938
    break;
3939
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
3940
#ifndef NO_EMBEDDED_ACCESS_CHECKS
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3941
  case SQLCOM_SHOW_GRANTS:
3942 3943
    if ((thd->security_ctx->priv_user &&
	 !strcmp(thd->security_ctx->priv_user, lex->grant_user->user.str)) ||
3944
	!check_access(thd, SELECT_ACL, "mysql",0,1,0,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3945 3946 3947 3948
    {
      res = mysql_show_grants(thd,lex->grant_user);
    }
    break;
hf@deer.(none)'s avatar
hf@deer.(none) committed
3949
#endif
3950
  case SQLCOM_HA_OPEN:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3951 3952 3953
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_db_used(thd, all_tables) ||
	check_table_access(thd, SELECT_ACL, all_tables, 0))
3954
      goto error;
monty@mysql.com's avatar
monty@mysql.com committed
3955
    res= mysql_ha_open(thd, first_table, 0);
3956 3957
    break;
  case SQLCOM_HA_CLOSE:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3958 3959
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_db_used(thd, all_tables))
3960
      goto error;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3961
    res= mysql_ha_close(thd, first_table);
3962 3963
    break;
  case SQLCOM_HA_READ:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3964
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
3965 3966 3967 3968 3969
    /*
      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.
    */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3970
    if (check_db_used(thd, all_tables))
3971
      goto error;
3972
    unit->set_limit(select_lex);
3973
    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
3974
                       lex->insert_list, lex->ha_rkey_mode, select_lex->where,
3975
                       unit->select_limit_cnt, unit->offset_limit_cnt);
3976 3977
    break;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3978
  case SQLCOM_BEGIN:
3979 3980 3981 3982 3983 3984
    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;
    }
3985
    if (begin_trans(thd))
3986
      goto error;
serg@serg.mylan's avatar
serg@serg.mylan committed
3987
    send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3988 3989
    break;
  case SQLCOM_COMMIT:
3990
    if (end_trans(thd, lex->tx_release ? COMMIT_RELEASE :
serg@serg.mylan's avatar
serg@serg.mylan committed
3991
                              lex->tx_chain ? COMMIT_AND_CHAIN : COMMIT))
3992
      goto error;
3993
    send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3994 3995
    break;
  case SQLCOM_ROLLBACK:
3996
    if (end_trans(thd, lex->tx_release ? ROLLBACK_RELEASE :
serg@serg.mylan's avatar
serg@serg.mylan committed
3997
                              lex->tx_chain ? ROLLBACK_AND_CHAIN : ROLLBACK))
3998
      goto error;
3999
    send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4000
    break;
serg@serg.mylan's avatar
serg@serg.mylan committed
4001
  case SQLCOM_RELEASE_SAVEPOINT:
serg@serg.mylan's avatar
serg@serg.mylan committed
4002
  {
4003 4004
    SAVEPOINT *sv;
    for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
serg@serg.mylan's avatar
serg@serg.mylan committed
4005 4006 4007
    {
      if (my_strnncoll(system_charset_info,
                       (uchar *)lex->ident.str, lex->ident.length,
4008
                       (uchar *)sv->name, sv->length) == 0)
serg@serg.mylan's avatar
serg@serg.mylan committed
4009 4010
        break;
    }
4011
    if (sv)
serg@serg.mylan's avatar
serg@serg.mylan committed
4012
    {
4013
      if (ha_release_savepoint(thd, sv))
serg@serg.mylan's avatar
serg@serg.mylan committed
4014
        res= TRUE; // cannot happen
serg@serg.mylan's avatar
serg@serg.mylan committed
4015 4016
      else
        send_ok(thd);
4017
      thd->transaction.savepoints=sv->prev;
serg@serg.mylan's avatar
serg@serg.mylan committed
4018
    }
4019
    else
serg@serg.mylan's avatar
serg@serg.mylan committed
4020
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4021
    break;
serg@serg.mylan's avatar
serg@serg.mylan committed
4022
  }
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4023
  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
serg@serg.mylan's avatar
serg@serg.mylan committed
4024
  {
4025 4026
    SAVEPOINT *sv;
    for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
4027 4028 4029
    {
      if (my_strnncoll(system_charset_info,
                       (uchar *)lex->ident.str, lex->ident.length,
4030
                       (uchar *)sv->name, sv->length) == 0)
4031 4032
        break;
    }
4033
    if (sv)
4034
    {
4035
      if (ha_rollback_to_savepoint(thd, sv))
4036 4037
        res= TRUE; // cannot happen
      else
serg@serg.mylan's avatar
serg@serg.mylan committed
4038 4039 4040 4041 4042 4043 4044 4045
      {
        if ((thd->options & OPTION_STATUS_NO_TRANS_UPDATE) &&
            !thd->slave_thread)
          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                       ER_WARNING_NOT_COMPLETE_ROLLBACK,
                       ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
        send_ok(thd);
      }
4046
      thd->transaction.savepoints=sv;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4047 4048
    }
    else
4049
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4050
    break;
4051
  }
4052
  case SQLCOM_SAVEPOINT:
4053 4054
    if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN) ||
          thd->in_sub_stmt) || !opt_using_transactions)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4055
      send_ok(thd);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4056
    else
4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094
    {
      SAVEPOINT **sv, *newsv;
      for (sv=&thd->transaction.savepoints; *sv; sv=&(*sv)->prev)
      {
        if (my_strnncoll(system_charset_info,
                         (uchar *)lex->ident.str, lex->ident.length,
                         (uchar *)(*sv)->name, (*sv)->length) == 0)
          break;
      }
      if (*sv) /* old savepoint of the same name exists */
      {
        newsv=*sv;
        ha_release_savepoint(thd, *sv); // it cannot fail
        *sv=(*sv)->prev;
      }
      else if ((newsv=(SAVEPOINT *) alloc_root(&thd->transaction.mem_root,
                                               savepoint_alloc_size)) == 0)
      {
        my_error(ER_OUT_OF_RESOURCES, MYF(0));
        break;
      }
      newsv->name=strmake_root(&thd->transaction.mem_root,
                               lex->ident.str, lex->ident.length);
      newsv->length=lex->ident.length;
      /*
        if we'll get an error here, don't add new savepoint to the list.
        we'll lose a little bit of memory in transaction mem_root, but it'll
        be free'd when transaction ends anyway
      */
      if (ha_savepoint(thd, newsv))
        res= TRUE;
      else
      {
        newsv->prev=thd->transaction.savepoints;
        thd->transaction.savepoints=newsv;
        send_ok(thd);
      }
    }
4095
    break;
4096 4097
  case SQLCOM_CREATE_PROCEDURE:
  case SQLCOM_CREATE_SPFUNCTION:
monty@mysql.com's avatar
monty@mysql.com committed
4098
  {
4099
    uint namelen;
4100
    char *name, *db;
4101
    int result;
4102

4103
    DBUG_ASSERT(lex->sphead != 0);
4104

4105 4106
    if (!lex->sphead->m_db.str || !lex->sphead->m_db.str[0])
    {
4107
      if (!thd->db)
4108 4109 4110 4111 4112 4113 4114 4115 4116 4117
      {
        my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
        delete lex->sphead;
        lex->sphead= 0;
        goto error;
      }
      lex->sphead->m_db.length= strlen(thd->db);
      lex->sphead->m_db.str= thd->db;
    }

4118 4119
    if (check_access(thd, CREATE_PROC_ACL, lex->sphead->m_db.str, 0, 0, 0,
                     is_schema_db(lex->sphead->m_db.str)))
4120 4121 4122 4123 4124 4125
    {
      delete lex->sphead;
      lex->sphead= 0;
      goto error;
    }

4126
    if (end_active_trans(thd)) 
4127
    {
4128 4129 4130
      delete lex->sphead;
      lex->sphead= 0;
      goto error;
4131
    }
4132 4133

    name= lex->sphead->name(&namelen);
4134
#ifdef HAVE_DLOPEN
monty@mysql.com's avatar
monty@mysql.com committed
4135 4136 4137
    if (lex->sphead->m_type == TYPE_ENUM_FUNCTION)
    {
      udf_func *udf = find_udf(name, namelen);
4138

monty@mysql.com's avatar
monty@mysql.com committed
4139
      if (udf)
4140
      {
4141
	my_error(ER_UDF_EXISTS, MYF(0), name);
4142
	delete lex->sphead;
4143
	lex->sphead= 0;
4144
	goto error;
4145
      }
monty@mysql.com's avatar
monty@mysql.com committed
4146 4147 4148
    }
#endif

4149 4150 4151 4152 4153
    /*
      We need to copy name and db in order to use them for
      check_routine_access which is called after lex->sphead has
      been deleted.
    */
4154
    name= thd->strdup(name); 
4155 4156
    lex->sphead->m_db.str= db= thd->strmake(lex->sphead->m_db.str,
                                            lex->sphead->m_db.length);
4157
    res= (result= lex->sphead->create(thd));
4158 4159
    if (result == SP_OK)
    {
4160 4161 4162 4163 4164 4165
      /*
        We must cleanup the unit and the lex here because
        sp_grant_privileges calls (indirectly) db_find_routine,
        which in turn may call yyparse with THD::lex.
        TODO: fix db_find_routine to use a temporary lex.
      */
4166
      lex->unit.cleanup();
monty@mysql.com's avatar
monty@mysql.com committed
4167 4168
      delete lex->sphead;
      lex->sphead= 0;
4169
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4170
      /* only add privileges if really neccessary */
4171
      if (sp_automatic_privileges && !opt_noacl &&
4172 4173 4174
          check_routine_access(thd, DEFAULT_CREATE_PROC_ACLS,
      			       db, name,
                               lex->sql_command == SQLCOM_CREATE_PROCEDURE, 1))
4175 4176
      {
        close_thread_tables(thd);
4177 4178
        if (sp_grant_privileges(thd, db, name, 
                                lex->sql_command == SQLCOM_CREATE_PROCEDURE))
4179 4180 4181 4182
          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 
	  	       ER_PROC_AUTO_GRANT_FAIL,
		       ER(ER_PROC_AUTO_GRANT_FAIL));
      }
4183
#endif
4184
      send_ok(thd);
4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204
    }
    else
    {
      switch (result) {
      case SP_WRITE_ROW_FAILED:
	my_error(ER_SP_ALREADY_EXISTS, MYF(0), SP_TYPE_STRING(lex), name);
	break;
      case SP_NO_DB_ERROR:
	my_error(ER_BAD_DB_ERROR, MYF(0), lex->sphead->m_db.str);
	break;
      case SP_BAD_IDENTIFIER:
	my_error(ER_TOO_LONG_IDENT, MYF(0), name);
	break;
      case SP_BODY_TOO_LONG:
	my_error(ER_TOO_LONG_BODY, MYF(0), name);
	break;
      default:
	my_error(ER_SP_STORE_FAILED, MYF(0), SP_TYPE_STRING(lex), name);
	break;
      }
4205
      lex->unit.cleanup();
monty@mysql.com's avatar
monty@mysql.com committed
4206 4207 4208
      delete lex->sphead;
      lex->sphead= 0;
      goto error;
4209
    }
monty@mysql.com's avatar
monty@mysql.com committed
4210 4211
    break;
  }
4212 4213 4214 4215
  case SQLCOM_CALL:
    {
      sp_head *sp;

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

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

4256
#ifndef EMBEDDED_LIBRARY
4257 4258
	my_bool nsok= thd->net.no_send_ok;
	thd->net.no_send_ok= TRUE;
4259
#endif
4260
	if (sp->m_flags & sp_head::MULTI_RESULTS)
4261
	{
4262
	  if (! (thd->client_capabilities & CLIENT_MULTI_RESULTS))
4263
	  {
4264 4265 4266 4267
            /*
              The client does not support multiple result sets being sent
              back
            */
4268
	    my_error(ER_SP_BADSELECT, MYF(0), sp->m_qname.str);
4269 4270 4271 4272 4273
#ifndef EMBEDDED_LIBRARY
	    thd->net.no_send_ok= nsok;
#endif
	    goto error;
	  }
monty@mysql.com's avatar
monty@mysql.com committed
4274 4275 4276 4277 4278 4279 4280
          /*
            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;
4281 4282
	}

4283
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4284 4285 4286
	if (check_routine_access(thd, EXECUTE_ACL,
				 sp->m_db.str, sp->m_name.str, TRUE, 0) ||
          sp_change_security_context(thd, sp, &save_ctx))
4287 4288 4289 4290 4291 4292
	{
#ifndef EMBEDDED_LIBRARY
	  thd->net.no_send_ok= nsok;
#endif
	  goto error;
	}
4293 4294 4295
	if (save_ctx &&
            check_routine_access(thd, EXECUTE_ACL,
                                 sp->m_db.str, sp->m_name.str, TRUE, 0))
4296 4297 4298 4299
	{
#ifndef EMBEDDED_LIBRARY
	  thd->net.no_send_ok= nsok;
#endif
4300
	  sp_restore_security_context(thd, save_ctx);
4301 4302 4303
	  goto error;
	}

4304
#endif
pem@mysql.comhem.se's avatar
pem@mysql.comhem.se committed
4305 4306
	select_limit= thd->variables.select_limit;
	thd->variables.select_limit= HA_POS_ERROR;
4307

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

pem@mysql.comhem.se's avatar
pem@mysql.comhem.se committed
4326
	thd->variables.select_limit= select_limit;
4327
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4328
	sp_restore_security_context(thd, save_ctx);
4329
#endif
4330

4331
#ifndef EMBEDDED_LIBRARY
4332
	thd->net.no_send_ok= nsok;
4333
#endif
monty@mysql.com's avatar
monty@mysql.com committed
4334
        thd->server_status&= ~bits_to_be_cleared;
4335

4336
	if (!res)
monty@mysql.com's avatar
monty@mysql.com committed
4337 4338
	  send_ok(thd, (ulong) (thd->row_count_func < 0 ? 0 :
                                thd->row_count_func));
4339 4340
	else
	  goto error;		// Substatement should already have sent error
4341
      }
4342
      break;
4343 4344
    }
  case SQLCOM_ALTER_PROCEDURE:
4345
  case SQLCOM_ALTER_FUNCTION:
4346
    {
4347
      int result;
4348 4349 4350 4351
      sp_head *sp;
      st_sp_chistics chistics;

      memcpy(&chistics, &lex->sp_chistics, sizeof(chistics));
4352
      if (lex->sql_command == SQLCOM_ALTER_PROCEDURE)
4353 4354
        sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                            &thd->sp_proc_cache, FALSE);
4355
      else
4356 4357
        sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                            &thd->sp_func_cache, FALSE);
monty@mysql.com's avatar
monty@mysql.com committed
4358
      mysql_reset_errors(thd, 0);
4359
      if (! sp)
4360 4361 4362 4363 4364 4365 4366 4367 4368
      {
	if (lex->spname->m_db.str)
	  result= SP_KEY_NOT_FOUND;
	else
	{
	  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
	  goto error;
	}
      }
4369 4370
      else
      {
4371 4372 4373
        if (check_routine_access(thd, ALTER_PROC_ACL, sp->m_db.str, 
				 sp->m_name.str,
                                 lex->sql_command == SQLCOM_ALTER_PROCEDURE, 0))
4374
	  goto error;
4375 4376 4377

        if (end_active_trans(thd)) 
          goto error;
4378
	memcpy(&lex->sp_chistics, &chistics, sizeof(lex->sp_chistics));
4379 4380
        if ((sp->m_type == TYPE_ENUM_FUNCTION) &&
            !trust_function_creators &&  mysql_bin_log.is_open() &&
4381 4382 4383 4384 4385 4386 4387 4388 4389 4390
            !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));
          result= SP_INTERNAL_ERROR;
        }
        else
        {
4391 4392 4393 4394 4395 4396
          /*
            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.
          */
4397 4398 4399 4400 4401
          if (lex->sql_command == SQLCOM_ALTER_PROCEDURE)
            result= sp_update_procedure(thd, lex->spname, &lex->sp_chistics);
          else
            result= sp_update_function(thd, lex->spname, &lex->sp_chistics);
        }
4402
      }
4403
      switch (result)
4404
      {
4405
      case SP_OK:
4406 4407 4408 4409 4410 4411
        if (mysql_bin_log.is_open())
        {
          thd->clear_error();
          Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
          mysql_bin_log.write(&qinfo);
        }
4412
	send_ok(thd);
4413 4414
	break;
      case SP_KEY_NOT_FOUND:
4415 4416
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4417 4418
	goto error;
      default:
4419 4420
	my_error(ER_SP_CANT_ALTER, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4421
	goto error;
4422
      }
4423
      break;
4424 4425
    }
  case SQLCOM_DROP_PROCEDURE:
4426
  case SQLCOM_DROP_FUNCTION:
4427
    {
4428
      sp_head *sp;
4429
      int result;
4430
      char *db, *name;
4431

4432
      if (lex->sql_command == SQLCOM_DROP_PROCEDURE)
4433 4434
        sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                            &thd->sp_proc_cache, FALSE);
4435
      else
4436 4437
        sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                            &thd->sp_func_cache, FALSE);
monty@mysql.com's avatar
monty@mysql.com committed
4438
      mysql_reset_errors(thd, 0);
4439
      if (sp)
4440
      {
4441 4442
        db= thd->strdup(sp->m_db.str);
	name= thd->strdup(sp->m_name.str);
4443 4444
	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
4445
          goto error;
4446 4447 4448

        if (end_active_trans(thd)) 
          goto error;
4449
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4450
	if (sp_automatic_privileges && !opt_noacl &&
4451 4452
	    sp_revoke_privileges(thd, db, name, 
                                 lex->sql_command == SQLCOM_DROP_PROCEDURE))
4453 4454 4455 4456 4457
	{
	  push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 
		       ER_PROC_AUTO_REVOKE_FAIL,
		       ER(ER_PROC_AUTO_REVOKE_FAIL));
	}
4458
#endif
4459
	if (lex->sql_command == SQLCOM_DROP_PROCEDURE)
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
4460
	  result= sp_drop_procedure(thd, lex->spname);
4461
	else
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
4462
	  result= sp_drop_function(thd, lex->spname);
4463 4464 4465
      }
      else
      {
4466
#ifdef HAVE_DLOPEN
4467 4468 4469 4470 4471 4472
	if (lex->sql_command == SQLCOM_DROP_FUNCTION)
	{
          udf_func *udf = find_udf(lex->spname->m_name.str,
                                   lex->spname->m_name.length);
          if (udf)
          {
4473
	    if (check_access(thd, DELETE_ACL, "mysql", 0, 1, 0, 0))
4474 4475
	      goto error;
	    if (!(res = mysql_drop_function(thd, &lex->spname->m_name)))
4476
	    {
4477 4478
	      send_ok(thd);
	      break;
4479 4480
	    }
	  }
4481
	}
4482
#endif
4483 4484 4485 4486 4487 4488 4489
	if (lex->spname->m_db.str)
	  result= SP_KEY_NOT_FOUND;
	else
	{
	  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
	  goto error;
	}
4490
      }
4491 4492
      res= result;
      switch (result)
4493 4494
      {
      case SP_OK:
4495 4496 4497 4498 4499 4500
        if (mysql_bin_log.is_open())
        {
          thd->clear_error();
          Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
          mysql_bin_log.write(&qinfo);
        }
4501
	send_ok(thd);
4502 4503
	break;
      case SP_KEY_NOT_FOUND:
4504 4505
	if (lex->drop_if_exists)
	{
4506
	  push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
4507
			      ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST),
4508
			      SP_COM_STRING(lex), lex->spname->m_name.str);
4509
	  res= FALSE;
4510 4511 4512
	  send_ok(thd);
	  break;
	}
4513 4514
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4515 4516
	goto error;
      default:
4517 4518
	my_error(ER_SP_DROP_FAILED, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_qname.str);
4519
	goto error;
4520
      }
4521
      break;
4522
    }
4523 4524
  case SQLCOM_SHOW_CREATE_PROC:
    {
4525
      if (lex->spname->m_name.length > NAME_LEN)
4526
      {
4527
	my_error(ER_TOO_LONG_IDENT, MYF(0), lex->spname->m_name.str);
4528 4529
	goto error;
      }
4530
      if (sp_show_create_procedure(thd, lex->spname) != SP_OK)
4531
      {			/* We don't distinguish between errors for now */
4532 4533
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
4534 4535 4536 4537 4538 4539
	goto error;
      }
      break;
    }
  case SQLCOM_SHOW_CREATE_FUNC:
    {
4540
      if (lex->spname->m_name.length > NAME_LEN)
4541
      {
4542
	my_error(ER_TOO_LONG_IDENT, MYF(0), lex->spname->m_name.str);
4543 4544
	goto error;
      }
4545
      if (sp_show_create_function(thd, lex->spname) != SP_OK)
4546
      {			/* We don't distinguish between errors for now */
4547 4548
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
4549 4550 4551 4552 4553 4554
	goto error;
      }
      break;
    }
  case SQLCOM_SHOW_STATUS_PROC:
    {
4555
      res= sp_show_status_procedure(thd, (lex->wild ?
4556 4557 4558 4559 4560
					  lex->wild->ptr() : NullS));
      break;
    }
  case SQLCOM_SHOW_STATUS_FUNC:
    {
4561
      res= sp_show_status_function(thd, (lex->wild ? 
4562 4563 4564
					 lex->wild->ptr() : NullS));
      break;
    }
pem@mysql.com's avatar
pem@mysql.com committed
4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576
#ifndef DBUG_OFF
  case SQLCOM_SHOW_PROC_CODE:
  case SQLCOM_SHOW_FUNC_CODE:
    {
      sp_head *sp;

      if (lex->spname->m_name.length > NAME_LEN)
      {
	my_error(ER_TOO_LONG_IDENT, MYF(0), lex->spname->m_name.str);
	goto error;
      }
      if (lex->sql_command == SQLCOM_SHOW_PROC_CODE)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4577 4578
        sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname,
                            &thd->sp_proc_cache, FALSE);
pem@mysql.com's avatar
pem@mysql.com committed
4579
      else
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4580 4581
        sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname,
                            &thd->sp_func_cache, FALSE);
pem@mysql.com's avatar
pem@mysql.com committed
4582
      if (!sp || !sp->show_routine_code(thd))
4583 4584
      {
        /* We don't distinguish between errors for now */
pem@mysql.com's avatar
pem@mysql.com committed
4585 4586 4587 4588 4589 4590 4591
        my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 SP_COM_STRING(lex), lex->spname->m_name.str);
        goto error;
      }
      break;
    }
#endif // ifndef DBUG_OFF
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4592 4593
  case SQLCOM_CREATE_VIEW:
    {
4594 4595 4596
      if (end_active_trans(thd))
        goto error;

4597 4598 4599
      if (!(res= mysql_create_view(thd, thd->lex->create_view_mode)) &&
          mysql_bin_log.is_open())
      {
4600
        String buff;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4601 4602 4603 4604
        const LEX_STRING command[3]=
          {{(char *)STRING_WITH_LEN("CREATE ")},
           {(char *)STRING_WITH_LEN("ALTER ")},
           {(char *)STRING_WITH_LEN("CREATE OR REPLACE ")}};
4605
        thd->clear_error();
4606 4607 4608 4609

        buff.append(command[thd->lex->create_view_mode].str,
                    command[thd->lex->create_view_mode].length);
        view_store_options(thd, first_table, &buff);
4610
        buff.append(STRING_WITH_LEN("VIEW "));
4611 4612
        /* Test if user supplied a db (ie: we did not use thd->db) */
        if (first_table->db != thd->db && first_table->db[0])
4613 4614 4615 4616 4617 4618 4619
        {
          append_identifier(thd, &buff, first_table->db,
                            first_table->db_length);
          buff.append('.');
        }
        append_identifier(thd, &buff, first_table->table_name,
                          first_table->table_name_length);
4620
        buff.append(STRING_WITH_LEN(" AS "));
4621 4622 4623
        buff.append(first_table->source.str, first_table->source.length);

        Query_log_event qinfo(thd, buff.ptr(), buff.length(), 0, FALSE);
4624 4625
        mysql_bin_log.write(&qinfo);
      }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4626 4627 4628 4629
      break;
    }
  case SQLCOM_DROP_VIEW:
    {
4630 4631 4632
      if (check_table_access(thd, DROP_ACL, all_tables, 0) ||
          end_active_trans(thd))
        goto error;
4633 4634 4635
      if (!(res= mysql_drop_view(thd, first_table, thd->lex->drop_mode)) &&
          mysql_bin_log.is_open())
      {
4636
        thd->clear_error();
4637 4638 4639
        Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
        mysql_bin_log.write(&qinfo);
      }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4640 4641
      break;
    }
4642 4643
  case SQLCOM_CREATE_TRIGGER:
  {
4644 4645 4646
    if (end_active_trans(thd))
      goto error;

4647 4648 4649
    res= mysql_create_or_drop_trigger(thd, all_tables, 1);

    /* We don't care about trigger body after this point */
4650 4651 4652 4653 4654 4655
    delete lex->sphead;
    lex->sphead= 0;
    break;
  }
  case SQLCOM_DROP_TRIGGER:
  {
4656 4657 4658
    if (end_active_trans(thd))
      goto error;

4659 4660 4661
    res= mysql_create_or_drop_trigger(thd, all_tables, 0);
    break;
  }
4662
  case SQLCOM_XA_START:
4663 4664
    if (thd->transaction.xid_state.xa_state == XA_IDLE &&
        thd->lex->xa_opt == XA_RESUME)
4665
    {
4666
      if (! thd->transaction.xid_state.xid.eq(thd->lex->xid))
4667 4668 4669 4670
      {
        my_error(ER_XAER_NOTA, MYF(0));
        break;
      }
4671
      thd->transaction.xid_state.xa_state=XA_ACTIVE;
4672 4673 4674
      send_ok(thd);
      break;
    }
serg@serg.mylan's avatar
serg@serg.mylan committed
4675
    if (thd->lex->xa_opt != XA_NONE)
4676 4677 4678 4679
    { // JOIN is not supported yet. TODO
      my_error(ER_XAER_INVAL, MYF(0));
      break;
    }
4680
    if (thd->transaction.xid_state.xa_state != XA_NOTR)
4681
    {
4682
      my_error(ER_XAER_RMFAIL, MYF(0),
4683
               xa_state_names[thd->transaction.xid_state.xa_state]);
4684 4685 4686 4687 4688 4689 4690
      break;
    }
    if (thd->active_transaction() || thd->locked_tables)
    {
      my_error(ER_XAER_OUTSIDE, MYF(0));
      break;
    }
4691 4692 4693 4694 4695 4696 4697 4698 4699
    if (xid_cache_search(thd->lex->xid))
    {
      my_error(ER_XAER_DUPID, MYF(0));
      break;
    }
    DBUG_ASSERT(thd->transaction.xid_state.xid.is_null());
    thd->transaction.xid_state.xa_state=XA_ACTIVE;
    thd->transaction.xid_state.xid.set(thd->lex->xid);
    xid_cache_insert(&thd->transaction.xid_state);
4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711
    thd->options= ((thd->options & (ulong) ~(OPTION_STATUS_NO_TRANS_UPDATE)) |
                   OPTION_BEGIN);
    thd->server_status|= SERVER_STATUS_IN_TRANS;
    send_ok(thd);
    break;
  case SQLCOM_XA_END:
    /* fake it */
    if (thd->lex->xa_opt != XA_NONE)
    { // SUSPEND and FOR MIGRATE are not supported yet. TODO
      my_error(ER_XAER_INVAL, MYF(0));
      break;
    }
4712
    if (thd->transaction.xid_state.xa_state != XA_ACTIVE)
4713
    {
4714
      my_error(ER_XAER_RMFAIL, MYF(0),
4715
               xa_state_names[thd->transaction.xid_state.xa_state]);
4716 4717
      break;
    }
4718
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4719 4720 4721 4722
    {
      my_error(ER_XAER_NOTA, MYF(0));
      break;
    }
4723
    thd->transaction.xid_state.xa_state=XA_IDLE;
4724 4725 4726
    send_ok(thd);
    break;
  case SQLCOM_XA_PREPARE:
4727
    if (thd->transaction.xid_state.xa_state != XA_IDLE)
4728
    {
4729
      my_error(ER_XAER_RMFAIL, MYF(0),
4730
               xa_state_names[thd->transaction.xid_state.xa_state]);
4731 4732
      break;
    }
4733
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4734 4735 4736 4737 4738 4739 4740
    {
      my_error(ER_XAER_NOTA, MYF(0));
      break;
    }
    if (ha_prepare(thd))
    {
      my_error(ER_XA_RBROLLBACK, MYF(0));
4741 4742
      xid_cache_delete(&thd->transaction.xid_state);
      thd->transaction.xid_state.xa_state=XA_NOTR;
4743 4744
      break;
    }
4745
    thd->transaction.xid_state.xa_state=XA_PREPARED;
4746 4747 4748
    send_ok(thd);
    break;
  case SQLCOM_XA_COMMIT:
4749
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4750
    {
4751 4752
      XID_STATE *xs=xid_cache_search(thd->lex->xid);
      if (!xs || xs->in_thd)
4753
        my_error(ER_XAER_NOTA, MYF(0));
serg@serg.mylan's avatar
serg@serg.mylan committed
4754
      else
4755 4756 4757
      {
        ha_commit_or_rollback_by_xid(thd->lex->xid, 1);
        xid_cache_delete(xs);
serg@serg.mylan's avatar
serg@serg.mylan committed
4758
        send_ok(thd);
4759
      }
4760 4761
      break;
    }
4762
    if (thd->transaction.xid_state.xa_state == XA_IDLE &&
monty@mysql.com's avatar
monty@mysql.com committed
4763
        thd->lex->xa_opt == XA_ONE_PHASE)
4764
    {
4765 4766 4767
      int r;
      if ((r= ha_commit(thd)))
        my_error(r == 1 ? ER_XA_RBROLLBACK : ER_XAER_RMERR, MYF(0));
4768 4769 4770
      else
        send_ok(thd);
    }
4771
    else if (thd->transaction.xid_state.xa_state == XA_PREPARED &&
monty@mysql.com's avatar
monty@mysql.com committed
4772
             thd->lex->xa_opt == XA_NONE)
4773
    {
4774 4775 4776
      if (wait_if_global_read_lock(thd, 0, 0))
      {
        ha_rollback(thd);
4777
        my_error(ER_XAER_RMERR, MYF(0));
4778
      }
4779
      else
4780 4781 4782 4783 4784 4785 4786
      {
        if (ha_commit_one_phase(thd, 1))
          my_error(ER_XAER_RMERR, MYF(0));
        else
          send_ok(thd);
        start_waiting_global_read_lock(thd);
      }
4787 4788 4789
    }
    else
    {
4790
      my_error(ER_XAER_RMFAIL, MYF(0),
4791
               xa_state_names[thd->transaction.xid_state.xa_state]);
4792 4793 4794 4795
      break;
    }
    thd->options&= ~(ulong) (OPTION_BEGIN | OPTION_STATUS_NO_TRANS_UPDATE);
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
4796 4797
    xid_cache_delete(&thd->transaction.xid_state);
    thd->transaction.xid_state.xa_state=XA_NOTR;
4798 4799
    break;
  case SQLCOM_XA_ROLLBACK:
4800
    if (!thd->transaction.xid_state.xid.eq(thd->lex->xid))
4801
    {
4802 4803
      XID_STATE *xs=xid_cache_search(thd->lex->xid);
      if (!xs || xs->in_thd)
4804
        my_error(ER_XAER_NOTA, MYF(0));
serg@serg.mylan's avatar
serg@serg.mylan committed
4805
      else
4806 4807 4808
      {
        ha_commit_or_rollback_by_xid(thd->lex->xid, 0);
        xid_cache_delete(xs);
serg@serg.mylan's avatar
serg@serg.mylan committed
4809
        send_ok(thd);
4810
      }
4811 4812
      break;
    }
4813 4814
    if (thd->transaction.xid_state.xa_state != XA_IDLE &&
        thd->transaction.xid_state.xa_state != XA_PREPARED)
4815
    {
4816
      my_error(ER_XAER_RMFAIL, MYF(0),
4817
               xa_state_names[thd->transaction.xid_state.xa_state]);
4818 4819 4820 4821 4822 4823 4824 4825
      break;
    }
    if (ha_rollback(thd))
      my_error(ER_XAER_RMERR, MYF(0));
    else
      send_ok(thd);
    thd->options&= ~(ulong) (OPTION_BEGIN | OPTION_STATUS_NO_TRANS_UPDATE);
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
4826 4827
    xid_cache_delete(&thd->transaction.xid_state);
    thd->transaction.xid_state.xa_state=XA_NOTR;
4828 4829
    break;
  case SQLCOM_XA_RECOVER:
4830
    res= mysql_xa_recover(thd);
4831 4832 4833
    break;
  default:
    DBUG_ASSERT(0);                             /* Impossible */
4834
    send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4835 4836
    break;
  }
monty@mysql.com's avatar
monty@mysql.com committed
4837
  thd->proc_info="query end";
4838
  /* Two binlog-related cleanups: */
4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851

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

4852
  /*
4853 4854 4855 4856 4857 4858
    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
    wants.

    We do not change the value for a CALL or EXECUTE statement, so the value
    generated by the last called (or executed) statement is preserved.
4859
   */
4860 4861
  if (lex->sql_command != SQLCOM_CALL && lex->sql_command != SQLCOM_EXECUTE &&
      uc_update_queries[lex->sql_command]<2)
4862
    thd->row_count_func= -1;
4863
  DBUG_RETURN(res || thd->net.report_error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4864 4865

error:
4866
  DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4867 4868 4869
}


bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4870 4871
/*
  Check grants for commands which work only with one table and all other
4872
  tables belonging to subselects or implicitly opened tables.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4873

4874
  SYNOPSIS
monty@mysql.com's avatar
monty@mysql.com committed
4875 4876
    check_one_table_access()
    thd			Thread handler
4877
    privilege		requested privilege
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4878
    all_tables		global table list of query
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4879 4880 4881

  RETURN
    0 - OK
monty@mysql.com's avatar
monty@mysql.com committed
4882
    1 - access denied, error is sent to client
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4883 4884
*/

4885
bool check_one_table_access(THD *thd, ulong privilege, TABLE_LIST *all_tables)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4886
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4887
  if (check_access(thd, privilege, all_tables->db,
4888 4889
		   &all_tables->grant.privilege, 0, 0,
                   test(all_tables->schema_table)))
monty@mysql.com's avatar
monty@mysql.com committed
4890
    return 1;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4891

4892
  /* Show only 1 table for check_grant */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4893
  if (grant_option && check_grant(thd, privilege, all_tables, 0, 1, 0))
monty@mysql.com's avatar
monty@mysql.com committed
4894
    return 1;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4895

4896
  /* Check rights on tables of subselects and implictly opened tables */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4897
  TABLE_LIST *subselects_tables;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4898
  if ((subselects_tables= all_tables->next_global))
monty@mysql.com's avatar
monty@mysql.com committed
4899
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4900
    if ((check_table_access(thd, SELECT_ACL, subselects_tables, 0)))
monty@mysql.com's avatar
monty@mysql.com committed
4901 4902 4903
      return 1;
  }
  return 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4904 4905 4906
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
4907
/****************************************************************************
4908
  Get the user (global) and database privileges for all used tables
4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921

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

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

    save_priv	In this we store global and db level grants for the table
		Note that we don't store db level grants if the global grants
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4922 4923
                is enough to satisfy the request and the global grants contains
                a SELECT grant.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4924 4925 4926
****************************************************************************/

bool
4927
check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv,
4928
	     bool dont_check_global_grants, bool no_errors, bool schema_db)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4929
{
4930
  Security_context *sctx= thd->security_ctx;
4931 4932
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  ulong db_access;
4933
  bool  db_is_pattern= test(want_access & GRANT_ACL);
4934 4935
#endif
  ulong dummy;
4936 4937
  DBUG_ENTER("check_access");
  DBUG_PRINT("enter",("db: %s  want_access: %lu  master_access: %lu",
4938
                      db ? db : "", want_access, sctx->master_access));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4939 4940 4941 4942 4943
  if (save_priv)
    *save_priv=0;
  else
    save_priv= &dummy;

4944
  if ((!db || !db[0]) && !thd->db && !dont_check_global_grants)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4945
  {
4946
    DBUG_PRINT("error",("No database"));
4947
    if (!no_errors)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4948 4949
      my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR),
                 MYF(0));                       /* purecov: tested */
4950
    DBUG_RETURN(TRUE);				/* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4951 4952
  }

4953 4954 4955 4956 4957
  if (schema_db)
  {
    if (want_access & ~(SELECT_ACL | EXTRA_ACL))
    {
      if (!no_errors)
4958 4959
      {
        const char *db_name= db ? db : thd->db;
4960
        my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
4961 4962
                 sctx->priv_user, sctx->priv_host, db_name);
      }
4963 4964 4965 4966 4967 4968 4969 4970 4971
      DBUG_RETURN(TRUE);
    }
    else
    {
      *save_priv= SELECT_ACL;
      DBUG_RETURN(FALSE);
    }
  }

monty@mysql.com's avatar
monty@mysql.com committed
4972 4973 4974
#ifdef NO_EMBEDDED_ACCESS_CHECKS
  DBUG_RETURN(0);
#else
4975
  if ((sctx->master_access & want_access) == want_access)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4976
  {
4977 4978 4979 4980 4981
    /*
      If we don't have a global SELECT privilege, we have to get the database
      specific access rights to be able to handle queries of type
      UPDATE t1 SET a=1 WHERE b > 0
    */
4982 4983
    db_access= sctx->db_access;
    if (!(sctx->master_access & SELECT_ACL) &&
4984
	(db && (!thd->db || db_is_pattern || strcmp(db,thd->db))))
4985 4986 4987
      db_access=acl_get(sctx->host, sctx->ip, sctx->priv_user, db,
                        db_is_pattern);
    *save_priv=sctx->master_access | db_access;
4988
    DBUG_RETURN(FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4989
  }
4990
  if (((want_access & ~sctx->master_access) & ~(DB_ACLS | EXTRA_ACL)) ||
4991
      ! db && dont_check_global_grants)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4992
  {						// We can never grant this
4993
    DBUG_PRINT("error",("No possible access"));
4994
    if (!no_errors)
4995
      my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
4996 4997
               sctx->priv_user,
               sctx->priv_host,
4998 4999 5000
               (thd->password ?
                ER(ER_YES) :
                ER(ER_NO)));                    /* purecov: tested */
5001
    DBUG_RETURN(TRUE);				/* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5002 5003 5004
  }

  if (db == any_db)
5005
    DBUG_RETURN(FALSE);				// Allow select on anything
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5006

5007
  if (db && (!thd->db || db_is_pattern || strcmp(db,thd->db)))
5008 5009
    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
5010
  else
5011
    db_access= sctx->db_access;
5012
  DBUG_PRINT("info",("db_access: %lu", db_access));
monty@mysql.com's avatar
monty@mysql.com committed
5013
  /* Remove SHOW attribute and access rights we already have */
5014
  want_access &= ~(sctx->master_access | EXTRA_ACL);
5015 5016
  DBUG_PRINT("info",("db_access: %lu  want_access: %lu",
                     db_access, want_access));
5017
  db_access= ((*save_priv=(db_access | sctx->master_access)) & want_access);
5018 5019

  /* grant_option is set if there exists a single table or column grant */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5020
  if (db_access == want_access ||
5021
      (grant_option && !dont_check_global_grants &&
5022
       !(want_access & ~(db_access | TABLE_ACLS | PROC_ACLS))))
5023
    DBUG_RETURN(FALSE);				/* Ok */
5024 5025

  DBUG_PRINT("error",("Access denied"));
5026
  if (!no_errors)
5027
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
5028
             sctx->priv_user, sctx->priv_host,
5029 5030 5031
             (db ? db : (thd->db ?
                         thd->db :
                         "unknown")));          /* purecov: tested */
5032
  DBUG_RETURN(TRUE);				/* purecov: tested */
monty@mysql.com's avatar
monty@mysql.com committed
5033
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5034 5035 5036
}


5037 5038 5039 5040 5041 5042 5043 5044 5045
/*
  check for global access and give descriptive error message if it fails

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

  WARNING
5046
    One gets access right if one has ANY of the rights in want_access
5047 5048 5049 5050 5051 5052 5053 5054
    This is useful as one in most cases only need one global right,
    but in some case we want to check if the user has SUPER or
    REPL_CLIENT_ACL rights.

  RETURN
    0	ok
    1	Access denied.  In this case an error is sent to the client
*/
5055 5056

bool check_global_access(THD *thd, ulong want_access)
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
5057
{
monty@mysql.com's avatar
monty@mysql.com committed
5058 5059 5060
#ifdef NO_EMBEDDED_ACCESS_CHECKS
  return 0;
#else
5061
  char command[128];
5062
  if ((thd->security_ctx->master_access & want_access))
5063 5064
    return 0;
  get_privilege_desc(command, sizeof(command), want_access);
5065
  my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), command);
5066
  return 1;
monty@mysql.com's avatar
monty@mysql.com committed
5067
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
5068 5069 5070
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
5071
/*
5072 5073
  Check the privilege for all used tables.  Table privileges are cached
  in the table list for GRANT checking
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5074 5075
*/

5076
bool
5077
check_table_access(THD *thd, ulong want_access,TABLE_LIST *tables,
5078
		   bool no_errors)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5079
{
5080 5081
  uint found=0;
  ulong found_access=0;
5082 5083 5084
  TABLE_LIST *org_tables= tables;
  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
  /*
5085 5086 5087
    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.
5088
  */
5089
  for (; tables != first_not_own_table; tables= tables->next_global)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5090
  {
5091
    if (tables->schema_table && 
5092
        (want_access & ~(SELECT_ACL | EXTRA_ACL | FILE_ACL)))
5093 5094 5095
    {
      if (!no_errors)
        my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
5096
                 thd->security_ctx->priv_user, thd->security_ctx->priv_host,
5097 5098 5099
                 information_schema_name.str);
      return TRUE;
    }
5100 5101 5102 5103 5104
    /*
       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);
5105
    if (tables->derived || tables->schema_table || tables->belong_to_view ||
5106
        (tables->table && (int)tables->table->s->tmp_table) ||
5107 5108
        my_tz_check_n_skip_implicit_tables(&tables,
                                           thd->lex->time_zone_tables_used))
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
5109
      continue;
5110 5111
    if ((thd->security_ctx->master_access & want_access) ==
        (want_access & ~EXTRA_ACL) &&
5112
	thd->db)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5113
      tables->grant.privilege= want_access;
5114
    else if (tables->db && tables->db == thd->db)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5115 5116 5117 5118 5119
    {
      if (found && !grant_option)		// db already checked
	tables->grant.privilege=found_access;
      else
      {
5120
	if (check_access(thd,want_access,tables->db,&tables->grant.privilege,
5121
			 0, no_errors, test(tables->schema_table)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5122 5123
	  return TRUE;				// Access denied
	found_access=tables->grant.privilege;
5124
	found=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5125 5126
      }
    }
5127
    else if (check_access(thd,want_access,tables->db,&tables->grant.privilege,
5128
			  0, no_errors, test(tables->schema_table)))
5129
      return TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5130 5131
  }
  if (grant_option)
5132
    return check_grant(thd,want_access & ~EXTRA_ACL,org_tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5133
		       test(want_access & EXTRA_ACL), UINT_MAX, no_errors);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5134 5135 5136
  return FALSE;
}

5137

5138
bool
5139 5140
check_routine_access(THD *thd, ulong want_access,char *db, char *name,
		     bool is_proc, bool no_errors)
5141 5142 5143 5144 5145
{
  TABLE_LIST tables[1];
  
  bzero((char *)tables, sizeof(TABLE_LIST));
  tables->db= db;
5146
  tables->table_name= tables->alias= name;
5147
  
monty@mysql.com's avatar
monty@mysql.com committed
5148 5149 5150 5151 5152 5153 5154
  /*
    The following test is just a shortcut for check_access() (to avoid
    calculating db_access) under the assumption that it's common to
    give persons global right to execute all stored SP (but not
    necessary to create them).
  */
  if ((thd->security_ctx->master_access & want_access) == want_access)
5155 5156
    tables->grant.privilege= want_access;
  else if (check_access(thd,want_access,db,&tables->grant.privilege,
monty@mysql.com's avatar
monty@mysql.com committed
5157
			0, no_errors, 0))
5158 5159
    return TRUE;
  
5160
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5161
  if (grant_option)
5162
    return check_grant_routine(thd, want_access, tables, is_proc, no_errors);
5163
#endif
5164 5165 5166 5167

  return FALSE;
}

5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182

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

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

  RETURN
    0            ok
    1            error
*/

5183 5184
bool check_some_routine_access(THD *thd, const char *db, const char *name,
                               bool is_proc)
5185 5186
{
  ulong save_priv;
5187
  if (thd->security_ctx->master_access & SHOW_PROC_ACLS)
5188
    return FALSE;
5189 5190 5191 5192 5193
  /*
    There are no routines in information_schema db. So we can safely
    pass zero to last paramter of check_access function
  */
  if (!check_access(thd, SHOW_PROC_ACLS, db, &save_priv, 0, 1, 0) ||
5194 5195
      (save_priv & SHOW_PROC_ACLS))
    return FALSE;
5196
  return check_routine_level_acl(thd, db, name, is_proc);
5197 5198 5199
}


5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224
/*
  Check if the given table has any of the asked privileges

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

  RETURN
    0  ok
    1  error
*/


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

  /* This loop will work as long as we have less than 32 privileges */
  for (access= 1; access < want_access ; access<<= 1)
  {
    if (access & want_access)
    {
      if (!check_access(thd, access, table->db,
5225 5226
                        &table->grant.privilege, 0, 1,
                        test(table->schema_table)) &&
5227 5228 5229 5230 5231 5232 5233 5234 5235
          !grant_option || !check_grant(thd, access, table, 0, 1, 1))
        DBUG_RETURN(0);
    }
  }
  DBUG_PRINT("exit",("no matching access rights"));
  DBUG_RETURN(1);
}


5236 5237
bool check_merge_table_access(THD *thd, char *db,
			      TABLE_LIST *table_list)
5238 5239 5240 5241
{
  int error=0;
  if (table_list)
  {
5242
    /* Check that all tables use the current database */
5243
    TABLE_LIST *tmp;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5244
    for (tmp= table_list; tmp; tmp= tmp->next_local)
5245 5246 5247 5248
    {
      if (!tmp->db || !tmp->db[0])
	tmp->db=db;
    }
5249
    error=check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL,
hf@deer.(none)'s avatar
hf@deer.(none) committed
5250
			     table_list,0);
5251 5252 5253 5254
  }
  return error;
}

hf@deer.(none)'s avatar
hf@deer.(none) committed
5255 5256 5257

static bool check_db_used(THD *thd,TABLE_LIST *tables)
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5258
  for (; tables; tables= tables->next_global)
hf@deer.(none)'s avatar
hf@deer.(none) committed
5259 5260 5261 5262 5263
  {
    if (!tables->db)
    {
      if (!(tables->db=thd->db))
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5264 5265
	my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR),
                   MYF(0));                     /* purecov: tested */
hf@deer.(none)'s avatar
hf@deer.(none) committed
5266 5267 5268 5269 5270 5271
	return TRUE;				/* purecov: tested */
      }
    }
  }
  return FALSE;
}
5272

5273

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5274 5275 5276 5277 5278 5279 5280 5281 5282 5283
/****************************************************************************
	Check stack size; Send error if there isn't enough stack to continue
****************************************************************************/

#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
5284 5285 5286 5287
#ifndef DBUG_OFF
long max_stack_used;
#endif

5288
#ifndef EMBEDDED_LIBRARY
5289 5290 5291 5292 5293 5294 5295 5296
/*
  Note: The 'buf' parameter is necessary, even if it is unused here.
  - fix_fields functions has a "dummy" buffer large enough for the
    corresponding exec. (Thus we only have to check in fix_fields.)
  - Passing to check_stack_overrun() prevents the compiler from removing it.
 */
bool check_stack_overrun(THD *thd, long margin,
			 char *buf __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5297 5298
{
  long stack_used;
5299
  DBUG_ASSERT(thd == current_thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5300
  if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >=
monty@mysql.com's avatar
monty@mysql.com committed
5301
      (long) (thread_stack - margin))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5302
  {
5303 5304 5305
    sprintf(errbuff[0],ER(ER_STACK_OVERRUN_NEED_MORE),
            stack_used,thread_stack,margin);
    my_message(ER_STACK_OVERRUN_NEED_MORE,errbuff[0],MYF(0));
5306
    thd->fatal_error();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5307 5308
    return 1;
  }
monty@mysql.com's avatar
monty@mysql.com committed
5309 5310 5311
#ifndef DBUG_OFF
  max_stack_used= max(max_stack_used, stack_used);
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5312 5313
  return 0;
}
5314
#endif /* EMBEDDED_LIBRARY */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5315 5316 5317 5318

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

5319
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5320 5321
{
  LEX	*lex=current_lex;
5322
  ulong old_info=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348
  if ((uint) *yystacksize >= MY_YACC_MAX)
    return 1;
  if (!lex->yacc_yyvs)
    old_info= *yystacksize;
  *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
  if (!(lex->yacc_yyvs= (char*)
	my_realloc((gptr) lex->yacc_yyvs,
		   *yystacksize*sizeof(**yyvs),
		   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
      !(lex->yacc_yyss= (char*)
	my_realloc((gptr) lex->yacc_yyss,
		   *yystacksize*sizeof(**yyss),
		   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
    return 1;
  if (old_info)
  {						// Copy old info from stack
    memcpy(lex->yacc_yyss, (gptr) *yyss, old_info*sizeof(**yyss));
    memcpy(lex->yacc_yyvs, (gptr) *yyvs, old_info*sizeof(**yyvs));
  }
  *yyss=(short*) lex->yacc_yyss;
  *yyvs=(YYSTYPE*) lex->yacc_yyvs;
  return 0;
}


/****************************************************************************
5349
  Initialize global thd variables needed for query
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5350 5351
****************************************************************************/

5352
void
5353
mysql_init_query(THD *thd, uchar *buf, uint length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5354 5355
{
  DBUG_ENTER("mysql_init_query");
5356
  lex_start(thd, buf, length);
5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377
  mysql_reset_thd_for_next_command(thd);
  DBUG_VOID_RETURN;
}


/*
 Reset THD part responsible for command processing state.

 DESCRIPTION
   This needs to be called before execution of every statement
   (prepared or conventional).

 TODO
   Make it a method of THD and align its name with the rest of
   reset/end/start/init methods.
   Call it after we use THD for queries, not before.
*/

void mysql_reset_thd_for_next_command(THD *thd)
{
  DBUG_ENTER("mysql_reset_thd_for_next_command");
5378
  thd->free_list= 0;
5379
  thd->select_number= 1;
5380
  thd->last_insert_id_used= thd->query_start_used= thd->insert_id_used=0;
5381
  thd->is_fatal_error= thd->time_zone_used= 0;
monty@mysql.com's avatar
monty@mysql.com committed
5382
  thd->server_status&= ~ (SERVER_MORE_RESULTS_EXISTS | 
monty@mysql.com's avatar
monty@mysql.com committed
5383 5384
                          SERVER_QUERY_NO_INDEX_USED |
                          SERVER_QUERY_NO_GOOD_INDEX_USED);
5385
  DBUG_ASSERT(thd->security_ctx== &thd->main_security_ctx);
5386
  thd->tmp_table_used= 0;
5387 5388
  if (!thd->in_sub_stmt)
  {
5389
    if (opt_bin_log)
5390
    {
5391
      reset_dynamic(&thd->user_var_events);
5392 5393
      thd->user_var_events_alloc= thd->mem_root;
    }
5394
    thd->clear_error();
5395 5396 5397 5398
    thd->total_warn_count=0;			// Warnings for this query
    thd->rand_used= 0;
    thd->sent_row_count= thd->examined_row_count= 0;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5399 5400 5401
  DBUG_VOID_RETURN;
}

5402

5403 5404 5405
void
mysql_init_select(LEX *lex)
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5406
  SELECT_LEX *select_lex= lex->current_select;
5407
  select_lex->init_select();
5408
  lex->wild= 0;
5409 5410
  if (select_lex == &lex->select_lex)
  {
5411
    DBUG_ASSERT(lex->result == 0);
5412 5413
    lex->exchange= 0;
  }
5414 5415
}

5416

5417
bool
5418
mysql_new_select(LEX *lex, bool move_down)
5419
{
5420
  SELECT_LEX *select_lex;
5421
  THD *thd= lex->thd;
5422 5423
  DBUG_ENTER("mysql_new_select");

5424
  if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
5425
    DBUG_RETURN(1);
5426
  select_lex->select_number= ++thd->select_number;
5427
  select_lex->parent_lex= lex; /* Used in init_query. */
5428 5429
  select_lex->init_query();
  select_lex->init_select();
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
5430 5431
  lex->nest_level++;
  select_lex->nest_level= lex->nest_level;
5432 5433 5434 5435 5436
  /*
    Don't evaluate this subquery during statement prepare even if
    it's a constant one. The flag is switched off in the end of
    mysql_stmt_prepare.
  */
konstantin@mysql.com's avatar
konstantin@mysql.com committed
5437
  if (thd->stmt_arena->is_stmt_prepare())
5438
    select_lex->uncacheable|= UNCACHEABLE_PREPARE;
5439 5440
  if (move_down)
  {
5441
    SELECT_LEX_UNIT *unit;
5442
    lex->subqueries= TRUE;
5443
    /* first select_lex of subselect or derived table */
5444
    if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
5445
      DBUG_RETURN(1);
5446

5447 5448
    unit->init_query();
    unit->init_select();
5449
    unit->thd= thd;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5450
    unit->include_down(lex->current_select);
5451 5452
    unit->link_next= 0;
    unit->link_prev= 0;
5453
    unit->return_to= lex->current_select;
5454
    select_lex->include_down(unit);
5455 5456 5457 5458 5459
    /*
      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;
5460 5461
  }
  else
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5462
  {
5463
    Name_resolution_context *outer_context;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5464 5465
    if (lex->current_select->order_list.first && !lex->current_select->braces)
    {
5466
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY");
5467
      DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5468
    }
5469
    select_lex->include_neighbour(lex->current_select);
5470 5471 5472 5473 5474 5475
    /*
      we are not sure that we have one level of SELECTs above, so we take
      outer_context address from first select of unit
    */
    outer_context=
      select_lex->master_unit()->first_select()->context.outer_context;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5476 5477 5478 5479 5480 5481 5482 5483
    SELECT_LEX_UNIT *unit= select_lex->master_unit();
    SELECT_LEX *fake= unit->fake_select_lex;
    if (!fake)
    {
      /*
	as far as we included SELECT_LEX for UNION unit should have
	fake SELECT_LEX for UNION processing
      */
5484
      if (!(fake= unit->fake_select_lex= new (thd->mem_root) SELECT_LEX()))
5485
        DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5486 5487 5488
      fake->include_standalone(unit,
			       (SELECT_LEX_NODE**)&unit->fake_select_lex);
      fake->select_number= INT_MAX;
5489
      fake->parent_lex= lex; /* Used in init_query. */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5490 5491
      fake->make_empty_select();
      fake->linkage= GLOBAL_OPTIONS_TYPE;
5492
      fake->select_limit= 0;
5493 5494 5495 5496 5497

      fake->context.outer_context= outer_context;
      /* allow item list resolving in fake select for ORDER BY */
      fake->context.resolve_in_select_list= TRUE;
      fake->context.select_lex= fake;
5498 5499 5500 5501 5502
      /*
        Remove the name resolution context of the fake select from the
        context stack.
       */
      lex->pop_context();
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5503
    }
5504
    select_lex->context.outer_context= outer_context;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5505
  }
peter@mysql.com's avatar
peter@mysql.com committed
5506

5507
  select_lex->master_unit()->global_parameters= select_lex;
5508
  select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
5509
  lex->current_select= select_lex;
5510 5511 5512 5513 5514
  /*
    in subquery is SELECT query and we allow resolution of names in SELECT
    list
  */
  select_lex->context.resolve_in_select_list= TRUE;
5515
  DBUG_RETURN(0);
5516
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5517

5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532
/*
  Create a select to return the same output as 'SELECT @@var_name'.

  SYNOPSIS
    create_select_for_variable()
    var_name		Variable name

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

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

void create_select_for_variable(const char *var_name)
{
5533
  THD *thd;
5534
  LEX *lex;
5535
  LEX_STRING tmp, null_lex_string;
5536 5537
  Item *var;
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
5538
  DBUG_ENTER("create_select_for_variable");
5539 5540

  thd= current_thd;
pem@mysql.telia.com's avatar
pem@mysql.telia.com committed
5541
  lex= thd->lex;
5542 5543 5544 5545
  mysql_init_select(lex);
  lex->sql_command= SQLCOM_SELECT;
  tmp.str= (char*) var_name;
  tmp.length=strlen(var_name);
5546
  bzero((char*) &null_lex_string.str, sizeof(null_lex_string));
5547 5548 5549 5550
  /*
    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
5551 5552 5553 5554 5555 5556
  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);
  }
5557 5558 5559
  DBUG_VOID_RETURN;
}

5560

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5561 5562
void mysql_init_multi_delete(LEX *lex)
{
5563
  lex->sql_command=  SQLCOM_DELETE_MULTI;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5564
  mysql_init_select(lex);
5565 5566
  lex->select_lex.select_limit= 0;
  lex->unit.select_limit_cnt= HA_POS_ERROR;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5567
  lex->select_lex.table_list.save_and_clear(&lex->auxilliary_table_list);
5568
  lex->lock_option= using_update_log ? TL_READ_NO_INSERT : TL_READ;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5569 5570
  lex->query_tables= 0;
  lex->query_tables_last= &lex->query_tables;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5571
}
5572

5573

5574 5575 5576 5577
/*
  When you modify mysql_parse(), you may need to mofify
  mysql_test_parse_for_slave() in this same file.
*/
5578

5579
void mysql_parse(THD *thd, char *inBuf, uint length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5580 5581
{
  DBUG_ENTER("mysql_parse");
5582
  mysql_init_query(thd, (uchar*) inBuf, length);
5583
  if (query_cache_send_result_to_client(thd, inBuf, length) <= 0)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5584
  {
5585
    LEX *lex= thd->lex;
5586
    
5587 5588
    sp_cache_flush_obsolete(&thd->sp_proc_cache);
    sp_cache_flush_obsolete(&thd->sp_func_cache);
5589
    
5590
    if (!yyparse((void *)thd) && ! thd->is_fatal_error)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5591
    {
hf@deer.(none)'s avatar
hf@deer.(none) committed
5592
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5593
      if (mqh_used && thd->user_connect &&
5594
	  check_mqh(thd, lex->sql_command))
5595 5596 5597 5598
      {
	thd->net.error = 0;
      }
      else
hf@deer.(none)'s avatar
hf@deer.(none) committed
5599
#endif
5600
      {
5601
	if (thd->net.report_error)
5602 5603
	{
	  if (thd->lex->sphead)
5604 5605 5606 5607
	  {
	    delete thd->lex->sphead;
	    thd->lex->sphead= NULL;
	  }
5608
	}
5609 5610
	else
	{
5611 5612 5613 5614 5615 5616 5617 5618 5619 5620
          /*
            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.
          */
serg@serg.mylan's avatar
serg@serg.mylan committed
5621 5622
          if (lex->found_semicolon &&
              (thd->query_length= (ulong)(lex->found_semicolon - thd->query)))
5623 5624
            thd->query_length--;
          /* Actually execute the query */
5625
	  mysql_execute_command(thd);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
5626
	  query_cache_end_of_result(thd);
5627
	}
5628
      }
5629
      lex->unit.cleanup();
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5630 5631
    }
    else
5632 5633
    {
      DBUG_PRINT("info",("Command aborted. Fatal_error: %d",
5634
			 thd->is_fatal_error));
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5635
      query_cache_abort(&thd->net);
5636
      lex->unit.cleanup();
5637
      if (thd->lex->sphead)
5638
      {
monty@mysql.com's avatar
monty@mysql.com committed
5639
	/* Clean up after failed stored procedure/function */
5640 5641 5642
	delete thd->lex->sphead;
	thd->lex->sphead= NULL;
      }
5643
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5644
    thd->proc_info="freeing items";
5645
    thd->end_statement();
5646
    thd->cleanup_after_query();
5647
    DBUG_ASSERT(thd->change_list.is_empty());
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5648
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5649 5650 5651 5652
  DBUG_VOID_RETURN;
}


monty@mysql.com's avatar
monty@mysql.com committed
5653
#ifdef HAVE_REPLICATION
5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664
/*
  Usable by the replication SQL thread only: just parse a query to know if it
  can be ignored because of replicate-*-table rules.

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

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

5669
  mysql_init_query(thd, (uchar*) inBuf, length);
monty@mysql.com's avatar
monty@mysql.com committed
5670
  if (!yyparse((void*) thd) && ! thd->is_fatal_error &&
5671
      all_tables_not_ok(thd,(TABLE_LIST*) lex->select_lex.table_list.first))
monty@mysql.com's avatar
monty@mysql.com committed
5672
    error= 1;                  /* Ignore question */
5673
  thd->end_statement();
5674
  thd->cleanup_after_query();
monty@mysql.com's avatar
monty@mysql.com committed
5675
  DBUG_RETURN(error);
5676
}
monty@mysql.com's avatar
monty@mysql.com committed
5677
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5678

5679

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5681 5682 5683 5684 5685
/*****************************************************************************
** Store field definition for create
** Return 0 if ok
******************************************************************************/

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5686
bool add_field_to_list(THD *thd, char *field_name, enum_field_types type,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5687
		       char *length, char *decimals,
5688
		       uint type_modifier,
5689 5690
		       Item *default_value, Item *on_update_value,
                       LEX_STRING *comment,
5691 5692
		       char *change,
                       List<String> *interval_list, CHARSET_INFO *cs,
5693
		       uint uint_geom_type)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5694 5695
{
  register create_field *new_field;
5696
  LEX  *lex= thd->lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5697 5698 5699 5700
  DBUG_ENTER("add_field_to_list");

  if (strlen(field_name) > NAME_LEN)
  {
5701
    my_error(ER_TOO_LONG_IDENT, MYF(0), field_name); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5702 5703 5704 5705 5706
    DBUG_RETURN(1);				/* purecov: inspected */
  }
  if (type_modifier & PRI_KEY_FLAG)
  {
    lex->col_list.push_back(new key_part_spec(field_name,0));
5707
    lex->key_list.push_back(new Key(Key::PRIMARY, NullS, HA_KEY_ALG_UNDEF,
5708
				    0, lex->col_list));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5709 5710 5711 5712 5713
    lex->col_list.empty();
  }
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
  {
    lex->col_list.push_back(new key_part_spec(field_name,0));
5714
    lex->key_list.push_back(new Key(Key::UNIQUE, NullS, HA_KEY_ALG_UNDEF, 0,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5715 5716 5717 5718
				    lex->col_list));
    lex->col_list.empty();
  }

5719
  if (default_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5720
  {
5721
    /* 
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5722 5723
      Default value should be literal => basic constants =>
      no need fix_fields()
5724 5725 5726
      
      We allow only one function as part of default value - 
      NOW() as default for TIMESTAMP type.
5727
    */
5728 5729 5730
    if (default_value->type() == Item::FUNC_ITEM && 
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
         type == FIELD_TYPE_TIMESTAMP))
5731
    {
5732
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name);
5733 5734 5735
      DBUG_RETURN(1);
    }
    else if (default_value->type() == Item::NULL_ITEM)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5736
    {
5737
      default_value= 0;
5738 5739 5740
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
	  NOT_NULL_FLAG)
      {
5741
	my_error(ER_INVALID_DEFAULT, MYF(0), field_name);
5742 5743 5744 5745 5746
	DBUG_RETURN(1);
      }
    }
    else if (type_modifier & AUTO_INCREMENT_FLAG)
    {
5747
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5748 5749 5750
      DBUG_RETURN(1);
    }
  }
5751 5752 5753

  if (on_update_value && type != FIELD_TYPE_TIMESTAMP)
  {
5754
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name);
5755 5756
    DBUG_RETURN(1);
  }
5757

5758 5759 5760 5761 5762 5763
  if (type == FIELD_TYPE_TIMESTAMP && length)
  {
    /* Display widths are no longer supported for TIMSTAMP as of MySQL 4.1.
       In other words, for declarations such as TIMESTAMP(2), TIMESTAMP(4),
       and so on, the display width is ignored.
    */
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
5764
    char buf[32];
5765
    my_snprintf(buf, sizeof(buf), "TIMESTAMP(%s)", length);
5766 5767 5768
    push_warning_printf(thd,MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_WARN_DEPRECATED_SYNTAX,
                        ER(ER_WARN_DEPRECATED_SYNTAX),
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
5769
                        buf, "TIMESTAMP");
5770 5771
  }

5772 5773 5774 5775
  if (!(new_field= new create_field()) ||
      new_field->init(thd, field_name, type, length, decimals, type_modifier,
                      default_value, on_update_value, comment, change,
                      interval_list, cs, uint_geom_type))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5776
    DBUG_RETURN(1);
5777 5778 5779 5780 5781 5782

  lex->create_list.push_back(new_field);
  lex->last_field=new_field;
  DBUG_RETURN(0);
}

5783

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5784 5785 5786 5787 5788 5789 5790 5791
/* Store position for column in ALTER TABLE .. ADD column */

void store_position_for_column(const char *name)
{
  current_lex->last_field->after=my_const_cast(char*) (name);
}

bool
5792
add_proc_to_list(THD* thd, Item *item)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5793 5794 5795 5796
{
  ORDER *order;
  Item	**item_ptr;

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5797
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5798 5799 5800 5801 5802
    return 1;
  item_ptr = (Item**) (order+1);
  *item_ptr= item;
  order->item=item_ptr;
  order->free_me=0;
5803
  thd->lex->proc_list.link_in_list((byte*) order,(byte**) &order->next);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5804 5805 5806 5807 5808 5809 5810 5811
  return 0;
}


/* Fix escaping of _, % and \ in database and table names (for ODBC) */

static void remove_escape(char *name)
{
5812 5813
  if (!*name)					// For empty DB names
    return;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5814 5815
  char *to;
#ifdef USE_MB
5816
  char *strend=name+(uint) strlen(name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5817 5818 5819 5820 5821
#endif
  for (to=name; *name ; name++)
  {
#ifdef USE_MB
    int l;
5822 5823
    if (use_mb(system_charset_info) &&
        (l = my_ismbchar(system_charset_info, name, strend)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5824 5825 5826 5827 5828 5829 5830 5831
    {
	while (l--)
	    *to++ = *name++;
	name--;
	continue;
    }
#endif
    if (*name == '\\' && name[1])
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5832
      name++;					// Skip '\\'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5833 5834 5835 5836 5837 5838 5839 5840 5841 5842
    *to++= *name;
  }
  *to=0;
}

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


monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5843
bool add_to_list(THD *thd, SQL_LIST &list,Item *item,bool asc)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5844 5845 5846
{
  ORDER *order;
  DBUG_ENTER("add_to_list");
5847
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5848
    DBUG_RETURN(1);
5849 5850
  order->item_ptr= item;
  order->item= &order->item_ptr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5851 5852 5853
  order->asc = asc;
  order->free_me=0;
  order->used=0;
5854
  order->counter_used= 0;
5855
  list.link_in_list((byte*) order,(byte**) &order->next);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5856 5857 5858 5859
  DBUG_RETURN(0);
}


monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878
/*
  Add a table to list of used tables

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

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

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5879 5880
TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
					     Table_ident *table,
5881
					     LEX_STRING *alias,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5882 5883
					     ulong table_options,
					     thr_lock_type lock_type,
5884 5885
					     List<String> *use_index_arg,
					     List<String> *ignore_index_arg,
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
5886
                                             LEX_STRING *option)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5887 5888
{
  register TABLE_LIST *ptr;
5889
  TABLE_LIST *previous_table_ref; /* The table preceding the current one. */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5890
  char *alias_str;
5891
  LEX *lex= thd->lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5892
  DBUG_ENTER("add_table_to_list");
5893
  LINT_INIT(previous_table_ref);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5894 5895 5896 5897

  if (!table)
    DBUG_RETURN(0);				// End of memory
  alias_str= alias ? alias->str : table->table.str;
5898
  if (check_table_name(table->table.str,table->table.length) ||
5899
      table->db.str && check_db_name(table->db.str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5900
  {
5901
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5902 5903 5904 5905
    DBUG_RETURN(0);
  }

  if (!alias)					/* Alias is case sensitive */
5906 5907 5908
  {
    if (table->sel)
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5909 5910
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
                 ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
5911 5912
      DBUG_RETURN(0);
    }
5913
    if (!(alias_str=thd->memdup(alias_str,table->table.length+1)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5914
      DBUG_RETURN(0);
5915
  }
5916
  if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5917
    DBUG_RETURN(0);				/* purecov: inspected */
peter@mysql.com's avatar
peter@mysql.com committed
5918
  if (table->db.str)
5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929
  {
    ptr->db= table->db.str;
    ptr->db_length= table->db.length;
  }
  else if (thd->db)
  {
    ptr->db= thd->db;
    ptr->db_length= thd->db_length;
  }
  else
  {
5930 5931
    /* The following can't be "" as we may do 'casedn_str()' on it */
    ptr->db= empty_c_string;
5932 5933
    ptr->db_length= 0;
  }
konstantin@mysql.com's avatar
konstantin@mysql.com committed
5934
  if (thd->stmt_arena->is_stmt_prepare_or_first_sp_execute())
5935
    ptr->db= thd->strdup(ptr->db);
peter@mysql.com's avatar
peter@mysql.com committed
5936

5937
  ptr->alias= alias_str;
5938 5939
  if (lower_case_table_names && table->table.length)
    my_casedn_str(files_charset_info, table->table.str);
5940 5941
  ptr->table_name=table->table.str;
  ptr->table_name_length=table->table.length;
5942
  ptr->lock_type=   lock_type;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5943 5944
  ptr->updating=    test(table_options & TL_OPTION_UPDATING);
  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
5945
  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
5946
  ptr->derived=	    table->sel;
5947 5948
  if (!ptr->derived && !my_strcasecmp(system_charset_info, ptr->db,
                                      information_schema_name.str))
5949
  {
5950
    ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, ptr->table_name);
5951 5952 5953
    if (!schema_table ||
        (schema_table->hidden && 
         lex->orig_sql_command == SQLCOM_END))  // not a 'show' command
5954
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5955
      my_error(ER_UNKNOWN_TABLE, MYF(0),
5956
               ptr->table_name, information_schema_name.str);
5957 5958
      DBUG_RETURN(0);
    }
5959
    ptr->schema_table_name= ptr->table_name;
5960 5961
    ptr->schema_table= schema_table;
  }
5962
  ptr->select_lex=  lex->current_select;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5963
  ptr->cacheable_table= 1;
5964 5965 5966 5967 5968 5969
  if (use_index_arg)
    ptr->use_index=(List<String> *) thd->memdup((gptr) use_index_arg,
						sizeof(*use_index_arg));
  if (ignore_index_arg)
    ptr->ignore_index=(List<String> *) thd->memdup((gptr) ignore_index_arg,
						   sizeof(*ignore_index_arg));
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
5970
  ptr->option= option ? option->str : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5971
  /* check that used name is unique */
5972
  if (lock_type != TL_IGNORE)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5973
  {
timour@mysql.com's avatar
timour@mysql.com committed
5974 5975 5976 5977
    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 ;
5978
	 tables ;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5979
	 tables=tables->next_local)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5980
    {
5981 5982
      if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
	  !strcmp(ptr->db, tables->db))
5983
      {
5984
	my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
5985 5986
	DBUG_RETURN(0);				/* purecov: tested */
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5987 5988
    }
  }
5989 5990 5991
  /* Store the table reference preceding the current one. */
  if (table_list.elements > 0)
  {
5992 5993 5994 5995 5996 5997
    /*
      table_list.next points to the last inserted TABLE_LIST->next_local'
      element
    */
    previous_table_ref= (TABLE_LIST*) (table_list.next -
                                       offsetof(TABLE_LIST, next_local));
5998
    DBUG_ASSERT(previous_table_ref);
5999 6000 6001 6002 6003 6004 6005 6006
    /*
      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;
6007
  }
6008

6009 6010 6011 6012 6013 6014
  /*
    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'.
  */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6015
  table_list.link_in_list((byte*) ptr, (byte**) &ptr->next_local);
6016
  ptr->next_name_resolution_table= NULL;
6017
  /* Link table in global list (all used tables) */
6018
  lex->add_to_query_tables(ptr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6019 6020 6021
  DBUG_RETURN(ptr);
}

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

6023 6024 6025 6026
/*
  Initialize a new table list for a nested join

  SYNOPSIS
6027
    init_nested_join()
6028
    thd         current thread
6029

6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048
  DESCRIPTION
    The function initializes a structure of the TABLE_LIST type
    for a nested join. It sets up its nested join list as empty.
    The created structure is added to the front of the current
    join list in the st_select_lex object. Then the function
    changes the current nest level for joins to refer to the newly
    created empty list after having saved the info on the old level
    in the initialized structure.

  RETURN VALUE
    0,  if success
    1,  otherwise
*/

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

6050 6051
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
6052
    DBUG_RETURN(1);
6053 6054 6055
  nested_join= ptr->nested_join=
    ((NESTED_JOIN*) ((byte*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));

6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075
  join_list->push_front(ptr);
  ptr->embedding= embedding;
  ptr->join_list= join_list;
  embedding= ptr;
  join_list= &nested_join->join_list;
  join_list->empty();
  DBUG_RETURN(0);
}


/*
  End a nested join table list

  SYNOPSIS
    end_nested_join()
    thd         current thread

  DESCRIPTION
    The function returns to the previous join nest level.
    If the current level contains only one member, the function
6076
    moves it one level up, eliminating the nest.
6077 6078 6079 6080 6081 6082 6083 6084 6085

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

TABLE_LIST *st_select_lex::end_nested_join(THD *thd)
{
  TABLE_LIST *ptr;
6086
  NESTED_JOIN *nested_join;
6087
  DBUG_ENTER("end_nested_join");
6088

6089
  DBUG_ASSERT(embedding);
6090 6091 6092
  ptr= embedding;
  join_list= ptr->join_list;
  embedding= ptr->embedding;
6093
  nested_join= ptr->nested_join;
6094 6095 6096 6097 6098 6099 6100 6101 6102
  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;
  }
6103
  else if (nested_join->join_list.elements == 0)
6104 6105
  {
    join_list->pop();
6106
    ptr= 0;                                     // return value
6107
  }
6108 6109 6110 6111 6112 6113 6114 6115
  DBUG_RETURN(ptr);
}


/*
  Nest last join operation

  SYNOPSIS
6116
    nest_last_join()
6117 6118 6119 6120 6121 6122
    thd         current thread

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

  RETURN VALUE
6123 6124 6125
    0  Error
    #  Pointer to TABLE_LIST element created for the new nested join

6126 6127 6128 6129 6130 6131
*/

TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
6132
  List<TABLE_LIST> *embedded_list;
6133
  DBUG_ENTER("nest_last_join");
6134

6135 6136
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                       sizeof(NESTED_JOIN))))
6137
    DBUG_RETURN(0);
6138 6139 6140
  nested_join= ptr->nested_join=
    ((NESTED_JOIN*) ((byte*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));

6141 6142
  ptr->embedding= embedding;
  ptr->join_list= join_list;
6143
  embedded_list= &nested_join->join_list;
6144
  embedded_list->empty();
6145 6146

  for (uint i=0; i < 2; i++)
6147 6148 6149 6150 6151
  {
    TABLE_LIST *table= join_list->pop();
    table->join_list= embedded_list;
    table->embedding= ptr;
    embedded_list->push_back(table);
6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164
    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.
      */
      if (table->join_using_fields)
      {
        ptr->join_using_fields= table->join_using_fields;
        table->join_using_fields= NULL;
      }
    }
6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204
  }
  join_list->push_front(ptr);
  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
  DBUG_RETURN(ptr);
}


/*
  Add a table to the current join list

  SYNOPSIS
    add_joined_table()
    table       the table to add

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

  RETURN VALUE
    None
*/

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


/*
  Convert a right join into equivalent left join

  SYNOPSIS
    convert_right_join()
    thd         current thread
6205 6206 6207

  DESCRIPTION
    The function takes the current join list t[0],t[1] ... and
6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230
    effectively converts it into the list t[1],t[0] ...
    Although the outer_join flag for the new nested table contains
    JOIN_TYPE_RIGHT, it will be handled as the inner table of a left join
    operation.

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

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

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

    SELECT * FROM t1 LEFT JOIN t2 ON on_expr1 RIGHT JOIN t3  ON on_expr2 =>
      SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1

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

6231
TABLE_LIST *st_select_lex::convert_right_join()
6232 6233
{
  TABLE_LIST *tab2= join_list->pop();
6234
  TABLE_LIST *tab1= join_list->pop();
6235 6236 6237 6238 6239 6240 6241 6242 6243
  DBUG_ENTER("convert_right_join");

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

  DBUG_RETURN(tab1);
}

6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256
/*
  Set lock for all tables in current select level

  SYNOPSIS:
    set_lock_for_tables()
    lock_type			Lock to set for tables

  NOTE:
    If lock is a write lock, then tables->updating is set 1
    This is to get tables_ok to know that the table is updated by the
    query
*/

6257
void st_select_lex::set_lock_for_tables(thr_lock_type lock_type)
6258 6259 6260 6261 6262 6263
{
  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
6264 6265 6266
  for (TABLE_LIST *tables= (TABLE_LIST*) table_list.first;
       tables;
       tables= tables->next_local)
6267 6268 6269 6270 6271 6272 6273
  {
    tables->lock_type= lock_type;
    tables->updating=  for_update;
  }
  DBUG_VOID_RETURN;
}

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

6275
/*
6276 6277
  Push a new name resolution context for a JOIN ... ON clause to the
  context stack of a query block.
6278 6279

  SYNOPSIS
6280
    push_new_name_resolution_context()
6281
    thd       pointer to current thread
timour@mysql.com's avatar
timour@mysql.com committed
6282
    left_op   left  operand of the JOIN
6283 6284 6285 6286
    right_op  rigth operand of the JOIN

  DESCRIPTION
    Create a new name resolution context for a JOIN ... ON clause,
6287 6288 6289
    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.
6290 6291

  RETURN
6292 6293
    FALSE  if all is OK
    TRUE   if a memory allocation error occured
6294 6295
*/

6296 6297 6298
bool
push_new_name_resolution_context(THD *thd,
                                 TABLE_LIST *left_op, TABLE_LIST *right_op)
6299 6300
{
  Name_resolution_context *on_context;
6301
  if (!(on_context= new (thd->mem_root) Name_resolution_context))
6302
    return TRUE;
6303 6304 6305 6306 6307
  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();
6308
  return thd->lex->push_context(on_context);
6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328
}


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

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

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

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

void add_join_on(TABLE_LIST *b, Item *expr)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6329
{
6330
  if (expr)
6331
  {
6332
    if (!b->on_expr)
6333
      b->on_expr= expr;
6334 6335
    else
    {
6336 6337 6338 6339 6340 6341
      /*
        If called from the parser, this happens if you have both a
        right and left join. If called later, it happens if we add more
        than one condition to the ON clause.
      */
      b->on_expr= new Item_cond_and(b->on_expr,expr);
6342 6343
    }
    b->on_expr->top_level_item();
6344
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6345 6346 6347
}


6348
/*
6349 6350
  Mark that there is a NATURAL JOIN or JOIN ... USING between two
  tables.
6351 6352 6353

  SYNOPSIS
    add_join_natural()
6354 6355 6356 6357
    a			Left join argument
    b			Right join argument
    using_fields        Field names from USING clause
  
6358
  IMPLEMENTATION
6359 6360 6361 6362 6363 6364 6365 6366 6367 6368
    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
6369 6370 6371
    SELECT * FROM t1 NATURAL LEFT JOIN t2
     <=>
    SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382

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

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

  RETURN
    None
6383 6384
*/

6385
void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6386
{
6387 6388
  b->natural_join= a;
  b->join_using_fields= using_fields;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6389 6390
}

6391

6392
/*
6393 6394 6395 6396
  Reload/resets privileges and the different caches.

  SYNOPSIS
    reload_acl_and_cache()
6397
    thd			Thread handler (can be NULL!)
6398 6399 6400 6401 6402
    options             What should be reset/reloaded (tables, privileges,
    slave...)
    tables              Tables to flush (if any)
    write_to_binlog     Depending on 'options', it may be very bad to write the
                        query to the binlog (e.g. FLUSH SLAVE); this is a
6403 6404 6405
                        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.
6406 6407 6408

  RETURN
    0	 ok
6409
    !=0  error.  thd->killed or thd->net.report_error is set
6410 6411
*/

6412 6413
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
6414 6415 6416
{
  bool result=0;
  select_errors=0;				/* Write if more errors */
6417
  bool tmp_write_to_binlog= 1;
6418

6419
  if (thd && thd->in_sub_stmt)
6420 6421 6422 6423 6424
  {
    my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "FLUSH");
    return 1;
  }

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
6425
#ifndef NO_EMBEDDED_ACCESS_CHECKS
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6426 6427
  if (options & REFRESH_GRANT)
  {
6428 6429 6430 6431 6432 6433
    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)))
6434 6435
    {
      thd->thread_stack= (char*) &tmp_thd;
6436
      thd->store_globals();
6437
    }
6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449
    if (thd)
    {
      (void)acl_reload(thd);
      (void)grant_reload(thd);
    }
    if (tmp_thd)
    {
      delete tmp_thd;
      /* Remember that we don't have a THD */
      my_pthread_setspecific_ptr(THR_THD,  0);
      thd= 0;
    }
6450
    reset_mqh((LEX_USER *)NULL, TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6451
  }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
6452
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6453 6454
  if (options & REFRESH_LOG)
  {
6455
    /*
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6456 6457
      Flush the normal query log, the update log, the binary log,
      the slow query log, and the relay log (if it exists).
6458
    */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6459

6460
    /*
monty@mysql.com's avatar
monty@mysql.com committed
6461 6462 6463 6464
      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)
6465 6466
    */
    tmp_write_to_binlog= 0;
6467 6468
    mysql_log.new_file(1);
    mysql_slow_log.new_file(1);
6469
    mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
6470
#ifdef HAVE_REPLICATION
6471
    pthread_mutex_lock(&LOCK_active_mi);
6472
    rotate_relay_log(active_mi);
6473
    pthread_mutex_unlock(&LOCK_active_mi);
6474
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6475 6476
    if (ha_flush_logs())
      result=1;
6477 6478
    if (flush_error_log())
      result=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6479
  }
6480
#ifdef HAVE_QUERY_CACHE
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6481 6482
  if (options & REFRESH_QUERY_CACHE_FREE)
  {
6483
    query_cache.pack();				// FLUSH QUERY CACHE
6484
    options &= ~REFRESH_QUERY_CACHE;    // Don't flush cache, just free memory
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6485 6486 6487
  }
  if (options & (REFRESH_TABLES | REFRESH_QUERY_CACHE))
  {
6488
    query_cache.flush();			// RESET QUERY CACHE
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6489
  }
6490
#endif /*HAVE_QUERY_CACHE*/
6491 6492 6493 6494 6495
  /*
    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
6496
  {
6497
    if ((options & REFRESH_READ_LOCK) && thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6498
    {
6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509
      /*
        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
6510
        {
6511 6512 6513 6514 6515
          if ((*lock_p)->type == TL_WRITE)
          {
            my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
            return 1;
          }
monty@mysql.com's avatar
monty@mysql.com committed
6516
        }
6517
      }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
6518 6519 6520 6521
      /*
	Writing to the binlog could cause deadlocks, as we don't log
	UNLOCK TABLES
      */
6522
      tmp_write_to_binlog= 0;
6523
      if (lock_global_read_lock(thd))
6524
	return 1;                               // Killed
6525 6526
      result=close_cached_tables(thd,(options & REFRESH_FAST) ? 0 : 1,
                                 tables);
6527
      if (make_global_read_lock_block_commit(thd)) // Killed
6528 6529 6530 6531 6532
      {
        /* 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
6533
    }
6534 6535
    else
      result=close_cached_tables(thd,(options & REFRESH_FAST) ? 0 : 1, tables);
6536
    my_dbopt_cleanup();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6537 6538 6539
  }
  if (options & REFRESH_HOSTS)
    hostname_cache_refresh();
monty@mysql.com's avatar
monty@mysql.com committed
6540
  if (thd && (options & REFRESH_STATUS))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6541 6542 6543
    refresh_status();
  if (options & REFRESH_THREADS)
    flush_thread_cache();
6544
#ifdef HAVE_REPLICATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6545
  if (options & REFRESH_MASTER)
6546 6547
  {
    tmp_write_to_binlog= 0;
6548
    if (reset_master(thd))
6549
    {
6550
      result=1;
6551 6552
      thd->fatal_error();                       // Ensure client get error
    }
6553
  }
6554
#endif
6555
#ifdef OPENSSL
6556 6557 6558 6559 6560 6561
   if (options & REFRESH_DES_KEY_FILE)
   {
     if (des_key_file)
       result=load_des_key_file(des_key_file);
   }
#endif
6562
#ifdef HAVE_REPLICATION
6563 6564
 if (options & REFRESH_SLAVE)
 {
6565
   tmp_write_to_binlog= 0;
6566
   pthread_mutex_lock(&LOCK_active_mi);
6567
   if (reset_slave(thd, active_mi))
6568
     result=1;
6569
   pthread_mutex_unlock(&LOCK_active_mi);
6570
 }
6571
#endif
6572
 if (options & REFRESH_USER_RESOURCES)
monty@mysql.com's avatar
monty@mysql.com committed
6573
   reset_mqh((LEX_USER *) NULL);
6574
 *write_to_binlog= tmp_write_to_binlog;
6575
 return result;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6576 6577
}

6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589
/*
  kill on thread

  SYNOPSIS
    kill_one_thread()
    thd			Thread class
    id			Thread id

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

hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
6590
void kill_one_thread(THD *thd, ulong id, bool only_kill_query)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6591 6592 6593
{
  THD *tmp;
  uint error=ER_NO_SUCH_THREAD;
6594 6595
  VOID(pthread_mutex_lock(&LOCK_thread_count)); // For unlink from list
  I_List_iterator<THD> it(threads);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6596 6597 6598 6599
  while ((tmp=it++))
  {
    if (tmp->thread_id == id)
    {
6600 6601
      pthread_mutex_lock(&tmp->LOCK_delete);	// Lock from delete
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6602 6603 6604
    }
  }
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
6605 6606
  if (tmp)
  {
6607 6608
    if ((thd->security_ctx->master_access & SUPER_ACL) ||
	!strcmp(thd->security_ctx->user, tmp->security_ctx->user))
6609
    {
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
6610
      tmp->awake(only_kill_query ? THD::KILL_QUERY : THD::KILL_CONNECTION);
6611 6612 6613 6614 6615 6616 6617
      error=0;
    }
    else
      error=ER_KILL_DENIED_ERROR;
    pthread_mutex_unlock(&tmp->LOCK_delete);
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
6618
  if (!error)
6619
    send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6620
  else
6621
    my_error(error, MYF(0), id);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6622 6623
}

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
6625 6626 6627 6628 6629 6630 6631 6632
/* Clear most status variables */

static void refresh_status(void)
{
  pthread_mutex_lock(&LOCK_status);
  for (struct show_var_st *ptr=status_vars; ptr->name; ptr++)
  {
    if (ptr->type == SHOW_LONG)
6633
      *(ulong*) ptr->value= 0;
6634 6635 6636 6637 6638 6639 6640
    else if (ptr->type == SHOW_LONG_STATUS)
    {
      THD *thd= current_thd;
      /* We must update the global status before cleaning up the thread */
      add_to_status(&global_status_var, &thd->status_var);
      bzero((char*) &thd->status_var, sizeof(thd->status_var));
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6641
  }
timour@mysql.com's avatar
timour@mysql.com committed
6642 6643
  /* Reset the counters of all key caches (default and named). */
  process_key_caches(reset_key_cache_counters);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6644 6645
  pthread_mutex_unlock(&LOCK_status);
}
6646 6647 6648 6649


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

6650 6651
static bool append_file_to_dir(THD *thd, const char **filename_ptr,
			       const char *table_name)
6652
{
6653
  char buff[FN_REFLEN],*ptr, *end;
6654 6655 6656 6657 6658 6659 6660
  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))
  {
6661
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
6662 6663 6664 6665
    return 1;
  }
  /* Fix is using unix filename format on dos */
  strmov(buff,*filename_ptr);
6666
  end=convert_dirname(buff, *filename_ptr, NullS);
6667
  if (!(ptr=thd->alloc((uint) (end-buff)+(uint) strlen(table_name)+1)))
6668 6669
    return 1;					// End of memory
  *filename_ptr=ptr;
6670
  strxmov(ptr,buff,table_name,NullS);
6671 6672
  return 0;
}
6673

6674

6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688
/*
  Check if the select is a simple select (not an union)

  SYNOPSIS
    check_simple_select()

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

bool check_simple_select()
{
  THD *thd= current_thd;
6689 6690
  LEX *lex= thd->lex;
  if (lex->current_select != &lex->select_lex)
6691 6692
  {
    char command[80];
6693 6694
    strmake(command, lex->yylval->symbol.str,
	    min(lex->yylval->symbol.length, sizeof(command)-1));
6695
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
6696 6697 6698 6699
    return 1;
  }
  return 0;
}
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6700

6701

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6702
Comp_creator *comp_eq_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6703
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6704
  return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6705 6706
}

6707

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6708
Comp_creator *comp_ge_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6709
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6710
  return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6711 6712
}

6713

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6714
Comp_creator *comp_gt_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6715
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6716
  return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6717 6718
}

6719

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6720
Comp_creator *comp_le_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6721
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6722
  return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6723 6724
}

6725

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6726
Comp_creator *comp_lt_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6727
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6728
  return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6729 6730
}

6731

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6732
Comp_creator *comp_ne_creator(bool invert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6733
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6734
  return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6735
}
6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755


/*
  Construct ALL/ANY/SOME subquery Item

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

  RETURN VALUE
    constructed Item (or 0 if out of memory)
*/
Item * all_any_subquery_creator(Item *left_expr,
				chooser_compare_func_creator cmp,
				bool all,
				SELECT_LEX *select_lex)
{
serg@serg.mylan's avatar
serg@serg.mylan committed
6756
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
6757
    return new Item_in_subselect(left_expr, select_lex);
serg@serg.mylan's avatar
serg@serg.mylan committed
6758 6759

  if ((cmp == &comp_ne_creator) && all)        // <> ALL <=> NOT IN
6760 6761 6762
    return new Item_func_not(new Item_in_subselect(left_expr, select_lex));

  Item_allany_subselect *it=
6763
    new Item_allany_subselect(left_expr, (*cmp)(all), select_lex, all);
6764
  if (all)
6765
    return it->upper_item= new Item_func_not_all(it);	/* ALL */
6766

6767
  return it->upper_item= new Item_func_nop_all(it);      /* ANY/SOME */
6768
}
6769 6770


6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782
/*
  CREATE INDEX and DROP INDEX are implemented by calling ALTER TABLE with
  the proper arguments.  This isn't very fast but it should work for most
  cases.

  In the future ALTER TABLE will notice that only added indexes
  and create these one by one for the existing table without having to do
  a full rebuild.

  One should normally create all indexes with CREATE TABLE or ALTER TABLE.
*/

6783
bool mysql_create_index(THD *thd, TABLE_LIST *table_list, List<Key> &keys)
6784 6785
{
  List<create_field> fields;
6786 6787
  ALTER_INFO alter_info;
  alter_info.flags= ALTER_ADD_INDEX;
6788 6789 6790 6791 6792
  HA_CREATE_INFO create_info;
  DBUG_ENTER("mysql_create_index");
  bzero((char*) &create_info,sizeof(create_info));
  create_info.db_type=DB_TYPE_DEFAULT;
  create_info.default_table_charset= thd->variables.collation_database;
6793
  DBUG_RETURN(mysql_alter_table(thd,table_list->db,table_list->table_name,
6794
				&create_info, table_list,
6795
				fields, keys, 0, (ORDER*)0,
monty@mysql.com's avatar
monty@mysql.com committed
6796
				DUP_ERROR, 0, &alter_info, 1));
6797 6798 6799
}


6800
bool mysql_drop_index(THD *thd, TABLE_LIST *table_list, ALTER_INFO *alter_info)
6801 6802 6803 6804 6805 6806 6807 6808
{
  List<create_field> fields;
  List<Key> keys;
  HA_CREATE_INFO create_info;
  DBUG_ENTER("mysql_drop_index");
  bzero((char*) &create_info,sizeof(create_info));
  create_info.db_type=DB_TYPE_DEFAULT;
  create_info.default_table_charset= thd->variables.collation_database;
6809 6810
  alter_info->clear();
  alter_info->flags= ALTER_DROP_INDEX;
6811
  DBUG_RETURN(mysql_alter_table(thd,table_list->db,table_list->table_name,
6812
				&create_info, table_list,
6813
				fields, keys, 0, (ORDER*)0,
monty@mysql.com's avatar
monty@mysql.com committed
6814
				DUP_ERROR, 0, alter_info, 1));
6815
}
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
6816 6817


6818 6819 6820 6821 6822
/*
  Multi update query pre-check

  SYNOPSIS
    multi_update_precheck()
6823
    thd		Thread handler
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6824
    tables	Global/local table list (have to be the same)
6825

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6826
  RETURN VALUE
6827 6828
    FALSE OK
    TRUE  Error
6829
*/
6830

6831
bool multi_update_precheck(THD *thd, TABLE_LIST *tables)
6832 6833 6834 6835 6836
{
  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
6837
  DBUG_ENTER("multi_update_precheck");
6838 6839 6840

  if (select_lex->item_list.elements != lex->value_list.elements)
  {
6841
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
6842
    DBUG_RETURN(TRUE);
6843 6844 6845 6846 6847
  }
  /*
    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
6848
  for (table= tables; table; table= table->next_local)
6849
  {
6850 6851 6852
    if (table->derived)
      table->grant.privilege= SELECT_ACL;
    else if ((check_access(thd, UPDATE_ACL, table->db,
6853 6854
                           &table->grant.privilege, 0, 1,
                           test(table->schema_table)) ||
6855 6856
              grant_option &&
              check_grant(thd, UPDATE_ACL, table, 0, 1, 1)) &&
monty@mysql.com's avatar
monty@mysql.com committed
6857
             (check_access(thd, SELECT_ACL, table->db,
6858 6859
                           &table->grant.privilege, 0, 0,
                           test(table->schema_table)) ||
monty@mysql.com's avatar
monty@mysql.com committed
6860
              grant_option && check_grant(thd, SELECT_ACL, table, 0, 1, 0)))
6861
      DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6862

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6863
    table->table_in_first_from_clause= 1;
6864
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6865 6866 6867
  /*
    Is there tables of subqueries?
  */
6868
  if (&lex->select_lex != lex->all_selects_list || lex->time_zone_tables_used)
6869
  {
6870
    DBUG_PRINT("info",("Checking sub query list"));
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6871
    for (table= tables; table; table= table->next_global)
6872
    {
monty@mysql.com's avatar
monty@mysql.com committed
6873 6874 6875
      if (!my_tz_check_n_skip_implicit_tables(&table,
                                              lex->time_zone_tables_used) &&
          !table->table_in_first_from_clause)
6876 6877
      {
	if (check_access(thd, SELECT_ACL, table->db,
6878 6879
			 &table->grant.privilege, 0, 0,
                         test(table->schema_table)) ||
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6880
	    grant_option && check_grant(thd, SELECT_ACL, table, 0, 1, 0))
6881
	  DBUG_RETURN(TRUE);
6882 6883 6884 6885 6886 6887
      }
    }
  }

  if (select_lex->order_list.elements)
    msg= "ORDER BY";
6888
  else if (select_lex->select_limit)
6889 6890 6891 6892
    msg= "LIMIT";
  if (msg)
  {
    my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
6893
    DBUG_RETURN(TRUE);
6894
  }
6895
  DBUG_RETURN(FALSE);
6896 6897 6898 6899 6900 6901 6902
}

/*
  Multi delete query pre-check

  SYNOPSIS
    multi_delete_precheck()
6903
    thd			Thread handler
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6904
    tables		Global/local table list
6905

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6906
  RETURN VALUE
6907 6908
    FALSE OK
    TRUE  error
6909
*/
6910

6911
bool multi_delete_precheck(THD *thd, TABLE_LIST *tables)
6912 6913 6914 6915
{
  SELECT_LEX *select_lex= &thd->lex->select_lex;
  TABLE_LIST *aux_tables=
    (TABLE_LIST *)thd->lex->auxilliary_table_list.first;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6916
  DBUG_ENTER("multi_delete_precheck");
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6917

6918 6919 6920 6921 6922
  /* sql_yacc guarantees that tables and aux_tables are not zero */
  DBUG_ASSERT(aux_tables != 0);
  if (check_db_used(thd, tables) || check_db_used(thd,aux_tables) ||
      check_table_access(thd,SELECT_ACL, tables,0) ||
      check_table_access(thd,DELETE_ACL, aux_tables,0))
6923
    DBUG_RETURN(TRUE);
6924 6925
  if ((thd->options & OPTION_SAFE_UPDATES) && !select_lex->where)
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6926 6927
    my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
               ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
6928
    DBUG_RETURN(TRUE);
6929
  }
6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956
  DBUG_RETURN(FALSE);
}


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

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

  RETURN VALUE
    FALSE - success
    TRUE  - error
*/

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

  lex->table_count= 0;

  for (target_tbl= (TABLE_LIST *)lex->auxilliary_table_list.first;
       target_tbl; target_tbl= target_tbl->next_local)
6957
  {
6958
    lex->table_count++;
6959 6960
    /* All tables in aux_tables must be found in FROM PART */
    TABLE_LIST *walk;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6961
    for (walk= tables; walk; walk= walk->next_local)
6962
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6963 6964 6965
      if (!my_strcasecmp(table_alias_charset,
			 target_tbl->alias, walk->alias) &&
	  !strcmp(walk->db, target_tbl->db))
6966 6967 6968 6969
	break;
    }
    if (!walk)
    {
6970
      my_error(ER_UNKNOWN_TABLE, MYF(0),
6971
               target_tbl->table_name, "MULTI DELETE");
6972
      DBUG_RETURN(TRUE);
6973
    }
serg@serg.mylan's avatar
serg@serg.mylan committed
6974 6975 6976 6977 6978
    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
6979
    walk->updating= target_tbl->updating;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6980
    walk->lock_type= target_tbl->lock_type;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6981
    target_tbl->correspondent_table= walk;	// Remember corresponding table
6982
  }
6983
  DBUG_RETURN(FALSE);
6984 6985 6986
}


bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6987 6988 6989 6990 6991
/*
  simple UPDATE query pre-check

  SYNOPSIS
    update_precheck()
6992 6993
    thd		Thread handler
    tables	Global table list
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6994 6995

  RETURN VALUE
6996 6997
    FALSE OK
    TRUE  Error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6998
*/
6999

7000
bool update_precheck(THD *thd, TABLE_LIST *tables)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7001 7002 7003 7004
{
  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
7005
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
7006
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7007
  }
7008 7009
  DBUG_RETURN(check_db_used(thd, tables) ||
	       check_one_table_access(thd, UPDATE_ACL, tables));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7010 7011 7012 7013 7014 7015 7016 7017
}


/*
  simple DELETE query pre-check

  SYNOPSIS
    delete_precheck()
7018 7019
    thd		Thread handler
    tables	Global table list
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7020 7021

  RETURN VALUE
7022 7023
    FALSE  OK
    TRUE   error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7024
*/
7025

7026
bool delete_precheck(THD *thd, TABLE_LIST *tables)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7027 7028 7029
{
  DBUG_ENTER("delete_precheck");
  if (check_one_table_access(thd, DELETE_ACL, tables))
7030
    DBUG_RETURN(TRUE);
7031
  /* Set privilege for the WHERE clause */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7032
  tables->grant.want_privilege=(SELECT_ACL & ~tables->grant.privilege);
7033
  DBUG_RETURN(FALSE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7034 7035 7036 7037 7038 7039 7040 7041
}


/*
  simple INSERT query pre-check

  SYNOPSIS
    insert_precheck()
7042 7043
    thd		Thread handler
    tables	Global table list
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7044 7045

  RETURN VALUE
7046 7047
    FALSE  OK
    TRUE   error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7048
*/
7049

bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
7050
bool insert_precheck(THD *thd, TABLE_LIST *tables)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7051 7052 7053 7054
{
  LEX *lex= thd->lex;
  DBUG_ENTER("insert_precheck");

7055 7056 7057 7058
  /*
    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
7059 7060 7061
  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
7062 7063

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

7066
  if (lex->update_list.elements != lex->value_list.elements)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7067
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7068
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
7069
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7070
  }
7071
  DBUG_RETURN(FALSE);
7072
}
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7073 7074 7075 7076 7077 7078 7079


/*
  CREATE TABLE query pre-check

  SYNOPSIS
    create_table_precheck()
7080 7081 7082
    thd			Thread handler
    tables		Global table list
    create_table	Table which will be created
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7083 7084

  RETURN VALUE
7085 7086
    FALSE   OK
    TRUE   Error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7087
*/
7088

7089 7090
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
7091 7092
{
  LEX *lex= thd->lex;
7093 7094
  SELECT_LEX *select_lex= &lex->select_lex;
  ulong want_priv;
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
7095
  bool error= TRUE;                                 // Error message is given
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7096
  DBUG_ENTER("create_table_precheck");
7097 7098 7099

  want_priv= ((lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) ?
              CREATE_TMP_ACL : CREATE_ACL);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7100 7101
  lex->create_info.alias= create_table->alias;
  if (check_access(thd, want_priv, create_table->db,
7102 7103
		   &create_table->grant.privilege, 0, 0,
                   test(create_table->schema_table)) ||
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7104 7105 7106
      check_merge_table_access(thd, create_table->db,
			       (TABLE_LIST *)
			       lex->create_info.merge_list.first))
7107 7108 7109 7110 7111 7112 7113 7114 7115
    goto err;
  if (grant_option && want_priv != CREATE_TMP_ACL &&
      check_grant(thd, want_priv, create_table, 0, UINT_MAX, 0))
    goto err;

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

7116 7117
#ifdef NOT_NECESSARY_TO_CHECK_CREATE_TABLE_EXIST_WHEN_PREPARING_STATEMENT
    /* This code throws an ill error for CREATE TABLE t1 SELECT * FROM t1 */
7118
    /*
monty@mysql.com's avatar
monty@mysql.com committed
7119 7120 7121
      Only do the check for PS, becasue we on execute we have to check that
      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).
7122
    */
konstantin@mysql.com's avatar
konstantin@mysql.com committed
7123
    if (thd->stmt_arena->is_stmt_prepare_or_first_sp_execute())
7124
    {
monty@mysql.com's avatar
monty@mysql.com committed
7125 7126 7127 7128
      /*
        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
7129
          find_table_in_global_list(tables, create_table->db,
7130
                                    create_table->table_name))
monty@mysql.com's avatar
monty@mysql.com committed
7131
      {
7132
	error= FALSE;
monty@mysql.com's avatar
monty@mysql.com committed
7133 7134 7135
        goto err;
      }
    }
7136
#endif
7137 7138 7139
    if (tables && check_table_access(thd, SELECT_ACL, tables,0))
      goto err;
  }
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
7140
  error= FALSE;
7141 7142 7143

err:
  DBUG_RETURN(error);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7144
}
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7145 7146 7147 7148 7149 7150 7151


/*
  negate given expression

  SYNOPSIS
    negate_expression()
7152
    thd  thread handler
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180
    expr expression for negation

  RETURN
    negated expression
*/

Item *negate_expression(THD *thd, Item *expr)
{
  Item *negated;
  if (expr->type() == Item::FUNC_ITEM &&
      ((Item_func *) expr)->functype() == Item_func::NOT_FUNC)
  {
    /* it is NOT(NOT( ... )) */
    Item *arg= ((Item_func *) expr)->arguments()[0];
    enum_parsing_place place= thd->lex->current_select->parsing_place;
    if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING)
      return arg;
    /*
      if it is not boolean function then we have to emulate value of
      not(not(a)), it will be a != 0
    */
    return new Item_func_ne(arg, new Item_int((char*) "0", 0, 1));
  }

  if ((negated= expr->neg_transformer(thd)) != 0)
    return negated;
  return new Item_func_not(expr);
}
7181

7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220
/*
  Set the specified definer to the default value, which is the current user in
  the thread. Also check that the current user satisfies to the definers
  requirements.
 
  SYNOPSIS
    get_default_definer()
    thd       [in] thread handler
    definer   [out] definer
 
  RETURN
    error status, that is:
      - FALSE -- on success;
      - TRUE -- on error (current user can not be a definer).
*/
 
bool get_default_definer(THD *thd, LEX_USER *definer)
{
  /* Check that current user has non-empty host name. */

  const Security_context *sctx= thd->security_ctx;

  if (sctx->priv_host[0] == 0)
  {
    my_error(ER_MALFORMED_DEFINER, MYF(0));
    return TRUE;
  }

  /* Fill in. */

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

  return FALSE;
}

7221 7222

/*
7223 7224
  Create definer with the given user and host names. Also check that the user
  and host names satisfy definers requirements.
7225 7226

  SYNOPSIS
7227 7228 7229 7230
    create_definer()
    thd         [in] thread handler
    user_name   [in] user name
    host_name   [in] host name
7231 7232

  RETURN
7233 7234 7235
    On success, return a valid pointer to the created and initialized
    LEX_STRING, which contains definer information.
    On error, return 0.
7236 7237
*/

7238
LEX_USER *create_definer(THD *thd, LEX_STRING *user_name, LEX_STRING *host_name)
7239
{
7240 7241 7242
  LEX_USER *definer;

  /* Check that specified host name is valid. */
7243

7244
  if (host_name->length == 0)
7245
  {
7246 7247
    my_error(ER_MALFORMED_DEFINER, MYF(0));
    return 0;
7248
  }
7249

7250 7251
  /* Create and initialize. */

7252
  if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER))))
7253 7254 7255 7256 7257 7258
    return 0;

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

  return definer;
7259
}