~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_parse.cc

  • Committer: Andy Lester
  • Date: 2008-08-10 02:15:48 UTC
  • mto: (266.1.31 use-replace-funcs)
  • mto: This revision was merged to the branch mainline in revision 295.
  • Revision ID: andy@petdance.com-20080810021548-0zx8nhzva6al10k3
Added a proper const qualifer.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
   You should have received a copy of the GNU General Public License
13
13
   along with this program; if not, write to the Free Software
14
 
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
15
 
 
16
 
#include "config.h"
17
 
 
18
 
#define DRIZZLE_LEX 1
19
 
 
20
 
#include "drizzled/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);
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
 
15
 
 
16
#define MYSQL_LEX 1
 
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 & MYSQL_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, TABLE_LIST *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, TABLE_LIST *tables)
 
138
{
 
139
  for (TABLE_LIST *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
                                                TABLE_LIST *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= strend(user)+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
    TABLE_LIST 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= strend(packet);
 
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) MYSQL_OPTION_MULTI_STATEMENTS_ON:
 
850
      thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
 
851
      my_eof(thd);
 
852
      break;
 
853
    case (int) MYSQL_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->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
 
352
950
/**
353
 
  Create a TableList object for an INFORMATION_SCHEMA table.
 
951
  Create a TABLE_LIST object for an INFORMATION_SCHEMA table.
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 TABLE_LIST 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
    TABLE_LIST **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
 
  TableList *table_list= (TableList*) select_lex->table_list.first;
 
1038
  TABLE_LIST *table_list= (TABLE_LIST*) 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
  TABLE_LIST *first_table= (TABLE_LIST*) select_lex->table_list.first;
451
1150
  /* list of all tables in query */
452
 
  TableList *all_tables;
 
1151
  TABLE_LIST *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
  */
471
1173
  all_tables= lex->query_tables;
472
1174
  /* set context for commands which do not use setup_tables */
473
1175
  select_lex->
474
 
    context.resolve_in_table_list_only((TableList*)select_lex->
 
1176
    context.resolve_in_table_list_only((TABLE_LIST*)select_lex->
475
1177
                                       table_list.first);
476
1178
 
477
1179
  /*
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, (ulong)
 
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, (ulong)
 
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
    TABLE_LIST *create_table= lex->unlink_first_table(&link_to_local);
 
1394
    TABLE_LIST *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
      /*
 
1471
        Disable non-empty MERGE tables with CREATE...SELECT. Too
 
1472
        complicated. See Bug #26379. Empty MERGE tables are read-only
 
1473
        and don't allow CREATE...SELECT anyway.
 
1474
      */
 
1475
      if (create_info.used_fields & HA_CREATE_USED_UNION)
 
1476
      {
 
1477
        my_error(ER_WRONG_OBJECT, MYF(0), create_table->db,
 
1478
                 create_table->table_name, "BASE TABLE");
 
1479
        res= 1;
 
1480
        goto end_with_restore_list;
 
1481
      }
 
1482
 
 
1483
      if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
 
1484
      {
 
1485
        lex->link_first_table_back(create_table, link_to_local);
 
1486
        create_table->create= true;
 
1487
      }
 
1488
 
 
1489
      if (!(res= open_and_lock_tables(thd, lex->query_tables)))
 
1490
      {
 
1491
        /*
 
1492
          Is table which we are changing used somewhere in other parts
 
1493
          of query
 
1494
        */
 
1495
        if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
 
1496
        {
 
1497
          TABLE_LIST *duplicate;
 
1498
          create_table= lex->unlink_first_table(&link_to_local);
 
1499
          if ((duplicate= unique_table(thd, create_table, select_tables, 0)))
 
1500
          {
 
1501
            update_non_unique_table_error(create_table, "CREATE", duplicate);
 
1502
            res= 1;
 
1503
            goto end_with_restore_list;
 
1504
          }
 
1505
        }
 
1506
        /* If we create merge table, we have to test tables in merge, too */
 
1507
        if (create_info.used_fields & HA_CREATE_USED_UNION)
 
1508
        {
 
1509
          TABLE_LIST *tab;
 
1510
          for (tab= (TABLE_LIST*) create_info.merge_list.first;
 
1511
               tab;
 
1512
               tab= tab->next_local)
 
1513
          {
 
1514
            TABLE_LIST *duplicate;
 
1515
            if ((duplicate= unique_table(thd, tab, select_tables, 0)))
 
1516
            {
 
1517
              update_non_unique_table_error(tab, "CREATE", duplicate);
 
1518
              res= 1;
 
1519
              goto end_with_restore_list;
 
1520
            }
 
1521
          }
 
1522
        }
 
1523
 
 
1524
        /*
 
1525
          select_create is currently not re-execution friendly and
 
1526
          needs to be created for every execution of a PS/SP.
 
1527
        */
 
1528
        if ((result= new select_create(create_table,
 
1529
                                       &create_info,
 
1530
                                       &alter_info,
 
1531
                                       select_lex->item_list,
 
1532
                                       lex->duplicates,
 
1533
                                       lex->ignore,
 
1534
                                       select_tables)))
 
1535
        {
 
1536
          /*
 
1537
            CREATE from SELECT give its SELECT_LEX for SELECT,
 
1538
            and item_list belong to SELECT
 
1539
          */
 
1540
          res= handle_select(thd, lex, result, 0);
 
1541
          delete result;
 
1542
        }
 
1543
      }
 
1544
      else if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
 
1545
        create_table= lex->unlink_first_table(&link_to_local);
 
1546
 
 
1547
    }
 
1548
    else
 
1549
    {
 
1550
      /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
 
1551
      if (create_info.options & HA_LEX_CREATE_TMP_TABLE)
 
1552
        thd->options|= OPTION_KEEP_LOG;
 
1553
      /* regular create */
 
1554
      if (create_info.options & HA_LEX_CREATE_TABLE_LIKE)
 
1555
        res= mysql_create_like_table(thd, create_table, select_tables,
 
1556
                                     &create_info);
 
1557
      else
 
1558
      {
 
1559
        res= mysql_create_table(thd, create_table->db,
 
1560
                                create_table->table_name, &create_info,
 
1561
                                &alter_info, 0, 0);
 
1562
      }
 
1563
      if (!res)
 
1564
        my_ok(thd);
 
1565
    }
 
1566
 
 
1567
    /* put tables back for PS rexecuting */
 
1568
end_with_restore_list:
 
1569
    lex->link_first_table_back(create_table, link_to_local);
 
1570
    break;
 
1571
  }
 
1572
  case SQLCOM_CREATE_INDEX:
 
1573
    /* Fall through */
 
1574
  case SQLCOM_DROP_INDEX:
 
1575
  /*
 
1576
    CREATE INDEX and DROP INDEX are implemented by calling ALTER
 
1577
    TABLE with proper arguments.
 
1578
 
 
1579
    In the future ALTER TABLE will notice that the request is to
 
1580
    only add indexes and create these one by one for the existing
 
1581
    table without having to do a full rebuild.
 
1582
  */
 
1583
  {
 
1584
    /* Prepare stack copies to be re-execution safe */
 
1585
    HA_CREATE_INFO create_info;
 
1586
    Alter_info alter_info(lex->alter_info, thd->mem_root);
 
1587
 
 
1588
    if (thd->is_fatal_error) /* out of memory creating a copy of alter_info */
 
1589
      goto error;
 
1590
 
 
1591
    assert(first_table == all_tables && first_table != 0);
 
1592
    if (end_active_trans(thd))
 
1593
      goto error;
 
1594
    /*
 
1595
      Currently CREATE INDEX or DROP INDEX cause a full table rebuild
 
1596
      and thus classify as slow administrative statements just like
 
1597
      ALTER TABLE.
 
1598
    */
 
1599
    thd->enable_slow_log= opt_log_slow_admin_statements;
 
1600
 
 
1601
    memset(&create_info, 0, sizeof(create_info));
 
1602
    create_info.db_type= 0;
 
1603
    create_info.row_type= ROW_TYPE_NOT_USED;
 
1604
    create_info.default_table_charset= thd->variables.collation_database;
 
1605
 
 
1606
    res= mysql_alter_table(thd, first_table->db, first_table->table_name,
 
1607
                           &create_info, first_table, &alter_info,
 
1608
                           0, (ORDER*) 0, 0);
 
1609
    break;
 
1610
  }
 
1611
  case SQLCOM_SLAVE_START:
 
1612
  {
 
1613
    pthread_mutex_lock(&LOCK_active_mi);
 
1614
    start_slave(thd,active_mi,1 /* net report*/);
 
1615
    pthread_mutex_unlock(&LOCK_active_mi);
 
1616
    break;
 
1617
  }
 
1618
  case SQLCOM_SLAVE_STOP:
 
1619
  /*
 
1620
    If the client thread has locked tables, a deadlock is possible.
 
1621
    Assume that
 
1622
    - the client thread does LOCK TABLE t READ.
 
1623
    - then the master updates t.
 
1624
    - then the SQL slave thread wants to update t,
 
1625
      so it waits for the client thread because t is locked by it.
 
1626
    - then the client thread does SLAVE STOP.
 
1627
      SLAVE STOP waits for the SQL slave thread to terminate its
 
1628
      update t, which waits for the client thread because t is locked by it.
 
1629
    To prevent that, refuse SLAVE STOP if the
 
1630
    client thread has locked tables
 
1631
  */
 
1632
  if (thd->locked_tables || thd->active_transaction() || thd->global_read_lock)
 
1633
  {
 
1634
    my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
 
1635
               ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
 
1636
    goto error;
 
1637
  }
 
1638
  {
 
1639
    pthread_mutex_lock(&LOCK_active_mi);
 
1640
    stop_slave(thd,active_mi,1/* net report*/);
 
1641
    pthread_mutex_unlock(&LOCK_active_mi);
 
1642
    break;
 
1643
  }
 
1644
 
 
1645
  case SQLCOM_ALTER_TABLE:
 
1646
    assert(first_table == all_tables && first_table != 0);
 
