~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2003 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
16
#define MYSQL_LEX 1
17
#include "mysql_priv.h"
18
#include "sql_repl.h"
19
#include "rpl_filter.h"
20
#include "repl_failsafe.h"
21
#include <m_ctype.h>
22
#include <myisam.h>
23
#include <my_dir.h>
24
25
/**
26
  @defgroup Runtime_Environment Runtime Environment
27
  @{
28
*/
29
30
static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables);
31
32
const char *any_db="*any*";	// Special symbol for check_access
33
34
const LEX_STRING command_name[]={
35
  { C_STRING_WITH_LEN("Sleep") },
36
  { C_STRING_WITH_LEN("Quit") },
37
  { C_STRING_WITH_LEN("Init DB") },
38
  { C_STRING_WITH_LEN("Query") },
39
  { C_STRING_WITH_LEN("Field List") },
40
  { C_STRING_WITH_LEN("Create DB") },
41
  { C_STRING_WITH_LEN("Drop DB") },
42
  { C_STRING_WITH_LEN("Refresh") },
43
  { C_STRING_WITH_LEN("Shutdown") },
44
  { C_STRING_WITH_LEN("Statistics") },
45
  { C_STRING_WITH_LEN("Processlist") },
46
  { C_STRING_WITH_LEN("Connect") },
47
  { C_STRING_WITH_LEN("Kill") },
48
  { C_STRING_WITH_LEN("Debug") },
49
  { C_STRING_WITH_LEN("Ping") },
50
  { C_STRING_WITH_LEN("Time") },
51
  { C_STRING_WITH_LEN("Delayed insert") },
52
  { C_STRING_WITH_LEN("Change user") },
53
  { C_STRING_WITH_LEN("Binlog Dump") },
54
  { C_STRING_WITH_LEN("Table Dump") },
55
  { C_STRING_WITH_LEN("Connect Out") },
56
  { C_STRING_WITH_LEN("Register Slave") },
57
  { C_STRING_WITH_LEN("Prepare") },
58
  { C_STRING_WITH_LEN("Execute") },
59
  { C_STRING_WITH_LEN("Long Data") },
60
  { C_STRING_WITH_LEN("Close stmt") },
61
  { C_STRING_WITH_LEN("Reset stmt") },
62
  { C_STRING_WITH_LEN("Set option") },
63
  { C_STRING_WITH_LEN("Fetch") },
64
  { C_STRING_WITH_LEN("Daemon") },
65
  { C_STRING_WITH_LEN("Error") }  // Last command number
66
};
67
68
const char *xa_state_names[]={
69
  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED"
70
};
71
72
static void unlock_locked_tables(THD *thd)
73
{
74
  if (thd->locked_tables)
75
  {
76
    thd->lock=thd->locked_tables;
77
    thd->locked_tables=0;			// Will be automatically closed
78
    close_thread_tables(thd);			// Free tables
79
  }
80
}
81
82
83
bool end_active_trans(THD *thd)
84
{
85
  int error=0;
86
  DBUG_ENTER("end_active_trans");
87
  if (unlikely(thd->in_sub_stmt))
88
  {
89
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
90
    DBUG_RETURN(1);
91
  }
92
  if (thd->transaction.xid_state.xa_state != XA_NOTR)
93
  {
94
    my_error(ER_XAER_RMFAIL, MYF(0),
95
             xa_state_names[thd->transaction.xid_state.xa_state]);
96
    DBUG_RETURN(1);
97
  }
98
  if (thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN |
99
		      OPTION_TABLE_LOCK))
100
  {
101
    DBUG_PRINT("info",("options: 0x%llx", thd->options));
102
    /* Safety if one did "drop table" on locked tables */
103
    if (!thd->locked_tables)
104
      thd->options&= ~OPTION_TABLE_LOCK;
105
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
106
    if (ha_commit(thd))
107
      error=1;
108
  }
109
  thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
110
  thd->transaction.all.modified_non_trans_table= FALSE;
111
  DBUG_RETURN(error);
112
}
113
114
115
bool begin_trans(THD *thd)
116
{
117
  int error=0;
118
  if (unlikely(thd->in_sub_stmt))
119
  {
120
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
121
    return 1;
122
  }
123
  if (thd->locked_tables)
124
  {
125
    thd->lock=thd->locked_tables;
126
    thd->locked_tables=0;			// Will be automatically closed
127
    close_thread_tables(thd);			// Free tables
128
  }
129
  if (end_active_trans(thd))
130
    error= -1;
131
  else
132
  {
133
    LEX *lex= thd->lex;
134
    thd->options|= OPTION_BEGIN;
135
    thd->server_status|= SERVER_STATUS_IN_TRANS;
136
    if (lex->start_transaction_opt & MYSQL_START_TRANS_OPT_WITH_CONS_SNAPSHOT)
137
      error= ha_start_consistent_snapshot(thd);
138
  }
139
  return error;
140
}
141
142
#ifdef HAVE_REPLICATION
143
/**
144
  Returns true if all tables should be ignored.
145
*/
146
inline bool all_tables_not_ok(THD *thd, TABLE_LIST *tables)
147
{
148
  return rpl_filter->is_on() && tables &&
149
         !rpl_filter->tables_ok(thd->db, tables);
150
}
151
#endif
152
153
154
static bool some_non_temp_table_to_be_updated(THD *thd, TABLE_LIST *tables)
155
{
156
  for (TABLE_LIST *table= tables; table; table= table->next_global)
157
  {
158
    DBUG_ASSERT(table->db && table->table_name);
159
    if (table->updating &&
160
        !find_temporary_table(thd, table->db, table->table_name))
161
      return 1;
162
  }
163
  return 0;
164
}
165
166
167
/**
168
  Mark all commands that somehow changes a table.
169
170
  This is used to check number of updates / hour.
171
172
  sql_command is actually set to SQLCOM_END sometimes
173
  so we need the +1 to include it in the array.
174
175
  See COMMAND_FLAG_xxx for different type of commands
176
     2  - query that returns meaningful ROW_COUNT() -
177
          a number of modified rows
178
*/
179
180
uint sql_command_flags[SQLCOM_END+1];
181
182
void init_update_queries(void)
183
{
184
  bzero((uchar*) &sql_command_flags, sizeof(sql_command_flags));
185
186
  sql_command_flags[SQLCOM_CREATE_TABLE]=   CF_CHANGES_DATA;
187
  sql_command_flags[SQLCOM_CREATE_INDEX]=   CF_CHANGES_DATA;
188
  sql_command_flags[SQLCOM_ALTER_TABLE]=    CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
189
  sql_command_flags[SQLCOM_TRUNCATE]=       CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
190
  sql_command_flags[SQLCOM_DROP_TABLE]=     CF_CHANGES_DATA;
191
  sql_command_flags[SQLCOM_LOAD]=           CF_CHANGES_DATA;
192
  sql_command_flags[SQLCOM_CREATE_DB]=      CF_CHANGES_DATA;
193
  sql_command_flags[SQLCOM_DROP_DB]=        CF_CHANGES_DATA;
194
  sql_command_flags[SQLCOM_RENAME_TABLE]=   CF_CHANGES_DATA;
195
  sql_command_flags[SQLCOM_DROP_INDEX]=     CF_CHANGES_DATA;
196
197
  sql_command_flags[SQLCOM_UPDATE]=	    CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
198
  sql_command_flags[SQLCOM_UPDATE_MULTI]=   CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
199
  sql_command_flags[SQLCOM_INSERT]=	    CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
200
  sql_command_flags[SQLCOM_INSERT_SELECT]=  CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
201
  sql_command_flags[SQLCOM_DELETE]=         CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
202
  sql_command_flags[SQLCOM_DELETE_MULTI]=   CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
203
  sql_command_flags[SQLCOM_REPLACE]=        CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
204
  sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
205
206
  sql_command_flags[SQLCOM_SHOW_STATUS]=      CF_STATUS_COMMAND;
207
  sql_command_flags[SQLCOM_SHOW_DATABASES]=   CF_STATUS_COMMAND;
208
  sql_command_flags[SQLCOM_SHOW_OPEN_TABLES]= CF_STATUS_COMMAND;
209
  sql_command_flags[SQLCOM_SHOW_FIELDS]=      CF_STATUS_COMMAND;
210
  sql_command_flags[SQLCOM_SHOW_KEYS]=        CF_STATUS_COMMAND;
211
  sql_command_flags[SQLCOM_SHOW_VARIABLES]=   CF_STATUS_COMMAND;
212
  sql_command_flags[SQLCOM_SHOW_CHARSETS]=    CF_STATUS_COMMAND;
213
  sql_command_flags[SQLCOM_SHOW_COLLATIONS]=  CF_STATUS_COMMAND;
214
  sql_command_flags[SQLCOM_SHOW_NEW_MASTER]= CF_STATUS_COMMAND;
215
  sql_command_flags[SQLCOM_SHOW_BINLOGS]= CF_STATUS_COMMAND;
216
  sql_command_flags[SQLCOM_SHOW_SLAVE_HOSTS]= CF_STATUS_COMMAND;
217
  sql_command_flags[SQLCOM_SHOW_BINLOG_EVENTS]= CF_STATUS_COMMAND;
218
  sql_command_flags[SQLCOM_SHOW_WARNS]= CF_STATUS_COMMAND;
219
  sql_command_flags[SQLCOM_SHOW_ERRORS]= CF_STATUS_COMMAND;
220
  sql_command_flags[SQLCOM_SHOW_ENGINE_STATUS]= CF_STATUS_COMMAND;
221
  sql_command_flags[SQLCOM_SHOW_ENGINE_MUTEX]= CF_STATUS_COMMAND;
222
  sql_command_flags[SQLCOM_SHOW_ENGINE_LOGS]= CF_STATUS_COMMAND;
223
  sql_command_flags[SQLCOM_SHOW_PROCESSLIST]= CF_STATUS_COMMAND;
224
  sql_command_flags[SQLCOM_SHOW_CREATE_DB]=  CF_STATUS_COMMAND;
225
  sql_command_flags[SQLCOM_SHOW_CREATE]=  CF_STATUS_COMMAND;
226
  sql_command_flags[SQLCOM_SHOW_MASTER_STAT]=  CF_STATUS_COMMAND;
227
  sql_command_flags[SQLCOM_SHOW_SLAVE_STAT]=  CF_STATUS_COMMAND;
228
229
   sql_command_flags[SQLCOM_SHOW_TABLES]=       (CF_STATUS_COMMAND |
230
                                               CF_SHOW_TABLE_COMMAND);
231
  sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND |
232
                                                CF_SHOW_TABLE_COMMAND);
233
234
  /*
235
    The following is used to preserver CF_ROW_COUNT during the
236
    a CALL or EXECUTE statement, so the value generated by the
237
    last called (or executed) statement is preserved.
238
    See mysql_execute_command() for how CF_ROW_COUNT is used.
239
  */
240
  sql_command_flags[SQLCOM_EXECUTE]= 		CF_HAS_ROW_COUNT;
241
242
  /*
243
    The following admin table operations are allowed
244
    on log tables.
245
  */
246
  sql_command_flags[SQLCOM_REPAIR]=           CF_WRITE_LOGS_COMMAND;
247
  sql_command_flags[SQLCOM_OPTIMIZE]=         CF_WRITE_LOGS_COMMAND;
248
  sql_command_flags[SQLCOM_ANALYZE]=          CF_WRITE_LOGS_COMMAND;
249
}
250
251
252
bool is_update_query(enum enum_sql_command command)
253
{
254
  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
255
  return (sql_command_flags[command] & CF_CHANGES_DATA) != 0;
256
}
257
258
void execute_init_command(THD *thd, sys_var_str *init_command_var,
259
			  rw_lock_t *var_mutex)
260
{
261
  Vio* save_vio;
262
  ulong save_client_capabilities;
263
264
  thd_proc_info(thd, "Execution of init_command");
265
  /*
266
    We need to lock init_command_var because
267
    during execution of init_command_var query
268
    values of init_command_var can't be changed
269
  */
270
  rw_rdlock(var_mutex);
271
  save_client_capabilities= thd->client_capabilities;
272
  thd->client_capabilities|= CLIENT_MULTI_QUERIES;
273
  /*
274
    We don't need return result of execution to client side.
275
    To forbid this we should set thd->net.vio to 0.
276
  */
277
  save_vio= thd->net.vio;
278
  thd->net.vio= 0;
279
  dispatch_command(COM_QUERY, thd,
280
                   init_command_var->value,
281
                   init_command_var->value_length);
282
  rw_unlock(var_mutex);
283
  thd->client_capabilities= save_client_capabilities;
284
  thd->net.vio= save_vio;
285
}
286
287
288
/**
289
  Execute commands from bootstrap_file.
290
291
  Used when creating the initial grant tables.
292
*/
293
294
pthread_handler_t handle_bootstrap(void *arg)
295
{
296
  THD *thd=(THD*) arg;
297
  FILE *file=bootstrap_file;
298
  char *buff;
299
  const char* found_semicolon= NULL;
300
301
  /* The following must be called before DBUG_ENTER */
302
  thd->thread_stack= (char*) &thd;
303
  if (my_thread_init() || thd->store_globals())
304
  {
305
    close_connection(thd, ER_OUT_OF_RESOURCES, 1);
306
    thd->fatal_error();
307
    goto end;
308
  }
309
  DBUG_ENTER("handle_bootstrap");
310
311
  pthread_detach_this_thread();
312
  thd->thread_stack= (char*) &thd;
313
314
  if (thd->variables.max_join_size == HA_POS_ERROR)
315
    thd->options |= OPTION_BIG_SELECTS;
316
317
  thd_proc_info(thd, 0);
318
  thd->version=refresh_version;
319
  thd->security_ctx->priv_user=
320
    thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME));
321
  thd->security_ctx->priv_host[0]=0;
322
  /*
323
    Make the "client" handle multiple results. This is necessary
324
    to enable stored procedures with SELECTs and Dynamic SQL
325
    in init-file.
326
  */
327
  thd->client_capabilities|= CLIENT_MULTI_RESULTS;
328
329
  buff= (char*) thd->net.buff;
330
  thd->init_for_queries();
331
  while (fgets(buff, thd->net.max_packet, file))
332
  {
333
    /* strlen() can't be deleted because fgets() doesn't return length */
334
    ulong length= (ulong) strlen(buff);
335
    while (buff[length-1] != '\n' && !feof(file))
336
    {
337
      /*
338
        We got only a part of the current string. Will try to increase
339
        net buffer then read the rest of the current string.
340
      */
341
      /* purecov: begin tested */
342
      if (net_realloc(&(thd->net), 2 * thd->net.max_packet))
343
      {
344
        net_end_statement(thd);
345
        bootstrap_error= 1;
346
        break;
347
      }
348
      buff= (char*) thd->net.buff;
349
      fgets(buff + length, thd->net.max_packet - length, file);
350
      length+= (ulong) strlen(buff + length);
351
      /* purecov: end */
352
    }
353
    if (bootstrap_error)
354
      break;                                    /* purecov: inspected */
355
356
    while (length && (my_isspace(thd->charset(), buff[length-1]) ||
357
                      buff[length-1] == ';'))
358
      length--;
359
    buff[length]=0;
360
361
    /* Skip lines starting with delimiter */
362
    if (strncmp(buff, STRING_WITH_LEN("delimiter")) == 0)
363
      continue;
364
365
    thd->query_length=length;
366
    thd->query= (char*) thd->memdup_w_gap(buff, length+1, 
367
                                          thd->db_length+1);
368
    thd->query[length] = '\0';
369
    DBUG_PRINT("query",("%-.4096s",thd->query));
370
371
    /*
372
      We don't need to obtain LOCK_thread_count here because in bootstrap
373
      mode we have only one thread.
374
    */
375
    thd->query_id=next_query_id();
376
    thd->set_time();
377
    mysql_parse(thd, thd->query, length, & found_semicolon);
378
    close_thread_tables(thd);			// Free tables
379
380
    bootstrap_error= thd->is_error();
381
    net_end_statement(thd);
382
383
    if (bootstrap_error)
384
      break;
385
386
    free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
387
    free_root(&thd->transaction.mem_root,MYF(MY_KEEP_PREALLOC));
388
  }
389
390
end:
391
  net_end(&thd->net);
392
  thd->cleanup();
393
  delete thd;
394
395
  (void) pthread_mutex_lock(&LOCK_thread_count);
396
  thread_count--;
397
  (void) pthread_mutex_unlock(&LOCK_thread_count);
398
  (void) pthread_cond_broadcast(&COND_thread_count);
399
  my_thread_end();
400
  pthread_exit(0);
401
  DBUG_RETURN(0);
402
}
403
404
/* This works because items are allocated with sql_alloc() */
405
406
void free_items(Item *item)
407
{
408
  Item *next;
409
  DBUG_ENTER("free_items");
410
  for (; item ; item=next)
411
  {
412
    next=item->next;
413
    item->delete_self();
414
  }
415
  DBUG_VOID_RETURN;
416
}
417
418
/* This works because items are allocated with sql_alloc() */
419
420
void cleanup_items(Item *item)
421
{
422
  DBUG_ENTER("cleanup_items");
423
  for (; item ; item=item->next)
424
    item->cleanup();
425
  DBUG_VOID_RETURN;
426
}
427
428
/**
429
  Ends the current transaction and (maybe) begin the next.
430
431
  @param thd            Current thread
432
  @param completion     Completion type
433
434
  @retval
435
    0   OK
436
*/
437
438
int end_trans(THD *thd, enum enum_mysql_completiontype completion)
439
{
440
  bool do_release= 0;
441
  int res= 0;
442
  DBUG_ENTER("end_trans");
443
444
  if (unlikely(thd->in_sub_stmt))
445
  {
446
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
447
    DBUG_RETURN(1);
448
  }
449
  if (thd->transaction.xid_state.xa_state != XA_NOTR)
450
  {
451
    my_error(ER_XAER_RMFAIL, MYF(0),
452
             xa_state_names[thd->transaction.xid_state.xa_state]);
453
    DBUG_RETURN(1);
454
  }
455
  switch (completion) {
456
  case COMMIT:
457
    /*
458
     We don't use end_active_trans() here to ensure that this works
459
     even if there is a problem with the OPTION_AUTO_COMMIT flag
460
     (Which of course should never happen...)
461
    */
462
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
463
    res= ha_commit(thd);
464
    thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
465
    thd->transaction.all.modified_non_trans_table= FALSE;
466
    break;
467
  case COMMIT_RELEASE:
468
    do_release= 1; /* fall through */
469
  case COMMIT_AND_CHAIN:
470
    res= end_active_trans(thd);
471
    if (!res && completion == COMMIT_AND_CHAIN)
472
      res= begin_trans(thd);
473
    break;
474
  case ROLLBACK_RELEASE:
475
    do_release= 1; /* fall through */
476
  case ROLLBACK:
477
  case ROLLBACK_AND_CHAIN:
478
  {
479
    thd->server_status&= ~SERVER_STATUS_IN_TRANS;
480
    if (ha_rollback(thd))
481
      res= -1;
482
    thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
483
    thd->transaction.all.modified_non_trans_table= FALSE;
484
    if (!res && (completion == ROLLBACK_AND_CHAIN))
485
      res= begin_trans(thd);
486
    break;
487
  }
488
  default:
489
    res= -1;
490
    my_error(ER_UNKNOWN_COM_ERROR, MYF(0));
491
    DBUG_RETURN(-1);
492
  }
493
494
  if (res < 0)
495
    my_error(thd->killed_errno(), MYF(0));
496
  else if ((res == 0) && do_release)
497
    thd->killed= THD::KILL_CONNECTION;
498
499
  DBUG_RETURN(res);
500
}
501
502
503
/**
504
  Read one command from connection and execute it (query or simple command).
505
  This function is called in loop from thread function.
506
507
  For profiling to work, it must never be called recursively.
508
509
  @retval
510
    0  success
511
  @retval
512
    1  request of thread shutdown (see dispatch_command() description)
513
*/
514
515
bool do_command(THD *thd)
516
{
517
  bool return_value;
518
  char *packet= 0;
519
  ulong packet_length;
520
  NET *net= &thd->net;
521
  enum enum_server_command command;
522
  DBUG_ENTER("do_command");
523
524
  /*
525
    indicator of uninitialized lex => normal flow of errors handling
526
    (see my_message_sql)
527
  */
528
  thd->lex->current_select= 0;
529
530
  /*
531
    This thread will do a blocking read from the client which
532
    will be interrupted when the next command is received from
533
    the client, the connection is closed or "net_wait_timeout"
534
    number of seconds has passed
535
  */
536
  my_net_set_read_timeout(net, thd->variables.net_wait_timeout);
537
538
  /*
539
    XXX: this code is here only to clear possible errors of init_connect. 
540
    Consider moving to init_connect() instead.
541
  */
542
  thd->clear_error();				// Clear error message
543
  thd->main_da.reset_diagnostics_area();
544
545
  net_new_transaction(net);
546
547
  packet_length= my_net_read(net);
548
  if (packet_length == packet_error)
549
  {
550
    DBUG_PRINT("info",("Got error %d reading command from socket %s",
551
		       net->error,
552
		       vio_description(net->vio)));
553
554
    /* Check if we can continue without closing the connection */
555
556
    /* The error must be set. */
557
    DBUG_ASSERT(thd->is_error());
558
    net_end_statement(thd);
559
560
    if (net->error != 3)
561
    {
562
      return_value= TRUE;                       // We have to close it.
563
      goto out;
564
    }
565
566
    net->error= 0;
567
    return_value= FALSE;
568
    goto out;
569
  }
570
571
  packet= (char*) net->read_pos;
572
  /*
573
    'packet_length' contains length of data, as it was stored in packet
574
    header. In case of malformed header, my_net_read returns zero.
575
    If packet_length is not zero, my_net_read ensures that the returned
576
    number of bytes was actually read from network.
577
    There is also an extra safety measure in my_net_read:
578
    it sets packet[packet_length]= 0, but only for non-zero packets.
579
  */
580
  if (packet_length == 0)                       /* safety */
581
  {
582
    /* Initialize with COM_SLEEP packet */
583
    packet[0]= (uchar) COM_SLEEP;
584
    packet_length= 1;
585
  }
586
  /* Do not rely on my_net_read, extra safety against programming errors. */
587
  packet[packet_length]= '\0';                  /* safety */
588
589
  command= (enum enum_server_command) (uchar) packet[0];
590
591
  if (command >= COM_END)
592
    command= COM_END;                           // Wrong command
593
594
  DBUG_PRINT("info",("Command on %s = %d (%s)",
595
                     vio_description(net->vio), command,
596
                     command_name[command].str));
597
598
  /* Restore read timeout value */
599
  my_net_set_read_timeout(net, thd->variables.net_read_timeout);
600
601
  DBUG_ASSERT(packet_length);
602
  return_value= dispatch_command(command, thd, packet+1, (uint) (packet_length-1));
603
604
out:
605
  DBUG_RETURN(return_value);
606
}
607
608
/**
609
  Determine if an attempt to update a non-temporary table while the
610
  read-only option was enabled has been made.
611
612
  This is a helper function to mysql_execute_command.
613
614
  @note SQLCOM_MULTI_UPDATE is an exception and dealt with elsewhere.
615
616
  @see mysql_execute_command
617
618
  @returns Status code
619
    @retval TRUE The statement should be denied.
620
    @retval FALSE The statement isn't updating any relevant tables.
621
*/
622
623
static my_bool deny_updates_if_read_only_option(THD *thd,
624
                                                TABLE_LIST *all_tables)
