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