1647
    {
 
1648
      /*
 
1649
        Code in mysql_alter_table() may modify its HA_CREATE_INFO argument,
 
1650
        so we have to use a copy of this structure to make execution
 
1651
        prepared statement- safe. A shallow copy is enough as no memory
 
1652
        referenced from this structure will be modified.
 
1653
      */
 
1654
      HA_CREATE_INFO create_info(lex->create_info);
 
1655
      Alter_info alter_info(lex->alter_info, thd->mem_root);
 
1656
 
 
1657
      if (thd->is_fatal_error) /* out of memory creating a copy of alter_info */
 
1658
      {
 
1659
        goto error;
 
1660
      }
 
1661
 
 
1662
      /* Must be set in the parser */
 
1663
      assert(select_lex->db);
 
1664
 
 
1665
      { // Rename of table
 
1666
          TABLE_LIST tmp_table;
 
1667
          memset(&tmp_table, 0, sizeof(tmp_table));
 
1668
          tmp_table.table_name= lex->name.str;
 
1669
          tmp_table.db=select_lex->db;
 
1670
      }
 
1671
 
 
1672
      /* Don't yet allow changing of symlinks with ALTER TABLE */
 
1673
      if (create_info.data_file_name)
 
1674
        push_warning(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN, 0,
 
1675
                     "DATA DIRECTORY option ignored");
 
1676
      if (create_info.index_file_name)
 
1677
        push_warning(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN, 0,
 
1678
                     "INDEX DIRECTORY option ignored");
 
1679
      create_info.data_file_name= create_info.index_file_name= NULL;
 
1680
      /* ALTER TABLE ends previous transaction */
 
1681
      if (end_active_trans(thd))
 
1682
        goto error;
 
1683
 
 
1684
      if (!thd->locked_tables &&
 
1685
          !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
 
1686
      {
 
1687
        res= 1;
 
1688
        break;
 
1689
      }
 
1690
 
 
1691
      thd->enable_slow_log= opt_log_slow_admin_statements;
 
1692
      res= mysql_alter_table(thd, select_lex->db, lex->name.str,
 
1693
                             &create_info,
 
1694
                             first_table,
 
1695
                             &alter_info,
 
1696
                             select_lex->order_list.elements,
 
1697
                             (ORDER *) select_lex->order_list.first,
 
1698
                             lex->ignore);
 
1699
      break;
 
1700
    }
 
1701
  case SQLCOM_RENAME_TABLE:
 
1702
  {
 
1703
    assert(first_table == all_tables && first_table != 0);
 
1704
    TABLE_LIST *table;
 
1705
    for (table= first_table; table; table= table->next_local->next_local)
 
1706
    {
 
1707
      TABLE_LIST old_list, new_list;
 
1708
      /*
 
1709
        we do not need initialize old_list and new_list because we will
 
1710
        come table[0] and table->next[0] there
 
1711
      */
 
1712
      old_list= table[0];
 
1713
      new_list= table->next_local[0];
 
1714
    }
 
1715
 
 
1716
    if (end_active_trans(thd) || mysql_rename_tables(thd, first_table, 0))
 
1717
      {
 
1718
        goto error;
 
1719
      }
 
1720
    break;
 
1721
  }
 
1722
  case SQLCOM_SHOW_BINLOGS:
 
1723
    {
 
1724
      res = show_binlogs(thd);
 
1725
      break;
 
1726
    }
 
1727
  case SQLCOM_SHOW_CREATE:
 
1728
    assert(first_table == all_tables && first_table != 0);
 
1729
    {
 
1730
      res= mysqld_show_create(thd, first_table);
 
1731
      break;
 
1732
    }
 
1733
  case SQLCOM_CHECKSUM:
 
1734
  {
 
1735
    assert(first_table == all_tables && first_table != 0);
 
1736
    res = mysql_checksum_table(thd, first_table, &lex->check_opt);
 
1737
    break;
 
1738
  }
 
1739
  case SQLCOM_REPAIR:
 
1740
  {
 
1741
    assert(first_table == all_tables && first_table != 0);
 
1742
    thd->enable_slow_log= opt_log_slow_admin_statements;
 
1743
    res= mysql_repair_table(thd, first_table, &lex->check_opt);
 
1744
    /* ! we write after unlocking the table */
 
1745
    if (!res && !lex->no_write_to_binlog)
 
1746
    {
 
1747
      /*
 
1748
        Presumably, REPAIR and binlog writing doesn't require synchronization
 
1749
      */
 
1750
      write_bin_log(thd, true, thd->query, thd->query_length);
 
1751
    }
 
1752
    select_lex->table_list.first= (uchar*) first_table;
 
1753
    lex->query_tables=all_tables;
 
1754
    break;
 
1755
  }
 
1756
  case SQLCOM_CHECK:
 
1757
  {
 
1758
    assert(first_table == all_tables && first_table != 0);
 
1759
    thd->enable_slow_log= opt_log_slow_admin_statements;
 
1760
    res = mysql_check_table(thd, first_table, &lex->check_opt);
 
1761
    select_lex->table_list.first= (uchar*) first_table;
 
1762
    lex->query_tables=all_tables;
 
1763
    break;
 
1764
  }
 
1765
  case SQLCOM_ANALYZE:
 
1766
  {
 
1767
    assert(first_table == all_tables && first_table != 0);
 
1768
    thd->enable_slow_log= opt_log_slow_admin_statements;
 
1769
    res= mysql_analyze_table(thd, first_table, &lex->check_opt);
 
1770
    /* ! we write after unlocking the table */
 
1771
    if (!res && !lex->no_write_to_binlog)
 
1772
    {
 
1773
      /*
 
1774
        Presumably, ANALYZE and binlog writing doesn't require synchronization
 
1775
      */
 
1776
      write_bin_log(thd, true, thd->query, thd->query_length);
 
1777
    }
 
1778
    select_lex->table_list.first= (uchar*) first_table;
 
1779
    lex->query_tables=all_tables;
 
1780
    break;
 
1781
  }
 
1782
 
 
1783
  case SQLCOM_OPTIMIZE:
 
1784
  {
 
1785
    assert(first_table == all_tables && first_table != 0);
 
1786
    thd->enable_slow_log= opt_log_slow_admin_statements;
 
1787
    res= (specialflag & (SPECIAL_SAFE_MODE | SPECIAL_NO_NEW_FUNC)) ?
 
1788
      mysql_recreate_table(thd, first_table) :
 
1789
      mysql_optimize_table(thd, first_table, &lex->check_opt);
 
1790
    /* ! we write after unlocking the table */
 
1791
    if (!res && !lex->no_write_to_binlog)
 
1792
    {
 
1793
      /*
 
1794
        Presumably, OPTIMIZE and binlog writing doesn't require synchronization
 
1795
      */
 
1796
      write_bin_log(thd, true, thd->query, thd->query_length);
 
1797
    }
 
1798
    select_lex->table_list.first= (uchar*) first_table;
 
1799
    lex->query_tables=all_tables;
 
1800
    break;
 
1801
  }
 
1802
  case SQLCOM_UPDATE:
 
1803
    assert(first_table == all_tables && first_table != 0);
 
1804
    if (update_precheck(thd, all_tables))
 
1805
      break;
 
1806
    assert(select_lex->offset_limit == 0);
 
1807
    unit->set_limit(select_lex);
 
1808
    res= (up_result= mysql_update(thd, all_tables,
 
1809
                                  select_lex->item_list,
 
1810
                                  lex->value_list,
 
1811
                                  select_lex->where,
 
1812
                                  select_lex->order_list.elements,
 
1813
                                  (ORDER *) select_lex->order_list.first,
 
1814
                                  unit->select_limit_cnt,
 
1815
                                  lex->duplicates, lex->ignore));
 
1816
    /* mysql_update return 2 if we need to switch to multi-update */
 
1817
    if (up_result != 2)
 
1818
      break;
 
1819
    /* Fall through */
 
1820
  case SQLCOM_UPDATE_MULTI:
 
1821
  {
 
1822
    assert(first_table == all_tables && first_table != 0);
 
1823
    /* if we switched from normal update, rights are checked */
 
1824
    if (up_result != 2)
 
1825
    {
 
1826
      if ((res= multi_update_precheck(thd, all_tables)))
 
1827
        break;
 
1828
    }
 
1829
    else
 
1830
      res= 0;
 
1831
 
 
1832
    res= mysql_multi_update_prepare(thd);
 
1833
 
 
1834
    /* Check slave filtering rules */
 
1835
    if (unlikely(thd->slave_thread))
 
1836
    {
 
1837
      if (all_tables_not_ok(thd, all_tables))
 
1838
      {
 
1839
        if (res!= 0)
 
1840
        {
 
1841
          res= 0;             /* don't care of prev failure  */
 
1842
          thd->clear_error(); /* filters are of highest prior */
 
1843
        }
 
1844
        /* we warn the slave SQL thread */
 
1845
        my_error(ER_SLAVE_IGNORED_TABLE, MYF(0));
 
1846
        break;
 
1847
      }
 
1848
      if (res)
 
1849
        break;
 
1850
    }
 
1851
    else
 
1852
    {
 
1853
      if (res)
 
1854
        break;
 
1855
      if (opt_readonly &&
 
1856
          some_non_temp_table_to_be_updated(thd, all_tables))
 
1857
      {
 
1858
        my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
 
1859
        break;
 
1860
      }
 
1861
    }  /* unlikely */
 
1862
 
 
1863
    res= mysql_multi_update(thd, all_tables,
 
1864
                            &select_lex->item_list,
 
1865
                            &lex->value_list,
 
1866
                            select_lex->where,
 
1867
                            select_lex->options,
 
1868
                            lex->duplicates, lex->ignore, unit, select_lex);
 
1869
    break;
 
1870
  }
 
1871
  case SQLCOM_REPLACE:
 
1872
  case SQLCOM_INSERT:
 
1873
  {
 
1874
    assert(first_table == all_tables && first_table != 0);
 
1875
    if ((res= insert_precheck(thd, all_tables)))
 
1876
      break;
 
1877
 
 
1878
    if (!thd->locked_tables &&
 
1879
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
 
1880
    {
 
1881
      res= 1;
 
1882
      break;
 
1883
    }
 
1884
 
 
1885
    res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
 
1886
                      lex->update_list, lex->value_list,
 
1887
                      lex->duplicates, lex->ignore);
 
1888
 
 
1889
    break;
 
1890
  }
 
1891
  case SQLCOM_REPLACE_SELECT:
 
1892
  case SQLCOM_INSERT_SELECT:
 
1893
  {
 
1894
    select_result *sel_result;
 
1895
    assert(first_table == all_tables && first_table != 0);
 
1896
    if ((res= insert_precheck(thd, all_tables)))
 
1897
      break;
 
1898
 
 
1899
    /* Fix lock for first table */
 
1900
    if (first_table->lock_type == TL_WRITE_DELAYED)
 
1901
      first_table->lock_type= TL_WRITE;
 
1902
 
 
1903
    /* Don't unlock tables until command is written to binary log */
 
1904
    select_lex->options|= SELECT_NO_UNLOCK;
 
1905
 
 
1906
    unit->set_limit(select_lex);
 
1907
 
 
1908
    if (! thd->locked_tables &&
 
1909
        ! (need_start_waiting= ! wait_if_global_read_lock(thd, 0, 1)))
 
1910
    {
 
1911
      res= 1;
 
1912
      break;
 
1913
    }
 
1914
 
 
1915
    if (!(res= open_and_lock_tables(thd, all_tables)))
 
1916
    {
 
1917
      /* Skip first table, which is the table we are inserting in */
 
1918
      TABLE_LIST *second_table= first_table->next_local;
 
1919
      select_lex->table_list.first= (uchar*) second_table;
 
1920
      select_lex->context.table_list= 
 
1921
        select_lex->context.first_name_resolution_table= second_table;
 
1922
      res= mysql_insert_select_prepare(thd);
 
1923
      if (!res && (sel_result= new select_insert(first_table,
 
1924
                                                 first_table->table,
 
1925
                                                 &lex->field_list,
 
1926
                                                 &lex->update_list,
 
1927
                                                 &lex->value_list,
 
1928
                                                 lex->duplicates,
 
1929
                                                 lex->ignore)))
 
1930
      {
 
1931
        res= handle_select(thd, lex, sel_result, OPTION_SETUP_TABLES_DONE);
 
1932
        /*
 
1933
          Invalidate the table in the query cache if something changed
 
1934
          after unlocking when changes become visible.
 
1935
          TODO: this is workaround. right way will be move invalidating in
 
1936
          the unlock procedure.
 
1937
        */
 
1938
        if (first_table->lock_type ==  TL_WRITE_CONCURRENT_INSERT &&
 
1939
            thd->lock)
 
1940
        {
 
1941
          /* INSERT ... SELECT should invalidate only the very first table */
 
1942
          TABLE_LIST *save_table= first_table->next_local;
 
1943
          first_table->next_local= 0;
 
1944
          first_table->next_local= save_table;
 
1945
        }
 
1946
        delete sel_result;
 
1947
      }
 
1948
      /* revert changes for SP */
 
1949
      select_lex->table_list.first= (uchar*) first_table;
 
1950
    }
 
1951
 
 
1952
    break;
 
1953
  }
 
1954
  case SQLCOM_TRUNCATE:
 
1955
    if (end_active_trans(thd))
 
1956
    {
 
1957
      res= -1;
 
1958
      break;
 
1959
    }
 
1960
    assert(first_table == all_tables && first_table != 0);
 
1961
    /*
 
1962
      Don't allow this within a transaction because we want to use
 
1963
      re-generate table
 
1964
    */
 
1965
    if (thd->locked_tables || thd->active_transaction())
 
1966
    {
 
1967
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
 
1968
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
 
1969
      goto error;
 
1970
    }
 
1971
 
 
1972
    res= mysql_truncate(thd, first_table, 0);
 
1973
 
 
1974
    break;
 
1975
  case SQLCOM_DELETE:
 
1976
  {
 
1977
    assert(first_table == all_tables && first_table != 0);
 
1978
    assert(select_lex->offset_limit == 0);
 
1979
    unit->set_limit(select_lex);
 
1980
 
 
1981
    if (!thd->locked_tables &&
 
1982
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
 
1983
    {
 
1984
      res= 1;
 
1985
      break;
 
1986
    }
 
1987
 
 
1988
    res = mysql_delete(thd, all_tables, select_lex->where,
 
1989
                       &select_lex->order_list,
 
1990
                       unit->select_limit_cnt, select_lex->options,
 
1991
                       false);
 
1992
    break;
 
1993
  }
 
1994
  case SQLCOM_DELETE_MULTI:
 
1995
  {
 
1996
    assert(first_table == all_tables && first_table != 0);
 
1997
    TABLE_LIST *aux_tables=
 
1998
      (TABLE_LIST *)thd->lex->auxiliary_table_list.first;
 
1999
    multi_delete *del_result;
 
2000
 
 
2001
    if (!thd->locked_tables &&
 
2002
        !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
 
2003
    {
 
2004
      res= 1;
 
2005
      break;
 
2006
    }
 
2007
 
 
2008
    if ((res= multi_delete_precheck(thd, all_tables)))
 
2009
      break;
 
2010
 
 
2011
    /* condition will be true on SP re-excuting */
 
2012
    if (select_lex->item_list.elements != 0)
 
2013
      select_lex->item_list.empty();
 
2014
    if (add_item_to_list(thd, new Item_null()))
 
2015
      goto error;
 
2016
 
 
2017
    thd_proc_info(thd, "init");
 
2018
    if ((res= open_and_lock_tables(thd, all_tables)))
 
2019
      break;
 
2020
 
 
2021
    if ((res= mysql_multi_delete_prepare(thd)))
 
2022
      goto error;
 
2023
 
 
2024
    if (!thd->is_fatal_error &&
 
2025
        (del_result= new multi_delete(aux_tables, lex->table_count)))
 
2026
    {
 
2027
      res= mysql_select(thd, &select_lex->ref_pointer_array,
 
2028
                        select_lex->get_table_list(),
 
2029
                        select_lex->with_wild,
 
2030
                        select_lex->item_list,
 
2031
                        select_lex->where,
 
2032
                        0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL,
 
2033
                        (ORDER *)NULL,
 
2034
                        select_lex->options | thd->options |
 
2035
                        SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
 
2036
                        OPTION_SETUP_TABLES_DONE,
 
2037
                        del_result, unit, select_lex);
 
2038
      res|= thd->is_error();
 
2039
      if (res)
 
2040
        del_result->abort();
 
2041
      delete del_result;
 
2042
    }
 
2043
    else
 
2044
      res= true;                                // Error
 
2045
    break;
 
2046
  }
 
2047
  case SQLCOM_DROP_TABLE:
 
2048
  {
 
2049
    assert(first_table == all_tables && first_table != 0);
 
2050
    if (!lex->drop_temporary)
 
2051
    {
 
2052
      if (end_active_trans(thd))
 
2053
        goto error;
 
2054
    }
 
2055
    else
 
2056
    {
 
2057
      /*
 
2058
        If this is a slave thread, we may sometimes execute some 
 
2059
        DROP / * 40005 TEMPORARY * / TABLE
 
2060
        that come from parts of binlogs (likely if we use RESET SLAVE or CHANGE
 
2061
        MASTER TO), while the temporary table has already been dropped.
 
2062
        To not generate such irrelevant "table does not exist errors",
 
2063
        we silently add IF EXISTS if TEMPORARY was used.
 
2064
      */
 
2065
      if (thd->slave_thread)
 
2066
        lex->drop_if_exists= 1;
 
2067
 
 
2068
      /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
 
2069
      thd->options|= OPTION_KEEP_LOG;
 
2070
    }
 
2071
    /* DDL and binlog write order protected by LOCK_open */
 
2072
    res= mysql_rm_table(thd, first_table, lex->drop_if_exists, lex->drop_temporary);
 
2073
  }
 
2074
  break;
 
2075
  case SQLCOM_SHOW_PROCESSLIST:
 
2076
    mysqld_list_processes(thd, NullS, lex->verbose);
 
2077
    break;
 
2078
  case SQLCOM_SHOW_ENGINE_LOGS:
 
2079
    {
 
2080
      res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS);
 
2081
      break;
 
2082
    }
 
2083
  case SQLCOM_CHANGE_DB:
 
2084
  {
 
2085
    LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) };
 
2086
 
 
2087
    if (!mysql_change_db(thd, &db_str, false))
 
2088
      my_ok(thd);
 
2089
 
 
2090
    break;
 
2091
  }
 
2092
 
 
2093
  case SQLCOM_LOAD:
 
2094
  {
 
2095
    assert(first_table == all_tables && first_table != 0);
 
2096
    if (lex->local_file)
 
2097
    {
 
2098
      if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) ||
 
2099
          !opt_local_infile)
 
2100
      {
 
2101
        my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0));
 
2102
        goto error;
 
2103
      }
 
2104
    }
 
2105
 
 
2106
    res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
 
2107
                    lex->update_list, lex->value_list, lex->duplicates,
 
2108
                    lex->ignore, (bool) lex->local_file);
 
2109
    break;
 
2110
  }
 
2111
 
 
2112
  case SQLCOM_SET_OPTION:
 
2113
  {
 
2114
    List<set_var_base> *lex_var_list= &lex->var_list;
 
2115
 
 
2116
    if (lex->autocommit && end_active_trans(thd))
 
2117
      goto error;
 
2118
 
 
2119
    if (open_and_lock_tables(thd, all_tables))
 
2120
      goto error;
 
2121
    if (lex->one_shot_set && not_all_support_one_shot(lex_var_list))
 
2122
    {
 
2123
      my_error(ER_RESERVED_SYNTAX, MYF(0), "SET ONE_SHOT");
 
2124
      goto error;
 
2125
    }
 
2126
    if (!(res= sql_set_variables(thd, lex_var_list)))
 
2127
    {
 
2128
      /*
 
2129
        If the previous command was a SET ONE_SHOT, we don't want to forget
 
2130
        about the ONE_SHOT property of that SET. So we use a |= instead of = .
 
2131
      */
 
2132
      thd->one_shot_set|= lex->one_shot_set;
 
2133
      my_ok(thd);
 
2134
    }
 
2135
    else
 
2136
    {
 
2137
      /*
 
2138
        We encountered some sort of error, but no message was sent.
 
2139
        Send something semi-generic here since we don't know which
 
2140
        assignment in the list caused the error.
 
2141
      */
 
2142
      if (!thd->is_error())
 
2143
        my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET");
 
2144
      goto error;
 
2145
    }
 
2146
 
 
2147
    break;
 
2148
  }
 
2149
 
 
2150
  case SQLCOM_UNLOCK_TABLES:
 
2151
    /*
 
2152
      It is critical for mysqldump --single-transaction --master-data that
 
2153
      UNLOCK TABLES does not implicitely commit a connection which has only
 
2154
      done FLUSH TABLES WITH READ LOCK + BEGIN. If this assumption becomes
 
2155
      false, mysqldump will not work.
 
2156
    */
 
2157
    unlock_locked_tables(thd);
 
2158
    if (thd->options & OPTION_TABLE_LOCK)
 
2159
    {
 
2160
      end_active_trans(thd);
 
2161
      thd->options&= ~(OPTION_TABLE_LOCK);
 
2162
    }
 
