~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to sql/sql_parse.cc

Removed/replaced a couple DBUG calls

Show diffs side-by-side

added added

removed removed

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