~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_parse.cc

  • Committer: Monty Taylor
  • Date: 2008-09-16 00:00:48 UTC
  • mto: This revision was merged to the branch mainline in revision 391.
  • Revision ID: monty@inaugust.com-20080916000048-3rvrv3gv9l0ad3gs
Fixed copyright headers in drizzled/

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