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