2163
    if (thd->global_read_lock)
 
2164
      unlock_global_read_lock(thd);
 
2165
    my_ok(thd);
 
2166
    break;
 
2167
  case SQLCOM_LOCK_TABLES:
 
2168
    /*
 
2169
      We try to take transactional locks if
 
2170
      - only transactional locks are requested (lex->lock_transactional) and
 
2171
      - no non-transactional locks exist (!thd->locked_tables).
 
2172
    */
 
2173
    if (lex->lock_transactional && !thd->locked_tables)
 
2174
    {
 
2175
      int rc;
 
2176
      /*
 
2177
        All requested locks are transactional and no non-transactional
 
2178
        locks exist.
 
2179
      */
 
2180
      if ((rc= try_transactional_lock(thd, all_tables)) == -1)
 
2181
        goto error;
 
2182
      if (rc == 0)
 
2183
      {
 
2184
        my_ok(thd);
 
2185
        break;
 
2186
      }
 
2187
      /*
 
2188
        Non-transactional locking has been requested or
 
2189
        non-transactional locks exist already or transactional locks are
 
2190
        not supported by all storage engines. Take non-transactional
 
2191
        locks.
 
2192
      */
 
2193
    }
 
2194
    /*
 
2195
      One or more requested locks are non-transactional and/or
 
2196
      non-transactional locks exist or a storage engine does not support
 
2197
      transactional locks. Check if at least one transactional lock is
 
2198
      requested. If yes, warn about the conversion to non-transactional
 
2199
      locks or abort in strict mode.
 
2200
    */
 
2201
    if (check_transactional_lock(thd, all_tables))
 
2202
      goto error;
 
2203
    unlock_locked_tables(thd);
 
2204
    /* we must end the trasaction first, regardless of anything */
 
2205
    if (end_active_trans(thd))
 
2206
      goto error;
 
2207
    thd->in_lock_tables=1;
 
2208
    thd->options|= OPTION_TABLE_LOCK;
 
2209
 
 
2210
    if (!(res= simple_open_n_lock_tables(thd, all_tables)))
 
2211
    {
 
2212
      thd->locked_tables=thd->lock;
 
2213
      thd->lock=0;
 
2214
      (void) set_handler_table_locks(thd, all_tables, false);
 
2215
      my_ok(thd);
 
2216
    }
 
2217
    else
 
2218
    {
 
2219
      /* 
 
2220
        Need to end the current transaction, so the storage engine (InnoDB)
 
2221
        can free its locks if LOCK TABLES locked some tables before finding
 
2222
        that it can't lock a table in its list
 
2223
      */
 
2224
      ha_autocommit_or_rollback(thd, 1);
 
2225
      end_active_trans(thd);
 
2226
      thd->options&= ~(OPTION_TABLE_LOCK);
 
2227
    }
 
2228
    thd->in_lock_tables=0;
 
2229
    break;
 
2230
  case SQLCOM_CREATE_DB:
 
2231
  {
 
2232
    /*
 
2233
      As mysql_create_db() may modify HA_CREATE_INFO structure passed to
 
2234
      it, we need to use a copy of LEX::create_info to make execution
 
2235
      prepared statement- safe.
 
2236
    */
 
2237
    HA_CREATE_INFO create_info(lex->create_info);
 
2238
    if (end_active_trans(thd))
 
2239
    {
 
2240
      res= -1;
 
2241
      break;
 
2242
    }
 
2243
    char *alias;
 
2244
    if (!(alias=thd->strmake(lex->name.str, lex->name.length)) ||
 
2245
        check_db_name(&lex->name))
 
2246
    {
 
2247
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
 
2248
      break;
 
2249
    }
 
2250
    /*
 
2251
      If in a slave thread :
 
2252
      CREATE DATABASE DB was certainly not preceded by USE DB.
 
2253
      For that reason, db_ok() in sql/slave.cc did not check the
 
2254
      do_db/ignore_db. And as this query involves no tables, tables_ok()
 
2255
      above was not called. So we have to check rules again here.
 
2256
    */
 
2257
    if (thd->slave_thread && 
 
2258
        (!rpl_filter->db_ok(lex->name.str) ||
 
2259
         !rpl_filter->db_ok_with_wild_table(lex->name.str)))
 
2260
    {
 
2261
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
 
2262
      break;
 
2263
    }
 
2264
    res= mysql_create_db(thd,(lower_case_table_names == 2 ? alias :
 
2265
                              lex->name.str), &create_info, 0);
 
2266
    break;
 
2267
  }
 
2268
  case SQLCOM_DROP_DB:
 
2269
  {
 
2270
    if (end_active_trans(thd))
 
2271
    {
 
2272
      res= -1;
 
2273
      break;
 
2274
    }
 
2275
    if (check_db_name(&lex->name))
 
2276
    {
 
2277
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
 
2278
      break;
 
2279
    }
 
2280
    /*
 
2281
      If in a slave thread :
 
2282
      DROP DATABASE DB may not be preceded by USE DB.
 
2283
      For that reason, maybe db_ok() in sql/slave.cc did not check the 
 
2284
      do_db/ignore_db. And as this query involves no tables, tables_ok()
 
2285
      above was not called. So we have to check rules again here.
 
2286
    */
 
2287
    if (thd->slave_thread && 
 
2288
        (!rpl_filter->db_ok(lex->name.str) ||
 
2289
         !rpl_filter->db_ok_with_wild_table(lex->name.str)))
 
2290
    {
 
2291
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
 
2292
      break;
 
2293
    }
 
2294
    if (thd->locked_tables || thd->active_transaction())
 
2295
    {
 
2296
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
 
2297
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
 
2298
      goto error;
 
2299
    }
 
2300
    res= mysql_rm_db(thd, lex->name.str, lex->drop_if_exists, 0);
 
2301
    break;
 
2302
  }
 
2303
  case SQLCOM_ALTER_DB:
 
2304
  {
 
2305
    LEX_STRING *db= &lex->name;
 
2306
    HA_CREATE_INFO create_info(lex->create_info);
 
2307
    if (check_db_name(db))
 
2308
    {
 
2309
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
 
2310
      break;
 
2311
    }
 
2312
    /*
 
2313
      If in a slave thread :
 
2314
      ALTER DATABASE DB may not be preceded by USE DB.
 
2315
      For that reason, maybe db_ok() in sql/slave.cc did not check the
 
2316
      do_db/ignore_db. And as this query involves no tables, tables_ok()
 
2317
      above was not called. So we have to check rules again here.
 
2318
    */
 
2319
    if (thd->slave_thread &&
 
2320
        (!rpl_filter->db_ok(db->str) ||
 
2321
         !rpl_filter->db_ok_with_wild_table(db->str)))
 
2322
    {
 
2323
      my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
 
2324
      break;
 
2325
    }
 
2326
    if (thd->locked_tables || thd->active_transaction())
 
2327
    {
 
2328
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
 
2329
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
 
2330
      goto error;
 
2331
    }
 
2332
    res= mysql_alter_db(thd, db->str, &create_info);
 
2333
    break;
 
2334
  }
 
2335
  case SQLCOM_SHOW_CREATE_DB:
 
2336
  {
 
2337
    if (check_db_name(&lex->name))
 
2338
    {
 
2339
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
 
2340
      break;
 
2341
    }
 
2342
    res= mysqld_show_create_db(thd, lex->name.str, &lex->create_info);
 
2343
    break;
 
2344
  }
 
2345
  case SQLCOM_RESET:
 
2346
    /*
 
2347
      RESET commands are never written to the binary log, so we have to
 
2348
      initialize this variable because RESET shares the same code as FLUSH
 
2349
    */
 
2350
    lex->no_write_to_binlog= 1;
 
2351
  case SQLCOM_FLUSH:
 
2352
  {
 
2353
    bool write_to_binlog;
 
2354
 
 
2355
    /*
 
2356
      reload_cache() will tell us if we are allowed to write to the
 
2357
      binlog or not.
 
2358
    */
 
2359
    if (!reload_cache(thd, lex->type, first_table, &write_to_binlog))
 
2360
    {
 
2361
      /*
 
2362
        We WANT to write and we CAN write.
 
2363
        ! we write after unlocking the table.
 
2364
      */
 
2365
      /*
 
2366
        Presumably, RESET and binlog writing doesn't require synchronization
 
2367
      */
 
2368
      if (!lex->no_write_to_binlog && write_to_binlog)
 
2369
      {
 
2370
        write_bin_log(thd, false, thd->query, thd->query_length);
 
2371
      }
 
2372
      my_ok(thd);
 
2373
    } 
 
2374
    
 
2375
    break;
 
2376
  }
 
2377
  case SQLCOM_KILL:
 
2378
  {
 
2379
    Item *it= (Item *)lex->value_list.head();
 
2380
 
 
2381
    if (lex->table_or_sp_used())
 
2382
    {
 
2383
      my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Usage of subqueries or stored "
 
2384
               "function calls as part of this statement");
 
2385
      break;
 
2386
    }
 
2387
 
 
2388
    if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1))
 
2389
    {
 
2390
      my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY),
 
2391
                 MYF(0));
 
2392
      goto error;
 
2393
    }
 
2394
    sql_kill(thd, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY);
 
2395
    break;
 
2396
  }
 
2397
  case SQLCOM_BEGIN:
 
2398
    if (thd->transaction.xid_state.xa_state != XA_NOTR)
 
2399
    {
 
2400
      my_error(ER_XAER_RMFAIL, MYF(0),
 
2401
               xa_state_names[thd->transaction.xid_state.xa_state]);
 
2402
      break;
 
2403
    }
 
2404
    /*
 
2405
      Breakpoints for backup testing.
 
2406
    */
 
2407
    if (begin_trans(thd))
 
2408
      goto error;
 
2409
    my_ok(thd);
 
2410
    break;
 
2411
  case SQLCOM_COMMIT:
 
2412
    if (end_trans(thd, lex->tx_release ? COMMIT_RELEASE :
 
2413
                              lex->tx_chain ? COMMIT_AND_CHAIN : COMMIT))
 
2414
      goto error;
 
2415
    my_ok(thd);
 
2416
    break;
 
2417
  case SQLCOM_ROLLBACK:
 
2418
    if (end_trans(thd, lex->tx_release ? ROLLBACK_RELEASE :
 
2419
                              lex->tx_chain ? ROLLBACK_AND_CHAIN : ROLLBACK))
 
2420
      goto error;
 
2421
    my_ok(thd);
 
2422
    break;
 
2423
  case SQLCOM_RELEASE_SAVEPOINT:
 
2424
  {
 
2425
    SAVEPOINT *sv;
 
2426
    for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
 
2427
    {
 
2428
      if (my_strnncoll(system_charset_info,
 
2429
                       (uchar *)lex->ident.str, lex->ident.length,
 
2430
                       (uchar *)sv->name, sv->length) == 0)
 
2431
        break;
 
2432
    }
 
2433
    if (sv)
 
2434
    {
 
2435
      if (ha_release_savepoint(thd, sv))
 
2436
        res= true; // cannot happen
 
2437
      else
 
2438
        my_ok(thd);
 
2439
      thd->transaction.savepoints=sv->prev;
 
2440
    }
 
2441
    else
 
2442
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
 
2443
    break;
 
2444
  }
 
2445
  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
 
2446
  {
 
2447
    SAVEPOINT *sv;
 
2448
    for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
 
2449
    {
 
2450
      if (my_strnncoll(system_charset_info,
 
2451
                       (uchar *)lex->ident.str, lex->ident.length,
 
2452
                       (uchar *)sv->name, sv->length) == 0)
 
2453
        break;
 
2454
    }
 
2455
    if (sv)
 
2456
    {
 
2457
      if (ha_rollback_to_savepoint(thd, sv))
 
2458
        res= true; // cannot happen
 
2459
      else
 
2460
      {
 
2461
        if (((thd->options & OPTION_KEEP_LOG) || 
 
2462
             thd->transaction.all.modified_non_trans_table) &&
 
2463
            !thd->slave_thread)
 
2464
          push_warning(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
2465
                       ER_WARNING_NOT_COMPLETE_ROLLBACK,
 
2466
                       ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
 
2467
        my_ok(thd);
 
2468
      }
 
2469
      thd->transaction.savepoints=sv;
 
2470
    }
 
2471
    else
 
2472
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
 
2473
    break;
 
2474
  }
 
2475
  case SQLCOM_SAVEPOINT:
 
2476
    if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN) ||
 
2477
          thd->in_sub_stmt) || !opt_using_transactions)
 
2478
      my_ok(thd);
 
2479
    else
 
2480
    {
 
2481
      SAVEPOINT **sv, *newsv;
 
2482
      for (sv=&thd->transaction.savepoints; *sv; sv=&(*sv)->prev)
 
2483
      {
 
2484
        if (my_strnncoll(system_charset_info,
 
2485
                         (uchar *)lex->ident.str, lex->ident.length,
 
2486
                         (uchar *)(*sv)->name, (*sv)->length) == 0)
 
2487
          break;
 
2488
      }
 
2489
      if (*sv) /* old savepoint of the same name exists */
 
2490
      {
 
2491
        newsv=*sv;
 
2492
        ha_release_savepoint(thd, *sv); // it cannot fail
 
2493
        *sv=(*sv)->prev;
 
2494
      }
 
2495
      else if ((newsv=(SAVEPOINT *) alloc_root(&thd->transaction.mem_root,
 
2496
                                               savepoint_alloc_size)) == 0)
 
2497
      {
 
2498
        my_error(ER_OUT_OF_RESOURCES, MYF(0));
 
2499
        break;
 
2500
      }
 
2501
      newsv->name=strmake_root(&thd->transaction.mem_root,
 
2502
                               lex->ident.str, lex->ident.length);
 
2503
      newsv->length=lex->ident.length;
 
2504
      /*
 
2505
        if we'll get an error here, don't add new savepoint to the list.
 
2506
        we'll lose a little bit of memory in transaction mem_root, but it'll
 
2507
        be free'd when transaction ends anyway
 
2508
      */
 
2509
      if (ha_savepoint(thd, newsv))
 
2510
        res= true;
 
2511
      else
 
2512
      {
 
2513
        newsv->prev=thd->transaction.savepoints;
 
2514
        thd->transaction.savepoints=newsv;
 
2515
        my_ok(thd);
 
2516
      }
 
2517
    }
 
2518
    break;
 
2519
  case SQLCOM_BINLOG_BASE64_EVENT:
 
2520
  {
 
2521
    mysql_client_binlog_statement(thd);
 
2522
    break;
 
2523
  }
 
2524
  default:
 
2525
    assert(0);                             /* Impossible */
 
2526
    my_ok(thd);
 
2527
    break;
 
2528
  }
 
2529
  thd_proc_info(thd, "query end");
 
2530
 
 
2531
  /*
 
2532
    Binlog-related cleanup:
 
2533
    Reset system variables temporarily modified by SET ONE SHOT.
 
2534
 
 
2535
    Exception: If this is a SET, do nothing. This is to allow
 
2536
    mysqlbinlog to print many SET commands (in this case we want the
 
2537
    charset temp setting to live until the real query). This is also
 
2538
    needed so that SET CHARACTER_SET_CLIENT... does not cancel itself
 
2539
    immediately.
 
2540
  */
 
2541
  if (thd->one_shot_set && lex->sql_command != SQLCOM_SET_OPTION)
 
2542
    reset_one_shot_variables(thd);
 
2543
 
