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