625
{
626
  DBUG_ENTER("deny_updates_if_read_only_option");
627
628
  if (!opt_readonly)
629
    DBUG_RETURN(FALSE);
630
631
  LEX *lex= thd->lex;
632
633
  if (!(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA))
634
    DBUG_RETURN(FALSE);
635
636
  /* Multi update is an exception and is dealt with later. */
637
  if (lex->sql_command == SQLCOM_UPDATE_MULTI)
638
    DBUG_RETURN(FALSE);
639
640
  const my_bool create_temp_tables= 
641
    (lex->sql_command == SQLCOM_CREATE_TABLE) &&
642
    (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE);
643
644
  const my_bool drop_temp_tables= 
645
    (lex->sql_command == SQLCOM_DROP_TABLE) &&
646
    lex->drop_temporary;
647
648
  const my_bool update_real_tables=
649
    some_non_temp_table_to_be_updated(thd, all_tables) &&
650
    !(create_temp_tables || drop_temp_tables);
651
652
653
  const my_bool create_or_drop_databases=
654
    (lex->sql_command == SQLCOM_CREATE_DB) ||
655
    (lex->sql_command == SQLCOM_DROP_DB);
656
657
  if (update_real_tables || create_or_drop_databases)
658
  {
659
      /*
660
        An attempt was made to modify one or more non-temporary tables.
661
      */
662
      DBUG_RETURN(TRUE);
663
  }
664
665
666
  /* Assuming that only temporary tables are modified. */
667
  DBUG_RETURN(FALSE);
668
}
669
670
/**
671
  Perform one connection-level (COM_XXXX) command.
672
673
  @param command         type of command to perform
674
  @param thd             connection handle
675
  @param packet          data for the command, packet is always null-terminated
676
  @param packet_length   length of packet + 1 (to show that data is
677
                         null-terminated) except for COM_SLEEP, where it
678
                         can be zero.
679
680
  @todo
681
    set thd->lex->sql_command to SQLCOM_END here.
682
  @todo
683
    The following has to be changed to an 8 byte integer
684
685
  @retval
686
    0   ok
687
  @retval
688
    1   request of thread shutdown, i. e. if command is
689
        COM_QUIT/COM_SHUTDOWN
690
*/
691
bool dispatch_command(enum enum_server_command command, THD *thd,
692
		      char* packet, uint packet_length)
693
{
694
  NET *net= &thd->net;
695
  bool error= 0;
696
  DBUG_ENTER("dispatch_command");
697
  DBUG_PRINT("info",("packet: '%*.s'; command: %d", packet_length, packet, command));
698
699
  thd->command=command;
700
  /*
701
    Commands which always take a long time are logged into
702
    the slow log only if opt_log_slow_admin_statements is set.
703
  */
704
  thd->enable_slow_log= TRUE;
705
  thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
706
  thd->set_time();
707
  VOID(pthread_mutex_lock(&LOCK_thread_count));
708
  thd->query_id= global_query_id;
709
710
  switch( command ) {
711
  /* Ignore these statements. */
712
  case COM_STATISTICS:
713
  case COM_PING:
714
    break;
715
  /* Only increase id on these statements but don't count them. */
716
  case COM_STMT_PREPARE: 
717
  case COM_STMT_CLOSE:
718
  case COM_STMT_RESET:
719
    next_query_id();
720
    break;
721
  /* Increase id and count all other statements. */
722
  default:
723
    statistic_increment(thd->status_var.questions, &LOCK_status);
724
    next_query_id();
725
  }
726
727
  thread_running++;
728
  /* TODO: set thd->lex->sql_command to SQLCOM_END here */
729
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
730
731
  thd->server_status&=
732
           ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
733
  switch (command) {
734
  case COM_INIT_DB:
735
  {
736
    LEX_STRING tmp;
737
    status_var_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB]);
738
    thd->convert_string(&tmp, system_charset_info,
739
                        packet, packet_length, thd->charset());
740
    if (!mysql_change_db(thd, &tmp, FALSE))
741
    {
742
      general_log_write(thd, command, thd->db, thd->db_length);
743
      my_ok(thd);
744
    }
745
    break;
746
  }
747
  case COM_REGISTER_SLAVE:
748
  {
749
    if (!register_slave(thd, (uchar*)packet, packet_length))
750
      my_ok(thd);
751
    break;
752
  }
753
  case COM_CHANGE_USER:
754
  {
755
    status_var_increment(thd->status_var.com_other);
756
    char *user= (char*) packet, *packet_end= packet + packet_length;
757
    /* Safe because there is always a trailing \0 at the end of the packet */
758
    char *passwd= strend(user)+1;
759
760
    thd->clear_error();                         // if errors from rollback
761
762
    /*
763
      Old clients send null-terminated string ('\0' for empty string) for
764
      password.  New clients send the size (1 byte) + string (not null
765
      terminated, so also '\0' for empty string).
766
767
      Cast *passwd to an unsigned char, so that it doesn't extend the sign
768
      for *passwd > 127 and become 2**32-127 after casting to uint.
769
    */
770
    char db_buff[NAME_LEN+1];                 // buffer to store db in utf8
771
    char *db= passwd;
772
    char *save_db;
773
    /*
774
      If there is no password supplied, the packet must contain '\0',
775
      in any type of handshake (4.1 or pre-4.1).
776
     */
777
    if (passwd >= packet_end)
778
    {
779
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
780
      break;
781
    }
782
    uint passwd_len= (thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
783
                      (uchar)(*passwd++) : strlen(passwd));
784
    uint dummy_errors, save_db_length, db_length;
785
    int res;
786
    Security_context save_security_ctx= *thd->security_ctx;
787
    USER_CONN *save_user_connect;
788
789
    db+= passwd_len + 1;
790
    /*
791
      Database name is always NUL-terminated, so in case of empty database
792
      the packet must contain at least the trailing '\0'.
793
    */
794
    if (db >= packet_end)
795
    {
796
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
797
      break;
798
    }
799
    db_length= strlen(db);
800
801
    char *ptr= db + db_length + 1;
802
    uint cs_number= 0;
803
804
    if (ptr < packet_end)
805
    {
806
      if (ptr + 2 > packet_end)
807
      {
808
        my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
809
        break;
810
      }
811
812
      cs_number= uint2korr(ptr);
813
    }
814
815
    /* Convert database name to utf8 */
816
    db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
817
                             system_charset_info, db, db_length,
818
                             thd->charset(), &dummy_errors)]= 0;
819
    db= db_buff;
820
821
    /* Save user and privileges */
822
    save_db_length= thd->db_length;
823
    save_db= thd->db;
824
    save_user_connect= thd->user_connect;
825
826
    if (!(thd->security_ctx->user= my_strdup(user, MYF(0))))
827
    {
828
      thd->security_ctx->user= save_security_ctx.user;
829
      my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
830
      break;
831
    }
832
833
    /* Clear variables that are allocated */
834
    thd->user_connect= 0;
835
    thd->security_ctx->priv_user= thd->security_ctx->user;
836
    res= check_user(thd, COM_CHANGE_USER, passwd, passwd_len, db, FALSE);
837
838
    if (res)
839
    {
840
      x_free(thd->security_ctx->user);
841
      *thd->security_ctx= save_security_ctx;
842
      thd->user_connect= save_user_connect;
843
      thd->db= save_db;
844
      thd->db_length= save_db_length;
845
    }
846
    else
847
    {
848
      x_free(save_db);
849
      x_free(save_security_ctx.user);
850
851
      if (cs_number)
852
      {
853
        thd_init_client_charset(thd, cs_number);
854
        thd->update_charset();
855
      }
856
    }
857
    break;
858
  }
859
  case COM_STMT_EXECUTE:
860
  case COM_STMT_FETCH:
861
  case COM_STMT_SEND_LONG_DATA:
862
  case COM_STMT_PREPARE:
863
  case COM_STMT_CLOSE:
864
  case COM_STMT_RESET:
865
  {
866
    /* We should toss an error here */
867
    break;
868
  }
869
  case COM_QUERY:
870
  {
871
    if (alloc_query(thd, packet, packet_length))
872
      break;					// fatal error is set
873
    char *packet_end= thd->query + thd->query_length;
874
    /* 'b' stands for 'buffer' parameter', special for 'my_snprintf' */
875
    const char* end_of_stmt= NULL;
876
877
    general_log_write(thd, command, thd->query, thd->query_length);
878
    DBUG_PRINT("query",("%-.4096s",thd->query));
879
880
    if (!(specialflag & SPECIAL_NO_PRIOR))
881
      my_pthread_setprio(pthread_self(),QUERY_PRIOR);
882
883
    mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt);
884
885
    while (!thd->killed && (end_of_stmt != NULL) && ! thd->is_error())
886
    {
887
      char *beginning_of_next_stmt= (char*) end_of_stmt;
888
889
      net_end_statement(thd);
890
      /*
891
        Multiple queries exits, execute them individually
892
      */
893
      close_thread_tables(thd);
894
      ulong length= (ulong)(packet_end - beginning_of_next_stmt);
895
896
      log_slow_statement(thd);
897
898
      /* Remove garbage at start of query */
899
      while (length > 0 && my_isspace(thd->charset(), *beginning_of_next_stmt))
900
      {
901
        beginning_of_next_stmt++;
902
        length--;
903
      }
904
905
      VOID(pthread_mutex_lock(&LOCK_thread_count));
906
      thd->query_length= length;
907
      thd->query= beginning_of_next_stmt;
908
      /*
909
        Count each statement from the client.
910
      */
911
      statistic_increment(thd->status_var.questions, &LOCK_status);
912
      thd->query_id= next_query_id();
913
      thd->set_time(); /* Reset the query start time. */
914
      /* TODO: set thd->lex->sql_command to SQLCOM_END here */
915
      VOID(pthread_mutex_unlock(&LOCK_thread_count));
916
917
      mysql_parse(thd, beginning_of_next_stmt, length, &end_of_stmt);
918
    }
919
920
    if (!(specialflag & SPECIAL_NO_PRIOR))
921
      my_pthread_setprio(pthread_self(),WAIT_PRIOR);
922
    DBUG_PRINT("info",("query ready"));
923
    break;
924
  }
925
  case COM_FIELD_LIST:				// This isn't actually needed
926
  {
927
    char *fields, *packet_end= packet + packet_length, *arg_end;
928
    /* Locked closure of all tables */
929
    TABLE_LIST table_list;
930
    LEX_STRING conv_name;
931
932
    /* used as fields initializator */
933
    lex_start(thd);
934
935
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
936
    bzero((char*) &table_list,sizeof(table_list));
937
    if (thd->copy_db_to(&table_list.db, &table_list.db_length))
938
      break;
939
    /*
940
      We have name + wildcard in packet, separated by endzero
941
    */
942
    arg_end= strend(packet);
943
    thd->convert_string(&conv_name, system_charset_info,
944
			packet, (uint) (arg_end - packet), thd->charset());
945
    table_list.alias= table_list.table_name= conv_name.str;
946
    packet= arg_end + 1;
947
948
    if (!my_strcasecmp(system_charset_info, table_list.db,
949
                       INFORMATION_SCHEMA_NAME.str))
950
    {
951
      ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, table_list.alias);
952
      if (schema_table)
953
        table_list.schema_table= schema_table;
954
    }
955
956
    thd->query_length= (uint) (packet_end - packet); // Don't count end \0
957
    if (!(thd->query=fields= (char*) thd->memdup(packet,thd->query_length+1)))
958
      break;
959
    general_log_print(thd, command, "%s %s", table_list.table_name, fields);
960
    if (lower_case_table_names)
961
      my_casedn_str(files_charset_info, table_list.table_name);
962
963
    /* init structures for VIEW processing */
964
    table_list.select_lex= &(thd->lex->select_lex);
965
966
    lex_start(thd);
967
    mysql_reset_thd_for_next_command(thd);
968
969
    thd->lex->
970
      select_lex.table_list.link_in_list((uchar*) &table_list,
971
                                         (uchar**) &table_list.next_local);
972
    thd->lex->add_to_query_tables(&table_list);
973
974
    /* switch on VIEW optimisation: do not fill temporary tables */
975
    thd->lex->sql_command= SQLCOM_SHOW_FIELDS;
976
    mysqld_list_fields(thd,&table_list,fields);
977
    thd->lex->unit.cleanup();
978
    thd->cleanup_after_query();
979
    break;
980
  }
981
  case COM_QUIT:
982
    /* We don't calculate statistics for this command */
983
    general_log_print(thd, command, NullS);
984
    net->error=0;				// Don't give 'abort' message
985
    thd->main_da.disable_status();              // Don't send anything back
986
    error=TRUE;					// End server
987
    break;
988
  case COM_BINLOG_DUMP:
989
    {
990
      ulong pos;
991
      ushort flags;
992
      uint32 slave_server_id;
993
994
      status_var_increment(thd->status_var.com_other);
995
      thd->enable_slow_log= opt_log_slow_admin_statements;
996
      /* TODO: The following has to be changed to an 8 byte integer */
997
      pos = uint4korr(packet);
998
      flags = uint2korr(packet + 4);
999
      thd->server_id=0; /* avoid suicide */
1000
      if ((slave_server_id= uint4korr(packet+6))) // mysqlbinlog.server_id==0
1001
	kill_zombie_dump_threads(slave_server_id);
1002
      thd->server_id = slave_server_id;
1003
1004
      general_log_print(thd, command, "Log: '%s'  Pos: %ld", packet+10,
1005
                      (long) pos);
1006
      mysql_binlog_send(thd, thd->strdup(packet + 10), (my_off_t) pos, flags);
1007
      unregister_slave(thd,1,1);
1008
      /*  fake COM_QUIT -- if we get here, the thread needs to terminate */
1009
      error = TRUE;
1010
      break;
1011
    }
1012
  case COM_SHUTDOWN:
1013
  {
1014
    status_var_increment(thd->status_var.com_other);
1015
    /*
1016
      If the client is < 4.1.3, it is going to send us no argument; then
1017
      packet_length is 0, packet[0] is the end 0 of the packet. Note that
1018
      SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in
1019
      packet[0].
1020
    */
1021
    enum mysql_enum_shutdown_level level=
1022
      (enum mysql_enum_shutdown_level) (uchar) packet[0];
1023
    if (level == SHUTDOWN_DEFAULT)
1024
      level= SHUTDOWN_WAIT_ALL_BUFFERS; // soon default will be configurable
1025
    else if (level != SHUTDOWN_WAIT_ALL_BUFFERS)
1026
    {
1027
      my_error(ER_NOT_SUPPORTED_YET, MYF(0), "this shutdown level");
1028
      break;
1029
    }
1030
    DBUG_PRINT("quit",("Got shutdown command for level %u", level));
1031
    general_log_print(thd, command, NullS);
1032
    my_eof(thd);
1033
    close_thread_tables(thd);			// Free before kill
1034
    kill_mysql();
1035
    error=TRUE;
1036
    break;
1037
  }
1038
  case COM_STATISTICS:
1039
  {
1040
    STATUS_VAR current_global_status_var;
1041
    ulong uptime;
1042
    uint length;
1043
    ulonglong queries_per_second1000;
1044
    char buff[250];
1045
    uint buff_len= sizeof(buff);
1046
1047
    general_log_print(thd, command, NullS);
1048
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]);
1049
    calc_sum_of_all_status(&current_global_status_var);
1050
    if (!(uptime= (ulong) (thd->start_time - server_start_time)))
1051
      queries_per_second1000= 0;
1052
    else
1053
      queries_per_second1000= thd->query_id * LL(1000) / uptime;
1054
1055
    length= my_snprintf((char*) buff, buff_len - 1,
1056
                        "Uptime: %lu  Threads: %d  Questions: %lu  "
1057
                        "Slow queries: %lu  Opens: %lu  Flush tables: %lu  "
1058
                        "Open tables: %u  Queries per second avg: %u.%u",
1059
                        uptime,
1060
                        (int) thread_count, (ulong) thd->query_id,
1061
                        current_global_status_var.long_query_count,
1062
                        current_global_status_var.opened_tables,
1063
                        refresh_version,
1064
                        cached_open_tables(),
1065
                        (uint) (queries_per_second1000 / 1000),
1066
                        (uint) (queries_per_second1000 % 1000));
1067
    /* Store the buffer in permanent memory */
1068
    my_ok(thd, 0, 0, buff);
1069
    VOID(my_net_write(net, (uchar*) buff, length));
1070
    VOID(net_flush(net));
1071
    thd->main_da.disable_status();
1072
    break;
1073
  }
1074
  case COM_PING:
1075
    status_var_increment(thd->status_var.com_other);
1076
    my_ok(thd);				// Tell client we are alive
1077
    break;
1078
  case COM_PROCESS_INFO:
1079
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]);
1080
    general_log_print(thd, command, NullS);
1081
    mysqld_list_processes(thd, NullS, 0);
1082
    break;
1083
  case COM_PROCESS_KILL:
1084
  {
1085
    status_var_increment(thd->status_var.com_stat[SQLCOM_KILL]);
1086
    ulong id=(ulong) uint4korr(packet);
1087
    sql_kill(thd,id,false);
1088
    break;
1089
  }
1090
  case COM_SET_OPTION:
1091
  {
1092
    status_var_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION]);
1093
    uint opt_command= uint2korr(packet);
1094
1095
    switch (opt_command) {
1096
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON:
1097
      thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
1098
      my_eof(thd);
1099
      break;
1100
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF:
1101
      thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
1102
      my_eof(thd);
1103
      break;
1104
    default:
1105
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1106
      break;
1107
    }
1108
    break;
1109
  }
1110
  case COM_DEBUG:
1111
    status_var_increment(thd->status_var.com_other);
1112
    mysql_print_status();
1113
    general_log_print(thd, command, NullS);
1114
    my_eof(thd);
1115
    break;
1116
  case COM_SLEEP:
1117
  case COM_CONNECT:				// Impossible here
1118
  case COM_TIME:				// Impossible from client
1119
  case COM_END:
1120
  default:
1121
    my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1122
    break;
1123
  }
1124
1125
  /* If commit fails, we should be able to reset the OK status. */
1126
  thd->main_da.can_overwrite_status= TRUE;
1127
  ha_autocommit_or_rollback(thd, thd->is_error());
1128
  thd->main_da.can_overwrite_status= FALSE;
1129
1130
  thd->transaction.stmt.reset();
1131
1132
1133
  /* report error issued during command execution */
1134
  if (thd->killed_errno())
1135
  {
1136
    if (! thd->main_da.is_set())
1137
      thd->send_kill_message();
1138
  }
1139
  if (thd->killed == THD::KILL_QUERY || thd->killed == THD::KILL_BAD_DATA)
1140
  {
1141
    thd->killed= THD::NOT_KILLED;
1142
    thd->mysys_var->abort= 0;
1143
  }
1144
1145
  net_end_statement(thd);
1146
1147
  thd->proc_info= "closing tables";
1148
  /* Free tables */
1149
  close_thread_tables(thd);
1150
1151
  log_slow_statement(thd);
1152
1153
  thd_proc_info(thd, "cleaning up");
1154
  VOID(pthread_mutex_lock(&LOCK_thread_count)); // For process list
1155
  thd_proc_info(thd, 0);
1156
  thd->command=COM_SLEEP;
1157
  thd->query=0;
1158
  thd->query_length=0;
1159
  thread_running--;
1160
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
1161
  thd->packet.shrink(thd->variables.net_buffer_length);	// Reclaim some memory
1162
  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
1163
  DBUG_RETURN(error);