505
2544
  /*
506
2545
    The return value for ROW_COUNT() is "implementation dependent" if the
507
2546
    statement is not DELETE, INSERT or UPDATE, but -1 is what JDBC and ODBC
508
2547
    wants. We also keep the last value in case of SQLCOM_CALL or
509
2548
    SQLCOM_EXECUTE.
510
2549
  */
511
 
  if (! (sql_command_flags[lex->sql_command].test(CF_BIT_HAS_ROW_COUNT)))
 
2550
  if (!(sql_command_flags[lex->sql_command] & CF_HAS_ROW_COUNT))
 
2551
    thd->row_count_func= -1;
 
2552
 
 
2553
  goto finish;
 
2554
 
 
2555
error:
 
2556
  res= true;
 
2557
 
 
2558
finish:
 
2559
  if (need_start_waiting)
512
2560
  {
513
 
    session->row_count_func= -1;
 
2561
    /*
 
2562
      Release the protection against the global read lock and wake
 
2563
      everyone, who might want to set a global read lock.
 
2564
    */
 
2565
    start_waiting_global_read_lock(thd);
514
2566
  }
515
 
 
516
 
  return (res || session->is_error());
 
2567
  return(res || thd->is_error());
517
2568
}
518
 
bool execute_sqlcom_select(Session *session, TableList *all_tables)
 
2569
 
 
2570
bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables)
519
2571
{
520
 
  LEX   *lex= session->lex;
 
2572
  LEX   *lex= thd->lex;
521
2573
  select_result *result=lex->result;
522
 
  bool res= false;
 
2574
  bool res;
523
2575
  /* assign global limit variable if limit is not given */
524
2576
  {
525
 
    Select_Lex *param= lex->unit.global_parameters;
 
2577
    SELECT_LEX *param= lex->unit.global_parameters;
526
2578
    if (!param->explicit_limit)
527
2579
      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)))
 
2580
        new Item_int((uint64_t) thd->variables.select_limit);
 
2581
  }
 
2582
  if (!(res= open_and_lock_tables(thd, all_tables)))
544
2583
  {
545
2584
    if (lex->describe)
546
2585
    {
551
2590
        even if the query itself redirects the output.
552
2591
      */
553
2592
      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);
 
2593
        return 1;                               /* purecov: inspected */
 
2594
      thd->send_explain_fields(result);
 
2595
      res= mysql_explain_union(thd, &thd->lex->unit, result);
558
2596
      if (lex->describe & DESCRIBE_EXTENDED)
559
2597
      {
560
2598
        char buff[1024];
561
2599
        String str(buff,(uint32_t) sizeof(buff), system_charset_info);
562
2600
        str.length(0);
563
 
        session->lex->unit.print(&str, QT_ORDINARY);
 
2601
        thd->lex->unit.print(&str, QT_ORDINARY);
564
2602
        str.append('\0');
565
 
        push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
 
2603
        push_warning(thd, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
566
2604
                     ER_YES, str.ptr());
567
2605
      }
568
2606
      if (res)
574
2612
    else
575
2613
    {
576
2614
      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
 
 
 
2615
        return 1;                               /* purecov: inspected */
 
2616
      res= handle_select(thd, lex, result, 0);
585
2617
      if (result != lex->result)
586
2618
        delete result;
587
2619
    }
589
2621
  return res;
590
2622
}
591
2623
 
 
2624
/****************************************************************************
 
2625
        Check stack size; Send error if there isn't enough stack to continue
 
2626
****************************************************************************/
 
2627
#if STACK_DIRECTION < 0
 
2628
#define used_stack(A,B) (long) (A - B)
 
2629
#else
 
2630
#define used_stack(A,B) (long) (B - A)
 
2631
#endif
 
2632
 
 
2633
/**
 
2634
  @note
 
2635
  Note: The 'buf' parameter is necessary, even if it is unused here.
 
2636
  - fix_fields functions has a "dummy" buffer large enough for the
 
2637
    corresponding exec. (Thus we only have to check in fix_fields.)
 
2638
  - Passing to check_stack_overrun() prevents the compiler from removing it.
 
2639
*/
 
2640
bool check_stack_overrun(THD *thd, long margin,
 
2641
                         uchar *buf __attribute__((unused)))
 
2642
{
 
2643
  long stack_used;
 
2644
  assert(thd == current_thd);
 
2645
  if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >=
 
2646
      (long) (my_thread_stack_size - margin))
 
2647
  {
 
2648
    sprintf(errbuff[0],ER(ER_STACK_OVERRUN_NEED_MORE),
 
2649
            stack_used,my_thread_stack_size,margin);
 
2650
    my_message(ER_STACK_OVERRUN_NEED_MORE,errbuff[0],MYF(ME_FATALERROR));
 
2651
    return 1;
 
2652
  }
 
2653
  return 0;
 
2654
}
592
2655
 
593
2656
#define MY_YACC_INIT 1000                       // Start with big alloc
594
2657
#define MY_YACC_MAX  32000                      // Because of 'short'
595
2658
 
596
2659
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
597
2660
{
598
 
  LEX   *lex= current_session->lex;
 
2661
  LEX   *lex= current_thd->lex;
599
2662
  ulong old_info=0;
600
 
  if ((uint32_t) *yystacksize >= MY_YACC_MAX)
 
2663
  if ((uint) *yystacksize >= MY_YACC_MAX)
601
2664
    return 1;
602
2665
  if (!lex->yacc_yyvs)
603
2666
    old_info= *yystacksize;
604
2667
  *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;
 
2668
  if (!(lex->yacc_yyvs= (uchar*)
 
2669
        my_realloc(lex->yacc_yyvs,
 
2670
                   *yystacksize*sizeof(**yyvs),
 
2671
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
 
2672
      !(lex->yacc_yyss= (uchar*)
 
2673
        my_realloc(lex->yacc_yyss,
 
2674
                   *yystacksize*sizeof(**yyss),
 
2675
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
 
2676
    return 1;
615
2677
  if (old_info)
616
2678
  {                                             // Copy old info from stack
617
2679
    memcpy(lex->yacc_yyss, *yyss, old_info*sizeof(**yyss));
623
2685
}
624
2686
 
625
2687
 
 
2688
/**
 
2689
 Reset THD part responsible for command processing state.
 
2690
 
 
2691
   This needs to be called before execution of every statement
 
2692
   (prepared or conventional).
 
2693
   It is not called by substatements of routines.
 
2694
 
 
2695
  @todo
 
2696
   Make it a method of THD and align its name with the rest of
 
2697
   reset/end/start/init methods.
 
2698
  @todo
 
2699
   Call it after we use THD for queries, not before.
 
2700
*/
 
2701
 
 
2702
void mysql_reset_thd_for_next_command(THD *thd)
 
2703
{
 
2704
  assert(! thd->in_sub_stmt);
 
2705
  thd->free_list= 0;
 
2706
  thd->select_number= 1;
 
2707
  /*
 
2708
    Those two lines below are theoretically unneeded as
 
2709
    THD::cleanup_after_query() should take care of this already.
 
2710
  */
 
2711
  thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
 
2712
  thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
 
2713
 
 
2714
  thd->query_start_used= 0;
 
2715
  thd->is_fatal_error= thd->time_zone_used= 0;
 
2716
  thd->server_status&= ~ (SERVER_MORE_RESULTS_EXISTS | 
 
2717
                          SERVER_QUERY_NO_INDEX_USED |
 
2718
                          SERVER_QUERY_NO_GOOD_INDEX_USED);
 
2719
  /*
 
2720
    If in autocommit mode and not in a transaction, reset
 
2721
    OPTION_STATUS_NO_TRANS_UPDATE | OPTION_KEEP_LOG to not get warnings
 
2722
    in ha_rollback_trans() about some tables couldn't be rolled back.
 
2723
  */
 
2724
  if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)))
 
2725
  {
 
2726
    thd->options&= ~OPTION_KEEP_LOG;
 
2727
    thd->transaction.all.modified_non_trans_table= false;
 
2728
  }
 
2729
  assert(thd->security_ctx== &thd->main_security_ctx);
 
2730
  thd->thread_specific_used= false;
 
2731
 
 
2732
  if (opt_bin_log)
 
2733
  {
 
2734
    reset_dynamic(&thd->user_var_events);
 
2735
    thd->user_var_events_alloc= thd->mem_root;
 
2736
  }
 
2737
  thd->clear_error();
 
2738
  thd->main_da.reset_diagnostics_area();
 
2739
  thd->total_warn_count=0;                      // Warnings for this query
 
2740
  thd->rand_used= 0;
 
2741
  thd->sent_row_count= thd->examined_row_count= 0;
 
2742
 
 
2743
  /*
 
2744
    Because we come here only for start of top-statements, binlog format is
 
2745
    constant inside a complex statement (using stored functions) etc.
 
2746
  */
 
2747
  thd->reset_current_stmt_binlog_row_based();
 
2748
 
 
2749
  return;
 
2750
}
 
2751
 
 
2752
 
626
2753
void
627
 
init_select(LEX *lex)
 
2754
mysql_init_select(LEX *lex)
628
2755
{
629
 
  Select_Lex *select_lex= lex->current_select;
 
2756
  SELECT_LEX *select_lex= lex->current_select;
630
2757
  select_lex->init_select();
631
2758
  lex->wild= 0;
632
2759
  if (select_lex == &lex->select_lex)
638
2765
 
639
2766
 
640
2767
bool
641
 
new_select(LEX *lex, bool move_down)
 
2768
mysql_new_select(LEX *lex, bool move_down)
642
2769
{
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;
 
2770
  SELECT_LEX *select_lex;
 
2771
  THD *thd= lex->thd;
 
2772
 
 
2773
  if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
 
2774
    return(1);
 
2775
  select_lex->select_number= ++thd->select_number;
650
2776
  select_lex->parent_lex= lex; /* Used in init_query. */
651
2777
  select_lex->init_query();
652
2778
  select_lex->init_select();
653
2779
  lex->nest_level++;
654
 
 
655
2780
  if (lex->nest_level > (int) MAX_SELECT_NESTING)
656
2781
  {
657
2782
    my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
658
2783
    return(1);
659
2784
  }
660
 
 
661
2785
  select_lex->nest_level= lex->nest_level;
662
2786
  if (move_down)
663
2787
  {
664
 
    Select_Lex_Unit *unit;
 
2788
    SELECT_LEX_UNIT *unit;
 
2789
    lex->subqueries= true;
665
2790
    /* first select_lex of subselect or derived table */
666
 
    if (!(unit= new (session->mem_root) Select_Lex_Unit()))
 
2791
    if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
667
2792
      return(1);
668
2793
 
669
2794
    unit->init_query();
670
2795
    unit->init_select();
671
 
    unit->session= session;
 
2796
    unit->thd= thd;
672
2797
    unit->include_down(lex->current_select);
673
2798
    unit->link_next= 0;
674
2799
    unit->link_prev= 0;
684
2809
  {
685
2810
    if (lex->current_select->order_list.first && !lex->current_select->braces)
686
2811
    {
687
 
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "order_st BY");
688
 
      return true;
 
2812
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY");
 
2813
      return(1);
689
2814
    }
690
 
 
691
2815
    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=
 
2816
    SELECT_LEX_UNIT *unit= select_lex->master_unit();                              
 
2817
    if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->thd))
 
2818
      return(1);
 
2819
    select_lex->context.outer_context= 
698
2820
                unit->first_select()->context.outer_context;
699
2821
  }
700
2822
 
701
2823
  select_lex->master_unit()->global_parameters= select_lex;
702
 
  select_lex->include_global((Select_Lex_Node**)&lex->all_selects_list);
 
2824
  select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
703
2825
  lex->current_select= select_lex;
704
2826
  /*
705
2827
    in subquery is SELECT query and we allow resolution of names in SELECT
706
2828
    list
707
2829
  */
708
2830
  select_lex->context.resolve_in_select_list= true;
709
 
 
710
 
  return false;
 
2831
  return(0);
711
2832
}
712
2833
 
713
2834
/**
720
2841
  @param var_name               Variable name
721
2842
*/
722
2843
 
723
 
void create_select_for_variable(Session *session, const char *var_name)
 
2844
void create_select_for_variable(const char *var_name)
724
2845
{
 
2846
  THD *thd;
725
2847
  LEX *lex;
726
2848
  LEX_STRING tmp, null_lex_string;
727
2849
  Item *var;
728
 
  char buff[MAX_SYS_VAR_LENGTH*2+4+8];
729
 
  char *end= buff;
 
2850
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
730
2851
 
731
 
  lex= session->lex;
732
 
  init_select(lex);
 
2852
  thd= current_thd;
 
2853
  lex= thd->lex;
 
2854
  mysql_init_select(lex);
733
2855
  lex->sql_command= SQLCOM_SELECT;
734
2856
  tmp.str= (char*) var_name;
735
2857
  tmp.length=strlen(var_name);
738
2860
    We set the name of Item to @@session.var_name because that then is used
739
2861
    as the column name in the output.
740
2862
  */
741
 
  if ((var= get_system_var(session, OPT_SESSION, tmp, null_lex_string)))
 
2863
  if ((var= get_system_var(thd, OPT_SESSION, tmp, null_lex_string)))
742
2864
  {
743
 
    end+= snprintf(buff, sizeof(buff), "@@session.%s", var_name);
 
2865
    end= strxmov(buff, "@@session.", var_name, NullS);
744
2866
    var->set_name(buff, end-buff, system_charset_info);
745
 
    session->add_item_to_list(var);
 
2867
    add_item_to_list(thd, var);
746
2868
  }
747
 
}
748
 
 
 
2869
  return;
 
2870
}
 
2871
 
 
2872
 
 
2873
void mysql_init_multi_delete(LEX *lex)
 
2874
{
 
2875
  lex->sql_command=  SQLCOM_DELETE_MULTI;
 
2876
  mysql_init_select(lex);
 
2877
  lex->select_lex.select_limit= 0;
 
2878
  lex->unit.select_limit_cnt= HA_POS_ERROR;
 
2879
  lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list);
 
2880
  lex->lock_option= using_update_log ? TL_READ_NO_INSERT : TL_READ;
 
2881
  lex->query_tables= 0;
 
2882
  lex->query_tables_last= &lex->query_tables;
 
2883
}
 
2884
 
 
2885
 
 
2886
/*
 
2887
  When you modify mysql_parse(), you may need to mofify
 
2888
  mysql_test_parse_for_slave() in this same file.
 
2889
*/
749
2890
 
750
2891
/**
751
2892
  Parse a query.
752
2893
 
753
 
  @param       session     Current thread
 
2894
  @param       thd     Current thread
754
2895
  @param       inBuf   Begining of the query text
755
2896
  @param       length  Length of the query text
 
2897
  @param[out]  found_semicolon For multi queries, position of the character of
 
2898
                               the next query in the query text.
756
2899
*/
757
2900
 
758
 
void parse(Session *session, const char *inBuf, uint32_t length)
 
2901
void mysql_parse(THD *thd, const char *inBuf, uint length,
 
2902
                 const char ** found_semicolon)
