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