1164
}
1165
1166
1167
void log_slow_statement(THD *thd)
1168
{
1169
  DBUG_ENTER("log_slow_statement");
1170
1171
  /*
1172
    The following should never be true with our current code base,
1173
    but better to keep this here so we don't accidently try to log a
1174
    statement in a trigger or stored function
1175
  */
1176
  if (unlikely(thd->in_sub_stmt))
1177
    DBUG_VOID_RETURN;                           // Don't set time for sub stmt
1178
1179
  /*
1180
    Do not log administrative statements unless the appropriate option is
1181
    set; do not log into slow log if reading from backup.
1182
  */
1183
  if (thd->enable_slow_log && !thd->user_time)
1184
  {
1185
    thd_proc_info(thd, "logging slow query");
1186
    ulonglong end_utime_of_query= thd->current_utime();
1187
1188
    if (((end_utime_of_query - thd->utime_after_lock) >
1189
         thd->variables.long_query_time ||
1190
         ((thd->server_status &
1191
           (SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED)) &&
1192
          opt_log_queries_not_using_indexes &&
1193
           !(sql_command_flags[thd->lex->sql_command] & CF_STATUS_COMMAND))) &&
1194
        thd->examined_row_count >= thd->variables.min_examined_row_limit)
1195
    {
1196
      thd_proc_info(thd, "logging slow query");
1197
      thd->status_var.long_query_count++;
1198
      slow_log_print(thd, thd->query, thd->query_length, end_utime_of_query);
1199
    }
1200
  }
1201
  DBUG_VOID_RETURN;
1202
}
1203
1204
1205
/**
1206
  Create a TABLE_LIST object for an INFORMATION_SCHEMA table.
1207
1208
    This function is used in the parser to convert a SHOW or DESCRIBE
1209
    table_name command to a SELECT from INFORMATION_SCHEMA.
1210
    It prepares a SELECT_LEX and a TABLE_LIST object to represent the
1211
    given command as a SELECT parse tree.
1212
1213
  @param thd              thread handle
1214
  @param lex              current lex
1215
  @param table_ident      table alias if it's used
1216
  @param schema_table_idx the type of the INFORMATION_SCHEMA table to be
1217
                          created
1218
1219
  @note
1220
    Due to the way this function works with memory and LEX it cannot
1221
    be used outside the parser (parse tree transformations outside
1222
    the parser break PS and SP).
1223
1224
  @retval
1225
    0                 success
1226
  @retval
1227
    1                 out of memory or SHOW commands are not allowed
1228
                      in this version of the server.
1229
*/
1230
1231
int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident,
1232
                         enum enum_schema_tables schema_table_idx)
1233
{
1234
  SELECT_LEX *schema_select_lex= NULL;
1235
  DBUG_ENTER("prepare_schema_table");
1236
1237
  switch (schema_table_idx) {
1238
  case SCH_SCHEMATA:
1239
    break;
1240
  case SCH_TABLE_NAMES:
1241
  case SCH_TABLES:
1242
    {
1243
      LEX_STRING db;
1244
      size_t dummy;
1245
      if (lex->select_lex.db == NULL &&
1246
          lex->copy_db_to(&lex->select_lex.db, &dummy))
1247
      {
1248
        DBUG_RETURN(1);
1249
      }
1250
      schema_select_lex= new SELECT_LEX();
1251
      db.str= schema_select_lex->db= lex->select_lex.db;
1252
      schema_select_lex->table_list.first= NULL;
1253
      db.length= strlen(db.str);
1254
1255
      if (check_db_name(&db))
1256
      {
1257
        my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
1258
        DBUG_RETURN(1);
1259
      }
1260
      break;
1261
    }
1262
  case SCH_COLUMNS:
1263
  case SCH_STATISTICS:
1264
  {
1265
    DBUG_ASSERT(table_ident);
1266
    TABLE_LIST **query_tables_last= lex->query_tables_last;
1267
    schema_select_lex= new SELECT_LEX();
1268
    /* 'parent_lex' is used in init_query() so it must be before it. */
1269
    schema_select_lex->parent_lex= lex;
1270
    schema_select_lex->init_query();
1271
    if (!schema_select_lex->add_table_to_list(thd, table_ident, 0, 0, TL_READ))
1272
      DBUG_RETURN(1);
1273
    lex->query_tables_last= query_tables_last;
1274
    break;
1275
  }
1276
  case SCH_OPEN_TABLES:
1277
  case SCH_VARIABLES:
1278
  case SCH_STATUS:
1279
  case SCH_CHARSETS:
1280
  case SCH_COLLATIONS:
1281
  case SCH_COLLATION_CHARACTER_SET_APPLICABILITY:
1282
  case SCH_TABLE_CONSTRAINTS:
1283
  case SCH_KEY_COLUMN_USAGE:
1284
  default:
1285
    break;
1286
  }
1287
  
1288
  SELECT_LEX *select_lex= lex->current_select;
1289
  assert(select_lex);
1290
  if (make_schema_select(thd, select_lex, schema_table_idx))
1291
  {
1292
    DBUG_RETURN(1);
1293
  }
1294
  TABLE_LIST *table_list= (TABLE_LIST*) select_lex->table_list.first;
1295
  assert(table_list);
1296
  table_list->schema_select_lex= schema_select_lex;
1297
  table_list->schema_table_reformed= 1;
1298
  DBUG_RETURN(0);
1299
}
1300
1301
1302
/**
1303
  Read query from packet and store in thd->query.
1304
  Used in COM_QUERY and COM_STMT_PREPARE.
1305
1306
    Sets the following THD variables:
1307
  - query
1308
  - query_length
1309
1310
  @retval
1311
    FALSE ok
1312
  @retval
1313
    TRUE  error;  In this case thd->fatal_error is set
1314
*/
1315
1316
bool alloc_query(THD *thd, const char *packet, uint packet_length)
1317
{
1318
  /* Remove garbage at start and end of query */
1319
  while (packet_length > 0 && my_isspace(thd->charset(), packet[0]))
1320
  {
1321
    packet++;
1322
    packet_length--;
1323
  }
1324
  const char *pos= packet + packet_length;     // Point at end null
1325
  while (packet_length > 0 &&
1326
	 (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1])))
1327
  {
1328
    pos--;
1329
    packet_length--;
1330
  }
1331
  /* We must allocate some extra memory for query cache */
1332
  thd->query_length= 0;                        // Extra safety: Avoid races
1333
  if (!(thd->query= (char*) thd->memdup_w_gap((uchar*) (packet),
1334
					      packet_length,
1335
					      thd->db_length+ 1)))
1336
    return TRUE;
1337
  thd->query[packet_length]=0;
1338
  thd->query_length= packet_length;
1339
1340
  /* Reclaim some memory */
1341
  thd->packet.shrink(thd->variables.net_buffer_length);
1342
  thd->convert_buffer.shrink(thd->variables.net_buffer_length);
1343
1344
  return FALSE;
1345
}
1346
1347
static void reset_one_shot_variables(THD *thd) 
1348
{
1349
  thd->variables.character_set_client=
1350
    global_system_variables.character_set_client;
1351
  thd->variables.collation_connection=
1352
    global_system_variables.collation_connection;
1353
  thd->variables.collation_database=
1354
    global_system_variables.collation_database;
1355
  thd->variables.collation_server=
1356
    global_system_variables.collation_server;
1357
  thd->update_charset();
1358
  thd->variables.time_zone=
1359
    global_system_variables.time_zone;
1360
  thd->variables.lc_time_names= &my_locale_en_US;
1361
  thd->one_shot_set= 0;
1362
}
1363
1364
1365
/**
1366
  Execute command saved in thd and lex->sql_command.
1367
1368
    Before every operation that can request a write lock for a table
1369
    wait if a global read lock exists. However do not wait if this
1370
    thread has locked tables already. No new locks can be requested
1371
    until the other locks are released. The thread that requests the
1372
    global read lock waits for write locked tables to become unlocked.
1373
1374
    Note that wait_if_global_read_lock() sets a protection against a new
1375
    global read lock when it succeeds. This needs to be released by
1376
    start_waiting_global_read_lock() after the operation.
1377
1378
  @param thd                       Thread handle
1379
1380
  @todo
1381
    - Invalidate the table in the query cache if something changed
1382
    after unlocking when changes become visible.
1383
    TODO: this is workaround. right way will be move invalidating in
1384
    the unlock procedure.
1385
    - TODO: use check_change_password()
1386
    - JOIN is not supported yet. TODO
1387
    - SUSPEND and FOR MIGRATE are not supported yet. TODO
1388
1389
  @retval
1390
    FALSE       OK
1391
  @retval
1392
    TRUE        Error
1393
*/
1394
1395
int
1396
mysql_execute_command(THD *thd)
1397
{
1398
  int res= FALSE;
1399
  bool need_start_waiting= FALSE; // have protection against global read lock
1400
  int  up_result= 0;
1401
  LEX  *lex= thd->lex;
1402
  /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
1403
  SELECT_LEX *select_lex= &lex->select_lex;
1404
  /* first table of first SELECT_LEX */
1405
  TABLE_LIST *first_table= (TABLE_LIST*) select_lex->table_list.first;
1406
  /* list of all tables in query */
1407
  TABLE_LIST *all_tables;
1408
  /* most outer SELECT_LEX_UNIT of query */
1409
  SELECT_LEX_UNIT *unit= &lex->unit;
1410
  /* Saved variable value */
1411
  DBUG_ENTER("mysql_execute_command");
1412
1413
  /*
1414
    In many cases first table of main SELECT_LEX have special meaning =>
1415
    check that it is first table in global list and relink it first in 
1416
    queries_tables list if it is necessary (we need such relinking only
1417
    for queries with subqueries in select list, in this case tables of
1418
    subqueries will go to global list first)
1419
1420
    all_tables will differ from first_table only if most upper SELECT_LEX
1421
    do not contain tables.
1422
1423
    Because of above in place where should be at least one table in most
1424
    outer SELECT_LEX we have following check:
1425
    DBUG_ASSERT(first_table == all_tables);
1426
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
1427
  */
1428
  lex->first_lists_tables_same();
1429
  /* should be assigned after making first tables same */
1430
  all_tables= lex->query_tables;
1431
  /* set context for commands which do not use setup_tables */
1432
  select_lex->
1433
    context.resolve_in_table_list_only((TABLE_LIST*)select_lex->
1434
                                       table_list.first);
1435
1436
  /*
1437
    Reset warning count for each query that uses tables
1438
    A better approach would be to reset this for any commands
1439
    that is not a SHOW command or a select that only access local
1440
    variables, but for now this is probably good enough.
1441
    Don't reset warnings when executing a stored routine.
1442
  */
1443
  if (all_tables || !lex->is_single_level_stmt())
1444
    mysql_reset_errors(thd, 0);
1445
1446
#ifdef HAVE_REPLICATION
1447
  if (unlikely(thd->slave_thread))
1448
  {
1449
    /*
1450
      Check if statment should be skipped because of slave filtering
1451
      rules
1452
1453
      Exceptions are:
1454
      - UPDATE MULTI: For this statement, we want to check the filtering
1455
        rules later in the code
1456
      - SET: we always execute it (Not that many SET commands exists in
1457
        the binary log anyway -- only 4.1 masters write SET statements,
1458
	in 5.0 there are no SET statements in the binary log)
1459
      - DROP TEMPORARY TABLE IF EXISTS: we always execute it (otherwise we
1460
        have stale files on slave caused by exclusion of one tmp table).
1461
    */
1462
    if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) &&
1463
	!(lex->sql_command == SQLCOM_SET_OPTION) &&
1464
	!(lex->sql_command == SQLCOM_DROP_TABLE &&
1465
          lex->drop_temporary && lex->drop_if_exists) &&
1466
        all_tables_not_ok(thd, all_tables))
1467
    {
1468
      /* we warn the slave SQL thread */
1469
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
1470
      if (thd->one_shot_set)
1471
      {
1472
        /*
1473
          It's ok to check thd->one_shot_set here:
1474
1475
          The charsets in a MySQL 5.0 slave can change by both a binlogged
1476
          SET ONE_SHOT statement and the event-internal charset setting, 
1477
          and these two ways to change charsets do not seems to work
1478
          together.
1479
1480
          At least there seems to be problems in the rli cache for
1481
          charsets if we are using ONE_SHOT.  Note that this is normally no
1482
          problem because either the >= 5.0 slave reads a 4.1 binlog (with
1483
          ONE_SHOT) *or* or 5.0 binlog (without ONE_SHOT) but never both."
1484
        */
1485
        reset_one_shot_variables(thd);
1486
      }
1487
      DBUG_RETURN(0);
1488
    }
1489
  }
1490
  else
1491
  {
1492
#endif /* HAVE_REPLICATION */
1493
    /*
1494
      When option readonly is set deny operations which change non-temporary
1495
      tables. Except for the replication thread and the 'super' users.
1496
    */
1497
    if (deny_updates_if_read_only_option(thd, all_tables))
1498
    {
1499
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
1500
      DBUG_RETURN(-1);
1501
    }
1502
#ifdef HAVE_REPLICATION
1503
  } /* endif unlikely slave */
1504
#endif
1505
  status_var_increment(thd->status_var.com_stat[lex->sql_command]);
1506
1507
  DBUG_ASSERT(thd->transaction.stmt.modified_non_trans_table == FALSE);
1508
  
1509
  switch (lex->sql_command) {
1510
  case SQLCOM_SHOW_STATUS:
1511
  {
1512
    system_status_var old_status_var= thd->status_var;
1513
    thd->initial_status_var= &old_status_var;
1514
    res= execute_sqlcom_select(thd, all_tables);
1515
    /* Don't log SHOW STATUS commands to slow query log */
1516
    thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED |
1517
                           SERVER_QUERY_NO_GOOD_INDEX_USED);
1518
    /*
1519
      restore status variables, as we don't want 'show status' to cause
1520
      changes
1521
    */
1522
    pthread_mutex_lock(&LOCK_status);
1523
    add_diff_to_status(&global_status_var, &thd->status_var,
1524
                       &old_status_var);
1525
    thd->status_var= old_status_var;
1526
    pthread_mutex_unlock(&LOCK_status);
1527
    break;
1528
  }
1529
  case SQLCOM_SHOW_DATABASES:
1530
  case SQLCOM_SHOW_TABLES:
1531
  case SQLCOM_SHOW_TABLE_STATUS:
1532
  case SQLCOM_SHOW_OPEN_TABLES:
1533
  case SQLCOM_SHOW_FIELDS:
1534
  case SQLCOM_SHOW_KEYS:
1535
  case SQLCOM_SHOW_VARIABLES:
1536
  case SQLCOM_SHOW_CHARSETS:
1537
  case SQLCOM_SHOW_COLLATIONS:
1538
  case SQLCOM_SELECT:
1539
  {
1540
    thd->status_var.last_query_cost= 0.0;
1541
    res= execute_sqlcom_select(thd, all_tables);
1542
    break;
1543
  }
1544
  case SQLCOM_PREPARE:
1545
  {
1546
    break;
1547
  }
1548
  case SQLCOM_EXECUTE:
1549
  {
1550
    break;
1551
  }
1552
  case SQLCOM_DEALLOCATE_PREPARE:
1553
  {
1554
    break;
1555
  }
1556
  case SQLCOM_EMPTY_QUERY:
1557
    my_ok(thd);
1558
    break;
1559
1560
  case SQLCOM_PURGE:
1561
  {
1562
    res = purge_master_logs(thd, lex->to_log);
1563
    break;
1564
  }
1565
  case SQLCOM_PURGE_BEFORE:
1566
  {
1567
    Item *it;
1568
1569
    /* PURGE MASTER LOGS BEFORE 'data' */
1570
    it= (Item *)lex->value_list.head();
1571
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) ||
1572
        it->check_cols(1))
1573
    {
1574
      my_error(ER_WRONG_ARGUMENTS, MYF(0), "PURGE LOGS BEFORE");
1575
      goto error;
1576
    }
1577
    it= new Item_func_unix_timestamp(it);
1578
    /*
1579
      it is OK only emulate fix_fieds, because we need only
1580
      value of constant
1581
    */
1582
    it->quick_fix_field();
1583
    res = purge_master_logs_before_date(thd, (ulong)it->val_int());
1584
    break;
1585
  }
1586
  case SQLCOM_SHOW_WARNS:
1587
  {
1588
    res= mysqld_show_warnings(thd, (ulong)
1589
			      ((1L << (uint) MYSQL_ERROR::WARN_LEVEL_NOTE) |
1590
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_WARN) |
1591
			       (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR)
1592
			       ));
1593
    break;
1594
  }
1595
  case SQLCOM_SHOW_ERRORS:
1596
  {
1597
    res= mysqld_show_warnings(thd, (ulong)
1598
			      (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR));
1599
    break;
1600
  }
1601
  case SQLCOM_SHOW_NEW_MASTER:
1602
  {
1603
    /* This query don't work now. See comment in repl_failsafe.cc */
1604
#ifndef WORKING_NEW_MASTER
1605
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "SHOW NEW MASTER");
1606
    goto error;
1607
#else
1608
    res = show_new_master(thd);
1609
    break;
1610
#endif
1611
  }
1612
1613
#ifdef HAVE_REPLICATION
1614
  case SQLCOM_SHOW_SLAVE_HOSTS:
1615
  {
1616
    res = show_slave_hosts(thd);
1617
    break;
1618
  }
1619
  case SQLCOM_SHOW_BINLOG_EVENTS:
1620
  {
1621
    res = mysql_show_binlog_events(thd);
1622
    break;
1623
  }
1624
#endif
1625
1626
  case SQLCOM_ASSIGN_TO_KEYCACHE:
1627
  {
1628
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
1629
    res= mysql_assign_to_keycache(thd, first_table, &lex->ident);
1630
    break;
1631
  }
1632
  case SQLCOM_PRELOAD_KEYS:
1633
  {
1634
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
1635
    res = mysql_preload_keys(thd, first_table);
1636
    break;
1637
  }
1638
#ifdef HAVE_REPLICATION
1639
  case SQLCOM_CHANGE_MASTER:
1640
  {
1641
    pthread_mutex_lock(&LOCK_active_mi);
1642
    res = change_master(thd,active_mi);
1643
    pthread_mutex_unlock(&LOCK_active_mi);
1644
    break;
1645
  }
1646
  case SQLCOM_SHOW_SLAVE_STAT:
1647
  {
1648
    pthread_mutex_lock(&LOCK_active_mi);
1649
    if (active_mi != NULL)
1650
    {
1651
      res = show_master_info(thd, active_mi);
1652
    }
1653
    else
1654
    {
1655
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0,
1656
                   "the master info structure does not exist");
1657
      my_ok(thd);
1658
    }
1659
    pthread_mutex_unlock(&LOCK_active_mi);
1660
    break;
1661
  }
1662
  case SQLCOM_SHOW_MASTER_STAT:
1663
  {
1664
    res = show_binlog_info(thd);
1665
    break;
1666
  }
1667
1668
#endif /* HAVE_REPLICATION */
1669
  case SQLCOM_SHOW_ENGINE_STATUS:
1670
    {
1671
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS);
1672
      break;
1673
    }
1674
  case SQLCOM_SHOW_ENGINE_MUTEX:
1675
    {
1676
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX);
1677
      break;
1678
    }
1679
  case SQLCOM_CREATE_TABLE:
1680
  {
1681
    /* If CREATE TABLE of non-temporary table, do implicit commit */
1682
    if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
1683
    {
1684
      if (end_active_trans(thd))
1685
      {
1686
	res= -1;
1687
	break;
1688
      }
1689
    }
1690
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
1691
    bool link_to_local;
1692
    // Skip first table, which is the table we are creating
1693
    TABLE_LIST *create_table= lex->unlink_first_table(&link_to_local);
1694
    TABLE_LIST *select_tables= lex->query_tables;
1695
    /*
1696
      Code below (especially in mysql_create_table() and select_create
1697
      methods) may modify HA_CREATE_INFO structure in LEX, so we have to
1698
      use a copy of this structure to make execution prepared statement-
1699
      safe. A shallow copy is enough as this code won't modify any memory
1700
      referenced from this structure.
1701
    */
1702
    HA_CREATE_INFO create_info(lex->create_info);
1703
    /*
1704
      We need to copy alter_info for the same reasons of re-execution
1705
      safety, only in case of Alter_info we have to do (almost) a deep
1706
      copy.
1707
    */
1708
    Alter_info alter_info(lex->alter_info, thd->mem_root);
1709
1710
    if (thd->is_fatal_error)
1711
    {
1712
      /* If out of memory when creating a copy of alter_info. */
1713
      res= 1;
1714
      goto end_with_restore_list;
1715
    }
1716
1717
    if ((res= create_table_precheck(thd, select_tables, create_table)))
1718
      goto end_with_restore_list;
1719
1720
    /* Might have been updated in create_table_precheck */
1721
    create_info.alias= create_table->alias;
1722
1723
#ifdef HAVE_READLINK
1724
    /* Fix names if symlinked tables */
1725
    if (append_file_to_dir(thd, &create_info.data_file_name,
1726
			   create_table->table_name) ||
1727
	append_file_to_dir(thd, &create_info.index_file_name,
1728
			   create_table->table_name))
1729
      goto end_with_restore_list;
1730
#endif
1731
    /*
1732
      If we are using SET CHARSET without DEFAULT, add an implicit
1733
      DEFAULT to not confuse old users. (This may change).
1734
    */
1735
    if ((create_info.used_fields &
1736
	 (HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) ==
1737
	HA_CREATE_USED_CHARSET)
1738
    {
1739
      create_info.used_fields&= ~HA_CREATE_USED_CHARSET;
1740
      create_info.used_fields|= HA_CREATE_USED_DEFAULT_CHARSET;
1741
      create_info.default_table_charset= create_info.table_charset;
1742
      create_info.table_charset= 0;
1743
    }
1744
    /*
1745
      The create-select command will open and read-lock the select table
1746
      and then create, open and write-lock the new table. If a global
1747
      read lock steps in, we get a deadlock. The write lock waits for
1748
      the global read lock, while the global read lock waits for the
1749
      select table to be closed. So we wait until the global readlock is
1750
      gone before starting both steps. Note that
1751
      wait_if_global_read_lock() sets a protection against a new global
1752
      read lock when it succeeds. This needs to be released by
1753
      start_waiting_global_read_lock(). We protect the normal CREATE
1754
      TABLE in the same way. That way we avoid that a new table is
1755
      created during a gobal read lock.
1756
    */
1757
    if (!thd->locked_tables &&
1758
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
1759
    {
1760
      res= 1;
1761
      goto end_with_restore_list;
1762
    }
1763
    if (select_lex->item_list.elements)		// With select
1764
    {
1765
      select_result *result;
1766
1767
      select_lex->options|= SELECT_NO_UNLOCK;
1768
      unit->set_limit(select_lex);
1769
1770
      /*
1771
        Disable non-empty MERGE tables with CREATE...SELECT. Too
1772
        complicated. See Bug #26379. Empty MERGE tables are read-only
1773
        and don't allow CREATE...SELECT anyway.
1774
      */
1775
      if (create_info.used_fields & HA_CREATE_USED_UNION)
1776
      {
1777
        my_error(ER_WRONG_OBJECT, MYF(0), create_table->db,
1778
                 create_table->table_name, "BASE TABLE");
1779
        res= 1;
1780
        goto end_with_restore_list;
1781
      }
1782
1783
      if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
1784
      {
1785
        lex->link_first_table_back(create_table, link_to_local);
1786
        create_table->create= TRUE;
1787
      }
1788
1789
      if (!(res= open_and_lock_tables(thd, lex->query_tables)))
1790
      {
1791
        /*
1792
          Is table which we are changing used somewhere in other parts
1793
          of query
1794
        */
1795
        if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
1796
        {
1797
          TABLE_LIST *duplicate;
1798
          create_table= lex->unlink_first_table(&link_to_local);
1799
          if ((duplicate= unique_table(thd, create_table, select_tables, 0)))
1800
          {
1801
            update_non_unique_table_error(create_table, "CREATE", duplicate);
1802
            res= 1;
1803
            goto end_with_restore_list;
1804
          }
1805
        }
1806
        /* If we create merge table, we have to test tables in merge, too */
1807
        if (create_info.used_fields & HA_CREATE_USED_UNION)
1808
        {
1809
          TABLE_LIST *tab;
1810
          for (tab= (TABLE_LIST*) create_info.merge_list.first;
1811
               tab;
1812
               tab= tab->next_local)
1813
          {
1814
            TABLE_LIST *duplicate;
1815
            if ((duplicate= unique_table(thd, tab, select_tables, 0)))
1816
            {
1817
              update_non_unique_table_error(tab, "CREATE", duplicate);
1818
              res= 1;
1819
              goto end_with_restore_list;
1820
            }
1821
          }
1822
        }
1823
1824
        /*
1825
          select_create is currently not re-execution friendly and
1826
          needs to be created for every execution of a PS/SP.
1827
        */
1828
        if ((result= new select_create(create_table,
1829
                                       &create_info,
1830
                                       &alter_info,
1831
                                       select_lex->item_list,
1832
                                       lex->duplicates,
1833
                                       lex->ignore,
1834
                                       select_tables)))
1835
        {
1836
          /*
1837
            CREATE from SELECT give its SELECT_LEX for SELECT,
1838
            and item_list belong to SELECT
1839
          */
1840
          res= handle_select(thd, lex, result, 0);
1841
          delete result;
1842
        }
1843
      }
1844
      else if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
1845
        create_table= lex->unlink_first_table(&link_to_local);
1846
1847
    }
1848
    else
1849
    {
1850
      /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
1851
      if (create_info.options & HA_LEX_CREATE_TMP_TABLE)
1852
        thd->options|= OPTION_KEEP_LOG;
1853
      /* regular create */
1854
      if (create_info.options & HA_LEX_CREATE_TABLE_LIKE)
1855
        res= mysql_create_like_table(thd, create_table, select_tables,
1856
                                     &create_info);
1857
      else
1858
      {
1859
        res= mysql_create_table(thd, create_table->db,
1860
                                create_table->table_name, &create_info,
1861
                                &alter_info, 0, 0);
1862
      }
1863
      if (!res)
1864
	my_ok(thd);
1865
    }
1866
1867
    /* put tables back for PS rexecuting */
1868
end_with_restore_list:
1869
    lex->link_first_table_back(create_table, link_to_local);
1870
    break;
1871
  }
1872
  case SQLCOM_CREATE_INDEX:
1873
    /* Fall through */
1874
  case SQLCOM_DROP_INDEX:
1875
  /*
1876
    CREATE INDEX and DROP INDEX are implemented by calling ALTER
1877
    TABLE with proper arguments.
1878
1879
    In the future ALTER TABLE will notice that the request is to
1880
    only add indexes and create these one by one for the existing
1881
    table without having to do a full rebuild.
1882
  */
1883
  {
1884
    /* Prepare stack copies to be re-execution safe */
1885
    HA_CREATE_INFO create_info;
1886
    Alter_info alter_info(lex->alter_info, thd->mem_root);
1887
1888
    if (thd->is_fatal_error) /* out of memory creating a copy of alter_info */
1889
      goto error;
1890
1891
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
1892
    if (end_active_trans(thd))
1893
      goto error;
1894
    /*
1895
      Currently CREATE INDEX or DROP INDEX cause a full table rebuild
1896
      and thus classify as slow administrative statements just like
1897
      ALTER TABLE.
1898
    */
1899
    thd->enable_slow_log= opt_log_slow_admin_statements;
1900
1901
    bzero((char*) &create_info, sizeof(create_info));
1902
    create_info.db_type= 0;
1903
    create_info.row_type= ROW_TYPE_NOT_USED;
1904
    create_info.default_table_charset= thd->variables.collation_database;
1905
1906
    res= mysql_alter_table(thd, first_table->db, first_table->table_name,
1907
                           &create_info, first_table, &alter_info,
1908
                           0, (ORDER*) 0, 0);
1909
    break;
1910
  }
1911
#ifdef HAVE_REPLICATION
1912
  case SQLCOM_SLAVE_START:
1913
  {
1914
    pthread_mutex_lock(&LOCK_active_mi);
1915
    start_slave(thd,active_mi,1 /* net report*/);
1916
    pthread_mutex_unlock(&LOCK_active_mi);
1917
    break;
1918
  }
1919
  case SQLCOM_SLAVE_STOP:
1920
  /*
1921
    If the client thread has locked tables, a deadlock is possible.
1922
    Assume that
1923
    - the client thread does LOCK TABLE t READ.
1924
    - then the master updates t.
1925
    - then the SQL slave thread wants to update t,
1926
      so it waits for the client thread because t is locked by it.
1927
    - then the client thread does SLAVE STOP.
1928
      SLAVE STOP waits for the SQL slave thread to terminate its
1929
      update t, which waits for the client thread because t is locked by it.
1930
    To prevent that, refuse SLAVE STOP if the
1931
    client thread has locked tables
1932
  */
1933
  if (thd->locked_tables || thd->active_transaction() || thd->global_read_lock)
1934
  {
1935
    my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
1936
               ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
1937
    goto error;
1938
  }
1939
  {
1940
    pthread_mutex_lock(&LOCK_active_mi);
1941
    stop_slave(thd,active_mi,1/* net report*/);
1942
    pthread_mutex_unlock(&LOCK_active_mi);
1943
    break;
1944
  }
1945
#endif /* HAVE_REPLICATION */
1946
1947
  case SQLCOM_ALTER_TABLE:
1948
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
1949
    {
1950
      /*
1951
        Code in mysql_alter_table() may modify its HA_CREATE_INFO argument,
1952
        so we have to use a copy of this structure to make execution
1953
        prepared statement- safe. A shallow copy is enough as no memory
1954
        referenced from this structure will be modified.
1955
      */
1956
      HA_CREATE_INFO create_info(lex->create_info);
1957
      Alter_info alter_info(lex->alter_info, thd->mem_root);
1958
1959
      if (thd->is_fatal_error) /* out of memory creating a copy of alter_info */
1960
      {
1961
        goto error;
1962
      }
1963
1964
      /* Must be set in the parser */
1965
      DBUG_ASSERT(select_lex->db);
1966
1967
      { // Rename of table
1968
          TABLE_LIST tmp_table;
1969
          bzero((char*) &tmp_table,sizeof(tmp_table));
1970
          tmp_table.table_name= lex->name.str;
1971
          tmp_table.db=select_lex->db;
1972
      }
1973
1974
      /* Don't yet allow changing of symlinks with ALTER TABLE */
1975
      if (create_info.data_file_name)
1976
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0,
1977
                     "DATA DIRECTORY option ignored");
1978
      if (create_info.index_file_name)
1979
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0,
1980
                     "INDEX DIRECTORY option ignored");
1981
      create_info.data_file_name= create_info.index_file_name= NULL;
1982
      /* ALTER TABLE ends previous transaction */
1983
      if (end_active_trans(thd))
1984
	goto error;
1985
1986
      if (!thd->locked_tables &&
1987
          !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
1988
      {
1989
        res= 1;
1990
        break;
1991
      }
1992
1993
      thd->enable_slow_log= opt_log_slow_admin_statements;
1994
      res= mysql_alter_table(thd, select_lex->db, lex->name.str,
1995
                             &create_info,
1996
                             first_table,
1997
                             &alter_info,
1998
                             select_lex->order_list.elements,
1999
                             (ORDER *) select_lex->order_list.first,
2000
                             lex->ignore);
2001
      break;
2002
    }
2003
  case SQLCOM_RENAME_TABLE:
2004
  {
2005
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2006
    TABLE_LIST *table;
2007
    for (table= first_table; table; table= table->next_local->next_local)
2008
    {
2009
      TABLE_LIST old_list, new_list;
2010
      /*
2011
        we do not need initialize old_list and new_list because we will
2012
        come table[0] and table->next[0] there
2013
      */
2014
      old_list= table[0];
2015
      new_list= table->next_local[0];
2016
    }
2017
2018
    if (end_active_trans(thd) || mysql_rename_tables(thd, first_table, 0))
2019
      {
2020
        goto error;
2021
      }
2022
    break;
2023
  }
2024
  case SQLCOM_SHOW_BINLOGS:
2025
    {
2026
      res = show_binlogs(thd);
2027
      break;
2028
    }
2029
  case SQLCOM_SHOW_CREATE:
2030
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2031
    {
2032
      res= mysqld_show_create(thd, first_table);
2033
      break;
2034
    }
2035
  case SQLCOM_CHECKSUM:
2036
  {
2037
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2038
    res = mysql_checksum_table(thd, first_table, &lex->check_opt);
2039
    break;
2040
  }
2041
  case SQLCOM_REPAIR:
2042
  {
2043
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2044
    thd->enable_slow_log= opt_log_slow_admin_statements;
2045
    res= mysql_repair_table(thd, first_table, &lex->check_opt);
2046
    /* ! we write after unlocking the table */
2047
    if (!res && !lex->no_write_to_binlog)
2048
    {
2049
      /*
2050
        Presumably, REPAIR and binlog writing doesn't require synchronization
2051
      */
2052
      write_bin_log(thd, TRUE, thd->query, thd->query_length);
2053
    }
2054
    select_lex->table_list.first= (uchar*) first_table;
2055
    lex->query_tables=all_tables;
2056
    break;
2057
  }
2058
  case SQLCOM_CHECK:
2059
  {
2060
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2061
    thd->enable_slow_log= opt_log_slow_admin_statements;
2062
    res = mysql_check_table(thd, first_table, &lex->check_opt);
2063
    select_lex->table_list.first= (uchar*) first_table;
2064
    lex->query_tables=all_tables;
2065
    break;
2066
  }
2067
  case SQLCOM_ANALYZE:
2068
  {
2069
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2070
    thd->enable_slow_log= opt_log_slow_admin_statements;
2071
    res= mysql_analyze_table(thd, first_table, &lex->check_opt);
2072
    /* ! we write after unlocking the table */
2073
    if (!res && !lex->no_write_to_binlog)
2074
    {
2075
      /*
2076
        Presumably, ANALYZE and binlog writing doesn't require synchronization
2077
      */
2078
      write_bin_log(thd, TRUE, thd->query, thd->query_length);
2079
    }
2080
    select_lex->table_list.first= (uchar*) first_table;
2081
    lex->query_tables=all_tables;
2082
    break;
2083
  }
2084
2085
  case SQLCOM_OPTIMIZE:
2086
  {
2087
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2088
    thd->enable_slow_log= opt_log_slow_admin_statements;
2089
    res= (specialflag & (SPECIAL_SAFE_MODE | SPECIAL_NO_NEW_FUNC)) ?
2090
      mysql_recreate_table(thd, first_table) :
2091
      mysql_optimize_table(thd, first_table, &lex->check_opt);
2092
    /* ! we write after unlocking the table */
2093
    if (!res && !lex->no_write_to_binlog)
2094
    {
2095
      /*
2096
        Presumably, OPTIMIZE and binlog writing doesn't require synchronization
2097
      */
2098
      write_bin_log(thd, TRUE, thd->query, thd->query_length);
2099
    }
2100
    select_lex->table_list.first= (uchar*) first_table;
2101
    lex->query_tables=all_tables;
2102
    break;
2103
  }
2104
  case SQLCOM_UPDATE:
2105
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2106
    if (update_precheck(thd, all_tables))
2107
      break;
2108
    DBUG_ASSERT(select_lex->offset_limit == 0);
2109
    unit->set_limit(select_lex);
2110
    res= (up_result= mysql_update(thd, all_tables,
2111
                                  select_lex->item_list,
2112
                                  lex->value_list,
2113
                                  select_lex->where,
2114
                                  select_lex->order_list.elements,
2115
                                  (ORDER *) select_lex->order_list.first,
2116
                                  unit->select_limit_cnt,
2117
                                  lex->duplicates, lex->ignore));
2118
    /* mysql_update return 2 if we need to switch to multi-update */
2119
    if (up_result != 2)
2120
      break;
2121
    /* Fall through */
2122
  case SQLCOM_UPDATE_MULTI:
2123
  {
2124
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2125
    /* if we switched from normal update, rights are checked */
2126
    if (up_result != 2)
2127
    {
2128
      if ((res= multi_update_precheck(thd, all_tables)))
2129
        break;
2130
    }
2131
    else
2132
      res= 0;
2133
2134
    res= mysql_multi_update_prepare(thd);
2135
2136
#ifdef HAVE_REPLICATION
2137
    /* Check slave filtering rules */
2138
    if (unlikely(thd->slave_thread))
2139
    {
2140
      if (all_tables_not_ok(thd, all_tables))
2141
      {
2142
        if (res!= 0)
2143
        {
2144
          res= 0;             /* don't care of prev failure  */
2145
          thd->clear_error(); /* filters are of highest prior */
2146
        }
2147
        /* we warn the slave SQL thread */
2148
        my_error(ER_SLAVE_IGNORED_TABLE, MYF(0));
2149
        break;
2150
      }
2151
      if (res)
2152
        break;
2153
    }
2154
    else
2155
    {
2156
#endif /* HAVE_REPLICATION */
2157
      if (res)
2158
        break;
2159
      if (opt_readonly &&
2160
	  some_non_temp_table_to_be_updated(thd, all_tables))
2161
      {
2162
	my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
2163
	break;
2164
      }
2165
#ifdef HAVE_REPLICATION
2166
    }  /* unlikely */
2167
#endif
2168
2169
    res= mysql_multi_update(thd, all_tables,
2170
                            &select_lex->item_list,
2171
                            &lex->value_list,
2172
                            select_lex->where,
2173
                            select_lex->options,
2174
                            lex->duplicates, lex->ignore, unit, select_lex);
2175
    break;
2176
  }
2177
  case SQLCOM_REPLACE:
2178
#ifndef DBUG_OFF
2179
    if (mysql_bin_log.is_open())
2180
    {
2181
      /*
2182
        Generate an incident log event before writing the real event
2183
        to the binary log.  We put this event is before the statement
2184
        since that makes it simpler to check that the statement was
2185
        not executed on the slave (since incidents usually stop the
2186
        slave).
2187
2188
        Observe that any row events that are generated will be
2189
        generated before.
2190
2191
        This is only for testing purposes and will not be present in a
2192
        release build.
2193
      */
2194
2195
      Incident incident= INCIDENT_NONE;
2196
      DBUG_PRINT("debug", ("Just before generate_incident()"));
2197
      DBUG_EXECUTE_IF("incident_database_resync_on_replace",
2198
                      incident= INCIDENT_LOST_EVENTS;);
2199
      if (incident)
2200
      {
2201
        Incident_log_event ev(thd, incident);
2202
        mysql_bin_log.write(&ev);
2203
        mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
2204
      }
2205
      DBUG_PRINT("debug", ("Just after generate_incident()"));
2206
    }
2207
#endif
2208
  case SQLCOM_INSERT:
2209
  {
2210
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2211
    if ((res= insert_precheck(thd, all_tables)))
2212
      break;
2213
2214
    if (!thd->locked_tables &&
2215
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
2216
    {
2217
      res= 1;
2218
      break;
2219
    }
2220
2221
    res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
2222
		      lex->update_list, lex->value_list,
2223
                      lex->duplicates, lex->ignore);
2224
2225
    break;
2226
  }
2227
  case SQLCOM_REPLACE_SELECT:
2228
  case SQLCOM_INSERT_SELECT:
2229
  {
2230
    select_result *sel_result;
2231
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2232
    if ((res= insert_precheck(thd, all_tables)))
2233
      break;
2234
2235
    /* Fix lock for first table */
2236
    if (first_table->lock_type == TL_WRITE_DELAYED)
2237
      first_table->lock_type= TL_WRITE;
2238
2239
    /* Don't unlock tables until command is written to binary log */
2240
    select_lex->options|= SELECT_NO_UNLOCK;
2241
2242
    unit->set_limit(select_lex);
2243
2244
    if (! thd->locked_tables &&
2245
        ! (need_start_waiting= ! wait_if_global_read_lock(thd, 0, 1)))
2246
    {
2247
      res= 1;
2248
      break;
2249
    }
2250
2251
    if (!(res= open_and_lock_tables(thd, all_tables)))
2252
    {
2253
      /* Skip first table, which is the table we are inserting in */
2254
      TABLE_LIST *second_table= first_table->next_local;
2255
      select_lex->table_list.first= (uchar*) second_table;
2256
      select_lex->context.table_list= 
2257
        select_lex->context.first_name_resolution_table= second_table;
2258
      res= mysql_insert_select_prepare(thd);
2259
      if (!res && (sel_result= new select_insert(first_table,
2260
                                                 first_table->table,
2261
                                                 &lex->field_list,
2262
                                                 &lex->update_list,
2263
                                                 &lex->value_list,
2264
                                                 lex->duplicates,
2265
                                                 lex->ignore)))
2266
      {
2267
	res= handle_select(thd, lex, sel_result, OPTION_SETUP_TABLES_DONE);
2268
        /*
2269
          Invalidate the table in the query cache if something changed
2270
          after unlocking when changes become visible.
2271
          TODO: this is workaround. right way will be move invalidating in
2272
          the unlock procedure.
2273
        */
2274
        if (first_table->lock_type ==  TL_WRITE_CONCURRENT_INSERT &&
2275
            thd->lock)
2276
        {
2277
          /* INSERT ... SELECT should invalidate only the very first table */
2278
          TABLE_LIST *save_table= first_table->next_local;
2279
          first_table->next_local= 0;
2280
          first_table->next_local= save_table;
2281
        }
2282
        delete sel_result;
2283
      }
2284
      /* revert changes for SP */
2285
      select_lex->table_list.first= (uchar*) first_table;
2286
    }
2287
2288
    break;
2289
  }
2290
  case SQLCOM_TRUNCATE:
2291
    if (end_active_trans(thd))
2292
    {
2293
      res= -1;
2294
      break;
2295
    }
2296
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2297
    /*
2298
      Don't allow this within a transaction because we want to use
2299
      re-generate table
2300
    */
2301
    if (thd->locked_tables || thd->active_transaction())
2302
    {
2303
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
2304
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2305
      goto error;
2306
    }
2307
2308
    res= mysql_truncate(thd, first_table, 0);
2309
2310
    break;
2311
  case SQLCOM_DELETE:
2312
  {
2313
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2314
    DBUG_ASSERT(select_lex->offset_limit == 0);
2315
    unit->set_limit(select_lex);
2316
2317
    if (!thd->locked_tables &&
2318
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
2319
    {
2320
      res= 1;
2321
      break;
2322
    }
2323
2324
    res = mysql_delete(thd, all_tables, select_lex->where,
2325
                       &select_lex->order_list,
2326
                       unit->select_limit_cnt, select_lex->options,
2327
                       FALSE);
2328
    break;
2329
  }
2330
  case SQLCOM_DELETE_MULTI:
2331
  {
2332
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2333
    TABLE_LIST *aux_tables=
2334
      (TABLE_LIST *)thd->lex->auxiliary_table_list.first;
2335
    multi_delete *del_result;
2336
2337
    if (!thd->locked_tables &&
2338
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
2339
    {
2340
      res= 1;
2341
      break;
2342
    }
2343
2344
    if ((res= multi_delete_precheck(thd, all_tables)))
2345
      break;
2346
2347
    /* condition will be TRUE on SP re-excuting */
2348
    if (select_lex->item_list.elements != 0)
2349
      select_lex->item_list.empty();
2350
    if (add_item_to_list(thd, new Item_null()))
2351
      goto error;
2352
2353
    thd_proc_info(thd, "init");
2354
    if ((res= open_and_lock_tables(thd, all_tables)))
2355
      break;
2356
2357
    if ((res= mysql_multi_delete_prepare(thd)))
2358
      goto error;
2359
2360
    if (!thd->is_fatal_error &&
2361
        (del_result= new multi_delete(aux_tables, lex->table_count)))
2362
    {
2363
      res= mysql_select(thd, &select_lex->ref_pointer_array,
2364
			select_lex->get_table_list(),
2365
			select_lex->with_wild,
2366
			select_lex->item_list,
2367
			select_lex->where,
2368
			0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL,
2369
			(ORDER *)NULL,
2370
			select_lex->options | thd->options |
2371
			SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
2372
                        OPTION_SETUP_TABLES_DONE,
2373
			del_result, unit, select_lex);
2374
      res|= thd->is_error();
2375
      if (res)
2376
        del_result->abort();
2377
      delete del_result;
2378
    }
2379
    else
2380
      res= TRUE;                                // Error
2381
    break;
2382
  }
2383
  case SQLCOM_DROP_TABLE:
2384
  {
2385
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2386
    if (!lex->drop_temporary)
2387
    {
2388
      if (end_active_trans(thd))
2389
        goto error;
2390
    }
2391
    else
2392
    {
2393
      /*
2394
	If this is a slave thread, we may sometimes execute some 
2395
	DROP / * 40005 TEMPORARY * / TABLE
2396
	that come from parts of binlogs (likely if we use RESET SLAVE or CHANGE
2397
	MASTER TO), while the temporary table has already been dropped.
2398
	To not generate such irrelevant "table does not exist errors",
2399
	we silently add IF EXISTS if TEMPORARY was used.
2400
      */
2401
      if (thd->slave_thread)
2402
        lex->drop_if_exists= 1;
2403
2404
      /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
2405
      thd->options|= OPTION_KEEP_LOG;
2406
    }
2407
    /* DDL and binlog write order protected by LOCK_open */
2408
    res= mysql_rm_table(thd, first_table, lex->drop_if_exists,
2409
			lex->drop_temporary);
2410
  }
2411
  break;
2412
  case SQLCOM_SHOW_PROCESSLIST:
2413
    mysqld_list_processes(thd, NullS, lex->verbose);
2414
    break;
2415
  case SQLCOM_SHOW_ENGINE_LOGS:
2416
    {
2417
      res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS);
2418
      break;
2419
    }
2420
  case SQLCOM_CHANGE_DB:
2421
  {
2422
    LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) };
2423
2424
    if (!mysql_change_db(thd, &db_str, FALSE))
2425
      my_ok(thd);
2426
2427
    break;
2428
  }