759
2903
{
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
 
  {
 
2904
  /*
 
2905
    Warning.
 
2906
    The purpose of query_cache_send_result_to_client() is to lookup the
 
2907
    query in the query cache first, to avoid parsing and executing it.
 
2908
    So, the natural implementation would be to:
 
2909
    - first, call query_cache_send_result_to_client,
 
2910
    - second, if caching failed, initialise the lexical and syntactic parser.
 
2911
    The problem is that the query cache depends on a clean initialization
 
2912
    of (among others) lex->safe_to_cache_query and thd->server_status,
 
2913
    which are reset respectively in
 
2914
    - lex_start()
 
2915
    - mysql_reset_thd_for_next_command()
 
2916
    So, initializing the lexical analyser *before* using the query cache
 
2917
    is required for the cache to work properly.
 
2918
    FIXME: cleanup the dependencies in the code to simplify this.
 
2919
  */
 
2920
  lex_start(thd);
 
2921
  mysql_reset_thd_for_next_command(thd);
 
2922
 
 
2923
  {
 
2924
    LEX *lex= thd->lex;
 
2925
 
 
2926
    Lex_input_stream lip(thd, inBuf, length);
 
2927
 
 
2928
    bool err= parse_sql(thd, &lip, NULL);
 
2929
    *found_semicolon= lip.found_semicolon;
 
2930
 
 
2931
    if (!err)
781
2932
    {
782
 
      if (not session->is_error())
783
2933
      {
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);
 
2934
        if (! thd->is_error())
 
2935
        {
 
2936
          /*
 
2937
            Binlog logs a string starting from thd->query and having length
 
2938
            thd->query_length; so we set thd->query_length correctly (to not
 
2939
            log several statements in one event, when we executed only first).
 
2940
            We set it to not see the ';' (otherwise it would get into binlog
 
2941
            and Query_log_event::print() would give ';;' output).
 
2942
            This also helps display only the current query in SHOW
 
2943
            PROCESSLIST.
 
2944
            Note that we don't need LOCK_thread_count to modify query_length.
 
2945
          */
 
2946
          if (*found_semicolon &&
 
2947
              (thd->query_length= (ulong)(*found_semicolon - thd->query)))
 
2948
            thd->query_length--;
 
2949
          /* Actually execute the query */
 
2950
          mysql_execute_command(thd);
 
2951
        }
800
2952
      }
801
2953
    }
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();
 
2954
    else
 
2955
    {
 
2956
      assert(thd->is_error());
 
2957
    }
 
2958
    lex->unit.cleanup();
 
2959
    thd_proc_info(thd, "freeing items");
 
2960
    thd->end_statement();
 
2961
    thd->cleanup_after_query();
 
2962
    assert(thd->change_list.is_empty());
 
2963
  }
 
2964
 
 
2965
  return;
 
2966
}
 
2967
 
 
2968
 
 
2969
/*
 
2970
  Usable by the replication SQL thread only: just parse a query to know if it
 
2971
  can be ignored because of replicate-*-table rules.
 
2972
 
 
2973
  @retval
 
2974
    0   cannot be ignored
 
2975
  @retval
 
2976
    1   can be ignored
 
2977
*/
 
2978
 
 
2979
bool mysql_test_parse_for_slave(THD *thd, char *inBuf, uint length)
 
2980
{
 
2981
  LEX *lex= thd->lex;
 
2982
  bool error= 0;
 
2983
 
 
2984
  Lex_input_stream lip(thd, inBuf, length);
 
2985
  lex_start(thd);
 
2986
  mysql_reset_thd_for_next_command(thd);
 
2987
 
 
2988
  if (!parse_sql(thd, &lip, NULL) &&
 
2989
      all_tables_not_ok(thd,(TABLE_LIST*) lex->select_lex.table_list.first))
 
2990
    error= 1;                  /* Ignore question */
 
2991
  thd->end_statement();
 
2992
  thd->cleanup_after_query();
 
2993
  return(error);
812
2994
}
813
2995
 
814
2996
 
820
3002
    Return 0 if ok
821
3003
*/
822
3004
 
823
 
bool add_field_to_list(Session *session, LEX_STRING *field_name, enum_field_types type,
 
3005
bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum_field_types type,
824
3006
                       char *length, char *decimals,
825
 
                       uint32_t type_modifier,
 
3007
                       uint type_modifier,
826
3008
                       enum column_format_type column_format,
827
3009
                       Item *default_value, Item *on_update_value,
828
3010
                       LEX_STRING *comment,
829
3011
                       char *change,
830
3012
                       List<String> *interval_list, const CHARSET_INFO * const cs)
831
3013
{
832
 
  register CreateField *new_field;
833
 
  LEX  *lex= session->lex;
834
 
  statement::AlterTable *statement= (statement::AlterTable *)lex->statement;
 
3014
  register Create_field *new_field;
 
3015
  LEX  *lex= thd->lex;
835
3016
 
836
3017
  if (check_identifier_name(field_name, ER_TOO_LONG_IDENT))
837
 
    return true;
 
3018
    return(1);                          /* purecov: inspected */
838
3019
 
839
3020
  if (type_modifier & PRI_KEY_FLAG)
840
3021
  {
843
3024
    key= new Key(Key::PRIMARY, null_lex_str,
844
3025
                      &default_key_create_info,
845
3026
                      0, lex->col_list);
846
 
    statement->alter_info.key_list.push_back(key);
 
3027
    lex->alter_info.key_list.push_back(key);
847
3028
    lex->col_list.empty();
848
3029
  }
849
3030
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
853
3034
    key= new Key(Key::UNIQUE, null_lex_str,
854
3035
                 &default_key_create_info, 0,
855
3036
                 lex->col_list);
856
 
    statement->alter_info.key_list.push_back(key);
 
3037
    lex->alter_info.key_list.push_back(key);
857
3038
    lex->col_list.empty();
858
3039
  }
859
3040
 
860
3041
  if (default_value)
861
3042
  {
862
 
    /*
 
3043
    /* 
863
3044
      Default value should be literal => basic constants =>
864
3045
      no need fix_fields()
865
 
 
866
 
      We allow only one function as part of default value -
 
3046
      
 
3047
      We allow only one function as part of default value - 
867
3048
      NOW() as default for TIMESTAMP type.
868
3049
    */
869
 
    if (default_value->type() == Item::FUNC_ITEM &&
 
3050
    if (default_value->type() == Item::FUNC_ITEM && 
870
3051
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
871
 
         (type == DRIZZLE_TYPE_TIMESTAMP or type == DRIZZLE_TYPE_MICROTIME)))
 
3052
         type == DRIZZLE_TYPE_TIMESTAMP))
872
3053
    {
873
3054
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
874
 
      return true;
 
3055
      return(1);
875
3056
    }
876
3057
    else if (default_value->type() == Item::NULL_ITEM)
877
3058
    {
878
3059
      default_value= 0;
879
 
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) == NOT_NULL_FLAG)
 
3060
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
 
3061
          NOT_NULL_FLAG)
880
3062
      {
881
3063
        my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
882
 
        return true;
 
3064
        return(1);
883
3065
      }
884
3066
    }
885
3067
    else if (type_modifier & AUTO_INCREMENT_FLAG)
886
3068
    {
887
3069
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
888
 
      return true;
 
3070
      return(1);
889
3071
    }
890
3072
  }
891
3073
 
892
 
  if (on_update_value && (type != DRIZZLE_TYPE_TIMESTAMP and type != DRIZZLE_TYPE_MICROTIME))
 
3074
  if (on_update_value && type != DRIZZLE_TYPE_TIMESTAMP)
893
3075
  {
894
3076
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
895
 
    return true;
 
3077
    return(1);
896
3078
  }
897
3079
 
898
 
  if (!(new_field= new CreateField()) ||
899
 
      new_field->init(session, field_name->str, type, length, decimals, type_modifier,
 
3080
  if (!(new_field= new Create_field()) ||
 
3081
      new_field->init(thd, field_name->str, type, length, decimals, type_modifier,
900
3082
                      default_value, on_update_value, comment, change,
901
3083
                      interval_list, cs, 0, column_format))
902
 
    return true;
 
3084
    return(1);
903
3085
 
904
 
  statement->alter_info.create_list.push_back(new_field);
 
3086
  lex->alter_info.create_list.push_back(new_field);
905
3087
  lex->last_field=new_field;
906
 
 
907
 
  return false;
 
3088
  return(0);
 
3089
}
 
3090
 
 
3091
 
 
3092
/** Store position for column in ALTER TABLE .. ADD column. */
 
3093
 
 
3094
void store_position_for_column(const char *name)
 
3095
{
 
3096
  current_thd->lex->last_field->after=my_const_cast(char*) (name);
 
3097
}
 
3098
 
 
3099
bool
 
3100
add_proc_to_list(THD* thd, Item *item)
 
3101
{
 
3102
  ORDER *order;
 
3103
  Item  **item_ptr;
 
3104
 
 
3105
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*))))
 
3106
    return 1;
 
3107
  item_ptr = (Item**) (order+1);
 
3108
  *item_ptr= item;
 
3109
  order->item=item_ptr;
 
3110
  order->free_me=0;
 
3111
  thd->lex->proc_list.link_in_list((uchar*) order,(uchar**) &order->next);
 
3112
  return 0;
 
3113
}
 
3114
 
 
3115
 
 
3116
/**
 
3117
  save order by and tables in own lists.
 
3118
*/
 
3119
 
 
3120
bool add_to_list(THD *thd, SQL_LIST &list,Item *item,bool asc)
 
3121
{
 
3122
  ORDER *order;
 
3123
  if (!(order = (ORDER *) thd->alloc(sizeof(ORDER))))
 
3124
    return(1);
 
3125
  order->item_ptr= item;
 
3126
  order->item= &order->item_ptr;
 
3127
  order->asc = asc;
 
3128
  order->free_me=0;
 
3129
  order->used=0;
 
3130
  order->counter_used= 0;
 
3131
  list.link_in_list((uchar*) order,(uchar**) &order->next);
 
3132
  return(0);
908
3133
}
909
3134
 
910
3135
 
924
3149
  @retval
925
3150
      0         Error
926
3151
  @retval
927
 
    \#  Pointer to TableList element added to the total table list
 
3152
    \#  Pointer to TABLE_LIST element added to the total table list
928
3153
*/
929
3154
 
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)
 
3155
TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
 
3156
                                             Table_ident *table,
 
3157
                                             LEX_STRING *alias,
 
3158
                                             uint32_t table_options,
 
3159
                                             thr_lock_type lock_type,
 
3160
                                             List<Index_hint> *index_hints_arg,
 
3161
                                             LEX_STRING *option)
937
3162
{
938
 
  TableList *ptr;
939
 
  TableList *previous_table_ref; /* The table preceding the current one. */
 
3163
  register TABLE_LIST *ptr;
 
3164
  TABLE_LIST *previous_table_ref; /* The table preceding the current one. */
940
3165
  char *alias_str;
941
 
  LEX *lex= session->lex;
 
3166
  LEX *lex= thd->lex;
942
3167
 
943
3168
  if (!table)
944
 
    return NULL;                                // End of memory
 
3169
    return(0);                          // End of memory
945
3170
  alias_str= alias ? alias->str : table->table.str;
946
 
  if (! table_options.test(TL_OPTION_ALIAS) &&
 
3171
  if (!test(table_options & TL_OPTION_ALIAS) && 
947
3172
      check_table_name(table->table.str, table->table.length))
948
3173
  {
949
3174
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
950
 
    return NULL;
 
3175
    return(0);
951
3176
  }
952
3177
 
953
 
  if (table->is_derived_table() == false && table->db.str)
 
3178
  if (table->is_derived_table() == false && table->db.str &&
 
3179
      check_db_name(&table->db))
954
3180
  {
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
 
    }
 
3181
    my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
 
3182
    return(0);
964
3183
  }
965
3184
 
966
3185
  if (!alias)                                   /* Alias is case sensitive */
969
3188
    {
970
3189
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
971
3190
                 ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
972
 
      return NULL;
 
3191
      return(0);
973
3192
    }
974
 
    if (!(alias_str= (char*) session->getMemRoot()->duplicate(alias_str,table->table.length+1)))
975
 
      return NULL;
 
3193
    if (!(alias_str= (char*) thd->memdup(alias_str,table->table.length+1)))
 
3194
      return(0);
976
3195
  }
977
 
  if (!(ptr = (TableList *) session->calloc(sizeof(TableList))))
978
 
    return NULL;
979
 
 
 
3196
  if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST))))
 
3197
    return(0);                          /* purecov: inspected */
980
3198
  if (table->db.str)
981
3199
  {
982
 
    ptr->setIsFqtn(true);
983
 
    ptr->setSchemaName(table->db.str);
 
3200
    ptr->is_fqtn= true;
 
3201
    ptr->db= table->db.str;
984
3202
    ptr->db_length= table->db.length;
985
3203
  }
986
 
  else if (lex->copy_db_to(ptr->getSchemaNamePtr(), &ptr->db_length))
987
 
    return NULL;
 
3204
  else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
 
3205
    return(0);
988
3206
  else
989
 
    ptr->setIsFqtn(false);
 
3207
    ptr->is_fqtn= false;
990
3208
 
991
3209
  ptr->alias= alias_str;
992
 
  ptr->setIsAlias(alias ? true : false);
993
 
  ptr->setTableName(table->table.str);
 
3210
  ptr->is_alias= alias ? true : false;
 
3211
  if (lower_case_table_names && table->table.length)
 
3212
    table->table.length= my_casedn_str(files_charset_info, table->table.str);
 
3213
  ptr->table_name=table->table.str;
994
3214
  ptr->table_name_length=table->table.length;
995
3215
  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);
 
3216
  ptr->lock_timeout= -1;      /* default timeout */
 
3217
  ptr->lock_transactional= 1; /* allow transactional locks */
 
3218
  ptr->updating=    test(table_options & TL_OPTION_UPDATING);
 
3219
  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
 
3220
  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
998
3221
  ptr->derived=     table->sel;
 
3222
  if (!ptr->derived && !my_strcasecmp(system_charset_info, ptr->db,
 
3223
                                      INFORMATION_SCHEMA_NAME.str))
 
3224
  {
 
3225
    ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, ptr->table_name);
 
3226
    if (!schema_table ||
 
3227
        (schema_table->hidden && 
 
3228
         ((sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0 || 
 
3229
          /*
 
3230
            this check is used for show columns|keys from I_S hidden table
 
3231
          */
 
3232
          lex->sql_command == SQLCOM_SHOW_FIELDS ||
 
3233
          lex->sql_command == SQLCOM_SHOW_KEYS)))
 
3234
    {
 
3235
      my_error(ER_UNKNOWN_TABLE, MYF(0),
 
3236
               ptr->table_name, INFORMATION_SCHEMA_NAME.str);
 
3237
      return(0);
 
3238
    }
 
3239
    ptr->schema_table_name= ptr->table_name;
 
3240
    ptr->schema_table= schema_table;
 
3241
  }
999
3242
  ptr->select_lex=  lex->current_select;
 
3243
  ptr->cacheable_table= 1;
1000
3244
  ptr->index_hints= index_hints_arg;
1001
3245
  ptr->option= option ? option->str : 0;
1002
3246
  /* check that used name is unique */
1003
3247
  if (lock_type != TL_IGNORE)
1004
3248
  {
1005
 
    TableList *first_table= (TableList*) table_list.first;
1006
 
    for (TableList *tables= first_table ;
 
3249
    TABLE_LIST *first_table= (TABLE_LIST*) table_list.first;
 
3250
    for (TABLE_LIST *tables= first_table ;
1007
3251
         tables ;
1008
3252
         tables=tables->next_local)
1009
3253
    {
1010
 
      if (not my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
1011
 
          not my_strcasecmp(system_charset_info, ptr->getSchemaName(), tables->getSchemaName()))
 
3254
      if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
 
3255
          !strcmp(ptr->db, tables->db))
1012
3256
      {
1013
 
        my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str);
1014
 
        return NULL;
 
3257
        my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
 
3258
        return(0);                              /* purecov: tested */
1015
3259
      }
1016
3260
    }
1017
3261
  }
1019
3263
  if (table_list.elements > 0)
