~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_parse.cc

Merge Monty.

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