2429
2430
  case SQLCOM_LOAD:
2431
  {
2432
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
2433
    if (lex->local_file)
2434
    {
2435
      if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) ||
2436
          !opt_local_infile)
2437
      {
2438
	my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0));
2439
	goto error;
2440
      }
2441
    }
2442
2443
    res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
2444
                    lex->update_list, lex->value_list, lex->duplicates,
2445
                    lex->ignore, (bool) lex->local_file);
2446
    break;
2447
  }
2448
2449
  case SQLCOM_SET_OPTION:
2450
  {
2451
    List<set_var_base> *lex_var_list= &lex->var_list;
2452
2453
    if (lex->autocommit && end_active_trans(thd))
2454
      goto error;
2455
2456
    if (open_and_lock_tables(thd, all_tables))
2457
      goto error;
2458
    if (lex->one_shot_set && not_all_support_one_shot(lex_var_list))
2459
    {
2460
      my_error(ER_RESERVED_SYNTAX, MYF(0), "SET ONE_SHOT");
2461
      goto error;
2462
    }
2463
    if (!(res= sql_set_variables(thd, lex_var_list)))
2464
    {
2465
      /*
2466
        If the previous command was a SET ONE_SHOT, we don't want to forget
2467
        about the ONE_SHOT property of that SET. So we use a |= instead of = .
2468
      */
2469
      thd->one_shot_set|= lex->one_shot_set;
2470
      my_ok(thd);
2471
    }
2472
    else
2473
    {
2474
      /*
2475
        We encountered some sort of error, but no message was sent.
2476
        Send something semi-generic here since we don't know which
2477
        assignment in the list caused the error.
2478
      */
2479
      if (!thd->is_error())
2480
        my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET");
2481
      goto error;
2482
    }
2483
2484
    break;
2485
  }
2486
2487
  case SQLCOM_UNLOCK_TABLES:
2488
    /*
2489
      It is critical for mysqldump --single-transaction --master-data that
2490
      UNLOCK TABLES does not implicitely commit a connection which has only
2491
      done FLUSH TABLES WITH READ LOCK + BEGIN. If this assumption becomes
2492
      false, mysqldump will not work.
2493
    */
2494
    unlock_locked_tables(thd);
2495
    if (thd->options & OPTION_TABLE_LOCK)
2496
    {
2497
      end_active_trans(thd);
2498
      thd->options&= ~(OPTION_TABLE_LOCK);
2499
    }
2500
    if (thd->global_read_lock)
2501
      unlock_global_read_lock(thd);
2502
    my_ok(thd);
2503
    break;
2504
  case SQLCOM_LOCK_TABLES:
2505
    /*
2506
      We try to take transactional locks if
2507
      - only transactional locks are requested (lex->lock_transactional) and
2508
      - no non-transactional locks exist (!thd->locked_tables).
2509
    */
2510
    DBUG_PRINT("lock_info", ("lex->lock_transactional: %d  "
2511
                             "thd->locked_tables: 0x%lx",
2512
                             lex->lock_transactional,
2513
                             (long) thd->locked_tables));
2514
    if (lex->lock_transactional && !thd->locked_tables)
2515
    {
2516
      int rc;
2517
      /*
2518
        All requested locks are transactional and no non-transactional
2519
        locks exist.
2520
      */
2521
      if ((rc= try_transactional_lock(thd, all_tables)) == -1)
2522
        goto error;
2523
      if (rc == 0)
2524
      {
2525
        my_ok(thd);
2526
        break;
2527
      }
2528
      /*
2529
        Non-transactional locking has been requested or
2530
        non-transactional locks exist already or transactional locks are
2531
        not supported by all storage engines. Take non-transactional
2532
        locks.
2533
      */
2534
    }
2535
    /*
2536
      One or more requested locks are non-transactional and/or
2537
      non-transactional locks exist or a storage engine does not support
2538
      transactional locks. Check if at least one transactional lock is
2539
      requested. If yes, warn about the conversion to non-transactional
2540
      locks or abort in strict mode.
2541
    */
2542
    if (check_transactional_lock(thd, all_tables))
2543
      goto error;
2544
    unlock_locked_tables(thd);
2545
    /* we must end the trasaction first, regardless of anything */
2546
    if (end_active_trans(thd))
2547
      goto error;
2548
    thd->in_lock_tables=1;
2549
    thd->options|= OPTION_TABLE_LOCK;
2550
2551
    if (!(res= simple_open_n_lock_tables(thd, all_tables)))
2552
    {
2553
      thd->locked_tables=thd->lock;
2554
      thd->lock=0;
2555
      (void) set_handler_table_locks(thd, all_tables, FALSE);
2556
      DBUG_PRINT("lock_info", ("thd->locked_tables: 0x%lx",
2557
                               (long) thd->locked_tables));
2558
      my_ok(thd);
2559
    }
2560
    else
2561
    {
2562
      /* 
2563
        Need to end the current transaction, so the storage engine (InnoDB)
2564
        can free its locks if LOCK TABLES locked some tables before finding
2565
        that it can't lock a table in its list
2566
      */
2567
      ha_autocommit_or_rollback(thd, 1);
2568
      end_active_trans(thd);
2569
      thd->options&= ~(OPTION_TABLE_LOCK);
2570
    }
2571
    thd->in_lock_tables=0;
2572
    break;
2573
  case SQLCOM_CREATE_DB:
2574
  {
2575
    /*
2576
      As mysql_create_db() may modify HA_CREATE_INFO structure passed to
2577
      it, we need to use a copy of LEX::create_info to make execution
2578
      prepared statement- safe.
2579
    */
2580
    HA_CREATE_INFO create_info(lex->create_info);
2581
    if (end_active_trans(thd))
2582
    {
2583
      res= -1;
2584
      break;
2585
    }
2586
    char *alias;
2587
    if (!(alias=thd->strmake(lex->name.str, lex->name.length)) ||
2588
        check_db_name(&lex->name))
2589
    {
2590
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
2591
      break;
2592
    }
2593
    /*
2594
      If in a slave thread :
2595
      CREATE DATABASE DB was certainly not preceded by USE DB.
2596
      For that reason, db_ok() in sql/slave.cc did not check the
2597
      do_db/ignore_db. And as this query involves no tables, tables_ok()
2598
      above was not called. So we have to check rules again here.
2599
    */
2600
    if (thd->slave_thread && 
2601
	(!rpl_filter->db_ok(lex->name.str) ||
2602
	 !rpl_filter->db_ok_with_wild_table(lex->name.str)))
2603
    {
2604
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2605
      break;
2606
    }
2607
    res= mysql_create_db(thd,(lower_case_table_names == 2 ? alias :
2608
                              lex->name.str), &create_info, 0);
2609
    break;
2610
  }
2611
  case SQLCOM_DROP_DB:
2612
  {
2613
    if (end_active_trans(thd))
2614
    {
2615
      res= -1;
2616
      break;
2617
    }
2618
    if (check_db_name(&lex->name))
2619
    {
2620
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
2621
      break;
2622
    }
2623
    /*
2624
      If in a slave thread :
2625
      DROP DATABASE DB may not be preceded by USE DB.
2626
      For that reason, maybe db_ok() in sql/slave.cc did not check the 
2627
      do_db/ignore_db. And as this query involves no tables, tables_ok()
2628
      above was not called. So we have to check rules again here.
2629
    */
2630
#ifdef HAVE_REPLICATION
2631
    if (thd->slave_thread && 
2632
	(!rpl_filter->db_ok(lex->name.str) ||
2633
	 !rpl_filter->db_ok_with_wild_table(lex->name.str)))
2634
    {
2635
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2636
      break;
2637
    }
2638
#endif
2639
    if (thd->locked_tables || thd->active_transaction())
2640
    {
2641
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
2642
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2643
      goto error;
2644
    }
2645
    res= mysql_rm_db(thd, lex->name.str, lex->drop_if_exists, 0);
2646
    break;
2647
  }
2648
  case SQLCOM_ALTER_DB_UPGRADE:
2649
  {
2650
    LEX_STRING *db= & lex->name;
2651
    if (end_active_trans(thd))
2652
    {
2653
      res= 1;
2654
      break;
2655
    }
2656
#ifdef HAVE_REPLICATION
2657
    if (thd->slave_thread && 
2658
       (!rpl_filter->db_ok(db->str) ||
2659
        !rpl_filter->db_ok_with_wild_table(db->str)))
2660
    {
2661
      res= 1;
2662
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2663
      break;
2664
    }
2665
#endif
2666
    if (check_db_name(db))
2667
    {
2668
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
2669
      break;
2670
    }
2671
    if (thd->locked_tables || thd->active_transaction())
2672
    {
2673
      res= 1;
2674
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
2675
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2676
      goto error;
2677
    }
2678
2679
    res= mysql_upgrade_db(thd, db);
2680
    if (!res)
2681
      my_ok(thd);
2682
    break;
2683
  }
2684
  case SQLCOM_ALTER_DB:
2685
  {
2686
    LEX_STRING *db= &lex->name;
2687
    HA_CREATE_INFO create_info(lex->create_info);
2688
    if (check_db_name(db))
2689
    {
2690
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
2691
      break;
2692
    }
2693
    /*
2694
      If in a slave thread :
2695
      ALTER DATABASE DB may not be preceded by USE DB.
2696
      For that reason, maybe db_ok() in sql/slave.cc did not check the
2697
      do_db/ignore_db. And as this query involves no tables, tables_ok()
2698
      above was not called. So we have to check rules again here.
2699
    */
2700
#ifdef HAVE_REPLICATION
2701
    if (thd->slave_thread &&
2702
	(!rpl_filter->db_ok(db->str) ||
2703
	 !rpl_filter->db_ok_with_wild_table(db->str)))
2704
    {
2705
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2706
      break;
2707
    }
2708
#endif
2709
    if (thd->locked_tables || thd->active_transaction())
2710
    {
2711
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
2712
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2713
      goto error;
2714
    }
2715
    res= mysql_alter_db(thd, db->str, &create_info);
2716
    break;
2717
  }
2718
  case SQLCOM_SHOW_CREATE_DB:
2719
  {
2720
    DBUG_EXECUTE_IF("4x_server_emul",
2721
                    my_error(ER_UNKNOWN_ERROR, MYF(0)); goto error;);
2722
    if (check_db_name(&lex->name))
2723
    {
2724
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
2725
      break;
2726
    }
2727
    res= mysqld_show_create_db(thd, lex->name.str, &lex->create_info);
2728
    break;
2729
  }
2730
  case SQLCOM_RESET:
2731
    /*
2732
      RESET commands are never written to the binary log, so we have to
2733
      initialize this variable because RESET shares the same code as FLUSH
2734
    */
2735
    lex->no_write_to_binlog= 1;
2736
  case SQLCOM_FLUSH:
2737
  {
2738
    bool write_to_binlog;
2739
2740
    /*
2741
      reload_cache() will tell us if we are allowed to write to the
2742
      binlog or not.
2743
    */
2744
    if (!reload_cache(thd, lex->type, first_table, &write_to_binlog))
2745
    {
2746
      /*
2747
        We WANT to write and we CAN write.
2748
        ! we write after unlocking the table.
2749
      */
2750
      /*
2751
        Presumably, RESET and binlog writing doesn't require synchronization
2752
      */
2753
      if (!lex->no_write_to_binlog && write_to_binlog)
2754
      {
2755
        write_bin_log(thd, FALSE, thd->query, thd->query_length);
2756
      }
2757
      my_ok(thd);
2758
    } 
2759
    
2760
    break;
2761
  }
2762
  case SQLCOM_KILL:
2763
  {
2764
    Item *it= (Item *)lex->value_list.head();
2765
2766
    if (lex->table_or_sp_used())
2767
    {
2768
      my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Usage of subqueries or stored "
2769
               "function calls as part of this statement");
2770
      break;
2771
    }
2772
2773
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1))
2774
    {
2775
      my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY),
2776
		 MYF(0));
2777
      goto error;
2778
    }
2779
    sql_kill(thd, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY);
2780
    break;
2781
  }
2782
  case SQLCOM_BEGIN:
2783
    if (thd->transaction.xid_state.xa_state != XA_NOTR)
2784
    {
2785
      my_error(ER_XAER_RMFAIL, MYF(0),
2786
               xa_state_names[thd->transaction.xid_state.xa_state]);
2787
      break;
2788
    }
2789
    /*
2790
      Breakpoints for backup testing.
2791
    */
2792
    if (begin_trans(thd))
2793
      goto error;
2794
    my_ok(thd);
2795
    break;
2796
  case SQLCOM_COMMIT:
2797
    if (end_trans(thd, lex->tx_release ? COMMIT_RELEASE :
2798
                              lex->tx_chain ? COMMIT_AND_CHAIN : COMMIT))
2799
      goto error;
2800
    my_ok(thd);
2801
    break;
2802
  case SQLCOM_ROLLBACK:
2803
    if (end_trans(thd, lex->tx_release ? ROLLBACK_RELEASE :
2804
                              lex->tx_chain ? ROLLBACK_AND_CHAIN : ROLLBACK))
2805
      goto error;
2806
    my_ok(thd);
2807
    break;
2808
  case SQLCOM_RELEASE_SAVEPOINT:
2809
  {
2810
    SAVEPOINT *sv;
2811
    for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
2812
    {
2813
      if (my_strnncoll(system_charset_info,
2814
                       (uchar *)lex->ident.str, lex->ident.length,
2815
                       (uchar *)sv->name, sv->length) == 0)
2816
        break;
2817
    }
2818
    if (sv)
2819
    {
2820
      if (ha_release_savepoint(thd, sv))
2821
        res= TRUE; // cannot happen
2822
      else
2823
        my_ok(thd);
2824
      thd->transaction.savepoints=sv->prev;
2825
    }
2826
    else
2827
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
2828
    break;
2829
  }
2830
  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
2831
  {
2832
    SAVEPOINT *sv;
2833
    for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
2834
    {
2835
      if (my_strnncoll(system_charset_info,
2836
                       (uchar *)lex->ident.str, lex->ident.length,
2837
                       (uchar *)sv->name, sv->length) == 0)
2838
        break;
2839
    }
2840
    if (sv)
2841
    {
2842
      if (ha_rollback_to_savepoint(thd, sv))
2843
        res= TRUE; // cannot happen
2844
      else
2845
      {
2846
        if (((thd->options & OPTION_KEEP_LOG) || 
2847
             thd->transaction.all.modified_non_trans_table) &&
2848
            !thd->slave_thread)
2849
          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2850
                       ER_WARNING_NOT_COMPLETE_ROLLBACK,
2851
                       ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
2852
        my_ok(thd);
2853
      }
2854
      thd->transaction.savepoints=sv;
2855
    }
2856
    else
2857
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
2858
    break;
2859
  }
2860
  case SQLCOM_SAVEPOINT:
2861
    if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN) ||
2862
          thd->in_sub_stmt) || !opt_using_transactions)
2863
      my_ok(thd);
2864
    else
2865
    {
2866
      SAVEPOINT **sv, *newsv;
2867
      for (sv=&thd->transaction.savepoints; *sv; sv=&(*sv)->prev)
2868
      {
2869
        if (my_strnncoll(system_charset_info,
2870
                         (uchar *)lex->ident.str, lex->ident.length,
2871
                         (uchar *)(*sv)->name, (*sv)->length) == 0)
2872
          break;
2873
      }
2874
      if (*sv) /* old savepoint of the same name exists */
2875
      {
2876
        newsv=*sv;
2877
        ha_release_savepoint(thd, *sv); // it cannot fail
2878
        *sv=(*sv)->prev;
2879
      }
2880
      else if ((newsv=(SAVEPOINT *) alloc_root(&thd->transaction.mem_root,
2881
                                               savepoint_alloc_size)) == 0)
2882
      {
2883
        my_error(ER_OUT_OF_RESOURCES, MYF(0));
2884
        break;
2885
      }
2886
      newsv->name=strmake_root(&thd->transaction.mem_root,
2887
                               lex->ident.str, lex->ident.length);
2888
      newsv->length=lex->ident.length;
2889
      /*
2890
        if we'll get an error here, don't add new savepoint to the list.
2891
        we'll lose a little bit of memory in transaction mem_root, but it'll
2892
        be free'd when transaction ends anyway
2893
      */
2894
      if (ha_savepoint(thd, newsv))
2895
        res= TRUE;
2896
      else
2897
      {
2898
        newsv->prev=thd->transaction.savepoints;
2899
        thd->transaction.savepoints=newsv;
2900
        my_ok(thd);
2901
      }
2902
    }
2903
    break;
2904
  case SQLCOM_BINLOG_BASE64_EVENT:
2905
  {
2906
    mysql_client_binlog_statement(thd);
2907
    break;
2908
  }
2909
  default:
2910
    DBUG_ASSERT(0);                             /* Impossible */
2911
    my_ok(thd);
2912
    break;
2913
  }
2914
  thd_proc_info(thd, "query end");
2915
2916
  /*
2917
    Binlog-related cleanup:
2918
    Reset system variables temporarily modified by SET ONE SHOT.
2919
2920
    Exception: If this is a SET, do nothing. This is to allow
2921
    mysqlbinlog to print many SET commands (in this case we want the
2922
    charset temp setting to live until the real query). This is also
2923
    needed so that SET CHARACTER_SET_CLIENT... does not cancel itself
2924
    immediately.
2925
  */
2926
  if (thd->one_shot_set && lex->sql_command != SQLCOM_SET_OPTION)
2927
    reset_one_shot_variables(thd);
2928
2929
  /*
2930
    The return value for ROW_COUNT() is "implementation dependent" if the
2931
    statement is not DELETE, INSERT or UPDATE, but -1 is what JDBC and ODBC
2932
    wants. We also keep the last value in case of SQLCOM_CALL or
2933
    SQLCOM_EXECUTE.
2934
  */
2935
  if (!(sql_command_flags[lex->sql_command] & CF_HAS_ROW_COUNT))
2936
    thd->row_count_func= -1;
2937
2938
  goto finish;
2939
2940
error:
2941
  res= TRUE;
2942
2943
finish:
2944
  if (need_start_waiting)
2945
  {
2946
    /*
2947
      Release the protection against the global read lock and wake
2948
      everyone, who might want to set a global read lock.
2949
    */
2950
    start_waiting_global_read_lock(thd);
2951
  }
2952
  DBUG_RETURN(res || thd->is_error());
2953
}
2954
2955
2956
static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables)
2957
{
2958
  LEX	*lex= thd->lex;
2959
  select_result *result=lex->result;
2960
  bool res;
2961
  /* assign global limit variable if limit is not given */
2962
  {
2963
    SELECT_LEX *param= lex->unit.global_parameters;
2964
    if (!param->explicit_limit)
2965
      param->select_limit=
2966
        new Item_int((ulonglong) thd->variables.select_limit);
2967
  }
2968
  if (!(res= open_and_lock_tables(thd, all_tables)))
2969
  {
2970
    if (lex->describe)
2971
    {
2972
      /*
2973
        We always use select_send for EXPLAIN, even if it's an EXPLAIN
2974
        for SELECT ... INTO OUTFILE: a user application should be able
2975
        to prepend EXPLAIN to any query and receive output for it,
2976
        even if the query itself redirects the output.
2977
      */
2978
      if (!(result= new select_send()))
2979
        return 1;                               /* purecov: inspected */
2980
      thd->send_explain_fields(result);
2981
      res= mysql_explain_union(thd, &thd->lex->unit, result);
2982
      if (lex->describe & DESCRIBE_EXTENDED)
2983
      {
2984
        char buff[1024];
2985
        String str(buff,(uint32) sizeof(buff), system_charset_info);
2986
        str.length(0);
2987
        thd->lex->unit.print(&str, QT_ORDINARY);
2988
        str.append('\0');
2989
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
2990
                     ER_YES, str.ptr());
2991
      }
2992
      if (res)
2993
        result->abort();
2994
      else
2995
        result->send_eof();
2996
      delete result;
2997
    }
2998
    else
2999
    {
3000
      if (!result && !(result= new select_send()))
3001
        return 1;                               /* purecov: inspected */
3002
      res= handle_select(thd, lex, result, 0);
3003
      if (result != lex->result)
3004
        delete result;
3005
    }
3006
  }
3007
  return res;
3008
}
3009
3010
/****************************************************************************
3011
	Check stack size; Send error if there isn't enough stack to continue
3012
****************************************************************************/
3013
#if STACK_DIRECTION < 0
3014
#define used_stack(A,B) (long) (A - B)
3015
#else
3016
#define used_stack(A,B) (long) (B - A)
3017
#endif
3018
3019
#ifndef DBUG_OFF
3020
long max_stack_used;
3021
#endif
3022
3023
/**
3024
  @note
3025
  Note: The 'buf' parameter is necessary, even if it is unused here.
3026
  - fix_fields functions has a "dummy" buffer large enough for the
3027
    corresponding exec. (Thus we only have to check in fix_fields.)
3028
  - Passing to check_stack_overrun() prevents the compiler from removing it.
3029
*/
3030
bool check_stack_overrun(THD *thd, long margin,
3031
			 uchar *buf __attribute__((unused)))