1020
3264
  {
1021
3265
    /*
1022
 
      table_list.next points to the last inserted TableList->next_local'
 
3266
      table_list.next points to the last inserted TABLE_LIST->next_local'
1023
3267
      element
1024
3268
      We don't use the offsetof() macro here to avoid warnings from gcc
1025
3269
    */
1026
 
    previous_table_ref= (TableList*) ((char*) table_list.next -
 
3270
    previous_table_ref= (TABLE_LIST*) ((char*) table_list.next -
1027
3271
                                       ((char*) &(ptr->next_local) -
1028
3272
                                        (char*) ptr));
1029
3273
    /*
1030
3274
      Set next_name_resolution_table of the previous table reference to point
1031
3275
      to the current table reference. In effect the list
1032
 
      TableList::next_name_resolution_table coincides with
1033
 
      TableList::next_local. Later this may be changed in
 
3276
      TABLE_LIST::next_name_resolution_table coincides with
 
3277
      TABLE_LIST::next_local. Later this may be changed in
1034
3278
      store_top_level_join_columns() for NATURAL/USING joins.
1035
3279
    */
1036
3280
    previous_table_ref->next_name_resolution_table= ptr;
1042
3286
    previous table reference to 'ptr'. Here we also add one element to the
1043
3287
    list 'table_list'.
1044
3288
  */
1045
 
  table_list.link_in_list((unsigned char*) ptr, (unsigned char**) &ptr->next_local);
 
3289
  table_list.link_in_list((uchar*) ptr, (uchar**) &ptr->next_local);
1046
3290
  ptr->next_name_resolution_table= NULL;
1047
3291
  /* Link table in global list (all used tables) */
1048
3292
  lex->add_to_query_tables(ptr);
1049
 
  return ptr;
 
3293
  return(ptr);
1050
3294
}
1051
3295
 
1052
3296
 
1053
3297
/**
1054
3298
  Initialize a new table list for a nested join.
1055
3299
 
1056
 
    The function initializes a structure of the TableList type
 
3300
    The function initializes a structure of the TABLE_LIST type
1057
3301
    for a nested join. It sets up its nested join list as empty.
1058
3302
    The created structure is added to the front of the current
1059
 
    join list in the Select_Lex object. Then the function
 
3303
    join list in the st_select_lex object. Then the function
1060
3304
    changes the current nest level for joins to refer to the newly
1061
3305
    created empty list after having saved the info on the old level
1062
3306
    in the initialized structure.
1063
3307
 
1064
 
  @param session         current thread
 
3308
  @param thd         current thread
1065
3309
 
1066
3310
  @retval
1067
3311
    0   if success
1069
3313
    1   otherwise
1070
3314
*/
1071
3315
 
1072
 
bool Select_Lex::init_nested_join(Session *session)
 
3316
bool st_select_lex::init_nested_join(THD *thd)
1073
3317
{
1074
 
  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();
 
3318
  TABLE_LIST *ptr;
 
3319
  NESTED_JOIN *nested_join;
 
3320
 
 
3321
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
 
3322
                                       sizeof(NESTED_JOIN))))
 
3323
    return(1);
 
3324
  nested_join= ptr->nested_join=
 
3325
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
 
3326
 
1082
3327
  join_list->push_front(ptr);
1083
 
  ptr->setEmbedding(embedding);
1084
 
  ptr->setJoinList(join_list);
 
3328
  ptr->embedding= embedding;
 
3329
  ptr->join_list= join_list;
1085
3330
  ptr->alias= (char*) "(nested_join)";
1086
3331
  embedding= ptr;
1087
3332
  join_list= &nested_join->join_list;
1088
3333
  join_list->empty();
1089
 
  return false;
 
3334
  return(0);
1090
3335
}
1091
3336
 
1092
3337
 
1097
3342
    If the current level contains only one member, the function
1098
3343
    moves it one level up, eliminating the nest.
1099
3344
 
1100
 
  @param session         current thread
 
3345
  @param thd         current thread
1101
3346
 
1102
3347
  @return
1103
 
    - Pointer to TableList element added to the total table list, if success
 
3348
    - Pointer to TABLE_LIST element added to the total table list, if success
1104
3349
    - 0, otherwise
1105
3350
*/
1106
3351
 
1107
 
TableList *Select_Lex::end_nested_join(Session *)
 
3352
TABLE_LIST *st_select_lex::end_nested_join(THD *thd __attribute__((unused)))
1108
3353
{
1109
 
  TableList *ptr;
1110
 
  NestedJoin *nested_join;
 
3354
  TABLE_LIST *ptr;
 
3355
  NESTED_JOIN *nested_join;
1111
3356
 
1112
3357
  assert(embedding);
1113
3358
  ptr= embedding;
1114
 
  join_list= ptr->getJoinList();
1115
 
  embedding= ptr->getEmbedding();
1116
 
  nested_join= ptr->getNestedJoin();
 
3359
  join_list= ptr->join_list;
 
3360
  embedding= ptr->embedding;
 
3361
  nested_join= ptr->nested_join;
1117
3362
  if (nested_join->join_list.elements == 1)
1118
3363
  {
1119
 
    TableList *embedded= nested_join->join_list.head();
 
3364
    TABLE_LIST *embedded= nested_join->join_list.head();
1120
3365
    join_list->pop();
1121
 
    embedded->setJoinList(join_list);
1122
 
    embedded->setEmbedding(embedding);
 
3366
    embedded->join_list= join_list;
 
3367
    embedded->embedding= embedding;
1123
3368
    join_list->push_front(embedded);
1124
3369
    ptr= embedded;
1125
3370
  }
1126
3371
  else if (nested_join->join_list.elements == 0)
1127
3372
  {
1128
3373
    join_list->pop();
1129
 
    ptr= NULL;                                     // return value
 
3374
    ptr= 0;                                     // return value
1130
3375
  }
1131
 
  return ptr;
 
3376
  return(ptr);
1132
3377
}
1133
3378
 
1134
3379
 
1137
3382
 
1138
3383
    The function nest last join operation as if it was enclosed in braces.
1139
3384
 
1140
 
  @param session         current thread
 
3385
  @param thd         current thread
1141
3386
 
1142
3387
  @retval
1143
3388
    0  Error
1144
3389
  @retval
1145
 
    \#  Pointer to TableList element created for the new nested join
 
3390
    \#  Pointer to TABLE_LIST element created for the new nested join
1146
3391
*/
1147
3392
 
1148
 
TableList *Select_Lex::nest_last_join(Session *session)
 
3393
TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
1149
3394
{
1150
 
  TableList *ptr;
1151
 
  NestedJoin *nested_join;
1152
 
  List<TableList> *embedded_list;
1153
 
 
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);
 
3395
  TABLE_LIST *ptr;
 
3396
  NESTED_JOIN *nested_join;
 
3397
  List<TABLE_LIST> *embedded_list;
 
3398
 
 
3399
  if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
 
3400
                                       sizeof(NESTED_JOIN))))
 
3401
    return(0);
 
3402
  nested_join= ptr->nested_join=
 
3403
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
 
3404
 
 
3405
  ptr->embedding= embedding;
 
3406
  ptr->join_list= join_list;
1161
3407
  ptr->alias= (char*) "(nest_last_join)";
1162
3408
  embedded_list= &nested_join->join_list;
1163
3409
  embedded_list->empty();
1164
3410
 
1165
 
  for (uint32_t i=0; i < 2; i++)
 
3411
  for (uint i=0; i < 2; i++)
1166
3412
  {
1167
 
    TableList *table= join_list->pop();
1168
 
    table->setJoinList(embedded_list);
1169
 
    table->setEmbedding(ptr);
 
3413
    TABLE_LIST *table= join_list->pop();
 
3414
    table->join_list= embedded_list;
 
3415
    table->embedding= ptr;
1170
3416
    embedded_list->push_back(table);
1171
3417
    if (table->natural_join)
1172
3418
    {
1181
3427
  }
1182
3428
  join_list->push_front(ptr);
1183
3429
  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
1184
 
  return ptr;
 
3430
  return(ptr);
1185
3431
}
1186
3432
 
1187
3433
 
1189
3435
  Add a table to the current join list.
1190
3436
 
1191
3437
    The function puts a table in front of the current join list
1192
 
    of Select_Lex object.
 
3438
    of st_select_lex object.
1193
3439
    Thus, joined tables are put into this list in the reverse order
1194
3440
    (the most outer join operation follows first).
1195
3441
 
1199
3445
    None
1200
3446
*/
1201
3447
 
1202
 
void Select_Lex::add_joined_table(TableList *table)
 
3448
void st_select_lex::add_joined_table(TABLE_LIST *table)
1203
3449
{
1204
3450
  join_list->push_front(table);
1205
 
  table->setJoinList(join_list);
1206
 
  table->setEmbedding(embedding);
 
3451
  table->join_list= join_list;
 
3452
  table->embedding= embedding;
 
3453
  return;
1207
3454
}
1208
3455
 
1209
3456
 
1231
3478
      SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1
1232
3479
   @endverbatim
1233
3480
 
1234
 
  @param session         current thread
 
3481
  @param thd         current thread
1235
3482
 
1236
3483
  @return
1237
3484
    - Pointer to the table representing the inner table, if success
1238
3485
    - 0, otherwise
1239
3486
*/
1240
3487
 
1241
 
TableList *Select_Lex::convert_right_join()
 
3488
TABLE_LIST *st_select_lex::convert_right_join()
1242
3489
{
1243
 
  TableList *tab2= join_list->pop();
1244
 
  TableList *tab1= join_list->pop();
 
3490
  TABLE_LIST *tab2= join_list->pop();
 
3491
  TABLE_LIST *tab1= join_list->pop();
1245
3492
 
1246
3493
  join_list->push_front(tab2);
1247
3494
  join_list->push_front(tab1);
1248
3495
  tab1->outer_join|= JOIN_TYPE_RIGHT;
1249
3496
 
1250
 
  return tab1;
 
3497
  return(tab1);
1251
3498
}
1252
3499
 
1253
3500
/**
1261
3508
    query
1262
3509
*/
1263
3510
 
1264
 
void Select_Lex::set_lock_for_tables(thr_lock_type lock_type)
 
3511
void st_select_lex::set_lock_for_tables(thr_lock_type lock_type)
1265
3512
{
1266
 
  for (TableList *tables= (TableList*) table_list.first;
 
3513
  bool for_update= lock_type >= TL_READ_NO_INSERT;
 
3514
 
 
3515
  for (TABLE_LIST *tables= (TABLE_LIST*) table_list.first;
1267
3516
       tables;
1268
3517
       tables= tables->next_local)
1269
3518
  {
1270
3519
    tables->lock_type= lock_type;
 
3520
    tables->updating=  for_update;
1271
3521
  }
 
3522
  return;
1272
3523
}
1273
3524
 
1274
3525
 
1275
3526
/**
1276
 
  Create a fake Select_Lex for a unit.
 
3527
  Create a fake SELECT_LEX for a unit.
1277
3528
 
1278
 
    The method create a fake Select_Lex object for a unit.
 
3529
    The method create a fake SELECT_LEX object for a unit.
1279
3530
    This object is created for any union construct containing a union
1280
3531
    operation and also for any single select union construct of the form
1281
3532
    @verbatim
1282
 
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ...
 
3533
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ... 
1283
3534
    @endvarbatim
1284
3535
    or of the form
1285
3536
    @varbatim
1286
3537
    (SELECT ... ORDER BY LIMIT n) ORDER BY ...
1287
3538
    @endvarbatim
1288
 
 
1289
 
  @param session_arg               thread handle
 
3539
  
 
3540
  @param thd_arg                   thread handle
1290
3541
 
1291
3542
  @note
1292
3543
    The object is used to retrieve rows from the temporary table
1298
3549
    0     on success
1299
3550
*/
1300
3551
 
1301
 
bool Select_Lex_Unit::add_fake_select_lex(Session *session_arg)
 
3552
bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg)
1302
3553
{
1303
 
  Select_Lex *first_sl= first_select();
 
3554
  SELECT_LEX *first_sl= first_select();
1304
3555
  assert(!fake_select_lex);
1305
3556
 
1306
 
  if (!(fake_select_lex= new (session_arg->mem_root) Select_Lex()))
 
3557
  if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX()))
1307
3558
      return(1);
1308
 
  fake_select_lex->include_standalone(this,
1309
 
                                      (Select_Lex_Node**)&fake_select_lex);
 
3559
  fake_select_lex->include_standalone(this, 
 
3560
                                      (SELECT_LEX_NODE**)&fake_select_lex);
1310
3561
  fake_select_lex->select_number= INT_MAX;
1311
 
  fake_select_lex->parent_lex= session_arg->lex; /* Used in init_query. */
 
3562
  fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */
1312
3563
  fake_select_lex->make_empty_select();
1313
3564
  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
1314
3565
  fake_select_lex->select_limit= 0;
1320
3571
 
1321
3572
  if (!is_union())
1322
3573
  {
1323
 
    /*
1324
 
      This works only for
 
3574
    /* 
 
3575
      This works only for 
1325
3576
      (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
1326
3577
      (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
1327
3578
      just before the parser starts processing order_list
1328
 
    */
 
3579
    */ 
1329
3580
    global_parameters= fake_select_lex;
1330
3581
    fake_select_lex->no_table_names_allowed= 1;
1331
 
    session_arg->lex->current_select= fake_select_lex;
 
3582
    thd_arg->lex->current_select= fake_select_lex;
1332
3583
  }
1333
 
  session_arg->lex->pop_context();
 
3584
  thd_arg->lex->pop_context();
1334
3585
  return(0);
1335
3586
}
1336
3587
 
1344
3595
    to be used for name resolution, and push the newly created
1345
3596
    context to the stack of contexts of the query.
1346
3597
 
1347
 
  @param session       pointer to current thread
 
3598
  @param thd       pointer to current thread
1348
3599
  @param left_op   left  operand of the JOIN
1349
3600
  @param right_op  rigth operand of the JOIN
1350
3601
 
1355
3606
*/
1356
3607
 
1357
3608
bool
1358
 
push_new_name_resolution_context(Session *session,
1359
 
                                 TableList *left_op, TableList *right_op)
 
3609
push_new_name_resolution_context(THD *thd,
 
3610
                                 TABLE_LIST *left_op, TABLE_LIST *right_op)
1360
3611
{
1361
3612
  Name_resolution_context *on_context;
1362
 
  if (!(on_context= new (session->mem_root) Name_resolution_context))
 
3613
  if (!(on_context= new (thd->mem_root) Name_resolution_context))
1363
3614
    return true;
1364
3615
  on_context->init();
1365
3616
  on_context->first_name_resolution_table=
1366
3617
    left_op->first_leaf_for_name_resolution();
1367
3618
  on_context->last_name_resolution_table=
1368
3619
    right_op->last_leaf_for_name_resolution();
1369
 
  return session->lex->push_context(on_context);
 
3620
  return thd->lex->push_context(on_context);
1370
3621
}
1371
3622
 
1372
3623
 
1384
3635
    true   if all is OK
1385
3636
*/
1386
3637
 
1387
 
void add_join_on(TableList *b, Item *expr)
 
