~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_parse.cc

  • Committer: Brian Aker
  • Date: 2008-10-06 06:47:29 UTC
  • Revision ID: brian@tangent.org-20081006064729-2i9mhjkzyvow9xsm
Remove uint.

Show diffs side-by-side

added added

removed removed

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