3032
{
3033
  long stack_used;
3034
  DBUG_ASSERT(thd == current_thd);
3035
  if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >=
3036
      (long) (my_thread_stack_size - margin))
3037
  {
3038
    sprintf(errbuff[0],ER(ER_STACK_OVERRUN_NEED_MORE),
3039
            stack_used,my_thread_stack_size,margin);
3040
    my_message(ER_STACK_OVERRUN_NEED_MORE,errbuff[0],MYF(ME_FATALERROR));
3041
    return 1;
3042
  }
3043
#ifndef DBUG_OFF
3044
  max_stack_used= max(max_stack_used, stack_used);
3045
#endif
3046
  return 0;
3047
}
3048
3049
#define MY_YACC_INIT 1000			// Start with big alloc
3050
#define MY_YACC_MAX  32000			// Because of 'short'
3051
3052
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
3053
{
3054
  LEX	*lex= current_thd->lex;
3055
  ulong old_info=0;
3056
  if ((uint) *yystacksize >= MY_YACC_MAX)
3057
    return 1;
3058
  if (!lex->yacc_yyvs)
3059
    old_info= *yystacksize;
3060
  *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
3061
  if (!(lex->yacc_yyvs= (uchar*)
3062
	my_realloc(lex->yacc_yyvs,
3063
		   *yystacksize*sizeof(**yyvs),
3064
		   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
3065
      !(lex->yacc_yyss= (uchar*)
3066
	my_realloc(lex->yacc_yyss,
3067
		   *yystacksize*sizeof(**yyss),
3068
		   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
3069
    return 1;
3070
  if (old_info)
3071
  {						// Copy old info from stack
3072
    memcpy(lex->yacc_yyss, (uchar*) *yyss, old_info*sizeof(**yyss));
3073
    memcpy(lex->yacc_yyvs, (uchar*) *yyvs, old_info*sizeof(**yyvs));
3074
  }
3075
  *yyss=(short*) lex->yacc_yyss;
3076
  *yyvs=(YYSTYPE*) lex->yacc_yyvs;
3077
  return 0;
3078
}
3079
3080
3081
/**
3082
 Reset THD part responsible for command processing state.
3083
3084
   This needs to be called before execution of every statement
3085
   (prepared or conventional).
3086
   It is not called by substatements of routines.
3087
3088
  @todo
3089
   Make it a method of THD and align its name with the rest of
3090
   reset/end/start/init methods.
3091
  @todo
3092
   Call it after we use THD for queries, not before.
3093
*/
3094
3095
void mysql_reset_thd_for_next_command(THD *thd)
3096
{
3097
  DBUG_ENTER("mysql_reset_thd_for_next_command");
3098
  DBUG_ASSERT(! thd->in_sub_stmt);
3099
  thd->free_list= 0;
3100
  thd->select_number= 1;
3101
  /*
3102
    Those two lines below are theoretically unneeded as
3103
    THD::cleanup_after_query() should take care of this already.
3104
  */
3105
  thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
3106
  thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
3107
3108
  thd->query_start_used= 0;
3109
  thd->is_fatal_error= thd->time_zone_used= 0;
3110
  thd->server_status&= ~ (SERVER_MORE_RESULTS_EXISTS | 
3111
                          SERVER_QUERY_NO_INDEX_USED |
3112
                          SERVER_QUERY_NO_GOOD_INDEX_USED);
3113
  /*
3114
    If in autocommit mode and not in a transaction, reset
3115
    OPTION_STATUS_NO_TRANS_UPDATE | OPTION_KEEP_LOG to not get warnings
3116
    in ha_rollback_trans() about some tables couldn't be rolled back.
3117
  */
3118
  if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)))
3119
  {
3120
    thd->options&= ~OPTION_KEEP_LOG;
3121
    thd->transaction.all.modified_non_trans_table= FALSE;
3122
  }
3123
  DBUG_ASSERT(thd->security_ctx== &thd->main_security_ctx);
3124
  thd->thread_specific_used= FALSE;
3125
3126
  if (opt_bin_log)
3127
  {
3128
    reset_dynamic(&thd->user_var_events);
3129
    thd->user_var_events_alloc= thd->mem_root;
3130
  }
3131
  thd->clear_error();
3132
  thd->main_da.reset_diagnostics_area();
3133
  thd->total_warn_count=0;			// Warnings for this query
3134
  thd->rand_used= 0;
3135
  thd->sent_row_count= thd->examined_row_count= 0;
3136
3137
  /*
3138
    Because we come here only for start of top-statements, binlog format is
3139
    constant inside a complex statement (using stored functions) etc.
3140
  */
3141
  thd->reset_current_stmt_binlog_row_based();
3142
3143
  DBUG_VOID_RETURN;
3144
}
3145
3146
3147
void
3148
mysql_init_select(LEX *lex)
3149
{
3150
  SELECT_LEX *select_lex= lex->current_select;
3151
  select_lex->init_select();
3152
  lex->wild= 0;
3153
  if (select_lex == &lex->select_lex)
3154
  {
3155
    DBUG_ASSERT(lex->result == 0);
3156
    lex->exchange= 0;
3157
  }
3158
}
3159
3160
3161
bool
3162
mysql_new_select(LEX *lex, bool move_down)
3163
{
3164
  SELECT_LEX *select_lex;
3165
  THD *thd= lex->thd;
3166
  DBUG_ENTER("mysql_new_select");
3167
3168
  if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
3169
    DBUG_RETURN(1);
3170
  select_lex->select_number= ++thd->select_number;
3171
  select_lex->parent_lex= lex; /* Used in init_query. */
3172
  select_lex->init_query();
3173
  select_lex->init_select();
3174
  lex->nest_level++;
3175
  if (lex->nest_level > (int) MAX_SELECT_NESTING)
3176
  {
3177
    my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
3178
    DBUG_RETURN(1);
3179
  }
3180
  select_lex->nest_level= lex->nest_level;
3181
  if (move_down)
3182
  {
3183
    SELECT_LEX_UNIT *unit;
3184
    lex->subqueries= TRUE;
3185
    /* first select_lex of subselect or derived table */
3186
    if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
3187
      DBUG_RETURN(1);
3188
3189
    unit->init_query();
3190
    unit->init_select();
3191
    unit->thd= thd;
3192
    unit->include_down(lex->current_select);
3193
    unit->link_next= 0;
3194
    unit->link_prev= 0;
3195
    unit->return_to= lex->current_select;
3196
    select_lex->include_down(unit);
3197
    /*
3198
      By default we assume that it is usual subselect and we have outer name
3199
      resolution context, if no we will assign it to 0 later
3200
    */
3201
    select_lex->context.outer_context= &select_lex->outer_select()->context;
3202
  }
3203
  else
3204
  {
3205
    if (lex->current_select->order_list.first && !lex->current_select->braces)
3206
    {
3207
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY");
3208
      DBUG_RETURN(1);
3209
    }
3210
    select_lex->include_neighbour(lex->current_select);
3211
    SELECT_LEX_UNIT *unit= select_lex->master_unit();                              
3212
    if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->thd))
3213
      DBUG_RETURN(1);
3214
    select_lex->context.outer_context= 
3215
                unit->first_select()->context.outer_context;
3216
  }
3217
3218
  select_lex->master_unit()->global_parameters= select_lex;
3219
  select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
3220
  lex->current_select= select_lex;
3221
  /*
3222
    in subquery is SELECT query and we allow resolution of names in SELECT
3223
    list
3224
  */
3225
  select_lex->context.resolve_in_select_list= TRUE;
3226
  DBUG_RETURN(0);
3227
}
3228
3229
/**
3230
  Create a select to return the same output as 'SELECT @@var_name'.
3231
3232
  Used for SHOW COUNT(*) [ WARNINGS | ERROR].
3233
3234
  This will crash with a core dump if the variable doesn't exists.
3235
3236
  @param var_name		Variable name
3237
*/
3238
3239
void create_select_for_variable(const char *var_name)
3240
{
3241
  THD *thd;
3242
  LEX *lex;
3243
  LEX_STRING tmp, null_lex_string;
3244
  Item *var;
3245
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
3246
  DBUG_ENTER("create_select_for_variable");
3247
3248
  thd= current_thd;
3249
  lex= thd->lex;
3250
  mysql_init_select(lex);
3251
  lex->sql_command= SQLCOM_SELECT;
3252
  tmp.str= (char*) var_name;
3253
  tmp.length=strlen(var_name);
3254
  bzero((char*) &null_lex_string.str, sizeof(null_lex_string));
3255
  /*
3256
    We set the name of Item to @@session.var_name because that then is used
3257
    as the column name in the output.
3258
  */
3259
  if ((var= get_system_var(thd, OPT_SESSION, tmp, null_lex_string)))
3260
  {
3261
    end= strxmov(buff, "@@session.", var_name, NullS);
3262
    var->set_name(buff, end-buff, system_charset_info);
3263
    add_item_to_list(thd, var);
3264
  }
3265
  DBUG_VOID_RETURN;
3266
}
3267
3268
3269
void mysql_init_multi_delete(LEX *lex)
3270
{
3271
  lex->sql_command=  SQLCOM_DELETE_MULTI;
3272
  mysql_init_select(lex);
3273
  lex->select_lex.select_limit= 0;
3274
  lex->unit.select_limit_cnt= HA_POS_ERROR;
3275
  lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list);
3276
  lex->lock_option= using_update_log ? TL_READ_NO_INSERT : TL_READ;
3277
  lex->query_tables= 0;
3278
  lex->query_tables_last= &lex->query_tables;
3279
}
3280
3281
3282
/*
3283
  When you modify mysql_parse(), you may need to mofify
3284
  mysql_test_parse_for_slave() in this same file.
3285
*/
3286
3287
/**
3288
  Parse a query.
3289
3290
  @param       thd     Current thread
3291
  @param       inBuf   Begining of the query text
3292
  @param       length  Length of the query text
3293
  @param[out]  found_semicolon For multi queries, position of the character of
3294
                               the next query in the query text.
3295
*/
3296
3297
void mysql_parse(THD *thd, const char *inBuf, uint length,
3298
                 const char ** found_semicolon)
3299
{
3300
  DBUG_ENTER("mysql_parse");
3301
3302
  DBUG_EXECUTE_IF("parser_debug", turn_parser_debug_on(););
3303
3304
  /*
3305
    Warning.
3306
    The purpose of query_cache_send_result_to_client() is to lookup the
3307
    query in the query cache first, to avoid parsing and executing it.
3308
    So, the natural implementation would be to:
3309
    - first, call query_cache_send_result_to_client,
3310
    - second, if caching failed, initialise the lexical and syntactic parser.
3311
    The problem is that the query cache depends on a clean initialization
3312
    of (among others) lex->safe_to_cache_query and thd->server_status,
3313
    which are reset respectively in
3314
    - lex_start()
3315
    - mysql_reset_thd_for_next_command()
3316
    So, initializing the lexical analyser *before* using the query cache
3317
    is required for the cache to work properly.
3318
    FIXME: cleanup the dependencies in the code to simplify this.
3319
  */
3320
  lex_start(thd);
3321
  mysql_reset_thd_for_next_command(thd);
3322
3323
  {
3324
    LEX *lex= thd->lex;
3325
3326
    Lex_input_stream lip(thd, inBuf, length);
3327
3328
    bool err= parse_sql(thd, &lip, NULL);
3329
    *found_semicolon= lip.found_semicolon;
3330
3331
    if (!err)
3332
    {
3333
      {
3334
	if (! thd->is_error())
3335
	{
3336
          /*
3337
            Binlog logs a string starting from thd->query and having length
3338
            thd->query_length; so we set thd->query_length correctly (to not
3339
            log several statements in one event, when we executed only first).
3340
            We set it to not see the ';' (otherwise it would get into binlog
3341
            and Query_log_event::print() would give ';;' output).
3342
            This also helps display only the current query in SHOW
3343
            PROCESSLIST.
3344
            Note that we don't need LOCK_thread_count to modify query_length.
3345
          */
3346
          if (*found_semicolon &&
3347
              (thd->query_length= (ulong)(*found_semicolon - thd->query)))
3348
            thd->query_length--;
3349
          /* Actually execute the query */
3350
          mysql_execute_command(thd);
3351
	}
3352
      }
3353
    }
3354
    else
3355
    {
3356
      DBUG_ASSERT(thd->is_error());
3357
      DBUG_PRINT("info",("Command aborted. Fatal_error: %d",
3358
			 thd->is_fatal_error));
3359
    }
3360
    lex->unit.cleanup();
3361
    thd_proc_info(thd, "freeing items");
3362
    thd->end_statement();
3363
    thd->cleanup_after_query();
3364
    DBUG_ASSERT(thd->change_list.is_empty());
3365
  }
3366
3367
  DBUG_VOID_RETURN;
3368
}
3369
3370
3371
#ifdef HAVE_REPLICATION
3372
/*
3373
  Usable by the replication SQL thread only: just parse a query to know if it
3374
  can be ignored because of replicate-*-table rules.
3375
3376
  @retval
3377
    0	cannot be ignored
3378
  @retval
3379
    1	can be ignored
3380
*/
3381
3382
bool mysql_test_parse_for_slave(THD *thd, char *inBuf, uint length)
3383
{
3384
  LEX *lex= thd->lex;
3385
  bool error= 0;
3386
  DBUG_ENTER("mysql_test_parse_for_slave");
3387
3388
  Lex_input_stream lip(thd, inBuf, length);
3389
  lex_start(thd);
3390
  mysql_reset_thd_for_next_command(thd);
3391
3392
  if (!parse_sql(thd, &lip, NULL) &&
3393
      all_tables_not_ok(thd,(TABLE_LIST*) lex->select_lex.table_list.first))
3394
    error= 1;                  /* Ignore question */
3395
  thd->end_statement();
3396
  thd->cleanup_after_query();
3397
  DBUG_RETURN(error);
3398
}
3399
#endif
3400
3401
3402
3403
/**
3404
  Store field definition for create.
3405
3406
  @return
3407
    Return 0 if ok
3408
*/
3409
3410
bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum_field_types type,
3411
		       char *length, char *decimals,
3412
		       uint type_modifier,
3413
                       enum ha_storage_media storage_type,
3414
                       enum column_format_type column_format,
3415
		       Item *default_value, Item *on_update_value,
3416
                       LEX_STRING *comment,
3417
		       char *change,
3418
                       List<String> *interval_list, CHARSET_INFO *cs)
3419
{
3420
  register Create_field *new_field;
3421
  LEX  *lex= thd->lex;
3422
  DBUG_ENTER("add_field_to_list");
3423
3424
  if (check_identifier_name(field_name, ER_TOO_LONG_IDENT))
3425
    DBUG_RETURN(1);				/* purecov: inspected */
3426
3427
  if (type_modifier & PRI_KEY_FLAG)
3428
  {
3429
    Key *key;
3430
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
3431
    key= new Key(Key::PRIMARY, null_lex_str,
3432
                      &default_key_create_info,
3433
                      0, lex->col_list);
3434
    lex->alter_info.key_list.push_back(key);
3435
    lex->col_list.empty();
3436
  }
3437
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
3438
  {
3439
    Key *key;
3440
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
3441
    key= new Key(Key::UNIQUE, null_lex_str,
3442
                 &default_key_create_info, 0,
3443
                 lex->col_list);
3444
    lex->alter_info.key_list.push_back(key);
3445
    lex->col_list.empty();
3446
  }
3447
3448
  if (default_value)
3449
  {
3450
    /* 
3451
      Default value should be literal => basic constants =>
3452
      no need fix_fields()
3453
      
3454
      We allow only one function as part of default value - 
3455
      NOW() as default for TIMESTAMP type.
3456
    */
3457
    if (default_value->type() == Item::FUNC_ITEM && 
3458
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
3459
         type == MYSQL_TYPE_TIMESTAMP))
3460
    {
3461
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
3462
      DBUG_RETURN(1);
3463
    }
3464
    else if (default_value->type() == Item::NULL_ITEM)
3465
    {
3466
      default_value= 0;
3467
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
3468
	  NOT_NULL_FLAG)
3469
      {
3470
	my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
3471
	DBUG_RETURN(1);
3472
      }
3473
    }
3474
    else if (type_modifier & AUTO_INCREMENT_FLAG)
3475
    {
3476
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
3477
      DBUG_RETURN(1);
3478
    }
3479
  }
3480
3481
  if (on_update_value && type != MYSQL_TYPE_TIMESTAMP)
3482
  {
3483
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
3484
    DBUG_RETURN(1);
3485
  }
3486
3487
  if (!(new_field= new Create_field()) ||
3488
      new_field->init(thd, field_name->str, type, length, decimals, type_modifier,
3489
                      default_value, on_update_value, comment, change,
3490
                      interval_list, cs, 0,
3491
                      storage_type, column_format))
3492
    DBUG_RETURN(1);
3493
3494
  lex->alter_info.create_list.push_back(new_field);
3495
  lex->last_field=new_field;
3496
  DBUG_RETURN(0);
3497
}
3498
3499
3500
/** Store position for column in ALTER TABLE .. ADD column. */
3501
3502
void store_position_for_column(const char *name)
3503
{
3504
  current_thd->lex->last_field->after=my_const_cast(char*) (name);
3505
}
3506
3507
bool
3508
add_proc_to_list(THD* thd, Item *item)
3509
{
3510
  ORDER *order;
3511
  Item	**item_ptr;
3512
3513
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*))))
3514
    return 1;
3515
  item_ptr = (Item**) (order+1);
3516
  *item_ptr= item;
3517
  order->item=item_ptr;
3518
  order->free_me=0;
3519
  thd->lex->proc_list.link_in_list((uchar*) order,(uchar**) &order->next);
3520
  return 0;
3521
}
3522
3523
3524
/**
3525
  save order by and tables in own lists.
3526
*/
3527
3528
bool add_to_list(THD *thd, SQL_LIST &list,Item *item,bool asc)
3529
{
3530
  ORDER *order;
3531
  DBUG_ENTER("add_to_list");
3532
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER))))
3533
    DBUG_RETURN(1);
3534
  order->item_ptr= item;
3535
  order->item= &order->item_ptr;
3536
  order->asc = asc;
3537
  order->free_me=0;
3538
  order->used=0;
3539
  order->counter_used= 0;
3540
  list.link_in_list((uchar*) order,(uchar**) &order->next);
3541
  DBUG_RETURN(0);
3542
}
3543
3544
3545
/**
3546
  Add a table to list of used tables.
3547
3548
  @param table		Table to add
3549
  @param alias		alias for table (or null if no alias)
3550
  @param table_options	A set of the following bits:
3551
                         - TL_OPTION_UPDATING : Table will be updated
3552
                         - TL_OPTION_FORCE_INDEX : Force usage of index
3553
                         - TL_OPTION_ALIAS : an alias in multi table DELETE
3554
  @param lock_type	How table should be locked
3555
  @param use_index	List of indexed used in USE INDEX
3556
  @param ignore_index	List of indexed used in IGNORE INDEX
3557
3558
  @retval
3559
      0		Error
3560
  @retval
3561
    \#	Pointer to TABLE_LIST element added to the total table list
3562
*/
3563
3564
TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
3565
					     Table_ident *table,
3566
					     LEX_STRING *alias,
3567
					     ulong table_options,
3568
					     thr_lock_type lock_type,
3569
					     List<Index_hint> *index_hints_arg,
3570
                                             LEX_STRING *option)
3571
{
3572
  register TABLE_LIST *ptr;
3573
  TABLE_LIST *previous_table_ref; /* The table preceding the current one. */
3574
  char *alias_str;
3575
  LEX *lex= thd->lex;
3576
  DBUG_ENTER("add_table_to_list");
3577
3578
  if (!table)
3579
    DBUG_RETURN(0);				// End of memory
3580
  alias_str= alias ? alias->str : table->table.str;
3581
  if (!test(table_options & TL_OPTION_ALIAS) && 
3582
      check_table_name(table->table.str, table->table.length))
3583
  {
3584
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
3585
    DBUG_RETURN(0);
3586
  }
3587
3588
  if (table->is_derived_table() == FALSE && table->db.str &&
3589
      check_db_name(&table->db))
3590
  {
3591
    my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
3592
    DBUG_RETURN(0);
3593
  }
3594
3595
  if (!alias)					/* Alias is case sensitive */
3596
  {
3597
    if (table->sel)
3598
    {
3599
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
3600
                 ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
3601
      DBUG_RETURN(0);
3602
    }
3603
    if (!(alias_str= (char*) thd->memdup(alias_str,table->table.length+1)))
3604
      DBUG_RETURN(0);
3605
  }
3606
  if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST))))
3607
    DBUG_RETURN(0);				/* purecov: inspected */
3608
  if (table->db.str)
3609
  {
3610
    ptr->is_fqtn= TRUE;
3611
    ptr->db= table->db.str;
3612
    ptr->db_length= table->db.length;
3613
  }
3614
  else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
3615
    DBUG_RETURN(0);
3616
  else
3617
    ptr->is_fqtn= FALSE;
3618
3619
  ptr->alias= alias_str;
3620
  ptr->is_alias= alias ? TRUE : FALSE;
3621
  if (lower_case_table_names && table->table.length)
3622
    table->table.length= my_casedn_str(files_charset_info, table->table.str);
3623
  ptr->table_name=table->table.str;
3624
  ptr->table_name_length=table->table.length;
3625
  ptr->lock_type=   lock_type;
3626
  ptr->lock_timeout= -1;      /* default timeout */
3627
  ptr->lock_transactional= 1; /* allow transactional locks */
3628
  ptr->updating=    test(table_options & TL_OPTION_UPDATING);
3629
  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
3630
  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
3631
  ptr->derived=	    table->sel;