3638
void add_join_on(TABLE_LIST *b, Item *expr)
1388
3639
{
1389
3640
  if (expr)
1390
3641
  {
1437
3688
  @param using_fields    Field names from USING clause
1438
3689
*/
1439
3690
 
1440
 
void add_join_natural(TableList *a, TableList *b, List<String> *using_fields,
1441
 
                      Select_Lex *lex)
 
3691
void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields,
 
3692
                      SELECT_LEX *lex)
1442
3693
{
1443
3694
  b->natural_join= a;
1444
3695
  lex->prev_join_using= using_fields;
1446
3697
 
1447
3698
 
1448
3699
/**
 
3700
  Reload/resets privileges and the different caches.
 
3701
 
 
3702
  @param thd Thread handler (can be NULL!)
 
3703
  @param options What should be reset/reloaded (tables, privileges, slave...)
 
3704
  @param tables Tables to flush (if any)
 
3705
  @param write_to_binlog True if we can write to the binlog.
 
3706
               
 
3707
  @note Depending on 'options', it may be very bad to write the
 
3708
    query to the binlog (e.g. FLUSH SLAVE); this is a
 
3709
    pointer where reload_cache() will put 0 if
 
3710
    it thinks we really should not write to the binlog.
 
3711
    Otherwise it will put 1.
 
3712
 
 
3713
  @return Error status code
 
3714
    @retval 0 Ok
 
3715
    @retval !=0  Error; thd->killed is set or thd->is_error() is true
 
3716
*/
 
3717
 
 
3718
bool reload_cache(THD *thd, ulong options, TABLE_LIST *tables,
 
3719
                          bool *write_to_binlog)
 
3720
{
 
3721
  bool result=0;
 
3722
  select_errors=0;                              /* Write if more errors */
 
3723
  bool tmp_write_to_binlog= 1;
 
3724
 
 
3725
  assert(!thd || !thd->in_sub_stmt);
 
3726
 
 
3727
  if (options & REFRESH_LOG)
 
3728
  {
 
3729
    /*
 
3730
      Flush the normal query log, the update log, the binary log,
 
3731
      the slow query log, the relay log (if it exists) and the log
 
3732
      tables.
 
3733
    */
 
3734
 
 
3735
    /*
 
3736
      Writing this command to the binlog may result in infinite loops
 
3737
      when doing mysqlbinlog|mysql, and anyway it does not really make
 
3738
      sense to log it automatically (would cause more trouble to users
 
3739
      than it would help them)
 
3740
    */
 
3741
    tmp_write_to_binlog= 0;
 
3742
    if( mysql_bin_log.is_open() )
 
3743
    {
 
3744
      mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
 
3745
    }
 
3746
    pthread_mutex_lock(&LOCK_active_mi);
 
3747
    rotate_relay_log(active_mi);
 
3748
    pthread_mutex_unlock(&LOCK_active_mi);
 
3749
 
 
3750
    /* flush slow and general logs */
 
3751
    logger.flush_logs(thd);
 
3752
 
 
3753
    if (ha_flush_logs(NULL))
 
3754
      result=1;
 
3755
    if (flush_error_log())
 
3756
      result=1;
 
3757
  }
 
3758
  /*
 
3759
    Note that if REFRESH_READ_LOCK bit is set then REFRESH_TABLES is set too
 
3760
    (see sql_yacc.yy)
 
3761
  */
 
3762
  if (options & (REFRESH_TABLES | REFRESH_READ_LOCK)) 
 
3763
  {
 
3764
    if ((options & REFRESH_READ_LOCK) && thd)
 
3765
    {
 
3766
      /*
 
3767
        We must not try to aspire a global read lock if we have a write
 
3768
        locked table. This would lead to a deadlock when trying to
 
3769
        reopen (and re-lock) the table after the flush.
 
3770
      */
 
3771
      if (thd->locked_tables)
 
3772
      {
 
3773
        THR_LOCK_DATA **lock_p= thd->locked_tables->locks;
 
3774
        THR_LOCK_DATA **end_p= lock_p + thd->locked_tables->lock_count;
 
3775
 
 
3776
        for (; lock_p < end_p; lock_p++)
 
3777
        {
 
3778
          if ((*lock_p)->type >= TL_WRITE_ALLOW_WRITE)
 
3779
          {
 
3780
            my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
 
3781
            return 1;
 
3782
          }
 
3783
        }
 
3784
      }
 
3785
      /*
 
3786
        Writing to the binlog could cause deadlocks, as we don't log
 
3787
        UNLOCK TABLES
 
3788
      */
 
3789
      tmp_write_to_binlog= 0;
 
3790
      if (lock_global_read_lock(thd))
 
3791
        return 1;                               // Killed
 
3792
      result= close_cached_tables(thd, tables, false, (options & REFRESH_FAST) ?
 
3793
                                  false : true, true);
 
3794
      if (make_global_read_lock_block_commit(thd)) // Killed
 
3795
      {
 
3796
        /* Don't leave things in a half-locked state */
 
3797
        unlock_global_read_lock(thd);
 
3798
        return 1;
 
3799
      }
 
3800
    }
 
3801
    else
 
3802
      result= close_cached_tables(thd, tables, false, (options & REFRESH_FAST) ?
 
3803
                                  false : true, false);
 
3804
    my_dbopt_cleanup();
 
3805
  }
 
3806
  if (thd && (options & REFRESH_STATUS))
 
3807
    refresh_status(thd);
 
3808
  if (options & REFRESH_THREADS)
 
3809
    flush_thread_cache();
 
3810
  if (options & REFRESH_MASTER)
 
3811
  {
 
3812
    assert(thd);
 
3813
    tmp_write_to_binlog= 0;
 
3814
    if (reset_master(thd))
 
3815
    {
 
3816
      result=1;
 
3817
    }
 
3818
  }
 
3819
 if (options & REFRESH_SLAVE)
 
3820
 {
 
3821
   tmp_write_to_binlog= 0;
 
3822
   pthread_mutex_lock(&LOCK_active_mi);
 
3823
   if (reset_slave(thd, active_mi))
 
3824
     result=1;
 
3825
   pthread_mutex_unlock(&LOCK_active_mi);
 
3826
 }
 
3827
 *write_to_binlog= tmp_write_to_binlog;
 
3828
 return result;
 
3829
}
 
3830
 
 
3831
 
 
3832
/**
 
3833
  kill on thread.
 
3834
 
 
3835
  @param thd                    Thread class
 
3836
  @param id                     Thread id
 
3837
  @param only_kill_query        Should it kill the query or the connection
 
3838
 
 
3839
  @note
 
3840
    This is written such that we have a short lock on LOCK_thread_count
 
3841
*/
 
3842
 
 
3843
static unsigned int
 
3844
kill_one_thread(THD *thd __attribute__((unused)),
 
3845
                ulong id, bool only_kill_query)
 
3846
{
 
3847
  THD *tmp;
 
3848
  uint error=ER_NO_SUCH_THREAD;
 
3849
  VOID(pthread_mutex_lock(&LOCK_thread_count)); // For unlink from list
 
3850
  I_List_iterator<THD> it(threads);
 
3851
  while ((tmp=it++))
 
3852
  {
 
3853
    if (tmp->command == COM_DAEMON)
 
3854
      continue;
 
3855
    if (tmp->thread_id == id)
 
3856
    {
 
3857
      pthread_mutex_lock(&tmp->LOCK_delete);    // Lock from delete
 
3858
      break;
 
3859
    }
 
3860
  }
 
3861
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
 
3862
  if (tmp)
 
3863
  {
 
3864
    tmp->awake(only_kill_query ? THD::KILL_QUERY : THD::KILL_CONNECTION);
 
3865
    error=0;
 
3866
    pthread_mutex_unlock(&tmp->LOCK_delete);
 
3867
  }
 
3868
  return(error);
 
3869
}
 
3870
 
 
3871
 
 
3872
/*
 
3873
  kills a thread and sends response
 
3874
 
 
3875
  SYNOPSIS
 
3876
    sql_kill()
 
3877
    thd                 Thread class
 
3878
    id                  Thread id
 
3879
    only_kill_query     Should it kill the query or the connection
 
3880
*/
 
3881
 
 
3882
void sql_kill(THD *thd, ulong id, bool only_kill_query)
 
3883
{
 
3884
  uint error;
 
3885
  if (!(error= kill_one_thread(thd, id, only_kill_query)))
 
3886
    my_ok(thd);
 
3887
  else
 
3888
    my_error(error, MYF(0), id);
 
3889
}
 
3890
 
 
3891
 
 
3892
/** If pointer is not a null pointer, append filename to it. */
 
3893
 
 
3894
bool append_file_to_dir(THD *thd, const char **filename_ptr,
 
3895
                        const char *table_name)
 
3896
{
 
3897
  char buff[FN_REFLEN],*ptr, *end;
 
3898
  if (!*filename_ptr)
 
3899
    return 0;                                   // nothing to do
 
3900
 
 
3901
  /* Check that the filename is not too long and it's a hard path */
 
3902
  if (strlen(*filename_ptr)+strlen(table_name) >= FN_REFLEN-1 ||
 
3903
      !test_if_hard_path(*filename_ptr))
 
3904
  {
 
3905
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
 
3906
    return 1;
 
3907
  }
 
3908
  /* Fix is using unix filename format on dos */
 
3909
  stpcpy(buff,*filename_ptr);
 
3910
  end=convert_dirname(buff, *filename_ptr, NullS);
 
3911
  if (!(ptr= (char*) thd->alloc((size_t) (end-buff) + strlen(table_name)+1)))
 
3912
    return 1;                                   // End of memory
 
3913
  *filename_ptr=ptr;
 
3914
  strxmov(ptr,buff,table_name,NullS);
 
3915
  return 0;
 
3916
}
 
3917
 
 
3918
 
 
3919
/**
1449
3920
  Check if the select is a simple select (not an union).
1450
3921
 
1451
3922
  @retval
1454
3925
    1   error   ; In this case the error messege is sent to the client
1455
3926
*/
1456
3927
 
1457
 
bool check_simple_select(Session::pointer session)
 
3928
bool check_simple_select()
1458
3929
{
1459
 
  LEX *lex= session->lex;
 
3930
  THD *thd= current_thd;
 
3931
  LEX *lex= thd->lex;
1460
3932
  if (lex->current_select != &lex->select_lex)
1461
3933
  {
1462
3934
    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;
 
3935
    Lex_input_stream *lip= thd->m_lip;
 
3936
    strmake(command, lip->yylval->symbol.str,
 
3937
            min(lip->yylval->symbol.length, sizeof(command)-1));
1467
3938
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
1468
3939
    return 1;
1469
3940
  }
1471
3942
}
1472
3943
 
1473
3944
 
 
3945
Comp_creator *comp_eq_creator(bool invert)
 
3946
{
 
3947
  return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
 
3948
}
 
3949
 
 
3950
 
 
3951
Comp_creator *comp_ge_creator(bool invert)
 
3952
{
 
3953
  return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator;
 
3954
}
 
3955
 
 
3956
 
 
3957
Comp_creator *comp_gt_creator(bool invert)
 
3958
{
 
3959
  return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator;
 
3960
}
 
3961
 
 
3962
 
 
3963
Comp_creator *comp_le_creator(bool invert)
 
3964
{
 
3965
  return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator;
 
3966
}
 
3967
 
 
3968
 
 
3969
Comp_creator *comp_lt_creator(bool invert)
 
3970
{
 
3971
  return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator;
 
3972
}
 
3973
 
 
3974
 
 
3975
Comp_creator *comp_ne_creator(bool invert)
 
3976
{
 
3977
  return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
 
3978
}
 
3979
 
 
3980
 
1474
3981
/**
1475
3982
  Construct ALL/ANY/SOME subquery Item.
1476
3983
 
1483
3990
    constructed Item (or 0 if out of memory)
1484
3991
*/
1485
3992
Item * all_any_subquery_creator(Item *left_expr,
1486
 
                                chooser_compare_func_creator cmp,
1487
 
                                bool all,
1488
 
                                Select_Lex *select_lex)
 
3993
                                chooser_compare_func_creator cmp,
 
3994
                                bool all,
 
3995
                                SELECT_LEX *select_lex)
1489
3996
{
1490
3997
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
1491
3998
    return new Item_in_subselect(left_expr, select_lex);
1503
4010
 
1504
4011
 
1505
4012
/**
1506
 
  Update query pre-check.
 
4013
  Multi update query pre-check.
1507
4014
 
1508
 
  @param session                Thread handler
 
4015
  @param thd            Thread handler
1509
4016
  @param tables Global/local table list (have to be the same)
1510
4017
 
1511
4018
  @retval
1514
4021
    true  Error
1515
4022
*/
1516
4023
 
1517
 
bool update_precheck(Session *session, TableList *)
 
4024
bool multi_update_precheck(THD *thd,
 
4025
                           TABLE_LIST *tables __attribute__((unused)))
1518
4026
{
1519
4027
  const char *msg= 0;
1520
 
  LEX *lex= session->lex;
1521
 
  Select_Lex *select_lex= &lex->select_lex;
 
4028
  LEX *lex= thd->lex;
 
4029
  SELECT_LEX *select_lex= &lex->select_lex;
1522
4030
 
1523
 
  if (session->lex->select_lex.item_list.elements != session->lex->value_list.elements)
 
4031
  if (select_lex->item_list.elements != lex->value_list.elements)
1524
4032
  {
1525
4033
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
1526
4034
    return(true);
1527
4035
  }
1528
4036
 
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)
 
4037
  if (select_lex->order_list.elements)
 
4038
    msg= "ORDER BY";
 
4039
  else if (select_lex->select_limit)
 
4040
    msg= "LIMIT";
 
4041
  if (msg)
 
4042
  {
 
4043
    my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
 
4044
    return(true);
 
4045
  }
 
4046
  return(false);
 
4047
}
 
4048
 
 
4049
/**
 
4050
  Multi delete query pre-check.
 
4051
 
 
4052
  @param thd                    Thread handler
 
4053
  @param tables         Global/local table list
 
4054
 
 
4055
  @retval
 
4056
    false OK
 
4057
  @retval
 
4058
    true  error
 
4059
*/
 
4060
 
 
4061
bool multi_delete_precheck(THD *thd,
 
4062
                           TABLE_LIST *tables __attribute__((unused)))
 
4063
{
 
4064
  SELECT_LEX *select_lex= &thd->lex->select_lex;
 
4065
  TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
 
4066
 
 
4067
  thd->lex->query_tables_own_last= 0;
 
4068
  thd->lex->query_tables_own_last= save_query_tables_own_last;
 
4069
 
 
4070
  if ((thd->options & OPTION_SAFE_UPDATES) && !select_lex->where)
 
4071
  {
 
4072
    my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
 
4073
               ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
 
4074
    return(true);
 
4075
  }
 
4076
  return(false);
 
4077
}
 
4078
 
 
4079
 
 
4080
/*
 
4081
  Given a table in the source list, find a correspondent table in the
 
4082
  table references list.
 
4083
 
 
4084
  @param lex Pointer to LEX representing multi-delete.
 
4085
  @param src Source table to match.
 
4086
  @param ref Table references list.
 
4087
 
 
4088
  @remark The source table list (tables listed before the FROM clause
 
4089
  or tables listed in the FROM clause before the USING clause) may
 
4090
  contain table names or aliases that must match unambiguously one,
 
4091
  and only one, table in the target table list (table references list,
 
4092
  after FROM/USING clause).
 
4093
 
 
4094
  @return Matching table, NULL otherwise.
 
4095
*/
 
4096
 
 
4097
static TABLE_LIST *multi_delete_table_match(LEX *lex __attribute__((unused)),
 
4098
                                            TABLE_LIST *tbl,
 
4099
                                            TABLE_LIST *tables)
 
4100
{
 
4101
  TABLE_LIST *match= NULL;
 
4102
 
 
4103
  for (TABLE_LIST *elem= tables; elem; elem= elem->next_local)
 
4104
  {
 
4105
    int cmp;
 
4106
 
 
4107
    if (tbl->is_fqtn && elem->is_alias)
 
4108
      continue; /* no match */
 
4109
    if (tbl->is_fqtn && elem->is_fqtn)
 
4110
      cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) ||
 
4111
           strcmp(tbl->db, elem->db);
 
4112
    else if (elem->is_alias)
 
4113
      cmp= my_strcasecmp(table_alias_charset, tbl->alias, elem->alias);
 
4114
    else
 
4115
      cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) ||
 
4116
           strcmp(tbl->db, elem->db);
 
4117
 
 
4118
    if (cmp)
 
4119
      continue;
 
4120
 
 
4121
    if (match)
1536
4122
    {
1537
 
      my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
 
4123
      my_error(ER_NONUNIQ_TABLE, MYF(0), elem->alias);
 
4124
      return(NULL);
 
4125
    }
 
4126
 
 
4127
    match= elem;
 
4128
  }
 
4129
 
 
4130
  if (!match)
 
4131
    my_error(ER_UNKNOWN_TABLE, MYF(0), tbl->table_name, "MULTI DELETE");
 
4132
 
 
4133
  return(match);
 
4134
}
 
4135
 
 
4136
 
 
4137
/**
 
4138
  Link tables in auxilary table list of multi-delete with corresponding
 
4139
  elements in main table list, and set proper locks for them.
 
4140
 
 
4141
  @param lex   pointer to LEX representing multi-delete
 
4142
 
 
4143
  @retval
 
4144
    false   success
 
4145
  @retval
 
4146
    true    error
 
4147
*/
 
4148
 
 
4149
bool multi_delete_set_locks_and_link_aux_tables(LEX *lex)
 
4150
{
 
4151
  TABLE_LIST *tables= (TABLE_LIST*)lex->select_lex.table_list.first;
 
4152
  TABLE_LIST *target_tbl;
 
4153
 
 
4154
  lex->table_count= 0;
 
4155
 
 
4156
  for (target_tbl= (TABLE_LIST *)lex->auxiliary_table_list.first;
 
4157
       target_tbl; target_tbl= target_tbl->next_local)
 
4158
  {
 
4159
    lex->table_count++;
 
4160
    /* All tables in aux_tables must be found in FROM PART */
 
4161
    TABLE_LIST *walk= multi_delete_table_match(lex, target_tbl, tables);
 
4162
    if (!walk)
1538
4163
      return(true);
 
4164
    if (!walk->derived)
 
4165
    {
 
4166
      target_tbl->table_name= walk->table_name;
 
4167
      target_tbl->table_name_length= walk->table_name_length;
1539
4168
    }
 
4169
    walk->updating= target_tbl->updating;
 
4170
    walk->lock_type= target_tbl->lock_type;
 
4171
    target_tbl->correspondent_table= walk;      // Remember corresponding table
 
4172
  }
 
4173
  return(false);
 
4174
}
 
4175
 
 
4176
 
 
4177
/**
 
4178
  simple UPDATE query pre-check.
 
4179
 
 
4180
  @param thd            Thread handler
 
4181
  @param tables Global table list
 
4182
 
 
4183
  @retval
 
4184
    false OK
 
4185
  @retval
 
4186
    true  Error
 
4187
*/
 
4188
 
 
4189
bool update_precheck(THD *thd, TABLE_LIST *tables __attribute__((unused)))
 
4190
{
 
4191
  if (thd->lex->select_lex.item_list.elements != thd->lex->value_list.elements)
 
4192
  {
 
4193
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
 
4194
    return(true);
1540
4195
  }
1541
4196
  return(false);
1542
4197
}
1545
4200
/**
1546
4201
  simple INSERT query pre-check.
1547
4202
 
1548
 
  @param session                Thread handler
 
4203
  @param thd            Thread handler
1549
4204
  @param tables Global table list
1550
4205
 
1551
4206
  @retval
1554
4209
    true   error
1555
4210
*/
1556
4211
 
1557
 
bool insert_precheck(Session *session, TableList *)
 
4212
bool insert_precheck(THD *thd, TABLE_LIST *tables __attribute__((unused)))
1558
4213
{
1559
 
  LEX *lex= session->lex;
 
4214
  LEX *lex= thd->lex;
1560
4215
 
1561
4216
  /*
1562
4217
    Check that we have modify privileges for the first table and
1572
4227
 
1573
4228
 
1574
4229
/**
 
4230
  CREATE TABLE query pre-check.
 
4231
 
 
4232
  @param thd                    Thread handler
 
4233
  @param tables         Global table list
 
4234
  @param create_table           Table which will be created
 
4235
 
 
4236
  @retval
 
4237
    false   OK
 
4238
  @retval
 
4239
    true   Error
 
4240
*/
 
4241
 
 
4242
bool create_table_precheck(THD *thd,
 
4243
                           TABLE_LIST *tables __attribute__((unused)),
 
4244
                           TABLE_LIST *create_table)
 
4245
{
 
4246
  LEX *lex= thd->lex;
 
4247
  SELECT_LEX *select_lex= &lex->select_lex;
 
4248
  bool error= true;                                 // Error message is given
 
4249
 
 
4250
  if (create_table && (strcmp(create_table->db, "information_schema") == 0))
 
4251
  {
 
4252
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), "", "", INFORMATION_SCHEMA_NAME.str);
 
4253
    return(true);
 
4254
  }
 
4255
 
 
4256
  if (select_lex->item_list.elements)
 
4257
  {
 
4258
    /* Check permissions for used tables in CREATE TABLE ... SELECT */
 
4259
 
 
4260
#ifdef NOT_NECESSARY_TO_CHECK_CREATE_TABLE_EXIST_WHEN_PREPARING_STATEMENT
 
4261
    /* This code throws an ill error for CREATE TABLE t1 SELECT * FROM t1 */
 
4262
    /*
 
4263
      Only do the check for PS, because we on execute we have to check that
 
4264
      against the opened tables to ensure we don't use a table that is part
 
4265
      of the view (which can only be done after the table has been opened).
 
4266
    */
 
4267
    if (thd->stmt_arena->is_stmt_prepare_or_first_sp_execute())
 
4268
    {
 
4269
      /*
 
4270
        For temporary tables we don't have to check if the created table exists
 
4271
      */
 
4272
      if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) &&
 
4273
          find_table_in_global_list(tables, create_table->db,
 
4274
                                    create_table->table_name))
 
4275
      {
 
4276
        error= false;
 
4277
        goto err;
 
4278
      }
 
4279
    }
 
4280
#endif
 
4281
  }
 
4282
  error= false;
 
4283
 
 
4284
  return(error);
 
4285
}
 
4286
 
 
4287
 
 
4288
/**
1575
4289
  negate given expression.
1576
4290
 
1577
 
  @param session  thread handler
 
4291
  @param thd  thread handler
1578
4292
  @param expr expression for negation
1579
4293
 
1580
4294
  @return
1581
4295
    negated expression
1582
4296
*/
1583
4297
 
1584
 
Item *negate_expression(Session *session, Item *expr)
 
4298
Item *negate_expression(THD *thd, Item *expr)
1585
4299
{
1586
4300
  Item *negated;
1587
4301
  if (expr->type() == Item::FUNC_ITEM &&
1589
4303
  {
1590
4304
    /* it is NOT(NOT( ... )) */
1591
4305
    Item *arg= ((Item_func *) expr)->arguments()[0];
1592
 
    enum_parsing_place place= session->lex->current_select->parsing_place;
 
4306
    enum_parsing_place place= thd->lex->current_select->parsing_place;
1593
4307
    if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING)
1594
4308
      return arg;
1595
4309
    /*
1599
4313
    return new Item_func_ne(arg, new Item_int((char*) "0", 0, 1));
1600
4314
  }
1601
4315
 
1602
 
  if ((negated= expr->neg_transformer(session)) != 0)
 
4316
  if ((negated= expr->neg_transformer(thd)) != 0)
1603
4317
    return negated;
1604
4318
  return new Item_func_not(expr);
1605
4319
}
1606
4320
 
1607
4321
 
 
4322
/**
 
4323
  Check that byte length of a string does not exceed some limit.
 
4324
 
 
4325
  @param str         string to be checked
 
4326
  @param err_msg     error message to be displayed if the string is too long
 
4327
  @param max_length  max length
 
4328
 
 
4329
  @retval
 
4330
    false   the passed string is not longer than max_length
 
4331
  @retval
 
4332
    true    the passed string is longer than max_length
 
4333
 
 
4334
  NOTE
 
4335
    The function is not used in existing code but can be useful later?
 
4336
*/
 
4337
 
 
4338
bool check_string_byte_length(LEX_STRING *str, const char *err_msg,
 
4339
                              uint max_byte_length)
 
4340
{
 
4341
  if (str->length <= max_byte_length)
 
4342
    return false;
 
4343
 
 
4344
  my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_byte_length);
 
4345
 
 
4346
  return true;
 
4347
}
 
4348
 
 
4349
 
1608
4350
/*
1609
4351
  Check that char length of a string does not exceed some limit.
1610
4352
 
1622
4364
 
1623
4365
 
1624
4366
bool check_string_char_length(LEX_STRING *str, const char *err_msg,
1625
 
                              uint32_t max_char_length, const CHARSET_INFO * const cs,
 
4367
                              uint max_char_length, const CHARSET_INFO * const cs,
1626
4368
                              bool no_error)
1627
4369
{
1628
4370
  int well_formed_error;
1629
 
  uint32_t res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
 
4371
  uint res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
1630
4372
                                      max_char_length, &well_formed_error);
1631
4373
 
1632
4374
  if (!well_formed_error &&  str->length == res)
1638
4380
}
1639
4381
 
1640
4382
 
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)
 
4383
bool check_identifier_name(LEX_STRING *str, uint max_char_length,
 
4384
                           uint err_code, const char *param_for_err_msg)
1644
4385
{
 
4386
#ifdef HAVE_CHARSET_utf8mb3
1645
4387
  /*
1646
4388
    We don't support non-BMP characters in identifiers at the moment,
1647
4389
    so they should be prohibited until such support is done.
1648
4390
    This is why we use the 3-byte utf8 to check well-formedness here.
1649
4391
  */
1650
 
  const CHARSET_INFO * const cs= &my_charset_utf8mb4_general_ci;
1651
 
 
 
4392
  const CHARSET_INFO * const cs= &my_charset_utf8mb3_general_ci;
 
4393
#else
 
4394
  const CHARSET_INFO * const cs= system_charset_info;
 
4395
#endif
1652
4396
  int well_formed_error;
1653
 
  uint32_t res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
 
4397
  uint res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
1654
4398
                                      max_char_length, &well_formed_error);
1655
4399
 
1656
4400
  if (well_formed_error)
1658
4402
    my_error(ER_INVALID_CHARACTER_STRING, MYF(0), "identifier", str->str);
1659
4403
    return true;
1660
4404
  }
1661
 
 
 
4405
  
1662
4406
  if (str->length == res)
1663
4407
    return false;
1664
4408
 
1665
4409
  switch (err_code)
1666
4410
  {
1667
 
  case EE_OK:
 
4411
  case 0:
1668
4412
    break;
1669
4413
  case ER_WRONG_STRING_LENGTH:
1670
4414
    my_error(err_code, MYF(0), str->str, param_for_err_msg, max_char_length);
1676
4420
    assert(0);
1677
4421
    break;
1678
4422
  }
1679
 
 
1680
4423
  return true;
1681
4424
}
1682
4425
 
1683
4426
 
 
4427
/*
 
4428
  Check if path does not contain mysql data home directory
 
4429
  SYNOPSIS
 
4430
    test_if_data_home_dir()
 
4431
    dir                     directory
 
4432
    conv_home_dir           converted data home directory
 
4433
    home_dir_len            converted data home directory length
 
4434
 
 
4435
  RETURN VALUES
 
4436
    0   ok
 
4437
    1   error  
 
4438
*/
 
4439
 
 
4440
bool test_if_data_home_dir(const char *dir)
 
4441
{
 
4442
  char path[FN_REFLEN], conv_path[FN_REFLEN];
 
4443
  uint dir_len, home_dir_len= strlen(mysql_unpacked_real_data_home);
 
4444
 
 
4445
  if (!dir)
 
4446
    return(0);
 
4447
 
 
4448
  (void) fn_format(path, dir, "", "",
 
4449
                   (MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS));
 
4450
  dir_len= unpack_dirname(conv_path, dir);
 
4451
 
 
4452
  if (home_dir_len < dir_len)
 
4453
  {
 
4454
    if (!my_strnncoll(character_set_filesystem,
 
4455
                      (const uchar*) conv_path, home_dir_len,
 
4456
                      (const uchar*) mysql_unpacked_real_data_home,
 
4457
                      home_dir_len))
 
4458
      return(1);
 
4459
  }
 
4460
  return(0);
 
4461
}
 
4462
 
 
4463
 
 
4464
extern int MYSQLparse(void *thd); // from sql_yacc.cc
 
4465
 
 
4466
 
1684
4467
/**
1685
 
  This is a wrapper of DRIZZLEparse(). All the code should call parse_sql()
1686
 
  instead of DRIZZLEparse().
 
4468
  This is a wrapper of MYSQLparse(). All the code should call parse_sql()
 
4469
  instead of MYSQLparse().
1687
4470
 
1688
 
  @param session Thread context.
 
4471
  @param thd Thread context.
1689
4472
  @param lip Lexer context.
 
4473
  @param creation_ctx Object creation context.
1690
4474
 
1691
4475
  @return Error status.
1692
4476
    @retval false on success.
1693
4477
    @retval true on parsing error.
1694
4478
*/
1695
4479
 
1696
 
static bool parse_sql(Session *session, Lex_input_stream *lip)
 
4480
bool parse_sql(THD *thd,
 
4481
               Lex_input_stream *lip,
 
4482
               Object_creation_ctx *creation_ctx)
1697
4483
{
1698
 
  assert(session->m_lip == NULL);
1699
 
 
1700
 
  DRIZZLE_QUERY_PARSE_START(session->getQueryString()->c_str());
 
4484
  assert(thd->m_lip == NULL);
 
4485
 
 
4486
  /* Backup creation context. */
 
4487
 
 
4488
  Object_creation_ctx *backup_ctx= NULL;
 
4489
 
 
4490
  if (creation_ctx)
 
4491
    backup_ctx= creation_ctx->set_n_backup(thd);
1701
4492
 
1702
4493
  /* Set Lex_input_stream. */
1703
4494
 
1704
 
  session->m_lip= lip;
 
4495
  thd->m_lip= lip;
1705
4496
 
1706
4497
  /* Parse the query. */
1707
4498
 
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());
 
4499
  bool mysql_parse_status= MYSQLparse(thd) != 0;
 
4500
 
 
4501
  /* Check that if MYSQLparse() failed, thd->is_error() is set. */
 
4502
 
 
4503
  assert(!mysql_parse_status || thd->is_error());
1713
4504
 
1714
4505
  /* Reset Lex_input_stream. */
1715
4506
 
1716
 
  session->m_lip= NULL;
1717
 
 
1718
 
  DRIZZLE_QUERY_PARSE_DONE(parse_status || session->is_fatal_error);
 
4507
  thd->m_lip= NULL;
 
4508
 
 
4509
  /* Restore creation context. */
 
4510
 
 
4511
  if (creation_ctx)
 
4512
    creation_ctx->restore_env(thd, backup_ctx);
1719
4513
 
1720
4514
  /* That's it. */
1721
4515
 
1722
 
  return parse_status || session->is_fatal_error;
 
4516
  return mysql_parse_status || thd->is_fatal_error;
1723
4517
}
1724
4518
 
1725
4519
/**
1726
4520
  @} (end of group Runtime_Environment)
1727
4521
*/
1728
 
 
1729
 
} /* namespace drizzled */