3632
  if (!ptr->derived && !my_strcasecmp(system_charset_info, ptr->db,
3633
                                      INFORMATION_SCHEMA_NAME.str))
3634
  {
3635
    ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, ptr->table_name);
3636
    if (!schema_table ||
3637
        (schema_table->hidden && 
3638
         ((sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0 || 
3639
          /*
3640
            this check is used for show columns|keys from I_S hidden table
3641
          */
3642
          lex->sql_command == SQLCOM_SHOW_FIELDS ||
3643
          lex->sql_command == SQLCOM_SHOW_KEYS)))
3644
    {
3645
      my_error(ER_UNKNOWN_TABLE, MYF(0),
3646
               ptr->table_name, INFORMATION_SCHEMA_NAME.str);
3647
      DBUG_RETURN(0);
3648
    }
3649
    ptr->schema_table_name= ptr->table_name;
3650
    ptr->schema_table= schema_table;
3651
  }
3652
  ptr->select_lex=  lex->current_select;
3653
  ptr->cacheable_table= 1;
3654
  ptr->index_hints= index_hints_arg;
3655
  ptr->option= option ? option->str : 0;
3656
  /* check that used name is unique */
3657
  if (lock_type != TL_IGNORE)
3658
  {
3659
    TABLE_LIST *first_table= (TABLE_LIST*) table_list.first;
3660
    for (TABLE_LIST *tables= first_table ;
3661
	 tables ;
3662
	 tables=tables->next_local)
3663
    {
3664
      if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
3665
	  !strcmp(ptr->db, tables->db))
3666
      {
3667
	my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
3668
	DBUG_RETURN(0);				/* purecov: tested */
3669
      }
3670
    }
3671
  }
3672
  /* Store the table reference preceding the current one. */
3673
  if (table_list.elements > 0)
3674
  {
3675
    /*
3676
      table_list.next points to the last inserted TABLE_LIST->next_local'
3677
      element
3678
      We don't use the offsetof() macro here to avoid warnings from gcc
3679
    */
3680
    previous_table_ref= (TABLE_LIST*) ((char*) table_list.next -
3681
                                       ((char*) &(ptr->next_local) -
3682
                                        (char*) ptr));
3683
    /*
3684
      Set next_name_resolution_table of the previous table reference to point
3685
      to the current table reference. In effect the list
3686
      TABLE_LIST::next_name_resolution_table coincides with
3687
      TABLE_LIST::next_local. Later this may be changed in
3688
      store_top_level_join_columns() for NATURAL/USING joins.
3689
    */
3690
    previous_table_ref->next_name_resolution_table= ptr;
3691
  }
3692
3693
  /*
3694
    Link the current table reference in a local list (list for current select).
3695
    Notice that as a side effect here we set the next_local field of the
3696
    previous table reference to 'ptr'. Here we also add one element to the
3697
    list 'table_list'.
3698
  */
3699
  table_list.link_in_list((uchar*) ptr, (uchar**) &ptr->next_local);
3700
  ptr->next_name_resolution_table= NULL;
3701
  /* Link table in global list (all used tables) */
3702
  lex->add_to_query_tables(ptr);
3703
  DBUG_RETURN(ptr);
3704
}
3705
3706
3707
/**
3708
  Initialize a new table list for a nested join.
3709
3710
    The function initializes a structure of the TABLE_LIST type
3711
    for a nested join. It sets up its nested join list as empty.
3712
    The created structure is added to the front of the current
3713
    join list in the st_select_lex object. Then the function
3714
    changes the current nest level for joins to refer to the newly
3715
    created empty list after having saved the info on the old level
3716
    in the initialized structure.
3717
3718
  @param thd         current thread
3719
3720
  @retval
3721
    0   if success
3722
  @retval
3723
    1   otherwise
3724
*/
3725
3726
bool st_select_lex::init_nested_join(THD *thd)
3727
{
3728
  TABLE_LIST *ptr;
3729
  NESTED_JOIN *nested_join;
3730
  DBUG_ENTER("init_nested_join");
3731
3732
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
3733
                                       sizeof(NESTED_JOIN))))
3734
    DBUG_RETURN(1);
3735
  nested_join= ptr->nested_join=
3736
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
3737
3738
  join_list->push_front(ptr);
3739
  ptr->embedding= embedding;
3740
  ptr->join_list= join_list;
3741
  ptr->alias= (char*) "(nested_join)";
3742
  embedding= ptr;
3743
  join_list= &nested_join->join_list;
3744
  join_list->empty();
3745
  DBUG_RETURN(0);
3746
}
3747
3748
3749
/**
3750
  End a nested join table list.
3751
3752
    The function returns to the previous join nest level.
3753
    If the current level contains only one member, the function
3754
    moves it one level up, eliminating the nest.
3755
3756
  @param thd         current thread
3757
3758
  @return
3759
    - Pointer to TABLE_LIST element added to the total table list, if success
3760
    - 0, otherwise
3761
*/
3762
3763
TABLE_LIST *st_select_lex::end_nested_join(THD *thd)
3764
{
3765
  TABLE_LIST *ptr;
3766
  NESTED_JOIN *nested_join;
3767
  DBUG_ENTER("end_nested_join");
3768
3769
  DBUG_ASSERT(embedding);
3770
  ptr= embedding;
3771
  join_list= ptr->join_list;
3772
  embedding= ptr->embedding;
3773
  nested_join= ptr->nested_join;
3774
  if (nested_join->join_list.elements == 1)
3775
  {
3776
    TABLE_LIST *embedded= nested_join->join_list.head();
3777
    join_list->pop();
3778
    embedded->join_list= join_list;
3779
    embedded->embedding= embedding;
3780
    join_list->push_front(embedded);
3781
    ptr= embedded;
3782
  }
3783
  else if (nested_join->join_list.elements == 0)
3784
  {
3785
    join_list->pop();
3786
    ptr= 0;                                     // return value
3787
  }
3788
  DBUG_RETURN(ptr);
3789
}
3790
3791
3792
/**
3793
  Nest last join operation.
3794
3795
    The function nest last join operation as if it was enclosed in braces.
3796
3797
  @param thd         current thread
3798
3799
  @retval
3800
    0  Error
3801
  @retval
3802
    \#  Pointer to TABLE_LIST element created for the new nested join
3803
*/
3804
3805
TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
3806
{
3807
  TABLE_LIST *ptr;
3808
  NESTED_JOIN *nested_join;
3809
  List<TABLE_LIST> *embedded_list;
3810
  DBUG_ENTER("nest_last_join");
3811
3812
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
3813
                                       sizeof(NESTED_JOIN))))
3814
    DBUG_RETURN(0);
3815
  nested_join= ptr->nested_join=
3816
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
3817
3818
  ptr->embedding= embedding;
3819
  ptr->join_list= join_list;
3820
  ptr->alias= (char*) "(nest_last_join)";
3821
  embedded_list= &nested_join->join_list;
3822
  embedded_list->empty();
3823
3824
  for (uint i=0; i < 2; i++)
3825
  {
3826
    TABLE_LIST *table= join_list->pop();
3827
    table->join_list= embedded_list;
3828
    table->embedding= ptr;
3829
    embedded_list->push_back(table);
3830
    if (table->natural_join)
3831
    {
3832
      ptr->is_natural_join= TRUE;
3833
      /*
3834
        If this is a JOIN ... USING, move the list of joined fields to the
3835
        table reference that describes the join.
3836
      */
3837
      if (prev_join_using)
3838
        ptr->join_using_fields= prev_join_using;
3839
    }
3840
  }
3841
  join_list->push_front(ptr);
3842
  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
3843
  DBUG_RETURN(ptr);
3844
}
3845
3846
3847
/**
3848
  Add a table to the current join list.
3849
3850
    The function puts a table in front of the current join list
3851
    of st_select_lex object.
3852
    Thus, joined tables are put into this list in the reverse order
3853
    (the most outer join operation follows first).
3854
3855
  @param table       the table to add
3856
3857
  @return
3858
    None
3859
*/
3860
3861
void st_select_lex::add_joined_table(TABLE_LIST *table)
3862
{
3863
  DBUG_ENTER("add_joined_table");
3864
  join_list->push_front(table);
3865
  table->join_list= join_list;
3866
  table->embedding= embedding;
3867
  DBUG_VOID_RETURN;
3868
}
3869
3870
3871
/**
3872
  Convert a right join into equivalent left join.
3873
3874
    The function takes the current join list t[0],t[1] ... and
3875
    effectively converts it into the list t[1],t[0] ...
3876
    Although the outer_join flag for the new nested table contains
3877
    JOIN_TYPE_RIGHT, it will be handled as the inner table of a left join
3878
    operation.
3879
3880
  EXAMPLES
3881
  @verbatim
3882
    SELECT * FROM t1 RIGHT JOIN t2 ON on_expr =>
3883
      SELECT * FROM t2 LEFT JOIN t1 ON on_expr
3884
3885
    SELECT * FROM t1,t2 RIGHT JOIN t3 ON on_expr =>
3886
      SELECT * FROM t1,t3 LEFT JOIN t2 ON on_expr
3887
3888
    SELECT * FROM t1,t2 RIGHT JOIN (t3,t4) ON on_expr =>
3889
      SELECT * FROM t1,(t3,t4) LEFT JOIN t2 ON on_expr
3890
3891
    SELECT * FROM t1 LEFT JOIN t2 ON on_expr1 RIGHT JOIN t3  ON on_expr2 =>
3892
      SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1
3893
   @endverbatim
3894
3895
  @param thd         current thread
3896
3897
  @return
3898
    - Pointer to the table representing the inner table, if success
3899
    - 0, otherwise
3900
*/
3901
3902
TABLE_LIST *st_select_lex::convert_right_join()
3903
{
3904
  TABLE_LIST *tab2= join_list->pop();
3905
  TABLE_LIST *tab1= join_list->pop();
3906
  DBUG_ENTER("convert_right_join");
3907
3908
  join_list->push_front(tab2);
3909
  join_list->push_front(tab1);
3910
  tab1->outer_join|= JOIN_TYPE_RIGHT;
3911
3912
  DBUG_RETURN(tab1);
3913
}
3914
3915
/**
3916
  Set lock for all tables in current select level.
3917
3918
  @param lock_type			Lock to set for tables
3919
3920
  @note
3921
    If lock is a write lock, then tables->updating is set 1
3922
    This is to get tables_ok to know that the table is updated by the
3923
    query
3924
*/
3925
3926
void st_select_lex::set_lock_for_tables(thr_lock_type lock_type)
3927
{
3928
  bool for_update= lock_type >= TL_READ_NO_INSERT;
3929
  DBUG_ENTER("set_lock_for_tables");
3930
  DBUG_PRINT("enter", ("lock_type: %d  for_update: %d", lock_type,
3931
		       for_update));
3932
3933
  for (TABLE_LIST *tables= (TABLE_LIST*) table_list.first;
3934
       tables;
3935
       tables= tables->next_local)
3936
  {
3937
    tables->lock_type= lock_type;
3938
    tables->updating=  for_update;
3939
  }
3940
  DBUG_VOID_RETURN;
3941
}
3942
3943
3944
/**
3945
  Create a fake SELECT_LEX for a unit.
3946
3947
    The method create a fake SELECT_LEX object for a unit.
3948
    This object is created for any union construct containing a union
3949
    operation and also for any single select union construct of the form
3950
    @verbatim
3951
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ... 
3952
    @endvarbatim
3953
    or of the form
3954
    @varbatim
3955
    (SELECT ... ORDER BY LIMIT n) ORDER BY ...
3956
    @endvarbatim
3957
  
3958
  @param thd_arg		   thread handle
3959
3960
  @note
3961
    The object is used to retrieve rows from the temporary table
3962
    where the result on the union is obtained.
3963
3964
  @retval
3965
    1     on failure to create the object
3966
  @retval
3967
    0     on success
3968
*/
3969
3970
bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg)
3971
{
3972
  SELECT_LEX *first_sl= first_select();
3973
  DBUG_ENTER("add_fake_select_lex");
3974
  DBUG_ASSERT(!fake_select_lex);
3975
3976
  if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX()))
3977
      DBUG_RETURN(1);
3978
  fake_select_lex->include_standalone(this, 
3979
                                      (SELECT_LEX_NODE**)&fake_select_lex);
3980
  fake_select_lex->select_number= INT_MAX;
3981
  fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */
3982
  fake_select_lex->make_empty_select();
3983
  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
3984
  fake_select_lex->select_limit= 0;
3985
3986
  fake_select_lex->context.outer_context=first_sl->context.outer_context;
3987
  /* allow item list resolving in fake select for ORDER BY */
3988
  fake_select_lex->context.resolve_in_select_list= TRUE;
3989
  fake_select_lex->context.select_lex= fake_select_lex;
3990
3991
  if (!is_union())
3992
  {
3993
    /* 
3994
      This works only for 
3995
      (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
3996
      (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
3997
      just before the parser starts processing order_list
3998
    */ 
3999
    global_parameters= fake_select_lex;
4000
    fake_select_lex->no_table_names_allowed= 1;
4001
    thd_arg->lex->current_select= fake_select_lex;
4002
  }
4003
  thd_arg->lex->pop_context();
4004
  DBUG_RETURN(0);
4005
}
4006
4007
4008
/**
4009
  Push a new name resolution context for a JOIN ... ON clause to the
4010
  context stack of a query block.
4011
4012
    Create a new name resolution context for a JOIN ... ON clause,
4013
    set the first and last leaves of the list of table references
4014
    to be used for name resolution, and push the newly created
4015
    context to the stack of contexts of the query.
4016
4017
  @param thd       pointer to current thread
4018
  @param left_op   left  operand of the JOIN
4019
  @param right_op  rigth operand of the JOIN
4020
4021
  @retval
4022
    FALSE  if all is OK
4023
  @retval
4024
    TRUE   if a memory allocation error occured
4025
*/
4026
4027
bool
4028
push_new_name_resolution_context(THD *thd,
4029
                                 TABLE_LIST *left_op, TABLE_LIST *right_op)
4030
{
4031
  Name_resolution_context *on_context;
4032
  if (!(on_context= new (thd->mem_root) Name_resolution_context))
4033
    return TRUE;
4034
  on_context->init();
4035
  on_context->first_name_resolution_table=
4036
    left_op->first_leaf_for_name_resolution();
4037
  on_context->last_name_resolution_table=
4038
    right_op->last_leaf_for_name_resolution();
4039
  return thd->lex->push_context(on_context);
4040
}
4041
4042
4043
/**
4044
  Add an ON condition to the second operand of a JOIN ... ON.
4045
4046
    Add an ON condition to the right operand of a JOIN ... ON clause.
4047
4048
  @param b     the second operand of a JOIN ... ON
4049
  @param expr  the condition to be added to the ON clause
4050
4051
  @retval
4052
    FALSE  if there was some error
4053
  @retval
4054
    TRUE   if all is OK
4055
*/
4056
4057
void add_join_on(TABLE_LIST *b, Item *expr)
4058
{
4059
  if (expr)
4060
  {
4061
    if (!b->on_expr)
4062
      b->on_expr= expr;
4063
    else
4064
    {
4065
      /*
4066
        If called from the parser, this happens if you have both a
4067
        right and left join. If called later, it happens if we add more
4068
        than one condition to the ON clause.
4069
      */
4070
      b->on_expr= new Item_cond_and(b->on_expr,expr);
4071
    }
4072
    b->on_expr->top_level_item();
4073
  }
4074
}
4075
4076
4077
/**
4078
  Mark that there is a NATURAL JOIN or JOIN ... USING between two
4079
  tables.
4080
4081
    This function marks that table b should be joined with a either via
4082
    a NATURAL JOIN or via JOIN ... USING. Both join types are special
4083
    cases of each other, so we treat them together. The function
4084
    setup_conds() creates a list of equal condition between all fields
4085
    of the same name for NATURAL JOIN or the fields in 'using_fields'
4086
    for JOIN ... USING. The list of equality conditions is stored
4087
    either in b->on_expr, or in JOIN::conds, depending on whether there
4088
    was an outer join.
4089
4090
  EXAMPLE
4091
  @verbatim
4092
    SELECT * FROM t1 NATURAL LEFT JOIN t2
4093
     <=>
4094
    SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
4095
4096
    SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond>
4097
     <=>
4098
    SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>)
4099
4100
    SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
4101
     <=>
4102
    SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
4103
   @endverbatim
4104
4105
  @param a		  Left join argument
4106
  @param b		  Right join argument
4107
  @param using_fields    Field names from USING clause
4108
*/
4109
4110
void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields,
4111
                      SELECT_LEX *lex)
4112
{
4113
  b->natural_join= a;
4114
  lex->prev_join_using= using_fields;
4115
}
4116
4117
4118
/**
4119
  Reload/resets privileges and the different caches.
4120
4121
  @param thd Thread handler (can be NULL!)
4122
  @param options What should be reset/reloaded (tables, privileges, slave...)
4123
  @param tables Tables to flush (if any)
4124
  @param write_to_binlog True if we can write to the binlog.
4125
               
4126
  @note Depending on 'options', it may be very bad to write the
4127
    query to the binlog (e.g. FLUSH SLAVE); this is a
4128
    pointer where reload_cache() will put 0 if
4129
    it thinks we really should not write to the binlog.
4130
    Otherwise it will put 1.
4131
4132
  @return Error status code
4133
    @retval 0 Ok
4134
    @retval !=0  Error; thd->killed is set or thd->is_error() is true
4135
*/
4136
4137
bool reload_cache(THD *thd, ulong options, TABLE_LIST *tables,
4138
                          bool *write_to_binlog)
4139
{
4140
  bool result=0;
4141
  select_errors=0;				/* Write if more errors */
4142
  bool tmp_write_to_binlog= 1;
4143
4144
  DBUG_ASSERT(!thd || !thd->in_sub_stmt);
4145
4146
  if (options & REFRESH_LOG)
4147
  {
4148
    /*
4149
      Flush the normal query log, the update log, the binary log,
4150
      the slow query log, the relay log (if it exists) and the log
4151
      tables.
4152
    */
4153
4154
    /*
4155
      Writing this command to the binlog may result in infinite loops
4156
      when doing mysqlbinlog|mysql, and anyway it does not really make
4157
      sense to log it automatically (would cause more trouble to users
4158
      than it would help them)
4159
    */
4160
    tmp_write_to_binlog= 0;
4161
    if( mysql_bin_log.is_open() )
4162
    {
4163
      mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
4164
    }
4165
    pthread_mutex_lock(&LOCK_active_mi);
4166
    rotate_relay_log(active_mi);
4167
    pthread_mutex_unlock(&LOCK_active_mi);
4168
4169
    /* flush slow and general logs */
4170
    logger.flush_logs(thd);
4171
4172
    if (ha_flush_logs(NULL))
4173
      result=1;
4174
    if (flush_error_log())
4175
      result=1;
4176
  }
4177
  /*
4178
    Note that if REFRESH_READ_LOCK bit is set then REFRESH_TABLES is set too
4179
    (see sql_yacc.yy)
4180
  */
4181
  if (options & (REFRESH_TABLES | REFRESH_READ_LOCK)) 
4182
  {
4183
    if ((options & REFRESH_READ_LOCK) && thd)
4184
    {
4185
      /*
4186
        We must not try to aspire a global read lock if we have a write
4187
        locked table. This would lead to a deadlock when trying to
4188
        reopen (and re-lock) the table after the flush.
4189
      */
4190
      if (thd->locked_tables)
4191
      {
4192
        THR_LOCK_DATA **lock_p= thd->locked_tables->locks;
4193
        THR_LOCK_DATA **end_p= lock_p + thd->locked_tables->lock_count;
4194
4195
        for (; lock_p < end_p; lock_p++)
4196
        {
4197
          if ((*lock_p)->type >= TL_WRITE_ALLOW_WRITE)
4198
          {
4199
            my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
4200
            return 1;
4201
          }
4202
        }
4203
      }
4204
      /*
4205
	Writing to the binlog could cause deadlocks, as we don't log
4206
	UNLOCK TABLES
4207
      */
4208
      tmp_write_to_binlog= 0;
4209
      if (lock_global_read_lock(thd))
4210
	return 1;                               // Killed
4211
      result= close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ?
4212
                                  FALSE : TRUE, TRUE);
4213
      if (make_global_read_lock_block_commit(thd)) // Killed
4214
      {
4215
        /* Don't leave things in a half-locked state */
4216
        unlock_global_read_lock(thd);
4217
        return 1;
4218
      }
4219
    }
4220
    else
4221
      result= close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ?
4222
                                  FALSE : TRUE, FALSE);
4223
    my_dbopt_cleanup();
4224
  }
4225
  if (thd && (options & REFRESH_STATUS))
4226
    refresh_status(thd);
4227
  if (options & REFRESH_THREADS)
4228
    flush_thread_cache();
4229
  if (options & REFRESH_MASTER)
4230
  {
4231
    DBUG_ASSERT(thd);
4232
    tmp_write_to_binlog= 0;
4233
    if (reset_master(thd))
4234
    {
4235
      result=1;
4236
    }
4237
  }
4238
 if (options & REFRESH_SLAVE)
4239
 {
4240
   tmp_write_to_binlog= 0;
4241
   pthread_mutex_lock(&LOCK_active_mi);
4242
   if (reset_slave(thd, active_mi))
4243
     result=1;
4244
   pthread_mutex_unlock(&LOCK_active_mi);
4245
 }
4246
 *write_to_binlog= tmp_write_to_binlog;
4247
 return result;
4248
}
4249
4250
4251
/**
4252
  kill on thread.
4253
4254
  @param thd			Thread class
4255
  @param id			Thread id
4256
  @param only_kill_query        Should it kill the query or the connection
4257
4258
  @note
4259
    This is written such that we have a short lock on LOCK_thread_count
4260
*/
4261
4262
uint kill_one_thread(THD *thd, ulong id, bool only_kill_query)
4263
{
4264
  THD *tmp;
4265
  uint error=ER_NO_SUCH_THREAD;
4266
  DBUG_ENTER("kill_one_thread");
4267
  DBUG_PRINT("enter", ("id=%lu only_kill=%d", id, only_kill_query));
4268
  VOID(pthread_mutex_lock(&LOCK_thread_count)); // For unlink from list
4269
  I_List_iterator<THD> it(threads);
4270
  while ((tmp=it++))
4271
  {
4272
    if (tmp->command == COM_DAEMON)
4273
      continue;
4274
    if (tmp->thread_id == id)
4275
    {
4276
      pthread_mutex_lock(&tmp->LOCK_delete);	// Lock from delete
4277
      break;
4278
    }
4279
  }
4280
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
4281
  if (tmp)
4282
  {
4283
    tmp->awake(only_kill_query ? THD::KILL_QUERY : THD::KILL_CONNECTION);
4284
    error=0;
4285
    pthread_mutex_unlock(&tmp->LOCK_delete);
4286
  }
4287
  DBUG_PRINT("exit", ("%d", error));
4288
  DBUG_RETURN(error);
4289
}
4290
4291
4292
/*
4293
  kills a thread and sends response
4294
4295
  SYNOPSIS
4296
    sql_kill()
4297
    thd			Thread class
4298
    id			Thread id
4299
    only_kill_query     Should it kill the query or the connection
4300
*/
4301
4302
void sql_kill(THD *thd, ulong id, bool only_kill_query)
4303
{
4304
  uint error;
4305
  if (!(error= kill_one_thread(thd, id, only_kill_query)))
4306
    my_ok(thd);
4307
  else
4308
    my_error(error, MYF(0), id);
4309
}
4310
4311
4312
/** If pointer is not a null pointer, append filename to it. */
4313
4314
bool append_file_to_dir(THD *thd, const char **filename_ptr,
4315
                        const char *table_name)
4316
{
4317
  char buff[FN_REFLEN],*ptr, *end;
4318
  if (!*filename_ptr)
4319
    return 0;					// nothing to do
4320
4321
  /* Check that the filename is not too long and it's a hard path */
4322
  if (strlen(*filename_ptr)+strlen(table_name) >= FN_REFLEN-1 ||
4323
      !test_if_hard_path(*filename_ptr))
4324
  {
4325
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
4326
    return 1;
4327
  }
4328
  /* Fix is using unix filename format on dos */
4329
  strmov(buff,*filename_ptr);
4330
  end=convert_dirname(buff, *filename_ptr, NullS);
4331
  if (!(ptr= (char*) thd->alloc((size_t) (end-buff) + strlen(table_name)+1)))
4332
    return 1;					// End of memory
4333
  *filename_ptr=ptr;
4334
  strxmov(ptr,buff,table_name,NullS);
4335
  return 0;
4336
}
4337
4338
4339
/**
4340
  Check if the select is a simple select (not an union).
4341
4342
  @retval
4343
    0	ok
4344
  @retval
4345
    1	error	; In this case the error messege is sent to the client
4346
*/
4347
4348
bool check_simple_select()
4349
{
4350
  THD *thd= current_thd;
4351
  LEX *lex= thd->lex;
4352
  if (lex->current_select != &lex->select_lex)
4353
  {
4354
    char command[80];
4355
    Lex_input_stream *lip= thd->m_lip;
4356
    strmake(command, lip->yylval->symbol.str,
4357
	    min(lip->yylval->symbol.length, sizeof(command)-1));
4358
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
4359
    return 1;
4360
  }
4361
  return 0;
4362
}
4363
4364
4365
Comp_creator *comp_eq_creator(bool invert)
4366
{
4367
  return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
4368
}
4369
4370
4371
Comp_creator *comp_ge_creator(bool invert)
4372
{
4373
  return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator;
4374
}
4375
4376
4377
Comp_creator *comp_gt_creator(bool invert)
4378
{
4379
  return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator;
4380
}
4381
4382
4383
Comp_creator *comp_le_creator(bool invert)
4384
{
4385
  return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator;
4386
}
4387
4388
4389
Comp_creator *comp_lt_creator(bool invert)
4390
{
4391
  return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator;
4392
}
4393
4394
4395
Comp_creator *comp_ne_creator(bool invert)
4396
{
4397
  return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
4398
}
4399
4400
4401
/**
4402
  Construct ALL/ANY/SOME subquery Item.
4403
4404
  @param left_expr   pointer to left expression
4405
  @param cmp         compare function creator
4406
  @param all         true if we create ALL subquery
4407
  @param select_lex  pointer on parsed subquery structure
4408
4409
  @return
4410
    constructed Item (or 0 if out of memory)
4411
*/
4412
Item * all_any_subquery_creator(Item *left_expr,
4413
				chooser_compare_func_creator cmp,
4414
				bool all,
4415
				SELECT_LEX *select_lex)
4416
{
4417
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
4418
    return new Item_in_subselect(left_expr, select_lex);
4419
4420
  if ((cmp == &comp_ne_creator) && all)        // <> ALL <=> NOT IN
4421
    return new Item_func_not(new Item_in_subselect(left_expr, select_lex));
4422
4423
  Item_allany_subselect *it=
4424
    new Item_allany_subselect(left_expr, cmp, select_lex, all);
4425
  if (all)
4426
    return it->upper_item= new Item_func_not_all(it);	/* ALL */
4427
4428
  return it->upper_item= new Item_func_nop_all(it);      /* ANY/SOME */
4429
}
4430
4431
4432
/**
4433
  Multi update query pre-check.
4434
4435
  @param thd		Thread handler
4436
  @param tables	Global/local table list (have to be the same)
4437
4438
  @retval
4439
    FALSE OK
4440
  @retval
4441
    TRUE  Error
4442
*/
4443
4444
bool multi_update_precheck(THD *thd, TABLE_LIST *tables)
4445
{
4446
  const char *msg= 0;
4447
  LEX *lex= thd->lex;
4448
  SELECT_LEX *select_lex= &lex->select_lex;
4449
  DBUG_ENTER("multi_update_precheck");
4450
4451
  if (select_lex->item_list.elements != lex->value_list.elements)
4452
  {
4453
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
4454
    DBUG_RETURN(TRUE);
4455
  }
4456
4457
  if (select_lex->order_list.elements)
4458
    msg= "ORDER BY";
4459
  else if (select_lex->select_limit)
4460
    msg= "LIMIT";
4461
  if (msg)
4462
  {
4463
    my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
4464
    DBUG_RETURN(TRUE);
4465
  }
4466
  DBUG_RETURN(FALSE);
4467
}
4468
4469
/**
4470
  Multi delete query pre-check.
4471
4472
  @param thd			Thread handler
4473
  @param tables		Global/local table list
4474
4475
  @retval
4476
    FALSE OK
4477
  @retval
4478
    TRUE  error
4479
*/
4480
4481
bool multi_delete_precheck(THD *thd, TABLE_LIST *tables)
4482
{
4483
  SELECT_LEX *select_lex= &thd->lex->select_lex;
4484
  TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
4485
  DBUG_ENTER("multi_delete_precheck");
4486
4487
  thd->lex->query_tables_own_last= 0;
4488
  thd->lex->query_tables_own_last= save_query_tables_own_last;
4489
4490
  if ((thd->options & OPTION_SAFE_UPDATES) && !select_lex->where)
4491
  {
4492
    my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
4493
               ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
4494
    DBUG_RETURN(TRUE);
4495
  }
4496
  DBUG_RETURN(FALSE);
4497
}
4498
4499
4500
/*
4501
  Given a table in the source list, find a correspondent table in the
4502
  table references list.
4503
4504
  @param lex Pointer to LEX representing multi-delete.
4505
  @param src Source table to match.
4506
  @param ref Table references list.
4507
4508
  @remark The source table list (tables listed before the FROM clause
4509
  or tables listed in the FROM clause before the USING clause) may
4510
  contain table names or aliases that must match unambiguously one,
4511
  and only one, table in the target table list (table references list,
4512
  after FROM/USING clause).
4513
4514
  @return Matching table, NULL otherwise.
4515
*/
4516
4517
static TABLE_LIST *multi_delete_table_match(LEX *lex, TABLE_LIST *tbl,
4518
                                            TABLE_LIST *tables)
4519
{
4520
  TABLE_LIST *match= NULL;
4521
  DBUG_ENTER("multi_delete_table_match");
4522
4523
  for (TABLE_LIST *elem= tables; elem; elem= elem->next_local)
4524
  {
4525
    int cmp;
4526
4527
    if (tbl->is_fqtn && elem->is_alias)
4528
      continue; /* no match */
4529
    if (tbl->is_fqtn && elem->is_fqtn)
4530
      cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) ||
4531
           strcmp(tbl->db, elem->db);
4532
    else if (elem->is_alias)
4533
      cmp= my_strcasecmp(table_alias_charset, tbl->alias, elem->alias);
4534
    else
4535
      cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) ||
4536
           strcmp(tbl->db, elem->db);
4537
4538
    if (cmp)
4539
      continue;
4540
4541
    if (match)
4542
    {
4543
      my_error(ER_NONUNIQ_TABLE, MYF(0), elem->alias);
4544
      DBUG_RETURN(NULL);
4545
    }
4546
4547
    match= elem;
4548
  }
4549
4550
  if (!match)
4551
    my_error(ER_UNKNOWN_TABLE, MYF(0), tbl->table_name, "MULTI DELETE");
4552
4553
  DBUG_RETURN(match);
4554
}
4555
4556
4557
/**
4558
  Link tables in auxilary table list of multi-delete with corresponding
4559
  elements in main table list, and set proper locks for them.
4560
4561
  @param lex   pointer to LEX representing multi-delete
4562
4563
  @retval
4564
    FALSE   success
4565
  @retval
4566
    TRUE    error
4567
*/
4568
4569
bool multi_delete_set_locks_and_link_aux_tables(LEX *lex)
4570
{
4571
  TABLE_LIST *tables= (TABLE_LIST*)lex->select_lex.table_list.first;
4572
  TABLE_LIST *target_tbl;
4573
  DBUG_ENTER("multi_delete_set_locks_and_link_aux_tables");
4574
4575
  lex->table_count= 0;
4576
4577
  for (target_tbl= (TABLE_LIST *)lex->auxiliary_table_list.first;
4578
       target_tbl; target_tbl= target_tbl->next_local)
4579
  {
4580
    lex->table_count++;
4581
    /* All tables in aux_tables must be found in FROM PART */
4582
    TABLE_LIST *walk= multi_delete_table_match(lex, target_tbl, tables);
4583
    if (!walk)
4584
      DBUG_RETURN(TRUE);
4585
    if (!walk->derived)
4586
    {
4587
      target_tbl->table_name= walk->table_name;
4588
      target_tbl->table_name_length= walk->table_name_length;
4589
    }
4590
    walk->updating= target_tbl->updating;
4591
    walk->lock_type= target_tbl->lock_type;
4592
    target_tbl->correspondent_table= walk;	// Remember corresponding table
4593
  }
4594
  DBUG_RETURN(FALSE);
4595
}
4596
4597
4598
/**
4599
  simple UPDATE query pre-check.
4600
4601
  @param thd		Thread handler
4602
  @param tables	Global table list
4603
4604
  @retval
4605
    FALSE OK
4606
  @retval
4607
    TRUE  Error
4608
*/
4609
4610
bool update_precheck(THD *thd, TABLE_LIST *tables)
4611
{
4612
  DBUG_ENTER("update_precheck");
4613
  if (thd->lex->select_lex.item_list.elements != thd->lex->value_list.elements)
4614
  {
4615
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
4616
    DBUG_RETURN(TRUE);
4617
  }
4618
  DBUG_RETURN(FALSE);
4619
}
4620
4621
4622
/**
4623
  simple INSERT query pre-check.
4624
4625
  @param thd		Thread handler
4626
  @param tables	Global table list
4627
4628
  @retval
4629
    FALSE  OK
4630
  @retval
4631
    TRUE   error
4632
*/
4633
4634
bool insert_precheck(THD *thd, TABLE_LIST *tables)
4635
{
4636
  LEX *lex= thd->lex;
4637
  DBUG_ENTER("insert_precheck");
4638
4639
  /*
4640
    Check that we have modify privileges for the first table and
4641
    select privileges for the rest
4642
  */
4643
  if (lex->update_list.elements != lex->value_list.elements)
4644
  {
4645
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
4646
    DBUG_RETURN(TRUE);
4647
  }
4648
  DBUG_RETURN(FALSE);
4649
}
4650
4651
4652
/**
4653
  CREATE TABLE query pre-check.
4654
4655
  @param thd			Thread handler
4656
  @param tables		Global table list
4657
  @param create_table	        Table which will be created
4658
4659
  @retval
4660
    FALSE   OK
4661
  @retval
4662
    TRUE   Error
4663
*/
4664
4665
bool create_table_precheck(THD *thd, TABLE_LIST *tables,
4666
                           TABLE_LIST *create_table)
4667
{
4668
  LEX *lex= thd->lex;
4669
  SELECT_LEX *select_lex= &lex->select_lex;
4670
  bool error= TRUE;                                 // Error message is given
4671
  DBUG_ENTER("create_table_precheck");
4672
4673
  if (create_table && (strcmp(create_table->db, "information_schema") == 0))
4674
  {
4675
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), "", "", INFORMATION_SCHEMA_NAME.str);
4676
    DBUG_RETURN(TRUE);
4677
  }
4678
4679
  if (select_lex->item_list.elements)
4680
  {
4681
    /* Check permissions for used tables in CREATE TABLE ... SELECT */
4682
4683
#ifdef NOT_NECESSARY_TO_CHECK_CREATE_TABLE_EXIST_WHEN_PREPARING_STATEMENT
4684
    /* This code throws an ill error for CREATE TABLE t1 SELECT * FROM t1 */
4685
    /*
4686
      Only do the check for PS, because we on execute we have to check that
4687
      against the opened tables to ensure we don't use a table that is part
4688
      of the view (which can only be done after the table has been opened).
4689
    */
4690
    if (thd->stmt_arena->is_stmt_prepare_or_first_sp_execute())
4691
    {
4692
      /*
4693
        For temporary tables we don't have to check if the created table exists
4694
      */
4695
      if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) &&
4696
          find_table_in_global_list(tables, create_table->db,
4697
                                    create_table->table_name))
4698
      {
4699
	error= FALSE;
4700
        goto err;
4701
      }
4702
    }
4703
#endif
4704
  }
4705
  error= FALSE;
4706
4707
  DBUG_RETURN(error);
4708
}
4709
4710
4711
/**
4712
  negate given expression.
4713
4714
  @param thd  thread handler
4715
  @param expr expression for negation
4716
4717
  @return
4718
    negated expression
4719
*/
4720
4721
Item *negate_expression(THD *thd, Item *expr)
4722
{
4723
  Item *negated;
4724
  if (expr->type() == Item::FUNC_ITEM &&
4725
      ((Item_func *) expr)->functype() == Item_func::NOT_FUNC)
4726
  {
4727
    /* it is NOT(NOT( ... )) */
4728
    Item *arg= ((Item_func *) expr)->arguments()[0];
4729
    enum_parsing_place place= thd->lex->current_select->parsing_place;
4730
    if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING)
4731
      return arg;
4732
    /*
4733
      if it is not boolean function then we have to emulate value of
4734
      not(not(a)), it will be a != 0
4735
    */
4736
    return new Item_func_ne(arg, new Item_int((char*) "0", 0, 1));
4737
  }
4738
4739
  if ((negated= expr->neg_transformer(thd)) != 0)
4740
    return negated;
4741
  return new Item_func_not(expr);
4742
}
4743
4744
4745
/**
4746
  Check that byte length of a string does not exceed some limit.
4747
4748
  @param str         string to be checked
4749
  @param err_msg     error message to be displayed if the string is too long
4750
  @param max_length  max length
4751
4752
  @retval
4753
    FALSE   the passed string is not longer than max_length
4754
  @retval
4755
    TRUE    the passed string is longer than max_length
4756
4757
  NOTE
4758
    The function is not used in existing code but can be useful later?
4759
*/
4760
4761
bool check_string_byte_length(LEX_STRING *str, const char *err_msg,
4762
                              uint max_byte_length)
4763
{
4764
  if (str->length <= max_byte_length)
4765
    return FALSE;
4766
4767
  my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_byte_length);
4768
4769
  return TRUE;
4770
}
4771
4772
4773
/*
4774
  Check that char length of a string does not exceed some limit.
4775
4776
  SYNOPSIS
4777
  check_string_char_length()
4778
      str              string to be checked
4779
      err_msg          error message to be displayed if the string is too long
4780
      max_char_length  max length in symbols
4781
      cs               string charset
4782
4783
  RETURN
4784
    FALSE   the passed string is not longer than max_char_length
4785
    TRUE    the passed string is longer than max_char_length
4786
*/
4787
4788
4789
bool check_string_char_length(LEX_STRING *str, const char *err_msg,
4790
                              uint max_char_length, CHARSET_INFO *cs,
4791
                              bool no_error)
4792
{
4793
  int well_formed_error;
4794
  uint res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
4795
                                      max_char_length, &well_formed_error);
4796
4797
  if (!well_formed_error &&  str->length == res)
4798
    return FALSE;
4799
4800
  if (!no_error)
4801
    my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_char_length);
4802
  return TRUE;
4803
}
4804
4805
4806
bool check_identifier_name(LEX_STRING *str, uint max_char_length,
4807
                           uint err_code, const char *param_for_err_msg)
4808
{
4809
#ifdef HAVE_CHARSET_utf8mb3
4810
  /*
4811
    We don't support non-BMP characters in identifiers at the moment,
4812
    so they should be prohibited until such support is done.
4813
    This is why we use the 3-byte utf8 to check well-formedness here.
4814
  */
4815
  CHARSET_INFO *cs= &my_charset_utf8mb3_general_ci;
4816
#else
4817
  CHARSET_INFO *cs= system_charset_info;
4818
#endif
4819
  int well_formed_error;
4820
  uint res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
4821
                                      max_char_length, &well_formed_error);
4822
4823
  if (well_formed_error)
4824
  {
4825
    my_error(ER_INVALID_CHARACTER_STRING, MYF(0), "identifier", str->str);
4826
    return TRUE;
4827
  }
4828
  
4829
  if (str->length == res)
4830
    return FALSE;
4831
4832
  switch (err_code)
4833
  {
4834
  case 0:
4835
    break;
4836
  case ER_WRONG_STRING_LENGTH:
4837
    my_error(err_code, MYF(0), str->str, param_for_err_msg, max_char_length);
4838
    break;
4839
  case ER_TOO_LONG_IDENT:
4840
    my_error(err_code, MYF(0), str->str);
4841
    break;
4842
  default:
4843
    DBUG_ASSERT(0);
4844
    break;
4845
  }
4846
  return TRUE;
4847
}
4848
4849
4850
/*
4851
  Check if path does not contain mysql data home directory
4852
  SYNOPSIS
4853
    test_if_data_home_dir()
4854
    dir                     directory
4855
    conv_home_dir           converted data home directory
4856
    home_dir_len            converted data home directory length
4857
4858
  RETURN VALUES
4859
    0	ok
4860
    1	error  
4861
*/
4862
4863
bool test_if_data_home_dir(const char *dir)
4864
{
4865
  char path[FN_REFLEN], conv_path[FN_REFLEN];
4866
  uint dir_len, home_dir_len= strlen(mysql_unpacked_real_data_home);
4867
  DBUG_ENTER("test_if_data_home_dir");
4868
4869
  if (!dir)
4870
    DBUG_RETURN(0);
4871
4872
  (void) fn_format(path, dir, "", "",
4873
                   (MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS));
4874
  dir_len= unpack_dirname(conv_path, dir);
4875
4876
  if (home_dir_len < dir_len)
4877
  {
4878
    if (lower_case_file_system)
4879
    {
4880
      if (!my_strnncoll(character_set_filesystem,
4881
                        (const uchar*) conv_path, home_dir_len,
4882
                        (const uchar*) mysql_unpacked_real_data_home,
4883
                        home_dir_len))
4884
        DBUG_RETURN(1);
4885
    }
4886
    else if (!memcmp(conv_path, mysql_unpacked_real_data_home, home_dir_len))
4887
      DBUG_RETURN(1);
4888
  }
4889
  DBUG_RETURN(0);
4890
}
4891
4892
4893
extern int MYSQLparse(void *thd); // from sql_yacc.cc
4894
4895
4896
/**
4897
  This is a wrapper of MYSQLparse(). All the code should call parse_sql()
4898
  instead of MYSQLparse().
4899
4900
  @param thd Thread context.
4901
  @param lip Lexer context.
4902
  @param creation_ctx Object creation context.
4903
4904
  @return Error status.
4905
    @retval FALSE on success.
4906
    @retval TRUE on parsing error.
4907
*/
4908
4909
bool parse_sql(THD *thd,
4910
               Lex_input_stream *lip,
4911
               Object_creation_ctx *creation_ctx)
4912
{
4913
  DBUG_ASSERT(thd->m_lip == NULL);
4914
4915
  /* Backup creation context. */
4916
4917
  Object_creation_ctx *backup_ctx= NULL;
4918
4919
  if (creation_ctx)
4920
    backup_ctx= creation_ctx->set_n_backup(thd);
4921
4922
  /* Set Lex_input_stream. */
4923
4924
  thd->m_lip= lip;
4925
4926
  /* Parse the query. */
4927
4928
  bool mysql_parse_status= MYSQLparse(thd) != 0;
4929
4930
  /* Check that if MYSQLparse() failed, thd->is_error() is set. */
4931
4932
  DBUG_ASSERT(!mysql_parse_status || thd->is_error());
4933
4934
  /* Reset Lex_input_stream. */
4935
4936
  thd->m_lip= NULL;
4937
4938
  /* Restore creation context. */
4939
4940
  if (creation_ctx)
4941
    creation_ctx->restore_env(thd, backup_ctx);
4942
4943
  /* That's it. */
4944
4945
  return mysql_parse_status || thd->is_fatal_error;
4946
}
4947
4948
/**
4949
  @} (end of group Runtime_Environment)
4950
*/